@mcpjam/inspector 3.12.4 → 3.12.5

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.
Files changed (37) hide show
  1. package/README.md +29 -21
  2. package/bin/access-link.mjs +53 -0
  3. package/bin/start.js +47 -14
  4. package/dist/client/assets/OAuthDesktopReturnNotice-B_x9xTE-.css +2 -0
  5. package/dist/client/assets/OAuthDesktopReturnNotice-LlC451lX.js +11 -0
  6. package/dist/client/assets/{app-bootstrap-B7TKDg4p.js → app-bootstrap-2jatN7gw.js} +363 -361
  7. package/dist/client/assets/{button-BgMj96d7.js → button-B2OH2ei2.js} +2 -2
  8. package/dist/client/assets/{chunk-YOKDWASO-DiKLTu3U.js → chunk-YOKDWASO-uJ3KOQV7.js} +5 -5
  9. package/dist/client/assets/{dead-clicks-autocapture-B2D_6BXS.js → dead-clicks-autocapture-D055GjVp.js} +2 -2
  10. package/dist/client/assets/{error-reporting-6uZvG5HZ.js → error-reporting-DGP36KLx.js} +57 -57
  11. package/dist/client/assets/{error-reporting-xR8v_8my.js → error-reporting-FWZKbZxG.js} +1 -1
  12. package/dist/client/assets/{exception-autocapture-Xx2wbAOf.js → exception-autocapture-103gdJjL.js} +2 -2
  13. package/dist/client/assets/{failed-request-tracker-BH4w1sBR.js → failed-request-tracker-Cp9_VFMm.js} +2 -2
  14. package/dist/client/assets/{highlighted-body-KPVGNVTW-DIgOE9D7.js → highlighted-body-KPVGNVTW-Dx70h1nm.js} +2 -2
  15. package/dist/client/assets/index-rskHnM3O.js +4 -0
  16. package/dist/client/assets/{jszip.min-C24J_3Y_.js → jszip.min-CwJyI5tb.js} +2 -2
  17. package/dist/client/assets/{mermaid-HWGCJPDP-BTzLBCkg.js → mermaid-HWGCJPDP-Ck3prJKl.js} +1 -1
  18. package/dist/client/assets/{posthog-recorder-CEtP2mh8.js → posthog-recorder-tKuMFijV.js} +2 -2
  19. package/dist/client/assets/{preload-helper-Cfn3cu1N.js → preload-helper-DrcoTQ49.js} +2 -2
  20. package/dist/client/assets/{rolldown-runtime-BPNN4GNu.js → rolldown-runtime-7FnpGOz6.js} +1 -1
  21. package/dist/client/assets/{surveys-CWniVjxJ.js → surveys-BsZYxM6N.js} +2 -2
  22. package/dist/client/assets/{trace-timeline-D-nhBNaR.js → trace-timeline-BOZvHcOG.js} +1 -1
  23. package/dist/client/assets/{trace-timeline-D9qZRjVv.js → trace-timeline-Bf9Oai70.js} +8 -8
  24. package/dist/client/assets/{web-vitals-zTwn9Gi6.js → web-vitals-DdzaVN3H.js} +2 -2
  25. package/dist/client/index.html +7 -7
  26. package/dist/server/chunk-3EDQFXTF.js +4801 -0
  27. package/dist/server/{chunk-5RE7KJ2M.js → chunk-4PYR7GMQ.js} +16 -197
  28. package/dist/server/{chunk-5T6DFO27.js → chunk-QA6VJT6A.js} +961 -963
  29. package/dist/server/chunk-SH24KJBI.js +194 -0
  30. package/dist/server/{consent-lifetime-PTGAZQSU.js → consent-lifetime-M7PS6RUU.js} +3 -2
  31. package/dist/server/harness-install-cli.js +1 -1
  32. package/dist/server/index.js +14093 -15925
  33. package/dist/server/local-turn-XXOSZHMT.js +12 -0
  34. package/package.json +14 -11
  35. package/dist/client/assets/OAuthDesktopReturnNotice-B2D5moE-.css +0 -2
  36. package/dist/client/assets/OAuthDesktopReturnNotice-CTGRhDuo.js +0 -11
  37. package/dist/client/assets/index-Cu4ySOft.js +0 -4
@@ -1,102 +1,102 @@
1
- import{t as iy}from"./failed-request-tracker-BH4w1sBR.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};e.SENTRY_RELEASE={id:"3.12.4"};var t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ad0e8314-7ca7-444d-8380-cec7b6d0012c",e._sentryDebugIdIdentifier="sentry-dbid-ad0e8314-7ca7-444d-8380-cec7b6d0012c")}catch{}})();var Gt=[],It=[],sy=Uint8Array,$a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var bn=0,oy=$a.length;bn<oy;++bn)Gt[bn]=$a[bn],It[$a.charCodeAt(bn)]=bn;It[45]=62;It[95]=63;function ay(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function cy(e,t,r){return(t+r)*3/4-r}function ro(e){for(var t,r=ay(e),n=r[0],i=r[1],s=new sy(cy(e,n,i)),o=0,a=i>0?n-4:n,c=0;c<a;c+=4)t=It[e.charCodeAt(c)]<<18|It[e.charCodeAt(c+1)]<<12|It[e.charCodeAt(c+2)]<<6|It[e.charCodeAt(c+3)],s[o++]=t>>16&255,s[o++]=t>>8&255,s[o++]=t&255;return i===2&&(t=It[e.charCodeAt(c)]<<2|It[e.charCodeAt(c+1)]>>4,s[o++]=t&255),i===1&&(t=It[e.charCodeAt(c)]<<10|It[e.charCodeAt(c+1)]<<4|It[e.charCodeAt(c+2)]>>2,s[o++]=t>>8&255,s[o++]=t&255),s}function ly(e){return Gt[e>>18&63]+Gt[e>>12&63]+Gt[e>>6&63]+Gt[e&63]}function uy(e,t,r){for(var n,i=[],s=t;s<r;s+=3)n=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),i.push(ly(n));return i.join("")}function no(e){for(var t,r=e.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(uy(e,o,o+s>a?a:o+s));return n===1?(t=e[r-1],i.push(Gt[t>>2]+Gt[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],i.push(Gt[t>>10]+Gt[t>>4&63]+Gt[t<<2&63]+"=")),i.join("")}function sM(e){if(e===void 0)return{};if(!Yp(e))throw new Error(`The arguments to a Convex function must be an object. Received: ${e}`);return e}function oM(e){if(typeof e>"u")throw new Error("Client created with undefined deployment address. If you used an environment variable, check that it's set.");if(typeof e!="string")throw new Error(`Invalid deployment address: found ${e}".`);if(!(e.startsWith("http:")||e.startsWith("https:")))throw new Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${e}".`);try{new URL(e)}catch{throw new Error(`Invalid deployment address: "${e}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(e.endsWith(".convex.site"))throw new Error(`Invalid deployment address: "${e}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}function Yp(e){const t=typeof e=="object",r=Object.getPrototypeOf(e),n=r===null||r===Object.prototype||r?.constructor?.name==="Object";return t&&n}var Xp=!0,Wn=BigInt("-9223372036854775808"),Ul=BigInt("9223372036854775807"),kc=BigInt("0"),dy=BigInt("8"),hy=BigInt("256"),Ca="This commit timestamp is unresolved: its value is assigned when the mutation commits. Read the document after the mutation completes to get its value.",Qp=class{[Symbol.toPrimitive](e){if(e==="string")return this.toString();throw new Error(Ca)}valueOf(){throw new Error(Ca)}toJSON(){throw new Error(Ca)}toString(){return"[unresolved commit timestamp]"}},py=new Qp;function ef(e){return Number.isNaN(e)||!Number.isFinite(e)||Object.is(e,-0)}function fy(e){e<kc&&(e-=Wn+Wn);let t=e.toString(16);t.length%2===1&&(t="0"+t);const r=new Uint8Array(new ArrayBuffer(8));let n=0;for(const i of t.match(/.{2}/g).reverse())r.set([parseInt(i,16)],n++),e>>=dy;return no(r)}function vy(e){const t=ro(e);if(t.byteLength!==8)throw new Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let r=kc,n=kc;for(const i of t)r+=BigInt(i)*hy**n,n++;return r>Ul&&(r+=Wn+Wn),r}function gy(e){if(e<Wn||Ul<e)throw new Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);const t=new ArrayBuffer(8);return new DataView(t).setBigInt64(0,e,!0),no(new Uint8Array(t))}function my(e){const t=ro(e);if(t.byteLength!==8)throw new Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);return new DataView(t.buffer).getBigInt64(0,!0)}var _y=DataView.prototype.setBigInt64?gy:fy,yy=DataView.prototype.getBigInt64?my:vy,Yu=1024;function Rc(e){if(e.length>Yu)throw new Error(`Field name ${e} exceeds maximum field name length ${Yu}.`);if(e.startsWith("$"))throw new Error(`Field name ${e} starts with a '$', which is reserved.`);for(let t=0;t<e.length;t+=1){const r=e.charCodeAt(t);if(r<32||r>=127)throw new Error(`Field name ${e} has invalid character '${e[t]}': Field names can only contain non-control ASCII characters`)}}function Xu(e){if(e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string")return e;if(Array.isArray(e))return e.map(n=>Xu(n));if(typeof e!="object")throw new Error(`Unexpected type of ${e}`);const t=Object.entries(e);if(t.length===1){const n=t[0][0];if(n==="$bytes"){if(typeof e.$bytes!="string")throw new Error(`Malformed $bytes field on ${e}`);return ro(e.$bytes).buffer}if(n==="$integer"){if(typeof e.$integer!="string")throw new Error(`Malformed $integer field on ${e}`);return yy(e.$integer)}if(n==="$float"){if(typeof e.$float!="string")throw new Error(`Malformed $float field on ${e}`);const i=ro(e.$float);if(i.byteLength!==8)throw new Error(`Received ${i.byteLength} bytes, expected 8 for $float`);const s=new DataView(i.buffer).getFloat64(0,Xp);if(!ef(s))throw new Error(`Float ${s} should be encoded as a number`);return s}if(n==="$commitTs"){if(e.$commitTs!==null)throw new Error(`Malformed $commitTs field on ${e}`);return py}if(n==="$set")throw new Error("Received a Set which is no longer supported as a Convex type.");if(n==="$map")throw new Error("Received a Map which is no longer supported as a Convex type.")}const r={};for(const[n,i]of Object.entries(e))Rc(n),r[n]=Xu(i);return r}var by=16384;function Fn(e){const t=JSON.stringify(e,(r,n)=>n===void 0?"undefined":typeof n=="bigint"?`${n.toString()}n`:n);if(t.length>by){const r="[...truncated]";let n=16370;const i=t.codePointAt(n-1);return i!==void 0&&i>65535&&(n-=1),t.substring(0,n)+r}return t}function io(e,t,r,n){if(e===void 0){const o=r&&` (present at path ${r} in original object ${Fn(t)})`;throw new Error(`undefined is not a valid Convex value${o}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(e===null)return e;if(typeof e=="bigint"){if(e<Wn||Ul<e)throw new Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);return{$integer:_y(e)}}if(typeof e=="number")if(ef(e)){const o=new ArrayBuffer(8);return new DataView(o).setFloat64(0,e,Xp),{$float:no(new Uint8Array(o))}}else return e;if(typeof e=="boolean"||typeof e=="string")return e;if(e instanceof ArrayBuffer)return{$bytes:no(new Uint8Array(e))};if(e instanceof Qp)return{$commitTs:null};if(Array.isArray(e))return e.map((o,a)=>io(o,t,r+`[${a}]`,!1));if(e instanceof Set)throw new Error(Pa(r,"Set",[...e],t));if(e instanceof Map)throw new Error(Pa(r,"Map",[...e],t));if(!Yp(e)){const o=e?.constructor?.name,a=o?`${o} `:"";throw new Error(Pa(r,a,e,t))}const i={},s=Object.entries(e);s.sort(([o,a],[c,l])=>o===c?0:o<c?-1:1);for(const[o,a]of s)a!==void 0?(Rc(o),i[o]=io(a,t,r+`.${o}`,!1)):n&&(Rc(o),i[o]=wy(a,t,r+`.${o}`));return i}function Pa(e,t,r,n){return e?`${t}${Fn(r)} is not a supported Convex type (present at path ${e} in original object ${Fn(n)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${Fn(r)} is not a supported Convex type.`}function wy(e,t,r){if(e===void 0)return{$undefined:null};if(t===void 0)throw new Error(`Programming error. Current value is ${Fn(e)} but original value is undefined`);return io(e,t,r,!1)}function aM(e){return io(e,e,"",!1)}var Sy=Object.defineProperty,Ey=(e,t,r)=>t in e?Sy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Oa=(e,t,r)=>Ey(e,typeof t!="symbol"?t+"":t,r),Qu,ed,ky=Symbol.for("ConvexError"),Ry=class extends(ed=Error,Qu=ky,ed){constructor(e){super(typeof e=="string"?e:Fn(e)),Oa(this,"name","ConvexError"),Oa(this,"data"),Oa(this,Qu,!0),this.data=e}};function Fl(e){if(!(e instanceof Ry))return!1;const t=e.data;return typeof t=="object"&&t!==null&&t.kind==="forbidden"}var so;function cM(e){try{so=new URL(e).hostname}catch{so=void 0}}function Ac(e){try{const t=new URL(e);if(!/^https?:$/.test(t.protocol))return;const r=t.pathname.replace(/(\/(?:results|conformance\/shared|evals\/shared|organizations)\/)[^/]+/g,"$1[redacted]").replace(/(\/(?:user-testing|chatbox)\/[^/]+\/)[^/]+/g,"$1[redacted]");return`${t.origin}${r}`}catch{return}}function Oi(e){const t=/^\[CONVEX Q\(([\w/.-]+:[\w.-]+)\)\]/.exec(e);if(!t)return;const r=/\[Request ID: ([a-f\d]+)\]/i.exec(e)?.[1],n=`${t[0]}${r?` [Request ID: ${r}]`:""} ${/\bServer Error\b/.test(e)?"Server Error":"Query failed"}`;return{functionName:t[1],requestId:r,safeMessage:n}}function tf(e){const t=Oi(e);if(t)return{convex_function:t.functionName,...t.requestId?{request_id:t.requestId}:{},...so?{convex_backend:so}:{}}}function Ay(e){const t=Oi(e.message);if(!t)return e;const r=new Error(t.safeMessage);if(r.name=e.name,e.stack){const n=e.stack.split(`
2
- `).filter(i=>/^(\s+at |[^@]*@(?:https?|file|webpack|vite):)/.test(i));r.stack=`${r.name}: ${r.message}
3
- ${n.join(`
4
- `)}`}return r}function rf(e=500){const t=new Set;return(r,n)=>{if(!r||!n)return!1;const i=`${r}:${n}`;return t.has(i)?!0:(t.add(i),t.size>e&&t.delete(t.values().next().value),!1)}}function lM(e=500){const t=rf(e);return(r,n={})=>{try{const i=r.exception?.values,s=i?.find(u=>Oi(u.value??"")),o=Oi(s?.value??"");if(!o)return r;if(Fl(n.originalException))return null;const a=tf(s.value),c=typeof r.tags?.convex_backend=="string"?r.tags.convex_backend:a.convex_backend;if(t(c,o.requestId))return null;s.value=o.safeMessage,r.message&&(r.message=o.safeMessage),r.tags={...r.tags,...a,...c?{convex_backend:c}:{}};const l=Ac((typeof r.extra?.page_location=="string"?r.extra.page_location:void 0)??r.request?.url??(typeof window<"u"?window.location.href:""));r.request=l?{url:l}:void 0,r.breadcrumbs=void 0,r.extra={...typeof r.extra?.boundary=="string"?{boundary:r.extra.boundary}:{},...typeof r.extra?.componentStack=="string"?{componentStack:r.extra.componentStack}:{},...l?{page_location:l}:{}};for(const u of i??[])if(u!==s&&u.value&&(u.value=Oi(u.value)?.safeMessage??"Query failure cause"),u.stacktrace)for(const h of u.stacktrace.frames??[])delete h.vars;return r.transaction?.includes("/")&&(r.transaction=Ac(`https://route.invalid${r.transaction}`)?.replace("https://route.invalid","")),r}catch{return null}}}var Iy=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,nf="8.55.1",$t=globalThis;function qo(e,t,r){const n=r||$t,i=n.__SENTRY__=n.__SENTRY__||{},s=i[nf]=i["8.55.1"]||{};return s[e]||(s[e]=t())}var jo=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,Ty="Sentry Logger ",td=["debug","info","warn","error","log","assert","trace"],rd={};function sf(e){if(!("console"in $t))return e();const t=$t.console,r={},n=Object.keys(rd);n.forEach(i=>{const s=rd[i];r[i]=t[i],t[i]=s});try{return e()}finally{n.forEach(i=>{t[i]=r[i]})}}function $y(){let e=!1;const t={enable:()=>{e=!0},disable:()=>{e=!1},isEnabled:()=>e};return jo?td.forEach(r=>{t[r]=(...n)=>{e&&sf(()=>{$t.console[r](`${Ty}[${r}]:`,...n)})}}):td.forEach(r=>{t[r]=()=>{}}),t}var cn=qo("logger",$y),of=50;var nd=/\(error: (.*)\)/,id=/captureMessage|captureException/;function Cy(...e){const t=e.sort((r,n)=>r[0]-n[0]).map(r=>r[1]);return(r,n=0,i=0)=>{const s=[],o=r.split(`
5
- `);for(let a=n;a<o.length;a++){const c=o[a];if(c.length>1024)continue;const l=nd.test(c)?c.replace(nd,"$1"):c;if(!l.match(/\S*Error: /)){for(const u of t){const h=u(l);if(h){s.push(h);break}}if(s.length>=of+i)break}}return Py(s.slice(i))}}function uM(e){return Array.isArray(e)?Cy(...e):e}function Py(e){if(!e.length)return[];const t=Array.from(e);return/sentryWrapped/.test(ms(t).function||"")&&t.pop(),t.reverse(),id.test(ms(t).function||"")&&(t.pop(),id.test(ms(t).function||"")&&t.pop()),t.slice(0,of).map(r=>({...r,filename:r.filename||ms(t).filename,function:r.function||"?"}))}function ms(e){return e[e.length-1]||{}}var xa="<anonymous>";function Oy(e){try{return!e||typeof e!="function"?xa:e.name||xa}catch{return xa}}function dM(e){const t=e.exception;if(t){const r=[];try{return t.values.forEach(n=>{n.stacktrace.frames&&r.push(...n.stacktrace.frames)}),r}catch{return}}}function cs(){return ql($t),$t}function ql(e){const t=e.__SENTRY__=e.__SENTRY__||{};return t.version=t.version||"8.55.1",t[nf]=t["8.55.1"]||{}}var af=Object.prototype.toString;function xy(e){switch(af.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return Ho(e,Error)}}function ai(e,t){return af.call(e)===`[object ${t}]`}function hM(e){return ai(e,"ErrorEvent")}function pM(e){return ai(e,"DOMError")}function fM(e){return ai(e,"DOMException")}function oo(e){return ai(e,"String")}function My(e){return typeof e=="object"&&e!==null&&"__sentry_template_string__"in e&&"__sentry_template_values__"in e}function vM(e){return e===null||My(e)||typeof e!="object"&&typeof e!="function"}function jl(e){return ai(e,"Object")}function Ly(e){return typeof Event<"u"&&Ho(e,Event)}function Dy(e){return typeof Element<"u"&&Ho(e,Element)}function Ny(e){return ai(e,"RegExp")}function Hl(e){return!!(e&&e.then&&typeof e.then=="function")}function zy(e){return jl(e)&&"nativeEvent"in e&&"preventDefault"in e&&"stopPropagation"in e}function Ho(e,t){try{return e instanceof t}catch{return!1}}function cf(e){return!!(typeof e=="object"&&e!==null&&(e.__isVue||e._isVue))}var qn=$t,Uy=80;function Fy(e,t={}){if(!e)return"<unknown>";try{let r=e;const n=5,i=[];let s=0,o=0;const a=" > ",c=3;let l;const u=Array.isArray(t)?t:t.keyAttrs,h=!Array.isArray(t)&&t.maxStringLength||Uy;for(;r&&s++<n&&(l=qy(r,u),!(l==="html"||s>1&&o+i.length*c+l.length>=h));)i.push(l),o+=l.length,r=r.parentNode;return i.reverse().join(a)}catch{return"<unknown>"}}function qy(e,t){const r=e,n=[];if(!r||!r.tagName)return"";if(qn.HTMLElement&&r instanceof HTMLElement&&r.dataset){if(r.dataset.sentryComponent)return r.dataset.sentryComponent;if(r.dataset.sentryElement)return r.dataset.sentryElement}n.push(r.tagName.toLowerCase());const i=t&&t.length?t.filter(s=>r.getAttribute(s)).map(s=>[s,r.getAttribute(s)]):null;if(i&&i.length)i.forEach(s=>{n.push(`[${s[0]}="${s[1]}"]`)});else{r.id&&n.push(`#${r.id}`);const s=r.className;if(s&&oo(s)){const o=s.split(/\s+/);for(const a of o)n.push(`.${a}`)}}for(const s of["aria-label","type","name","title","alt"]){const o=r.getAttribute(s);o&&n.push(`[${s}="${o}"]`)}return n.join("")}function gM(){try{return qn.document.location.href}catch{return""}}function mM(e){return qn.document&&qn.document.querySelector?qn.document.querySelector(e):null}function _M(e){if(!qn.HTMLElement)return null;let t=e;const r=5;for(let n=0;n<r;n++){if(!t)return null;if(t instanceof HTMLElement){if(t.dataset.sentryComponent)return t.dataset.sentryComponent;if(t.dataset.sentryElement)return t.dataset.sentryElement}t=t.parentNode}return null}function xi(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function yM(e,t){if(!Array.isArray(e))return"";const r=[];for(let n=0;n<e.length;n++){const i=e[n];try{cf(i)?r.push("[VueViewModel]"):r.push(String(i))}catch{r.push("[value cannot be serialized]")}}return r.join(t)}function jy(e,t,r=!1){return oo(e)?Ny(t)?t.test(e):oo(t)?r?e===t:e.includes(t):!1:!1}function bM(e,t=[],r=!1){return t.some(n=>jy(e,n,r))}function wM(e,t,r){if(!(t in e))return;const n=e[t],i=r(n);typeof i=="function"&&Hy(i,n);try{e[t]=i}catch{jo&&cn.log(`Failed to replace method "${t}" in object`,e)}}function Zn(e,t,r){try{Object.defineProperty(e,t,{value:r,writable:!0,configurable:!0})}catch{jo&&cn.log(`Failed to add non-enumerable property "${t}" to object`,e)}}function Hy(e,t){try{e.prototype=t.prototype=t.prototype||{},Zn(e,"__sentry_original__",t)}catch{}}function SM(e){return e.__sentry_original__}function lf(e){if(xy(e))return{message:e.message,name:e.name,stack:e.stack,...od(e)};if(Ly(e)){const t={type:e.type,target:sd(e.target),currentTarget:sd(e.currentTarget),...od(e)};return typeof CustomEvent<"u"&&Ho(e,CustomEvent)&&(t.detail=e.detail),t}else return e}function sd(e){try{return Dy(e)?Fy(e):Object.prototype.toString.call(e)}catch{return"<unknown>"}}function od(e){if(typeof e=="object"&&e!==null){const t={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t}else return{}}function EM(e,t=40){const r=Object.keys(lf(e));r.sort();const n=r[0];if(!n)return"[object has no keys]";if(n.length>=t)return xi(n,t);for(let i=r.length;i>0;i--){const s=r.slice(0,i).join(", ");if(!(s.length>t))return i===r.length?s:xi(s,t)}return""}function zt(e){return Ic(e,new Map)}function Ic(e,t){if(Vy(e)){const r=t.get(e);if(r!==void 0)return r;const n={};t.set(e,n);for(const i of Object.getOwnPropertyNames(e))typeof e[i]<"u"&&(n[i]=Ic(e[i],t));return n}if(Array.isArray(e)){const r=t.get(e);if(r!==void 0)return r;const n=[];return t.set(e,n),e.forEach(i=>{n.push(Ic(i,t))}),n}return e}function Vy(e){if(!jl(e))return!1;try{const t=Object.getPrototypeOf(e).constructor.name;return!t||t==="Object"}catch{return!0}}var uf=1e3;function Vl(){return Date.now()/uf}function By(){const{performance:e}=$t;if(!e||!e.now)return Vl;const t=Date.now()-e.now(),r=e.timeOrigin==null?t:e.timeOrigin;return()=>(r+e.now())/uf}var Bl=By(),_s,kM=(()=>{const{performance:e}=$t;if(!e||!e.now){_s="none";return}const t=36e5,r=e.now(),n=Date.now(),i=e.timeOrigin?Math.abs(e.timeOrigin+r-n):t,s=i<t,o=e.timing&&e.timing.navigationStart,a=typeof o=="number"?Math.abs(o+r-n):t;return s||a<t?i<=a?(_s="timeOrigin",e.timeOrigin):(_s="navigationStart",o):(_s="dateNow",n)})();function Ir(){const e=$t,t=e.crypto||e.msCrypto;let r=()=>Math.random()*16;try{if(t&&t.randomUUID)return t.randomUUID().replace(/-/g,"");t&&t.getRandomValues&&(r=()=>{const n=new Uint8Array(1);return t.getRandomValues(n),n[0]})}catch{}return"10000000100040008000100000000000".replace(/[018]/g,n=>(n^(r()&15)>>n/4).toString(16))}function df(e){return e.exception&&e.exception.values?e.exception.values[0]:void 0}function RM(e){const{message:t,event_id:r}=e;if(t)return t;const n=df(e);return n?n.type&&n.value?`${n.type}: ${n.value}`:n.type||n.value||r||"<unknown>":r||"<unknown>"}function AM(e,t,r){const n=e.exception=e.exception||{},i=n.values=n.values||[],s=i[0]=i[0]||{};s.value||(s.value=t||""),s.type||(s.type=r||"Error")}function Gy(e,t){const r=df(e);if(!r)return;const n={type:"generic",handled:!0},i=r.mechanism;if(r.mechanism={...n,...i,...t},t&&"data"in t){const s={...i&&i.data,...t.data};r.mechanism.data=s}}function IM(e){if(Wy(e))return!0;try{Zn(e,"__sentry_captured__",!0)}catch{}return!1}function Wy(e){try{return e.__sentry_captured__}catch{}}var sr;(function(e){e[e.PENDING=0]="PENDING";const r=1;e[e.RESOLVED=r]="RESOLVED";const n=2;e[e.REJECTED=n]="REJECTED"})(sr||(sr={}));function TM(e){return new Gl(t=>{t(e)})}function $M(e){return new Gl((t,r)=>{r(e)})}var Gl=class Xr{constructor(t){Xr.prototype.__init.call(this),Xr.prototype.__init2.call(this),Xr.prototype.__init3.call(this),Xr.prototype.__init4.call(this),this._state=sr.PENDING,this._handlers=[];try{t(this._resolve,this._reject)}catch(r){this._reject(r)}}then(t,r){return new Xr((n,i)=>{this._handlers.push([!1,s=>{if(!t)n(s);else try{n(t(s))}catch(o){i(o)}},s=>{if(!r)i(s);else try{n(r(s))}catch(o){i(o)}}]),this._executeHandlers()})}catch(t){return this.then(r=>r,t)}finally(t){return new Xr((r,n)=>{let i,s;return this.then(o=>{s=!1,i=o,t&&t()},o=>{s=!0,i=o,t&&t()}).then(()=>{if(s){n(i);return}r(i)})})}__init(){this._resolve=t=>{this._setResult(sr.RESOLVED,t)}}__init2(){this._reject=t=>{this._setResult(sr.REJECTED,t)}}__init3(){this._setResult=(t,r)=>{if(this._state===sr.PENDING){if(Hl(r)){r.then(this._resolve,this._reject);return}this._state=t,this._value=r,this._executeHandlers()}}}__init4(){this._executeHandlers=()=>{if(this._state===sr.PENDING)return;const t=this._handlers.slice();this._handlers=[],t.forEach(r=>{r[0]||(this._state===sr.RESOLVED&&r[1](this._value),this._state===sr.REJECTED&&r[2](this._value),r[0]=!0)})}}};function Zy(e){const t=Bl(),r={sid:Ir(),init:!0,timestamp:t,started:t,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>Ky(r)};return e&&Vo(r,e),r}function Vo(e,t={}){if(t.user&&(!e.ipAddress&&t.user.ip_address&&(e.ipAddress=t.user.ip_address),!e.did&&!t.did&&(e.did=t.user.id||t.user.email||t.user.username)),e.timestamp=t.timestamp||Bl(),t.abnormal_mechanism&&(e.abnormal_mechanism=t.abnormal_mechanism),t.ignoreDuration&&(e.ignoreDuration=t.ignoreDuration),t.sid&&(e.sid=t.sid.length===32?t.sid:Ir()),t.init!==void 0&&(e.init=t.init),!e.did&&t.did&&(e.did=`${t.did}`),typeof t.started=="number"&&(e.started=t.started),e.ignoreDuration)e.duration=void 0;else if(typeof t.duration=="number")e.duration=t.duration;else{const r=e.timestamp-e.started;e.duration=r>=0?r:0}t.release&&(e.release=t.release),t.environment&&(e.environment=t.environment),!e.ipAddress&&t.ipAddress&&(e.ipAddress=t.ipAddress),!e.userAgent&&t.userAgent&&(e.userAgent=t.userAgent),typeof t.errors=="number"&&(e.errors=t.errors),t.status&&(e.status=t.status)}function Jy(e,t){let r={};t?r={status:t}:e.status==="ok"&&(r={status:"exited"}),Vo(e,r)}function Ky(e){return zt({sid:`${e.sid}`,init:e.init,started:new Date(e.started*1e3).toISOString(),timestamp:new Date(e.timestamp*1e3).toISOString(),status:e.status,errors:e.errors,did:typeof e.did=="number"||typeof e.did=="string"?`${e.did}`:void 0,duration:e.duration,abnormal_mechanism:e.abnormal_mechanism,attrs:{release:e.release,environment:e.environment,ip_address:e.ipAddress,user_agent:e.userAgent}})}function ao(){return Ir()}function Jn(){return Ir().substring(16)}function Bo(e,t,r=2){if(!t||typeof t!="object"||r<=0)return t;if(e&&t&&Object.keys(t).length===0)return e;const n={...e};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[i]=Bo(n[i],t[i],r-1));return n}var Tc="_sentrySpan";function ad(e,t){t?Zn(e,Tc,t):delete e[Tc]}function $c(e){return e[Tc]}var Yy=100,Xy=class hf{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:ao(),spanId:Jn()}}clone(){const t=new hf;return t._breadcrumbs=[...this._breadcrumbs],t._tags={...this._tags},t._extra={...this._extra},t._contexts={...this._contexts},this._contexts.flags&&(t._contexts.flags={values:[...this._contexts.flags.values]}),t._user=this._user,t._level=this._level,t._session=this._session,t._transactionName=this._transactionName,t._fingerprint=this._fingerprint,t._eventProcessors=[...this._eventProcessors],t._requestSession=this._requestSession,t._attachments=[...this._attachments],t._sdkProcessingMetadata={...this._sdkProcessingMetadata},t._propagationContext={...this._propagationContext},t._client=this._client,t._lastEventId=this._lastEventId,ad(t,$c(this)),t}setClient(t){this._client=t}setLastEventId(t){this._lastEventId=t}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(t){this._scopeListeners.push(t)}addEventProcessor(t){return this._eventProcessors.push(t),this}setUser(t){return this._user=t||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&Vo(this._session,{user:t}),this._notifyScopeListeners(),this}getUser(){return this._user}getRequestSession(){return this._requestSession}setRequestSession(t){return this._requestSession=t,this}setTags(t){return this._tags={...this._tags,...t},this._notifyScopeListeners(),this}setTag(t,r){return this._tags={...this._tags,[t]:r},this._notifyScopeListeners(),this}setExtras(t){return this._extra={...this._extra,...t},this._notifyScopeListeners(),this}setExtra(t,r){return this._extra={...this._extra,[t]:r},this._notifyScopeListeners(),this}setFingerprint(t){return this._fingerprint=t,this._notifyScopeListeners(),this}setLevel(t){return this._level=t,this._notifyScopeListeners(),this}setTransactionName(t){return this._transactionName=t,this._notifyScopeListeners(),this}setContext(t,r){return r===null?delete this._contexts[t]:this._contexts[t]=r,this._notifyScopeListeners(),this}setSession(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(t){if(!t)return this;const r=typeof t=="function"?t(this):t,[n,i]=r instanceof xr?[r.getScopeData(),r.getRequestSession()]:jl(r)?[t,t.requestSession]:[],{tags:s,extra:o,user:a,contexts:c,level:l,fingerprint:u=[],propagationContext:h}=n||{};return this._tags={...this._tags,...s},this._extra={...this._extra,...o},this._contexts={...this._contexts,...c},a&&Object.keys(a).length&&(this._user=a),l&&(this._level=l),u.length&&(this._fingerprint=u),h&&(this._propagationContext=h),i&&(this._requestSession=i),this}clear(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._session=void 0,ad(this,void 0),this._attachments=[],this.setPropagationContext({traceId:ao()}),this._notifyScopeListeners(),this}addBreadcrumb(t,r){const n=typeof r=="number"?r:Yy;if(n<=0)return this;const i={timestamp:Vl(),...t};return this._breadcrumbs.push(i),this._breadcrumbs.length>n&&(this._breadcrumbs=this._breadcrumbs.slice(-n),this._client&&this._client.recordDroppedEvent("buffer_overflow","log_item")),this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(t){return this._attachments.push(t),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:$c(this)}}setSDKProcessingMetadata(t){return this._sdkProcessingMetadata=Bo(this._sdkProcessingMetadata,t,2),this}setPropagationContext(t){return this._propagationContext={spanId:Jn(),...t},this}getPropagationContext(){return this._propagationContext}captureException(t,r){const n=r&&r.event_id?r.event_id:Ir();if(!this._client)return cn.warn("No client configured on scope - will not capture exception!"),n;const i=new Error("Sentry syntheticException");return this._client.captureException(t,{originalException:t,syntheticException:i,...r,event_id:n},this),n}captureMessage(t,r,n){const i=n&&n.event_id?n.event_id:Ir();if(!this._client)return cn.warn("No client configured on scope - will not capture message!"),i;const s=new Error(t);return this._client.captureMessage(t,r,{originalException:t,syntheticException:s,...n,event_id:i},this),i}captureEvent(t,r){const n=r&&r.event_id?r.event_id:Ir();return this._client?(this._client.captureEvent(t,{...r,event_id:n},this),n):(cn.warn("No client configured on scope - will not capture event!"),n)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach(t=>{t(this)}),this._notifyingListeners=!1)}},xr=Xy;function Qy(){return qo("defaultCurrentScope",()=>new xr)}function e0(){return qo("defaultIsolationScope",()=>new xr)}var t0=class{constructor(e,t){let r;e?r=e:r=new xr;let n;t?n=t:n=new xr,this._stack=[{scope:r}],this._isolationScope=n}withScope(e){const t=this._pushScope();let r;try{r=e(t)}catch(n){throw this._popScope(),n}return Hl(r)?r.then(n=>(this._popScope(),n),n=>{throw this._popScope(),n}):(this._popScope(),r)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){const e=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:e}),e}_popScope(){return this._stack.length<=1?!1:!!this._stack.pop()}};function Kn(){const e=cs(),t=ql(e);return t.stack=t.stack||new t0(Qy(),e0())}function r0(e){return Kn().withScope(e)}function n0(e,t){const r=Kn();return r.withScope(()=>(r.getStackTop().scope=e,t(e)))}function cd(e){return Kn().withScope(()=>e(Kn().getIsolationScope()))}function i0(){return{withIsolationScope:cd,withScope:r0,withSetScope:n0,withSetIsolationScope:(e,t)=>cd(t),getCurrentScope:()=>Kn().getScope(),getIsolationScope:()=>Kn().getIsolationScope()}}function Go(e){const t=ql(e);return t.acs?t.acs:i0()}function Vr(){const e=cs();return Go(e).getCurrentScope()}function _n(){const e=cs();return Go(e).getIsolationScope()}function s0(){return qo("globalScope",()=>new xr)}function CM(...e){const t=cs(),r=Go(t);if(e.length===2){const[n,i]=e;return n?r.withSetScope(n,i):r.withScope(i)}return r.withScope(e[0])}function ls(){return Vr().getClient()}function PM(e){const{traceId:t,spanId:r,parentSpanId:n}=e.getPropagationContext();return zt({trace_id:t,span_id:r,parent_span_id:n})}var o0="_sentryMetrics";function a0(e){const t=e[o0];if(!t)return;const r={};for(const[,[n,i]]of t)(r[n]||(r[n]=[])).push(zt(i));return r}var c0="sentry.source",l0="sentry.sample_rate",u0="sentry.op",d0="sentry.origin",OM="sentry.idle_span_finish_reason",xM="sentry.measurement_unit",MM="sentry.measurement_value",LM="sentry.custom_span_name",DM="sentry.profile_id",NM="sentry.exclusive_time";function h0(e){if(e<400&&e>=100)return{code:1};if(e>=400&&e<500)switch(e){case 401:return{code:2,message:"unauthenticated"};case 403:return{code:2,message:"permission_denied"};case 404:return{code:2,message:"not_found"};case 409:return{code:2,message:"already_exists"};case 413:return{code:2,message:"failed_precondition"};case 429:return{code:2,message:"resource_exhausted"};case 499:return{code:2,message:"cancelled"};default:return{code:2,message:"invalid_argument"}}if(e>=500&&e<600)switch(e){case 501:return{code:2,message:"unimplemented"};case 503:return{code:2,message:"unavailable"};case 504:return{code:2,message:"deadline_exceeded"};default:return{code:2,message:"internal_error"}}return{code:2,message:"unknown_error"}}function zM(e,t){e.setAttribute("http.response.status_code",t);const r=h0(t);r.message!=="unknown_error"&&e.setStatus(r)}var p0="sentry-",f0=/^sentry-/;function pf(e){const t=v0(e);if(!t)return;const r=Object.entries(t).reduce((n,[i,s])=>{if(i.match(f0)){const o=i.slice(7);n[o]=s}return n},{});if(Object.keys(r).length>0)return r}function UM(e){if(e)return g0(Object.entries(e).reduce((t,[r,n])=>(n&&(t[`${p0}${r}`]=n),t),{}))}function v0(e){if(!(!e||!oo(e)&&!Array.isArray(e)))return Array.isArray(e)?e.reduce((t,r)=>{const n=ld(r);return Object.entries(n).forEach(([i,s])=>{t[i]=s}),t},{}):ld(e)}function ld(e){return e.split(",").map(t=>t.split("=").map(r=>decodeURIComponent(r.trim()))).reduce((t,[r,n])=>(r&&n&&(t[r]=n),t),{})}function g0(e){if(Object.keys(e).length!==0)return Object.entries(e).reduce((t,[r,n],i)=>{const s=`${encodeURIComponent(r)}=${encodeURIComponent(n)}`,o=i===0?s:`${t},${s}`;return o.length>8192?(jo&&cn.warn(`Not adding key: ${r} with val: ${n} to baggage header due to exceeding baggage size limits.`),t):o},"")}var m0=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$");function _0(e){if(!e)return;const t=e.match(m0);if(!t)return;let r;return t[3]==="1"?r=!0:t[3]==="0"&&(r=!1),{traceId:t[1],parentSampled:r,parentSpanId:t[2]}}function FM(e,t){const r=_0(e),n=pf(t);if(!r||!r.traceId)return{traceId:ao(),spanId:Jn()};const{traceId:i,parentSpanId:s,parentSampled:o}=r;return{traceId:i,parentSpanId:s,spanId:Jn(),sampled:o,dsc:n||{}}}function y0(e=ao(),t=Jn(),r){let n="";return r!==void 0&&(n=r?"-1":"-0"),`${e}-${t}${n}`}var ud=!1;function qM(e){const{spanId:t,traceId:r}=e.spanContext(),{data:n,op:i,parent_span_id:s,status:o,origin:a}=Wo(e);return zt({parent_span_id:s,span_id:t,trace_id:r,data:n,op:i,status:o,origin:a})}function b0(e){const{spanId:t,traceId:r,isRemote:n}=e.spanContext(),i=n?t:Wo(e).parent_span_id,s=n?Jn():t;return zt({parent_span_id:i,span_id:s,trace_id:r})}function jM(e){const{traceId:t,spanId:r}=e.spanContext(),n=Wl(e);return y0(t,r,n)}function dd(e){return typeof e=="number"?hd(e):Array.isArray(e)?e[0]+e[1]/1e9:e instanceof Date?hd(e.getTime()):Bl()}function hd(e){return e>9999999999?e/1e3:e}function Wo(e){if(S0(e))return e.getSpanJSON();try{const{spanId:t,traceId:r}=e.spanContext();if(w0(e)){const{attributes:n,startTime:i,name:s,endTime:o,parentSpanId:a,status:c}=e;return zt({span_id:t,trace_id:r,data:n,description:s,parent_span_id:a,start_timestamp:dd(i),timestamp:dd(o)||void 0,status:E0(c),op:n[u0],origin:n[d0],_metrics_summary:a0(e)})}return{span_id:t,trace_id:r}}catch{return{}}}function w0(e){const t=e;return!!t.attributes&&!!t.startTime&&!!t.name&&!!t.endTime&&!!t.status}function S0(e){return typeof e.getSpanJSON=="function"}function Wl(e){const{traceFlags:t}=e.spanContext();return t===1}function E0(e){if(!(!e||e.code===0))return e.code===1?"ok":e.message||"unknown_error"}var ln="_sentryChildSpans",Cc="_sentryRootSpan";function HM(e,t){const r=e[Cc]||e;Zn(t,Cc,r),e[ln]?e[ln].add(t):Zn(e,ln,new Set([t]))}function VM(e,t){e[ln]&&e[ln].delete(t)}function BM(e){const t=new Set;function r(n){if(!t.has(n)&&Wl(n)){t.add(n);const i=n[ln]?Array.from(n[ln]):[];for(const s of i)r(s)}}return r(e),Array.from(t)}function ff(e){return e[Cc]||e}function GM(){const e=cs(),t=Go(e);return t.getActiveSpan?t.getActiveSpan():$c(Vr())}function WM(){ud||(sf(()=>{console.warn("[Sentry] Deprecation warning: Returning null from `beforeSendSpan` will be disallowed from SDK version 9.0.0 onwards. The callback will only support mutating spans. To drop certain spans, configure the respective integrations directly.")}),ud=!0)}function k0(e){if(typeof __SENTRY_TRACING__=="boolean"&&!__SENTRY_TRACING__)return!1;const t=ls(),r=e||t&&t.getOptions();return!!r&&(r.enableTracing||"tracesSampleRate"in r||"tracesSampler"in r)}var R0="production",vf="_frozenDsc";function ZM(e,t){Zn(e,vf,t)}function gf(e,t){const r=t.getOptions(),{publicKey:n}=t.getDsn()||{},i=zt({environment:r.environment||"production",release:r.release,public_key:n,trace_id:e});return t.emit("createDsc",i),i}function JM(e,t){const r=t.getPropagationContext();return r.dsc||gf(r.traceId,e)}function A0(e){const t=ls();if(!t)return{};const r=ff(e),n=r[vf];if(n)return n;const i=r.spanContext().traceState,s=i&&i.get("sentry.dsc"),o=s&&pf(s);if(o)return o;const a=gf(e.spanContext().traceId,t),c=Wo(r),l=c.data||{},u=l[l0];u!=null&&(a.sample_rate=`${u}`);const h=l[c0],d=c.description;return h!=="url"&&d&&(a.transaction=d),k0()&&(a.sampled=String(Wl(r))),t.emit("createDsc",a,r),a}function I0(){const e=typeof WeakSet=="function",t=e?new WeakSet:[];function r(i){if(e)return t.has(i)?!0:(t.add(i),!1);for(let s=0;s<t.length;s++)if(t[s]===i)return!0;return t.push(i),!1}function n(i){if(e)t.delete(i);else for(let s=0;s<t.length;s++)if(t[s]===i){t.splice(s,1);break}}return[r,n]}function fr(e,t=100,r=1/0){try{return Pc("",e,t,r)}catch(n){return{ERROR:`**non-serializable** (${n})`}}}function T0(e,t=3,r=102400){const n=fr(e,t);return O0(n)>r?T0(e,t-1,r):n}function Pc(e,t,r=1/0,n=1/0,i=I0()){const[s,o]=i;if(t==null||["boolean","string"].includes(typeof t)||typeof t=="number"&&Number.isFinite(t))return t;const a=$0(e,t);if(!a.startsWith("[object "))return a;if(t.__sentry_skip_normalization__)return t;const c=typeof t.__sentry_override_normalization_depth__=="number"?t.__sentry_override_normalization_depth__:r;if(c===0)return a.replace("object ","");if(s(t))return"[Circular ~]";const l=t;if(l&&typeof l.toJSON=="function")try{return Pc("",l.toJSON(),c-1,n,i)}catch{}const u=Array.isArray(t)?[]:{};let h=0;const d=lf(t);for(const p in d){if(!Object.prototype.hasOwnProperty.call(d,p))continue;if(h>=n){u[p]="[MaxProperties ~]";break}const f=d[p];u[p]=Pc(p,f,c-1,n,i),h++}return o(t),u}function $0(e,t){try{if(e==="domain"&&t&&typeof t=="object"&&t._events)return"[Domain]";if(e==="domainEmitter")return"[DomainEmitter]";if(typeof global<"u"&&t===global)return"[Global]";if(typeof window<"u"&&t===window)return"[Window]";if(typeof document<"u"&&t===document)return"[Document]";if(cf(t))return"[VueViewModel]";if(zy(t))return"[SyntheticEvent]";if(typeof t=="number"&&!Number.isFinite(t))return`[${t}]`;if(typeof t=="function")return`[Function: ${Oy(t)}]`;if(typeof t=="symbol")return`[${String(t)}]`;if(typeof t=="bigint")return`[BigInt: ${String(t)}]`;const r=C0(t);return/^HTML(\w*)Element$/.test(r)?`[HTMLElement: ${r}]`:`[object ${r}]`}catch(r){return`**non-serializable** (${r})`}}function C0(e){const t=Object.getPrototypeOf(e);return t?t.constructor.name:"null prototype"}function P0(e){return~-encodeURI(e).split(/%..|./).length}function O0(e){return P0(JSON.stringify(e))}function Oc(e,t,r,n=0){return new Gl((i,s)=>{const o=e[n];if(t===null||typeof o!="function")i(t);else{const a=o({...t},r);Iy&&o.id&&a===null&&cn.log(`Event processor "${o.id}" dropped event`),Hl(a)?a.then(c=>Oc(e,c,r,n+1).then(i)).then(null,s):Oc(e,a,r,n+1).then(i).then(null,s)}})}var ys,pd,bs;function x0(e){const t=$t._sentryDebugIds;if(!t)return{};const r=Object.keys(t);return bs&&r.length===pd||(pd=r.length,bs=r.reduce((n,i)=>{ys||(ys={});const s=ys[i];if(s)n[s[0]]=s[1];else{const o=e(i);for(let a=o.length-1;a>=0;a--){const c=o[a],l=c&&c.filename,u=t[i];if(l&&u){n[l]=u,ys[i]=[l,u];break}}}return n},{})),bs}function M0(e,t){const{fingerprint:r,span:n,breadcrumbs:i,sdkProcessingMetadata:s}=t;L0(e,t),n&&z0(e,n),U0(e,r),D0(e,i),N0(e,s)}function fd(e,t){const{extra:r,tags:n,user:i,contexts:s,level:o,sdkProcessingMetadata:a,breadcrumbs:c,fingerprint:l,eventProcessors:u,attachments:h,propagationContext:d,transactionName:p,span:f}=t;ws(e,"extra",r),ws(e,"tags",n),ws(e,"user",i),ws(e,"contexts",s),e.sdkProcessingMetadata=Bo(e.sdkProcessingMetadata,a,2),o&&(e.level=o),p&&(e.transactionName=p),f&&(e.span=f),c.length&&(e.breadcrumbs=[...e.breadcrumbs,...c]),l.length&&(e.fingerprint=[...e.fingerprint,...l]),u.length&&(e.eventProcessors=[...e.eventProcessors,...u]),h.length&&(e.attachments=[...e.attachments,...h]),e.propagationContext={...e.propagationContext,...d}}function ws(e,t,r){e[t]=Bo(e[t],r,1)}function L0(e,t){const{extra:r,tags:n,user:i,contexts:s,level:o,transactionName:a}=t,c=zt(r);c&&Object.keys(c).length&&(e.extra={...c,...e.extra});const l=zt(n);l&&Object.keys(l).length&&(e.tags={...l,...e.tags});const u=zt(i);u&&Object.keys(u).length&&(e.user={...u,...e.user});const h=zt(s);h&&Object.keys(h).length&&(e.contexts={...h,...e.contexts}),o&&(e.level=o),a&&e.type!=="transaction"&&(e.transaction=a)}function D0(e,t){const r=[...e.breadcrumbs||[],...t];e.breadcrumbs=r.length?r:void 0}function N0(e,t){e.sdkProcessingMetadata={...e.sdkProcessingMetadata,...t}}function z0(e,t){e.contexts={trace:b0(t),...e.contexts},e.sdkProcessingMetadata={dynamicSamplingContext:A0(t),...e.sdkProcessingMetadata};const r=ff(t),n=Wo(r).description;n&&!e.transaction&&e.type==="transaction"&&(e.transaction=n)}function U0(e,t){e.fingerprint=e.fingerprint?Array.isArray(e.fingerprint)?e.fingerprint:[e.fingerprint]:[],t&&(e.fingerprint=e.fingerprint.concat(t)),e.fingerprint&&!e.fingerprint.length&&delete e.fingerprint}function KM(e,t,r,n,i,s){const{normalizeDepth:o=3,normalizeMaxBreadth:a=1e3}=e,c={...t,event_id:t.event_id||r.event_id||Ir(),timestamp:t.timestamp||Vl()},l=r.integrations||e.integrations.map(v=>v.name);F0(c,e),H0(c,l),i&&i.emit("applyFrameMetadata",t),t.type===void 0&&q0(c,e.stackParser);const u=B0(n,r.captureContext);r.mechanism&&Gy(c,r.mechanism);const h=i?i.getEventProcessors():[],d=s0().getScopeData();if(s){const v=s.getScopeData();fd(d,v)}if(u){const v=u.getScopeData();fd(d,v)}const p=[...r.attachments||[],...d.attachments];p.length&&(r.attachments=p),M0(c,d);const f=[...h,...d.eventProcessors];return Oc(f,c,r).then(v=>(v&&j0(v),typeof o=="number"&&o>0?V0(v,o,a):v))}function F0(e,t){const{environment:r,release:n,dist:i,maxValueLength:s=250}=t;e.environment=e.environment||r||"production",!e.release&&n&&(e.release=n),!e.dist&&i&&(e.dist=i),e.message&&(e.message=xi(e.message,s));const o=e.exception&&e.exception.values&&e.exception.values[0];o&&o.value&&(o.value=xi(o.value,s));const a=e.request;a&&a.url&&(a.url=xi(a.url,s))}function q0(e,t){const r=x0(t);try{e.exception.values.forEach(n=>{n.stacktrace.frames.forEach(i=>{r&&i.filename&&(i.debug_id=r[i.filename])})})}catch{}}function j0(e){const t={};try{e.exception.values.forEach(n=>{n.stacktrace.frames.forEach(i=>{i.debug_id&&(i.abs_path?t[i.abs_path]=i.debug_id:i.filename&&(t[i.filename]=i.debug_id),delete i.debug_id)})})}catch{}if(Object.keys(t).length===0)return;e.debug_meta=e.debug_meta||{},e.debug_meta.images=e.debug_meta.images||[];const r=e.debug_meta.images;Object.entries(t).forEach(([n,i])=>{r.push({type:"sourcemap",code_file:n,debug_id:i})})}function H0(e,t){t.length>0&&(e.sdk=e.sdk||{},e.sdk.integrations=[...e.sdk.integrations||[],...t])}function V0(e,t,r){if(!e)return null;const n={...e,...e.breadcrumbs&&{breadcrumbs:e.breadcrumbs.map(i=>({...i,...i.data&&{data:fr(i.data,t,r)}}))},...e.user&&{user:fr(e.user,t,r)},...e.contexts&&{contexts:fr(e.contexts,t,r)},...e.extra&&{extra:fr(e.extra,t,r)}};return e.contexts&&e.contexts.trace&&n.contexts&&(n.contexts.trace=e.contexts.trace,e.contexts.trace.data&&(n.contexts.trace.data=fr(e.contexts.trace.data,t,r))),e.spans&&(n.spans=e.spans.map(i=>({...i,...i.data&&{data:fr(i.data,t,r)}}))),e.contexts&&e.contexts.flags&&n.contexts&&(n.contexts.flags=fr(e.contexts.flags,3,r)),n}function B0(e,t){if(!t)return e;const r=e?e.clone():new xr;return r.update(t),r}function G0(e){if(e)return W0(e)?{captureContext:e}:J0(e)?{captureContext:e}:e}function W0(e){return e instanceof xr||typeof e=="function"}var Z0=["user","level","extra","contexts","tags","fingerprint","requestSession","propagationContext"];function J0(e){return Object.keys(e).some(t=>Z0.includes(t))}function K0(e,t){return Vr().captureException(e,G0(t))}function YM(e,t){const r=typeof t=="string"?t:void 0,n=typeof t!="string"?{captureContext:t}:void 0;return Vr().captureMessage(e,r,n)}function XM(e,t){return Vr().captureEvent(e,t)}function QM(e,t){_n().setContext(e,t)}function eL(e,t){_n().setTag(e,t)}function tL(e){_n().setUser(e)}function rL(){const e=ls();return!!e&&e.getOptions().enabled!==!1&&!!e.getTransport()}function nL(e){_n().addEventProcessor(e)}function iL(e){const t=ls(),r=_n(),n=Vr(),{release:i,environment:s=R0}=t&&t.getOptions()||{},{userAgent:o}=$t.navigator||{},a=Zy({release:i,environment:s,user:n.getUser()||r.getUser(),...o&&{userAgent:o},...e}),c=r.getSession();return c&&c.status==="ok"&&Vo(c,{status:"exited"}),mf(),r.setSession(a),n.setSession(a),a}function mf(){const e=_n(),t=Vr(),r=t.getSession()||e.getSession();r&&Jy(r),_f(),e.setSession(),t.setSession()}function _f(){const e=_n(),t=Vr(),r=ls(),n=t.getSession()||e.getSession();n&&r&&r.captureSession(n)}function sL(e=!1){if(e){mf();return}_f()}var A="u">typeof window?window:void 0,ut="u">typeof globalThis?globalThis:A,nt=ut?.navigator,N=ut?.document,je=ut?.location,Zi=ut?.fetch,Zl=ut?.XMLHttpRequest&&"withCredentials"in new ut.XMLHttpRequest?ut.XMLHttpRequest:void 0,vd=ut?.AbortController,Y0=ut?.CompressionStream,ft=nt?.userAgent;function yf(){return!(!A||A.navigator.onLine===!1)}var pi=typeof globalThis<"u"?globalThis:A;pi&&typeof self>"u"&&(pi.self=pi),pi&&typeof File>"u"&&(pi.File=function(){});var te=A??{},gd="0.9.0",lr={DEBUG:!1,LIB_VERSION:gd,LIB_NAME:"browser-common",JS_SDK_VERSION:gd},Vt=(function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.AiQueue="ai_queue",e.AiCaptureQueue="ai_capture_queue",e.LogsQueue="logs_queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.PushRegistered="push_registered",e.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysInProgress="surveys_in_progress",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e})({}),xc=(function(e){return e.GZipJS="gzip-js",e.Base64="base64",e})({}),X0=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"],Q0=["token"];function ue(e,t){return e.indexOf(t)!==-1}var Zo=function(e){return e.trim()},Mc=function(e){return e.replace(/^\$/,"")};function bf(e){var t;const r=[];return(t=JSON.stringify(e,function(n,i){if(typeof i=="bigint")return i.toString();if(typeof i!="function"&&typeof i!="symbol"){if(i instanceof Error)return{name:i.name,message:i.message,stack:i.stack};if(i&&typeof i=="object"){for(;r.length>0&&r[r.length-1]!==this;)r.pop();if(r.includes(i))return"[Circular]";r.push(i)}return i}}))!==null&&t!==void 0?t:"null"}var wf=Object.prototype,Jl=wf.hasOwnProperty,Jo=wf.toString,ce=Array.isArray||function(e){return Jo.call(e)==="[object Array]"},rt=e=>typeof e=="function",be=e=>e===Object(e)&&!ce(e),_t=e=>{if(be(e)){for(const t in e)if(Jl.call(e,t))return!1;return!0}return!1},O=e=>e===void 0,ye=e=>Jo.call(e)=="[object String]",Mi=e=>ye(e)&&e.trim().length===0,He=e=>e===null,ge=e=>O(e)||He(e),We=e=>Jo.call(e)=="[object Number]"&&e==e,tr=e=>We(e)&&e>0,gt=e=>Jo.call(e)==="[object Boolean]",eb=e=>ue(X0,e),tb=e=>ue(Q0,e);function Sf(e){return e===null||typeof e!="object"}function co(e,t){return{}.toString.call(e)===`[object ${t}]`}function ci(e){switch({}.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Ef(e,Error)}}function Kl(e){return"u">typeof Event&&Ef(e,Event)}function Ef(e,t){try{return e instanceof t}catch{return!1}}var rb=[!0,"true",1,"1","yes"],Ma=e=>ue(rb,e),nb=[!1,"false",0,"0","no"];function md(e,t,r,n,i,s,o){try{var a=e[s](o),c=a.value}catch(l){r(l);return}a.done?t(c):Promise.resolve(c).then(n,i)}function Ue(e){return function(){var t=this,r=arguments;return new Promise(function(n,i){var s=e.apply(t,r);function o(c){md(s,n,i,o,a,"next",c)}function a(c){md(s,n,i,o,a,"throw",c)}o(void 0)})}}var ib=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],_d=function(e,t=[]){if(!e)return!1;const r=e.toLowerCase();return ib.concat(t).some(n=>{const i=n.toLowerCase();return r.indexOf(i)!==-1})};function Wt(e,t,r,n,i){return t>r&&(n.warn("min cannot be greater than max."),t=r),We(e)?e>r?(n.warn(" cannot be greater than max: "+r+". Using max value instead."),r):t>e?(n.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(n.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+i),Wt(i??r,t,r,n))}var sb=class{constructor(e){this.C={},this.I=e.I,this.R=Wt(e.bucketSize,0,100,e.$),this.A=Wt(e.refillRate,0,this.R,e.$),this.O=Wt(e.refillInterval,0,864e5,e.$)}F(e,t){const r=Math.floor((t-e.lastAccess)/this.O);r>0&&(e.tokens=Math.min(e.tokens+r*this.A,this.R),e.lastAccess=e.lastAccess+r*this.O)}consumeRateLimit(e){var t;const r=Date.now(),n=String(e);let i=this.C[n];return i?this.F(i,r):(i={tokens:this.R,lastAccess:r},this.C[n]=i),i.tokens===0||(i.tokens--,i.tokens===0&&((t=this.I)===null||t===void 0||t.call(this,e)),i.tokens===0)}stop(){this.C={}}},Yn="Mobile",Ji="Android",lo="Tablet",kf="Android Tablet",Rf="iPad",Af="Apple Watch",js="Safari",Ko="BlackBerry",If="Samsung Internet",Hs="Chrome",Tf="Chrome iOS",$f="Internet Explorer",Cf="Internet Explorer Mobile",Pf="Opera",Of="Microsoft Edge",Vs="Firefox",xf="Firefox iOS",uo="Nintendo",ho="PlayStation",Yo="Xbox",Mf="Android Mobile",Lf="Mobile Safari",La="Windows",Df="Windows Phone",yd="Nokia",Lc="Ouya",ob="Generic "+Yn.toLowerCase(),Nf="Generic "+lo.toLowerCase(),Dc="Konqueror",zf="Oculus Browser",Uf="Vivaldi",Ff="Yandex",qf="Whale",jf="DuckDuckGo",Hf="Pale Moon",Vf="Waterfox",Nc="Brave",Bf="Claude",Gf="Codex",Wf="ChatGPT",Zf="Google Search App",Da=new RegExp("Version/(\\d+(\\.\\d+)?)"),Na=new RegExp("(Claude|Codex|ChatGPT)\\/(\\d+(\\.\\d+)?)"),ab=new RegExp(Yo,"i"),cb=new RegExp("PlayStation \\w+","i"),lb=new RegExp("Nintendo \\w+","i"),Yl=new RegExp("BlackBerry|PlayBook|BB10","i"),ub={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"},Jf=function(e,t,r,n){return t=t||"",(function(i){return i?.brave?Nc:null})(r)||(n?.detectGoogleSearchApp&&ue(e,"GSA/")?Zf:ue(e," OPR/")&&ue(e,"Mini")?"Opera Mini":ue(e," OPR/")?Pf:Yl.test(e)?Ko:ue(e,"IEMobile")||ue(e,"WPDesktop")?Cf:ue(e,"OculusBrowser")?zf:ue(e,"SamsungBrowser")?If:ue(e,"Edge")||ue(e,"Edg/")?Of:ue(e,"Vivaldi/")?Uf:ue(e,"YaBrowser/")?Ff:ue(e,"Whale/")?qf:ue(e,"DuckDuckGo/")||ue(e,"Ddg/")?jf:ue(e,"Claude/")?Bf:ue(e,"Codex/")?Gf:ue(e,"ChatGPT/")?Wf:ue(e,"FBIOS")?"Facebook Mobile":ue(e,"UCWEB")||ue(e,"UCBrowser")?"UC Browser":ue(e,"CriOS")?Tf:ue(e,"CrMo")||ue(e,Hs)?Hs:ue(e,Ji)&&ue(e,js)?Mf:ue(e,"FxiOS")?xf:ue(e.toLowerCase(),Dc.toLowerCase())?Dc:ue(e,"Brave/")?Nc:((i,s)=>s&&ue(s,"Apple")||(function(o){return ue(o,js)&&!ue(o,Hs)&&!ue(o,Ji)})(i))(e,t)?ue(e,Yn)?Lf:js:ue(e,"PaleMoon/")?Hf:ue(e,"Waterfox/")?Vf:ue(e,Vs)?Vs:ue(e,"MSIE")||ue(e,"Trident/")?$f:ue(e,"Gecko")?Vs:"")},db={[Cf]:[new RegExp("rv:(\\d+(\\.\\d+)?)")],[Of]:[new RegExp("Edge?\\/(\\d+(\\.\\d+)?)")],[Hs]:[new RegExp("(Chrome|CrMo)\\/(\\d+(\\.\\d+)?)")],[Tf]:[new RegExp("CriOS\\/(\\d+(\\.\\d+)?)")],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/(\\d+(\\.\\d+)?)")],[js]:[Da],[Lf]:[Da],[Pf]:[new RegExp("(Opera|OPR)\\/(\\d+(\\.\\d+)?)")],[Vs]:[new RegExp("Firefox\\/(\\d+(\\.\\d+)?)")],[xf]:[new RegExp("FxiOS\\/(\\d+(\\.\\d+)?)")],[Dc]:[new RegExp("Konqueror[:/]?(\\d+(\\.\\d+)?)","i")],[Ko]:[new RegExp("BlackBerry (\\d+(\\.\\d+)?)"),Da],[Mf]:[new RegExp("android\\s(\\d+(\\.\\d+)?)","i")],[If]:[new RegExp("SamsungBrowser\\/(\\d+(\\.\\d+)?)")],[zf]:[new RegExp("OculusBrowser\\/(\\d+(\\.\\d+)?)")],[Uf]:[new RegExp("Vivaldi\\/(\\d+(\\.\\d+)?)")],[Ff]:[new RegExp("YaBrowser\\/(\\d+(\\.\\d+)?)")],[qf]:[new RegExp("Whale\\/(\\d+(\\.\\d+)?)")],[Nc]:[new RegExp("Brave\\/(\\d+(\\.\\d+)?)")],[Bf]:[Na],[Gf]:[Na],[Wf]:[Na],[jf]:[new RegExp("(DuckDuckGo|Ddg)\\/(\\d+(\\.\\d+)?)")],[Hf]:[new RegExp("PaleMoon\\/(\\d+(\\.\\d+)?)")],[Vf]:[new RegExp("Waterfox\\/(\\d+(\\.\\d+)?)")],[Zf]:[new RegExp("GSA\\/(\\d+(\\.\\d+)?)")],[$f]:[new RegExp("(rv:|MSIE )(\\d+(\\.\\d+)?)")],Mozilla:[new RegExp("rv:(\\d+(\\.\\d+)?)")]},hb=function(e,t,r,n){const i=Jf(e,t,r,n),s=db[i];if(O(s))return null;for(let o=0;s.length>o;o++){const a=e.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},bd=[[new RegExp("Xbox; Xbox (.*?)[);]","i"),e=>[Yo,e&&e[1]||""]],[new RegExp(uo,"i"),[uo,""]],[new RegExp(ho,"i"),[ho,""]],[Yl,[Ko,""]],[new RegExp(La,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[Df,""];if(new RegExp(Yn).test(t)&&!/IEMobile\b/.test(t))return["Windows Mobile",""];const r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=ub[r[1]]||"";return/arm/i.test(t)&&(n="RT"),[La,n]}return[La,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>e&&e[3]?["iOS",[e[3],e[4],e[5]||"0"].join(".")]:["iOS",""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=O(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("(Android (\\d+)\\.(\\d+)\\.?(\\d+)?|Android)","i"),e=>e&&e[2]?[Ji,[e[2],e[3],e[4]||"0"].join(".")]:[Ji,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{const t=["Mac OS X",""];return e&&e[1]&&(t[1]=[e[1],e[2],e[3]||"0"].join(".")),t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,["Chrome OS",""]],[/Linux|debian/i,["Linux",""]]],Kf=function(e){for(let t=0;bd.length>t;t++){const[r,n]=bd[t],i=r.exec(e),s=i&&(rt(n)?n(i,e):n);if(s)return s}return["",""]},Yf=function(e){return lb.test(e)?uo:cb.test(e)?ho:ab.test(e)?Yo:new RegExp(Lc,"i").test(e)?Lc:new RegExp("(Windows Phone|WPDesktop)","i").test(e)?Df:/iPad/.test(e)?Rf:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?Af:Yl.test(e)?Ko:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(yd,"i").test(e)?yd:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(e)||/(kf[a-z]+)( bui|\)).+silk\//i.test(e)?"Kindle Fire":/(Android|ZTE)/i.test(e)?new RegExp(Yn).test(e)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(e)||/pixel[\daxl ]{1,6}/i.test(e)&&!/pixel c/i.test(e)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(e)||/lmy47v/i.test(e)&&!/QTAQZ3/i.test(e)?Ji:kf:new RegExp("(pda|Mobile)","i").test(e)?ob:new RegExp(lo,"i").test(e)&&!new RegExp("Tablet pc","i").test(e)?Nf:""},pb=function(e,t){var r;const n=Yf(e);return n===Rf||n===kf||n==="Kobo"||n==="Kindle Fire"||n===Nf?lo:n===uo||n===Yo||n===ho||n===Lc?"Console":n===Af?"Wearable":n?Yn:t?.userAgentDataPlatform==="Android"&&((r=t?.maxTouchPoints)!==null&&r!==void 0?r:0)>0?600>Math.min((i=t?.screenWidth)!==null&&i!==void 0?i:0,(s=t?.screenHeight)!==null&&s!==void 0?s:0)/((o=t?.devicePixelRatio)!==null&&o!==void 0?o:1)?Yn:lo:"Desktop";var i,s,o},za=/\bFBAV\/(\d+(?:\.\d+)*)/i,wd=[[/\bInstagram(?:[ /](\d+(?:\.\d+)*))?\b/i,"Instagram"],[/\bBarcelona[ /](\d+(?:\.\d+)*)?/i,"Threads"],[/\b(?:MessengerForiOS|(?:FBAN|FB_IAB)\/Orca-Android)\b/i,"Messenger",za],[/\bFBAN\/EMA\b/i,"Facebook Lite",za],[/\b(?:FBIOS|(?:FBAN|FB_IAB)\/(?:FB4A|FBIOS))\b/i,"Facebook",za],[/\bLinkedInApp(?:\]?\/(\d+(?:\.\d+)*))?\b/i,"LinkedIn"],[/\bTwitter(?:Android| for (?:iPhone|iPad|Android))(?:\/(\d+(?:\.\d+)*))?\b/i,"Twitter"],[/\b(?:musical_ly|trill)(?:[_/](\d+\.\d+(?:\.\d+)*))?(?=\b|_)/i,"TikTok",/\bapp_version\/(\d+(?:\.\d+)*)/i],[/\b(?:MicroMessenger|WeChat)\/(\d+(?:\.\d+)*)?/i,"WeChat"],[/\bLine\/(\d+(?:\.\d+)*)?/i,"Line"],[/\bGSA\/(\d+(?:\.\d+)*)?/i,"Google"],[/\[Pinterest\/(?:iOS|Android)\b|\bPinterest(?: for (?:Android(?: Tablet)?|iOS))?\/(\d+(?:\.\d+)*)/i,"Pinterest"],[/\b(?:WA4A|WAiOS)\/(\d+(?:\.\d+)*)?/i,"WhatsApp"],[/\bSnapchat[ /](\d+(?:\.\d+)*)?/i,"Snapchat"],[/\bBing(?:Web|Sapphire)\/(\d+(?:\.\d+)*)?/i,"Bing"],[/\bNAVER\(inapp; search;/i,"Naver",/\bNAVER\(inapp; search;[^;)]*; (\d+(?:\.\d+)*)/i],[/\bKAKAOTALK[ /](\d+\.\d+(?:\.\d+)*)?/i,"KakaoTalk"]],zc="[Truncated]",us="[Unserializable]";function jn(e){let t="";for(let r=0;e.length>r;r++){const n=e.charCodeAt(r);if(55296>n||n>56319)t+=56320>n||n>57343?e[r]:"�";else{const i=e.charCodeAt(r+1);56320>i||i>57343?t+="�":(t+=e[r]+e[r+1],r++)}}return t}function Xf(e,t){if(!t)return e;let r=[];try{r=Object.keys(t)}catch{r=[]}for(const n of r){let i;try{i=t[n]}catch{i=us}Object.defineProperty(e,n,{value:i,enumerable:!0,writable:!0,configurable:!0})}return e}var Bs=3e5,Qf=class{record(e){if(e.kind==="too-large")return;if(e.kind!=="retry-later")return void this.reset();if(!e.retryAfterMs)return;const t=this.isOpen(),r=Date.now(),n=Math.min(e.retryAfterMs,Bs);if(!t)return this.ts=r,void(this.es=r+n);this.es=Math.max(this.es,Math.min(r+n,this.ts+Bs))}remainingMs(){const e=Date.now();if(this.ts-5e3>e)return this.reset(),0;const t=Math.min(Bs,Math.max(0,this.es-e));return t===0&&this.reset(),t}isOpen(){return this.remainingMs()>0}reset(){this.es=0,this.ts=0}constructor(){this.es=0,this.ts=0}},fb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Sd(e,t){return typeof(r=e)=="string"&&fb.test(r)?e:t();var r}function ev(e,t){const r=new Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function Mr(e){return e&&e.split("#")[0]}function Ed(e){try{return e()}catch{return}}function tv(e,t){const r=setTimeout(e,t);return r!=null&&r.unref&&r?.unref(),r}function kd(e,t,r){return rv.apply(this,arguments)}function rv(){return(rv=Ue(function*(e,t,r){let n;try{return yield Promise.race([e,new Promise((i,s)=>{n=tv(()=>{try{r?.(),i()}catch(o){s(o)}},t)})])}finally{clearTimeout(n)}})).apply(this,arguments)}var Ss,Rd,Ua;function vb(e){const t=globalThis._posthogChunkIds;if(!t)return;const r=Object.keys(t);return Ua&&r.length===Rd||(Rd=r.length,Ua=r.reduce((n,i)=>{Ss||(Ss={});const s=Ss[i];if(s)n[s[0]]=s[1];else{const o=e(i);for(let a=o.length-1;a>=0;a--){const c=o[a],l=c?.filename,u=t[i];if(l&&u){n[l]=u,Ss[i]=[l,u];break}}}return n},{})),Ua}function Li(e){return Li=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Li(e)}function gb(e,t,r){return(t=(function(n){var i=(function(s){if(Li(s)!="object"||!s)return s;var o=s[Symbol.toPrimitive];if(o!==void 0){var a=o.call(s,"string");if(Li(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(s)})(n);return Li(i)=="symbol"?i:i+""})(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Ad(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function b(e){for(var t=1;arguments.length>t;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Ad(Object(r),!0).forEach(function(n){gb(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Ad(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}var mb=class{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){const r=t&&t.mechanism||{handled:!0,type:"generic"},n=this.buildCoercingContext(r,t,0).apply(e),i=this.buildParsingContext(t),s=this.parseStacktrace(n,i);return{$exception_list:this.convertToExceptionList(s,r),$exception_level:"error"}}modifyFrames(e){var t=this;return Ue(function*(){for(const r of e)r.stacktrace&&r.stacktrace.frames&&ce(r.stacktrace.frames)&&(r.stacktrace.frames=yield t.applyModifiers(r.stacktrace.frames));return e})()}coerceFallback(e){var t;return{type:"Error",value:"Unknown error",stack:(t=e.syntheticException)===null||t===void 0?void 0:t.stack,synthetic:!0}}parseStacktrace(e,t){var r;let n,i;if(e.cause!=null&&(n=this.parseStacktrace(e.cause,t)),e.stack!=""&&e.stack!=null)try{i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)}catch{}return b(b({},e),{},{cause:n,stack:i,errors:(r=e.errors)===null||r===void 0?void 0:r.map(s=>this.parseStacktrace(s,t))})}applyChunkIds(e,t){return e.map(r=>(r.filename&&t&&(r.chunk_id=t[r.filename]),r))}applyCoercers(e,t){for(const r of this.coercers)if(r.match(e))return r.coerce(e,t);return this.coerceFallback(t)}applyModifiers(e){var t=this;return Ue(function*(){let r=e;for(const n of t.modifiers)r=yield n(r);return r})()}convertToExceptionList(e,t){const r=[],n=(i,s,o)=>{var a;const c=r.length,l=s===void 0?b(b({type:typeof t.type=="string"&&t.type.length>0?t.type:"generic"},typeof t.handled=="boolean"?{handled:t.handled}:t.handled===void 0?{handled:!0}:{}),{},{synthetic:typeof t.synthetic=="boolean"?t.synthetic:i.synthetic,exception_id:c}):{type:"chained",source:o,synthetic:i.synthetic,exception_id:c,parent_id:s},u={type:i.type,value:i.value,mechanism:l};i.stack&&(u.stacktrace={type:"raw",frames:i.stack}),r.push(u),i.cause&&n(i.cause,c,"cause");for(const h of(a=i.errors)!==null&&a!==void 0?a:[])n(h,c,"member")};return n(e),r}buildParsingContext(e){var t;return{chunkIdMap:vb(this.stackParser),skipFirstLines:(t=e.skipFirstLines)!==null&&t!==void 0?t:1}}getAggregateErrors(e){try{if(ci(e)){let r=Object.getPrototypeOf(e);for(let n=0;r&&100>n;n++){var t;const i=(t=Object.getOwnPropertyDescriptor(r,"constructor"))===null||t===void 0?void 0:t.value;if(typeof i=="function"&&i.name==="AggregateError"){const s=e.errors;return ce(s)?s:void 0}r=Object.getPrototypeOf(r)}}}catch{}}buildCoercingContext(e,t,r=0){let n=0,i=0,s=!1;const o=new Set,a=[],c={},l=(d,p,f=0)=>{const v=u(p,f),m=v.apply;if(v.apply=C=>{a.push(d);try{return m(C)}finally{a.pop()}},f>4||f>0&&a.indexOf(d)!==-1)return this.coerceFallback(v);const _=typeof d=="object"&&d!==null||typeof d=="function";if(f===0&&n>=50||_&&o.has(d))return;_&&o.add(d),f===0&&n++;const w=this.getAggregateErrors(d);let S,T;s||(s=!!w);try{if(S=this.applyCoercers(d,v),!S)throw c}catch(C){if(C===c)return void(f===0&&n--);if(!s)throw C;S=this.coerceFallback(v)}if(!w||n>=50)return S;try{T=w.length}catch{return S}if(!Number.isInteger(T)||0>T||T>4294967295)return S;const I=[];for(let C=0;50>n&&1e3>i&&T>C;C++){let M;i++;try{M=v.next(w[C])}catch{n++,M=this.coerceFallback(u(p+1))}M&&I.push(M)}return b(b({},S),{},{errors:I})},u=(d,p=0)=>b(b({},t),{},{syntheticException:d==0?t.syntheticException:void 0,mechanism:d==0?e:{},apply(f){const v=l(f,d,p+1);if(!v)throw c;return v},next:f=>l(f,d+1)}),h=u(r);return b(b({},h),{},{apply:d=>{var p;return(p=l(d,r))!==null&&p!==void 0?p:this.coerceFallback(h)}})}},_b=/^([a-z][a-z0-9.+-]+):/i,yb=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function bb(e){if(!e||e==="<anonymous>")return!1;const t=_b.exec(e);return!t||yb.includes(t[1].toLowerCase())}function Uc(e,t,r,n,i){const s={platform:e,filename:t,function:r==="<anonymous>"?"?":r,in_app:bb(t)};return O(n)||(s.lineno=n),O(i)||(s.colno=i),s}var nv=(e,t)=>{const r=e.indexOf("safari-extension")!==-1,n=e.indexOf("safari-web-extension")!==-1;return r||n?[e.indexOf("@")!==-1?e.split("@")[0]:"?",r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},wb=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Sb=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Eb=/\((\S*)(?::(\d+))(?::(\d+))\)/,kb=(e,t)=>{const r=wb.exec(e);if(r){const[,i,s,o]=r;return Uc(t,i,"?",+s,+o)}const n=Sb.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){const o=Eb.exec(n[2]);o&&(n[2]=o[1],n[3]=o[2],n[4]=o[3])}const[i,s]=nv(n[1]||"?",n[2]);return Uc(t,s,i,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}},Rb=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Ab=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Ib=(e,t)=>{const r=Rb.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){const s=Ab.exec(r[3]);s&&(r[1]=r[1]||"eval",r[3]=s[1],r[4]=s[2],r[5]="")}let n=r[3],i=r[1]||"?";return[i,n]=nv(i,n),Uc(t,n,i,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}},Id=/\(error: (.*)\)/;function Xl(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function Tb(e){for(let t=1;10>=t;t++){const r=e.length-2*t;if(0>r)break;let n=!0;for(let i=0;t>i;i++)if(!Xl(e[r+i],e[r+t+i])){n=!1;break}if(n){for(let i=0;t>i;i++)e[r+i]=e[r+t+i];return e.length=r+t,{start:r,length:t}}}}function $b(e,t){const r=t.start+t.length,n=sv(e,t);n&&e.splice(r+n===e.length?r:t.start,n)}function iv(e,t){let r=t.start;for(;r>0&&Xl(e[r-1],e[r-1+t.length]);)r--;return t.start-r}function sv(e,t){const r=t.start+t.length;let n=r;for(;e.length>n&&Xl(e[n],e[n-t.length]);)n++;return n-r}function Cb(e,t){const r=t[0];let n=e.length-(r?iv(e,r):0);for(const i of t)n-=sv(e,i);return n}function Pb(e,t,r){for(let n=0;e.length>n;n++){const i=e[(t+n)%e.length],s=e[(r+n)%e.length];if(i!==s)return s>i}return!1}var Ob=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){const r=ye(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){const t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return co(e,"DOMException")}isDOMError(e){return co(e,"DOMError")}},xb=class{match(e){return ci(e)}coerce(e,t){var r;const n=this.getStack(e),i=n===void 0?(r=t.syntheticException)===null||r===void 0?void 0:r.stack:void 0,s=!!i;return{type:this.getType(e),value:this.getMessage(e,t),stack:n??i,cause:e.cause?t.next(e.cause):void 0,synthetic:s}}getType(e){return e.name||e.constructor.name}getMessage(e,t){const r=e.message;return String(r.error&&typeof r.error.message=="string"?r.error.message:r)}getStack(e){try{const t=e.stacktrace;if(typeof t=="string"&&t.length>0)return t;const r=e.stack;return typeof r=="string"&&r.length>0?r:void 0}catch{return}}},Mb=class{match(e){return!!co(e,"ErrorEvent")&&(e.error!=null||this.ur(e))}coerce(e,t){var r;if(e.error!=null)return t.apply(e.error);const n=t.apply(e.message);return b(b({},n),{},{stack:(r=this.cr(e))!==null&&r!==void 0?r:n.stack,synthetic:!0})}ur(e){return ye(e.message)&&e.message.length>0}cr(e){var t,r;const n=e,i=(t=n.lineno)!==null&&t!==void 0?t:0,s=(r=n.colno)!==null&&r!==void 0?r:0;if(ye(n.filename)&&n.filename.length!==0&&i!==0)return`Error
6
- at ${n.filename}:${i}:${s}`}},Lb=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,Db=class{match(e){return typeof e=="string"}coerce(e,t){var r;const[n,i]=this.getInfos(e);return{type:n??"Error",value:i??e,stack:(r=t.syntheticException)===null||r===void 0?void 0:r.stack,synthetic:!0}}getInfos(e){let t="Error",r=e;const n=e.match(Lb);return n&&(t=n[1],r=n[2]),[t,r]}},Nb=["fatal","error","warning","log","info","debug"];function ov(e,t=40){const r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){const i=r.slice(0,n).join(", ");if(t>=i.length)return n===r.length?i:i.length>t?`${i.slice(0,t)}...`:i}return""}var zb=class{match(e){return typeof e=="object"&&e!==null}coerce(e,t){var r,n;const i=this.getErrorPropertyFromObject(e);return i?t.apply(i):{type:this.getType(e),value:this.getValue(e),stack:(r=this.getStack(e))!==null&&r!==void 0?r:(n=t.syntheticException)===null||n===void 0?void 0:n.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(Kl(e))return e.constructor.name;const t="name"in e?e.name:void 0;return ye(t)&&!Mi(t)?t:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let r=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(r+=` with message: '${e.message}'`),r}if("message"in e&&typeof e.message=="string")return e.message;const t=this.getObjectClassName(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${ov(e)}`}isSeverityLevel(e){return ye(e)&&!Mi(e)&&Nb.indexOf(e)>=0}getStack(e){try{return ye(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:ye(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(const t in e)if({}.hasOwnProperty.call(e,t)){const r=e[t];if(ci(r))return r}}getObjectClassName(e){try{const t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}},Ub=class{match(e){return Kl(e)}coerce(e,t){var r;const n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${ov(e)}`,stack:(r=t.syntheticException)===null||r===void 0?void 0:r.stack,synthetic:!0}}},Fb=class{match(e){return Sf(e)}coerce(e,t){var r;return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:(r=t.syntheticException)===null||r===void 0?void 0:r.stack,synthetic:!0}}},qb=class{match(e){return co(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Kl(e))return!1;try{const t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){var r;const n=this.getUnhandledRejectionReason(e);return Sf(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:(r=t.syntheticException)===null||r===void 0?void 0:r.stack,synthetic:!0}:t.apply(n)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}},po="$message",fo="$timestamp",jb=new Set([po,fo]),Fa={enabled:!0,max_bytes:32768};function vo(e){var t;return e?{enabled:(t=e.enabled)!==null&&t!==void 0?t:Fa.enabled,max_bytes:Vb(e.max_bytes,Fa.max_bytes)}:b({},Fa)}var Hb=class{constructor(e){this.ns=[],this.ss=0,this.Rr=vo(e)}setConfig(e){this.Rr=vo(e),this.rs()}add(e){const t=(function(n){let i;try{i=bf(n)}catch{return}try{const s=JSON.parse(i);if(!be(s))return;const o=s,a=o[po],c=o[fo];return!ye(a)||a.trim().length===0||!ye(c)&&!We(c)?void 0:{step:o,json:i}}catch{return}})(e);if(!t)return;const r=(function(n){if("u">typeof TextEncoder)return new TextEncoder().encode(n).length;const i=encodeURIComponent(n);let s=0;for(let o=0;i.length>o;o++)i[o]==="%"?(s+=1,o+=2):s+=1;return s})(t.json);r>this.Rr.max_bytes||(this.ns.push({step:t.step,bytes:r}),this.ss+=r,this.rs())}getAttachable(){return this.ns.map(e=>e.step)}clear(){this.ns=[],this.ss=0}size(){return this.ns.length}rs(){for(;this.ss>this.Rr.max_bytes&&this.ns.length>0;){const e=this.ns.shift();e&&(this.ss-=e.bytes)}}};function Vb(e,t){if(!We(e)||e===1/0||e===-1/0)return t;const r=Math.floor(e);return 0>r?t:r}var Td=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};function $d(e){return typeof e=="string"||e}function Cd(e){return typeof e=="string"?e:void 0}var Bb=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],av="NativeGzipValidationError",Fc=e=>e.length>=2&&e[0]===31&&e[1]===139,Pd=(e,t)=>e===xc.GZipJS||t===xc.GZipJS||t==="gzip",Od=e=>!(!e||typeof e!="object")&&("name"in e?String(e.name):"")==="NotReadableError",fi,Es=e=>{throw ev(av,`Native gzip produced invalid output: ${e}`)},Gb=(xd=Ue(function*(e,t){18>e.size&&Es("too-short");const r=new Uint8Array(yield e.slice(0,10).arrayBuffer());Fc(r)&&r[2]===8||Es("invalid-header");const n=new DataView(yield e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==(s=>{const o=(()=>{if(fi)return fi;fi=[];for(let c=0;256>c;c++){let l=c;for(let u=0;8>u;u++)l=1&l?3988292384^l>>>1:l>>>1;fi[c]=l>>>0}return fi})();let a=4294967295;for(let c=0;s.length>c;c++)a=o[255&(a^s[c])]^a>>>8;return(4294967295^a)>>>0})(t)&&Es("invalid-crc");const i=t.length>>>0;n.getUint32(4,!0)!==i&&Es("invalid-size")}),function(e,t){return xd.apply(this,arguments)}),xd;function qc(){return qc=Ue(function*(e,t=!0,r){try{const i=new TextEncoder().encode(e),s=new globalThis.CompressionStream("gzip"),o=s.writable.getWriter(),a=o.write(i).then(()=>o.close()).catch((n=Ue(function*(u){try{yield o.abort(u)}catch{}throw u}),function(u){return n.apply(this,arguments)})),c=new Response(s.readable).blob(),[l]=yield Promise.all([c,a]);return yield Gb(l,i),l}catch(i){if(r?.rethrow)throw i;return t&&console.error("Failed to gzip compress data",i),null}var n}),qc.apply(this,arguments)}function cv(e,t){if(e==null)return{};var r,n,i=(function(o,a){if(o==null)return{};var c={};for(var l in o)if({}.hasOwnProperty.call(o,l)){if(a.includes(l))continue;c[l]=o[l]}return c})(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(n=0;s.length>n;n++)t.includes(r=s[n])||{}.propertyIsEnumerable.call(e,r)&&(i[r]=e[r])}return i}var Wb={}.propertyIsEnumerable;function go(e,t){try{return lv(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function Ql(e,t,r,n){if(0>=r.remainingNodes)return{stringValue:zc};if(r.remainingNodes--,gt(e))return{boolValue:e};if(typeof e=="bigint")return(function(i,s){const o=i.toString(),a=BigInt("9223372036854775808");return i>=a||-a>i?(s?.debug(`Attribute ${o} is outside the int64 range; encoding it as a string`),{stringValue:o}):{intValue:o}})(e,t);if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if(typeof BigInt>"u")return{stringValue:String(e)};const i=BigInt(e).toString();return e>=9223372036854776e3||-9223372036854776e3>e?(t?.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i}):{intValue:i}}return{doubleValue:e}}if(typeof e=="string")return{stringValue:jn(e)};if(typeof e=="function")return{stringValue:"[Function]"};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(r.ancestors.has(e))return{stringValue:"[Circular]"};if(n>=20)return{stringValue:zc};if(e instanceof Date){const i=e.getTime(),s=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof s=="string"?jn(s):String(s)}}r.ancestors.add(e);try{try{const i=e.toJSON;if(typeof i=="function")return Ql(i.call(e),t,r,n+1)}catch{}return ce(e)?{arrayValue:{values:Zb(e,t,r,n+1)}}:{kvlistValue:{values:lv(e,t,r,n+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:jn(String(e))}}function Zb(e,t,r,n){const i=[],s=Math.min(e.length,1e3);let o=0;for(;s>o&&r.remainingNodes>0;o++)try{const a=o in e?e[o]:void 0;if(ge(a))continue;i.push(Ql(a,t,r,n))}catch{i.push({stringValue:us})}return e.length>o&&i.push({stringValue:zc}),i}function lv(e,t,r,n){const i=[];for(const s in e)if(Wb.call(e,s)){if(!s){t?.debug("Dropping an attribute with an empty key");continue}if(i.length>=1e3||0>=r.remainingNodes){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{const o=e[s];if(He(o)||O(o))continue;i.push({key:jn(s),value:Ql(o,t,r,n)})}catch{i.push({key:jn(s),value:{stringValue:us}})}}return i}function uv(e,t,r){return b(b(b(b({},Xf({},e.resourceAttributes)),{},{"service.name":e.serviceName||"unknown_service"},e.environment&&{"deployment.environment":e.environment}),e.serviceVersion&&{"service.version":e.serviceVersion}),{},{"telemetry.sdk.name":t,"telemetry.sdk.version":r})}var Jb=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function dv(e,t){const r=Xf({},e),n={};for(const i of Jb)({}).hasOwnProperty.call(r,i)&&(n[i]=r[i],delete r[i]);return[...go(r,t),...go(n,t)]}var Md={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"},hv={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},Kb=hv.info;function Yb(e){try{return jn(String(e))}catch{return us}}function Xb(e,t,r,n){const i=e.level||"info",{text:s,number:o}=hv[i]||Kb,a=(function(d=Date.now()){return String(d)+"000000"})(We(n)?n:void 0),c={};t.distinctId&&(c.posthogDistinctId=t.distinctId),t.sessionId&&(c.sessionId=t.sessionId),t.windowId&&(c["window.id"]=t.windowId),ge(t.sessionStartTimestamp)||(c.sessionStartTimestamp=String(t.sessionStartTimestamp)),ge(t.lastActivityTimestamp)||(c.lastActivityTimestamp=String(t.lastActivityTimestamp)),t.currentUrl&&(c["url.full"]=t.currentUrl),t.screenName&&(c["screen.name"]=t.screenName),t.appState&&(c["app.state"]=t.appState),t.activeFeatureFlags&&t.activeFeatureFlags.length>0&&(c.feature_flags=t.activeFeatureFlags);const l=b({},c),u=e.attributes;if(u){let d=[];try{d=Object.keys(u)}catch{d=[]}for(const p of d){let f;try{f=u[p]}catch{f=us}Object.defineProperty(l,p,{value:f,enumerable:!0,writable:!0,configurable:!0})}}const h={timeUnixNano:a,observedTimeUnixNano:a,severityNumber:o,severityText:s,body:{stringValue:Yb(e.body)},attributes:go(l,r)};return e.trace_id&&(h.traceId=e.trace_id),e.span_id&&(h.spanId=e.span_id),O(e.trace_flags)||(h.flags=e.trace_flags),h}function pv(e,t,r){return uv(e,t,r)}function fv(e,t,r,n){return{resourceLogs:[{resource:{attributes:dv(t)},scopeLogs:[{scope:{name:r,version:n},logRecords:e}]}]}}var vv=class{constructor(e){this.ls=e,this.us=0}get pending(){return!!this.hs}arm(e){this.clear(),this.us=Date.now()+e,this.hs=tv(()=>{this.hs=void 0,this.ls()},e)}armNoEarlierThan(e){this.hs&&Date.now()+e<=this.us||this.arm(e)}clear(){this.hs&&(clearTimeout(this.hs),this.hs=void 0)}};function gv(){return .75+.5*Math.random()}function mv(e,t,r,n){const i=Math.min(Math.max(0,t-1),6),s=e*Math.pow(2,i);return Math.round((n===void 0?s:Math.min(s,Math.max(n,e)))*r)}var Qb=class{constructor(e,t,r,n,i,s=()=>Promise.resolve(),o){var a;this._instance=e,this.Rr=t,this.$=r,this.cs=n,this.ds=i,this.vs=s,this.fs=o,this.ps=new vv(()=>this.gs()),this.ys=null,this.bs=0,this._s=0,this.ws=new Qf,this.ks=0,this.Ss=1,this.xs=0,this.Cs=0,this.$s=!1,this.Ts=t.maxBufferSize,this.Is=Math.max((a=t.maxQueueSize)!==null&&a!==void 0?a:t.maxBufferSize,t.maxBufferSize),this.Ms=t.flushIntervalMs,this.Es=t.maxBatchRecordsPerPost,this.Ps=t.rateCapWindowMs,this.Rs=t.maxLogsPerInterval}clearQueue(){this._s++,this._instance.setPersistedProperty(Vt.LogsQueue,[])}reset(){this.ps.clear(),this.xs=0,this.Cs=0,this.$s=!1,this.ks=0,this.Ss=1,this.ws.reset(),this.Es=this.Rr.maxBatchRecordsPerPost}onReconnect(){this.ks=0,this.Ss=1,this.ws.isOpen()?this.As()&&this.Fs():this.gs()}captureLog(e,t){var r;if(this._instance.isDisabled||this._instance.optedOut||!e?.body)return;const n=this.Os(e);if(n===null)return;if(!n.body)return void this.$.info("Log was rejected in beforeSend function");if(!this.Ds())return;const i={record:Xb(n,(r=t?.context)!==null&&r!==void 0?r:this.cs(),this.$,t?.occurredAtMs)};this.ds(()=>this.Ls(i))}Os(e){const t=this.Rr.beforeSend;if(!t)return e;const r=ce(t)?t:[t];let n=e;for(const i of r)try{const s=i(n);if(!s)return this.$.info("Log was rejected in beforeSend function"),null;n=s}catch(s){return this.$.error("Error in beforeSend function for log:",s),null}return n}Ds(){if(this.Rs===void 0)return!0;const e=Date.now(),t=e-this.xs;return this.Ps>t&&t>=0||(this.xs=e,this.Cs=0,this.$s=!1),this.Rs>this.Cs?(this.Cs++,!0):(this.$s||(this.$.warn(`captureLog dropping logs: exceeded ${this.Rs} logs per ${this.Ps}ms`),this.$s=!0),!1)}flush(){var e=this;return Ue(function*(){if(!e._instance.isDisabled)return e.ys||(e.ys=e.Ns().finally(()=>{e.ys=null})),e.ys})()}Ns(){var e=this;return Ue(function*(){var t;e.ps.clear();let r=(t=e._instance.getPersistedProperty(Vt.LogsQueue))!==null&&t!==void 0?t:[];if(r.length===0)return;const n=r.length;let i=0;for(;r.length>0&&n>i;){var s,o;const a=e._s;e.bs=0;const c=Math.min(r.length,e.Es),l=r.slice(0,c),u=fv(l.map(d=>d.record),e.qs(),(s=e.fs)!==null&&s!==void 0?s:e._instance.getLibraryId(),e._instance.getLibraryVersion()),h=yield e._instance.js(u);if(e._s!==a)return;if(h.kind==="too-large"&&l.length>1)e.Es=Math.max(1,Math.floor(l.length/2)),e.$.warn(`Logs batch of size ${l.length} was too large for the ingestion endpoint, reducing batch size to ${e.Es}`);else if(e.ws.record(h),e.ps.pending&&e.ps.arm(Math.max(e.Ms,e.ws.remainingMs())),h.kind==="retry-later"||(h.kind==="too-large"?e.$.warn("Dropping a single log record with batch size 1 — the record is larger than the server cap and cannot be split further."):h.kind==="ok"&&e.Rr.maxBatchRecordsPerPost>e.Es&&(e.Es=Math.min(e.Rr.maxBatchRecordsPerPost,e.Es+1)),yield e.Bs(l.length),r=(o=e._instance.getPersistedProperty(Vt.LogsQueue))!==null&&o!==void 0?o:[],i+=l.length,h.kind==="fatal"))throw h.error}})()}Bs(e){var t=this;return Ue(function*(){var r;const n=Math.max(0,e-t.bs),i=(r=t._instance.getPersistedProperty(Vt.LogsQueue))!==null&&r!==void 0?r:[];t._instance.setPersistedProperty(Vt.LogsQueue,i.slice(n)),yield t.vs()})()}qs(){return pv(this.Rr,this._instance.getLibraryId(),this._instance.getLibraryVersion())}Ls(e){var t;if(this._instance.optedOut)return;const r=(t=this._instance.getPersistedProperty(Vt.LogsQueue))!==null&&t!==void 0?t:[];this.Is>r.length||(r.shift(),this.bs++,this.$.info("Logs queue is full, dropping oldest record.")),r.push(e),this._instance.setPersistedProperty(Vt.LogsQueue,r),this.Ts>r.length||this.ws.isOpen()?this.Fs():this.gs()}Fs(){this.ps.pending||this.ps.arm(Math.max(this.Ms,this.ws.remainingMs()))}Hs(){return Math.max(mv(this.Ms,this.ks,this.Ss,3e4),this.ws.remainingMs())}As(){const e=this._instance.getPersistedProperty(Vt.LogsQueue);return!!e&&e.length>0}shutdown(e){var t=this;return Ue(function*(){t.ps.clear();const r=t.flush().catch(()=>{});e!==void 0?yield kd(r,e):yield r})()}flushWithTimeout(e){var t=this;return Ue(function*(){const r=t.flush();yield kd(r,e,()=>{r.catch(()=>{})})})()}gs(){this.flush().then(()=>{this.ks=0,this.Ss=1},e=>{this.ks++,this.Ss=gv(),this.$.error("PostHog logs flush failed:",e)}).finally(()=>{!this._instance.isDisabled&&this.As()&&this.ps.armNoEarlierThan(this.Hs())})}},qa=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ld(e){return String(e)+"000000"}function Dd(e,t,r,n){let i="";return n&&(i=Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(n[s])}`).join(",")),`${e}\0${t}\0${r??""}\0${i}`}var ew=class{constructor(e,t,r){this._instance=e,this.Rr=t,this.$=r,this.zs=new Map,this.ps=new vv(()=>this.flush().catch(n=>{this.$.error("Metrics flush failed:",n)})),this.ys=null,this.Us=!1,this.Ws=new Map,this.Vs=new Set,this.ws=new Qf,this.ks=0,this.Ss=1,this.Gs=0}count(e,t=1,r){this.Zs({name:e,type:"count",value:t,unit:r?.unit,attributes:r?.attributes})}gauge(e,t,r){this.Zs({name:e,type:"gauge",value:t,unit:r?.unit,attributes:r?.attributes})}histogram(e,t,r){this.Zs({name:e,type:"histogram",value:t,unit:r?.unit,attributes:r?.attributes})}flush(){var e=this;const t=this.ys,r=(function(){var n=Ue(function*(){t&&(yield t.catch(()=>{})),yield e.Qs()});return function(){return n.apply(this,arguments)}})()().finally(()=>{this.ys===r&&(this.ys=null)});return this.ys=r,r}drainWindow(){if(this.zs.size===0)return null;const e=this.zs;return this.zs=new Map,this.Us=!1,this.Ws=new Map,this.Vs=new Set,this.Js(e)}reset(){this.Gs++,this.ws.reset(),this.ks=0,this.Ss=1,this.ps.clear(),this.zs=new Map,this.ys=null,this.Us=!1,this.Ws=new Map,this.Vs=new Set}Zs(e){if(this._instance.isDisabled||this._instance.optedOut)return;const t=this.Os(e);if(t===null)return;if(!t.name||typeof t.name!="string")return void this.$.warn("Dropping metric with empty name");if(typeof t.value!="number"||!Number.isFinite(t.value))return void this.$.warn(`Dropping metric '${t.name}': value must be a finite number`);if(t.type==="count"&&0>t.value)return void this.$.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let r,n;try{r=t.attributes?b({},t.attributes):void 0,n=Dd(t.type,t.name,t.unit,r)}catch(o){this.$.warn(`Dropping metric '${t.name}': attributes could not be serialized`,o);return}let i=this.zs.get(n);if(!i){if(!this.Ks())return;i={name:t.name,type:t.type,unit:t.unit,attributes:r,windowStartMs:Date.now()},this.zs.set(n,i)}const s=this.Ws.get(t.name);s===void 0?this.Ws.set(t.name,t.type):s===t.type||this.Vs.has(t.name)||(this.Vs.add(t.name),this.$.warn(`Metric name '${t.name}' is already used as a ${s}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`)),this.Xs(i,t.value),this.Fs()}Ks(){return this.Rr.maxSeriesPerFlush>this.zs.size||(this.Us||(this.Us=!0,this.$.warn(`Metric series cap reached (${this.Rr.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}Xs(e,t){switch(e.type){case"count":var r;e.total=((r=e.total)!==null&&r!==void 0?r:0)+t;break;case"gauge":e.last=t;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:new Array(qa.length+1).fill(0)});const n=e.hist;n.count+=1,n.sum+=t,n.min=Math.min(n.min,t),n.max=Math.max(n.max,t),n.bucketCounts[(function(i,s){for(let o=0;s.length>o;o++)if(s[o]>=i)return o;return s.length})(t,qa)]+=1;break}}}Os(e){const t=this.Rr.beforeSend;if(!t)return e;const r=ce(t)?t:[t];let n=e;for(const i of r)try{const s=i(n);if(!s)return this.$.info("Metric was rejected in beforeSend function"),null;n=s}catch(s){return this.$.error("Error in beforeSend function for metric:",s),null}return n}Fs(){this.ps.pending||this.ps.arm(this.Hs())}Hs(){return Math.max(mv(this.Rr.flushIntervalMs,this.ks,this.Ss,3e4),this.ws.remainingMs())}Qs(){var e=this;return Ue(function*(){if(e.ps.clear(),e.zs.size===0)return;const t=e.zs;e.zs=new Map,e.Us=!1,e.Ws=new Map,e.Vs=new Set;const r=e.Gs,n=yield e._instance.Ys(e.Js(t));if(r===e.Gs)switch(e.ws.record(n),n.kind==="retry-later"?(e.ks++,e.Ss=gv()):(e.ks=0,e.Ss=1),e.ps.pending&&e.ps.arm(e.Hs()),n.kind){case"ok":return;case"retry-later":e.ho(t),e.ps.armNoEarlierThan(e.Hs());return;case"too-large":e.$.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":e.$.error("Failed to send metrics batch:",n.error);return}})()}Js(e){return t=this.vo(e),r=(function(s,o,a){return uv(s,o,a)})(this.Rr,this._instance.getLibraryId(),this._instance.getLibraryVersion()),n=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:dv(r)},scopeMetrics:[{scope:{name:n,version:i},metrics:t}]}]};var t,r,n,i}vo(e){const t=Ld(Date.now()),r=new Map;for(const o of e.values()){var n;const a=Dd(o.type,o.name,o.unit,void 0);let c=r.get(a);c||(c=b({name:o.name},o.unit&&{unit:o.unit}),o.type==="count"?c.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:o.type==="gauge"?c.gauge={dataPoints:[]}:c.histogram={aggregationTemporality:1,dataPoints:[]},r.set(a,c));const l=go((n=o.attributes)!==null&&n!==void 0?n:{},this.$),u=Ld(o.windowStartMs);if(o.type==="count"){var i;const h={attributes:l,startTimeUnixNano:u,timeUnixNano:t,asDouble:(i=o.total)!==null&&i!==void 0?i:0};c.sum.dataPoints.push(h)}else if(o.type==="gauge"){var s;const h={attributes:l,timeUnixNano:t,asDouble:(s=o.last)!==null&&s!==void 0?s:0};c.gauge.dataPoints.push(h)}else o.hist&&c.histogram.dataPoints.push({attributes:l,startTimeUnixNano:u,timeUnixNano:t,count:o.hist.count,sum:o.hist.sum,min:o.hist.min,max:o.hist.max,bucketCounts:o.hist.bucketCounts,explicitBounds:qa})}return Array.from(r.values())}ho(e){for(const[n,i]of e){const s=this.zs.get(n);if(s)switch(s.windowStartMs=Math.min(s.windowStartMs,i.windowStartMs),s.type){case"count":var t,r;s.total=((t=s.total)!==null&&t!==void 0?t:0)+((r=i.total)!==null&&r!==void 0?r:0);break;case"gauge":break;case"histogram":if(i.hist)if(s.hist){s.hist.count+=i.hist.count,s.hist.sum+=i.hist.sum,s.hist.min=Math.min(s.hist.min,i.hist.min),s.hist.max=Math.max(s.hist.max,i.hist.max);for(let o=0;s.hist.bucketCounts.length>o;o++)s.hist.bucketCounts[o]+=i.hist.bucketCounts[o]}else s.hist=i.hist}else this.Ks()&&this.zs.set(n,i)}}},_v=(e,{debugEnabled:t}={})=>{const r={N(n,...i){A&&(lr.DEBUG||A.POSTHOG_DEBUG||t)&&!O(A.console)&&A.console&&("__rrweb_original__"in A.console[n]?A.console[n].__rrweb_original__:A.console[n])(e,...i)},debug(...n){r.N("debug",...n)},info(...n){r.N("log",...n)},warn(...n){r.N("warn",...n)},error(...n){r.N("error",...n)},critical(...n){console.error(e,...n)},uninitializedWarning(n){r.error(`You must initialize PostHog before calling ${n}`)},createLogger:(n,i)=>_v(`${e} ${n}`,i)};return r},j=_v("[PostHog.js]"),Be=j.createLogger,tw=Be("[ExternalScriptsLoader]"),mo=e=>{const t=N?.querySelectorAll("script");if(t){for(let r=0;t.length>r;r++)if(t[r].src===e||t[r].getAttribute("src")===e)return t[r]}},Qr=(e,t,r)=>{if(e.config.disable_external_dependency_loading)return tw.warn(`${t} was requested but loading of external scripts is disabled.`),r("Loading of external scripts is disabled");const n=mo(t);if(n){if(n.__posthog_loading_callback_fired)return r();const s=n.__posthog_loading_error;return s?r(s):(n.addEventListener("load",o=>{n.__posthog_loading_callback_fired=!0,r(void 0,o)}),void n.addEventListener("error",o=>{n.__posthog_loading_error=o,r(o)}))}const i=()=>{if(!N)return r("document not found");if(mo(t))return Qr(e,t,r);let s=N.createElement("script");if(s.type="text/javascript",s.crossOrigin="anonymous",s.src=t,s.onload=a=>{s.__posthog_loading_callback_fired=!0,r(void 0,a)},s.onerror=a=>{s.__posthog_loading_error=a,r(a)},e.config.prepare_external_dependency_script&&(s=e.config.prepare_external_dependency_script(s)),!s)return r("prepare_external_dependency_script returned null");if(e.config.external_scripts_inject_target==="head")N.head.appendChild(s);else{const a=N.querySelectorAll("body > script");var o;a.length>0?(o=a[0].parentNode)===null||o===void 0||o.insertBefore(s,a[0]):N.body.appendChild(s)}};N?.body?i():N?.addEventListener("DOMContentLoaded",i)},ja={},Nd=(e,t)=>{let r=`/static/${t}.js?v=${e.version}`;return t==="toolbar"&&(r=`${r}&t=${Math.floor(Date.now()/3e5)*3e5}`),e.requestRouter.endpointFor("assets",r)};te.__PosthogExtensions__=te.__PosthogExtensions__||{},te.__PosthogExtensions__.loadExternalDependency=(e,t,r)=>{if(t==="remote-config"){const i=e.requestRouter.endpointFor("assets",`/array/${e.config.token}/config.js`);Qr(e,i,r);return}const n=e.config.strict_script_versioning;if(n){const i=e.requestRouter.endpointFor("assets",`/static/${e.version}/${t}.js`),s=ja[i];if(n==="fallback"&&s){if(mo(s))return void Qr(e,s,r);delete ja[i]}Qr(e,i,n==="fallback"?(o,a)=>{if(o)if(typeof o=="string")r(o);else{var c;const l=Nd(e,t);ja[i]=l;const u=mo(i);u==null||(c=u.parentNode)===null||c===void 0||c.removeChild(u),Qr(e,l,r)}else r(void 0,a)}:r);return}Qr(e,Nd(e,t),r)},te.__PosthogExtensions__.loadSiteApp=(e,t,r)=>{const n=e.requestRouter.endpointFor("api",t);Qr(e,n,r)},lr.DEBUG=!1,lr.LIB_VERSION="1.434.12",lr.LIB_NAME="web";var et=lr,rw="$people_distinct_id",Ot="distinct_id",eu="$device_id",Ha="$device_model",_o="__alias",nw="__cmpns",zd="$fbc",Hn="$fbc_persistence",Ud="$fbp",Di="$fbp_persistence",jc="__timers",yv="$autocapture_disabled_server_side",Hc="$heatmaps_enabled_server_side",Vc="$exception_capture_enabled_server_side",bv="$error_tracking_suppression_rules",Bc="$error_tracking_capture_extension_exceptions",Gc="$web_vitals_enabled_server_side",tu="$dead_clicks_enabled_server_side",ru="$product_tours_enabled_server_side",wv="$logs_capture_enabled_server_side",Sv="$web_vitals_allowed_metrics",Ni="$session_recording_remote_config",iw="$session_recording_enabled_server_side",sw="$replay_sample_rate",ow="$replay_override_sampling",aw="$replay_override_linked_flag",cw="$replay_override_url_trigger",lw="$replay_override_event_trigger",$n="$sesid",Ev="$session_is_sampled",uw="$session_past_minimum_duration",dw="$session_recording_url_trigger_activated_session",hw="$session_recording_event_trigger_activated_session",pw="$debug_first_full_snapshot_timestamp",fw="$sess_rec_flush_size",xt="$enabled_feature_flags",or="$active_feature_flags",Wc="$early_access_features",un="$feature_flag_details",Sr="$feature_flag_payloads",dn="$feature_flag_request_id",zi="$minimal_flag_called_events",Ht="$override_feature_flags",en="$override_feature_flag_payloads",Er="$stored_person_properties",kr="$stored_group_properties",kv="$groups",Zc="$surveys",yo="$surveys_loaded_at",Rv="$surveys_activated",Av="$surveys_activated_session",Iv="$surveys_activated_timestamps",Jc="ph_product_tours",vw="$product_tours_activated",gw="$product_tours_activated_session",mw="$conversations_widget_session_id",_w="$conversations_ticket_id",yw="$conversations_widget_state",bw="$conversations_user_traits",Rr="$flag_call_reported",Ii="$flag_call_reported_session_id",Ki="$feature_flag_errors",Tr="$feature_flag_evaluated_at",vt="$user_state",Kc="$client_session_props",ww="$capture_rate_limit",Tv="$initial_campaign_params",$v="$initial_referrer_info",Cn="$initial_person_info",nu="$epp",Va="$posthog_cookieless",Cv="$cookieless_mode",Pv="$sdk_debug_extensions_init_method",Ov="$sdk_debug_extensions_init_time_ms",xv="$sdk_debug_recording_script_not_loaded",Mv="$sdk_debug_replay_stale_config",Sw="$sdk_debug_replay_event_trigger_status",Ew="$sdk_debug_replay_linked_flag_trigger_status",kw="$sdk_debug_replay_matched_recording_trigger_groups",Rw="$sdk_debug_replay_pending_trigger_conditions",Aw="$sdk_debug_replay_remote_trigger_matching_config",Iw="$sdk_debug_replay_trigger_groups_count",Tw="$sdk_debug_replay_url_trigger_status",$w="$session_recording_start_reason",iu="PostHog loadExternalDependency extension not found.",ar="anonymous",Gs="identified",Lv="identified_only",Yi="visibilitychange",bo="beforeunload",su="$pageview",Fd="$pageleave",Dv="$identify",qd="$groupidentify";function Pn(e,t){ce(e)&&e.forEach(t)}function $e(e,t){if(!ge(e))if(ce(e))e.forEach(t);else if((r=>r instanceof FormData)(e))e.forEach((r,n)=>t(r,n));else for(const r in e)Jl.call(e,r)&&t(e[r],r)}var Le=function(e,...t){for(const r of t)for(const n in r)r[n]!==void 0&&(e[n]=r[n]);return e};function Ws(e){const t=Object.keys(e);let r=t.length;const n=new Array(r);for(;r--;)n[r]=[t[r],e[t[r]]];return n}var Cw=function(e){return function(...t){try{return e.apply(this,t)}catch(r){j.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),j.critical(r)}}},ou=function(e){const t={};return $e(e,function(r,n){(ye(r)&&r.length>0||We(r))&&(t[n]=r)}),t};function Nv(e){const t=b({},e);for(const r of["name","message","stack","cause","errors"])try{r in e&&(t[r]=e[r])}catch{}return t}var Pw=["herokuapp.com","vercel.app","netlify.app"];function Ow(e){const t=e?.hostname;if(!ye(t))return!1;const r=t.split(".").slice(-2).join(".");for(const n of Pw)if(r===n)return!1;return!0}function Ie(e,t,r,n){const{capture:i=!1,passive:s=!0}=n??{};e?.addEventListener(t,r,{capture:i,passive:s})}function Yc(e){return e.name==="ph_toolbar_internal"}var Ui=e=>{if(N){try{const t=e+"=",r=N.cookie.split(";").filter(n=>n.length);for(let n=0;r.length>n;n++){let i=r[n];for(;i.charAt(0)==" ";)i=i.substring(1,i.length);if(i.indexOf(t)===0)return decodeURIComponent(i.substring(t.length,i.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(e){return 0>e?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return We(e)&&isFinite(e)&&Math.floor(e)===e});var xw=class Xc{constructor(t){if(this.bytes=t,t.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(t,r,n,i){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(n)||!Number.isInteger(i)||0>t||0>r||0>n||0>i||t>0xffffffffffff||r>4095||n>1073741823||i>4294967295)throw new RangeError("invalid field value");const s=new Uint8Array(16);return s[0]=t/Math.pow(2,40),s[1]=t/Math.pow(2,32),s[2]=t/Math.pow(2,24),s[3]=t/Math.pow(2,16),s[4]=t/256,s[5]=t,s[6]=112|r>>>8,s[7]=r,s[8]=128|n>>>24,s[9]=n>>>16,s[10]=n>>>8,s[11]=n,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new Xc(s)}toString(){let t="";for(let r=0;this.bytes.length>r;r++)t=t+(this.bytes[r]>>>4).toString(16)+(15&this.bytes[r]).toString(16),r!==3&&r!==5&&r!==7&&r!==9||(t+="-");if(t.length!==36)throw new Error("Invalid UUIDv7 was generated");return t}clone(){return new Xc(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;16>r;r++){const n=this.bytes[r]-t.bytes[r];if(n!==0)return Math.sign(n)}return 0}},Mw=class{generate(){const e=this.generateOrAbort();if(!O(e))return e;{this.Ct=0;const t=this.generateOrAbort();if(O(t))throw new Error("Could not generate UUID after timestamp reset");return t}}generateOrAbort(){const e=(()=>{const t=Date.now();return We(t)&&isFinite(t)?Math.min(Math.max(Math.floor(t),0),0xffffffffffff):0})();if(e>this.Ct)this.Ct=e,this.Mt();else{if(this.Ct>=e+1e4)return;this.It++,this.It>4398046511103&&(this.Ct++,this.Mt())}return xw.fromFieldsV7(this.Ct,Math.trunc(this.It/Math.pow(2,30)),this.It&Math.pow(2,30)-1,this.Tt.nextUint32())}Mt(){this.It=1024*this.Tt.nextUint32()+(1023&this.Tt.nextUint32())}constructor(){this.Ct=0,this.It=0,this.Tt=new Lw}},zv=e=>{if("u">typeof UUIDV7_DENY_WEAK_RNG&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(let t=0;e.length>t;t++)e[t]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return e};A&&!O(A.crypto)&&crypto.getRandomValues&&(zv=e=>crypto.getRandomValues(e));var Lw=class{nextUint32(){return this.Rt.length>this.$t||(zv(this.Rt),this.$t=0),this.Rt[this.$t++]}constructor(){this.Rt=new Uint32Array(8),this.$t=1/0}},jd,Nt=()=>Dw().toString(),Dw=()=>(jd||(jd=new Mw)).generate(),vi="",Nw=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,wn=null,qe={Et(){if(!He(wn))return wn;if(wn=!1,N)try{const e=`__ph_cookie_support_${Nt()}`;qe.At(e,"xyz"),wn=Ui(e)==='"xyz"',qe.Lt(e)}catch{wn=!1}return wn},Pt(e){j.error("cookieStore error: "+e)},Ot:Ui,Dt(e){let t;try{t=JSON.parse(qe.Ot(e))||{}}catch{}return t},At(e,t,r,n,i){if(!N)return!1;try{let s="",o="";const a=(function(l,u){if(u){let h=(function(d,p=N){if(vi)return vi;if(!p||["localhost","127.0.0.1"].includes(d))return"";const f=d.split(".");let v=Math.min(f.length,8);const m="dmn_chk_"+Nt();for(;!vi&&v--;){const _=f.slice(v).join("."),w=m+"=1;domain=."+_+";path=/";p.cookie=w+";max-age=3",p.cookie.includes(m)&&(p.cookie=w+";max-age=0",vi=_)}return vi})(l);if(!h){const d=(p=>{const f=p.match(Nw);return f?f[0]:""})(l);d!==h&&j.info("Warning: cookie subdomain discovery mismatch",d,h),h=d}return h?"; domain=."+h:""}return""})(N.location.hostname,n);if(r){const l=new Date;l.setTime(l.getTime()+864e5*r),s="; expires="+l.toUTCString()}i&&(o="; secure");const c=e+"="+encodeURIComponent(JSON.stringify(t))+s+"; SameSite=Lax; path=/"+a+o;return c.length>3686.4&&j.warn("cookieStore warning: large cookie, len="+c.length),N.cookie=c,!0}catch{return!1}},Lt(e,t){if(N?.cookie&&(!t||!He(Ui(e))))try{qe.At(e,"",-1,t)}catch{return}}},Ba=null,ke={Et(){if(!He(Ba))return Ba;let e=!0;if(O(A))e=!1;else try{const t="__mplssupport__";ke.At(t,"xyz"),ke.Ot(t)!=='"xyz"'&&(e=!1),ke.Lt(t)}catch{e=!1}return e||j.error("localStorage unsupported; falling back to cookie store"),Ba=e,e},Pt(e){j.error("localStorage error: "+e)},Ot(e){try{return A?.localStorage.getItem(e)}catch(t){ke.Pt(t)}return null},Dt(e){try{return JSON.parse(ke.Ot(e))||{}}catch{}return null},At(e,t){try{return A?.localStorage.setItem(e,JSON.stringify(t)),!0}catch(r){ke.Pt(r)}return!1},Lt(e){try{A?.localStorage.removeItem(e)}catch(t){ke.Pt(t)}}},Ga=[Er,or,xt,un,Sr,dn,Tr,Ki,Rr],tn=[eu,Ot,$n,Ev,nu,Cn,Hn,vt],wo=e=>e+"_cpm",zw=["__proto__","constructor","prototype"],Wa=e=>{if(!be(e))return{};const t={};return Object.keys(e).forEach(r=>{zw.indexOf(r)===-1&&(t[r]=e[r])}),t},Za=(e,t=[])=>{const r={};return[...tn,...t].forEach(n=>{const i=e[n];O(i)||He(i)||i===""||(r[n]=i)}),r},Uv=e=>{let t=5381,r=2166136261;for(let n=0;e.length>n;n++){const i=e.charCodeAt(n);t=33*t^i,r=Math.imul(r^i,16777619)}return e.length.toString(36)+"."+(t>>>0).toString(36)+"."+(r>>>0).toString(36)},Hd=(e,t)=>({p:t,f:Uv(JSON.stringify(e))}),Vd=(e,t)=>{if(!t)return{properties:[],isValid:!1};try{const r=qe.Dt(wo(e)),n=r?.f===Uv(t)&&ce(r.p);return{properties:n?r.p:[],isValid:n}}catch{return{properties:[],isValid:!1}}},Ja=(e,t)=>t+"|"+(qe.Ot(wo(e))||""),Sn={},Qc={Et:()=>!0,Pt(e){j.error("memoryStorage error: "+e)},Ot:e=>e in Sn?Sn[e]:null,Dt:e=>e in Sn?Sn[e]:null,At:(e,t)=>(Sn[e]=t,!0),Lt(e){delete Sn[e]}},Wr=null,xe={Et(){if(!He(Wr))return Wr;if(Wr=!0,O(A))Wr=!1;else try{const e="__support__";xe.At(e,"xyz"),xe.Ot(e)!=='"xyz"'&&(Wr=!1),xe.Lt(e)}catch{Wr=!1}return Wr},Pt(e){j.error("sessionStorage error: ",e)},Ot(e){try{return A?.sessionStorage.getItem(e)}catch(t){xe.Pt(t)}return null},Dt(e){try{return JSON.parse(xe.Ot(e))||null}catch{}return null},At(e,t){try{return A?.sessionStorage.setItem(e,JSON.stringify(t)),!0}catch(r){xe.Pt(r)}return!1},Lt(e){try{A?.sessionStorage.removeItem(e)}catch(t){xe.Pt(t)}}},Uw=class{constructor(e){this._instance=e}get Rr(){return this._instance.config}get consent(){return this.Lo()?0:this.No}isOptedOut(){return this.Rr.cookieless_mode==="always"||this.isRejected()||this.consent===-1&&this.Rr.cookieless_mode==="on_reject"}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Rr.opt_out_capturing_by_default}optInOut(e){this.qo.At(this.jo,e?1:0,this.Rr.cookie_expiration,this.Rr.cross_subdomain_cookie,this.Rr.secure_cookie)}reset(){this.qo.Lt(this.jo,this.Rr.cross_subdomain_cookie)}get jo(){const{token:e,opt_out_capturing_cookie_prefix:t,consent_persistence_name:r}=this._instance.config;return r||(t?t+e:"__ph_opt_in_out_"+e)}get No(){const e=this.qo.Ot(this.jo);return Ma(e)?1:ue(nb,e)?0:-1}get qo(){const e=this.Rr.opt_out_capturing_persistence_type,t=e==="localStorage"?ke:qe,r=t.Et()?t:Qc;if(!this.Bo||this.Bo!==r){this.Bo=r;const n=e==="localStorage"?qe:ke;n.Ot(this.jo)&&(this.Bo.Ot(this.jo)||this.optInOut(Ma(n.Ot(this.jo))),n.Lt(this.jo,this.Rr.cross_subdomain_cookie))}return this.Bo}Lo(){return!!this.Rr.respect_dnt&&[nt?.doNotTrack,nt?.msDoNotTrack,te.doNotTrack,nt?.globalPrivacyControl].some(e=>Ma(e))}};function Fv(e,t){var r;const n=e==null||(r=e.config)===null||r===void 0?void 0:r.get_current_url;if(!rt(n))return t;try{const i=n(t);return ye(i)&&i?i:t}catch(i){return j.error("Error in get_current_url, falling back to window.location.href",i),t}}function Bd(e){var t;return e instanceof Element&&(e.id==="__POSTHOG_TOOLBAR__"||!!(!((t=e.closest)===null||t===void 0)&&t.call(e,".toolbar-global-fade-container")))}function Kt(e){return!!e&&e.nodeType===1}function lt(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function qv(e){return!!e&&e.nodeType===3}function au(e){return!!e&&e.nodeType===11&&Kt(e.host)}function cu(e){return e?Zo(e).split(/\s+/):[]}function Gd(e,t){const r=(function(n){var i;const s=A==null||(i=A.location)===null||i===void 0?void 0:i.href;return O(s)?void 0:Fv(n,s)})(t);return!!(r&&e&&e.some(n=>r.match(n)))}function Xn(e){let t="";switch(typeof e.className){case"string":t=e.className;break;case"object":t=(e.className&&"baseVal"in e.className?e.className.baseVal:null)||e.getAttribute("class")||"";break;default:t=""}return cu(t)}function jv(e){return ge(e)?null:Zo(e).split(/(\s+)/).filter(t=>qi(t)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Xi(e){let t="";return Vn(e)&&!Qi(e)&&e.childNodes&&e.childNodes.length&&$e(e.childNodes,function(r){var n;qv(r)&&r.textContent&&(t+=(n=jv(r.textContent))!==null&&n!==void 0?n:"")}),Zo(t)}function Fi(e){var t;return O(e.target)?e.srcElement||null:!((t=e.target)===null||t===void 0)&&t.shadowRoot?e.composedPath()[0]||null:e.target||null}var lu=["a","button","form","input","select","textarea","label"];function el(e,t){const r=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector;try{return!!r&&r.call(e,t)}catch{return!1}}function tl(e,t){if(O(t))return!0;for(const r of e)if(t.some(n=>el(r,n)))return!0;return!1}function Hv(e){const t=e.parentNode;return!(!t||!Kt(t))&&t}var Ka=[".ph-no-autocapture","[data-ph-no-autocapture]"],Vv=["next","previous","prev",">","<"],Fw=[...Vv,"+","-","−","–"],Wd=(e,t)=>/[a-z0-9]/i.test(t)?e.includes(t):e===t,Zd=[".ph-no-rageclick",".ph-no-capture"],qw=["","text","search","email","password","url","tel","number"];function Bv(e,t){if(!A||uu(e))return!1;let r,n,i;var s,o;if(gt(t)?(r=!!t&&Zd,n=void 0,i=!1):(r=(s=t?.css_selector_ignorelist)!==null&&s!==void 0?s:Zd,n=t?.content_ignorelist,i=(o=t?.ignore_text_selection)!==null&&o!==void 0&&o),r===!1||i&&(function(c){return!(!c||!Kt(c))&&(!!lt(c,"textarea")||(lt(c,"input")?ue(qw,(c.getAttribute("type")||"").toLowerCase()):(function(l){var u;if(l.isContentEditable)return!0;const h=(u=l.getAttribute)===null||u===void 0?void 0:u.call(l,"contenteditable");return h==="true"||h===""})(c)))})(e))return!1;const{targetElementList:a}=Gv(e,!1);return!(function(c,l){if(c===!1||O(c))return!1;let u;if(c===!0)u=Vv;else{if(!ce(c))return!1;if(c.length>10)return j.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;u=c.map(h=>h.toLowerCase())}return l.some(({safeText:h,ariaLabel:d})=>u.some(p=>Wd(h,p)||Wd(d,p)))})(n,a.map(c=>{var l;return{safeText:Xi(c).toLowerCase(),ariaLabel:((l=c.getAttribute("aria-label"))===null||l===void 0?void 0:l.toLowerCase().trim())||""}}))&&!tl(a,r)}var uu=e=>!e||lt(e,"html")||!Kt(e),Gv=(e,t)=>{if(!A||uu(e))return{parentIsUsefulElement:!1,targetElementList:[]};let r=!1;const n=[e];let i=e;for(;i.parentNode&&!lt(i,"body");){if(au(i.parentNode)){n.push(i.parentNode.host),i=i.parentNode.host;continue}const s=Hv(i);if(!s)break;if(t||lu.indexOf(s.tagName.toLowerCase())>-1)r=!0;else try{const o=A.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(r=!0)}catch{}n.push(s),i=s}return{parentIsUsefulElement:r,targetElementList:n}};function Vn(e){const t=new Set;let r=0;for(let s=e;s.parentNode&&!lt(s,"body");s=s.parentNode){if(r++>=1e3||t.has(s))return!1;t.add(s);const o=Xn(s);if(ue(o,"ph-sensitive")||ue(o,"ph-no-capture"))return!1}if(ue(Xn(e),"ph-include"))return!0;const n=e.type||"";if(ye(n))switch(n.toLowerCase()){case"hidden":case"password":return!1}const i=e.name||e.id||"";return!ye(i)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(i.replace(/[^a-zA-Z0-9]/g,""))}function Qi(e){return!!(lt(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||lt(e,"select")||lt(e,"textarea")||e.getAttribute("contenteditable")==="true")}var Jd=new RegExp("^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$"),Kd=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,jw=[16,15,14,13],Hw=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Yd=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Xd=/[0-9A-Za-z_]/;function Vw(e){let t=0,r=!1;for(let n=e.length-1;n>=0;n--){let i=e.charCodeAt(n)-48;r&&(i*=2,i>9&&(i-=9)),t+=i,r=!r}return t%10==0}function qi(e,t=!0){return!(ge(e)||ye(e)&&(e=Zo(e),(t?Jd.test((e||"").replace(/[- ]/g,"")):(function(r){let n;for(Kd.lastIndex=0;n=Kd.exec(r);){const i=n[2];if(!i)continue;const s=i.replace(/[- ]/g,"");for(let o=0;s.length>o;o++)for(const a of jw){const c=o+a;if(s.length>=c){const l=s.slice(o,c);if(Jd.test(l)&&Vw(l))return!0}}}return!1})(e))||(t?Hw.test(e):(function(r){let n;for(Yd.lastIndex=0;n=Yd.exec(r);){const i=n[1],s=n[3];if(!(i&&s&&Xd.test(i)&&Xd.test(s)))return!0}return!1})(e))))}function Qd(e){let t=Xi(e);return t=`${t} ${Wv(e)}`.trim(),qi(t)?t:""}function Wv(e){let t="";return e&&e.childNodes&&e.childNodes.length&&$e(e.childNodes,function(r){var n;if(r&&((n=r.tagName)===null||n===void 0?void 0:n.toLowerCase())==="span")try{const i=Xi(r);t=`${t} ${i}`.trim(),r.childNodes&&r.childNodes.length&&(t=`${t} ${Wv(r)}`.trim())}catch(i){j.error("[AutoCapture]",i)}}),t}function eh(e){return e.replace(/"|\\"/g,'\\"')}function Bw(e){const t=e.attr__class;if(t)return ce(t)?t:cu(t)}var ks=Be("[Dead Clicks]"),Gw=()=>!0,Ww=e=>{var t;const r=!!(!((t=e.instance.persistence)===null||t===void 0)&&t.get_property(tu)),n=e.instance.config.capture_dead_clicks;return gt(n)?n:!!be(n)||r},th=class{get lazyLoadedDeadClicksAutocapture(){return this.Ho}constructor(e,t,r){this.instance=e,this.isEnabled=t,this.onCapture=r,this.startIfEnabledOrStop()}onRemoteConfig(e){if(!e.ok)return;const t=e.config;"captureDeadClicks"in t&&(this.instance.persistence&&this.instance.persistence.register({[tu]:t.captureDeadClicks}),this.startIfEnabledOrStop())}startIfEnabledOrStop(){this.isEnabled(this)?this.zo(()=>{this.Uo()}):this.stop()}zo(e){var t,r,n;!((t=te.__PosthogExtensions__)===null||t===void 0)&&t.initDeadClicksAutocapture?e():(r=te.__PosthogExtensions__)===null||r===void 0||(n=r.loadExternalDependency)===null||n===void 0||n.call(r,this.instance,"dead-clicks-autocapture",i=>{i?ks.error("failed to load script",i):e()})}Uo(){var e;if(N){if(!this.Ho&&(!((e=te.__PosthogExtensions__)===null||e===void 0)&&e.initDeadClicksAutocapture)){const t=be(this.instance.config.capture_dead_clicks)?b({},this.instance.config.capture_dead_clicks):{};t.__onCapture=this.onCapture,this.onCapture&&(t.capture_dead_swipes=!1),this.Ho=te.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,t),this.Ho.start(N),ks.info("starting...")}}else ks.error("`document` not found. Cannot start.")}stop(){this.Ho&&(this.Ho.stop(),this.Ho=void 0,ks.info("stopping..."))}},gi=Be("[SegmentIntegration]");function rh(e,t,r=!0){const n=e.config.segment;if(!n)return t();const{analytics:i,filterProperties:s}=(a=>rt(a.register))(o=n)?{analytics:o}:o;var o;(function(a,c,l,u){const h=p=>{const f=()=>p.anonymousId()||Nt();a.config.get_device_id=f,u&&p.id()&&(a.register({distinct_id:p.id(),$device_id:f()}),a.persistence.set_property(vt,Gs)),l(u?void 0:p.anonymousId()||void 0)},d=c.user();"then"in d&&rt(d.then)?d.then(h):h(d)})(e,i,a=>{i.register(((c,l,{filterProperties:u}={})=>{typeof Promise<"u"&&Promise.resolve||gi.warn("This browser does not have Promise support, and can not use the segment integration");const h=(d,p)=>{if(!p)return d;const f=!!l&&d.event.anonymousId===l&&!d.event.userId;f||d.event.userId||d.event.anonymousId===c.get_distinct_id()||(gi.info("No userId set, resetting PostHog"),c.reset()),f||(l=void 0),d.event.userId&&d.event.userId!==c.get_distinct_id()&&(gi.info("UserId set, identifying with PostHog"),c.identify(d.event.userId));let v=c.calculateEventProperties(p,d.event.properties);if(!ge(u)){const m=d.event.properties||{},_={};for(const S of Object.keys(v))Jl.call(m,S)||(_[S]=v[S]);const w=((S,T)=>{const I=ce(S)?S:[S];let C=b({},T);for(const M of I)try{if(C=M(C),ge(C))return null}catch(L){return gi.error("Error in Segment filterProperties:",L),null}return C})(u,_);if(ge(w))return d;v=w}return d.event.properties=Object.assign({},v,d.event.properties),d};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded(){return!0},load(){return Promise.resolve()},track(d){return h(d,d.event.event)},page(d){return h(d,su)},identify(d){return h(d,Dv)},screen(d){return h(d,"$screen")}}})(e,a,{filterProperties:s})).then(()=>{t()},c=>{gi.error("Failed to register the Segment integration",c),t()})},r)}var Zv="posthog-js";function Jv(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:s=!0}={}){return o=>{var a,c,l,u,h;if(i!=="*"&&!i.includes(o.level)||!e.__loaded)return o;o.tags||(o.tags={});const d=e.requestRouter.endpointFor("ui",`/project/${e.config.token}/person/${e.get_distinct_id()}`);o.tags["PostHog Person URL"]=d,e.sessionRecordingStarted()&&(o.tags["PostHog Recording URL"]=e.get_session_replay_url({withTimestamp:!0}));const p=((a=o.exception)===null||a===void 0?void 0:a.values)||[],f=p.map(_=>b(b({},_),{},{stacktrace:_.stacktrace?b(b({},_.stacktrace),{},{type:"raw",frames:(_.stacktrace.frames||[]).map(w=>b(b({},w),{},{platform:"web:javascript"}))}):void 0})),v={$exception_message:((c=p[0])===null||c===void 0?void 0:c.value)||o.message,$exception_type:(l=p[0])===null||l===void 0?void 0:l.type,$exception_level:o.level,$exception_list:f,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:((u=p[0])===null||u===void 0?void 0:u.value)||o.message,$sentry_exception_type:(h=p[0])===null||h===void 0?void 0:h.type,$sentry_tags:o.tags};var m;return t&&r&&(v.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),s&&((m=e.exceptions)===null||m===void 0||m.sendExceptionEvent(v)),o}}var Zw=class{constructor(e,t,r,n,i,s){this.name=Zv,this.setupOnce=function(o){o(Jv(e,{organization:t,projectId:r,prefix:n,severityAllowList:i,sendExceptionsToPostHog:s==null||s}))}}},nh=class{constructor(e){this.Wo=(t,r,n)=>{n&&(n.noSessionId||n.activityTimeout||n.sessionPastMaximumLength||n.crossTabAdoption)&&(j.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:t,changeReason:n}),this.Vo=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.Go()}Go(){var e;this.Zo=(e=this._instance.sessionManager)===null||e===void 0?void 0:e.onSessionId(this.Wo)}destroy(){var e;(e=this.Zo)===null||e===void 0||e.call(this),this.Zo=void 0}doPageView(e,t){var r;const n=this.Qo(e,t);return this.Vo={pathname:(r=A?.location.pathname)!==null&&r!==void 0?r:"",pageViewId:t,timestamp:e},this._instance.scrollManager.resetContext(),n}doPageLeave(e){var t;return this.Qo(e,(t=this.Vo)===null||t===void 0?void 0:t.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.Vo)===null||e===void 0?void 0:e.pageViewId}}Qo(e,t){const r=this.Vo;if(!r)return{$pageview_id:t};let n={$pageview_id:t,$prev_pageview_id:r.pageViewId};const i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){let{maxScrollHeight:s,lastScrollY:o,maxScrollY:a,maxContentHeight:c,lastContentY:l,maxContentY:u}=i;if(!(O(s)||O(o)||O(a)||O(c)||O(l)||O(u))){s=Math.ceil(s),o=Math.ceil(o),a=Math.ceil(a),c=Math.ceil(c),l=Math.ceil(l),u=Math.ceil(u);const h=s>1?Wt(o/s,0,1,j):1,d=s>1?Wt(a/s,0,1,j):1,p=c>1?Wt(l/c,0,1,j):1,f=c>1?Wt(u/c,0,1,j):1;n=Le(n,{$prev_pageview_last_scroll:o,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:a,$prev_pageview_max_scroll_percentage:d,$prev_pageview_last_content:l,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:u,$prev_pageview_max_content_percentage:f})}}return r.pathname&&(n.$prev_pageview_pathname=r.pathname),r.timestamp&&(n.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),n}},mi=["flags","surveys"],Jw={[rw]:{exposure:"hidden"},[_o]:{exposure:"hidden"},[nw]:{exposure:"hidden"},[jc]:{exposure:"hidden"},[Hn]:{exposure:"hidden"},[Di]:{exposure:"hidden"},[yv]:{exposure:"event"},[Hc]:{exposure:"hidden"},[wv]:{exposure:"hidden"},[Vc]:{exposure:"event"},[bv]:{exposure:"hidden"},[Bc]:{exposure:"event"},[Gc]:{exposure:"event"},[tu]:{exposure:"event"},[ru]:{exposure:"hidden"},[Sv]:{exposure:"event"},[Ni]:{exposure:"hidden"},[iw]:{exposure:"hidden"},[$n]:{exposure:"hidden"},[Ev]:{exposure:"event"},[sw]:{exposure:"event",shouldSkipFromEventProperties:e=>He(e)},[uw]:{exposure:"event"},[dw]:{exposure:"event"},[hw]:{exposure:"event"},[pw]:{exposure:"event"},[fw]:{exposure:"hidden"},[xt]:{exposure:"hidden",storageGroup:"flags"},[or]:{exposure:"hidden",storageGroup:"flags"},[Wc]:{exposure:"hidden"},[un]:{exposure:"hidden",storageGroup:"flags"},[Sr]:{exposure:"hidden",storageGroup:"flags"},[dn]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[zi]:{exposure:"hidden",storageGroup:"flags"},[Ht]:{exposure:"hidden"},[en]:{exposure:"hidden"},[Er]:{exposure:"hidden"},[kr]:{exposure:"hidden"},[Zc]:{exposure:"hidden",storageGroup:"surveys"},[yo]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Rv]:{exposure:"event"},[Av]:{exposure:"hidden"},[Iv]:{exposure:"hidden"},[Jc]:{exposure:"hidden"},[vw]:{exposure:"hidden"},[gw]:{exposure:"hidden"},[mw]:{exposure:"event"},[_w]:{exposure:"event"},[yw]:{exposure:"event"},[bw]:{exposure:"event"},[Rr]:{exposure:"hidden"},[Ii]:{exposure:"hidden"},[kv]:{exposure:"event"},[Ki]:{exposure:"hidden"},[Tr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[vt]:{exposure:"hidden"},[Kc]:{exposure:"hidden"},[ww]:{exposure:"hidden"},[Tv]:{exposure:"hidden"},[$v]:{exposure:"hidden"},[Cn]:{exposure:"hidden"},[nu]:{exposure:"hidden"},[ow]:{exposure:"event"},[aw]:{exposure:"event"},[cw]:{exposure:"event"},[lw]:{exposure:"event"},[Pv]:{exposure:"event"},[Ov]:{exposure:"event"},[xv]:{exposure:"event"},[Mv]:{exposure:"event"},[Sw]:{exposure:"event"},[Ew]:{exposure:"event"},[kw]:{exposure:"event"},[Rw]:{exposure:"event"},[Aw]:{exposure:"event"},[Iw]:{exposure:"event"},[Tw]:{exposure:"event"},[$w]:{exposure:"event"}},Kw=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],at=e=>{const t=Jw[e];if(t)return t;for(const[r,n]of Kw)if(e.indexOf(r)===0)return n},On=(e,t)=>{try{let r;return JSON.stringify(e,(n,i)=>{var s;return ci(i)?((s=r)!==null&&s!==void 0||(r=new WeakMap),r.has(i)||r.set(i,Nv(i)),r.get(i)):typeof i=="bigint"?i.toString():i},t)}catch{return bf(e)}},Lr=e=>{const t=N?.createElement("a");return O(t)?null:(t.href=e,t)},Qn=function(e,t){const r=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&");let n;for(let i=0;r.length>i;i++){const s=r[i].split("=");if(s[0]===t){n=s;break}}if(!ce(n)||2>n.length)return"";{let i=n[1];try{i=decodeURIComponent(i)}catch{j.error("Skipping decoding for malformed query param: "+i)}return i.replace(/\+/g," ")}},es=function(e,t,r){if(!e||!t||!t.length)return e;const n=e.split("#"),i=n[1],s=(n[0]||"").split("?"),o=s[1],a=s[0],c=(o||"").split("&"),l=[];for(let h=0;c.length>h;h++){const d=c[h].split("=");ce(d)&&(t.includes(d[0])?l.push(d[0]+"="+r):l.push(c[h]))}let u=a;return o!=null&&(u+="?"+l.join("&")),i!=null&&(u+="#"+i),u},So=function(e,t){const r=e.match(new RegExp(t+"=([^&]*)"));return r?r[1]:null},Kv=(e,t)=>e>=t&&yf(),Yv=(e,t,r,n)=>{if(e===0){if(yf()){const i=t+1;return i===r&&n(),i}return t}return 0},ei=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Yw=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ei],ts="<masked>",Xw=["li_fat_id"];function Xv(e,t,r){if(!N)return{};const n=t?[...ei,...r||[]]:[],i=Qv(es(N.URL,n,ts),e),s=(function(){const o={};return $e(Xw,function(a){const c=Ui(a);o[a]=c||null}),o})();return Le(s,i)}function Qv(e,t){const r=Yw.concat(t||[]),n={};return $e(r,function(i){const s=Qn(e,i);n[i]=s||null}),n}function eg(e){const t=(function(i){return i?i.search("https?://(.*)google.([^/?]*)")===0?"google":i.search("https?://(.*)bing.com")===0?"bing":i.search("https?://(.*)yahoo.com")===0?"yahoo":i.search("https?://(.*)duckduckgo.com")===0?"duckduckgo":null:null})(e),r=t!="yahoo"?"q":"p",n={};if(!He(t)){n.$search_engine=t;const i=N?Qn(N.referrer,r):"";i.length&&(n.ph_keyword=i)}return n}function tg(){return navigator.language||navigator.userLanguage}function Qw(){const e=tg();return typeof e=="string"?e.split("-")[0]:void 0}var Eo="$direct";function rg(){return N?.referrer||Eo}function ng(e,t,r=!1){const n=e?[...ei,...t||[]]:[],i=r?Mr(je?.href):je?.href,s=i?.substring(0,1e3);return{r:rg().substring(0,1e3),u:s?es(s,n,ts):void 0}}function ig(e,t=!1){var r;const{r:n,u:i}=e,s=t?Mr(i):i,o={$referrer:n,$referring_domain:n==null?void 0:n==Eo?Eo:(r=Lr(n))===null||r===void 0?void 0:r.host};if(s){o.$current_url=s;const a=Lr(s);o.$host=a?.host,o.$pathname=a?.pathname;const c=Qv(s);Le(o,c)}if(n){const a=eg(n);Le(o,a)}return o}function sg(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function eS(){try{return new Date().getTimezoneOffset()}catch{return}}var tS={flags:Tr,surveys:yo},rS=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Rs=e=>`${e}_cookie_identity_change_pending`,As=e=>{let t="",r=0;for(const n of e){const i=encodeURIComponent(JSON.stringify(n).slice(1,-1)).length;if(r+i>1e3)break;t+=n,r+=i}return t},Qe="main",rr=[xt,or,un,Sr,dn,Tr,zi,Er],Ya=e=>rr.indexOf(e)!==-1,og=[Hn,Di],ih=e=>og.indexOf(e)!==-1,hr=(e,t)=>{try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}},En=e=>{if(!e)return{};const t=JSON.parse(e);return be(t)?t:{}},sh=(e,t)=>{$e(e,(r,n)=>{const i=at(n);i&&i.exposure!=="event"||{}.hasOwnProperty.call(t,n)||delete e[n]})},Xa=class{constructor(e,t,r=!0){if(this.Jo={},this.Ko=!1,this.Xo=!1,this.Yo=!1,this.ta=!1,this.ea=!1,this.ia=new Map,this.na=!1,this.sa=!1,this.ra=!1,this.oa=new Set,this.aa=new Set,this.Rr=e,this.la=r,this.props={},this.ua=void 0,this.ha=(n=>{let i="";return n.token&&(i=n.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),n.persistence_name?"ph_"+n.persistence_name:"ph_"+i+"_posthog"})(e),this.qo=this.ca(e),this.Yo=this.da(e),this.load(),this.va(),e.debug&&j.info("Persistence loaded",e.persistence,b({},this.props)),this.update_config(e,e,t),this.save(),A){const n=()=>this.flush();Ie(A,"beforeunload",n,{capture:!1}),Ie(A,"pagehide",n,{capture:!1}),this.fa=i=>{if(this.Ko&&(!i.storageArea||i.storageArea===A?.localStorage)&&i.key)if(i.key!==this.ha){if(this.Yo){const s=mi.find(o=>i.key===this.pa(o));s&&this.ga(i.key,s)}}else this.ga(i.key,Qe)},Ie(A,"storage",this.fa)}}markCrossTabFeatureFlagChanges(e){Object.entries(e).forEach(([t,r])=>{const n=this.ia.get(t);if(!Ya(t)||n===!0)return;if(r===!0)return void this.ma(t,!0);const i=new Set(n||[]);r.forEach(s=>i.add(s)),i.size&&this.ma(t,i)})}onCrossTabFeatureFlagChange(e){return this.aa.add(e),()=>this.aa.delete(e)}destroy(){this.fa&&A&&(A.removeEventListener("storage",this.fa),this.fa=void 0),this.aa.clear()}ga(e,t,r=!0){if(this.mi)return!1;let n,i;try{if(i=ke.Ot(e),He(i)){const a=this.ya(t);return a.storageValue=null,t!==Qe&&(a.persisted=!1),!1}n=En(i)}catch{return!1}const s=t===Qe?n:ke.Dt(this.ha);if(s&&this.ba(s))return!1;const o=this._a(n,t,r);return t===Qe&&this.Yo&&!hr(this.wa().main,n)||this.ka(n,t,!0,i),o}ba(e){const t=this.props[Ot],r=e[Ot];return!O(t)&&!O(r)&&t!==r}ka(e,t,r,n){const i=this.ya(t);i.storageValue=n,t!==Qe&&(i.persisted=r);try{i.fingerprint=this.Sa(e,t)}catch{i.fingerprint=void 0}}_a(e,t,r){let n=!1;return rr.forEach(i=>{var s;const o=(s=at(i))===null||s===void 0?void 0:s.storageGroup;if(t===Qe&&this.Yo&&o||t!==Qe&&o!==t)return;const a=i in e,c=this.xa(i,a?e[i]:void 0),l=this.ia.has(i)?i in this.props:a;l===i in this.props&&hr(c,this.props[i])||(l?this.Ca(i,c,!1):this.$a(i,!1),n=!0)}),n&&r&&this.aa.forEach(i=>i()),n}Ta(){if(!this.Ko)return!1;try{this.ra=!1;const e=ke.Ot(this.ha),t=this.ya(Qe);let r,n=!1,i=!1;if(e!==t.storageValue)if(He(e))t.storageValue=null;else{if(r=En(e),this.ra=!this.sa&&this.ba(r),this.ra)return!1;i=this._a(r,Qe,!1),!this.Yo||hr(this.wa().main,r)?this.ka(r,Qe,!0,e):t.storageValue=e,n=!0}return this.Yo&&mi.forEach(s=>{const o=ke.Ot(this.pa(s)),a=this.ya(s),c=r||{},l=n&&rr.some(h=>{var d;return((d=at(h))===null||d===void 0?void 0:d.storageGroup)===s&&h in c});if(o===a.storageValue&&!l)return;if(He(o))return a.storageValue=null,a.persisted=!1,void(l&&(i=this._a(c,s,!1)||i));const u=En(o);i=this._a(u,s,!1)||i,this.ka(u,s,!0,o)}),i}catch{return!1}}ma(e,t){this.ia.set(e,t);const r=at(e);r!=null&&r.volatile||(this.ya((this.Yo?r?.storageGroup:void 0)||Qe).fingerprint=void 0,this.Ia(e))}Ma(){rr.forEach(e=>this.ia.set(e,!0))}va(){if(this.Ko)try{const e=ke.Ot(this.ha),t=En(e);this.ya(Qe).storageValue=e,rr.forEach(r=>{var n;const i=this.Yo?(n=at(r))===null||n===void 0?void 0:n.storageGroup:void 0,s=i?ke.Ot(this.pa(i)):null;if(i){const a=this.ya(i);a.storageValue=s,a.persisted=!He(s)}const o=i&&!He(s)?En(s):t;r in this.props?this.Ea(r,o[r],this.props[r]):r in o&&this.ma(r,!0)})}catch{}}xa(e,t){const r=this.ia.get(e);if(!r)return t;if(r===!0)return this.props[e];if(e==="$active_feature_flags"){const s=new Set(ce(t)?t:[]),o=new Set(ce(this.props[e])?this.props[e]:[]);return r.forEach(a=>o.has(a)?s.add(a):s.delete(a)),Array.from(s)}const n=be(t)?b({},t):{},i=be(this.props[e])?this.props[e]:{};return r.forEach(s=>{s in i?n[s]=i[s]:delete n[s]}),n}Ea(e,t,r){if(!Ya(e))return;const n=this.ia.get(e);if(n===!0)return;let i=t;if(this.Ko)try{var s;const a=this.Yo?(s=at(e))===null||s===void 0?void 0:s.storageGroup:void 0,c=a?this.pa(a):this.ha;i=En(ke.Ot(c))[e]}catch{}const o=new Set(n||[]);if(e==="$active_feature_flags"){if(!O(t)&&!ce(t)||!O(i)&&!ce(i)||!ce(r))return void this.ma(e,!0);const a=new Set(t||[]),c=new Set(i||[]),l=new Set(r);new Set([...a,...l]).forEach(u=>{a.has(u)!==l.has(u)&&o.add(u)}),o.forEach(u=>{c.has(u)===l.has(u)&&o.delete(u)})}else{if(!be(r))return void(hr(i,r)?this.ia.delete(e):this.ma(e,!0));{if(!O(t)&&!be(t)||O(t)&&_t(r)&&O(i))return void this.ma(e,!0);const a=be(t)?t:{},c=be(i)?i:{};new Set([...Object.keys(a),...Object.keys(r)]).forEach(l=>{l in a==l in r&&hr(a[l],r[l])||o.add(l)}),o.forEach(l=>{l in c==l in r&&hr(c[l],r[l])&&o.delete(l)})}}o.size?this.ma(e,o):this.ia.delete(e)}Pa(){var e;const t=(e=this.Rr)===null||e===void 0?void 0:e.persistence_save_debounce_ms;return We(t)&&t>0?t:0}Ra(e){if(this.Rr.cookieWinsOnConflict&&this.Rr.persistence.toLowerCase()==="localstorage+cookie")if(e)try{const t=Za(e,this.Rr.cookie_persisted_properties||[]),r=Hd(t,this.Rr.cookie_persisted_properties||[]),n=JSON.stringify(t)+"|"+JSON.stringify(r),i=qe.Ot(this.ha)||void 0;i&&Ja(this.ha,i)===n&&(this.Aa=n,this.Fa=i)}catch{}else try{const t=qe.Ot(this.ha)||void 0;this.Aa=t?Ja(this.ha,t):void 0,this.Fa=t}catch{}}syncCookieProperties(){return this.Oa(this.Rr)}Oa(e,t=!1){if(this.mi&&!t||this.ea||!e.cookieWinsOnConflict||e.persistence.toLowerCase()!=="localstorage+cookie")return!1;let r;try{r=qe.Ot(this.ha)||void 0}catch{}if(!r||r===this.Fa)return!1;const n=Ja(this.ha,r);let i;try{i=Wa(JSON.parse(r))}catch{return!1}if((qe.Ot(this.ha)||void 0)!==r)return!1;this.Aa=n,this.Fa=r;const s=Vd(this.ha,r),o=[...tn,...s.properties],a={};if(Object.keys(i).forEach(v=>{const m=i[v];(O(m)||He(m)||m===""||v==="$user_state"&&m!=="anonymous"&&m!=="identified")&&(a[v]=!0,delete i[v])}),_t(i))return!1;const c="distinct_id"in i||i.$user_state==="anonymous"||i.$user_state==="identified",l=this.props,u=l[Ot],h=l[vt],d=Le({},l);[...tn,...e.cookie_persisted_properties||[]].forEach(v=>{if(o.indexOf(v)!==-1&&!(v in i)&&!a[v]&&(c||v!=="distinct_id"&&v!=="$user_state")){const m=d[v];(s.isValid||tn.indexOf(v)===-1||m!==!1&&m!==0)&&delete d[v]}}),this.props=Le(d,i),rr.forEach(v=>{const m=v in this.props;v in l===m&&hr(l[v],this.props[v])||(m?this.Ea(v,l[v],this.props[v]):this.ma(v,!0))}),!c||"$user_state"in i||"$user_state"in this.props||this.Ca(vt,ar);const p=this.props[Ot],f=this.props[vt];return!c||p===u&&f===h||(this.sa=!0,this.ta=!0,xe.At(Rs(this.ha),!0),this.$a(Er),this.$a(or),this.$a(xt),this.$a(un),this.$a(Sr),this.$a(dn),this.$a(Tr),this.$a(Ki),this.$a(Rr),f!=="anonymous"||h!=="identified"&&i.$user_state!=="anonymous"&&(O(u)||p===u)||(sh(this.props,i),this.$a(kr)),f==="identified"?this.props.$user_id=p:delete this.props.$user_id,this.$a(_o)),!0}consumeCookieIdentityChange(){const e=Rs(this.ha),t=this.ta||!!xe.Ot(e);return this.ta=!1,t&&xe.Lt(e),t}Da(e=!1){return!(this.ea||this.mi&&!e||!this.Rr.cookieWinsOnConflict||this.Rr.persistence.toLowerCase()!=="localstorage+cookie"||(this.ea=!0,0))}La(){this.ea&&(O(this.Na)||(clearTimeout(this.Na),this.Na=void 0),delete this.Jo[Qe],this.qa(!0))}ja(e=!0){if(this.ea)try{e?this.La():O(this.Na)||(clearTimeout(this.Na),this.Na=void 0)}finally{this.ea=!1}}isDisabled(){return!!this.mi}ca(e){rS.indexOf(e.persistence.toLowerCase())===-1&&(j.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");const t=((o=[],a=!1)=>{const c=[...tn,...o];return b(b({},ke),{},{Dt(l){try{let h,d={};try{h=qe.Ot(l)||void 0,d=h?Wa(JSON.parse(h)):{}}catch{}const p=JSON.parse(ke.Ot(l)||"{}");let f;if(a){const v=Vd(l,h),m=[...tn,...v.properties],_={};Object.keys(d).forEach(S=>{const T=d[S];He(T)||T===""||S==="$user_state"&&T!=="anonymous"&&T!=="identified"||(_[S]=T)});const w="distinct_id"in _||_.$user_state==="anonymous"||_.$user_state==="identified";if(Object.keys(_).length>0){var u;const S=p[Ot],T=(u=p.$user_state)!==null&&u!==void 0?u:ar;c.forEach(I=>{if(m.indexOf(I)!==-1&&!(I in d)&&(w||I!=="distinct_id"&&I!=="$user_state")){const C=p[I];(v.isValid||tn.indexOf(I)===-1||C!==!1&&C!==0)&&delete p[I]}}),!w||"$user_state"in d||"$user_state"in p||(p[vt]=ar),!w||("distinct_id"in _?_[Ot]:p[Ot])===S&&("$user_state"in _?_[vt]:p[vt])===T||(Ga.forEach(I=>delete p[I]),_.$user_state==="identified"&&"distinct_id"in _?p.$user_id=_[Ot]:delete p.$user_id,_.$user_state!=="identified"&&(delete p[kv],delete p[kr]),delete p.__alias)}f=Le(p,_)}else f=Le(d,p);return ke.At(l,f),f}catch{}return null},At(l,u,h,d,p,f){const v=ke.At(l,u,void 0,void 0,f);try{const m=Za(u,o);if(Object.keys(m).length){if(a){const _=wo(l),w=Hd(m,o);if(qe.At(_,w,h,d,p,f),qe.Ot(_)!==JSON.stringify(w)){qe.Lt(_,d);const S=Za(u);return qe.At(l,S,h,d,p,f),v}}qe.At(l,m,h,d,p,f)}}catch(m){ke.Pt(m)}return v},Lt(l,u){try{A?.localStorage.removeItem(l),qe.Lt(l,u),qe.Lt(wo(l),u)}catch(h){ke.Pt(h)}}})})(e.cookie_persisted_properties||[],e.cookieWinsOnConflict);let r,n=!1,i=!1;const s=e.persistence.toLowerCase();return s==="localstorage"&&ke.Et()?(r=ke,i=!0):s==="localstorage+cookie"&&t.Et()?(r=t,i=!0,n=!0):s==="sessionstorage"&&xe.Et()?r=xe:s==="memory"?r=Qc:s==="cookie"&&qe.Et()?(r=qe,n=!0):t.Et()?(r=t,i=!0,n=!0):qe.Et()?(r=qe,n=!0):r=Qc,this.Ko=i,this.Xo=n,r}pa(e){return`${this.ha}__${e}`}da(e){return this.Ko&&!!e.split_storage}properties(){const e={};return $e(this.props,(t,r)=>{const n=at(r);if(!n||n.exposure==="event"){var i;if(!(n==null||(i=n.shouldSkipFromEventProperties)===null||i===void 0)&&i.call(n,t))return;e[r]=t}}),e}load(e=!1){if(this.mi&&!e)return;const t=this.Rr.cookieWinsOnConflict&&this.Rr.persistence.toLowerCase()==="localstorage+cookie",r=t?ke.Dt(this.ha):null;let n={};if(t)try{n=Wa(qe.Dt(this.ha)),$e(n,(a,c)=>{(O(a)||He(a)||a==="")&&delete n[c]})}catch{}const i=this.qo.Dt(this.ha);if(i&&(this.props=Le({},i)),this.Yo&&this.Ba(),t&&i){var s,o;const a=r?.[Ot],c=(s=r?.$user_state)!==null&&s!==void 0?s:ar,l=i[Ot],u=(o=i.$user_state)!==null&&o!==void 0?o:ar;if(l!==a||u!==c){this.ta=!0,xe.At(Rs(this.ha),!0);const h=Le({},this.props);Ga.forEach(p=>delete h[p]),u!=="anonymous"||c!=="identified"&&n.$user_state!=="anonymous"&&(O(a)||l===a)||(sh(h,n),delete h[kr]),this.props=h;const d=new Set;Ga.forEach(p=>{var f;const v=(f=at(p))===null||f===void 0?void 0:f.storageGroup;v&&d.add(v)}),d.forEach(p=>{const f={};$e(this.props,(v,m)=>{var _;((_=at(m))===null||_===void 0?void 0:_.storageGroup)===p&&(f[m]=v)}),_t(f)?(ke.Lt(this.pa(p)),this.Jo[p]={}):ke.At(this.pa(p),f)&&(this.Jo[p]={persisted:!0,fingerprint:this.Sa(f,p)})})}}xe.Ot(Rs(this.ha))&&(this.ta=!0)}Ba(){for(const e of mi){const t=ke.Dt(this.pa(e));if(t&&!_t(t)){const r=this.ya(e);r.persisted=!0,this.Ha(e)||(r.fingerprint=this.Sa(t,e)),this.za(e,t)||Le(this.props,t)}}}Ha(e){return Object.keys(this.props).some(t=>{var r;return((r=at(t))===null||r===void 0?void 0:r.storageGroup)===e})}za(e,t){const r=tS[e];if(!r)return!1;const n=t[r],i=this.props[r];return We(n)&&We(i)&&i>n}refreshKey(e){var t;if(this.mi||this.oa.has(e))return;const r=this.Yo?(t=at(e))===null||t===void 0?void 0:t.storageGroup:void 0,n=r?ke.Dt(this.pa(r)):this.qo.Dt(this.ha);if(n&&e in n)this.Ca(e,n[e],!1);else{if(r){const i=this.qo.Dt(this.ha);if(i&&e in i)return void this.Ca(e,i[e],!1)}this.$a(e,!1)}}save(){if(this.mi)return;const e=this.Pa();e>0?O(this.Na)&&(this.Na=setTimeout(()=>{this.Na=void 0,this.qa()},e)):this.qa()}flush(){O(this.Na)||(clearTimeout(this.Na),this.Na=void 0,this.qa())}qa(e=!1){if(this.mi||this.ea&&!e)return;e||(this.syncCookieProperties(),this.Rr.cookieWinsOnConflict&&this.Rr.persistence.toLowerCase()==="localstorage+cookie"||og.forEach(i=>this.refreshKey(i)));const t=!e&&!this.na;t||(this.ra=!1);const r=!!t&&this.Ta();if(this.ra)return void(this.Rr.debug&&j.warn("skipping persistence write because storage belongs to a different distinct ID"));if(this.Yo)return this.Ua(),void(r&&this.aa.forEach(i=>i()));const n=this.Wa(this.qo,this.ha,this.props,Qe);n==="written"&&this.Ra(this.props),n!=="failed"&&(this.ia.clear(),this.sa=!1,this.oa.clear()),r&&this.aa.forEach(i=>i())}Ua(){const{main:e,groups:t}=this.wa(),r=this.Wa(this.qo,this.ha,e,Qe);r==="written"&&this.Ra(e),r!=="failed"&&(this.sa=!1,this.oa.clear(),rr.forEach(i=>{var s;(s=at(i))!==null&&s!==void 0&&s.storageGroup||this.ia.delete(i)}));for(const i of mi){var n;const s=t[i];if(_t(s)&&!(!((n=this.Jo[i])===null||n===void 0)&&n.persisted)){rr.forEach(a=>{var c;((c=at(a))===null||c===void 0?void 0:c.storageGroup)===i&&this.ia.delete(a)});continue}const o=this.Wa(ke,this.pa(i),s,i);o!=="failed"&&rr.forEach(a=>{const c=at(a);c?.storageGroup!==i||o!=="written"&&c.volatile||this.ia.delete(a)})}}wa(){const e={},t={flags:{},surveys:{}};return $e(this.props,(r,n)=>{var i;const s=(i=at(n))===null||i===void 0?void 0:i.storageGroup;s?t[s][n]=r:e[n]=r}),{main:e,groups:t}}Sa(e,t){if(t===Qe)return JSON.stringify(e)+"|"+this.Va+"|"+this.Ga+"|"+this.Za;const r={};return $e(e,(n,i)=>{var s;r[i]=!((s=at(i))===null||s===void 0)&&s.volatile?"__volatile__":n}),JSON.stringify(r)}Wa(e,t,r,n){const i=this.ya(n);if(n!==Qe&&!i.dirty&&!O(i.fingerprint))return"skipped";let s;try{if(s=this.Sa(r,n),s===i.fingerprint)return i.dirty=!1,"skipped"}catch{s=void 0}return e.At(t,r,this.Va,this.Ga,this.Za,this.Rr.debug)?(i.dirty=!1,n!==Qe&&(i.persisted=!0),O(s)||(i.fingerprint=s),this.Ko&&(i.storageValue=ke.Ot(t)),"written"):(this.Rr.debug&&j.warn(`failed to persist storage entry "${t}"; will retry on next save`),"failed")}remove({keepGroupEntries:e=!1}={}){if(this.Ma(),O(this.Na)||(clearTimeout(this.Na),this.Na=void 0),this.qo.Lt(this.ha,!1),this.qo.Lt(this.ha,!0),!e&&this.la)for(const t of mi)ke.Lt(this.pa(t));e?delete this.Jo[Qe]:this.Jo={},this.Aa=void 0,this.Fa=void 0}clear(){this.remove(),this.props={}}register_once(e,t,r){if(be(e)){this.syncCookieProperties(),O(t)&&(t="None"),this.Va=O(r)?this.Qa:r;let n=!1;if($e(e,(i,s)=>{this.props.hasOwnProperty(s)&&this.props[s]!==t||(this.Ca(s,i),n=!0)}),n)return this.save(),!0}return!1}register(e,t){if(be(e)){this.syncCookieProperties(),this.Va=O(t)?this.Qa:t;let r=!1;if($e(e,(n,i)=>{e.hasOwnProperty(i)&&(this.props[i]!==n||be(n)||ce(n))&&(this.Ca(i,n),r=!0)}),r)return this.save(),!0}return!1}unregister(e){this.syncCookieProperties();const t=typeof e=="string"?[e]:e;let r=!1;for(const n of t)n in this.props&&(this.$a(n),r=!0);r&&this.save()}update_campaign_params(){const e=N?.URL;if(e===this.ua)return;const t=Xv(this.Rr.custom_campaign_params,this.Rr.mask_personal_data_properties,this.Rr.custom_personal_data_properties),r=!_t(ou(t));return r&&this.register(t),this.ua=e,r?t:void 0}update_search_keyword(){this.register((function(){const e=N?.referrer;return e?eg(e):{}})())}update_referrer_info(){var e;this.register_once({$referrer:rg(),$referring_domain:N?.referrer&&((e=Lr(N.referrer))===null||e===void 0?void 0:e.host)||Eo},void 0)}set_initial_person_info(){if(this.props.$initial_campaign_params||this.props.$initial_referrer_info)return;const e=ng(this.Rr.mask_personal_data_properties,this.Rr.custom_personal_data_properties,this.Rr.disable_capture_url_hashes);this.register_once({[Cn]:this.Xo?{r:As(e.r),u:e.u?As(e.u):void 0}:e},void 0)}get_initial_props(){const e={};$e([$v,Tv],r=>{const n=this.props[r];n&&$e(n,function(i,s){e["$initial_"+Mc(s)]=i})});const t=this.props[Cn];if(t){const r=(function(n,i=!1){const s=ig(n,i),o={};return $e(s,function(a,c){o[`$initial_${Mc(c)}`]=a}),o})(t,this.Rr.disable_capture_url_hashes);Le(e,r)}return e}safe_merge(e){return $e(this.props,function(t,r){r in e||(e[r]=t)}),e}update_config(e,t,r){const n=e.persistence!==t.persistence,i=!((p,f)=>{if(p.length!==f.length)return!1;const v=[...p].sort(),m=[...f].sort();return v.every((_,w)=>_===m[w])})(e.cookie_persisted_properties||[],t.cookie_persisted_properties||[]),s=n||i,o=e.cookieWinsOnConflict!==t.cookieWinsOnConflict,a=e.disable_persistence||!!r,c=!!this.mi&&!a;a||this.Oa(t,c),this.Rr=e,!a&&(n||i||o)&&(this.Aa=void 0,this.Fa=void 0,this.Oa(b(b({},e),{},{cookie_persisted_properties:t.cookie_persisted_properties}),c));const l=s||o?this.ca(e):this.qo;this.Ja();const u=this.da(e),h=s||u!==this.Yo,d=!a&&(h||e.cross_subdomain_cookie!==this.Ga||e.secure_cookie!==this.Za)&&this.Da(c);this.na=h;try{if(this.Qa=this.Va=e.cookie_expiration,this.set_disabled(a),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),h){const p=this.props;this.clear(),this.qo=l,this.Yo=u,this.props=p,this.save()}else o&&(this.qo=l,a||(delete this.Jo[Qe],this.qa()))}finally{this.na=!1,d&&this.ja()}}Ja(){const e=this.props[Cn];if(!this.Xo||!be(e)||typeof e.r!="string")return;const t=As(e.r),r=typeof e.u=="string"?As(e.u):e.u;t===e.r&&r===e.u||this.Ca(Cn,b(b({},e),{},{r:t,u:r}))}set_disabled(e){this.mi=e,this.mi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ga&&(this.Ga=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.Za&&(this.Za=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,t){const r=this.props.__timers||{};r[e]=t,this.Ca(jc,r),this.save()}remove_event_timer(e){const t=this.props.__timers||{},r=t[e];return O(r)||(delete t[e],this.Ca(jc,t),this.save()),r}get_property(e){return this.props[e]}set_property(e,t){this.Ca(e,t),this.save()}Ca(e,t,r=!0){var n;const i=this.props[e];this.props[e]=t,r&&(e!=="distinct_id"&&e!=="$user_state"||i===t||(this.sa=!0),ih(e)&&!hr(i,t)&&this.oa.add(e),this.Ea(e,i,t),(n=at(e))!==null&&n!==void 0&&n.volatile||this.Ia(e))}$a(e,t=!0){delete this.props[e],t&&(Ya(e)&&this.ma(e,!0),ih(e)&&this.oa.add(e),this.Ia(e))}Ia(e){var t;const r=(t=at(e))===null||t===void 0?void 0:t.storageGroup;r&&(this.ya(r).dirty=!0)}ya(e){return this.Jo[e]||(this.Jo[e]={})}},Et={GZipJS:"gzip-js",Base64:"base64"},_i={Activation:"events",Cancellation:"cancelEvents"},Qa={Popover:"popover",API:"api",Widget:"widget",ExternalSurvey:"external_survey"},cr={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent",ABANDONED:"survey abandoned"},ec={SURVEY_ID:"$survey_id",SURVEY_NAME:"$survey_name",SURVEY_RESPONSE:"$survey_response",SURVEY_ITERATION:"$survey_iteration",SURVEY_ITERATION_START_DATE:"$survey_iteration_start_date",SURVEY_PARTIALLY_COMPLETED:"$survey_partially_completed",SURVEY_SUBMISSION_ID:"$survey_submission_id",SURVEY_QUESTIONS:"$survey_questions",SURVEY_COMPLETED:"$survey_completed",PRODUCT_TOUR_ID:"$product_tour_id",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date",SURVEY_LANGUAGE:"$survey_language"},rl={Popover:"popover",Inline:"inline"};function Is(e){let t=!0;return{dispose(){if(t){t=!1;const r=e();r&&rt(r.then)&&r.then(void 0,()=>{})}}}}var nS={SHOWN:"product tour shown",DISMISSED:"product tour dismissed",COMPLETED:"product tour completed",STEP_SHOWN:"product tour step shown",STEP_COMPLETED:"product tour step completed",BUTTON_CLICKED:"product tour button clicked",STEP_SELECTOR_FAILED:"product tour step selector failed",BANNER_CONTAINER_SELECTOR_FAILED:"product tour banner container selector failed",BANNER_ACTION_CLICKED:"product tour banner action clicked"},oh={TOUR_ID:"$product_tour_id",TOUR_NAME:"$product_tour_name",TOUR_ITERATION:"$product_tour_iteration",TOUR_RENDER_REASON:"$product_tour_render_reason",TOUR_STEP_ID:"$product_tour_step_id",TOUR_STEP_ORDER:"$product_tour_step_order",TOUR_STEP_TYPE:"$product_tour_step_type",TOUR_DISMISS_REASON:"$product_tour_dismiss_reason",TOUR_BUTTON_TEXT:"$product_tour_button_text",TOUR_BUTTON_ACTION:"$product_tour_button_action",TOUR_BUTTON_LINK:"$product_tour_button_link",TOUR_BUTTON_TOUR_ID:"$product_tour_button_tour_id",TOUR_STEPS_COUNT:"$product_tour_steps_count",TOUR_STEP_SELECTOR:"$product_tour_step_selector",TOUR_STEP_SELECTOR_FOUND:"$product_tour_step_selector_found",TOUR_STEP_ELEMENT_TAG:"$product_tour_step_element_tag",TOUR_STEP_ELEMENT_ID:"$product_tour_step_element_id",TOUR_STEP_ELEMENT_CLASSES:"$product_tour_step_element_classes",TOUR_STEP_ELEMENT_TEXT:"$product_tour_step_element_text",TOUR_ERROR:"$product_tour_error",TOUR_MATCHES_COUNT:"$product_tour_matches_count",TOUR_FAILURE_PHASE:"$product_tour_failure_phase",TOUR_WAITED_FOR_ELEMENT:"$product_tour_waited_for_element",TOUR_WAIT_DURATION_MS:"$product_tour_wait_duration_ms",TOUR_BANNER_SELECTOR:"$product_tour_banner_selector",TOUR_LINKED_SURVEY_ID:"$product_tour_linked_survey_id",USE_MANUAL_SELECTOR:"$use_manual_selector",INFERENCE_DATA_PRESENT:"$inference_data_present",TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},ah=Be("[RateLimiter]"),iS=class{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=t=>{const r=t.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach(n=>{ah.info(`${n||"events"} is quota limited.`),this.serverLimits[n]=new Date().getTime()+6e4})}catch(n){ah.warn(`could not rate limit - continuing. Error: "${n?.message}"`,{text:r});return}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)===null||e===void 0?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)===null||e===void 0?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e=!1){var t,r,n;const{captureEventsBurstLimit:i,captureEventsPerSecond:s}=this,o=new Date().getTime(),a=(t=(r=this.instance.persistence)===null||r===void 0?void 0:r.get_property("$capture_rate_limit"))!==null&&t!==void 0?t:{tokens:i,last:o};a.tokens+=(o-a.last)/1e3*s,a.last=o,a.tokens>i&&(a.tokens=i);const c=1>a.tokens;if(c||e||(a.tokens=Math.max(0,a.tokens-1)),c&&!e){const l=(We(a.dropped)?a.dropped:0)+1;a.dropped=l,!this.lastEventRateLimited&&this.Ka(l)&&(a.dropped=0)}return this.lastEventRateLimited=c,(n=this.instance.persistence)===null||n===void 0||n.set_property("$capture_rate_limit",a),{isRateLimited:c,remainingTokens:a.tokens}}Xa(e){const t=this.instance.config.property_denylist;return!ce(t)||!t.includes(e)}Ya(){var e;if(this.Xa("$current_url")&&this.Xa("$pathname")&&je?.pathname)return`${(e=je.origin)!==null&&e!==void 0?e:""}${je.pathname}`}Ka(e){var t,r;const{captureEventsBurstLimit:n,captureEventsPerSecond:i}=this,s=this.Ya(),o=this.Xa("$session_id")?(t=(r=this.instance).get_session_id)===null||t===void 0?void 0:t.call(r):void 0,a=[`${e} event(s) dropped since the last warning`,s?`triggered on ${s}`:void 0,o?`session ${o}`:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:`posthog-js client rate limited: ${a}. Config is set to ${i} events per second and ${n} events burst limit.`},{skip_client_rate_limiting:!0})}isServerRateLimited(e){const t=this.serverLimits[e||"events"]||!1;return t!==!1&&new Date().getTime()<t}},pr=Be("[RemoteConfig]"),ag=class{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=te._POSTHOG_REMOTE_CONFIG)===null||e===void 0||(e=e[this._instance.config.token])===null||e===void 0?void 0:e.config}tl(e){var t,r,n;!((t=te.__PosthogExtensions__)===null||t===void 0)&&t.loadExternalDependency?(r=te.__PosthogExtensions__)===null||r===void 0||(n=r.loadExternalDependency)===null||n===void 0||n.call(r,this._instance,"remote-config",()=>e(this.remoteConfig)):e()}el(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets",`/array/${this._instance.config.token}/config`),callback:e})}load(){try{if(this.remoteConfig)return pr.info("Using preloaded remote config",this.remoteConfig),void this.il(this.remoteConfig);if(this._instance.nl())return void pr.warn("Remote config is disabled. Falling back to local config.");this.tl(e=>{if(!e)return pr.info("No config found after loading remote JS config. Falling back to JSON."),void this.el(t=>{this.il(t.json,t)});this.il(e)})}catch(e){pr.error("Error loading remote config",e),this.il()}}il(e,t){!e&&t&&(t.statusCode===0?t.error||pr.warn("Failed to fetch remote config from PostHog."):pr.error("Failed to fetch remote config from PostHog."));try{this._instance.il(e?{ok:!0,config:e}:{ok:!1})}catch(n){pr.error("Error applying remote config",n)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var r;(r=this._instance.featureFlags)===null||r===void 0||r.ensureFlagsLoaded()}catch(n){pr.error("Error loading feature flags",n)}}},kt=Uint8Array,mt=Uint16Array,ti=Uint32Array,du=new kt([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),hu=new kt([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),ch=new kt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),cg=function(e,t){for(var r=new mt(31),n=0;31>n;++n)r[n]=t+=1<<e[n-1];var i=new ti(r[30]);for(n=1;30>n;++n)for(var s=r[n];r[n+1]>s;++s)i[s]=s-r[n]<<5|n;return[r,i]},lg=cg(du,2),nl=lg[1];lg[0][28]=258,nl[258]=28;for(var lh=cg(hu,0)[1],il=new mt(32768),Ve=0;32768>Ve;++Ve){var kn=(43690&Ve)>>>1|(21845&Ve)<<1;il[Ve]=((65280&(kn=(61680&(kn=(52428&kn)>>>2|(13107&kn)<<2))>>>4|(3855&kn)<<4))>>>8|(255&kn)<<8)>>>1}var ji=function(e,t,r){for(var n=e.length,i=0,s=new mt(t);n>i;++i)++s[e[i]-1];var o,a=new mt(t);for(i=0;t>i;++i)a[i]=a[i-1]+s[i-1]<<1;if(r){o=new mt(1<<t);var c=15-t;for(i=0;n>i;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],h=a[e[i]-1]++<<u,d=h|(1<<u)-1;d>=h;++h)o[il[h]>>>c]=l}else for(o=new mt(n),i=0;n>i;++i)o[i]=il[a[e[i]-1]++]>>>15-e[i];return o},vn=new kt(288);for(Ve=0;144>Ve;++Ve)vn[Ve]=8;for(Ve=144;256>Ve;++Ve)vn[Ve]=9;for(Ve=256;280>Ve;++Ve)vn[Ve]=7;for(Ve=280;288>Ve;++Ve)vn[Ve]=8;var ko=new kt(32);for(Ve=0;32>Ve;++Ve)ko[Ve]=5;var sS=ji(vn,9,0),oS=ji(ko,5,0),ug=function(e){return(e/8|0)+(7&e&&1)},dg=function(e,t,r){(t==null||0>t)&&(t=0),(r==null||r>e.length)&&(r=e.length);var n=new(e instanceof mt?mt:e instanceof ti?ti:kt)(r-t);return n.set(e.subarray(t,r)),n},Xt=function(e,t,r){var n=t/8|0;e[n]|=r<<=7&t,e[n+1]|=r>>>8},yi=function(e,t,r){var n=t/8|0;e[n]|=r<<=7&t,e[n+1]|=r>>>8,e[n+2]|=r>>>16},tc=function(e,t){for(var r=[],n=0;e.length>n;++n)e[n]&&r.push({s:n,f:e[n]});var i=r.length,s=r.slice();if(!i)return[new kt(0),0];if(i==1){var o=new kt(r[0].s+1);return o[r[0].s]=1,[o,1]}r.sort(function(I,C){return I.f-C.f}),r.push({s:-1,f:25001});var a=r[0],c=r[1],l=0,u=1,h=2;for(r[0]={s:-1,f:a.f+c.f,l:a,r:c};u!=i-1;)a=r[r[h].f>r[l].f?l++:h++],c=r[l!=u&&r[h].f>r[l].f?l++:h++],r[u++]={s:-1,f:a.f+c.f,l:a,r:c};var d=s[0].s;for(n=1;i>n;++n)s[n].s>d&&(d=s[n].s);var p=new mt(d+1),f=sl(r[u-1],p,0);if(f>t){n=0;var v=0,m=f-t,_=1<<m;for(s.sort(function(I,C){return p[C.s]-p[I.s]||I.f-C.f});i>n;++n){var w=s[n].s;if(t>=p[w])break;v+=_-(1<<f-p[w]),p[w]=t}for(v>>>=m;v>0;){var S=s[n].s;t>p[S]?v-=1<<t-p[S]++-1:++n}for(;n>=0&&v;--n){var T=s[n].s;p[T]==t&&(--p[T],++v)}f=t}return[new kt(p),f]},sl=function(e,t,r){return e.s==-1?Math.max(sl(e.l,t,r+1),sl(e.r,t,r+1)):t[e.s]=r},uh=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new mt(++t),n=0,i=e[0],s=1,o=function(c){r[n++]=c},a=1;t>=a;++a)if(e[a]==i&&a!=t)++s;else{if(!i&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(i),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(i);s=1,i=e[a]}return[r.subarray(0,n),t]},bi=function(e,t){for(var r=0,n=0;t.length>n;++n)r+=e[n]*t[n];return r},Zs=function(e,t,r){var n=r.length,i=ug(t+2);e[i]=255&n,e[i+1]=n>>>8,e[i+2]=255^e[i],e[i+3]=255^e[i+1];for(var s=0;n>s;++s)e[i+s+4]=r[s];return 8*(i+4+n)},dh=function(e,t,r,n,i,s,o,a,c,l,u){Xt(t,u++,r),++i[256];for(var h=tc(i,15),d=h[0],p=h[1],f=tc(s,15),v=f[0],m=f[1],_=uh(d),w=_[0],S=_[1],T=uh(v),I=T[0],C=T[1],M=new mt(19),L=0;w.length>L;++L)M[31&w[L]]++;for(L=0;I.length>L;++L)M[31&I[L]]++;for(var q=tc(M,7),X=q[0],ee=q[1],k=19;k>4&&!X[ch[k-1]];--k);var ie,H,oe,$,Q=l+5<<3,y=bi(i,vn)+bi(s,ko)+o,V=bi(i,d)+bi(s,v)+o+14+3*k+bi(M,X)+(2*M[16]+3*M[17]+7*M[18]);if(y>=Q&&V>=Q)return Zs(t,u,e.subarray(c,c+l));if(Xt(t,u,1+(y>V)),u+=2,y>V){ie=ji(d,p,0),H=d,oe=ji(v,m,0),$=v;var K=ji(X,ee,0);for(Xt(t,u,S-257),Xt(t,u+5,C-1),Xt(t,u+10,k-4),u+=14,L=0;k>L;++L)Xt(t,u+3*L,X[ch[L]]);u+=3*k;for(var le=[w,I],de=0;2>de;++de){var Ce=le[de];for(L=0;Ce.length>L;++L)Xt(t,u,K[Re=31&Ce[L]]),u+=X[Re],Re>15&&(Xt(t,u,Ce[L]>>>5&127),u+=Ce[L]>>>12)}}else ie=sS,H=vn,oe=oS,$=ko;for(L=0;a>L;++L)if(n[L]>255){var Re;yi(t,u,ie[257+(Re=n[L]>>>18&31)]),u+=H[Re+257],Re>7&&(Xt(t,u,n[L]>>>23&31),u+=du[Re]);var _e=31&n[L];yi(t,u,oe[_e]),u+=$[_e],_e>3&&(yi(t,u,n[L]>>>5&8191),u+=hu[_e])}else yi(t,u,ie[n[L]]),u+=H[n[L]];return yi(t,u,ie[256]),u+H[256]},aS=new ti([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),cS=new kt(0),lS=(function(){for(var e=new ti(256),t=0;256>t;++t){for(var r=t,n=9;--n;)r=(1&r&&3988292384)^r>>>1;e[t]=r}return e})(),rc=function(e,t,r){for(;r;++t)e[t]=r,r>>>=8};function uS(e,t){t===void 0&&(t={});var r=(function(){var d=4294967295;return{p(p){for(var f=d,v=0;p.length>v;++v)f=lS[255&f^p[v]]^f>>>8;d=f},d(){return 4294967295^d}}})(),n=e.length;r.p(e);var i,s,o,a,c,l,u=(a=10+((i=t).filename&&i.filename.length+1||0),c=8,(function(d,p,f,v,m,_){var w=d.length,S=new kt(v+w+5*(1+Math.floor(w/7e3))+m),T=S.subarray(v,S.length-m),I=0;if(!p||8>w)for(var C=0;w>=C;C+=65535){var M=C+65535;w>M?I=Zs(T,I,d.subarray(C,M)):(T[C]=_,I=Zs(T,I,d.subarray(C,w)))}else{for(var L=aS[p-1],q=L>>>13,X=8191&L,ee=(1<<f)-1,k=new mt(32768),ie=new mt(ee+1),H=Math.ceil(f/3),oe=2*H,$=function(g){return(d[g]^d[g+1]<<H^d[g+2]<<oe)&ee},Q=new ti(25e3),y=new mt(288),V=new mt(32),K=0,le=0,de=(C=0,0),Ce=0,Re=0;w>C;++C){var _e=$(C),ve=32767&C,Je=ie[_e];if(k[ve]=Je,ie[_e]=ve,C>=Ce){var Xe=w-C;if((K>7e3||de>24576)&&Xe>423){I=dh(d,T,0,Q,y,V,le,de,Re,C-Re,I),de=K=le=0,Re=C;for(var Pe=0;286>Pe;++Pe)y[Pe]=0;for(Pe=0;30>Pe;++Pe)V[Pe]=0}var z=2,se=0,ae=X,he=ve-Je&32767;if(Xe>2&&_e==$(C-he))for(var Oe=Math.min(q,Xe)-1,we=Math.min(32767,C),Se=Math.min(258,Xe);we>=he&&--ae&&ve!=Je;){if(d[C+z]==d[C+z-he]){for(var pe=0;Se>pe&&d[C+pe]==d[C+pe-he];++pe);if(pe>z){if(z=pe,se=he,pe>Oe)break;var me=Math.min(he,pe-2),Ee=0;for(Pe=0;me>Pe;++Pe){var Ge=C-he+Pe+32768&32767,U=Ge-k[Ge]+32768&32767;U>Ee&&(Ee=U,Je=Ge)}}}he+=(ve=Je)-(Je=k[ve])+32768&32767}if(se){Q[de++]=268435456|nl[z]<<18|lh[se];var W=31&nl[z],Y=31&lh[se];le+=du[W]+hu[Y],++y[257+W],++V[Y],Ce=C+z,++K}else Q[de++]=d[C],++y[d[C]]}}I=dh(d,T,_,Q,y,V,le,de,Re,C-Re,I),_||(I=Zs(T,I,cS))}return dg(S,0,v+ug(I)+m)})(s=e,(o=t).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,c,!l)),h=u.length;return(function(d,p){var f=p.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>p.level?4:p.level==9?2:0,d[9]=3,p.mtime!=0&&rc(d,4,Math.floor(new Date(p.mtime||Date.now())/1e3)),f){d[3]=8;for(var v=0;f.length>=v;++v)d[v+10]=f.charCodeAt(v)}})(u,t),rc(u,h-8,r.d()),rc(u,h-4,n),u}var dS=!!Zl||!!Zi,hg=new WeakMap,pg="text/plain",nc=0,Js=!1,fg=(e,t)=>{const[r,n]=e.split("#"),[i,s]=r.split("?");if(!s)return e;const o=s.split("&").filter(a=>a.split("=")[0]!==t).join("&");return`${i}${o?`?${o}`:""}${n?`#${n}`:""}`},ds=(e,t,r=!0)=>{var n;const[i,s]=e.split("?"),o=b({},t),a=(n=s?.split("&").map(l=>{var u;const[h,d]=l.split("="),p=r&&(u=o[h])!==null&&u!==void 0?u:d;return delete o[h],`${h}=${p}`}))!==null&&n!==void 0?n:[],c=(function(l,u="&"){let h,d;const p=[];return $e(l,function(f,v){O(f)||O(v)||v==="undefined"||(h=encodeURIComponent((m=>m instanceof File)(f)?f.name:f.toString()),d=encodeURIComponent(v),p[p.length]=d+"="+h)}),p.join(u)})(o);return c&&a.push(c),a.length>0?`${i}?${a.join("&")}`:i},ic=e=>{if(e.sl)return e.sl;const{data:t,compression:r}=e;if(!t)return;if(r===Et.GZipJS){const i=uS((function(s){var o=s.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(s);for(var a=new kt(s.length+(s.length>>>1)),c=0,l=function(p){a[c++]=p},u=0;o>u;++u){if(c+5>a.length){var h=new kt(c+8+(o-u<<1));h.set(a),a=h}var d=s.charCodeAt(u);128>d?l(d):2048>d?(l(192|d>>>6),l(128|63&d)):d>55295&&57344>d?(l(240|(d=65536+(1047552&d)|1023&s.charCodeAt(++u))>>>18),l(128|d>>>12&63),l(128|d>>>6&63),l(128|63&d)):(l(224|d>>>12),l(128|d>>>6&63),l(128|63&d))}return dg(a,0,c)})(On(t)),{mtime:0});return{contentType:pg,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(r===Et.Base64){const i=(s=>"data="+encodeURIComponent(typeof s=="string"?s:On(s)))((function(s){return s&&btoa(encodeURIComponent(s).replace(/%([0-9A-F]{2})/g,(o,a)=>String.fromCharCode(parseInt(a,16))))})(On(t)));return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}const n=On(t);return{contentType:"application/json",body:n,estimatedSize:new Blob([n]).size}},vg=e=>{const t=()=>e.transport==="sendBeacon"?{url:ds(e.url,{compression:Et.Base64}),encodedBody:ic(b(b({},e),{},{compression:Et.Base64,sl:void 0}))}:{url:fg(e.url,"compression"),encodedBody:ic(b(b({},e),{},{compression:void 0,sl:void 0}))};let r;try{r=ic(e)}catch(i){if(Pd(e.compression,Qn(e.url,"compression")))return j.error("Failed to gzip request body, sending uncompressed payload",i),t();throw i}return r&&Pd(e.compression,Qn(e.url,"compression"))&&!((n=r.body)instanceof ArrayBuffer?Fc(new Uint8Array(n)):ArrayBuffer.isView(n)&&Fc(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Js=!0,t()):{url:e.url,encodedBody:r};var n},gg=e=>{try{return vg(e)}catch(r){var t;j.error(r),(t=e.callback)===null||t===void 0||t.call(e,{statusCode:0,error:r});return}},hS=(function(){var e=Ue(function*(t){const r=yield(function(i){return qc.apply(this,arguments)})(On(t.data),et.DEBUG,{rethrow:!0});if(!r)return t;const n=yield r.arrayBuffer();return b(b({},t),{},{sl:{contentType:pg,body:n,estimatedSize:n.byteLength}})});return function(t){return e.apply(this,arguments)}})(),pS=/Failed to fetch|NetworkError|Load failed/i,mg=e=>e?.name==="TypeError"&&pS.test(e?.message||""),_g=e=>{try{const t=(function(r,n=Date.now()){if(typeof r!="string"||!r)return;const i=r.trim(),s=/^\d+\s*,/.test(i)?i.slice(0,i.indexOf(",")).trim():i;if(/^\d+$/.test(s)){const c=1e3*Math.min(Number(s),300);return c>0?c:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(s))return;const o=/^\w{3} \w{3} /.test(s)?s+" GMT":s,a=Date.parse(o)-n;return Number.isFinite(a)&&a>0?Math.min(a,Bs):void 0})(e());return O(t)?void 0:Math.min(t,3e4)}catch{return}},yg=e=>{const t=gg(e);if(!t)return;const r=new Zl;hg.set(r,!0);const{url:n,encodedBody:i}=t;r.open(e.method||"GET",n,!0);const{contentType:s,body:o}=i??{};$e(e.headers,function(a,c){r.setRequestHeader(c,a)}),s&&r.setRequestHeader("Content-Type",s),e.timeout&&(r.timeout=e.timeout),r.onreadystatechange=()=>{if(r.readyState===4){var a;const c={statusCode:r.status,text:r.responseText};if(r.status===200)try{c.json=JSON.parse(r.responseText)}catch{}(a=e.callback)===null||a===void 0||a.call(e,c,_g(()=>r.getResponseHeader("Retry-After")))}},r.send(o)},bg=e=>{const t=gg(e);if(!t)return;const{url:r,encodedBody:n}=t,{contentType:i,body:s,estimatedSize:o}=n??{},a=new Headers;$e(e.headers,function(f,v){a.append(v,f)}),i&&a.append("Content-Type",i);let c=null,l=!1;if(vd){const f=new vd;c={signal:f.signal,timeout:setTimeout(()=>{l=!0;try{f.abort(ev("AbortError","PostHog request timed out"+((v=e.timeout)?` after ${v}ms`:"")))}catch(m){h(m)}var v},e.timeout)}}let u=!1;const h=f=>{var v;u||(u=!0,l&&f?.name==="AbortError"||mg(f)?j.warn(f):j.error(f),(v=e.callback)===null||v===void 0||v.call(e,{statusCode:0,error:f}))};let d=0;const p=()=>{nc-=d,d=0,c&&clearTimeout(c.timeout)};try{const f=b({method:e?.method||"GET",headers:a,referrerPolicy:"strict-origin",body:s,signal:c?.signal},e.fetchOptions),v=o??(O(s)?0:void 0);f.keepalive=f.method==="POST"&&!e.rl&&f.keepalive!==!1&&f.body===s&&!O(v)&&v>=0&&52428.8>nc+v,f.keepalive&&(d=v,nc+=d),Zi(r,f).then(m=>m.text().then(_=>{var w;if(u)return;const S={statusCode:m.status,text:_};if(m.status===200)try{S.json=JSON.parse(_)}catch(T){j.error(T)}u=!0,p(),(w=e.callback)===null||w===void 0||w.call(e,S,_g(()=>m.headers.get("Retry-After")))})).catch(m=>{p(),h(m)}).finally(p)}catch(f){p(),h(f)}},ol=e=>{try{var t;const{url:r,encodedBody:n}=vg(e),{contentType:i,body:s,estimatedSize:o}=n??{};if(!s)return;const a=s instanceof Blob?s:new Blob([s],{type:i});if(nt.sendBeacon(r,a))return;const c=ce(e.data)?e.data:(t=e.data)===null||t===void 0?void 0:t.batch;if(ce(c)&&c.length>1&&(o??0)>16384){const l=Math.ceil(c.length/2),u=h=>ce(e.data)?h:b(b({},e.data),{},{batch:h});ol(b(b({},e),{},{data:u(c.slice(0,l))})),ol(b(b({},e),{},{data:u(c.slice(l))}));return}j.warn(`Beacon of ~${o??0} bytes was rejected by the browser, falling back to ${Zi?"fetch":"XHR"}`),Zi?bg(b(b({},e),{},{rl:!0})):yg(e)}catch(r){j.warn("Beacon send failed",r)}},hh=(e,t,r,n)=>{const i=n==="query"?t==="POST"?"sent_at":"_":void 0;return ds(r===Et.GZipJS?fg(e,"compression"):e,b(b({},i?{[i]:Date.now().toString()}:{}),r===Et.GZipJS?{}:{compression:r}))},fS=(()=>{const e=[];return Zi&&e.push({transport:"fetch",method:bg}),Zl&&e.push({transport:"XHR",method:yg}),nt!=null&&nt.sendBeacon&&e.push({transport:"sendBeacon",method:ol}),e})(),wg=!dS&&ft?.indexOf("MSIE")===-1&&ft?.indexOf("Mozilla")===-1;function Sg(e,t,r){var n,i,s;r&&(t=b(b({},t),{},{callback:o=>r(o)})),e.__loaded?wg?e.__request_queue.push(t):e.rateLimiter.isServerRateLimited(t.batchKey)?t.fireCallbackOnDrop&&((i=t.callback)===null||i===void 0||i.call(t,{statusCode:429})):(t.transport=t.transport||e.config.api_transport,t.headers=b(b({},e.config.request_headers),t.headers),t.compression=t.compression==="best-available"?(n=e.compression)!==null&&n!==void 0?n:t.compressionFallback:t.compression,(O(e.config.disable_beacon)?e.config.__preview_disable_beacon:e.config.disable_beacon)&&(t.disableTransport=["sendBeacon"]),t.fetchOptions=t.fetchOptions||e.config.fetch_options,((o,a)=>{var c,l,u;const h=b(b({},o),{},{callback:a??(m=>{var _;return(_=o.callback)===null||_===void 0?void 0:_.call(o,m)})});h.timeout=h.timeout||6e4;const d=(c=h.transport)!==null&&c!==void 0?c:"fetch";d==="sendBeacon"&&O(h.compression)&&h.data&&(h.compression=Et.Base64),h.method==="POST"&&h.data&&(h.timestampMode==="capture-body"?h.data=(m=>{var _,w;const S=(ce(m)?m:[m]).map(I=>b(b({},I),I.timestamp instanceof Date&&!isNaN(I.timestamp.getTime())?{timestamp:I.timestamp.toISOString()}:{})),T=S[0];return{api_key:(_=T==null||(w=T.properties)===null||w===void 0?void 0:w.token)!==null&&_!==void 0?_:T?.token,batch:S,sent_at:new Date().toISOString()}})(h.data):h.timestampMode==="body"&&(h.data=((m,_=new Date().toISOString())=>ce(m)?m.map(w=>b(b({},w),{},{sent_at:_})):b(b({},m),{},{sent_at:_}))(h.data))),h.url=hh(h.url,h.method,h.compression,h.timestampMode);const p=fS.filter(m=>!h.disableTransport||!m.transport||!h.disableTransport.includes(m.transport)),f=(l=(u=(function(m,_){for(let w=0;m.length>w;w++)if(_(m[w]))return m[w]})(p,m=>m.transport===d))===null||u===void 0?void 0:u.method)!==null&&l!==void 0?l:p[0].method;if(!f)throw new Error("No available transport method");const v=m=>{try{f(m)}catch(w){var _;mg(w)?j.warn(w):j.error(w),(_=h.callback)===null||_===void 0||_.call(h,{statusCode:0,error:w})}};d!=="sendBeacon"&&!h.preferSyncCompression&&h.data&&h.compression===Et.GZipJS&&Y0&&typeof Promise<"u"&&!Js?hS(h).then(m=>{v(m)}).catch(m=>{if(Od(m))return Js=!0,void v(b(b({},h),{},{compression:void 0,url:hh(o.url,o.method,void 0,o.timestampMode)}));(_=>{if(!_||typeof _!="object")return!1;const w="name"in _?String(_.name):"";return Od(_)||w===av})(m)&&(Js=!0),v(h)}):v(h)})(t,(o,a)=>{var c,l,u;e.rateLimiter.checkForLimiting(o),400>o.statusCode||(c=(l=e.config).on_request_error)===null||c===void 0||c.call(l,o),r?r(o,a):(u=t.callback)===null||u===void 0||u.call(t,o)})):t.fireCallbackOnDrop&&((s=t.callback)===null||s===void 0||s.call(t,{statusCode:0}))}var vS=class{constructor(e,t){this.ol=!0,this.al=[],this.ll=Wt(t?.flush_interval_ms||3e3,250,5e3,j.createLogger("flush interval"),3e3),this.ul=e}enqueue(e){this.al.push(e),this.hl||this.cl()}unload(){this.dl();const e=this.al.length>0?this.vl():{},t=Object.values(e);[...t.filter(r=>r.url.indexOf("/e")===0),...t.filter(r=>r.url.indexOf("/e")!==0)].map(r=>{this.fl(r,"sendBeacon")})}enable(){this.ol=!1,this.cl()}cl(){this.ol||(this.hl=setTimeout(()=>{if(this.dl(),this.al.length>0){const e=this.vl();for(const t in e)this.fl(e[t])}},this.ll))}fl(e,t){try{this.ul(e,t)}catch(r){j.error(r)}}dl(){clearTimeout(this.hl),this.hl=void 0}vl(){const e={};return $e(this.al,t=>{var r;const n=t,i=((n?n.batchKey:null)||n.url)+(n.batchGroup?`:${n.batchGroup}`:"");O(e[i])&&(e[i]=b(b({},n),{},{data:[]})),(r=e[i].data)===null||r===void 0||r.push(n.data)}),this.al=[],e}},gS=["retriesPerformedSoFar"],mS=class{constructor(e){this._instance=e,this.pl=!1,this.gl=3e3,this.al=[],this.al=[],this.ml=!0,this.resume()}resume(){if(!O(A)&&"onLine"in A.navigator){if(this.ml=A.navigator.onLine,this.yl)return;this.yl=()=>{this.ml=!0,this.bl()},this._l=()=>{this.ml=!1},Ie(A,"online",this.yl),Ie(A,"offline",this._l)}}get length(){return this.al.length}retriableRequest(e,t){let{retriesPerformedSoFar:r}=e,n=cv(e,gS);tr(r)&&(n.url=ds(n.url,{retry_count:r})),Sg(this._instance,t?b(b({},n),{},{transport:t}):n,(i,s)=>{var o;if(i.statusCode!==200&&(400>i.statusCode||i.statusCode>=500)){if((i.statusCode===0?3:10)>(r??0))return void this.Ls(b({retriesPerformedSoFar:r},n),s);i.statusCode===0&&j.warn(`Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after ${r??0} retries.`)}(o=n.callback)===null||o===void 0||o.call(n,i)})}Ls(e,t){const r=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=r+1;const n=Math.max((function(o){const a=3e3*Math.pow(2,o),c=a/2,l=Math.min(18e5,a),u=(Math.random()-.5)*(l-c);return Math.ceil(l+u)})(r),t??0),i=Date.now()+n;this.al.push({retryAt:i,requestOptions:e});let s=`Enqueued failed request for retry in ${n}`;navigator.onLine||(s+=" (Browser is offline)"),j.warn(s),this.pl||(this.pl=!0,this.wl())}wl(){if(this.kl&&clearTimeout(this.kl),this.al.length===0)return this.pl=!1,void(this.kl=void 0);this.kl=setTimeout(()=>{this.ml&&this.al.length>0&&this.bl(),this.wl()},this.gl)}bl(){const e=Date.now(),t=[],r=this.al.filter(n=>e>n.retryAt||(t.push(n),!1));if(this.al=t,r.length>0)for(const{requestOptions:n}of r)this.retriableRequest(n)}unload(){this.kl&&(clearTimeout(this.kl),this.kl=void 0),this.pl=!1,O(A)||(this.yl&&(A.removeEventListener("online",this.yl),this.yl=void 0),this._l&&(A.removeEventListener("offline",this._l),this._l=void 0));for(const{requestOptions:e}of this.al)try{this._instance._send_request(b(b({},e),{},{transport:"sendBeacon"}))}catch(t){j.error(t)}this.al=[]}},_S=class{constructor(e){this._instance=e,this.Sl=()=>{var t,r,n,i;this.xl||(this.xl={});const s=this.scrollElement(),o=this.scrollY(),a=s?Math.max(0,s.scrollHeight-s.clientHeight):0,c=o+(s?.clientHeight||0),l=s?.scrollHeight||0;this.xl.lastScrollY=Math.ceil(o),this.xl.maxScrollY=Math.max(o,(t=this.xl.maxScrollY)!==null&&t!==void 0?t:0),this.xl.maxScrollHeight=Math.max(a,(r=this.xl.maxScrollHeight)!==null&&r!==void 0?r:0),this.xl.lastContentY=c,this.xl.maxContentY=Math.max(c,(n=this.xl.maxContentY)!==null&&n!==void 0?n:0),this.xl.maxContentHeight=Math.max(l,(i=this.xl.maxContentHeight)!==null&&i!==void 0?i:0)}}get Cl(){return this._instance.config.scroll_root_selector}getContext(){return this.xl}resetContext(){const e=this.xl;return this.xl=void 0,setTimeout(this.Sl,0),e}startMeasuringScrollPosition(){Ie(A,"scroll",this.Sl,{capture:!0}),Ie(A,"scrollend",this.Sl,{capture:!0}),Ie(A,"resize",this.Sl)}scrollElement(){if(this.Cl){const r=ce(this.Cl)?this.Cl:[this.Cl];for(const n of r){var e;const i=A==null||(e=A.document)===null||e===void 0?void 0:e.querySelector(n);if(i)return i}return}var t;return A==null||(t=A.document)===null||t===void 0?void 0:t.documentElement}$l(e){var t,r;const n=e==="y"?"scrollTop":"scrollLeft";if(this.Cl){const i=this.scrollElement();return i&&i[n]||0}return A?e==="y"?A.scrollY||A.pageYOffset||((t=A.document)===null||t===void 0||(t=t.documentElement)===null||t===void 0?void 0:t.scrollTop)||0:A.scrollX||A.pageXOffset||((r=A.document)===null||r===void 0||(r=r.documentElement)===null||r===void 0?void 0:r.scrollLeft)||0:0}scrollY(){return this.$l("y")}scrollX(){return this.$l("x")}},yS=e=>ng(e?.config.mask_personal_data_properties,e?.config.custom_personal_data_properties,e?.config.disable_capture_url_hashes),ph=class{constructor(e,t,r,n){this.Be=i=>{const s=this.Tl();if(s&&s.sessionId===i)return;const o={sessionId:i,props:this.Il(this._instance)};this.Ml.register({[Kc]:o})},this._instance=e,this.El=t,this.Ml=r,this.Il=n||yS,this.El.onSessionId(this.Be)}Tl(){return this.Ml.props[Kc]}getSetOnceProps(){var e;const t=(e=this.Tl())===null||e===void 0?void 0:e.props;return t?"r"in t?ig(t,this._instance.config.disable_capture_url_hashes):{$referring_domain:t.referringDomain,$pathname:t.initialPathName,utm_source:t.utm_source,utm_campaign:t.utm_campaign,utm_medium:t.utm_medium,utm_content:t.utm_content,utm_term:t.utm_term}:{}}getSessionProps(){const e={};return $e(ou(this.getSetOnceProps()),(t,r)=>{r==="$current_url"&&(r="url"),e[`$session_entry_${Mc(r)}`]=t}),e}},Ro=class{on(e,t){return this.Pl[e]||(this.Pl[e]=[]),this.Pl[e].push(t),()=>{this.Pl[e]=this.Pl[e].filter(r=>r!==t)}}emit(e,t){for(const r of this.Pl[e]||[])r(t);for(const r of this.Pl["*"]||[])r(e,t)}constructor(){this.Pl={}}},Rn=Be("[SessionId]"),fh=864e5,vh=class{on(e,t){return this.Rl.on(e,t)}constructor(e,t,r){var n;if(this.Al=null,this.Fl=null,this.Ol=[],this.Dl=void 0,this.Ll=!1,this.Rl=new Ro,this.Nl=(s,o)=>!(!tr(s)||!tr(o))&&Math.abs(s-o)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Rr=e.config,this.Ml=e.persistence,this.He=void 0,this.Xt=void 0,this._sessionStartTimestamp=null,this.ql=void 0,this._sessionActivityTimestamp=null,this.jl=t||Nt,this.Bl=r||Nt;const i=this.Rr.persistence_name||this.Rr.token;if(this._sessionTimeoutMs=1e3*Wt(this.Rr.session_idle_timeout_seconds||1800,60,36e3,Rn.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.Hl(),this.zl="ph_"+i+"_window_id",this.Ul="ph_"+i+"_primary_window_exists",this.Wl()){const s=xe.Dt(this.zl),o=xe.Dt(this.Ul);s&&!o?this.He=s:xe.Lt(this.zl),xe.At(this.Ul,!0)}(n=this.Rr.bootstrap)!==null&&n!==void 0&&n.sessionID&&this.setBootstrapSessionId(this.Rr.bootstrap.sessionID),this.Vl()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return O(this.Ol)&&(this.Ol=[]),this.Ol.push(e),this.Xt&&e(this.Xt,this.He),()=>{this.Ol=this.Ol.filter(t=>t!==e)}}Wl(){return this.Rr.persistence!=="memory"&&!this.Ml.mi&&xe.Et()}Gl(e){e!==this.He&&(this.He=e,this.Wl()&&xe.At(this.zl,e))}Zl(){return this.He?this.He:this.Wl()?xe.Dt(this.zl):null}Ql(e){const t=this.Al;return!He(t)&&!He(e)&&5e3>Math.abs(e-t)}Jl(e,t,r){const n=t!==this._sessionActivityTimestamp,i=!(e!==this.Xt||r!==this._sessionStartTimestamp);this._sessionStartTimestamp=r,this._sessionActivityTimestamp=t,this.Xt=e,i&&!n||i&&this.Ql(t)||(this.Al=t,this.Ml.register({[$n]:[t,e,r]}))}Kl(){var e;const t=(e=this.Rr)===null||e===void 0?void 0:e.persistence_save_debounce_ms;return tr(t)&&t>0}Xl(){this.Kl()?this.Ml.refreshKey($n):(this.Ml.flush(),this.Ml.load())}Yl(){var e;if(He(this._sessionActivityTimestamp)||this._sessionActivityTimestamp===this.Al)return;this.Xl();const[,t,r]=this.tu();t===this.Xt&&r===this._sessionStartTimestamp&&(this.Al=this._sessionActivityTimestamp,this.Ml.register({[$n]:[this._sessionActivityTimestamp,(e=this.Xt)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Ml.flush())}eu(){const[e]=this.tu(),t=tr(e)?e:0,r=tr(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(t,r)}iu(e){return this.Xl(),this.Nl(e,this.eu())}tu(){const e=this.Ml.props[$n];return ce(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Al=null,this.ql=void 0,clearTimeout(this.nu),this.nu=void 0,this.Jl(null,null,null)}setBootstrapSessionId(e,t=!1){const r=((n,i=new Date().getTime())=>{try{const s=(o=>{const a=o.replace(/-/g,"");if(a.length!==32)throw new Error("Not a valid UUID");if(a[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(a.substring(0,12),16)})(n);return s>i+6e4?void Rn.error("Bootstrap sessionID cannot be in the future"):s}catch(s){Rn.error("Invalid sessionID in bootstrap",s);return}})(e);return!O(r)&&(t?this.ql={sessionId:e,sessionStartTimestamp:r}:this.Jl(e,new Date().getTime(),r),!0)}destroy(){this.Ll=!0,this.Yl(),clearTimeout(this.nu),this.nu=void 0,this.Dl&&A&&(A.removeEventListener(bo,this.Dl,{capture:!1}),this.Dl=void 0),this.Ol=[]}Vl(){this.Dl=()=>{this.Yl(),this.Wl()&&xe.Lt(this.Ul)},Ie(A,bo,this.Dl,{capture:!1})}checkAndGetSessionAndWindowId(e=!1,t=null,r=!1){if(this.Rr.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');const n=t||new Date().getTime(),i=this.Xt;if(r)this.Fl=n;else if(He(this.Fl)||this.Fl>n||n-this.Fl>=1e3){var s,o;(s=(o=this.Ml).syncCookieProperties)===null||s===void 0||s.call(o),this.Fl=n}let[,a,c]=this.tu();const l=!O(i)&&a!==i,u=this.eu();let h=this.Zl();const d=this.ql,p=!!d&&(d.sessionStartTimestamp>n+6e4||n-d.sessionStartTimestamp>fh),f=d?p:tr(c)&&Math.abs(n-c)>fh;let v=!1,m=l,_=!a||!!d;const w=a;let S=!_&&!e&&this.Nl(n,u);if(S&&(S=this.iu(n),S||Rn.info("cross-tab refresh kept the session alive",{sessionId:a}),[,a,c]=this.tu(),S||(_=!a||!!d)),_||S||f){m=!1;const M=d&&!p;a=M?d.sessionId:this.jl(),h=this.Bl(),Rn.info("new session ID assigned",{sessionId:a,windowId:h,bootstrapped:!!M,changeReason:{noSessionId:_,activityTimeout:S,sessionPastMaximumLength:f}}),c=M?d.sessionStartTimestamp:n,this.ql=void 0,v=!0}else h||(h=this.Bl(),v=!0),m=m||a!==w,m&&(Rn.info("adopted cross-tab session id",{sessionId:a,windowId:h}),v=!0);const T=tr(u)&&e&&!f?u:n,I=tr(c)?c:new Date().getTime();this.Gl(h),this.Jl(a,T,I),e||this.Hl();const C={noSessionId:_,activityTimeout:S,sessionPastMaximumLength:f,crossTabAdoption:m};return v&&this.Ol.forEach(M=>M(a,h,C)),{sessionId:a,windowId:h,sessionStartTimestamp:I,changeReason:v?C:void 0,lastActivityTimestamp:u}}Hl(){this.Ll||(clearTimeout(this.nu),this.nu=setTimeout(()=>{if(!this.Ll)if(this.iu(new Date().getTime())){const e=this.Xt;this.resetSessionId(),this.Rl.emit("forcedIdleReset",{idleSessionId:e})}else this.Hl()},1.1*this.sessionTimeoutMs))}},Eg=function(e,t){if(!e)return!1;const r=e.userAgent;if(r&&_d(r,t))return!0;try{const n=e?.userAgentData;if(n?.brands&&n.brands.some(i=>_d(i?.brand,t)))return!0}catch{}return!!e.webdriver};function kg(){return(kg=Ue(function*(){const e=nt?.userAgentData;if(e?.getHighEntropyValues)try{const t=yield e.getHighEntropyValues(["model"]),r=t?.model;return ye(r)&&r.length>0?r:void 0}catch(t){j.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",t);return}})).apply(this,arguments)}function bS(e,t){let r=`$survey_${t}/${e.id}`;return e.current_iteration&&e.current_iteration>0&&(r=`$survey_${t}/${e.id}/${e.current_iteration}`),r}function Rg(e){var t;return!!(!((t=e.conditions)===null||t===void 0||(t=t.events)===null||t===void 0||(t=t.values)===null||t===void 0)&&t.length)}var Ao=(e,t)=>{if(!(r=>{try{new RegExp(r)}catch{return!1}return!0})(t))return!1;try{return new RegExp(t).test(e)}catch{return!1}},Ts=e=>e.toLowerCase(),Ag={exact:(e,t)=>t.some(r=>e.some(n=>r===n)),is_not:(e,t)=>t.every(r=>e.every(n=>r!==n)),regex:(e,t)=>t.some(r=>e.some(n=>Ao(r,n))),not_regex:(e,t)=>t.every(r=>e.every(n=>!Ao(r,n))),icontains:(e,t)=>t.map(Ts).some(r=>e.map(Ts).some(n=>r.includes(n))),not_icontains:(e,t)=>t.map(Ts).every(r=>e.map(Ts).every(n=>!r.includes(n))),gt:(e,t)=>t.some(r=>{const n=parseFloat(r);return!isNaN(n)&&e.some(i=>n>parseFloat(i))}),lt:(e,t)=>t.some(r=>{const n=parseFloat(r);return!isNaN(n)&&e.some(i=>n<parseFloat(i))})};function Ig(e,t){return!e||Object.entries(e).every(([r,n])=>{const i=t?.[r];if(i==null)return!1;const s=Ag[n.operator];return!!s&&s(n.values.map(String),[String(i)])})}function sc(e,t,r){return On({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:r})}var al="custom",gh="i.posthog.com",wS=/^\/static\//,SS=["/s/","/e/","/i/"],ES=class{constructor(e){this.su={},this.instance=e}get apiHost(){const e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){const e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e;let t=(e=this.instance.config.ui_host)===null||e===void 0?void 0:e.replace(/\/$/,"");return t||(t=this.apiHost.replace(`.${gh}`,".posthog.com")),t==="https://app.posthog.com"?"https://us.posthog.com":t}get region(){return this.su[this.apiHost]||(this.su[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":al),this.su[this.apiHost]}ru(e){if(!wS.test(e))return;const t=this.instance.config.asset_host;return typeof t=="string"&&t.trim().replace(/\/$/,"")||void 0}ou(e){const t=Lr(e);return t?t.protocol+"//"+t.host+t.pathname:void 0}au(e,t,r){if(e==="ui")return r;let n=r;const i=this.instance.config.rewriteRequestPath;if(i){var s;const o=((s=Lr(r))===null||s===void 0?void 0:s.href)||r;n=i(new URL(o)).toString()}if(i&&e==="api"&&SS.some(o=>t.indexOf(o)===0)){const o=this.ou(n);if(o){const a=this.apiHost;let c=this.lu;c?.apiHost===a&&c.rewriteRequestPath===i||(c={apiHost:a,rewriteRequestPath:i,urls:new Set},this.lu=c),c.urls.add(o)}}return n}isIngestionEndpoint(e){const t=this.lu,r=this.ou(e);return t?.apiHost===this.apiHost&&t.rewriteRequestPath===this.instance.config.rewriteRequestPath&&!!r&&t.urls.has(r)}endpointFor(e,t=""){if(t&&(t=t[0]==="/"?t:`/${t}`),e==="ui")return this.au(e,t,this.uiHost+t);if(e==="flags")return this.au(e,t,this.flagsApiHost+t);if(e==="assets"){const n=this.ru(t);if(n)return this.au(e,t,`${n}${t}`)}if(this.region===al)return this.au(e,t,this.apiHost+t);const r=gh+t;switch(e){case"assets":return this.au(e,t,`https://${this.region}-assets.${r}`);case"api":return this.au(e,t,`https://${this.region}.${r}`)}}},Te=Be("[Surveys]"),Tg=e=>{try{const t=(r=>((n,i)=>`seenSurvey_${(function(s){return s.current_iteration&&s.current_iteration>0?`${s.id}_${s.current_iteration}`:s.id})(i)}`)(0,r))(e);if(localStorage.getItem(t))return;localStorage.setItem(t,"true")}catch(t){Te.error("Failed to persist survey seen state",t)}},kS=[Qa.Popover,Qa.Widget,Qa.API],RS={ignoreConditions:!1,ignoreDelay:!1,displayType:rl.Popover},AS=Be("[PostHog ExternalIntegrations]"),IS={intercom:"intercom-integration",crispChat:"crisp-chat-integration"},TS=class{constructor(e){this._instance=e}zo(e,t){var r,n;(r=te.__PosthogExtensions__)===null||r===void 0||(n=r.loadExternalDependency)===null||n===void 0||n.call(r,this._instance,e,i=>{if(i)return AS.error("failed to load script",i);t()})}startIfEnabledOrStop(){var e;for(const[i,s]of Object.entries((e=this._instance.config.integrations)!==null&&e!==void 0?e:{})){var t,r,n;s&&!((t=te.__PosthogExtensions__)!==null&&t!==void 0&&(t=t.integrations)!==null&&t!==void 0&&t[i])&&this.zo(IS[i],()=>{var o;(o=te.__PosthogExtensions__)===null||o===void 0||(o=o.integrations)===null||o===void 0||(o=o[i])===null||o===void 0||o.start(this._instance)}),!s&&(r=te.__PosthogExtensions__)!==null&&r!==void 0&&(r=r.integrations)!==null&&r!==void 0&&r[i]&&((n=te.__PosthogExtensions__)===null||n===void 0||(n=n.integrations)===null||n===void 0||(n=n[i])===null||n===void 0||n.stop())}}},$S=class{constructor(e,t){this.$=e,this.wo=t,this.uu=new Map,this.Io=!1}add(e){var t=this;return Ue(function*(){if(t.Io)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(t.uu.has(e.name))throw new Error(`Browser extension "${e.name}" is already registered`);t.uu.set(e.name,e);try{const r=e.setup(t.wo);r&&(yield r)}catch(r){const n=t.uu.get(e.name)===e;n&&t.uu.delete(e.name),t.$.error(`Failed to set up browser extension "${e.name}"`,r),n&&t.hu(e)}})()}getExtension(e){return this.uu.get(e)}dispose(){if(this.Io)return;this.Io=!0;const e=Array.from(this.uu.values()).reverse();this.uu.clear();for(const t of e)this.hu(t)}hu(e){try{var t;const r=(t=e.dispose)===null||t===void 0?void 0:t.call(e);r&&rt(r.then)&&r.then(void 0,n=>{this.$.error(`Failed to dispose browser extension "${e.name}"`,n)})}catch(r){this.$.error(`Failed to dispose browser extension "${e.name}"`,r)}}},CS=class{constructor(e){this._instance=e}initialize(){}get(e){const t=this._instance.persistence;if(typeof e=="string")return t?.get_property(e);const r={};for(const n of e){const i=t?.get_property(n);O(i)||(r[n]=i)}return r}set(e,t){var r;(r=this._instance.persistence)===null||r===void 0||r.register(typeof e=="string"?{[e]:t}:e)}remove(e){var t;(t=this._instance.persistence)===null||t===void 0||t.unregister(e)}},mh="extensionsRemoteConfig",PS=class{constructor(e){this.instance=e,this.Io=!1,this.$=j,this.cu=e.du,this.kv=new CS(e),this.onEvent=t=>Is(this.instance.on("eventCaptured",r=>{try{t({event:r.event,properties:r.properties})}catch(n){this.$.error("Browser extension event listener failed",n)}})),this.onRemoteConfig=t=>{if(this.Io)return Is(()=>{});const r=i=>{try{t(i)}catch(s){this.$.error("Browser extension remote config listener failed",s)}},n=this.instance.vu.on(mh,r);return this.cu&&r(this.cu),Is(n)},this.fu=new $S(j.createLogger("[BrowserExtensions]"),this)}get logger(){return this.$}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property("$device_id"))!==null&&e!==void 0?e:this.distinctId}get deviceId(){const e=this.instance.get_property(eu);return typeof e=="string"?e:void 0}get library(){return{name:et.LIB_NAME,version:et.LIB_VERSION}}get initialPersonProperties(){var e,t;return(e=(t=this.instance.persistence)===null||t===void 0?void 0:t.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,t,r,n;const i=(e=this.instance.sessionManager)===null||e===void 0?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(t=i?.sessionId)!==null&&t!==void 0?t:"",windowId:(r=i?.windowId)!==null&&r!==void 0?r:"",sessionStartTimestamp:(n=i?.sessionStartTimestamp)!==null&&n!==void 0?n:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get canCapture(){return this.instance.is_capturing()}get projectToken(){return this.instance.config.token}add(e){return this.fu.add(e)}getExtension(e){return this.fu.getExtension(e)}capture(e,t,r){r?this.instance.capture(e,t,{timestamp:r.timestamp,uuid:r.uuid,$set:r.set,$set_once:r.setOnce}):this.instance.capture(e,t)}registerDynamicEventProperties(e){return Is(this.instance.pu(e))}handleRemoteConfig(e){this.Io||(this.cu=e,this.instance.vu.emit(mh,e))}sendRequest(e){var t=this;return Ue(function*(r,n={}){var i;const s=t.instance.requestRouter.endpointFor((i=n.target)!==null&&i!==void 0?i:"api",r),o={method:n.method,url:n.query?ds(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,compressionFallback:n.target==="flags"&&n.compression==="best-available"?xc.Base64:void 0,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(t.instance._send_request(o),{statusCode:202}):new Promise(a=>{o.callback=a,t.instance._send_request(o)})}).apply(this,arguments)}dispose(){this.Io||(this.Io=!0,this.fu.dispose())}},Hi={},oc=0,Vi=()=>{},_h='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',wi="Surveys module not available",yh="sanitize_properties is deprecated. Use before_send instead",$g="Invalid value for property_denylist config: ",OS=/^[A-Za-z0-9_-]{1,400}$/,bh=/^fb\.[0-9]+\.[0-9]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?$/,wh=/^fb\.[0-9]+\.[0-9]+\.[0-9]+$/,xS=["token","distinct_id",Cv],Ti="posthog",MS=e=>{const t={};return e&&e!=="unset"&&("2025-11-30">e||(t.strictMinimumDuration=!0),"2026-05-30">e||(t.canvasCapture={resolutionScale:.6}),"2026-06-25">e||(t.streamNetworkBody=!0),"2026-08-30">e||(t.captureJsonLd=!0)),t},ac=e=>{var t;return b({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Ow(N?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Vi,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:e??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:je&&ye(je?.search)&&je.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,reuseAnonymousId:!1,disable_external_dependency_loading:!1,strict_script_versioning:"fallback",enable_recording_console_log:void 0,secure_cookie:(A==null||(t=A.location)===null||t===void 0?void 0:t.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,feature_flag_request_max_retries:1,surveys_request_timeout_ms:1e4,on_request_error(r){j.error("Bad HTTP status: "+r.statusCode+" "+r.text)},get_device_id:r=>r,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:Lv,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:3e3},error_tracking:{},_onCapture:Vi},(r=>({rageclick:r&&r>="2026-05-30"?{content_ignorelist:Fw,ignore_text_selection:!0}:!r||"2025-11-30">r||{content_ignorelist:!0},capture_pageview:!r||"2025-05-24">r||"history_change",session_recording:MS(r),external_scripts_inject_target:r&&r>="2026-01-30"?"head":"body",internal_or_test_user_hostname:r&&r>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:r&&r>="2026-05-30"?250:0,split_storage:!(!r||"2026-05-30">r),detect_google_search_app:!(!r||"2026-05-30">r),disable_capture_url_hashes:!(!r||"2026-06-25">r),cookieWinsOnConflict:!(!r||r==="unset"||"2026-08-29">r)}))(e))},LS=[["process_person","person_profiles"],["xhr_headers","request_headers"],["cookie_name","persistence_name"],["disable_cookie","disable_persistence"],["__preview_disable_beacon","disable_beacon"],["store_google","save_campaign_params"],["verbose","debug"],["__preview_cookie_wins_on_conflict","cookieWinsOnConflict"]],Sh=e=>{const t={};for(const[i,s]of LS)O(e[i])||(t[s]=e[i]);const r=Le({},t,e),n=e.__preview_external_dependency_versioned_paths;return O(n)||(O(e.strict_script_versioning)&&(r.strict_script_versioning=!!n),ye(n)&&O(e.asset_host)&&(r.asset_host=n)),ce(e.property_blacklist)&&(O(e.property_denylist)?r.property_denylist=e.property_blacklist:ce(e.property_denylist)?r.property_denylist=[...e.property_blacklist,...e.property_denylist]:j.error($g+e.property_denylist)),r},DS=class{constructor(){this.__forceAllowLocalhost=!1}get gu(){return this.__forceAllowLocalhost}set gu(e){j.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},Bi=class vr{mu(t){if(!t)return;const r=this.uu.indexOf(t);r!==-1&&this.uu.splice(r,1)}yu(t,r){var n;return this.mu(t),this.uu.push(r),(n=r.initialize)===null||n===void 0||n.call(r),r}bu(){return this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isRejected()}_u(){if(this.wu||this.config.reuseAnonymousId||this.config.segment||this.bu())return;const t=this.config.persistence==="memory"||this.config.persistence==="sessionStorage";if(!t&&!this.config.disable_persistence||this.ku)return;let r,n,i;t?(r=`persistence is set to '${this.config.persistence}'`,n=this.config.persistence==="memory"?"on every page load":"for every new browser tab or window",i="Either set persistence to 'localStorage+cookie', keep this persistence and pass a stable ID through bootstrap.distinctID, or enable reuseAnonymousId."):(r="persistence is disabled (disable_persistence is true)",n="on every page load",i="Either set disable_persistence to false, keep persistence disabled and pass a stable ID through bootstrap.distinctID, or enable reuseAnonymousId."),this.wu=!0,console.warn("[PostHog.js]",`${r} but no bootstrap.distinctID was provided. PostHog will mint a new distinct ID ${n}, so calling identify() merges a new ID onto the person each time. A person can then pass the distinct-ID limit and its events stop appearing on person pages and the session tab. ${i}`)}Su(){if(this.bu()||this.get_distinct_id()!=="$posthog_cookieless")return;const t=this.persistence;if(!t)return;this.xu()||t.load(!0);const r=this.get_distinct_id();if(!r||r==="$posthog_cookieless"){const n=this.config.get_device_id(Nt());this.register({distinct_id:n,$device_id:n}),t.set_property(vt,ar)}this.Cu()}get decideEndpointWasHit(){var t,r;return(t=(r=this.featureFlags)===null||r===void 0?void 0:r.hasLoadedFlags)!==null&&t!==void 0&&t}get flagsEndpointWasHit(){var t,r;return(t=(r=this.featureFlags)===null||r===void 0?void 0:r.hasLoadedFlags)!==null&&t!==void 0&&t}constructor(){var t;this.$u=!1,this.Tu=!1,this.webPerformance=new DS,this.Iu=!1,this.version=et.LIB_VERSION,this.Mu=new Set,this.Eu="",this.vu=new Ro,this.uu=[],this.Pu=[],this.ku=!1,this.wu=!1,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=ac(),this.SentryIntegration=Zw,this.sentryIntegration=n=>(function(i,s){const o=Jv(i,s);return{name:Zv,processEvent:a=>o(a)}})(this,n),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Ru=!1,this.Au=null,this.Fu=null,this.Ou=null,this.scrollManager=new _S(this),this.pageViewManager=new nh(this),this.rateLimiter=new iS(this),this.requestRouter=new ES(this),this.consent=new Uw(this),this.externalIntegrations=new TS(this);const r=(t=vr.__defaultExtensionClasses)!==null&&t!==void 0?t:{};this.featureFlags=r.featureFlags&&new r.featureFlags(this),this.toolbar=r.toolbar&&new r.toolbar(this),this.surveys=r.surveys&&new r.surveys(this),this.conversations=r.conversations&&new r.conversations(this),this.logs=r.logs&&new r.logs(this),this.metrics=r.metrics&&new r.metrics(this),this.experiments=r.experiments&&new r.experiments(this),this.exceptions=r.exceptions&&new r.exceptions(this),this.people={set:(n,i,s)=>{const o=ye(n)?{[n]:i}:n;this.setPersonProperties(o),s?.({})},set_once:(n,i,s)=>{const o=ye(n)?{[n]:i}:n;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",n=>j.info(`send "${n?.event}"`,n))}init(t,r,n){if(n&&n!==Ti){var i;const s=(i=Hi[n])!==null&&i!==void 0?i:new vr;return s._init(t,r,n),Hi[n]=s,Hi[Ti][n]=s,s}return this._init(t,r,n)}_init(t,r={},n){var i,s,o;const a=ye(t)?t.trim():"";if(!a)return j.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;var c;if(this.__loaded)return a!==((c=this.config)===null||c===void 0?void 0:c.token)?console.warn("[PostHog.js]",`You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('${a}', { ... }, 'project2')`):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=ac(r.defaults),r.debug=this.Du(r.debug),this.Lu=r,this.Nu=[],r.person_profiles?this.Fu=r.person_profiles:r.process_person&&(this.Fu=r.process_person);const l=ac(r.defaults),u=Sh(r),h=Le({},l,u,{name:n,token:a});be(l.rageclick)&&be(u.rageclick)&&(h.rageclick=Le({},l.rageclick,u.rageclick)),be(l.session_recording)&&be(u.session_recording)&&(h.session_recording=Le({},l.session_recording,u.session_recording)),this.set_config(h),this.config.on_xhr_error&&j.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=r.disable_compression?void 0:Et.GZipJS;const d=this.xu();if(this.persistence=new Xa(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Xa(b(b({},this.config),{},{persistence:"sessionStorage"}),d,!1),this.Eu="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&xe.Et()){const _=xe.Dt(this.Eu);ce(_)&&_.forEach(w=>{ye(w)&&this.Mu.add(w)})}else xe.Lt(this.Eu);const p=b({},this.persistence.props),f=b({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.qu=new vS((_,w)=>this.ju(_,w),this.config.request_queue_config),this.Bu=new mS(this),this.__request_queue=[];const v=this.bu();v||(this.sessionManager=new vh(this),this.sessionPropsManager=new ph(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId((_,w,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.crossTabAdoption)&&this.Hu()})),this.zu(),this.config.__preview_deferred_init_extensions?(j.info("Deferring extension initialization to improve startup performance"),setTimeout(()=>{this.Uu(v)},0)):(j.info("Initializing extensions synchronously"),this.Uu(v)),et.DEBUG=et.DEBUG||this.config.debug,et.DEBUG&&j.info("Starting in debug mode",{this:this,config:r,thisC:b({},this.config),p,s:f}),this.config.identity_distinct_id&&!((i=r.bootstrap)!==null&&i!==void 0&&i.distinctID)&&(r.bootstrap=b(b({},r.bootstrap),{},{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0}));const m=(s=r.bootstrap)===null||s===void 0?void 0:s.distinctID;if(this.ku=!!m&&!Mi(m),(o=r.bootstrap)===null||o===void 0?void 0:o.distinctID){const _=r.bootstrap.distinctID,w=this.get_distinct_id(),S=this.persistence.get_property(vt);if(r.bootstrap.isIdentifiedID&&w!=null&&w!==_&&S==="anonymous")this.identify(_);else if(r.bootstrap.isIdentifiedID&&w!=null&&w!==_&&S==="identified")j.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{const T=this.config.get_device_id(Nt()),I=r.bootstrap.isIdentifiedID?T:_;this.persistence.set_property(vt,r.bootstrap.isIdentifiedID?Gs:ar),this.register({distinct_id:_,$device_id:I})}}if(v)this.register_once({distinct_id:Va,$device_id:null},"");else if(!this.get_distinct_id()){const _=this.config.get_device_id(Nt());this.register_once({distinct_id:_,$device_id:_},""),this.persistence.set_property(vt,ar)}return Ie(A,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),Ie(A,"pageshow",()=>{var _;this.$u=!1,this.Tu||(_=this.Bu)===null||_===void 0||_.resume()}),r.segment?rh(this,()=>this.Wu()):this.Wu(),rt(this.config._onCapture)&&this.config._onCapture!==Vi&&(j.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",_=>this.config._onCapture(_.event,_))),this.config.ip&&j.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return kg.apply(this,arguments)})().then(_=>{_&&this.register({[Ha]:_})}).catch(Vi),this}Vu(t){const r=t;return ye(r.name)&&rt(r.setup)}Gu(t,r){this.Vu(t)?r.push(()=>{this.Zu().add(t).catch(()=>{var n;return(n=t.dispose)===null||n===void 0?void 0:n.call(t)}).catch(n=>{j.error(`Failed to dispose browser extension "${t.name}"`,n)})}):this.uu.push(t)}zu(){var t,r,n;const i=(t=(r=this.config.__extensionClasses)===null||r===void 0?void 0:r.featureFlags)!==null&&t!==void 0?t:(n=vr.__defaultExtensionClasses)===null||n===void 0?void 0:n.featureFlags;var s,o,a;i&&(this.featureFlags&&this.featureFlags instanceof i||((s=this.Qu)===null||s===void 0||s.call(this),this.Qu=void 0,this.featureFlags=new i(this)),rt(this.featureFlags.onReloading)&&rt(this.featureFlags.setup)?this.Qu||(this.Qu=this.featureFlags.onReloading(()=>{this.vu.emit("featureFlagsReloading",!0)}),this.Zu().add(this.featureFlags)):(o=(a=this.featureFlags).initialize)===null||o===void 0||o.call(a))}Uu(t){const r=performance.now(),n=b(b({},vr.__defaultExtensionClasses),this.config.__extensionClasses),i=[];var s,o,a,c,l,u,h;n.exceptions&&this.uu.push(this.exceptions=(s=this.exceptions)!==null&&s!==void 0?s:new n.exceptions(this)),n.historyAutocapture&&this.uu.push(this.historyAutocapture=new n.historyAutocapture(this)),n.tracingHeaders&&this.uu.push(this.tracingHeaders=new n.tracingHeaders(this)),n.siteApps&&this.uu.push(this.siteApps=new n.siteApps(this)),n.sessionRecording&&!t&&this.uu.push(this.sessionRecording=new n.sessionRecording(this)),this.config.disable_scroll_properties||i.push(()=>{this.scrollManager.startMeasuringScrollPosition()}),n.autocapture&&this.Gu(this.autocapture=new n.autocapture(this),i),n.surveys&&this.Gu(this.surveys=(o=this.surveys)!==null&&o!==void 0?o:new n.surveys(this),i),n.logs&&this.Gu(this.logs=(a=this.logs)!==null&&a!==void 0?a:new n.logs(this),i),n.metrics&&this.uu.push(this.metrics=(c=this.metrics)!==null&&c!==void 0?c:new n.metrics(this)),n.conversations&&this.uu.push(this.conversations=(l=this.conversations)!==null&&l!==void 0?l:new n.conversations(this)),n.productTours&&this.uu.push(this.productTours=new n.productTours(this)),n.heatmaps&&this.uu.push(this.heatmaps=new n.heatmaps(this)),n.webVitalsAutocapture&&this.uu.push(this.webVitalsAutocapture=new n.webVitalsAutocapture(this)),n.exceptionObserver&&this.uu.push(this.exceptionObserver=new n.exceptionObserver(this)),n.deadClicksAutocapture&&this.uu.push(this.deadClicksAutocapture=new n.deadClicksAutocapture(this,Ww)),n.toolbar&&this.uu.push(this.toolbar=(u=this.toolbar)!==null&&u!==void 0?u:new n.toolbar(this)),n.experiments&&this.uu.push(this.experiments=(h=this.experiments)!==null&&h!==void 0?h:new n.experiments(this)),this.uu.forEach(d=>{d.initialize&&i.push(()=>{var p;(p=d.initialize)===null||p===void 0||p.call(d)})}),i.push(()=>{if(this.Ju){const d=this.Ju;this.Ju=void 0,this.uu.forEach(p=>{var f;return(f=p.onRemoteConfig)===null||f===void 0?void 0:f.call(p,d)})}}),this.Ku(i,r)}Ku(t,r){for(;t.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-r>=30&&t.length>0)return void setTimeout(()=>{this.Ku(t,r)},0);const i=t.shift();if(i)try{i()}catch(s){j.error("Error initializing extension:",s)}}const n=Math.round(performance.now()-r);this.register_for_session({[Pv]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Ov]:n}),this.config.__preview_deferred_init_extensions&&j.info(`PostHog extensions initialized (${n}ms)`)}il(t){var r;if(!N||!N.body)return j.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this.il(t)},500);if(this.config.__preview_deferred_init_extensions&&(this.Ju=t),this.du=t,this.compression=void 0,t.ok){var n;const i=t.config;i.supportedCompression&&!this.config.disable_compression&&(this.compression=ue(i.supportedCompression,Et.GZipJS)?Et.GZipJS:ue(i.supportedCompression,Et.Base64)?Et.Base64:void 0),(n=i.analytics)!==null&&n!==void 0&&n.endpoint&&(this.analyticsDefaultEndpoint=i.analytics.endpoint)}this.set_config({person_profiles:this.Fu?this.Fu:Lv}),(r=this.Xu)===null||r===void 0||r.handleRemoteConfig(t),this.uu.forEach(i=>{var s;return(s=i.onRemoteConfig)===null||s===void 0?void 0:s.call(i,t)})}Wu(){try{this.config.loaded(this)}catch(t){j.critical("`loaded` function failed",t)}if(this.Yu(),this.config.internal_or_test_user_hostname&&je?.hostname){const t=je.hostname,r=this.config.internal_or_test_user_hostname;(typeof r=="string"?t===r:r.test(t))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this.bu())&&this.th()},1),this.eh=new ag(this),this.eh.load()}Yu(){var t;this.is_capturing()&&this.config.request_batching&&((t=this.qu)===null||t===void 0||t.enable())}_dom_loaded(){this.is_capturing()&&Pn(this.__request_queue,t=>this.ju(t)),this.__request_queue=[],this.Yu()}_handle_unload(){var t,r,n,i,s,o;this.$u=!0,(t=this.surveys)===null||t===void 0||(r=t.handlePageUnload)===null||r===void 0||r.call(t),(n=this.metrics)===null||n===void 0||n.flush("sendBeacon"),this.config.request_batching?(this.ih()&&this.capture(Fd),(i=this.logs)===null||i===void 0||i.flushLogs("sendBeacon"),(s=this.qu)===null||s===void 0||s.unload(),(o=this.Bu)===null||o===void 0||o.unload()):this.ih()&&this.capture(Fd,null,{transport:"sendBeacon"})}_send_request(t){Sg(this,t)}ju(t,r){this.Bu?this.Bu.retriableRequest(t,r):this._send_request(r?b(b({},t),{},{transport:r}):t)}_execute_array(t){oc++;try{let r;const n=[],i=[],s=[];Pn(t,a=>{if(a)if(r=a[0],ce(r))s.push(a);else if(rt(a))try{a.call(this)}catch(c){j.error("Error executing queued PostHog call",a,c)}else ce(a)&&r==="alias"?n.push(a):ce(a)&&r.indexOf("capture")!==-1&&rt(this[r])?s.push(a):i.push(a)});const o=function(a,c){Pn(a,function(l){try{if(ce(l[0])){let u=c;$e(l,function(h){u=u[h[0]].apply(u,h.slice(1))})}else c[l[0]].apply(c,l.slice(1))}catch(u){j.error("Error executing queued PostHog call",l,u)}})};o(n,this),o(i,this),o(s,this)}finally{oc--}}push(t){if(oc>0&&ce(t)&&ye(t[0])){const r=vr.prototype[t[0]];rt(r)&&r.apply(this,t.slice(1));return}this._execute_array([t])}get nh(){return{property:zd,persistenceKey:Hn,cookieName:"_fbc",pattern:bh,register:(t,r)=>{var n;return(n=this.persistence)===null||n===void 0?void 0:n.register({[Hn]:{value:t,delivered:r}})},unregister:()=>{var t;return(t=this.persistence)===null||t===void 0?void 0:t.unregister(Hn)}}}get sh(){return{property:Ud,persistenceKey:Di,cookieName:"_fbp",pattern:wh,register:(t,r)=>{var n;return(n=this.persistence)===null||n===void 0?void 0:n.register({[Di]:{value:t,delivered:r}})},unregister:()=>{var t;return(t=this.persistence)===null||t===void 0?void 0:t.unregister(Di)}}}rh(t){var r;const n=(r=this.persistence)===null||r===void 0?void 0:r.get_property(t.persistenceKey);return ye(n)&&t.pattern.test(n)?{value:n,delivered:!1}:be(n)&&ye(n.value)&&t.pattern.test(n.value)?{value:n.value,delivered:n.delivered===!0}:void 0}oh(t,r,n){return r===n?.value?{value:r,pending:!n.delivered}:(t.register(r,!1),{value:r,pending:!0})}ah(t){if(!this.config.save_campaign_params||this.bu())return;const r=Ui(t.cookieName);return ye(r)&&t.pattern.test(r)?r:void 0}uh(t,r,n,i){if(!this.persistence)return;const s=this.nh;this.persistence.refreshKey(s.persistenceKey);const o=this.rh(s);if(i)return void s.unregister();if(n)return ye(r)&&bh.test(r)?this.oh(s,r,o):void s.unregister();const a=ye(t)&&OS.test(t)?t:void 0,c=this.ah(s);return c&&((l,u,h)=>{const d=l.split(".");if(u)return d[3]===u;if(!h)return!0;const p=h.value.split(".");return d[3]===p[3]||Number(d[2])>Number(p[2])})(c,a,o)?this.oh(s,c,o):a?o?.value.split(".")[3]===a?{value:o.value,pending:!o.delivered}:this.oh(s,`fb.1.${Date.now()}.${a}`,o):o?{value:o.value,pending:!o.delivered}:void 0}hh(t,r,n){if(!this.persistence)return;const i=this.sh;this.persistence.refreshKey(i.persistenceKey);const s=this.rh(i);if(n)return void i.unregister();if(r)return ye(t)&&wh.test(t)?this.oh(i,t,s):void i.unregister();const o=this.ah(i);return o?this.oh(i,o,s):s?{value:s.value,pending:!s.delivered}:void 0}dh(t,r){if(!this.persistence)return;this.persistence.refreshKey(t.persistenceKey);const n=this.rh(t);n?.value!==r||n.delivered||t.register(r,!0)}capture(t,r,n){var i,s;if(!(this.__loaded&&this.persistence&&this.sessionPersistence&&this.qu))return void j.uninitializedWarning("posthog.capture");if(!this.is_capturing())return;if(O(t)||!ye(t))return void j.error("No event name provided to posthog.capture");this.Su();const o=!this.config.opt_out_useragent_filter&&this._is_bot();if(o&&!this.config.__preview_capture_bot_pageviews)return;const a=n?.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(a?.isRateLimited)return void j.critical("This capture call is ignored due to client rate limiting.");let c;r!=null&&r.$current_url&&!ye(r?.$current_url)&&(j.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),r==null||delete r.$current_url),t!=="$exception"||n!=null&&n.fh||j.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&(c=this.sessionPersistence.update_campaign_params()),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();const l=new Date,u=n?.timestamp||l,h=Sd(n?.uuid,Nt);let d={uuid:h,event:t,properties:this.calculateEventProperties(t,r||{},u,h)};t==="$pageview"&&this.config.__preview_capture_bot_pageviews&&o&&(d.event="$bot_pageview",d.properties.$browser_type="bot"),a&&(d.properties.$lib_rate_limit_remaining_tokens=a.remainingTokens);const p=t==="$feature_flag_called"&&d.properties.$feature_flag_has_experiment===!1&&this.get_property("$minimal_flag_called_events")===!0;n!=null&&n.$set&&!p&&(d.$set=n?.$set);const f=be(r?.$set)?r.$set:void 0,v=ce(r?.$unset)?r.$unset:[],m=n?.$unset||[],_=H=>{var oe;const $=!!n?.$set&&H in n.$set;return{hasProvided:$||!!f&&H in f,provided:$?n==null||(oe=n.$set)===null||oe===void 0?void 0:oe[H]:f?.[H],unset:v.indexOf(H)!==-1||m.indexOf(H)!==-1}},w=_(zd),S=_(Ud),T=[{channel:this.nh,hasProvided:w.hasProvided,update:this.uh(c?.fbclid,w.provided,w.hasProvided,w.unset)},{channel:this.sh,hasProvided:S.hasProvided,update:this.hh(S.provided,S.hasProvided,S.unset)}];for(const{channel:H,hasProvided:oe,update:$}of T)$&&d.properties.$process_person_profile===!0&&$.pending&&!oe&&!p&&(d.$set=b({[H.property]:$.value},d.$set));const I=n?.$unset;I&&(d.$unset=I);const C=p?void 0:this.ph(n?.$set_once,t!==qd,t===Dv);if(C&&(d.$set_once=C),n!=null&&n._noTruncate||(M=this.config.properties_string_max_length,d=(function(H,oe){const $=new Set;return(function Q(y,V){if(y!==Object(y))return oe?oe(y):y;if($.has(y))return;let K;if($.add(y),ce(y))K=[],Pn(y,le=>{K.push(Q(le))});else{const le={};$e(ci(y)?Nv(y):y,(de,Ce)=>{$.has(de)||(le[Ce]=Q(de,Ce))}),K=le}return K})(H)})(d,H=>ye(H)?H.slice(0,M):H)),d.timestamp=u,O(n?.timestamp)||(d.properties.$event_time_override_provided=!0,d.properties.$event_time_override_system_time=l),p&&(d.properties=((H,oe=[])=>{const $={},Q=y=>{H[y]!==void 0&&($[y]=H[y])};return Bb.forEach(Q),oe.forEach(Q),$})(d.properties,xS)),t===cr.DISMISSED||t===cr.SENT){const H=r?.[ec.SURVEY_ID],oe=r?.[ec.SURVEY_ITERATION];Tg({id:H,current_iteration:oe}),d.$set=b(b({},d.$set),{},{[bS({id:H,current_iteration:oe},t===cr.SENT?"responded":"dismissed")]:!0})}else t===cr.SHOWN&&(d.$set=b(b({},d.$set),{},{[ec.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));var M;if(t===nS.SHOWN){const H=r?.[oh.TOUR_TYPE];H&&(d.$set=b(b({},d.$set),{},{[`${oh.TOUR_LAST_SEEN_DATE}/${H}`]:new Date().toISOString()}))}const L=b(b({},d.properties.$set),d.$set);if(_t(L)||this.setPersonPropertiesForFlags(L),!ge(this.config.before_send)){const H=this.Os(d);if(!H)return;d=H,d.uuid=Sd(d.uuid,Nt)}const q=T.filter(({channel:H,update:oe})=>{var $,Q,y;const V=($=(Q=d.$set)===null||Q===void 0?void 0:Q[H.property])!==null&&$!==void 0?$:be((y=d.properties)===null||y===void 0?void 0:y.$set)?d.properties.$set[H.property]:void 0;return oe?.pending&&V===oe.value});this.vu.emit("eventCaptured",d);const X=(i=n?._url)!==null&&i!==void 0?i:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),ee=n?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(X),k=b(b(b({method:"POST",url:X,data:d,compression:"best-available",preferSyncCompression:n?.send_instantly,timestampMode:ee?"body":"capture-body",batchKey:n?._batchKey},ee&&(!((s=d.properties)===null||s===void 0)&&s.$session_id)?{batchGroup:d.properties.$session_id+(d.properties.$window_id?`-${d.properties.$window_id}`:"")}:{}),n?.transport?{transport:n.transport}:{}),q.length?{fireCallbackOnDrop:!0,callback:H=>{if(H.statusCode>=200&&300>H.statusCode)for(const{channel:oe,update:$}of q)this.dh(oe,$.value)}}:{});if(!this.config.request_batching||n&&!n?._batchKey||n?.send_instantly||q.length){var ie;let H;!k.transport&&!k.callback&&_t((ie=this.config.request_headers)!==null&&ie!==void 0?ie:{})&&this.$u&&(H="sendBeacon"),this.ju(k,H)}else this.qu.enqueue(k);return d}_addCaptureHook(t){return this.on("eventCaptured",r=>t(r.event,r))}getExtension(t){var r;return(r=this.Xu)===null||r===void 0?void 0:r.getExtension(t)}Zu(){var t;return(t=this.Xu)!==null&&t!==void 0?t:this.Xu=new PS(this)}pu(t){this.Pu.push(t);let r=!0;return()=>{if(!r)return;r=!1;const n=this.Pu.indexOf(t);n!==-1&&this.Pu.splice(n,1)}}gh(t=!0){var r,n,i;return!!(!((r=this.persistence)===null||r===void 0)&&r.consumeCookieIdentityChange())&&(this.Ou=null,this.persistence.get_property("$user_state")==="anonymous"&&((i=this.sessionPersistence)===null||i===void 0||i.clear(),this.Mu.clear(),this.mh()),(n=this.featureFlags)===null||n===void 0||n.reset(),t&&this.reloadFeatureFlags(),!0)}calculateEventProperties(t,r,n,i,s){if(n=n||new Date,!this.persistence||!this.sessionPersistence)return r;this.persistence.syncCookieProperties(),this.gh();const o=s?void 0:this.persistence.remove_event_timer(t);let a=b({},r);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.bu()&&(a[Cv]=!0),t==="$snapshot"){const w=b(b({},this.persistence.properties()),this.sessionPersistence.properties());return a.distinct_id=w.distinct_id,(!ye(a.distinct_id)&&!We(a.distinct_id)||Mi(a.distinct_id))&&j.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}const c=(function(w,S,T,I=!1){var C,M,L,q;if(!ft)return{};const X=w?[...ei,...S||[]]:[],[ee,k]=Kf(ft),[ie,H]=(function(Re){for(let _e=0;wd.length>_e;_e++){const[ve,Je,Xe]=wd[_e],Pe=Re.match(ve);if(Pe){const z=Xe&&Re.match(Xe)||Pe;return[Je,z?.[1]||""]}}return["",""]})(ft),oe=(function(){const Re="u">typeof navigator?navigator:void 0;return Re?.brave?{brave:!0}:{}})(),$={};O(T)||($.detectGoogleSearchApp=T);const Q={},y=(C=navigator)===null||C===void 0||(C=C.userAgentData)===null||C===void 0?void 0:C.platform,V=(M=navigator)===null||M===void 0?void 0:M.maxTouchPoints,K=A==null||(L=A.screen)===null||L===void 0?void 0:L.width,le=A==null||(q=A.screen)===null||q===void 0?void 0:q.height,de=A?.devicePixelRatio;O(y)||(Q.userAgentDataPlatform=y),O(V)||(Q.maxTouchPoints=V),O(K)||(Q.screenWidth=K),O(le)||(Q.screenHeight=le),O(de)||(Q.devicePixelRatio=de);const Ce=Le(ou({$os:ee,$os_version:k,$browser:Jf(ft,navigator.vendor,oe,$),$webview_app:ie,$webview_app_version:H,$device:Yf(ft),$device_type:pb(ft,Q),$timezone:sg(),$timezone_offset:eS()}),{$current_url:es(I?Mr(je?.href):je?.href,X,ts),$host:je?.host,$pathname:je?.pathname,$raw_user_agent:ft.length>1e3?ft.substring(0,997)+"...":ft,$browser_version:hb(ft,navigator.vendor,oe,$),$browser_language:tg(),$browser_language_prefix:Qw(),$screen_height:A?.screen.height,$screen_width:A?.screen.width,$viewport_height:A?.innerHeight,$viewport_width:A?.innerWidth,$lib:lr.LIB_NAME,$lib_version:lr.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return lr.SDK_DIST_CHANNEL&&(Ce.$sdk_dist_channel=lr.SDK_DIST_CHANNEL),Ce})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){const{sessionId:w,windowId:S}=this.sessionManager.checkAndGetSessionAndWindowId(s,n.getTime(),!0);a.$session_id=w,a.$window_id=S}this.sessionPropsManager&&Le(a,this.sessionPropsManager.getSessionProps());try{var l;this.sessionRecording&&Le(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(l=this.Bu)===null||l===void 0?void 0:l.length}catch(w){a.$sdk_debug_error_capturing_properties=String(w)}let u;if(this.requestRouter.region===al&&(a.$lib_custom_api_host=this.config.api_host),u=t!=="$pageview"||s?t!=="$pageleave"||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(n):this.pageViewManager.doPageView(n,i),a=Le(a,u),t==="$pageview"&&N&&(a.title=N.title),!O(o)){const w=n.getTime()-o;a.$duration=parseFloat((w/1e3).toFixed(3))}ft&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");const h=this.persistence.properties(),d=this.sessionPersistence.properties(),p=a.$groups,f=h.$groups;be(p)&&!_t(p)&&(a.$groups=b(b({},be(f)?f:{}),p)),$e(["$referrer","$referring_domain"],w=>{w in h&&delete d[w]});const v={};if(this.Pu.length>0)for(const w of this.Pu.slice())try{Le(v,w())}catch(S){j.error("Failed to produce browser extension event properties",S)}a=Le({},c,h,d,b(b({},v),a)),a.$is_identified=this._isIdentified(),ce(this.config.property_denylist)?$e(this.config.property_denylist,function(w){delete a[w]}):j.error($g+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);const m=this.config.sanitize_properties;m&&(j.error(yh),a=m(a,t));const _=this.yh();return a.$process_person_profile=_,_&&!s&&this.bh("_calculate_event_properties"),a}ph(t,r=!0,n=!1){var i;if(!this.persistence||!this.yh()||this.Iu&&!n)return t;const s=this.persistence.get_initial_props(),o=(i=this.sessionPropsManager)===null||i===void 0?void 0:i.getSetOnceProps();let a=Le({},s,o||{},t||{});const c=this.config.sanitize_properties;return c&&(j.error(yh),a=c(a,"$set_once")),r&&(this.Iu=!0),_t(a)?void 0:a}register(t,r){var n;(n=this.persistence)===null||n===void 0||n.register(t,r)}register_once(t,r,n){var i;(i=this.persistence)===null||i===void 0||i.register_once(t,r,n)}register_for_session(t){var r,n;(r=this.persistence)===null||r===void 0||r.syncCookieProperties(),this.gh(),(n=this.sessionPersistence)===null||n===void 0||n.register(t),Object.keys(t).forEach(i=>this.Mu.add(i)),this.mh()}unregister(t){var r;(r=this.persistence)===null||r===void 0||r.unregister(t)}unregister_for_session(t){var r;(r=this.sessionPersistence)===null||r===void 0||r.unregister(t),this.Mu.delete(t),this.mh()}_h(t,r){this.register({[t]:r})}Hu(){this.Mu.forEach(t=>{var r;(r=this.sessionPersistence)===null||r===void 0||r.unregister(t)}),this.Mu.clear(),this.mh()}mh(){var t;if(!this.Eu)return;if(this.config.persistence==="memory"||!((t=this.sessionPersistence)===null||t===void 0)&&t.mi||!xe.Et())return void xe.Lt(this.Eu);const r=[];this.Mu.forEach(n=>r.push(n)),r.length>0?xe.At(this.Eu,r):xe.Lt(this.Eu)}getFeatureFlag(t,r){var n;return(n=this.featureFlags)===null||n===void 0?void 0:n.getFeatureFlag(t,r)}getFeatureFlagPayload(t){var r;return(r=this.featureFlags)===null||r===void 0?void 0:r.getFeatureFlagPayload(t)}getFeatureFlagResult(t,r){var n;return(n=this.featureFlags)===null||n===void 0?void 0:n.getFeatureFlagResult(t,r)}getAllFeatureFlags(){var t,r;return(t=(r=this.featureFlags)===null||r===void 0?void 0:r.getAllFeatureFlags())!==null&&t!==void 0?t:[]}isFeatureEnabled(t,r){var n,i;return(n=(i=this.featureFlags)===null||i===void 0?void 0:i.isFeatureEnabled(t,r))!==null&&n!==void 0?n:r?.defaultValue}reloadFeatureFlags(){var t;(t=this.featureFlags)===null||t===void 0||t.reloadFeatureFlags()}updateFlags(t,r,n){var i;(i=this.featureFlags)===null||i===void 0||i.updateFlags(t,r,n)}updateEarlyAccessFeatureEnrollment(t,r,n){var i;(i=this.featureFlags)===null||i===void 0||i.updateEarlyAccessFeatureEnrollment(t,r,n)}getEarlyAccessFeatures(t,r=!1,n){var i;return(i=this.featureFlags)===null||i===void 0?void 0:i.getEarlyAccessFeatures(t,r,n)}on(t,r){return this.vu.on(t,r)}onFeatureFlags(t){return this.featureFlags?this.featureFlags.onFeatureFlags(t):(t([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(t){return this.surveys?this.surveys.onSurveysLoaded(t):(t([],{isLoaded:!1,error:wi}),()=>{})}onSessionId(t){var r,n;return(r=(n=this.sessionManager)===null||n===void 0?void 0:n.onSessionId(t))!==null&&r!==void 0?r:()=>{}}getSurveys(t,r=!1){this.surveys?this.surveys.getSurveys(t,r):t([],{isLoaded:!1,error:wi})}getActiveMatchingSurveys(t,r=!1){this.surveys?this.surveys.getActiveMatchingSurveys(t,r):t([],{isLoaded:!1,error:wi})}renderSurvey(t,r){var n;(n=this.surveys)===null||n===void 0||n.renderSurvey(t,r)}displaySurvey(t,r=RS){var n;(n=this.surveys)===null||n===void 0||n.displaySurvey(t,r)}cancelPendingSurvey(t){var r;(r=this.surveys)===null||r===void 0||r.cancelPendingSurvey(t)}canRenderSurvey(t){var r,n;return(r=(n=this.surveys)===null||n===void 0?void 0:n.canRenderSurvey(t))!==null&&r!==void 0?r:{visible:!1,disabledReason:wi}}canRenderSurveyAsync(t,r=!1){var n,i;return(n=(i=this.surveys)===null||i===void 0?void 0:i.canRenderSurveyAsync(t,r))!==null&&n!==void 0?n:Promise.resolve({visible:!1,disabledReason:wi})}wh(t){return!t||Mi(t)?(j.critical("Unique user id has not been set in posthog.identify"),!1):t==="$posthog_cookieless"?(j.critical(`The string "${t}" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.`),!1):!["distinct_id","distinctid"].includes(t.toLowerCase())&&!["undefined","null"].includes(t.toLowerCase())||(j.critical(`The string "${t}" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.`),!1)}identify(t,r,n){if(!this.__loaded||!this.persistence)return j.uninitializedWarning("posthog.identify");if(We(t)&&(t=t.toString(),j.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),!this.wh(t)||!this.bh("posthog.identify"))return;this.Su();const i=this.get_distinct_id(),s=this.persistence.syncCookieProperties()&&this.get_distinct_id()!==i,o=this.gh(!1),a=this.persistence.Da();let c=!1;try{const u=this.get_distinct_id();this.register({$user_id:t}),this.get_property("$device_id")||this.register_once({$had_persisted_distinct_id:!0,$device_id:u},""),t!==u&&t!==this.get_property("__alias")&&(this.unregister(_o),this.register({distinct_id:t}));const h=(this.persistence.get_property("$user_state")||"anonymous")===ar,d=t!==u,p=!d&&h;if(d&&h){var l;const f=this.config.reuseAnonymousId?{distinct_id:t}:{distinct_id:t,$anon_distinct_id:u};this.persistence.set_property(vt,Gs),this.setPersonPropertiesForFlags({$set:r||{},$set_once:n||{}},!1),this.config.cookieWinsOnConflict&&this.persistence.La(),this.capture("$identify",f,{$set:r||{},$set_once:n||{}})&&(this.Ou=sc(t,r,n)),(l=this.featureFlags)===null||l===void 0||l.setAnonymousDistinctId(this.config.reuseAnonymousId?void 0:u)}else if(p){this.persistence.set_property(vt,Gs);const f=r||{},v=n||{};this.setPersonPropertiesForFlags({$set:f,$set_once:v},!1),this.config.cookieWinsOnConflict&&this.persistence.La(),this.capture("$set",{$set:f,$set_once:v})&&(this.Ou=sc(t,r,n))}else(r||n)&&this.setPersonProperties(r,n);d||s||o?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Rr)):p&&(r||n)&&this.reloadFeatureFlags(),c=!0}finally{a&&this.persistence.ja(c)}}setPersonProperties(t,r){if(!t&&!r||!this.bh("posthog.setPersonProperties"))return;const n=sc(this.get_distinct_id(),t,r);this.Ou!==n?(this.setPersonPropertiesForFlags({$set:t||{},$set_once:r||{}},!0),this.capture("$set",{$set:t||{},$set_once:r||{}})&&(this.Ou=n)):j.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}unsetPersonProperties(t){var r;const n=(ce(t)?t:[t]).filter(i=>ye(i)&&i.length>0);n.length!==0&&this.bh("posthog.unsetPersonProperties")&&((r=this.featureFlags)===null||r===void 0||r.unsetPersonPropertiesForFlags(n,!0),this.capture("$set",{$unset:n}),this.Ou=null)}group(t,r,n){var i;if(!t||!r)return void j.error("posthog.group requires a group type and group key");(i=this.persistence)===null||i===void 0||i.syncCookieProperties(),this.gh();const s=this.getGroups(),o=s[t]!==r;if(o&&this.resetGroupPropertiesForFlags(t),this.register({$groups:b(b({},s),{},{[t]:r})}),(o||n)&&this.yh()){const a={$group_type:t,$group_key:r};n&&(a.$group_set=n),this.capture(qd,a)}n&&this.setGroupPropertiesForFlags({[t]:n}),o&&!n&&this.reloadFeatureFlags()}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(t,r=!0){var n;(n=this.featureFlags)===null||n===void 0||n.setPersonPropertiesForFlags(t,r)}resetPersonPropertiesForFlags(t=!0){var r;(r=this.featureFlags)===null||r===void 0||r.resetPersonPropertiesForFlags(t)}setGroupPropertiesForFlags(t,r=!0){var n;this.bh("posthog.setGroupPropertiesForFlags")&&((n=this.featureFlags)===null||n===void 0||n.setGroupPropertiesForFlags(t,r))}resetGroupPropertiesForFlags(t){var r;(r=this.featureFlags)===null||r===void 0||r.resetGroupPropertiesForFlags(t)}reset(t){const r=gt(t)?t:t?.resetDeviceID,n=gt(t)||t==null?void 0:t.bootstrap;this.kh(r,!1,n)}kh(t,r=!1,n){var i,s,o,a,c,l;if(j.info("reset"),!this.__loaded)return j.uninitializedWarning("posthog.reset");const u=n?.sessionID;this.config.bootstrap=n||((i=this.Lu)===null||i===void 0?void 0:i.bootstrap)||{},(s=this.featureFlags)===null||s===void 0||(o=s.updateConfig)===null||o===void 0||o.call(s,this.config,this.nl());const h=this.get_property(eu),d=this.get_property(Ha),p=this.get_property(Ni);(a=this.sessionRecording)===null||a===void 0||a.flushBeforeIdentityReset();const f=this.is_capturing();this.consent.reset(),r||!f||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after.");const v=(c=this.persistence)===null||c===void 0||(l=c.Da)===null||l===void 0?void 0:l.call(c);let m=!1;try{var _,w,S,T,I,C,M,L,q,X,ee,k,ie;if((_=this.persistence)===null||_===void 0||_.clear(),(w=this.sessionPersistence)===null||w===void 0||w.clear(),this.Mu.clear(),this.mh(),O(p)||(X=this.persistence)===null||X===void 0||X.register({$session_recording_remote_config:p}),(S=this.surveys)===null||S===void 0||S.reset(),(T=this.featureFlags)===null||T===void 0||T.reset(),(I=this.conversations)===null||I===void 0||I.reset(),(C=this.logs)===null||C===void 0||C.reset(),(M=this.metrics)===null||M===void 0||M.reset(),(L=this.persistence)===null||L===void 0||L.set_property("$user_state","anonymous"),(q=this.sessionManager)===null||q===void 0||q.resetSessionId(),this.Ou=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:Va,$device_id:null},"");else{const $=this.config.get_device_id(Nt());this.register_once({distinct_id:$,$device_id:t?$:h},""),t||O(d)||this.register({[Ha]:d})}if(this.register({$last_posthog_reset:new Date().toISOString()},1),n&&(n.distinctID&&!this.bu()&&((ie=this.persistence)===null||ie===void 0||ie.set_property("$user_state",n.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:n.distinctID})),(ee=this.featureFlags)===null||ee===void 0||ee.initialize(),!ge(u)&&!(!((k=this.sessionManager)===null||k===void 0)&&k.setBootstrapSessionId(u,!0)))){const $=b({},n);delete $.sessionID,this.config.bootstrap=$}delete this.config.identity_distinct_id,delete this.config.identity_hash,delete this.config.identity_claims,m=!0}finally{var H,oe;v&&((H=this.persistence)===null||H===void 0||(oe=H.ja)===null||oe===void 0||oe.call(H,m))}this.reloadFeatureFlags()}shutdown(t){var r=this;return Ue(function*(){var n,i,s,o,a,c,l,u;if(r.__loaded){r.Tu=!0,r.Zu().dispose(),(n=r.sessionRecording)===null||n===void 0||n.dispose(),(i=r.logs)===null||i===void 0||i.flushLogs("sendBeacon"),(s=r.metrics)===null||s===void 0||s.flush("sendBeacon"),(o=r.metrics)===null||o===void 0||o.dispose(),(a=r.qu)===null||a===void 0||a.unload(),(c=r.Bu)===null||c===void 0||c.unload();try{var h;(h=r.featureFlags)===null||h===void 0||h.destroy()}catch(d){j.error("Error while destroying feature flags",d)}(l=r.persistence)===null||l===void 0||l.destroy(),(u=r.sessionPersistence)===null||u===void 0||u.destroy()}else j.uninitializedWarning("posthog.shutdown")})()}setIdentity(t,r){var n;delete this.config.identity_claims,this.config.identity_distinct_id=t,this.config.identity_hash=r,this.alias(t),(n=this.conversations)===null||n===void 0||n.Sh()}clearIdentity(){var t;delete this.config.identity_distinct_id,delete this.config.identity_hash,delete this.config.identity_claims,(t=this.conversations)===null||t===void 0||t.xh()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var t,r;return(t=(r=this.sessionManager)===null||r===void 0?void 0:r.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&t!==void 0?t:""}get_session_replay_url(t){if(!this.sessionManager)return"";const{sessionId:r,sessionStartTimestamp:n}=this.sessionManager.checkAndGetSessionAndWindowId(!0);let i=this.requestRouter.endpointFor("ui",`/project/${this.config.token}/replay/${r}`);if(t?.withTimestamp&&n){var s;const o=(s=t.timestampLookBack)!==null&&s!==void 0?s:10;if(!n)return i;i+=`?t=${Math.max(Math.floor((new Date().getTime()-n)/1e3)-o,0)}`}return i}alias(t,r){return t===this.get_property("$people_distinct_id")?(j.critical("Attempting to create alias for existing People user - aborting."),-2):this.bh("posthog.alias")?(O(r)&&(r=this.get_distinct_id()),t!==r?(this._h(_o,t),this.capture("$create_alias",{alias:t,distinct_id:r})):(j.warn("alias matches current distinct_id - skipping api call."),this.identify(t),-1)):void 0}set_config(t){const r=b({},this.config);if(be(t)){var n,i,s,o,a,c,l,u,h,d,p,f,v,m;Le(this.config,Sh(t));const w=this.xu();(n=this.persistence)===null||n===void 0||n.update_config(this.config,r,w),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Xa(b(b({},this.config),{},{persistence:"sessionStorage"}),w,!1);const S=this.Du(this.config.debug);var _;gt(S)&&(this.config.debug=S),gt(this.config.debug)&&(this.config.debug?(et.DEBUG=!0,ke.Et()&&ke.At("ph_debug",!0),j.info("set_config",{config:t,oldConfig:r,newConfig:b({},this.config)})):(et.DEBUG=!1,ke.Et()&&ke.Lt("ph_debug"))),(i=this.featureFlags)===null||i===void 0||(s=i.updateConfig)===null||s===void 0||s.call(i,this.config,this.nl()),(o=this.exceptionObserver)===null||o===void 0||o.onConfigChange(),(a=this.exceptions)===null||a===void 0||a.onConfigChange(),(c=this.metrics)===null||c===void 0||c.onConfigChange(),(l=this.sessionRecording)===null||l===void 0||l.startIfEnabledOrStop(),(u=this.tracingHeaders)===null||u===void 0||u.startIfEnabledOrStop(),(h=this.autocapture)===null||h===void 0||h.startIfEnabled(),(d=this.heatmaps)===null||d===void 0||d.startIfEnabled(),("capture_pageview"in t||"disable_capture_url_hashes"in t)&&((_=this.historyAutocapture)===null||_===void 0||_.startIfEnabledOrStop()),(p=this.exceptionObserver)===null||p===void 0||p.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)===null||f===void 0||f.startIfEnabledOrStop(),(v=this.surveys)===null||v===void 0||v.loadIfEnabled(),this.Cu(),(m=this.externalIntegrations)===null||m===void 0||m.startIfEnabledOrStop(),!r.segment&&this.config.segment&&this.persistence&&rh(this,Vi,!1)}}_overrideSDKInfo(t,r){et.LIB_NAME=t,et.LIB_VERSION=r}startSessionRecording(t){const r=t===!0,n={sampling:r||!!t?.sampling,linked_flag:r||!!t?.linked_flag,url_trigger:r||!!t?.url_trigger,event_trigger:r||!!t?.event_trigger};var i,s,o,a,c;Object.values(n).some(Boolean)&&((i=this.sessionManager)===null||i===void 0||i.checkAndGetSessionAndWindowId(),n.sampling&&((s=this.sessionRecording)===null||s===void 0||s.overrideSampling()),n.linked_flag&&((o=this.sessionRecording)===null||o===void 0||o.overrideLinkedFlag()),n.url_trigger&&((a=this.sessionRecording)===null||a===void 0||a.overrideTrigger("url")),n.event_trigger&&((c=this.sessionRecording)===null||c===void 0||c.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var t;return!!(!((t=this.sessionRecording)===null||t===void 0)&&t.started)}captureException(t,r){try{if(!this.exceptions)return;const n=this.exceptions.buildProperties(t,{handled:!0,syntheticException:new Error("PostHog syntheticException")});return this.exceptions.sendExceptionEvent(b(b({},n),r))}catch{return}}addExceptionStep(t,r){var n;(n=this.exceptions)===null||n===void 0||n.addExceptionStep(t,r)}captureLog(t){var r;(r=this.logs)===null||r===void 0||r.captureLog(t)}get logger(){var t,r;return(t=(r=this.logs)===null||r===void 0?void 0:r.logger)!==null&&t!==void 0?t:vr.Ch}startExceptionAutocapture(t){this.set_config({capture_exceptions:t==null||t})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(t){var r,n;return(r=(n=this.toolbar)===null||n===void 0?void 0:n.loadToolbar(t))!==null&&r!==void 0&&r}get_property(t){var r;return(r=this.persistence)===null||r===void 0?void 0:r.props[t]}getSessionProperty(t){var r;return(r=this.sessionPersistence)===null||r===void 0?void 0:r.props[t]}toString(){var t;let r=(t=this.config.name)!==null&&t!==void 0?t:Ti;return r!==Ti&&(r="posthog."+r),r}_isIdentified(){var t,r;return((t=this.persistence)===null||t===void 0?void 0:t.get_property("$user_state"))==="identified"||((r=this.sessionPersistence)===null||r===void 0?void 0:r.get_property("$user_state"))==="identified"}yh(){var t,r;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&_t(this.getGroups())&&!(!((t=this.persistence)===null||t===void 0||(t=t.props)===null||t===void 0)&&t.__alias)&&!(!((r=this.persistence)===null||r===void 0||(r=r.props)===null||r===void 0)&&r.$epp))}ih(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&!!this.config.capture_pageview}createPersonProfile(){this.yh()||this.bh("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.bh("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}bh(t){return this.config.person_profiles==="never"?(j.error(t+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this._u(),this._h(nu,!0),!0)}xu(){if(this.config.cookieless_mode==="always")return!0;const t=this.consent.isOptedOut();return this.config.disable_persistence||t&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!=="on_reject")}Cu(){var t,r;const n=this.xu();var i,s,o;return this.is_capturing()||(i=this.logs)===null||i===void 0||i.$h(),((t=this.persistence)===null||t===void 0?void 0:t.mi)!==n&&((s=this.persistence)===null||s===void 0||s.set_disabled(n)),((r=this.sessionPersistence)===null||r===void 0?void 0:r.mi)!==n&&((o=this.sessionPersistence)===null||o===void 0||o.set_disabled(n)),n&&(this.Mu.clear(),this.mh()),n}opt_in_capturing(t){var r;if(this.config.cookieless_mode!=="always"){if(this.bu()){var n,i,s,o,a,c;(n=this.sessionRecording)===null||n===void 0||n.dispose({discardBufferedEvents:!0}),this.kh(!0,!0),(i=this.sessionManager)===null||i===void 0||i.destroy(),(s=this.pageViewManager)===null||s===void 0||s.destroy(),this.sessionManager=new vh(this),this.pageViewManager=new nh(this),this.persistence&&(this.sessionPropsManager=new ph(this,this.sessionManager,this.persistence));const p=(o=(a=this.config.__extensionClasses)===null||a===void 0?void 0:a.sessionRecording)!==null&&o!==void 0?o:(c=vr.__defaultExtensionClasses)===null||c===void 0?void 0:c.sessionRecording;var l,u;p&&(this.sessionRecording=this.yu(this.sessionRecording,new p(this)),this.du&&((l=this.sessionRecording)===null||l===void 0||(u=l.onRemoteConfig)===null||u===void 0||u.call(l,this.du)))}var h,d;this.consent.optInOut(!0),this.Cu(),this.Yu(),(r=this.sessionRecording)===null||r===void 0||r.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&((h=this.surveys)===null||h===void 0||h.loadIfEnabled()),(O(t?.captureEventName)||t!=null&&t.captureEventName)&&this.capture((d=t?.captureEventName)!==null&&d!==void 0?d:"$opt_in",t?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.th()}else j.warn(_h)}opt_out_capturing(){if(this.config.cookieless_mode==="always")return void j.warn(_h);const t=this.config.cookieless_mode==="on_reject"?this.sessionRecording:void 0;var r,n;t?.dispose({discardBufferedEvents:!0}),this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.kh(!0,!0),this.consent.optInOut(!1),this.Cu(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:Va,$device_id:null}),this.mu(t),this.sessionRecording=void 0,(r=this.sessionManager)===null||r===void 0||r.destroy(),(n=this.pageViewManager)===null||n===void 0||n.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.th(),this.Yu())}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){const t=this.consent.consent;return t===1?"granted":t===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.Cu()}_is_bot(){return nt?Eg(nt,this.config.custom_blocked_useragents):void 0}th(){N&&(N.visibilityState==="visible"?this.Ru||(this.Ru=!0,this.capture(su,{title:N.title},{send_instantly:!0}),this.Au&&(N.removeEventListener(Yi,this.Au),this.Au=null)):this.Au||(this.Au=this.th.bind(this),Ie(N,Yi,this.Au)))}debug(t){t===!1?(A?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(A?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}nl(){const t=this.Lu||{};return"advanced_disable_flags"in t?!!t.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(j.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(r,n,i,s,o){const a=n in r&&!ge(r[n]),c=i in r&&!ge(r[i]);return a?r[n]:!!c&&(o&&o.warn(`Config field '${i}' is deprecated. Please use '${n}' instead. The old field will be removed in a future major version.`),r[i])})(t,"advanced_disable_flags","advanced_disable_decide",0,j)}Os(t){var r;if(ge(this.config.before_send))return t;const n=Object.keys((r=t.properties)!==null&&r!==void 0?r:{}).filter(tb),i=ce(this.config.before_send)?this.config.before_send:[this.config.before_send];let s=t;for(const o of i)try{if(s=o(s),ge(s)){const a=`Event '${t.event}' was rejected in beforeSend function`;return eb(t.event)?j.warn(`${a}. This can cause unexpected behavior.`):j.info(a),null}s.properties&&!_t(s.properties)||j.warn(`Event '${t.event}' has no properties after beforeSend function, this is likely an error.`)}catch(a){return j.error(`Error in beforeSend function for event '${t.event}':`,a),null}for(const o of n)if(s.properties&&ge(s.properties[o]))return j.warn(`Event '${t.event}' had its '${o}' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped.`),null;return s}getPageViewId(){var t;return(t=this.pageViewManager.Vo)===null||t===void 0?void 0:t.pageViewId}captureTraceFeedback(t,r){this.capture("$ai_feedback",{$ai_trace_id:String(t),$ai_feedback_text:r})}captureTraceMetric(t,r,n){this.capture("$ai_metric",{$ai_trace_id:String(t),$ai_metric_name:r,$ai_metric_value:String(n)})}Du(t){const r=gt(t)&&!t,n=ke.Et()&&ke.Ot("ph_debug")==="true";return!r&&(!!n||t)}};Bi.__defaultExtensionClasses={},Bi.Ch=(()=>{const e=()=>{};return{trace:e,debug:e,info:e,warn:e,error:e,fatal:e}})(),(function(e,t){for(let r=0;t.length>r;r++)e.prototype[t[r]]=Cw(e.prototype[t[r]])})(Bi,["identify"]);var Cg=class{constructor(e){this.disabled=e===!1;const t=be(e)?e:{};this.thresholdPx=t.threshold_px||30,this.timeoutMs=t.timeout_ms||1e3,this.clickCount=t.click_count||3,this.clicks=[]}isRageClick(e,t,r){if(this.disabled)return!1;const n=this.clicks[this.clicks.length-1];if(n&&Math.abs(e-n.x)+Math.abs(t-n.y)<this.thresholdPx&&this.timeoutMs>r-n.timestamp){if(this.clicks.push({x:e,y:t,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:t,timestamp:r}];return!1}},cc="$copy_autocapture",lc=Be("[AutoCapture]");function uc(e,t){return t.length>e?t.slice(0,e)+"...":t}function NS(e){if(e.previousElementSibling)return e.previousElementSibling;let t=e;do t=t.previousSibling;while(t&&!Kt(t));return t}function zS(e,{e:t,maskAllElementAttributes:r,maskAllText:n,elementAttributeIgnoreList:i,elementsChainAsString:s,disableCaptureUrlHashes:o}){var a,c;if(!Kt(e))return{props:{}};const l=[e],u=new Set([e]);let h=e;for(;h.parentNode&&!lt(h,"body")&&1e3>l.length;){if(au(h.parentNode)){const C=h.parentNode.host;if(u.has(C))break;u.add(C),l.push(C),h=C;continue}if(!Kt(h.parentNode)||u.has(h.parentNode))break;u.add(h.parentNode),l.push(h.parentNode),h=h.parentNode}const d=t.type==="click"&&e.namespaceURI==="http://www.w3.org/2000/svg"?l.findIndex(C=>lt(C,"button")||lt(C,"a")):-1;d>0&&(n=n||l.slice(0,d+1).some(C=>!Vn(C)||Qi(C)));const p=[],f={};let v,m=!1,_=!1;if($e(l,C=>{const M=Vn(C);if(lt(C,"a")&&!r&&!i?.includes("href")){const L=C.getAttribute("href");m=!!(M&&L&&qi(L))&&(o?Mr(L):L)}ue(Xn(C),"ph-no-capture")&&(_=!0),p.push((function(L,q,X,ee,k=!1){const ie=L.tagName.toLowerCase(),H={tag_name:ie};lu.indexOf(ie)>-1&&!X&&(H.$el_text=ie.toLowerCase()==="a"||ie.toLowerCase()==="button"?uc(1024,Qd(L)):uc(1024,Xi(L)));const oe=Xn(L);q||ee!=null&&ee.includes("class")||0>=oe.length||(H.classes=oe.filter(function(V){return V!==""})),$e(L.attributes,function(V){var K;if((!Qi(L)||["name","id","class","aria-label"].indexOf(V.name)!==-1)&&!ee?.includes(V.name)&&!q&&qi(V.value)&&(!ye(K=V.name)||K.substring(0,10)!=="_ngcontent"&&K.substring(0,7)!=="_nghost")){let le=V.value;V.name==="class"&&(le=cu(le).join(" ")),H["attr__"+V.name]=uc(1024,V.name==="href"&&k?Mr(le):le)}});let $=1,Q=1,y=L;for(;y=NS(y);)$++,y.tagName===L.tagName&&Q++;return H.nth_child=$,H.nth_of_type=Q,H})(C,r,n,i,o)),$e((function(L){if(!Vn(L))return{};const q={};return $e(L.attributes,function(X){if(X.name&&X.name.indexOf("data-ph-capture-attribute")===0){const ee=X.name.replace("data-ph-capture-attribute-",""),k=X.value;ee&&k&&qi(k)&&(q[ee]=k)}}),q})(C),(L,q)=>{({}).hasOwnProperty.call(f,q)||(f[q]=L)})}),_)return{props:{},explicitNoCapture:_};if(d>0&&(e=l[d],p.splice(0,d)),n||(p[0].$el_text=lt(e,"a")||lt(e,"button")?Qd(e):Xi(e)),m){var w,S;p[0].attr__href=m;const C=(w=Lr(m))===null||w===void 0?void 0:w.host,M=A==null||(S=A.location)===null||S===void 0?void 0:S.host;C&&M&&C!==M&&(v=m)}return{props:Le((I=t.type,{$event_type:I,$ce_version:1}),s?{}:{$elements:p},{$elements_chain:(T=p,ce(T)?(function(C){return C.map(M=>{var L,q;let X="";if(M.tag_name&&(X+=M.tag_name),M.attr_class){M.attr_class.sort();for(const ie of M.attr_class)X+=`.${ie.replace(/"/g,"")}`}const ee=b(b(b(b({},M.text?{text:M.text}:{}),{},{"nth-child":(L=M.nth_child)!==null&&L!==void 0?L:0,"nth-of-type":(q=M.nth_of_type)!==null&&q!==void 0?q:0},M.href?{href:M.href}:{}),M.attr_id?{attr_id:M.attr_id}:{}),M.attributes),k={};return Ws(ee).sort(([ie],[H])=>(function(oe,$){return $>oe?-1:oe>$?1:0})(ie,H)).forEach(([ie,H])=>k[eh(ie.toString())]=eh(H.toString())),X+=":",X+=Ws(k).map(([ie,H])=>`${ie}="${H}"`).join(""),X}).join(";")})((function(C){return C.map(M=>{var L,q;const X={text:(L=M.$el_text)===null||L===void 0?void 0:L.slice(0,400),tag_name:M.tag_name,href:(q=M.attr__href)===null||q===void 0?void 0:q.slice(0,2048),attr_class:Bw(M),attr_id:M.attr__id,nth_child:M.nth_child,nth_of_type:M.nth_of_type,attributes:{}};return Ws(M).filter(([ee])=>ee.indexOf("attr__")===0).forEach(([ee,k])=>X.attributes[ee]=k),X})})(T)):"")},!((a=p[0])===null||a===void 0)&&a.$el_text?{$el_text:(c=p[0])===null||c===void 0?void 0:c.$el_text}:{},v&&t.type==="click"?{$external_click_url:v}:{},f),target:e};var T,I}var US=class{fo(){this.po=void 0,clearTimeout(this.mo),this.mo=void 0}yo(e){var t;if(!Vn(e))return!0;const r=(t=this.bo().css_selector_ignorelist)!==null&&t!==void 0?t:Ka,n=new Set;let i=e;for(;i;){if(n.size>=1e3||n.has(i))return!0;n.add(i);const s=i,o=Xn(s);if(ue(o,"ph-no-capture")||ue(o,"ph-sensitive")||Qi(s)||r.some(c=>el(s,c)))return!0;const a=i.parentNode;i=au(a)?a.host:a&&Kt(a)?a:null}return!1}_o(e){if(!this.isEnabled||e.type==="pointercancel")return void this.fo();if(e.type==="pointerdown"){this.fo();const n=Fi(e);var t;e.isPrimary&&e.button===0&&!e.ctrlKey&&n&&Kt(n)&&(this.po={target:n,excluded:this.yo(n),id:e.pointerId,x:e.clientX,y:e.clientY,released:!1,distinctId:(t=this.wo)===null||t===void 0?void 0:t.distinctId});return}const r=this.po;r&&(e.pointerId!==r.id||Math.abs(e.clientX-r.x)>5||Math.abs(e.clientY-r.y)>5?this.fo():e.type==="pointerup"&&(r.released=!0,this.mo=setTimeout(()=>this.fo(),0)))}ko(e){var t;const r=this.po;this.fo();const n=Fi(e);if(r?.released&&r.target.isConnected&&r.distinctId===((t=this.wo)===null||t===void 0?void 0:t.distinctId)&&e.pointerId===r.id&&(e.detail>0||e.pointerType==="touch"||e.pointerType==="pen")&&e.button===0&&5>=Math.abs(e.clientX-r.x)&&5>=Math.abs(e.clientY-r.y)&&n&&(lt(n,"html")||lt(n,"body"))){var i;if(r.excluded)return null;const s=(i=this.bo().css_selector_ignorelist)!==null&&i!==void 0?i:Ka;return[n,N?.documentElement,N?.body].some(o=>{if(!o)return!1;const a=Xn(o);return ue(a,"ph-no-capture")||ue(a,"ph-sensitive")||!Vn(o)||Qi(o)||s.some(c=>el(o,c))})?null:r.target}}constructor(e){this.So=e,this.name="autocapture",this.xo=!1,this.Co=null,this.$o=!1,this.To=!1,this.Rr={enabled:!1,rageclick:!1,maskAllElementAttributes:!1,maskAllText:!1,disableCaptureUrlHashes:!1,remoteRequestsDisabled:!1},this.Io=!1,this.So.refresh(this.Rr),this.rageclicks=new Cg(this.Rr.rageclick),this.Mo=null}setup(e){this.Eo(),this.wo=e;const t=e.onRemoteConfig(this.onRemoteConfig.bind(this));this.Io?t.dispose():(this.Po=t,this.startIfEnabled())}dispose(){var e;this.Io||(this.Io=!0,this.wo=void 0,(e=this.Po)===null||e===void 0||e.dispose(),this.Po=void 0,this.Ro())}bo(){return this.So.refresh(this.Rr),this.Rr}Eo(){var e,t;return this.bo(),this.Rr.url_allowlist=(e=this.Rr.url_allowlist)===null||e===void 0?void 0:e.map(r=>new RegExp(r)),this.Rr.url_ignorelist=(t=this.Rr.url_ignorelist)===null||t===void 0?void 0:t.map(r=>new RegExp(r)),this.Rr}Ao(){if(!this.isBrowserSupported())return void lc.info("Disabling Automatic Event Collection because this browser is not supported");if(!A||!N)return;const e=this.Fo=t=>{t=t||A?.event;try{if(t.type==="blur")return void this.fo();if(t.type.indexOf("pointer")===0)return void this._o(t);const r=t.type==="click"?this.ko(t):void 0;if(He(r))return;this.Oo(t,"$autocapture",r)}catch(r){lc.error("Failed to capture event",r)}};if(Ie(A,"blur",e),Ie(N,"submit",e,{capture:!0}),Ie(N,"change",e,{capture:!0}),Ie(N,"click",e,{capture:!0}),$e(["pointerdown","pointermove","pointerup","pointercancel"],t=>{Ie(N,t,e,{capture:!0})}),this.bo().capture_copied_text){const t=this.Do=r=>{r=r||A?.event;try{this.Oo(r,cc)}catch(n){lc.error("Failed to capture clipboard event",n)}};Ie(N,"copy",t,{capture:!0}),Ie(N,"cut",t,{capture:!0}),Ie(N,"paste",t,{capture:!0})}}Ro(){this.fo(),this.Fo&&(A?.removeEventListener("blur",this.Fo),$e(["pointerdown","pointermove","pointerup","pointercancel"],e=>{N?.removeEventListener(e,this.Fo,!0)}),N?.removeEventListener("submit",this.Fo,!0),N?.removeEventListener("change",this.Fo,!0),N?.removeEventListener("click",this.Fo,!0),this.Fo=void 0),this.Do&&(N?.removeEventListener("copy",this.Do,!0),N?.removeEventListener("cut",this.Do,!0),N?.removeEventListener("paste",this.Do,!0),this.Do=void 0),this.xo=!1}startIfEnabled(){this.isEnabled||this.fo(),!this.Io&&this.wo&&this.isEnabled&&!this.xo&&(this.Ao(),this.xo=!0)}onRemoteConfig(e){if(this.Io)return;if(this.$o=!0,!e.ok)return void this.startIfEnabled();const t=e.config;t.elementsChainAsString&&(this.To=t.elementsChainAsString);const r=t.autocapture_opt_out;var n;gt(r)&&((n=this.wo)===null||n===void 0||n.kv.set("$autocapture_disabled_server_side",r),this.Co=r),this.startIfEnabled()}setElementSelectors(e){this.Mo=e}getElementSelectors(e,t){var r;const n=[];return(r=this.Mo)===null||r===void 0||r.forEach(i=>{N?.querySelectorAll(i)?.forEach(s=>{e!==s&&t!==s||ue(n,i)||n.push(i)})}),n}get isEnabled(){var e,t;if(this.Io)return!1;const r=(e=this.wo)===null||e===void 0?void 0:e.kv.get(yv),n=this.Co,i=this.bo();if(!i.remoteRequestsDisabled&&!this.$o)return!1;const s=i.remoteRequestsDisabled&&!this.$o;if(He(n)&&!gt(r)&&!s)return!1;const o=(t=this.Co)!==null&&t!==void 0?t:!!r;return!!i.enabled&&!o}Oo(e,t="$autocapture",r){if(!this.isEnabled)return void this.fo();let n=r||Fi(e);qv(n)&&(n=n.parentNode||null);const i=this.Eo();var s;t==="$autocapture"&&e.type==="click"&&e instanceof MouseEvent&&i.rageclick&&(s=this.rageclicks)!==null&&s!==void 0&&s.isRageClick(e.clientX,e.clientY,e.timeStamp||new Date().getTime())&&Bv(n,i.rageclick)&&this.Oo(e,"$rageclick",r);const o=t===cc,a=o?b(b({},i),{},{dom_event_allowlist:void 0}):i;if(n&&(function(h,d,p,f,v,m){var _;if(!A||uu(h)||p?.url_allowlist&&!Gd(p.url_allowlist,m)||p?.url_ignorelist&&Gd(p.url_ignorelist,m))return!1;if(p?.dom_event_allowlist){const I=p.dom_event_allowlist;if(I&&!I.some(C=>d.type===C))return!1}const{parentIsUsefulElement:w,targetElementList:S}=Gv(h,f);if(!(function(I,C){const M=C?.element_allowlist;if(O(M))return!0;for(const L of I)if(M.some(q=>L.tagName.toLowerCase()===q))return!0;return!1})(S,p)||!tl(S,p?.css_selector_allowlist)||tl(S,(_=p?.css_selector_ignorelist)!==null&&_!==void 0?_:Ka))return!1;try{const I=A.getComputedStyle(h);if(I&&I.getPropertyValue("cursor")==="pointer"&&d.type==="click")return!0}catch{}const T=h.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(v||["submit"]).indexOf(d.type)>=0;case"input":case"select":case"textarea":return(v||["change","click"]).indexOf(d.type)>=0;default:return w?(v||["click"]).indexOf(d.type)>=0:(v||["click"]).indexOf(d.type)>=0&&(lu.indexOf(T)>-1||h.getAttribute("contenteditable")==="true")}})(n,e,a,o,o?["copy","cut","paste"]:void 0,{config:{get_current_url:i.getCurrentUrl}})){var c;const{props:h,explicitNoCapture:d,target:p}=zS(n,{e,maskAllElementAttributes:i.maskAllElementAttributes,maskAllText:i.maskAllText,elementAttributeIgnoreList:i.element_attribute_ignorelist,elementsChainAsString:this.To,disableCaptureUrlHashes:i.disableCaptureUrlHashes});if(d)return!1;const f=this.getElementSelectors(n,p);if(f&&f.length>0&&(h.$element_selectors=f),t===cc){const v=e.type||"clipboard";if(v!=="paste"){var l,u;const m=A==null||(l=A.getSelection())===null||l===void 0?void 0:l.toString(),_=jv(m);if(!_)return!1;h.$selected_content=_,h.$clipboard_text_length=(u=m?.length)!==null&&u!==void 0?u:0}h.$copy_type=v}return(c=this.wo)===null||c===void 0||c.capture(t,h),!0}}isBrowserSupported(){return rt(N?.querySelectorAll)}},FS=class{constructor(e){this._instance=e}refresh(e){const t=this._instance.config,r=be(t.autocapture)?t.autocapture:void 0;e.enabled=!!t.autocapture,e.rageclick=t.rageclick,e.maskAllElementAttributes=t.mask_all_element_attributes,e.maskAllText=t.mask_all_text,e.disableCaptureUrlHashes=t.disable_capture_url_hashes,e.getCurrentUrl=t.get_current_url,e.remoteRequestsDisabled=this._instance.nl(),e.url_allowlist=r?.url_allowlist,e.url_ignorelist=r?.url_ignorelist,e.dom_event_allowlist=r?.dom_event_allowlist,e.element_allowlist=r?.element_allowlist,e.css_selector_allowlist=r?.css_selector_allowlist,e.css_selector_ignorelist=r?.css_selector_ignorelist,e.element_attribute_ignorelist=r?.element_attribute_ignorelist,e.capture_copied_text=r?.capture_copied_text}},Si=Be("[ExceptionAutocapture]"),Eh=()=>{},kh=e=>{var t;if(rt(e))return(t=e.__posthog_layer__)!==null&&t!==void 0?t:e.__rrweb_layer__};function rs(e,t,r){try{if(!(t in e))return Eh;const n={next:e[t]},i=r(function(...s){return n.next.apply(this,s)});return rt(i)&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:n}})),e[t]=i,()=>{if(e[t]===i)return void(e[t]=n.next);let s=e[t],o=kh(s);for(;o;){if(o.next===i)return void(o.next=n.next);s=o.next,o=kh(s)}}}catch{return Eh}}var qS=Be("[TracingHeaders]"),Zr=Be("[Web Vitals]"),Rh=9e5,Ah=["CLS","FCP","INP","LCP"],jS=["INP","LCP"],HS=["interactionTarget","interactionType","inputDelay","processingDuration","presentationDelay","loadState","target","url","timeToFirstByte","resourceLoadDelay","resourceLoadDuration","elementRenderDelay","largestShiftTarget","largestShiftTime","largestShiftValue","firstByteToFCP"],dc="disabled",Ih="lazy_loading",Qt=Be("[SessionRecording]"),VS=Be("[Heatmaps]");function hc(e){return be(e)&&"clientX"in e&&"clientY"in e&&We(e.clientX)&&We(e.clientY)}var $s=Be("[Product Tours]"),pc=e=>{var t;return!e.config.disable_product_tours&&!!(!((t=e.persistence)===null||t===void 0)&&t.get_property(ru))},BS=["$set_once","$set"],jt=Be("[SiteApps]"),Th="Error while initializing PostHog app with config id ",Pg=(e,t)=>e?.then?e.then(t):t(e),An="SDK is not enabled or survey functionality is not yet loaded",$h="Disabled. Not loading surveys.",GS=class{constructor(e,t){this.So=e,this.Th=t,this.name="surveys",this._surveyEventReceiver=null,this._surveyManager=null,this.Ih=!1,this.Mh=[],this.Eh=null,this.Ph=null,this.Io=!1,this.Rh=new Set,this.onRemoteConfig=r=>{if(this.Io||this.Rr.disableSurveys)return;if(!r.ok)return Te.warn("Remote config unavailable. Not loading surveys.");const n=r.config.surveys;if(ge(n))return Te.warn("Flags not loaded yet. Not loading surveys.");this.Ah=gt(n)?n:n.length>0,Te.info(`flags response received, isSurveysEnabled: ${this.Ah}`),this.loadIfEnabled()}}setup(e){if(!this.Io)return this.Fh=e,Pg(e.kv.initialize(),()=>{if(this.Fh!==e||this.Io)return;this.Fh=void 0,this.wo=e;const t=e.onRemoteConfig(this.onRemoteConfig);this.Io?t.dispose():(this.Po=t,this.loadIfEnabled())})}dispose(){var e,t,r,n;this.Io||(this.Io=!0,this.Fh=void 0,this.wo=void 0,(e=this.Po)===null||e===void 0||e.dispose(),this.Po=void 0,(t=this._surveyEventReceiver)===null||t===void 0||t.dispose(),this._surveyEventReceiver=null,(r=this._surveyManager)===null||r===void 0||(n=r.dispose)===null||n===void 0||n.call(r),this._surveyManager=null,this.Mh=[],this.Eh=null,this.Rh.forEach(i=>clearTimeout(i)),this.Rh.clear())}get Rr(){return this.So.get()}initialize(){this.loadIfEnabled()}reset(){var e,t;(e=this._surveyManager)===null||e===void 0||(t=e.clearInMemoryInProgressSurveyState)===null||t===void 0||t.call(e);try{var r;(r=this._surveyEventReceiver)===null||r===void 0||r.reset(),localStorage.removeItem("lastSeenSurveyDate");const n=[];for(let i=0;i<localStorage.length;i++){const s=localStorage.key(i);(s!=null&&s.startsWith("seenSurvey_")||s!=null&&s.startsWith("inProgressSurvey_"))&&n.push(s)}n.forEach(i=>localStorage.removeItem(i))}catch{}}loadIfEnabled(){if(this.Io||!this.wo)return;const e=this.Rr;if(this._surveyManager)return;if(this.Ih)return void Te.info("Already initializing surveys, skipping...");if(e.disableSurveys)return void Te.info($h);if(e.cookielessMode&&this.So.isOptedOut())return void Te.info("Not loading surveys in cookieless mode without consent.");const t=this.So.getExtensions();if(!t)return void Te.error("PostHog Extensions not found.");if(O(this.Ah)&&!e.advancedEnableSurveys)return;const r=this.Ah||e.advancedEnableSurveys;this.Ih=!0;try{const n=t.generateSurveys;if(n)return this.Oh(n,r),void(this.Ih=!1);const i=t.loadExternalDependency;if(!i)return this.Dh(iu),void(this.Ih=!1);i(s=>{try{if(this.Io)return;const o=this.So.getExtensions();s||!o?.generateSurveys?this.Dh("Could not load surveys script",s):this.Oh(o.generateSurveys,r)}finally{this.Ih=!1}})}catch(n){throw this.Ih=!1,this.Dh("Error initializing surveys",n),n}}Oh(e,t){this.Io||(this._surveyManager=e(t),this._surveyEventReceiver=this.So.createEventReceiver(),Te.info("Surveys loaded successfully"),this.Lh({isLoaded:!0}))}Dh(e,t){Te.error(e,t),this.Lh({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.Mh.push(e),this._surveyManager&&this.Lh({isLoaded:!0}),()=>{this.Mh=this.Mh.filter(t=>t!==e)}}getSurveys(e,t=!1){var r;const n=(r=this.wo)!==null&&r!==void 0?r:this.Th;if(!n||this.Io)return;if(this.Rr.disableSurveys)return Te.info($h),e([]);const i=n.kv.get(Zc);if(i&&!t)return e(i,{isLoaded:!0}),void(this.Nh()&&this.getSurveys(()=>{},!0));if(this.Eh)return void this.Eh.then(({surveys:a,context:c})=>{this.Io||e(a,c)}).catch(a=>Te.error("Error in survey callback",a));const s=this.qh("/api/surveys/",{method:"GET",query:{token:n.projectToken},sentAt:"query",timeoutMs:this.Rr.requestTimeoutMs}).then(a=>{try{return this.jh(n,a)}catch(c){return Te.error("Error processing surveys response",c),this.jh(n,{statusCode:0,error:c})}},a=>this.jh(n,{statusCode:0,error:a}));this.Eh=s;const o=()=>{this.Eh===s&&(this.Eh=null)};s.then(a=>{o(),this.Io||e(a.surveys,a.context)},o).catch(a=>Te.error("Error in survey callback",a))}qh(e,t){const r=this.wo;return r?r.sendRequest(e,t):new Promise(n=>n({statusCode:0,error:new Error(An)}))}jh(e,t){if(this.Io)return{surveys:[],context:{isLoaded:!1,error:An}};const r=t.statusCode;if(r!==200||!t.json){const o=`Surveys API could not be loaded, status: ${r}`;return r!==0?Te.error(o):t.error||Te.warn(o),this.Ph=Date.now(),{surveys:[],context:{isLoaded:!1,error:o}}}this.Ph=null;const n=t.json.surveys||[],i=n.filter(o=>(function(a){return!(!a.start_date||a.end_date)})(o)&&(Rg(o)||(function(a){var c;return!!(!((c=a.conditions)===null||c===void 0||(c=c.actions)===null||c===void 0||(c=c.values)===null||c===void 0)&&c.length)})(o)));var s;return i.length>0&&((s=this._surveyEventReceiver)===null||s===void 0||s.register(i)),e.kv.set({[Zc]:n,[yo]:Date.now()}),{surveys:n,context:{isLoaded:!0}}}Nh(){return this.Bh()&&!this.Eh&&!this.Hh()}Bh(){var e,t;const r=(e=(t=this.wo)!==null&&t!==void 0?t:this.Th)===null||e===void 0?void 0:e.kv.get(yo);return We(r)&&Date.now()-r>3e5}Hh(){return We(this.Ph)&&3e5>Date.now()-this.Ph}markSurveyAsSeen(e,t){var r;const n={id:e,current_iteration:(r=t?.iteration)!==null&&r!==void 0?r:null};Tg(n);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Lh(e){for(const t of this.Mh)try{if(!e.isLoaded)return t([],e);this.getSurveys(t)}catch(r){Te.error("Error in survey callback",r)}}getActiveMatchingSurveys(e,t=!1){if(!ge(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);Te.warn("init was not called")}zh(e){let t=null;return this.getSurveys(r=>{var n;t=(n=r.find(i=>i.id===e))!==null&&n!==void 0?n:null}),t}Uh(e){if(ge(this._surveyManager))return{eligible:!1,reason:An};const t=typeof e=="string"?this.zh(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}Wh(e){if(!this.So.isCapturing())return{eligible:!1,reason:"PostHog is not capturing, so a survey response cannot be recorded"};if(ge(this._surveyManager))return{eligible:!1,reason:An};const t=typeof e=="string"?this.zh(e):e;return t?this._surveyManager.checkSurveyRenderability(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(ge(this._surveyManager))return Te.warn("init was not called"),{visible:!1,disabledReason:An};const t=this.Wh(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return ge(this._surveyManager)?(Te.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:An})):new Promise(r=>{this.getSurveys(n=>{var i;const s=(i=n.find(o=>o.id===e))!==null&&i!==void 0?i:null;if(s){const o=this.Wh(s);r({visible:o.eligible,disabledReason:o.reason})}else r({visible:!1,disabledReason:"Survey not found"})},t)})}renderSurvey(e,t,r){var n;if(!this.So.isCapturing())return;if(ge(this._surveyManager))return void Te.warn("init was not called");const i=typeof e=="string"?this.zh(e):e;if(!i?.id)return void Te.warn("Survey not found");if(!kS.includes(i.type))return void Te.warn(`Surveys of type ${i.type} cannot be rendered in the app`);const s=N?.querySelector(t);if(s){if(!((n=i.appearance)===null||n===void 0)&&n.surveyPopupDelaySeconds){Te.info(`Rendering survey ${i.id} with delay of ${i.appearance.surveyPopupDelaySeconds} seconds`);const o=setTimeout(()=>{var a,c;this.Rh.delete(o),!this.Io&&this.So.isCapturing()&&(Te.info(`Rendering survey ${i.id} with delay of ${(a=i.appearance)===null||a===void 0?void 0:a.surveyPopupDelaySeconds} seconds`),(c=this._surveyManager)===null||c===void 0||c.renderSurvey(i,s,r),Te.info(`Survey ${i.id} rendered`))},1e3*i.appearance.surveyPopupDelaySeconds);this.Rh.add(o);return}this._surveyManager.renderSurvey(i,s,r)}else Te.warn("Survey element not found")}displaySurvey(e,t){var r;if(!this.So.isCapturing())return;if(ge(this._surveyManager))return void Te.warn("init was not called");const n=this.zh(e);if(!n)return void Te.warn("Survey not found");let i=n;if((r=n.appearance)!==null&&r!==void 0&&r.surveyPopupDelaySeconds&&t.ignoreDelay&&(i=b(b({},n),{},{appearance:b(b({},n.appearance),{},{surveyPopupDelaySeconds:0})})),t.displayType!==rl.Popover&&t.initialResponses&&Te.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),t.ignoreConditions===!1){const s=this.Uh(n);if(!s.eligible)return void Te.warn("Survey is not eligible to be displayed: ",s.reason)}t.displayType!==rl.Inline?this._surveyManager.handlePopoverSurvey(i,t):this.renderSurvey(i,t.selector,t.properties)}cancelPendingSurvey(e){ge(this._surveyManager)?Te.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e,t;(e=this._surveyManager)===null||e===void 0||(t=e.handlePageUnload)===null||t===void 0||t.call(e)}};function In(e,t,r){if(ge(e))return!1;switch(r){case"exact":return e===t;case"contains":{const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(n,"i").test(e)}case"regex":try{return new RegExp(t).test(e)}catch{return!1}default:return!1}}var WS=class{constructor(e){this._instance=e,this.Vh=new Set,this.Gh=new Set,this.Zh=new Ro,this.Qh=(t,r)=>this.Jh(t,r)&&this.Kh(t,r)&&this.Xh(t,r)&&this.Yh(t,r),this.Jh=(t,r)=>!r?.event||t?.event===r?.event}init(){var e,t;O((e=this._instance)===null||e===void 0?void 0:e._addCaptureHook)||(this.tc=(t=this._instance)===null||t===void 0?void 0:t._addCaptureHook((r,n)=>{this.on(r,n)}))}dispose(){var e;(e=this.tc)===null||e===void 0||e.call(this),this.tc=void 0,this.Zh=new Ro}register(e){var t,r;if(!O((t=this._instance)===null||t===void 0?void 0:t._addCaptureHook)&&(e.forEach(n=>{var i;this.Vh.add(n),(i=n.steps)===null||i===void 0||i.forEach(s=>{this.Gh.add(s?.event||"")})}),(r=this._instance)===null||r===void 0?void 0:r.autocapture)){const n=new Set;this.Vh.forEach(i=>{var s;(s=i.steps)===null||s===void 0||s.forEach(o=>{o!=null&&o.selector&&n.add(o.selector)})}),this._instance.autocapture.setElementSelectors(n)}}replace(e){this.Vh.clear(),this.Gh.clear(),this.register(e)}on(e,t){t!=null&&e.length!=0&&(this.Gh.has(e)||this.Gh.has(t.event))&&this.Vh.forEach(r=>{this.ec(t,r)&&this.Zh.emit("actionCaptured",r.name)})}nc(e){this.onAction("actionCaptured",t=>e(t))}ec(e,t){if(t?.steps==null)return!1;for(const r of t.steps)if(this.Qh(e,r))return!0;return!1}onAction(e,t){return this.Zh.on(e,t)}Kh(e,t){if(t?.url){var r;const n=e==null||(r=e.properties)===null||r===void 0?void 0:r.$current_url;if(!n||typeof n!="string"||!In(n,t.url,t.url_matching||"contains"))return!1}return!0}Xh(e,t){return!!this.sc(e,t)&&!!this.rc(e,t)&&!!this.oc(e,t)}sc(e,t){var r;if(!t?.href)return!0;const n=this.ac(e);if(n.length>0)return n.some(s=>In(s.href,t.href,t.href_matching||"exact"));const i=(e==null||(r=e.properties)===null||r===void 0?void 0:r.$elements_chain)||"";return!!i&&In((function(s){const o=s.match(/(?::|")href="(.*?)"/);return o?o[1]:""})(i),t.href,t.href_matching||"exact")}rc(e,t){var r;if(!t?.text)return!0;const n=this.ac(e);if(n.length>0)return n.some(c=>In(c.text,t.text,t.text_matching||"exact")||In(c.$el_text,t.text,t.text_matching||"exact"));const i=(e==null||(r=e.properties)===null||r===void 0?void 0:r.$elements_chain)||"";return!!i&&(s=(function(c){const l=[],u=/(?::|")text="(.*?)"/g;let h;for(;!ge(h=u.exec(c));)l.includes(h[1])||l.push(h[1]);return l})(i),o=t.text,a=t.text_matching||"exact",s.some(c=>In(c,o,a)));var s,o,a}oc(e,t){var r,n;if(!t?.selector)return!0;const i=e==null||(r=e.properties)===null||r===void 0?void 0:r.$element_selectors;if(i?.includes(t.selector))return!0;const s=(e==null||(n=e.properties)===null||n===void 0?void 0:n.$elements_chain)||"";if(t.selector_regex&&s)try{return new RegExp(t.selector_regex).test(s)}catch{return!1}return!1}ac(e){var t;return(e==null||(t=e.properties)===null||t===void 0?void 0:t.$elements)==null?[]:e?.properties.$elements}Yh(e,t){return!t?.properties||t.properties.length===0||Ig(t.properties.reduce((r,n)=>{const i=ce(n.value)?n.value.map(String):n.value!=null?[String(n.value)]:[];return r[n.key]={values:i,operator:n.operator||"exact"},r},{}),e?.properties)}},ZS=class{constructor(e){var t,r;this.lc=[],this._instance=e,this.uc=new Map,this.hc=new Map,this.cc=new Map,this.dc=(t=this._instance)===null||t===void 0||(r=t.onSessionId)===null||r===void 0?void 0:r.call(t,n=>this.vc(n))}fc(e){return!1}gc(){return null}mc(e){}yc(){}bc(e,t){return!!e&&Ig(e.propertyFilters,t?.properties)}_c(e,t){const r=new Map;return e.forEach(n=>{var i;(i=n.conditions)===null||i===void 0||(i=i[t])===null||i===void 0||(i=i.values)===null||i===void 0||i.forEach(s=>{if(s?.name){const o=r.get(s.name)||[];o.push(n.id),r.set(s.name,o)}})}),r}wc(e,t,r){const n=(r===_i.Activation?this.uc:this.hc).get(e);let i=[];return this.kc(s=>{i=s.filter(o=>n?.includes(o.id))}),i.filter(s=>{var o;const a=(o=s.conditions)===null||o===void 0||(o=o[r])===null||o===void 0||(o=o.values)===null||o===void 0?void 0:o.find(c=>c.name===e);return this.bc(a,t)})}register(e){this.Sc(e,!1)}replace(e){this.Sc(e,!0)}Sc(e,t){var r;O((r=this._instance)===null||r===void 0?void 0:r._addCaptureHook)||(this.xc(e,t),this.Cc(e,t))}Cc(e,t){const r=e.filter(s=>{var o;return(o=s.conditions)===null||o===void 0||(o=o.actions)===null||o===void 0||(o=o.values)===null||o===void 0?void 0:o.length});var n;if(t&&this.cc.clear(),r.length===0)return void(t&&((n=this.$c)===null||n===void 0||n.replace([])));this.$c||(this.$c=new WS(this._instance),this.$c.init(),this.$c.nc(s=>this.onAction(s)));const i=[];r.forEach(s=>{var o;(o=s.conditions)===null||o===void 0||(o=o.actions)===null||o===void 0||o.values.forEach(a=>{if(i.push(a),a.name){var c;const l=(c=this.cc.get(a.name))!==null&&c!==void 0?c:[];l.includes(s.id)||l.push(s.id),this.cc.set(a.name,l)}})}),t?this.$c.replace(i):this.$c.register(i)}Tc(e,t){t.forEach((r,n)=>{var i;const s=(i=e.get(n))!==null&&i!==void 0?i:[];r.forEach(o=>{s.includes(o)||s.push(o)}),e.set(n,s)})}xc(e,t){var r,n;const i=e.filter(c=>{var l,u;return((l=c.conditions)===null||l===void 0?void 0:l.events)&&((u=c.conditions)===null||u===void 0||(u=u.events)===null||u===void 0||(u=u.values)===null||u===void 0?void 0:u.length)>0}),s=e.filter(c=>{var l,u;return((l=c.conditions)===null||l===void 0?void 0:l.cancelEvents)&&((u=c.conditions)===null||u===void 0||(u=u.cancelEvents)===null||u===void 0||(u=u.values)===null||u===void 0?void 0:u.length)>0}),o=this._c(e,_i.Activation),a=this._c(e,_i.Cancellation);t?(this.uc=o,this.hc=a):(this.Tc(this.uc,o),this.Tc(this.hc,a)),(i.length!==0||s.length!==0)&&((r=this.tc)!==null&&r!==void 0||(this.tc=(n=this._instance)===null||n===void 0?void 0:n._addCaptureHook((c,l)=>{this.onEvent(c,l)})))}onEvent(e,t){var r,n;const i=this.Ic(),s=(t==null||(r=t.properties)===null||r===void 0?void 0:r.$survey_id)||(t==null||(n=t.properties)===null||n===void 0?void 0:n.$product_tour_id);if(s&&this.getActivatedIds().includes(s)){const a=this.Mc(e,s);if(a==="consume")return i.info("event consumed activated item, removing it",{event:e,itemId:s}),void this.Ec([s]);if(a==="persist")return i.info("shown item promoted to persisted activation",{event:e,itemId:s}),this.Pc(s),void this.Rc([s])}if(this.hc.has(e)){const a=this.wc(e,t,_i.Cancellation);a.length>0&&(i.info("cancel event matched, cancelling items",{event:e,itemsToCancel:a.map(c=>c.id)}),this.Ec(a.map(c=>c.id)),a.forEach(c=>this.Ac(c.id)))}if(!this.uc.has(e))return;i.info("event name matched",{event:e,eventPayload:t,items:this.uc.get(e)});const o=this.wc(e,t,_i.Activation);this.Fc(o.map(a=>a.id))}onAction(e){this.cc.has(e)&&this.Fc(this.cc.get(e)||[])}Fc(e){var t,r;if(e.length===0)return;const n=!!(!((t=this._instance)===null||t===void 0||(r=t.get_session_id)===null||r===void 0)&&r.call(t)),i=[];for(const s of e)n&&this.fc(s)?this.Pc(s)&&this.Oc(s):i.push(s);i.length>0&&(this.lc=[...new Set([...this.lc,...i])]),this.Ic().info("updating activated items",{activatedItems:this.getActivatedIds()})}Pc(e){this.lc=this.lc.filter(r=>r!==e);const t=this.Dc();return!t.includes(e)&&(this.Lc([...t,e]),this.Nc(),!0)}Ec(e){const t=new Set(e);this.lc=this.lc.filter(i=>!t.has(i));const r=this.qc(),n=r.filter(i=>!t.has(i));n.length!==r.length&&(this.Lc(n),n.length===0&&this.jc()),this.Rc(e)}Bc(){var e;const t=this.gc();if(!t)return{};const r=(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0?void 0:e.props[t];return r&&typeof r=="object"?r:{}}Oc(e){if(!this.gc())return;const t=this.Bc();this.mc(b(b({},t),{},{[e]:Date.now()}))}Rc(e){if(!this.gc())return;const t=this.Bc(),r={};let n=!1;for(const[i,s]of Object.entries(t))e.includes(i)?n=!0:r[i]=s;n&&(_t(r)?this.yc():this.mc(r))}Hc(){this.gc()&&this.yc()}getActivationTimestamp(e){if(!this.Dc().includes(e))return;const t=this.Bc()[e];return We(t)?t:void 0}qc(){var e;const t=this.zc();return((e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0?void 0:e.props[t])||[]}Dc(){var e,t,r;const n=this.qc();if(n.length===0)return[];const i=(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0?void 0:e.props[this.Uc()],s=(t=this._instance)===null||t===void 0||(r=t.get_session_id)===null||r===void 0?void 0:r.call(t);return s&&i===s?n:[]}Nc(){var e,t;const r=(e=this._instance)===null||e===void 0||(t=e.get_session_id)===null||t===void 0?void 0:t.call(e);r&&this.Wc(r)}jc(){this.Vc()}vc(e){var t;const r=(t=this._instance)===null||t===void 0||(t=t.persistence)===null||t===void 0?void 0:t.props[this.Uc()];if(r&&r!==e){const n=this.qc(),i=this.Bc();n.length>0&&(this.Lc([]),n.filter(s=>We(i[s])).forEach(s=>this.Ac(s))),this.jc(),this.Hc()}}getActivatedIds(){return[...new Set([...this.Dc(),...this.lc])].filter(e=>!this.Gc(e))}dispose(){var e,t,r;(e=this.dc)===null||e===void 0||e.call(this),this.dc=void 0,(t=this.tc)===null||t===void 0||t.call(this),this.tc=void 0,(r=this.$c)===null||r===void 0||r.dispose(),this.$c=void 0}reset(){this.lc=[],this.qc().length>0&&this.Lc([]),this.jc(),this.Hc()}getEventToItemsMap(){return this.uc}Zc(){return this.$c}},JS=class extends ZS{constructor(e){super(e)}zc(){return Rv}Uc(){return Av}gc(){return Iv}mc(e){var t;(t=this._instance)===null||t===void 0||(t=t.persistence)===null||t===void 0||t.register({$surveys_activated_timestamps:e})}yc(){var e;(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0||e.unregister("$surveys_activated_timestamps")}fc(e){var t;let r;this.kc(i=>{r=i.find(s=>s.id===e)});const n=r==null||(t=r.appearance)===null||t===void 0?void 0:t.surveyPopupDelaySeconds;return We(n)&&n>0}Qc(){return cr.SHOWN}kc(e){var t;(t=this._instance)===null||t===void 0||t.getSurveys(e)}Ac(e){var t;(t=this._instance)===null||t===void 0||t.cancelPendingSurvey(e)}Ic(){return Te}Lc(e){var t;(t=this._instance)===null||t===void 0||(t=t.persistence)===null||t===void 0||t.register({$surveys_activated:e})}Wc(e){var t;(t=this._instance)===null||t===void 0||(t=t.persistence)===null||t===void 0||t.register({$surveys_activated_session:e})}Vc(){var e;(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0||e.unregister("$surveys_activated_session")}Gc(){return!1}Mc(e,t){let r;return this.kc(n=>{r=n.find(i=>i.id===t)}),!r||(function(n){var i;return Rg(n)&&!!(!((i=n.conditions)===null||i===void 0||(i=i.events)===null||i===void 0)&&i.repeatedActivation)||n.schedule==="always"})(r)?e===cr.SHOWN?"consume":"ignore":e===cr.SHOWN?"persist":e===cr.DISMISSED||e===cr.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}},KS=class{constructor(e){this._instance=e}initialize(){}get(e){if(typeof e=="string")return this._instance.get_property(e);const t={};for(const r of e){const n=this._instance.get_property(r);O(n)||(t[r]=n)}return t}set(e,t){this._instance.register(typeof e=="string"?{[e]:t}:e)}remove(e){typeof e!="string"?e.forEach(t=>this._instance.unregister(t)):this._instance.unregister(e)}},YS=class{constructor(e){this._instance=e}get(){const e=this._instance.config;return{disableSurveys:e.disable_surveys,cookielessMode:!!e.cookieless_mode,advancedEnableSurveys:e.advanced_enable_surveys,requestTimeoutMs:e.surveys_request_timeout_ms}}isOptedOut(){return this._instance.consent.isOptedOut()}isCapturing(){return this._instance.is_capturing()}getExtensions(){const e=te?.__PosthogExtensions__;if(!e)return;const{generateSurveys:t,loadExternalDependency:r}=e;return{generateSurveys:t?n=>t(this._instance,n):void 0,loadExternalDependency:r?n=>r(this._instance,"surveys",n):void 0}}createEventReceiver(){return new JS(this._instance)}},XS=A?.location?So(A.location.hash,"__posthog")||So(location.hash,"state"):null,Ch="_postHogToolbarParams",Ph=Be("[Toolbar]"),Oh=Be("[FeatureFlags]"),QS=class{constructor(e,t=!1){this.Jc=!1,this.update(e,t)}update(e,t){this.Kc=((r,n)=>{var i,s,o,a,c,l,u,h;return{bootstrap:{featureFlags:(i=(s=r.bootstrap)===null||s===void 0?void 0:s.featureFlags)!==null&&i!==void 0?i:void 0,featureFlagPayloads:(o=(a=r.bootstrap)===null||a===void 0?void 0:a.featureFlagPayloads)!==null&&o!==void 0?o:void 0},remoteRequestsDisabled:n,featureFlagsDisabled:!!r.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!r.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!r.advanced_feature_flags_dedup_per_session,cacheTtlMs:r.feature_flag_cache_ttl_ms,refreshIntervalMs:(c=r.remote_config_refresh_interval_ms)!==null&&c!==void 0?c:3e5,idleRefreshBackoff:O(r.remote_config_refresh_interval_ms),requestTimeoutMs:r.feature_flag_request_timeout_ms,requestMaxRetries:Math.max(0,(l=r.feature_flag_request_max_retries)!==null&&l!==void 0?l:1),compression:r.disable_compression?void 0:"best-available",evaluationContexts:(u=(h=r.evaluation_contexts)!==null&&h!==void 0?h:r.evaluation_environments)!==null&&u!==void 0?u:[],flagKeys:ce(r.flag_keys)?r.flag_keys:void 0}})(e,t),!e.evaluation_environments||e.evaluation_contexts||this.Jc||(Oh.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.Jc=!0),O(e.flag_keys)||ce(e.flag_keys)||Oh.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.Kc}},xh=Be("[FeatureFlags]"),Jr=Be("[FeatureFlags]",{debugEnabled:!0}),fc=`" failed. Feature flags didn't load in time.`,eE=[502,504],Mh=["click","keydown","wheel","touchstart","pointerdown"],Lh="connection_error",Dh=e=>{const t={};for(let r=0;e.length>r;r++)t[e[r]]=!0;return t},Nh=e=>{const t={};for(const[r,n]of Ws(e||{}))n&&(t[r]=n);return t},zh=e=>ci(e)&&(e.name==="RangeError"&&e.message.indexOf("Maximum call stack size exceeded")===0||e.name==="InternalError"&&e.message==="too much recursion"),Pt=Be("[Error tracking]"),cl="webkit-masked-url:",tE=[{value:"isolatedAPI.contexts.topHostname",exact:!1},{value:"No response from target",exact:!0}],rE=["chrome-extension://","moz-extension://","safari-extension:","safari-web-extension:",cl],nE=["__firefox__","__gCrWeb"],Uh="Refusing to render web experiment since the viewer is a likely bot",iE={icontains:(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())>-1,not_icontains:(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())===-1,regex:(e,t)=>Ao(t,e),not_regex:(e,t)=>!Ao(t,e),exact:(e,t)=>t===e,is_not:(e,t)=>t!==e},Rt=Be("[Conversations]"),Kr="Conversations not available yet.";function Fh(e,t){var r,n,i,s,o,a,c;const l=(r=e?.flushIntervalMs)!==null&&r!==void 0?r:3e3,u=(n=e?.maxBufferSize)!==null&&n!==void 0?n:100,h=t?.consoleCapture?void 0:(i=e?.maxLogsPerInterval)!==null&&i!==void 0?i:1e3,d=O(h)?Math.max(u,2048):Math.max(u,h),p=b(b({},(function(){let f="",v="";try{const m=nt?.userAgent;m&&([f,v]=Kf(m))}catch{}return(function(m,_){const w=(function(S){if(S)return{}.hasOwnProperty.call(Md,S)?Md[S]:S})(m);return b(b({},w?{"os.name":w}:{}),_?{"os.version":_}:{})})(f,v)})()),e?.resourceAttributes);return{serviceName:(s=(o=p?.["service.name"])!==null&&o!==void 0?o:e?.serviceName)!==null&&s!==void 0?s:t?.serviceNameDefault,serviceVersion:(a=p?.["service.version"])!==null&&a!==void 0?a:e?.serviceVersion,environment:(c=p?.["deployment.environment"])!==null&&c!==void 0?c:e?.environment,resourceAttributes:p,beforeSend:e?.beforeSend,flushIntervalMs:l,maxBufferSize:u,maxQueueSize:d,maxBatchRecordsPerPost:100,rateCapWindowMs:l,maxLogsPerInterval:h,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}}var sE=["debug","log","warn","error","info"],oE=e=>{for(;e?.__rrweb_original__;)e=e.__rrweb_original__;return e},qh="console",Og="__posthogHandledLogsRequestError",vc=(e,t)=>{const r=e instanceof Error?e:new Error(t);return r[Og]=!0,r},jh=e=>!!e&&typeof e=="object"&&e[Og]===!0,Io=Be("[NetworkMetrics]"),pu=()=>{var e;return!(A==null||(e=A.performance)===null||e===void 0)&&e.now?A.performance.now():Date.now()},aE={"http:":80,"https:":443},cE=new Set(["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"]),xg=(e,t)=>{var r;const n=String(t);return{method:String(e).toUpperCase(),url:((r=Lr(n))===null||r===void 0?void 0:r.href)||n}},ll=(e,t,r,n,i,s,o=!1)=>{try{var a,c;const l=i();if(!l)return;const u=r||void 0,h=pu()-n,d=Lr(t.url);if(d&&d.protocol!=="http:"&&d.protocol!=="https:")return;const p={url:d?.href||t.url,method:t.method},f=rt(l.name)?l.name(p):ye(l.name)?l.name:"http.client.request.duration";if(!f)return;const v=o&&!u?void 0:((_,w)=>_?400>_?void 0:String(_):w?.name||"_OTHER")(u,s),m=b(b(b(b(b({},(_=>{const w=cE.has(_)?_:"_OTHER";return b({"http.request.method":w},w==="_OTHER"&&_!==w?{"http.request.method_original":_}:{})})(p.method)),d?(_=>{return{"server.address":_.hostname.startsWith("[")&&_.hostname.endsWith("]")?_.hostname.slice(1,-1):_.hostname,"server.port":Number(_.port)||aE[_.protocol],"url.scheme":_.protocol.slice(0,-1),"url.template":(w=_.pathname,w.split("/").map(S=>(T=>/^\d+$/.test(T)||T.length>=8&&/^[0-9a-f-]*\d[0-9a-f-]*$/i.test(T))(S)?":id":S).join("/"))};var w})(d):{}),u?{"http.response.status_code":u}:{}),v?{"error.type":v}:{}),(a=l.attributes)===null||a===void 0?void 0:a.call(l,p,{status:u,durationMs:h}));(c=e.metrics)===null||c===void 0||c.histogram(f,h,{unit:"ms",attributes:m})}catch(l){Io.error("Failed to record network metric",l)}},Mg=()=>{},lE=(e,t)=>rt(A?.fetch)?rs(A,"fetch",r=>function(...n){const i=pu(),s=r.apply(this,n);if(!t())return s;try{var o,a,c;const[l,u]=n,h=xg((o=(a=u?.method)!==null&&a!==void 0?a:l?.method)!==null&&o!==void 0?o:"GET",(c=l?.url)!==null&&c!==void 0?c:l);return s.then(d=>(ll(e,h,d?.status,i,t,void 0,!0),d),d=>{throw ll(e,h,void 0,i,t,d),d})}catch(l){return Io.error("Failed to observe fetch",l),s}}):Mg,uE=(e,t)=>{var r;const n=A==null||(r=A.XMLHttpRequest)===null||r===void 0?void 0:r.prototype;if(!n)return Mg;const i=new WeakMap,s=rs(n,"open",a=>function(...c){try{hg.has(this)||i.set(this,xg(c[0],c[1]))}catch(l){Io.error("Failed to observe XHR open",l)}return a.apply(this,c)}),o=rs(n,"send",a=>function(...c){let l;try{const u=i.get(this);if(u&&t()){const h=pu();l=()=>{this.removeEventListener("loadend",l),ll(e,u,this.status,h,t)},Ie(this,"loadend",l)}}catch(u){Io.error("Failed to observe XHR send",u)}try{return a.apply(this,c)}catch(u){throw l&&this.removeEventListener("loadend",l),u}});return()=>{s(),o()}},Xo={featureFlags:class{constructor(e){this.name="featureFlags",this.Xc=!1,this.featureFlagEventHandlers=[],this.$=xh,this.Yc={},this.td={},this.ed=[],this.nd=!1,this.sd=!1,this.rd=0,this.od=!1,this.ad=!1,this.ld=!1,this.ud=!1,this.hd=0,this.dd=!1,this.an=()=>{const t=this.vd();this.hd=0,t&&this.reloadFeatureFlags()},this.fd=()=>{var t,r;const n=this.pd,i=(t=this.gd)!==null&&t!==void 0?t:n;O(n)||O(i)||this.Rr.remoteRequestsDisabled||!N||N.visibilityState==="hidden"||Date.now()-((r=this.md)!==null&&r!==void 0?r:0)<i||(this.gd=this.dd||!this.Rr.idleRefreshBackoff?n:Math.min(2*i,36e5),this.dd=!1,this.reloadFeatureFlags(),this.yd())},this.bd=()=>{this.dd&&this.gd===this.pd||this._d()},this.ln=()=>{N?.visibilityState==="visible"&&this._d()},"get"in e?this.So=e:(this._instance=e,this.wd=new QS(e.config,e.nl()),this.So=this.wd)}updateConfig(e,t){var r;(r=this.wd)===null||r===void 0||r.update(e,t),this.wo&&this.kd()}setup(e){return this.Fh=e,this.$=e.logger.createLogger("[FeatureFlags]"),Pg(e.kv.initialize(),()=>{this.Fh===e&&(this.Fh=void 0,this.wo=e,this.Sd(e))})}Sd(e){var t;if(this.wo===e)return A&&Ie(A,"online",this.an),this.kd(),this.xd=e.registerDynamicEventProperties(()=>this.Cd()?this.Yc:this.td),this.$d=(t=this._instance)===null||t===void 0||(t=t.persistence)===null||t===void 0?void 0:t.onCrossTabFeatureFlagChange(()=>{this.Td(),this.Id(),this.Md()}),this.Id(),this.initialize()}_d(){this.dd=!0,this.gd=this.pd,this.fd()}kd(){const e=this.Rr.refreshIntervalMs,t=!this.Rr.remoteRequestsDisabled&&N&&!O(e)&&e>0?e:void 0;this.Rr.idleRefreshBackoff||(this.gd=t),t!==this.pd&&(this.Ed(),O(t)||(this.pd=t,this.gd=t,this.yd(),N!=null&&N.addEventListener&&(Ie(N,Yi,this.ln),Pn(Mh,r=>{Ie(N,r,this.bd,{capture:!0})}))))}yd(){O(this.pd)||(O(this.Pd)||clearInterval(this.Pd),this.md=Date.now(),this.Pd=setInterval(this.fd,this.pd))}Ed(){var e;O(this.Pd)||(clearInterval(this.Pd),this.Pd=void 0,N==null||(e=N.removeEventListener)===null||e===void 0||e.call(N,"visibilitychange",this.ln),Pn(Mh,t=>{var r;N==null||(r=N.removeEventListener)===null||r===void 0||r.call(N,t,this.bd,{capture:!0})})),this.pd=void 0,this.gd=void 0,this.dd=!1,this.md=void 0}destroy(){this.Rd()}dispose(){this.Rd()}Rd(){var e,t;this.Ed(),this.rd++,this.ad=!1,this.Fh=void 0,this.wo&&(this.Ad(),(e=this.xd)===null||e===void 0||e.dispose(),this.xd=void 0,(t=this.$d)===null||t===void 0||t.call(this),this.$d=void 0,this.ed=[],A?.removeEventListener("online",this.an),this.wo=void 0)}get Rr(){return this.So.get()}Fd(e){var t;return this.Od&&e in this.Od?this.Od[e]:(t=this.wo)===null||t===void 0?void 0:t.kv.get(e)}Td(){return!!this.Od&&(this.Od=void 0,!0)}Dd(){var e;return!O((e=this.wo)===null||e===void 0?void 0:e.kv.get("$enabled_feature_flags"))&&this.Td()}At(e){this.Ld(()=>{var t;return(t=this.wo)===null||t===void 0?void 0:t.kv.set(e)})}Nd(e,t,r){var n;if(!(!((n=this._instance)===null||n===void 0)&&n.persistence)||!e.$enabled_feature_flags)return;const i=this.Fd("$enabled_feature_flags")||{},s=e.$enabled_feature_flags||{},o=t.flags||t.featureFlags,a=t.flags?Object.entries(t.flags).filter(([,_])=>!_?.failed).map(([_])=>_):[],c=!!t.errorsWhileComputingFlags&&!!t.flags,l=c?a:r&&!ce(o)?Object.keys(o||{}):Array.from(new Set([...Object.keys(i),...Object.keys(s)])),u=this.Fd("$feature_flag_payloads")||{},h=e.$feature_flag_payloads||{},d=c||r?l:Array.from(new Set([...Object.keys(u),...Object.keys(h)])),p=!c&&!r,f=!!p||l,v=!!p||d,m={[or]:f,[xt]:f,[Sr]:v};e.$feature_flag_details&&(m[un]=f);for(const _ of[dn,Tr,zi])O(e[_])||(m[_]=!0);this._instance.persistence.markCrossTabFeatureFlagChanges(m)}Lt(e){this.Ld(()=>{var t;return(t=this.wo)===null||t===void 0?void 0:t.kv.remove(e)})}Ld(e){try{e()}catch(t){this.$.error("Failed to update feature flag persistence",t)}}Id(){const e={};for(const n of[or,Sr,dn,Ht]){const i=this.Fd(n);O(i)||(e[n]=i)}this.Yc=e;const t=b({},e),r=this.Fd(xt);if(r)for(const[n,i]of Object.entries(r))t[`$feature/${n}`]=i;this.td=t}Cd(){const e=this.Rr.cacheTtlMs;if(!e||0>=e)return!1;const t=this.Fd(Tr);return typeof t!="number"||Date.now()-t>e}qd(){return!!this.Cd()&&(this.ud||this.sd||(this.ud=!0,this.$.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}jd(){const e=this.Rr.evaluationContexts;return e?.length?e.filter(t=>{const r=t&&typeof t=="string"&&t.trim().length>0;return r||this.$.error("Invalid evaluation context found:",t,"Expected non-empty string"),r}):[]}Bd(){const e=this.Rr.flagKeys;if(!O(e))return e.filter(t=>{const r=t&&typeof t=="string"&&t.trim().length>0;return r||this.$.error("Invalid flag key found:",t,"Expected non-empty string"),r})}initialize(){var e,t;const r=this.Rr,n=(e=(t=r.bootstrap)===null||t===void 0?void 0:t.featureFlags)!==null&&e!==void 0?e:{};if(Object.keys(n).length){var i,s;const o=(i=(s=r.bootstrap)===null||s===void 0?void 0:s.featureFlagPayloads)!==null&&i!==void 0?i:{},a=Object.keys(n).filter(l=>!O(n[l])).reduce((l,u)=>(l[u]=n[u],l),{}),c=Object.keys(o).filter(l=>a[l]).reduce((l,u)=>(l[u]=o[u],l),{});return this.Hd({featureFlags:a,featureFlagPayloads:c},void 0,{persist:!1})}}updateFlags(e,t,r){var n,i;const s=r?.merge&&(n=this.Fd("$enabled_feature_flags"))!==null&&n!==void 0?n:{},o=r?.merge&&(i=this.Fd("$feature_flag_payloads"))!==null&&i!==void 0?i:{},a=b(b({},s),e),c=b(b({},o),t),l={};for(const[u,h]of Object.entries(a))l[u]={key:u,enabled:$d(h),variant:Cd(h),reason:void 0,metadata:O(c?.[u])?void 0:{id:0,version:void 0,description:void 0,payload:c[u]}};this.Hd({flags:l})}get hasLoadedFlags(){return this.nd}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){const e=this.Fd(un),t=this.Fd(Ht),r=this.Fd(en);if(!r&&!t)return e||{};const n=Le({},e||{}),i=[...new Set([...Object.keys(r||{}),...Object.keys(t||{})])];for(const a of i){var s;const c=n[a],l=t?.[a],u=O(l)?(s=c?.enabled)!==null&&s!==void 0&&s:!!l,h=O(l)?c?.variant:typeof l=="string"?l:void 0,d=r?.[a],p=b(b({},c),{},{enabled:u,variant:u?h??c?.variant:void 0});var o;u!==c?.enabled&&(p.original_enabled=c?.enabled),h!==c?.variant&&(p.original_variant=c?.variant),d&&(p.metadata=b(b({},c?.metadata),{},{payload:d,original_payload:c==null||(o=c.metadata)===null||o===void 0?void 0:o.payload})),n[a]=p}return this.Xc||(this.$.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:r,finalDetails:n}),this.Xc=!0),n}getAllFeatureFlags(){const e=this.getFlagVariants(),t=this.getFlagPayloads();return Object.keys(e).map(r=>{const n=e[r];return{key:r,enabled:$d(n),variant:Cd(n),payload:Td(t[r])}})}getFlagVariants(){const e=this.Fd(xt),t=this.Fd(Ht);if(!t)return e||{};const r=Le({},e||{}),n=Object.keys(t);for(let i=0;n.length>i;i++)r[n[i]]=t[n[i]];return this.Xc||(this.$.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:t,finalFlags:r}),this.Xc=!0),r}getFlagPayloads(){const e=this.Fd(Sr),t=this.Fd(en);if(!t)return e||{};const r=Le({},e||{}),n=Object.keys(t);for(let i=0;n.length>i;i++)r[n[i]]=t[n[i]];return this.Xc||(this.$.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:t,finalPayloads:r}),this.Xc=!0),r}reloadFeatureFlags(){this.od||this.Rr.featureFlagsDisabled||this.vd()||(this.sd&&(this.ad=!0),this.zd||(this.ed.slice().forEach(e=>{try{e()}catch(t){this.$.error("Error while running feature flags reloading callback",t)}}),this.zd=setTimeout(()=>{this.Ud()},5)))}Ad(){clearTimeout(this.zd),this.zd=void 0}onReloading(e){return this.ed.push(e),()=>{this.ed=this.ed.filter(t=>t!==e)}}ensureFlagsLoaded(){this.nd||this.sd||this.zd||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.od=e}resetFlagCallReported(){this.Lt(Rr)}Ud(e){this.Ad();const t=this.wo;if(!t||this.Rr.remoteRequestsDisabled||this.vd())return;if(this.sd)return void(this.ad=!0);const r={token:t.projectToken,distinct_id:t.distinctId,groups:t.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:b(b(b({},t.initialPersonProperties),this.Fd("$stored_person_properties")||{}),{},{$lib:t.library.name,$lib_version:t.library.version}),group_properties:this.Fd(kr),timezone:sg()};O(t.deviceId)||(r.$device_id=t.deviceId),(e!=null&&e.disableFlags||this.Rr.featureFlagsDisabled)&&(r.disable_flags=!0);const n=this.jd();n.length&&(r.evaluation_contexts=n);const i=this.Bd();O(i)||(r.flag_keys=i);const s=this.Rr.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.rd;this.sd=!0;const c=()=>{this.ad&&(this.ad=!1,this.Ud())},l=f=>{var v,m;const _=(v=f.json)!==null&&v!==void 0?v:{},w=f.statusCode!==200;if(this.sd=!1,a!==this.rd)return void c();if(this.Wd(f.statusCode),w||this.ad||(this.$anon_distinct_id=void 0),r.disable_flags&&!this.ad)return;this.ld=!w;const S=[];f.error?S.push(f.error instanceof Error&&f.error.name==="AbortError"?"timeout":f.error instanceof Error?Lh:"unknown_error"):f.statusCode!==200&&S.push(`api_error_${f.statusCode}`),_.errorsWhileComputingFlags&&S.push("errors_while_computing_flags");const T=!!(!((m=_.quotaLimited)===null||m===void 0)&&m.includes("feature_flags"));T&&S.push("quota_limited"),this.At({[Ki]:S}),T?this.$.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):r.disable_flags||this.Hd(_,w,{partialResponse:s}),c()},u=f=>{this.sd=!1,a===this.rd&&(this.At({[Ki]:[Lh]}),this.$.error("Feature flag request failed",f),this.Dd()&&this.Md(!0)),c()};let h=this.Rr.requestMaxRetries;const d=()=>h>0&&a===this.rd,p=()=>{if(a!==this.rd||!this.wo||this.Rr.remoteRequestsDisabled)return this.sd=!1,void c();try{t.sendRequest(o,{target:"flags",method:"POST",body:r,compression:this.Rr.compression,sentAt:"body",timeoutMs:this.Rr.requestTimeoutMs}).then(f=>{if((v=>eE.includes(v.statusCode)||(m=>m.statusCode===0&&m.error instanceof Error&&m.error.name==="AbortError")(v))(f)&&d())return h--,void setTimeout(p,500);l(f)}).catch(u)}catch(f){u(f)}};p()}vd(){return Kv(this.hd,3)}Wd(e){this.hd=Yv(e,this.hd,3,()=>this.$.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes."))}getFeatureFlag(e,t={}){var r;if(t.fresh&&!this.ld)return;if(!(this.nd||this.getFlags()&&this.getFlags().length>0))return void this.$.warn('getFeatureFlag for key "'+e+fc);if(this.qd())return;const n=this.getFeatureFlagResult(e,t);return(r=n?.variant)!==null&&r!==void 0?r:n?.enabled}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){const t=this.getFeatureFlagResult(e,{send_event:!1});return t?.payload}getFeatureFlagResult(e,t={}){if(t.fresh&&!this.ld)return;if(!(this.nd||this.getFlags()&&this.getFlags().length>0))return void this.$.warn('getFeatureFlagResult for key "'+e+fc);if(this.qd())return;const r=this.getFlagVariants(),n=e in r,i=r[e],s=this.getFlagPayloads()[e],o=String(i),a=this.Fd("$feature_flag_request_id")||void 0,c=this.Fd("$feature_flag_evaluated_at")||void 0;let l,u=this.Fd("$flag_call_reported")||{};if(this.Rr.deduplicateCallsPerSession){var h;const q=(h=this.wo)===null||h===void 0?void 0:h.session.sessionId,X=this.Fd(Ii);q&&q!==X&&(u={},l=q)}if(t.send_event||!("send_event"in t))if(e in u&&u[e].includes(o))l&&this.At({[Rr]:u,[Ii]:l});else{var d,p,f,v,m,_,w,S,T,I,C,M;ce(u[e])?u[e].push(o):u[e]=[o],this.At(b({[Rr]:u},l?{[Ii]:l}:{}));const q=this.getFeatureFlagDetails(e),X=[...(d=this.Fd("$feature_flag_errors"))!==null&&d!==void 0?d:[]];O(i)&&X.push("flag_missing");const ee={$feature_flag:e,$feature_flag_response:i,$feature_flag_payload:s??null,$feature_flag_request_id:a,$feature_flag_evaluated_at:c,$feature_flag_bootstrapped_response:(p=(f=this.Rr.bootstrap)===null||f===void 0||(f=f.featureFlags)===null||f===void 0?void 0:f[e])!==null&&p!==void 0?p:null,$feature_flag_bootstrapped_payload:(v=(m=this.Rr.bootstrap)===null||m===void 0||(m=m.featureFlagPayloads)===null||m===void 0?void 0:m[e])!==null&&v!==void 0?v:null,$used_bootstrap_value:!this.ld};O(q==null||(_=q.metadata)===null||_===void 0?void 0:_.has_experiment)||(ee.$feature_flag_has_experiment=q.metadata.has_experiment),O(q==null||(w=q.metadata)===null||w===void 0?void 0:w.version)||(ee.$feature_flag_version=q.metadata.version);const k=(S=q==null||(T=q.reason)===null||T===void 0?void 0:T.description)!==null&&S!==void 0?S:q==null||(I=q.reason)===null||I===void 0?void 0:I.code;var L;k&&(ee.$feature_flag_reason=k),q!=null&&(C=q.metadata)!==null&&C!==void 0&&C.id&&(ee.$feature_flag_id=q.metadata.id),O(q?.original_variant)&&O(q?.original_enabled)||(ee.$feature_flag_original_response=O(q.original_variant)?q.original_enabled:q.original_variant),q!=null&&(M=q.metadata)!==null&&M!==void 0&&M.original_payload&&(ee.$feature_flag_original_payload=q==null||(L=q.metadata)===null||L===void 0?void 0:L.original_payload),X.length&&(ee.$feature_flag_error=X.join(",")),this.Vd(ee)}else l&&this.At({[Rr]:u,[Ii]:l});return n?{key:e,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:Td(s)}:void 0}Vd(e){try{var t;(t=this.wo)===null||t===void 0||t.capture("$feature_flag_called",e)}catch(r){this.$.error("Failed to capture feature flag call",r)}}getRemoteConfigPayload(e,t){this.Gd(e,t)}Gd(e,t){var r=this;return Ue(function*(){const n=r.wo;if(!n)return;const i={distinct_id:n.distinctId,token:n.projectToken,person_properties:{$lib:n.library.name,$lib_version:n.library.version}},s=r.jd();s.length&&(i.evaluation_contexts=s);const o=r.Bd();let a;O(o)||(i.flag_keys=o);try{var c;const l=(c=(yield n.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:i,compression:r.Rr.compression,sentAt:"body",timeoutMs:r.Rr.requestTimeoutMs})).json)===null||c===void 0?void 0:c.featureFlagPayloads;a=l?.[e]||void 0}catch(l){r.$.error("Remote config feature flag request failed",l);return}try{t(a)}catch(l){r.$.error("Remote config feature flag callback failed",l)}})()}isFeatureEnabled(e,t={}){if(t.fresh&&!this.ld)return t.defaultValue;if(!(this.nd||this.getFlags()&&this.getFlags().length>0))return this.$.warn('isFeatureEnabled for key "'+e+fc),t.defaultValue;const r=this.getFeatureFlag(e,t);return O(r)?t.defaultValue:!!r}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(t=>t!==e)}receivedFeatureFlags(e,t,r){this.Hd(e,t,r)}Hd(e,t,r){if(!this.wo)return;this.nd=!0;const n=((i,s={},o={},a={},c,l=xh)=>{const u=((S,T)=>{const I=S.flags;if(I){const C=Object.fromEntries(Object.keys(I).map(L=>{var q;return[L,(q=I[L].variant)!==null&&q!==void 0?q:I[L].enabled]})),M=Object.fromEntries(Object.keys(I).filter(L=>I[L].enabled).filter(L=>{var q;return!O((q=I[L].metadata)===null||q===void 0?void 0:q.payload)}).map(L=>{var q;return[L,(q=I[L].metadata)===null||q===void 0?void 0:q.payload]}));return b(b({},S),{},{featureFlags:C,featureFlagPayloads:M})}return S.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),S})(i,l),h=u.flags,d=u.featureFlags,p=u.featureFlagPayloads;if(!d)return;const f=i.requestId,v=i.evaluatedAt;if(ce(d)){l.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");const S={};if(d)for(let T=0;d.length>T;T++)S[d[T]]=!0;return{[or]:d,[xt]:S,[zi]:!1}}let m=d,_=p,w=h;if(c?.partialResponse){const S=Object.keys(m),T=_||{};m=b(b({},s),m),_=b(b({},o),T),S.forEach(I=>{I in T||_==null||delete _[I]}),w=b(b({},a),w)}else if(i.errorsWhileComputingFlags)if(h){const S=new Set(Object.keys(h).filter(I=>{var C;return!(!((C=h[I])===null||C===void 0)&&C.failed)}));m=b(b({},s),Object.fromEntries(Object.entries(m).filter(([I])=>S.has(I))));const T=Object.fromEntries(Object.entries(_||{}).filter(([I])=>S.has(I)));_=b(b({},o),T),S.forEach(I=>{I in T||_==null||delete _[I]}),w=b(b({},a),Object.fromEntries(Object.entries(w||{}).filter(([I])=>S.has(I))))}else m=b(b({},s),m),_=b(b({},o),_),w=b(b({},a),w);return b(b({[or]:Object.keys(Nh(m)),[xt]:m||{},[Sr]:_||{},[un]:w||{},[zi]:i.minimalFlagCalledEvents===!0},f?{[dn]:f}:{}),v?{[Tr]:v}:{})})(e,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),r,this.$);if(n)if(r?.persist===!1){const i=!O(this.wo.kv.get(xt));this.Od=n,i||this.At(n)}else this.Td(),this.Nd(n,e,!!r?.partialResponse),this.At(n);else t&&this.Dd();t||(this.ud=!1),this.Md(t)}override(e,t=!1){this.$.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:t})}overrideFeatureFlags(e){this.Zd(e)}Zd(e){if(this.wo){if(e===!1)return this.Lt([Ht,en]),this.Md(),void Jr.info("All overrides cleared");if(ce(e))return this.At({[Ht]:Dh(e)}),this.Md(),void Jr.info("Flag overrides set",{flags:e});if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var t;const r=e;this.Xc=!!((t=r.suppressWarning)!==null&&t!==void 0&&t);const n={},i=r.flags,s=r.payloads;i&&(n[Ht]=ce(i)?Dh(i):i),s&&(n[en]=s),Object.keys(n).length&&this.At(n),i===!1&&s===!1?this.Lt([Ht,en]):i===!1?this.Lt(Ht):s===!1&&this.Lt(en),this.Md(),i===!1?Jr.info("Flag overrides cleared"):i&&Jr.info("Flag overrides set",{flags:i}),s===!1?Jr.info("Payload overrides cleared"):s&&Jr.info("Payload overrides set",{payloads:s});return}if(e&&typeof e=="object")return this.At({[Ht]:e}),this.Md(),void Jr.info("Flag overrides set",{flags:e});this.$.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:e})}else this.$.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.nd){const{flags:t,flagVariants:r}=this.Qd();try{e(t,r)}catch(n){this.$.error("Error while running feature flags callback",n)}}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,r){var n;const i=(this.Fd("$early_access_features")||[]).find(l=>l.flagKey===e),s={[`$feature_enrollment/${e}`]:t},o={$feature_flag:e,$feature_enrollment:t,$set:s};i&&(o.$early_access_feature_name=i.name),r&&(o.$feature_enrollment_stage=r);const a=b(b({},this.getFlagVariants()),{},{[e]:t});(n=this._instance)===null||n===void 0||(n=n.persistence)===null||n===void 0||n.markCrossTabFeatureFlagChanges({$active_feature_flags:[e],$enabled_feature_flags:[e],$stored_person_properties:Object.keys(s)}),this.At({[or]:Object.keys(Nh(a)),[xt]:a,[Er]:b(b({},this.Fd("$stored_person_properties")||{}),s)}),this.Md();try{var c;(c=this.wo)===null||c===void 0||c.capture("$feature_enrollment_update",o)}catch(l){this.$.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(e,t=!1,r){const n=this.Fd(Wc);!n||t?this.Jd(e,r):e(n)}Jd(e,t){var r=this;return Ue(function*(){const n=r.wo;if(!n)return;const i=t?`&${t.map(o=>`stage=${o}`).join("&")}`:"";let s;try{const o=yield n.sendRequest(`/api/early_access_features/?token=${n.projectToken}${i}`,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;s=o.json.earlyAccessFeatures,r.At({[Wc]:s})}catch(o){r.$.error("Early access feature request failed",o);return}try{e(s)}catch(o){r.$.error("Early access feature callback failed",o)}})()}Qd(){const e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter(r=>t[r]),flagVariants:Object.keys(t).filter(r=>t[r]).reduce((r,n)=>(r[n]=t[n],r),{})}}Md(e){this.Id();const{flags:t,flagVariants:r}=this.Qd();this.featureFlagEventHandlers.forEach(n=>{try{n(t,r,{errorsLoading:e})}catch(i){this.$.error("Error while running feature flags callback",i)}})}setPersonPropertiesForFlags(e,t=!0){this.Kd(e,t)}Kd(e,t=!0){const r=this.Fd("$stored_person_properties")||{},n=e?.$set||(e?.$set_once?{}:e),i=e?.$set_once,s={};if(i)for(const o in i)({}).hasOwnProperty.call(i,o)&&(o in r||(s[o]=i[o]));this.At({[Er]:b(b(b({},r),s),n)}),t&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(e,t=!0){const r=b({},this.Fd("$stored_person_properties")||{});e.forEach(n=>{delete r[n]}),this.At({[Er]:r}),t&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(e=!0){this.Lt(Er),e&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(e,t=!0){const r=this.Fd("$stored_group_properties")||{},n=b({},r);for(const i of Object.keys(e))n[i]=b(b({},r[i]),e[i]);this.At({[kr]:n}),t&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){const t=this.Fd("$stored_group_properties")||{};this.At({[kr]:b(b({},t),{},{[e]:{}})})}else this.Lt(kr)}reset(){this.rd++,this.ad=!1,this.Yc={},this.td={},this.Od=void 0,this.nd=!1,this.od=!1,this.ld=!1,this.$anon_distinct_id=void 0,this.Ad(),this.Xc=!1,this.hd=0}}},dE={sessionRecording:class{get Rr(){return this._instance.config}get Ml(){return this._instance.persistence}get started(){var e;return!!(!((e=this.Xd)===null||e===void 0)&&e.isStarted)}get status(){var e,t;return this.Yd==="awaiting_config"||this.Yd==="missing_config"?this.Yd:(e=(t=this.Xd)===null||t===void 0?void 0:t.status)!==null&&e!==void 0?e:this.Yd}constructor(e){if(this._instance=e,this._forceAllowLocalhostNetworkCapture=!1,this.Yd=dc,this.tv=void 0,this.ev=!1,this.Xe=(()=>{var t,r;if(!N?.visibilityState||N.visibilityState==="visible")return!0;const n=A==null||(t=A.performance)===null||t===void 0||(r=t.getEntriesByType)===null||r===void 0?void 0:r.call(t,"visibility-state");return!n?.length||n.some(i=>i.name==="visible")})(),this.ln=()=>{var t,r;N?.visibilityState==="visible"&&(this.Xe=!0,(t=this.Xd)===null||t===void 0||(r=t.setDocumentWasEverVisible)===null||r===void 0||r.call(t,!0))},!this._instance.sessionManager)throw Qt.error("started without valid sessionManager"),new Error("[SessionRecording] started without valid sessionManager. This is a bug.");if(this.Rr.cookieless_mode==="always")throw new Error('[SessionRecording] cannot be used with cookieless_mode="always"');N!=null&&N.addEventListener&&Ie(N,"visibilitychange",this.ln)}initialize(){this.startIfEnabledOrStop()}dispose({discardBufferedEvents:e=!1}={}){var t;this.ev=!0,N==null||(t=N.removeEventListener)===null||t===void 0||t.call(N,"visibilitychange",this.ln),e?this.iv(!0):this.stopRecording()}get nv(){var e;const t=!!(!((e=this._instance.get_property("$session_recording_remote_config"))===null||e===void 0)&&e.enabled),r=!this.Rr.disable_session_recording,n=this.Rr.disable_session_recording||this._instance.consent.isOptedOut();return A&&t&&r&&!n}startIfEnabledOrStop(e){var t;if(this.ev||this.nv&&(!((t=this.Xd)===null||t===void 0)&&t.isStarted))return;const r=!O(Object.assign)&&!O(Array.from);this.nv&&r?(this.sv(e),Qt.info("starting")):(this.Yd=dc,this.stopRecording())}sv(e){var t,r;if(this.nv)if(this.Yd!=="awaiting_config"&&this.Yd!=="missing_config"&&(this.Yd=Ih),(te==null||(t=te.__PosthogExtensions__)===null||t===void 0||(t=t.rrweb)===null||t===void 0?void 0:t.record)&&((r=te.__PosthogExtensions__)===null||r===void 0?void 0:r.initSessionRecording))this.rv(e);else{var n,i;const s=this._instance.sessionManager;(n=te.__PosthogExtensions__)===null||n===void 0||(i=n.loadExternalDependency)===null||i===void 0||i.call(n,this._instance,this.ov,o=>{if(!this.ev&&this.nv&&this._instance.sessionManager===s)return o?(this._instance.register_for_session({$sdk_debug_recording_script_not_loaded:!0}),Qt.error("could not load recorder",o)):void this.rv(e);this.Yd="disabled"})}}stopRecording(){var e,t;(e=this.tv)===null||e===void 0||e.call(this),this.tv=void 0,(t=this.Xd)===null||t===void 0||t.stop()}iv(e=!1){var t,r;(t=this.tv)===null||t===void 0||t.call(this),this.tv=void 0,(r=this.Xd)===null||r===void 0||r.discard({discardProducerEvents:e})}av(){var e,t;(e=this.Ml)===null||e===void 0||e.unregister("$session_is_sampled"),(t=this.Ml)===null||t===void 0||t.unregister("$replay_sample_rate")}lv(e,t){if(ge(e))return null;const r=We(e)?e:parseFloat(e);return typeof(n=r)!="number"||!Number.isFinite(n)||0>n||n>1?(Qt.warn(`${t} must be between 0 and 1. Ignoring invalid value:`,e),null):r;var n}uv(e){if(this.Ml){var t,r;const n=this.Ml,i=()=>{var s;const o=e.sessionRecording===!1?void 0:e.sessionRecording,a=this.lv((s=this.Rr.session_recording)===null||s===void 0?void 0:s.sampleRate,"session_recording.sampleRate"),c=this.lv(o?.sampleRate,"remote config sampleRate"),l=a??c;ge(l)&&this.av();const u=o?.minimumDurationMilliseconds;n.register({[Ni]:b(b({cache_timestamp:Date.now(),enabled:!!o},o),{},{networkPayloadCapture:b({capturePerformance:e.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:l,minimumDurationMilliseconds:O(u)?null:u,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};i(),(t=this.tv)===null||t===void 0||t.call(this),this.tv=(r=this._instance.sessionManager)===null||r===void 0?void 0:r.onSessionId(i)}}onRemoteConfig(e){const t=e.ok?e.config:void 0;t&&"sessionRecording"in t?t.sessionRecording===!1?(this.uv(t),this.iv()):(this.uv(t),this.startIfEnabledOrStop()):(this.Yd==="awaiting_config"&&(this.Yd="missing_config",this._instance.register_for_session({[Mv]:!0}),Qt.warn("config refresh failed, recording will not start until page reload")),this.startIfEnabledOrStop())}log(e,t="log"){var r;!((r=this.Xd)===null||r===void 0)&&r.log?this.Xd.log(e,t):Qt.warn("log called before recorder was ready")}get ov(){var e,t;const r=(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0?void 0:e.get_property(Ni);return(r==null||(t=r.scriptConfig)===null||t===void 0?void 0:t.script)||"lazy-recorder"}hv(){const e=this._instance.get_property(Ni);if(!e)return!1;let t;try{t=typeof e=="object"?e:JSON.parse(e)}catch(r){return Qt.warn("persisted remote config for session recording is invalid and will be ignored",r),!1}return!ge(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}rv(e){var t,r,n;if(!this.ev&&this.nv&&this._instance.sessionManager){if(!(!((t=te.__PosthogExtensions__)===null||t===void 0)&&t.initSessionRecording))return Qt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[xv]:!0});var i;if(this.Xd||(this.Xd=(i=te.__PosthogExtensions__)===null||i===void 0?void 0:i.initSessionRecording(this._instance,this.Xe),this.Xd._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.hv()){if(this.Yd==="missing_config"||this.Yd==="awaiting_config")return;this.Yd="awaiting_config",Qt.info("persisted remote config is stale, requesting fresh config before starting"),new ag(this._instance).load();return}this.Yd=Ih,(r=(n=this.Xd).setDocumentWasEverVisible)===null||r===void 0||r.call(n,this.Xe),this.Xd.start(e)}else this.Yd=dc}onRRwebEmit(e){var t,r;(t=this.Xd)===null||t===void 0||(r=t.onRRwebEmit)===null||r===void 0||r.call(t,e)}overrideLinkedFlag(){var e,t;this.Xd||(t=this.Ml)===null||t===void 0||t.register({$replay_override_linked_flag:!0}),(e=this.Xd)===null||e===void 0||e.overrideLinkedFlag()}overrideSampling(){var e,t;this.Xd||(t=this.Ml)===null||t===void 0||t.register({$replay_override_sampling:!0}),(e=this.Xd)===null||e===void 0||e.overrideSampling()}overrideTrigger(e){var t,r;this.Xd||(r=this.Ml)===null||r===void 0||r.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(t=this.Xd)===null||t===void 0||t.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.Xd)===null||e===void 0?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,t){var r;return!!(!((r=this.Xd)===null||r===void 0)&&r.tryAddCustomEvent(e,t))}flushBeforeIdentityReset(){var e,t;(e=this.Xd)===null||e===void 0||(t=e.flushBeforeIdentityReset)===null||t===void 0||t.call(e)}}},hE={autocapture:class extends US{constructor(e){super(new FS(e)),this.instance=e}},historyAutocapture:class{constructor(e){this._instance=e,this.dv=this.vv()}initialize(){this.startIfEnabled()}get isEnabled(){const e=this.fv();return!!(e.path||e.search||this.pv(e))}startIfEnabled(){this.isEnabled&&(j.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}startIfEnabledOrStop(){this.stop(),this.dv=this.vv(),this.startIfEnabled()}stop(){this.gv&&this.gv(),this.gv=void 0,this.mv&&this.mv(),this.mv=void 0,j.info("History API monitoring stopped")}monitorHistoryChanges(){A&&A.history&&(this.yv("pushState"),this.yv("replaceState"),this.bv(),this.pv()&&this._v())}yv(e){var t;if(!A||!((t=A.history[e])===null||t===void 0)&&t.__posthog_wrapped__)return;const r=this;rs(A.history,e,n=>function(i,s,o){n.call(this,i,s,o),r.wv(e)})}vv(){const e=A?.location;if(e?.pathname)return{pathname:e.pathname,search:e.search,hash:e.hash}}fv(){const e=this._instance.config.capture_pageview;return e==="history_change"?{path:!0}:be(e)?e:{}}pv(e=this.fv()){return!!e.hash&&!this._instance.config.disable_capture_url_hashes}Sv(e){const t=this.fv(),r=this.dv;return!(!r||!(t.path&&e.pathname!==r.pathname||t.search&&e.search!==r.search||this.pv(t)&&e.hash!==r.hash))}wv(e){try{const t=this.vv();if(!t)return;this.Sv(t)&&this._instance.capture(su,{navigation_type:e}),this.dv=t}catch(t){j.error(`Error capturing ${e} pageview`,t)}}bv(){if(this.gv)return;const e=()=>{this.wv("popstate")};Ie(A,"popstate",e),this.gv=()=>{A&&A.removeEventListener("popstate",e)}}_v(){if(this.mv)return;const e=()=>{this.wv("hashchange")};Ie(A,"hashchange",e),this.mv=()=>{A&&A.removeEventListener("hashchange",e)}}},heatmaps:class{get Rr(){return this.instance.config}constructor(e){var t;this.xv=!1,this.xo=!1,this.Cv=null,this.instance=e,this.xv=!!(!((t=this.instance.persistence)===null||t===void 0)&&t.props[Hc]),this.rageclicks=new Cg(e.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){let e=5e3;return be(this.Rr.capture_heatmaps)&&this.Rr.capture_heatmaps.flush_interval_milliseconds&&(e=this.Rr.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return ge(this.Rr.capture_heatmaps)?ge(this.Rr.enable_heatmaps)?this.xv:this.Rr.enable_heatmaps:this.Rr.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.xo)return;VS.info("starting..."),this.$v(),this.ln()}else{var e;clearInterval((e=this.Cv)!==null&&e!==void 0?e:void 0),this.Tv(),this.getAndClearBuffer()}}onRemoteConfig(e){if(!e.ok)return;const t=e.config;if(!("heatmaps"in t))return;const r=!!t.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Hc]:r}),this.xv=r,this.startIfEnabled()}getAndClearBuffer(){const e=this.Rt;return this.Rt=void 0,e}Iv(e){hc(e.originalEvent)&&this.Tr(e.originalEvent,"deadclick")}ln(){this.Cv&&clearInterval(this.Cv),this.Cv=N?.visibilityState==="visible"?setInterval(this.bl.bind(this),this.flushIntervalMilliseconds):null}$v(){A&&N&&(this.Mv=this.bl.bind(this),Ie(A,bo,this.Mv),this.Ev=e=>this.Tr(e||A?.event),Ie(N,"click",this.Ev,{capture:!0}),this.Pv=e=>this.Rv(e||A?.event),Ie(N,"mousemove",this.Pv,{capture:!0}),this.Av=new th(this.instance,Gw,this.Iv.bind(this)),this.Av.startIfEnabledOrStop(),this.Fv=this.ln.bind(this),Ie(N,Yi,this.Fv),this.xo=!0)}Tv(){var e;A&&N&&(this.Mv&&A.removeEventListener(bo,this.Mv),this.Ev&&N.removeEventListener("click",this.Ev,{capture:!0}),this.Pv&&N.removeEventListener("mousemove",this.Pv,{capture:!0}),this.Fv&&N.removeEventListener(Yi,this.Fv),clearTimeout(this.Ov),(e=this.Av)===null||e===void 0||e.stop(),this.xo=!1)}Dv(e,t){const r=this.instance.scrollManager.scrollY(),n=this.instance.scrollManager.scrollX(),i=this.instance.scrollManager.scrollElement(),s=(function(o,a,c){let l=o;for(;l&&Kt(l)&&!lt(l,"body");){if(l===c)return!1;let p;try{var u,h,d;p=(u=(h=(d=l.ownerDocument)===null||d===void 0?void 0:d.defaultView)!==null&&h!==void 0?h:A)===null||u===void 0?void 0:u.getComputedStyle(l).position}catch{return!1}if(ue(a,p))return!0;l=Hv(l)}return!1})(Fi(e),["fixed","sticky"],i);return{x:e.clientX+(s?0:n),y:e.clientY+(s?0:r),target_fixed:s,type:t}}Tr(e,t="click"){var r;if(Bd(e.target)||!hc(e))return;const n=this.Dv(e,t);(r=this.rageclicks)!==null&&r!==void 0&&r.isRageClick(e.clientX,e.clientY,new Date().getTime())&&Bv(Fi(e),this.instance.config.rageclick)&&this.Zs(b(b({},n),{},{type:"rageclick"})),this.Zs(n)}Rv(e){!Bd(e.target)&&hc(e)&&(clearTimeout(this.Ov),this.Ov=setTimeout(()=>{this.Zs(this.Dv(e,"mousemove"))},500))}Zs(e){if(!A)return;const t=this.Rr.disable_capture_url_hashes?Mr(A.location.href):A.location.href,r=this.Rr.custom_personal_data_properties,n=this.Rr.mask_personal_data_properties?[...ei,...r||[]]:[],i=es(t,n,ts);this.Rt=this.Rt||{},this.Rt[i]||(this.Rt[i]=[]),this.Rt[i].push(e)}bl(){this.Rt&&!_t(this.Rt)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:th,webVitalsAutocapture:class{constructor(e){var t;this._instance=e,this.xv=!1,this.xo=!1,this.Rt={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.Lv=()=>{clearTimeout(this.Nv),this.Nv=void 0,this.Rt.metrics.length!==0&&(this._instance.capture("$web_vitals",b({$current_url:this.Rt.url},this.Rt.metrics.reduce((r,n)=>b(b({},r),{},{[`$web_vitals_${n.name}_event`]:b({},n),[`$web_vitals_${n.name}_value`]:n.value}),{}))),this.Rt={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.qv=r=>{var n;if(this.Rt=this.Rt||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},ge(r?.name)||ge(r?.value))return void Zr.error("Invalid metric received",r);const i=typeof r.navigationURL=="string"?r.navigationURL:void 0,s=this.jv(i);if(O(s))return;const o=We(r.navigationId)||typeof r.navigationId=="string"?`navigation:${r.navigationId}`:`url:${s}`;if(this.Bv&&r.value>=this.Bv)return void Zr.error("Ignoring metric with value >= "+this.Bv,r);this.Rt.navigationKey!==o&&(this.Lv(),this.Nv=setTimeout(this.Lv,this.flushToCaptureTimeoutMs)),O(this.Rt.navigationKey)&&(this.Rt.navigationKey=o,this.Rt.url=s),this.Rt.firstMetricTimestamp=O(this.Rt.firstMetricTimestamp)?Date.now():this.Rt.firstMetricTimestamp;const a=(n=this._instance.sessionManager)===null||n===void 0?void 0:n.checkAndGetSessionAndWindowId(!0),c=b(b(b({},r),i?{navigationURL:s}:{}),{},{$current_url:s,timestamp:Date.now()});if(delete c.entries,be(r.attribution)&&this.attributionMetrics.indexOf(r.name)>-1){const l={};for(const u of HS){const h=u==="url"&&typeof r.attribution[u]=="string"?this.jv(r.attribution[u]):r.attribution[u];O(h)||(l[u]=h)}c.attribution=l}else delete c.attribution;O(a)||(c.$session_id=a.sessionId,c.$window_id=a.windowId),this.Rt.metrics.push(c),this.Rt.metrics.length===this.allowedMetrics.length&&this.Lv()},this.Hv=()=>{if(this.xo)return;let r,n,i,s,o=!1;const a=te.__PosthogExtensions__,c=a?.postHogWebVitalsCallbacksByFlavor,l=c?.[this.zv]||(this.zv==="web-vitals"&&O(c)?a?.postHogWebVitalsCallbacks:void 0);if(!O(l)){const d=l.withoutAttribution,p=this.attributionMetrics;o=!O(d),r=p.indexOf("LCP")>-1?l.onLCP:d?.onLCP||l.onLCP,n=p.indexOf("CLS")>-1?l.onCLS:d?.onCLS||l.onCLS,i=p.indexOf("FCP")>-1?l.onFCP:d?.onFCP||l.onFCP,s=p.indexOf("INP")>-1?l.onINP:d?.onINP||l.onINP}if(!(r&&n&&i&&s))return void Zr.error("web vitals callbacks not loaded - not starting");const u={reportSoftNavs:this.useSoftNavs},h=o&&this.attributionMetrics.indexOf("INP")>-1?b(b({},u),{},{includeProcessedEventEntries:!1}):u;this.allowedMetrics.indexOf("LCP")>-1&&r(this.qv.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&n(this.qv.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&i(this.qv.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.qv.bind(this),h),this.xo=!0},this.xv=!!(!((t=this._instance.persistence)===null||t===void 0)&&t.props[Gc]),this.startIfEnabled()}get Uv(){return this._instance.config.capture_performance}get allowedMetrics(){var e,t;const r=be(this.Uv)?(e=this.Uv)===null||e===void 0?void 0:e.web_vitals_allowed_metrics:void 0;return ge(r)?((t=this._instance.persistence)===null||t===void 0?void 0:t.props.$web_vitals_allowed_metrics)||Ah:r}get flushToCaptureTimeoutMs(){return(be(this.Uv)?this.Uv.web_vitals_delayed_flush_ms:void 0)||5e3}get attributionMetrics(){const e=be(this.Uv)?this.Uv.web_vitals_attribution:void 0;return gt(e)?e?Ah:[]:ce(e)?e:jS}get useAttribution(){return this.attributionMetrics.length>0}get useSoftNavs(){const e=be(this.Uv)?this.Uv.__preview_web_vitals_soft_navs:void 0;return e!=null&&e}get Bv(){const e=be(this.Uv)&&We(this.Uv.__web_vitals_max_value)?this.Uv.__web_vitals_max_value:Rh;return e>0&&6e4>=e?Rh:e}get isEnabled(){const e=je?.protocol;if(e!=="http:"&&e!=="https:")return Zr.info("Web Vitals are disabled on non-http/https protocols"),!1;const t=be(this.Uv)?this.Uv.web_vitals:gt(this.Uv)?this.Uv:void 0;return gt(t)?t:this.xv}startIfEnabled(){this.isEnabled&&!this.xo&&(Zr.info("enabled, starting..."),this.zo(this.Hv))}onRemoteConfig(e){if(!e.ok)return;const t=e.config;if(!("capturePerformance"in t))return;const r=be(t.capturePerformance)&&!!t.capturePerformance.web_vitals,n=be(t.capturePerformance)?t.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Gc]:r}),this._instance.persistence.register({[Sv]:n})),this.xv=r,this.startIfEnabled()}get zv(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}zo(e){var t;const r=te.__PosthogExtensions__,n=this.zv,i=r?.postHogWebVitalsCallbacksByFlavor;i?.[n]||n==="web-vitals"&&O(i)&&r?.postHogWebVitalsCallbacks?e():r==null||(t=r.loadExternalDependency)===null||t===void 0||t.call(r,this._instance,n,s=>{s?Zr.error("failed to load script",s):e()})}jv(e){const t=e||A?.location.href;if(!t)return void Zr.error("Could not determine current URL");const r=this._instance.config.disable_capture_url_hashes?Mr(t):t,n=this._instance.config.custom_personal_data_properties,i=this._instance.config.mask_personal_data_properties?[...ei,...n||[]]:[];return es(r,i,ts)}}},pE={exceptionObserver:class{constructor(e){var t;this.Hv=()=>{var r;if(!A||!this.isEnabled||!(!((r=te.__PosthogExtensions__)===null||r===void 0)&&r.errorWrappingFunctions))return;const n=te.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,i=te.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=te.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Wv&&this.Rr.capture_unhandled_errors&&(this.Wv=n(this.captureException.bind(this))),!this.Vv&&this.Rr.capture_unhandled_rejections&&(this.Vv=i(this.captureException.bind(this))),!this.Gv&&this.Rr.capture_console_errors&&(this.Gv=s(this.captureException.bind(this)))}catch(o){Si.error("failed to start",o),this.Zv()}},this._instance=e,this.Qv=!!(!((t=this._instance.persistence)===null||t===void 0)&&t.props[Vc]),this.wt=new sb(b(b({},(function(r={}){var n,i,s,o;return{refillRate:(n=(i=r.exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:r.__exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:1,bucketSize:(s=(o=r.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:r.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking)),{},{refillInterval:1e4,$:Si})),this.Rr=this.Jv(),this.startIfEnabledOrStop()}Jv(){const e=this._instance.config.capture_exceptions;let t={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return be(e)?t=b(b({},t),e):(O(e)?this.Qv:e)&&(t=b(b({},t),{},{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),t}get isEnabled(){return this.Rr.capture_console_errors||this.Rr.capture_unhandled_errors||this.Rr.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Si.info("enabled"),this.Zv(),this.zo(this.Hv)):this.Zv()}zo(e){var t,r,n;!((t=te.__PosthogExtensions__)===null||t===void 0)&&t.errorWrappingFunctions?e():(r=te.__PosthogExtensions__)===null||r===void 0||(n=r.loadExternalDependency)===null||n===void 0||n.call(r,this._instance,"exception-autocapture",i=>{if(i)return Si.error("failed to load script",i);e()})}Zv(){var e,t,r;(e=this.Wv)===null||e===void 0||e.call(this),this.Wv=void 0,(t=this.Vv)===null||t===void 0||t.call(this),this.Vv=void 0,(r=this.Gv)===null||r===void 0||r.call(this),this.Gv=void 0}onRemoteConfig(e){if(!e.ok)return;const t=e.config;"autocaptureExceptions"in t&&(this.Qv=!!t.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[Vc]:this.Qv}),this.Rr=this.Jv(),this.startIfEnabledOrStop())}onConfigChange(){this.Rr=this.Jv()}captureException(e){try{var t,r,n;const i=(t=e==null||(r=e.$exception_list)===null||r===void 0||(r=r[0])===null||r===void 0?void 0:r.type)!==null&&t!==void 0?t:"Exception";if(this.wt.consumeRateLimit(i))return void Si.info("Skipping exception capture because of client rate limiting.",{exception:i});(n=this._instance.exceptions)===null||n===void 0||n.sendExceptionEvent(e)}catch{}}},exceptions:class{constructor(e){var t,r;this.Kv=[],this.Xv=new mb([new Ob,new qb,new Mb,new xb,new Ub,new zb,new Db,new Fb],(function(n,...i){return(s,o=0)=>{const a=[],c=s.split(`
7
- `),l=Math.min(c.length,o+1e3),u=[];for(let p=o;l>p;p++){const f=c[p];if(f.length>1024)continue;const v=Id.test(f)?f.replace(Id,"$1"):f;if(!v.match(/\S*Error: /)){for(const m of i){const _=m(v,n);if(_){a.push(_);const w=Tb(a);if(w){for(let S=u.length-1;S>=0;S--){const T=u[S];if(w.start>=T.start+T.length)break;u.pop()}u.push(w)}break}}if(Cb(a,u)>=50)break}}const h=[...u].sort((p,f)=>f.start-p.start),d=h[h.length-1];if(d){const p=iv(a,d);a.splice(d.start-p,p);for(const f of h)f.start-=p}for(const p of h)$b(a,p);return u.some(p=>p.start===0&&a.length===p.length)&&(function(p){const f=p.map(m=>`${m.function}|${m.filename}|${m.lineno}|${m.colno}|${m.module}`);let v=0;for(let m=1;f.length>m;m++)Pb(f,m,v)&&(v=m);p.push(...p.splice(0,v))})(a),(function(p){if(!p.length)return[];const f=Array.from(p);return f.reverse(),f.slice(0,50).map(v=>{return b(b({},v),{},{filename:v.filename||(m=f,m[m.length-1]||{}).filename,function:v.function||"?"});var m})})(a)}})("web:javascript",kb,Ib)),this._instance=e,this.Kv=(t=(r=this._instance.persistence)===null||r===void 0?void 0:r.get_property("$error_tracking_suppression_rules"))!==null&&t!==void 0?t:[],this.Yv=vo(this.tf()),this.ef=new Hb(this.Yv)}onConfigChange(){this.Yv=vo(this.tf()),this.ef.setConfig(this.Yv)}onRemoteConfig(e){var t,r,n;if(!e.ok)return;const i=e.config;if(!("errorTracking"in i))return;const s=(t=(r=i.errorTracking)===null||r===void 0?void 0:r.suppressionRules)!==null&&t!==void 0?t:[],o=(n=i.errorTracking)===null||n===void 0?void 0:n.captureExtensionExceptions;this.Kv=s,this._instance.persistence&&this._instance.persistence.register({[bv]:this.Kv,[Bc]:o})}get if(){var e;const t=!!this._instance.get_property(Bc),r=this._instance.config.error_tracking.captureExtensionExceptions;return(e=r??t)!==null&&e!==void 0&&e}buildProperties(e,t){return this.Xv.buildFromUnknown(e,{syntheticException:t?.syntheticException,mechanism:{handled:t?.handled}})}addExceptionStep(e,t){if(this.Yv.enabled)try{if(!ye(e)||e.trim().length===0)return void Pt.warn("Ignoring exception step because message must be a non-empty string");const{sanitizedProperties:r,droppedKeys:n}=(function(i){if(!i)return{sanitizedProperties:{},droppedKeys:[]};const s=[];return{sanitizedProperties:Object.keys(i).reduce((o,a)=>jb.has(a)?(s.push(a),o):(o[a]=i[a],o),{}),droppedKeys:s}})(this.nf(t));n.length>0&&Pt.warn("Ignoring reserved exception step fields",{droppedKeys:n}),this.ef.add(b({[po]:e,[fo]:new Date().toISOString()},r))}catch(r){Pt.error("Failed to add exception step. Ignoring breadcrumb.",r)}}sendExceptionEvent(e){try{const t=e.$exception_list;if(this.sf(t)){if(this.rf(t))return this.af("Exception dropped: matched a suppression rule"),void Pt.info("Skipping exception capture because a suppression rule matched");if(!this.if&&this.lf(t))return this.af("Exception dropped: thrown by a browser extension"),void Pt.info("Skipping exception capture because it was thrown by an extension");if(!this.if&&this.uf(t))return this.af("Exception dropped: thrown by an injected browser script"),void Pt.info("Skipping exception capture because it was thrown by an injected browser script");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hf(t))return this.af("Exception dropped: thrown by the PostHog SDK"),void Pt.info("Skipping exception capture because it was thrown by the PostHog SDK")}const r=this.Yv.enabled&&ge(e.$exception_steps)?this.cf(e):e,n=(function(){const i=globalThis._posthogReleaseId;return typeof i=="string"&&i.length>0?i:void 0})();n&&(r.$release_id=n);try{const i=this._instance.capture("$exception",r,{_noTruncate:!0,_batchKey:"exceptionEvent",fh:!0});return i&&this.ef.clear(),i}catch(i){zh(i)||Pt.error("Failed to capture exception event. Dropping this exception.",i),this.ef.clear();return}}catch(t){zh(t)||Pt.error("Failed to process exception event. Ignoring this exception.",t);return}}cf(e){try{const t=this.ef.getAttachable();return t.length===0?e:b(b({},e),{},{$exception_steps:t})}catch(t){return Pt.error("Failed to read buffered exception steps. Capturing exception without steps.",t),e}}af(e){this.Yv.enabled&&this.ef.add({[po]:e,[fo]:new Date().toISOString()})}nf(e){return be(e)?b({},e):{}}tf(){var e,t;return(e=(t=this._instance.config.error_tracking)===null||t===void 0?void 0:t.exception_steps)!==null&&e!==void 0?e:{}}rf(e){if(e.length===0)return!1;try{const t=e.reduce((r,{type:n,value:i})=>(ye(n)&&n.length>0&&r.$exception_types.push(n),ye(i)&&i.length>0&&r.$exception_values.push(i),r),{$exception_types:[],$exception_values:[]});return this.Kv.some(r=>{const n=r.values.map(i=>{const s=Ag[i.operator],o=t[i.key];if(!s||!o)return!1;const a=ce(i.value)?i.value:[i.value];return a.length>0&&s(a,o)});return r.type==="OR"?n.some(Boolean):n.every(Boolean)})}catch(t){return Pt.warn("Failed to evaluate suppression rules. Capturing the exception.",t),!1}}lf(e){const t=e.flatMap(n=>{var i,s;return(i=(s=n.stacktrace)===null||s===void 0?void 0:s.frames)!==null&&i!==void 0?i:[]}),r=t.filter(({filename:n})=>!!n&&rE.some(i=>n.startsWith(i)));return r.length!==0&&(!r.every(({filename:n})=>!!n&&n.startsWith(cl))||e.some(({type:n,value:i})=>n==="NoResponse"||ye(i)&&tE.some(({value:s,exact:o})=>o?i===s:i.includes(s)))&&!t.some(({in_app:n,filename:i})=>n&&!i?.startsWith(cl)))}uf(e){return e.some(({value:t})=>ye(t)&&nE.some(r=>t.includes(r)))}hf(e){if(e.length>0){var t,r,n,i;const s=(t=(r=e[0].stacktrace)===null||r===void 0?void 0:r.frames)!==null&&t!==void 0?t:[],o=s[s.length-1];return(n=o==null||(i=o.filename)===null||i===void 0?void 0:i.includes("posthog.com/static"))!==null&&n!==void 0&&n}return!1}sf(e){return!ge(e)&&ce(e)}}},fE=b({productTours:class{get Ml(){return this._instance.persistence}constructor(e){this.df=null,this.vf=null,this._instance=e}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(!e.ok)return;const t=e.config;if("productTours"in t){var r,n;if(this.Ml&&this.Ml.register({[ru]:!!t.productTours}),!pc(this._instance))return!this.df&&ge((r=this.Ml)===null||r===void 0?void 0:r.props.ph_product_tours)||$s.info("product tours disabled; stopping and clearing cached tours"),(n=this.df)===null||n===void 0||n.stop(),this.df=null,void this.clearCache();this.loadIfEnabled()}}loadIfEnabled(){!this.df&&pc(this._instance)&&this.zo(()=>this.ff())}zo(e){var t,r,n;!((t=te.__PosthogExtensions__)===null||t===void 0)&&t.generateProductTours?e():(r=te.__PosthogExtensions__)===null||r===void 0||(n=r.loadExternalDependency)===null||n===void 0||n.call(r,this._instance,"product-tours",i=>{i?$s.error("Could not load product tours script",i):e()})}ff(){var e;!this.df&&(e=te.__PosthogExtensions__)!==null&&e!==void 0&&e.generateProductTours&&(this.df=te.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t=!1){if(ce(this.vf)&&!t)return void e(this.vf,{isLoaded:!0});const r=this.Ml;if(r){const n=r.props[Jc];if(ce(n)&&!t)return this.vf=n,void e(n,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api",`/api/product_tours/?token=${this._instance.config.token}`),method:"GET",timestampMode:"query",callback:n=>{if(!pc(this._instance))return void e([],{isLoaded:!0});const i=n.statusCode;if(i!==200||!n.json){const o=`Product Tours API could not be loaded, status: ${i}`;i===0?n.error||$s.warn(o):$s.error(o),e([],{isLoaded:!1,error:o});return}const s=ce(n.json.product_tours)?n.json.product_tours:[];this.vf=s,r&&r.register({[Jc]:s}),e(s,{isLoaded:!0})}})}getActiveProductTours(e){ge(this.df)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this.df.getActiveProductTours(e)}showProductTour(e){var t;(t=this.df)===null||t===void 0||t.showTourById(e)}previewTour(e){this.df?this.df.previewTour(e):this.zo(()=>{var t;this.ff(),(t=this.df)===null||t===void 0||t.previewTour(e)})}dismissProductTour(){var e;(e=this.df)===null||e===void 0||e.dismissTour("user_clicked_skip")}nextStep(){var e;(e=this.df)===null||e===void 0||e.nextStep()}previousStep(){var e;(e=this.df)===null||e===void 0||e.previousStep()}clearCache(){var e;this.vf=null,(e=this.Ml)===null||e===void 0||e.unregister("ph_product_tours")}resetTour(e){var t;(t=this.df)===null||t===void 0||t.resetTour(e)}resetAllTours(){var e;(e=this.df)===null||e===void 0||e.resetAllTours()}cancelPendingTour(e){var t;(t=this.df)===null||t===void 0||t.cancelPendingTour(e)}}},Xo),vE={siteApps:class{constructor(e){this._instance=e,this.pf=0,this.gf=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}mf(e,t){if(!t)return;const r=this.globalsForEvent(t);this.gf.push(r),this.gf.length>1e3&&(this.gf=this.gf.slice(10))}get siteAppLoaders(){var e;return(e=te._POSTHOG_REMOTE_CONFIG)===null||e===void 0||(e=e[this._instance.config.token])===null||e===void 0?void 0:e.siteApps}initialize(){if(this.isEnabled){const e=this._instance._addCaptureHook(this.mf.bind(this));this.yf=()=>{e(),this.gf=[],this.yf=void 0}}}globalsForEvent(e){var t,r,n,i,s,o,a;if(!e)throw new Error("Event payload is required");const c={},l=this._instance.get_property("$groups")||[],u=this._instance.get_property("$stored_group_properties")||{};for(const[p,f]of Object.entries(u))c[p]={id:l[p],type:p,properties:f};const{$set_once:h,$set:d}=e;return{event:b(b({},cv(e,BS)),{},{properties:b(b(b({},e.properties),d?{$set:b(b({},(t=(r=e.properties)===null||r===void 0?void 0:r.$set)!==null&&t!==void 0?t:{}),d)}:{}),h?{$set_once:b(b({},(n=(i=e.properties)===null||i===void 0?void 0:i.$set_once)!==null&&n!==void 0?n:{}),h)}:{}),elements_chain:(s=(o=e.properties)===null||o===void 0?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=e.properties)===null||a===void 0?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:c}}bf(e){var t;const r=(t=e.tagName)===null||t===void 0?void 0:t.toLowerCase();return r==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(e)||(jt.error("prepare_external_dependency_stylesheet returned null"),null):r==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(e)||(jt.error("prepare_external_dependency_script returned null"),null):e}_f(){var e,t,r,n,i,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};const c=N?.defaultView,l=c==null||(e=c.Node)===null||e===void 0?void 0:e.prototype;if(!c||!l)return()=>{};if(this.pf++,this.wf)return this.kf();const u=[],h=this,d=new WeakSet,p=(m,_,w)=>{if(!m?.[_])return;const S=m[_];m[_]=w(S),u.push(()=>{m[_]=S})},f=m=>{if(d.has(m))return m;const _=h.bf(m);return _&&d.add(_),_},v=m=>m.map(_=>typeof _=="string"?_:f(_)).filter(_=>!He(_));return p(l,"appendChild",m=>function(_){const w=f(_);return w?m.call(this,w):_}),p(l,"insertBefore",m=>function(_,w){const S=f(_);return S?m.call(this,S,w):_}),p(l,"replaceChild",m=>function(_,w){const S=f(_);return S?m.call(this,S,w):w}),[(t=c.Element)===null||t===void 0?void 0:t.prototype,(r=c.Document)===null||r===void 0?void 0:r.prototype,(n=c.DocumentFragment)===null||n===void 0?void 0:n.prototype].forEach(m=>{p(m,"append",_=>function(...w){return _.apply(this,v(w))}),p(m,"prepend",_=>function(...w){return _.apply(this,v(w))})}),[(i=c.Element)===null||i===void 0?void 0:i.prototype,(s=c.CharacterData)===null||s===void 0?void 0:s.prototype,(o=c.DocumentType)===null||o===void 0?void 0:o.prototype].forEach(m=>{p(m,"before",_=>function(...w){return _.apply(this,v(w))}),p(m,"after",_=>function(...w){return _.apply(this,v(w))}),p(m,"replaceWith",_=>function(...w){const S=v(w);return w.length&&!S.length?void 0:_.apply(this,S)})}),p((a=c.Element)===null||a===void 0?void 0:a.prototype,"insertAdjacentElement",m=>function(_,w){const S=f(w);return S?m.call(this,_,S):null}),this.wf=()=>{u.forEach(m=>m()),this.wf=void 0},this.kf()}kf(){let e=!1;return()=>{var t;e||(e=!0,this.pf--,this.pf===0&&((t=this.wf)===null||t===void 0||t.call(this)))}}Sf(e,t=!0){const r=this._f();try{const n=e(r);return t&&r(),n}catch(n){throw r(),n}}setupSiteApp(e){const t=this.apps[e.id],r=()=>{var s;!t.errored&&this.gf.length&&(jt.info(`Processing ${this.gf.length} events for site app with id ${e.id}`),this.gf.forEach(o=>this.Sf(()=>{var a;return(a=t.processEvent)===null||a===void 0?void 0:a.call(t,o)})),t.processedBuffer=!0),Object.values(this.apps).every(o=>o.processedBuffer||o.errored)&&((s=this.yf)===null||s===void 0||s.call(this))};let n=!1;const i=s=>{t.errored=!s,t.loaded=!0,jt.info(`Site app with id ${e.id} ${s?"loaded":"errored"}`),n&&r()};try{const{processEvent:s}=this.Sf(o=>e.init({posthog:this._instance,callback(a){o(),i(a)}}),!1);s&&(t.processEvent=s),n=!0}catch(s){jt.error(Th+e.id,s),i(!1)}if(n&&t.loaded)try{r()}catch(s){jt.error(`Error while processing buffered events PostHog app with config id ${e.id}`,s),t.errored=!0}}xf(){const e=this.siteAppLoaders||[];for(const t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(const t of e)this.setupSiteApp(t)}Cf(e){if(Object.keys(this.apps).length===0)return;const t=this.globalsForEvent(e);for(const r of Object.values(this.apps))try{this.Sf(()=>{var n;return(n=r.processEvent)===null||n===void 0?void 0:n.call(r,t)})}catch(n){jt.error(`Error while processing event ${e.event} for site app ${r.id}`,n)}}onRemoteConfig(e){var t,r,n;if(!((t=this.siteAppLoaders)===null||t===void 0)&&t.length)return this.isEnabled?(this.xf(),void this._instance.on("eventCaptured",a=>this.Cf(a))):void jt.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((r=this.yf)===null||r===void 0||r.call(this),!e.ok)return;const i=e.config;if(!((n=i.siteApps)===null||n===void 0)&&n.length)if(this.isEnabled)for(const{id:a,url:c}of i.siteApps){var s,o;te[`__$$ph_site_app_${a}`]=this._instance,(s=te.__PosthogExtensions__)===null||s===void 0||(o=s.loadSiteApp)===null||o===void 0||o.call(s,this._instance,c,l=>{if(l)return jt.error(Th+a,l)})}else jt.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}},gE={tracingHeaders:class{constructor(e){this._instance=e,this.$f=void 0,this.Tf=void 0,this.If=void 0,this.Hv=()=>{const t=this.Mf();var r,n;t?(O(this.$f)&&(this.$f=(r=te.__PosthogExtensions__)===null||r===void 0||(r=r.tracingHeadersPatchFns)===null||r===void 0?void 0:r._patchXHR(t,()=>this._instance.get_distinct_id(),this._instance.sessionManager)),O(this.Tf)&&(this.Tf=(n=te.__PosthogExtensions__)===null||n===void 0||(n=n.tracingHeadersPatchFns)===null||n===void 0?void 0:n._patchFetch(t,()=>this._instance.get_distinct_id(),this._instance.sessionManager))):this.Zv()}}initialize(){this.startIfEnabledOrStop()}zo(e){var t,r,n;!((t=te.__PosthogExtensions__)===null||t===void 0)&&t.tracingHeadersPatchFns?e():(r=te.__PosthogExtensions__)===null||r===void 0||(n=r.loadExternalDependency)===null||n===void 0||n.call(r,this._instance,"tracing-headers",i=>{if(i)return qS.error("failed to load script",i);e()})}Ef(){var e,t;return(e=(t=this._instance.config.tracing_headers)!==null&&t!==void 0?t:this._instance.config.addTracingHeaders)!==null&&e!==void 0?e:this._instance.config.__add_tracing_headers}Mf(){const e=this.Ef();return ce(e)?(ce(this.If)?this.If.splice(0,this.If.length,...e):this.If=[...e],e.length>0?this.If:void 0):(ce(this.If)&&this.If.splice(0),this.If=e||void 0,this.If)}Zv(){var e,t;(e=this.$f)===null||e===void 0||e.call(this),(t=this.Tf)===null||t===void 0||t.call(this),this.$f=void 0,this.Tf=void 0}startIfEnabledOrStop(){this.Mf()?this.zo(this.Hv):this.Zv()}}},mE=b({surveys:class extends GS{constructor(e){var t;super(new YS(e),(t=e,{get projectToken(){return t.config.token},kv:new KS(t)})),this._instance=e}qh(e,t){const r=t.query?ds(e,t.query):e;return new Promise(n=>{var i;this._instance._send_request({method:t.method,url:this._instance.requestRouter.endpointFor((i=t.target)!==null&&i!==void 0?i:"api",r),data:t.body,headers:t.headers,timeout:t.timeoutMs,fireCallbackOnDrop:!0,transport:t.transport,compression:t.compression,timestampMode:t.sentAt,callback:n})})}}},Xo),_E={toolbar:class{constructor(e){this.instance=e}Pf(e){te.ph_toolbar_state=e}Rf(){var e;return(e=te.ph_toolbar_state)!==null&&e!==void 0?e:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(e=void 0,t=void 0,r=void 0){var n,i;if(Yc(this.instance.config)||!A||!N)return!1;e=(n=e)!==null&&n!==void 0?n:A.location,r=(i=r)!==null&&i!==void 0?i:A.history;try{if(!t){try{A.localStorage.setItem("test","test"),A.localStorage.removeItem("test")}catch{return!1}t=A?.localStorage}const s=XS||So(e.hash,"__posthog")||So(e.hash,"state");let o;const a=s?Ed(()=>JSON.parse(atob(decodeURIComponent(s))))||Ed(()=>JSON.parse(decodeURIComponent(s))):null;return a&&a.action==="ph_authorize"?(o=a,o.source="url",o&&Object.keys(o).length>0&&(a.desiredHash?e.hash=a.desiredHash:r?r.replaceState(r.state,"",e.pathname+e.search):e.hash="")):(o=JSON.parse(t.getItem(Ch)||"{}"),o.source="localstorage",delete o.userIntent),!(!o.token||this.instance.config.token!==o.token||(this.loadToolbar(o),0))}catch{return!1}}Af(e){const t=te.ph_load_toolbar||te.ph_load_editor;!ge(t)&&rt(t)?t(e,this.instance):Ph.warn("No toolbar load function found")}loadToolbar(e){const t=!!N?.getElementById("__POSTHOG_TOOLBAR__");if(!A||t)return!1;const r=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,n=b(b({token:this.instance.config.token},e),{},{apiURL:this.instance.requestRouter.endpointFor("ui")},r?{instrument:!1}:{});if(A.localStorage.setItem(Ch,JSON.stringify(b(b({},n),{},{source:void 0}))),this.Rf()===2)this.Af(n);else if(this.Rf()===0){var i,s;this.Pf(1),(i=te.__PosthogExtensions__)===null||i===void 0||(s=i.loadExternalDependency)===null||s===void 0||s.call(i,this.instance,"toolbar",o=>{if(o)return Ph.error("[Toolbar] Failed to load",o),void this.Pf(0);this.Pf(2),this.Af(n)}),Ie(A,"turbolinks:load",()=>{this.Pf(0),this.loadToolbar(n)})}return!0}Ff(e){return this.loadToolbar(e)}maybeLoadEditor(e=void 0,t=void 0,r=void 0){return this.maybeLoadToolbar(e,t,r)}}},yE=b({experiments:class ht{get Rr(){return this._instance.config}constructor(t){this._instance=t,this.getWebExperimentsAndEvaluateDisplayLogic=(r=!1)=>{this.getWebExperiments(n=>{ht.Of("retrieved web experiments from the server"),this.Df=new Map,n.forEach(i=>{if(i.feature_flag_key){var s;this.Df&&(ht.Of("setting flag key ",i.feature_flag_key," to web experiment ",i),(s=this.Df)===null||s===void 0||s.set(i.feature_flag_key,i));const o=this._instance.getFeatureFlag(i.feature_flag_key);ye(o)&&i.variants[o]&&this.Lf(i.name,o,i.variants[o].transforms)}else if(i.variants)for(const o in i.variants){const a=i.variants[o];ht.Nf(a,this._instance)&&this.Lf(i.name,o,a.transforms)}})},r)},this._instance.onFeatureFlags(r=>{this.onFeatureFlags(r)})}initialize(){}onFeatureFlags(t){if(this._is_bot())ht.Of(Uh);else if(!this.Rr.disable_web_experiments){if(ge(this.Df))return this.Df=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ht.Of("applying feature flags",t),t.forEach(r=>{var n;if(this.Df&&(!((n=this.Df)===null||n===void 0)&&n.has(r))){var i;const s=this._instance.getFeatureFlag(r),o=(i=this.Df)===null||i===void 0?void 0:i.get(r);s&&o!=null&&o.variants[s]&&this.Lf(o.name,s,o.variants[s].transforms)}})}}previewWebExperiment(){const t=ht.getWindowLocation();if(t?.search){const r=Qn(t?.search,"__experiment_id"),n=Qn(t?.search,"__experiment_variant");r&&n&&(ht.Of(`previewing web experiments ${r} && ${n}`),this.getWebExperiments(i=>{this.qf(parseInt(r),n,i)},!1,!0))}}loadIfEnabled(){this.Rr.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(t,r,n){if(this.Rr.disable_web_experiments&&!n)return t([]);const i=this._instance.get_property("$web_experiments");if(i&&!r)return t(i);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api",`/api/web_experiments/?token=${this.Rr.token}`),method:"GET",timestampMode:"query",callback:s=>t(s.statusCode===200&&s.json&&s.json.experiments||[])})}qf(t,r,n){const i=n.filter(s=>s.id===t);i&&i.length>0&&(ht.Of(`Previewing web experiment [${i[0].name}] with variant [${r}]`),this.Lf(i[0].name,r,i[0].variants[r].transforms))}static Nf(t,r){return!ge(t.conditions)&&ht.jf(t,r)&&ht.Bf(t)}static jf(t,r){var n;if(ge(t.conditions)||ge((n=t.conditions)===null||n===void 0?void 0:n.url))return!0;const i=ht.getWindowLocation();if(i){var s,o,a;const c=Fv(r,i.href);return!(!((s=t.conditions)===null||s===void 0)&&s.url)||iE[(o=(a=t.conditions)===null||a===void 0?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](t.conditions.url,c)}return!1}static getWindowLocation(){return A?.location}static Bf(t){var r;if(ge(t.conditions)||ge((r=t.conditions)===null||r===void 0?void 0:r.utm))return!0;const n=Xv();if(n.utm_source){var i,s,o,a,c,l,u,h;const d=!(!((i=t.conditions)===null||i===void 0||(i=i.utm)===null||i===void 0)&&i.utm_campaign)||((s=t.conditions)===null||s===void 0||(s=s.utm)===null||s===void 0?void 0:s.utm_campaign)==n.utm_campaign,p=!(!((o=t.conditions)===null||o===void 0||(o=o.utm)===null||o===void 0)&&o.utm_source)||((a=t.conditions)===null||a===void 0||(a=a.utm)===null||a===void 0?void 0:a.utm_source)==n.utm_source,f=!(!((c=t.conditions)===null||c===void 0||(c=c.utm)===null||c===void 0)&&c.utm_medium)||((l=t.conditions)===null||l===void 0||(l=l.utm)===null||l===void 0?void 0:l.utm_medium)==n.utm_medium,v=!(!((u=t.conditions)===null||u===void 0||(u=u.utm)===null||u===void 0)&&u.utm_term)||((h=t.conditions)===null||h===void 0||(h=h.utm)===null||h===void 0?void 0:h.utm_term)==n.utm_term;return d&&f&&v&&p}return!1}static Of(t,...r){j.info(`[WebExperiments] ${t}`,r)}Lf(t,r,n){this._is_bot()?ht.Of(Uh):r!=="control"?n.forEach(i=>{if(i.selector){var s;ht.Of(`applying transform of variant ${r} for experiment ${t} `,i),((s=document)===null||s===void 0?void 0:s.querySelectorAll(i.selector))?.forEach(o=>{const a=o;i.html&&(a.innerHTML=i.html),i.css&&a.setAttribute("style",i.css)})}}):ht.Of("Control variants leave the page unmodified.")}_is_bot(){return nt&&this._instance?Eg(nt,this.Rr.custom_blocked_useragents):void 0}}},Xo),bE={conversations:class{constructor(e){this._instance=e,this.Hf=void 0,this._conversationsManager=null,this.zf=!1,this.ne=null,this.Uf=!1}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(this._instance.config.disable_conversations||(this.Wf=e.ok,!e.ok))return;const t=e.config.conversations;ge(t)||(gt(t)?this.Hf=t:(this.Hf=t.enabled,this.ne=t),this.loadIfEnabled())}reset(){var e;(e=this._conversationsManager)===null||e===void 0||e.reset(),this._conversationsManager=null,this.Hf=void 0,this.ne=null,this.Wf=void 0,this.Uf=!1}loadIfEnabled(){if(this._conversationsManager||this.zf||this._instance.config.disable_conversations||Yc(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())return;const e=te?.__PosthogExtensions__;if(e&&!O(this.Hf)&&this.Hf)if(this.ne&&this.ne.token){this.zf=!0;try{const t=e.initConversations;if(t)return this.Vf(t),void(this.zf=!1);const r=e.loadExternalDependency;if(!r)return void this.Gf(iu);r(this._instance,"conversations",n=>{n||!e.initConversations?this.Gf("Could not load conversations script",n):this.Vf(e.initConversations),this.zf=!1})}catch(t){this.Gf("Error initializing conversations",t),this.zf=!1}}else Rt.error("Conversations enabled but missing token in remote config.")}Vf(e){if(this.ne)try{this._conversationsManager=e(this.ne,this._instance),this.Uf=!1,Rt.info("Conversations loaded successfully")}catch(t){this.Gf("Error completing conversations initialization",t)}else Rt.error("Cannot complete initialization: remote config is null")}Gf(e,t){Rt.error(e,t),this._conversationsManager=null,this.zf=!1,this.Uf=!0}show(){this._conversationsManager?this._conversationsManager.show():Rt.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Hf===!0&&!He(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":Yc(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Wf===!1?"remote_config_failed":O(this.Hf)?this.Wf?"disabled_in_project":"remote_config_pending":this.Hf?ge(this.ne)||!this.ne.token?"missing_token":te?.__PosthogExtensions__?this.zf?"initializing":this.Uf?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var e,t;return(e=(t=this._conversationsManager)===null||t===void 0?void 0:t.isVisible())!==null&&e!==void 0&&e}sendMessage(e,t,r){var n=this;return Ue(function*(){return n._conversationsManager?n._conversationsManager.sendMessage(e,t,r):(Rt.warn(Kr),null)})()}getMessages(e,t){var r=this;return Ue(function*(){return r._conversationsManager?r._conversationsManager.getMessages(e,t):(Rt.warn(Kr),null)})()}markAsRead(e){var t=this;return Ue(function*(){return t._conversationsManager?t._conversationsManager.markAsRead(e):(Rt.warn(Kr),null)})()}getTickets(e){var t=this;return Ue(function*(){return t._conversationsManager?t._conversationsManager.getTickets(e):(Rt.warn(Kr),null)})()}requestRestoreLink(e){var t=this;return Ue(function*(){return t._conversationsManager?t._conversationsManager.requestRestoreLink(e):(Rt.warn(Kr),null)})()}restoreFromToken(e){var t=this;return Ue(function*(){return t._conversationsManager?t._conversationsManager.restoreFromToken(e):(Rt.warn(Kr),null)})()}restoreFromUrlToken(){var e=this;return Ue(function*(){return e._conversationsManager?e._conversationsManager.restoreFromUrlToken():(Rt.warn(Kr),null)})()}getCurrentTicketId(){var e,t;return(e=(t=this._conversationsManager)===null||t===void 0?void 0:t.getCurrentTicketId())!==null&&e!==void 0?e:null}getWidgetSessionId(){var e,t;return(e=(t=this._conversationsManager)===null||t===void 0?void 0:t.getWidgetSessionId())!==null&&e!==void 0?e:null}Sh(){var e;(e=this._conversationsManager)===null||e===void 0||e.setIdentity()}xh(){var e;(e=this._conversationsManager)===null||e===void 0||e.clearIdentity()}}},wE={logs:class{constructor(e){var t;this._instance=e,this.name="logs",this.Zf=!1,this.Qf=!1,this.Jf=!1,this.$=Be("[logs]"),this.Kf=b(b({},this.$),{},{error:(...r)=>{r.some(jh)||this.$.error(...r)}}),this.al=[],this.Xf=[],this.hd=0,this.Io=!1,this.Yf=[],this.tp=[],this.ep=!1,this.np=!1,this.sp=()=>{var r,n;this.Io||(this.hd=0,(r=this.rp)===null||r===void 0||r.onReconnect(),(n=this.op)===null||n===void 0||n.onReconnect())},this._instance&&(t=this._instance.config.logs)!==null&&t!==void 0&&t.captureConsoleLogs&&(this.Zf=!0),A&&Ie(A,"online",this.sp)}ap(e,t,r,n){var i;const s=Fh((i=this._instance)===null||i===void 0||(i=i.config)===null||i===void 0?void 0:i.logs,r);return[new Qb(this.lp(e,t),s,this.Kf,()=>this.up(),o=>o(),void 0,n),s]}hp(){var e;const t=(e=this._instance)===null||e===void 0||(e=e.config)===null||e===void 0?void 0:e.logs;var r;return this.rp&&this.cp===t||((r=this.rp)===null||r===void 0||r.reset(),this.cp=t,[this.rp,this.dp]=this.ap(()=>this.al,n=>{this.al=n})),this.rp}vp(){var e;const t=(e=this._instance)===null||e===void 0||(e=e.config)===null||e===void 0?void 0:e.logs;var r;return this.op&&this.fp===t||((r=this.op)===null||r===void 0||r.reset(),this.fp=t,[this.op,this.pp]=this.ap(()=>this.Xf,n=>{this.Xf=n},{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},qh)),this.op}setup(e){var t;if(this.Io)return;this.wo=e,(t=this._instance)!==null&&t!==void 0&&(t=t.config)!==null&&t!==void 0&&(t=t.logs)!==null&&t!==void 0&&t.captureConsoleLogs&&(this.Zf=!0),(this.Zf||this.gp()&&this.mp())&&this.yp();let r=!1;const n=e.onRemoteConfig(i=>{var s;r=i.ok&&((s=i.config.logs)===null||s===void 0?void 0:s.captureConsoleLogs)===!0,this.onRemoteConfig(i)});this.Io?n.dispose():(this.Po=n,r||this.loadIfEnabled())}dispose(){var e,t,r,n;this.Io||(this.Io=!0,this.bp(),(e=this.Po)===null||e===void 0||e.dispose(),this.Po=void 0,this.wo=void 0,this.Jf=!1,A?.removeEventListener("online",this.sp),(t=this._p)===null||t===void 0||t.call(this),this._p=void 0,(r=this.rp)===null||r===void 0||r.reset(),(n=this.op)===null||n===void 0||n.reset())}onRemoteConfig(e){var t,r;if(this.Io)return;const n=e.ok?(t=e.config.logs)===null||t===void 0?void 0:t.captureConsoleLogs:void 0;ge(n)?this.wp():((r=this._instance)===null||r===void 0||(r=r.persistence)===null||r===void 0||r.register({$logs_capture_enabled_server_side:!!n}),n?(this.Zf=!0,this.Qf||this.yp(),this.loadIfEnabled()):this.wp())}reset(){var e,t,r,n;this.bp(),(e=this.rp)===null||e===void 0||e.clearQueue(),this.al=[],(t=this.rp)===null||t===void 0||t.reset(),(r=this.op)===null||r===void 0||r.clearQueue(),this.Xf=[],(n=this.op)===null||n===void 0||n.reset(),this.hd=0}captureLog(e){this.Io||this.hp().captureLog(e)}captureConsoleLog(e){this.Io||this.vp().captureLog(e)}captureBufferedConsoleLog(e,t,r){this.Io||this.vp().captureLog(e,{context:t,occurredAtMs:r})}mp(){var e;return!!(!((e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0||(e=e.props)===null||e===void 0)&&e[wv])}gp(){var e,t,r;return!(!((e=this._instance)===null||e===void 0||(t=e.nl)===null||t===void 0)&&t.call(e))||!!(!((r=te._POSTHOG_REMOTE_CONFIG)===null||r===void 0||(r=r[this._instance.config.token])===null||r===void 0)&&r.config)}$h(){var e;this.bp(),(e=this.op)===null||e===void 0||e.clearQueue(),this.Xf=[]}wp(){this.Zf||this.bp()}yp(){var e;if(this.ep||!te?.console)return;const t=Fh((e=this._instance)===null||e===void 0||(e=e.config)===null||e===void 0?void 0:e.logs).maxBufferSize;let r=!0;this.tp.push(()=>{r=!1});for(const n of sE){let i;try{i=oE(te.console[n])}catch{continue}i&&this.tp.push(rs(te.console,n,s=>{const o=(...a)=>{try{r&&this.kp(n,a,t)}catch{}return s.apply(te.console,a)};return o.__rrweb_original__=i,o}))}this.ep=!0,this.Sp=setTimeout(()=>{this.bp()},3e4)}kp(e,t,r){var n;if(this.ep&&!this.np&&t.length!==0)if(!((n=this._instance)===null||n===void 0)&&n.is_capturing()){if(r>this.Yf.length){this.np=!0;try{this.Yf.push({level:e,args:t,occurredAtMs:Date.now(),context:this.up()})}finally{this.np=!1}}}else this.bp()}bp(){if(this.Yf=[],this.ep){this.ep=!1,this.Sp&&(clearTimeout(this.Sp),this.Sp=void 0);for(const e of this.tp)e();this.tp=[]}}xp(){const e=this.Yf;return this.bp(),e}get logger(){return this.Cp||(this.Cp={trace:(e,t)=>this.captureLog({body:e,level:"trace",attributes:t}),debug:(e,t)=>this.captureLog({body:e,level:"debug",attributes:t}),info:(e,t)=>this.captureLog({body:e,level:"info",attributes:t}),warn:(e,t)=>this.captureLog({body:e,level:"warn",attributes:t}),error:(e,t)=>this.captureLog({body:e,level:"error",attributes:t}),fatal:(e,t)=>this.captureLog({body:e,level:"fatal",attributes:t})}),this.Cp}flushLogs(e){e?this.$p(e):(this.rp&&this.rp.flush().catch(t=>this.Tp(t)),this.op&&this.op.flush().catch(t=>this.Tp(t)))}Tp(e){jh(e)||this.$.error("PostHog logs flush failed:",e)}loadIfEnabled(){if(this.Io||!this.Zf||this.Qf||this.Jf)return;const e=te?.__PosthogExtensions__;if(!e)return this.$.error("PostHog Extensions not found."),void this.bp();const t=e.loadExternalDependency;if(!t)return this.$.error(iu),void this.bp();this.Jf=!0;try{t(this._instance,"logs",r=>{if(this.Jf=!1,this.Io||!this.Zf)return;const n=e.logs;if(r||!n?.initializeLogs)this.$.error("Could not load logs script",r),this.bp();else{var i;const a=this.xp();var s,o;this._p=n.initializeLogs((i=this.wo)!==null&&i!==void 0?i:this._instance),this.Qf=!0,a.length>0&&((s=n.replayConsoleBuffer)===null||s===void 0||s.call(n,(o=this.wo)!==null&&o!==void 0?o:this._instance,a))}})}catch(r){throw this.Jf=!1,r}}lp(e,t){const r=this._instance;return{get isDisabled(){return!1},get optedOut(){return!r.is_capturing()},getPersistedProperty:n=>n===Vt.LogsQueue?e():void 0,setPersistedProperty(n,i){var s;n===Vt.LogsQueue&&t((s=i)!==null&&s!==void 0?s:[])},js:n=>this.js(n),getLibraryId:()=>et.LIB_NAME,getLibraryVersion:()=>et.LIB_VERSION}}js(e){return new Promise(t=>{if(Kv(this.hd,3))return void t({kind:"fatal",error:vc(void 0,"logs endpoint is unreachable, dropping batch")});let r=!1;const n=s=>{r||(r=!0,clearTimeout(i),t(s))},i=setTimeout(()=>{this.$.warn("Logs request timed out before receiving a response"),n({kind:"retry-later",error:vc(void 0,"logs request timed out")})},9e4);this._instance._send_request({method:"POST",url:this.Ip(),data:e,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{const o=s.statusCode;if(this.Mp(o),o>=200&&300>o)n({kind:"ok"});else if(o===413)n({kind:"too-large"});else if(o!==0&&o!==408&&o!==429&&500>o)n({kind:"fatal",error:new Error(`logs request failed with status ${o}`)});else{var a;o===0?(s.error||this.$.warn("Logs request failed before receiving an HTTP response"),n({kind:"retry-later",error:vc(s.error,"logs request failed before receiving an HTTP response")})):n({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error(`logs request failed with status ${o}`)})}}})})}Mp(e){(e!==0||this._instance.__loaded)&&(this.hd=Yv(e,this.hd,3,()=>this.$.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes.")))}$p(e){this.al.length>0&&this.Ep(e,this.al,this.dp,et.LIB_NAME,t=>{this.al=t}),this.Xf.length>0&&this.Ep(e,this.Xf,this.pp,qh,t=>{this.Xf=t})}Ep(e,t,r,n,i){if(t.length===0)return;const s=t.map(a=>a.record);i([]);const o=fv(s,pv(r,et.LIB_NAME,et.LIB_VERSION),n,et.LIB_VERSION);this._instance._send_request({method:"POST",url:this.Ip(),data:o,compression:"best-available",batchKey:"logs",transport:e})}Ip(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}up(){var e;const t={};if(t.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){const{sessionId:r,windowId:n,sessionStartTimestamp:i,lastActivityTimestamp:s}=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0);t.sessionId=r,t.windowId=n,ge(i)||(t.sessionStartTimestamp=i),ge(s)||(t.lastActivityTimestamp=s)}if(te!=null&&(e=te.location)!==null&&e!==void 0&&e.href&&(t.currentUrl=this._instance.config.disable_capture_url_hashes?Mr(te.location.href):te.location.href),this._instance.featureFlags){const r=this._instance.featureFlags.getFlags();r&&r.length>0&&(t.activeFeatureFlags=r)}return t}}},SE={metrics:class{constructor(e){this._instance=e,this.$=Be("[metrics]"),this.Io=!1}initialize(){this.onConfigChange()}onConfigChange(){var e;if(this.Io)return;const t=!!(!((e=this._instance.config.metrics)===null||e===void 0)&&e.network);t&&!this.Pp?this.Pp=(r=>{let n=!0;const i=()=>n?(a=>{var c;const l=(c=a.config.metrics)===null||c===void 0?void 0:c.network;return l===!0?{}:l||void 0})(r):void 0,s=lE(r,i),o=uE(r,i);return()=>{n=!1,s(),o()}})(this._instance):!t&&this.Pp&&(this.Pp(),this.Pp=void 0)}hp(){var e;const t=(e=this._instance)===null||e===void 0||(e=e.config)===null||e===void 0?void 0:e.metrics;var r;return this.rp&&this.cp===t||((r=this.rp)===null||r===void 0||r.reset(),this.cp=t,this.rp=new ew(this.lp(),(function(n){var i,s,o,a,c;const l=n?.resourceAttributes;return{serviceName:(i=l?.["service.name"])!==null&&i!==void 0?i:n?.serviceName,serviceVersion:(s=l?.["service.version"])!==null&&s!==void 0?s:n?.serviceVersion,environment:(o=l?.["deployment.environment"])!==null&&o!==void 0?o:n?.environment,resourceAttributes:l,beforeSend:n?.beforeSend,flushIntervalMs:(a=n?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(c=n?.maxSeriesPerFlush)!==null&&c!==void 0?c:1e3}})(t),this.$)),this.rp}count(e,t=1,r){this.hp().count(e,t,r)}gauge(e,t,r){this.hp().gauge(e,t,r)}histogram(e,t,r){this.hp().histogram(e,t,r)}flush(e){if(!this.rp)return Promise.resolve();if(e){const t=this.rp.drainWindow();return t&&this.Ys(t,e),Promise.resolve()}return this.rp.flush().catch(t=>this.$.error("PostHog metrics flush failed:",t))}reset(){var e;(e=this.rp)===null||e===void 0||e.reset()}dispose(){var e,t;this.Io=!0,(e=this.Pp)===null||e===void 0||e.call(this),this.Pp=void 0,(t=this.rp)===null||t===void 0||t.reset()}lp(){const e=this._instance,t=this;return{get isDisabled(){return!1},get optedOut(){return!e.is_capturing()},Ys:r=>t.Ys(r),getLibraryId:()=>et.LIB_NAME,getLibraryVersion:()=>et.LIB_VERSION}}Ys(e,t){return new Promise(r=>{let n=!1;const i=o=>{n||(n=!0,clearTimeout(s),r(o))},s=setTimeout(()=>i({kind:"retry-later",error:new Error("metrics request timed out")}),9e4);this._instance._send_request(b(b({method:"POST",url:this.Rp(),data:e,compression:"best-available",batchKey:"metrics"},t&&{transport:t}),{},{fireCallbackOnDrop:!0,callback(o){const a=o.statusCode;if(a>=200&&300>a)i({kind:"ok"});else if(a===413)i({kind:"too-large"});else if(a!==0&&a!==408&&a!==429&&500>a)i({kind:"fatal",error:new Error(`metrics request failed with status ${a}`)});else{var c;i({kind:"retry-later",error:(c=o.error)!==null&&c!==void 0?c:new Error(`metrics request failed with status ${a}`)})}}}))})}Rp(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}};Bi.__defaultExtensionClasses=b({},b(b(b(b(b(b(b(b(b(b(b(b(b({},Xo),dE),hE),pE),fE),vE),mE),gE),_E),yE),bE),wE),SE));var EE=(function(){et.SDK_DIST_CHANNEL="npm";const e=Hi[Ti]=new Bi;return(function(){function t(){t.done||(t.done=!0,wg=!1,$e(Hi,function(r){r._dom_loaded()}))}N?.addEventListener?N.readyState==="complete"?t():Ie(N,"DOMContentLoaded",t,{capture:!1}):A&&j.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),e})(),kE=EE,oL=Object.freeze({maxObservations:24,maxSummaryChars:400,maxEvidenceRefs:8,maxEvidenceRefChars:200,maxModelIdChars:128,maxVersionChars:64}),aL=Object.freeze({status:"not-requested",reason:"not_requested",detail:"this run did not request model-backed observations, so nothing was charged"});function Lg(e){return e.status==="skipped"&&e.skipReason==="could-not-run"}function RE(e){return e.status==="skipped"&&e.skipReason!=="could-not-run"}function AE(e){if(e.some(n=>n.status==="failed"))return{outcome:"failed"};const t=e.filter(Lg);if(t.length===0)return e.length===0?{outcome:"incomplete",incompleteReason:"no checks were selected, so this run establishes nothing"}:{outcome:"passed"};const r=Array.from(new Set(t.map(n=>n.error?.message??"reason unavailable")));return{outcome:"incomplete",incompleteReason:`${t.length} of ${e.length} selected check(s) could not run, so this run does not establish conformance (${t.map(n=>n.id).join(", ")}): ${r.join(" ")}`}}var IE="2026-08-19",TE="https://docs.claude.com/en/docs/mcp",$E=["directory","verification","submission","review-criteria","authentication","lazy-authentication","enterprise-managed-auth","troubleshooting","mcp-apps/cross-compatibility","mcp-apps/external-links","mcp-apps/troubleshooting","mcp-apps/design-guidelines"],CE={},PE=$E.map(e=>({page:e,url:`${TE}/${e}`,revision:CE[e]??null,snapshotDate:IE})),OE=Object.freeze(Object.fromEntries(PE.map(e=>[e.page,e])));function gr(e,t){const r=OE[e];return{page:r.page,section:t,url:r.url,revision:r.revision,snapshotDate:r.snapshotDate}}function Dg(e){return e.class==="required"||e.class==="runtime-blocker"}var cL=["runtime-compatibility","directory-policy","optional-features","submission-artifacts","experience-insights"];function xE(e){return Dg(e)}var ME=["experience"];var LE=["claude.experience.tool-descriptions-uninformative","claude.experience.tool-overlap","claude.experience.connector-purpose-unclear","claude.experience.consent-scope-unclear","claude.experience.listing-copy-placeholder","claude.experience.destructive-tool-underexplained","claude.experience.app-copy-mismatched"],lL=Object.freeze({readinessKind:"claude-directory-readiness",observationKinds:ME,knownIds:LE,schemaVersion:"1"}),DE=[{id:"claude.experience.tool-descriptions-uninformative",title:"Tool descriptions may not tell Claude when to use the tool",lane:"experience-insights",class:"heuristic",source:gr("review-criteria","§Tool quality"),remediation:"Describe when a tool should be reached for, not only what it does; Claude picks tools from these sentences."},{id:"claude.experience.tool-overlap",title:"Two or more tools may cover the same job",lane:"experience-insights",class:"heuristic",source:gr("review-criteria","§Tool quality"),remediation:"Overlapping tools make selection ambiguous; consider merging them or sharpening what separates them."},{id:"claude.experience.connector-purpose-unclear",title:"What this connector is for may not be clear from its surface",lane:"experience-insights",class:"manual-review",source:gr("review-criteria","§Usefulness"),remediation:"A reviewer should be able to say what the connector is for from the listing and the tool names alone."},{id:"claude.experience.consent-scope-unclear",title:"It may not be clear to a user what they are authorizing",lane:"experience-insights",class:"manual-review",source:gr("authentication","§Consent"),remediation:"State which account is connected and what scope it grants, in the copy the user sees at consent time."},{id:"claude.experience.listing-copy-placeholder",title:"Listing copy may still contain placeholder text",lane:"experience-insights",class:"manual-review",source:gr("submission","§Listing"),remediation:"Review the listing fields for template text before submitting; reviewers reject placeholder copy."},{id:"claude.experience.destructive-tool-underexplained",title:"A destructive tool may not explain its consequences",lane:"experience-insights",class:"manual-review",source:gr("review-criteria","§Safety"),remediation:"Say plainly in the description what a destructive tool changes and whether it can be undone."},{id:"claude.experience.app-copy-mismatched",title:"An app's rendered copy may not match what its tool returns",lane:"experience-insights",class:"heuristic",source:gr("mcp-apps/design-guidelines","§Content"),remediation:"A widget that says something different from the tool's text response leaves the model and the user disagreeing."}],uL=Object.freeze({experienceLane:"experience-insights",engineVersion:"1",mappings:DE}),Hh="2026-08-19",To="https://developers.openai.com/plugins",dL=`${To}/llms.txt`,hL=`${To}/changelog`,Ng=["quickstart","app-guidelines","reference","changelog","plan/use-case","plan/tools","concepts/plugins","concepts/skills","concepts/ui-guidelines","build/plugins","build/skills","build/mcp-server","build/chatgpt-ui","build/auth","build/monetization","build/examples","deploy/connect-chatgpt","deploy/submission","deploy/submission-errors","deploy/troubleshooting","guides/optimize-metadata","guides/submit-claude-plugin","guides/product-checkout-conversion-spec"],zg=[{page:"help/plugins-in-chatgpt-and-codex",url:"https://help.openai.com/en/articles/20001256-plugins-in-chatgpt-and-codex"},{page:"help/submitting-apps-to-the-chatgpt-app-directory",url:"https://help.openai.com/en/articles/20001040-submitting-apps-to-the-chatgpt-app-directory"}],pL=[...Ng,...zg.map(e=>e.page)],Vh={},NE=[...Ng.map(e=>({page:e,url:`${To}/${e}`,revisionUrl:`${To}/${e}.md`,format:"markdown",revision:Vh[e]??null,snapshotDate:Hh})),...zg.map(e=>({page:e.page,url:e.url,revisionUrl:e.url,format:"html",revision:Vh[e.page]??null,snapshotDate:Hh}))],zE=Object.freeze(Object.fromEntries(NE.map(e=>[e.page,e])));function Bt(e,t){const r=zE[e];return{page:r.page,section:t,url:r.url,revision:r.revision,snapshotDate:r.snapshotDate}}var fL=["runtime-compatibility","directory-policy","plugin-package","release-contract","optional-features","submission-artifacts","experience-insights"],Tn={serverUrl:"serverUrl",pluginBundle:"pluginBundle",submissionProfile:"submissionProfile",draftSnapshot:"draftSnapshot",publishedSnapshot:"publishedSnapshot",toolListing:"toolListing",importedSkills:"importedSkills"},vL=Object.freeze({"skills-only":{hasMcpServer:!1,hasUploadedPackage:!0,hasImportedSkills:!1,requiredInputs:[Tn.pluginBundle],summary:"a skills package with no MCP server"},"mcp-only":{hasMcpServer:!0,hasUploadedPackage:!1,hasImportedSkills:!1,requiredInputs:[Tn.serverUrl],summary:"an MCP endpoint with no uploaded package"},"mcp-imported-skills":{hasMcpServer:!0,hasUploadedPackage:!1,hasImportedSkills:!0,requiredInputs:[Tn.serverUrl,Tn.importedSkills],summary:"an MCP endpoint whose skills are imported at scan time"},"mcp-uploaded-skills":{hasMcpServer:!0,hasUploadedPackage:!0,hasImportedSkills:!1,requiredInputs:[Tn.serverUrl,Tn.pluginBundle],summary:"an MCP endpoint plus an uploaded skills package"}}),gL=Object.freeze({"technical-preflight":["runtime-compatibility","directory-policy","plugin-package"],"submission-ready":["runtime-compatibility","directory-policy","plugin-package","submission-artifacts","release-contract"]});function UE(e){return typeof e=="object"&&e!==null&&e.readinessKind==="openai-directory-readiness"}var FE=["experience"];var qE=["openai.experience.tool-descriptions-uninformative","openai.experience.tool-overlap","openai.experience.naming-inconsistent","openai.experience.listing-copy-placeholder","openai.experience.listing-copy-overpromises","openai.experience.skill-overlap","openai.experience.destructive-tool-underexplained","openai.experience.auth-story-unclear"],mL=Object.freeze({readinessKind:"openai-directory-readiness",observationKinds:FE,knownIds:qE,schemaVersion:"1"}),jE=[{id:"openai.experience.tool-descriptions-uninformative",title:"Tool descriptions may not tell the model when to use the tool",lane:"experience-insights",class:"heuristic",source:Bt("guides/optimize-metadata","§Tool descriptions"),remediation:"Describe when a tool should be reached for, not only what it does; the model picks tools from these sentences."},{id:"openai.experience.tool-overlap",title:"Two or more tools may cover the same job",lane:"experience-insights",class:"heuristic",source:Bt("plan/tools","§Naming"),remediation:"Overlapping tools make selection ambiguous; consider merging them or sharpening the descriptions that separate them."},{id:"openai.experience.naming-inconsistent",title:"Tool names may not follow one convention",lane:"experience-insights",class:"heuristic",source:Bt("plan/tools","§Naming"),remediation:"Pick one naming convention across the whole surface; mixed conventions read as two servers merged."},{id:"openai.experience.listing-copy-placeholder",title:"Listing copy may still contain placeholder text",lane:"experience-insights",class:"manual-review",source:Bt("app-guidelines","§Listing quality"),remediation:"Review the listing fields for template text before submitting; reviewers reject placeholder copy."},{id:"openai.experience.listing-copy-overpromises",title:"Listing copy may claim capabilities the tools do not implement",lane:"experience-insights",class:"manual-review",source:Bt("app-guidelines","§Listing quality"),remediation:"Check that every capability the listing advertises is reachable through a tool this server actually exposes."},{id:"openai.experience.skill-overlap",title:"Two or more skills may describe the same task",lane:"experience-insights",class:"heuristic",source:Bt("app-guidelines","§Listing quality"),remediation:"Skills that overlap compete for the same trigger; separate their scopes or fold them together."},{id:"openai.experience.destructive-tool-underexplained",title:"A destructive tool may not explain its consequences",lane:"experience-insights",class:"manual-review",source:Bt("app-guidelines","§Predictable side effects"),remediation:"Say plainly in the description what a destructive tool changes and whether it can be undone."},{id:"openai.experience.auth-story-unclear",title:"It may not be clear to a user what they are authorizing",lane:"experience-insights",class:"manual-review",source:Bt("build/auth","§Consent"),remediation:"State which account is connected and what scope it grants, in the copy the user sees at consent time."}],_L=Object.freeze({experienceLane:"experience-insights",engineVersion:"2",mappings:jE}),HE=["https://claude.ai/api/mcp/auth_callback","https://claude.com/api/mcp/auth_callback"];var VE=".claudemcpcontent.com";var BE="text/html;profile=mcp-app",GE={toolListingMs:5e3,handshakeMs:3e3,widgetFirstPaintMs:3e3},WE={minViewportWidthPx:320,minTouchTargetPx:44},mr={nameMaxLength:100,taglineMaxLength:55,descriptionMaxLength:2e3,categoriesMin:1,categoriesMax:5,screenshotsMin:3,screenshotsMax:5,screenshotMinWidthPx:1e3,toolNameMaxLength:64},yL={callbackUrls:HE,loopbackRedirectIgnoresPort:!0,appContentDomainSuffix:VE,appContentDomainHashLength:32,appHtmlMime:BE,latencyBudgets:GE,appDesignBudgets:WE,submissionLimits:mr,source:gr("directory","Host profile constants")},bL=Object.freeze({status:"aborted"});function x(e,t,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:o,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);const l=o.prototype,u=Object.keys(l);for(let h=0;h<u.length;h++){const d=u[h];d in a||(a[d]=l[d].bind(a))}}const i=r?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:e});function o(a){var c;const l=r?.Parent?new s:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(const u of l._zod.deferred)u();return l}return Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var Bn=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ug=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}},ul={};function Dr(e){return e&&Object.assign(ul,e),ul}function Fg(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,n])=>t.indexOf(+r)===-1).map(([r,n])=>n)}function dl(e,t){return typeof t=="bigint"?t.toString():t}function Qo(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function fu(e){return e==null}function vu(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function ZE(e,t){const r=(e.toString().split(".")[1]||"").length,n=t.toString();let i=(n.split(".")[1]||"").length;if(i===0&&/\d?e-\d?/.test(n)){const o=n.match(/\d?e-(\d?)/);o?.[1]&&(i=Number.parseInt(o[1]))}const s=r>i?r:i;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}var Bh=Symbol("evaluating");function Ae(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==Bh)return n===void 0&&(n=Bh,n=r()),n},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function yn(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Br(...e){const t={};for(const r of e){const n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function Gh(e){return JSON.stringify(e)}function JE(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var qg="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ns(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var KE=Qo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch{return!1}});function ri(e){if(ns(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(ns(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function jg(e){return ri(e)?{...e}:Array.isArray(e)?[...e]:e}var YE=new Set(["string","number","symbol"]);function ni(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dr(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function re(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function XE(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var QE={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function ek(e,t){const r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return dr(e,Br(e._zod.def,{get shape(){const i={};for(const s in t){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&(i[s]=r.shape[s])}return yn(this,"shape",i),i},checks:[]}))}function tk(e,t){const r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");return dr(e,Br(e._zod.def,{get shape(){const i={...e._zod.def.shape};for(const s in t){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&delete i[s]}return yn(this,"shape",i),i},checks:[]}))}function rk(e,t){if(!ri(t))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0){const n=e._zod.def.shape;for(const i in t)if(Object.getOwnPropertyDescriptor(n,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return dr(e,Br(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return yn(this,"shape",n),n}}))}function nk(e,t){if(!ri(t))throw new Error("Invalid input to safeExtend: expected a plain object");return dr(e,Br(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return yn(this,"shape",r),r}}))}function ik(e,t){return dr(e,Br(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return yn(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:[]}))}function sk(e,t,r){const n=t._zod.def.checks;if(n&&n.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");return dr(t,Br(t._zod.def,{get shape(){const i=t._zod.def.shape,s={...i};if(r)for(const o in r){if(!(o in i))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=e?new e({type:"optional",innerType:i[o]}):i[o])}else for(const o in i)s[o]=e?new e({type:"optional",innerType:i[o]}):i[o];return yn(this,"shape",s),s},checks:[]}))}function ok(e,t,r){return dr(t,Br(t._zod.def,{get shape(){const n=t._zod.def.shape,i={...n};if(r)for(const s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(const s in n)i[s]=new e({type:"nonoptional",innerType:n[s]});return yn(this,"shape",i),i}}))}function xn(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function on(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Cs(e){return typeof e=="string"?e:e?.message}function Nr(e,t,r){const n={...e,path:e.path??[]};return e.message||(n.message=Cs(e.inst?._zod.def?.error?.(e))??Cs(t?.error?.(e))??Cs(r.customError?.(e))??Cs(r.localeError?.(e))??"Invalid input"),delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function gu(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function is(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}var Hg=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,dl,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Vg=x("$ZodError",Hg),Bg=x("$ZodError",Hg,{Parent:Error});function ak(e,t=r=>r.message){const r={},n=[];for(const i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}function ck(e,t=r=>r.message){const r={_errors:[]},n=i=>{for(const s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(o=>n({issues:o}));else if(s.code==="invalid_key")n({issues:s.issues});else if(s.code==="invalid_element")n({issues:s.issues});else if(s.path.length===0)r._errors.push(t(s));else{let o=r,a=0;for(;a<s.path.length;){const c=s.path[a];a!==s.path.length-1?o[c]=o[c]||{_errors:[]}:(o[c]=o[c]||{_errors:[]},o[c]._errors.push(t(s))),o=o[c],a++}}};return n(e),r}var mu=e=>(t,r,n,i)=>{const s=n?Object.assign(n,{async:!1}):{async:!1},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Bn;if(o.issues.length){const a=new(i?.Err??e)(o.issues.map(c=>Nr(c,s,Dr())));throw qg(a,i?.callee),a}return o.value},_u=e=>async(t,r,n,i)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){const a=new(i?.Err??e)(o.issues.map(c=>Nr(c,s,Dr())));throw qg(a,i?.callee),a}return o.value},ea=e=>(t,r,n)=>{const i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Bn;return s.issues.length?{success:!1,error:new(e??Vg)(s.issues.map(o=>Nr(o,i,Dr())))}:{success:!0,data:s.value}},lk=ea(Bg),ta=e=>async(t,r,n)=>{const i=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(o=>Nr(o,i,Dr())))}:{success:!0,data:s.value}},uk=ta(Bg),dk=e=>(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return mu(e)(t,r,i)},hk=e=>(t,r,n)=>mu(e)(t,r,n),pk=e=>async(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return _u(e)(t,r,i)},fk=e=>async(t,r,n)=>_u(e)(t,r,n),vk=e=>(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return ea(e)(t,r,i)},gk=e=>(t,r,n)=>ea(e)(t,r,n),mk=e=>async(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return ta(e)(t,r,i)},_k=e=>async(t,r,n)=>ta(e)(t,r,n),yk=/^[cC][^\s-]{8,}$/,bk=/^[0-9a-z]+$/,wk=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Sk=/^[0-9a-vA-V]{20}$/,Ek=/^[A-Za-z0-9]{27}$/,kk=/^[a-zA-Z0-9_-]{21}$/,Rk=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ak=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Wh=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Ik=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Tk="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function $k(){return new RegExp(Tk,"u")}var Ck=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Pk=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Ok=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,xk=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Mk=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Gg=/^[A-Za-z0-9_-]*$/,Lk=/^\+[1-9]\d{6,14}$/,Wg="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Dk=new RegExp(`^${Wg}$`);function Zg(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Nk(e){return new RegExp(`^${Zg(e)}$`)}function zk(e){const t=Zg({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Wg}T(?:${n})$`)}var Uk=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Fk=/^-?\d+$/,Jg=/^-?\d+(?:\.\d+)?$/,qk=/^(?:true|false)$/i,jk=/^null$/i,Hk=/^undefined$/i,Vk=/^[^A-Z]*$/,Bk=/^[^a-z]*$/,St=x("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Kg={number:"number",bigint:"bigint",object:"date"},Yg=x("$ZodCheckLessThan",(e,t)=>{St.init(e,t);const r=Kg[typeof t.value];e._zod.onattach.push(n=>{const i=n._zod.bag,s=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Xg=x("$ZodCheckGreaterThan",(e,t)=>{St.init(e,t);const r=Kg[typeof t.value];e._zod.onattach.push(n=>{const i=n._zod.bag,s=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Gk=x("$ZodCheckMultipleOf",(e,t)=>{St.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):ZE(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Wk=x("$ZodCheckNumberFormat",(e,t)=>{St.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[i,s]=QE[t.format];e._zod.onattach.push(o=>{const a=o._zod.bag;a.format=t.format,a.minimum=i,a.maximum=s,r&&(a.pattern=Fk)}),e._zod.check=o=>{const a=o.value;if(r){if(!Number.isInteger(a)){o.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?o.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):o.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}a<i&&o.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>s&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),Zk=x("$ZodCheckMaxLength",(e,t)=>{var r;St.init(e,t),(r=e._zod.def).when??(r.when=n=>{const i=n.value;return!fu(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{const i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const i=n.value;if(i.length<=t.maximum)return;const s=gu(i);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Jk=x("$ZodCheckMinLength",(e,t)=>{var r;St.init(e,t),(r=e._zod.def).when??(r.when=n=>{const i=n.value;return!fu(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{const i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const i=n.value;if(i.length>=t.minimum)return;const s=gu(i);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Kk=x("$ZodCheckLengthEquals",(e,t)=>{var r;St.init(e,t),(r=e._zod.def).when??(r.when=n=>{const i=n.value;return!fu(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{const i=n._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=n=>{const i=n.value,s=i.length;if(s===t.length)return;const o=gu(i),a=s>t.length;n.issues.push({origin:o,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),ra=x("$ZodCheckStringFormat",(e,t)=>{var r,n;St.init(e,t),e._zod.onattach.push(i=>{const s=i._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Yk=x("$ZodCheckRegex",(e,t)=>{ra.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Xk=x("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Vk),ra.init(e,t)}),Qk=x("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Bk),ra.init(e,t)}),eR=x("$ZodCheckIncludes",(e,t)=>{St.init(e,t);const r=ni(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(i=>{const s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),tR=x("$ZodCheckStartsWith",(e,t)=>{St.init(e,t);const r=new RegExp(`^${ni(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),rR=x("$ZodCheckEndsWith",(e,t)=>{St.init(e,t);const r=new RegExp(`.*${ni(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),nR=x("$ZodCheckOverwrite",(e,t)=>{St.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}}),iR=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const t=e.split(`
1
+ import{t as ty}from"./failed-request-tracker-Cp9_VFMm.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};e.SENTRY_RELEASE={id:"3.12.5"};var t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4af54f1c-74bb-4b8c-9679-58258eb17592",e._sentryDebugIdIdentifier="sentry-dbid-4af54f1c-74bb-4b8c-9679-58258eb17592")}catch{}})();var Jx=null,Kx="write",Zu=null,ry=String(101376);function Yx(){return Zu?`https://discord.com/oauth2/authorize?${new URLSearchParams({client_id:Zu,scope:"bot applications.commands",permissions:ry}).toString()}`:null}var ny=["timeout","network","upstream_status","bad_json","bad_payload","provisioning"],iy=/^[A-Z][A-Z0-9_]{1,63}$/;function sy(e){return typeof e=="string"&&ny.includes(e)}function oy(e){if(!e||typeof e!="object")return;const{reason:t,upstreamStatus:r,networkCode:n}=e;if(!sy(t))return;const i={reason:t};return typeof r=="number"&&Number.isInteger(r)&&r>=100&&r<=599&&(i.upstreamStatus=r),typeof n=="string"&&iy.test(n)&&(i.networkCode=n),i}var Zp="mcpjam_guest_session_v1",bc="mcpjam_guest_activated",zo=3e5,bt=null,gr=null,mr=null,Kr=null,Jp=!1,Rr=0,wc=new Set,ay=6e5,In=null,di=null;function Kp(){for(const e of wc)e()}function Yp(e){di!==null&&(clearTimeout(di),di=null),In=e,e&&(di=setTimeout(()=>{di=null,In===e&&Yp(null)},Math.max(0,e.until-Date.now()))),Kp()}function cy(){return In&&In.until<=Date.now()&&(In=null),In}function Uo(e){const t=bt?.guestId??null;bt=e,t!==(bt?.guestId??null)&&Kp()}function Xx(e){return wc.add(e),()=>{wc.delete(e)}}function Qx(e){if(e)try{localStorage.getItem(bc)!==e&&localStorage.setItem(bc,e)}catch{}}function eM(e){if(!e)return!1;try{return localStorage.getItem(bc)===e}catch{return!1}}function ly(){if(typeof window>"u")return;const e=window.__MCP_GUEST_BOOTSTRAP__;try{delete window.__MCP_GUEST_BOOTSTRAP__}catch{window.__MCP_GUEST_BOOTSTRAP__=void 0}e&&(typeof e.token!="string"||e.token.length===0||typeof e.expiresAt!="number"||typeof e.guestId!="string"||e.guestId.length===0||e.expiresAt-zo<=Date.now()||(bt={guestId:e.guestId,token:e.token,expiresAt:e.expiresAt}))}ly();function Ll(){if(Jp)return null;try{const e=localStorage.getItem(Zp);if(!e)return null;const t=JSON.parse(e);return typeof t.token=="string"&&t.token.length>0?t.token:null}catch{return null}}function Ju(){try{localStorage.removeItem(Zp)}catch{}Jp=!0}var Ri=class extends Error{status;upstreamFailure;constructor(e,t,r){super(e),this.name="GuestSessionRequestError",this.status=t,this.upstreamFailure=r}},Xp=class extends Ri{retryAfterMs;constructor(e){super("guest-session creation refused (429)"),this.name="GuestSessionRefusedError",this.retryAfterMs=e}},uy=1e3;async function dy(e){if(typeof e.json!="function")return;let t;try{const r=await Promise.race([e.json(),new Promise(n=>{t=setTimeout(()=>n(void 0),uy)})]);return oy(r?.details)}catch{return}finally{t!==void 0&&clearTimeout(t)}}function hy(e){if(!e)return"";const t=e.networkCode??(e.upstreamStatus!==void 0?String(e.upstreamStatus):void 0);return` (${e.reason}${t?` ${t}`:""})`}function py(e){const t=e?Number.parseInt(e,10):NaN;return Number.isFinite(t)&&t>0?t*1e3:ay}async function Dl(e,t){const r={mode:e};t&&(r.legacyToken=t);let n;try{n=await fetch("/api/web/guest-session",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})}catch(s){throw new Ri(s instanceof Error?s.message:"network error")}if(n.status===204)return t&&Ju(),null;if(n.status===429)throw new Xp(py(n.headers?.get?.("retry-after")));if(!n.ok){const s=await dy(n);throw new Ri(`guest-session request failed: ${n.status} ${n.statusText}${hy(s)}`,n.status,s)}let i;try{i=await n.json()}catch(s){throw new Ri(`guest-session response was not valid JSON: ${s instanceof Error?s.message:String(s)}`)}if(typeof i?.token!="string"||typeof i?.expiresAt!="number")throw new Ri("guest-session response missing token or expiresAt");return t&&Ju(),i}async function fy(){if(bt&&bt.expiresAt-zo>Date.now())return bt;if(cy())return null;if(gr)return gr;const e=Ll(),t=Rr;let r=Promise.resolve(null);return r=(async()=>{try{const n=await Dl("lookup_or_create",e);return n&&t===Rr&&Uo(n),n}catch(n){if(n instanceof Xp)return Yp({until:Date.now()+n.retryAfterMs}),null;throw console.error("Failed to create guest session:",n),n}finally{gr===r&&(gr=null)}})(),gr=r,r.catch(()=>{}),gr}async function vy(){try{return await fy()}catch{return null}}async function tM(){return(await vy())?.token??null}function Sc(){return bt&&bt.expiresAt-zo>Date.now()?bt:null}async function gy(){if(bt&&bt.expiresAt-zo>Date.now())return bt.token;if(mr)return(await mr)?.token??null;const e=Ll(),t=Rr;let r=Promise.resolve(null);return r=(async()=>{try{const n=await Dl("lookup_only",e);return n&&t===Rr&&Uo(n),n}finally{mr===r&&(mr=null)}})(),mr=r,(await mr)?.token??null}async function rM(){const e=Sc();if(e?.guestId)return e.guestId;try{await gy()}catch{return null}return Sc()?.guestId??null}function my(){Rr+=1,Uo(null),gr=null,mr=null,Kr=null}async function nM(){let e=!1;try{const t=await fetch("/api/web/guest-session/revoke",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"}});if(t.ok)try{e=(await t.json())?.revoked===!0}catch{e=!1}}catch(t){console.error("Failed to revoke guest session:",t)}finally{my()}return e}async function iM(){try{const e=await fetch("/api/web/guest-session/promotion-proof",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"}});if(e.status===204||!e.ok)return null;const t=await e.json();return typeof t.token=="string"&&t.token.length>0?t.token:null}catch(e){return console.error("Failed to fetch guest promotion proof:",e),null}}async function _y(){if(Kr)return(await Kr)?.token??null;Rr+=1;const e=Rr;bt=null,gr=null,mr=null,Kr=(async()=>{try{const t=await Dl("lookup_or_create",Ll());return t&&e===Rr&&Uo(t),t}catch(t){throw console.error("Failed to refresh guest session:",t),t}})(),Kr.catch(()=>{});try{return(await Kr)?.token??null}finally{Kr=null}}async function sM(){try{return await _y()}catch{return null}}var oM=Object.freeze({maxObservations:24,maxSummaryChars:400,maxEvidenceRefs:8,maxEvidenceRefChars:200,maxModelIdChars:128,maxVersionChars:64}),aM=Object.freeze({status:"not-requested",reason:"not_requested",detail:"this run did not request model-backed observations, so nothing was charged"});function Qp(e){return e.status==="skipped"&&e.skipReason==="could-not-run"}function yy(e){return e.status==="skipped"&&e.skipReason!=="could-not-run"}function by(e){if(e.some(n=>n.status==="failed"))return{outcome:"failed"};const t=e.filter(Qp);if(t.length===0)return e.length===0?{outcome:"incomplete",incompleteReason:"no checks were selected, so this run establishes nothing"}:{outcome:"passed"};const r=Array.from(new Set(t.map(n=>n.error?.message??"reason unavailable")));return{outcome:"incomplete",incompleteReason:`${t.length} of ${e.length} selected check(s) could not run, so this run does not establish conformance (${t.map(n=>n.id).join(", ")}): ${r.join(" ")}`}}var wy="2026-08-19",Sy="https://docs.claude.com/en/docs/mcp",Ey=["directory","verification","submission","review-criteria","authentication","lazy-authentication","enterprise-managed-auth","troubleshooting","mcp-apps/cross-compatibility","mcp-apps/external-links","mcp-apps/troubleshooting","mcp-apps/design-guidelines"],ky={},Ry=Ey.map(e=>({page:e,url:`${Sy}/${e}`,revision:ky[e]??null,snapshotDate:wy})),Ay=Object.freeze(Object.fromEntries(Ry.map(e=>[e.page,e])));function hr(e,t){const r=Ay[e];return{page:r.page,section:t,url:r.url,revision:r.revision,snapshotDate:r.snapshotDate}}function ef(e){return e.class==="required"||e.class==="runtime-blocker"}var cM=["runtime-compatibility","directory-policy","optional-features","submission-artifacts","experience-insights"];function Iy(e){return ef(e)}var Ty=["experience"];var Cy=["claude.experience.tool-descriptions-uninformative","claude.experience.tool-overlap","claude.experience.connector-purpose-unclear","claude.experience.consent-scope-unclear","claude.experience.listing-copy-placeholder","claude.experience.destructive-tool-underexplained","claude.experience.app-copy-mismatched"],lM=Object.freeze({readinessKind:"claude-directory-readiness",observationKinds:Ty,knownIds:Cy,schemaVersion:"1"}),$y=[{id:"claude.experience.tool-descriptions-uninformative",title:"Tool descriptions may not tell Claude when to use the tool",lane:"experience-insights",class:"heuristic",source:hr("review-criteria","§Tool quality"),remediation:"Describe when a tool should be reached for, not only what it does; Claude picks tools from these sentences."},{id:"claude.experience.tool-overlap",title:"Two or more tools may cover the same job",lane:"experience-insights",class:"heuristic",source:hr("review-criteria","§Tool quality"),remediation:"Overlapping tools make selection ambiguous; consider merging them or sharpening what separates them."},{id:"claude.experience.connector-purpose-unclear",title:"What this connector is for may not be clear from its surface",lane:"experience-insights",class:"manual-review",source:hr("review-criteria","§Usefulness"),remediation:"A reviewer should be able to say what the connector is for from the listing and the tool names alone."},{id:"claude.experience.consent-scope-unclear",title:"It may not be clear to a user what they are authorizing",lane:"experience-insights",class:"manual-review",source:hr("authentication","§Consent"),remediation:"State which account is connected and what scope it grants, in the copy the user sees at consent time."},{id:"claude.experience.listing-copy-placeholder",title:"Listing copy may still contain placeholder text",lane:"experience-insights",class:"manual-review",source:hr("submission","§Listing"),remediation:"Review the listing fields for template text before submitting; reviewers reject placeholder copy."},{id:"claude.experience.destructive-tool-underexplained",title:"A destructive tool may not explain its consequences",lane:"experience-insights",class:"manual-review",source:hr("review-criteria","§Safety"),remediation:"Say plainly in the description what a destructive tool changes and whether it can be undone."},{id:"claude.experience.app-copy-mismatched",title:"An app's rendered copy may not match what its tool returns",lane:"experience-insights",class:"heuristic",source:hr("mcp-apps/design-guidelines","§Content"),remediation:"A widget that says something different from the tool's text response leaves the model and the user disagreeing."}],uM=Object.freeze({experienceLane:"experience-insights",engineVersion:"1",mappings:$y}),Ku="2026-08-19",eo="https://developers.openai.com/plugins",dM=`${eo}/llms.txt`,hM=`${eo}/changelog`,tf=["quickstart","app-guidelines","reference","changelog","plan/use-case","plan/tools","concepts/plugins","concepts/skills","concepts/ui-guidelines","build/plugins","build/skills","build/mcp-server","build/chatgpt-ui","build/auth","build/monetization","build/examples","deploy/connect-chatgpt","deploy/submission","deploy/submission-errors","deploy/troubleshooting","guides/optimize-metadata","guides/submit-claude-plugin","guides/product-checkout-conversion-spec"],rf=[{page:"help/plugins-in-chatgpt-and-codex",url:"https://help.openai.com/en/articles/20001256-plugins-in-chatgpt-and-codex"},{page:"help/submitting-apps-to-the-chatgpt-app-directory",url:"https://help.openai.com/en/articles/20001040-submitting-apps-to-the-chatgpt-app-directory"}],pM=[...tf,...rf.map(e=>e.page)],Yu={},Py=[...tf.map(e=>({page:e,url:`${eo}/${e}`,revisionUrl:`${eo}/${e}.md`,format:"markdown",revision:Yu[e]??null,snapshotDate:Ku})),...rf.map(e=>({page:e.page,url:e.url,revisionUrl:e.url,format:"html",revision:Yu[e.page]??null,snapshotDate:Ku}))],Oy=Object.freeze(Object.fromEntries(Py.map(e=>[e.page,e])));function jt(e,t){const r=Oy[e];return{page:r.page,section:t,url:r.url,revision:r.revision,snapshotDate:r.snapshotDate}}var fM=["runtime-compatibility","directory-policy","plugin-package","release-contract","optional-features","submission-artifacts","experience-insights"],_n={serverUrl:"serverUrl",pluginBundle:"pluginBundle",submissionProfile:"submissionProfile",draftSnapshot:"draftSnapshot",publishedSnapshot:"publishedSnapshot",toolListing:"toolListing",importedSkills:"importedSkills"},vM=Object.freeze({"skills-only":{hasMcpServer:!1,hasUploadedPackage:!0,hasImportedSkills:!1,requiredInputs:[_n.pluginBundle],summary:"a skills package with no MCP server"},"mcp-only":{hasMcpServer:!0,hasUploadedPackage:!1,hasImportedSkills:!1,requiredInputs:[_n.serverUrl],summary:"an MCP endpoint with no uploaded package"},"mcp-imported-skills":{hasMcpServer:!0,hasUploadedPackage:!1,hasImportedSkills:!0,requiredInputs:[_n.serverUrl,_n.importedSkills],summary:"an MCP endpoint whose skills are imported at scan time"},"mcp-uploaded-skills":{hasMcpServer:!0,hasUploadedPackage:!0,hasImportedSkills:!1,requiredInputs:[_n.serverUrl,_n.pluginBundle],summary:"an MCP endpoint plus an uploaded skills package"}}),gM=Object.freeze({"technical-preflight":["runtime-compatibility","directory-policy","plugin-package"],"submission-ready":["runtime-compatibility","directory-policy","plugin-package","submission-artifacts","release-contract"]});function xy(e){return typeof e=="object"&&e!==null&&e.readinessKind==="openai-directory-readiness"}var My=["experience"];var Ly=["openai.experience.tool-descriptions-uninformative","openai.experience.tool-overlap","openai.experience.naming-inconsistent","openai.experience.listing-copy-placeholder","openai.experience.listing-copy-overpromises","openai.experience.skill-overlap","openai.experience.destructive-tool-underexplained","openai.experience.auth-story-unclear"],mM=Object.freeze({readinessKind:"openai-directory-readiness",observationKinds:My,knownIds:Ly,schemaVersion:"1"}),Dy=[{id:"openai.experience.tool-descriptions-uninformative",title:"Tool descriptions may not tell the model when to use the tool",lane:"experience-insights",class:"heuristic",source:jt("guides/optimize-metadata","§Tool descriptions"),remediation:"Describe when a tool should be reached for, not only what it does; the model picks tools from these sentences."},{id:"openai.experience.tool-overlap",title:"Two or more tools may cover the same job",lane:"experience-insights",class:"heuristic",source:jt("plan/tools","§Naming"),remediation:"Overlapping tools make selection ambiguous; consider merging them or sharpening the descriptions that separate them."},{id:"openai.experience.naming-inconsistent",title:"Tool names may not follow one convention",lane:"experience-insights",class:"heuristic",source:jt("plan/tools","§Naming"),remediation:"Pick one naming convention across the whole surface; mixed conventions read as two servers merged."},{id:"openai.experience.listing-copy-placeholder",title:"Listing copy may still contain placeholder text",lane:"experience-insights",class:"manual-review",source:jt("app-guidelines","§Listing quality"),remediation:"Review the listing fields for template text before submitting; reviewers reject placeholder copy."},{id:"openai.experience.listing-copy-overpromises",title:"Listing copy may claim capabilities the tools do not implement",lane:"experience-insights",class:"manual-review",source:jt("app-guidelines","§Listing quality"),remediation:"Check that every capability the listing advertises is reachable through a tool this server actually exposes."},{id:"openai.experience.skill-overlap",title:"Two or more skills may describe the same task",lane:"experience-insights",class:"heuristic",source:jt("app-guidelines","§Listing quality"),remediation:"Skills that overlap compete for the same trigger; separate their scopes or fold them together."},{id:"openai.experience.destructive-tool-underexplained",title:"A destructive tool may not explain its consequences",lane:"experience-insights",class:"manual-review",source:jt("app-guidelines","§Predictable side effects"),remediation:"Say plainly in the description what a destructive tool changes and whether it can be undone."},{id:"openai.experience.auth-story-unclear",title:"It may not be clear to a user what they are authorizing",lane:"experience-insights",class:"manual-review",source:jt("build/auth","§Consent"),remediation:"State which account is connected and what scope it grants, in the copy the user sees at consent time."}],_M=Object.freeze({experienceLane:"experience-insights",engineVersion:"2",mappings:Dy}),Ny=["https://claude.ai/api/mcp/auth_callback","https://claude.com/api/mcp/auth_callback"];var zy=".claudemcpcontent.com";var Uy="text/html;profile=mcp-app",Fy={toolListingMs:5e3,handshakeMs:3e3,widgetFirstPaintMs:3e3},qy={minViewportWidthPx:320,minTouchTargetPx:44},pr={nameMaxLength:100,taglineMaxLength:55,descriptionMaxLength:2e3,categoriesMin:1,categoriesMax:5,screenshotsMin:3,screenshotsMax:5,screenshotMinWidthPx:1e3,toolNameMaxLength:64},yM={callbackUrls:Ny,loopbackRedirectIgnoresPort:!0,appContentDomainSuffix:zy,appContentDomainHashLength:32,appHtmlMime:Uy,latencyBudgets:Fy,appDesignBudgets:qy,submissionLimits:pr,source:hr("directory","Host profile constants")},bM=Object.freeze({status:"aborted"});function x(e,t,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:o,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);const l=o.prototype,u=Object.keys(l);for(let h=0;h<u.length;h++){const d=u[h];d in a||(a[d]=l[d].bind(a))}}const i=r?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:e});function o(a){var c;const l=r?.Parent?new s:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(const u of l._zod.deferred)u();return l}return Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var zn=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},nf=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}},Ec={};function Pr(e){return e&&Object.assign(Ec,e),Ec}function sf(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,n])=>t.indexOf(+r)===-1).map(([r,n])=>n)}function kc(e,t){return typeof t=="bigint"?t.toString():t}function Fo(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Nl(e){return e==null}function zl(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function jy(e,t){const r=(e.toString().split(".")[1]||"").length,n=t.toString();let i=(n.split(".")[1]||"").length;if(i===0&&/\d?e-\d?/.test(n)){const o=n.match(/\d?e-(\d?)/);o?.[1]&&(i=Number.parseInt(o[1]))}const s=r>i?r:i;return Number.parseInt(e.toFixed(s).replace(".",""))%Number.parseInt(t.toFixed(s).replace(".",""))/10**s}var Xu=Symbol("evaluating");function Ae(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==Xu)return n===void 0&&(n=Xu,n=r()),n},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function gn(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function jr(...e){const t={};for(const r of e){const n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function Qu(e){return JSON.stringify(e)}function Hy(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var of="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Gi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Vy=Fo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch{return!1}});function Bn(e){if(Gi(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(Gi(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function af(e){return Bn(e)?{...e}:Array.isArray(e)?[...e]:e}var By=new Set(["string","number","symbol"]);function Gn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function lr(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function re(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Gy(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Wy={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Zy(e,t){const r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return lr(e,jr(e._zod.def,{get shape(){const i={};for(const s in t){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&(i[s]=r.shape[s])}return gn(this,"shape",i),i},checks:[]}))}function Jy(e,t){const r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");return lr(e,jr(e._zod.def,{get shape(){const i={...e._zod.def.shape};for(const s in t){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&delete i[s]}return gn(this,"shape",i),i},checks:[]}))}function Ky(e,t){if(!Bn(t))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0){const n=e._zod.def.shape;for(const i in t)if(Object.getOwnPropertyDescriptor(n,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return lr(e,jr(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return gn(this,"shape",n),n}}))}function Yy(e,t){if(!Bn(t))throw new Error("Invalid input to safeExtend: expected a plain object");return lr(e,jr(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return gn(this,"shape",r),r}}))}function Xy(e,t){return lr(e,jr(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return gn(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:[]}))}function Qy(e,t,r){const n=t._zod.def.checks;if(n&&n.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");return lr(t,jr(t._zod.def,{get shape(){const i=t._zod.def.shape,s={...i};if(r)for(const o in r){if(!(o in i))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=e?new e({type:"optional",innerType:i[o]}):i[o])}else for(const o in i)s[o]=e?new e({type:"optional",innerType:i[o]}):i[o];return gn(this,"shape",s),s},checks:[]}))}function e0(e,t,r){return lr(t,jr(t._zod.def,{get shape(){const n=t._zod.def.shape,i={...n};if(r)for(const s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(const s in n)i[s]=new e({type:"nonoptional",innerType:n[s]});return gn(this,"shape",i),i}}))}function Tn(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function nn(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function vs(e){return typeof e=="string"?e:e?.message}function Or(e,t,r){const n={...e,path:e.path??[]};return e.message||(n.message=vs(e.inst?._zod.def?.error?.(e))??vs(t?.error?.(e))??vs(r.customError?.(e))??vs(r.localeError?.(e))??"Invalid input"),delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Ul(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Wi(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}var cf=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,kc,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},lf=x("$ZodError",cf),uf=x("$ZodError",cf,{Parent:Error});function t0(e,t=r=>r.message){const r={},n=[];for(const i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}function r0(e,t=r=>r.message){const r={_errors:[]},n=i=>{for(const s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(o=>n({issues:o}));else if(s.code==="invalid_key")n({issues:s.issues});else if(s.code==="invalid_element")n({issues:s.issues});else if(s.path.length===0)r._errors.push(t(s));else{let o=r,a=0;for(;a<s.path.length;){const c=s.path[a];a!==s.path.length-1?o[c]=o[c]||{_errors:[]}:(o[c]=o[c]||{_errors:[]},o[c]._errors.push(t(s))),o=o[c],a++}}};return n(e),r}var Fl=e=>(t,r,n,i)=>{const s=n?Object.assign(n,{async:!1}):{async:!1},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new zn;if(o.issues.length){const a=new(i?.Err??e)(o.issues.map(c=>Or(c,s,Pr())));throw of(a,i?.callee),a}return o.value},ql=e=>async(t,r,n,i)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){const a=new(i?.Err??e)(o.issues.map(c=>Or(c,s,Pr())));throw of(a,i?.callee),a}return o.value},qo=e=>(t,r,n)=>{const i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new zn;return s.issues.length?{success:!1,error:new(e??lf)(s.issues.map(o=>Or(o,i,Pr())))}:{success:!0,data:s.value}},n0=qo(uf),jo=e=>async(t,r,n)=>{const i=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(o=>Or(o,i,Pr())))}:{success:!0,data:s.value}},i0=jo(uf),s0=e=>(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Fl(e)(t,r,i)},o0=e=>(t,r,n)=>Fl(e)(t,r,n),a0=e=>async(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return ql(e)(t,r,i)},c0=e=>async(t,r,n)=>ql(e)(t,r,n),l0=e=>(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return qo(e)(t,r,i)},u0=e=>(t,r,n)=>qo(e)(t,r,n),d0=e=>async(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return jo(e)(t,r,i)},h0=e=>async(t,r,n)=>jo(e)(t,r,n),p0=/^[cC][^\s-]{8,}$/,f0=/^[0-9a-z]+$/,v0=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,g0=/^[0-9a-vA-V]{20}$/,m0=/^[A-Za-z0-9]{27}$/,_0=/^[a-zA-Z0-9_-]{21}$/,y0=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,b0=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ed=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,w0=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,S0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function E0(){return new RegExp(S0,"u")}var k0=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,R0=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,A0=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,I0=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,T0=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,df=/^[A-Za-z0-9_-]*$/,C0=/^\+[1-9]\d{6,14}$/,hf="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",$0=new RegExp(`^${hf}$`);function pf(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function P0(e){return new RegExp(`^${pf(e)}$`)}function O0(e){const t=pf({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${hf}T(?:${n})$`)}var x0=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},M0=/^-?\d+$/,ff=/^-?\d+(?:\.\d+)?$/,L0=/^(?:true|false)$/i,D0=/^null$/i,N0=/^undefined$/i,z0=/^[^A-Z]*$/,U0=/^[^a-z]*$/,wt=x("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),vf={number:"number",bigint:"bigint",object:"date"},gf=x("$ZodCheckLessThan",(e,t)=>{wt.init(e,t);const r=vf[typeof t.value];e._zod.onattach.push(n=>{const i=n._zod.bag,s=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),mf=x("$ZodCheckGreaterThan",(e,t)=>{wt.init(e,t);const r=vf[typeof t.value];e._zod.onattach.push(n=>{const i=n._zod.bag,s=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),F0=x("$ZodCheckMultipleOf",(e,t)=>{wt.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):jy(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),q0=x("$ZodCheckNumberFormat",(e,t)=>{wt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[i,s]=Wy[t.format];e._zod.onattach.push(o=>{const a=o._zod.bag;a.format=t.format,a.minimum=i,a.maximum=s,r&&(a.pattern=M0)}),e._zod.check=o=>{const a=o.value;if(r){if(!Number.isInteger(a)){o.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?o.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):o.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}a<i&&o.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>s&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),j0=x("$ZodCheckMaxLength",(e,t)=>{var r;wt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const i=n.value;return!Nl(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{const i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const i=n.value;if(i.length<=t.maximum)return;const s=Ul(i);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),H0=x("$ZodCheckMinLength",(e,t)=>{var r;wt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const i=n.value;return!Nl(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{const i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const i=n.value;if(i.length>=t.minimum)return;const s=Ul(i);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),V0=x("$ZodCheckLengthEquals",(e,t)=>{var r;wt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const i=n.value;return!Nl(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{const i=n._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=n=>{const i=n.value,s=i.length;if(s===t.length)return;const o=Ul(i),a=s>t.length;n.issues.push({origin:o,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ho=x("$ZodCheckStringFormat",(e,t)=>{var r,n;wt.init(e,t),e._zod.onattach.push(i=>{const s=i._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),B0=x("$ZodCheckRegex",(e,t)=>{Ho.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),G0=x("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=z0),Ho.init(e,t)}),W0=x("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=U0),Ho.init(e,t)}),Z0=x("$ZodCheckIncludes",(e,t)=>{wt.init(e,t);const r=Gn(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(i=>{const s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),J0=x("$ZodCheckStartsWith",(e,t)=>{wt.init(e,t);const r=new RegExp(`^${Gn(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),K0=x("$ZodCheckEndsWith",(e,t)=>{wt.init(e,t);const r=new RegExp(`.*${Gn(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Y0=x("$ZodCheckOverwrite",(e,t)=>{wt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}}),X0=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const t=e.split(`
8
2
  `).filter(i=>i),r=Math.min(...t.map(i=>i.length-i.trimStart().length)),n=t.map(i=>i.slice(r)).map(i=>" ".repeat(this.indent*2)+i);for(const i of n)this.content.push(i)}compile(){const e=Function,t=this?.args,r=[...(this?.content??[""]).map(n=>` ${n}`)];return new e(...t,r.join(`
9
- `))}},sR={major:4,minor:3,patch:6},Me=x("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=sR;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const i of n)for(const s of i._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(o,a,c)=>{let l=xn(o),u;for(const h of a){if(h._zod.def.when){if(!h._zod.def.when(o))continue}else if(l)continue;const d=o.issues.length,p=h._zod.check(o);if(p instanceof Promise&&c?.async===!1)throw new Bn;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,o.issues.length!==d&&(l||(l=xn(o,d)))});else{if(o.issues.length===d)continue;l||(l=xn(o,d))}}return u?u.then(()=>o):o},s=(o,a,c)=>{if(xn(o))return o.aborted=!0,o;const l=i(a,n,c);if(l instanceof Promise){if(c.async===!1)throw new Bn;return l.then(u=>e._zod.parse(u,c))}return e._zod.parse(l,c)};e._zod.run=(o,a)=>{if(a.skipChecks)return e._zod.parse(o,a);if(a.direction==="backward"){const l=e._zod.parse({value:o.value,issues:[]},{...a,skipChecks:!0});return l instanceof Promise?l.then(u=>s(u,o,a)):s(l,o,a)}const c=e._zod.parse(o,a);if(c instanceof Promise){if(a.async===!1)throw new Bn;return c.then(l=>i(l,n,a))}return i(c,n,a)}}Ae(e,"~standard",()=>({validate:i=>{try{const s=lk(e,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return uk(e,i).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}))}),yu=x("$ZodString",(e,t)=>{Me.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Uk(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Ze=x("$ZodStringFormat",(e,t)=>{ra.init(e,t),yu.init(e,t)}),oR=x("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Ak),Ze.init(e,t)}),aR=x("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Wh(r))}else t.pattern??(t.pattern=Wh());Ze.init(e,t)}),cR=x("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ik),Ze.init(e,t)}),lR=x("$ZodURL",(e,t)=>{Ze.init(e,t),e._zod.check=r=>{try{const n=r.value.trim(),i=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=i.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),uR=x("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=$k()),Ze.init(e,t)}),dR=x("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=kk),Ze.init(e,t)}),hR=x("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=yk),Ze.init(e,t)}),pR=x("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=bk),Ze.init(e,t)}),fR=x("$ZodULID",(e,t)=>{t.pattern??(t.pattern=wk),Ze.init(e,t)}),vR=x("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Sk),Ze.init(e,t)}),gR=x("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ek),Ze.init(e,t)}),mR=x("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=zk(t)),Ze.init(e,t)}),_R=x("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Dk),Ze.init(e,t)}),yR=x("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Nk(t)),Ze.init(e,t)}),bR=x("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Rk),Ze.init(e,t)}),wR=x("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ck),Ze.init(e,t),e._zod.bag.format="ipv4"}),SR=x("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Pk),Ze.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),ER=x("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Ok),Ze.init(e,t)}),kR=x("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=xk),Ze.init(e,t),e._zod.check=r=>{const n=r.value.split("/");try{if(n.length!==2)throw new Error;const[i,s]=n;if(!s)throw new Error;const o=Number(s);if(`${o}`!==s)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${i}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Qg(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var RR=x("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Mk),Ze.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{Qg(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function AR(e){if(!Gg.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/");return Qg(t.padEnd(Math.ceil(t.length/4)*4,"="))}var IR=x("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Gg),Ze.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{AR(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),TR=x("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Lk),Ze.init(e,t)});function $R(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const i=JSON.parse(atob(n));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}var CR=x("$ZodJWT",(e,t)=>{Ze.init(e,t),e._zod.check=r=>{$R(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),em=x("$ZodNumber",(e,t)=>{Me.init(e,t),e._zod.pattern=e._zod.bag.pattern??Jg,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;const s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...s?{received:s}:{}}),r}}),PR=x("$ZodNumberFormat",(e,t)=>{Wk.init(e,t),em.init(e,t)}),OR=x("$ZodBoolean",(e,t)=>{Me.init(e,t),e._zod.pattern=qk,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}const i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}}),xR=x("$ZodUndefined",(e,t)=>{Me.init(e,t),e._zod.pattern=Hk,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(r,n)=>{const i=r.value;return typeof i>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:i,inst:e}),r}}),MR=x("$ZodNull",(e,t)=>{Me.init(e,t),e._zod.pattern=jk,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),r}}),LR=x("$ZodAny",(e,t)=>{Me.init(e,t),e._zod.parse=r=>r}),DR=x("$ZodUnknown",(e,t)=>{Me.init(e,t),e._zod.parse=r=>r}),NR=x("$ZodNever",(e,t)=>{Me.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Zh(e,t,r){e.issues.length&&t.issues.push(...on(r,e.issues)),t.value[r]=e.value}var zR=x("$ZodArray",(e,t)=>{Me.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);const s=[];for(let o=0;o<i.length;o++){const a=i[o],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(l=>Zh(l,r,o))):Zh(c,r,o)}return s.length?Promise.all(s).then(()=>r):r}});function $o(e,t,r,n,i){if(e.issues.length){if(i&&!(r in n))return;t.issues.push(...on(r,e.issues))}e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}function tm(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const r=XE(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function rm(e,t,r,n,i,s){const o=[],a=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optout==="optional";for(const h in t){if(a.has(h))continue;if(l==="never"){o.push(h);continue}const d=c.run({value:t[h],issues:[]},n);d instanceof Promise?e.push(d.then(p=>$o(p,r,h,t,u))):$o(d,r,h,t,u)}return o.length&&r.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:s}),e.length?Promise.all(e).then(()=>r):r}var UR=x("$ZodObject",(e,t)=>{if(Me.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const o=t.shape;Object.defineProperty(t,"shape",{get:()=>{const a={...o};return Object.defineProperty(t,"shape",{value:a}),a}})}const r=Qo(()=>tm(t));Ae(e._zod,"propValues",()=>{const o=t.shape,a={};for(const c in o){const l=o[c]._zod;if(l.values){a[c]??(a[c]=new Set);for(const u of l.values)a[c].add(u)}}return a});const n=ns,i=t.catchall;let s;e._zod.parse=(o,a)=>{s??(s=r.value);const c=o.value;if(!n(c))return o.issues.push({expected:"object",code:"invalid_type",input:c,inst:e}),o;o.value={};const l=[],u=s.shape;for(const h of s.keys){const d=u[h],p=d._zod.optout==="optional",f=d._zod.run({value:c[h],issues:[]},a);f instanceof Promise?l.push(f.then(v=>$o(v,o,h,c,p))):$o(f,o,h,c,p)}return i?rm(l,c,o,a,r.value,e):l.length?Promise.all(l).then(()=>o):o}}),FR=x("$ZodObjectJIT",(e,t)=>{UR.init(e,t);const r=e._zod.parse,n=Qo(()=>tm(t)),i=d=>{const p=new iR(["shape","payload","ctx"]),f=n.value,v=S=>{const T=Gh(S);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};p.write("const input = payload.value;");const m=Object.create(null);let _=0;for(const S of f.keys)m[S]=`key_${_++}`;p.write("const newResult = {};");for(const S of f.keys){const T=m[S],I=Gh(S),C=d[S]?._zod?.optout==="optional";p.write(`const ${T} = ${v(S)};`),C?p.write(`
3
+ `))}},Q0={major:4,minor:3,patch:6},Me=x("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Q0;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const i of n)for(const s of i._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(o,a,c)=>{let l=Tn(o),u;for(const h of a){if(h._zod.def.when){if(!h._zod.def.when(o))continue}else if(l)continue;const d=o.issues.length,p=h._zod.check(o);if(p instanceof Promise&&c?.async===!1)throw new zn;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,o.issues.length!==d&&(l||(l=Tn(o,d)))});else{if(o.issues.length===d)continue;l||(l=Tn(o,d))}}return u?u.then(()=>o):o},s=(o,a,c)=>{if(Tn(o))return o.aborted=!0,o;const l=i(a,n,c);if(l instanceof Promise){if(c.async===!1)throw new zn;return l.then(u=>e._zod.parse(u,c))}return e._zod.parse(l,c)};e._zod.run=(o,a)=>{if(a.skipChecks)return e._zod.parse(o,a);if(a.direction==="backward"){const l=e._zod.parse({value:o.value,issues:[]},{...a,skipChecks:!0});return l instanceof Promise?l.then(u=>s(u,o,a)):s(l,o,a)}const c=e._zod.parse(o,a);if(c instanceof Promise){if(a.async===!1)throw new zn;return c.then(l=>i(l,n,a))}return i(c,n,a)}}Ae(e,"~standard",()=>({validate:i=>{try{const s=n0(e,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return i0(e,i).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}))}),jl=x("$ZodString",(e,t)=>{Me.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??x0(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Ze=x("$ZodStringFormat",(e,t)=>{Ho.init(e,t),jl.init(e,t)}),eb=x("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=b0),Ze.init(e,t)}),tb=x("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ed(r))}else t.pattern??(t.pattern=ed());Ze.init(e,t)}),rb=x("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=w0),Ze.init(e,t)}),nb=x("$ZodURL",(e,t)=>{Ze.init(e,t),e._zod.check=r=>{try{const n=r.value.trim(),i=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=i.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),ib=x("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=E0()),Ze.init(e,t)}),sb=x("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=_0),Ze.init(e,t)}),ob=x("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=p0),Ze.init(e,t)}),ab=x("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=f0),Ze.init(e,t)}),cb=x("$ZodULID",(e,t)=>{t.pattern??(t.pattern=v0),Ze.init(e,t)}),lb=x("$ZodXID",(e,t)=>{t.pattern??(t.pattern=g0),Ze.init(e,t)}),ub=x("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=m0),Ze.init(e,t)}),db=x("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=O0(t)),Ze.init(e,t)}),hb=x("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=$0),Ze.init(e,t)}),pb=x("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=P0(t)),Ze.init(e,t)}),fb=x("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=y0),Ze.init(e,t)}),vb=x("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=k0),Ze.init(e,t),e._zod.bag.format="ipv4"}),gb=x("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=R0),Ze.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),mb=x("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=A0),Ze.init(e,t)}),_b=x("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=I0),Ze.init(e,t),e._zod.check=r=>{const n=r.value.split("/");try{if(n.length!==2)throw new Error;const[i,s]=n;if(!s)throw new Error;const o=Number(s);if(`${o}`!==s)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${i}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function _f(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var yb=x("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=T0),Ze.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{_f(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function bb(e){if(!df.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/");return _f(t.padEnd(Math.ceil(t.length/4)*4,"="))}var wb=x("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=df),Ze.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{bb(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Sb=x("$ZodE164",(e,t)=>{t.pattern??(t.pattern=C0),Ze.init(e,t)});function Eb(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const i=JSON.parse(atob(n));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}var kb=x("$ZodJWT",(e,t)=>{Ze.init(e,t),e._zod.check=r=>{Eb(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),yf=x("$ZodNumber",(e,t)=>{Me.init(e,t),e._zod.pattern=e._zod.bag.pattern??ff,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;const s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...s?{received:s}:{}}),r}}),Rb=x("$ZodNumberFormat",(e,t)=>{q0.init(e,t),yf.init(e,t)}),Ab=x("$ZodBoolean",(e,t)=>{Me.init(e,t),e._zod.pattern=L0,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}const i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}}),Ib=x("$ZodUndefined",(e,t)=>{Me.init(e,t),e._zod.pattern=N0,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(r,n)=>{const i=r.value;return typeof i>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:i,inst:e}),r}}),Tb=x("$ZodNull",(e,t)=>{Me.init(e,t),e._zod.pattern=D0,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),r}}),Cb=x("$ZodAny",(e,t)=>{Me.init(e,t),e._zod.parse=r=>r}),$b=x("$ZodUnknown",(e,t)=>{Me.init(e,t),e._zod.parse=r=>r}),Pb=x("$ZodNever",(e,t)=>{Me.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function td(e,t,r){e.issues.length&&t.issues.push(...nn(r,e.issues)),t.value[r]=e.value}var Ob=x("$ZodArray",(e,t)=>{Me.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);const s=[];for(let o=0;o<i.length;o++){const a=i[o],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(l=>td(l,r,o))):td(c,r,o)}return s.length?Promise.all(s).then(()=>r):r}});function to(e,t,r,n,i){if(e.issues.length){if(i&&!(r in n))return;t.issues.push(...nn(r,e.issues))}e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}function bf(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const r=Gy(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function wf(e,t,r,n,i,s){const o=[],a=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optout==="optional";for(const h in t){if(a.has(h))continue;if(l==="never"){o.push(h);continue}const d=c.run({value:t[h],issues:[]},n);d instanceof Promise?e.push(d.then(p=>to(p,r,h,t,u))):to(d,r,h,t,u)}return o.length&&r.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:s}),e.length?Promise.all(e).then(()=>r):r}var xb=x("$ZodObject",(e,t)=>{if(Me.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const o=t.shape;Object.defineProperty(t,"shape",{get:()=>{const a={...o};return Object.defineProperty(t,"shape",{value:a}),a}})}const r=Fo(()=>bf(t));Ae(e._zod,"propValues",()=>{const o=t.shape,a={};for(const c in o){const l=o[c]._zod;if(l.values){a[c]??(a[c]=new Set);for(const u of l.values)a[c].add(u)}}return a});const n=Gi,i=t.catchall;let s;e._zod.parse=(o,a)=>{s??(s=r.value);const c=o.value;if(!n(c))return o.issues.push({expected:"object",code:"invalid_type",input:c,inst:e}),o;o.value={};const l=[],u=s.shape;for(const h of s.keys){const d=u[h],p=d._zod.optout==="optional",f=d._zod.run({value:c[h],issues:[]},a);f instanceof Promise?l.push(f.then(v=>to(v,o,h,c,p))):to(f,o,h,c,p)}return i?wf(l,c,o,a,r.value,e):l.length?Promise.all(l).then(()=>o):o}}),Mb=x("$ZodObjectJIT",(e,t)=>{xb.init(e,t);const r=e._zod.parse,n=Fo(()=>bf(t)),i=d=>{const p=new X0(["shape","payload","ctx"]),f=n.value,v=S=>{const T=Qu(S);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};p.write("const input = payload.value;");const m=Object.create(null);let _=0;for(const S of f.keys)m[S]=`key_${_++}`;p.write("const newResult = {};");for(const S of f.keys){const T=m[S],C=Qu(S),$=d[S]?._zod?.optout==="optional";p.write(`const ${T} = ${v(S)};`),$?p.write(`
10
4
  if (${T}.issues.length) {
11
- if (${I} in input) {
5
+ if (${C} in input) {
12
6
  payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
13
7
  ...iss,
14
- path: iss.path ? [${I}, ...iss.path] : [${I}]
8
+ path: iss.path ? [${C}, ...iss.path] : [${C}]
15
9
  })));
16
10
  }
17
11
  }
18
12
 
19
13
  if (${T}.value === undefined) {
20
- if (${I} in input) {
21
- newResult[${I}] = undefined;
14
+ if (${C} in input) {
15
+ newResult[${C}] = undefined;
22
16
  }
23
17
  } else {
24
- newResult[${I}] = ${T}.value;
18
+ newResult[${C}] = ${T}.value;
25
19
  }
26
20
 
27
21
  `):p.write(`
28
22
  if (${T}.issues.length) {
29
23
  payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
30
24
  ...iss,
31
- path: iss.path ? [${I}, ...iss.path] : [${I}]
25
+ path: iss.path ? [${C}, ...iss.path] : [${C}]
32
26
  })));
33
27
  }
34
28
 
35
29
  if (${T}.value === undefined) {
36
- if (${I} in input) {
37
- newResult[${I}] = undefined;
30
+ if (${C} in input) {
31
+ newResult[${C}] = undefined;
38
32
  }
39
33
  } else {
40
- newResult[${I}] = ${T}.value;
34
+ newResult[${C}] = ${T}.value;
41
35
  }
42
36
 
43
- `)}p.write("payload.value = newResult;"),p.write("return payload;");const w=p.compile();return(S,T)=>w(d,S,T)};let s;const o=ns,a=!ul.jitless,l=a&&KE.value,u=t.catchall;let h;e._zod.parse=(d,p)=>{h??(h=n.value);const f=d.value;return o(f)?a&&l&&p?.async===!1&&p.jitless!==!0?(s||(s=i(t.shape)),d=s(d,p),u?rm([],f,d,p,h,e):d):r(d,p):(d.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),d)}});function Jh(e,t,r,n){for(const s of e)if(s.issues.length===0)return t.value=s.value,t;const i=e.filter(s=>!xn(s));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(s=>s.issues.map(o=>Nr(o,n,Dr())))}),t)}var nm=x("$ZodUnion",(e,t)=>{Me.init(e,t),Ae(e._zod,"optin",()=>t.options.some(i=>i._zod.optin==="optional")?"optional":void 0),Ae(e._zod,"optout",()=>t.options.some(i=>i._zod.optout==="optional")?"optional":void 0),Ae(e._zod,"values",()=>{if(t.options.every(i=>i._zod.values))return new Set(t.options.flatMap(i=>Array.from(i._zod.values)))}),Ae(e._zod,"pattern",()=>{if(t.options.every(i=>i._zod.pattern)){const i=t.options.map(s=>s._zod.pattern);return new RegExp(`^(${i.map(s=>vu(s.source)).join("|")})$`)}});const r=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(i,s)=>{if(r)return n(i,s);let o=!1;const a=[];for(const c of t.options){const l=c._zod.run({value:i.value,issues:[]},s);if(l instanceof Promise)a.push(l),o=!0;else{if(l.issues.length===0)return l;a.push(l)}}return o?Promise.all(a).then(c=>Jh(c,i,e,s)):Jh(a,i,e,s)}}),qR=x("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,nm.init(e,t);const r=e._zod.parse;Ae(e._zod,"propValues",()=>{const i={};for(const s of t.options){const o=s._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[a,c]of Object.entries(o)){i[a]||(i[a]=new Set);for(const l of c)i[a].add(l)}}return i});const n=Qo(()=>{const i=t.options,s=new Map;for(const o of i){const a=o._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(const c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,o)}}return s});e._zod.parse=(i,s)=>{const o=i.value;if(!ns(o))return i.issues.push({code:"invalid_type",expected:"object",input:o,inst:e}),i;const a=n.value.get(o?.[t.discriminator]);return a?a._zod.run(i,s):t.unionFallback?r(i,s):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:o,path:[t.discriminator],inst:e}),i)}}),jR=x("$ZodIntersection",(e,t)=>{Me.init(e,t),e._zod.parse=(r,n)=>{const i=r.value,s=t.left._zod.run({value:i,issues:[]},n),o=t.right._zod.run({value:i,issues:[]},n);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([a,c])=>Kh(r,a,c)):Kh(r,s,o)}});function hl(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(ri(e)&&ri(t)){const r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),i={...e,...t};for(const s of n){const o=hl(e[s],t[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};i[s]=o.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<e.length;n++){const i=e[n],s=t[n],o=hl(i,s);if(!o.valid)return{valid:!1,mergeErrorPath:[n,...o.mergeErrorPath]};r.push(o.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Kh(e,t,r){const n=new Map;let i;for(const a of t.issues)if(a.code==="unrecognized_keys"){i??(i=a);for(const c of a.keys)n.has(c)||n.set(c,{}),n.get(c).l=!0}else e.issues.push(a);for(const a of r.issues)if(a.code==="unrecognized_keys")for(const c of a.keys)n.has(c)||n.set(c,{}),n.get(c).r=!0;else e.issues.push(a);const s=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&i&&e.issues.push({...i,keys:s}),xn(e))return e;const o=hl(t.value,r.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var HR=x("$ZodTuple",(e,t)=>{Me.init(e,t);const r=t.items;e._zod.parse=(n,i)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({input:s,inst:e,expected:"tuple",code:"invalid_type"}),n;n.value=[];const o=[],a=[...r].reverse().findIndex(u=>u._zod.optin!=="optional"),c=a===-1?0:r.length-a;if(!t.rest){const u=s.length>r.length,h=s.length<c-1;if(u||h)return n.issues.push({...u?{code:"too_big",maximum:r.length,inclusive:!0}:{code:"too_small",minimum:r.length},input:s,inst:e,origin:"array"}),n}let l=-1;for(const u of r){if(l++,l>=s.length&&l>=c)continue;const h=u._zod.run({value:s[l],issues:[]},i);h instanceof Promise?o.push(h.then(d=>Ps(d,n,l))):Ps(h,n,l)}if(t.rest){const u=s.slice(r.length);for(const h of u){l++;const d=t.rest._zod.run({value:h,issues:[]},i);d instanceof Promise?o.push(d.then(p=>Ps(p,n,l))):Ps(d,n,l)}}return o.length?Promise.all(o).then(()=>n):n}});function Ps(e,t,r){e.issues.length&&t.issues.push(...on(r,e.issues)),t.value[r]=e.value}var VR=x("$ZodRecord",(e,t)=>{Me.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!ri(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;const s=[],o=t.keyType._zod.values;if(o){r.value={};const a=new Set;for(const l of o)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){a.add(typeof l=="number"?l.toString():l);const u=t.valueType._zod.run({value:i[l],issues:[]},n);u instanceof Promise?s.push(u.then(h=>{h.issues.length&&r.issues.push(...on(l,h.issues)),r.value[l]=h.value})):(u.issues.length&&r.issues.push(...on(l,u.issues)),r.value[l]=u.value)}let c;for(const l in i)a.has(l)||(c=c??[],c.push(l));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:c})}else{r.value={};for(const a of Reflect.ownKeys(i)){if(a==="__proto__")continue;let c=t.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&Jg.test(a)&&c.issues.length){const u=t.keyType._zod.run({value:Number(a),issues:[]},n);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");u.issues.length===0&&(c=u)}if(c.issues.length){t.mode==="loose"?r.value[a]=i[a]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(u=>Nr(u,n,Dr())),input:a,path:[a],inst:e});continue}const l=t.valueType._zod.run({value:i[a],issues:[]},n);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&r.issues.push(...on(a,u.issues)),r.value[c.value]=u.value})):(l.issues.length&&r.issues.push(...on(a,l.issues)),r.value[c.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),BR=x("$ZodEnum",(e,t)=>{Me.init(e,t);const r=Fg(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(i=>YE.has(typeof i)).map(i=>typeof i=="string"?ni(i):i.toString()).join("|")})$`),e._zod.parse=(i,s)=>{const o=i.value;return n.has(o)||i.issues.push({code:"invalid_value",values:r,input:o,inst:e}),i}}),GR=x("$ZodLiteral",(e,t)=>{if(Me.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?ni(n):n?ni(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,i)=>{const s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}}),WR=x("$ZodTransform",(e,t)=>{Me.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Ug(e.constructor.name);const i=t.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(s=>(r.value=s,r));if(i instanceof Promise)throw new Bn;return r.value=i,r}});function Yh(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var im=x("$ZodOptional",(e,t)=>{Me.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ae(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ae(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${vu(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>Yh(s,r.value)):Yh(i,r.value)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),ZR=x("$ZodExactOptional",(e,t)=>{im.init(e,t),Ae(e._zod,"values",()=>t.innerType._zod.values),Ae(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),JR=x("$ZodNullable",(e,t)=>{Me.init(e,t),Ae(e._zod,"optin",()=>t.innerType._zod.optin),Ae(e._zod,"optout",()=>t.innerType._zod.optout),Ae(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${vu(r.source)}|null)$`):void 0}),Ae(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),KR=x("$ZodDefault",(e,t)=>{Me.init(e,t),e._zod.optin="optional",Ae(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>Xh(s,t)):Xh(i,t)}});function Xh(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var YR=x("$ZodPrefault",(e,t)=>{Me.init(e,t),e._zod.optin="optional",Ae(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),XR=x("$ZodNonOptional",(e,t)=>{Me.init(e,t),Ae(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>Qh(s,e)):Qh(i,e)}});function Qh(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var QR=x("$ZodCatch",(e,t)=>{Me.init(e,t),Ae(e._zod,"optin",()=>t.innerType._zod.optin),Ae(e._zod,"optout",()=>t.innerType._zod.optout),Ae(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(o=>Nr(o,n,Dr()))},input:r.value}),r.issues=[]),r)):(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(s=>Nr(s,n,Dr()))},input:r.value}),r.issues=[]),r)}}),eA=x("$ZodPipe",(e,t)=>{Me.init(e,t),Ae(e._zod,"values",()=>t.in._zod.values),Ae(e._zod,"optin",()=>t.in._zod.optin),Ae(e._zod,"optout",()=>t.out._zod.optout),Ae(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){const s=t.out._zod.run(r,n);return s instanceof Promise?s.then(o=>Os(o,t.in,n)):Os(s,t.in,n)}const i=t.in._zod.run(r,n);return i instanceof Promise?i.then(s=>Os(s,t.out,n)):Os(i,t.out,n)}});function Os(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}var tA=x("$ZodReadonly",(e,t)=>{Me.init(e,t),Ae(e._zod,"propValues",()=>t.innerType._zod.propValues),Ae(e._zod,"values",()=>t.innerType._zod.values),Ae(e._zod,"optin",()=>t.innerType?._zod?.optin),Ae(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(ep):ep(i)}});function ep(e){return e.value=Object.freeze(e.value),e}var rA=x("$ZodLazy",(e,t)=>{Me.init(e,t),Ae(e._zod,"innerType",()=>t.getter()),Ae(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Ae(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Ae(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Ae(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),nA=x("$ZodCustom",(e,t)=>{St.init(e,t),Me.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then(s=>tp(s,r,n,e));tp(i,r,n,e)}});function tp(e,t,r,n){if(!e){const i={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(i.params=n._zod.def.params),t.issues.push(is(i))}}var rp,iA=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const r=t[0];return this._map.set(e,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};delete r.id;const n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function sA(){return new iA}(rp=globalThis).__zod_globalRegistry??(rp.__zod_globalRegistry=sA());var $i=globalThis.__zod_globalRegistry;function oA(e,t){return new e({type:"string",...re(t)})}function aA(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...re(t)})}function np(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...re(t)})}function cA(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...re(t)})}function lA(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...re(t)})}function uA(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...re(t)})}function dA(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...re(t)})}function hA(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...re(t)})}function pA(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...re(t)})}function fA(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...re(t)})}function vA(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...re(t)})}function gA(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...re(t)})}function mA(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...re(t)})}function _A(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...re(t)})}function yA(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...re(t)})}function bA(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...re(t)})}function wA(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...re(t)})}function SA(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...re(t)})}function EA(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...re(t)})}function kA(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...re(t)})}function RA(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...re(t)})}function AA(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...re(t)})}function IA(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...re(t)})}function TA(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...re(t)})}function $A(e,t){return new e({type:"string",format:"date",check:"string_format",...re(t)})}function CA(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...re(t)})}function PA(e,t){return new e({type:"string",format:"duration",check:"string_format",...re(t)})}function OA(e,t){return new e({type:"number",checks:[],...re(t)})}function xA(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...re(t)})}function MA(e,t){return new e({type:"boolean",...re(t)})}function LA(e,t){return new e({type:"undefined",...re(t)})}function DA(e,t){return new e({type:"null",...re(t)})}function NA(e){return new e({type:"any"})}function zA(e){return new e({type:"unknown"})}function UA(e,t){return new e({type:"never",...re(t)})}function ip(e,t){return new Yg({check:"less_than",...re(t),value:e,inclusive:!1})}function gc(e,t){return new Yg({check:"less_than",...re(t),value:e,inclusive:!0})}function sp(e,t){return new Xg({check:"greater_than",...re(t),value:e,inclusive:!1})}function mc(e,t){return new Xg({check:"greater_than",...re(t),value:e,inclusive:!0})}function op(e,t){return new Gk({check:"multiple_of",...re(t),value:e})}function sm(e,t){return new Zk({check:"max_length",...re(t),maximum:e})}function Co(e,t){return new Jk({check:"min_length",...re(t),minimum:e})}function om(e,t){return new Kk({check:"length_equals",...re(t),length:e})}function FA(e,t){return new Yk({check:"string_format",format:"regex",...re(t),pattern:e})}function qA(e){return new Xk({check:"string_format",format:"lowercase",...re(e)})}function jA(e){return new Qk({check:"string_format",format:"uppercase",...re(e)})}function HA(e,t){return new eR({check:"string_format",format:"includes",...re(t),includes:e})}function VA(e,t){return new tR({check:"string_format",format:"starts_with",...re(t),prefix:e})}function BA(e,t){return new rR({check:"string_format",format:"ends_with",...re(t),suffix:e})}function li(e){return new nR({check:"overwrite",tx:e})}function GA(e){return li(t=>t.normalize(e))}function WA(){return li(e=>e.trim())}function ZA(){return li(e=>e.toLowerCase())}function JA(){return li(e=>e.toUpperCase())}function KA(){return li(e=>JE(e))}function YA(e,t,r){return new e({type:"array",element:t,...re(r)})}function XA(e,t,r){const n=re(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function QA(e,t,r){return new e({type:"custom",check:"custom",fn:t,...re(r)})}function eI(e){const t=tI(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(is(n,r.value,t._zod.def));else{const i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),r.issues.push(is(i))}},e(r.value,r)));return t}function tI(e,t){const r=new St({check:"custom",...re(t)});return r._zod.check=e,r}function Po(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??$i,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Fe(e,t,r={path:[],schemaPath:[]}){var n;const i=e._zod.def,s=t.seen.get(e);if(s)return s.count++,r.schemaPath.includes(e)&&(s.cycle=r.path),s.schema;const o={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,o);const a=e._zod.toJSONSchema?.();if(a)o.schema=a;else{const l={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,l);else{const h=o.schema,d=t.processors[i.type];if(!d)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);d(e,t,h,l)}const u=e._zod.parent;u&&(o.ref||(o.ref=u),Fe(u,t,l),t.seen.get(u).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io==="input"&&pt(e)&&(delete o.schema.examples,delete o.schema.default),t.io==="input"&&o.schema._prefault&&((n=o.schema).default??(n.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Oo(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=new Map;for(const o of e.seen.entries()){const a=e.metadataRegistry.get(o[0])?.id;if(a){const c=n.get(a);if(c&&c!==o[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,o[0])}}const i=o=>{const a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const u=e.external.registry.get(o[0])?.id,h=e.external.uri??(p=>p);if(u)return{ref:h(u)};const d=o[1].defId??o[1].schema.id??`schema${e.counter++}`;return o[1].defId=d,{defId:d,ref:`${h("__shared")}#/${a}/${d}`}}if(o[1]===r)return{ref:"#"};const c=`#/${a}/`,l=o[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:c+l}},s=o=>{if(o[1].schema.$ref)return;const a=o[1],{ref:c,defId:l}=i(o);a.def={...a.schema},l&&(a.defId=l);const u=a.schema;for(const h in u)delete u[h];u.$ref=c};if(e.cycles==="throw")for(const o of e.seen.entries()){const a=o[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
37
+ `)}p.write("payload.value = newResult;"),p.write("return payload;");const w=p.compile();return(S,T)=>w(d,S,T)};let s;const o=Gi,a=!Ec.jitless,l=a&&Vy.value,u=t.catchall;let h;e._zod.parse=(d,p)=>{h??(h=n.value);const f=d.value;return o(f)?a&&l&&p?.async===!1&&p.jitless!==!0?(s||(s=i(t.shape)),d=s(d,p),u?wf([],f,d,p,h,e):d):r(d,p):(d.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),d)}});function rd(e,t,r,n){for(const s of e)if(s.issues.length===0)return t.value=s.value,t;const i=e.filter(s=>!Tn(s));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(s=>s.issues.map(o=>Or(o,n,Pr())))}),t)}var Sf=x("$ZodUnion",(e,t)=>{Me.init(e,t),Ae(e._zod,"optin",()=>t.options.some(i=>i._zod.optin==="optional")?"optional":void 0),Ae(e._zod,"optout",()=>t.options.some(i=>i._zod.optout==="optional")?"optional":void 0),Ae(e._zod,"values",()=>{if(t.options.every(i=>i._zod.values))return new Set(t.options.flatMap(i=>Array.from(i._zod.values)))}),Ae(e._zod,"pattern",()=>{if(t.options.every(i=>i._zod.pattern)){const i=t.options.map(s=>s._zod.pattern);return new RegExp(`^(${i.map(s=>zl(s.source)).join("|")})$`)}});const r=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(i,s)=>{if(r)return n(i,s);let o=!1;const a=[];for(const c of t.options){const l=c._zod.run({value:i.value,issues:[]},s);if(l instanceof Promise)a.push(l),o=!0;else{if(l.issues.length===0)return l;a.push(l)}}return o?Promise.all(a).then(c=>rd(c,i,e,s)):rd(a,i,e,s)}}),Lb=x("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Sf.init(e,t);const r=e._zod.parse;Ae(e._zod,"propValues",()=>{const i={};for(const s of t.options){const o=s._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[a,c]of Object.entries(o)){i[a]||(i[a]=new Set);for(const l of c)i[a].add(l)}}return i});const n=Fo(()=>{const i=t.options,s=new Map;for(const o of i){const a=o._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(const c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,o)}}return s});e._zod.parse=(i,s)=>{const o=i.value;if(!Gi(o))return i.issues.push({code:"invalid_type",expected:"object",input:o,inst:e}),i;const a=n.value.get(o?.[t.discriminator]);return a?a._zod.run(i,s):t.unionFallback?r(i,s):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:o,path:[t.discriminator],inst:e}),i)}}),Db=x("$ZodIntersection",(e,t)=>{Me.init(e,t),e._zod.parse=(r,n)=>{const i=r.value,s=t.left._zod.run({value:i,issues:[]},n),o=t.right._zod.run({value:i,issues:[]},n);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([a,c])=>nd(r,a,c)):nd(r,s,o)}});function Rc(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Bn(e)&&Bn(t)){const r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),i={...e,...t};for(const s of n){const o=Rc(e[s],t[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};i[s]=o.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<e.length;n++){const i=e[n],s=t[n],o=Rc(i,s);if(!o.valid)return{valid:!1,mergeErrorPath:[n,...o.mergeErrorPath]};r.push(o.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function nd(e,t,r){const n=new Map;let i;for(const a of t.issues)if(a.code==="unrecognized_keys"){i??(i=a);for(const c of a.keys)n.has(c)||n.set(c,{}),n.get(c).l=!0}else e.issues.push(a);for(const a of r.issues)if(a.code==="unrecognized_keys")for(const c of a.keys)n.has(c)||n.set(c,{}),n.get(c).r=!0;else e.issues.push(a);const s=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&i&&e.issues.push({...i,keys:s}),Tn(e))return e;const o=Rc(t.value,r.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var Nb=x("$ZodTuple",(e,t)=>{Me.init(e,t);const r=t.items;e._zod.parse=(n,i)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({input:s,inst:e,expected:"tuple",code:"invalid_type"}),n;n.value=[];const o=[],a=[...r].reverse().findIndex(u=>u._zod.optin!=="optional"),c=a===-1?0:r.length-a;if(!t.rest){const u=s.length>r.length,h=s.length<c-1;if(u||h)return n.issues.push({...u?{code:"too_big",maximum:r.length,inclusive:!0}:{code:"too_small",minimum:r.length},input:s,inst:e,origin:"array"}),n}let l=-1;for(const u of r){if(l++,l>=s.length&&l>=c)continue;const h=u._zod.run({value:s[l],issues:[]},i);h instanceof Promise?o.push(h.then(d=>gs(d,n,l))):gs(h,n,l)}if(t.rest){const u=s.slice(r.length);for(const h of u){l++;const d=t.rest._zod.run({value:h,issues:[]},i);d instanceof Promise?o.push(d.then(p=>gs(p,n,l))):gs(d,n,l)}}return o.length?Promise.all(o).then(()=>n):n}});function gs(e,t,r){e.issues.length&&t.issues.push(...nn(r,e.issues)),t.value[r]=e.value}var zb=x("$ZodRecord",(e,t)=>{Me.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!Bn(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;const s=[],o=t.keyType._zod.values;if(o){r.value={};const a=new Set;for(const l of o)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){a.add(typeof l=="number"?l.toString():l);const u=t.valueType._zod.run({value:i[l],issues:[]},n);u instanceof Promise?s.push(u.then(h=>{h.issues.length&&r.issues.push(...nn(l,h.issues)),r.value[l]=h.value})):(u.issues.length&&r.issues.push(...nn(l,u.issues)),r.value[l]=u.value)}let c;for(const l in i)a.has(l)||(c=c??[],c.push(l));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:c})}else{r.value={};for(const a of Reflect.ownKeys(i)){if(a==="__proto__")continue;let c=t.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&ff.test(a)&&c.issues.length){const u=t.keyType._zod.run({value:Number(a),issues:[]},n);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");u.issues.length===0&&(c=u)}if(c.issues.length){t.mode==="loose"?r.value[a]=i[a]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(u=>Or(u,n,Pr())),input:a,path:[a],inst:e});continue}const l=t.valueType._zod.run({value:i[a],issues:[]},n);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&r.issues.push(...nn(a,u.issues)),r.value[c.value]=u.value})):(l.issues.length&&r.issues.push(...nn(a,l.issues)),r.value[c.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Ub=x("$ZodEnum",(e,t)=>{Me.init(e,t);const r=sf(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(i=>By.has(typeof i)).map(i=>typeof i=="string"?Gn(i):i.toString()).join("|")})$`),e._zod.parse=(i,s)=>{const o=i.value;return n.has(o)||i.issues.push({code:"invalid_value",values:r,input:o,inst:e}),i}}),Fb=x("$ZodLiteral",(e,t)=>{if(Me.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?Gn(n):n?Gn(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,i)=>{const s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}}),qb=x("$ZodTransform",(e,t)=>{Me.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new nf(e.constructor.name);const i=t.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(s=>(r.value=s,r));if(i instanceof Promise)throw new zn;return r.value=i,r}});function id(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var Ef=x("$ZodOptional",(e,t)=>{Me.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ae(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ae(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${zl(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>id(s,r.value)):id(i,r.value)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),jb=x("$ZodExactOptional",(e,t)=>{Ef.init(e,t),Ae(e._zod,"values",()=>t.innerType._zod.values),Ae(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),Hb=x("$ZodNullable",(e,t)=>{Me.init(e,t),Ae(e._zod,"optin",()=>t.innerType._zod.optin),Ae(e._zod,"optout",()=>t.innerType._zod.optout),Ae(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${zl(r.source)}|null)$`):void 0}),Ae(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),Vb=x("$ZodDefault",(e,t)=>{Me.init(e,t),e._zod.optin="optional",Ae(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>sd(s,t)):sd(i,t)}});function sd(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Bb=x("$ZodPrefault",(e,t)=>{Me.init(e,t),e._zod.optin="optional",Ae(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),Gb=x("$ZodNonOptional",(e,t)=>{Me.init(e,t),Ae(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>od(s,e)):od(i,e)}});function od(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var Wb=x("$ZodCatch",(e,t)=>{Me.init(e,t),Ae(e._zod,"optin",()=>t.innerType._zod.optin),Ae(e._zod,"optout",()=>t.innerType._zod.optout),Ae(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(o=>Or(o,n,Pr()))},input:r.value}),r.issues=[]),r)):(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(s=>Or(s,n,Pr()))},input:r.value}),r.issues=[]),r)}}),Zb=x("$ZodPipe",(e,t)=>{Me.init(e,t),Ae(e._zod,"values",()=>t.in._zod.values),Ae(e._zod,"optin",()=>t.in._zod.optin),Ae(e._zod,"optout",()=>t.out._zod.optout),Ae(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){const s=t.out._zod.run(r,n);return s instanceof Promise?s.then(o=>ms(o,t.in,n)):ms(s,t.in,n)}const i=t.in._zod.run(r,n);return i instanceof Promise?i.then(s=>ms(s,t.out,n)):ms(i,t.out,n)}});function ms(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}var Jb=x("$ZodReadonly",(e,t)=>{Me.init(e,t),Ae(e._zod,"propValues",()=>t.innerType._zod.propValues),Ae(e._zod,"values",()=>t.innerType._zod.values),Ae(e._zod,"optin",()=>t.innerType?._zod?.optin),Ae(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(ad):ad(i)}});function ad(e){return e.value=Object.freeze(e.value),e}var Kb=x("$ZodLazy",(e,t)=>{Me.init(e,t),Ae(e._zod,"innerType",()=>t.getter()),Ae(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Ae(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Ae(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Ae(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),Yb=x("$ZodCustom",(e,t)=>{wt.init(e,t),Me.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then(s=>cd(s,r,n,e));cd(i,r,n,e)}});function cd(e,t,r,n){if(!e){const i={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(i.params=n._zod.def.params),t.issues.push(Wi(i))}}var ld,Xb=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const r=t[0];return this._map.set(e,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};delete r.id;const n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Qb(){return new Xb}(ld=globalThis).__zod_globalRegistry??(ld.__zod_globalRegistry=Qb());var Ai=globalThis.__zod_globalRegistry;function ew(e,t){return new e({type:"string",...re(t)})}function tw(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...re(t)})}function ud(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...re(t)})}function rw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...re(t)})}function nw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...re(t)})}function iw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...re(t)})}function sw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...re(t)})}function ow(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...re(t)})}function aw(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...re(t)})}function cw(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...re(t)})}function lw(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...re(t)})}function uw(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...re(t)})}function dw(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...re(t)})}function hw(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...re(t)})}function pw(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...re(t)})}function fw(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...re(t)})}function vw(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...re(t)})}function gw(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...re(t)})}function mw(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...re(t)})}function _w(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...re(t)})}function yw(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...re(t)})}function bw(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...re(t)})}function ww(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...re(t)})}function Sw(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...re(t)})}function Ew(e,t){return new e({type:"string",format:"date",check:"string_format",...re(t)})}function kw(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...re(t)})}function Rw(e,t){return new e({type:"string",format:"duration",check:"string_format",...re(t)})}function Aw(e,t){return new e({type:"number",checks:[],...re(t)})}function Iw(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...re(t)})}function Tw(e,t){return new e({type:"boolean",...re(t)})}function Cw(e,t){return new e({type:"undefined",...re(t)})}function $w(e,t){return new e({type:"null",...re(t)})}function Pw(e){return new e({type:"any"})}function Ow(e){return new e({type:"unknown"})}function xw(e,t){return new e({type:"never",...re(t)})}function dd(e,t){return new gf({check:"less_than",...re(t),value:e,inclusive:!1})}function Aa(e,t){return new gf({check:"less_than",...re(t),value:e,inclusive:!0})}function hd(e,t){return new mf({check:"greater_than",...re(t),value:e,inclusive:!1})}function Ia(e,t){return new mf({check:"greater_than",...re(t),value:e,inclusive:!0})}function pd(e,t){return new F0({check:"multiple_of",...re(t),value:e})}function kf(e,t){return new j0({check:"max_length",...re(t),maximum:e})}function ro(e,t){return new H0({check:"min_length",...re(t),minimum:e})}function Rf(e,t){return new V0({check:"length_equals",...re(t),length:e})}function Mw(e,t){return new B0({check:"string_format",format:"regex",...re(t),pattern:e})}function Lw(e){return new G0({check:"string_format",format:"lowercase",...re(e)})}function Dw(e){return new W0({check:"string_format",format:"uppercase",...re(e)})}function Nw(e,t){return new Z0({check:"string_format",format:"includes",...re(t),includes:e})}function zw(e,t){return new J0({check:"string_format",format:"starts_with",...re(t),prefix:e})}function Uw(e,t){return new K0({check:"string_format",format:"ends_with",...re(t),suffix:e})}function si(e){return new Y0({check:"overwrite",tx:e})}function Fw(e){return si(t=>t.normalize(e))}function qw(){return si(e=>e.trim())}function jw(){return si(e=>e.toLowerCase())}function Hw(){return si(e=>e.toUpperCase())}function Vw(){return si(e=>Hy(e))}function Bw(e,t,r){return new e({type:"array",element:t,...re(r)})}function Gw(e,t,r){const n=re(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Ww(e,t,r){return new e({type:"custom",check:"custom",fn:t,...re(r)})}function Zw(e){const t=Jw(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Wi(n,r.value,t._zod.def));else{const i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),r.issues.push(Wi(i))}},e(r.value,r)));return t}function Jw(e,t){const r=new wt({check:"custom",...re(t)});return r._zod.check=e,r}function no(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Ai,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Fe(e,t,r={path:[],schemaPath:[]}){var n;const i=e._zod.def,s=t.seen.get(e);if(s)return s.count++,r.schemaPath.includes(e)&&(s.cycle=r.path),s.schema;const o={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,o);const a=e._zod.toJSONSchema?.();if(a)o.schema=a;else{const l={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,l);else{const h=o.schema,d=t.processors[i.type];if(!d)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);d(e,t,h,l)}const u=e._zod.parent;u&&(o.ref||(o.ref=u),Fe(u,t,l),t.seen.get(u).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io==="input"&&dt(e)&&(delete o.schema.examples,delete o.schema.default),t.io==="input"&&o.schema._prefault&&((n=o.schema).default??(n.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function io(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=new Map;for(const o of e.seen.entries()){const a=e.metadataRegistry.get(o[0])?.id;if(a){const c=n.get(a);if(c&&c!==o[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,o[0])}}const i=o=>{const a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const u=e.external.registry.get(o[0])?.id,h=e.external.uri??(p=>p);if(u)return{ref:h(u)};const d=o[1].defId??o[1].schema.id??`schema${e.counter++}`;return o[1].defId=d,{defId:d,ref:`${h("__shared")}#/${a}/${d}`}}if(o[1]===r)return{ref:"#"};const c=`#/${a}/`,l=o[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:c+l}},s=o=>{if(o[1].schema.$ref)return;const a=o[1],{ref:c,defId:l}=i(o);a.def={...a.schema},l&&(a.defId=l);const u=a.schema;for(const h in u)delete u[h];u.$ref=c};if(e.cycles==="throw")for(const o of e.seen.entries()){const a=o[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
44
38
 
45
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of e.seen.entries()){const a=o[1];if(t===o[0]){s(o);continue}if(e.external){const c=e.external.registry.get(o[0])?.id;if(t!==o[0]&&c){s(o);continue}}if(e.metadataRegistry.get(o[0])?.id){s(o);continue}if(a.cycle){s(o);continue}if(a.count>1&&e.reused==="ref"){s(o);continue}}}function xo(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=o=>{const a=e.seen.get(o);if(a.ref===null)return;const c=a.def??a.schema,l={...c},u=a.ref;if(a.ref=null,u){n(u);const d=e.seen.get(u),p=d.schema;if(p.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(p)):Object.assign(c,p),Object.assign(c,l),o._zod.parent===u)for(const f in c)f==="$ref"||f==="allOf"||f in l||delete c[f];if(p.$ref&&d.def)for(const f in c)f==="$ref"||f==="allOf"||f in d.def&&JSON.stringify(c[f])===JSON.stringify(d.def[f])&&delete c[f]}const h=o._zod.parent;if(h&&h!==u){n(h);const d=e.seen.get(h);if(d?.schema.$ref&&(c.$ref=d.schema.$ref,d.def))for(const p in c)p==="$ref"||p==="allOf"||p in d.def&&JSON.stringify(c[p])===JSON.stringify(d.def[p])&&delete c[p]}e.override({zodSchema:o,jsonSchema:c,path:a.path??[]})};for(const o of[...e.seen.entries()].reverse())n(o[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const o=e.external.registry.get(t)?.id;if(!o)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(o)}Object.assign(i,r.def??r.schema);const s=e.external?.defs??{};for(const o of e.seen.entries()){const a=o[1];a.def&&a.defId&&(s[a.defId]=a.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?i.$defs=s:i.definitions=s);try{const o=JSON.parse(JSON.stringify(i));return Object.defineProperty(o,"~standard",{value:{...t["~standard"],jsonSchema:{input:Mo(t,"input",e.processors),output:Mo(t,"output",e.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function pt(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return pt(n.element,r);if(n.type==="set")return pt(n.valueType,r);if(n.type==="lazy")return pt(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return pt(n.innerType,r);if(n.type==="intersection")return pt(n.left,r)||pt(n.right,r);if(n.type==="record"||n.type==="map")return pt(n.keyType,r)||pt(n.valueType,r);if(n.type==="pipe")return pt(n.in,r)||pt(n.out,r);if(n.type==="object"){for(const i in n.shape)if(pt(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(const i of n.options)if(pt(i,r))return!0;return!1}if(n.type==="tuple"){for(const i of n.items)if(pt(i,r))return!0;return!!(n.rest&&pt(n.rest,r))}return!1}var rI=(e,t={})=>r=>{const n=Po({...r,processors:t});return Fe(e,n),Oo(n,e),xo(n,e)},Mo=(e,t,r={})=>n=>{const{libraryOptions:i,target:s}=n??{},o=Po({...i??{},target:s,io:t,processors:r});return Fe(e,o),Oo(o,e),xo(o,e)},nI={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},am=(e,t,r,n)=>{const i=r;i.type="string";const{minimum:s,maximum:o,format:a,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof s=="number"&&(i.minLength=s),typeof o=="number"&&(i.maxLength=o),a&&(i.format=nI[a]??a,i.format===""&&delete i.format,a==="time"&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){const u=[...c];u.length===1?i.pattern=u[0].source:u.length>1&&(i.allOf=[...u.map(h=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))])}},cm=(e,t,r,n)=>{const i=r,{minimum:s,maximum:o,format:a,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof a=="string"&&a.includes("int")?i.type="integer":i.type="number",typeof u=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u),typeof s=="number"&&(i.minimum=s,typeof u=="number"&&t.target!=="draft-04"&&(u>=s?delete i.minimum:delete i.exclusiveMinimum)),typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l),typeof o=="number"&&(i.maximum=o,typeof l=="number"&&t.target!=="draft-04"&&(l<=o?delete i.maximum:delete i.exclusiveMaximum)),typeof c=="number"&&(i.multipleOf=c)},lm=(e,t,r,n)=>{r.type="boolean"},iI=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},sI=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},um=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},dm=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},oI=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},hm=(e,t,r,n)=>{r.not={}},pm=(e,t,r,n)=>{},fm=(e,t,r,n)=>{},aI=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},vm=(e,t,r,n)=>{const i=e._zod.def,s=Fg(i.entries);s.every(o=>typeof o=="number")&&(r.type="number"),s.every(o=>typeof o=="string")&&(r.type="string"),r.enum=s},gm=(e,t,r,n)=>{const i=e._zod.def,s=[];for(const o of i.values)if(o===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(o))}else s.push(o);if(s.length!==0)if(s.length===1){const o=s[0];r.type=o===null?"null":typeof o,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[o]:r.const=o}else s.every(o=>typeof o=="number")&&(r.type="number"),s.every(o=>typeof o=="string")&&(r.type="string"),s.every(o=>typeof o=="boolean")&&(r.type="boolean"),s.every(o=>o===null)&&(r.type="null"),r.enum=s},cI=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},lI=(e,t,r,n)=>{const i=r,s=e._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=s.source},uI=(e,t,r,n)=>{const i=r,s={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:a,mime:c}=e._zod.bag;o!==void 0&&(s.minLength=o),a!==void 0&&(s.maxLength=a),c?c.length===1?(s.contentMediaType=c[0],Object.assign(i,s)):(Object.assign(i,s),i.anyOf=c.map(l=>({contentMediaType:l}))):Object.assign(i,s)},dI=(e,t,r,n)=>{r.type="boolean"},mm=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},hI=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},_m=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},pI=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},fI=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},ym=(e,t,r,n)=>{const i=r,s=e._zod.def,{minimum:o,maximum:a}=e._zod.bag;typeof o=="number"&&(i.minItems=o),typeof a=="number"&&(i.maxItems=a),i.type="array",i.items=Fe(s.element,t,{...n,path:[...n.path,"items"]})},bm=(e,t,r,n)=>{const i=r,s=e._zod.def;i.type="object",i.properties={};const o=s.shape;for(const l in o)i.properties[l]=Fe(o[l],t,{...n,path:[...n.path,"properties",l]});const a=new Set(Object.keys(o)),c=new Set([...a].filter(l=>{const u=s.shape[l]._zod;return t.io==="input"?u.optin===void 0:u.optout===void 0}));c.size>0&&(i.required=Array.from(c)),s.catchall?._zod.def.type==="never"?i.additionalProperties=!1:s.catchall?s.catchall&&(i.additionalProperties=Fe(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},wm=(e,t,r,n)=>{const i=e._zod.def,s=i.inclusive===!1,o=i.options.map((a,c)=>Fe(a,t,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=o:r.anyOf=o},Sm=(e,t,r,n)=>{const i=e._zod.def,s=Fe(i.left,t,{...n,path:[...n.path,"allOf",0]}),o=Fe(i.right,t,{...n,path:[...n.path,"allOf",1]}),a=c=>"allOf"in c&&Object.keys(c).length===1;r.allOf=[...a(s)?s.allOf:[s],...a(o)?o.allOf:[o]]},Em=(e,t,r,n)=>{const i=r,s=e._zod.def;i.type="array";const o=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=s.items.map((d,p)=>Fe(d,t,{...n,path:[...n.path,o,p]})),l=s.rest?Fe(s.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null;t.target==="draft-2020-12"?(i.prefixItems=c,l&&(i.items=l)):t.target==="openapi-3.0"?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));const{minimum:u,maximum:h}=e._zod.bag;typeof u=="number"&&(i.minItems=u),typeof h=="number"&&(i.maxItems=h)},km=(e,t,r,n)=>{const i=r,s=e._zod.def;i.type="object";const o=s.keyType,a=o._zod.bag?.patterns;if(s.mode==="loose"&&a&&a.size>0){const l=Fe(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});i.patternProperties={};for(const u of a)i.patternProperties[u.source]=l}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(i.propertyNames=Fe(s.keyType,t,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=Fe(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const c=o._zod.values;if(c){const l=[...c].filter(u=>typeof u=="string"||typeof u=="number");l.length>0&&(i.required=l)}},Rm=(e,t,r,n)=>{const i=e._zod.def,s=Fe(i.innerType,t,n),o=t.seen.get(e);t.target==="openapi-3.0"?(o.ref=i.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},Am=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType},Im=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},Tm=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},$m=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=o},Cm=(e,t,r,n)=>{const i=e._zod.def,s=t.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;Fe(s,t,n);const o=t.seen.get(e);o.ref=s},Pm=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType,r.readOnly=!0},vI=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType},bu=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType},Om=(e,t,r,n)=>{const i=e._zod.innerType;Fe(i,t,n);const s=t.seen.get(e);s.ref=i},ap={string:am,number:cm,boolean:lm,bigint:iI,symbol:sI,null:um,undefined:dm,void:oI,never:hm,any:pm,unknown:fm,date:aI,enum:vm,literal:gm,nan:cI,template_literal:lI,file:uI,success:dI,custom:mm,function:hI,transform:_m,map:pI,set:fI,array:ym,object:bm,union:wm,intersection:Sm,tuple:Em,record:km,nullable:Rm,nonoptional:Am,default:Im,prefault:Tm,catch:$m,pipe:Cm,readonly:Pm,promise:vI,optional:bu,lazy:Om};function wL(e,t){if("_idmap"in e){const n=e,i=Po({...t,processors:ap}),s={};for(const a of n._idmap.entries()){const[c,l]=a;Fe(l,i)}const o={};i.external={registry:n,uri:t?.uri,defs:s};for(const a of n._idmap.entries()){const[c,l]=a;Oo(i,l),o[c]=xo(i,l)}return Object.keys(s).length>0&&(o.__shared={[i.target==="draft-2020-12"?"$defs":"definitions"]:s}),{schemas:o}}const r=Po({...t,processors:ap});return Fe(e,r),Oo(r,e),xo(r,e)}var gI=x("ZodISODateTime",(e,t)=>{mR.init(e,t),Ye.init(e,t)});function mI(e){return TA(gI,e)}var _I=x("ZodISODate",(e,t)=>{_R.init(e,t),Ye.init(e,t)});function yI(e){return $A(_I,e)}var bI=x("ZodISOTime",(e,t)=>{yR.init(e,t),Ye.init(e,t)});function wI(e){return CA(bI,e)}var SI=x("ZodISODuration",(e,t)=>{bR.init(e,t),Ye.init(e,t)});function EI(e){return PA(SI,e)}var xm=(e,t)=>{Vg.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>ck(e,r)},flatten:{value:r=>ak(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,dl,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,dl,2)}},isEmpty:{get(){return e.issues.length===0}}})},SL=x("ZodError",xm),Ct=x("ZodError",xm,{Parent:Error}),kI=mu(Ct),RI=_u(Ct),AI=ea(Ct),II=ta(Ct),TI=dk(Ct),$I=hk(Ct),CI=pk(Ct),PI=fk(Ct),OI=vk(Ct),xI=gk(Ct),MI=mk(Ct),LI=_k(Ct),Ne=x("ZodType",(e,t)=>(Me.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Mo(e,"input"),output:Mo(e,"output")}}),e.toJSONSchema=rI(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(Br(t,{checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),e.with=e.check,e.clone=(r,n)=>dr(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>kI(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>AI(e,r,n),e.parseAsync=async(r,n)=>RI(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>II(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>TI(e,r,n),e.decode=(r,n)=>$I(e,r,n),e.encodeAsync=async(r,n)=>CI(e,r,n),e.decodeAsync=async(r,n)=>PI(e,r,n),e.safeEncode=(r,n)=>OI(e,r,n),e.safeDecode=(r,n)=>xI(e,r,n),e.safeEncodeAsync=async(r,n)=>MI(e,r,n),e.safeDecodeAsync=async(r,n)=>LI(e,r,n),e.refine=(r,n)=>e.check(CT(r,n)),e.superRefine=r=>e.check(PT(r)),e.overwrite=r=>e.check(li(r)),e.optional=()=>up(e),e.exactOptional=()=>mT(e),e.nullable=()=>dp(e),e.nullish=()=>up(dp(e)),e.nonoptional=r=>ET(e,r),e.array=()=>Mt(e),e.or=r=>cT([e,r]),e.and=r=>dT(e,r),e.transform=r=>gl(e,Um(r)),e.default=r=>bT(e,r),e.prefault=r=>ST(e,r),e.catch=r=>RT(e,r),e.pipe=r=>gl(e,r),e.readonly=()=>TT(e),e.describe=r=>{const n=e.clone();return $i.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return $i.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return $i.get(e);const n=e.clone();return $i.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=r=>r(e),e)),Mm=x("_ZodString",(e,t)=>{yu.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(n,i,s)=>am(e,n,i,s);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(FA(...n)),e.includes=(...n)=>e.check(HA(...n)),e.startsWith=(...n)=>e.check(VA(...n)),e.endsWith=(...n)=>e.check(BA(...n)),e.min=(...n)=>e.check(Co(...n)),e.max=(...n)=>e.check(sm(...n)),e.length=(...n)=>e.check(om(...n)),e.nonempty=(...n)=>e.check(Co(1,...n)),e.lowercase=n=>e.check(qA(n)),e.uppercase=n=>e.check(jA(n)),e.trim=()=>e.check(WA()),e.normalize=(...n)=>e.check(GA(...n)),e.toLowerCase=()=>e.check(ZA()),e.toUpperCase=()=>e.check(JA()),e.slugify=()=>e.check(KA())}),DI=x("ZodString",(e,t)=>{yu.init(e,t),Mm.init(e,t),e.email=r=>e.check(aA(NI,r)),e.url=r=>e.check(hA(zI,r)),e.jwt=r=>e.check(IA(QI,r)),e.emoji=r=>e.check(pA(UI,r)),e.guid=r=>e.check(np(cp,r)),e.uuid=r=>e.check(cA(xs,r)),e.uuidv4=r=>e.check(lA(xs,r)),e.uuidv6=r=>e.check(uA(xs,r)),e.uuidv7=r=>e.check(dA(xs,r)),e.nanoid=r=>e.check(fA(FI,r)),e.guid=r=>e.check(np(cp,r)),e.cuid=r=>e.check(vA(qI,r)),e.cuid2=r=>e.check(gA(jI,r)),e.ulid=r=>e.check(mA(HI,r)),e.base64=r=>e.check(kA(KI,r)),e.base64url=r=>e.check(RA(YI,r)),e.xid=r=>e.check(_A(VI,r)),e.ksuid=r=>e.check(yA(BI,r)),e.ipv4=r=>e.check(bA(GI,r)),e.ipv6=r=>e.check(wA(WI,r)),e.cidrv4=r=>e.check(SA(ZI,r)),e.cidrv6=r=>e.check(EA(JI,r)),e.e164=r=>e.check(AA(XI,r)),e.datetime=r=>e.check(mI(r)),e.date=r=>e.check(yI(r)),e.time=r=>e.check(wI(r)),e.duration=r=>e.check(EI(r))});function ze(e){return oA(DI,e)}var Ye=x("ZodStringFormat",(e,t)=>{Ze.init(e,t),Mm.init(e,t)}),NI=x("ZodEmail",(e,t)=>{cR.init(e,t),Ye.init(e,t)}),cp=x("ZodGUID",(e,t)=>{oR.init(e,t),Ye.init(e,t)}),xs=x("ZodUUID",(e,t)=>{aR.init(e,t),Ye.init(e,t)}),zI=x("ZodURL",(e,t)=>{lR.init(e,t),Ye.init(e,t)}),UI=x("ZodEmoji",(e,t)=>{uR.init(e,t),Ye.init(e,t)}),FI=x("ZodNanoID",(e,t)=>{dR.init(e,t),Ye.init(e,t)}),qI=x("ZodCUID",(e,t)=>{hR.init(e,t),Ye.init(e,t)}),jI=x("ZodCUID2",(e,t)=>{pR.init(e,t),Ye.init(e,t)}),HI=x("ZodULID",(e,t)=>{fR.init(e,t),Ye.init(e,t)}),VI=x("ZodXID",(e,t)=>{vR.init(e,t),Ye.init(e,t)}),BI=x("ZodKSUID",(e,t)=>{gR.init(e,t),Ye.init(e,t)}),GI=x("ZodIPv4",(e,t)=>{wR.init(e,t),Ye.init(e,t)}),WI=x("ZodIPv6",(e,t)=>{SR.init(e,t),Ye.init(e,t)}),ZI=x("ZodCIDRv4",(e,t)=>{ER.init(e,t),Ye.init(e,t)}),JI=x("ZodCIDRv6",(e,t)=>{kR.init(e,t),Ye.init(e,t)}),KI=x("ZodBase64",(e,t)=>{RR.init(e,t),Ye.init(e,t)}),YI=x("ZodBase64URL",(e,t)=>{IR.init(e,t),Ye.init(e,t)}),XI=x("ZodE164",(e,t)=>{TR.init(e,t),Ye.init(e,t)}),QI=x("ZodJWT",(e,t)=>{CR.init(e,t),Ye.init(e,t)}),Lm=x("ZodNumber",(e,t)=>{em.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(n,i,s)=>cm(e,n,i,s),e.gt=(n,i)=>e.check(sp(n,i)),e.gte=(n,i)=>e.check(mc(n,i)),e.min=(n,i)=>e.check(mc(n,i)),e.lt=(n,i)=>e.check(ip(n,i)),e.lte=(n,i)=>e.check(gc(n,i)),e.max=(n,i)=>e.check(gc(n,i)),e.int=n=>e.check(lp(n)),e.safe=n=>e.check(lp(n)),e.positive=n=>e.check(sp(0,n)),e.nonnegative=n=>e.check(mc(0,n)),e.negative=n=>e.check(ip(0,n)),e.nonpositive=n=>e.check(gc(0,n)),e.multipleOf=(n,i)=>e.check(op(n,i)),e.step=(n,i)=>e.check(op(n,i)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function Lo(e){return OA(Lm,e)}var eT=x("ZodNumberFormat",(e,t)=>{PR.init(e,t),Lm.init(e,t)});function lp(e){return xA(eT,e)}var tT=x("ZodBoolean",(e,t)=>{OR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>lm(e,r,n,i)});function rn(e){return MA(tT,e)}var rT=x("ZodUndefined",(e,t)=>{xR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>dm(e,r,n,i)});function EL(e){return LA(rT,e)}var nT=x("ZodNull",(e,t)=>{MR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>um(e,r,n,i)});function kL(e){return DA(nT,e)}var iT=x("ZodAny",(e,t)=>{LR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>pm(e,r,n,i)});function RL(){return NA(iT)}var sT=x("ZodUnknown",(e,t)=>{DR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>fm(e,r,n,i)});function pl(){return zA(sT)}var oT=x("ZodNever",(e,t)=>{NR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>hm(e,r,n,i)});function Dm(e){return UA(oT,e)}var aT=x("ZodArray",(e,t)=>{zR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>ym(e,r,n,i),e.element=t.element,e.min=(r,n)=>e.check(Co(r,n)),e.nonempty=r=>e.check(Co(1,r)),e.max=(r,n)=>e.check(sm(r,n)),e.length=(r,n)=>e.check(om(r,n)),e.unwrap=()=>e.element});function Mt(e,t){return YA(aT,e,t)}var wu=x("ZodObject",(e,t)=>{FR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>bm(e,r,n,i),Ae(e,"shape",()=>t.shape),e.keyof=()=>Ar(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:pl()}),e.loose=()=>e.clone({...e._zod.def,catchall:pl()}),e.strict=()=>e.clone({...e._zod.def,catchall:Dm()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>rk(e,r),e.safeExtend=r=>nk(e,r),e.merge=r=>ik(e,r),e.pick=r=>ek(e,r),e.omit=r=>tk(e,r),e.partial=(...r)=>sk(Fm,e,r[0]),e.required=(...r)=>ok(qm,e,r[0])});function hn(e,t){const r={type:"object",shape:e??{},...re(t)};return new wu(r)}function AL(e,t){return new wu({type:"object",shape:e,catchall:Dm(),...re(t)})}function IL(e,t){return new wu({type:"object",shape:e,catchall:pl(),...re(t)})}var Nm=x("ZodUnion",(e,t)=>{nm.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>wm(e,r,n,i),e.options=t.options});function cT(e,t){return new Nm({type:"union",options:e,...re(t)})}var lT=x("ZodDiscriminatedUnion",(e,t)=>{Nm.init(e,t),qR.init(e,t)});function TL(e,t,r){return new lT({type:"union",options:t,discriminator:e,...re(r)})}var uT=x("ZodIntersection",(e,t)=>{jR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Sm(e,r,n,i)});function dT(e,t){return new uT({type:"intersection",left:e,right:t})}var hT=x("ZodTuple",(e,t)=>{HR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Em(e,r,n,i),e.rest=r=>e.clone({...e._zod.def,rest:r})});function $L(e,t,r){const n=t instanceof Me,i=n?r:t;return new hT({type:"tuple",items:e,rest:n?t:null,...re(i)})}var zm=x("ZodRecord",(e,t)=>{VR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>km(e,r,n,i),e.keyType=t.keyType,e.valueType=t.valueType});function fl(e,t,r){return new zm({type:"record",keyType:e,valueType:t,...re(r)})}function pT(e,t,r){const n=dr(e);return n._zod.values=void 0,new zm({type:"record",keyType:n,valueType:t,...re(r)})}var vl=x("ZodEnum",(e,t)=>{BR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(n,i,s)=>vm(e,n,i,s),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(n,i)=>{const s={};for(const o of n)if(r.has(o))s[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new vl({...t,checks:[],...re(i),entries:s})},e.exclude=(n,i)=>{const s={...t.entries};for(const o of n)if(r.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new vl({...t,checks:[],...re(i),entries:s})}});function Ar(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new vl({type:"enum",entries:r,...re(t)})}var fT=x("ZodLiteral",(e,t)=>{GR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>gm(e,r,n,i),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function CL(e,t){return new fT({type:"literal",values:Array.isArray(e)?e:[e],...re(t)})}var vT=x("ZodTransform",(e,t)=>{WR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>_m(e,r,n,i),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Ug(e.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(is(s,r.value,t));else{const o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),r.issues.push(is(o))}};const i=t.transform(r.value,r);return i instanceof Promise?i.then(s=>(r.value=s,r)):(r.value=i,r)}});function Um(e){return new vT({type:"transform",transform:e})}var Fm=x("ZodOptional",(e,t)=>{im.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>bu(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function up(e){return new Fm({type:"optional",innerType:e})}var gT=x("ZodExactOptional",(e,t)=>{ZR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>bu(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function mT(e){return new gT({type:"optional",innerType:e})}var _T=x("ZodNullable",(e,t)=>{JR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Rm(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function dp(e){return new _T({type:"nullable",innerType:e})}var yT=x("ZodDefault",(e,t)=>{KR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Im(e,r,n,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function bT(e,t){return new yT({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():jg(t)}})}var wT=x("ZodPrefault",(e,t)=>{YR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Tm(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function ST(e,t){return new wT({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():jg(t)}})}var qm=x("ZodNonOptional",(e,t)=>{XR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Am(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function ET(e,t){return new qm({type:"nonoptional",innerType:e,...re(t)})}var kT=x("ZodCatch",(e,t)=>{QR.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>$m(e,r,n,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function RT(e,t){return new kT({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var AT=x("ZodPipe",(e,t)=>{eA.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Cm(e,r,n,i),e.in=t.in,e.out=t.out});function gl(e,t){return new AT({type:"pipe",in:e,out:t})}var IT=x("ZodReadonly",(e,t)=>{tA.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Pm(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function TT(e){return new IT({type:"readonly",innerType:e})}var $T=x("ZodLazy",(e,t)=>{rA.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Om(e,r,n,i),e.unwrap=()=>e._zod.def.getter()});function PL(e){return new $T({type:"lazy",getter:e})}var Su=x("ZodCustom",(e,t)=>{nA.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>mm(e,r,n,i)});function OL(e,t){return XA(Su,e??(()=>!0),t)}function CT(e,t={}){return QA(Su,e,t)}function PT(e){return eI(e)}function xL(e,t={}){const r=new Su({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...re(t)});return r._zod.bag.Class=e,r._zod.check=n=>{n.value instanceof e||n.issues.push({code:"invalid_type",expected:e.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}function ML(e,t){return gl(Um(e),t)}var OT=["oauth-dcr","oauth-cimd","oauth-preregistered","static-header","authless","custom-connection"],xT=["no-user-data","processes-user-data","stores-user-data","shares-with-third-parties"],MT=["ownsOrIsAuthorizedForService","accurateDataHandlingDisclosure","compliesWithUsagePolicies","noProhibitedContent","maintainsSecurityPractices","respondsToSecurityReports","keepsListingAccurate"],Ms=ze().url().refine(e=>e.startsWith("https://"),{message:"must be an https:// URL"}),LT=hn({url:ze().min(1),mimeType:ze().min(1),widthPx:Lo().int().positive(),heightPx:Lo().int().positive(),prompt:ze().min(1)}),LL=hn({name:ze().min(1).max(mr.nameMaxLength),tagline:ze().min(1).max(mr.taglineMaxLength),description:ze().min(1).max(mr.descriptionMaxLength),categories:Mt(ze().min(1)).min(mr.categoriesMin).max(mr.categoriesMax),slug:ze().min(1).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"must be a lowercase kebab-case slug"),documentationUrl:Ms,privacyPolicyUrl:Ms,supportUrl:Ms,iconUrl:Ms,declaredAuthMode:Ar(OT),dataHandling:Mt(Ar(xT)).min(1),screenshots:Mt(LT).min(mr.screenshotsMin).max(mr.screenshotsMax),attestations:fl(Ar(MT),rn())}),Ks={maxCompressedBytes:104857600,maxUncompressedBytes:536870912,maxEntries:5e3},DT={canonical:".codex-plugin/plugin.json",accepted:[".agent-plugin/plugin.json",".claude-plugin/plugin.json"]},Lt={nameMaxLength:100,displayNameMaxLength:100,shortDescriptionMaxLength:255,descriptionMaxLength:2e3,defaultPromptMaxLength:255,toolNameMaxLength:64,skillNameMaxLength:64},jm=["productivity","education","developer-tools","design","writing","research","data-analysis","marketing","sales","finance","health","travel","entertainment"],Ys={minEdgePx:48,maxEdgePx:4096,mustBeSquare:!0,maxBytes:5242880,acceptedMimeTypes:["image/png","image/jpeg","image/webp","image/svg+xml"]},NT={lightBackground:"#FFFFFF",darkBackground:"#212121",minRatio:2},nn={maxSkillMarkdownBytes:262144,maxPageBytes:1048576,maxSkillTotalBytes:5242880,maxImportedTotalBytes:8388608,maxSkills:5,maxPagesPerSkill:10},zT="/.well-known/openai-apps-challenge",UT="text/html;profile=mcp-app",FT="/mcp",qT=["readOnlyHint","destructiveHint","openWorldHint"],ml={successCount:5,failureCount:3},jT={originChangeRequiresNewPlugin:!0,uiContentChangesStayLive:!0,uiContentCacheSeconds:3600},DL={archiveLimits:Ks,manifestLocations:DT,fieldLimits:Lt,listingCategories:jm,imageConstraints:Ys,brandColorContrast:NT,mcpSkillLimits:nn,domainVerificationPath:zT,appHtmlMime:UT,expectedMcpPath:FT,requiredToolAnnotations:qT,submissionTestCases:ml,releaseRules:jT,source:Bt("deploy/submission","Host profile constants")},Z=e=>Bt("deploy/submission-errors",e),HT=[{id:"archive-too-large",category:"package-archive",severity:"blocking",message:"The uploaded archive exceeds the maximum compressed size.",limit:{name:"archiveLimits.maxCompressedBytes",value:Ks.maxCompressedBytes},source:Z("§Shared package checks → Archive size")},{id:"archive-expands-too-large",category:"package-archive",severity:"blocking",message:"The archive's contents exceed the maximum uncompressed size when expanded.",limit:{name:"archiveLimits.maxUncompressedBytes",value:Ks.maxUncompressedBytes},source:Z("§Shared package checks → Archive size")},{id:"archive-too-many-entries",category:"package-archive",severity:"blocking",message:"The archive contains more entries than the maximum allowed.",limit:{name:"archiveLimits.maxEntries",value:Ks.maxEntries},source:Z("§Shared package checks → Entry count")},{id:"archive-encrypted-entry",category:"package-archive",severity:"blocking",message:"The archive contains an encrypted entry, which cannot be scanned.",source:Z("§Shared package checks → Archive integrity")},{id:"archive-path-traversal",category:"package-archive",severity:"blocking",message:"An entry path escapes the package root via a `..` segment.",source:Z("§Shared package checks → Entry paths")},{id:"archive-absolute-path",category:"package-archive",severity:"blocking",message:"An entry path is absolute rather than package-relative.",source:Z("§Shared package checks → Entry paths")},{id:"archive-backslash-path",category:"package-archive",severity:"blocking",message:"An entry path uses a backslash separator.",source:Z("§Shared package checks → Entry paths")},{id:"archive-empty-path-segment",category:"package-archive",severity:"blocking",message:"An entry path contains an empty or `.` segment.",source:Z("§Shared package checks → Entry paths")},{id:"archive-path-whitespace",category:"package-archive",severity:"blocking",message:"An entry path has leading or trailing whitespace.",source:Z("§Shared package checks → Entry paths")},{id:"archive-path-control-character",category:"package-archive",severity:"blocking",message:"An entry path contains a control character or NUL byte.",source:Z("§Shared package checks → Entry paths")},{id:"archive-duplicate-path",category:"package-archive",severity:"blocking",message:"Two entries normalize to the same path, including case-insensitive collisions.",source:Z("§Shared package checks → Entry paths")},{id:"archive-symlink-entry",category:"package-archive",severity:"blocking",message:"The archive contains a symlink or hardlink entry.",source:Z("§Shared package checks → Archive integrity")},{id:"manifest-missing",category:"package-manifest",severity:"blocking",message:"The package contains no plugin manifest.",source:Z("§Shared package checks → Manifest")},{id:"manifest-invalid-json",category:"package-manifest",severity:"blocking",message:"The plugin manifest is not valid JSON.",source:Z("§Shared package checks → Manifest")},{id:"manifest-name-missing",category:"package-manifest",severity:"blocking",message:"The manifest declares no plugin name.",source:Z("§Shared package checks → Manifest")},{id:"manifest-name-too-long",category:"package-manifest",severity:"blocking",message:"The manifest's plugin name exceeds the maximum length.",limit:{name:"fieldLimits.nameMaxLength",value:Lt.nameMaxLength},source:Z("§Shared package checks → Manifest")},{id:"manifest-version-invalid",category:"package-manifest",severity:"blocking",message:"The manifest's version is not a valid semantic version.",source:Z("§Shared package checks → Manifest")},{id:"interface-display-name-missing",category:"package-manifest",severity:"blocking",message:"The OpenAI interface document declares no display name.",source:Z("§Listing fields → Interface")},{id:"interface-display-name-too-long",category:"package-manifest",severity:"blocking",message:"The interface display name exceeds the maximum length.",limit:{name:"fieldLimits.displayNameMaxLength",value:Lt.displayNameMaxLength},source:Z("§Listing fields → Interface")},{id:"interface-short-description-too-long",category:"package-manifest",severity:"blocking",message:"The interface short description exceeds the maximum length.",limit:{name:"fieldLimits.shortDescriptionMaxLength",value:Lt.shortDescriptionMaxLength},source:Z("§Listing fields → Interface")},{id:"interface-default-prompt-too-long",category:"package-manifest",severity:"blocking",message:"The interface default prompt exceeds the maximum length.",limit:{name:"fieldLimits.defaultPromptMaxLength",value:Lt.defaultPromptMaxLength},source:Z("§Listing fields → Interface")},{id:"interface-brand-color-invalid",category:"package-manifest",severity:"blocking",message:"The brand color is not a six-digit hex value.",source:Z("§Listing fields → Interface")},{id:"interface-brand-color-low-contrast",category:"package-manifest",severity:"blocking",message:"The brand color does not meet the minimum contrast ratio against both the light and dark backgrounds.",source:Z("§Listing fields → Interface")},{id:"interface-yaml-invalid",category:"package-manifest",severity:"blocking",message:"The OpenAI interface document is not valid YAML.",source:Z("§Listing fields → Interface")},{id:"interface-unsupported-text",category:"package-manifest",severity:"blocking",message:"A text field contains control characters or Unicode line/paragraph separators.",source:Z("§Listing fields → Text")},{id:"skill-metadata-missing",category:"package-skills",severity:"blocking",message:"A skill directory contains no SKILL.md.",source:Z("§Skills → Structure")},{id:"skill-frontmatter-invalid",category:"package-skills",severity:"blocking",message:"A skill's SKILL.md frontmatter is missing or malformed.",source:Z("§Skills → Frontmatter")},{id:"skill-name-missing",category:"package-skills",severity:"blocking",message:"A skill's frontmatter declares no name.",source:Z("§Skills → Frontmatter")},{id:"skill-name-too-long",category:"package-skills",severity:"blocking",message:"A skill name exceeds the maximum length.",limit:{name:"fieldLimits.skillNameMaxLength",value:Lt.skillNameMaxLength},source:Z("§Skills → Frontmatter")},{id:"skill-description-missing",category:"package-skills",severity:"blocking",message:"A skill's frontmatter declares no description.",source:Z("§Skills → Frontmatter")},{id:"skill-name-collision",category:"package-skills",severity:"blocking",message:"Two skills in the package declare the same name.",source:Z("§Skills → Structure")},{id:"asset-unsupported-type",category:"package-assets",severity:"blocking",message:"An image is not one of the accepted formats.",source:Z("§Images → Format")},{id:"asset-too-large",category:"package-assets",severity:"blocking",message:"An image exceeds the maximum file size.",limit:{name:"imageConstraints.maxBytes",value:Ys.maxBytes},source:Z("§Images → Size")},{id:"asset-too-small",category:"package-assets",severity:"blocking",message:"An image is smaller than the minimum edge length.",limit:{name:"imageConstraints.minEdgePx",value:Ys.minEdgePx},source:Z("§Images → Dimensions")},{id:"asset-too-big-dimensions",category:"package-assets",severity:"blocking",message:"An image exceeds the maximum edge length.",limit:{name:"imageConstraints.maxEdgePx",value:Ys.maxEdgePx},source:Z("§Images → Dimensions")},{id:"asset-not-square",category:"package-assets",severity:"blocking",message:"An image is not square.",source:Z("§Images → Dimensions")},{id:"asset-undecodable",category:"package-assets",severity:"blocking",message:"An image's dimensions could not be read from its bytes.",source:Z("§Images → Format")},{id:"asset-svg-malformed",category:"package-assets",severity:"blocking",message:"An SVG is not well-formed XML or has no `svg` root element.",source:Z("§Images → SVG")},{id:"asset-svg-no-dimensions",category:"package-assets",severity:"blocking",message:"An SVG declares neither a numeric width/height pair nor a numeric viewBox.",source:Z("§Images → SVG")},{id:"asset-missing",category:"package-assets",severity:"blocking",message:"An asset referenced by the manifest is absent from the package.",source:Z("§Images → Format")},{id:"listing-category-unknown",category:"listing-fields",severity:"blocking",message:"The listing names a category outside the supported set.",source:Z("§Listing fields → Categories")},{id:"listing-description-too-long",category:"listing-fields",severity:"blocking",message:"The listing description exceeds the maximum length.",limit:{name:"fieldLimits.descriptionMaxLength",value:Lt.descriptionMaxLength},source:Z("§Listing fields → Description")},{id:"listing-promotional-metadata",category:"listing-fields",severity:"blocking",message:"Listing metadata contains promotional language, pricing claims, or ranking claims.",source:Z("§Listing fields → Description")},{id:"listing-privacy-policy-missing",category:"listing-fields",severity:"blocking",message:"The listing declares no privacy policy URL.",source:Z("§Listing fields → Links")},{id:"listing-support-url-missing",category:"listing-fields",severity:"blocking",message:"The listing declares no support URL.",source:Z("§Listing fields → Links")},{id:"mcp-endpoint-not-https",category:"mcp-server",severity:"blocking",message:"The MCP endpoint is not served over HTTPS.",source:Z("§MCP tools → Endpoint")},{id:"mcp-endpoint-unreachable",category:"mcp-server",severity:"blocking",message:"The MCP endpoint could not be reached during the scan.",source:Z("§MCP tools → Endpoint")},{id:"mcp-tool-name-too-long",category:"mcp-server",severity:"blocking",message:"A tool name exceeds the maximum length.",limit:{name:"fieldLimits.toolNameMaxLength",value:Lt.toolNameMaxLength},source:Z("§MCP tools → Metadata")},{id:"mcp-tool-description-missing",category:"mcp-server",severity:"blocking",message:"A tool declares no description.",source:Z("§MCP tools → Metadata")},{id:"mcp-tool-annotations-missing",category:"mcp-server",severity:"blocking",message:"A tool is missing one or more of the required annotation hints.",source:Z("§MCP tools → Annotations")},{id:"mcp-tool-schema-invalid",category:"mcp-server",severity:"blocking",message:"A tool's input or output schema is not a valid JSON Schema object.",source:Z("§MCP tools → Schemas")},{id:"mcp-domain-not-verified",category:"mcp-server",severity:"blocking",message:"The MCP server's domain has not completed domain verification.",source:Z("§MCP tools → Domain verification")},{id:"mcp-csp-domain-missing",category:"mcp-server",severity:"blocking",message:"A UI resource loads from a domain absent from the declared content security policy.",source:Z("§MCP tools → Content security policy")},{id:"mcp-ui-domain-missing",category:"mcp-server",severity:"blocking",message:"A UI resource declares no `_meta.ui.domain`.",source:Z("§MCP tools → UI resources")},{id:"mcp-ui-domain-duplicate",category:"mcp-server",severity:"blocking",message:"Two UI resources declare the same `_meta.ui.domain`.",source:Z("§MCP tools → UI resources")},{id:"mcp-ui-mime-invalid",category:"mcp-server",severity:"blocking",message:"A UI resource does not declare the plugin UI MIME profile.",source:Z("§MCP tools → UI resources")},{id:"mcp-skill-too-many",category:"mcp-skills",severity:"blocking",message:"The server advertises more importable skills than the maximum.",limit:{name:"mcpSkillLimits.maxSkills",value:nn.maxSkills},source:Z("§Skills → Imported from MCP")},{id:"mcp-skill-markdown-too-large",category:"mcp-skills",severity:"blocking",message:"An imported skill's markdown exceeds the maximum size.",limit:{name:"mcpSkillLimits.maxSkillMarkdownBytes",value:nn.maxSkillMarkdownBytes},source:Z("§Skills → Imported from MCP")},{id:"mcp-skill-page-too-large",category:"mcp-skills",severity:"blocking",message:"An imported skill's supporting page exceeds the maximum size.",limit:{name:"mcpSkillLimits.maxPageBytes",value:nn.maxPageBytes},source:Z("§Skills → Imported from MCP")},{id:"mcp-skill-too-many-pages",category:"mcp-skills",severity:"blocking",message:"An imported skill has more supporting pages than the maximum.",limit:{name:"mcpSkillLimits.maxPagesPerSkill",value:nn.maxPagesPerSkill},source:Z("§Skills → Imported from MCP")},{id:"mcp-skill-total-too-large",category:"mcp-skills",severity:"blocking",message:"An imported skill's total footprint exceeds the maximum.",limit:{name:"mcpSkillLimits.maxSkillTotalBytes",value:nn.maxSkillTotalBytes},source:Z("§Skills → Imported from MCP")},{id:"mcp-skills-total-too-large",category:"mcp-skills",severity:"blocking",message:"The imported skills exceed the maximum combined size.",limit:{name:"mcpSkillLimits.maxImportedTotalBytes",value:nn.maxImportedTotalBytes},source:Z("§Skills → Imported from MCP")},{id:"mcp-skill-digest-mismatch",category:"mcp-skills",severity:"blocking",message:"An imported skill's declared digest does not match the resource served for it.",source:Z("§Skills → Imported from MCP")},{id:"mcp-skill-frontmatter-mismatch",category:"mcp-skills",severity:"blocking",message:"An imported skill's listing metadata disagrees with its SKILL.md frontmatter.",source:Z("§Skills → Imported from MCP")},{id:"mcp-skill-scan-failed",category:"mcp-skills",severity:"blocking",message:"The skill scan failed, so the draft's imported skills were not updated.",source:Z("§Skills → Imported from MCP")},{id:"review-success-tests-missing",category:"review-materials",severity:"blocking",message:"Fewer successful test cases were supplied than required.",limit:{name:"submissionTestCases.successCount",value:ml.successCount},source:Z("§Review materials → Test cases")},{id:"review-failure-tests-missing",category:"review-materials",severity:"blocking",message:"Fewer graceful-failure test cases were supplied than required.",limit:{name:"submissionTestCases.failureCount",value:ml.failureCount},source:Z("§Review materials → Test cases")},{id:"review-demo-credentials-missing",category:"review-materials",severity:"blocking",message:"The submission authenticates users but supplies no reviewer demo credentials.",source:Z("§Review materials → Demo access")},{id:"review-demo-recording-missing",category:"review-materials",severity:"blocking",message:"No demo recording was supplied.",source:Z("§Review materials → Demo access")},{id:"review-release-notes-missing",category:"review-materials",severity:"blocking",message:"An updated submission supplies no release notes.",source:Z("§Review materials → Release notes")},{id:"review-attestation-missing",category:"review-materials",severity:"blocking",message:"A required policy attestation was not affirmed.",source:Z("§Review materials → Attestations")},{id:"review-identity-not-verified",category:"review-materials",severity:"blocking",message:"The submitting account has not completed identity verification.",source:Z("§Review materials → Account")},{id:"review-write-permission-missing",category:"review-materials",severity:"blocking",message:"The submitting account lacks the app-write permission.",source:Z("§Review materials → Account")},{id:"review-geography-missing",category:"review-materials",severity:"blocking",message:"The submission declares no country availability.",source:Z("§Review materials → Availability")},{id:"review-annotation-justification-missing",category:"review-materials",severity:"advisory",message:"A tool annotated as destructive or open-world carries no justification for review.",source:Z("§Review materials → Test cases")},{id:"review-scan-stale",category:"review-materials",severity:"blocking",message:"The draft's scan predates the current server contract; re-run Scan Tools.",source:Z("§MCP tools → Scan")},{id:"exclusion-mcp-servers-in-skills-only",category:"exclusions",severity:"blocking",message:"A skills-only submission declares MCP servers, which that shape excludes.",source:Z("§Shared package checks → Excluded content")},{id:"exclusion-app-config-in-public-package",category:"exclusions",severity:"blocking",message:"The package contains an `.app.json`, which maps registered connections for local or workspace use and is excluded from a public submission.",source:Z("§Shared package checks → Excluded content")},{id:"exclusion-screenshots-without-ui",category:"exclusions",severity:"blocking",message:"Screenshots were supplied for a submission that renders no UI template.",source:Z("§Images → Screenshots")},{id:"exclusion-bundle-in-mcp-only",category:"exclusions",severity:"blocking",message:"An MCP-only submission supplies a package archive.",source:Z("§Shared package checks → Excluded content")},{id:"exclusion-unsupported-surface",category:"exclusions",severity:"blocking",message:"The package contains a surface the plugin directory does not support.",source:Z("§Shared package checks → Excluded content")}],NL=Object.freeze(Object.fromEntries(HT.map(e=>[e.id,e]))),VT=["ownsOrIsAuthorizedForService","accurateDataDisclosure","compliesWithUsagePolicies","noProhibitedContent","maintainsSecurityPractices","respondsToSecurityReports","keepsListingAccurate"],BT=["none","account-identifiers","user-content","usage-analytics","payment-information","location","health","shared-with-third-parties"],GT=["in-submission-form","shared-out-of-band","not-required-authless"],_c=ze().url().refine(e=>e.startsWith("https://"),{message:"must be an https:// URL"}),hp=hn({prompt:ze().min(1),expectation:ze().min(1)}),WT=hn({reference:ze().min(1),mimeType:ze().min(1),widthPx:Lo().int().positive(),heightPx:Lo().int().positive(),prompt:ze().min(1)}),zL=hn({name:ze().min(1).max(Lt.nameMaxLength),shortDescription:ze().min(1).max(Lt.shortDescriptionMaxLength),description:ze().min(1).max(Lt.descriptionMaxLength),categories:Mt(Ar(jm)).min(1),privacyPolicyUrl:_c,supportUrl:_c,documentationUrl:_c.optional(),testCases:hn({successful:Mt(hp),gracefulFailure:Mt(hp)}),demoCredentials:hn({provided:rn(),delivery:Ar(GT)}),demoRecordingProvided:rn(),screenshots:Mt(WT).default([]),releaseNotes:ze().min(1).optional(),identityVerified:rn(),accountPermissions:Mt(ze().min(1)).default([]),availableCountries:Mt(ze().length(2)).default([]),dataResidencyEligible:rn().optional(),privacyPolicyDataTypes:Mt(Ar(BT)).default([]),annotationJustifications:fl(ze(),ze().min(1)).default({}),frameDomainExplanations:fl(ze(),ze().min(1)).default({}),domainVerificationToken:ze().min(1).optional(),lastScanAt:ze().datetime().optional(),hasPublishedVersion:rn().optional(),attestations:pT(Ar(VT),rn())}),UL=new TextDecoder("utf-8",{fatal:!1}),Eu=Symbol.for("yaml.alias"),ZT=Symbol.for("yaml.document"),pn=Symbol.for("yaml.map"),Hm=Symbol.for("yaml.pair"),ku=Symbol.for("yaml.scalar"),hs=Symbol.for("yaml.seq"),Yt=Symbol.for("yaml.node.type"),ui=e=>!!e&&typeof e=="object"&&e[Yt]===Eu,ps=e=>!!e&&typeof e=="object"&&e[Yt]===ZT,Ru=e=>!!e&&typeof e=="object"&&e[Yt]===pn,st=e=>!!e&&typeof e=="object"&&e[Yt]===Hm,ot=e=>!!e&&typeof e=="object"&&e[Yt]===ku,na=e=>!!e&&typeof e=="object"&&e[Yt]===hs;function bt(e){if(e&&typeof e=="object")switch(e[Yt]){case pn:case hs:return!0}return!1}function it(e){if(e&&typeof e=="object")switch(e[Yt]){case Eu:case pn:case ku:case hs:return!0}return!1}var Vm=e=>(ot(e)||bt(e))&&!!e.anchor,yt=Symbol("break visit"),Bm=Symbol("skip children"),Zt=Symbol("remove node");function fs(e,t){const r=Gm(t);ps(e)?Mn(null,e.contents,r,Object.freeze([e]))===Zt&&(e.contents=null):Mn(null,e,r,Object.freeze([]))}fs.BREAK=yt;fs.SKIP=Bm;fs.REMOVE=Zt;function Mn(e,t,r,n){const i=Wm(e,t,r,n);if(it(i)||st(i))return Zm(e,n,i),Mn(e,i,r,n);if(typeof i!="symbol"){if(bt(t)){n=Object.freeze(n.concat(t));for(let s=0;s<t.items.length;++s){const o=Mn(s,t.items[s],r,n);if(typeof o=="number")s=o-1;else{if(o===yt)return yt;o===Zt&&(t.items.splice(s,1),s-=1)}}}else if(st(t)){n=Object.freeze(n.concat(t));const s=Mn("key",t.key,r,n);if(s===yt)return yt;s===Zt&&(t.key=null);const o=Mn("value",t.value,r,n);if(o===yt)return yt;o===Zt&&(t.value=null)}}return i}async function Au(e,t){const r=Gm(t);ps(e)?await Ln(null,e.contents,r,Object.freeze([e]))===Zt&&(e.contents=null):await Ln(null,e,r,Object.freeze([]))}Au.BREAK=yt;Au.SKIP=Bm;Au.REMOVE=Zt;async function Ln(e,t,r,n){const i=await Wm(e,t,r,n);if(it(i)||st(i))return Zm(e,n,i),Ln(e,i,r,n);if(typeof i!="symbol"){if(bt(t)){n=Object.freeze(n.concat(t));for(let s=0;s<t.items.length;++s){const o=await Ln(s,t.items[s],r,n);if(typeof o=="number")s=o-1;else{if(o===yt)return yt;o===Zt&&(t.items.splice(s,1),s-=1)}}}else if(st(t)){n=Object.freeze(n.concat(t));const s=await Ln("key",t.key,r,n);if(s===yt)return yt;s===Zt&&(t.key=null);const o=await Ln("value",t.value,r,n);if(o===yt)return yt;o===Zt&&(t.value=null)}}return i}function Gm(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Wm(e,t,r,n){if(typeof r=="function")return r(e,t,n);if(Ru(t))return r.Map?.(e,t,n);if(na(t))return r.Seq?.(e,t,n);if(st(t))return r.Pair?.(e,t,n);if(ot(t))return r.Scalar?.(e,t,n);if(ui(t))return r.Alias?.(e,t,n)}function Zm(e,t,r){const n=t[t.length-1];if(bt(n))n.items[e]=r;else if(st(n))e==="key"?n.key=r:n.value=r;else if(ps(n))n.contents=r;else{const i=ui(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}var JT={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},KT=e=>e.replace(/[!,[\]{}]/g,t=>JT[t]),Jm=class nr{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},nr.defaultYaml,t),this.tags=Object.assign({},nr.defaultTags,r)}clone(){const t=new nr(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){const t=new nr(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:nr.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},nr.defaultTags)}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:nr.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},nr.defaultTags),this.atNextDocument=!1);const n=t.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[s,o]=n;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;const[s]=n;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{const o=/^\d+\.\d+$/.test(s);return r(6,`Unsupported YAML version ${s}`,o),!1}}default:return r(0,`Unknown directive ${i}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){const o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}const[,n,i]=t.match(/^(.*!)([^!]*)$/s);i||r(`The ${t} tag has no suffix`);const s=this.tags[n];if(s)try{return s+decodeURIComponent(i)}catch(o){return r(String(o)),null}return n==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(const[r,n]of Object.entries(this.tags))if(t.startsWith(n))return r+KT(t.substring(n.length));return t[0]==="!"?t:`!<${t}>`}toString(t){const r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let i;if(t&&n.length>0&&it(t.contents)){const s={};fs(t.contents,(o,a)=>{it(a)&&a.tag&&(s[a.tag]=!0)}),i=Object.keys(s)}else i=[];for(const[s,o]of n)s==="!!"&&o==="tag:yaml.org,2002:"||(!t||i.some(a=>a.startsWith(o)))&&r.push(`%TAG ${s} ${o}`);return r.join(`
46
- `)}};Jm.defaultYaml={explicit:!1,version:"1.2"};Jm.defaultTags={"!!":"tag:yaml.org,2002:"};function Km(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){const t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(t)}return!0}function Ci(e,t,r,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,s=n.length;i<s;++i){const o=n[i],a=Ci(e,n,String(i),o);a===void 0?delete n[i]:a!==o&&(n[i]=a)}else if(n instanceof Map)for(const i of Array.from(n.keys())){const s=n.get(i),o=Ci(e,n,i,s);o===void 0?n.delete(i):o!==s&&n.set(i,o)}else if(n instanceof Set)for(const i of Array.from(n)){const s=Ci(e,n,i,i);s===void 0?n.delete(i):s!==i&&(n.delete(i),n.add(s))}else for(const[i,s]of Object.entries(n)){const o=Ci(e,n,i,s);o===void 0?delete n[i]:o!==s&&(n[i]=o)}return e.call(t,r,n)}function Ft(e,t,r){if(Array.isArray(e))return e.map((n,i)=>Ft(n,String(i),r));if(e&&typeof e.toJSON=="function"){if(!r||!Vm(e))return e.toJSON(t,r);const n={aliasCount:0,count:1,res:void 0};r.anchors.set(e,n),r.onCreate=s=>{n.res=s,delete r.onCreate};const i=e.toJSON(t,r);return r.onCreate&&r.onCreate(i),i}return typeof e=="bigint"&&!r?.keep?Number(e):e}var Iu=class{constructor(e){Object.defineProperty(this,Yt,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:r,onAnchor:n,reviver:i}={}){if(!ps(e))throw new TypeError("A document argument is required");const s={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},o=Ft(this,"",s);if(typeof n=="function")for(const{count:a,res:c}of s.anchors.values())n(c,a);return typeof i=="function"?Ci(i,{"":o},"",o):o}},YT=class extends Iu{constructor(e){super(Eu),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if(t?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;t?.aliasResolveCache?r=t.aliasResolveCache:(r=[],fs(e,{Node:(i,s)=>{(ui(s)||Vm(s))&&r.push(s)}}),t&&(t.aliasResolveCache=r));let n;for(const i of r){if(i===this)break;i.anchor===this.source&&(n=i)}if(n&&t){const{anchors:i,doc:s,maxAliasCount:o}=t;let a=i.get(n);if(a||(Ft(n,null,t),a=i.get(n)),a?.res===void 0)throw new ReferenceError("This should not happen: Alias anchor was not resolved?");if(o>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Xs(s,n,i)),a.count*a.aliasCount>o))throw new ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return n}toJSON(e,t){if(!t)return{source:this.source};const r=this.resolve(t.doc,t);if(!r){const n=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(n)}return t.anchors.get(r).res}toString(e,t,r){const n=`*${this.source}`;if(e){if(Km(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${n} `}return n}};function Xs(e,t,r){if(ui(t)){const n=t.resolve(e),i=r&&n&&r.get(n);return i?i.count*i.aliasCount:0}else if(bt(t)){let n=0;for(const i of t.items){const s=Xs(e,i,r);s>n&&(n=s)}return n}else if(st(t)){const n=Xs(e,t.key,r),i=Xs(e,t.value,r);return Math.max(n,i)}return 1}var Ym=e=>!e||typeof e!="function"&&typeof e!="object",Ke=class extends Iu{constructor(e){super(ku),this.value=e}toJSON(e,t){return t?.keep?this.value:Ft(this.value,e,t)}toString(){return String(this.value)}};Ke.BLOCK_FOLDED="BLOCK_FOLDED";Ke.BLOCK_LITERAL="BLOCK_LITERAL";Ke.PLAIN="PLAIN";Ke.QUOTE_DOUBLE="QUOTE_DOUBLE";Ke.QUOTE_SINGLE="QUOTE_SINGLE";var XT="tag:yaml.org,2002:";function QT(e,t,r){if(t){const n=r.filter(s=>s.tag===t),i=n.find(s=>!s.format)??n[0];if(!i)throw new Error(`Tag ${t} not found`);return i}return r.find(n=>n.identify?.(e)&&!n.format)}function Do(e,t,r){if(ps(e)&&(e=e.contents),it(e))return e;if(st(e)){const h=r.schema[pn].createNode?.(r.schema,null,r);return h.items.push(e),h}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());const{aliasDuplicateObjects:n,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=r;let c;if(n&&e&&typeof e=="object"){if(c=a.get(e),c)return c.anchor??(c.anchor=i(e)),new YT(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t=XT+t.slice(2));let l=QT(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){const h=new Ke(e);return c&&(c.node=h),h}l=e instanceof Map?o[pn]:Symbol.iterator in Object(e)?o[hs]:o[pn]}s&&(s(l),delete r.onTagObj);const u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new Ke(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function pp(e,t,r){let n=r;for(let i=t.length-1;i>=0;--i){const s=t[i];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){const o=[];o[s]=n,n=o}else n=new Map([[s,n]])}return Do(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var e$=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Xm=class extends Iu{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(r=>it(r)||st(r)?r.clone(e):r),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(e$(e))this.add(t);else{const[r,...n]=e,i=this.get(r,!0);if(bt(i))i.addIn(n,t);else if(i===void 0&&this.schema)this.set(r,pp(this.schema,n,t));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(e){const[t,...r]=e;if(r.length===0)return this.delete(t);const n=this.get(t,!0);if(bt(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){const[r,...n]=e,i=this.get(r,!0);return n.length===0?!t&&ot(i)?i.value:i:bt(i)?i.getIn(n,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!st(t))return!1;const r=t.value;return r==null||e&&ot(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){const[t,...r]=e;if(r.length===0)return this.has(t);const n=this.get(t,!0);return bt(n)?n.hasIn(r):!1}setIn(e,t){const[r,...n]=e;if(n.length===0)this.set(r,t);else{const i=this.get(r,!0);if(bt(i))i.setIn(n,t);else if(i===void 0&&this.schema)this.set(r,pp(this.schema,n,t));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}},t$=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function ss(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Dn=(e,t,r)=>e.endsWith(`
47
- `)?ss(r,t):r.includes(`
39
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of e.seen.entries()){const a=o[1];if(t===o[0]){s(o);continue}if(e.external){const c=e.external.registry.get(o[0])?.id;if(t!==o[0]&&c){s(o);continue}}if(e.metadataRegistry.get(o[0])?.id){s(o);continue}if(a.cycle){s(o);continue}if(a.count>1&&e.reused==="ref"){s(o);continue}}}function so(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=o=>{const a=e.seen.get(o);if(a.ref===null)return;const c=a.def??a.schema,l={...c},u=a.ref;if(a.ref=null,u){n(u);const d=e.seen.get(u),p=d.schema;if(p.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(p)):Object.assign(c,p),Object.assign(c,l),o._zod.parent===u)for(const f in c)f==="$ref"||f==="allOf"||f in l||delete c[f];if(p.$ref&&d.def)for(const f in c)f==="$ref"||f==="allOf"||f in d.def&&JSON.stringify(c[f])===JSON.stringify(d.def[f])&&delete c[f]}const h=o._zod.parent;if(h&&h!==u){n(h);const d=e.seen.get(h);if(d?.schema.$ref&&(c.$ref=d.schema.$ref,d.def))for(const p in c)p==="$ref"||p==="allOf"||p in d.def&&JSON.stringify(c[p])===JSON.stringify(d.def[p])&&delete c[p]}e.override({zodSchema:o,jsonSchema:c,path:a.path??[]})};for(const o of[...e.seen.entries()].reverse())n(o[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const o=e.external.registry.get(t)?.id;if(!o)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(o)}Object.assign(i,r.def??r.schema);const s=e.external?.defs??{};for(const o of e.seen.entries()){const a=o[1];a.def&&a.defId&&(s[a.defId]=a.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?i.$defs=s:i.definitions=s);try{const o=JSON.parse(JSON.stringify(i));return Object.defineProperty(o,"~standard",{value:{...t["~standard"],jsonSchema:{input:oo(t,"input",e.processors),output:oo(t,"output",e.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function dt(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return dt(n.element,r);if(n.type==="set")return dt(n.valueType,r);if(n.type==="lazy")return dt(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return dt(n.innerType,r);if(n.type==="intersection")return dt(n.left,r)||dt(n.right,r);if(n.type==="record"||n.type==="map")return dt(n.keyType,r)||dt(n.valueType,r);if(n.type==="pipe")return dt(n.in,r)||dt(n.out,r);if(n.type==="object"){for(const i in n.shape)if(dt(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(const i of n.options)if(dt(i,r))return!0;return!1}if(n.type==="tuple"){for(const i of n.items)if(dt(i,r))return!0;return!!(n.rest&&dt(n.rest,r))}return!1}var Kw=(e,t={})=>r=>{const n=no({...r,processors:t});return Fe(e,n),io(n,e),so(n,e)},oo=(e,t,r={})=>n=>{const{libraryOptions:i,target:s}=n??{},o=no({...i??{},target:s,io:t,processors:r});return Fe(e,o),io(o,e),so(o,e)},Yw={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Af=(e,t,r,n)=>{const i=r;i.type="string";const{minimum:s,maximum:o,format:a,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof s=="number"&&(i.minLength=s),typeof o=="number"&&(i.maxLength=o),a&&(i.format=Yw[a]??a,i.format===""&&delete i.format,a==="time"&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){const u=[...c];u.length===1?i.pattern=u[0].source:u.length>1&&(i.allOf=[...u.map(h=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))])}},If=(e,t,r,n)=>{const i=r,{minimum:s,maximum:o,format:a,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof a=="string"&&a.includes("int")?i.type="integer":i.type="number",typeof u=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u),typeof s=="number"&&(i.minimum=s,typeof u=="number"&&t.target!=="draft-04"&&(u>=s?delete i.minimum:delete i.exclusiveMinimum)),typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l),typeof o=="number"&&(i.maximum=o,typeof l=="number"&&t.target!=="draft-04"&&(l<=o?delete i.maximum:delete i.exclusiveMaximum)),typeof c=="number"&&(i.multipleOf=c)},Tf=(e,t,r,n)=>{r.type="boolean"},Xw=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},Qw=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},Cf=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},$f=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},eS=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},Pf=(e,t,r,n)=>{r.not={}},Of=(e,t,r,n)=>{},xf=(e,t,r,n)=>{},tS=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Mf=(e,t,r,n)=>{const i=e._zod.def,s=sf(i.entries);s.every(o=>typeof o=="number")&&(r.type="number"),s.every(o=>typeof o=="string")&&(r.type="string"),r.enum=s},Lf=(e,t,r,n)=>{const i=e._zod.def,s=[];for(const o of i.values)if(o===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(o))}else s.push(o);if(s.length!==0)if(s.length===1){const o=s[0];r.type=o===null?"null":typeof o,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[o]:r.const=o}else s.every(o=>typeof o=="number")&&(r.type="number"),s.every(o=>typeof o=="string")&&(r.type="string"),s.every(o=>typeof o=="boolean")&&(r.type="boolean"),s.every(o=>o===null)&&(r.type="null"),r.enum=s},rS=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},nS=(e,t,r,n)=>{const i=r,s=e._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=s.source},iS=(e,t,r,n)=>{const i=r,s={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:a,mime:c}=e._zod.bag;o!==void 0&&(s.minLength=o),a!==void 0&&(s.maxLength=a),c?c.length===1?(s.contentMediaType=c[0],Object.assign(i,s)):(Object.assign(i,s),i.anyOf=c.map(l=>({contentMediaType:l}))):Object.assign(i,s)},sS=(e,t,r,n)=>{r.type="boolean"},Df=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},oS=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},Nf=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},aS=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},cS=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},zf=(e,t,r,n)=>{const i=r,s=e._zod.def,{minimum:o,maximum:a}=e._zod.bag;typeof o=="number"&&(i.minItems=o),typeof a=="number"&&(i.maxItems=a),i.type="array",i.items=Fe(s.element,t,{...n,path:[...n.path,"items"]})},Uf=(e,t,r,n)=>{const i=r,s=e._zod.def;i.type="object",i.properties={};const o=s.shape;for(const l in o)i.properties[l]=Fe(o[l],t,{...n,path:[...n.path,"properties",l]});const a=new Set(Object.keys(o)),c=new Set([...a].filter(l=>{const u=s.shape[l]._zod;return t.io==="input"?u.optin===void 0:u.optout===void 0}));c.size>0&&(i.required=Array.from(c)),s.catchall?._zod.def.type==="never"?i.additionalProperties=!1:s.catchall?s.catchall&&(i.additionalProperties=Fe(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},Ff=(e,t,r,n)=>{const i=e._zod.def,s=i.inclusive===!1,o=i.options.map((a,c)=>Fe(a,t,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=o:r.anyOf=o},qf=(e,t,r,n)=>{const i=e._zod.def,s=Fe(i.left,t,{...n,path:[...n.path,"allOf",0]}),o=Fe(i.right,t,{...n,path:[...n.path,"allOf",1]}),a=c=>"allOf"in c&&Object.keys(c).length===1;r.allOf=[...a(s)?s.allOf:[s],...a(o)?o.allOf:[o]]},jf=(e,t,r,n)=>{const i=r,s=e._zod.def;i.type="array";const o=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=s.items.map((d,p)=>Fe(d,t,{...n,path:[...n.path,o,p]})),l=s.rest?Fe(s.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null;t.target==="draft-2020-12"?(i.prefixItems=c,l&&(i.items=l)):t.target==="openapi-3.0"?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));const{minimum:u,maximum:h}=e._zod.bag;typeof u=="number"&&(i.minItems=u),typeof h=="number"&&(i.maxItems=h)},Hf=(e,t,r,n)=>{const i=r,s=e._zod.def;i.type="object";const o=s.keyType,a=o._zod.bag?.patterns;if(s.mode==="loose"&&a&&a.size>0){const l=Fe(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});i.patternProperties={};for(const u of a)i.patternProperties[u.source]=l}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(i.propertyNames=Fe(s.keyType,t,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=Fe(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const c=o._zod.values;if(c){const l=[...c].filter(u=>typeof u=="string"||typeof u=="number");l.length>0&&(i.required=l)}},Vf=(e,t,r,n)=>{const i=e._zod.def,s=Fe(i.innerType,t,n),o=t.seen.get(e);t.target==="openapi-3.0"?(o.ref=i.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},Bf=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType},Gf=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},Wf=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Zf=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=o},Jf=(e,t,r,n)=>{const i=e._zod.def,s=t.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;Fe(s,t,n);const o=t.seen.get(e);o.ref=s},Kf=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType,r.readOnly=!0},lS=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType},Hl=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType},Yf=(e,t,r,n)=>{const i=e._zod.innerType;Fe(i,t,n);const s=t.seen.get(e);s.ref=i},fd={string:Af,number:If,boolean:Tf,bigint:Xw,symbol:Qw,null:Cf,undefined:$f,void:eS,never:Pf,any:Of,unknown:xf,date:tS,enum:Mf,literal:Lf,nan:rS,template_literal:nS,file:iS,success:sS,custom:Df,function:oS,transform:Nf,map:aS,set:cS,array:zf,object:Uf,union:Ff,intersection:qf,tuple:jf,record:Hf,nullable:Vf,nonoptional:Bf,default:Gf,prefault:Wf,catch:Zf,pipe:Jf,readonly:Kf,promise:lS,optional:Hl,lazy:Yf};function wM(e,t){if("_idmap"in e){const n=e,i=no({...t,processors:fd}),s={};for(const a of n._idmap.entries()){const[c,l]=a;Fe(l,i)}const o={};i.external={registry:n,uri:t?.uri,defs:s};for(const a of n._idmap.entries()){const[c,l]=a;io(i,l),o[c]=so(i,l)}return Object.keys(s).length>0&&(o.__shared={[i.target==="draft-2020-12"?"$defs":"definitions"]:s}),{schemas:o}}const r=no({...t,processors:fd});return Fe(e,r),io(r,e),so(r,e)}var uS=x("ZodISODateTime",(e,t)=>{db.init(e,t),Ye.init(e,t)});function dS(e){return Sw(uS,e)}var hS=x("ZodISODate",(e,t)=>{hb.init(e,t),Ye.init(e,t)});function pS(e){return Ew(hS,e)}var fS=x("ZodISOTime",(e,t)=>{pb.init(e,t),Ye.init(e,t)});function vS(e){return kw(fS,e)}var gS=x("ZodISODuration",(e,t)=>{fb.init(e,t),Ye.init(e,t)});function mS(e){return Rw(gS,e)}var Xf=(e,t)=>{lf.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>r0(e,r)},flatten:{value:r=>t0(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,kc,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,kc,2)}},isEmpty:{get(){return e.issues.length===0}}})},SM=x("ZodError",Xf),Ct=x("ZodError",Xf,{Parent:Error}),_S=Fl(Ct),yS=ql(Ct),bS=qo(Ct),wS=jo(Ct),SS=s0(Ct),ES=o0(Ct),kS=a0(Ct),RS=c0(Ct),AS=l0(Ct),IS=u0(Ct),TS=d0(Ct),CS=h0(Ct),Ne=x("ZodType",(e,t)=>(Me.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:oo(e,"input"),output:oo(e,"output")}}),e.toJSONSchema=Kw(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(jr(t,{checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),e.with=e.check,e.clone=(r,n)=>lr(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>_S(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>bS(e,r,n),e.parseAsync=async(r,n)=>yS(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>wS(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>SS(e,r,n),e.decode=(r,n)=>ES(e,r,n),e.encodeAsync=async(r,n)=>kS(e,r,n),e.decodeAsync=async(r,n)=>RS(e,r,n),e.safeEncode=(r,n)=>AS(e,r,n),e.safeDecode=(r,n)=>IS(e,r,n),e.safeEncodeAsync=async(r,n)=>TS(e,r,n),e.safeDecodeAsync=async(r,n)=>CS(e,r,n),e.refine=(r,n)=>e.check(kE(r,n)),e.superRefine=r=>e.check(RE(r)),e.overwrite=r=>e.check(si(r)),e.optional=()=>md(e),e.exactOptional=()=>dE(e),e.nullable=()=>_d(e),e.nullish=()=>md(_d(e)),e.nonoptional=r=>mE(e,r),e.array=()=>Ot(e),e.or=r=>rE([e,r]),e.and=r=>sE(e,r),e.transform=r=>Cc(e,iv(r)),e.default=r=>fE(e,r),e.prefault=r=>gE(e,r),e.catch=r=>yE(e,r),e.pipe=r=>Cc(e,r),e.readonly=()=>SE(e),e.describe=r=>{const n=e.clone();return Ai.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Ai.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Ai.get(e);const n=e.clone();return Ai.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=r=>r(e),e)),Qf=x("_ZodString",(e,t)=>{jl.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(n,i,s)=>Af(e,n,i,s);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(Mw(...n)),e.includes=(...n)=>e.check(Nw(...n)),e.startsWith=(...n)=>e.check(zw(...n)),e.endsWith=(...n)=>e.check(Uw(...n)),e.min=(...n)=>e.check(ro(...n)),e.max=(...n)=>e.check(kf(...n)),e.length=(...n)=>e.check(Rf(...n)),e.nonempty=(...n)=>e.check(ro(1,...n)),e.lowercase=n=>e.check(Lw(n)),e.uppercase=n=>e.check(Dw(n)),e.trim=()=>e.check(qw()),e.normalize=(...n)=>e.check(Fw(...n)),e.toLowerCase=()=>e.check(jw()),e.toUpperCase=()=>e.check(Hw()),e.slugify=()=>e.check(Vw())}),$S=x("ZodString",(e,t)=>{jl.init(e,t),Qf.init(e,t),e.email=r=>e.check(tw(PS,r)),e.url=r=>e.check(ow(OS,r)),e.jwt=r=>e.check(ww(WS,r)),e.emoji=r=>e.check(aw(xS,r)),e.guid=r=>e.check(ud(vd,r)),e.uuid=r=>e.check(rw(_s,r)),e.uuidv4=r=>e.check(nw(_s,r)),e.uuidv6=r=>e.check(iw(_s,r)),e.uuidv7=r=>e.check(sw(_s,r)),e.nanoid=r=>e.check(cw(MS,r)),e.guid=r=>e.check(ud(vd,r)),e.cuid=r=>e.check(lw(LS,r)),e.cuid2=r=>e.check(uw(DS,r)),e.ulid=r=>e.check(dw(NS,r)),e.base64=r=>e.check(_w(VS,r)),e.base64url=r=>e.check(yw(BS,r)),e.xid=r=>e.check(hw(zS,r)),e.ksuid=r=>e.check(pw(US,r)),e.ipv4=r=>e.check(fw(FS,r)),e.ipv6=r=>e.check(vw(qS,r)),e.cidrv4=r=>e.check(gw(jS,r)),e.cidrv6=r=>e.check(mw(HS,r)),e.e164=r=>e.check(bw(GS,r)),e.datetime=r=>e.check(dS(r)),e.date=r=>e.check(pS(r)),e.time=r=>e.check(vS(r)),e.duration=r=>e.check(mS(r))});function ze(e){return ew($S,e)}var Ye=x("ZodStringFormat",(e,t)=>{Ze.init(e,t),Qf.init(e,t)}),PS=x("ZodEmail",(e,t)=>{rb.init(e,t),Ye.init(e,t)}),vd=x("ZodGUID",(e,t)=>{eb.init(e,t),Ye.init(e,t)}),_s=x("ZodUUID",(e,t)=>{tb.init(e,t),Ye.init(e,t)}),OS=x("ZodURL",(e,t)=>{nb.init(e,t),Ye.init(e,t)}),xS=x("ZodEmoji",(e,t)=>{ib.init(e,t),Ye.init(e,t)}),MS=x("ZodNanoID",(e,t)=>{sb.init(e,t),Ye.init(e,t)}),LS=x("ZodCUID",(e,t)=>{ob.init(e,t),Ye.init(e,t)}),DS=x("ZodCUID2",(e,t)=>{ab.init(e,t),Ye.init(e,t)}),NS=x("ZodULID",(e,t)=>{cb.init(e,t),Ye.init(e,t)}),zS=x("ZodXID",(e,t)=>{lb.init(e,t),Ye.init(e,t)}),US=x("ZodKSUID",(e,t)=>{ub.init(e,t),Ye.init(e,t)}),FS=x("ZodIPv4",(e,t)=>{vb.init(e,t),Ye.init(e,t)}),qS=x("ZodIPv6",(e,t)=>{gb.init(e,t),Ye.init(e,t)}),jS=x("ZodCIDRv4",(e,t)=>{mb.init(e,t),Ye.init(e,t)}),HS=x("ZodCIDRv6",(e,t)=>{_b.init(e,t),Ye.init(e,t)}),VS=x("ZodBase64",(e,t)=>{yb.init(e,t),Ye.init(e,t)}),BS=x("ZodBase64URL",(e,t)=>{wb.init(e,t),Ye.init(e,t)}),GS=x("ZodE164",(e,t)=>{Sb.init(e,t),Ye.init(e,t)}),WS=x("ZodJWT",(e,t)=>{kb.init(e,t),Ye.init(e,t)}),ev=x("ZodNumber",(e,t)=>{yf.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(n,i,s)=>If(e,n,i,s),e.gt=(n,i)=>e.check(hd(n,i)),e.gte=(n,i)=>e.check(Ia(n,i)),e.min=(n,i)=>e.check(Ia(n,i)),e.lt=(n,i)=>e.check(dd(n,i)),e.lte=(n,i)=>e.check(Aa(n,i)),e.max=(n,i)=>e.check(Aa(n,i)),e.int=n=>e.check(gd(n)),e.safe=n=>e.check(gd(n)),e.positive=n=>e.check(hd(0,n)),e.nonnegative=n=>e.check(Ia(0,n)),e.negative=n=>e.check(dd(0,n)),e.nonpositive=n=>e.check(Aa(0,n)),e.multipleOf=(n,i)=>e.check(pd(n,i)),e.step=(n,i)=>e.check(pd(n,i)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function ao(e){return Aw(ev,e)}var ZS=x("ZodNumberFormat",(e,t)=>{Rb.init(e,t),ev.init(e,t)});function gd(e){return Iw(ZS,e)}var JS=x("ZodBoolean",(e,t)=>{Ab.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Tf(e,r,n,i)});function Yr(e){return Tw(JS,e)}var KS=x("ZodUndefined",(e,t)=>{Ib.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>$f(e,r,n,i)});function EM(e){return Cw(KS,e)}var YS=x("ZodNull",(e,t)=>{Tb.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Cf(e,r,n,i)});function kM(e){return $w(YS,e)}var XS=x("ZodAny",(e,t)=>{Cb.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Of(e,r,n,i)});function RM(){return Pw(XS)}var QS=x("ZodUnknown",(e,t)=>{$b.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>xf(e,r,n,i)});function Ac(){return Ow(QS)}var eE=x("ZodNever",(e,t)=>{Pb.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Pf(e,r,n,i)});function tv(e){return xw(eE,e)}var tE=x("ZodArray",(e,t)=>{Ob.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>zf(e,r,n,i),e.element=t.element,e.min=(r,n)=>e.check(ro(r,n)),e.nonempty=r=>e.check(ro(1,r)),e.max=(r,n)=>e.check(kf(r,n)),e.length=(r,n)=>e.check(Rf(r,n)),e.unwrap=()=>e.element});function Ot(e,t){return Bw(tE,e,t)}var Vl=x("ZodObject",(e,t)=>{Mb.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Uf(e,r,n,i),Ae(e,"shape",()=>t.shape),e.keyof=()=>br(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Ac()}),e.loose=()=>e.clone({...e._zod.def,catchall:Ac()}),e.strict=()=>e.clone({...e._zod.def,catchall:tv()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>Ky(e,r),e.safeExtend=r=>Yy(e,r),e.merge=r=>Xy(e,r),e.pick=r=>Zy(e,r),e.omit=r=>Jy(e,r),e.partial=(...r)=>Qy(sv,e,r[0]),e.required=(...r)=>e0(ov,e,r[0])});function on(e,t){const r={type:"object",shape:e??{},...re(t)};return new Vl(r)}function AM(e,t){return new Vl({type:"object",shape:e,catchall:tv(),...re(t)})}function IM(e,t){return new Vl({type:"object",shape:e,catchall:Ac(),...re(t)})}var rv=x("ZodUnion",(e,t)=>{Sf.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Ff(e,r,n,i),e.options=t.options});function rE(e,t){return new rv({type:"union",options:e,...re(t)})}var nE=x("ZodDiscriminatedUnion",(e,t)=>{rv.init(e,t),Lb.init(e,t)});function TM(e,t,r){return new nE({type:"union",options:t,discriminator:e,...re(r)})}var iE=x("ZodIntersection",(e,t)=>{Db.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>qf(e,r,n,i)});function sE(e,t){return new iE({type:"intersection",left:e,right:t})}var oE=x("ZodTuple",(e,t)=>{Nb.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>jf(e,r,n,i),e.rest=r=>e.clone({...e._zod.def,rest:r})});function CM(e,t,r){const n=t instanceof Me,i=n?r:t;return new oE({type:"tuple",items:e,rest:n?t:null,...re(i)})}var nv=x("ZodRecord",(e,t)=>{zb.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Hf(e,r,n,i),e.keyType=t.keyType,e.valueType=t.valueType});function Ic(e,t,r){return new nv({type:"record",keyType:e,valueType:t,...re(r)})}function aE(e,t,r){const n=lr(e);return n._zod.values=void 0,new nv({type:"record",keyType:n,valueType:t,...re(r)})}var Tc=x("ZodEnum",(e,t)=>{Ub.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(n,i,s)=>Mf(e,n,i,s),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(n,i)=>{const s={};for(const o of n)if(r.has(o))s[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Tc({...t,checks:[],...re(i),entries:s})},e.exclude=(n,i)=>{const s={...t.entries};for(const o of n)if(r.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new Tc({...t,checks:[],...re(i),entries:s})}});function br(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Tc({type:"enum",entries:r,...re(t)})}var cE=x("ZodLiteral",(e,t)=>{Fb.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Lf(e,r,n,i),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function $M(e,t){return new cE({type:"literal",values:Array.isArray(e)?e:[e],...re(t)})}var lE=x("ZodTransform",(e,t)=>{qb.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Nf(e,r,n,i),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new nf(e.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(Wi(s,r.value,t));else{const o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),r.issues.push(Wi(o))}};const i=t.transform(r.value,r);return i instanceof Promise?i.then(s=>(r.value=s,r)):(r.value=i,r)}});function iv(e){return new lE({type:"transform",transform:e})}var sv=x("ZodOptional",(e,t)=>{Ef.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Hl(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function md(e){return new sv({type:"optional",innerType:e})}var uE=x("ZodExactOptional",(e,t)=>{jb.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Hl(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function dE(e){return new uE({type:"optional",innerType:e})}var hE=x("ZodNullable",(e,t)=>{Hb.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Vf(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function _d(e){return new hE({type:"nullable",innerType:e})}var pE=x("ZodDefault",(e,t)=>{Vb.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Gf(e,r,n,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function fE(e,t){return new pE({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():af(t)}})}var vE=x("ZodPrefault",(e,t)=>{Bb.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Wf(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function gE(e,t){return new vE({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():af(t)}})}var ov=x("ZodNonOptional",(e,t)=>{Gb.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Bf(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function mE(e,t){return new ov({type:"nonoptional",innerType:e,...re(t)})}var _E=x("ZodCatch",(e,t)=>{Wb.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Zf(e,r,n,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function yE(e,t){return new _E({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var bE=x("ZodPipe",(e,t)=>{Zb.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Jf(e,r,n,i),e.in=t.in,e.out=t.out});function Cc(e,t){return new bE({type:"pipe",in:e,out:t})}var wE=x("ZodReadonly",(e,t)=>{Jb.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Kf(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function SE(e){return new wE({type:"readonly",innerType:e})}var EE=x("ZodLazy",(e,t)=>{Kb.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Yf(e,r,n,i),e.unwrap=()=>e._zod.def.getter()});function PM(e){return new EE({type:"lazy",getter:e})}var Bl=x("ZodCustom",(e,t)=>{Yb.init(e,t),Ne.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Df(e,r,n,i)});function OM(e,t){return Gw(Bl,e??(()=>!0),t)}function kE(e,t={}){return Ww(Bl,e,t)}function RE(e){return Zw(e)}function xM(e,t={}){const r=new Bl({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...re(t)});return r._zod.bag.Class=e,r._zod.check=n=>{n.value instanceof e||n.issues.push({code:"invalid_type",expected:e.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}function MM(e,t){return Cc(iv(e),t)}var AE=["oauth-dcr","oauth-cimd","oauth-preregistered","static-header","authless","custom-connection"],IE=["no-user-data","processes-user-data","stores-user-data","shares-with-third-parties"],TE=["ownsOrIsAuthorizedForService","accurateDataHandlingDisclosure","compliesWithUsagePolicies","noProhibitedContent","maintainsSecurityPractices","respondsToSecurityReports","keepsListingAccurate"],ys=ze().url().refine(e=>e.startsWith("https://"),{message:"must be an https:// URL"}),CE=on({url:ze().min(1),mimeType:ze().min(1),widthPx:ao().int().positive(),heightPx:ao().int().positive(),prompt:ze().min(1)}),LM=on({name:ze().min(1).max(pr.nameMaxLength),tagline:ze().min(1).max(pr.taglineMaxLength),description:ze().min(1).max(pr.descriptionMaxLength),categories:Ot(ze().min(1)).min(pr.categoriesMin).max(pr.categoriesMax),slug:ze().min(1).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"must be a lowercase kebab-case slug"),documentationUrl:ys,privacyPolicyUrl:ys,supportUrl:ys,iconUrl:ys,declaredAuthMode:br(AE),dataHandling:Ot(br(IE)).min(1),screenshots:Ot(CE).min(pr.screenshotsMin).max(pr.screenshotsMax),attestations:Ic(br(TE),Yr())}),Us={maxCompressedBytes:104857600,maxUncompressedBytes:536870912,maxEntries:5e3},$E={canonical:".codex-plugin/plugin.json",accepted:[".agent-plugin/plugin.json",".claude-plugin/plugin.json"]},xt={nameMaxLength:100,displayNameMaxLength:100,shortDescriptionMaxLength:255,descriptionMaxLength:2e3,defaultPromptMaxLength:255,toolNameMaxLength:64,skillNameMaxLength:64},av=["productivity","education","developer-tools","design","writing","research","data-analysis","marketing","sales","finance","health","travel","entertainment"],Fs={minEdgePx:48,maxEdgePx:4096,mustBeSquare:!0,maxBytes:5242880,acceptedMimeTypes:["image/png","image/jpeg","image/webp","image/svg+xml"]},PE={lightBackground:"#FFFFFF",darkBackground:"#212121",minRatio:2},Xr={maxSkillMarkdownBytes:262144,maxPageBytes:1048576,maxSkillTotalBytes:5242880,maxImportedTotalBytes:8388608,maxSkills:5,maxPagesPerSkill:10},OE="/.well-known/openai-apps-challenge",xE="text/html;profile=mcp-app",ME="/mcp",LE=["readOnlyHint","destructiveHint","openWorldHint"],$c={successCount:5,failureCount:3},DE={originChangeRequiresNewPlugin:!0,uiContentChangesStayLive:!0,uiContentCacheSeconds:3600},DM={archiveLimits:Us,manifestLocations:$E,fieldLimits:xt,listingCategories:av,imageConstraints:Fs,brandColorContrast:PE,mcpSkillLimits:Xr,domainVerificationPath:OE,appHtmlMime:xE,expectedMcpPath:ME,requiredToolAnnotations:LE,submissionTestCases:$c,releaseRules:DE,source:jt("deploy/submission","Host profile constants")},Z=e=>jt("deploy/submission-errors",e),NE=[{id:"archive-too-large",category:"package-archive",severity:"blocking",message:"The uploaded archive exceeds the maximum compressed size.",limit:{name:"archiveLimits.maxCompressedBytes",value:Us.maxCompressedBytes},source:Z("§Shared package checks → Archive size")},{id:"archive-expands-too-large",category:"package-archive",severity:"blocking",message:"The archive's contents exceed the maximum uncompressed size when expanded.",limit:{name:"archiveLimits.maxUncompressedBytes",value:Us.maxUncompressedBytes},source:Z("§Shared package checks → Archive size")},{id:"archive-too-many-entries",category:"package-archive",severity:"blocking",message:"The archive contains more entries than the maximum allowed.",limit:{name:"archiveLimits.maxEntries",value:Us.maxEntries},source:Z("§Shared package checks → Entry count")},{id:"archive-encrypted-entry",category:"package-archive",severity:"blocking",message:"The archive contains an encrypted entry, which cannot be scanned.",source:Z("§Shared package checks → Archive integrity")},{id:"archive-path-traversal",category:"package-archive",severity:"blocking",message:"An entry path escapes the package root via a `..` segment.",source:Z("§Shared package checks → Entry paths")},{id:"archive-absolute-path",category:"package-archive",severity:"blocking",message:"An entry path is absolute rather than package-relative.",source:Z("§Shared package checks → Entry paths")},{id:"archive-backslash-path",category:"package-archive",severity:"blocking",message:"An entry path uses a backslash separator.",source:Z("§Shared package checks → Entry paths")},{id:"archive-empty-path-segment",category:"package-archive",severity:"blocking",message:"An entry path contains an empty or `.` segment.",source:Z("§Shared package checks → Entry paths")},{id:"archive-path-whitespace",category:"package-archive",severity:"blocking",message:"An entry path has leading or trailing whitespace.",source:Z("§Shared package checks → Entry paths")},{id:"archive-path-control-character",category:"package-archive",severity:"blocking",message:"An entry path contains a control character or NUL byte.",source:Z("§Shared package checks → Entry paths")},{id:"archive-duplicate-path",category:"package-archive",severity:"blocking",message:"Two entries normalize to the same path, including case-insensitive collisions.",source:Z("§Shared package checks → Entry paths")},{id:"archive-symlink-entry",category:"package-archive",severity:"blocking",message:"The archive contains a symlink or hardlink entry.",source:Z("§Shared package checks → Archive integrity")},{id:"manifest-missing",category:"package-manifest",severity:"blocking",message:"The package contains no plugin manifest.",source:Z("§Shared package checks → Manifest")},{id:"manifest-invalid-json",category:"package-manifest",severity:"blocking",message:"The plugin manifest is not valid JSON.",source:Z("§Shared package checks → Manifest")},{id:"manifest-name-missing",category:"package-manifest",severity:"blocking",message:"The manifest declares no plugin name.",source:Z("§Shared package checks → Manifest")},{id:"manifest-name-too-long",category:"package-manifest",severity:"blocking",message:"The manifest's plugin name exceeds the maximum length.",limit:{name:"fieldLimits.nameMaxLength",value:xt.nameMaxLength},source:Z("§Shared package checks → Manifest")},{id:"manifest-version-invalid",category:"package-manifest",severity:"blocking",message:"The manifest's version is not a valid semantic version.",source:Z("§Shared package checks → Manifest")},{id:"interface-display-name-missing",category:"package-manifest",severity:"blocking",message:"The OpenAI interface document declares no display name.",source:Z("§Listing fields → Interface")},{id:"interface-display-name-too-long",category:"package-manifest",severity:"blocking",message:"The interface display name exceeds the maximum length.",limit:{name:"fieldLimits.displayNameMaxLength",value:xt.displayNameMaxLength},source:Z("§Listing fields → Interface")},{id:"interface-short-description-too-long",category:"package-manifest",severity:"blocking",message:"The interface short description exceeds the maximum length.",limit:{name:"fieldLimits.shortDescriptionMaxLength",value:xt.shortDescriptionMaxLength},source:Z("§Listing fields → Interface")},{id:"interface-default-prompt-too-long",category:"package-manifest",severity:"blocking",message:"The interface default prompt exceeds the maximum length.",limit:{name:"fieldLimits.defaultPromptMaxLength",value:xt.defaultPromptMaxLength},source:Z("§Listing fields → Interface")},{id:"interface-brand-color-invalid",category:"package-manifest",severity:"blocking",message:"The brand color is not a six-digit hex value.",source:Z("§Listing fields → Interface")},{id:"interface-brand-color-low-contrast",category:"package-manifest",severity:"blocking",message:"The brand color does not meet the minimum contrast ratio against both the light and dark backgrounds.",source:Z("§Listing fields → Interface")},{id:"interface-yaml-invalid",category:"package-manifest",severity:"blocking",message:"The OpenAI interface document is not valid YAML.",source:Z("§Listing fields → Interface")},{id:"interface-unsupported-text",category:"package-manifest",severity:"blocking",message:"A text field contains control characters or Unicode line/paragraph separators.",source:Z("§Listing fields → Text")},{id:"skill-metadata-missing",category:"package-skills",severity:"blocking",message:"A skill directory contains no SKILL.md.",source:Z("§Skills → Structure")},{id:"skill-frontmatter-invalid",category:"package-skills",severity:"blocking",message:"A skill's SKILL.md frontmatter is missing or malformed.",source:Z("§Skills → Frontmatter")},{id:"skill-name-missing",category:"package-skills",severity:"blocking",message:"A skill's frontmatter declares no name.",source:Z("§Skills → Frontmatter")},{id:"skill-name-too-long",category:"package-skills",severity:"blocking",message:"A skill name exceeds the maximum length.",limit:{name:"fieldLimits.skillNameMaxLength",value:xt.skillNameMaxLength},source:Z("§Skills → Frontmatter")},{id:"skill-description-missing",category:"package-skills",severity:"blocking",message:"A skill's frontmatter declares no description.",source:Z("§Skills → Frontmatter")},{id:"skill-name-collision",category:"package-skills",severity:"blocking",message:"Two skills in the package declare the same name.",source:Z("§Skills → Structure")},{id:"asset-unsupported-type",category:"package-assets",severity:"blocking",message:"An image is not one of the accepted formats.",source:Z("§Images → Format")},{id:"asset-too-large",category:"package-assets",severity:"blocking",message:"An image exceeds the maximum file size.",limit:{name:"imageConstraints.maxBytes",value:Fs.maxBytes},source:Z("§Images → Size")},{id:"asset-too-small",category:"package-assets",severity:"blocking",message:"An image is smaller than the minimum edge length.",limit:{name:"imageConstraints.minEdgePx",value:Fs.minEdgePx},source:Z("§Images → Dimensions")},{id:"asset-too-big-dimensions",category:"package-assets",severity:"blocking",message:"An image exceeds the maximum edge length.",limit:{name:"imageConstraints.maxEdgePx",value:Fs.maxEdgePx},source:Z("§Images → Dimensions")},{id:"asset-not-square",category:"package-assets",severity:"blocking",message:"An image is not square.",source:Z("§Images → Dimensions")},{id:"asset-undecodable",category:"package-assets",severity:"blocking",message:"An image's dimensions could not be read from its bytes.",source:Z("§Images → Format")},{id:"asset-svg-malformed",category:"package-assets",severity:"blocking",message:"An SVG is not well-formed XML or has no `svg` root element.",source:Z("§Images → SVG")},{id:"asset-svg-no-dimensions",category:"package-assets",severity:"blocking",message:"An SVG declares neither a numeric width/height pair nor a numeric viewBox.",source:Z("§Images → SVG")},{id:"asset-missing",category:"package-assets",severity:"blocking",message:"An asset referenced by the manifest is absent from the package.",source:Z("§Images → Format")},{id:"listing-category-unknown",category:"listing-fields",severity:"blocking",message:"The listing names a category outside the supported set.",source:Z("§Listing fields → Categories")},{id:"listing-description-too-long",category:"listing-fields",severity:"blocking",message:"The listing description exceeds the maximum length.",limit:{name:"fieldLimits.descriptionMaxLength",value:xt.descriptionMaxLength},source:Z("§Listing fields → Description")},{id:"listing-promotional-metadata",category:"listing-fields",severity:"blocking",message:"Listing metadata contains promotional language, pricing claims, or ranking claims.",source:Z("§Listing fields → Description")},{id:"listing-privacy-policy-missing",category:"listing-fields",severity:"blocking",message:"The listing declares no privacy policy URL.",source:Z("§Listing fields → Links")},{id:"listing-support-url-missing",category:"listing-fields",severity:"blocking",message:"The listing declares no support URL.",source:Z("§Listing fields → Links")},{id:"mcp-endpoint-not-https",category:"mcp-server",severity:"blocking",message:"The MCP endpoint is not served over HTTPS.",source:Z("§MCP tools → Endpoint")},{id:"mcp-endpoint-unreachable",category:"mcp-server",severity:"blocking",message:"The MCP endpoint could not be reached during the scan.",source:Z("§MCP tools → Endpoint")},{id:"mcp-tool-name-too-long",category:"mcp-server",severity:"blocking",message:"A tool name exceeds the maximum length.",limit:{name:"fieldLimits.toolNameMaxLength",value:xt.toolNameMaxLength},source:Z("§MCP tools → Metadata")},{id:"mcp-tool-description-missing",category:"mcp-server",severity:"blocking",message:"A tool declares no description.",source:Z("§MCP tools → Metadata")},{id:"mcp-tool-annotations-missing",category:"mcp-server",severity:"blocking",message:"A tool is missing one or more of the required annotation hints.",source:Z("§MCP tools → Annotations")},{id:"mcp-tool-schema-invalid",category:"mcp-server",severity:"blocking",message:"A tool's input or output schema is not a valid JSON Schema object.",source:Z("§MCP tools → Schemas")},{id:"mcp-domain-not-verified",category:"mcp-server",severity:"blocking",message:"The MCP server's domain has not completed domain verification.",source:Z("§MCP tools → Domain verification")},{id:"mcp-csp-domain-missing",category:"mcp-server",severity:"blocking",message:"A UI resource loads from a domain absent from the declared content security policy.",source:Z("§MCP tools → Content security policy")},{id:"mcp-ui-domain-missing",category:"mcp-server",severity:"blocking",message:"A UI resource declares no `_meta.ui.domain`.",source:Z("§MCP tools → UI resources")},{id:"mcp-ui-domain-duplicate",category:"mcp-server",severity:"blocking",message:"Two UI resources declare the same `_meta.ui.domain`.",source:Z("§MCP tools → UI resources")},{id:"mcp-ui-mime-invalid",category:"mcp-server",severity:"blocking",message:"A UI resource does not declare the plugin UI MIME profile.",source:Z("§MCP tools → UI resources")},{id:"mcp-skill-too-many",category:"mcp-skills",severity:"blocking",message:"The server advertises more importable skills than the maximum.",limit:{name:"mcpSkillLimits.maxSkills",value:Xr.maxSkills},source:Z("§Skills → Imported from MCP")},{id:"mcp-skill-markdown-too-large",category:"mcp-skills",severity:"blocking",message:"An imported skill's markdown exceeds the maximum size.",limit:{name:"mcpSkillLimits.maxSkillMarkdownBytes",value:Xr.maxSkillMarkdownBytes},source:Z("§Skills → Imported from MCP")},{id:"mcp-skill-page-too-large",category:"mcp-skills",severity:"blocking",message:"An imported skill's supporting page exceeds the maximum size.",limit:{name:"mcpSkillLimits.maxPageBytes",value:Xr.maxPageBytes},source:Z("§Skills → Imported from MCP")},{id:"mcp-skill-too-many-pages",category:"mcp-skills",severity:"blocking",message:"An imported skill has more supporting pages than the maximum.",limit:{name:"mcpSkillLimits.maxPagesPerSkill",value:Xr.maxPagesPerSkill},source:Z("§Skills → Imported from MCP")},{id:"mcp-skill-total-too-large",category:"mcp-skills",severity:"blocking",message:"An imported skill's total footprint exceeds the maximum.",limit:{name:"mcpSkillLimits.maxSkillTotalBytes",value:Xr.maxSkillTotalBytes},source:Z("§Skills → Imported from MCP")},{id:"mcp-skills-total-too-large",category:"mcp-skills",severity:"blocking",message:"The imported skills exceed the maximum combined size.",limit:{name:"mcpSkillLimits.maxImportedTotalBytes",value:Xr.maxImportedTotalBytes},source:Z("§Skills → Imported from MCP")},{id:"mcp-skill-digest-mismatch",category:"mcp-skills",severity:"blocking",message:"An imported skill's declared digest does not match the resource served for it.",source:Z("§Skills → Imported from MCP")},{id:"mcp-skill-frontmatter-mismatch",category:"mcp-skills",severity:"blocking",message:"An imported skill's listing metadata disagrees with its SKILL.md frontmatter.",source:Z("§Skills → Imported from MCP")},{id:"mcp-skill-scan-failed",category:"mcp-skills",severity:"blocking",message:"The skill scan failed, so the draft's imported skills were not updated.",source:Z("§Skills → Imported from MCP")},{id:"review-success-tests-missing",category:"review-materials",severity:"blocking",message:"Fewer successful test cases were supplied than required.",limit:{name:"submissionTestCases.successCount",value:$c.successCount},source:Z("§Review materials → Test cases")},{id:"review-failure-tests-missing",category:"review-materials",severity:"blocking",message:"Fewer graceful-failure test cases were supplied than required.",limit:{name:"submissionTestCases.failureCount",value:$c.failureCount},source:Z("§Review materials → Test cases")},{id:"review-demo-credentials-missing",category:"review-materials",severity:"blocking",message:"The submission authenticates users but supplies no reviewer demo credentials.",source:Z("§Review materials → Demo access")},{id:"review-demo-recording-missing",category:"review-materials",severity:"blocking",message:"No demo recording was supplied.",source:Z("§Review materials → Demo access")},{id:"review-release-notes-missing",category:"review-materials",severity:"blocking",message:"An updated submission supplies no release notes.",source:Z("§Review materials → Release notes")},{id:"review-attestation-missing",category:"review-materials",severity:"blocking",message:"A required policy attestation was not affirmed.",source:Z("§Review materials → Attestations")},{id:"review-identity-not-verified",category:"review-materials",severity:"blocking",message:"The submitting account has not completed identity verification.",source:Z("§Review materials → Account")},{id:"review-write-permission-missing",category:"review-materials",severity:"blocking",message:"The submitting account lacks the app-write permission.",source:Z("§Review materials → Account")},{id:"review-geography-missing",category:"review-materials",severity:"blocking",message:"The submission declares no country availability.",source:Z("§Review materials → Availability")},{id:"review-annotation-justification-missing",category:"review-materials",severity:"advisory",message:"A tool annotated as destructive or open-world carries no justification for review.",source:Z("§Review materials → Test cases")},{id:"review-scan-stale",category:"review-materials",severity:"blocking",message:"The draft's scan predates the current server contract; re-run Scan Tools.",source:Z("§MCP tools → Scan")},{id:"exclusion-mcp-servers-in-skills-only",category:"exclusions",severity:"blocking",message:"A skills-only submission declares MCP servers, which that shape excludes.",source:Z("§Shared package checks → Excluded content")},{id:"exclusion-app-config-in-public-package",category:"exclusions",severity:"blocking",message:"The package contains an `.app.json`, which maps registered connections for local or workspace use and is excluded from a public submission.",source:Z("§Shared package checks → Excluded content")},{id:"exclusion-screenshots-without-ui",category:"exclusions",severity:"blocking",message:"Screenshots were supplied for a submission that renders no UI template.",source:Z("§Images → Screenshots")},{id:"exclusion-bundle-in-mcp-only",category:"exclusions",severity:"blocking",message:"An MCP-only submission supplies a package archive.",source:Z("§Shared package checks → Excluded content")},{id:"exclusion-unsupported-surface",category:"exclusions",severity:"blocking",message:"The package contains a surface the plugin directory does not support.",source:Z("§Shared package checks → Excluded content")}],NM=Object.freeze(Object.fromEntries(NE.map(e=>[e.id,e]))),zE=["ownsOrIsAuthorizedForService","accurateDataDisclosure","compliesWithUsagePolicies","noProhibitedContent","maintainsSecurityPractices","respondsToSecurityReports","keepsListingAccurate"],UE=["none","account-identifiers","user-content","usage-analytics","payment-information","location","health","shared-with-third-parties"],FE=["in-submission-form","shared-out-of-band","not-required-authless"],Ta=ze().url().refine(e=>e.startsWith("https://"),{message:"must be an https:// URL"}),yd=on({prompt:ze().min(1),expectation:ze().min(1)}),qE=on({reference:ze().min(1),mimeType:ze().min(1),widthPx:ao().int().positive(),heightPx:ao().int().positive(),prompt:ze().min(1)}),zM=on({name:ze().min(1).max(xt.nameMaxLength),shortDescription:ze().min(1).max(xt.shortDescriptionMaxLength),description:ze().min(1).max(xt.descriptionMaxLength),categories:Ot(br(av)).min(1),privacyPolicyUrl:Ta,supportUrl:Ta,documentationUrl:Ta.optional(),testCases:on({successful:Ot(yd),gracefulFailure:Ot(yd)}),demoCredentials:on({provided:Yr(),delivery:br(FE)}),demoRecordingProvided:Yr(),screenshots:Ot(qE).default([]),releaseNotes:ze().min(1).optional(),identityVerified:Yr(),accountPermissions:Ot(ze().min(1)).default([]),availableCountries:Ot(ze().length(2)).default([]),dataResidencyEligible:Yr().optional(),privacyPolicyDataTypes:Ot(br(UE)).default([]),annotationJustifications:Ic(ze(),ze().min(1)).default({}),frameDomainExplanations:Ic(ze(),ze().min(1)).default({}),domainVerificationToken:ze().min(1).optional(),lastScanAt:ze().datetime().optional(),hasPublishedVersion:Yr().optional(),attestations:aE(br(zE),Yr())}),UM=new TextDecoder("utf-8",{fatal:!1}),Gl=Symbol.for("yaml.alias"),jE=Symbol.for("yaml.document"),an=Symbol.for("yaml.map"),cv=Symbol.for("yaml.pair"),Wl=Symbol.for("yaml.scalar"),os=Symbol.for("yaml.seq"),Jt=Symbol.for("yaml.node.type"),oi=e=>!!e&&typeof e=="object"&&e[Jt]===Gl,as=e=>!!e&&typeof e=="object"&&e[Jt]===jE,Zl=e=>!!e&&typeof e=="object"&&e[Jt]===an,it=e=>!!e&&typeof e=="object"&&e[Jt]===cv,st=e=>!!e&&typeof e=="object"&&e[Jt]===Wl,Vo=e=>!!e&&typeof e=="object"&&e[Jt]===os;function yt(e){if(e&&typeof e=="object")switch(e[Jt]){case an:case os:return!0}return!1}function nt(e){if(e&&typeof e=="object")switch(e[Jt]){case Gl:case an:case Wl:case os:return!0}return!1}var lv=e=>(st(e)||yt(e))&&!!e.anchor,mt=Symbol("break visit"),uv=Symbol("skip children"),Gt=Symbol("remove node");function cs(e,t){const r=dv(t);as(e)?Cn(null,e.contents,r,Object.freeze([e]))===Gt&&(e.contents=null):Cn(null,e,r,Object.freeze([]))}cs.BREAK=mt;cs.SKIP=uv;cs.REMOVE=Gt;function Cn(e,t,r,n){const i=hv(e,t,r,n);if(nt(i)||it(i))return pv(e,n,i),Cn(e,i,r,n);if(typeof i!="symbol"){if(yt(t)){n=Object.freeze(n.concat(t));for(let s=0;s<t.items.length;++s){const o=Cn(s,t.items[s],r,n);if(typeof o=="number")s=o-1;else{if(o===mt)return mt;o===Gt&&(t.items.splice(s,1),s-=1)}}}else if(it(t)){n=Object.freeze(n.concat(t));const s=Cn("key",t.key,r,n);if(s===mt)return mt;s===Gt&&(t.key=null);const o=Cn("value",t.value,r,n);if(o===mt)return mt;o===Gt&&(t.value=null)}}return i}async function Jl(e,t){const r=dv(t);as(e)?await $n(null,e.contents,r,Object.freeze([e]))===Gt&&(e.contents=null):await $n(null,e,r,Object.freeze([]))}Jl.BREAK=mt;Jl.SKIP=uv;Jl.REMOVE=Gt;async function $n(e,t,r,n){const i=await hv(e,t,r,n);if(nt(i)||it(i))return pv(e,n,i),$n(e,i,r,n);if(typeof i!="symbol"){if(yt(t)){n=Object.freeze(n.concat(t));for(let s=0;s<t.items.length;++s){const o=await $n(s,t.items[s],r,n);if(typeof o=="number")s=o-1;else{if(o===mt)return mt;o===Gt&&(t.items.splice(s,1),s-=1)}}}else if(it(t)){n=Object.freeze(n.concat(t));const s=await $n("key",t.key,r,n);if(s===mt)return mt;s===Gt&&(t.key=null);const o=await $n("value",t.value,r,n);if(o===mt)return mt;o===Gt&&(t.value=null)}}return i}function dv(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function hv(e,t,r,n){if(typeof r=="function")return r(e,t,n);if(Zl(t))return r.Map?.(e,t,n);if(Vo(t))return r.Seq?.(e,t,n);if(it(t))return r.Pair?.(e,t,n);if(st(t))return r.Scalar?.(e,t,n);if(oi(t))return r.Alias?.(e,t,n)}function pv(e,t,r){const n=t[t.length-1];if(yt(n))n.items[e]=r;else if(it(n))e==="key"?n.key=r:n.value=r;else if(as(n))n.contents=r;else{const i=oi(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}var HE={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},VE=e=>e.replace(/[!,[\]{}]/g,t=>HE[t]),fv=class Qt{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Qt.defaultYaml,t),this.tags=Object.assign({},Qt.defaultTags,r)}clone(){const t=new Qt(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){const t=new Qt(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Qt.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Qt.defaultTags)}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:Qt.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Qt.defaultTags),this.atNextDocument=!1);const n=t.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[s,o]=n;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;const[s]=n;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{const o=/^\d+\.\d+$/.test(s);return r(6,`Unsupported YAML version ${s}`,o),!1}}default:return r(0,`Unknown directive ${i}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){const o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}const[,n,i]=t.match(/^(.*!)([^!]*)$/s);i||r(`The ${t} tag has no suffix`);const s=this.tags[n];if(s)try{return s+decodeURIComponent(i)}catch(o){return r(String(o)),null}return n==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(const[r,n]of Object.entries(this.tags))if(t.startsWith(n))return r+VE(t.substring(n.length));return t[0]==="!"?t:`!<${t}>`}toString(t){const r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let i;if(t&&n.length>0&&nt(t.contents)){const s={};cs(t.contents,(o,a)=>{nt(a)&&a.tag&&(s[a.tag]=!0)}),i=Object.keys(s)}else i=[];for(const[s,o]of n)s==="!!"&&o==="tag:yaml.org,2002:"||(!t||i.some(a=>a.startsWith(o)))&&r.push(`%TAG ${s} ${o}`);return r.join(`
40
+ `)}};fv.defaultYaml={explicit:!1,version:"1.2"};fv.defaultTags={"!!":"tag:yaml.org,2002:"};function vv(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){const t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(t)}return!0}function Ii(e,t,r,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,s=n.length;i<s;++i){const o=n[i],a=Ii(e,n,String(i),o);a===void 0?delete n[i]:a!==o&&(n[i]=a)}else if(n instanceof Map)for(const i of Array.from(n.keys())){const s=n.get(i),o=Ii(e,n,i,s);o===void 0?n.delete(i):o!==s&&n.set(i,o)}else if(n instanceof Set)for(const i of Array.from(n)){const s=Ii(e,n,i,i);s===void 0?n.delete(i):s!==i&&(n.delete(i),n.add(s))}else for(const[i,s]of Object.entries(n)){const o=Ii(e,n,i,s);o===void 0?delete n[i]:o!==s&&(n[i]=o)}return e.call(t,r,n)}function zt(e,t,r){if(Array.isArray(e))return e.map((n,i)=>zt(n,String(i),r));if(e&&typeof e.toJSON=="function"){if(!r||!lv(e))return e.toJSON(t,r);const n={aliasCount:0,count:1,res:void 0};r.anchors.set(e,n),r.onCreate=s=>{n.res=s,delete r.onCreate};const i=e.toJSON(t,r);return r.onCreate&&r.onCreate(i),i}return typeof e=="bigint"&&!r?.keep?Number(e):e}var Kl=class{constructor(e){Object.defineProperty(this,Jt,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:r,onAnchor:n,reviver:i}={}){if(!as(e))throw new TypeError("A document argument is required");const s={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},o=zt(this,"",s);if(typeof n=="function")for(const{count:a,res:c}of s.anchors.values())n(c,a);return typeof i=="function"?Ii(i,{"":o},"",o):o}},BE=class extends Kl{constructor(e){super(Gl),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if(t?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;t?.aliasResolveCache?r=t.aliasResolveCache:(r=[],cs(e,{Node:(i,s)=>{(oi(s)||lv(s))&&r.push(s)}}),t&&(t.aliasResolveCache=r));let n;for(const i of r){if(i===this)break;i.anchor===this.source&&(n=i)}if(n&&t){const{anchors:i,doc:s,maxAliasCount:o}=t;let a=i.get(n);if(a||(zt(n,null,t),a=i.get(n)),a?.res===void 0)throw new ReferenceError("This should not happen: Alias anchor was not resolved?");if(o>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=qs(s,n,i)),a.count*a.aliasCount>o))throw new ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return n}toJSON(e,t){if(!t)return{source:this.source};const r=this.resolve(t.doc,t);if(!r){const n=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(n)}return t.anchors.get(r).res}toString(e,t,r){const n=`*${this.source}`;if(e){if(vv(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${n} `}return n}};function qs(e,t,r){if(oi(t)){const n=t.resolve(e),i=r&&n&&r.get(n);return i?i.count*i.aliasCount:0}else if(yt(t)){let n=0;for(const i of t.items){const s=qs(e,i,r);s>n&&(n=s)}return n}else if(it(t)){const n=qs(e,t.key,r),i=qs(e,t.value,r);return Math.max(n,i)}return 1}var gv=e=>!e||typeof e!="function"&&typeof e!="object",Ke=class extends Kl{constructor(e){super(Wl),this.value=e}toJSON(e,t){return t?.keep?this.value:zt(this.value,e,t)}toString(){return String(this.value)}};Ke.BLOCK_FOLDED="BLOCK_FOLDED";Ke.BLOCK_LITERAL="BLOCK_LITERAL";Ke.PLAIN="PLAIN";Ke.QUOTE_DOUBLE="QUOTE_DOUBLE";Ke.QUOTE_SINGLE="QUOTE_SINGLE";var GE="tag:yaml.org,2002:";function WE(e,t,r){if(t){const n=r.filter(s=>s.tag===t),i=n.find(s=>!s.format)??n[0];if(!i)throw new Error(`Tag ${t} not found`);return i}return r.find(n=>n.identify?.(e)&&!n.format)}function co(e,t,r){if(as(e)&&(e=e.contents),nt(e))return e;if(it(e)){const h=r.schema[an].createNode?.(r.schema,null,r);return h.items.push(e),h}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());const{aliasDuplicateObjects:n,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=r;let c;if(n&&e&&typeof e=="object"){if(c=a.get(e),c)return c.anchor??(c.anchor=i(e)),new BE(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t=GE+t.slice(2));let l=WE(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){const h=new Ke(e);return c&&(c.node=h),h}l=e instanceof Map?o[an]:Symbol.iterator in Object(e)?o[os]:o[an]}s&&(s(l),delete r.onTagObj);const u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new Ke(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function bd(e,t,r){let n=r;for(let i=t.length-1;i>=0;--i){const s=t[i];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){const o=[];o[s]=n,n=o}else n=new Map([[s,n]])}return co(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var ZE=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,mv=class extends Kl{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(r=>nt(r)||it(r)?r.clone(e):r),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(ZE(e))this.add(t);else{const[r,...n]=e,i=this.get(r,!0);if(yt(i))i.addIn(n,t);else if(i===void 0&&this.schema)this.set(r,bd(this.schema,n,t));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(e){const[t,...r]=e;if(r.length===0)return this.delete(t);const n=this.get(t,!0);if(yt(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){const[r,...n]=e,i=this.get(r,!0);return n.length===0?!t&&st(i)?i.value:i:yt(i)?i.getIn(n,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!it(t))return!1;const r=t.value;return r==null||e&&st(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){const[t,...r]=e;if(r.length===0)return this.has(t);const n=this.get(t,!0);return yt(n)?n.hasIn(r):!1}setIn(e,t){const[r,...n]=e;if(n.length===0)this.set(r,t);else{const i=this.get(r,!0);if(yt(i))i.setIn(n,t);else if(i===void 0&&this.schema)this.set(r,bd(this.schema,n,t));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}},JE=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Zi(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Pn=(e,t,r)=>e.endsWith(`
41
+ `)?Zi(r,t):r.includes(`
48
42
  `)?`
49
- `+ss(r,t):(e.endsWith(" ")?"":" ")+r,Qm="flow",r$="block",n$="quoted";function ia(e,t,r="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return e;i<s&&(s=0);const c=Math.max(1+s,1+i-t.length);if(e.length<=c)return e;const l=[],u={};let h=i-t.length;typeof n=="number"&&(n>i-Math.max(2,s)?l.push(0):h=i-n);let d,p,f=!1,v=-1,m=-1,_=-1;r==="block"&&(v=fp(e,v,t.length),v!==-1&&(h=v+c));for(let S;S=e[v+=1];){if(r==="quoted"&&S==="\\"){switch(m=v,e[v+1]){case"x":v+=3;break;case"u":v+=5;break;case"U":v+=9;break;default:v+=1}_=v}if(S===`
50
- `)r==="block"&&(v=fp(e,v,t.length)),h=v+t.length+c,d=void 0;else{if(S===" "&&p&&p!==" "&&p!==`
43
+ `+Zi(r,t):(e.endsWith(" ")?"":" ")+r,_v="flow",KE="block",YE="quoted";function Bo(e,t,r="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return e;i<s&&(s=0);const c=Math.max(1+s,1+i-t.length);if(e.length<=c)return e;const l=[],u={};let h=i-t.length;typeof n=="number"&&(n>i-Math.max(2,s)?l.push(0):h=i-n);let d,p,f=!1,v=-1,m=-1,_=-1;r==="block"&&(v=wd(e,v,t.length),v!==-1&&(h=v+c));for(let S;S=e[v+=1];){if(r==="quoted"&&S==="\\"){switch(m=v,e[v+1]){case"x":v+=3;break;case"u":v+=5;break;case"U":v+=9;break;default:v+=1}_=v}if(S===`
44
+ `)r==="block"&&(v=wd(e,v,t.length)),h=v+t.length+c,d=void 0;else{if(S===" "&&p&&p!==" "&&p!==`
51
45
  `&&p!==" "){const T=e[v+1];T&&T!==" "&&T!==`
52
- `&&T!==" "&&(d=v)}if(v>=h)if(d)l.push(d),h=d+c,d=void 0;else if(r==="quoted"){for(;p===" "||p===" ";)p=S,S=e[v+=1],f=!0;const T=v>_+1?v-2:m-1;if(u[T])return e;l.push(T),u[T]=!0,h=T+c,d=void 0}else f=!0}p=S}if(f&&a&&a(),l.length===0)return e;o&&o();let w=e.slice(0,l[0]);for(let S=0;S<l.length;++S){const T=l[S],I=l[S+1]||e.length;T===0?w=`
53
- ${t}${e.slice(0,I)}`:(r==="quoted"&&u[T]&&(w+=`${e[T]}\\`),w+=`
54
- ${t}${e.slice(T+1,I)}`)}return w}function fp(e,t,r){let n=t,i=t+1,s=e[i];for(;s===" "||s===" ";)if(t<i+r)s=e[++t];else{do s=e[++t];while(s&&s!==`
55
- `);n=t,i=t+1,s=e[i]}return n}var sa=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),oa=e=>/^(%|---|\.\.\.)/m.test(e);function i$(e,t,r){if(!t||t<0)return!1;const n=t-r,i=e.length;if(i<=n)return!1;for(let s=0,o=0;s<i;++s)if(e[s]===`
56
- `){if(s-o>n)return!0;if(o=s+1,i-o<=n)return!1}return!0}function Gi(e,t){const r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;const{implicitKey:n}=t,i=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(oa(e)?" ":"");let o="",a=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(a,c);const u=r.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=r.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||r[c+2]==='"'||r.length<i)c+=1;else{for(o+=r.slice(a,c)+`
46
+ `&&T!==" "&&(d=v)}if(v>=h)if(d)l.push(d),h=d+c,d=void 0;else if(r==="quoted"){for(;p===" "||p===" ";)p=S,S=e[v+=1],f=!0;const T=v>_+1?v-2:m-1;if(u[T])return e;l.push(T),u[T]=!0,h=T+c,d=void 0}else f=!0}p=S}if(f&&a&&a(),l.length===0)return e;o&&o();let w=e.slice(0,l[0]);for(let S=0;S<l.length;++S){const T=l[S],C=l[S+1]||e.length;T===0?w=`
47
+ ${t}${e.slice(0,C)}`:(r==="quoted"&&u[T]&&(w+=`${e[T]}\\`),w+=`
48
+ ${t}${e.slice(T+1,C)}`)}return w}function wd(e,t,r){let n=t,i=t+1,s=e[i];for(;s===" "||s===" ";)if(t<i+r)s=e[++t];else{do s=e[++t];while(s&&s!==`
49
+ `);n=t,i=t+1,s=e[i]}return n}var Go=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Wo=e=>/^(%|---|\.\.\.)/m.test(e);function XE(e,t,r){if(!t||t<0)return!1;const n=t-r,i=e.length;if(i<=n)return!1;for(let s=0,o=0;s<i;++s)if(e[s]===`
50
+ `){if(s-o>n)return!0;if(o=s+1,i-o<=n)return!1}return!0}function $i(e,t){const r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;const{implicitKey:n}=t,i=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(Wo(e)?" ":"");let o="",a=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(a,c);const u=r.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=r.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||r[c+2]==='"'||r.length<i)c+=1;else{for(o+=r.slice(a,c)+`
57
51
 
58
52
  `;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
59
- `,c+=2;o+=s,r[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+r.slice(a):r,n?o:ia(o,s,n$,sa(t,!1))}function _l(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
60
- `)||/[ \t]\n|\n[ \t]/.test(e))return Gi(e,t);const r=t.indent||(oa(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
61
- ${r}`)+"'";return t.implicitKey?n:ia(n,r,Qm,sa(t,!1))}function Nn(e,t){const{singleQuote:r}=t.options;let n;if(r===!1)n=Gi;else{const i=e.includes('"'),s=e.includes("'");i&&!s?n=_l:s&&!i?n=Gi:n=r?_l:Gi}return n(e,t)}var yl;try{yl=new RegExp(`(^|(?<!
53
+ `,c+=2;o+=s,r[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+r.slice(a):r,n?o:Bo(o,s,YE,Go(t,!1))}function Pc(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
54
+ `)||/[ \t]\n|\n[ \t]/.test(e))return $i(e,t);const r=t.indent||(Wo(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
55
+ ${r}`)+"'";return t.implicitKey?n:Bo(n,r,_v,Go(t,!1))}function On(e,t){const{singleQuote:r}=t.options;let n;if(r===!1)n=$i;else{const i=e.includes('"'),s=e.includes("'");i&&!s?n=Pc:s&&!i?n=$i:n=r?Pc:$i}return n(e,t)}var Oc;try{Oc=new RegExp(`(^|(?<!
62
56
  ))
63
57
  +(?!
64
- |$)`,"g")}catch{yl=/\n+(?!\n|$)/g}function Qs({comment:e,type:t,value:r},n,i,s){const{blockQuote:o,commentString:a,lineWidth:c}=n.options;if(!o||/\n[\t ]+$/.test(r))return Nn(r,n);const l=n.indent||(n.forceBlockIndent||oa(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===Ke.BLOCK_FOLDED?!1:t===Ke.BLOCK_LITERAL?!0:!i$(r,c,l.length);if(!r)return u?`|
58
+ |$)`,"g")}catch{Oc=/\n+(?!\n|$)/g}function js({comment:e,type:t,value:r},n,i,s){const{blockQuote:o,commentString:a,lineWidth:c}=n.options;if(!o||/\n[\t ]+$/.test(r))return On(r,n);const l=n.indent||(n.forceBlockIndent||Wo(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===Ke.BLOCK_FOLDED?!1:t===Ke.BLOCK_LITERAL?!0:!XE(r,c,l.length);if(!r)return u?`|
65
59
  `:`>
66
60
  `;let h,d;for(d=r.length;d>0;--d){const T=r[d-1];if(T!==`
67
61
  `&&T!==" "&&T!==" ")break}let p=r.substring(d);const f=p.indexOf(`
68
62
  `);f===-1?h="-":r===p||f!==p.length-1?(h="+",s&&s()):h="",p&&(r=r.slice(0,-p.length),p[p.length-1]===`
69
- `&&(p=p.slice(0,-1)),p=p.replace(yl,`$&${l}`));let v=!1,m,_=-1;for(m=0;m<r.length;++m){const T=r[m];if(T===" ")v=!0;else if(T===`
63
+ `&&(p=p.slice(0,-1)),p=p.replace(Oc,`$&${l}`));let v=!1,m,_=-1;for(m=0;m<r.length;++m){const T=r[m];if(T===" ")v=!0;else if(T===`
70
64
  `)_=m;else break}let w=r.substring(0,_<m?_+1:m);w&&(r=r.substring(w.length),w=w.replace(/\n+/g,`$&${l}`));let S=(v?l?"2":"1":"")+h;if(e&&(S+=" "+a(e.replace(/ ?[\r\n]+/g," ")),i&&i()),!u){const T=r.replace(/\n+/g,`
71
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`);let I=!1;const C=sa(n,!0);o!=="folded"&&t!==Ke.BLOCK_FOLDED&&(C.onOverflow=()=>{I=!0});const M=ia(`${w}${T}${p}`,l,r$,C);if(!I)return`>${S}
65
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`);let C=!1;const $=Go(n,!0);o!=="folded"&&t!==Ke.BLOCK_FOLDED&&($.onOverflow=()=>{C=!0});const M=Bo(`${w}${T}${p}`,l,KE,$);if(!C)return`>${S}
72
66
  ${l}${M}`}return r=r.replace(/\n+/g,`$&${l}`),`|${S}
73
- ${l}${w}${r}${p}`}function s$(e,t,r,n){const{type:i,value:s}=e,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=t;if(a&&s.includes(`
74
- `)||u&&/[[\]{},]/.test(s))return Nn(s,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes(`
75
- `)?Nn(s,t):Qs(e,t,r,n);if(!a&&!u&&i!==Ke.PLAIN&&s.includes(`
76
- `))return Qs(e,t,r,n);if(oa(s)){if(c==="")return t.forceBlockIndent=!0,Qs(e,t,r,n);if(a&&c===l)return Nn(s,t)}const h=s.replace(/\n+/g,`$&
77
- ${c}`);if(o){const d=v=>v.default&&v.tag!=="tag:yaml.org,2002:str"&&v.test?.test(h),{compat:p,tags:f}=t.doc.schema;if(f.some(d)||p?.some(d))return Nn(s,t)}return a?h:ia(h,c,Qm,sa(t,!1))}function o$(e,t,r,n){const{implicitKey:i,inFlow:s}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)});let{type:a}=e;a!==Ke.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Ke.QUOTE_DOUBLE);const c=u=>{switch(u){case Ke.BLOCK_FOLDED:case Ke.BLOCK_LITERAL:return i||s?Nn(o.value,t):Qs(o,t,r,n);case Ke.QUOTE_DOUBLE:return Gi(o.value,t);case Ke.QUOTE_SINGLE:return _l(o.value,t);case Ke.PLAIN:return s$(o,t,r,n);default:return null}};let l=c(a);if(l===null){const{defaultKeyType:u,defaultStringType:h}=t.options,d=i&&u||h;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}function a$(e,t){const r=Object.assign({blockQuote:!0,commentString:t$,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t);let n;switch(r.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:n,options:r}}function c$(e,t){if(t.tag){const i=e.filter(s=>s.tag===t.tag);if(i.length>0)return i.find(s=>s.format===t.format)??i[0]}let r,n;if(ot(t)){n=t.value;let i=e.filter(s=>s.identify?.(n));if(i.length>1){const s=i.filter(o=>o.test);s.length>0&&(i=s)}r=i.find(s=>s.format===t.format)??i.find(s=>!s.format)}else n=t,r=e.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!r){const i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return r}function l$(e,t,{anchors:r,doc:n}){if(!n.directives)return"";const i=[],s=(ot(e)||bt(e))&&e.anchor;s&&Km(s)&&(r.add(s),i.push(`&${s}`));const o=e.tag??(t.default?null:t.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}function No(e,t,r,n){if(st(e))return e.toString(t,r,n);if(ui(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i;const s=it(e)?e:t.doc.createNode(e,{onTagObj:c=>i=c});i??(i=c$(t.doc.schema.tags,s));const o=l$(s,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);const a=typeof i.stringify=="function"?i.stringify(s,t,r,n):ot(s)?o$(s,t,r,n):s.toString(t,r,n);return o?ot(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
78
- ${t.indent}${a}`:a}function u$({key:e,value:t},r,n,i){const{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:h}}=r;let d=it(e)&&e.comment||null;if(h){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(bt(e)||!it(e)&&typeof e=="object")throw new Error("With simple keys, collection cannot be used as a key value")}let p=!h&&(!e||d&&t==null&&!r.inFlow||bt(e)||(ot(e)?e.type===Ke.BLOCK_FOLDED||e.type===Ke.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(h||!s),indent:a+c});let f=!1,v=!1,m=No(e,r,()=>f=!0,()=>v=!0);if(!p&&!r.inFlow&&m.length>1024){if(h)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(r.inFlow){if(s||t==null)return f&&n&&n(),m===""?"?":p?`? ${m}`:m}else if(s&&!h||t==null&&p)return m=`? ${m}`,d&&!f?m+=Dn(m,r.indent,l(d)):v&&i&&i(),m;f&&(d=null),p?(d&&(m+=Dn(m,r.indent,l(d))),m=`? ${m}
79
- ${a}:`):(m=`${m}:`,d&&(m+=Dn(m,r.indent,l(d))));let _,w,S;it(t)?(_=!!t.spaceBefore,w=t.commentBefore,S=t.comment):(_=!1,w=null,S=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!p&&!d&&ot(t)&&(r.indentAtStart=m.length+1),v=!1,!u&&c.length>=2&&!r.inFlow&&!p&&na(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let T=!1;const I=No(t,r,()=>T=!0,()=>v=!0);let C=" ";if(d||_||w){if(C=_?`
80
- `:"",w){const M=l(w);C+=`
81
- ${ss(M,r.indent)}`}I===""&&!r.inFlow?C===`
82
- `&&S&&(C=`
67
+ ${l}${w}${r}${p}`}function QE(e,t,r,n){const{type:i,value:s}=e,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=t;if(a&&s.includes(`
68
+ `)||u&&/[[\]{},]/.test(s))return On(s,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes(`
69
+ `)?On(s,t):js(e,t,r,n);if(!a&&!u&&i!==Ke.PLAIN&&s.includes(`
70
+ `))return js(e,t,r,n);if(Wo(s)){if(c==="")return t.forceBlockIndent=!0,js(e,t,r,n);if(a&&c===l)return On(s,t)}const h=s.replace(/\n+/g,`$&
71
+ ${c}`);if(o){const d=v=>v.default&&v.tag!=="tag:yaml.org,2002:str"&&v.test?.test(h),{compat:p,tags:f}=t.doc.schema;if(f.some(d)||p?.some(d))return On(s,t)}return a?h:Bo(h,c,_v,Go(t,!1))}function ek(e,t,r,n){const{implicitKey:i,inFlow:s}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)});let{type:a}=e;a!==Ke.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Ke.QUOTE_DOUBLE);const c=u=>{switch(u){case Ke.BLOCK_FOLDED:case Ke.BLOCK_LITERAL:return i||s?On(o.value,t):js(o,t,r,n);case Ke.QUOTE_DOUBLE:return $i(o.value,t);case Ke.QUOTE_SINGLE:return Pc(o.value,t);case Ke.PLAIN:return QE(o,t,r,n);default:return null}};let l=c(a);if(l===null){const{defaultKeyType:u,defaultStringType:h}=t.options,d=i&&u||h;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}function tk(e,t){const r=Object.assign({blockQuote:!0,commentString:JE,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t);let n;switch(r.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:n,options:r}}function rk(e,t){if(t.tag){const i=e.filter(s=>s.tag===t.tag);if(i.length>0)return i.find(s=>s.format===t.format)??i[0]}let r,n;if(st(t)){n=t.value;let i=e.filter(s=>s.identify?.(n));if(i.length>1){const s=i.filter(o=>o.test);s.length>0&&(i=s)}r=i.find(s=>s.format===t.format)??i.find(s=>!s.format)}else n=t,r=e.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!r){const i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return r}function nk(e,t,{anchors:r,doc:n}){if(!n.directives)return"";const i=[],s=(st(e)||yt(e))&&e.anchor;s&&vv(s)&&(r.add(s),i.push(`&${s}`));const o=e.tag??(t.default?null:t.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}function lo(e,t,r,n){if(it(e))return e.toString(t,r,n);if(oi(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i;const s=nt(e)?e:t.doc.createNode(e,{onTagObj:c=>i=c});i??(i=rk(t.doc.schema.tags,s));const o=nk(s,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);const a=typeof i.stringify=="function"?i.stringify(s,t,r,n):st(s)?ek(s,t,r,n):s.toString(t,r,n);return o?st(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
72
+ ${t.indent}${a}`:a}function ik({key:e,value:t},r,n,i){const{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:h}}=r;let d=nt(e)&&e.comment||null;if(h){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(yt(e)||!nt(e)&&typeof e=="object")throw new Error("With simple keys, collection cannot be used as a key value")}let p=!h&&(!e||d&&t==null&&!r.inFlow||yt(e)||(st(e)?e.type===Ke.BLOCK_FOLDED||e.type===Ke.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(h||!s),indent:a+c});let f=!1,v=!1,m=lo(e,r,()=>f=!0,()=>v=!0);if(!p&&!r.inFlow&&m.length>1024){if(h)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(r.inFlow){if(s||t==null)return f&&n&&n(),m===""?"?":p?`? ${m}`:m}else if(s&&!h||t==null&&p)return m=`? ${m}`,d&&!f?m+=Pn(m,r.indent,l(d)):v&&i&&i(),m;f&&(d=null),p?(d&&(m+=Pn(m,r.indent,l(d))),m=`? ${m}
73
+ ${a}:`):(m=`${m}:`,d&&(m+=Pn(m,r.indent,l(d))));let _,w,S;nt(t)?(_=!!t.spaceBefore,w=t.commentBefore,S=t.comment):(_=!1,w=null,S=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!p&&!d&&st(t)&&(r.indentAtStart=m.length+1),v=!1,!u&&c.length>=2&&!r.inFlow&&!p&&Vo(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let T=!1;const C=lo(t,r,()=>T=!0,()=>v=!0);let $=" ";if(d||_||w){if($=_?`
74
+ `:"",w){const M=l(w);$+=`
75
+ ${Zi(M,r.indent)}`}C===""&&!r.inFlow?$===`
76
+ `&&S&&($=`
83
77
 
84
- `):C+=`
85
- ${r.indent}`}else if(!p&&bt(t)){const M=I[0],L=I.indexOf(`
86
- `),q=L!==-1,X=r.inFlow??t.flow??t.items.length===0;if(q||!X){let ee=!1;if(q&&(M==="&"||M==="!")){let k=I.indexOf(" ");M==="&"&&k!==-1&&k<L&&I[k+1]==="!"&&(k=I.indexOf(" ",k+1)),(k===-1||L<k)&&(ee=!0)}ee||(C=`
87
- ${r.indent}`)}}else(I===""||I[0]===`
88
- `)&&(C="");return m+=C+I,r.inFlow?T&&n&&n():S&&!T?m+=Dn(m,r.indent,l(S)):v&&i&&i(),m}function d$(e,t){(e==="debug"||e==="warn")&&console.warn(t)}var Ls="<<",yc={identify:e=>e===Ls||typeof e=="symbol"&&e.description===Ls,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Ke(Symbol(Ls)),{addToJSMap:e_}),stringify:()=>Ls},h$=(e,t)=>(yc.identify(t)||ot(t)&&(!t.type||t.type===Ke.PLAIN)&&yc.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===yc.tag&&r.default);function e_(e,t,r){const n=t_(e,r);if(na(n))for(const i of n.items)bc(e,t,i);else if(Array.isArray(n))for(const i of n)bc(e,t,i);else bc(e,t,n)}function bc(e,t,r){const n=t_(e,r);if(!Ru(n))throw new Error("Merge sources must be maps or map aliases");const i=n.toJSON(null,e,Map);for(const[s,o]of i)t instanceof Map?t.has(s)||t.set(s,o):t instanceof Set?t.add(s):Object.prototype.hasOwnProperty.call(t,s)||Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function t_(e,t){return e&&ui(t)?t.resolve(e.doc,e):t}function r_(e,t,{key:r,value:n}){if(it(r)&&r.addToJSMap)r.addToJSMap(e,t,n);else if(h$(e,r))e_(e,t,n);else{const i=Ft(r,"",e);if(t instanceof Map)t.set(i,Ft(n,i,e));else if(t instanceof Set)t.add(i);else{const s=p$(r,i,e),o=Ft(n,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}function p$(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(it(e)&&r?.doc){const n=a$(r.doc,{});n.anchors=new Set;for(const s of r.anchors.keys())n.anchors.add(s.anchor);n.inFlow=!0,n.inStringifyKey=!0;const i=e.toString(n);if(!r.mapKeyWarned){let s=JSON.stringify(i);s.length>40&&(s=s.substring(0,36)+'..."'),d$(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return i}return JSON.stringify(t)}function Tu(e,t,r){const n=Do(e,void 0,r),i=Do(t,void 0,r);return new fn(n,i)}var fn=class n_{constructor(t,r=null){Object.defineProperty(this,Yt,{value:Hm}),this.key=t,this.value=r}clone(t){let{key:r,value:n}=this;return it(r)&&(r=r.clone(t)),it(n)&&(n=n.clone(t)),new n_(r,n)}toJSON(t,r){const n=r?.mapAsMap?new Map:{};return r_(r,n,this)}toString(t,r,n){return t?.doc?u$(this,t,r,n):JSON.stringify(this)}};function i_(e,t,r){return(t.inFlow??e.flow?v$:f$)(e,t,r)}function f$({comment:e,items:t},r,{blockItemPrefix:n,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){const{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:s,type:null});let h=!1;const d=[];for(let f=0;f<t.length;++f){const v=t[f];let m=null;if(it(v))!h&&v.spaceBefore&&d.push(""),zo(r,d,v.commentBefore,h),v.comment&&(m=v.comment);else if(st(v)){const w=it(v.key)?v.key:null;w&&(!h&&w.spaceBefore&&d.push(""),zo(r,d,w.commentBefore,h))}h=!1;let _=No(v,u,()=>m=null,()=>h=!0);m&&(_+=Dn(_,s,l(m))),h&&m&&(h=!1),d.push(n+_)}let p;if(d.length===0)p=i.start+i.end;else{p=d[0];for(let f=1;f<d.length;++f){const v=d[f];p+=v?`
78
+ `):$+=`
79
+ ${r.indent}`}else if(!p&&yt(t)){const M=C[0],L=C.indexOf(`
80
+ `),q=L!==-1,X=r.inFlow??t.flow??t.items.length===0;if(q||!X){let ee=!1;if(q&&(M==="&"||M==="!")){let k=C.indexOf(" ");M==="&"&&k!==-1&&k<L&&C[k+1]==="!"&&(k=C.indexOf(" ",k+1)),(k===-1||L<k)&&(ee=!0)}ee||($=`
81
+ ${r.indent}`)}}else(C===""||C[0]===`
82
+ `)&&($="");return m+=$+C,r.inFlow?T&&n&&n():S&&!T?m+=Pn(m,r.indent,l(S)):v&&i&&i(),m}function sk(e,t){(e==="debug"||e==="warn")&&console.warn(t)}var bs="<<",Ca={identify:e=>e===bs||typeof e=="symbol"&&e.description===bs,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Ke(Symbol(bs)),{addToJSMap:yv}),stringify:()=>bs},ok=(e,t)=>(Ca.identify(t)||st(t)&&(!t.type||t.type===Ke.PLAIN)&&Ca.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===Ca.tag&&r.default);function yv(e,t,r){const n=bv(e,r);if(Vo(n))for(const i of n.items)$a(e,t,i);else if(Array.isArray(n))for(const i of n)$a(e,t,i);else $a(e,t,n)}function $a(e,t,r){const n=bv(e,r);if(!Zl(n))throw new Error("Merge sources must be maps or map aliases");const i=n.toJSON(null,e,Map);for(const[s,o]of i)t instanceof Map?t.has(s)||t.set(s,o):t instanceof Set?t.add(s):Object.prototype.hasOwnProperty.call(t,s)||Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function bv(e,t){return e&&oi(t)?t.resolve(e.doc,e):t}function wv(e,t,{key:r,value:n}){if(nt(r)&&r.addToJSMap)r.addToJSMap(e,t,n);else if(ok(e,r))yv(e,t,n);else{const i=zt(r,"",e);if(t instanceof Map)t.set(i,zt(n,i,e));else if(t instanceof Set)t.add(i);else{const s=ak(r,i,e),o=zt(n,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}function ak(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(nt(e)&&r?.doc){const n=tk(r.doc,{});n.anchors=new Set;for(const s of r.anchors.keys())n.anchors.add(s.anchor);n.inFlow=!0,n.inStringifyKey=!0;const i=e.toString(n);if(!r.mapKeyWarned){let s=JSON.stringify(i);s.length>40&&(s=s.substring(0,36)+'..."'),sk(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return i}return JSON.stringify(t)}function Yl(e,t,r){const n=co(e,void 0,r),i=co(t,void 0,r);return new cn(n,i)}var cn=class Sv{constructor(t,r=null){Object.defineProperty(this,Jt,{value:cv}),this.key=t,this.value=r}clone(t){let{key:r,value:n}=this;return nt(r)&&(r=r.clone(t)),nt(n)&&(n=n.clone(t)),new Sv(r,n)}toJSON(t,r){const n=r?.mapAsMap?new Map:{};return wv(r,n,this)}toString(t,r,n){return t?.doc?ik(this,t,r,n):JSON.stringify(this)}};function Ev(e,t,r){return(t.inFlow??e.flow?lk:ck)(e,t,r)}function ck({comment:e,items:t},r,{blockItemPrefix:n,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){const{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:s,type:null});let h=!1;const d=[];for(let f=0;f<t.length;++f){const v=t[f];let m=null;if(nt(v))!h&&v.spaceBefore&&d.push(""),uo(r,d,v.commentBefore,h),v.comment&&(m=v.comment);else if(it(v)){const w=nt(v.key)?v.key:null;w&&(!h&&w.spaceBefore&&d.push(""),uo(r,d,w.commentBefore,h))}h=!1;let _=lo(v,u,()=>m=null,()=>h=!0);m&&(_+=Pn(_,s,l(m))),h&&m&&(h=!1),d.push(n+_)}let p;if(d.length===0)p=i.start+i.end;else{p=d[0];for(let f=1;f<d.length;++f){const v=d[f];p+=v?`
89
83
  ${c}${v}`:`
90
84
  `}}return e?(p+=`
91
- `+ss(l(e),c),a&&a()):h&&o&&o(),p}function v$({items:e},t,{flowChars:r,itemIndent:n}){const{indent:i,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=t;n+=s;const c=Object.assign({},t,{indent:n,inFlow:!0,type:null});let l=!1,u=0;const h=[];for(let f=0;f<e.length;++f){const v=e[f];let m=null;if(it(v))v.spaceBefore&&h.push(""),zo(t,h,v.commentBefore,!1),v.comment&&(m=v.comment);else if(st(v)){const w=it(v.key)?v.key:null;w&&(w.spaceBefore&&h.push(""),zo(t,h,w.commentBefore,!1),w.comment&&(l=!0));const S=it(v.value)?v.value:null;S?(S.comment&&(m=S.comment),S.commentBefore&&(l=!0)):v.value==null&&w?.comment&&(m=w.comment)}m&&(l=!0);let _=No(v,c,()=>m=null);l||(l=h.length>u||_.includes(`
92
- `)),f<e.length-1?_+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=h.reduce((w,S)=>w+S.length+2,2)+(_.length+2)>t.options.lineWidth)),l&&(_+=",")),m&&(_+=Dn(_,n,a(m))),h.push(_),u=h.length}const{start:d,end:p}=r;if(h.length===0)return d+p;if(!l){const f=h.reduce((v,m)=>v+m.length+2,2);l=t.options.lineWidth>0&&f>t.options.lineWidth}if(l){let f=d;for(const v of h)f+=v?`
85
+ `+Zi(l(e),c),a&&a()):h&&o&&o(),p}function lk({items:e},t,{flowChars:r,itemIndent:n}){const{indent:i,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=t;n+=s;const c=Object.assign({},t,{indent:n,inFlow:!0,type:null});let l=!1,u=0;const h=[];for(let f=0;f<e.length;++f){const v=e[f];let m=null;if(nt(v))v.spaceBefore&&h.push(""),uo(t,h,v.commentBefore,!1),v.comment&&(m=v.comment);else if(it(v)){const w=nt(v.key)?v.key:null;w&&(w.spaceBefore&&h.push(""),uo(t,h,w.commentBefore,!1),w.comment&&(l=!0));const S=nt(v.value)?v.value:null;S?(S.comment&&(m=S.comment),S.commentBefore&&(l=!0)):v.value==null&&w?.comment&&(m=w.comment)}m&&(l=!0);let _=lo(v,c,()=>m=null);l||(l=h.length>u||_.includes(`
86
+ `)),f<e.length-1?_+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=h.reduce((w,S)=>w+S.length+2,2)+(_.length+2)>t.options.lineWidth)),l&&(_+=",")),m&&(_+=Pn(_,n,a(m))),h.push(_),u=h.length}const{start:d,end:p}=r;if(h.length===0)return d+p;if(!l){const f=h.reduce((v,m)=>v+m.length+2,2);l=t.options.lineWidth>0&&f>t.options.lineWidth}if(l){let f=d;for(const v of h)f+=v?`
93
87
  ${s}${i}${v}`:`
94
88
  `;return`${f}
95
- ${i}${p}`}else return`${d}${o}${h.join(" ")}${o}${p}`}function zo({indent:e,options:{commentString:t}},r,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){const s=ss(t(n),e);r.push(s.trimStart())}}function an(e,t){const r=ot(t)?t.value:t;for(const n of e)if(st(n)&&(n.key===t||n.key===r||ot(n.key)&&n.key.value===r))return n}var wr=class extends Xm{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(pn,e),this.items=[]}static from(e,t,r){const{keepUndefined:n,replacer:i}=r,s=new this(e),o=(a,c)=>{if(typeof i=="function")c=i.call(t,a,c);else if(Array.isArray(i)&&!i.includes(a))return;(c!==void 0||n)&&s.items.push(Tu(a,c,r))};if(t instanceof Map)for(const[a,c]of t)o(a,c);else if(t&&typeof t=="object")for(const a of Object.keys(t))o(a,t[a]);return typeof e.sortMapEntries=="function"&&s.items.sort(e.sortMapEntries),s}add(e,t){let r;st(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new fn(e,e?.value):r=new fn(e.key,e.value);const n=an(this.items,r.key),i=this.schema?.sortMapEntries;if(n){if(!t)throw new Error(`Key ${r.key} already set`);ot(n.value)&&Ym(r.value)?n.value.value=r.value:n.value=r.value}else if(i){const s=this.items.findIndex(o=>i(r,o)<0);s===-1?this.items.push(r):this.items.splice(s,0,r)}else this.items.push(r)}delete(e){const t=an(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const r=an(this.items,e)?.value;return(!t&&ot(r)?r.value:r)??void 0}has(e){return!!an(this.items,e)}set(e,t){this.add(new fn(e,t),!0)}toJSON(e,t,r){const n=r?new r:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(n);for(const i of this.items)r_(t,n,i);return n}toString(e,t,r){if(!e)return JSON.stringify(this);for(const n of this.items)if(!st(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),i_(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:t})}},g$={collection:"map",default:!0,nodeClass:wr,tag:"tag:yaml.org,2002:map",resolve(e,t){return Ru(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>wr.from(e,t,r)},Uo=class extends Xm{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(hs,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Ds(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const r=Ds(e);if(typeof r!="number")return;const n=this.items[r];return!t&&ot(n)?n.value:n}has(e){const t=Ds(e);return typeof t=="number"&&t<this.items.length}set(e,t){const r=Ds(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);const n=this.items[r];ot(n)&&Ym(t)?n.value=t:this.items[r]=t}toJSON(e,t){const r=[];t?.onCreate&&t.onCreate(r);let n=0;for(const i of this.items)r.push(Ft(i,String(n++),t));return r}toString(e,t,r){return e?i_(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:r,onComment:t}):JSON.stringify(this)}static from(e,t,r){const{replacer:n}=r,i=new this(e);if(t&&Symbol.iterator in Object(t)){let s=0;for(let o of t){if(typeof n=="function"){const a=t instanceof Set?o:String(s++);o=n.call(t,a,o)}i.items.push(Do(o,void 0,r))}}return i}};function Ds(e){let t=ot(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}var m$={collection:"seq",default:!0,nodeClass:Uo,tag:"tag:yaml.org,2002:seq",resolve(e,t){return na(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Uo.from(e,t,r)};function vp(e){return typeof e=="bigint"||Number.isInteger(e)}var Ns=({value:e})=>JSON.stringify(e),_$=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Ns},{identify:e=>e==null,createNode:()=>new Ke(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ns},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Ns},{identify:vp,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>vp(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Ns}],FL=[g$,m$].concat(_$,{default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}});function y$(e,t,r){const{replacer:n}=r,i=new Uo(e);i.tag="tag:yaml.org,2002:pairs";let s=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof n=="function"&&(o=n.call(t,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;i.items.push(Tu(a,c,r))}return i}var b$=class s_ extends Uo{constructor(){super(),this.add=wr.prototype.add.bind(this),this.delete=wr.prototype.delete.bind(this),this.get=wr.prototype.get.bind(this),this.has=wr.prototype.has.bind(this),this.set=wr.prototype.set.bind(this),this.tag=s_.tag}toJSON(t,r){if(!r)return super.toJSON(t);const n=new Map;r?.onCreate&&r.onCreate(n);for(const i of this.items){let s,o;if(st(i)?(s=Ft(i.key,"",r),o=Ft(i.value,s,r)):s=Ft(i,"",r),n.has(s))throw new Error("Ordered maps must not include duplicate keys");n.set(s,o)}return n}static from(t,r,n){const i=y$(t,r,n),s=new this;return s.items=i.items,s}};b$.tag="tag:yaml.org,2002:omap";var w$=class o_ extends wr{constructor(t){super(t),this.tag=o_.tag}add(t){let r;st(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new fn(t.key,null):r=new fn(t,null),an(this.items,r.key)||this.items.push(r)}get(t,r){const n=an(this.items,t);return!r&&st(n)?ot(n.key)?n.key.value:n.key:n}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);const n=an(this.items,t);n&&!r?this.items.splice(this.items.indexOf(n),1):!n&&r&&this.items.push(new fn(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,n){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,n);throw new Error("Set items must all have null values")}static from(t,r,n){const{replacer:i}=n,s=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof i=="function"&&(o=i.call(r,o,o)),s.items.push(Tu(o,null,n));return s}};w$.tag="tag:yaml.org,2002:set";var bl=Symbol("break visit"),S$=Symbol("skip children"),a_=Symbol("remove item");function ii(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),c_(Object.freeze([]),e,t)}ii.BREAK=bl;ii.SKIP=S$;ii.REMOVE=a_;ii.itemAtPath=(e,t)=>{let r=e;for(const[n,i]of t){const s=r?.[n];if(s&&"items"in s)r=s.items[i];else return}return r};ii.parentCollection=(e,t)=>{const r=ii.itemAtPath(e,t.slice(0,-1)),n=t[t.length-1][0],i=r?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function c_(e,t,r){let n=r(t,e);if(typeof n=="symbol")return n;for(const i of["key","value"]){const s=t[i];if(s&&"items"in s){for(let o=0;o<s.items.length;++o){const a=c_(Object.freeze(e.concat([[i,o]])),s.items[o],r);if(typeof a=="number")o=a-1;else{if(a===bl)return bl;a===a_&&(s.items.splice(o,1),o-=1)}}typeof n=="function"&&i==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}var wl=["2025-03-26","2025-06-18","2025-11-25","2026-07-28"],E$=wl[wl.length-1];function zs(e){return e===E$?`Latest (${e})`:e}var k$=new Set(["2024-10-07","2024-11-05","2025-03-26","2025-06-18","2025-11-25"]);function R$(e){return wl.includes(e)}function A$(e){return e.length>0&&!k$.has(e)}var I$=["verified","refuted","unverifiable"],T$=["oauth2-dcr","oauth2-cimd","oauth2-preregistered","api-key","none"],$$=["omit","fixed","challenge","all-supported"],C$=["none","client_secret_basic","client_secret_post"],P$=["hosted","org","local"],l_=["none","minimal","low","medium","high","xhigh","max"],O$=["none","openrouter"],x$=new Set(["modelId","source","connectionRef","nativeModelId","settings","fallback"]),M$=new Set(["kind","id"]),L$=new Set(["kind","providerKey","customProviderName"]),D$=new Set(["reasoningEffort","temperature"]),N$=new Set(["provider","model"]),z$=new Set(P$),U$=new Set(l_),F$=new Set(O$),q$=/^[a-z0-9][a-z0-9._:-]*\/[^\s/]\S*$/;function os(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function j$(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function $r(e,t){return e===""?t:`${e}.${t}`}function as(e,t,r,n){for(const i of Object.keys(e))t.has(i)||n.push({path:$r(r,i),code:"unknown_key",message:`unknown key "${i}" (a selection never carries credentials)`})}function Wi(e,t,r,n,i){const s=$r(r,t);if(!j$(e,t)||e[t]===void 0){i&&n.push({path:s,code:"required",message:"is required"});return}const o=e[t];if(typeof o!="string"){n.push({path:s,code:"invalid_type",message:"must be a string"});return}if(o.trim()===""||o.trim()!==o){n.push({path:s,code:"invalid_value",message:"must be a non-empty string without surrounding whitespace"});return}return o}function H$(e,t){const r="connectionRef";if(!os(e)){t.push({path:r,code:"invalid_type",message:"must be a plain object"});return}if(e.kind==="orgProvider"){as(e,M$,r,t);const n=Wi(e,"id",r,t,!0);return n===void 0?void 0:{kind:"orgProvider",id:n}}if(e.kind==="localProvider"){as(e,L$,r,t);const n=Wi(e,"providerKey",r,t,!0),i=Wi(e,"customProviderName",r,t,!1);return n===void 0?void 0:{kind:"localProvider",providerKey:n,...i!==void 0?{customProviderName:i}:{}}}t.push({path:$r(r,"kind"),code:e.kind===void 0?"required":"invalid_value",message:'must be "orgProvider" or "localProvider"'})}function V$(e,t){const r="settings";if(!os(e)){t.push({path:r,code:"invalid_type",message:"must be a plain object"});return}as(e,D$,r,t);const n={};if(e.reasoningEffort!==void 0&&(typeof e.reasoningEffort=="string"&&U$.has(e.reasoningEffort)?n.reasoningEffort=e.reasoningEffort:t.push({path:$r(r,"reasoningEffort"),code:"invalid_value",message:`must be one of ${l_.map(i=>`"${i}"`).join(", ")}`})),e.temperature!==void 0){const i=e.temperature;typeof i!="number"||!Number.isFinite(i)?t.push({path:$r(r,"temperature"),code:"invalid_type",message:"must be a finite number"}):i<0||i>2?t.push({path:$r(r,"temperature"),code:"out_of_range",message:"must be within [0, 2]"}):n.temperature=i}return n}function B$(e,t){const r="fallback";if(e===void 0){t.push({path:r,code:"required",message:"is required"});return}if(!os(e)){t.push({path:r,code:"invalid_type",message:"must be a plain object"});return}as(e,N$,r,t);let n=!0;if((typeof e.provider!="string"||!F$.has(e.provider))&&(n=!1,t.push({path:$r(r,"provider"),code:e.provider===void 0?"required":"invalid_value",message:'must be "none" or "openrouter"'})),e.model!=="none"&&(n=!1,t.push({path:$r(r,"model"),code:e.model===void 0?"required":"invalid_value",message:'must be "none" (no surface substitutes a different model)'})),!!n)return{provider:e.provider,model:"none"}}function G$(e){const t=[];if(!os(e))return{ok:!1,issues:[{path:"",code:"invalid_type",message:"must be a plain object"}]};as(e,x$,"",t);const r=Wi(e,"modelId","",t,!0);r!==void 0&&!q$.test(r)&&t.push({path:"modelId",code:"model_id_not_canonical",message:`"${r}" is not a canonical "provider/model" id`});let n;e.source===void 0?t.push({path:"source",code:"required",message:"is required"}):typeof e.source=="string"&&z$.has(e.source)?n=e.source:t.push({path:"source",code:"invalid_value",message:e.source==="legacy"?'"legacy" is read-only: a legacy selection is never saved':'must be "hosted", "org" or "local"'});const i=e.connectionRef===void 0?void 0:H$(e.connectionRef,t);if(n==="hosted"&&e.connectionRef!==void 0)t.push({path:"connectionRef",code:"connection_ref_mismatch",message:'must be absent when source is "hosted"'});else if(n==="org"||n==="local"){const l=n==="org"?"orgProvider":"localProvider";e.connectionRef===void 0?t.push({path:"connectionRef",code:"connection_ref_mismatch",message:`is required when source is "${n}" (kind "${l}")`}):os(e.connectionRef)&&(e.connectionRef.kind==="orgProvider"||e.connectionRef.kind==="localProvider")&&e.connectionRef.kind!==l&&t.push({path:"connectionRef.kind",code:"connection_ref_mismatch",message:`must be "${l}" when source is "${n}"`})}const s=Wi(e,"nativeModelId","",t,!1),o=e.settings===void 0?void 0:V$(e.settings,t),a=B$(e.fallback,t);if(t.length>0)return{ok:!1,issues:t};const c=o!==void 0&&(o.reasoningEffort!==void 0||o.temperature!==void 0);return{ok:!0,selection:{modelId:r,source:n,...i!==void 0?{connectionRef:i}:{},...s!==void 0?{nativeModelId:s}:{},...c?{settings:{...o.reasoningEffort!==void 0?{reasoningEffort:o.reasoningEffort}:{},...o.temperature!==void 0?{temperature:o.temperature}:{}}}:{},fallback:a}}}function W$(e){return G$(e).ok}function qL(e){const t=encodeURIComponent;let r="";if(e.source!=="legacy"&&e.connectionRef){const n=e.connectionRef;r=n.kind==="orgProvider"?t(n.id):n.customProviderName!==void 0?`${t(n.providerKey)}:${t(n.customProviderName)}`:t(n.providerKey)}return`${e.source}:${r}:${t(e.modelId)}`}function jL(e){return{provider:e==="chat"?"openrouter":"none",model:"none"}}var Z$=["inline","fullscreen","pip"],HL=new Set(Z$),eo=["mode","originAllowlist"],VL={allow_all:new Set(eo),read_only:new Set(eo),allowlist:new Set([...eo,"toolAllowlist"])},BL=new Set([...eo,"toolAllowlist"]),GL=new Set($$),WL=new Set(C$),ZL=new Set(I$),JL=new Set(T$),J$=["clientName","redirectUris","userAgent"],KL=new Set(J$);function K$(e){const t=new Uint8Array(e);let r="";for(let n=0;n<t.length;n++)r+=t[n].toString(16).padStart(2,"0");return r}async function u_(e){const t=new TextEncoder().encode(e);return K$(await crypto.subtle.digest("SHA-256",t))}function Sl(e){return Array.isArray(e)?e.map(Sl):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>[t,Sl(r)])):e}function Y$(e){return JSON.stringify(Sl(e))}function YL(e,t){if(t==="openai-apps"){const n=e;return typeof n?.type=="string"?n.type.replace("openai:",""):"unknown"}const r=e;return typeof r?.method=="string"?r.method:r?.result!==void 0?"result":r?.error!==void 0?"error":"unknown"}async function XL(e){const t=await crypto.subtle.digest("SHA-256",e),r=new Uint8Array(t);let n="";for(let i=0;i<r.length;i++)n+=r[i].toString(16).padStart(2,"0");return n}async function QL(e){return u_(Y$(e))}async function X$(e){const t=[...e].sort((r,n)=>r.path<n.path?-1:r.path>n.path?1:0);return u_(t.map(r=>`${r.path}\0${r.contentHash}\0`).join(""))}var Q$=/^[A-Za-z]:[\\/]/,eC=/[\u0000-\u001f\u007f]/,tC=new TextEncoder;function rC(e){return tC.encode(e).length}function nC(e){let t=e.length;for(;t>0;){const r=e[t-1];if(r!=="."&&r!==" ")break;t-=1}return e.slice(0,t)}function d_(e){if(typeof e!="string"||e.length===0)return{ok:!1,code:"PATH_EMPTY",message:"path is empty"};if(e.includes("\0"))return{ok:!1,code:"PATH_NUL_BYTE",message:"path contains a NUL byte"};if(eC.test(e))return{ok:!1,code:"PATH_INVALID_CHARACTER",message:"path contains control characters"};if(e.startsWith("/")||e.startsWith("\\")||Q$.test(e))return{ok:!1,code:"PATH_ABSOLUTE",message:`absolute paths are not allowed: "${e}"`};const t=e.replace(/\\/g,"/").split("/").filter(r=>r!==""&&r!==".");for(const r of t){if(r==="..")return{ok:!1,code:"PATH_TRAVERSAL",message:`path traversal ("..") is not allowed: "${e}"`};if(r.includes(":"))return{ok:!1,code:"PATH_INVALID_CHARACTER",message:`path segments must not contain ":" (drive prefix / alternate data stream): "${e}"`};const n=nC(r);if(n===""||n==="."||n==="..")return{ok:!1,code:"PATH_INVALID_CHARACTER",message:`path segment "${r}" is not portable (empty or dot name after trailing dot/space stripping)`}}return t.length===0?{ok:!1,code:"PATH_EMPTY",message:"path is empty"}:{ok:!0,path:t.join("/").normalize("NFC")}}function iC(e){return e.normalize("NFKC").toLowerCase()}function eD(e,t){return t===e||t.startsWith(`${e}/`)}function tD(e,t){const r=d_(t);return r.ok?{ok:!0,path:e===""?r.path:`${e}/${r.path}`}:r.code==="PATH_ABSOLUTE"||r.code==="PATH_TRAVERSAL"?{ok:!1,code:"PATH_ESCAPES_ROOT",message:`referenced path escapes the bundle root: "${t}"`}:r}function rD(e,t,r){e.length>t.maxEntries&&r.error("BUNDLE_TOO_MANY_ENTRIES",`bundle has ${e.length} entries; the limit is ${t.maxEntries}`);const n=new Set,i=new Map,s=[];let o=0,a=!1;for(const c of e){if(c.kind==="symlink"||c.kind==="hardlink"){r.error("PATH_LINK_ENTRY",`${c.kind} entries are not allowed`,{path:c.path});continue}const l=d_(c.path);if(!l.ok){r.error(l.code,l.message,{path:c.path});continue}const u=l.path;if(rC(u)>t.maxPathBytes){r.error("PATH_TOO_LONG",`path exceeds ${t.maxPathBytes} bytes`,{path:u});continue}if(u.split("/").length>t.maxPathDepth){r.error("PATH_TOO_DEEP",`path exceeds nesting depth ${t.maxPathDepth}`,{path:u});continue}if(n.has(u)){r.error("PATH_DUPLICATE",`duplicate normalized path: "${u}"`,{path:c.path});continue}n.add(u);const h=iC(u),d=i.get(h);if(d!==void 0){r.error("PATH_CASE_COLLISION",`"${u}" collides with "${d}" on case-insensitive filesystems`,{path:u});continue}if(i.set(h,u),c.kind!=="directory"){if(!Number.isFinite(c.size)||c.size<0){r.error("FILE_SIZE_MISMATCH","entry declares an invalid size",{path:u});continue}if(c.size>t.maxFileBytes){r.error("FILE_TOO_LARGE",`file exceeds the per-file limit of ${t.maxFileBytes} bytes`,{path:u});continue}o+=c.size,!a&&o>t.maxTotalBytes&&(a=!0,r.error("BUNDLE_TOO_LARGE",`total uncompressed content exceeds ${t.maxTotalBytes} bytes`)),s.push({sourcePath:c.path,path:u,size:c.size})}}return s.sort((c,l)=>c.path<l.path?-1:c.path>l.path?1:0),s}var sC=class extends Error{code;issues;constructor(e){const t=e.find(n=>n.severity==="error"),r=t?.code??"MANIFEST_INVALID_FIELD";super(t?`plugin bundle validation failed: ${t.code}: ${t.message}`:"plugin bundle validation failed"),this.name="PluginBundleError",this.code=r,this.issues=e}},nD=class{all=[];error(e,t,r){this.all.push({code:e,severity:"error",message:t,...r})}warn(e,t,r){this.all.push({code:e,severity:"warning",message:t,...r})}hasErrors(){return this.all.some(e=>e.severity==="error")}issues(){return[...this.all]}warnings(){return this.all.filter(e=>e.severity==="warning")}throwIfErrors(){if(this.hasErrors())throw new sC(this.issues())}absorbDemoted(e){for(const t of e.issues())this.all.push(t.severity==="error"?{...t,severity:"warning"}:t)}firstErrorMessage(){return this.all.find(e=>e.severity==="error")?.message}};var oC=/(secret|token|password|passwd|api[-_]?key|private[-_]?key|credential)/i,h_=/(bearer\s+\S|-----BEGIN|\b(?:sk|pk|rk|xox[a-z])-[A-Za-z0-9]|[a-z][a-z0-9+.-]*:\/\/[^/\s:@]*:[^/\s@]+@|[A-Za-z0-9+/_-]{40,})/i;function iD(e){return h_.test(e)}var Ei=Symbol("drop");function El(e,t,r,n,i){if(r>32)return i.reportedTooDeep||(i.reportedTooDeep=!0,n.issues.error("VALUE_TOO_DEEP",`${n.label}: field "${t}" nests deeper than 32 levels`,n.context)),Ei;if(typeof e=="string")return h_.test(e)?(n.issues.warn(n.secretCode,`${n.label}: value of "${t}" looks secret-bearing and is not stored`,n.context),Ei):e;if(typeof e=="number"||typeof e=="boolean"||e===null)return e;if(Array.isArray(e)){const s=[];for(let o=0;o<e.length;o++){const a=El(e[o],`${t}[${o}]`,r+1,n,i);a!==Ei&&s.push(a)}return s}if(typeof e=="object"){const s={};for(const[o,a]of Object.entries(e)){const c=t===""?o:`${t}.${o}`;if(oC.test(o)){n.issues.warn(n.secretCode,`${n.label}: field "${c}" looks secret-bearing and is not stored`,n.context);continue}const l=El(a,c,r+1,n,i);l!==Ei&&(s[o]=l)}return s}return Ei}function sD(e,t){return El(e,"",0,t,{reportedTooDeep:!1})}var oD="skills",aD="SKILL.md",p_=64,gp=1024;function aC(e){return e.length<1||e.length>p_||e.includes("--")?!1:/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(e)}var kl=class extends Error{constructor(){super("yaml value nests too deeply"),this.name="YamlValueTooDeepError"}};function Rl(e,t=0){const r=e.trim();if(r.length>=2&&(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")))return r.slice(1,-1);if(r==="true")return!0;if(r==="false")return!1;if(r==="null"||r==="~")return null;if(/^-?\d+(\.\d+)?$/.test(r))return Number(r);if(r.startsWith("[")&&r.endsWith("]")){if(t>=32)throw new kl;const n=r.slice(1,-1).trim();return n===""?[]:n.split(",").map(i=>Rl(i,t+1))}return r}function cC(e){const t={},r=[],n=[],i=e.split(/\r?\n/);let s=0;for(;s<i.length;){const o=i[s];if(/^\s*$/.test(o)||/^\s*#/.test(o)){s++;continue}const a=/^([A-Za-z0-9_.-]+):\s*(.*)$/.exec(o);if(!a){r.push(o),s++;continue}const c=a[1],l=a[2];if(l===""){const u=[];let h=s+1;for(;h<i.length;){const d=i[h];if(/^\s*$/.test(d)||/^\s*#/.test(d)){h++;continue}const p=/^\s+-\s*(.*)$/.exec(d);if(p){try{u.push(Rl(p[1]))}catch(f){if(!(f instanceof kl))throw f;n.push(d)}h++;continue}if(/^\s+\S/.test(d)){r.push(d),h++;continue}break}u.length>0?t[c]=u:t[c]="",s=h;continue}if(l==="|"||l==="|-"||l===">"||l===">-"){const u=[];let h=null,d=s+1;for(;d<i.length;){const p=i[d];if(/^\s*$/.test(p)){u.push(""),d++;continue}const f=p.length-p.trimStart().length;if(f===0)break;h===null&&(h=f),u.push(p.slice(Math.min(h,f))),d++}for(;u.length>0&&u[u.length-1]==="";)u.pop();t[c]=l.startsWith("|")?u.join(`
89
+ ${i}${p}`}else return`${d}${o}${h.join(" ")}${o}${p}`}function uo({indent:e,options:{commentString:t}},r,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){const s=Zi(t(n),e);r.push(s.trimStart())}}function sn(e,t){const r=st(t)?t.value:t;for(const n of e)if(it(n)&&(n.key===t||n.key===r||st(n.key)&&n.key.value===r))return n}var yr=class extends mv{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(an,e),this.items=[]}static from(e,t,r){const{keepUndefined:n,replacer:i}=r,s=new this(e),o=(a,c)=>{if(typeof i=="function")c=i.call(t,a,c);else if(Array.isArray(i)&&!i.includes(a))return;(c!==void 0||n)&&s.items.push(Yl(a,c,r))};if(t instanceof Map)for(const[a,c]of t)o(a,c);else if(t&&typeof t=="object")for(const a of Object.keys(t))o(a,t[a]);return typeof e.sortMapEntries=="function"&&s.items.sort(e.sortMapEntries),s}add(e,t){let r;it(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new cn(e,e?.value):r=new cn(e.key,e.value);const n=sn(this.items,r.key),i=this.schema?.sortMapEntries;if(n){if(!t)throw new Error(`Key ${r.key} already set`);st(n.value)&&gv(r.value)?n.value.value=r.value:n.value=r.value}else if(i){const s=this.items.findIndex(o=>i(r,o)<0);s===-1?this.items.push(r):this.items.splice(s,0,r)}else this.items.push(r)}delete(e){const t=sn(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const r=sn(this.items,e)?.value;return(!t&&st(r)?r.value:r)??void 0}has(e){return!!sn(this.items,e)}set(e,t){this.add(new cn(e,t),!0)}toJSON(e,t,r){const n=r?new r:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(n);for(const i of this.items)wv(t,n,i);return n}toString(e,t,r){if(!e)return JSON.stringify(this);for(const n of this.items)if(!it(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Ev(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:t})}},uk={collection:"map",default:!0,nodeClass:yr,tag:"tag:yaml.org,2002:map",resolve(e,t){return Zl(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>yr.from(e,t,r)},ho=class extends mv{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(os,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=ws(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const r=ws(e);if(typeof r!="number")return;const n=this.items[r];return!t&&st(n)?n.value:n}has(e){const t=ws(e);return typeof t=="number"&&t<this.items.length}set(e,t){const r=ws(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);const n=this.items[r];st(n)&&gv(t)?n.value=t:this.items[r]=t}toJSON(e,t){const r=[];t?.onCreate&&t.onCreate(r);let n=0;for(const i of this.items)r.push(zt(i,String(n++),t));return r}toString(e,t,r){return e?Ev(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:r,onComment:t}):JSON.stringify(this)}static from(e,t,r){const{replacer:n}=r,i=new this(e);if(t&&Symbol.iterator in Object(t)){let s=0;for(let o of t){if(typeof n=="function"){const a=t instanceof Set?o:String(s++);o=n.call(t,a,o)}i.items.push(co(o,void 0,r))}}return i}};function ws(e){let t=st(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}var dk={collection:"seq",default:!0,nodeClass:ho,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Vo(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>ho.from(e,t,r)};function Sd(e){return typeof e=="bigint"||Number.isInteger(e)}var Ss=({value:e})=>JSON.stringify(e),hk=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Ss},{identify:e=>e==null,createNode:()=>new Ke(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ss},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Ss},{identify:Sd,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>Sd(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Ss}],FM=[uk,dk].concat(hk,{default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}});function pk(e,t,r){const{replacer:n}=r,i=new ho(e);i.tag="tag:yaml.org,2002:pairs";let s=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof n=="function"&&(o=n.call(t,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;i.items.push(Yl(a,c,r))}return i}var fk=class kv extends ho{constructor(){super(),this.add=yr.prototype.add.bind(this),this.delete=yr.prototype.delete.bind(this),this.get=yr.prototype.get.bind(this),this.has=yr.prototype.has.bind(this),this.set=yr.prototype.set.bind(this),this.tag=kv.tag}toJSON(t,r){if(!r)return super.toJSON(t);const n=new Map;r?.onCreate&&r.onCreate(n);for(const i of this.items){let s,o;if(it(i)?(s=zt(i.key,"",r),o=zt(i.value,s,r)):s=zt(i,"",r),n.has(s))throw new Error("Ordered maps must not include duplicate keys");n.set(s,o)}return n}static from(t,r,n){const i=pk(t,r,n),s=new this;return s.items=i.items,s}};fk.tag="tag:yaml.org,2002:omap";var vk=class Rv extends yr{constructor(t){super(t),this.tag=Rv.tag}add(t){let r;it(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new cn(t.key,null):r=new cn(t,null),sn(this.items,r.key)||this.items.push(r)}get(t,r){const n=sn(this.items,t);return!r&&it(n)?st(n.key)?n.key.value:n.key:n}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);const n=sn(this.items,t);n&&!r?this.items.splice(this.items.indexOf(n),1):!n&&r&&this.items.push(new cn(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,n){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,n);throw new Error("Set items must all have null values")}static from(t,r,n){const{replacer:i}=n,s=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof i=="function"&&(o=i.call(r,o,o)),s.items.push(Yl(o,null,n));return s}};vk.tag="tag:yaml.org,2002:set";var xc=Symbol("break visit"),gk=Symbol("skip children"),Av=Symbol("remove item");function Wn(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Iv(Object.freeze([]),e,t)}Wn.BREAK=xc;Wn.SKIP=gk;Wn.REMOVE=Av;Wn.itemAtPath=(e,t)=>{let r=e;for(const[n,i]of t){const s=r?.[n];if(s&&"items"in s)r=s.items[i];else return}return r};Wn.parentCollection=(e,t)=>{const r=Wn.itemAtPath(e,t.slice(0,-1)),n=t[t.length-1][0],i=r?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function Iv(e,t,r){let n=r(t,e);if(typeof n=="symbol")return n;for(const i of["key","value"]){const s=t[i];if(s&&"items"in s){for(let o=0;o<s.items.length;++o){const a=Iv(Object.freeze(e.concat([[i,o]])),s.items[o],r);if(typeof a=="number")o=a-1;else{if(a===xc)return xc;a===Av&&(s.items.splice(o,1),o-=1)}}typeof n=="function"&&i==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}var Mc=["2025-03-26","2025-06-18","2025-11-25","2026-07-28"],mk=Mc[Mc.length-1];function Es(e){return e===mk?`Latest (${e})`:e}var _k=new Set(["2024-10-07","2024-11-05","2025-03-26","2025-06-18","2025-11-25"]);function yk(e){return Mc.includes(e)}function bk(e){return e.length>0&&!_k.has(e)}var wk=["verified","refuted","unverifiable"],Sk=["oauth2-dcr","oauth2-cimd","oauth2-preregistered","api-key","none"],Ek=["omit","fixed","challenge","all-supported"],kk=["none","client_secret_basic","client_secret_post"],Rk=["hosted","org","local"],Tv=["none","minimal","low","medium","high","xhigh","max"],Ak=["none","openrouter"],Ik=new Set(["modelId","source","connectionRef","nativeModelId","settings","fallback"]),Tk=new Set(["kind","id"]),Ck=new Set(["kind","providerKey","customProviderName"]),$k=new Set(["reasoningEffort","temperature"]),Pk=new Set(["provider","model"]),Ok=new Set(Rk),xk=new Set(Tv),Mk=new Set(Ak),Lk=/^[a-z0-9][a-z0-9._:-]*\/[^\s/]\S*$/;function Ji(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Dk(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ar(e,t){return e===""?t:`${e}.${t}`}function Ki(e,t,r,n){for(const i of Object.keys(e))t.has(i)||n.push({path:Ar(r,i),code:"unknown_key",message:`unknown key "${i}" (a selection never carries credentials)`})}function Pi(e,t,r,n,i){const s=Ar(r,t);if(!Dk(e,t)||e[t]===void 0){i&&n.push({path:s,code:"required",message:"is required"});return}const o=e[t];if(typeof o!="string"){n.push({path:s,code:"invalid_type",message:"must be a string"});return}if(o.trim()===""||o.trim()!==o){n.push({path:s,code:"invalid_value",message:"must be a non-empty string without surrounding whitespace"});return}return o}function Nk(e,t){const r="connectionRef";if(!Ji(e)){t.push({path:r,code:"invalid_type",message:"must be a plain object"});return}if(e.kind==="orgProvider"){Ki(e,Tk,r,t);const n=Pi(e,"id",r,t,!0);return n===void 0?void 0:{kind:"orgProvider",id:n}}if(e.kind==="localProvider"){Ki(e,Ck,r,t);const n=Pi(e,"providerKey",r,t,!0),i=Pi(e,"customProviderName",r,t,!1);return n===void 0?void 0:{kind:"localProvider",providerKey:n,...i!==void 0?{customProviderName:i}:{}}}t.push({path:Ar(r,"kind"),code:e.kind===void 0?"required":"invalid_value",message:'must be "orgProvider" or "localProvider"'})}function zk(e,t){const r="settings";if(!Ji(e)){t.push({path:r,code:"invalid_type",message:"must be a plain object"});return}Ki(e,$k,r,t);const n={};if(e.reasoningEffort!==void 0&&(typeof e.reasoningEffort=="string"&&xk.has(e.reasoningEffort)?n.reasoningEffort=e.reasoningEffort:t.push({path:Ar(r,"reasoningEffort"),code:"invalid_value",message:`must be one of ${Tv.map(i=>`"${i}"`).join(", ")}`})),e.temperature!==void 0){const i=e.temperature;typeof i!="number"||!Number.isFinite(i)?t.push({path:Ar(r,"temperature"),code:"invalid_type",message:"must be a finite number"}):i<0||i>2?t.push({path:Ar(r,"temperature"),code:"out_of_range",message:"must be within [0, 2]"}):n.temperature=i}return n}function Uk(e,t){const r="fallback";if(e===void 0){t.push({path:r,code:"required",message:"is required"});return}if(!Ji(e)){t.push({path:r,code:"invalid_type",message:"must be a plain object"});return}Ki(e,Pk,r,t);let n=!0;if((typeof e.provider!="string"||!Mk.has(e.provider))&&(n=!1,t.push({path:Ar(r,"provider"),code:e.provider===void 0?"required":"invalid_value",message:'must be "none" or "openrouter"'})),e.model!=="none"&&(n=!1,t.push({path:Ar(r,"model"),code:e.model===void 0?"required":"invalid_value",message:'must be "none" (no surface substitutes a different model)'})),!!n)return{provider:e.provider,model:"none"}}function qM(e){const t=[];if(!Ji(e))return{ok:!1,issues:[{path:"",code:"invalid_type",message:"must be a plain object"}]};Ki(e,Ik,"",t);const r=Pi(e,"modelId","",t,!0);r!==void 0&&!Lk.test(r)&&t.push({path:"modelId",code:"model_id_not_canonical",message:`"${r}" is not a canonical "provider/model" id`});let n;e.source===void 0?t.push({path:"source",code:"required",message:"is required"}):typeof e.source=="string"&&Ok.has(e.source)?n=e.source:t.push({path:"source",code:"invalid_value",message:e.source==="legacy"?'"legacy" is read-only: a legacy selection is never saved':'must be "hosted", "org" or "local"'});const i=e.connectionRef===void 0?void 0:Nk(e.connectionRef,t);if(n==="hosted"&&e.connectionRef!==void 0)t.push({path:"connectionRef",code:"connection_ref_mismatch",message:'must be absent when source is "hosted"'});else if(n==="org"||n==="local"){const l=n==="org"?"orgProvider":"localProvider";e.connectionRef===void 0?t.push({path:"connectionRef",code:"connection_ref_mismatch",message:`is required when source is "${n}" (kind "${l}")`}):Ji(e.connectionRef)&&(e.connectionRef.kind==="orgProvider"||e.connectionRef.kind==="localProvider")&&e.connectionRef.kind!==l&&t.push({path:"connectionRef.kind",code:"connection_ref_mismatch",message:`must be "${l}" when source is "${n}"`})}const s=Pi(e,"nativeModelId","",t,!1),o=e.settings===void 0?void 0:zk(e.settings,t),a=Uk(e.fallback,t);if(t.length>0)return{ok:!1,issues:t};const c=o!==void 0&&(o.reasoningEffort!==void 0||o.temperature!==void 0);return{ok:!0,selection:{modelId:r,source:n,...i!==void 0?{connectionRef:i}:{},...s!==void 0?{nativeModelId:s}:{},...c?{settings:{...o.reasoningEffort!==void 0?{reasoningEffort:o.reasoningEffort}:{},...o.temperature!==void 0?{temperature:o.temperature}:{}}}:{},fallback:a}}}function jM(e){const t=encodeURIComponent;let r="";if(e.source!=="legacy"&&e.connectionRef){const n=e.connectionRef;r=n.kind==="orgProvider"?t(n.id):n.customProviderName!==void 0?`${t(n.providerKey)}:${t(n.customProviderName)}`:t(n.providerKey)}return`${e.source}:${r}:${t(e.modelId)}`}function HM(e){return{provider:e==="chat"?"openrouter":"none",model:"none"}}var Fk=["inline","fullscreen","pip"],VM=new Set(Fk),Hs=["mode","originAllowlist"],BM={allow_all:new Set(Hs),read_only:new Set(Hs),allowlist:new Set([...Hs,"toolAllowlist"])},GM=new Set([...Hs,"toolAllowlist"]),WM=new Set(Ek),ZM=new Set(kk),JM=new Set(wk),KM=new Set(Sk),qk=["clientName","redirectUris","userAgent"],YM=new Set(qk);function jk(e){const t=new Uint8Array(e);let r="";for(let n=0;n<t.length;n++)r+=t[n].toString(16).padStart(2,"0");return r}async function Cv(e){const t=new TextEncoder().encode(e);return jk(await crypto.subtle.digest("SHA-256",t))}function Lc(e){return Array.isArray(e)?e.map(Lc):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>[t,Lc(r)])):e}function Hk(e){return JSON.stringify(Lc(e))}function XM(e,t){if(t==="openai-apps"){const n=e;return typeof n?.type=="string"?n.type.replace("openai:",""):"unknown"}const r=e;return typeof r?.method=="string"?r.method:r?.result!==void 0?"result":r?.error!==void 0?"error":"unknown"}async function QM(e){const t=await crypto.subtle.digest("SHA-256",e),r=new Uint8Array(t);let n="";for(let i=0;i<r.length;i++)n+=r[i].toString(16).padStart(2,"0");return n}async function eL(e){return Cv(Hk(e))}async function Vk(e){const t=[...e].sort((r,n)=>r.path<n.path?-1:r.path>n.path?1:0);return Cv(t.map(r=>`${r.path}\0${r.contentHash}\0`).join(""))}var Bk=/^[A-Za-z]:[\\/]/,Gk=/[\u0000-\u001f\u007f]/,Wk=new TextEncoder;function Zk(e){return Wk.encode(e).length}function Jk(e){let t=e.length;for(;t>0;){const r=e[t-1];if(r!=="."&&r!==" ")break;t-=1}return e.slice(0,t)}function $v(e){if(typeof e!="string"||e.length===0)return{ok:!1,code:"PATH_EMPTY",message:"path is empty"};if(e.includes("\0"))return{ok:!1,code:"PATH_NUL_BYTE",message:"path contains a NUL byte"};if(Gk.test(e))return{ok:!1,code:"PATH_INVALID_CHARACTER",message:"path contains control characters"};if(e.startsWith("/")||e.startsWith("\\")||Bk.test(e))return{ok:!1,code:"PATH_ABSOLUTE",message:`absolute paths are not allowed: "${e}"`};const t=e.replace(/\\/g,"/").split("/").filter(r=>r!==""&&r!==".");for(const r of t){if(r==="..")return{ok:!1,code:"PATH_TRAVERSAL",message:`path traversal ("..") is not allowed: "${e}"`};if(r.includes(":"))return{ok:!1,code:"PATH_INVALID_CHARACTER",message:`path segments must not contain ":" (drive prefix / alternate data stream): "${e}"`};const n=Jk(r);if(n===""||n==="."||n==="..")return{ok:!1,code:"PATH_INVALID_CHARACTER",message:`path segment "${r}" is not portable (empty or dot name after trailing dot/space stripping)`}}return t.length===0?{ok:!1,code:"PATH_EMPTY",message:"path is empty"}:{ok:!0,path:t.join("/").normalize("NFC")}}function Kk(e){return e.normalize("NFKC").toLowerCase()}function tL(e,t){return t===e||t.startsWith(`${e}/`)}function rL(e,t){const r=$v(t);return r.ok?{ok:!0,path:e===""?r.path:`${e}/${r.path}`}:r.code==="PATH_ABSOLUTE"||r.code==="PATH_TRAVERSAL"?{ok:!1,code:"PATH_ESCAPES_ROOT",message:`referenced path escapes the bundle root: "${t}"`}:r}function nL(e,t,r){e.length>t.maxEntries&&r.error("BUNDLE_TOO_MANY_ENTRIES",`bundle has ${e.length} entries; the limit is ${t.maxEntries}`);const n=new Set,i=new Map,s=[];let o=0,a=!1;for(const c of e){if(c.kind==="symlink"||c.kind==="hardlink"){r.error("PATH_LINK_ENTRY",`${c.kind} entries are not allowed`,{path:c.path});continue}const l=$v(c.path);if(!l.ok){r.error(l.code,l.message,{path:c.path});continue}const u=l.path;if(Zk(u)>t.maxPathBytes){r.error("PATH_TOO_LONG",`path exceeds ${t.maxPathBytes} bytes`,{path:u});continue}if(u.split("/").length>t.maxPathDepth){r.error("PATH_TOO_DEEP",`path exceeds nesting depth ${t.maxPathDepth}`,{path:u});continue}if(n.has(u)){r.error("PATH_DUPLICATE",`duplicate normalized path: "${u}"`,{path:c.path});continue}n.add(u);const h=Kk(u),d=i.get(h);if(d!==void 0){r.error("PATH_CASE_COLLISION",`"${u}" collides with "${d}" on case-insensitive filesystems`,{path:u});continue}if(i.set(h,u),c.kind!=="directory"){if(!Number.isFinite(c.size)||c.size<0){r.error("FILE_SIZE_MISMATCH","entry declares an invalid size",{path:u});continue}if(c.size>t.maxFileBytes){r.error("FILE_TOO_LARGE",`file exceeds the per-file limit of ${t.maxFileBytes} bytes`,{path:u});continue}o+=c.size,!a&&o>t.maxTotalBytes&&(a=!0,r.error("BUNDLE_TOO_LARGE",`total uncompressed content exceeds ${t.maxTotalBytes} bytes`)),s.push({sourcePath:c.path,path:u,size:c.size})}}return s.sort((c,l)=>c.path<l.path?-1:c.path>l.path?1:0),s}var Yk=class extends Error{code;issues;constructor(e){const t=e.find(n=>n.severity==="error"),r=t?.code??"MANIFEST_INVALID_FIELD";super(t?`plugin bundle validation failed: ${t.code}: ${t.message}`:"plugin bundle validation failed"),this.name="PluginBundleError",this.code=r,this.issues=e}},iL=class{all=[];error(e,t,r){this.all.push({code:e,severity:"error",message:t,...r})}warn(e,t,r){this.all.push({code:e,severity:"warning",message:t,...r})}hasErrors(){return this.all.some(e=>e.severity==="error")}issues(){return[...this.all]}warnings(){return this.all.filter(e=>e.severity==="warning")}throwIfErrors(){if(this.hasErrors())throw new Yk(this.issues())}absorbDemoted(e){for(const t of e.issues())this.all.push(t.severity==="error"?{...t,severity:"warning"}:t)}firstErrorMessage(){return this.all.find(e=>e.severity==="error")?.message}};var Xk=/(secret|token|password|passwd|api[-_]?key|private[-_]?key|credential)/i,Pv=/(bearer\s+\S|-----BEGIN|\b(?:sk|pk|rk|xox[a-z])-[A-Za-z0-9]|[a-z][a-z0-9+.-]*:\/\/[^/\s:@]*:[^/\s@]+@|[A-Za-z0-9+/_-]{40,})/i;function sL(e){return Pv.test(e)}var hi=Symbol("drop");function Dc(e,t,r,n,i){if(r>32)return i.reportedTooDeep||(i.reportedTooDeep=!0,n.issues.error("VALUE_TOO_DEEP",`${n.label}: field "${t}" nests deeper than 32 levels`,n.context)),hi;if(typeof e=="string")return Pv.test(e)?(n.issues.warn(n.secretCode,`${n.label}: value of "${t}" looks secret-bearing and is not stored`,n.context),hi):e;if(typeof e=="number"||typeof e=="boolean"||e===null)return e;if(Array.isArray(e)){const s=[];for(let o=0;o<e.length;o++){const a=Dc(e[o],`${t}[${o}]`,r+1,n,i);a!==hi&&s.push(a)}return s}if(typeof e=="object"){const s={};for(const[o,a]of Object.entries(e)){const c=t===""?o:`${t}.${o}`;if(Xk.test(o)){n.issues.warn(n.secretCode,`${n.label}: field "${c}" looks secret-bearing and is not stored`,n.context);continue}const l=Dc(a,c,r+1,n,i);l!==hi&&(s[o]=l)}return s}return hi}function oL(e,t){return Dc(e,"",0,t,{reportedTooDeep:!1})}var aL="skills",cL="SKILL.md",Ov=64,Ed=1024;function Qk(e){return e.length<1||e.length>Ov||e.includes("--")?!1:/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(e)}var Nc=class extends Error{constructor(){super("yaml value nests too deeply"),this.name="YamlValueTooDeepError"}};function zc(e,t=0){const r=e.trim();if(r.length>=2&&(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")))return r.slice(1,-1);if(r==="true")return!0;if(r==="false")return!1;if(r==="null"||r==="~")return null;if(/^-?\d+(\.\d+)?$/.test(r))return Number(r);if(r.startsWith("[")&&r.endsWith("]")){if(t>=32)throw new Nc;const n=r.slice(1,-1).trim();return n===""?[]:n.split(",").map(i=>zc(i,t+1))}return r}function eR(e){const t={},r=[],n=[],i=e.split(/\r?\n/);let s=0;for(;s<i.length;){const o=i[s];if(/^\s*$/.test(o)||/^\s*#/.test(o)){s++;continue}const a=/^([A-Za-z0-9_.-]+):\s*(.*)$/.exec(o);if(!a){r.push(o),s++;continue}const c=a[1],l=a[2];if(l===""){const u=[];let h=s+1;for(;h<i.length;){const d=i[h];if(/^\s*$/.test(d)||/^\s*#/.test(d)){h++;continue}const p=/^\s+-\s*(.*)$/.exec(d);if(p){try{u.push(zc(p[1]))}catch(f){if(!(f instanceof Nc))throw f;n.push(d)}h++;continue}if(/^\s+\S/.test(d)){r.push(d),h++;continue}break}u.length>0?t[c]=u:t[c]="",s=h;continue}if(l==="|"||l==="|-"||l===">"||l===">-"){const u=[];let h=null,d=s+1;for(;d<i.length;){const p=i[d];if(/^\s*$/.test(p)){u.push(""),d++;continue}const f=p.length-p.trimStart().length;if(f===0)break;h===null&&(h=f),u.push(p.slice(Math.min(h,f))),d++}for(;u.length>0&&u[u.length-1]==="";)u.pop();t[c]=l.startsWith("|")?u.join(`
96
90
  `):u.map(p=>p||`
97
- `).join(" "),s=d;continue}try{t[c]=Rl(l)}catch(u){if(!(u instanceof kl))throw u;n.push(o)}s++}return{data:t,unparsed:r,tooDeep:n}}function lC(e){const t=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(e);return t?{frontmatter:t[1],body:e.slice(t[0].length)}:null}function uC(e){return!Array.isArray(e)||e.some(t=>typeof t!="string")?null:e}async function cD(e){const{pluginName:t,directory:r,directoryName:n,skillFilePath:i,skillText:s,skillContentHash:o,files:a,issues:c}=e,l=`skill:${n}`,u={path:i,componentKey:l},h=lC(s);if(h===null)return c.error("SKILL_FRONTMATTER_MISSING",`skill "${n}" is missing YAML frontmatter in SKILL.md`,u),null;const{data:d,unparsed:p,tooDeep:f}=cC(h.frontmatter);for(const M of p)c.warn("SKILL_FRONTMATTER_UNPARSED",`skill "${n}": frontmatter line not interpreted: ${M.trim()}`,u);for(const M of f)c.error("VALUE_TOO_DEEP",`skill "${n}": frontmatter value nests deeper than 32 levels: ${M.trim().slice(0,80)}`,u);const v=d.name;if(typeof v!="string"||v.length===0)return c.error("SKILL_MISSING_NAME",`skill "${n}" is missing the required "name" field`,u),null;if(!aC(v))return c.error("SKILL_INVALID_NAME",`skill name "${v}" must be kebab-case ([a-z0-9-], 1-${p_} chars, no "--")`,u),null;v!==n&&c.warn("SKILL_NAME_MISMATCH",`skill name "${v}" does not match its directory "${n}"`,u);const m=d.description;if(typeof m!="string"||m.length===0)return c.error("SKILL_MISSING_DESCRIPTION",`skill "${n}" is missing the required "description" field`,u),null;if(m.length>gp)return c.error("SKILL_DESCRIPTION_TOO_LONG",`skill "${n}" description exceeds ${gp} characters`,u),null;let _;const w=d.allow_implicit_invocation;w!==void 0&&(typeof w!="boolean"?c.warn("SKILL_INVALID_METADATA",`skill "${n}": "allow_implicit_invocation" must be a boolean`,u):_=w);const S=[],T=d.mcp_tools;if(T!==void 0){const M=uC(T);if(M===null)c.warn("SKILL_INVALID_METADATA",`skill "${n}": "mcp_tools" must be a list of strings`,u);else for(const L of M)S.includes(L)||S.push(L)}const I=a.filter(M=>M.path!==i).map(M=>({path:M.path,relativePath:M.path.slice(r.length+1),size:M.size,contentHash:M.contentHash})),C=await X$(a.map(M=>({path:M.path.slice(r.length+1),contentHash:M.contentHash})));return{componentKey:l,directory:r,directoryName:n,skillFilePath:i,name:v,description:m,modelRef:`${t}/${v}`,instructions:h.body.trim(),frontmatter:d,frontmatterRaw:h.frontmatter,..._!==void 0?{allowImplicitInvocation:_}:{},mcpToolDependencies:S,supportingFiles:I,contentHash:o,aggregateHash:C}}var lD=new TextDecoder("utf-8",{fatal:!1}),dC=new Set(["access_token","refresh_token","id_token","client_secret","code","code_verifier","authorization_code","authorization","state","cookie","set_cookie","api_key"]),hC=[/^authorization$/i,/^proxy-authorization$/i,/^cookie$/i,/^set-cookie$/i,/^x-api-key$/i,/^api-key$/i,/^apikey$/i,/^x-auth-token$/i,/^x-csrf-token$/i,/^x-session-token$/i,/^x-access-token$/i,/^x-refresh-token$/i,/^x-client-secret$/i,/^x-credential$/i];function $u(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").toLowerCase()}var pC=["_type","_types","_endpoint","_endpoints","_supported","_method","_methods","_uri","_uris","_url","_urls","_alg","_algs","_values","_in"];function fC(e){return pC.some(t=>e.endsWith(t))}function Cu(e){return dC.has(e)?!0:fC(e)?!1:/(^|_)(token|secret|password|credential|cookie|auth)(_|$)/.test(e)||/(^|_)api_?key(_|$)/.test(e)}function vC(e){return Cu($u(e))}function gC(e){return Cu($u(e))||hC.some(t=>t.test(e))}function mC(e){return Cu($u(e))}function Pu(e){return typeof e!="string"||e.length<=8?"[redacted]":`${e.slice(0,4)}...[redacted]...${e.slice(-2)}`}var f_="client_secret|access_token|refresh_token|id_token|code_verifier|code|assertion|password|api[-_]?key|token|secret|state",v_=new RegExp(`(^|[^\\w-])((?:[\\w-]*[_-])?(?:${f_}))=[^&\\s"'<>]+`,"gi"),g_=`(?:(?:[\\w-]*[_-])?(?:${f_}))`,_C=new RegExp(`("${g_}"\\s*:\\s*)"(?:\\\\.|[^"\\\\])*"`,"gi"),yC=new RegExp(`("${g_}"\\s*:\\s*)"(?:\\\\[\\s\\S]?|[^"\\\\])*$`,"gi");var bC=new RegExp(`\\b((?:[\\w-]*[_-])?(?:client[-_]?secret|access[-_]?token|refresh[-_]?token|id[-_]?token|code[-_]?verifier))(\\s*[:=]\\s*)("(?:\\\\.|[^"\\\\])*"|[^&\\s"'<>,;]+)`,"gi");function m_(e){const t=e.replace(/[.,;:!?)\]}]+$/,"");return!/^[a-z]{1,20}$/.test(t)}function wC(e,t,r,n){return m_(n)?`${t}${r}[redacted]`:e}function Cr(e,t={}){const r=t.maxScanned??4e3,n=t.maxLength??500,i=e.length>r,s=(i?e.slice(0,r):e).replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/?#]*@/gi,"$1[redacted]@").replace(/(^|[\s(<"'])[^\s/@:]+:[^\s/]+@(?=[\w.-]+)/g,"$1[redacted]@").replace(bC,(o,a,c,l)=>`${a}${c}${l.startsWith('"')?'"[redacted]"':"[redacted]"}`).replace(v_,"$1$2=[redacted]").replace(/\b((?:proxy-)?authorization\s*[:=]\s*)(bearer|basic)\s+\S+/gi,"$1$2 [redacted]").replace(/\b(bearer|basic)(\s+)(\S+)/gi,wC).replace(_C,'$1"[redacted]"');return(i?s.replace(yC,'$1"[redacted]').replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/?#]*$/gi,"$1[redacted]"):s).slice(0,n)}function SC(e){if(!e)return;if(typeof e=="string"){const r=e.trim();if(!r)return;if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{const s=JSON.parse(r);if(typeof s=="object"&&s!==null&&!Array.isArray(s)){const o=Object.entries(s).flatMap(([a,c])=>typeof c=="string"?[[a,c]]:typeof c=="number"||typeof c=="boolean"?[[a,String(c)]]:[]);return o.length>0?Object.fromEntries(o):void 0}}catch{}const n=new URLSearchParams(r),i=Object.fromEntries(n.entries());return Object.keys(i).length>0?i:void 0}if(typeof e!="object"||e===null||Array.isArray(e))return;const t=Object.entries(e).flatMap(([r,n])=>typeof n=="string"?[[r,n]]:typeof n=="number"||typeof n=="boolean"?[[r,String(n)]]:[]);return t.length>0?Object.fromEntries(t):void 0}function EC(e){return Object.keys(e).every(t=>t.length<=64&&/^[A-Za-z0-9_.\-[\]]+$/.test(t))}var kC=3;function RC(e,t){return/^https?:\/\//i.test(e)?t>=kC?"[redacted]":Ou(e,t+1):e.replace(v_,"$1$2=[redacted]")}function Ou(e,t=0){try{const r=new URL(e);r.username="",r.password="";let n=!1;const i=new URLSearchParams;for(const[s,o]of r.searchParams.entries()){const a=mC(s)?"[redacted]":RC(o,t);n||=a!==o,i.append(s,a)}return n&&(r.search=i.toString()),r.hash&&(r.hash="#[redacted]"),r.toString()}catch{return Cr(e)}}function __(e){const t=e.trim();if(!t)return e;if(/^https?:\/\//i.test(t))return Ou(t);if(t.includes("=")||t.includes("&")||t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")){const r=SC(t);if(r&&EC(r))return Jt(r)}return Cr(t)}function Jt(e){return Array.isArray(e)?e.map(t=>Jt(t)):typeof e=="string"?__(e):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).map(([t,r])=>vC(t)?[t,Pu(r)]:[t,Jt(r)]))}function AC(e){const t=__(e);return typeof t=="string"?t:Pu(e)}function mp(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>gC(t)?[t,Pu(r)]:[t,AC(r)]))}function uD(e){const t=typeof e.callbackState=="string"&&e.callbackState.length>0;return e.issuedState?{statePresent:t,stateMatched:t&&e.callbackState===e.issuedState}:{statePresent:t}}function IC(e){return Al(e,[])}function Al(e,t){return Array.isArray(e)?e.map(r=>Al(r,t)):!e||typeof e!="object"?typeof e=="string"?TC(e):e:Object.fromEntries(Object.entries(e).map(([r,n])=>[r,CC(r,n,t)?"[REDACTED]":Al(n,[...t,r])]))}function TC(e){return e.replace(/\b(authorization|proxy-authorization|cookie|set-cookie)\s*:\s*[^\r\n]*/giu,(t,r)=>`${r}: [REDACTED]`).replace(/\bBearer(\s+)(\S+)/giu,$C).replace(/\b(access_token|refresh_token|client_secret|id_token|code|code_verifier|accessToken|refreshToken|clientSecret|idToken|codeVerifier)=([^&\s]+)/giu,"$1=[REDACTED]").replace(/(["']?(?:access_token|refresh_token|client_secret|id_token|code|code_verifier|accessToken|refreshToken|clientSecret|idToken|codeVerifier)["']?\s*:\s*["'])[^"']*(["'])/giu,"$1[REDACTED]$2")}function $C(e,t,r){return/^[A-Za-z_][A-Za-z0-9_-]*=/u.test(r)?e:m_(r)?`Bearer${t}[REDACTED]`:e}function CC(e,t,r){const n=e.toLowerCase().replace(/[^a-z0-9]/gu,"");return n==="code"?OC(t,r):n==="authorization"||n==="proxyauthorization"||n==="cookie"||n==="setcookie"?!0:(n==="codeverifier"||n==="accesstoken"||n.endsWith("accesstoken")||n==="refreshtoken"||n.endsWith("refreshtoken")||n==="clientsecret"||n.endsWith("clientsecret")||n==="idtoken"||n.endsWith("idtoken"))&&PC(t)||n==="apikey"||n==="xapikey"}function PC(e){return typeof e=="string"&&e.length>0}function OC(e,t){return t[t.length-1]==="error"||t[t.length-1]==="snapshotError"||typeof e!="string"||/^[A-Z0-9_:-]+$/u.test(e)?!1:e.length>0}var xC="ERA_NEGOTIATION_FAILED";function MC(e){return!!e&&typeof e=="object"&&e.code===xC}function LC(e){const t=new Set;let r=e;for(;MC(r)&&!t.has(r);){t.add(r);const n=r.data,i=(n&&typeof n=="object"?n.cause:void 0)??r.cause;if(i===void 0||i===r)break;r=i}return r}var At={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022,ResourceNotFound:-32602,ConnectionClosed:-32e3,RequestTimeout:-32001,UrlElicitationRequired:-32042},DC={HeaderMismatch:-32001,MissingRequiredClientCapability:-32003,UnsupportedProtocolVersion:-32004},NC="/troubleshooting/error-codes",_p={"jsonrpc/internal_error":"user_server","jsonrpc/invalid_response_format":"user_server","jsonrpc/parse_error":"ambiguous","jsonrpc/method_not_found":"ambiguous","jsonrpc/invalid_params":"ambiguous","jsonrpc/unsupported_protocol_version":"ambiguous","provider/invalid_tool_name":"ambiguous","oauth/well_known_unreachable":"ambiguous","transport/socket_hang_up":"ambiguous","transport/econnrefused":"user_config","transport/enotfound":"user_config","auth/http_401":"user_config","auth/http_403":"user_config","auth/missing_bearer":"user_config","auth/insufficient_scope":"user_config","auth/oauth_refresh_failed":"user_config","auth/consent_required":"user_config","oauth/invalid_client":"user_config","oauth/invalid_grant":"user_config","oauth/redirect_mismatch":"user_config","provider/auth_error":"user_config","provider/quota":"user_config","provider/mcpjam_limit":"user_config","provider/mcpjam_platform_budget":"user_config","account/suspended":"user_config","provider/mcpjam_limit_daily":"user_config","provider/mcpjam_limit_monthly":"user_config","provider/mcpjam_limit_insufficient":"user_config","provider/fallback_prohibited":"ambiguous","server/rate_limited":"user_server","jsonrpc/missing_required_client_capability":"user_config","jsonrpc/url_elicitation_required":"user_config","sdk/stateless_requires_http":"user_config","sdk/protocol_version_pin_unsupported":"user_config","sdk/not_yet_supported_in_stateless":"mcpjam","sdk/paginated_tool_header_discovery_unsupported":"mcpjam","provider/not_allowlisted":"mcpjam","oauth/no_bearer_challenge":"ambiguous","oauth/non_compliant_challenge":"user_server","auth/authorization_server_unreachable":"ambiguous","auth/proxy_rejected":"ambiguous","jsonrpc/connection_closed":"ambiguous","jsonrpc/request_timeout":"ambiguous","transport/etimedout":"ambiguous","transport/econnreset":"ambiguous","transport/eai_again":"ambiguous","transport/fetch_failed":"ambiguous","transport/undici":"ambiguous","jsonrpc/invalid_request":"ambiguous","jsonrpc/header_mismatch":"ambiguous","internal/unknown":"ambiguous","provider/empty_response":"ambiguous"};function fe(e,t,r,n,i,s,o="error"){return{slug:e,title:t,oneLine:r,likelyCauses:n,nextSteps:i,docsAnchor:`${NC}#${s}`,severity:o,..._p[e]?{origin:_p[e]}:{}}}var Il={"jsonrpc/parse_error":fe("jsonrpc/parse_error","Parse error (-32700)","The MCP wire contained JSON the inspector could not parse as JSON-RPC.",["The server emitted invalid JSON on the response channel.","A proxy or middleware mangled the response body.","Server emitted log output on stdout instead of stderr (STDIO transport).","The inspector sent malformed JSON and the server returned a parse error."],["Check the server's stdout/stderr for unintended log output.","Use the inspector's Traffic Log to inspect the raw response."],"parse-error"),"jsonrpc/invalid_request":fe("jsonrpc/invalid_request","Invalid request (-32600)","The server rejected the payload as not a well-formed JSON-RPC request.",["Client sent a request shape the server's MCP runtime does not accept.","Outdated server SDK that disagrees with the protocol version advertised."],["Verify the negotiated MCP protocol version.","Update the server's MCP SDK."],"invalid-request"),"jsonrpc/method_not_found":fe("jsonrpc/method_not_found","Method not found (-32601)","The server does not implement the JSON-RPC method that was called.",["The server hasn't implemented the requested MCP method.","Client and server are on incompatible MCP protocol versions.","The capability you expected was not advertised in `initialize`."],["Check the server's advertised capabilities in the connection info.","Confirm the protocol version negotiated at `initialize`."],"method-not-found"),"jsonrpc/invalid_params":fe("jsonrpc/invalid_params","Invalid params (-32602)","The server rejected the request parameters.",["Required field is missing from the call.","Field type does not match the tool's input schema.","Server-side validator is stricter than the published schema."],["Re-check the tool's input schema in the Tools tab.","Compare your call payload against the schema in the inspector."],"invalid-params"),"jsonrpc/internal_error":fe("jsonrpc/internal_error","Internal error (-32603)","The server hit an unexpected error while handling the request.",["Unhandled exception inside the server's tool/resource/prompt handler.","Downstream dependency (database, API) failed during the call."],["Check the server's logs around the time of the error.","Retry the request once the server is healthy."],"internal-error"),"jsonrpc/invalid_response_format":fe("jsonrpc/invalid_response_format","Invalid response format (-32603)","The server replied, but the result was not a valid MCP tool, resource, or prompt payload.",["The handler returned a string or custom object instead of the MCP result shape (usually `{ content: [...] }`)."],["Inspect the result in the Traffic Log and compare it to the MCP result shape.",'Return `{ content: [{ type: "text", text: "..." }] }` from the handler, or the matching resource/prompt result.'],"invalid-response-format"),"jsonrpc/connection_closed":fe("jsonrpc/connection_closed","Connection closed (-32000)","The underlying transport closed before the response could be delivered.",["STDIO server process exited or crashed mid-request.","HTTP server dropped the streaming connection.","Network blip between the inspector and the server."],["Restart the server and reconnect.","Check the server logs for a crash or exit message."],"connection-closed"),"jsonrpc/request_timeout":fe("jsonrpc/request_timeout","Request timed out (-32001)","The server did not respond within the configured request timeout.",["Server is overloaded or stuck on the operation.","Long-running tool call exceeds the inspector's per-request timeout.","Network latency between client and server."],["Increase the per-server request timeout in the Servers tab.","Use MCP `tasks/*` for operations that legitimately run long."],"request-timeout"),"jsonrpc/header_mismatch":fe("jsonrpc/header_mismatch","Protocol header mismatch (-32020)","The server returned an `MCP-Protocol-Version` header that does not match what the client negotiated.",["Server is enforcing a different protocol version than the one negotiated at `initialize`.","A proxy stripped or rewrote the `MCP-Protocol-Version` header."],["Verify the server's protocol-version pinning in the connection settings.","If you set an explicit protocol version per server, ensure it matches what the server advertises."],"header-mismatch"),"jsonrpc/unsupported_protocol_version":fe("jsonrpc/unsupported_protocol_version","Unsupported protocol version (-32022)","The server does not support any protocol version this inspector offered.",["Server pinned to a newer MCP draft your inspector build does not understand.","Server pinned to a legacy version this build dropped support for."],["Update the inspector to a newer build.","Check the supported versions list in the server's `server/discover` result (modern) or `initialize` response (legacy)."],"unsupported-protocol-version"),"jsonrpc/missing_required_client_capability":fe("jsonrpc/missing_required_client_capability","Missing required client capability (-32021)","The server refused the request because the client did not advertise a capability the operation requires.",["A server-initiated input request (elicitation, sampling) needs a client capability MCPJam did not declare.","The connection advertised a capability set the server considers insufficient for this operation."],["Enable the required client capability in the connection's Client settings.","Check the server's documentation for which client capabilities it requires."],"missing-required-client-capability"),"jsonrpc/url_elicitation_required":fe("jsonrpc/url_elicitation_required","URL elicitation required (-32042)","The server needs the user to visit an external URL to complete the operation.",["Server requested a URL elicitation (OAuth, payment, confirmation).","Operation cannot proceed until the user opens the URL in a browser."],["Open the elicited URL and complete the flow.","Re-issue the request after the external step completes."],"url-elicitation-required","warning"),"transport/econnrefused":fe("transport/econnrefused","Connection refused","Nothing is listening on the host and port the server URL points at.",["Server isn't running.","Port number is wrong in the server URL.","Server is bound to a different interface (e.g. only `127.0.0.1` but you're connecting via the LAN IP)."],["Start the server.","Double-check the URL's host and port.","For Docker/containers, confirm the port is published to your host."],"econnrefused"),"transport/econnreset":fe("transport/econnreset","Connection reset","The remote side closed the TCP connection abruptly.",["Server process crashed mid-request.","Intermediate proxy or load balancer dropped the connection.","Server hit an OS-level resource limit."],["Inspect the server logs for a crash.","Retry the request."],"econnreset"),"transport/etimedout":fe("transport/etimedout","Connection timed out","The OS-level TCP connection attempt did not complete in time.",["Wrong host/port in the server URL.","Firewall is silently dropping packets.","Server is overloaded and never accepted the connection."],["Verify the URL is reachable from your machine (e.g. `curl`).","Check firewall / VPN rules."],"etimedout"),"transport/enotfound":fe("transport/enotfound","Host not found","DNS lookup failed for the server's hostname.",["Hostname is misspelled in the URL.","DNS resolver is misconfigured.","You're offline."],["Confirm the hostname in the URL is correct.","Try resolving the host with `nslookup` or `dig`."],"enotfound"),"transport/eai_again":fe("transport/eai_again","Temporary DNS failure","DNS resolution failed with a transient error.",["Local DNS resolver is overloaded or restarting.","Upstream DNS server is briefly unavailable."],["Wait a few seconds and retry.","Switch to a different DNS resolver if this persists."],"eai-again","warning"),"transport/undici":fe("transport/undici","HTTP transport error","The underlying HTTP client (undici / fetch) reported a low-level transport failure.",["Server closed the connection mid-response.","TLS handshake failed.","Socket-level error during streaming."],["Inspect the Traffic Log for the failed request.","Verify the server's TLS certificate is valid."],"undici-transport-error"),"transport/fetch_failed":fe("transport/fetch_failed","Fetch failed","The HTTP request never produced a response.",["Server is unreachable (offline, wrong URL, blocked by firewall).","TLS handshake failed (self-signed cert, expired cert).","Mixed-content block (HTTPS page calling HTTP endpoint in browser)."],["Open the URL in a browser to confirm it loads.","If self-signed, install the certificate or switch to a trusted one."],"fetch-failed"),"transport/socket_hang_up":fe("transport/socket_hang_up","Socket hang up","The server closed the connection without sending a response.",["Server crashed or restarted during the request.","Reverse proxy timed the request out."],["Retry the request.","Check server-side logs for the crash."],"socket-hang-up"),"auth/http_401":fe("auth/http_401","Unauthorized (401)","The server requires authentication that wasn't provided or is no longer valid.",["Missing or expired bearer token.","OAuth access token expired and refresh failed.","Server changed its required authentication scheme."],["Re-authenticate using the Reconnect button on the server card.","If using OAuth, run through the OAuth flow again from Servers."],"unauthorized-401"),"auth/http_403":fe("auth/http_403","Forbidden (403)","You authenticated successfully but lack permission for the operation.",["OAuth scopes granted don't cover the requested operation.","Server-side ACL blocks this account."],["Re-run OAuth and request the additional scopes if the server allows.","Ask the server admin to grant the necessary permissions."],"forbidden-403"),"auth/oauth_refresh_failed":fe("auth/oauth_refresh_failed","OAuth token refresh failed","An expired OAuth access token could not be refreshed.",["Refresh token was revoked.","Refresh token expired.","Server returned `invalid_grant` to the refresh attempt."],["Click Reconnect on the server card to run a fresh OAuth flow."],"oauth-refresh-failed"),"auth/consent_required":fe("auth/consent_required","Sign-in required","This server needs your permission before it can connect.",["Reconnect ran without opening the sign-in prompt, so no OAuth token exists for this server yet."],["Click Reconnect and approve the request in the window that opens."],"consent-required","warning"),"auth/missing_bearer":fe("auth/missing_bearer","Missing bearer token","The API call did not include the required `Authorization: Bearer ...` header.",["Inspector session expired.","Sign-in token failed to attach to the request."],["Refresh the page and sign in again."],"missing-bearer"),"auth/insufficient_scope":fe("auth/insufficient_scope","Insufficient scope (403)","The server reported insufficient_scope: the grant does not cover this operation.",["The authorization did not request the scopes the server now requires.","The server added a scope requirement after the grant was issued."],["Re-authorize and grant the scopes the server names in its challenge."],"insufficient-scope"),"auth/authorization_server_unreachable":fe("auth/authorization_server_unreachable","Authorization server unreachable","The stored token could not be refreshed because the authorization server was unreachable or did not return a usable response.",["The authorization server is down or slow.","The refresh request could not leave the network it was made from."],["Retry in a minute; if it persists, check the authorization server's status.","Reconnect the server to obtain a fresh token once the authorization server is reachable."],"authorization-server-unreachable","warning"),"auth/proxy_rejected":fe("auth/proxy_rejected","HTML access rejection (403)","The response was HTTP 403 with an HTML content type and no authentication challenge; a proxy or firewall may be involved.",["An IP allowlist or WAF blocks the address the request came from.","A corporate proxy or SSO portal intercepted the request."],["Allow MCPJam's egress addresses, or the address you connect from, on the server's firewall.","Open the server URL in a browser from the same network to see what answers."],"proxy-rejected"),"oauth/no_bearer_challenge":fe("oauth/no_bearer_challenge","401 without a Bearer challenge","The response was HTTP 401 without a Bearer challenge. This response did not explain how to authorize.",["The server or an intermediary omitted a Bearer challenge.","The server expects a static API key and does not implement OAuth."],["Check OAuth discovery, including the well-known metadata fallback supported by newer MCP versions.","If the server expects an API key, configure it as a header on the server instead of OAuth."],"no-bearer-challenge"),"oauth/non_compliant_challenge":fe("oauth/non_compliant_challenge","Bearer challenge on the wrong status","The response reported invalid_token with HTTP 403; MCP requires HTTP 401 for an invalid or expired token.",["The server maps every authorization failure to 403.","A gateway rewrites the server's 401 to 403."],["Re-authorize the server to replace the rejected token.","Report the status mismatch to the server author; invalid-token recovery expects HTTP 401."],"non-compliant-challenge","warning"),"oauth/invalid_grant":fe("oauth/invalid_grant","OAuth: invalid grant","The OAuth server rejected the authorization code or refresh token.",["Authorization code was already redeemed.","Refresh token was revoked.","Authorization code expired (typical lifetime ~60s)."],["Start the OAuth flow again from the server card."],"oauth-invalid-grant"),"oauth/invalid_client":fe("oauth/invalid_client","OAuth: invalid client","The OAuth server does not recognize the client credentials.",["Client was deleted on the authorization server.","Dynamic registration cache is stale.","`client_id` was rotated server-side."],["Re-register the client (Reconnect from the server card triggers DCR if supported)."],"oauth-invalid-client"),"oauth/redirect_mismatch":fe("oauth/redirect_mismatch","OAuth: redirect URI mismatch","The redirect URI in the request does not match the one registered with the OAuth server.",["Authorization server requires the inspector's callback URL to be registered explicitly.","Server's allow-list is wrong."],["Add the inspector's callback URL to the OAuth server's allowed redirects.","Verify the inspector's base URL hasn't changed."],"oauth-redirect-mismatch"),"oauth/well_known_unreachable":fe("oauth/well_known_unreachable","OAuth metadata unreachable","The OAuth `.well-known` discovery endpoint could not be fetched.",["Authorization server is down.","Wrong issuer URL.","CORS blocks the discovery request from the browser."],["Confirm the issuer URL in the server config.","Open the `.well-known/openid-configuration` (or `oauth-authorization-server`) URL in a browser."],"oauth-well-known-unreachable"),"sdk/not_yet_supported_in_stateless":fe("sdk/not_yet_supported_in_stateless","Operation not supported on stateless transport","The inspector's stateless HTTP transport does not yet implement this MCP operation.",["Operation requires a server-initiated channel (subscriptions, MRTR) the stateless preview transport hasn't wired up yet."],["Switch the server to the legacy stateful transport in its protocol-mode toggle."],"not-yet-supported-in-stateless","warning"),"sdk/stateless_requires_http":fe("sdk/stateless_requires_http","Stateless transport requires HTTP","Stateless mode can only be used with an HTTP-transport server, not STDIO.",["You enabled the stateless protocol toggle on a stdio server."],["Disable the stateless toggle for stdio servers."],"stateless-requires-http"),"sdk/protocol_version_pin_unsupported":fe("sdk/protocol_version_pin_unsupported","Server doesn't support the pinned protocol version","This connection is pinned to one MCP protocol version, and the server does not offer it.",["The client profile you're emulating pins a protocol version this server hasn't adopted — a host set to the latest revision against a server that still speaks a 2025 one.","A per-server protocol override left pinned to a version the server dropped or never shipped."],["Set the protocol version to Automatic to negotiate whatever the server does support.","Or pick the version the server advertises — `server/discover` (modern) or the `initialize` response (legacy) lists them."],"protocol-version-pin-unsupported"),"sdk/paginated_tool_header_discovery_unsupported":fe("sdk/paginated_tool_header_discovery_unsupported","Paginated tool discovery not supported with header overrides","Paginated tools discovery cannot run alongside per-request header overrides on this transport.",["Conflicting combination of progressive tool discovery + per-server header overrides."],["Disable progressive tool discovery for this server, or move headers into the server config."],"paginated-tool-and-header-discovery-unsupported","warning"),"provider/invalid_tool_name":fe("provider/invalid_tool_name","Provider rejected the tool name","An LLM provider rejected a tool name (Anthropic's strict tool-name validator is the most common source).",["Tool name contains characters or length the provider does not allow.","Two attached servers expose tools whose namespaced names collide after sanitization."],["Rename the offending tool on the server.","Detach one of the colliding servers from the chat surface."],"provider-invalid-tool-name"),"provider/auth_error":fe("provider/auth_error","Provider authentication error","Your LLM provider rejected the API key for this request.",["Key is missing.","Key is invalid or revoked.","Key is for a different environment (project, region)."],["Add or update your API key under Settings → LLM Providers.","Verify the key in the provider's dashboard."],"provider-auth-error"),"provider/not_allowlisted":fe("provider/not_allowlisted","Model provider not enabled on MCPJam","This model's provider is not enabled on MCPJam's hosted AI gateway, so MCPJam can't run it. Retrying or changing your API key won't help.",["MCPJam's hosted gateway does not have this model's provider on its provider allowlist."],["Choose a model from a different provider.","Add your own key for this provider under Settings → LLM Providers (BYOK) to run the model on your key instead of MCPJam's gateway."],"provider-not-allowlisted","warning"),"provider/mcpjam_limit_daily":fe("provider/mcpjam_limit_daily","Out of MCPJam credits","Your organization's daily MCPJam credits are used up. They reset tomorrow.",["Chat, evals and swarm generation all draw on one daily bucket, shared across the organization."],["On Free, upgrade for a larger monthly allowance and access to top-ups. On eligible paid plans, buy shared credits to continue testing.","Wait for the daily allowance to reset.","Your own API key covers supported model inference. MCPJam features can still require credits; Swarm generation and persona turns always do."],"out-of-mcpjam-credits","warning"),"provider/mcpjam_limit_monthly":fe("provider/mcpjam_limit_monthly","Out of MCPJam credits","Your organization's available MCPJam credits are used up for this billing period.",["Paid plans include a monthly credit allowance shared across the organization. It renews with the billing period."],["On Free, upgrade for a larger monthly allowance and access to top-ups. On eligible paid plans, buy shared credits to continue testing.","Wait for the billing period to renew.","Your own API key covers supported model inference. MCPJam features can still require credits; Swarm generation and persona turns always do."],"out-of-mcpjam-credits","warning"),"provider/mcpjam_limit_insufficient":fe("provider/mcpjam_limit_insufficient","Not enough MCPJam credits","Your organization has MCPJam credits left, but not enough for this request.",["MCPJam reserves a request's worst-case cost before it runs, so an expensive model or a long conversation can need more than the remaining balance."],["Try a cheaper model or a shorter conversation.","On Free, upgrade for a larger monthly allowance and access to top-ups. On eligible paid plans, buy shared credits to continue testing.","Your own API key covers supported model inference. MCPJam features can still require credits; Swarm generation and persona turns always do."],"out-of-mcpjam-credits","warning"),"provider/fallback_prohibited":fe("provider/fallback_prohibited","Provider failed, fallback not permitted","The model's provider failed and this model selection does not allow a fallback provider, so the request stopped rather than running somewhere other than where it was asked to.",[`The provider serving this model returned an error or was unreachable, and the selection's fallback policy is "none" — the default for evals, swarms and judges, so a result never silently comes from a different provider.`],["Retry — the provider's failure may be temporary.","Pick a different model, or a model on a connection you control."],"provider-failed-fallback-not-permitted","warning"),"provider/mcpjam_platform_budget":fe("provider/mcpjam_platform_budget","MCPJam shared free allowance unavailable","The shared free allowance is exhausted or temporarily paused.",["This limit applies across free usage, not just your account."],["Wait until the supplied reset time, if present.","Use purchased credits or your own provider key for chat."],"mcpjam-platform-budget","warning"),"account/suspended":fe("account/suspended","Account suspended","This account has been suspended by MCPJam.",["Support has suspended this account."],["Contact founders@mcpjam.com for support."],"account-suspended","warning"),"provider/mcpjam_limit":fe("provider/mcpjam_limit","Out of MCPJam credits","Your organization is out of MCPJam credits, so this request could not continue.",["Chat, evals and swarm generation all draw on the same MCPJam allowance."],["On Free, upgrade for a larger monthly allowance and access to top-ups. On eligible paid plans, buy shared credits to continue testing.","Wait for the allowance to reset.","Your own API key covers supported model inference. MCPJam features can still require credits; Swarm generation and persona turns always do."],"out-of-mcpjam-credits","warning"),"provider/quota":fe("provider/quota","Provider quota / rate limit","Your LLM provider rejected the request because you hit a rate limit or quota.",["Daily/monthly quota exhausted.","Per-minute rate limit exceeded.","Free tier limits hit."],["Wait for the limit window to reset.","Upgrade your provider plan.","Switch to a different provider in Settings."],"provider-quota","warning"),"server/rate_limited":fe("server/rate_limited","MCP server rate limit","The MCP server rejected the request with HTTP 429 (too many requests).",["The server enforces its own per-client rate limit.","An upstream API the server calls is throttling it.","A burst of tool calls exceeded what the server allows."],["Wait for the server's limit window to reset, then retry.","Reduce concurrency or the number of tool calls in the run.","Check the server's own rate-limit documentation or logs."],"server-rate-limited","warning"),"provider/empty_response":fe("provider/empty_response","Model returned no response","The model returned no response, so the turn could not complete.",["The model request ended without usable content."],["Rerun the affected cases. If this recurs, report it with the run details."],"model-empty-response"),"internal/unknown":fe("internal/unknown","Unknown error","An error occurred that the inspector could not classify.",["Unhandled error path.","New error class the inspector hasn't been taught about yet."],["Open the details panel and copy the raw message.","File an issue with the raw message so we can add it to the catalog."],"unknown-error")};function y_(e,t=0){if(!e||typeof e!="object"||t>3)return;const r=e.code,n=typeof r=="string"?r:void 0;if(n!==void 0&&zC(n))return n;const i=e.cause;if(i!==void 0&&i!==e){const s=y_(i,t+1);if(s!==void 0)return s}return n}function zC(e){return UC.has(e)||e.startsWith("UND_ERR_")}var UC=new Set(["ECONNREFUSED","ECONNRESET","EAI_AGAIN","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET"]);function FC(e){return!!e&&typeof e=="object"&&typeof e.slug=="string"&&typeof e.title=="string"&&typeof e.oneLine=="string"&&typeof e.docsAnchor=="string"&&typeof e.severity=="string"&&typeof e.rawMessage=="string"&&Array.isArray(e.likelyCauses)&&Array.isArray(e.nextSteps)}function si(e){const t=IC(e);return typeof t=="string"?t:String(e)}function qC(e){if(!e||typeof e!="object")return;const t=e.name;return typeof t=="string"?t:void 0}function xu(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function b_(e){if(!e||typeof e!="object")return;const t=e.code;if(typeof t=="number"&&Number.isFinite(t))return t;const r=e.error;if(r&&typeof r=="object"){const n=r.code;if(typeof n=="number"&&Number.isFinite(n))return n}}function jC(e){if(!e||typeof e!="object")return;const t=e.code;return typeof t=="string"?t:void 0}function HC(e){if(!e||typeof e!="object")return;const t=e.statusCode;if(typeof t=="number")return t;const r=e.status;if(typeof r=="number")return r}function w_(e){return Il[e]??Il["internal/unknown"]}var VC=200;function Tl(e){const t=e.replace(/\s+/g," ").trim();return t.length<=VC?t:`${t.slice(0,199).trimEnd()}…`}function S_(e,t,r){if(t==="provider/mcpjam_limit_insufficient"){const n=Lu(r);return n?{...e,oneLine:n}:e}return t!=="internal/unknown"||!r?e:{...e,oneLine:Tl(r)}}var BC=["Backend step returned no content (stream error or empty response)","Backend step returned no messages (stream error or empty response)"];function GC(e){if(/NotYetSupportedInStateless/i.test(e))return"sdk/not_yet_supported_in_stateless";if(/StatelessRequiresHttpTransport/i.test(e))return"sdk/stateless_requires_http";if(/PaginatedToolHeaderDiscoveryUnsupported/i.test(e))return"sdk/paginated_tool_header_discovery_unsupported";if(/which this client is pinned to/i.test(e))return"sdk/protocol_version_pin_unsupported"}var WC={[At.ParseError]:"jsonrpc/parse_error",[At.InvalidRequest]:"jsonrpc/invalid_request",[At.MethodNotFound]:"jsonrpc/method_not_found",[At.InvalidParams]:"jsonrpc/invalid_params",[At.InternalError]:"jsonrpc/internal_error",[At.ConnectionClosed]:"jsonrpc/connection_closed",[At.HeaderMismatch]:"jsonrpc/header_mismatch",[At.MissingRequiredClientCapability]:"jsonrpc/missing_required_client_capability",[At.UnsupportedProtocolVersion]:"jsonrpc/unsupported_protocol_version",[DC.UnsupportedProtocolVersion]:"jsonrpc/unsupported_protocol_version",[At.UrlElicitationRequired]:"jsonrpc/url_elicitation_required"};function ZC(e){return/header[^a-z]*mismatch/i.test(e)||/MCP-Protocol-Version/i.test(e)?"jsonrpc/header_mismatch":"jsonrpc/request_timeout"}var JC=/^(?:MCP error -32603:\s*)?invalid response format$/i;function E_(e){return JC.test(e.trim())}function KC(e){return E_(e)?"jsonrpc/invalid_response_format":"jsonrpc/internal_error"}function k_(e){const t=e.toUpperCase();switch(t){case"ECONNREFUSED":return"transport/econnrefused";case"ECONNRESET":return"transport/econnreset";case"ETIMEDOUT":return"transport/etimedout";case"ENOTFOUND":return"transport/enotfound";case"EAI_AGAIN":return"transport/eai_again";default:return t.startsWith("UND_ERR_")?"transport/undici":void 0}}function YC(e){const t=e.toLowerCase();if(/\bsocket\s+hang\s+up\b/i.test(e))return"transport/socket_hang_up";for(const r of e.matchAll(/\b(E[A-Z]{2,}(?:_[A-Z]+)*|UND_ERR_[A-Z_]+)\b/g)){const n=k_(r[1]);if(n)return n}if(/\bfetch\s+failed\b/i.test(e))return"transport/fetch_failed";if(/\bgetaddrinfo\b/i.test(e))return"transport/enotfound";if(/\bconnection\s+(?:refused|reset|closed|timed?\s*out|aborted|error|failed)\b/i.test(e)||/\b(?:failed|unable)\s+to\s+connect\b/i.test(e))return t.includes("refused")?"transport/econnrefused":t.includes("reset")?"transport/econnreset":t.includes("timed out")||t.includes("timeout")?"transport/etimedout":t.includes("closed")?"jsonrpc/connection_closed":"transport/fetch_failed";if(/Invalid tool name/i.test(e))return"provider/invalid_tool_name";if(E_(e))return"jsonrpc/invalid_response_format"}function XC(e){const t=eP(e);if(!t)return;const r=QC(e)??(typeof t.error=="string"?t.error:typeof t.error_code=="string"?t.error_code:void 0);if(r)switch(r.toLowerCase()){case"invalid_grant":return"oauth/invalid_grant";case"invalid_client":return"oauth/invalid_client";case"invalid_redirect_uri":case"redirect_uri_mismatch":return"oauth/redirect_mismatch";default:return}}function QC(e){if(!e||typeof e!="object"||e.name!=="OAuthResponseError")return;const t=e.code;return typeof t=="string"&&t?t:void 0}function eP(e){if(!e||typeof e!="object")return;const t="body"in e?e.body:"data"in e?e.data:e;if(!(!t||typeof t!="object"))return t}function R_(e){if(!(e instanceof Error))return;const t=e.cause;if(!t||typeof t!="object")return;const r=typeof t.name=="string"?t.name:"Error",n=typeof t.message=="string"?si(t.message):"";if(n)return{name:r,message:n}}var yp={AUTH_ERROR:"auth/http_401",OAUTH_REQUIRED:"auth/http_401"};function tP(e){const t=qC(e);if(t==="MCPAuthError"||t==="UnauthorizedError")return"auth/http_401";const r=jC(e);if(r&&yp[r])return yp[r]}function bp(e){if(e===401)return"auth/http_401";if(e===403)return"auth/http_403";if(e===429)return"provider/quota"}function rP(e){if(/(?:^|[^\w.:])401\b/.test(e))return"auth/http_401";if(/(?:^|[^\w.:])403\b/.test(e))return"auth/http_403";if(/(?:^|[^\w.:])429\b|too many requests/i.test(e))return"provider/quota"}function nP(e){const t=xu(e),r=e&&typeof e=="object"?e:null,n=r?.data?.code??r?.code;if(n==="platform_free_budget_exhausted")return{slug:"provider/mcpjam_platform_budget",rawCode:n};if(n==="account_suspended")return{slug:"account/suspended",rawCode:n};if(BC.some(p=>t.startsWith(p)))return{slug:"provider/empty_response"};const i=GC(t);if(i)return{slug:i};const s=tP(e);if(s)return{slug:s};const o=b_(e);if(o!==void 0){if(o===-32001)return{slug:ZC(t),rawCode:o};if(o===At.InternalError)return{slug:KC(t),rawCode:o};const p=WC[o];if(p)return{slug:p,rawCode:o};const f=bp(o);if(f)return{slug:f,rawCode:o}}const a=y_(e);if(a){const p=k_(a);if(p)return{slug:p,rawCode:a}}if(/missing\s+(?:or\s+invalid\s+)?bearer/i.test(t)||/bearer\s+token\s+(?:is\s+)?required/i.test(t))return{slug:"auth/missing_bearer"};if(Lu(t))return{slug:"provider/mcpjam_limit_insufficient"};if(/\bout of MCPJam credits\b/i.test(t))return{slug:"provider/mcpjam_limit"};const c=pP(t);if(c)return{slug:c};const l=Mu(e);if(l!==void 0){const p=bp(l);if(p)return{slug:p,rawCode:l}}const u=XC(e);if(u)return{slug:u};const h=rP(t);if(h)return{slug:h};if(/refresh\s+token/i.test(t)&&/(failed|invalid|expired|revoked)/i.test(t))return{slug:"auth/oauth_refresh_failed"};if(/consent\s+is\s+required/i.test(t)||/^\s*reauthenticate\b[\s\S]*\bto\s+continue\b/i.test(t))return{slug:"auth/consent_required"};const d=YC(t);return d?{slug:d}:/well[-_]?known/i.test(t)&&/(unreachable|fail|404)/i.test(t)?{slug:"oauth/well_known_unreachable"}:{slug:"internal/unknown"}}var iP=new Set(["auth/http_401","auth/http_403","auth/missing_bearer","auth/oauth_refresh_failed","auth/authorization_server_unreachable","oauth/invalid_client","oauth/invalid_grant","provider/auth_error","provider/quota"]);function Mu(e){const t=new Set;let r=e;for(let n=0;n<5&&r&&typeof r=="object"&&!t.has(r);n++){t.add(r);const i=HC(r);if(i!==void 0)return i;const s=b_(r);if(s!==void 0&&s>=100&&s<=599)return s;if(r.name==="UnauthorizedError")return 401;const o=LC(r);r=o!==r?o:r.cause}}function sP(e,t){if(!t)return;if(t.refresh?.outcome==="authorization_server_unreachable")return"auth/authorization_server_unreachable";if(t.refresh?.outcome==="token_rejected")return"auth/oauth_refresh_failed";const r=t.challenge;if(!r)return;const n=Mu(e);if(n===401&&r.scheme!=="bearer")return"oauth/no_bearer_challenge";if(n===401)return"auth/http_401";if(n===403)return r.scheme==="bearer"&&r.error==="insufficient_scope"?"auth/insufficient_scope":r.scheme==="bearer"&&r.error==="invalid_token"?"oauth/non_compliant_challenge":r.scheme==="none"&&r.bodyKind==="html"?"auth/proxy_rejected":"auth/http_403"}function oP(e,t,r){if(t==="auth/insufficient_scope"&&r?.challenge?.scopes?.length)return{...e,oneLine:Tl(si(`${e.oneLine} Required scopes: ${r.challenge.scopes.join(" ")}.`))};const n=r?.challenge?.error;return!n||t!=="auth/http_401"&&t!=="auth/http_403"?e:{...e,oneLine:Tl(si(`${e.oneLine} The server reported \`${n}\`.`))}}var aP=new Set(["user_server","user_config","mcpjam","ambiguous"]);function cP(e){return typeof e=="string"&&aP.has(e)}function lP(e){const t=e?.origin;return cP(t)?t:"ambiguous"}function A_(e,t,r){return r?.credentialOwner==="mcpjam"&&iP.has(t)?{...e,origin:"mcpjam"}:e}function uP(e,t){return e==="provider/quota"&&t?.surface==="mcpServer"?"server/rate_limited":e}function dP(e,t){try{const r=si(xu(e)),n=sP(e,t),i=n?{slug:n}:nP(e),s=uP(i.slug,t),o=i.rawCode??(n?Mu(e):void 0),a=A_(oP(S_(w_(s),s,r),s,t),s,t),c=R_(e);return{...a,rawMessage:r,...o!==void 0?{rawCode:o}:{},...c?{cause:c}:{}}}catch{return I_(e,"Unknown")}}function dD(e,t,r){try{const n=A_(w_(e),e,r),i=t!==void 0?si(xu(t)):"",s=R_(t);return{...n,rawMessage:i,...s?{cause:s}:{}}}catch{return I_(t,"")}}function I_(e,t){const r=Il["internal/unknown"];let n=t;try{n=si(e instanceof Error?e.message:String(e??t))}catch{n=t}return{...S_(r,"internal/unknown",n),rawMessage:n}}var hP=/\bThis request needs about (\d+) MCPJam credits; your organization has (\d+) left[^.]{0,40}\./i;function Lu(e){const t=hP.exec(e);if(!t)return;const r=Number(t[1]),n=Number(t[2]);return Number.isSafeInteger(r)&&Number.isSafeInteger(n)&&n>0&&r>n?t[0]:void 0}function pP(e){if(Lu(e))return"provider/mcpjam_limit_insufficient";const t=/\b(daily|monthly)\s+mcpjam[\w\s-]{0,40}model limit/i.exec(e);if(t)return t[1].toLowerCase()==="monthly"?"provider/mcpjam_limit_monthly":"provider/mcpjam_limit_daily";if(/mcpjam[\w\s-]{0,40}model limit/i.test(e))return"provider/mcpjam_limit"}var $l="[A-Za-z0-9!#$%&'*+.^_`|~-]+";function fP(e){const t={},r=new RegExp(`(${$l})\\s*=\\s*(?:"((?:\\\\.|[^"\\\\])*)"|([^,\\s]+))`,"g");for(let n=r.exec(e);n;n=r.exec(e)){const i=n[2];t[n[1].toLowerCase()]=i!==void 0?i.replace(/\\([\s\S])/g,"$1"):n[3]??""}return t}function ur(e){return T_(e)[0]??{}}function Du(e){if(!e)return;const t=e.split(/\s+/).map(r=>r.trim()).filter(Boolean);return t.length>0?Array.from(new Set(t)):void 0}function vP(e,t){const r=[],n=new Set;for(const i of[...e??[],...t??[]]){const s=i?.trim();!s||n.has(s)||(n.add(s),r.push(s))}return r}function T_(e){if(!e)return[];const t=[];let r="",n=!1;for(let a=0;a<e.length;a++){const c=e[a];n&&c==="\\"&&a+1<e.length?(r+=c+e[a+1],a++):c==='"'?(n=!n,r+=c):c===","&&!n?(t.push(r),r=""):r+=c}t.push(r);const i=[],s=new RegExp(`^(${$l})\\s+(?!\\s*=)(.+)$`,"s"),o=new RegExp(`^(${$l})$`);for(const a of t){const c=a.trim();if(!c)continue;const l=s.exec(c),u=l?null:o.exec(c);l?i.push({scheme:l[1].toLowerCase(),params:[l[2]]}):u?i.push({scheme:u[1].toLowerCase(),params:[]}):i.length>0&&i[i.length-1].params.push(c)}return i.filter(a=>a.scheme==="bearer").map(a=>fP(a.params.join(", ")))}function gP(e){return T_(e).length>0}var zr=class extends Error{status;constructor(e,t){super(e),this.name="UnexpectedProbeStatusError",this.status=t}},$_="MCP server returned HTTP ";function hD(e){return e.startsWith($_)}function vs(e){if(e.status===401)return{kind:"challenged",specCompliant:!0};if(e.status===200)return{kind:"anonymous_allowed"};if(e.status===403&&gP(e.wwwAuthenticateHeader))return{kind:"challenged",specCompliant:!1};const t=e.serverMessage||e.statusText,r=`${$_}${e.status}${t?` ${t}`:""}`;return e.status===403?e.wwwAuthenticateHeader?.trim()?{kind:"unexpected",message:`${r}, and its WWW-Authenticate header offers no Bearer challenge. MCP OAuth has nothing to discover from without one, so the flow cannot continue against this server.`}:{kind:"unexpected",message:`${r} with no WWW-Authenticate challenge. MCP requires 401 with a WWW-Authenticate header to begin OAuth, so there is nothing to discover from. A bare 403 usually means a proxy, WAF, or IP allowlist rejected the request before the MCP server saw it.`}:{kind:"unexpected",message:`${r} where MCP requires 401 Unauthorized (or 200, if the server allows anonymous access).`}}function pD(e){return e.step!=="request_without_token"||e.status===void 0?!1:vs({status:e.status,statusText:e.statusText,wwwAuthenticateHeader:e.wwwAuthenticateHeader}).kind==="challenged"}function fD(e){const t=Number.isInteger(e.maxRetries)&&e.maxRetries>=0?e.maxRetries:1;switch(e.authMode){case"m2m":return"throw";case"debugger":return"manual";case"interactive":return e.attempt<t?"reauthorize":"throw"}}function mP(e){const t=e.customScopes?.trim();if(t)return t;const r=e.challengedScopes?.filter(Boolean)??[];if(r.length>0)return Array.from(new Set(r)).join(" ");const n=e.supportedScopes?.filter(Boolean)??[];if(n.length!==0)return Array.from(new Set(n)).join(" ")}var _P;_P=globalThis.crypto;var yP="Resource server does not implement OAuth 2.0 Protected Resource Metadata.",wp="No response while loading OAuth protected resource metadata.",bP="Failed to request resource metadata";function aa(e){const t=e instanceof Error?e.message:String(e);return`${bP}: ${t}`}function vD(e){return e==="Resource server does not implement OAuth 2.0 Protected Resource Metadata."||e===aa(new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata."))}function wP(e){try{const t=new URL(e);return t.protocol=t.protocol.toLowerCase(),t.hostname=t.hostname.toLowerCase(),t.hash="",t.pathname!=="/"&&t.pathname.endsWith("/")&&(t.pathname=t.pathname.slice(0,-1)),t.toString()}catch{return e}}function SP(e,t){if(e.origin!==t.origin||t.pathname.length<e.pathname.length)return!1;const r=t.pathname.endsWith("/")?t.pathname:`${t.pathname}/`,n=e.pathname.endsWith("/")?e.pathname:`${e.pathname}/`;return r.startsWith(n)}function EP(e,t,r){const n=c=>({value:e,source:t,status:"invalid",strictClientCompatible:!1,rfc9728Compliant:!1,rfc9728Reason:c,reason:c});let i;try{i=new URL(e)}catch{return n(`Resource indicator "${e}" is not a parseable URI.`)}if(i.hash)return n(`Resource indicator "${e}" must not include a fragment (RFC 8707 §2).`);if(i.protocol!=="https:"&&i.protocol!=="http:")return n(`Resource indicator "${e}" must be an https URL (RFC 9728 §2).`);let s;try{s=new URL(r)}catch{return n(`Server URL "${r}" is not a parseable URI.`)}if(i.origin!==s.origin){const c=`Resource indicator "${e}" is on a different origin than the server URL "${r}" — honoring it would let the server steer tokens to an audience it doesn't own.`;return{value:e,source:t,status:"incompatible",strictClientCompatible:!1,rfc9728Compliant:!1,rfc9728Reason:c,reason:c}}const o=SP(i,s),a=i.protocol!=="https:"?`Resource indicator "${e}" must use the https scheme to comply with RFC 9728.`:o?void 0:`Resource indicator "${e}" does not satisfy the protected-resource binding for server URL "${r}" required for RFC 9728 conformance.`;return{value:e,source:t,status:"valid",strictClientCompatible:o,rfc9728Compliant:a===void 0,...a?{rfc9728Reason:a}:{},...o?{}:{reason:`Resource indicator "${e}" is not a path prefix of the server URL "${r}"; clients that enforce the official MCP SDK's strict binding will refuse it.`}}}function kP(e){return e.resolved?e.resolved.value:e.serverUrl===void 0?e.prmResource:Cl({serverUrl:e.serverUrl,prmResource:e.prmResource}).value}function Cl(e){const t=[[e.prmResource,"prm"],[e.authorizationUrlResource,"authorization"],[e.configuredResource,"configured"]];for(const[n,i]of t){const s=n?.trim();if(s)return EP(s,i,e.serverUrl)}try{new URL(e.serverUrl)}catch{return{value:e.serverUrl,source:"server",status:"invalid",strictClientCompatible:!1,rfc9728Compliant:!1,rfc9728Reason:`Server URL "${e.serverUrl}" is not a parseable URI.`,reason:`Server URL "${e.serverUrl}" is not a parseable URI.`}}const r=new URL(e.serverUrl).protocol==="https:"?void 0:`Resource indicator "${e.serverUrl}" must use the https scheme to comply with RFC 9728.`;return{value:wP(e.serverUrl),source:"server",status:"valid",strictClientCompatible:!0,rfc9728Compliant:r===void 0,...r?{rfc9728Reason:r}:{}}}var C_="2025-11-25";async function P_(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(!(n instanceof TypeError))throw n;if(!t)return;try{return await r(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}}}function RP(e,t="",r={}){const n=t.endsWith("/")?t.slice(0,-1):t;return r.prependPathname?`${n}/.well-known/${e}`:`/.well-known/${e}${n}`}async function Sp(e,t,r=fetch){return P_(e,{"MCP-Protocol-Version":t,Accept:"application/json"},r)}function AP(e,t){return e?t==="/"?!1:e.status>=400&&e.status<500||e.status===502:!0}async function IP(e,t,r,n){const i=new URL(e),s=n?.protocolVersion??C_;let o;if(n?.metadataUrl)o=new URL(n.metadataUrl);else{const l=RP(t,i.pathname);o=new URL(l,n?.metadataServerUrl??i),o.search=i.search}let a=await Sp(o,s,r),c=!a;return!n?.metadataUrl&&AP(a,i.pathname)&&(a=await Sp(new URL(`/.well-known/${t}`,i),s,r),c||=!a),{response:a,sawNoResponse:c}}function TP(e){const t=typeof e=="string"?new URL(e):e;if(t.pathname==="/")return[{url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}];const r=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;return[{url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"},{url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}]}async function ca(e,t,r=fetch){const{response:n,sawNoResponse:i}=await IP(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n)throw new Error(wp);if(n.status===404)throw await n.text().catch(()=>{}),new Error(i?wp:yP);if(!n.ok)throw await n.text().catch(()=>{}),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return await n.json()}async function $P(e,{fetchFn:t=fetch,protocolVersion:r=C_}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"};for(const{url:i,type:s}of TP(e)){const o=await P_(i,n,t);if(o){if(!o.ok){if(await o.text().catch(()=>{}),o.status>=400&&o.status<500||o.status===502)continue;throw new Error(`HTTP ${o.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return await o.json()}}}async function gD(e,t){let r,n;try{r=await ca(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers?.length&&(n=r.authorization_servers[0])}catch(s){if(s instanceof TypeError)throw s}n||(n=String(new URL("/",e)));const i=await $P(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:String(n),authorizationServerMetadata:i,resourceMetadata:r}}function CP(e){const t=e?.token_endpoint_auth_methods_supported;if(!Array.isArray(t)||t.length===0)return["client_secret_basic"];const r=t.filter(n=>typeof n=="string");return r.length>0?r:["client_secret_basic"]}function la(e){const t=CP(e.authorizationServerMetadata);return e.hasClientSecret?t.includes("client_secret_basic")?{ok:!0,method:"client_secret_basic",supportedMethods:t}:t.includes("client_secret_post")?{ok:!0,method:"client_secret_post",supportedMethods:t}:t.includes("none")?{ok:!0,method:"none",supportedMethods:t}:{ok:!1,message:`Unsupported OAuth client authentication method: ${t.join(", ")||"none advertised"}.`,supportedMethods:t}:{ok:!0,method:"none",supportedMethods:t}}function Ep(e){return new URLSearchParams([["v",e]]).toString().slice(2)}function Ur(e){const{clientId:t,clientSecret:r,tokenEndpointAuthMethod:n}=e;if(r&&n==="client_secret_basic")return{headers:{Authorization:`Basic ${btoa(`${Ep(t??"")}:${Ep(r)}`)}`},bodyParams:{}};const i={};return t&&(i.client_id=t),r&&n!=="none"&&(i.client_secret=r),{headers:{},bodyParams:i}}function ua(e){const t=e.token_endpoint_auth_method;if(!(e.client_secret&&(!t||t==="none")))return t||"none"}var kp=300,O_="Authenticated request failed";function mD(e){return e.startsWith(`${O_}: `)}function er(e){if(typeof e!="string")return;const t=e.trim();return t||void 0}function Pl(e){return e.replace(/\s+/g," ").trim()}function x_(e){if(typeof e=="string")return er(e);if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,r=er(t.error_type),n=er(t.error_description),i=er(t.error_message)??n??er(t.message),s=er(t.error);if(r&&i)return er(`${r}: ${i}`);if(s&&n)return er(`${s}: ${n}`);if(s)return s;const o=t.error;if(o&&typeof o=="object"&&!Array.isArray(o)){const a=er(o.message);if(a)return a}return i}function M_(e,t){const r=Pl(Cr(t.statusText??"",{maxLength:kp})),n=x_(t.body),i=n?Pl(Cr(n,{maxLength:kp})):void 0;return`${e}: ${t.status}${r?` ${r}`:""}${i?`: ${i}`:""}`}function da(e){return M_(O_,e)}function ha(e){return M_("Token request failed",e)}function Rp(e){try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t+"=".repeat((4-t.length%4)%4);let n;if(typeof globalThis.atob=="function")n=globalThis.atob(r);else if(typeof Buffer<"u")n=Buffer.from(r,"base64").toString("utf-8");else return null;return JSON.parse(n)}catch{return null}}function PP(e){const t=e.split(".");return t.length!==3?null:{header:Rp(t[0]),payload:Rp(t[1]),signature:t[2]}}function Fr(e){return PP(e)?.payload??null}function De(e){try{return new Date(e*1e3).toLocaleString()}catch{return String(e)}}var _D={isInitiatingAuth:!1,currentStep:"idle",httpHistory:[],infoLogs:[],tokenEndpointAuthMethod:void 0};function pa(){return{isInitiatingAuth:!1,currentStep:"idle",serverUrl:void 0,wwwAuthenticateHeader:void 0,challengedScopes:void 0,resourceMetadataUrl:void 0,resourceMetadata:void 0,resourceIndicator:void 0,resourceIndicatorSuppressed:void 0,authorizationServerUrl:void 0,authorizationServerMetadata:void 0,clientId:void 0,clientSecret:void 0,tokenEndpointAuthMethod:void 0,codeVerifier:void 0,codeChallenge:void 0,codeChallengeMethod:void 0,authorizationUrl:void 0,authorizationCode:void 0,state:void 0,recordedIssuer:void 0,authorizationResponseIss:void 0,requestedScopes:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,lastRequest:void 0,lastResponse:void 0,httpHistory:[],infoLogs:[],error:void 0}}function zn(e,t){return`${e.substring(0,t)}...`}function Ol(e){if(typeof e=="string"&&e.trim()!=="")try{return new URL(e).pathname}catch{return`${e} (not an absolute URL)`}let t;try{t=typeof e=="string"||typeof e=="object"&&e!==null?JSON.stringify(e)??String(e):String(e)}catch{t="[unserializable value]"}return`${t} (not an absolute URL)`}function wc(e,t,r){return e.resourceIndicatorSuppressed?"omitted (emulation)":t.resourceValue(e)||r}function OP(e,t){return[{id:"request_without_token",label:"MCP request without token",description:"Client makes initial request without authorization",from:"client",to:"mcpServer",details:e.serverUrl?[{label:"POST",value:e.serverUrl},{label:"method",value:t.initialMcpMethod}]:void 0},{id:"received_401_unauthorized",label:"HTTP 401 Unauthorized with WWW-Authenticate header",description:"Server returns 401 with WWW-Authenticate header",from:"mcpServer",to:"client",details:e.resourceMetadataUrl!==void 0?[{label:"Note",value:"Extract resource_metadata URL"}]:void 0},{id:"request_resource_metadata",label:"Request Protected Resource Metadata",description:"Client requests metadata from well-known URI",from:"client",to:"mcpServer",details:e.resourceMetadataUrl!==void 0?[{label:"GET",value:Ol(e.resourceMetadataUrl)}]:void 0},{id:"received_resource_metadata",label:"Return metadata",description:"Server returns OAuth protected resource metadata",from:"mcpServer",to:"client",details:e.resourceMetadata?.authorization_servers?[{label:"Auth Server",value:e.resourceMetadata.authorization_servers[0]}]:void 0}]}function xP(e){return[{id:"cimd_prepare",label:"Client uses HTTPS URL as client_id",description:"Client prepares to use URL-based client identification",from:"client",to:"client",details:e.clientId?[{label:"client_id (URL)",value:e.clientId.includes("http")?e.clientId:"https://www.mcpjam.com/.well-known/oauth/client-metadata.json"},{label:"Method",value:"Client ID Metadata Document (CIMD)"}]:[{label:"Note",value:"HTTPS URL points to metadata document"}]},{id:"cimd_fetch_request",label:"Fetch metadata from client_id URL",description:"Authorization Server fetches client metadata from the URL",from:"authServer",to:"client",details:[{label:"Action",value:"GET client_id URL"},{label:"Note",value:"Server initiates metadata fetch during authorization"}]},{id:"cimd_metadata_response",label:"JSON metadata document",description:"Client hosting returns metadata with redirect_uris and client info",from:"client",to:"authServer",details:[{label:"Content-Type",value:"application/json"},{label:"Contains",value:"client_id, client_name, redirect_uris, etc."}]},{id:"received_client_credentials",label:"Validate metadata and redirect_uris",description:"Authorization Server validates fetched metadata",from:"authServer",to:"authServer",details:[{label:"Validates",value:"client_id matches URL, redirect_uris are valid"},{label:"Security",value:"SSRF protection, domain trust policies"}]}]}function MP(e,t,r){if(r==="cimd")return xP(e);const n=t.clientCredentialsExtras?.(e)??[];return r==="dcr"?[{id:"request_client_registration",label:`POST /register (${t.protocolVersion})`,description:"Client registers dynamically with Authorization Server",from:"client",to:"authServer",details:[{label:"Note",value:"Dynamic client registration (DCR)"},...t.dcrNotes??[]]},{id:"received_client_credentials",label:"Client Credentials",description:"Authorization Server returns client ID and credentials",from:"authServer",to:"client",details:e.clientId?[{label:"client_id",value:zn(e.clientId,20)},...n]:void 0}]:[{id:"received_client_credentials",label:`Use Pre-registered Client (${t.protocolVersion})`,description:"Client uses pre-configured credentials (skipped DCR)",from:"client",to:"client",details:e.clientId?[{label:"client_id",value:zn(e.clientId,20)},{label:"Note",value:"Pre-registered (no DCR needed)"},...n]:[{label:"Note",value:"Pre-registered client credentials"}]}]}function fa(e,t,r){return[...r.includesProtectedResourceMetadata?OP(e,r):[],{id:"request_authorization_server_metadata",label:r.authorizationServerMetadata.label,description:r.authorizationServerMetadata.description,from:"client",to:"authServer",details:e.authorizationServerUrl?[{label:"URL",value:e.authorizationServerUrl},{label:"Protocol",value:r.protocolVersion}]:void 0},{id:"received_authorization_server_metadata",label:"Authorization server metadata response",description:"Authorization Server returns metadata",from:"authServer",to:"client",details:e.authorizationServerMetadata?[{label:"Token",value:Ol(e.authorizationServerMetadata.token_endpoint)},{label:"Auth",value:Ol(e.authorizationServerMetadata.authorization_endpoint)}]:void 0},...MP(e,r,t),{id:"generate_pkce_parameters",label:r.pkce.label,description:r.pkce.description,from:"client",to:"client",details:e.codeChallenge?[{label:"code_challenge",value:zn(e.codeChallenge,15)},{label:"method",value:e.codeChallengeMethod||"S256"},{label:"resource",value:wc(e,r,"—")},{label:"Protocol",value:r.protocolVersion}]:void 0},{id:"authorization_request",label:"Open browser with authorization URL",description:"Client opens browser with authorization URL + code_challenge + resource",from:"client",to:"browser",details:e.authorizationUrl?[{label:"code_challenge",value:e.codeChallenge?.substring(0,12)+"..."||"S256"},{label:"resource",value:wc(e,r,"")},...r.authorizationRequestExtras?.(e)??[]]:void 0},{id:"browser_to_auth_server",label:"Authorization request with resource parameter",description:"Browser navigates to authorization endpoint",from:"browser",to:"authServer",details:e.authorizationUrl?[{label:"Note",value:"User authorizes in browser"}]:void 0},{id:"auth_redirect_to_browser",label:"Redirect to callback with authorization code",description:"Authorization Server redirects browser back to callback URL",from:"authServer",to:"browser",details:e.authorizationCode?[{label:"code",value:zn(e.authorizationCode,20)}]:void 0},{id:"received_authorization_code",label:"Authorization code callback",description:"Browser redirects back to client with authorization code",from:"browser",to:"client",details:e.authorizationCode?[{label:"code",value:zn(e.authorizationCode,20)}]:void 0},{id:"token_request",label:"Token request + code_verifier + resource",description:"Client exchanges authorization code for access token",from:"client",to:"authServer",details:e.codeVerifier?[{label:"grant_type",value:"authorization_code"},{label:"resource",value:wc(e,r,"")}]:void 0},{id:"received_access_token",label:"Access token (+ refresh token)",description:"Authorization Server returns access token",from:"authServer",to:"client",details:e.accessToken?[{label:"token_type",value:e.tokenType||"Bearer"},{label:"expires_in",value:e.expiresIn?.toString()||"3600"}]:void 0},{id:"authenticated_mcp_request",label:"MCP request with access token",description:"Client makes authenticated request to MCP server",from:"client",to:"mcpServer",details:e.accessToken?[{label:"POST",value:"tools/list"},{label:"Authorization",value:`Bearer ${zn(e.accessToken,15)}`}]:void 0},{id:"complete",label:"MCP response",description:"MCP Server returns successful response",from:"mcpServer",to:"client",details:e.accessToken?[{label:"Status",value:"200 OK"},{label:"Content",value:"tools, resources, prompts"}]:void 0}]}function ne(e,t,r,n,i,s={}){const{level:o="info",error:a}=s;return[...e.infoLogs||[],{id:r,step:t,label:n,data:i,timestamp:Date.now(),level:o,error:a}]}function LP(e,t,r,n){return!r||r.source!=="prm"||r.strictClientCompatible&&r.rfc9728Compliant?t:ne({...e,infoLogs:t},"received_resource_metadata","resource-identifier-mismatch","Resource identifier mismatch",{"Advertised resource":r.value,"Server URL":n,Status:r.status,Reason:r.reason,"RFC 9728 compliant":r.rfc9728Compliant,...r.rfc9728Reason?{"RFC 9728 reason":r.rfc9728Reason}:{},Note:r.status==="valid"?"The flow will send this interoperability-safe resource, but it is not RFC 9728 compliant and strict conformance surfaces will reject it.":"The debugger will send the advertised resource as-is so you can observe real behavior, but MCP clients — including MCPJam's Quick OAuth and the official MCP SDK — validate it against the server URL and will refuse to connect."},{level:"warning"})}function va(e,t,r,n){return ne({...e,infoLogs:t},r,"non-compliant-challenge-status","Non-compliant challenge status",{Received:`${n.status}${n.statusText?` ${n.statusText}`:""}`,Expected:"401 Unauthorized",Note:"The server sent a WWW-Authenticate Bearer challenge, so the debugger continues OAuth discovery from it. MCP requires 401 here — clients that decide to authenticate from the status code alone, including the official MCP SDK, will not start OAuth against this server."},{level:"warning"})}function Tt(e){return e instanceof Error?{message:e.message,details:{name:e.name,stack:e.stack}}:typeof e=="string"?{message:e}:{message:"Unexpected error",details:e}}function gn(e,t){if(!e||e.length===0)return e||void 0;const r=[...e],n={...r[r.length-1]};return r[r.length-1]={...n,error:t,duration:n.duration!==void 0?n.duration:Date.now()-n.timestamp},r}function dt(e,t={}){const r={},n=new Map,i=s=>{if(s)for(const[o,a]of Object.entries(s)){const c=o.toLowerCase(),l=n.get(c);l&&l!==o&&delete r[l],n.set(c,o),r[o]=a}};return i(e),i(t),r}function ct(e,t={}){const r=dt(e,t);for(const n of Object.keys(r))n.toLowerCase()==="authorization"&&delete r[n];return r}function Nu(e,t,r,n={}){try{const i=new URL(e).origin;return new URL(t,e).origin===i?dt(r,n):ct(r,n)}catch{return ct(r,n)}}function Pr(e){if(!e)return{};if(e instanceof Headers){const t={};return e.forEach((r,n)=>{t[n]=r}),t}return Array.isArray(e)?Object.fromEntries(e.map(([t,r])=>[t,String(r)])):Object.fromEntries(Object.entries(e).map(([t,r])=>[t,String(r)]))}function DP(e){if(typeof globalThis.btoa=="function"){const t=Array.from(e,r=>String.fromCharCode(r)).join("");return globalThis.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}if(typeof Buffer<"u")return Buffer.from(e).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");throw new Error("No base64 encoder available")}function qr(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=new Uint8Array(e);return crypto.getRandomValues(r),Array.from(r,n=>t[n%66]).join("")}async function ga(e){const t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return DP(new Uint8Array(r))}var ma="Authorization server metadata missing required 'issuer' field",NP=new Set(["2025-03-26"]),zP=new Set(["2025-03-26","2025-06-18"]);function UP(e){return!NP.has(e)}function FP(e){return!zP.has(e)}function L_(e,t){if(FP(t)){if(!e||e.length===0)return`PKCE is REQUIRED for ${t} protocol, but authorization server does not advertise code_challenge_methods_supported. Server is not compliant with ${t} spec.`;if(!e.includes("S256"))return`Authorization server advertises PKCE without S256 (advertised: ${e.join(", ")}). MCPJam will not downgrade to a weaker code challenge method, so the ${t} flow stops here. Use the OAuth debugger to observe this server's behavior without connecting.`}}function zu(e){const t=e.authorizationServers?.find(r=>typeof r=="string"&&r.trim()!=="")?.trim();return t?{authorizationServerUrl:t,substituted:!1}:UP(e.protocolVersion)?{authorizationServerUrl:e.fallbackServerUrl,substituted:!0,error:`Protected resource metadata does not list an authorization server. RFC 9728 \`authorization_servers\` is required by the ${e.protocolVersion} MCP profile; without it there is no server authorized to issue tokens for this resource, and using the MCP server's own URL would invent one.`}:{authorizationServerUrl:e.fallbackServerUrl,substituted:!0}}var qP="io.modelcontextprotocol/oauth-client-credentials",jP="io.modelcontextprotocol/protocolVersion",HP="io.modelcontextprotocol/clientCapabilities",VP="io.modelcontextprotocol/clientInfo";function Uu(e){switch(e){case"2025-11-25":return"2025-11-25";case"2026-07-28":return"2026-07-28";case"2025-06-18":case"2025-03-26":return"2024-11-05";default:return e}}function D_(e){return e!=="client_credentials"?{}:{extensions:{[qP]:{}}}}function Ut(e){return{jsonrpc:"2.0",method:"initialize",params:{protocolVersion:e.protocolVersion,capabilities:D_(e.authMode),clientInfo:{name:e.clientName,version:e.clientVersion}},id:e.id}}function Us(e){return{jsonrpc:"2.0",method:"tools/list",params:{_meta:{[jP]:e.protocolVersion,[HP]:D_(e.authMode),[VP]:{name:e.clientName,version:e.clientVersion}}},id:e.id}}var BP="***REDACTED***",GP=new Set(["client_secret","registration_access_token","access_token","refresh_token"]),_a="Authorization server metadata does not include a registration_endpoint. Configure a pre-registered client or use a different registration strategy.",ya="Authorization server metadata does not include a registration_endpoint required for DCR conformance.";function WP(e){const t=r=>{let n;try{n=new URL(r)}catch{return!0}if(n.protocol!=="http:"&&n.protocol!=="https:")return!0;if(n.protocol!=="http:")return!1;const i=n.hostname;return i==="localhost"||i==="127.0.0.1"||i==="[::1]"};return e.some(t)?"native":"web"}function ba(e){const{dynamicRegistrationDefaults:t}=e,r={...t,redirect_uris:t.redirect_uris??[e.redirectUri],grant_types:t.grant_types??["authorization_code","refresh_token"],response_types:t.response_types??["code"],token_endpoint_auth_method:t.token_endpoint_auth_method??"none"};return e.scope&&(r.scope=e.scope),{method:"POST",url:e.registrationEndpoint,headers:ct(e.customHeaders,{"Content-Type":"application/json"}),body:r}}function xl(e){if(Array.isArray(e))return e.map(xl);if(e&&typeof e=="object"){const t={};for(const[r,n]of Object.entries(e))t[r]=GP.has(r.toLowerCase())?BP:xl(n);return t}return e}function ZP(e){return{status:e.status,statusText:e.statusText,headers:{...e.headers},body:xl(e.body)}}function Ap(e,t){const r=[...e||[]];if(r.length>0){const n=r[r.length-1];r[r.length-1]={...n,response:t,duration:Date.now()-(n.timestamp||Date.now())}}return r}var Sc="Configure a pre-registered client or enable DCR on the authorization server.";async function wa(e){let t;try{t=await e.requestExecutor(e.request)}catch(o){const a=o instanceof Error?o.message:String(o),c={status:0,statusText:"Network Error",headers:{},body:{error:a}},l=`Client registration failed: ${a}`;return{status:"network_error",response:c,httpHistory:Ap(e.httpHistory,c),error:l,fallbackNote:"Client registration failed; using pre-registered client credentials.",errorWithFallbackHint:`${l}. ${Sc}`}}const r=ZP({status:t.status,statusText:t.statusText,headers:t.headers,body:t.body}),n=Ap(e.httpHistory,r);if(!t.ok){const o=`Dynamic Client Registration failed (${t.status}).`;return{status:"http_error",response:r,httpHistory:n,error:o,fallbackNote:`Dynamic Client Registration failed (${t.status}); using pre-registered client credentials.`,errorWithFallbackHint:`${o} ${Sc}`}}const i=t.body;if(!i||typeof i!="object"||Array.isArray(i)){const o="Client registration failed: the registration response body was not a JSON object";return{status:"invalid_response",response:r,httpHistory:n,error:o,fallbackNote:"Client registration failed; using pre-registered client credentials.",errorWithFallbackHint:`${o}. ${Sc}`}}const s={"Client ID":i.client_id,"Client Name":i.client_name,"Token Auth Method":i.token_endpoint_auth_method||"none","Redirect URIs":i.redirect_uris,"Grant Types":i.grant_types,"Response Types":i.response_types};return i.client_secret&&(s["Client Secret Issued"]=!0,s.Note="Server issued client_secret - this will be used in token requests"),{status:"registered",response:r,httpHistory:n,clientInfo:i,credentials:{clientId:typeof i.client_id=="string"?i.client_id:void 0,clientSecret:typeof i.client_secret=="string"?i.client_secret:void 0,tokenEndpointAuthMethod:typeof i.token_endpoint_auth_method=="string"?i.token_endpoint_auth_method:void 0,clientSecretExpiresAt:typeof i.client_secret_expires_at=="number"?i.client_secret_expires_at:void 0},missingClientId:typeof i.client_id!="string",nonCanonicalSuccessStatus:t.status!==201,infoLogData:s}}function Sa(e){return e?.sendResourceIndicator!==!1}function jr(e,t){const r=e?.scopeRequest;if(!r)return mP(t);switch(r.mode){case"omit":return;case"fixed":return r.scopes.join(" ");case"challenge":{const n=t.challengedScopes?.filter(Boolean)??[];return n.length>0?Array.from(new Set(n)).join(" "):void 0}case"all-supported":{const n=t.supportedScopes?.filter(Boolean)??[];return n.length>0?Array.from(new Set(n)).join(" "):void 0}}}function Ea(e,t){if(!t)return e;const r={...e};return t.dcrClientName!==void 0&&(r.client_name=t.dcrClientName),t.tokenEndpointAuthMethod!==void 0&&(r.token_endpoint_auth_method=t.tokenEndpointAuthMethod),t.dcrRedirectUris!==void 0&&(r.redirect_uris=[...t.dcrRedirectUris]),r}function Hr(e,t){return e?.tokenEndpointAuthMethod??t}function JP(e,t){return t?.userAgent?{...e??{},"User-Agent":t.userAgent}:e}function mn(e,t){return e?.mcpProtocolVersion??t}function KP(e,t){return fa(e,t,{protocolVersion:"2025-03-26",includesProtectedResourceMetadata:!1,initialMcpMethod:"initialize",authorizationServerMetadata:{label:"GET /.well-known/oauth-authorization-server from MCP base URL",description:"Direct discovery from MCP server base URL with fallback to /authorize, /token, /register"},pkce:{label:"Generate PKCE parameters",description:"Client generates code verifier and challenge (recommended), includes resource parameter"},resourceValue:r=>r.serverUrl})}function YP(e){return new URL(e).origin}function Ip(e){const t=new URL(e),r=[];if(t.pathname==="/"||t.pathname==="")r.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString());else{const n=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;r.push(new URL(`/.well-known/oauth-authorization-server${n}`,t.origin).toString()),r.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString())}return r}var XP=e=>{const{state:t,getState:r,updateState:n,serverUrl:i,serverName:s,redirectUrl:o,requestExecutor:a,scheduleAutoAdvance:c,loadPreregisteredCredentials:l,dynamicRegistration:u,customScopes:h,customHeaders:d,authMode:p,hasClientSecret:f=!1,strictConformance:v=!1,registrationStrategy:m="dcr",emulation:_}=e,w=o,S=mn(_,"2025-03-26"),T=mn(_,Uu("2025-03-26")),I=Sa(_),C=Ea(u??{},_);if(m==="dcr"&&!C.client_name)throw new Error("Dynamic registration metadata must include client_name");const M=()=>r?r():t,L=(k,ie={})=>a({url:k,method:ie.method||"GET",headers:Pr(ie.headers),body:ie.body}),q=k=>{const ie=la({authorizationServerMetadata:M().authorizationServerMetadata,hasClientSecret:!!(k||f)});if(!ie.ok)throw new Error(ie.message);return ie.method},X=async k=>{const{clientId:ie,clientSecret:H}=await l?.({serverName:s,serverUrl:i})??{};if(!ie)return;const oe=q(H),$={"Client ID":ie,"Client Secret":H||f?"Configured":"Not provided (public client)","Token Auth Method":oe,Note:k};return{clientId:ie,clientSecret:H||void 0,tokenEndpointAuthMethod:oe,infoLogs:ne(M(),"received_client_credentials","preregistered-fallback","Pre-registered Client",$)}},ee={state:t,updateState:n,proceedToNextStep:async()=>{const k=M();n({isInitiatingAuth:!0});const ie=H=>{c?.(()=>{ee.proceedToNextStep()},H)};try{switch(k.currentStep){case"idle":n({currentStep:"discovery_start",serverUrl:i,httpHistory:[],isInitiatingAuth:!1}),ie(50);return;case"request_without_token":if(!k.serverUrl)throw new Error("No server URL available");try{const z=await L(k.serverUrl,{method:"POST",headers:dt(d,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":S}),body:JSON.stringify(Ut({protocolVersion:T,authMode:p,clientName:"MCP Inspector",clientVersion:"1.0.0",id:1}))}),se={status:z.status,statusText:z.statusText,headers:z.headers,body:z.body},ae=[...k.httpHistory||[]];if(ae.length>0){const Oe=ae[ae.length-1];Oe.response=se,Oe.duration=Date.now()-(Oe.timestamp||Date.now())}const he=vs({status:z.status,statusText:z.statusText,wwwAuthenticateHeader:z.headers["www-authenticate"],serverMessage:z.body?.error?.message});if(he.kind==="challenged"||he.kind==="anonymous_allowed"){let Oe=he.kind==="anonymous_allowed"?ne(k,"discovery_start","optional-auth","Optional Authentication",{message:"Server allows anonymous access",note:"Proceeding with OAuth discovery for authenticated features"}):k.infoLogs;he.kind==="challenged"&&!he.specCompliant&&(Oe=va(k,Oe,"discovery_start",se)),n({currentStep:"discovery_start",lastResponse:se,httpHistory:ae,infoLogs:Oe,isInitiatingAuth:!1})}else throw n({lastResponse:se,httpHistory:ae}),new zr(he.message,z.status)}catch(z){throw z instanceof zr?z:new Error(`Failed to request MCP server: ${z instanceof Error?z.message:String(z)}`)}break;case"discovery_start":const H=k.serverUrl,oe={method:"GET",url:Ip(H)[0],headers:ct(d,{})};n({currentStep:"request_authorization_server_metadata",authorizationServerUrl:H,lastRequest:oe,lastResponse:void 0,httpHistory:[...k.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:oe}],isInitiatingAuth:!1}),ie(50);return;case"request_authorization_server_metadata":if(!k.authorizationServerUrl)throw new Error("No authorization server URL available");const $=Ip(k.authorizationServerUrl);let Q=null,y=null;for(const z of $)try{const se=ct(d,{"MCP-Protocol-Version":"2025-03-26"}),ae=[...k.httpHistory||[]];ae.length>0&&(ae[ae.length-1].request={method:"GET",url:z,headers:se}),n({lastRequest:{method:"GET",url:z,headers:se},httpHistory:ae});const he=await L(z,{method:"GET",headers:se});if(he.ok){Q=he.body,y=he;break}else if(he.status>=400&&he.status<500)continue}catch{continue}if(!Q){const z=YP(k.authorizationServerUrl);Q={issuer:z,authorization_endpoint:`${z}/authorize`,token_endpoint:`${z}/token`,registration_endpoint:`${z}/register`,response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]};const se=ne(M(),"received_authorization_server_metadata","fallback-endpoints","Using Fallback Endpoints",{Note:"Metadata discovery failed, using default endpoints per 2025-03-26 spec","Authorization Endpoint":Q.authorization_endpoint,"Token Endpoint":Q.token_endpoint,"Registration Endpoint":Q.registration_endpoint});n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:Q,infoLogs:se,isInitiatingAuth:!1});break}if(!Q.issuer)throw new Error(ma);if(!Q.authorization_endpoint)throw new Error("Authorization server metadata missing 'authorization_endpoint'");if(!Q.token_endpoint)throw new Error("Authorization server metadata missing 'token_endpoint'");if(!Q.response_types_supported?.includes("code"))throw new Error("Authorization server does not support 'code' response type");const V={status:y.status,statusText:y.statusText,headers:y.headers,body:Q},K=[...k.httpHistory||[]];if(K.length>0){const z=K[K.length-1];z.response=V,z.duration=Date.now()-(z.timestamp||Date.now())}const le=Q.code_challenge_methods_supported||[];(!le||le.length===0||!le.includes("S256"))&&console.warn("Authorization server may not support PKCE S256 (REQUIRED for 2025-03-26 spec)"),n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:Q,lastResponse:V,httpHistory:K,isInitiatingAuth:!1});break;case"received_authorization_server_metadata":if(!k.authorizationServerMetadata)throw new Error("No authorization server metadata available");if(m==="preregistered"){const{clientId:z,clientSecret:se}=await l?.({serverName:s,serverUrl:i})??{};if(!z){n({error:"Pre-registered client ID is required. Please configure OAuth credentials in the server settings.",isInitiatingAuth:!1});return}const ae=q(se),he={"Client ID":z,"Client Secret":se||f?"Configured":"Not provided (public client)","Token Auth Method":ae,Note:"Using pre-registered client credentials (skipped DCR)"},Oe=ne(M(),"received_client_credentials","dcr","Pre-registered Client",he);n({currentStep:"received_client_credentials",clientId:z,clientSecret:se||void 0,tokenEndpointAuthMethod:ae,infoLogs:Oe,isInitiatingAuth:!1})}else if(k.authorizationServerMetadata.registration_endpoint){const z=k.authorizationServerMetadata.scopes_supported,se=jr(_,{customScopes:h,supportedScopes:z}),ae=ba({registrationEndpoint:k.authorizationServerMetadata.registration_endpoint,redirectUri:w,dynamicRegistrationDefaults:C,scope:se,customHeaders:d});n({currentStep:"request_client_registration",lastRequest:ae,lastResponse:void 0,httpHistory:[...k.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:ae}],isInitiatingAuth:!1}),ie(50);return}else{if(v){n({error:ya,isInitiatingAuth:!1});return}const z=await X("Authorization server did not advertise registration_endpoint; using pre-registered client credentials.");if(!z){n({error:_a,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:z.clientId,clientSecret:z.clientSecret,tokenEndpointAuthMethod:z.tokenEndpointAuthMethod,infoLogs:z.infoLogs,error:void 0,isInitiatingAuth:!1})}break;case"request_client_registration":if(!k.authorizationServerMetadata?.registration_endpoint)throw new Error("No registration endpoint available");if(!k.lastRequest?.body)throw new Error("No client metadata in request");{const z=await wa({request:k.lastRequest,requestExecutor:a,httpHistory:k.httpHistory});if(z.status!=="registered"){if(n({lastResponse:z.response,httpHistory:z.httpHistory,error:z.error}),v){z.status==="invalid_response"&&n({isInitiatingAuth:!1});return}const ae=await X(z.fallbackNote);if(!ae){n({error:z.errorWithFallbackHint,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:ae.clientId,clientSecret:ae.clientSecret,tokenEndpointAuthMethod:ae.tokenEndpointAuthMethod,infoLogs:ae.infoLogs,error:void 0,isInitiatingAuth:!1});break}if(z.missingClientId){n({lastResponse:z.response,httpHistory:z.httpHistory,error:"Dynamic Client Registration response is missing a client_id.",isInitiatingAuth:!1});return}const se=ne(M(),"received_client_credentials","dcr","Dynamic Client Registration",z.infoLogData);n({currentStep:"received_client_credentials",clientId:z.credentials.clientId,clientSecret:z.credentials.clientSecret,tokenEndpointAuthMethod:ua(z.clientInfo),lastResponse:z.response,httpHistory:z.httpHistory,infoLogs:se,error:void 0,isInitiatingAuth:!1})}break;case"received_client_credentials":const de=qr(43),Ce=await ga(de),Re=ne(M(),"generate_pkce_parameters","pkce-generation","Generate PKCE Parameters (REQUIRED)",{code_challenge:Ce,method:"S256",...I?{resource:k.serverUrl||"Unknown"}:{resource:"(omitted — emulated client does not send RFC 8707 resource)"},note:"PKCE is REQUIRED for all clients in 2025-03-26 spec"});n({currentStep:"generate_pkce_parameters",codeVerifier:de,codeChallenge:Ce,codeChallengeMethod:"S256",...I?{}:{resourceIndicatorSuppressed:!0},state:qr(16),infoLogs:Re,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!k.authorizationServerMetadata?.authorization_endpoint||!k.clientId)throw new Error("Missing authorization endpoint or client ID");const _e=new URL(k.authorizationServerMetadata.authorization_endpoint);_e.searchParams.set("response_type","code"),_e.searchParams.set("client_id",k.clientId),_e.searchParams.set("redirect_uri",w),_e.searchParams.set("code_challenge",k.codeChallenge||""),_e.searchParams.set("code_challenge_method","S256"),_e.searchParams.set("state",k.state||""),k.serverUrl&&I&&_e.searchParams.set("resource",k.serverUrl);const ve=jr(_,{customScopes:h,supportedScopes:k.authorizationServerMetadata.scopes_supported});ve&&_e.searchParams.set("scope",ve);const Je=ne(M(),"authorization_request","auth-url","Authorization URL",{url:_e.toString()});n({currentStep:"authorization_request",authorizationUrl:_e.toString(),authorizationCode:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,infoLogs:Je,isInitiatingAuth:!1});break;case"authorization_request":n({currentStep:"received_authorization_code",isInitiatingAuth:!1});break;case"received_authorization_code":{if(!k.authorizationCode||k.authorizationCode.trim()===""){n({error:"Authorization code is required. Please paste the code you received from the authorization server.",isInitiatingAuth:!1});return}if(!k.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");const z=Ur({clientId:k.clientId,clientSecret:k.clientSecret,tokenEndpointAuthMethod:Hr(_,k.tokenEndpointAuthMethod)}),se={grant_type:"authorization_code",code:k.authorizationCode,redirect_uri:w,...z.bodyParams};k.codeVerifier&&(se.code_verifier=k.codeVerifier),k.serverUrl&&I&&(se.resource=k.serverUrl);const ae={method:"POST",url:k.authorizationServerMetadata.token_endpoint,headers:{"Content-Type":"application/x-www-form-urlencoded",...z.headers},body:se};n({currentStep:"token_request",lastRequest:ae,lastResponse:void 0,...I?{}:{resourceIndicatorSuppressed:!0},accessToken:void 0,refreshToken:void 0,httpHistory:[...k.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:ae}],isInitiatingAuth:!1}),ie(50);return}case"token_request":if(!k.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!k.authorizationCode)throw new Error("Missing authorization code");if(!k.codeVerifier)throw new Error("PKCE code_verifier is missing - REQUIRED by 2025-03-26 spec for token exchange");try{const z=Ur({clientId:k.clientId,clientSecret:k.clientSecret,tokenEndpointAuthMethod:Hr(_,k.tokenEndpointAuthMethod)}),se=new URLSearchParams({grant_type:"authorization_code",code:k.authorizationCode,redirect_uri:w,code_verifier:k.codeVerifier||"",...z.bodyParams});k.serverUrl&&I&&se.set("resource",k.serverUrl);const ae=await L(k.authorizationServerMetadata.token_endpoint,{method:"POST",headers:{...ct(d,{"Content-Type":"application/x-www-form-urlencoded"}),...z.headers},body:se.toString()}),he={status:ae.status,statusText:ae.statusText,headers:ae.headers,body:ae.body},Oe=[...k.httpHistory||[]];if(Oe.length>0){const pe=Oe[Oe.length-1];pe.response=he,pe.duration=Date.now()-(pe.timestamp||Date.now())}if(!ae.ok){n({lastResponse:he,httpHistory:Oe,authorizationCode:void 0,error:ha(ae),isInitiatingAuth:!1});return}const we=ae.body;let Se=(M().infoLogs||[]).filter(pe=>pe.id!=="auth-code"&&pe.id!=="oauth-tokens"&&pe.id!=="token");if(k.authorizationCode&&(Se=[...Se,{id:"auth-code",level:"info",step:"received_authorization_code",label:"Authorization Code",data:{code:k.authorizationCode},timestamp:Date.now()}]),we.access_token){const pe={access_token:we.access_token};we.refresh_token&&(pe.refresh_token=we.refresh_token),Se=[...Se,{id:"oauth-tokens",level:"info",step:"received_access_token",label:"OAuth Tokens",data:pe,timestamp:Date.now()}]}if(we.access_token){const pe=Fr(we.access_token);if(pe){const me={...pe};me.exp&&(me.exp=`${me.exp} (${De(me.exp)})`),me.iat&&(me.iat=`${me.iat} (${De(me.iat)})`),me.nbf&&(me.nbf=`${me.nbf} (${De(me.nbf)})`);const Ee={...me};if(me.aud){const Ge=k.serverUrl,U=(Array.isArray(me.aud)?me.aud:[me.aud]).some(W=>W===Ge);Ee._validation={expected_audience:Ge,audience_matches:U,note:U?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else Ee._validation={note:"⚠ No audience claim found - server should validate token binding"};Se=[...Se,{id:"token",step:"received_access_token",level:"info",label:"Access Token (Decoded JWT)",data:Ee,timestamp:Date.now()}]}}if(we.id_token){const pe=Fr(we.id_token);if(pe){const me={...pe};me.exp&&(me.exp=`${me.exp} (${De(me.exp)})`),me.iat&&(me.iat=`${me.iat} (${De(me.iat)})`),me.nbf&&(me.nbf=`${me.nbf} (${De(me.nbf)})`),me.auth_time&&(me.auth_time=`${me.auth_time} (${De(me.auth_time)})`),me._note="OIDC ID Token - Used for user identity verification",Se=[...Se,{id:"id-token",step:"received_access_token",level:"info",label:"ID Token (OIDC - Decoded JWT)",data:me,timestamp:Date.now()}]}}n({currentStep:"received_access_token",accessToken:we.access_token,refreshToken:we.refresh_token,tokenType:we.token_type||"Bearer",expiresIn:we.expires_in,lastResponse:he,httpHistory:Oe,infoLogs:Se,error:void 0,isInitiatingAuth:!1})}catch(z){const se={status:0,statusText:"Network Error",headers:{},body:{error:z instanceof Error?z.message:String(z)}},ae=[...k.httpHistory||[]];if(ae.length>0){const he=ae[ae.length-1];he.response=se,he.duration=Date.now()-(he.timestamp||Date.now())}n({lastResponse:se,httpHistory:ae,error:`Token exchange failed: ${z instanceof Error?z.message:String(z)}`,isInitiatingAuth:!1})}break;case"received_access_token":if(!k.serverUrl||!k.accessToken)throw new Error("Missing server URL or access token");const Xe={method:"POST",url:k.serverUrl,headers:{Authorization:`Bearer ${k.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:Ut({protocolVersion:T,authMode:p,clientName:"MCP Inspector",clientVersion:"1.0.0",id:2})},Pe=ne(M(),"authenticated_mcp_request","authenticated-init","Authenticated MCP Initialize Request",{Request:"MCP initialize with OAuth bearer token","Protocol Version":"2025-03-26",Client:"MCP Inspector v1.0.0",Endpoint:k.serverUrl});n({currentStep:"authenticated_mcp_request",lastRequest:Xe,lastResponse:void 0,httpHistory:[...k.httpHistory||[],{step:"authenticated_mcp_request",timestamp:Date.now(),request:Xe}],infoLogs:Pe,isInitiatingAuth:!1}),ie(50);return;case"authenticated_mcp_request":if(!k.serverUrl||!k.accessToken)throw new Error("Missing server URL or access token");try{const z=await L(k.serverUrl,{method:"POST",headers:dt(d,{Authorization:`Bearer ${k.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(Ut({protocolVersion:T,authMode:p,clientName:"MCP Inspector",clientVersion:"1.0.0",id:2}))}),se={status:z.status,statusText:z.statusText,headers:z.headers,body:z.body},ae=[...k.httpHistory||[]];if(ae.length>0){const pe=ae[ae.length-1];pe.response=se,pe.duration=Date.now()-(pe.timestamp||Date.now())}if(!z.ok){if(z.status>=400&&z.status<500)try{const pe={method:"GET",url:k.serverUrl,headers:{Authorization:`Bearer ${k.accessToken}`,Accept:"text/event-stream"}},me={step:"complete",timestamp:Date.now(),request:pe};ae.push(me);const Ee=await L(k.serverUrl,{method:"GET",headers:{Authorization:`Bearer ${k.accessToken}`,Accept:"text/event-stream"}});me.response={status:Ee.status,statusText:Ee.statusText,headers:Ee.headers,body:Ee.body},me.duration=Date.now()-me.timestamp;const Ge=Ee.body;if(Ge&&typeof Ge=="object"&&Ge.isOldTransport&&Ge.endpoint){const U=Ge.endpoint,W=new URL(U,k.serverUrl).toString(),Y=ne(M(),"authenticated_mcp_request","http-sse-detected","HTTP+SSE Transport Detected (2024-11-05)",{Transport:"HTTP+SSE (2024-11-05 - Deprecated)","SSE Stream URL":k.serverUrl,"POST Endpoint":W,"First Event":Ge.events?.[0],"Migration Note":"This transport is deprecated. Please update your server to use the 2025-03-26 Streamable HTTP transport.","How It Works":"Client connected via GET for SSE stream. Subsequent requests use POST to: "+W});n({currentStep:"complete",lastResponse:{status:Ee.status,statusText:"OK - HTTP+SSE Transport",headers:Ee.headers,body:{transport:"HTTP+SSE (2024-11-05)",sseStreamUrl:k.serverUrl,postEndpoint:W,events:Ge.events}},httpHistory:ae,infoLogs:Y,error:void 0,isInitiatingAuth:!1});return}}catch(pe){console.error("GET fallback failed:",pe)}n({lastResponse:se,httpHistory:ae,error:da(z),isInitiatingAuth:!1});return}let he=M().infoLogs||[];const Oe=z.headers["content-type"]||"",we=Oe.includes("text/event-stream");let Se=null;if(we&&z.body?.transport==="sse"?Se=z.body.mcpResponse:Se=z.body,we&&Se?.result?.protocolVersion){const pe={Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Protocol Version":Se.result.protocolVersion};Se.result.serverInfo&&(pe["Server Name"]=Se.result.serverInfo.name,pe["Server Version"]=Se.result.serverInfo.version),Se.result.capabilities&&(pe.Capabilities=Se.result.capabilities),he=ne(M(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",pe)}else if(we)he=ne(M(),"authenticated_mcp_request","mcp-transport","MCP Transport Detected",{Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Content-Type":Oe,Note:"Server returned streaming response. Initialize response delivered via SSE stream.",Events:z.body?.events?`${z.body.events.length} events parsed`:"No events parsed"});else if(Se?.result?.protocolVersion){const pe={Transport:"Streamable HTTP","Response Format":"JSON","Protocol Version":Se.result.protocolVersion};Se.result.serverInfo&&(pe["Server Name"]=Se.result.serverInfo.name,pe["Server Version"]=Se.result.serverInfo.version),Se.result.capabilities&&(pe.Capabilities=Se.result.capabilities),he=ne(M(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",pe)}n({currentStep:"complete",lastResponse:se,httpHistory:ae,infoLogs:he,error:void 0,isInitiatingAuth:!1})}catch(z){const se=Tt(z),ae={status:0,statusText:"Network Error",headers:{},body:{error:se.message,details:se.details}},he=[...k.httpHistory||[]];if(he.length>0){const Se={...he[he.length-1],response:ae,duration:Date.now()-(he[he.length-1]?.timestamp||Date.now()),error:se};he[he.length-1]=Se}const Oe=M(),we=ne(Oe,"authenticated_mcp_request",`error-authenticated_mcp_request-${Date.now()}`,"Authenticated MCP request failed",{request:Oe.lastRequest,error:se},{level:"error",error:se});n({lastResponse:ae,httpHistory:he,infoLogs:we,error:`Authenticated MCP request failed: ${se.message}`,isInitiatingAuth:!1})}break;case"complete":n({isInitiatingAuth:!1});break;default:n({isInitiatingAuth:!1})}}catch(H){const oe=M(),$=Tt(H),Q=ne(oe,oe.currentStep,`error-${oe.currentStep}-${Date.now()}`,"Step failed",{step:oe.currentStep,request:oe.lastRequest,response:oe.lastResponse,error:$},{level:"error",error:$}),y=gn(oe.httpHistory,$),V={error:$.message,infoLogs:Q,isInitiatingAuth:!1};y&&(V.httpHistory=y),n(V)}},startGuidedFlow:async()=>{n({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{n(pa())}};return ee};function Fu(e){const t=new URL(e);if(t.pathname!=="/"&&t.pathname!==""){const r=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;return new URL(`/.well-known/oauth-protected-resource${r}`,t.origin).toString()}return new URL("/.well-known/oauth-protected-resource",t.origin).toString()}var Tp="Could not discover authorization server metadata.";function QP(e){if("error"in e){const t=e.error instanceof Error?e.error.message:String(e.error);return`${e.url} failed: ${t}`}return e.status>=200&&e.status<300?`${e.url} returned HTTP ${e.status} with no metadata document`:`${e.url} returned HTTP ${e.status}`}function qu(e){return e.length===0?`${Tp} No well-known URL was tried.`:`${Tp} ${e.map(QP).join("; ")}.`}function di(e,t){return kP({serverUrl:e.serverUrl??t,prmResource:e.resourceMetadata?.resource,resolved:e.resourceIndicator})}function ju(e){const t=e.state.serverUrl??e.fallbackServerUrl,r=e.prmResource?.trim();if(!r){const o='Protected Resource Metadata is missing its required "resource" identifier (RFC 9728 §2).';if(e.enforcement!=="warn")throw new Error(o);return{resourceIndicator:Cl({serverUrl:t}),infoLogs:ne({...e.state,infoLogs:e.infoLogs},"received_resource_metadata","resource-identifier-mismatch","Resource identifier missing",{"Server URL":t,Reason:o,Note:"The debugger will fall back to the server URL as the resource indicator, but strict MCP clients treat this metadata as invalid."},{level:"warning"})}}const n=Cl({serverUrl:t,prmResource:r}),i=e.enforcement!=="warn"&&n.status!=="valid",s=e.enforcement==="reject-rfc9728"&&!n.rfc9728Compliant;if(n.source==="prm"&&(i||s))throw new Error((s?n.rfc9728Reason:void 0)??n.reason??"Protected Resource Metadata advertises an unusable resource identifier.");return{resourceIndicator:n,infoLogs:LP(e.state,e.infoLogs,n,t)}}var eO=e=>di(e);function tO(e,t){return fa(e,t,{protocolVersion:"2025-06-18",includesProtectedResourceMetadata:!0,initialMcpMethod:"initialize",authorizationServerMetadata:{label:"GET Authorization server metadata endpoint",description:"Try RFC8414 path, then RFC8414 root (no OIDC support)"},pkce:{label:"Generate PKCE parameters",description:"Client generates code verifier and challenge (recommended), includes resource parameter"},resourceValue:eO})}function $p(e){const t=new URL(e),r=[];if(t.pathname==="/"||t.pathname==="")r.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString());else{const n=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;r.push(new URL(`/.well-known/oauth-authorization-server${n}`,t.origin).toString()),r.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString())}return r}var rO=e=>{const{state:t,getState:r,updateState:n,serverUrl:i,serverName:s,redirectUrl:o,requestExecutor:a,scheduleAutoAdvance:c,loadPreregisteredCredentials:l,dynamicRegistration:u,customScopes:h,customHeaders:d,resourceMetadataUrl:p,authMode:f,hasClientSecret:v=!1,strictConformance:m=!1,resourceIndicatorEnforcement:_="warn",requiredMetadataEnforcement:w="reject",registrationStrategy:S="dcr",emulation:T}=e,I=o,C=mn(T,"2025-06-18"),M=mn(T,Uu("2025-06-18")),L=Sa(T),q=Ea(u??{},T);if(S==="dcr"&&!q.client_name)throw new Error("Dynamic registration metadata must include client_name");const X=()=>r?r():t,ee=()=>di(X(),i),k=($,Q={})=>a({url:$,method:Q.method||"GET",headers:Pr(Q.headers),body:Q.body}),ie=$=>{const Q=la({authorizationServerMetadata:X().authorizationServerMetadata,hasClientSecret:!!($||v)});if(!Q.ok)throw new Error(Q.message);return Q.method},H=async $=>{const{clientId:Q,clientSecret:y}=await l?.({serverName:s,serverUrl:i})??{};if(!Q)return;const V=ie(y),K={"Client ID":Q,"Client Secret":y||v?"Configured":"Not provided (public client)","Token Auth Method":V,Note:$};return{clientId:Q,clientSecret:y||void 0,tokenEndpointAuthMethod:V,infoLogs:ne(X(),"received_client_credentials","preregistered-fallback","Pre-registered Client",K)}},oe={state:t,updateState:n,proceedToNextStep:async()=>{const $=X();n({isInitiatingAuth:!0});const Q=y=>{c?.(()=>{oe.proceedToNextStep()},y)};try{switch($.currentStep){case"idle":{const U=dt(d,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":C}),W=Ut({protocolVersion:M,authMode:f,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}),Y={method:"POST",url:i,headers:U,body:W};n({currentStep:"request_without_token",serverUrl:i,lastRequest:Y,lastResponse:void 0,httpHistory:[...$.httpHistory||[],{step:"request_without_token",timestamp:Date.now(),request:Y}],isInitiatingAuth:!1}),Q(50);return}case"request_without_token":if(!$.serverUrl)throw new Error("No server URL available");try{const U=await k($.serverUrl,{method:"POST",headers:dt(d,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":C}),body:JSON.stringify(Ut({protocolVersion:M,authMode:f,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}))}),W={status:U.status,statusText:U.statusText,headers:U.headers,body:U.body},Y=[...$.httpHistory||[]];if(Y.length>0){const R=Y[Y.length-1];R.response=W,R.duration=Date.now()-(R.timestamp||Date.now())}const g=vs({status:U.status,statusText:U.statusText,wwwAuthenticateHeader:U.headers["www-authenticate"],serverMessage:U.body?.error?.message});if(g.kind==="challenged"){const R=U.headers["www-authenticate"],E=ur(R),P=Du(E.scope);let F=R?ne($,"received_401_unauthorized","www-authenticate","WWW-Authenticate Header",{header:R,...P&&P.length>0?{scope:P.join(" ")}:{},"Received from":$.serverUrl||"Unknown"}):$.infoLogs;g.specCompliant||(F=va($,F,"received_401_unauthorized",W)),n({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:R||void 0,challengedScopes:P,lastResponse:W,httpHistory:Y,infoLogs:F,isInitiatingAuth:!1})}else if(g.kind==="anonymous_allowed"){const R=ne($,"received_401_unauthorized","optional-auth","Optional Authentication Detected",{message:"Server allows anonymous access",note:"Proceeding with OAuth discovery for authenticated features"});n({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:void 0,challengedScopes:void 0,lastResponse:W,httpHistory:Y,infoLogs:R,isInitiatingAuth:!1})}else throw n({lastResponse:W,httpHistory:Y}),new zr(g.message,U.status)}catch(U){throw U instanceof zr?U:new Error(`Failed to request MCP server: ${U instanceof Error?U.message:String(U)}`)}break;case"received_401_unauthorized":{const U=ur($.wwwAuthenticateHeader);let W=p||U.resource_metadata;if(!W&&$.serverUrl&&(W=Fu($.serverUrl)),!W)throw new Error("Could not determine resource metadata URL");const Y={method:"GET",url:W,headers:dt(d,{})};n({currentStep:"request_resource_metadata",resourceMetadataUrl:W,lastRequest:Y,lastResponse:void 0,httpHistory:[...$.httpHistory||[],{step:"request_resource_metadata",timestamp:Date.now(),request:Y}],isInitiatingAuth:!1}),Q(50);return}case"request_resource_metadata":if(!$.serverUrl)throw new Error("No server URL available");const y=[...$.httpHistory||[]];let V=y.length>0&&y[y.length-1]?.step==="request_resource_metadata"&&!y[y.length-1]?.response?y.pop():void 0;const K=[],le=U=>{if(!U)return{};if(U instanceof Headers){const W={};return U.forEach((Y,g)=>{W[g]=Y}),W}return Array.isArray(U)?Object.fromEntries(U):Object.fromEntries(Object.entries(U).map(([W,Y])=>[W,String(Y)]))},de=async(U,W={})=>{const Y=typeof U=="string"?U:U.toString(),g=Nu(i,Y,d,le(W.headers)),R=V?{...V,timestamp:Date.now(),request:{method:W.method||"GET",url:Y,headers:g,body:W.body}}:{step:"request_resource_metadata",timestamp:Date.now(),request:{method:W.method||"GET",url:Y,headers:g,body:W.body}};V=void 0,K.push(R);try{const E=await k(Y,{method:W.method||"GET",headers:g,body:W.body});R.response={status:E.status,statusText:E.statusText,headers:E.headers,body:E.body},R.duration=Date.now()-R.timestamp;const P={status:E.status,statusText:E.statusText,headers:E.headers},F=typeof E.body=="string"?E.body:JSON.stringify(E.body??{});return new Response(F,P)}catch(E){throw R.error=Tt(E),R.duration=Date.now()-R.timestamp,E}};try{const U=(p||ur($.wwwAuthenticateHeader).resource_metadata)&&$.resourceMetadataUrl?{resourceMetadataUrl:$.resourceMetadataUrl}:void 0,W=await ca($.serverUrl,U,de),Y=[...y,...K],g=K[K.length-1],R=zu({authorizationServers:W.authorization_servers,fallbackServerUrl:i,protocolVersion:"2025-06-18"}),E=R.authorizationServerUrl;if(R.error&&w!=="observe"){n({resourceMetadata:W,resourceMetadataUrl:g?.request?.url||$.resourceMetadataUrl,lastRequest:g?.request,lastResponse:g?.response,httpHistory:Y,error:R.error,isInitiatingAuth:!1});return}let P=$.infoLogs??[];R.error&&(P=ne({...X(),infoLogs:P},"received_resource_metadata","authorization-server-substituted","Derived: Authorization Server (not advertised)",{Finding:R.error,"Using instead":E}));const{resourceIndicator:F,infoLogs:B}=ju({state:$,fallbackServerUrl:i,prmResource:W.resource,enforcement:_,infoLogs:P});n({currentStep:"received_resource_metadata",resourceMetadata:W,resourceIndicator:F,resourceMetadataUrl:g?.request?.url||$.resourceMetadataUrl,authorizationServerUrl:E,lastRequest:g?.request,lastResponse:g?.response,httpHistory:Y,infoLogs:B,isInitiatingAuth:!1})}catch(U){const W=gn([...y,...K],Tt(U));throw n({lastResponse:K[K.length-1]?.response,httpHistory:W}),new Error(aa(U))}break;case"received_resource_metadata":if(!$.authorizationServerUrl)throw new Error("No authorization server URL available");const Ce={method:"GET",url:$p($.authorizationServerUrl)[0],headers:ct(d,{})};n({currentStep:"request_authorization_server_metadata",lastRequest:Ce,lastResponse:void 0,httpHistory:[...$.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:Ce}],isInitiatingAuth:!1}),Q(50);return;case"request_authorization_server_metadata":if(!$.authorizationServerUrl)throw new Error("No authorization server URL available");const Re=$p($.authorizationServerUrl);let _e=null;const ve=[];let Je={},Xe=null;for(const U of Re)try{const W=ct(d,{}),Y=[...$.httpHistory||[]];Y.length>0&&(Y[Y.length-1].request={method:"GET",url:U,headers:W}),n({lastRequest:{method:"GET",url:U,headers:W},httpHistory:Y});const g=await k(U,{method:"GET",headers:ct(d,{})});if(g.ok){_e=g.body,Je=g.headers,Xe=g,_e||ve.push({url:U,status:g.status});break}ve.push({url:U,status:g.status})}catch(W){ve.push({url:U,error:W});continue}if(!_e||!Xe)throw new Error(qu(ve));if(!_e.issuer)throw new Error(ma);if(!_e.authorization_endpoint)throw new Error("Authorization server metadata missing 'authorization_endpoint'");if(!_e.token_endpoint)throw new Error("Authorization server metadata missing 'token_endpoint'");if(!_e.response_types_supported?.includes("code"))throw new Error("Authorization server does not support 'code' response type");const Pe={status:Xe.status,statusText:Xe.statusText,headers:Je,body:_e},z=[...$.httpHistory||[]];z.length>0&&(z[z.length-1].response=Pe);const se=_e.code_challenge_methods_supported||[];se.includes("S256")?n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:_e,lastResponse:Pe,httpHistory:z,isInitiatingAuth:!1}):(console.warn("Authorization server may not support S256 PKCE method. Supported methods:",se),n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:_e,lastResponse:Pe,httpHistory:z,error:"Warning: Authorization server may not support S256 PKCE method",isInitiatingAuth:!1}));break;case"received_authorization_server_metadata":if(!$.authorizationServerMetadata)throw new Error("No authorization server metadata available");if(S==="preregistered"){const{clientId:U,clientSecret:W}=await l?.({serverName:s,serverUrl:i})??{};if(!U){n({error:"Pre-registered client ID is required. Please configure OAuth credentials in the server settings.",isInitiatingAuth:!1});return}const Y=ie(W),g={"Client ID":U,"Client Secret":W||v?"Configured":"Not provided (public client)","Token Auth Method":Y,Note:"Using pre-registered client credentials from server config (skipped DCR)"},R=ne(X(),"received_client_credentials","dcr","Pre-registered Client",g);n({currentStep:"received_client_credentials",clientId:U,clientSecret:W||void 0,tokenEndpointAuthMethod:Y,infoLogs:R,isInitiatingAuth:!1})}else if($.authorizationServerMetadata.registration_endpoint){const U=$.resourceMetadata?.scopes_supported||$.authorizationServerMetadata.scopes_supported,W=jr(T,{customScopes:h,challengedScopes:$.challengedScopes,supportedScopes:U}),Y=ba({registrationEndpoint:$.authorizationServerMetadata.registration_endpoint,redirectUri:I,dynamicRegistrationDefaults:q,scope:W,customHeaders:d});n({currentStep:"request_client_registration",lastRequest:Y,lastResponse:void 0,httpHistory:[...$.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:Y}],isInitiatingAuth:!1}),Q(50);return}else{if(m){n({error:ya,isInitiatingAuth:!1});return}const U=await H("Authorization server did not advertise registration_endpoint; using pre-registered client credentials.");if(!U){n({error:_a,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:U.clientId,clientSecret:U.clientSecret,tokenEndpointAuthMethod:U.tokenEndpointAuthMethod,infoLogs:U.infoLogs,error:void 0,isInitiatingAuth:!1})}break;case"request_client_registration":{if(!$.authorizationServerMetadata?.registration_endpoint)throw new Error("No registration endpoint available");if(!$.lastRequest?.body)throw new Error("No client metadata in request");const U=await wa({request:$.lastRequest,requestExecutor:a,httpHistory:$.httpHistory});if(U.status!=="registered"){if(n({lastResponse:U.response,httpHistory:U.httpHistory,error:U.error}),m){U.status==="invalid_response"&&n({isInitiatingAuth:!1});return}const Y=await H(U.fallbackNote);if(!Y){n({error:U.errorWithFallbackHint,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpointAuthMethod:Y.tokenEndpointAuthMethod,infoLogs:Y.infoLogs,error:void 0,isInitiatingAuth:!1});break}if(U.missingClientId){n({lastResponse:U.response,httpHistory:U.httpHistory,error:"Dynamic Client Registration response is missing a client_id.",isInitiatingAuth:!1});return}const W=ne(X(),"received_client_credentials","dcr","Dynamic Client Registration",U.infoLogData);n({currentStep:"received_client_credentials",clientId:U.credentials.clientId,clientSecret:U.credentials.clientSecret,tokenEndpointAuthMethod:ua(U.clientInfo),lastResponse:U.response,httpHistory:U.httpHistory,infoLogs:W,error:void 0,isInitiatingAuth:!1});break}case"received_client_credentials":const ae=qr(43),he=await ga(ae),Oe=ne(X(),"generate_pkce_parameters","pkce-generation","Generate PKCE Parameters",{code_challenge:he,method:"S256",...L?{resource:ee()||"Unknown"}:{resource:"(omitted — emulated client does not send RFC 8707 resource)"}});n({currentStep:"generate_pkce_parameters",codeVerifier:ae,codeChallenge:he,codeChallengeMethod:"S256",...L?{}:{resourceIndicatorSuppressed:!0},state:qr(16),infoLogs:Oe,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!$.authorizationServerMetadata?.authorization_endpoint||!$.clientId)throw new Error("Missing authorization endpoint or client ID");const we=new URL($.authorizationServerMetadata.authorization_endpoint);we.searchParams.set("response_type","code"),we.searchParams.set("client_id",$.clientId),we.searchParams.set("redirect_uri",I),we.searchParams.set("code_challenge",$.codeChallenge||""),we.searchParams.set("code_challenge_method","S256"),we.searchParams.set("state",$.state||"");const Se=ee();Se&&L&&we.searchParams.set("resource",Se);const pe=jr(T,{customScopes:h,challengedScopes:$.challengedScopes,supportedScopes:$.resourceMetadata?.scopes_supported||$.authorizationServerMetadata.scopes_supported});pe&&we.searchParams.set("scope",pe);const me=ne(X(),"authorization_request","auth-url","Authorization URL",{url:we.toString()});n({currentStep:"authorization_request",authorizationUrl:we.toString(),authorizationCode:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,infoLogs:me,isInitiatingAuth:!1});break;case"authorization_request":n({currentStep:"received_authorization_code",isInitiatingAuth:!1});break;case"received_authorization_code":{if(!$.authorizationCode||$.authorizationCode.trim()===""){n({error:"Authorization code is required. Please paste the code you received from the authorization server.",isInitiatingAuth:!1});return}if(!$.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");const U=Ur({clientId:$.clientId,clientSecret:$.clientSecret,tokenEndpointAuthMethod:Hr(T,$.tokenEndpointAuthMethod)}),W={grant_type:"authorization_code",code:$.authorizationCode,redirect_uri:I,...U.bodyParams};$.codeVerifier&&(W.code_verifier=$.codeVerifier);const Y=ee();Y&&L&&(W.resource=Y);const g={method:"POST",url:$.authorizationServerMetadata.token_endpoint,headers:{"Content-Type":"application/x-www-form-urlencoded",...U.headers},body:W};n({currentStep:"token_request",lastRequest:g,lastResponse:void 0,...L?{}:{resourceIndicatorSuppressed:!0},accessToken:void 0,refreshToken:void 0,httpHistory:[...$.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:g}],isInitiatingAuth:!1}),Q(50);return}case"token_request":if(!$.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!$.authorizationCode)throw new Error("Missing authorization code");if(!$.codeVerifier)throw new Error("PKCE code_verifier is missing - cannot exchange token");try{const U=Ur({clientId:$.clientId,clientSecret:$.clientSecret,tokenEndpointAuthMethod:Hr(T,$.tokenEndpointAuthMethod)}),W=new URLSearchParams({grant_type:"authorization_code",code:$.authorizationCode,redirect_uri:I,code_verifier:$.codeVerifier||"",...U.bodyParams}),Y=ee();Y&&L&&W.set("resource",Y);const g=await k($.authorizationServerMetadata.token_endpoint,{method:"POST",headers:{...ct(d,{"Content-Type":"application/x-www-form-urlencoded"}),...U.headers},body:W.toString()}),R={status:g.status,statusText:g.statusText,headers:g.headers,body:g.body},E=[...$.httpHistory||[]];if(E.length>0){const B=E[E.length-1];B.response=R,B.duration=Date.now()-(B.timestamp||Date.now())}if(!g.ok){n({lastResponse:R,httpHistory:E,authorizationCode:void 0,error:ha(g),isInitiatingAuth:!1});return}const P=g.body;let F=(X().infoLogs||[]).filter(B=>B.id!=="auth-code"&&B.id!=="oauth-tokens"&&B.id!=="token");if($.authorizationCode&&(F=[...F,{id:"auth-code",step:"token_request",level:"info",label:"Authorization Code",data:{code:$.authorizationCode},timestamp:Date.now()}]),P.access_token){const B={access_token:P.access_token};P.refresh_token&&(B.refresh_token=P.refresh_token),F=[...F,{id:"oauth-tokens",step:"token_request",level:"info",label:"OAuth Tokens",data:B,timestamp:Date.now()}]}if(P.access_token){const B=Fr(P.access_token);if(B){const D={...B};D.exp&&(D.exp=`${D.exp} (${De(D.exp)})`),D.iat&&(D.iat=`${D.iat} (${De(D.iat)})`),D.nbf&&(D.nbf=`${D.nbf} (${De(D.nbf)})`);const G={...D};if(D.aud){const J=$.serverUrl,qt=(Array.isArray(D.aud)?D.aud:[D.aud]).some(Gr=>Gr===J);G._validation={expected_audience:J,audience_matches:qt,note:qt?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else G._validation={note:"⚠ No audience claim found - server should validate token binding"};F=[...F,{id:"token",step:"token_request",level:"info",label:"Access Token (Decoded JWT)",data:G,timestamp:Date.now()}]}}if(P.id_token){const B=Fr(P.id_token);if(B){const D={...B};D.exp&&(D.exp=`${D.exp} (${De(D.exp)})`),D.iat&&(D.iat=`${D.iat} (${De(D.iat)})`),D.nbf&&(D.nbf=`${D.nbf} (${De(D.nbf)})`),D.auth_time&&(D.auth_time=`${D.auth_time} (${De(D.auth_time)})`),D._note="OIDC ID Token - Used for user identity verification",F=[...F,{id:"id-token",step:"token_request",level:"info",label:"ID Token (OIDC - Decoded JWT)",data:D,timestamp:Date.now()}]}}n({currentStep:"received_access_token",accessToken:P.access_token,refreshToken:P.refresh_token,tokenType:P.token_type||"Bearer",expiresIn:P.expires_in,lastResponse:R,httpHistory:E,infoLogs:F,error:void 0,isInitiatingAuth:!1})}catch(U){const W={status:0,statusText:"Network Error",headers:{},body:{error:U instanceof Error?U.message:String(U)}},Y=[...$.httpHistory||[]];if(Y.length>0){const g=Y[Y.length-1];g.response=W,g.duration=Date.now()-(g.timestamp||Date.now())}n({lastResponse:W,httpHistory:Y,error:`Token exchange failed: ${U instanceof Error?U.message:String(U)}`,isInitiatingAuth:!1})}break;case"received_access_token":if(!$.serverUrl||!$.accessToken)throw new Error("Missing server URL or access token");const Ee={method:"POST",url:$.serverUrl,headers:{Authorization:`Bearer ${$.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":C},body:Ut({protocolVersion:M,authMode:f,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:2})},Ge=ne(X(),"authenticated_mcp_request","authenticated-init","Authenticated MCP Initialize Request",{Request:"MCP initialize with OAuth bearer token","Protocol Version":"2025-06-18",Client:"MCPJam Inspector v1.0.0",Endpoint:$.serverUrl});n({currentStep:"authenticated_mcp_request",lastRequest:Ee,lastResponse:void 0,httpHistory:[...$.httpHistory||[],{step:"authenticated_mcp_request",timestamp:Date.now(),request:Ee}],infoLogs:Ge,isInitiatingAuth:!1}),Q(50);return;case"authenticated_mcp_request":if(!$.serverUrl||!$.accessToken)throw new Error("Missing server URL or access token");try{const U=await k($.serverUrl,{method:"POST",headers:dt(d,{Authorization:`Bearer ${$.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":C}),body:JSON.stringify(Ut({protocolVersion:M,authMode:f,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:2}))}),W={status:U.status,statusText:U.statusText,headers:U.headers,body:U.body},Y=[...$.httpHistory||[]];if(Y.length>0){const F=Y[Y.length-1];F.response=W,F.duration=Date.now()-(F.timestamp||Date.now())}if(!U.ok){n({lastResponse:W,httpHistory:Y,error:da(U),isInitiatingAuth:!1});return}let g=X().infoLogs||[];const R=U.headers["content-type"]||"",E=R.includes("text/event-stream");let P=null;if(E&&U.body?.transport==="sse"?P=U.body.mcpResponse:P=U.body,E&&P?.result?.protocolVersion){const F={Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Protocol Version":P.result.protocolVersion};P.result.serverInfo&&(F["Server Name"]=P.result.serverInfo.name,F["Server Version"]=P.result.serverInfo.version),P.result.capabilities&&(F.Capabilities=P.result.capabilities),g=ne(X(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",F)}else if(E)g=ne(X(),"authenticated_mcp_request","mcp-transport","MCP Transport Detected",{Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Content-Type":R,Note:"Server returned streaming response. Initialize response delivered via SSE stream.",Events:U.body?.events?`${U.body.events.length} events parsed`:"No events parsed"});else if(P?.result?.protocolVersion){const F={Transport:"Streamable HTTP","Response Format":"JSON","Protocol Version":P.result.protocolVersion};P.result.serverInfo&&(F["Server Name"]=P.result.serverInfo.name,F["Server Version"]=P.result.serverInfo.version),P.result.capabilities&&(F.Capabilities=P.result.capabilities),g=ne(X(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",F)}n({currentStep:"complete",lastResponse:W,httpHistory:Y,infoLogs:g,error:void 0,isInitiatingAuth:!1})}catch(U){const W=Tt(U),Y={status:0,statusText:"Network Error",headers:{},body:{error:W.message,details:W.details}},g=[...$.httpHistory||[]];if(g.length>0){const P={...g[g.length-1],response:Y,duration:Date.now()-(g[g.length-1]?.timestamp||Date.now()),error:W};g[g.length-1]=P}const R=X(),E=ne(R,"authenticated_mcp_request",`error-authenticated_mcp_request-${Date.now()}`,"Authenticated MCP request failed",{request:R.lastRequest,error:W},{level:"error",error:W});n({lastResponse:Y,httpHistory:g,infoLogs:E,error:`Authenticated MCP request failed: ${W.message}`,isInitiatingAuth:!1})}break;case"complete":n({isInitiatingAuth:!1});break;default:n({isInitiatingAuth:!1})}}catch(y){const V=X(),K=Tt(y),le=ne(V,V.currentStep,`error-${V.currentStep}-${Date.now()}`,"Step failed",{step:V.currentStep,request:V.lastRequest,response:V.lastResponse,error:K},{level:"error",error:K}),de=gn(V.httpHistory,K),Ce={error:K.message,infoLogs:le,isInitiatingAuth:!1};de&&(Ce.httpHistory=de),n(Ce)}},startGuidedFlow:async()=>{n({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{n(pa())}};return oe};function ka(e){const t=e.replace(/^\[|\]$/g,"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)||t==="::1"}function yD(e){try{const{protocol:t,hostname:r}=new URL(e);return t==="http:"&&ka(r)}catch{return!1}}function N_(e,t={}){let r;try{r=new URL(e)}catch{throw new Error("Client ID metadata URL must be a valid absolute URL")}const n=t.allowLoopback===!0&&r.protocol==="http:"&&ka(r.hostname);if(!n&&(r.protocol!=="https:"||!r.hostname))throw new Error("Client ID metadata URL must be an absolute HTTPS URL");const i=n?/^http:\/\//i:/^https:\/\//i;if(!i.test(e))throw new Error(n?"Client ID metadata URL must use the http:// scheme (with two slashes)":"Client ID metadata URL must use the https:// scheme (with two slashes)");if(/[\u0000-\u0020\u007f\\]/.test(e))throw new Error("Client ID metadata URL must not contain control characters, whitespace, or backslashes");if(r.hash||e.includes("#"))throw new Error("Client ID metadata URL must not contain a fragment component");const s=e.split(/[?#]/,1)[0].replace(i,""),o=s.indexOf("/"),a=o===-1?s:s.slice(0,o),c=o===-1?"":s.slice(o);if(!a)throw new Error("Client ID metadata URL must contain a host immediately after https://");if(r.username||r.password||a.includes("@"))throw new Error("Client ID metadata URL must not contain a userinfo component");if(!c)throw new Error("Client ID metadata URL must contain a path component");const l=u=>{const h=u.replace(/%2e/gi,".");return h==="."||h===".."};if(c.split("/").some(l))throw new Error("Client ID metadata URL must not contain single-dot or double-dot path segments");return e}var nO=e=>di(e);function iO(e,t){return fa(e,t,{protocolVersion:"2025-11-25",includesProtectedResourceMetadata:!0,initialMcpMethod:"initialize",authorizationServerMetadata:{label:"GET Authorization server metadata endpoint",description:"Try OAuth path insertion, OIDC path insertion, OIDC path appending"},pkce:{label:`Generate PKCE (REQUIRED)
98
- Include resource parameter`,description:"Client generates code verifier and challenge (REQUIRED), includes resource parameter"},resourceValue:nO})}function Cp(e){const t=new URL(e),r=[];if(t.pathname==="/"||t.pathname==="")r.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString()),r.push(new URL("/.well-known/openid-configuration",t.origin).toString());else{const n=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;r.push(new URL(`/.well-known/oauth-authorization-server${n}`,t.origin).toString()),r.push(new URL(`/.well-known/openid-configuration${n}`,t.origin).toString()),r.push(new URL(`${n}/.well-known/openid-configuration`,t.origin).toString())}return r}var sO=e=>{const{state:t,getState:r,updateState:n,serverUrl:i,serverName:s,redirectUrl:o,requestExecutor:a,scheduleAutoAdvance:c,loadPreregisteredCredentials:l,dynamicRegistration:u,clientIdMetadataUrl:h,customScopes:d,customHeaders:p,resourceMetadataUrl:f,authMode:v,hasClientSecret:m=!1,strictConformance:_=!1,resourceIndicatorEnforcement:w="warn",requiredMetadataEnforcement:S="reject",registrationStrategy:T="cimd",emulation:I}=e,C=o,M=mn(I,"2025-11-25"),L=mn(I,Uu("2025-11-25")),q=Sa(I),X=Ea(u??{},I);let ee=h??"";if(T==="dcr"&&!X.client_name)throw new Error("Dynamic registration metadata must include client_name");if(T==="cimd"&&!ee)throw new Error("Client ID metadata URL is required for CIMD registration");T==="cimd"&&(ee=N_(ee));const k=()=>r?r():t,ie=()=>di(k(),i),H=(y,V={})=>a({url:y,method:V.method||"GET",headers:Pr(V.headers),body:V.body}),oe=y=>{const V=la({authorizationServerMetadata:k().authorizationServerMetadata,hasClientSecret:!!(y||m)});if(!V.ok)throw new Error(V.message);return V.method},$=async y=>{const{clientId:V,clientSecret:K}=await l?.({serverName:s,serverUrl:i})??{};if(!V)return;const le=oe(K),de={"Client ID":V,"Client Secret":K||m?"Configured":"Not provided (public client)","Token Auth Method":le,Note:y};return{clientId:V,clientSecret:K||void 0,tokenEndpointAuthMethod:le,infoLogs:ne(k(),"received_client_credentials","preregistered-fallback","Pre-registered Client",de)}},Q={state:t,updateState:n,proceedToNextStep:async()=>{const y=k();n({isInitiatingAuth:!0});const V=K=>{c?.(()=>{Q.proceedToNextStep()},K)};try{switch(y.currentStep){case"idle":{const g=dt(p,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":M}),R=Ut({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}),E={method:"POST",url:i,headers:g,body:R};n({currentStep:"request_without_token",serverUrl:i,lastRequest:E,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_without_token",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),V(50);return}case"request_without_token":if(!y.serverUrl)throw new Error("No server URL available");try{const g=await H(y.serverUrl,{method:"POST",headers:dt(p,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":M}),body:JSON.stringify(Ut({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}))}),R={status:g.status,statusText:g.statusText,headers:g.headers,body:g.body},E=[...y.httpHistory||[]];if(E.length>0){const F=E[E.length-1];F.response=R,F.duration=Date.now()-(F.timestamp||Date.now())}const P=vs({status:g.status,statusText:g.statusText,wwwAuthenticateHeader:g.headers["www-authenticate"],serverMessage:g.body?.error?.message});if(P.kind==="challenged"){const F=g.headers["www-authenticate"],B=ur(F),D=Du(B.scope);let G=F?ne(y,"received_401_unauthorized","www-authenticate","WWW-Authenticate Header",{header:F,...D&&D.length>0?{scope:D.join(" ")}:{},"Received from":y.serverUrl||"Unknown"}):y.infoLogs;P.specCompliant||(G=va(y,G,"received_401_unauthorized",R)),n({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:F||void 0,challengedScopes:D,lastResponse:R,httpHistory:E,infoLogs:G,isInitiatingAuth:!1})}else if(P.kind==="anonymous_allowed"){const F=ne(y,"received_401_unauthorized","optional-auth","Optional Authentication Detected",{message:"Server allows anonymous access",note:"Proceeding with OAuth discovery for authenticated features"});n({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:void 0,lastResponse:R,httpHistory:E,infoLogs:F,isInitiatingAuth:!1})}else throw n({lastResponse:R,httpHistory:E}),new zr(P.message,g.status)}catch(g){throw g instanceof zr?g:new Error(`Failed to request MCP server: ${g instanceof Error?g.message:String(g)}`)}break;case"received_401_unauthorized":{const g=ur(y.wwwAuthenticateHeader);let R=f||g.resource_metadata;if(!R&&y.serverUrl&&(R=Fu(y.serverUrl)),!R)throw new Error("Could not determine resource metadata URL");const E={method:"GET",url:R,headers:dt(p,{})};n({currentStep:"request_resource_metadata",resourceMetadataUrl:R,lastRequest:E,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_resource_metadata",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),V(50);return}case"request_resource_metadata":if(!y.serverUrl)throw new Error("No server URL available");const K=[...y.httpHistory||[]];let le=K.length>0&&K[K.length-1]?.step==="request_resource_metadata"&&!K[K.length-1]?.response?K.pop():void 0;const de=[],Ce=async(g,R={})=>{const E=typeof g=="string"?g:g.toString(),P=Nu(i,E,p,Pr(R.headers)),F=le?{...le,timestamp:Date.now(),request:{method:R.method||"GET",url:E,headers:P,body:R.body}}:{step:"request_resource_metadata",timestamp:Date.now(),request:{method:R.method||"GET",url:E,headers:P,body:R.body}};le=void 0,de.push(F);try{const B=await H(E,{method:R.method||"GET",headers:P,body:R.body});F.response={status:B.status,statusText:B.statusText,headers:B.headers,body:B.body},F.duration=Date.now()-F.timestamp;const D={status:B.status,statusText:B.statusText,headers:B.headers},G=typeof B.body=="string"?B.body:JSON.stringify(B.body??{});return new Response(G,D)}catch(B){throw F.error=Tt(B),F.duration=Date.now()-F.timestamp,B}};try{const g=(f||ur(y.wwwAuthenticateHeader).resource_metadata)&&y.resourceMetadataUrl?{resourceMetadataUrl:y.resourceMetadataUrl}:void 0,R=await ca(y.serverUrl,g,Ce),E=[...K,...de],P=de[de.length-1],F=zu({authorizationServers:R.authorization_servers,fallbackServerUrl:i,protocolVersion:"2025-11-25"}),B=F.authorizationServerUrl;if(F.error&&S!=="observe"){n({resourceMetadata:R,resourceMetadataUrl:P?.request?.url||y.resourceMetadataUrl,lastRequest:P?.request,lastResponse:P?.response,httpHistory:E,error:F.error,isInitiatingAuth:!1});return}let D=y.infoLogs??[];F.error&&(D=ne({...k(),infoLogs:D},"received_resource_metadata","authorization-server-substituted","Derived: Authorization Server (not advertised)",{Finding:F.error,"Using instead":B}));const G=ju({state:y,fallbackServerUrl:i,prmResource:R.resource,enforcement:w,infoLogs:D}),J=G.resourceIndicator;D=G.infoLogs,n({currentStep:"received_resource_metadata",resourceMetadata:R,resourceIndicator:J,resourceMetadataUrl:P?.request?.url||y.resourceMetadataUrl,authorizationServerUrl:B,lastRequest:P?.request,lastResponse:P?.response,httpHistory:E,infoLogs:D,isInitiatingAuth:!1})}catch(g){const R=gn([...K,...de],Tt(g));throw n({lastResponse:de[de.length-1]?.response,httpHistory:R}),new Error(aa(g))}break;case"received_resource_metadata":if(!y.authorizationServerUrl)throw new Error("No authorization server URL available");const Re={method:"GET",url:Cp(y.authorizationServerUrl)[0],headers:ct(p,{})};n({currentStep:"request_authorization_server_metadata",lastRequest:Re,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:Re}],isInitiatingAuth:!1}),V(50);return;case"request_authorization_server_metadata":if(!y.authorizationServerUrl)throw new Error("No authorization server URL available");const _e=Cp(y.authorizationServerUrl);let ve=null;const Je=[];let Xe={},Pe=null;for(const g of _e)try{const R=ct(p,{}),E=[...y.httpHistory||[]];E.length>0&&(E[E.length-1].request={method:"GET",url:g,headers:R}),n({lastRequest:{method:"GET",url:g,headers:R},httpHistory:E});const P=await H(g,{method:"GET",headers:ct(p,{})});if(P.ok){ve=P.body,Xe=P.headers,Pe=P,ve||Je.push({url:g,status:P.status});break}Je.push({url:g,status:P.status})}catch(R){Je.push({url:g,error:R});continue}if(!ve||!Pe)throw new Error(qu(Je));if(!ve.issuer)throw new Error(ma);if(!ve.authorization_endpoint)throw new Error("Authorization server metadata missing 'authorization_endpoint'");if(!ve.token_endpoint)throw new Error("Authorization server metadata missing 'token_endpoint'");if(!ve.response_types_supported?.includes("code"))throw new Error("Authorization server does not support 'code' response type");const z={status:Pe.status,statusText:Pe.statusText,headers:Xe,body:ve},se=[...y.httpHistory||[]];if(se.length>0){const g=se[se.length-1];g.response=z,g.duration=Date.now()-(g.timestamp||Date.now())}const ae=ve.code_challenge_methods_supported||[],he=L_(ae,"2025-11-25"),Oe=typeof ve.client_id_metadata_document_supported=="boolean"?ve.client_id_metadata_document_supported:"false (not advertised, defaults to false per spec)",we=ne(k(),"received_authorization_server_metadata","cimd-support","Derived: CIMD Support",{"CIMD Supported":Oe});if(he){if(_||S!=="observe"){n({lastResponse:z,httpHistory:se,infoLogs:we,error:he,isInitiatingAuth:!1});return}console.warn("Authorization server may not support S256 PKCE method. Supported methods:",ae),n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:ve,lastResponse:z,httpHistory:se,infoLogs:we,error:"Warning: Authorization server may not support S256 PKCE method",isInitiatingAuth:!1})}else n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:ve,lastResponse:z,httpHistory:se,infoLogs:we,isInitiatingAuth:!1});break;case"received_authorization_server_metadata":if(!y.authorizationServerMetadata)throw new Error("No authorization server metadata available");if(T==="cimd"){if(y.authorizationServerMetadata.client_id_metadata_document_supported!==!0){n({error:"The authorization server does not support Client ID Metadata Documents (client_id_metadata_document_supported is not advertised in AS metadata). Try using 'dcr' or 'preregistered' registration strategy instead.",isInitiatingAuth:!1});return}n({currentStep:"cimd_prepare",clientId:ee,isInitiatingAuth:!1}),V(800);return}else if(T==="preregistered"){const{clientId:g,clientSecret:R}=await l?.({serverName:s,serverUrl:i})??{};if(!g){n({error:"Pre-registered client ID is required. Please configure OAuth credentials in the server settings.",isInitiatingAuth:!1});return}const E=oe(R),P={"Client ID":g,"Client Secret":R||m?"Configured":"Not provided (public client)","Token Auth Method":E,Note:"Using pre-registered client credentials from server config (skipped DCR)"},F=ne(k(),"received_client_credentials","dcr","Pre-registered Client",P);n({currentStep:"received_client_credentials",clientId:g,clientSecret:R||void 0,tokenEndpointAuthMethod:E,infoLogs:F,isInitiatingAuth:!1})}else if(y.authorizationServerMetadata.registration_endpoint){const g=y.resourceMetadata?.scopes_supported||y.authorizationServerMetadata.scopes_supported,R=jr(I,{customScopes:d,challengedScopes:y.challengedScopes,supportedScopes:g}),E=ba({registrationEndpoint:y.authorizationServerMetadata.registration_endpoint,redirectUri:C,dynamicRegistrationDefaults:X,scope:R,customHeaders:p});n({currentStep:"request_client_registration",lastRequest:E,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),V(50);return}else{if(_){n({error:ya,isInitiatingAuth:!1});return}const g=await $("Authorization server did not advertise registration_endpoint; using pre-registered client credentials.");if(!g){n({error:_a,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:g.clientId,clientSecret:g.clientSecret,tokenEndpointAuthMethod:g.tokenEndpointAuthMethod,infoLogs:g.infoLogs,error:void 0,isInitiatingAuth:!1})}break;case"request_client_registration":if(!y.authorizationServerMetadata?.registration_endpoint)throw new Error("No registration endpoint available");if(!y.lastRequest?.body)throw new Error("No client metadata in request");{const g=await wa({request:y.lastRequest,requestExecutor:a,httpHistory:y.httpHistory});if(g.status!=="registered"){if(n({lastResponse:g.response,httpHistory:g.httpHistory,error:g.error,isInitiatingAuth:!1}),_)return;const E=await $(g.fallbackNote);if(!E){n({error:g.errorWithFallbackHint,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:E.clientId,clientSecret:E.clientSecret,tokenEndpointAuthMethod:E.tokenEndpointAuthMethod,infoLogs:E.infoLogs,error:void 0,isInitiatingAuth:!1});break}if(g.missingClientId){n({lastResponse:g.response,httpHistory:g.httpHistory,error:"Dynamic Client Registration response is missing a client_id.",isInitiatingAuth:!1});return}const R=ne(k(),"received_client_credentials","dcr","Dynamic Client Registration",g.infoLogData);n({currentStep:"received_client_credentials",clientId:g.credentials.clientId,clientSecret:g.credentials.clientSecret,tokenEndpointAuthMethod:ua(g.clientInfo),lastResponse:g.response,httpHistory:g.httpHistory,infoLogs:R,error:void 0,isInitiatingAuth:!1})}break;case"cimd_prepare":n({currentStep:"cimd_fetch_request",isInitiatingAuth:!1}),V(800);return;case"cimd_fetch_request":try{const g={method:"GET",url:ee,headers:Pr(void 0)},R=Date.now(),E=await H(ee,{method:"GET"});if(!E.ok)throw new Error(`CIMD endpoint returned HTTP ${E.status}`);const P={status:E.status,statusText:E.statusText,headers:E.headers,body:E.body};n({currentStep:"cimd_metadata_response",lastRequest:g,lastResponse:P,httpHistory:[...y.httpHistory||[],{step:"cimd_fetch_request",timestamp:R,duration:Date.now()-R,request:g,response:P}],isInitiatingAuth:!1}),V(800);return}catch(g){n({error:`CIMD metadata fetch failed: ${g instanceof Error?g.message:String(g)}. Try using 'dcr' or 'preregistered' registration strategy instead.`,isInitiatingAuth:!1});return}case"cimd_metadata_response":try{const g=y.lastResponse?.body;if(!g||typeof g!="object")throw new Error("CIMD metadata document was not available");if(g.client_id!==ee)throw new Error("CIMD client_id mismatch");const R=y.authorizationServerMetadata?.client_id_metadata_document_supported,E={"Client ID":ee,"Registration Method":"Client ID Metadata Document (CIMD)","Client Name":g.client_name||"MCPJam","Redirect URIs":g.redirect_uris||[],"Token Auth Method":g.token_endpoint_auth_method||"none",Validation:"✓ Metadata fetched and validated",Note:"Server fetched and validated client metadata from URL"};R?E["Server Support"]="✓ Advertised in metadata (client_id_metadata_document_supported: true)":E["Server Support"]="⚠ Not advertised (attempting anyway)";const P=ne(k(),"received_client_credentials","cimd","Client ID Metadata Document",E);n({currentStep:"received_client_credentials",clientId:ee,clientSecret:void 0,tokenEndpointAuthMethod:"none",infoLogs:P,isInitiatingAuth:!1})}catch(g){n({error:`CIMD validation failed: ${g instanceof Error?g.message:String(g)}. Try using 'dcr' or 'preregistered' registration strategy instead.`,isInitiatingAuth:!1});return}break;case"received_client_credentials":const Se=qr(43),pe=await ga(Se),me=ne(k(),"generate_pkce_parameters","pkce-generation","Generate PKCE Parameters",{code_challenge:pe,method:"S256",...q?{resource:ie()}:{resource:"(omitted — emulated client does not send RFC 8707 resource)"}});n({currentStep:"generate_pkce_parameters",codeVerifier:Se,codeChallenge:pe,codeChallengeMethod:"S256",...q?{}:{resourceIndicatorSuppressed:!0},state:qr(16),infoLogs:me,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!y.authorizationServerMetadata?.authorization_endpoint||!y.clientId)throw new Error("Missing authorization endpoint or client ID");const Ee=new URL(y.authorizationServerMetadata.authorization_endpoint);Ee.searchParams.set("response_type","code"),Ee.searchParams.set("client_id",y.clientId),Ee.searchParams.set("redirect_uri",C),Ee.searchParams.set("code_challenge",y.codeChallenge||""),Ee.searchParams.set("code_challenge_method","S256"),Ee.searchParams.set("state",y.state||""),q&&Ee.searchParams.set("resource",ie());const Ge=jr(I,{customScopes:d,challengedScopes:y.challengedScopes,supportedScopes:y.resourceMetadata?.scopes_supported||y.authorizationServerMetadata.scopes_supported});Ge&&Ee.searchParams.set("scope",Ge);const U=ne(k(),"authorization_request","auth-url","Authorization URL",{url:Ee.toString()});n({currentStep:"authorization_request",authorizationUrl:Ee.toString(),authorizationCode:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,infoLogs:U,isInitiatingAuth:!1});break;case"authorization_request":n({currentStep:"received_authorization_code",isInitiatingAuth:!1});break;case"received_authorization_code":{if(!y.authorizationCode||y.authorizationCode.trim()===""){n({error:"Authorization code is required. Please paste the code you received from the authorization server.",isInitiatingAuth:!1});return}if(!y.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");const g=Ur({clientId:y.clientId,clientSecret:y.clientSecret,tokenEndpointAuthMethod:Hr(I,y.tokenEndpointAuthMethod)}),R={grant_type:"authorization_code",code:y.authorizationCode,redirect_uri:C,...g.bodyParams};y.codeVerifier&&(R.code_verifier=y.codeVerifier),q&&(R.resource=ie());const E={method:"POST",url:y.authorizationServerMetadata.token_endpoint,headers:{"Content-Type":"application/x-www-form-urlencoded",...g.headers},body:R};n({currentStep:"token_request",lastRequest:E,lastResponse:void 0,...q?{}:{resourceIndicatorSuppressed:!0},accessToken:void 0,refreshToken:void 0,httpHistory:[...y.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),V(50);return}case"token_request":if(!y.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!y.authorizationCode)throw new Error("Missing authorization code");if(!y.codeVerifier)throw new Error("PKCE code_verifier is missing - cannot exchange token");try{const g=Ur({clientId:y.clientId,clientSecret:y.clientSecret,tokenEndpointAuthMethod:Hr(I,y.tokenEndpointAuthMethod)}),R=new URLSearchParams({grant_type:"authorization_code",code:y.authorizationCode,redirect_uri:C,code_verifier:y.codeVerifier||"",...g.bodyParams});q&&R.set("resource",ie());const E=await H(y.authorizationServerMetadata.token_endpoint,{method:"POST",headers:{...ct(p,{"Content-Type":"application/x-www-form-urlencoded"}),...g.headers},body:R.toString()}),P={status:E.status,statusText:E.statusText,headers:E.headers,body:E.body},F=[...y.httpHistory||[]];if(F.length>0){const G=F[F.length-1];G.response=P,G.duration=Date.now()-(G.timestamp||Date.now())}if(!E.ok){n({lastResponse:P,httpHistory:F,authorizationCode:void 0,error:ha(E),isInitiatingAuth:!1});return}const B=E.body;let D=(k().infoLogs||[]).filter(G=>G.id!=="auth-code"&&G.id!=="oauth-tokens"&&G.id!=="token");if(y.authorizationCode&&(D=[...D,{id:"auth-code",level:"info",step:"authorization_request",label:"Authorization Code",data:{code:y.authorizationCode},timestamp:Date.now()}]),B.access_token){const G={access_token:B.access_token};B.refresh_token&&(G.refresh_token=B.refresh_token),D=[...D,{id:"oauth-tokens",level:"info",step:"token_request",label:"OAuth Tokens",data:G,timestamp:Date.now()}]}if(B.access_token){const G=Fr(B.access_token);if(G){const J={...G};J.exp&&(J.exp=`${J.exp} (${De(J.exp)})`),J.iat&&(J.iat=`${J.iat} (${De(J.iat)})`),J.nbf&&(J.nbf=`${J.nbf} (${De(J.nbf)})`);const qt={...J};if(J.aud){const Gr=y.serverUrl,hi=(Array.isArray(J.aud)?J.aud:[J.aud]).some(Ta=>Ta===Gr);qt._validation={expected_audience:Gr,audience_matches:hi,note:hi?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else qt._validation={note:"⚠ No audience claim found - server should validate token binding"};D=[...D,{id:"token",level:"info",step:"token_request",label:"Access Token (Decoded JWT)",data:qt,timestamp:Date.now()}]}}if(B.id_token){const G=Fr(B.id_token);if(G){const J={...G};J.exp&&(J.exp=`${J.exp} (${De(J.exp)})`),J.iat&&(J.iat=`${J.iat} (${De(J.iat)})`),J.nbf&&(J.nbf=`${J.nbf} (${De(J.nbf)})`),J.auth_time&&(J.auth_time=`${J.auth_time} (${De(J.auth_time)})`),J._note="OIDC ID Token - Used for user identity verification",D=[...D,{id:"id-token",level:"info",step:"token_request",label:"ID Token (OIDC - Decoded JWT)",data:J,timestamp:Date.now()}]}}n({currentStep:"received_access_token",accessToken:B.access_token,refreshToken:B.refresh_token,tokenType:B.token_type||"Bearer",expiresIn:B.expires_in,lastResponse:P,httpHistory:F,infoLogs:D,error:void 0,isInitiatingAuth:!1})}catch(g){const R={status:0,statusText:"Network Error",headers:{},body:{error:g instanceof Error?g.message:String(g)}},E=[...y.httpHistory||[]];if(E.length>0){const P=E[E.length-1];P.response=R,P.duration=Date.now()-(P.timestamp||Date.now())}n({lastResponse:R,httpHistory:E,error:`Token exchange failed: ${g instanceof Error?g.message:String(g)}`,isInitiatingAuth:!1})}break;case"received_access_token":if(!y.serverUrl||!y.accessToken)throw new Error("Missing server URL or access token");const W={method:"POST",url:y.serverUrl,headers:{Authorization:`Bearer ${y.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":M},body:Ut({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:2})},Y=ne(k(),"authenticated_mcp_request","authenticated-init","Authenticated MCP Initialize Request",{Request:"MCP initialize with OAuth bearer token","Protocol Version":"2025-11-25",Client:"MCPJam Inspector v1.0.0",Endpoint:y.serverUrl});n({currentStep:"authenticated_mcp_request",lastRequest:W,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"authenticated_mcp_request",timestamp:Date.now(),request:W}],infoLogs:Y,isInitiatingAuth:!1}),V(50);return;case"authenticated_mcp_request":if(!y.serverUrl||!y.accessToken)throw new Error("Missing server URL or access token");try{const g=await H(y.serverUrl,{method:"POST",headers:dt(p,{Authorization:`Bearer ${y.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":M}),body:JSON.stringify(Ut({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:2}))}),R={status:g.status,statusText:g.statusText,headers:g.headers,body:g.body},E=[...y.httpHistory||[]];if(E.length>0){const G=E[E.length-1];G.response=R,G.duration=Date.now()-(G.timestamp||Date.now())}if(!g.ok){n({lastResponse:R,httpHistory:E,error:da(g),isInitiatingAuth:!1});return}let P=k().infoLogs||[];const F=g.headers["content-type"]||"",B=F.includes("text/event-stream");let D=null;if(B&&g.body?.transport==="sse"?D=g.body.mcpResponse:D=g.body,B&&D?.result?.protocolVersion){const G={Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Protocol Version":D.result.protocolVersion};D.result.serverInfo&&(G["Server Name"]=D.result.serverInfo.name,G["Server Version"]=D.result.serverInfo.version),D.result.capabilities&&(G.Capabilities=D.result.capabilities),P=ne(k(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",G)}else if(B)P=ne(k(),"authenticated_mcp_request","mcp-transport","MCP Transport Detected",{Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Content-Type":F,Note:"Server returned streaming response. Initialize response delivered via SSE stream.",Events:g.body?.events?`${g.body.events.length} events parsed`:"No events parsed"});else if(D?.result?.protocolVersion){const G={Transport:"Streamable HTTP","Response Format":"JSON","Protocol Version":D.result.protocolVersion};D.result.serverInfo&&(G["Server Name"]=D.result.serverInfo.name,G["Server Version"]=D.result.serverInfo.version),D.result.capabilities&&(G.Capabilities=D.result.capabilities),P=ne(k(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",G)}n({currentStep:"complete",lastResponse:R,httpHistory:E,infoLogs:P,error:void 0,isInitiatingAuth:!1})}catch(g){const R={status:0,statusText:"Network Error",headers:{},body:{error:g instanceof Error?g.message:String(g)}},E=[...y.httpHistory||[]];if(E.length>0){const P=E[E.length-1];P.response=R,P.duration=Date.now()-(P.timestamp||Date.now())}n({lastResponse:R,httpHistory:E,error:`Authenticated MCP request failed: ${g instanceof Error?g.message:String(g)}`,isInitiatingAuth:!1})}break;case"complete":n({isInitiatingAuth:!1});break;default:n({isInitiatingAuth:!1})}}catch(K){const le=k(),de=Tt(K),Ce=ne(le,le.currentStep,`error-${le.currentStep}-${Date.now()}`,"Step failed",{step:le.currentStep,request:le.lastRequest,response:le.lastResponse,error:de},{level:"error",error:de}),Re=gn(le.httpHistory,de),_e={error:de.message,infoLogs:Ce,isInitiatingAuth:!1};Re&&(_e.httpHistory=Re),n(_e)}},startGuidedFlow:async()=>{n({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{n(pa())}};return Q},oO=e=>di(e);function aO(e){const t=e.requestedScopes??[],r=e.challengedScopes??[],n=[];if(t.length>0&&n.push({label:"requested scopes",value:t.join(" ")}),r.length>0){const i=vP(t,r);n.push({label:"challenged scopes",value:r.join(" ")}),n.push({label:"scope union",value:i.join(" ")})}return n}function cO(e){const t=e.recordedIssuer??e.authorizationServerMetadata?.issuer;return t?[{label:"bound to issuer",value:t}]:[]}function lO(e,t){return fa(e,t,{protocolVersion:"2026-07-28",includesProtectedResourceMetadata:!0,initialMcpMethod:"tools/list",authorizationServerMetadata:{label:"GET Authorization server metadata endpoint",description:"Try OAuth path insertion, OIDC path insertion, OIDC path appending"},pkce:{label:`Generate PKCE (REQUIRED)
99
- Include resource parameter`,description:"Client generates code verifier and challenge (REQUIRED), includes resource parameter"},resourceValue:oO,dcrNotes:[{label:"Deprecated",value:"DCR is deprecated in 2026-07-28 (PR #2858). Prefer CIMD or a pre-registered client; DCR remains a compatibility fallback for authorization servers without CIMD support."}],clientCredentialsExtras:cO,authorizationRequestExtras:aO})}function Pp(e){const t=new URL(e),r=[];if(t.pathname==="/"||t.pathname==="")r.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString()),r.push(new URL("/.well-known/openid-configuration",t.origin).toString());else{const n=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;r.push(new URL(`/.well-known/oauth-authorization-server${n}`,t.origin).toString()),r.push(new URL(`/.well-known/openid-configuration${n}`,t.origin).toString()),r.push(new URL(`${n}/.well-known/openid-configuration`,t.origin).toString())}return r}function Op(e){const t=e.replace(/[\u0000-\u001f\u007f\u0085\u2028\u2029]+/g," ").trim();return`\`${t.length>256?`${t.slice(0,256)}…`:t}\``}function uO(e,t){let r,n;try{r=new URL(e),n=new URL(t)}catch{return!1}if(r.origin!==n.origin||r.search||r.hash||n.search||n.hash)return!1;const i=a=>a.endsWith("/")?a.slice(0,-1):a,s=i(r.pathname),o=i(n.pathname);return s===o?!1:s===""||s==="/"?o.length>0:o.startsWith(`${s}/`)}function dO(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}function xp(e,t){return e==null?!1:typeof e!="string"?!0:!dO(e,t)}function Mp(e){return typeof e=="string"?`"${e}"`:"a non-string value"}function hO(e){const{advertisedIssuer:t,discoveryUrl:r,tokenEndpoint:n,registrationEndpoint:i,allowPathScopedIssuer:s}=e,o=uO(t,r),a=s&&o,c=a&&xp(n,t),l=a&&xp(i,t);return a&&!c&&!l?{accepted:!0,hint:""}:{accepted:!1,hint:c?` The path-scoped authorization server's token endpoint (${Mp(n)}) is not on the same origin as its issuer ("${t}"); refusing to send credentials off-origin.`:l?` The path-scoped authorization server's registration endpoint (${Mp(i)}) is not on the same origin as its issuer ("${t}"); refusing dynamic registration off-origin.`:o?` The advertised issuer is the same-origin root of the discovery URL — a multi-tenant, path-scoped authorization server. Enable "Path-scoped authorization server" in the server's OAuth configuration (Advanced settings) to allow this.`:""}}function pO(e){const{recordedIssuer:t,returnedIss:r,issParameterSupported:n,enforcePresentIssMismatch:i=!0}=e;if(r!=null&&r!==""){if(t!==void 0&&r!==t){const s=`Authorization response \`iss\` does not match the issuer this flow started with. Recorded from authorization-server metadata: ${Op(t)}; returned on the callback: ${Op(r)}.`;return i?{ok:!1,reason:`${s} Refusing to exchange the authorization code; not displaying any server-supplied error parameters (RFC 9207).`}:{ok:!0,warning:`${s} This protocol version does not require RFC 9207 issuer validation, so the flow continues; on 2026-07-28 this stops the flow before the authorization code is redeemed.`}}return{ok:!0}}return n===!0?{ok:!1,reason:"Authorization server advertised `authorization_response_iss_parameter_supported: true` but the callback did not include an `iss` parameter (RFC 9207 requires it)."}:{ok:!0}}var fO=e=>{const{state:t,getState:r,updateState:n,serverUrl:i,serverName:s,redirectUrl:o,requestExecutor:a,scheduleAutoAdvance:c,loadPreregisteredCredentials:l,dynamicRegistration:u,clientIdMetadataUrl:h,customScopes:d,customHeaders:p,resourceMetadataUrl:f,authMode:v,hasClientSecret:m=!1,strictConformance:_=!1,allowPathScopedIssuer:w=!1,resourceIndicatorEnforcement:S="warn",requiredMetadataEnforcement:T="reject",registrationStrategy:I="cimd",emulation:C}=e,M=o,L=mn(C,"2026-07-28"),q=Sa(C),X=Ea(u??{},C);let ee=h??"";if(I==="dcr"&&!X.client_name)throw new Error("Dynamic registration metadata must include client_name");if(I==="cimd"&&!ee)throw new Error("Client ID metadata URL is required for CIMD registration");I==="cimd"&&(ee=N_(ee));const k=()=>r?r():t,ie=()=>di(k(),i),H=(y,V={})=>a({url:y,method:V.method||"GET",headers:Pr(V.headers),body:V.body}),oe=y=>{const V=la({authorizationServerMetadata:k().authorizationServerMetadata,hasClientSecret:!!(y||m)});if(!V.ok)throw new Error(V.message);return V.method},$=async y=>{const{clientId:V,clientSecret:K}=await l?.({serverName:s,serverUrl:i})??{};if(!V)return;const le=oe(K),de={"Client ID":V,"Client Secret":K||m?"Configured":"Not provided (public client)","Token Auth Method":le,Note:y};return{clientId:V,clientSecret:K||void 0,tokenEndpointAuthMethod:le,infoLogs:ne(k(),"received_client_credentials","preregistered-fallback","Pre-registered Client",de)}},Q={state:t,updateState:n,proceedToNextStep:async()=>{const y=k();n({isInitiatingAuth:!0});const V=K=>{c?.(()=>{Q.proceedToNextStep()},K)};try{switch(y.currentStep){case"idle":{const g=dt(p,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":L,"Mcp-Method":"tools/list"}),R=Us({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}),E={method:"POST",url:i,headers:g,body:R};n({currentStep:"request_without_token",serverUrl:i,lastRequest:E,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_without_token",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),V(50);return}case"request_without_token":if(!y.serverUrl)throw new Error("No server URL available");try{const g=await H(y.serverUrl,{method:"POST",headers:dt(p,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":L,"Mcp-Method":"tools/list"}),body:JSON.stringify(Us({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}))}),R={status:g.status,statusText:g.statusText,headers:g.headers,body:g.body},E=[...y.httpHistory||[]];if(E.length>0){const F=E[E.length-1];F.response=R,F.duration=Date.now()-(F.timestamp||Date.now())}const P=vs({status:g.status,statusText:g.statusText,wwwAuthenticateHeader:g.headers["www-authenticate"],serverMessage:g.body?.error?.message});if(P.kind==="challenged"){const F=g.headers["www-authenticate"],B=ur(F),D=Du(B.scope);let G=F?ne(y,"received_401_unauthorized","www-authenticate","WWW-Authenticate Header",{header:F,...D&&D.length>0?{scope:D.join(" ")}:{},"Received from":y.serverUrl||"Unknown"}):y.infoLogs;P.specCompliant||(G=va(y,G,"received_401_unauthorized",R)),n({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:F||void 0,challengedScopes:D,lastResponse:R,httpHistory:E,infoLogs:G,isInitiatingAuth:!1})}else if(P.kind==="anonymous_allowed"){const F=ne(y,"received_401_unauthorized","optional-auth","Optional Authentication Detected",{message:"Server allows anonymous access",note:"Proceeding with OAuth discovery for authenticated features"});n({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:void 0,lastResponse:R,httpHistory:E,infoLogs:F,isInitiatingAuth:!1})}else throw n({lastResponse:R,httpHistory:E}),new zr(P.message,g.status)}catch(g){throw g instanceof zr?g:new Error(`Failed to request MCP server: ${g instanceof Error?g.message:String(g)}`)}break;case"received_401_unauthorized":{const g=ur(y.wwwAuthenticateHeader);let R=f||g.resource_metadata;if(!R&&y.serverUrl&&(R=Fu(y.serverUrl)),!R)throw new Error("Could not determine resource metadata URL");const E={method:"GET",url:R,headers:dt(p,{})};n({currentStep:"request_resource_metadata",resourceMetadataUrl:R,lastRequest:E,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_resource_metadata",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),V(50);return}case"request_resource_metadata":if(!y.serverUrl)throw new Error("No server URL available");const K=[...y.httpHistory||[]];let le=K.length>0&&K[K.length-1]?.step==="request_resource_metadata"&&!K[K.length-1]?.response?K.pop():void 0;const de=[],Ce=async(g,R={})=>{const E=typeof g=="string"?g:g.toString(),P=Nu(i,E,p,Pr(R.headers)),F=le?{...le,timestamp:Date.now(),request:{method:R.method||"GET",url:E,headers:P,body:R.body}}:{step:"request_resource_metadata",timestamp:Date.now(),request:{method:R.method||"GET",url:E,headers:P,body:R.body}};le=void 0,de.push(F);try{const B=await H(E,{method:R.method||"GET",headers:P,body:R.body});F.response={status:B.status,statusText:B.statusText,headers:B.headers,body:B.body},F.duration=Date.now()-F.timestamp;const D={status:B.status,statusText:B.statusText,headers:B.headers},G=typeof B.body=="string"?B.body:JSON.stringify(B.body??{});return new Response(G,D)}catch(B){throw F.error=Tt(B),F.duration=Date.now()-F.timestamp,B}};try{const g=(f||ur(y.wwwAuthenticateHeader).resource_metadata)&&y.resourceMetadataUrl?{resourceMetadataUrl:y.resourceMetadataUrl}:void 0,R=await ca(y.serverUrl,g,Ce),E=[...K,...de],P=de[de.length-1],F=zu({authorizationServers:R.authorization_servers,fallbackServerUrl:i,protocolVersion:"2026-07-28"}),B=F.authorizationServerUrl;if(F.error&&T!=="observe"){n({resourceMetadata:R,resourceMetadataUrl:P?.request?.url||y.resourceMetadataUrl,lastRequest:P?.request,lastResponse:P?.response,httpHistory:E,error:F.error,isInitiatingAuth:!1});return}let D=y.infoLogs??[];F.error&&(D=ne({...k(),infoLogs:D},"received_resource_metadata","authorization-server-substituted","Derived: Authorization Server (not advertised)",{Finding:F.error,"Using instead":B}));const G=ju({state:y,fallbackServerUrl:i,prmResource:R.resource,enforcement:S,infoLogs:D}),J=G.resourceIndicator;D=G.infoLogs,n({currentStep:"received_resource_metadata",resourceMetadata:R,resourceIndicator:J,resourceMetadataUrl:P?.request?.url||y.resourceMetadataUrl,authorizationServerUrl:B,lastRequest:P?.request,lastResponse:P?.response,httpHistory:E,infoLogs:D,isInitiatingAuth:!1})}catch(g){const R=gn([...K,...de],Tt(g));throw n({lastResponse:de[de.length-1]?.response,httpHistory:R}),new Error(aa(g))}break;case"received_resource_metadata":if(!y.authorizationServerUrl)throw new Error("No authorization server URL available");const Re={method:"GET",url:Pp(y.authorizationServerUrl)[0],headers:ct(p,{})};n({currentStep:"request_authorization_server_metadata",lastRequest:Re,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:Re}],isInitiatingAuth:!1}),V(50);return;case"request_authorization_server_metadata":if(!y.authorizationServerUrl)throw new Error("No authorization server URL available");const _e=Pp(y.authorizationServerUrl);let ve=null;const Je=[];let Xe={},Pe=null;for(const g of _e)try{const R=ct(p,{}),E=[...y.httpHistory||[]];E.length>0&&(E[E.length-1].request={method:"GET",url:g,headers:R}),n({lastRequest:{method:"GET",url:g,headers:R},httpHistory:E});const P=await H(g,{method:"GET",headers:ct(p,{})});if(P.ok){ve=P.body,Xe=P.headers,Pe=P,ve||Je.push({url:g,status:P.status});break}Je.push({url:g,status:P.status})}catch(R){Je.push({url:g,error:R});continue}if(!ve||!Pe)throw new Error(qu(Je));if(!ve.issuer)throw new Error(ma);if(ve.issuer!==y.authorizationServerUrl){const g=hO({advertisedIssuer:ve.issuer,discoveryUrl:y.authorizationServerUrl,tokenEndpoint:ve.token_endpoint,registrationEndpoint:ve.registration_endpoint,allowPathScopedIssuer:w});if(!g.accepted)throw new Error(`Authorization server metadata \`issuer\` does not match the authorization server URL it was discovered from (expected "${y.authorizationServerUrl}", got "${ve.issuer}"). RFC 8414 §3.3 requires an exact match; refusing to continue.`+g.hint)}if(!ve.authorization_endpoint)throw new Error("Authorization server metadata missing 'authorization_endpoint'");if(!ve.token_endpoint)throw new Error("Authorization server metadata missing 'token_endpoint'");if(!ve.response_types_supported?.includes("code"))throw new Error("Authorization server does not support 'code' response type");const z={status:Pe.status,statusText:Pe.statusText,headers:Xe,body:ve},se=[...y.httpHistory||[]];if(se.length>0){const g=se[se.length-1];g.response=z,g.duration=Date.now()-(g.timestamp||Date.now())}const ae=ve.code_challenge_methods_supported||[],he=L_(ae,"2026-07-28"),Oe=typeof ve.client_id_metadata_document_supported=="boolean"?ve.client_id_metadata_document_supported:"false (not advertised, defaults to false per spec)";let we=ne(k(),"received_authorization_server_metadata","cimd-support","Derived: CIMD Support",{"CIMD Supported":Oe});if(ve.issuer!==y.authorizationServerUrl&&(we=ne({...k(),infoLogs:we},"received_authorization_server_metadata","path-scoped-issuer","Path-scoped authorization server",{"Discovery URL":y.authorizationServerUrl,"Advertised issuer":ve.issuer,Note:'The advertised issuer is the same-origin root of the discovery URL. Accepted because "Path-scoped authorization server" is enabled for this server; strict RFC 8414 §3.3 conformance requires an exact issuer match, and strict MCP clients may refuse to connect.'},{level:"warning"})),he){if(_||T!=="observe"){n({lastResponse:z,httpHistory:se,infoLogs:we,error:he,isInitiatingAuth:!1});return}console.warn("Authorization server may not support S256 PKCE method. Supported methods:",ae),n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:ve,lastResponse:z,httpHistory:se,infoLogs:we,error:"Warning: Authorization server may not support S256 PKCE method",isInitiatingAuth:!1})}else n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:ve,lastResponse:z,httpHistory:se,infoLogs:we,isInitiatingAuth:!1});break;case"received_authorization_server_metadata":if(!y.authorizationServerMetadata)throw new Error("No authorization server metadata available");if(I==="cimd"){if(y.authorizationServerMetadata.client_id_metadata_document_supported!==!0){n({error:"The authorization server does not support Client ID Metadata Documents (client_id_metadata_document_supported is not advertised in AS metadata). Try using 'dcr' or 'preregistered' registration strategy instead.",isInitiatingAuth:!1});return}n({currentStep:"cimd_prepare",clientId:ee,isInitiatingAuth:!1}),V(800);return}else if(I==="preregistered"){const{clientId:g,clientSecret:R}=await l?.({serverName:s,serverUrl:i})??{};if(!g){n({error:"Pre-registered client ID is required. Please configure OAuth credentials in the server settings.",isInitiatingAuth:!1});return}const E=oe(R),P={"Client ID":g,"Client Secret":R||m?"Configured":"Not provided (public client)","Token Auth Method":E,Note:"Using pre-registered client credentials from server config (skipped DCR)"},F=ne(k(),"received_client_credentials","dcr","Pre-registered Client",P);n({currentStep:"received_client_credentials",clientId:g,clientSecret:R||void 0,tokenEndpointAuthMethod:E,infoLogs:F,isInitiatingAuth:!1})}else if(y.authorizationServerMetadata.registration_endpoint){const g=y.resourceMetadata?.scopes_supported||y.authorizationServerMetadata.scopes_supported,R=jr(C,{customScopes:d,challengedScopes:y.challengedScopes,supportedScopes:g}),E=ba({registrationEndpoint:y.authorizationServerMetadata.registration_endpoint,redirectUri:M,dynamicRegistrationDefaults:{...X,application_type:X.application_type??WP(X.redirect_uris??[M])},scope:R,customHeaders:p}),P=ne(k(),"request_client_registration","dcr-deprecated","DCR is deprecated in 2026-07-28",{Note:"Dynamic Client Registration (RFC 7591) is deprecated as a registration mechanism in 2026-07-28 (PR #2858). It remains a compatibility fallback; prefer CIMD or a pre-registered client where the authorization server supports it."},{level:"warning"});n({currentStep:"request_client_registration",lastRequest:E,lastResponse:void 0,infoLogs:P,httpHistory:[...y.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),V(50);return}else{if(_){n({error:ya,isInitiatingAuth:!1});return}const g=await $("Authorization server did not advertise registration_endpoint; using pre-registered client credentials.");if(!g){n({error:_a,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:g.clientId,clientSecret:g.clientSecret,tokenEndpointAuthMethod:g.tokenEndpointAuthMethod,infoLogs:g.infoLogs,error:void 0,isInitiatingAuth:!1})}break;case"request_client_registration":if(!y.authorizationServerMetadata?.registration_endpoint)throw new Error("No registration endpoint available");if(!y.lastRequest?.body)throw new Error("No client metadata in request");{const g=await wa({request:y.lastRequest,requestExecutor:a,httpHistory:y.httpHistory});if(g.status!=="registered"){if(n({lastResponse:g.response,httpHistory:g.httpHistory,error:g.error,isInitiatingAuth:!1}),_)return;const E=await $(g.fallbackNote);if(!E){n({error:g.errorWithFallbackHint,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:E.clientId,clientSecret:E.clientSecret,tokenEndpointAuthMethod:E.tokenEndpointAuthMethod,infoLogs:E.infoLogs,error:void 0,isInitiatingAuth:!1});break}if(g.missingClientId){n({lastResponse:g.response,httpHistory:g.httpHistory,error:"Dynamic Client Registration response is missing a client_id.",isInitiatingAuth:!1});return}const R=ne(k(),"received_client_credentials","dcr","Dynamic Client Registration",g.infoLogData);n({currentStep:"received_client_credentials",clientId:g.credentials.clientId,clientSecret:g.credentials.clientSecret,tokenEndpointAuthMethod:ua(g.clientInfo),lastResponse:g.response,httpHistory:g.httpHistory,infoLogs:R,error:void 0,isInitiatingAuth:!1})}break;case"cimd_prepare":n({currentStep:"cimd_fetch_request",isInitiatingAuth:!1}),V(800);return;case"cimd_fetch_request":try{const g={method:"GET",url:ee,headers:Pr(void 0)},R=Date.now(),E=await H(ee,{method:"GET"});if(!E.ok)throw new Error(`CIMD endpoint returned HTTP ${E.status}`);const P={status:E.status,statusText:E.statusText,headers:E.headers,body:E.body};n({currentStep:"cimd_metadata_response",lastRequest:g,lastResponse:P,httpHistory:[...y.httpHistory||[],{step:"cimd_fetch_request",timestamp:R,duration:Date.now()-R,request:g,response:P}],isInitiatingAuth:!1}),V(800);return}catch(g){n({error:`CIMD metadata fetch failed: ${g instanceof Error?g.message:String(g)}. Try using 'dcr' or 'preregistered' registration strategy instead.`,isInitiatingAuth:!1});return}case"cimd_metadata_response":try{const g=y.lastResponse?.body;if(!g||typeof g!="object")throw new Error("CIMD metadata document was not available");if(g.client_id!==ee)throw new Error("CIMD client_id mismatch");const R=y.authorizationServerMetadata?.client_id_metadata_document_supported,E={"Client ID":ee,"Registration Method":"Client ID Metadata Document (CIMD)","Client Name":g.client_name||"MCPJam","Redirect URIs":g.redirect_uris||[],"Token Auth Method":g.token_endpoint_auth_method||"none",Validation:"✓ Metadata fetched and validated",Note:"Server fetched and validated client metadata from URL"};R?E["Server Support"]="✓ Advertised in metadata (client_id_metadata_document_supported: true)":E["Server Support"]="⚠ Not advertised (attempting anyway)";const P=ne(k(),"received_client_credentials","cimd","Client ID Metadata Document",E);n({currentStep:"received_client_credentials",clientId:ee,clientSecret:void 0,tokenEndpointAuthMethod:"none",infoLogs:P,isInitiatingAuth:!1})}catch(g){n({error:`CIMD validation failed: ${g instanceof Error?g.message:String(g)}. Try using 'dcr' or 'preregistered' registration strategy instead.`,isInitiatingAuth:!1});return}break;case"received_client_credentials":const Se=qr(43),pe=await ga(Se),me=ne(k(),"generate_pkce_parameters","pkce-generation","Generate PKCE Parameters",{code_challenge:pe,method:"S256",...q?{resource:ie()}:{resource:"(omitted — emulated client does not send RFC 8707 resource)"}});n({currentStep:"generate_pkce_parameters",codeVerifier:Se,codeChallenge:pe,codeChallengeMethod:"S256",...q?{}:{resourceIndicatorSuppressed:!0},state:qr(16),recordedIssuer:k().authorizationServerMetadata?.issuer,infoLogs:me,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!y.authorizationServerMetadata?.authorization_endpoint||!y.clientId)throw new Error("Missing authorization endpoint or client ID");const Ee=new URL(y.authorizationServerMetadata.authorization_endpoint);Ee.searchParams.set("response_type","code"),Ee.searchParams.set("client_id",y.clientId),Ee.searchParams.set("redirect_uri",M),Ee.searchParams.set("code_challenge",y.codeChallenge||""),Ee.searchParams.set("code_challenge_method","S256"),Ee.searchParams.set("state",y.state||""),q&&Ee.searchParams.set("resource",ie());const Ge=jr(C,{customScopes:d,challengedScopes:y.challengedScopes,supportedScopes:y.resourceMetadata?.scopes_supported||y.authorizationServerMetadata.scopes_supported});Ge&&Ee.searchParams.set("scope",Ge);const U=ne(k(),"authorization_request","auth-url","Authorization URL",{url:Ee.toString()});n({currentStep:"authorization_request",authorizationUrl:Ee.toString(),authorizationCode:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,requestedScopes:Ge?Ge.split(/\s+/).filter(Boolean):void 0,infoLogs:U,isInitiatingAuth:!1});break;case"authorization_request":n({currentStep:"received_authorization_code",isInitiatingAuth:!1});break;case"received_authorization_code":{if(!y.authorizationCode||y.authorizationCode.trim()===""){n({error:"Authorization code is required. Please paste the code you received from the authorization server.",isInitiatingAuth:!1});return}if(!y.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");const g=pO({recordedIssuer:y.recordedIssuer,returnedIss:y.authorizationResponseIss,issParameterSupported:void 0,enforcePresentIssMismatch:!0});if(!g.ok){n({error:g.reason,isInitiatingAuth:!1});return}const R=Ur({clientId:y.clientId,clientSecret:y.clientSecret,tokenEndpointAuthMethod:Hr(C,y.tokenEndpointAuthMethod)}),E={grant_type:"authorization_code",code:y.authorizationCode,redirect_uri:M,...R.bodyParams};y.codeVerifier&&(E.code_verifier=y.codeVerifier),q&&(E.resource=ie());const P={method:"POST",url:y.authorizationServerMetadata.token_endpoint,headers:{"Content-Type":"application/x-www-form-urlencoded",...R.headers},body:E};n({currentStep:"token_request",lastRequest:P,lastResponse:void 0,...q?{}:{resourceIndicatorSuppressed:!0},accessToken:void 0,refreshToken:void 0,httpHistory:[...y.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:P}],isInitiatingAuth:!1}),V(50);return}case"token_request":if(!y.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!y.authorizationCode)throw new Error("Missing authorization code");if(!y.codeVerifier)throw new Error("PKCE code_verifier is missing - cannot exchange token");try{const g=Ur({clientId:y.clientId,clientSecret:y.clientSecret,tokenEndpointAuthMethod:Hr(C,y.tokenEndpointAuthMethod)}),R=new URLSearchParams({grant_type:"authorization_code",code:y.authorizationCode,redirect_uri:M,code_verifier:y.codeVerifier||"",...g.bodyParams});q&&R.set("resource",ie());const E=await H(y.authorizationServerMetadata.token_endpoint,{method:"POST",headers:{...ct(p,{"Content-Type":"application/x-www-form-urlencoded"}),...g.headers},body:R.toString()}),P={status:E.status,statusText:E.statusText,headers:E.headers,body:E.body},F=[...y.httpHistory||[]];if(F.length>0){const G=F[F.length-1];G.response=P,G.duration=Date.now()-(G.timestamp||Date.now())}if(!E.ok){n({lastResponse:P,httpHistory:F,authorizationCode:void 0,error:ha(E),isInitiatingAuth:!1});return}const B=E.body;let D=(k().infoLogs||[]).filter(G=>G.id!=="auth-code"&&G.id!=="oauth-tokens"&&G.id!=="token");if(y.authorizationCode&&(D=[...D,{id:"auth-code",level:"info",step:"authorization_request",label:"Authorization Code",data:{code:y.authorizationCode},timestamp:Date.now()}]),B.access_token){const G={access_token:B.access_token};B.refresh_token&&(G.refresh_token=B.refresh_token),D=[...D,{id:"oauth-tokens",level:"info",step:"token_request",label:"OAuth Tokens",data:G,timestamp:Date.now()}]}if(B.access_token){const G=Fr(B.access_token);if(G){const J={...G};J.exp&&(J.exp=`${J.exp} (${De(J.exp)})`),J.iat&&(J.iat=`${J.iat} (${De(J.iat)})`),J.nbf&&(J.nbf=`${J.nbf} (${De(J.nbf)})`);const qt={...J};if(J.aud){const Gr=y.serverUrl,hi=(Array.isArray(J.aud)?J.aud:[J.aud]).some(Ta=>Ta===Gr);qt._validation={expected_audience:Gr,audience_matches:hi,note:hi?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else qt._validation={note:"⚠ No audience claim found - server should validate token binding"};D=[...D,{id:"token",level:"info",step:"token_request",label:"Access Token (Decoded JWT)",data:qt,timestamp:Date.now()}]}}if(B.id_token){const G=Fr(B.id_token);if(G){const J={...G};J.exp&&(J.exp=`${J.exp} (${De(J.exp)})`),J.iat&&(J.iat=`${J.iat} (${De(J.iat)})`),J.nbf&&(J.nbf=`${J.nbf} (${De(J.nbf)})`),J.auth_time&&(J.auth_time=`${J.auth_time} (${De(J.auth_time)})`),J._note="OIDC ID Token - Used for user identity verification",D=[...D,{id:"id-token",level:"info",step:"token_request",label:"ID Token (OIDC - Decoded JWT)",data:J,timestamp:Date.now()}]}}n({currentStep:"received_access_token",accessToken:B.access_token,refreshToken:B.refresh_token,tokenType:B.token_type||"Bearer",expiresIn:B.expires_in,lastResponse:P,httpHistory:F,infoLogs:D,error:void 0,isInitiatingAuth:!1})}catch(g){const R={status:0,statusText:"Network Error",headers:{},body:{error:g instanceof Error?g.message:String(g)}},E=[...y.httpHistory||[]];if(E.length>0){const P=E[E.length-1];P.response=R,P.duration=Date.now()-(P.timestamp||Date.now())}n({lastResponse:R,httpHistory:E,error:`Token exchange failed: ${g instanceof Error?g.message:String(g)}`,isInitiatingAuth:!1})}break;case"received_access_token":if(!y.serverUrl||!y.accessToken)throw new Error("Missing server URL or access token");const W={method:"POST",url:y.serverUrl,headers:{Authorization:`Bearer ${y.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":L,"Mcp-Method":"tools/list"},body:Us({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:2})},Y=ne(k(),"authenticated_mcp_request","authenticated-verify","Authenticated MCP Verify Request (tools/list)",{Request:"Stateless tools/list with OAuth bearer token","Protocol Version":"2026-07-28",Client:"MCPJam Inspector v1.0.0",Endpoint:y.serverUrl});n({currentStep:"authenticated_mcp_request",lastRequest:W,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"authenticated_mcp_request",timestamp:Date.now(),request:W}],infoLogs:Y,isInitiatingAuth:!1}),V(50);return;case"authenticated_mcp_request":if(!y.serverUrl||!y.accessToken)throw new Error("Missing server URL or access token");try{const g=await H(y.serverUrl,{method:"POST",headers:dt(p,{Authorization:`Bearer ${y.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":L,"Mcp-Method":"tools/list"}),body:JSON.stringify(Us({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:2}))}),R={status:g.status,statusText:g.statusText,headers:g.headers,body:g.body},E=[...y.httpHistory||[]];if(E.length>0){const G=E[E.length-1];G.response=R,G.duration=Date.now()-(G.timestamp||Date.now())}if(!g.ok){n({lastResponse:R,httpHistory:E,error:da(g),isInitiatingAuth:!1});return}let P=k().infoLogs||[];const F=g.headers["content-type"]||"",B=F.includes("text/event-stream");let D=null;if(B&&g.body?.transport==="sse"?D=g.body.mcpResponse:D=g.body,B&&D?.result?.protocolVersion){const G={Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Protocol Version":D.result.protocolVersion};D.result.serverInfo&&(G["Server Name"]=D.result.serverInfo.name,G["Server Version"]=D.result.serverInfo.version),D.result.capabilities&&(G.Capabilities=D.result.capabilities),P=ne(k(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",G)}else if(B)P=ne(k(),"authenticated_mcp_request","mcp-transport","MCP Transport Detected",{Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Content-Type":F,Note:"Server returned streaming response. tools/list verify response delivered via SSE stream.",Events:g.body?.events?`${g.body.events.length} events parsed`:"No events parsed"});else if(D?.result?.protocolVersion){const G={Transport:"Streamable HTTP","Response Format":"JSON","Protocol Version":D.result.protocolVersion};D.result.serverInfo&&(G["Server Name"]=D.result.serverInfo.name,G["Server Version"]=D.result.serverInfo.version),D.result.capabilities&&(G.Capabilities=D.result.capabilities),P=ne(k(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",G)}else if(D?.result){const G=Array.isArray(D.result.tools)?D.result.tools.length:void 0;P=ne(k(),"authenticated_mcp_request","mcp-token-verified","Access token verified (tools/list)",{Transport:"Streamable HTTP","Response Format":"JSON",Result:"Bearer token accepted; tools/list succeeded",...G!==void 0?{"Tools listed":G}:{}})}n({currentStep:"complete",lastResponse:R,httpHistory:E,infoLogs:P,error:void 0,isInitiatingAuth:!1})}catch(g){const R={status:0,statusText:"Network Error",headers:{},body:{error:g instanceof Error?g.message:String(g)}},E=[...y.httpHistory||[]];if(E.length>0){const P=E[E.length-1];P.response=R,P.duration=Date.now()-(P.timestamp||Date.now())}n({lastResponse:R,httpHistory:E,error:`Authenticated MCP request failed: ${g instanceof Error?g.message:String(g)}`,isInitiatingAuth:!1})}break;case"complete":n({isInitiatingAuth:!1});break;default:n({isInitiatingAuth:!1})}}catch(K){const le=k(),de=Tt(K),Ce=ne(le,le.currentStep,`error-${le.currentStep}-${Date.now()}`,"Step failed",{step:le.currentStep,request:le.lastRequest,response:le.lastResponse,error:de},{level:"error",error:de}),Re=gn(le.httpHistory,de),_e={error:de.message,infoLogs:Ce,isInitiatingAuth:!1};Re&&(_e.httpHistory=Re),n(_e)}},startGuidedFlow:async()=>{n({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{n(pa())}};return Q};function bD({protocolVersion:e,registrationStrategy:t,flowState:r}){switch(e){case"2025-03-26":return KP(r,t==="cimd"?"dcr":t);case"2025-06-18":return tO(r,t==="cimd"?"dcr":t);case"2025-11-25":return iO(r,t);case"2026-07-28":return lO(r,t);default:throw new Error(`Unknown protocol version: ${e}`)}}function Ra(e){return e.replace(/^\[|\]$/g,"").trim().toLowerCase().replace(/\.+$/,"")}function z_(e){const t=e.split(".").map(s=>parseInt(s,10));if(t.length!==4||t.some(s=>!Number.isInteger(s)||s<0||s>255))return!0;const[r,n,i]=t;return r===0||r===10||r===100&&n>=64&&n<=127||r===127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===0&&i===0||r===192&&n===0&&i===2||r===192&&n===88&&i===99||r===192&&n===168||r===198&&(n===18||n===19)||r===198&&n===51&&i===100||r===203&&n===0&&i===113||r>=224&&r<=239||r>=240}function U_(e){let t=e.trim().toLowerCase().split("%")[0];t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1));const r=t.match(/^(.*:)(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(r){const o=[r[2],r[3],r[4],r[5]].map(a=>parseInt(a,10));if(o.some(a=>a<0||a>255))return null;t=`${r[1]}${(o[0]<<8|o[1]).toString(16)}:${(o[2]<<8|o[3]).toString(16)}`}const n=o=>{if(o==="")return[];const a=[];for(const c of o.split(":")){if(!/^[0-9a-f]{1,4}$/.test(c))return null;a.push(parseInt(c,16))}return a},i=t.split("::");if(i.length>2)return null;if(i.length===2){const o=n(i[0]),a=n(i[1]);if(!o||!a)return null;const c=8-o.length-a.length;return c<1?null:[...o,...Array(c).fill(0),...a]}const s=n(t);return s&&s.length===8?s:null}function Lp(e,t){return z_(`${e>>8}.${e&255}.${t>>8}.${t&255}`)}function vO(e){const t=U_(e);if(!t||t.slice(0,6).every(n=>n===0)&&t[6]===0&&(t[7]===0||t[7]===1))return!0;const r=t[0]>>8;return(r&254)===252||t[0]>=65152&&t[0]<=65215||r===255||t[0]===8193&&t[1]===3512||t[0]===256&&t[1]===0&&t[2]===0&&t[3]===0?!0:t[0]===100&&t[1]===65435?t[2]===1?!0:Lp(t[6],t[7]):t[0]===0&&t[1]===0&&t[2]===0&&t[3]===0&&t[4]===0&&(t[5]===65535||t[5]===0)?Lp(t[6],t[7]):!1}function gO(e){const t=Ra(e);return/^\d+\.\d+\.\d+\.\d+$/.test(t)?z_(t):t.includes(":")?vO(t):!1}function mO(e){const t=Ra(e);return t==="localhost"||t.endsWith(".localhost")?!0:gO(t)}function _O(e){const t=Ra(e);return/^\d+\.\d+\.\d+\.\d+$/.test(t)?F_(t):t.includes(":")?yO(t):!1}function F_(e){const t=e.split(".").map(o=>parseInt(o,10));if(t.length!==4||t.some(o=>!Number.isInteger(o)||o<0||o>255))return!0;const[r,n,i,s]=t;return r===0||r===169&&n===254||r===100&&n===100&&i===100&&s===200||r>=224&&r<=239||r>=240}function Dp(e,t){return F_(`${e>>8}.${e&255}.${t>>8}.${t&255}`)}function yO(e){const t=U_(e);return t?t.slice(0,6).every(r=>r===0)&&t[6]===0&&(t[7]===0||t[7]===1)?t[7]===0:t[0]>=65152&&t[0]<=65215||t[0]>>8===255||t[0]===256&&t[1]===0&&t[2]===0&&t[3]===0||t[0]===64768&&t[1]===3778&&t[2]===0&&t[3]===0&&t[4]===0&&t[5]===0&&t[6]===0&&t[7]===596?!0:t[0]===100&&t[1]===65435||t[0]===0&&t[1]===0&&t[2]===0&&t[3]===0&&t[4]===0&&(t[5]===65535||t[5]===0)?Dp(t[6],t[7]):!1:!0}var bO=new Set(["metadata.google.internal","metadata.goog"]);function wO(e){const t=Ra(e);return bO.has(t)?!0:_O(t)}function q_(e){const t=e.replace(/^\[|\]$/g,"").toLowerCase(),r=t.match(/^::(?:ffff:)?(\d{1,3})\.\d{1,3}\.\d{1,3}\.\d{1,3}$/);if(r)return parseInt(r[1],10)===127;const n=t.match(/^::(?:ffff:)?([0-9a-f]{1,4}):[0-9a-f]{1,4}$/);return n?parseInt(n[1],16)>>8===127:!1}function wD(e){if(!e)return!1;try{const t=new URL(e).hostname;return ka(t)||q_(t)}catch{return!1}}var ki=class extends Error{url;reason;constructor(e,t,r){super(r),this.name="OAuthOutboundUrlBlockedError",this.url=e,this.reason=t}};function SO(e,t={}){let r;try{r=new URL(e)}catch{throw new ki(e,"invalid-url","Outbound OAuth fetch URL is not a valid absolute URL")}if(r.protocol!=="https:"&&r.protocol!=="http:")throw new ki(e,"invalid-scheme",`Outbound OAuth fetch must be http(s); got "${r.protocol}"`);const n=r.hostname;if(wO(n))throw new ki(e,"private-host",`Refusing outbound OAuth fetch to link-local or cloud-metadata host "${n}"`);if(t.allowPrivateNetwork===!0)return r;if(ka(n)||q_(n)){if(t.allowLoopback===!0)return r;throw new ki(e,"private-host",`Refusing outbound OAuth fetch to loopback host "${n}" (no loopback opt-in)`)}if(mO(n))throw new ki(e,"private-host",`Refusing outbound OAuth fetch to private/reserved host "${n}"`);return r}var EO=class extends Error{field;constructor(e,t){super(`OAuth response from ${t} carried a redacted \`${e}\`. Trace redaction was applied to data the OAuth flow consumes; a redaction sentinel is a non-empty string, so it would be sent upstream as a credential and rejected as invalid. Redaction belongs to the trace projection layer only.`),this.name="OAuthRedactedCredentialError",this.field=e}},kO=["access_token","refresh_token","id_token","client_secret"],RO=[/^\[redacted\]$/,/^[\s\S]{4}\.\.\.\[redacted\]\.\.\.[\s\S]{2}$/];function AO(e){try{const t=new URL(e.url);return`${t.origin}${t.pathname}`}catch{return"the authorization server"}}function IO(e,t){const r=e?.body;if(!r||typeof r!="object"||Array.isArray(r))return e;const n=r;for(const i of kO){const s=n[i];if(typeof s=="string"&&RO.some(o=>o.test(s)))throw new EO(i,AO(t))}return e}function TO(e){const{protocolVersion:t,allowLoopbackMetadataFetch:r,allowPrivateMetadataFetch:n,...i}=e,s=r??!1,o=n??!1,c={...i,requestExecutor:async l=>(SO(l.url,{allowLoopback:s,allowPrivateNetwork:o}),IO(await i.requestExecutor(l),l)),customHeaders:JP(i.customHeaders,i.emulation)};switch(t){case"2025-03-26":if(e.registrationStrategy==="cimd")throw new Error("CIMD registration is not supported in 2025-03-26 protocol. Use 'dcr' or 'preregistered' instead.");return XP(c);case"2025-06-18":if(e.registrationStrategy==="cimd")throw new Error("CIMD registration is not supported in 2025-06-18 protocol. Use 'dcr' or 'preregistered' instead.");return rO(c);case"2025-11-25":return sO(c);case"2026-07-28":return fO(c);default:throw new Error(`Unknown protocol version: ${t}`)}}function SD(e){switch(e){case"2025-03-26":return"dcr";case"2025-06-18":return"dcr";case"2025-11-25":return"cimd";case"2026-07-28":return"cimd";default:return"dcr"}}function ED(e){switch(e){case"2025-03-26":return["dcr","preregistered"];case"2025-06-18":return["dcr","preregistered"];case"2025-11-25":return["cimd","dcr","preregistered"];case"2026-07-28":return["cimd","dcr","preregistered"];default:return["dcr","preregistered"]}}var kD={"2025-03-26":{label:zs("2025-03-26"),description:"Original MCP OAuth specification with direct discovery",features:["Dynamic Client Registration (DCR) SHOULD be supported","Direct RFC8414 discovery from MCP server base URL","Fallback to default endpoints (/authorize, /token, /register)","PKCE is REQUIRED for all clients","No Protected Resource Metadata (RFC9728)"]},"2025-06-18":{label:zs("2025-06-18"),description:"MCP OAuth specification with resource metadata",features:["Dynamic Client Registration (DCR) SHOULD be supported","Protected Resource Metadata (RFC9728) required","RFC8414 discovery ONLY (no OIDC) with root fallback","PKCE recommended but not strictly enforced"]},"2025-11-25":{label:zs("2025-11-25"),description:"MCP OAuth specification with CIMD support",features:["Client ID Metadata Documents (CIMD) SHOULD be supported","Protected Resource Metadata (RFC9728) required","RFC8414 OR OIDC discovery without root fallback","PKCE strictly required and enforced","Enhanced security with URL-based client IDs"]},"2026-07-28":{label:zs("2026-07-28"),description:"Newest MCP OAuth specification: 2025-11-25 discovery plus OIDC application_type",features:["Client ID Metadata Documents (CIMD) SHOULD be supported","Protected Resource Metadata (RFC9728) required","RFC8414 OR OIDC discovery without root fallback","PKCE strictly required and enforced","SEP-837: OIDC application_type sent on Dynamic Client Registration"]}},$O=["idle","request_without_token","received_401_unauthorized","discovery_start","request_resource_metadata","received_resource_metadata","request_authorization_server_metadata","received_authorization_server_metadata","cimd_prepare","cimd_fetch_request","cimd_metadata_response","request_client_registration","received_client_credentials","generate_pkce_parameters","authorization_request","received_authorization_code","token_request","received_access_token","authenticated_mcp_request","complete","verify_list_tools","verify_call_tool"],CO={idle:{title:"Idle",summary:"The OAuth flow is ready to start.",teachableMoments:["Review your server selection and OAuth configuration before starting."]},request_without_token:{title:"Initial MCP Request",summary:"The client sends an unauthenticated initialize request to discover whether OAuth is required.",teachableMoments:["OAuth flows usually begin with a protected resource request that deliberately lacks credentials.","The response determines which discovery path the client must follow."]},received_401_unauthorized:{title:"401 Unauthorized Received",summary:"The MCP server indicates OAuth is required and often provides discovery hints in WWW-Authenticate.",teachableMoments:["Look for the resource metadata URL or realm in the header to understand where discovery begins."],tips:["If you get 200 instead, the server may allow optional OAuth or anonymous access."]},discovery_start:{title:"Start Discovery",summary:"The client derives authorization server endpoints from the MCP server URL.",teachableMoments:["Legacy servers rely on RFC8414 discovery directly from the MCP base URL.","Understanding how fallback URLs are constructed helps debug missing metadata issues."]},request_resource_metadata:{title:"Request Resource Metadata",summary:"The client requests RFC9728 resource metadata to learn which authorization server to use.",teachableMoments:["Protected resource metadata links the resource to one or more authorization servers.","If this step fails, check the MCP server's well-known configuration and headers."]},received_resource_metadata:{title:"Resource Metadata Received",summary:"The response describes supported authorization servers, scopes, and bearer method details.",teachableMoments:["Validate that the authorization server URL looks correct for the environment you're targeting."]},request_authorization_server_metadata:{title:"Request Authorization Server Metadata",summary:"The client requests the authorization server's well-known metadata endpoint (RFC8414 or OIDC).",teachableMoments:["Different protocol versions prioritize different discovery strategies (path insertion, appending, etc.).","Failure here often points to misconfigured issuer URLs or CORS/proxy issues."]},received_authorization_server_metadata:{title:"Authorization Server Metadata Received",summary:"Inspector validates the authorization, token, and optional registration endpoints.",teachableMoments:["Confirm PKCE methods include S256 for modern flows.","Check the available scopes and grant types to ensure the server supports what you need."]},cimd_prepare:{title:"Prepare CIMD",summary:"Draft protocol: the client prepares to use a Client ID Metadata Document (CIMD).",teachableMoments:["CIMD replaces static client IDs with an HTTPS URL that hosts client metadata."]},cimd_fetch_request:{title:"Authorization Server Fetches CIMD",summary:"The authorization server fetches the client's metadata document over HTTPS.",teachableMoments:["Monitor this step to diagnose TLS or hosting issues with your metadata document."]},cimd_metadata_response:{title:"CIMD Validated",summary:"The client confirms the authorization server successfully read the client metadata document.",teachableMoments:["Ensure redirect URIs declared in the document match the environment you're testing."]},request_client_registration:{title:"Request Dynamic Client Registration",summary:"The client submits metadata to register a public client with the authorization server.",teachableMoments:["Dynamic registration is optional in draft flows but required in earlier specs unless you pre-register.","Watch for HTTP 4xx responses that indicate validation failures."]},received_client_credentials:{title:"Client Credentials Received",summary:"The client stores client_id (and optionally client_secret) for the remainder of the flow.",teachableMoments:["Keep an eye on whether the server returned a secret; public clients should use PKCE instead."]},generate_pkce_parameters:{title:"Generate PKCE Parameters",summary:"The client creates a code verifier and challenge to protect the authorization code exchange.",teachableMoments:["PKCE S256 is required in draft specs and strongly recommended everywhere else."]},authorization_request:{title:"Authorization Request Ready",summary:"The client composes the authorization URL and waits for the user to approve access.",teachableMoments:["Inspect the URL to ensure scopes and redirect URI are what you expect."]},received_authorization_code:{title:"Authorization Code Received",summary:"The user completed consent and the client captured the returned authorization code.",teachableMoments:["State mismatches here usually indicate multiple concurrent authorizations or stale popups."]},token_request:{title:"Request Tokens with Authorization Code",summary:"The client calls the token endpoint with the authorization code and PKCE verifier.",teachableMoments:["Token endpoint errors often reveal scope or client configuration problems."]},received_access_token:{title:"Tokens Received",summary:"The client stores access and refresh tokens for subsequent authenticated MCP requests.",teachableMoments:["Check the token type and expiry to confirm the server honored offline access or refresh tokens."]},authenticated_mcp_request:{title:"Authenticated MCP Request",summary:"The client retries the MCP initialize call with the freshly issued access token.",teachableMoments:["Use this step to validate that MCP servers accept OAuth tokens and return capabilities."]},complete:{title:"Flow Complete",summary:"The client verified the server with OAuth credentials and recorded the final response.",teachableMoments:["Continue exploring with authenticated requests or reset to run the flow again."]},verify_list_tools:{title:"Verify: List Tools",summary:"Connect to the MCP server with the obtained token and list available tools.",teachableMoments:["This step confirms the OAuth token is actually usable for MCP operations."]},verify_call_tool:{title:"Verify: Call Tool",summary:"Execute a tool on the MCP server to confirm end-to-end functionality.",teachableMoments:["Calling a tool validates not just authentication but also authorization scopes."]}};function Np(e){return CO[e]??{title:e,summary:"No additional information available for this step."}}function _r(e){const t=$O.indexOf(e);return t===-1?Number.MAX_SAFE_INTEGER:t}function PO(e){return JSON.parse(JSON.stringify(e))}function OO(e){return{...e,request:{...e.request,url:Ou(e.request.url),headers:mp(e.request.headers),body:Jt(e.request.body)},...e.response?{response:{...e.response,headers:mp(e.response.headers),body:Jt(e.response.body)}}:{},...e.error?{error:{...e.error,...e.error.message?{message:Cr(e.error.message)}:{},details:Jt(e.error.details)}}:{}}}function xO(...e){const t=e.filter(r=>r!=null);if(t.length!==0)return Math.max(...t)}function MO(){return{syntheticStepTimestamps:{},lastSyntheticTimestamp:0}}function LO(e,t,r){if(!e)return r;const n=e.syntheticStepTimestamps[t];return typeof n=="number"?n:r}function zp(e,t,r,n){const i=LO(t,r,n),s=e.get(r);if(s)return s.startedAt=Math.min(s.startedAt,i),s.completedAt=Math.max(s.completedAt??i,n),s;const o={step:r,startedAt:i,completedAt:n};return e.set(r,o),o}function Yr(e,t,r,n,i,s){if(!n||e.has(r))return;let o=Date.now();t&&(o=Math.max(o,t.lastSyntheticTimestamp+1),t.syntheticStepTimestamps[r]=o,t.lastSyntheticTimestamp=o);const a=i==null?void 0:s?Jt(i):JSON.parse(JSON.stringify(i));e.set(r,{step:r,startedAt:o,completedAt:o,details:a})}function DO(e,t){if(e!==t.currentStep)return!1;switch(e){case"authorization_request":return!!t.authorizationUrl;case"received_authorization_code":return!!t.authorizationCode;case"received_access_token":return!!t.accessToken;case"complete":return t.currentStep==="complete";default:return!1}}function NO(e){if(!(!e||e.status<400))return x_(e.body)??`HTTP ${e.status} ${e.statusText}`}function zO(e){if(e.error?.message)return e.error.message;if(e.step==="request_client_registration")return NO(e.response)}function Up(e){return!e.error||!e.clientId||_r(e.currentStep)<=_r("request_client_registration")?!1:e.error.startsWith("Dynamic Client Registration failed")||e.error.startsWith("Client registration failed:")}function UO(e){const{state:t,context:r,sanitize:n=!0}=e,i=t.error?n?Cr(t.error):t.error:void 0,s={version:1,currentStep:t.currentStep,steps:[],httpHistory:(t.httpHistory??[]).map(u=>n?OO(u):PO(u)),...i?{error:i}:{}},o=_r(t.currentStep),a=new Map;for(const u of t.httpHistory??[]){const h=zp(a,r,u.step,u.timestamp);h.details||(h.details={request:n?Jt(u.request):u.request,...u.response?{response:n?Jt(u.response):u.response}:{}});const d=zO(u);d&&(h.error=Pl(n?Cr(d):d.slice(0,500)))}for(const u of t.infoLogs??[]){const h=zp(a,r,u.step,u.timestamp);h.message=u.label;const d=n?Jt(u.data):u.data;d&&typeof d=="object"&&d!==null&&!Array.isArray(d)&&(h.details=d),u.error?.message&&(h.error=n?Cr(u.error.message):u.error.message)}const c=Math.max(Date.now(),...(t.httpHistory??[]).map(u=>u.timestamp),...(t.infoLogs??[]).map(u=>u.timestamp),r?.lastSyntheticTimestamp??0);r&&(r.lastSyntheticTimestamp=Math.max(r.lastSyntheticTimestamp,c)),Yr(a,r,"received_client_credentials",!!t.clientId,{clientId:t.clientId},n),Yr(a,r,"generate_pkce_parameters",!!t.codeVerifier,{codeVerifier:t.codeVerifier},n),Yr(a,r,"authorization_request",!!t.authorizationUrl,{authorizationUrl:t.authorizationUrl},n),Yr(a,r,"received_authorization_code",!!t.authorizationCode,t.authorizationCode?{code:t.authorizationCode}:void 0,n),Yr(a,r,"received_access_token",!!t.accessToken,{tokenType:t.tokenType,expiresIn:t.expiresIn},n),Yr(a,r,"complete",t.currentStep==="complete",void 0,n);const l=a.get("request_client_registration");if(l?.error&&_r(t.currentStep)>_r("request_client_registration")&&t.clientId&&(l.recovered=!0,l.recoveredAt=xO(l.recoveredAt,l.completedAt,a.get("received_client_credentials")?.startedAt),l.recoveryMessage="Using pre-registered client credentials after registration failed."),t.error&&!Up(t)&&!a.has(t.currentStep)){Yr(a,r,t.currentStep,!0,void 0,n);const u=a.get(t.currentStep);u&&(u.error=i)}return s.steps=Array.from(a.values()).sort((u,h)=>u.startedAt-h.startedAt||_r(u.step)-_r(h.step)).map(u=>{const h=_r(u.step),d=u.step===t.currentStep&&!!t.error&&!Up(t),p=u.error??(d?i:void 0),f=u.recovered?"success":p?"error":h<o||t.currentStep==="complete"||DO(u.step,t)?"success":u.step===t.currentStep?"pending":"success";return{step:u.step,title:Np(u.step).title,status:f,message:u.message??Np(u.step).summary,...p?{error:p}:{},...u.details?{details:u.details}:{},...u.recovered?{recovered:!0}:{},...u.recoveredAt?{recoveredAt:u.recoveredAt}:{},...u.recoveryMessage?{recoveryMessage:u.recoveryMessage}:{},startedAt:u.startedAt,completedAt:f==="pending"?void 0:u.completedAt}}),s}function Fs(e){return{message:e instanceof Error?e.message:String(e)}}async function RD(e){const{maxSteps:t=40,onAuthorizationRequest:r,onTraceUpdate:n,getState:i,sanitizeTrace:s=!0,...o}=e;let a=e.state;const c=MO(),l=i??(()=>a),u=(v,m=l(),_=c)=>{n?.({trace:UO({state:m,context:_,sanitize:s}),state:m,reason:v})},h=v=>{a={...a,...v},e.updateState(v),u("state_update",a)},d=TO({...o,getState:l,updateState:h});let p=0;for(;l().currentStep!=="complete"&&p<t;){p+=1;const v=l();if(v.currentStep==="authorization_request"){if(!v.authorizationUrl)return h({error:"Authorization URL was not generated."}),{completed:!1,redirected:!1,state:l(),error:{message:"Authorization URL was not generated."}};if(!r)return h({error:"Authorization request requires an authorization handler."}),{completed:!1,redirected:!1,authorizationUrl:v.authorizationUrl,state:l(),error:{message:"Authorization request requires an authorization handler."}};try{const w=await r({authorizationUrl:v.authorizationUrl,state:v});if(w.type==="redirect")return u("redirect"),{completed:!1,redirected:!0,authorizationUrl:v.authorizationUrl,state:l()};h({currentStep:"received_authorization_code",authorizationCode:w.authorizationCode,error:void 0});continue}catch(w){return h({error:Fs(w).message}),{completed:!1,redirected:!1,authorizationUrl:v.authorizationUrl,state:l(),error:Fs(w)}}}const m=v.currentStep;try{await d.proceedToNextStep()}catch(w){return l().error?u("error"):h({error:Fs(w).message}),{completed:!1,redirected:!1,state:l(),error:Fs(w)}}const _=l();if(_.currentStep===m)return _.error?u("error",_):h({error:`Step ${m} did not advance.`}),{completed:!1,redirected:!1,state:l(),error:{message:l().error||`Step ${m} did not advance.`}}}const f=l();return p>=t&&f.currentStep!=="complete"?(h({error:"OAuth login exceeded its step guard."}),{completed:!1,redirected:!1,state:l(),error:{message:"OAuth login exceeded its step guard."}}):(u(f.currentStep==="complete"?"complete":"state_update"),{completed:f.currentStep==="complete",redirected:!1,authorizationUrl:f.authorizationUrl,state:f,...f.error?{error:{message:f.error}}:{}})}var AD=["server-initialize","ping","logging-set-level","completion-complete","capabilities-consistent","tools-list","tools-input-schemas-valid","tools-x-mcp-header-declarations-valid","prompts-list","resources-list","protocol-invalid-method-error","localhost-host-rebinding-rejected","localhost-host-valid-accepted","server-sse-polling-session","server-accepts-multiple-post-streams","server-sse-streams-functional","notification-post-accepted","get-stream-or-405","session-id-visible-ascii","post-response-content-type","modern-client-handshake","modern-server-discover","modern-result-type-present","modern-cacheable-result-hints","modern-cache-hint-coverage","modern-cache-hint-values-valid","modern-cache-scope-stable-across-pages","modern-protocol-version-header-mismatch","modern-method-header-mismatch","modern-name-header-mismatch","modern-unsupported-version-error","modern-missing-method-header-rejected","modern-header-names-case-insensitive","modern-undeclared-capability-error","modern-no-session-id","modern-removed-methods-not-found","modern-resource-not-found-invalid-params","modern-resource-read-no-empty-contents","modern-tool-output-schema-conformant","modern-logs-require-log-level","modern-subscription-ack-precedes-notifications","modern-subscription-filter-and-tagging","modern-subscription-graceful-close","wire-schema-valid"],FO={"2025-03-26":"legacy","2025-06-18":"legacy","2025-11-25":"legacy","2026-07-28":"modern"},ID=Object.keys(FO),TD={"server-initialize":["legacy"],ping:["legacy"],"capabilities-consistent":["legacy","modern"],"server-sse-polling-session":["legacy"],"server-accepts-multiple-post-streams":["legacy"],"server-sse-streams-functional":["legacy"],"notification-post-accepted":["legacy"],"get-stream-or-405":["legacy"],"session-id-visible-ascii":["legacy"],"post-response-content-type":["legacy","modern"],"localhost-host-rebinding-rejected":["legacy"],"localhost-host-valid-accepted":["legacy"],"tools-list":["legacy","modern"],"tools-input-schemas-valid":["legacy","modern"],"tools-x-mcp-header-declarations-valid":["modern"],"prompts-list":["legacy","modern"],"resources-list":["legacy","modern"],"logging-set-level":["legacy","modern"],"completion-complete":["legacy","modern"],"protocol-invalid-method-error":["legacy","modern"],"modern-client-handshake":["modern"],"modern-server-discover":["modern"],"modern-result-type-present":["modern"],"modern-cacheable-result-hints":["modern"],"modern-cache-hint-coverage":["modern"],"modern-cache-hint-values-valid":["modern"],"modern-cache-scope-stable-across-pages":["modern"],"modern-protocol-version-header-mismatch":["modern"],"modern-method-header-mismatch":["modern"],"modern-name-header-mismatch":["modern"],"modern-unsupported-version-error":["modern"],"modern-missing-method-header-rejected":["modern"],"modern-header-names-case-insensitive":["modern"],"modern-undeclared-capability-error":["modern"],"modern-no-session-id":["modern"],"modern-removed-methods-not-found":["modern"],"modern-resource-not-found-invalid-params":["modern"],"modern-resource-read-no-empty-contents":["modern"],"modern-tool-output-schema-conformant":["modern"],"modern-logs-require-log-level":["modern"],"modern-subscription-ack-precedes-notifications":["modern"],"modern-subscription-filter-and-tagging":["modern"],"modern-subscription-graceful-close":["modern"],"wire-schema-valid":["legacy","modern"]};function qO(){return"8.18.0"}var $D=qO();function j_(e,t){if(!t||t.pendingCheckIds.length===0)return{scored:[...e],pending:[]};const r=new Set(t.pendingCheckIds),n=[],i=[];for(const s of e)(r.has(s.id)?i:n).push(s);return{scored:n,pending:i}}var jO=95,H_=5,HO={should:2,may:1};function VO(e){const t=e.reduce((r,n)=>r+HO[n.tier],0);return Math.min(t,H_)}function Hu(e,t,r,n){const i=e.passed+e.failed+e.couldNotRun,s=VO(t);let o=null;if(i>0){const a=jO*e.passed/i,c=H_-s;o=Math.round(a+c),r!=="passed"?o=Math.min(o,94):t.length>0&&(o=Math.min(o,99))}return{score:o,outcome:r,applicable:i,...e,pending:e.pending??0,advisories:t,advicePointsLost:s,...n!==void 0?{protocolVersion:n}:{}}}function Vu(e,t=[],r,n){const{scored:i,pending:s}=j_(e,n),o={passed:i.filter(c=>c.status==="passed").length,failed:i.filter(c=>c.status==="failed").length,couldNotRun:i.filter(Lg).length,notApplicable:i.filter(RE).length,pending:s.length},{outcome:a}=AE(i);return Hu(o,t,a,r)}function Bu(e){const t={passed:Ri(e,a=>a.passed),failed:Ri(e,a=>a.failed),couldNotRun:Ri(e,a=>a.couldNotRun),notApplicable:Ri(e,a=>a.notApplicable),pending:Ri(e,a=>a.pending??0)},r=e.flatMap(a=>a.advisories??[]),n=e.map(a=>a.outcome),i=n.includes("failed")?"failed":n.includes("incomplete")?"incomplete":"passed",s=e.filter(a=>a.applicable>0),o=new Set(s.map(a=>a.protocolVersion));return Hu(t,r,i,s.length>0&&o.size===1?[...o][0]:void 0)}function Ri(e,t){return e.reduce((r,n)=>r+t(n),0)}function CD(e){if(e.score===null)return`not scored — 0 applicable checks (${e.notApplicable} not applicable)`;const t=[`${e.passed}/${e.applicable} applicable checks passed`];e.failed>0&&t.push(`${e.failed} failed`),e.couldNotRun>0&&t.push(`${e.couldNotRun} could not run`),e.advisories.length>0&&t.push(`${e.advisories.length} advisor${e.advisories.length===1?"y":"ies"} (−${e.advicePointsLost})`),(e.pending??0)>0&&t.push(`${e.pending} pending (unscored by this profile)`);const r=e.protocolVersion?` [${e.protocolVersion}]`:"";return`${e.score}/100 — ${t.join(", ")}${r}`}function Fp(e){return Vu(e.checks,(e.readiness??[]).filter(t=>t.informational!==!0).map(t=>({id:t.id,tier:t.specStrength==="MAY"?"may":"should"})),e.protocolVersion,e.profile)}function V_(e,t,r){const{scored:n}=j_(e,r);return Vu(e,n.flatMap(i=>(i.warnings??[]).map((s,o)=>({id:`${i.id}-warning-${o+1}`,tier:"may"}))),t,r)}function qp(e){return V_(e.checks,e.protocolVersion)}function BO(e){return V_(e.checks,e.discovery.protocolVersion,e.profile)}function jp(e){return e.outcome==="not-applicable"?Hu({passed:0,failed:0,couldNotRun:0,notApplicable:e.steps.length},[],"passed",e.protocolVersion):Vu(e.steps.map(t=>({id:t.step,status:t.status,...t.skipReason?{skipReason:t.skipReason}:{},...t.error?.message?{error:{message:t.error.message}}:{}})),[],e.protocolVersion)}var GO=8;function WO(e){return ir(e,0,new WeakSet)}function ir(e,t,r){if(e===null)return null;switch(typeof e){case"string":case"boolean":return e;case"number":return Number.isFinite(e)?e:String(e);case"bigint":return e.toString();case"undefined":case"function":case"symbol":return}const n=e;if(r.has(n))return"[circular]";if(t>=GO)return"[max-depth]";if(n instanceof Date)return n.toISOString();if(n instanceof URL)return n.toString();r.add(n);try{if(Array.isArray(n))return n.map(s=>ir(s,t+1,r)??null);if(n instanceof Map)return[...n.entries()].map(([s,o])=>[ir(s,t+1,r)??null,ir(o,t+1,r)??null]);if(n instanceof Set)return[...n].map(s=>ir(s,t+1,r)??null);const i={};if(n instanceof Error){i.name=n.name,i.message=n.message;const s=n;s.code!==void 0&&(i.code=ir(s.code,t+1,r)),s.statusCode!==void 0&&(i.statusCode=ir(s.statusCode,t+1,r)),s.cause!==void 0&&(i.cause=ir(s.cause,t+1,r))}for(const[s,o]of Object.entries(n)){const a=ir(o,t+1,r);a!==void 0&&(i[s]=a)}return i}finally{r.delete(n)}}function B_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Gn(e){const t=Object.entries(e).filter(([,r])=>r===void 0?!1:Array.isArray(r)?r.length>0:B_(r)?Object.keys(r).length>0:!0);if(t.length!==0)return WO(Object.fromEntries(t))}function ZO(e){if(e.httpAttempts.length!==0)return e.httpAttempts.map(t=>`${`${t.request.method} ${t.request.url}`} → ${t.response?`${t.response.status} ${t.response.statusText}`:"No response"}`).join(`
100
- `)}function JO(e,t){return{id:e.id,title:e.title,category:e.category,status:e.status,...t?.has(e.id)?{pending:!0}:{},...e.skipReason?{skipReason:e.skipReason}:{},durationMs:e.durationMs,description:e.description,...e.error?.message?{error:e.error.message}:{},...e.details!==void 0||e.error?.details!==void 0?{details:Gn({details:e.details,errorDetails:e.error?.details})}:{}}}function KO(e,t){return{id:e.id,title:e.title,category:e.category,status:e.status,...t?.has(e.id)?{pending:!0}:{},...e.skipReason?{skipReason:e.skipReason}:{},durationMs:e.durationMs,description:e.description,...e.error?.message?{error:e.error.message}:{},...e.details!==void 0||e.error?.details!==void 0||e.warnings?.length?{details:Gn({details:e.details,errorDetails:e.error?.details,warnings:e.warnings})}:{}}}function YO(e){const t=ZO(e);return{id:e.step,title:e.title||e.step,category:"oauth",status:e.status,durationMs:e.durationMs,description:e.summary,...e.error?.message?{error:e.error.message}:{},...e.error?.details!==void 0||e.warnings?.length||e.teachableMoments?.length?{details:Gn({errorDetails:e.error?.details,warnings:e.warnings,teachableMoments:e.teachableMoments})}:{},...t?{output:t}:{}}}function oi(e){const t=e.outcome;return t!=="passed"&&t!=="failed"&&t!=="incomplete"?{}:{outcome:t,...e.incompleteReason?{incompleteReason:e.incompleteReason}:{}}}function Gu(e){const t=e.map(r=>oi(r).outcome??(r.outcome==="not-applicable"||r.passed?"passed":"failed"));if(t.includes("failed"))return{outcome:"failed"};if(t.includes("incomplete")){const r=e.find(n=>oi(n).outcome==="incomplete");return{outcome:"incomplete",...r?.incompleteReason?{incompleteReason:r.incompleteReason}:{}}}return{outcome:"passed"}}function Hp(e,t,r){return{id:`mcp-${r+1}`,title:t,target:e.serverUrl,passed:e.passed,durationMs:e.durationMs,summary:e.summary,cases:(()=>{const n=new Set(e.profile?.pendingCheckIds??[]);return e.checks.map(i=>JO(i,n))})()}}function Ml(e,t,r,n="apps"){const i=new Set(e.profile?.pendingCheckIds??[]);return{id:`${n}-${r+1}`,title:t,target:e.target,passed:e.passed,durationMs:e.durationMs,summary:e.summary,cases:e.checks.map(s=>KO(s,i))}}function Vp(e,t,r){return{id:`oauth-${r+1}`,title:t,target:e.serverUrl,passed:e.passed,durationMs:e.durationMs,summary:e.summary,cases:e.steps.map(YO)}}function XO(e){return"checks"in e&&!("results"in e)&&"serverUrl"in e&&!("target"in e)}function QO(e){return"checks"in e&&!("results"in e)&&"target"in e}function ex(e){return"checks"in e&&!("results"in e)&&"discovery"in e&&B_(e.discovery)&&"wire"in e.discovery}function tx(e){return"steps"in e&&!("results"in e)}function rx(e){return"results"in e&&"serverUrl"in e&&!("target"in e)&&e.results.length>0&&"checks"in e.results[0]}function nx(e){return"results"in e&&"target"in e}function ix(e){return"results"in e&&"serverUrl"in e&&!("target"in e)&&e.results.length>0&&"steps"in e.results[0]}function sx(e){const t=e[0]?.profile;return t?e.every(r=>r.profile?.profileId===t.profileId&&r.profile?.profileVersion===t.profileVersion&&r.profile?.manifestDigest===t.manifestDigest)?{profile:t}:{}:{}}function ox(e){return"results"in e?{schemaVersion:1,kind:"protocol-conformance",name:e.name,passed:e.passed,...Gu(e.results),score:Bu(e.results.map(Fp)),...sx(e.results),durationMs:e.durationMs,groups:e.results.map((t,r)=>Hp(t,t.label,r))}:{schemaVersion:1,kind:"protocol-conformance",name:"MCP Protocol Conformance",passed:e.passed,...oi(e),score:Fp(e),...e.profile?{profile:e.profile}:{},durationMs:e.durationMs,groups:[Hp(e,"MCP Protocol Conformance",0)]}}function ax(e){return"results"in e?{schemaVersion:1,kind:"apps-conformance",name:e.name,passed:e.passed,...Gu(e.results),score:Bu(e.results.map(qp)),durationMs:e.durationMs,groups:e.results.map((t,r)=>Ml(t,t.label,r))}:{schemaVersion:1,kind:"apps-conformance",name:"MCP Apps Conformance",passed:e.passed,...oi(e),score:qp(e),durationMs:e.durationMs,groups:[Ml(e,"MCP Apps Conformance",0)]}}function cx(e){return"results"in e?{schemaVersion:1,kind:"oauth-conformance",name:e.name,passed:e.passed,...Gu(e.results),score:Bu(e.results.map(jp)),durationMs:e.durationMs,groups:e.results.map((t,r)=>Vp(t,t.label,r))}:{schemaVersion:1,kind:"oauth-conformance",name:"OAuth Conformance",passed:e.passed,...oi(e),score:jp(e),durationMs:e.durationMs,groups:[Vp(e,`${e.protocolVersion}/${e.registrationStrategy}`,0)]}}function lx(e){return"lanes"in e&&"findings"in e&&"badges"in e&&!("readinessKind"in e)}var ux={kind:"claude-directory-readiness",providerName:"Claude Directory Readiness",isResult:lx,isDispositive:e=>xE(e)};function dx(e){return e.status==="violated"?"failed":e.status==="satisfied"?"passed":"skipped"}function hx(e,t){const r=t.isDispositive,n=[],i=new Set,s=e.lanes.map(o=>{const a=e.findings.filter(c=>c.lane===o.lane);for(const c of a)i.add(c),!r(c)&&n.push({id:c.id,title:c.title,group:o.lane,kind:c.class,status:c.status,message:c.remediation??c.notEvaluatedReason,details:Gn({provenance:c.provenance,source:c.source,derivedFrom:c.derivedFrom,observed:c.details})});return{id:o.lane,title:o.lane,target:e.context.target,passed:o.status==="ready",durationMs:0,summary:o.summary,cases:a.filter(r).map(c=>({id:c.id,title:c.title,category:c.class,status:dx(c),skipReason:c.status==="not-evaluated"?"could-not-run":c.status==="not-applicable"?"not-applicable":void 0,durationMs:0,description:c.remediation,error:c.status==="violated"?c.remediation??"Requirement not satisfied":c.status==="not-evaluated"?c.notEvaluatedReason:void 0,details:Gn({provenance:c.provenance,intrusiveness:c.intrusiveness,source:c.source,requiresCapabilities:c.requiresCapabilities,derivedFrom:c.derivedFrom,observed:c.details})}))}});for(const o of e.findings)i.has(o)||n.push({id:o.id,title:o.title,group:o.lane,kind:o.class,status:o.status,message:o.remediation??o.notEvaluatedReason??"reported outside any lane in this result",details:Gn({provenance:o.provenance,source:o.source,orphanedLane:o.lane})});return{schemaVersion:1,kind:t.kind,name:t.providerName,passed:e.status==="ready",outcome:e.status==="ready"?"passed":e.status==="not-ready"?"failed":"incomplete",incompleteReason:e.status==="incomplete"?e.summary:void 0,durationMs:e.durationMs,groups:s,advisories:n}}var px={kind:"openai-directory-readiness",providerName:"OpenAI Plugin Directory Readiness",isResult:e=>UE(e),isDispositive:e=>Dg(e)},fx=[px,ux];function vx(e){return fx.find(t=>t.isResult(e))}function PD(e){const t=vx(e);if(t)return hx(e,t);if(XO(e)||rx(e))return ox(e);if(ex(e))return{schemaVersion:1,kind:"tasks-conformance",name:"MCP Tasks Conformance",passed:e.passed,...oi(e),score:BO(e),...e.profile?{profile:e.profile}:{},durationMs:e.durationMs,groups:[Ml(e,"MCP Tasks Conformance",0,"tasks")]};if(QO(e)||nx(e))return ax(e);if(tx(e)||ix(e))return cx(e);throw new Error("Unsupported conformance result shape")}var OD=Object.freeze({chatgpt:!0,copilot:!0,mcpjam:!0,claude:!1,"claude-desktop":!1,cursor:!1,codex:!1,goose:!1,slack:!1,vscode:!1,notion:!1});function Dt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function tt(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function Fo(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function gx(e){if(!Dt(e))return;if(e.source==="legacy"){const r=tt(e.modelId);return r?{source:"legacy",modelId:r}:void 0}if(!W$(e))return;const t=G_(e.connectionRef);return{modelId:e.modelId,source:e.source,...t?{connectionRef:t}:{},...e.nativeModelId!==void 0?{nativeModelId:e.nativeModelId}:{},...e.settings?{settings:{...e.settings.reasoningEffort!==void 0?{reasoningEffort:e.settings.reasoningEffort}:{},...e.settings.temperature!==void 0?{temperature:e.settings.temperature}:{}}}:{},fallback:{provider:e.fallback.provider,model:e.fallback.model}}}function G_(e){if(Dt(e)){if(e.kind==="orgProvider"){const t=tt(e.id);return t?{kind:"orgProvider",id:t}:void 0}if(e.kind==="localProvider"){const t=tt(e.providerKey);if(!t)return;const r=tt(e.customProviderName);return{kind:"localProvider",providerKey:t,...r?{customProviderName:r}:{}}}}}function mx(e){if(!Dt(e))return;const t=tt(e.rail),r=tt(e.providerKey);if(!t||!r)return;const n=tt(e.connectionLabel),i=Fo(e.credentialVersion),s=tt(e.nativeModelId);return{rail:t,providerKey:r,...n?{connectionLabel:n}:{},...i!==void 0?{credentialVersion:i}:{},...s?{nativeModelId:s}:{}}}function _x(e){if(!Dt(e))return;const t=tt(e.rail),r=tt(e.wireModelId),n=tt(e.outcome),i=Fo(e.at);if(!t||!r||!n||i===void 0)return;const s=tt(e.code);return{rail:t,wireModelId:r,outcome:n,...s?{code:s}:{},at:i}}function xD(e){if(!Dt(e))return;const t=gx(e.requested),r=e.resolved;if(!t||!Dt(r))return;const n=tt(r.rail),i=tt(r.wireModelId),s=mx(r.offering);if(!n||!i||!s)return;const o=e.effectiveSettings;if(!Dt(o))return;const a=Fo(o.maxOutputTokens);if(a===void 0)return;const c=G_(r.connectionRef),l=tt(r.nativeModelId),u=e.harness,h=Dt(u)?tt(u.id):void 0,d=Dt(u)?tt(u.runtimeVersion):void 0,p=tt(o.reasoningEffort),f=Fo(o.temperature),v=Array.isArray(e.attempts)?e.attempts.flatMap(T=>{const I=_x(T);return I?[I]:[]}):[],m=tt(e.upstreamModel),_=e.deviation,w=Dt(_)?tt(_.kind):void 0,S=Dt(_)&&typeof _.reason=="string"?_.reason:"";return{requested:t,resolved:{rail:n,wireModelId:i,...c?{connectionRef:c}:{},...l?{nativeModelId:l}:{},offering:s},...h&&d?{harness:{id:h,runtimeVersion:d}}:{},effectiveSettings:{...p?{reasoningEffort:p}:{},...f!==void 0?{temperature:f}:{},maxOutputTokens:a},attempts:v,...m?{upstreamModel:m}:{},...w?{deviation:{kind:w,reason:S}}:{}}}var yx={gateway:"Vercel AI Gateway",openrouter:"OpenRouter",orgCloud:"organization connection",local:"local key"};function Wu(e){return yx[e]??e}var bx={provider_fallback:"Provider fallback",model_substitution:"Model substituted",harness_substitution:"Harness substituted"};function wx(e){return bx[e]??e}function qs(e){const t=e.resolved.connectionRef;return t?.kind==="localProvider"&&t.customProviderName?t.customProviderName:e.resolved.offering.providerKey}function Sx(e){const{rail:t,offering:r}=e.resolved;switch(t){case"gateway":case"openrouter":return`${Wu(t)} (MCPJam key)`;case"orgCloud":return r.connectionLabel?`org connection "${r.connectionLabel}" (${qs(e)})`:`org ${qs(e)} connection`;case"local":return r.connectionLabel?`local key "${r.connectionLabel}" (${qs(e)})`:`local ${qs(e)} key`;default:return`${t} (${r.providerKey})`}}function Ex(e){return e===0?"max output provider default":`max output ${e.toLocaleString("en-US")} tokens`}function kx(e){const t=e.effectiveSettings;return[...t.reasoningEffort?[`effort ${t.reasoningEffort}`]:[],...t.temperature!==void 0?[`temperature ${t.temperature}`]:[],Ex(t.maxOutputTokens)]}function Rx(e){const{wireModelId:t,nativeModelId:r}=e.resolved,n=[...r&&r!==t?[`deployment ${r}`]:[],...e.upstreamModel&&e.upstreamModel!==t?[`provider reported ${e.upstreamModel}`]:[]];return n.length>0?`${t} (${n.join(", ")})`:t}function Ax(e){return[`Ran on ${Rx(e)} via ${Sx(e)}`,...e.harness?[`${e.harness.id} v${e.harness.runtimeVersion}`]:[],...kx(e)].join(", ")}var Ix={hosted:"MCPJam-hosted",org:"organization connection",local:"local key"};function Tx(e){const t=e.requested;if(t.source==="legacy")return`Requested ${t.modelId} (saved without a source; inferred at run time)`;const r=Ix[t.source]??t.source,n=t.fallback.provider==="none"?"no fallback permitted":`${Wu(t.fallback.provider)} fallback permitted`;return`Requested ${t.modelId} (${r}, ${n})`}function $x(e){return e.attempts.map((t,r)=>{const n=t.outcome==="ok"?"ok":t.outcome==="error"?`failed${t.code?` (${t.code})`:""}`:`${t.outcome}${t.code?` (${t.code})`:""}`;return`Attempt ${r+1}: ${Wu(t.rail)} · ${t.wireModelId} · ${n}`})}function MD(e){return{line:Ax(e),request:Tx(e),attempts:$x(e),...e.deviation?{deviation:{kind:e.deviation.kind,title:wx(e.deviation.kind),reason:e.deviation.reason}}:{}}}var Cx="=?base64?";function Px(e){const t=e.toLowerCase();if(t==="mcp-protocol-version")return"protocol-version";if(t==="mcp-method")return"method";if(t==="mcp-name")return"name";if(t==="mcp-session-id")return"session";if(t==="last-event-id")return"resumption";if(t.startsWith("mcp-param-"))return"param"}function Ox(e){const t=globalThis;if(typeof t.atob=="function"){const r=t.atob(e),n=new Uint8Array(r.length);for(let i=0;i<r.length;i+=1)n[i]=r.charCodeAt(i);return new TextDecoder("utf-8",{fatal:!0}).decode(n)}if(t.Buffer)return t.Buffer.from(e,"base64").toString("utf8");throw new Error("no base64 decoder available")}function to(e){if(!e.startsWith("=?base64?")||!e.endsWith("?=")||e.length<11)return{raw:e,encoded:!1,value:e};const t=e.slice(9,e.length-2);try{return{raw:e,encoded:!0,value:Ox(t)}}catch(r){return{raw:e,encoded:!0,value:e,decodeError:r instanceof Error?r.message:String(r)}}}var xx=new Set(["tools/call","resources/read","prompts/get"]),W_=new Set(["tasks/get","tasks/update","tasks/cancel"]);function Mx(e){return e===void 0?!1:xx.has(e)||W_.has(e)}var Bp=["protocol-version","method","name","param","session","resumption"];function Lx(e){return e!==void 0&&W_.has(e)?".params.taskId":e==="resources/read"?".params.uri":".params.name"}function Dx(e){const t=e.declarations??[],r=Wx(t,e.arguments);return t.map(n=>{const i=`${Z_}${n.headerName}`,s=r[i];return{header:i.toLowerCase(),displayName:i,expected:s===void 0?void 0:to(s).value,bodyField:`.params.arguments${n.path.map(o=>`.${o}`).join("")}`}})}function LD(e,t,r){const n=new Map;for(const[d,p]of Object.entries(e))n.set(d.toLowerCase(),{name:d,value:p});const i=n.get("mcp-protocol-version")?.value??t?.protocolVersion,s=!!i&&R$(i)&&A$(i)&&!!t,o=[],a=new Set,c=s&&t?[{header:"mcp-protocol-version",family:"protocol-version",bodyValue:t.protocolVersion,bodyField:"._meta protocolVersion",required:!0},{header:"mcp-method",family:"method",bodyValue:t.method,bodyField:".method",required:!0},{header:"mcp-name",family:"name",bodyValue:t.name,bodyField:Lx(t.method),required:Mx(t.method)}]:[];for(const d of c){a.add(d.header);const p=n.get(d.header);if(!p){d.required&&d.bodyValue!==void 0?o.push({name:d.header,family:d.family,status:"missing",bodyValue:d.bodyValue,bodyField:d.bodyField}):!d.required&&t?.method!==void 0&&o.push({name:d.header,family:d.family,status:"not-required"});continue}const f=to(p.value),v={name:p.name,family:d.family,raw:p.value,decoded:f.encoded&&!f.decodeError?f.value:void 0};f.decodeError?o.push({...v,status:"undecodable"}):d.bodyValue===void 0?o.push({...v,status:"unchecked"}):f.value===d.bodyValue?o.push({...v,status:"match",bodyField:d.bodyField}):o.push({...v,status:"mismatch",bodyValue:d.bodyValue,bodyField:d.bodyField})}const l=r!==void 0&&"arguments"in r,u=s&&r?Dx(r):[],h=s&&r?.declarations!==void 0;for(const d of u){a.add(d.header);const p=n.get(d.header);if(!p){if(!l){o.push({name:d.displayName,family:"param",status:"unchecked"});continue}o.push(d.expected===void 0?{name:d.displayName,family:"param",status:"not-required"}:{name:d.displayName,family:"param",status:"missing",bodyValue:d.expected,bodyField:d.bodyField});continue}const f=to(p.value),v={name:p.name,family:"param",raw:p.value,decoded:f.encoded&&!f.decodeError?f.value:void 0};f.decodeError?o.push({...v,status:"undecodable"}):l?d.expected===void 0?o.push({...v,status:"mismatch",bodyValue:"(absent from arguments)",bodyField:d.bodyField}):f.value===d.expected?o.push({...v,status:"match",bodyField:d.bodyField}):o.push({...v,status:"mismatch",bodyValue:d.expected,bodyField:d.bodyField}):o.push({...v,status:"unchecked"})}for(const[d,p]of n){if(a.has(d))continue;const f=Px(p.name);if(!f)continue;const v=to(p.value),m=s&&f==="param"&&!!v.decodeError,_=h&&f==="param"&&!m;o.push({name:p.name,family:f,raw:p.value,decoded:v.encoded&&!v.decodeError?v.value:void 0,status:m?"undecodable":_?"undeclared":"unchecked"})}return o.sort((d,p)=>Bp.indexOf(d.family)-Bp.indexOf(p.family)||d.name.localeCompare(p.name))}var Gp="x-mcp-header",Z_="Mcp-Param-",Nx=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,zx=new Set(["string","integer","boolean","number"]),Ux=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],Fx=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function qx(e){return e.length===0?"<root>":e.join(".")}function DD(e){const t=[],r=new Map,n=(s,o,a)=>{if(s===null||typeof s!="object")return;const c=s;if(Gp in c){const u=qx(o);if(!a||o.length===0)return`${u}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;const h=c[Gp];if(typeof h!="string"||h.length===0)return`${u}: x-mcp-header MUST be a non-empty string`;if(!Nx.test(h))return`${u}: x-mcp-header '${h}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;const d=typeof c.type=="string"?c.type:void 0;if(d===void 0||!zx.has(d))return`${u}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${d??"<none>"}`;const p=h.toLowerCase(),f=r.get(p);if(f!==void 0)return`x-mcp-header '${h}' is not case-insensitively unique (also declared as '${f}')`;r.set(p,h),t.push({path:o,headerName:h,type:d})}const l=c.properties;if(l!==null&&typeof l=="object")for(const[u,h]of Object.entries(l)){const d=n(h,[...o,u],a);if(d!==void 0)return d}for(const u of Ux){const h=c[u];if(h===void 0)continue;const d=h!==null&&typeof h=="object"&&Fx.has(u),p=Array.isArray(h)?h:d?Object.values(h):[h];for(const f of p){const v=n(f,[...o,`<${u}>`],!1);if(v!==void 0)return v}}},i=n(e,[],!0);return i===void 0?{valid:!0,declarations:t}:{valid:!1,reason:i}}function jx(e){const t=globalThis,r=new TextEncoder().encode(e);if(typeof t.btoa=="function"){let n="";for(const i of r)n+=String.fromCodePoint(i);return t.btoa(n)}if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");throw new Error("no base64 encoder available")}function Hx(e){if(e.length===0||e.startsWith("=?base64?")&&e.endsWith("?=")||e!==e.trim())return!0;for(let t=0;t<e.length;t+=1){const r=e.codePointAt(t);if(!(r===9||r>=32&&r<=126))return!0}return!1}function Vx(e){if(!Hx(e))return e;const t=jx(e);return`${Cx}${t}?=`}function Bx(e){if(typeof e=="string")return e;if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e)?void 0:String(e)}function Gx(e,t){let r=e;for(const n of t){if(r===null||typeof r!="object")return;r=r[n]}return r}function Wx(e,t){const r={};for(const n of e){const i=Gx(t,n.path);if(i==null)continue;const s=Bx(i);s!==void 0&&(r[`${Z_}${n.headerName}`]=Vx(s))}return r}var Zx="tracestate",Jx="baggage",Kx=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,Yx="0".repeat(32),Xx="0".repeat(16);function Qx(e){if(typeof e!="string")return;const t=Kx.exec(e);if(!t)return;const[,r,n,i,s]=t;if(!(r==="ff"||r!=="00")&&!(n===Yx||i===Xx))return{version:r,traceId:n,spanId:i,flags:s,sampled:(Number.parseInt(s,16)&1)===1}}function e1(e){return Qx(e)!==void 0}var t1=32,r1=/^(?:[a-z][a-z0-9_\-*/]{0,255}|[a-z0-9][a-z0-9_\-*/]{0,240}@[a-z][a-z0-9_\-*/]{0,13})$/,n1=/^[\x20-\x2b\x2d-\x3c\x3e-\x7e]{0,255}[\x21-\x2b\x2d-\x3c\x3e-\x7e]$/;function i1(e){if(typeof e!="string"||e.length===0)return!1;const t=e.split(",");if(t.length>t1)return!1;let r=0;for(const n of t){const i=n.trim();if(i.length===0)continue;r+=1;const s=i.indexOf("=");if(s<=0||!r1.test(i.slice(0,s))||!n1.test(i.slice(s+1)))return!1}return r>0}var s1=180,o1=8192,a1=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Wp=/^[\x21\x23-\x2b\x2d-\x3a\x3c-\x5b\x5d-\x7e]*$/;function c1(e){if(typeof e!="string"||e.length===0||e.length>o1)return!1;const t=e.split(",");if(t.length>s1)return!1;for(const r of t){const n=r.trim();if(n.length===0)return!1;const[i,...s]=n.split(";"),o=i.indexOf("=");if(o<=0||!a1.test(i.slice(0,o).trim())||!Wp.test(i.slice(o+1).trim()))return!1;for(const a of s)if(!Wp.test(a.replace(/=/g,"").trim()))return!1}return!0}function l1(e){if(!(!e||!e1(e.traceparent)))return{traceparent:e.traceparent,...i1(e.tracestate)?{tracestate:e.tracestate}:{},...c1(e.baggage)?{baggage:e.baggage}:{}}}function ND(e){if(!e||typeof e!="object")return;const t=r=>{const n=e[r];return typeof n=="string"?n:void 0};return l1({traceparent:t("traceparent")??"",tracestate:t(Zx),baggage:t(Jx)})}var zD=At.MissingRequiredClientCapability,u1=/\.[cm]?[jt]sx?$/,d1=/^(?:[a-z][a-z0-9+.-]*:\/\/|\/)/i;function h1(e,t){if(typeof e!="string"||!d1.test(e))return!1;let r;try{r=new URL(e,t)}catch{return!1}return r.origin!==t?!1:!u1.test(r.pathname)}function p1(e,t){return e.length===0?!1:e.every(r=>h1(r,t))}function f1(e,t){return e.length===0?!1:e.every(r=>p1(r,t))}var v1=["timeout","network","upstream_status","bad_json","bad_payload","provisioning"],g1=/^[A-Z][A-Z0-9_]{1,63}$/;function m1(e){return typeof e=="string"&&v1.includes(e)}function _1(e){if(!e||typeof e!="object")return;const{reason:t,upstreamStatus:r,networkCode:n}=e;if(!m1(t))return;const i={reason:t};return typeof r=="number"&&Number.isInteger(r)&&r>=100&&r<=599&&(i.upstreamStatus=r),typeof n=="string"&&g1.test(n)&&(i.networkCode=n),i}var J_="mcpjam_guest_session_v1",Ll="mcpjam_guest_activated",Aa=3e5,wt=null,yr=null,br=null,sn=null,K_=!1,Or=0,Dl=new Set,y1=6e5,Un=null,Ai=null;function Y_(){for(const e of Dl)e()}function X_(e){Ai!==null&&(clearTimeout(Ai),Ai=null),Un=e,e&&(Ai=setTimeout(()=>{Ai=null,Un===e&&X_(null)},Math.max(0,e.until-Date.now()))),Y_()}function b1(){return Un&&Un.until<=Date.now()&&(Un=null),Un}function Ia(e){const t=wt?.guestId??null;wt=e,t!==(wt?.guestId??null)&&Y_()}function UD(e){return Dl.add(e),()=>{Dl.delete(e)}}function FD(e){if(e)try{localStorage.getItem(Ll)!==e&&localStorage.setItem(Ll,e)}catch{}}function qD(e){if(!e)return!1;try{return localStorage.getItem(Ll)===e}catch{return!1}}function w1(){if(typeof window>"u")return;const e=window.__MCP_GUEST_BOOTSTRAP__;try{delete window.__MCP_GUEST_BOOTSTRAP__}catch{window.__MCP_GUEST_BOOTSTRAP__=void 0}e&&(typeof e.token!="string"||e.token.length===0||typeof e.expiresAt!="number"||typeof e.guestId!="string"||e.guestId.length===0||e.expiresAt-Aa<=Date.now()||(wt={guestId:e.guestId,token:e.token,expiresAt:e.expiresAt}))}w1();function Zu(){if(K_)return null;try{const e=localStorage.getItem(J_);if(!e)return null;const t=JSON.parse(e);return typeof t.token=="string"&&t.token.length>0?t.token:null}catch{return null}}function Zp(){try{localStorage.removeItem(J_)}catch{}K_=!0}var Pi=class extends Error{status;upstreamFailure;constructor(e,t,r){super(e),this.name="GuestSessionRequestError",this.status=t,this.upstreamFailure=r}},Q_=class extends Pi{retryAfterMs;constructor(e){super("guest-session creation refused (429)"),this.name="GuestSessionRefusedError",this.retryAfterMs=e}},S1=1e3;async function E1(e){if(typeof e.json!="function")return;let t;try{const r=await Promise.race([e.json(),new Promise(n=>{t=setTimeout(()=>n(void 0),S1)})]);return _1(r?.details)}catch{return}finally{t!==void 0&&clearTimeout(t)}}function k1(e){if(!e)return"";const t=e.networkCode??(e.upstreamStatus!==void 0?String(e.upstreamStatus):void 0);return` (${e.reason}${t?` ${t}`:""})`}function R1(e){const t=e?Number.parseInt(e,10):NaN;return Number.isFinite(t)&&t>0?t*1e3:y1}async function Ju(e,t){const r={mode:e};t&&(r.legacyToken=t);let n;try{n=await fetch("/api/web/guest-session",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})}catch(s){throw new Pi(s instanceof Error?s.message:"network error")}if(n.status===204)return t&&Zp(),null;if(n.status===429)throw new Q_(R1(n.headers?.get?.("retry-after")));if(!n.ok){const s=await E1(n);throw new Pi(`guest-session request failed: ${n.status} ${n.statusText}${k1(s)}`,n.status,s)}let i;try{i=await n.json()}catch(s){throw new Pi(`guest-session response was not valid JSON: ${s instanceof Error?s.message:String(s)}`)}if(typeof i?.token!="string"||typeof i?.expiresAt!="number")throw new Pi("guest-session response missing token or expiresAt");return t&&Zp(),i}async function A1(){if(wt&&wt.expiresAt-Aa>Date.now())return wt;if(b1())return null;if(yr)return yr;const e=Zu(),t=Or;let r=Promise.resolve(null);return r=(async()=>{try{const n=await Ju("lookup_or_create",e);return n&&t===Or&&Ia(n),n}catch(n){if(n instanceof Q_)return X_({until:Date.now()+n.retryAfterMs}),null;throw console.error("Failed to create guest session:",n),n}finally{yr===r&&(yr=null)}})(),yr=r,r.catch(()=>{}),yr}async function I1(){try{return await A1()}catch{return null}}async function jD(){return(await I1())?.token??null}function Nl(){return wt&&wt.expiresAt-Aa>Date.now()?wt:null}async function T1(){if(wt&&wt.expiresAt-Aa>Date.now())return wt.token;if(br)return(await br)?.token??null;const e=Zu(),t=Or;let r=Promise.resolve(null);return r=(async()=>{try{const n=await Ju("lookup_only",e);return n&&t===Or&&Ia(n),n}finally{br===r&&(br=null)}})(),br=r,(await br)?.token??null}async function HD(){const e=Nl();if(e?.guestId)return e.guestId;try{await T1()}catch{return null}return Nl()?.guestId??null}function $1(){Or+=1,Ia(null),yr=null,br=null,sn=null}async function VD(){let e=!1;try{const t=await fetch("/api/web/guest-session/revoke",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"}});if(t.ok)try{e=(await t.json())?.revoked===!0}catch{e=!1}}catch(t){console.error("Failed to revoke guest session:",t)}finally{$1()}return e}async function BD(){try{const e=await fetch("/api/web/guest-session/promotion-proof",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"}});if(e.status===204||!e.ok)return null;const t=await e.json();return typeof t.token=="string"&&t.token.length>0?t.token:null}catch(e){return console.error("Failed to fetch guest promotion proof:",e),null}}async function C1(){if(sn)return(await sn)?.token??null;Or+=1;const e=Or;wt=null,yr=null,br=null,sn=(async()=>{try{const t=await Ju("lookup_or_create",Zu());return t&&e===Or&&Ia(t),t}catch(t){throw console.error("Failed to refresh guest session:",t),t}})(),sn.catch(()=>{});try{return(await sn)?.token??null}finally{sn=null}}async function GD(){try{return await C1()}catch{return null}}var ey=new Set(["caniuse.dev","www.caniuse.dev"]),P1=new Set(["score.mcpjam.com","www.score.mcpjam.com"]),O1=new Set([...ey,...P1]),WD="https://app.mcpjam.com";function x1(e){return ey.has(e.toLowerCase())}function ZD(e=typeof window>"u"?void 0:window.location.hostname){return!!e&&x1(e)}var JD=null,KD="write",Jp=null,M1=String(101376);function YD(){return Jp?`https://discord.com/oauth2/authorize?${new URLSearchParams({client_id:Jp,scope:"bot applications.commands",permissions:M1}).toString()}`:null}var L1="phc_dTOPniyUNU2kD8Jx8yHMXSqiZHM8I91uWopTMX6EBE9",D1="https://us.i.posthog.com";function N1(){return typeof window<"u"&&window.location?.origin?.startsWith("http")?`${window.location.origin}/tlm`:D1}function ty(e){const t=Nl()?.guestId,r=e&&Object.keys(e).length>0?e:void 0;return!t&&!r?{}:{bootstrap:{...t?{distinctID:t,isIdentifiedID:!1}:{},...r?{featureFlags:r}:{}}}}var z1={advanced_disable_feature_flags:!0,advanced_disable_feature_flags_on_first_load:!0},U1=["/results/","/conformance/shared/","/evals/shared/"];function ry(e){let t=e;for(const r of U1){const n=r.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&");t=t.replace(new RegExp(`(${n})[^/?#]+`,"g"),"$1[redacted]")}return t=t.replace(/(\/organizations\/)[^/?#]+/g,"$1[redacted]"),t}var F1=new Set(["Load failed","Failed to fetch","NetworkError when attempting to fetch resource."]),q1=/^'TypeError' captured as exception with message: '([\s\S]*)'$/;function j1(e){const t=q1.exec(e.value),r=t?t[1]:e.type==="TypeError"?e.value:void 0;return r===void 0?!1:F1.has(r)||r.startsWith("Failed to fetch (")&&r.endsWith(")")}var H1=1e4;function V1(e){const t=e.$exception_list;if(!(Array.isArray(t)&&t.some(i=>typeof i?.value=="string"&&j1(i))))return;const r=iy();if(!r)return;const n=Date.now()-r.at;n>H1||(e.failed_request=`${r.method} ${ry(r.target)}`,e.failed_request_age_ms=n)}function B1(e,t){for(const r of["$current_url","$referrer","$pathname","$session_entry_url","$session_entry_pathname","$session_entry_referrer","$initial_current_url","$initial_pathname","$initial_referrer"])typeof e[r]=="string"&&(e[r]=ry(e[r]));return t==="$exception"&&V1(e),e}function G1(e){if(e?.event!=="$exception"||typeof window>"u")return e;const t=e.properties?.$exception_list;if(!Array.isArray(t))return e;const r=t.map(n=>{const i=n?.stacktrace?.frames;return Array.isArray(i)?i.map(s=>s?.filename):[]});return f1(r,window.location.origin)?null:e}var W1=O1;function gs(){return Z1()}function Z1(){return typeof window<"u"&&window.isElectron===!0}var J1="data-ph-no-capture",K1={maskAllInputs:!0,maskInputOptions:{password:!0},maskTextSelector:`[${J1}]`};function Ku(e=typeof window>"u"?void 0:window.location?.pathname){return!!e&&(e.startsWith("/results/")||e.startsWith("/conformance/shared/")||e.startsWith("/evals/shared/"))}function Y1(){return gs()&&!Ku()}var Ec=!1;function XD(e,t){try{if(!gs())return;if(Ku(t)){e.sessionRecordingStarted?.()&&(Ec=!0),e.stopSessionRecording?.();return}Ec&&(Ec=!1,e.startSessionRecording?.())}catch{}}function X1(e=typeof window>"u"?void 0:window.location?.hostname){const t=!!e&&W1.has(e.toLowerCase());return{capture_pageview:t?"history_change":!1,capture_pageleave:t}}var Kp={api_host:N1(),ui_host:"https://us.posthog.com",...ty(),...X1(),...z1,person_profiles:"always",sanitize_properties:B1,before_send:G1,capture_dead_clicks:!0,get capture_exceptions(){return gs()},get disable_session_recording(){return!Y1()},session_recording:K1,loaded:e=>{e.register({environment:"production",platform:zl(),version:"3.12.4",deployment:"self_hosted",source:"client"}),e.setPersonPropertiesForFlags?.({local_browser_security_version:"1",deployment:"self_hosted",platform:zl()})}};function Q1(e){const t=ty(e);return"bootstrap"in t?Object.defineProperties({},{...Object.getOwnPropertyDescriptors(Kp),bootstrap:{value:t.bootstrap,enumerable:!0,configurable:!0,writable:!0}}):Kp}var QD=()=>L1,eN=e=>Q1(e);function zl(){if(window?.isElectron){const e=navigator.userAgent.toLowerCase();return e.includes("mac")||e.includes("darwin")?"mac":e.includes("win")?"win":"electron"}return"npm"}function eM(){return"production"}function tN(e){const t=eM();return{location:e,platform:zl(),...t!==void 0?{environment:t}:{}}}function tM(e){try{if(typeof e!="object"||e===null)return;const t=e.normalized;return FC(t)?t:void 0}catch{return}}function rN(e,t){try{if(!gs()||Fl(e))return!1;const r=tM(e)??dP(e),n=lP(r);return n!=="mcpjam"?!1:(ny(e,{...t,extra:{...t.extra??{},slug:r.slug,origin:n}}),!0)}catch{return!1}}var rM=rf();function nM(e){if(e instanceof Error)return e;try{return new Error(typeof e=="string"?e:JSON.stringify(e))}catch{return new Error(String(e))}}function ny(e,t){if(Fl(e))return;const r=Ay(nM(e)),n=tf(r.message);if(n&&t.queryBackend&&(n.convex_backend=t.queryBackend),n&&rM(n.convex_backend,n.request_id))return;const i=n&&typeof window<"u"?Ac(window.location.href):void 0;try{K0(r,{level:t.level??"error",tags:{source:t.source,...n},...n?{extra:{boundary:t.extra?.boundary,componentStack:t.extra?.componentStack,page_location:i}}:t.extra?{extra:t.extra}:{}})}catch{}try{gs()&&!Ku()&&kE.captureException(r,{source:t.source,level:t.level??"error",...n?{...n,page_location:i}:t.extra??{}})}catch{}}function nN(e,t,r){ny(e,{source:r?`react_boundary:${r}`:"react_boundary",extra:{componentStack:t?.componentStack??void 0,boundary:r??"unnamed"}})}export{qO as $,sM as $i,sL as $n,$M as $r,oC as $t,qD as A,vM as Ai,Dm as An,NM as Ar,Cl as At,LD as B,cn as Bi,pl as Bn,a0 as Br,lP as Bt,T1 as C,fM as Ci,rn as Cn,qM as Cr,PP as Ct,b1 as D,Ho as Di,PL as Dn,p0 as Dr,$P as Dt,BD as E,Ly as Ei,dT as En,FM as Er,la as Et,f1 as F,dM as Fi,fl as Fn,MM as Fr,fD as Ft,MD as G,Iy as Gi,fL as Gn,CM as Gr,Jt as Gt,wx as H,jo as Hi,mI as Hn,Vr as Hr,m_ as Ht,ND as I,Oy as Ii,AL as In,u0 as Ir,dD as It,Bu as J,Ay as Ji,kE as Jn,ad as Jr,oD as Jt,PD as K,cM as Ki,UE as Kn,Go as Kr,Ou as Kt,Qx as L,uM as Li,ze as Ln,d0 as Lr,dP as Lt,VD as M,Hl as Mi,hn as Mn,LM as Mr,vP as Mt,UD as N,cs as Ni,up as Nn,OM as Nr,pD as Nt,I1 as O,My as Oi,CL as On,UM as Or,gD as Ot,_1 as P,Cy as Pi,ML as Pn,xM as Pr,hD as Pt,BO as Q,Xu as Qi,YM as Qn,Gl as Qr,nD as Qt,W_ as R,td as Ri,$L as Rn,l0 as Rr,FC as Rt,Nl as S,pM as Si,Mt as Sn,jM as Sr,Fr as St,jD as T,hM as Ti,TL as Tn,y0 as Tr,mD as Tt,Wu as U,$t as Ui,wL as Un,_n as Ur,SC as Ut,DD as V,rd as Vi,II as Vn,ls as Vr,uD as Vt,xD as W,nf as Wi,lk as Wn,PM as Wr,mp as Wt,jp as X,Ry as Xi,XM as Xn,ao as Xr,cD as Xt,qp as Y,Fl as Yi,nL as Yn,Jn as Yr,aD as Yt,Fp as Z,aM as Zi,K0 as Zn,Vo as Zr,sC as Zt,WD as _,xi as _i,Ar as _n,VM as _r,_a as _t,zl as a,Ir as ai,X$ as an,KM as ar,_r as at,GD as b,gM as bi,EL as bn,dd as br,ma as bt,Ku as c,Bl as ci,YL as cn,ZM as cr,SD as ct,Y1 as d,EM as di,qL as dn,k0 as dr,wO as dt,oM as ea,TM as ei,iD as en,rL as er,TD as et,tN as f,wM as fi,G$ as fn,HM as fr,mO as ft,YD as g,bM as gi,zs as gn,E0 as gr,N_ as gt,KD as h,yM as hi,A$ as hn,BM as hr,yD as ht,L1 as i,RM as ii,rD as in,iL as ir,UO as it,FD as j,oo as ji,Lo as jn,DM as jr,vD as jt,A1 as k,jl as ki,IL as kn,zM as kr,wP as kt,gs as l,Zn as li,Y$ as ln,JM as lr,ED as lt,JD as m,Hy as mi,R$ as mn,ff as mr,pO as mt,ny as n,ro as na,AM as ni,eD as nn,eL as nr,FO as nt,QD as o,kM as oi,QL as on,fr as or,Np as ot,XD as p,SM as pi,wl as pn,GM as pr,bD as pt,CD as q,lM as qi,cL as qn,$c as qr,Cr as qt,rN as r,IM as ri,tD as rn,tL as rr,RD as rt,eN as s,Vl as si,XL as sn,T0 as sr,TO as st,nN as t,no as ta,Gy as ti,sD as tn,QM as tr,AD as tt,ry as u,zt as ui,jL as un,A0 as ur,wD as ut,ZD as v,_M as vi,xL as vn,WM as vr,ya as vt,HD as w,xy as wi,OL as wn,m0 as wr,De as wt,C1 as x,Fy as xi,RL as xn,Wo as xr,_D as xt,$1 as y,mM as yi,kL as yn,Wl as yr,wa as yt,Px as z,sf as zi,cT as zn,c0 as zr,pP as zt};
91
+ `).join(" "),s=d;continue}try{t[c]=zc(l)}catch(u){if(!(u instanceof Nc))throw u;n.push(o)}s++}return{data:t,unparsed:r,tooDeep:n}}function tR(e){const t=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(e);return t?{frontmatter:t[1],body:e.slice(t[0].length)}:null}function rR(e){return!Array.isArray(e)||e.some(t=>typeof t!="string")?null:e}async function lL(e){const{pluginName:t,directory:r,directoryName:n,skillFilePath:i,skillText:s,skillContentHash:o,files:a,issues:c}=e,l=`skill:${n}`,u={path:i,componentKey:l},h=tR(s);if(h===null)return c.error("SKILL_FRONTMATTER_MISSING",`skill "${n}" is missing YAML frontmatter in SKILL.md`,u),null;const{data:d,unparsed:p,tooDeep:f}=eR(h.frontmatter);for(const M of p)c.warn("SKILL_FRONTMATTER_UNPARSED",`skill "${n}": frontmatter line not interpreted: ${M.trim()}`,u);for(const M of f)c.error("VALUE_TOO_DEEP",`skill "${n}": frontmatter value nests deeper than 32 levels: ${M.trim().slice(0,80)}`,u);const v=d.name;if(typeof v!="string"||v.length===0)return c.error("SKILL_MISSING_NAME",`skill "${n}" is missing the required "name" field`,u),null;if(!Qk(v))return c.error("SKILL_INVALID_NAME",`skill name "${v}" must be kebab-case ([a-z0-9-], 1-${Ov} chars, no "--")`,u),null;v!==n&&c.warn("SKILL_NAME_MISMATCH",`skill name "${v}" does not match its directory "${n}"`,u);const m=d.description;if(typeof m!="string"||m.length===0)return c.error("SKILL_MISSING_DESCRIPTION",`skill "${n}" is missing the required "description" field`,u),null;if(m.length>Ed)return c.error("SKILL_DESCRIPTION_TOO_LONG",`skill "${n}" description exceeds ${Ed} characters`,u),null;let _;const w=d.allow_implicit_invocation;w!==void 0&&(typeof w!="boolean"?c.warn("SKILL_INVALID_METADATA",`skill "${n}": "allow_implicit_invocation" must be a boolean`,u):_=w);const S=[],T=d.mcp_tools;if(T!==void 0){const M=rR(T);if(M===null)c.warn("SKILL_INVALID_METADATA",`skill "${n}": "mcp_tools" must be a list of strings`,u);else for(const L of M)S.includes(L)||S.push(L)}const C=a.filter(M=>M.path!==i).map(M=>({path:M.path,relativePath:M.path.slice(r.length+1),size:M.size,contentHash:M.contentHash})),$=await Vk(a.map(M=>({path:M.path.slice(r.length+1),contentHash:M.contentHash})));return{componentKey:l,directory:r,directoryName:n,skillFilePath:i,name:v,description:m,modelRef:`${t}/${v}`,instructions:h.body.trim(),frontmatter:d,frontmatterRaw:h.frontmatter,..._!==void 0?{allowImplicitInvocation:_}:{},mcpToolDependencies:S,supportingFiles:C,contentHash:o,aggregateHash:$}}var uL=new TextDecoder("utf-8",{fatal:!1}),nR=new Set(["access_token","refresh_token","id_token","client_secret","code","code_verifier","authorization_code","authorization","state","cookie","set_cookie","api_key"]),iR=[/^authorization$/i,/^proxy-authorization$/i,/^cookie$/i,/^set-cookie$/i,/^x-api-key$/i,/^api-key$/i,/^apikey$/i,/^x-auth-token$/i,/^x-csrf-token$/i,/^x-session-token$/i,/^x-access-token$/i,/^x-refresh-token$/i,/^x-client-secret$/i,/^x-credential$/i];function Xl(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").toLowerCase()}var sR=["_type","_types","_endpoint","_endpoints","_supported","_method","_methods","_uri","_uris","_url","_urls","_alg","_algs","_values","_in"];function oR(e){return sR.some(t=>e.endsWith(t))}function Ql(e){return nR.has(e)?!0:oR(e)?!1:/(^|_)(token|secret|password|credential|cookie|auth)(_|$)/.test(e)||/(^|_)api_?key(_|$)/.test(e)}function aR(e){return Ql(Xl(e))}function cR(e){return Ql(Xl(e))||iR.some(t=>t.test(e))}function lR(e){return Ql(Xl(e))}function eu(e){return typeof e!="string"||e.length<=8?"[redacted]":`${e.slice(0,4)}...[redacted]...${e.slice(-2)}`}var xv="client_secret|access_token|refresh_token|id_token|code_verifier|code|assertion|password|api[-_]?key|token|secret|state",Mv=new RegExp(`(^|[^\\w-])((?:[\\w-]*[_-])?(?:${xv}))=[^&\\s"'<>]+`,"gi"),Lv=`(?:(?:[\\w-]*[_-])?(?:${xv}))`,uR=new RegExp(`("${Lv}"\\s*:\\s*)"(?:\\\\.|[^"\\\\])*"`,"gi"),dR=new RegExp(`("${Lv}"\\s*:\\s*)"(?:\\\\[\\s\\S]?|[^"\\\\])*$`,"gi");var hR=new RegExp(`\\b((?:[\\w-]*[_-])?(?:client[-_]?secret|access[-_]?token|refresh[-_]?token|id[-_]?token|code[-_]?verifier))(\\s*[:=]\\s*)("(?:\\\\.|[^"\\\\])*"|[^&\\s"'<>,;]+)`,"gi");function Dv(e){const t=e.replace(/[.,;:!?)\]}]+$/,"");return!/^[a-z]{1,20}$/.test(t)}function pR(e,t,r,n){return Dv(n)?`${t}${r}[redacted]`:e}function Ir(e,t={}){const r=t.maxScanned??4e3,n=t.maxLength??500,i=e.length>r,s=(i?e.slice(0,r):e).replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/?#]*@/gi,"$1[redacted]@").replace(/(^|[\s(<"'])[^\s/@:]+:[^\s/]+@(?=[\w.-]+)/g,"$1[redacted]@").replace(hR,(o,a,c,l)=>`${a}${c}${l.startsWith('"')?'"[redacted]"':"[redacted]"}`).replace(Mv,"$1$2=[redacted]").replace(/\b((?:proxy-)?authorization\s*[:=]\s*)(bearer|basic)\s+\S+/gi,"$1$2 [redacted]").replace(/\b(bearer|basic)(\s+)(\S+)/gi,pR).replace(uR,'$1"[redacted]"');return(i?s.replace(dR,'$1"[redacted]').replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/?#]*$/gi,"$1[redacted]"):s).slice(0,n)}function fR(e){if(!e)return;if(typeof e=="string"){const r=e.trim();if(!r)return;if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{const s=JSON.parse(r);if(typeof s=="object"&&s!==null&&!Array.isArray(s)){const o=Object.entries(s).flatMap(([a,c])=>typeof c=="string"?[[a,c]]:typeof c=="number"||typeof c=="boolean"?[[a,String(c)]]:[]);return o.length>0?Object.fromEntries(o):void 0}}catch{}const n=new URLSearchParams(r),i=Object.fromEntries(n.entries());return Object.keys(i).length>0?i:void 0}if(typeof e!="object"||e===null||Array.isArray(e))return;const t=Object.entries(e).flatMap(([r,n])=>typeof n=="string"?[[r,n]]:typeof n=="number"||typeof n=="boolean"?[[r,String(n)]]:[]);return t.length>0?Object.fromEntries(t):void 0}function vR(e){return Object.keys(e).every(t=>t.length<=64&&/^[A-Za-z0-9_.\-[\]]+$/.test(t))}var gR=3;function mR(e,t){return/^https?:\/\//i.test(e)?t>=gR?"[redacted]":tu(e,t+1):e.replace(Mv,"$1$2=[redacted]")}function tu(e,t=0){try{const r=new URL(e);r.username="",r.password="";let n=!1;const i=new URLSearchParams;for(const[s,o]of r.searchParams.entries()){const a=lR(s)?"[redacted]":mR(o,t);n||=a!==o,i.append(s,a)}return n&&(r.search=i.toString()),r.hash&&(r.hash="#[redacted]"),r.toString()}catch{return Ir(e)}}function Nv(e){const t=e.trim();if(!t)return e;if(/^https?:\/\//i.test(t))return tu(t);if(t.includes("=")||t.includes("&")||t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")){const r=fR(t);if(r&&vR(r))return Wt(r)}return Ir(t)}function Wt(e){return Array.isArray(e)?e.map(t=>Wt(t)):typeof e=="string"?Nv(e):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).map(([t,r])=>aR(t)?[t,eu(r)]:[t,Wt(r)]))}function _R(e){const t=Nv(e);return typeof t=="string"?t:eu(e)}function kd(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>cR(t)?[t,eu(r)]:[t,_R(r)]))}function dL(e){const t=typeof e.callbackState=="string"&&e.callbackState.length>0;return e.issuedState?{statePresent:t,stateMatched:t&&e.callbackState===e.issuedState}:{statePresent:t}}function yR(e){return Uc(e,[])}function Uc(e,t){return Array.isArray(e)?e.map(r=>Uc(r,t)):!e||typeof e!="object"?typeof e=="string"?bR(e):e:Object.fromEntries(Object.entries(e).map(([r,n])=>[r,SR(r,n,t)?"[REDACTED]":Uc(n,[...t,r])]))}function bR(e){return e.replace(/\b(authorization|proxy-authorization|cookie|set-cookie)\s*:\s*[^\r\n]*/giu,(t,r)=>`${r}: [REDACTED]`).replace(/\bBearer(\s+)(\S+)/giu,wR).replace(/\b(access_token|refresh_token|client_secret|id_token|code|code_verifier|accessToken|refreshToken|clientSecret|idToken|codeVerifier)=([^&\s]+)/giu,"$1=[REDACTED]").replace(/(["']?(?:access_token|refresh_token|client_secret|id_token|code|code_verifier|accessToken|refreshToken|clientSecret|idToken|codeVerifier)["']?\s*:\s*["'])[^"']*(["'])/giu,"$1[REDACTED]$2")}function wR(e,t,r){return/^[A-Za-z_][A-Za-z0-9_-]*=/u.test(r)?e:Dv(r)?`Bearer${t}[REDACTED]`:e}function SR(e,t,r){const n=e.toLowerCase().replace(/[^a-z0-9]/gu,"");return n==="code"?kR(t,r):n==="authorization"||n==="proxyauthorization"||n==="cookie"||n==="setcookie"?!0:(n==="codeverifier"||n==="accesstoken"||n.endsWith("accesstoken")||n==="refreshtoken"||n.endsWith("refreshtoken")||n==="clientsecret"||n.endsWith("clientsecret")||n==="idtoken"||n.endsWith("idtoken"))&&ER(t)||n==="apikey"||n==="xapikey"}function ER(e){return typeof e=="string"&&e.length>0}function kR(e,t){return t[t.length-1]==="error"||t[t.length-1]==="snapshotError"||typeof e!="string"||/^[A-Z0-9_:-]+$/u.test(e)?!1:e.length>0}var RR="ERA_NEGOTIATION_FAILED";function AR(e){return!!e&&typeof e=="object"&&e.code===RR}function IR(e){const t=new Set;let r=e;for(;AR(r)&&!t.has(r);){t.add(r);const n=r.data,i=(n&&typeof n=="object"?n.cause:void 0)??r.cause;if(i===void 0||i===r)break;r=i}return r}var Rt={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022,ResourceNotFound:-32602,ConnectionClosed:-32e3,RequestTimeout:-32001,UrlElicitationRequired:-32042},TR={HeaderMismatch:-32001,MissingRequiredClientCapability:-32003,UnsupportedProtocolVersion:-32004},CR="/troubleshooting/error-codes",Rd={"jsonrpc/internal_error":"user_server","jsonrpc/invalid_response_format":"user_server","jsonrpc/parse_error":"ambiguous","jsonrpc/method_not_found":"ambiguous","jsonrpc/invalid_params":"ambiguous","jsonrpc/unsupported_protocol_version":"ambiguous","provider/invalid_tool_name":"ambiguous","oauth/well_known_unreachable":"ambiguous","transport/socket_hang_up":"ambiguous","transport/econnrefused":"user_config","transport/enotfound":"user_config","auth/http_401":"user_config","auth/http_403":"user_config","auth/missing_bearer":"user_config","auth/insufficient_scope":"user_config","auth/oauth_refresh_failed":"user_config","auth/consent_required":"user_config","oauth/invalid_client":"user_config","oauth/invalid_grant":"user_config","oauth/redirect_mismatch":"user_config","provider/auth_error":"user_config","provider/quota":"user_config","provider/mcpjam_limit":"user_config","provider/mcpjam_platform_budget":"user_config","account/suspended":"user_config","provider/mcpjam_limit_daily":"user_config","provider/mcpjam_limit_monthly":"user_config","provider/mcpjam_limit_insufficient":"user_config","provider/fallback_prohibited":"ambiguous","server/rate_limited":"user_server","jsonrpc/missing_required_client_capability":"user_config","jsonrpc/url_elicitation_required":"user_config","sdk/stateless_requires_http":"user_config","sdk/protocol_version_pin_unsupported":"user_config","sdk/not_yet_supported_in_stateless":"mcpjam","sdk/paginated_tool_header_discovery_unsupported":"mcpjam","provider/not_allowlisted":"mcpjam","oauth/no_bearer_challenge":"ambiguous","oauth/non_compliant_challenge":"user_server","auth/authorization_server_unreachable":"ambiguous","auth/proxy_rejected":"ambiguous","jsonrpc/connection_closed":"ambiguous","jsonrpc/request_timeout":"ambiguous","transport/etimedout":"ambiguous","transport/econnreset":"ambiguous","transport/eai_again":"ambiguous","transport/fetch_failed":"ambiguous","transport/undici":"ambiguous","jsonrpc/invalid_request":"ambiguous","jsonrpc/header_mismatch":"ambiguous","internal/unknown":"ambiguous","provider/empty_response":"ambiguous"};function fe(e,t,r,n,i,s,o="error"){return{slug:e,title:t,oneLine:r,likelyCauses:n,nextSteps:i,docsAnchor:`${CR}#${s}`,severity:o,...Rd[e]?{origin:Rd[e]}:{}}}var Fc={"jsonrpc/parse_error":fe("jsonrpc/parse_error","Parse error (-32700)","The MCP wire contained JSON the inspector could not parse as JSON-RPC.",["The server emitted invalid JSON on the response channel.","A proxy or middleware mangled the response body.","Server emitted log output on stdout instead of stderr (STDIO transport).","The inspector sent malformed JSON and the server returned a parse error."],["Check the server's stdout/stderr for unintended log output.","Use the inspector's Traffic Log to inspect the raw response."],"parse-error"),"jsonrpc/invalid_request":fe("jsonrpc/invalid_request","Invalid request (-32600)","The server rejected the payload as not a well-formed JSON-RPC request.",["Client sent a request shape the server's MCP runtime does not accept.","Outdated server SDK that disagrees with the protocol version advertised."],["Verify the negotiated MCP protocol version.","Update the server's MCP SDK."],"invalid-request"),"jsonrpc/method_not_found":fe("jsonrpc/method_not_found","Method not found (-32601)","The server does not implement the JSON-RPC method that was called.",["The server hasn't implemented the requested MCP method.","Client and server are on incompatible MCP protocol versions.","The capability you expected was not advertised in `initialize`."],["Check the server's advertised capabilities in the connection info.","Confirm the protocol version negotiated at `initialize`."],"method-not-found"),"jsonrpc/invalid_params":fe("jsonrpc/invalid_params","Invalid params (-32602)","The server rejected the request parameters.",["Required field is missing from the call.","Field type does not match the tool's input schema.","Server-side validator is stricter than the published schema."],["Re-check the tool's input schema in the Tools tab.","Compare your call payload against the schema in the inspector."],"invalid-params"),"jsonrpc/internal_error":fe("jsonrpc/internal_error","Internal error (-32603)","The server hit an unexpected error while handling the request.",["Unhandled exception inside the server's tool/resource/prompt handler.","Downstream dependency (database, API) failed during the call."],["Check the server's logs around the time of the error.","Retry the request once the server is healthy."],"internal-error"),"jsonrpc/invalid_response_format":fe("jsonrpc/invalid_response_format","Invalid response format (-32603)","The server replied, but the result was not a valid MCP tool, resource, or prompt payload.",["The handler returned a string or custom object instead of the MCP result shape (usually `{ content: [...] }`)."],["Inspect the result in the Traffic Log and compare it to the MCP result shape.",'Return `{ content: [{ type: "text", text: "..." }] }` from the handler, or the matching resource/prompt result.'],"invalid-response-format"),"jsonrpc/connection_closed":fe("jsonrpc/connection_closed","Connection closed (-32000)","The underlying transport closed before the response could be delivered.",["STDIO server process exited or crashed mid-request.","HTTP server dropped the streaming connection.","Network blip between the inspector and the server."],["Restart the server and reconnect.","Check the server logs for a crash or exit message."],"connection-closed"),"jsonrpc/request_timeout":fe("jsonrpc/request_timeout","Request timed out (-32001)","The server did not respond within the configured request timeout.",["Server is overloaded or stuck on the operation.","Long-running tool call exceeds the inspector's per-request timeout.","Network latency between client and server."],["Increase the per-server request timeout in the Servers tab.","Use MCP `tasks/*` for operations that legitimately run long."],"request-timeout"),"jsonrpc/header_mismatch":fe("jsonrpc/header_mismatch","Protocol header mismatch (-32020)","The server returned an `MCP-Protocol-Version` header that does not match what the client negotiated.",["Server is enforcing a different protocol version than the one negotiated at `initialize`.","A proxy stripped or rewrote the `MCP-Protocol-Version` header."],["Verify the server's protocol-version pinning in the connection settings.","If you set an explicit protocol version per server, ensure it matches what the server advertises."],"header-mismatch"),"jsonrpc/unsupported_protocol_version":fe("jsonrpc/unsupported_protocol_version","Unsupported protocol version (-32022)","The server does not support any protocol version this inspector offered.",["Server pinned to a newer MCP draft your inspector build does not understand.","Server pinned to a legacy version this build dropped support for."],["Update the inspector to a newer build.","Check the supported versions list in the server's `server/discover` result (modern) or `initialize` response (legacy)."],"unsupported-protocol-version"),"jsonrpc/missing_required_client_capability":fe("jsonrpc/missing_required_client_capability","Missing required client capability (-32021)","The server refused the request because the client did not advertise a capability the operation requires.",["A server-initiated input request (elicitation, sampling) needs a client capability MCPJam did not declare.","The connection advertised a capability set the server considers insufficient for this operation."],["Enable the required client capability in the connection's Client settings.","Check the server's documentation for which client capabilities it requires."],"missing-required-client-capability"),"jsonrpc/url_elicitation_required":fe("jsonrpc/url_elicitation_required","URL elicitation required (-32042)","The server needs the user to visit an external URL to complete the operation.",["Server requested a URL elicitation (OAuth, payment, confirmation).","Operation cannot proceed until the user opens the URL in a browser."],["Open the elicited URL and complete the flow.","Re-issue the request after the external step completes."],"url-elicitation-required","warning"),"transport/econnrefused":fe("transport/econnrefused","Connection refused","Nothing is listening on the host and port the server URL points at.",["Server isn't running.","Port number is wrong in the server URL.","Server is bound to a different interface (e.g. only `127.0.0.1` but you're connecting via the LAN IP)."],["Start the server.","Double-check the URL's host and port.","For Docker/containers, confirm the port is published to your host."],"econnrefused"),"transport/econnreset":fe("transport/econnreset","Connection reset","The remote side closed the TCP connection abruptly.",["Server process crashed mid-request.","Intermediate proxy or load balancer dropped the connection.","Server hit an OS-level resource limit."],["Inspect the server logs for a crash.","Retry the request."],"econnreset"),"transport/etimedout":fe("transport/etimedout","Connection timed out","The OS-level TCP connection attempt did not complete in time.",["Wrong host/port in the server URL.","Firewall is silently dropping packets.","Server is overloaded and never accepted the connection."],["Verify the URL is reachable from your machine (e.g. `curl`).","Check firewall / VPN rules."],"etimedout"),"transport/enotfound":fe("transport/enotfound","Host not found","DNS lookup failed for the server's hostname.",["Hostname is misspelled in the URL.","DNS resolver is misconfigured.","You're offline."],["Confirm the hostname in the URL is correct.","Try resolving the host with `nslookup` or `dig`."],"enotfound"),"transport/eai_again":fe("transport/eai_again","Temporary DNS failure","DNS resolution failed with a transient error.",["Local DNS resolver is overloaded or restarting.","Upstream DNS server is briefly unavailable."],["Wait a few seconds and retry.","Switch to a different DNS resolver if this persists."],"eai-again","warning"),"transport/undici":fe("transport/undici","HTTP transport error","The underlying HTTP client (undici / fetch) reported a low-level transport failure.",["Server closed the connection mid-response.","TLS handshake failed.","Socket-level error during streaming."],["Inspect the Traffic Log for the failed request.","Verify the server's TLS certificate is valid."],"undici-transport-error"),"transport/fetch_failed":fe("transport/fetch_failed","Fetch failed","The HTTP request never produced a response.",["Server is unreachable (offline, wrong URL, blocked by firewall).","TLS handshake failed (self-signed cert, expired cert).","Mixed-content block (HTTPS page calling HTTP endpoint in browser)."],["Open the URL in a browser to confirm it loads.","If self-signed, install the certificate or switch to a trusted one."],"fetch-failed"),"transport/socket_hang_up":fe("transport/socket_hang_up","Socket hang up","The server closed the connection without sending a response.",["Server crashed or restarted during the request.","Reverse proxy timed the request out."],["Retry the request.","Check server-side logs for the crash."],"socket-hang-up"),"auth/http_401":fe("auth/http_401","Unauthorized (401)","The server requires authentication that wasn't provided or is no longer valid.",["Missing or expired bearer token.","OAuth access token expired and refresh failed.","Server changed its required authentication scheme."],["Re-authenticate using the Reconnect button on the server card.","If using OAuth, run through the OAuth flow again from Servers."],"unauthorized-401"),"auth/http_403":fe("auth/http_403","Forbidden (403)","You authenticated successfully but lack permission for the operation.",["OAuth scopes granted don't cover the requested operation.","Server-side ACL blocks this account."],["Re-run OAuth and request the additional scopes if the server allows.","Ask the server admin to grant the necessary permissions."],"forbidden-403"),"auth/oauth_refresh_failed":fe("auth/oauth_refresh_failed","OAuth token refresh failed","An expired OAuth access token could not be refreshed.",["Refresh token was revoked.","Refresh token expired.","Server returned `invalid_grant` to the refresh attempt."],["Click Reconnect on the server card to run a fresh OAuth flow."],"oauth-refresh-failed"),"auth/consent_required":fe("auth/consent_required","Sign-in required","This server needs your permission before it can connect.",["Reconnect ran without opening the sign-in prompt, so no OAuth token exists for this server yet."],["Click Reconnect and approve the request in the window that opens."],"consent-required","warning"),"auth/missing_bearer":fe("auth/missing_bearer","Missing bearer token","The API call did not include the required `Authorization: Bearer ...` header.",["Inspector session expired.","Sign-in token failed to attach to the request."],["Refresh the page and sign in again."],"missing-bearer"),"auth/insufficient_scope":fe("auth/insufficient_scope","Insufficient scope (403)","The server reported insufficient_scope: the grant does not cover this operation.",["The authorization did not request the scopes the server now requires.","The server added a scope requirement after the grant was issued."],["Re-authorize and grant the scopes the server names in its challenge."],"insufficient-scope"),"auth/authorization_server_unreachable":fe("auth/authorization_server_unreachable","Authorization server unreachable","The stored token could not be refreshed because the authorization server was unreachable or did not return a usable response.",["The authorization server is down or slow.","The refresh request could not leave the network it was made from."],["Retry in a minute; if it persists, check the authorization server's status.","Reconnect the server to obtain a fresh token once the authorization server is reachable."],"authorization-server-unreachable","warning"),"auth/proxy_rejected":fe("auth/proxy_rejected","HTML access rejection (403)","The response was HTTP 403 with an HTML content type and no authentication challenge; a proxy or firewall may be involved.",["An IP allowlist or WAF blocks the address the request came from.","A corporate proxy or SSO portal intercepted the request."],["Allow MCPJam's egress addresses, or the address you connect from, on the server's firewall.","Open the server URL in a browser from the same network to see what answers."],"proxy-rejected"),"oauth/no_bearer_challenge":fe("oauth/no_bearer_challenge","401 without a Bearer challenge","The response was HTTP 401 without a Bearer challenge. This response did not explain how to authorize.",["The server or an intermediary omitted a Bearer challenge.","The server expects a static API key and does not implement OAuth."],["Check OAuth discovery, including the well-known metadata fallback supported by newer MCP versions.","If the server expects an API key, configure it as a header on the server instead of OAuth."],"no-bearer-challenge"),"oauth/non_compliant_challenge":fe("oauth/non_compliant_challenge","Bearer challenge on the wrong status","The response reported invalid_token with HTTP 403; MCP requires HTTP 401 for an invalid or expired token.",["The server maps every authorization failure to 403.","A gateway rewrites the server's 401 to 403."],["Re-authorize the server to replace the rejected token.","Report the status mismatch to the server author; invalid-token recovery expects HTTP 401."],"non-compliant-challenge","warning"),"oauth/invalid_grant":fe("oauth/invalid_grant","OAuth: invalid grant","The OAuth server rejected the authorization code or refresh token.",["Authorization code was already redeemed.","Refresh token was revoked.","Authorization code expired (typical lifetime ~60s)."],["Start the OAuth flow again from the server card."],"oauth-invalid-grant"),"oauth/invalid_client":fe("oauth/invalid_client","OAuth: invalid client","The OAuth server does not recognize the client credentials.",["Client was deleted on the authorization server.","Dynamic registration cache is stale.","`client_id` was rotated server-side."],["Re-register the client (Reconnect from the server card triggers DCR if supported)."],"oauth-invalid-client"),"oauth/redirect_mismatch":fe("oauth/redirect_mismatch","OAuth: redirect URI mismatch","The redirect URI in the request does not match the one registered with the OAuth server.",["Authorization server requires the inspector's callback URL to be registered explicitly.","Server's allow-list is wrong."],["Add the inspector's callback URL to the OAuth server's allowed redirects.","Verify the inspector's base URL hasn't changed."],"oauth-redirect-mismatch"),"oauth/well_known_unreachable":fe("oauth/well_known_unreachable","OAuth metadata unreachable","The OAuth `.well-known` discovery endpoint could not be fetched.",["Authorization server is down.","Wrong issuer URL.","CORS blocks the discovery request from the browser."],["Confirm the issuer URL in the server config.","Open the `.well-known/openid-configuration` (or `oauth-authorization-server`) URL in a browser."],"oauth-well-known-unreachable"),"sdk/not_yet_supported_in_stateless":fe("sdk/not_yet_supported_in_stateless","Operation not supported on stateless transport","The inspector's stateless HTTP transport does not yet implement this MCP operation.",["Operation requires a server-initiated channel (subscriptions, MRTR) the stateless preview transport hasn't wired up yet."],["Switch the server to the legacy stateful transport in its protocol-mode toggle."],"not-yet-supported-in-stateless","warning"),"sdk/stateless_requires_http":fe("sdk/stateless_requires_http","Stateless transport requires HTTP","Stateless mode can only be used with an HTTP-transport server, not STDIO.",["You enabled the stateless protocol toggle on a stdio server."],["Disable the stateless toggle for stdio servers."],"stateless-requires-http"),"sdk/protocol_version_pin_unsupported":fe("sdk/protocol_version_pin_unsupported","Server doesn't support the pinned protocol version","This connection is pinned to one MCP protocol version, and the server does not offer it.",["The client profile you're emulating pins a protocol version this server hasn't adopted — a host set to the latest revision against a server that still speaks a 2025 one.","A per-server protocol override left pinned to a version the server dropped or never shipped."],["Set the protocol version to Automatic to negotiate whatever the server does support.","Or pick the version the server advertises — `server/discover` (modern) or the `initialize` response (legacy) lists them."],"protocol-version-pin-unsupported"),"sdk/paginated_tool_header_discovery_unsupported":fe("sdk/paginated_tool_header_discovery_unsupported","Paginated tool discovery not supported with header overrides","Paginated tools discovery cannot run alongside per-request header overrides on this transport.",["Conflicting combination of progressive tool discovery + per-server header overrides."],["Disable progressive tool discovery for this server, or move headers into the server config."],"paginated-tool-and-header-discovery-unsupported","warning"),"provider/invalid_tool_name":fe("provider/invalid_tool_name","Provider rejected the tool name","An LLM provider rejected a tool name (Anthropic's strict tool-name validator is the most common source).",["Tool name contains characters or length the provider does not allow.","Two attached servers expose tools whose namespaced names collide after sanitization."],["Rename the offending tool on the server.","Detach one of the colliding servers from the chat surface."],"provider-invalid-tool-name"),"provider/auth_error":fe("provider/auth_error","Provider authentication error","Your LLM provider rejected the API key for this request.",["Key is missing.","Key is invalid or revoked.","Key is for a different environment (project, region)."],["Add or update your API key under Settings → LLM Providers.","Verify the key in the provider's dashboard."],"provider-auth-error"),"provider/not_allowlisted":fe("provider/not_allowlisted","Model provider not enabled on MCPJam","This model's provider is not enabled on MCPJam's hosted AI gateway, so MCPJam can't run it. Retrying or changing your API key won't help.",["MCPJam's hosted gateway does not have this model's provider on its provider allowlist."],["Choose a model from a different provider.","Add your own key for this provider under Settings → LLM Providers (BYOK) to run the model on your key instead of MCPJam's gateway."],"provider-not-allowlisted","warning"),"provider/mcpjam_limit_daily":fe("provider/mcpjam_limit_daily","Out of MCPJam credits","Your organization's daily MCPJam credits are used up. They reset tomorrow.",["Chat, evals and swarm generation all draw on one daily bucket, shared across the organization."],["On Free, upgrade for a larger monthly allowance and access to top-ups. On eligible paid plans, buy shared credits to continue testing.","Wait for the daily allowance to reset.","Your own API key covers supported model inference. MCPJam features can still require credits; Swarm generation and persona turns always do."],"out-of-mcpjam-credits","warning"),"provider/mcpjam_limit_monthly":fe("provider/mcpjam_limit_monthly","Out of MCPJam credits","Your organization's available MCPJam credits are used up for this billing period.",["Paid plans include a monthly credit allowance shared across the organization. It renews with the billing period."],["On Free, upgrade for a larger monthly allowance and access to top-ups. On eligible paid plans, buy shared credits to continue testing.","Wait for the billing period to renew.","Your own API key covers supported model inference. MCPJam features can still require credits; Swarm generation and persona turns always do."],"out-of-mcpjam-credits","warning"),"provider/mcpjam_limit_insufficient":fe("provider/mcpjam_limit_insufficient","Not enough MCPJam credits","Your organization has MCPJam credits left, but not enough for this request.",["MCPJam reserves a request's worst-case cost before it runs, so an expensive model or a long conversation can need more than the remaining balance."],["Try a cheaper model or a shorter conversation.","On Free, upgrade for a larger monthly allowance and access to top-ups. On eligible paid plans, buy shared credits to continue testing.","Your own API key covers supported model inference. MCPJam features can still require credits; Swarm generation and persona turns always do."],"out-of-mcpjam-credits","warning"),"provider/fallback_prohibited":fe("provider/fallback_prohibited","Provider failed, fallback not permitted","The model's provider failed and this model selection does not allow a fallback provider, so the request stopped rather than running somewhere other than where it was asked to.",[`The provider serving this model returned an error or was unreachable, and the selection's fallback policy is "none" — the default for evals, swarms and judges, so a result never silently comes from a different provider.`],["Retry — the provider's failure may be temporary.","Pick a different model, or a model on a connection you control."],"provider-failed-fallback-not-permitted","warning"),"provider/mcpjam_platform_budget":fe("provider/mcpjam_platform_budget","MCPJam shared free allowance unavailable","The shared free allowance is exhausted or temporarily paused.",["This limit applies across free usage, not just your account."],["Wait until the supplied reset time, if present.","Use purchased credits or your own provider key for chat."],"mcpjam-platform-budget","warning"),"account/suspended":fe("account/suspended","Account suspended","This account has been suspended by MCPJam.",["Support has suspended this account."],["Contact founders@mcpjam.com for support."],"account-suspended","warning"),"provider/mcpjam_limit":fe("provider/mcpjam_limit","Out of MCPJam credits","Your organization is out of MCPJam credits, so this request could not continue.",["Chat, evals and swarm generation all draw on the same MCPJam allowance."],["On Free, upgrade for a larger monthly allowance and access to top-ups. On eligible paid plans, buy shared credits to continue testing.","Wait for the allowance to reset.","Your own API key covers supported model inference. MCPJam features can still require credits; Swarm generation and persona turns always do."],"out-of-mcpjam-credits","warning"),"provider/quota":fe("provider/quota","Provider quota / rate limit","Your LLM provider rejected the request because you hit a rate limit or quota.",["Daily/monthly quota exhausted.","Per-minute rate limit exceeded.","Free tier limits hit."],["Wait for the limit window to reset.","Upgrade your provider plan.","Switch to a different provider in Settings."],"provider-quota","warning"),"server/rate_limited":fe("server/rate_limited","MCP server rate limit","The MCP server rejected the request with HTTP 429 (too many requests).",["The server enforces its own per-client rate limit.","An upstream API the server calls is throttling it.","A burst of tool calls exceeded what the server allows."],["Wait for the server's limit window to reset, then retry.","Reduce concurrency or the number of tool calls in the run.","Check the server's own rate-limit documentation or logs."],"server-rate-limited","warning"),"provider/empty_response":fe("provider/empty_response","Model returned no response","The model returned no response, so the turn could not complete.",["The model request ended without usable content."],["Rerun the affected cases. If this recurs, report it with the run details."],"model-empty-response"),"internal/unknown":fe("internal/unknown","Unknown error","An error occurred that the inspector could not classify.",["Unhandled error path.","New error class the inspector hasn't been taught about yet."],["Open the details panel and copy the raw message.","File an issue with the raw message so we can add it to the catalog."],"unknown-error")};function zv(e,t=0){if(!e||typeof e!="object"||t>3)return;const r=e.code,n=typeof r=="string"?r:void 0;if(n!==void 0&&$R(n))return n;const i=e.cause;if(i!==void 0&&i!==e){const s=zv(i,t+1);if(s!==void 0)return s}return n}function $R(e){return PR.has(e)||e.startsWith("UND_ERR_")}var PR=new Set(["ECONNREFUSED","ECONNRESET","EAI_AGAIN","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET"]);function OR(e){return!!e&&typeof e=="object"&&typeof e.slug=="string"&&typeof e.title=="string"&&typeof e.oneLine=="string"&&typeof e.docsAnchor=="string"&&typeof e.severity=="string"&&typeof e.rawMessage=="string"&&Array.isArray(e.likelyCauses)&&Array.isArray(e.nextSteps)}function Zn(e){const t=yR(e);return typeof t=="string"?t:String(e)}function xR(e){if(!e||typeof e!="object")return;const t=e.name;return typeof t=="string"?t:void 0}function ru(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function Uv(e){if(!e||typeof e!="object")return;const t=e.code;if(typeof t=="number"&&Number.isFinite(t))return t;const r=e.error;if(r&&typeof r=="object"){const n=r.code;if(typeof n=="number"&&Number.isFinite(n))return n}}function MR(e){if(!e||typeof e!="object")return;const t=e.code;return typeof t=="string"?t:void 0}function LR(e){if(!e||typeof e!="object")return;const t=e.statusCode;if(typeof t=="number")return t;const r=e.status;if(typeof r=="number")return r}function Fv(e){return Fc[e]??Fc["internal/unknown"]}var DR=200;function qc(e){const t=e.replace(/\s+/g," ").trim();return t.length<=DR?t:`${t.slice(0,199).trimEnd()}…`}function qv(e,t,r){if(t==="provider/mcpjam_limit_insufficient"){const n=iu(r);return n?{...e,oneLine:n}:e}return t!=="internal/unknown"||!r?e:{...e,oneLine:qc(r)}}var NR=["Backend step returned no content (stream error or empty response)","Backend step returned no messages (stream error or empty response)"];function zR(e){if(/NotYetSupportedInStateless/i.test(e))return"sdk/not_yet_supported_in_stateless";if(/StatelessRequiresHttpTransport/i.test(e))return"sdk/stateless_requires_http";if(/PaginatedToolHeaderDiscoveryUnsupported/i.test(e))return"sdk/paginated_tool_header_discovery_unsupported";if(/which this client is pinned to/i.test(e))return"sdk/protocol_version_pin_unsupported"}var UR={[Rt.ParseError]:"jsonrpc/parse_error",[Rt.InvalidRequest]:"jsonrpc/invalid_request",[Rt.MethodNotFound]:"jsonrpc/method_not_found",[Rt.InvalidParams]:"jsonrpc/invalid_params",[Rt.InternalError]:"jsonrpc/internal_error",[Rt.ConnectionClosed]:"jsonrpc/connection_closed",[Rt.HeaderMismatch]:"jsonrpc/header_mismatch",[Rt.MissingRequiredClientCapability]:"jsonrpc/missing_required_client_capability",[Rt.UnsupportedProtocolVersion]:"jsonrpc/unsupported_protocol_version",[TR.UnsupportedProtocolVersion]:"jsonrpc/unsupported_protocol_version",[Rt.UrlElicitationRequired]:"jsonrpc/url_elicitation_required"};function FR(e){return/header[^a-z]*mismatch/i.test(e)||/MCP-Protocol-Version/i.test(e)?"jsonrpc/header_mismatch":"jsonrpc/request_timeout"}var qR=/^(?:MCP error -32603:\s*)?invalid response format$/i;function jv(e){return qR.test(e.trim())}function jR(e){return jv(e)?"jsonrpc/invalid_response_format":"jsonrpc/internal_error"}function Hv(e){const t=e.toUpperCase();switch(t){case"ECONNREFUSED":return"transport/econnrefused";case"ECONNRESET":return"transport/econnreset";case"ETIMEDOUT":return"transport/etimedout";case"ENOTFOUND":return"transport/enotfound";case"EAI_AGAIN":return"transport/eai_again";default:return t.startsWith("UND_ERR_")?"transport/undici":void 0}}function HR(e){const t=e.toLowerCase();if(/\bsocket\s+hang\s+up\b/i.test(e))return"transport/socket_hang_up";for(const r of e.matchAll(/\b(E[A-Z]{2,}(?:_[A-Z]+)*|UND_ERR_[A-Z_]+)\b/g)){const n=Hv(r[1]);if(n)return n}if(/\bfetch\s+failed\b/i.test(e))return"transport/fetch_failed";if(/\bgetaddrinfo\b/i.test(e))return"transport/enotfound";if(/\bconnection\s+(?:refused|reset|closed|timed?\s*out|aborted|error|failed)\b/i.test(e)||/\b(?:failed|unable)\s+to\s+connect\b/i.test(e))return t.includes("refused")?"transport/econnrefused":t.includes("reset")?"transport/econnreset":t.includes("timed out")||t.includes("timeout")?"transport/etimedout":t.includes("closed")?"jsonrpc/connection_closed":"transport/fetch_failed";if(/Invalid tool name/i.test(e))return"provider/invalid_tool_name";if(jv(e))return"jsonrpc/invalid_response_format"}function VR(e){const t=GR(e);if(!t)return;const r=BR(e)??(typeof t.error=="string"?t.error:typeof t.error_code=="string"?t.error_code:void 0);if(r)switch(r.toLowerCase()){case"invalid_grant":return"oauth/invalid_grant";case"invalid_client":return"oauth/invalid_client";case"invalid_redirect_uri":case"redirect_uri_mismatch":return"oauth/redirect_mismatch";default:return}}function BR(e){if(!e||typeof e!="object"||e.name!=="OAuthResponseError")return;const t=e.code;return typeof t=="string"&&t?t:void 0}function GR(e){if(!e||typeof e!="object")return;const t="body"in e?e.body:"data"in e?e.data:e;if(!(!t||typeof t!="object"))return t}function Vv(e){if(!(e instanceof Error))return;const t=e.cause;if(!t||typeof t!="object")return;const r=typeof t.name=="string"?t.name:"Error",n=typeof t.message=="string"?Zn(t.message):"";if(n)return{name:r,message:n}}var Ad={AUTH_ERROR:"auth/http_401",OAUTH_REQUIRED:"auth/http_401"};function WR(e){const t=xR(e);if(t==="MCPAuthError"||t==="UnauthorizedError")return"auth/http_401";const r=MR(e);if(r&&Ad[r])return Ad[r]}function Id(e){if(e===401)return"auth/http_401";if(e===403)return"auth/http_403";if(e===429)return"provider/quota"}function ZR(e){if(/(?:^|[^\w.:])401\b/.test(e))return"auth/http_401";if(/(?:^|[^\w.:])403\b/.test(e))return"auth/http_403";if(/(?:^|[^\w.:])429\b|too many requests/i.test(e))return"provider/quota"}function JR(e){const t=ru(e),r=e&&typeof e=="object"?e:null,n=r?.data?.code??r?.code;if(n==="platform_free_budget_exhausted")return{slug:"provider/mcpjam_platform_budget",rawCode:n};if(n==="account_suspended")return{slug:"account/suspended",rawCode:n};if(NR.some(p=>t.startsWith(p)))return{slug:"provider/empty_response"};const i=zR(t);if(i)return{slug:i};const s=WR(e);if(s)return{slug:s};const o=Uv(e);if(o!==void 0){if(o===-32001)return{slug:FR(t),rawCode:o};if(o===Rt.InternalError)return{slug:jR(t),rawCode:o};const p=UR[o];if(p)return{slug:p,rawCode:o};const f=Id(o);if(f)return{slug:f,rawCode:o}}const a=zv(e);if(a){const p=Hv(a);if(p)return{slug:p,rawCode:a}}if(/missing\s+(?:or\s+invalid\s+)?bearer/i.test(t)||/bearer\s+token\s+(?:is\s+)?required/i.test(t))return{slug:"auth/missing_bearer"};if(iu(t))return{slug:"provider/mcpjam_limit_insufficient"};if(/\bout of MCPJam credits\b/i.test(t))return{slug:"provider/mcpjam_limit"};const c=sA(t);if(c)return{slug:c};const l=nu(e);if(l!==void 0){const p=Id(l);if(p)return{slug:p,rawCode:l}}const u=VR(e);if(u)return{slug:u};const h=ZR(t);if(h)return{slug:h};if(/refresh\s+token/i.test(t)&&/(failed|invalid|expired|revoked)/i.test(t))return{slug:"auth/oauth_refresh_failed"};if(/consent\s+is\s+required/i.test(t)||/^\s*reauthenticate\b[\s\S]*\bto\s+continue\b/i.test(t))return{slug:"auth/consent_required"};const d=HR(t);return d?{slug:d}:/well[-_]?known/i.test(t)&&/(unreachable|fail|404)/i.test(t)?{slug:"oauth/well_known_unreachable"}:{slug:"internal/unknown"}}var KR=new Set(["auth/http_401","auth/http_403","auth/missing_bearer","auth/oauth_refresh_failed","auth/authorization_server_unreachable","oauth/invalid_client","oauth/invalid_grant","provider/auth_error","provider/quota"]);function nu(e){const t=new Set;let r=e;for(let n=0;n<5&&r&&typeof r=="object"&&!t.has(r);n++){t.add(r);const i=LR(r);if(i!==void 0)return i;const s=Uv(r);if(s!==void 0&&s>=100&&s<=599)return s;if(r.name==="UnauthorizedError")return 401;const o=IR(r);r=o!==r?o:r.cause}}function YR(e,t){if(!t)return;if(t.refresh?.outcome==="authorization_server_unreachable")return"auth/authorization_server_unreachable";if(t.refresh?.outcome==="token_rejected")return"auth/oauth_refresh_failed";const r=t.challenge;if(!r)return;const n=nu(e);if(n===401&&r.scheme!=="bearer")return"oauth/no_bearer_challenge";if(n===401)return"auth/http_401";if(n===403)return r.scheme==="bearer"&&r.error==="insufficient_scope"?"auth/insufficient_scope":r.scheme==="bearer"&&r.error==="invalid_token"?"oauth/non_compliant_challenge":r.scheme==="none"&&r.bodyKind==="html"?"auth/proxy_rejected":"auth/http_403"}function XR(e,t,r){if(t==="auth/insufficient_scope"&&r?.challenge?.scopes?.length)return{...e,oneLine:qc(Zn(`${e.oneLine} Required scopes: ${r.challenge.scopes.join(" ")}.`))};const n=r?.challenge?.error;return!n||t!=="auth/http_401"&&t!=="auth/http_403"?e:{...e,oneLine:qc(Zn(`${e.oneLine} The server reported \`${n}\`.`))}}var QR=new Set(["user_server","user_config","mcpjam","ambiguous"]);function eA(e){return typeof e=="string"&&QR.has(e)}function tA(e){const t=e?.origin;return eA(t)?t:"ambiguous"}function Bv(e,t,r){return r?.credentialOwner==="mcpjam"&&KR.has(t)?{...e,origin:"mcpjam"}:e}function rA(e,t){return e==="provider/quota"&&t?.surface==="mcpServer"?"server/rate_limited":e}function nA(e,t){try{const r=Zn(ru(e)),n=YR(e,t),i=n?{slug:n}:JR(e),s=rA(i.slug,t),o=i.rawCode??(n?nu(e):void 0),a=Bv(XR(qv(Fv(s),s,r),s,t),s,t),c=Vv(e);return{...a,rawMessage:r,...o!==void 0?{rawCode:o}:{},...c?{cause:c}:{}}}catch{return Gv(e,"Unknown")}}function hL(e,t,r){try{const n=Bv(Fv(e),e,r),i=t!==void 0?Zn(ru(t)):"",s=Vv(t);return{...n,rawMessage:i,...s?{cause:s}:{}}}catch{return Gv(t,"")}}function Gv(e,t){const r=Fc["internal/unknown"];let n=t;try{n=Zn(e instanceof Error?e.message:String(e??t))}catch{n=t}return{...qv(r,"internal/unknown",n),rawMessage:n}}var iA=/\bThis request needs about (\d+) MCPJam credits; your organization has (\d+) left[^.]{0,40}\./i;function iu(e){const t=iA.exec(e);if(!t)return;const r=Number(t[1]),n=Number(t[2]);return Number.isSafeInteger(r)&&Number.isSafeInteger(n)&&n>0&&r>n?t[0]:void 0}function sA(e){if(iu(e))return"provider/mcpjam_limit_insufficient";const t=/\b(daily|monthly)\s+mcpjam[\w\s-]{0,40}model limit/i.exec(e);if(t)return t[1].toLowerCase()==="monthly"?"provider/mcpjam_limit_monthly":"provider/mcpjam_limit_daily";if(/mcpjam[\w\s-]{0,40}model limit/i.test(e))return"provider/mcpjam_limit"}var jc="[A-Za-z0-9!#$%&'*+.^_`|~-]+";function oA(e){const t={},r=new RegExp(`(${jc})\\s*=\\s*(?:"((?:\\\\.|[^"\\\\])*)"|([^,\\s]+))`,"g");for(let n=r.exec(e);n;n=r.exec(e)){const i=n[2];t[n[1].toLowerCase()]=i!==void 0?i.replace(/\\([\s\S])/g,"$1"):n[3]??""}return t}function cr(e){return Wv(e)[0]??{}}function su(e){if(!e)return;const t=e.split(/\s+/).map(r=>r.trim()).filter(Boolean);return t.length>0?Array.from(new Set(t)):void 0}function aA(e,t){const r=[],n=new Set;for(const i of[...e??[],...t??[]]){const s=i?.trim();!s||n.has(s)||(n.add(s),r.push(s))}return r}function Wv(e){if(!e)return[];const t=[];let r="",n=!1;for(let a=0;a<e.length;a++){const c=e[a];n&&c==="\\"&&a+1<e.length?(r+=c+e[a+1],a++):c==='"'?(n=!n,r+=c):c===","&&!n?(t.push(r),r=""):r+=c}t.push(r);const i=[],s=new RegExp(`^(${jc})\\s+(?!\\s*=)(.+)$`,"s"),o=new RegExp(`^(${jc})$`);for(const a of t){const c=a.trim();if(!c)continue;const l=s.exec(c),u=l?null:o.exec(c);l?i.push({scheme:l[1].toLowerCase(),params:[l[2]]}):u?i.push({scheme:u[1].toLowerCase(),params:[]}):i.length>0&&i[i.length-1].params.push(c)}return i.filter(a=>a.scheme==="bearer").map(a=>oA(a.params.join(", ")))}function cA(e){return Wv(e).length>0}var xr=class extends Error{status;constructor(e,t){super(e),this.name="UnexpectedProbeStatusError",this.status=t}},Zv="MCP server returned HTTP ";function pL(e){return e.startsWith(Zv)}function ls(e){if(e.status===401)return{kind:"challenged",specCompliant:!0};if(e.status===200)return{kind:"anonymous_allowed"};if(e.status===403&&cA(e.wwwAuthenticateHeader))return{kind:"challenged",specCompliant:!1};const t=e.serverMessage||e.statusText,r=`${Zv}${e.status}${t?` ${t}`:""}`;return e.status===403?e.wwwAuthenticateHeader?.trim()?{kind:"unexpected",message:`${r}, and its WWW-Authenticate header offers no Bearer challenge. MCP OAuth has nothing to discover from without one, so the flow cannot continue against this server.`}:{kind:"unexpected",message:`${r} with no WWW-Authenticate challenge. MCP requires 401 with a WWW-Authenticate header to begin OAuth, so there is nothing to discover from. A bare 403 usually means a proxy, WAF, or IP allowlist rejected the request before the MCP server saw it.`}:{kind:"unexpected",message:`${r} where MCP requires 401 Unauthorized (or 200, if the server allows anonymous access).`}}function fL(e){return e.step!=="request_without_token"||e.status===void 0?!1:ls({status:e.status,statusText:e.statusText,wwwAuthenticateHeader:e.wwwAuthenticateHeader}).kind==="challenged"}function vL(e){const t=Number.isInteger(e.maxRetries)&&e.maxRetries>=0?e.maxRetries:1;switch(e.authMode){case"m2m":return"throw";case"debugger":return"manual";case"interactive":return e.attempt<t?"reauthorize":"throw"}}function lA(e){const t=e.customScopes?.trim();if(t)return t;const r=e.challengedScopes?.filter(Boolean)??[];if(r.length>0)return Array.from(new Set(r)).join(" ");const n=e.supportedScopes?.filter(Boolean)??[];if(n.length!==0)return Array.from(new Set(n)).join(" ")}var uA;uA=globalThis.crypto;var dA="Resource server does not implement OAuth 2.0 Protected Resource Metadata.",Td="No response while loading OAuth protected resource metadata.",hA="Failed to request resource metadata";function Zo(e){const t=e instanceof Error?e.message:String(e);return`${hA}: ${t}`}function gL(e){return e==="Resource server does not implement OAuth 2.0 Protected Resource Metadata."||e===Zo(new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata."))}function pA(e){try{const t=new URL(e);return t.protocol=t.protocol.toLowerCase(),t.hostname=t.hostname.toLowerCase(),t.hash="",t.pathname!=="/"&&t.pathname.endsWith("/")&&(t.pathname=t.pathname.slice(0,-1)),t.toString()}catch{return e}}function fA(e,t){if(e.origin!==t.origin||t.pathname.length<e.pathname.length)return!1;const r=t.pathname.endsWith("/")?t.pathname:`${t.pathname}/`,n=e.pathname.endsWith("/")?e.pathname:`${e.pathname}/`;return r.startsWith(n)}function vA(e,t,r){const n=c=>({value:e,source:t,status:"invalid",strictClientCompatible:!1,rfc9728Compliant:!1,rfc9728Reason:c,reason:c});let i;try{i=new URL(e)}catch{return n(`Resource indicator "${e}" is not a parseable URI.`)}if(i.hash)return n(`Resource indicator "${e}" must not include a fragment (RFC 8707 §2).`);if(i.protocol!=="https:"&&i.protocol!=="http:")return n(`Resource indicator "${e}" must be an https URL (RFC 9728 §2).`);let s;try{s=new URL(r)}catch{return n(`Server URL "${r}" is not a parseable URI.`)}if(i.origin!==s.origin){const c=`Resource indicator "${e}" is on a different origin than the server URL "${r}" — honoring it would let the server steer tokens to an audience it doesn't own.`;return{value:e,source:t,status:"incompatible",strictClientCompatible:!1,rfc9728Compliant:!1,rfc9728Reason:c,reason:c}}const o=fA(i,s),a=i.protocol!=="https:"?`Resource indicator "${e}" must use the https scheme to comply with RFC 9728.`:o?void 0:`Resource indicator "${e}" does not satisfy the protected-resource binding for server URL "${r}" required for RFC 9728 conformance.`;return{value:e,source:t,status:"valid",strictClientCompatible:o,rfc9728Compliant:a===void 0,...a?{rfc9728Reason:a}:{},...o?{}:{reason:`Resource indicator "${e}" is not a path prefix of the server URL "${r}"; clients that enforce the official MCP SDK's strict binding will refuse it.`}}}function gA(e){return e.resolved?e.resolved.value:e.serverUrl===void 0?e.prmResource:Hc({serverUrl:e.serverUrl,prmResource:e.prmResource}).value}function Hc(e){const t=[[e.prmResource,"prm"],[e.authorizationUrlResource,"authorization"],[e.configuredResource,"configured"]];for(const[n,i]of t){const s=n?.trim();if(s)return vA(s,i,e.serverUrl)}try{new URL(e.serverUrl)}catch{return{value:e.serverUrl,source:"server",status:"invalid",strictClientCompatible:!1,rfc9728Compliant:!1,rfc9728Reason:`Server URL "${e.serverUrl}" is not a parseable URI.`,reason:`Server URL "${e.serverUrl}" is not a parseable URI.`}}const r=new URL(e.serverUrl).protocol==="https:"?void 0:`Resource indicator "${e.serverUrl}" must use the https scheme to comply with RFC 9728.`;return{value:pA(e.serverUrl),source:"server",status:"valid",strictClientCompatible:!0,rfc9728Compliant:r===void 0,...r?{rfc9728Reason:r}:{}}}var Jv="2025-11-25";async function Kv(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(!(n instanceof TypeError))throw n;if(!t)return;try{return await r(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}}}function mA(e,t="",r={}){const n=t.endsWith("/")?t.slice(0,-1):t;return r.prependPathname?`${n}/.well-known/${e}`:`/.well-known/${e}${n}`}async function Cd(e,t,r=fetch){return Kv(e,{"MCP-Protocol-Version":t,Accept:"application/json"},r)}function _A(e,t){return e?t==="/"?!1:e.status>=400&&e.status<500||e.status===502:!0}async function yA(e,t,r,n){const i=new URL(e),s=n?.protocolVersion??Jv;let o;if(n?.metadataUrl)o=new URL(n.metadataUrl);else{const l=mA(t,i.pathname);o=new URL(l,n?.metadataServerUrl??i),o.search=i.search}let a=await Cd(o,s,r),c=!a;return!n?.metadataUrl&&_A(a,i.pathname)&&(a=await Cd(new URL(`/.well-known/${t}`,i),s,r),c||=!a),{response:a,sawNoResponse:c}}function bA(e){const t=typeof e=="string"?new URL(e):e;if(t.pathname==="/")return[{url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}];const r=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;return[{url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"},{url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}]}async function Jo(e,t,r=fetch){const{response:n,sawNoResponse:i}=await yA(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n)throw new Error(Td);if(n.status===404)throw await n.text().catch(()=>{}),new Error(i?Td:dA);if(!n.ok)throw await n.text().catch(()=>{}),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return await n.json()}async function wA(e,{fetchFn:t=fetch,protocolVersion:r=Jv}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"};for(const{url:i,type:s}of bA(e)){const o=await Kv(i,n,t);if(o){if(!o.ok){if(await o.text().catch(()=>{}),o.status>=400&&o.status<500||o.status===502)continue;throw new Error(`HTTP ${o.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return await o.json()}}}async function mL(e,t){let r,n;try{r=await Jo(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers?.length&&(n=r.authorization_servers[0])}catch(s){if(s instanceof TypeError)throw s}n||(n=String(new URL("/",e)));const i=await wA(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:String(n),authorizationServerMetadata:i,resourceMetadata:r}}function SA(e){const t=e?.token_endpoint_auth_methods_supported;if(!Array.isArray(t)||t.length===0)return["client_secret_basic"];const r=t.filter(n=>typeof n=="string");return r.length>0?r:["client_secret_basic"]}function Ko(e){const t=SA(e.authorizationServerMetadata);return e.hasClientSecret?t.includes("client_secret_basic")?{ok:!0,method:"client_secret_basic",supportedMethods:t}:t.includes("client_secret_post")?{ok:!0,method:"client_secret_post",supportedMethods:t}:t.includes("none")?{ok:!0,method:"none",supportedMethods:t}:{ok:!1,message:`Unsupported OAuth client authentication method: ${t.join(", ")||"none advertised"}.`,supportedMethods:t}:{ok:!0,method:"none",supportedMethods:t}}function $d(e){return new URLSearchParams([["v",e]]).toString().slice(2)}function Mr(e){const{clientId:t,clientSecret:r,tokenEndpointAuthMethod:n}=e;if(r&&n==="client_secret_basic")return{headers:{Authorization:`Basic ${btoa(`${$d(t??"")}:${$d(r)}`)}`},bodyParams:{}};const i={};return t&&(i.client_id=t),r&&n!=="none"&&(i.client_secret=r),{headers:{},bodyParams:i}}function Yo(e){const t=e.token_endpoint_auth_method;if(!(e.client_secret&&(!t||t==="none")))return t||"none"}var Pd=300,ou="Authenticated request failed",Yv="Token request failed",EA=[Yv,ou];function _L(e){return e.startsWith(`${ou}: `)}function Kt(e){if(typeof e!="string")return;const t=e.trim();return t||void 0}function Vc(e){return e.replace(/\s+/g," ").trim()}function Xv(e){if(typeof e=="string")return Kt(e);if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,r=Kt(t.error_type),n=Kt(t.error_description),i=Kt(t.error_message)??n??Kt(t.message),s=Kt(t.error);if(r&&i)return Kt(`${r}: ${i}`);if(s&&n)return Kt(`${s}: ${n}`);if(s)return s;const o=t.error;if(o&&typeof o=="object"&&!Array.isArray(o)){const a=Kt(o.message);if(a)return a}return i}function Qv(e,t){const r=Vc(Ir(t.statusText??"",{maxLength:Pd})),n=Xv(t.body),i=n?Vc(Ir(n,{maxLength:Pd})):void 0;return`${e}: ${t.status}${r?` ${r}`:""}${i?`: ${i}`:""}`}function Xo(e){return Qv(ou,e)}function Qo(e){return Qv(Yv,e)}function kA(e){for(const t of EA){if(!e.startsWith(`${t}: `))continue;const r=e.slice(t.length+2),n=/^\d{3}/.exec(r)?.[0];if(!n)return t;const i=r.indexOf(": ",n.length),s=i===-1?void 0:/^[a-z][a-z0-9_]*(?=:|$)/.exec(r.slice(i+2))?.[0];return s?`${t}: ${n}: ${s}`:`${t}: ${n}`}}function Od(e){try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t+"=".repeat((4-t.length%4)%4);let n;if(typeof globalThis.atob=="function")n=globalThis.atob(r);else if(typeof Buffer<"u")n=Buffer.from(r,"base64").toString("utf-8");else return null;return JSON.parse(n)}catch{return null}}function RA(e){const t=e.split(".");return t.length!==3?null:{header:Od(t[0]),payload:Od(t[1]),signature:t[2]}}function Lr(e){return RA(e)?.payload??null}function De(e){try{return new Date(e*1e3).toLocaleString()}catch{return String(e)}}var yL={isInitiatingAuth:!1,currentStep:"idle",httpHistory:[],infoLogs:[],tokenEndpointAuthMethod:void 0};function ea(){return{isInitiatingAuth:!1,currentStep:"idle",serverUrl:void 0,wwwAuthenticateHeader:void 0,challengedScopes:void 0,resourceMetadataUrl:void 0,resourceMetadata:void 0,resourceIndicator:void 0,resourceIndicatorSuppressed:void 0,authorizationServerUrl:void 0,authorizationServerMetadata:void 0,clientId:void 0,clientSecret:void 0,tokenEndpointAuthMethod:void 0,codeVerifier:void 0,codeChallenge:void 0,codeChallengeMethod:void 0,authorizationUrl:void 0,authorizationCode:void 0,state:void 0,recordedIssuer:void 0,authorizationResponseIss:void 0,requestedScopes:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,lastRequest:void 0,lastResponse:void 0,httpHistory:[],infoLogs:[],error:void 0}}function xn(e,t){return`${e.substring(0,t)}...`}function Bc(e){if(typeof e=="string"&&e.trim()!=="")try{return new URL(e).pathname}catch{return`${e} (not an absolute URL)`}let t;try{t=typeof e=="string"||typeof e=="object"&&e!==null?JSON.stringify(e)??String(e):String(e)}catch{t="[unserializable value]"}return`${t} (not an absolute URL)`}function Pa(e,t,r){return e.resourceIndicatorSuppressed?"omitted (emulation)":t.resourceValue(e)||r}function AA(e,t){return[{id:"request_without_token",label:"MCP request without token",description:"Client makes initial request without authorization",from:"client",to:"mcpServer",details:e.serverUrl?[{label:"POST",value:e.serverUrl},{label:"method",value:t.initialMcpMethod}]:void 0},{id:"received_401_unauthorized",label:"HTTP 401 Unauthorized with WWW-Authenticate header",description:"Server returns 401 with WWW-Authenticate header",from:"mcpServer",to:"client",details:e.resourceMetadataUrl!==void 0?[{label:"Note",value:"Extract resource_metadata URL"}]:void 0},{id:"request_resource_metadata",label:"Request Protected Resource Metadata",description:"Client requests metadata from well-known URI",from:"client",to:"mcpServer",details:e.resourceMetadataUrl!==void 0?[{label:"GET",value:Bc(e.resourceMetadataUrl)}]:void 0},{id:"received_resource_metadata",label:"Return metadata",description:"Server returns OAuth protected resource metadata",from:"mcpServer",to:"client",details:e.resourceMetadata?.authorization_servers?[{label:"Auth Server",value:e.resourceMetadata.authorization_servers[0]}]:void 0}]}function IA(e){return[{id:"cimd_prepare",label:"Client uses HTTPS URL as client_id",description:"Client prepares to use URL-based client identification",from:"client",to:"client",details:e.clientId?[{label:"client_id (URL)",value:e.clientId.includes("http")?e.clientId:"https://www.mcpjam.com/.well-known/oauth/client-metadata.json"},{label:"Method",value:"Client ID Metadata Document (CIMD)"}]:[{label:"Note",value:"HTTPS URL points to metadata document"}]},{id:"cimd_fetch_request",label:"Fetch metadata from client_id URL",description:"Authorization Server fetches client metadata from the URL",from:"authServer",to:"client",details:[{label:"Action",value:"GET client_id URL"},{label:"Note",value:"Server initiates metadata fetch during authorization"}]},{id:"cimd_metadata_response",label:"JSON metadata document",description:"Client hosting returns metadata with redirect_uris and client info",from:"client",to:"authServer",details:[{label:"Content-Type",value:"application/json"},{label:"Contains",value:"client_id, client_name, redirect_uris, etc."}]},{id:"received_client_credentials",label:"Validate metadata and redirect_uris",description:"Authorization Server validates fetched metadata",from:"authServer",to:"authServer",details:[{label:"Validates",value:"client_id matches URL, redirect_uris are valid"},{label:"Security",value:"SSRF protection, domain trust policies"}]}]}function TA(e,t,r){if(r==="cimd")return IA(e);const n=t.clientCredentialsExtras?.(e)??[];return r==="dcr"?[{id:"request_client_registration",label:`POST /register (${t.protocolVersion})`,description:"Client registers dynamically with Authorization Server",from:"client",to:"authServer",details:[{label:"Note",value:"Dynamic client registration (DCR)"},...t.dcrNotes??[]]},{id:"received_client_credentials",label:"Client Credentials",description:"Authorization Server returns client ID and credentials",from:"authServer",to:"client",details:e.clientId?[{label:"client_id",value:xn(e.clientId,20)},...n]:void 0}]:[{id:"received_client_credentials",label:`Use Pre-registered Client (${t.protocolVersion})`,description:"Client uses pre-configured credentials (skipped DCR)",from:"client",to:"client",details:e.clientId?[{label:"client_id",value:xn(e.clientId,20)},{label:"Note",value:"Pre-registered (no DCR needed)"},...n]:[{label:"Note",value:"Pre-registered client credentials"}]}]}function ta(e,t,r){return[...r.includesProtectedResourceMetadata?AA(e,r):[],{id:"request_authorization_server_metadata",label:r.authorizationServerMetadata.label,description:r.authorizationServerMetadata.description,from:"client",to:"authServer",details:e.authorizationServerUrl?[{label:"URL",value:e.authorizationServerUrl},{label:"Protocol",value:r.protocolVersion}]:void 0},{id:"received_authorization_server_metadata",label:"Authorization server metadata response",description:"Authorization Server returns metadata",from:"authServer",to:"client",details:e.authorizationServerMetadata?[{label:"Token",value:Bc(e.authorizationServerMetadata.token_endpoint)},{label:"Auth",value:Bc(e.authorizationServerMetadata.authorization_endpoint)}]:void 0},...TA(e,r,t),{id:"generate_pkce_parameters",label:r.pkce.label,description:r.pkce.description,from:"client",to:"client",details:e.codeChallenge?[{label:"code_challenge",value:xn(e.codeChallenge,15)},{label:"method",value:e.codeChallengeMethod||"S256"},{label:"resource",value:Pa(e,r,"—")},{label:"Protocol",value:r.protocolVersion}]:void 0},{id:"authorization_request",label:"Open browser with authorization URL",description:"Client opens browser with authorization URL + code_challenge + resource",from:"client",to:"browser",details:e.authorizationUrl?[{label:"code_challenge",value:e.codeChallenge?.substring(0,12)+"..."||"S256"},{label:"resource",value:Pa(e,r,"")},...r.authorizationRequestExtras?.(e)??[]]:void 0},{id:"browser_to_auth_server",label:"Authorization request with resource parameter",description:"Browser navigates to authorization endpoint",from:"browser",to:"authServer",details:e.authorizationUrl?[{label:"Note",value:"User authorizes in browser"}]:void 0},{id:"auth_redirect_to_browser",label:"Redirect to callback with authorization code",description:"Authorization Server redirects browser back to callback URL",from:"authServer",to:"browser",details:e.authorizationCode?[{label:"code",value:xn(e.authorizationCode,20)}]:void 0},{id:"received_authorization_code",label:"Authorization code callback",description:"Browser redirects back to client with authorization code",from:"browser",to:"client",details:e.authorizationCode?[{label:"code",value:xn(e.authorizationCode,20)}]:void 0},{id:"token_request",label:"Token request + code_verifier + resource",description:"Client exchanges authorization code for access token",from:"client",to:"authServer",details:e.codeVerifier?[{label:"grant_type",value:"authorization_code"},{label:"resource",value:Pa(e,r,"")}]:void 0},{id:"received_access_token",label:"Access token (+ refresh token)",description:"Authorization Server returns access token",from:"authServer",to:"client",details:e.accessToken?[{label:"token_type",value:e.tokenType||"Bearer"},{label:"expires_in",value:e.expiresIn?.toString()||"3600"}]:void 0},{id:"authenticated_mcp_request",label:"MCP request with access token",description:"Client makes authenticated request to MCP server",from:"client",to:"mcpServer",details:e.accessToken?[{label:"POST",value:"tools/list"},{label:"Authorization",value:`Bearer ${xn(e.accessToken,15)}`}]:void 0},{id:"complete",label:"MCP response",description:"MCP Server returns successful response",from:"mcpServer",to:"client",details:e.accessToken?[{label:"Status",value:"200 OK"},{label:"Content",value:"tools, resources, prompts"}]:void 0}]}function ne(e,t,r,n,i,s={}){const{level:o="info",error:a}=s;return[...e.infoLogs||[],{id:r,step:t,label:n,data:i,timestamp:Date.now(),level:o,error:a}]}function CA(e,t,r,n){return!r||r.source!=="prm"||r.strictClientCompatible&&r.rfc9728Compliant?t:ne({...e,infoLogs:t},"received_resource_metadata","resource-identifier-mismatch","Resource identifier mismatch",{"Advertised resource":r.value,"Server URL":n,Status:r.status,Reason:r.reason,"RFC 9728 compliant":r.rfc9728Compliant,...r.rfc9728Reason?{"RFC 9728 reason":r.rfc9728Reason}:{},Note:r.status==="valid"?"The flow will send this interoperability-safe resource, but it is not RFC 9728 compliant and strict conformance surfaces will reject it.":"The debugger will send the advertised resource as-is so you can observe real behavior, but MCP clients — including MCPJam's Quick OAuth and the official MCP SDK — validate it against the server URL and will refuse to connect."},{level:"warning"})}function ra(e,t,r,n){return ne({...e,infoLogs:t},r,"non-compliant-challenge-status","Non-compliant challenge status",{Received:`${n.status}${n.statusText?` ${n.statusText}`:""}`,Expected:"401 Unauthorized",Note:"The server sent a WWW-Authenticate Bearer challenge, so the debugger continues OAuth discovery from it. MCP requires 401 here — clients that decide to authenticate from the status code alone, including the official MCP SDK, will not start OAuth against this server."},{level:"warning"})}function It(e){return e instanceof Error?{message:e.message,details:{name:e.name,stack:e.stack}}:typeof e=="string"?{message:e}:{message:"Unexpected error",details:e}}function pn(e,t){if(!e||e.length===0)return e||void 0;const r=[...e],n={...r[r.length-1]};return r[r.length-1]={...n,error:t,duration:n.duration!==void 0?n.duration:Date.now()-n.timestamp},r}function lt(e,t={}){const r={},n=new Map,i=s=>{if(s)for(const[o,a]of Object.entries(s)){const c=o.toLowerCase(),l=n.get(c);l&&l!==o&&delete r[l],n.set(c,o),r[o]=a}};return i(e),i(t),r}function at(e,t={}){const r=lt(e,t);for(const n of Object.keys(r))n.toLowerCase()==="authorization"&&delete r[n];return r}function au(e,t,r,n={}){try{const i=new URL(e).origin;return new URL(t,e).origin===i?lt(r,n):at(r,n)}catch{return at(r,n)}}function Tr(e){if(!e)return{};if(e instanceof Headers){const t={};return e.forEach((r,n)=>{t[n]=r}),t}return Array.isArray(e)?Object.fromEntries(e.map(([t,r])=>[t,String(r)])):Object.fromEntries(Object.entries(e).map(([t,r])=>[t,String(r)]))}function $A(e){if(typeof globalThis.btoa=="function"){const t=Array.from(e,r=>String.fromCharCode(r)).join("");return globalThis.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}if(typeof Buffer<"u")return Buffer.from(e).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");throw new Error("No base64 encoder available")}function Dr(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=new Uint8Array(e);return crypto.getRandomValues(r),Array.from(r,n=>t[n%66]).join("")}async function na(e){const t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return $A(new Uint8Array(r))}var ia="Authorization server metadata missing required 'issuer' field",PA=new Set(["2025-03-26"]),OA=new Set(["2025-03-26","2025-06-18"]);function xA(e){return!PA.has(e)}function MA(e){return!OA.has(e)}function eg(e,t){if(MA(t)){if(!e||e.length===0)return`PKCE is REQUIRED for ${t} protocol, but authorization server does not advertise code_challenge_methods_supported. Server is not compliant with ${t} spec.`;if(!e.includes("S256"))return`Authorization server advertises PKCE without S256 (advertised: ${e.join(", ")}). MCPJam will not downgrade to a weaker code challenge method, so the ${t} flow stops here. Use the OAuth debugger to observe this server's behavior without connecting.`}}function cu(e){const t=e.authorizationServers?.find(r=>typeof r=="string"&&r.trim()!=="")?.trim();return t?{authorizationServerUrl:t,substituted:!1}:xA(e.protocolVersion)?{authorizationServerUrl:e.fallbackServerUrl,substituted:!0,error:`Protected resource metadata does not list an authorization server. RFC 9728 \`authorization_servers\` is required by the ${e.protocolVersion} MCP profile; without it there is no server authorized to issue tokens for this resource, and using the MCP server's own URL would invent one.`}:{authorizationServerUrl:e.fallbackServerUrl,substituted:!0}}var LA="io.modelcontextprotocol/oauth-client-credentials",DA="io.modelcontextprotocol/protocolVersion",NA="io.modelcontextprotocol/clientCapabilities",zA="io.modelcontextprotocol/clientInfo";function lu(e){switch(e){case"2025-11-25":return"2025-11-25";case"2026-07-28":return"2026-07-28";case"2025-06-18":case"2025-03-26":return"2024-11-05";default:return e}}function tg(e){return e!=="client_credentials"?{}:{extensions:{[LA]:{}}}}function Dt(e){return{jsonrpc:"2.0",method:"initialize",params:{protocolVersion:e.protocolVersion,capabilities:tg(e.authMode),clientInfo:{name:e.clientName,version:e.clientVersion}},id:e.id}}function ks(e){return{jsonrpc:"2.0",method:"tools/list",params:{_meta:{[DA]:e.protocolVersion,[NA]:tg(e.authMode),[zA]:{name:e.clientName,version:e.clientVersion}}},id:e.id}}var UA="***REDACTED***",FA=new Set(["client_secret","registration_access_token","access_token","refresh_token"]),sa="Authorization server metadata does not include a registration_endpoint. Configure a pre-registered client or use a different registration strategy.",oa="Authorization server metadata does not include a registration_endpoint required for DCR conformance.";function qA(e){const t=r=>{let n;try{n=new URL(r)}catch{return!0}if(n.protocol!=="http:"&&n.protocol!=="https:")return!0;if(n.protocol!=="http:")return!1;const i=n.hostname;return i==="localhost"||i==="127.0.0.1"||i==="[::1]"};return e.some(t)?"native":"web"}function aa(e){const{dynamicRegistrationDefaults:t}=e,r={...t,redirect_uris:t.redirect_uris??[e.redirectUri],grant_types:t.grant_types??["authorization_code","refresh_token"],response_types:t.response_types??["code"],token_endpoint_auth_method:t.token_endpoint_auth_method??"none"};return e.scope&&(r.scope=e.scope),{method:"POST",url:e.registrationEndpoint,headers:at(e.customHeaders,{"Content-Type":"application/json"}),body:r}}function Gc(e){if(Array.isArray(e))return e.map(Gc);if(e&&typeof e=="object"){const t={};for(const[r,n]of Object.entries(e))t[r]=FA.has(r.toLowerCase())?UA:Gc(n);return t}return e}function jA(e){return{status:e.status,statusText:e.statusText,headers:{...e.headers},body:Gc(e.body)}}function xd(e,t){const r=[...e||[]];if(r.length>0){const n=r[r.length-1];r[r.length-1]={...n,response:t,duration:Date.now()-(n.timestamp||Date.now())}}return r}var Vs="Configure a pre-registered client or enable DCR on the authorization server.";async function ca(e){let t;try{t=await e.requestExecutor(e.request)}catch(o){const a=o instanceof Error?o.message:String(o),c={status:0,statusText:"Network Error",headers:{},body:{error:a}},l=`Client registration failed: ${a}`;return{status:"network_error",response:c,httpHistory:xd(e.httpHistory,c),error:l,fallbackNote:"Client registration failed; using pre-registered client credentials.",errorWithFallbackHint:`${l}. ${Vs}`}}const r=jA({status:t.status,statusText:t.statusText,headers:t.headers,body:t.body}),n=xd(e.httpHistory,r);if(!t.ok){const o=`Dynamic Client Registration failed (${t.status}).`;return{status:"http_error",response:r,httpHistory:n,error:o,fallbackNote:`Dynamic Client Registration failed (${t.status}); using pre-registered client credentials.`,errorWithFallbackHint:`${o} ${Vs}`}}const i=t.body;if(!i||typeof i!="object"||Array.isArray(i)){const o="Client registration failed: the registration response body was not a JSON object";return{status:"invalid_response",response:r,httpHistory:n,error:o,fallbackNote:"Client registration failed; using pre-registered client credentials.",errorWithFallbackHint:`${o}. ${Vs}`}}const s={"Client ID":i.client_id,"Client Name":i.client_name,"Token Auth Method":i.token_endpoint_auth_method||"none","Redirect URIs":i.redirect_uris,"Grant Types":i.grant_types,"Response Types":i.response_types};return i.client_secret&&(s["Client Secret Issued"]=!0,s.Note="Server issued client_secret - this will be used in token requests"),{status:"registered",response:r,httpHistory:n,clientInfo:i,credentials:{clientId:typeof i.client_id=="string"?i.client_id:void 0,clientSecret:typeof i.client_secret=="string"?i.client_secret:void 0,tokenEndpointAuthMethod:typeof i.token_endpoint_auth_method=="string"?i.token_endpoint_auth_method:void 0,clientSecretExpiresAt:typeof i.client_secret_expires_at=="number"?i.client_secret_expires_at:void 0},missingClientId:typeof i.client_id!="string",nonCanonicalSuccessStatus:t.status!==201,infoLogData:s}}function la(e){return e?.sendResourceIndicator!==!1}function Nr(e,t){const r=e?.scopeRequest;if(!r)return lA(t);switch(r.mode){case"omit":return;case"fixed":return r.scopes.join(" ");case"challenge":{const n=t.challengedScopes?.filter(Boolean)??[];return n.length>0?Array.from(new Set(n)).join(" "):void 0}case"all-supported":{const n=t.supportedScopes?.filter(Boolean)??[];return n.length>0?Array.from(new Set(n)).join(" "):void 0}}}function ua(e,t){if(!t)return e;const r={...e};return t.dcrClientName!==void 0&&(r.client_name=t.dcrClientName),t.tokenEndpointAuthMethod!==void 0&&(r.token_endpoint_auth_method=t.tokenEndpointAuthMethod),t.dcrRedirectUris!==void 0&&(r.redirect_uris=[...t.dcrRedirectUris]),r}function zr(e,t){return e?.tokenEndpointAuthMethod??t}function HA(e,t){return t?.userAgent?{...e??{},"User-Agent":t.userAgent}:e}function fn(e,t){return e?.mcpProtocolVersion??t}function VA(e,t){return ta(e,t,{protocolVersion:"2025-03-26",includesProtectedResourceMetadata:!1,initialMcpMethod:"initialize",authorizationServerMetadata:{label:"GET /.well-known/oauth-authorization-server from MCP base URL",description:"Direct discovery from MCP server base URL with fallback to /authorize, /token, /register"},pkce:{label:"Generate PKCE parameters",description:"Client generates code verifier and challenge (recommended), includes resource parameter"},resourceValue:r=>r.serverUrl})}function BA(e){return new URL(e).origin}function Md(e){const t=new URL(e),r=[];if(t.pathname==="/"||t.pathname==="")r.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString());else{const n=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;r.push(new URL(`/.well-known/oauth-authorization-server${n}`,t.origin).toString()),r.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString())}return r}var GA=e=>{const{state:t,getState:r,updateState:n,serverUrl:i,serverName:s,redirectUrl:o,requestExecutor:a,scheduleAutoAdvance:c,loadPreregisteredCredentials:l,dynamicRegistration:u,customScopes:h,customHeaders:d,authMode:p,hasClientSecret:f=!1,strictConformance:v=!1,registrationStrategy:m="dcr",emulation:_}=e,w=o,S=fn(_,"2025-03-26"),T=fn(_,lu("2025-03-26")),C=la(_),$=ua(u??{},_);if(m==="dcr"&&!$.client_name)throw new Error("Dynamic registration metadata must include client_name");const M=()=>r?r():t,L=(k,ie={})=>a({url:k,method:ie.method||"GET",headers:Tr(ie.headers),body:ie.body}),q=k=>{const ie=Ko({authorizationServerMetadata:M().authorizationServerMetadata,hasClientSecret:!!(k||f)});if(!ie.ok)throw new Error(ie.message);return ie.method},X=async k=>{const{clientId:ie,clientSecret:H}=await l?.({serverName:s,serverUrl:i})??{};if(!ie)return;const oe=q(H),I={"Client ID":ie,"Client Secret":H||f?"Configured":"Not provided (public client)","Token Auth Method":oe,Note:k};return{clientId:ie,clientSecret:H||void 0,tokenEndpointAuthMethod:oe,infoLogs:ne(M(),"received_client_credentials","preregistered-fallback","Pre-registered Client",I)}},ee={state:t,updateState:n,proceedToNextStep:async()=>{const k=M();n({isInitiatingAuth:!0});const ie=H=>{c?.(()=>{ee.proceedToNextStep()},H)};try{switch(k.currentStep){case"idle":n({currentStep:"discovery_start",serverUrl:i,httpHistory:[],isInitiatingAuth:!1}),ie(50);return;case"request_without_token":if(!k.serverUrl)throw new Error("No server URL available");try{const z=await L(k.serverUrl,{method:"POST",headers:lt(d,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":S}),body:JSON.stringify(Dt({protocolVersion:T,authMode:p,clientName:"MCP Inspector",clientVersion:"1.0.0",id:1}))}),se={status:z.status,statusText:z.statusText,headers:z.headers,body:z.body},ae=[...k.httpHistory||[]];if(ae.length>0){const Oe=ae[ae.length-1];Oe.response=se,Oe.duration=Date.now()-(Oe.timestamp||Date.now())}const he=ls({status:z.status,statusText:z.statusText,wwwAuthenticateHeader:z.headers["www-authenticate"],serverMessage:z.body?.error?.message});if(he.kind==="challenged"||he.kind==="anonymous_allowed"){let Oe=he.kind==="anonymous_allowed"?ne(k,"discovery_start","optional-auth","Optional Authentication",{message:"Server allows anonymous access",note:"Proceeding with OAuth discovery for authenticated features"}):k.infoLogs;he.kind==="challenged"&&!he.specCompliant&&(Oe=ra(k,Oe,"discovery_start",se)),n({currentStep:"discovery_start",lastResponse:se,httpHistory:ae,infoLogs:Oe,isInitiatingAuth:!1})}else throw n({lastResponse:se,httpHistory:ae}),new xr(he.message,z.status)}catch(z){throw z instanceof xr?z:new Error(`Failed to request MCP server: ${z instanceof Error?z.message:String(z)}`)}break;case"discovery_start":const H=k.serverUrl,oe={method:"GET",url:Md(H)[0],headers:at(d,{})};n({currentStep:"request_authorization_server_metadata",authorizationServerUrl:H,lastRequest:oe,lastResponse:void 0,httpHistory:[...k.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:oe}],isInitiatingAuth:!1}),ie(50);return;case"request_authorization_server_metadata":if(!k.authorizationServerUrl)throw new Error("No authorization server URL available");const I=Md(k.authorizationServerUrl);let Q=null,y=null;for(const z of I)try{const se=at(d,{"MCP-Protocol-Version":"2025-03-26"}),ae=[...k.httpHistory||[]];ae.length>0&&(ae[ae.length-1].request={method:"GET",url:z,headers:se}),n({lastRequest:{method:"GET",url:z,headers:se},httpHistory:ae});const he=await L(z,{method:"GET",headers:se});if(he.ok){Q=he.body,y=he;break}else if(he.status>=400&&he.status<500)continue}catch{continue}if(!Q){const z=BA(k.authorizationServerUrl);Q={issuer:z,authorization_endpoint:`${z}/authorize`,token_endpoint:`${z}/token`,registration_endpoint:`${z}/register`,response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]};const se=ne(M(),"received_authorization_server_metadata","fallback-endpoints","Using Fallback Endpoints",{Note:"Metadata discovery failed, using default endpoints per 2025-03-26 spec","Authorization Endpoint":Q.authorization_endpoint,"Token Endpoint":Q.token_endpoint,"Registration Endpoint":Q.registration_endpoint});n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:Q,infoLogs:se,isInitiatingAuth:!1});break}if(!Q.issuer)throw new Error(ia);if(!Q.authorization_endpoint)throw new Error("Authorization server metadata missing 'authorization_endpoint'");if(!Q.token_endpoint)throw new Error("Authorization server metadata missing 'token_endpoint'");if(!Q.response_types_supported?.includes("code"))throw new Error("Authorization server does not support 'code' response type");const V={status:y.status,statusText:y.statusText,headers:y.headers,body:Q},K=[...k.httpHistory||[]];if(K.length>0){const z=K[K.length-1];z.response=V,z.duration=Date.now()-(z.timestamp||Date.now())}const le=Q.code_challenge_methods_supported||[];(!le||le.length===0||!le.includes("S256"))&&console.warn("Authorization server may not support PKCE S256 (REQUIRED for 2025-03-26 spec)"),n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:Q,lastResponse:V,httpHistory:K,isInitiatingAuth:!1});break;case"received_authorization_server_metadata":if(!k.authorizationServerMetadata)throw new Error("No authorization server metadata available");if(m==="preregistered"){const{clientId:z,clientSecret:se}=await l?.({serverName:s,serverUrl:i})??{};if(!z){n({error:"Pre-registered client ID is required. Please configure OAuth credentials in the server settings.",isInitiatingAuth:!1});return}const ae=q(se),he={"Client ID":z,"Client Secret":se||f?"Configured":"Not provided (public client)","Token Auth Method":ae,Note:"Using pre-registered client credentials (skipped DCR)"},Oe=ne(M(),"received_client_credentials","dcr","Pre-registered Client",he);n({currentStep:"received_client_credentials",clientId:z,clientSecret:se||void 0,tokenEndpointAuthMethod:ae,infoLogs:Oe,isInitiatingAuth:!1})}else if(k.authorizationServerMetadata.registration_endpoint){const z=k.authorizationServerMetadata.scopes_supported,se=Nr(_,{customScopes:h,supportedScopes:z}),ae=aa({registrationEndpoint:k.authorizationServerMetadata.registration_endpoint,redirectUri:w,dynamicRegistrationDefaults:$,scope:se,customHeaders:d});n({currentStep:"request_client_registration",lastRequest:ae,lastResponse:void 0,httpHistory:[...k.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:ae}],isInitiatingAuth:!1}),ie(50);return}else{if(v){n({error:oa,isInitiatingAuth:!1});return}const z=await X("Authorization server did not advertise registration_endpoint; using pre-registered client credentials.");if(!z){n({error:sa,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:z.clientId,clientSecret:z.clientSecret,tokenEndpointAuthMethod:z.tokenEndpointAuthMethod,infoLogs:z.infoLogs,error:void 0,isInitiatingAuth:!1})}break;case"request_client_registration":if(!k.authorizationServerMetadata?.registration_endpoint)throw new Error("No registration endpoint available");if(!k.lastRequest?.body)throw new Error("No client metadata in request");{const z=await ca({request:k.lastRequest,requestExecutor:a,httpHistory:k.httpHistory});if(z.status!=="registered"){if(n({lastResponse:z.response,httpHistory:z.httpHistory,error:z.error}),v){z.status==="invalid_response"&&n({isInitiatingAuth:!1});return}const ae=await X(z.fallbackNote);if(!ae){n({error:z.errorWithFallbackHint,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:ae.clientId,clientSecret:ae.clientSecret,tokenEndpointAuthMethod:ae.tokenEndpointAuthMethod,infoLogs:ae.infoLogs,error:void 0,isInitiatingAuth:!1});break}if(z.missingClientId){n({lastResponse:z.response,httpHistory:z.httpHistory,error:"Dynamic Client Registration response is missing a client_id.",isInitiatingAuth:!1});return}const se=ne(M(),"received_client_credentials","dcr","Dynamic Client Registration",z.infoLogData);n({currentStep:"received_client_credentials",clientId:z.credentials.clientId,clientSecret:z.credentials.clientSecret,tokenEndpointAuthMethod:Yo(z.clientInfo),lastResponse:z.response,httpHistory:z.httpHistory,infoLogs:se,error:void 0,isInitiatingAuth:!1})}break;case"received_client_credentials":const de=Dr(43),$e=await na(de),Re=ne(M(),"generate_pkce_parameters","pkce-generation","Generate PKCE Parameters (REQUIRED)",{code_challenge:$e,method:"S256",...C?{resource:k.serverUrl||"Unknown"}:{resource:"(omitted — emulated client does not send RFC 8707 resource)"},note:"PKCE is REQUIRED for all clients in 2025-03-26 spec"});n({currentStep:"generate_pkce_parameters",codeVerifier:de,codeChallenge:$e,codeChallengeMethod:"S256",...C?{}:{resourceIndicatorSuppressed:!0},state:Dr(16),infoLogs:Re,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!k.authorizationServerMetadata?.authorization_endpoint||!k.clientId)throw new Error("Missing authorization endpoint or client ID");const _e=new URL(k.authorizationServerMetadata.authorization_endpoint);_e.searchParams.set("response_type","code"),_e.searchParams.set("client_id",k.clientId),_e.searchParams.set("redirect_uri",w),_e.searchParams.set("code_challenge",k.codeChallenge||""),_e.searchParams.set("code_challenge_method","S256"),_e.searchParams.set("state",k.state||""),k.serverUrl&&C&&_e.searchParams.set("resource",k.serverUrl);const ve=Nr(_,{customScopes:h,supportedScopes:k.authorizationServerMetadata.scopes_supported});ve&&_e.searchParams.set("scope",ve);const Je=ne(M(),"authorization_request","auth-url","Authorization URL",{url:_e.toString()});n({currentStep:"authorization_request",authorizationUrl:_e.toString(),authorizationCode:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,infoLogs:Je,isInitiatingAuth:!1});break;case"authorization_request":n({currentStep:"received_authorization_code",isInitiatingAuth:!1});break;case"received_authorization_code":{if(!k.authorizationCode||k.authorizationCode.trim()===""){n({error:"Authorization code is required. Please paste the code you received from the authorization server.",isInitiatingAuth:!1});return}if(!k.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");const z=Mr({clientId:k.clientId,clientSecret:k.clientSecret,tokenEndpointAuthMethod:zr(_,k.tokenEndpointAuthMethod)}),se={grant_type:"authorization_code",code:k.authorizationCode,redirect_uri:w,...z.bodyParams};k.codeVerifier&&(se.code_verifier=k.codeVerifier),k.serverUrl&&C&&(se.resource=k.serverUrl);const ae={method:"POST",url:k.authorizationServerMetadata.token_endpoint,headers:{"Content-Type":"application/x-www-form-urlencoded",...z.headers},body:se};n({currentStep:"token_request",lastRequest:ae,lastResponse:void 0,...C?{}:{resourceIndicatorSuppressed:!0},accessToken:void 0,refreshToken:void 0,httpHistory:[...k.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:ae}],isInitiatingAuth:!1}),ie(50);return}case"token_request":if(!k.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!k.authorizationCode)throw new Error("Missing authorization code");if(!k.codeVerifier)throw new Error("PKCE code_verifier is missing - REQUIRED by 2025-03-26 spec for token exchange");try{const z=Mr({clientId:k.clientId,clientSecret:k.clientSecret,tokenEndpointAuthMethod:zr(_,k.tokenEndpointAuthMethod)}),se=new URLSearchParams({grant_type:"authorization_code",code:k.authorizationCode,redirect_uri:w,code_verifier:k.codeVerifier||"",...z.bodyParams});k.serverUrl&&C&&se.set("resource",k.serverUrl);const ae=await L(k.authorizationServerMetadata.token_endpoint,{method:"POST",headers:{...at(d,{"Content-Type":"application/x-www-form-urlencoded"}),...z.headers},body:se.toString()}),he={status:ae.status,statusText:ae.statusText,headers:ae.headers,body:ae.body},Oe=[...k.httpHistory||[]];if(Oe.length>0){const pe=Oe[Oe.length-1];pe.response=he,pe.duration=Date.now()-(pe.timestamp||Date.now())}if(!ae.ok){n({lastResponse:he,httpHistory:Oe,authorizationCode:void 0,error:Qo(ae),isInitiatingAuth:!1});return}const we=ae.body;let Se=(M().infoLogs||[]).filter(pe=>pe.id!=="auth-code"&&pe.id!=="oauth-tokens"&&pe.id!=="token");if(k.authorizationCode&&(Se=[...Se,{id:"auth-code",level:"info",step:"received_authorization_code",label:"Authorization Code",data:{code:k.authorizationCode},timestamp:Date.now()}]),we.access_token){const pe={access_token:we.access_token};we.refresh_token&&(pe.refresh_token=we.refresh_token),Se=[...Se,{id:"oauth-tokens",level:"info",step:"received_access_token",label:"OAuth Tokens",data:pe,timestamp:Date.now()}]}if(we.access_token){const pe=Lr(we.access_token);if(pe){const me={...pe};me.exp&&(me.exp=`${me.exp} (${De(me.exp)})`),me.iat&&(me.iat=`${me.iat} (${De(me.iat)})`),me.nbf&&(me.nbf=`${me.nbf} (${De(me.nbf)})`);const Ee={...me};if(me.aud){const Ge=k.serverUrl,U=(Array.isArray(me.aud)?me.aud:[me.aud]).some(W=>W===Ge);Ee._validation={expected_audience:Ge,audience_matches:U,note:U?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else Ee._validation={note:"⚠ No audience claim found - server should validate token binding"};Se=[...Se,{id:"token",step:"received_access_token",level:"info",label:"Access Token (Decoded JWT)",data:Ee,timestamp:Date.now()}]}}if(we.id_token){const pe=Lr(we.id_token);if(pe){const me={...pe};me.exp&&(me.exp=`${me.exp} (${De(me.exp)})`),me.iat&&(me.iat=`${me.iat} (${De(me.iat)})`),me.nbf&&(me.nbf=`${me.nbf} (${De(me.nbf)})`),me.auth_time&&(me.auth_time=`${me.auth_time} (${De(me.auth_time)})`),me._note="OIDC ID Token - Used for user identity verification",Se=[...Se,{id:"id-token",step:"received_access_token",level:"info",label:"ID Token (OIDC - Decoded JWT)",data:me,timestamp:Date.now()}]}}n({currentStep:"received_access_token",accessToken:we.access_token,refreshToken:we.refresh_token,tokenType:we.token_type||"Bearer",expiresIn:we.expires_in,lastResponse:he,httpHistory:Oe,infoLogs:Se,error:void 0,isInitiatingAuth:!1})}catch(z){const se={status:0,statusText:"Network Error",headers:{},body:{error:z instanceof Error?z.message:String(z)}},ae=[...k.httpHistory||[]];if(ae.length>0){const he=ae[ae.length-1];he.response=se,he.duration=Date.now()-(he.timestamp||Date.now())}n({lastResponse:se,httpHistory:ae,error:`Token exchange failed: ${z instanceof Error?z.message:String(z)}`,isInitiatingAuth:!1})}break;case"received_access_token":if(!k.serverUrl||!k.accessToken)throw new Error("Missing server URL or access token");const Xe={method:"POST",url:k.serverUrl,headers:{Authorization:`Bearer ${k.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:Dt({protocolVersion:T,authMode:p,clientName:"MCP Inspector",clientVersion:"1.0.0",id:2})},Pe=ne(M(),"authenticated_mcp_request","authenticated-init","Authenticated MCP Initialize Request",{Request:"MCP initialize with OAuth bearer token","Protocol Version":"2025-03-26",Client:"MCP Inspector v1.0.0",Endpoint:k.serverUrl});n({currentStep:"authenticated_mcp_request",lastRequest:Xe,lastResponse:void 0,httpHistory:[...k.httpHistory||[],{step:"authenticated_mcp_request",timestamp:Date.now(),request:Xe}],infoLogs:Pe,isInitiatingAuth:!1}),ie(50);return;case"authenticated_mcp_request":if(!k.serverUrl||!k.accessToken)throw new Error("Missing server URL or access token");try{const z=await L(k.serverUrl,{method:"POST",headers:lt(d,{Authorization:`Bearer ${k.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(Dt({protocolVersion:T,authMode:p,clientName:"MCP Inspector",clientVersion:"1.0.0",id:2}))}),se={status:z.status,statusText:z.statusText,headers:z.headers,body:z.body},ae=[...k.httpHistory||[]];if(ae.length>0){const pe=ae[ae.length-1];pe.response=se,pe.duration=Date.now()-(pe.timestamp||Date.now())}if(!z.ok){if(z.status>=400&&z.status<500)try{const pe={method:"GET",url:k.serverUrl,headers:{Authorization:`Bearer ${k.accessToken}`,Accept:"text/event-stream"}},me={step:"complete",timestamp:Date.now(),request:pe};ae.push(me);const Ee=await L(k.serverUrl,{method:"GET",headers:{Authorization:`Bearer ${k.accessToken}`,Accept:"text/event-stream"}});me.response={status:Ee.status,statusText:Ee.statusText,headers:Ee.headers,body:Ee.body},me.duration=Date.now()-me.timestamp;const Ge=Ee.body;if(Ge&&typeof Ge=="object"&&Ge.isOldTransport&&Ge.endpoint){const U=Ge.endpoint,W=new URL(U,k.serverUrl).toString(),Y=ne(M(),"authenticated_mcp_request","http-sse-detected","HTTP+SSE Transport Detected (2024-11-05)",{Transport:"HTTP+SSE (2024-11-05 - Deprecated)","SSE Stream URL":k.serverUrl,"POST Endpoint":W,"First Event":Ge.events?.[0],"Migration Note":"This transport is deprecated. Please update your server to use the 2025-03-26 Streamable HTTP transport.","How It Works":"Client connected via GET for SSE stream. Subsequent requests use POST to: "+W});n({currentStep:"complete",lastResponse:{status:Ee.status,statusText:"OK - HTTP+SSE Transport",headers:Ee.headers,body:{transport:"HTTP+SSE (2024-11-05)",sseStreamUrl:k.serverUrl,postEndpoint:W,events:Ge.events}},httpHistory:ae,infoLogs:Y,error:void 0,isInitiatingAuth:!1});return}}catch(pe){console.error("GET fallback failed:",pe)}n({lastResponse:se,httpHistory:ae,error:Xo(z),isInitiatingAuth:!1});return}let he=M().infoLogs||[];const Oe=z.headers["content-type"]||"",we=Oe.includes("text/event-stream");let Se=null;if(we&&z.body?.transport==="sse"?Se=z.body.mcpResponse:Se=z.body,we&&Se?.result?.protocolVersion){const pe={Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Protocol Version":Se.result.protocolVersion};Se.result.serverInfo&&(pe["Server Name"]=Se.result.serverInfo.name,pe["Server Version"]=Se.result.serverInfo.version),Se.result.capabilities&&(pe.Capabilities=Se.result.capabilities),he=ne(M(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",pe)}else if(we)he=ne(M(),"authenticated_mcp_request","mcp-transport","MCP Transport Detected",{Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Content-Type":Oe,Note:"Server returned streaming response. Initialize response delivered via SSE stream.",Events:z.body?.events?`${z.body.events.length} events parsed`:"No events parsed"});else if(Se?.result?.protocolVersion){const pe={Transport:"Streamable HTTP","Response Format":"JSON","Protocol Version":Se.result.protocolVersion};Se.result.serverInfo&&(pe["Server Name"]=Se.result.serverInfo.name,pe["Server Version"]=Se.result.serverInfo.version),Se.result.capabilities&&(pe.Capabilities=Se.result.capabilities),he=ne(M(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",pe)}n({currentStep:"complete",lastResponse:se,httpHistory:ae,infoLogs:he,error:void 0,isInitiatingAuth:!1})}catch(z){const se=It(z),ae={status:0,statusText:"Network Error",headers:{},body:{error:se.message,details:se.details}},he=[...k.httpHistory||[]];if(he.length>0){const Se={...he[he.length-1],response:ae,duration:Date.now()-(he[he.length-1]?.timestamp||Date.now()),error:se};he[he.length-1]=Se}const Oe=M(),we=ne(Oe,"authenticated_mcp_request",`error-authenticated_mcp_request-${Date.now()}`,"Authenticated MCP request failed",{request:Oe.lastRequest,error:se},{level:"error",error:se});n({lastResponse:ae,httpHistory:he,infoLogs:we,error:`Authenticated MCP request failed: ${se.message}`,isInitiatingAuth:!1})}break;case"complete":n({isInitiatingAuth:!1});break;default:n({isInitiatingAuth:!1})}}catch(H){const oe=M(),I=It(H),Q=ne(oe,oe.currentStep,`error-${oe.currentStep}-${Date.now()}`,"Step failed",{step:oe.currentStep,request:oe.lastRequest,response:oe.lastResponse,error:I},{level:"error",error:I}),y=pn(oe.httpHistory,I),V={error:I.message,infoLogs:Q,isInitiatingAuth:!1};y&&(V.httpHistory=y),n(V)}},startGuidedFlow:async()=>{n({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{n(ea())}};return ee};function uu(e){const t=new URL(e);if(t.pathname!=="/"&&t.pathname!==""){const r=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;return new URL(`/.well-known/oauth-protected-resource${r}`,t.origin).toString()}return new URL("/.well-known/oauth-protected-resource",t.origin).toString()}var Ld="Could not discover authorization server metadata.";function WA(e){if("error"in e){const t=e.error instanceof Error?e.error.message:String(e.error);return`${e.url} failed: ${t}`}return e.status>=200&&e.status<300?`${e.url} returned HTTP ${e.status} with no metadata document`:`${e.url} returned HTTP ${e.status}`}function du(e){return e.length===0?`${Ld} No well-known URL was tried.`:`${Ld} ${e.map(WA).join("; ")}.`}function ai(e,t){return gA({serverUrl:e.serverUrl??t,prmResource:e.resourceMetadata?.resource,resolved:e.resourceIndicator})}function hu(e){const t=e.state.serverUrl??e.fallbackServerUrl,r=e.prmResource?.trim();if(!r){const o='Protected Resource Metadata is missing its required "resource" identifier (RFC 9728 §2).';if(e.enforcement!=="warn")throw new Error(o);return{resourceIndicator:Hc({serverUrl:t}),infoLogs:ne({...e.state,infoLogs:e.infoLogs},"received_resource_metadata","resource-identifier-mismatch","Resource identifier missing",{"Server URL":t,Reason:o,Note:"The debugger will fall back to the server URL as the resource indicator, but strict MCP clients treat this metadata as invalid."},{level:"warning"})}}const n=Hc({serverUrl:t,prmResource:r}),i=e.enforcement!=="warn"&&n.status!=="valid",s=e.enforcement==="reject-rfc9728"&&!n.rfc9728Compliant;if(n.source==="prm"&&(i||s))throw new Error((s?n.rfc9728Reason:void 0)??n.reason??"Protected Resource Metadata advertises an unusable resource identifier.");return{resourceIndicator:n,infoLogs:CA(e.state,e.infoLogs,n,t)}}var ZA=e=>ai(e);function JA(e,t){return ta(e,t,{protocolVersion:"2025-06-18",includesProtectedResourceMetadata:!0,initialMcpMethod:"initialize",authorizationServerMetadata:{label:"GET Authorization server metadata endpoint",description:"Try RFC8414 path, then RFC8414 root (no OIDC support)"},pkce:{label:"Generate PKCE parameters",description:"Client generates code verifier and challenge (recommended), includes resource parameter"},resourceValue:ZA})}function Dd(e){const t=new URL(e),r=[];if(t.pathname==="/"||t.pathname==="")r.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString());else{const n=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;r.push(new URL(`/.well-known/oauth-authorization-server${n}`,t.origin).toString()),r.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString())}return r}var KA=e=>{const{state:t,getState:r,updateState:n,serverUrl:i,serverName:s,redirectUrl:o,requestExecutor:a,scheduleAutoAdvance:c,loadPreregisteredCredentials:l,dynamicRegistration:u,customScopes:h,customHeaders:d,resourceMetadataUrl:p,authMode:f,hasClientSecret:v=!1,strictConformance:m=!1,resourceIndicatorEnforcement:_="warn",requiredMetadataEnforcement:w="reject",registrationStrategy:S="dcr",emulation:T}=e,C=o,$=fn(T,"2025-06-18"),M=fn(T,lu("2025-06-18")),L=la(T),q=ua(u??{},T);if(S==="dcr"&&!q.client_name)throw new Error("Dynamic registration metadata must include client_name");const X=()=>r?r():t,ee=()=>ai(X(),i),k=(I,Q={})=>a({url:I,method:Q.method||"GET",headers:Tr(Q.headers),body:Q.body}),ie=I=>{const Q=Ko({authorizationServerMetadata:X().authorizationServerMetadata,hasClientSecret:!!(I||v)});if(!Q.ok)throw new Error(Q.message);return Q.method},H=async I=>{const{clientId:Q,clientSecret:y}=await l?.({serverName:s,serverUrl:i})??{};if(!Q)return;const V=ie(y),K={"Client ID":Q,"Client Secret":y||v?"Configured":"Not provided (public client)","Token Auth Method":V,Note:I};return{clientId:Q,clientSecret:y||void 0,tokenEndpointAuthMethod:V,infoLogs:ne(X(),"received_client_credentials","preregistered-fallback","Pre-registered Client",K)}},oe={state:t,updateState:n,proceedToNextStep:async()=>{const I=X();n({isInitiatingAuth:!0});const Q=y=>{c?.(()=>{oe.proceedToNextStep()},y)};try{switch(I.currentStep){case"idle":{const U=lt(d,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":$}),W=Dt({protocolVersion:M,authMode:f,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}),Y={method:"POST",url:i,headers:U,body:W};n({currentStep:"request_without_token",serverUrl:i,lastRequest:Y,lastResponse:void 0,httpHistory:[...I.httpHistory||[],{step:"request_without_token",timestamp:Date.now(),request:Y}],isInitiatingAuth:!1}),Q(50);return}case"request_without_token":if(!I.serverUrl)throw new Error("No server URL available");try{const U=await k(I.serverUrl,{method:"POST",headers:lt(d,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":$}),body:JSON.stringify(Dt({protocolVersion:M,authMode:f,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}))}),W={status:U.status,statusText:U.statusText,headers:U.headers,body:U.body},Y=[...I.httpHistory||[]];if(Y.length>0){const R=Y[Y.length-1];R.response=W,R.duration=Date.now()-(R.timestamp||Date.now())}const g=ls({status:U.status,statusText:U.statusText,wwwAuthenticateHeader:U.headers["www-authenticate"],serverMessage:U.body?.error?.message});if(g.kind==="challenged"){const R=U.headers["www-authenticate"],E=cr(R),P=su(E.scope);let F=R?ne(I,"received_401_unauthorized","www-authenticate","WWW-Authenticate Header",{header:R,...P&&P.length>0?{scope:P.join(" ")}:{},"Received from":I.serverUrl||"Unknown"}):I.infoLogs;g.specCompliant||(F=ra(I,F,"received_401_unauthorized",W)),n({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:R||void 0,challengedScopes:P,lastResponse:W,httpHistory:Y,infoLogs:F,isInitiatingAuth:!1})}else if(g.kind==="anonymous_allowed"){const R=ne(I,"received_401_unauthorized","optional-auth","Optional Authentication Detected",{message:"Server allows anonymous access",note:"Proceeding with OAuth discovery for authenticated features"});n({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:void 0,challengedScopes:void 0,lastResponse:W,httpHistory:Y,infoLogs:R,isInitiatingAuth:!1})}else throw n({lastResponse:W,httpHistory:Y}),new xr(g.message,U.status)}catch(U){throw U instanceof xr?U:new Error(`Failed to request MCP server: ${U instanceof Error?U.message:String(U)}`)}break;case"received_401_unauthorized":{const U=cr(I.wwwAuthenticateHeader);let W=p||U.resource_metadata;if(!W&&I.serverUrl&&(W=uu(I.serverUrl)),!W)throw new Error("Could not determine resource metadata URL");const Y={method:"GET",url:W,headers:lt(d,{})};n({currentStep:"request_resource_metadata",resourceMetadataUrl:W,lastRequest:Y,lastResponse:void 0,httpHistory:[...I.httpHistory||[],{step:"request_resource_metadata",timestamp:Date.now(),request:Y}],isInitiatingAuth:!1}),Q(50);return}case"request_resource_metadata":if(!I.serverUrl)throw new Error("No server URL available");const y=[...I.httpHistory||[]];let V=y.length>0&&y[y.length-1]?.step==="request_resource_metadata"&&!y[y.length-1]?.response?y.pop():void 0;const K=[],le=U=>{if(!U)return{};if(U instanceof Headers){const W={};return U.forEach((Y,g)=>{W[g]=Y}),W}return Array.isArray(U)?Object.fromEntries(U):Object.fromEntries(Object.entries(U).map(([W,Y])=>[W,String(Y)]))},de=async(U,W={})=>{const Y=typeof U=="string"?U:U.toString(),g=au(i,Y,d,le(W.headers)),R=V?{...V,timestamp:Date.now(),request:{method:W.method||"GET",url:Y,headers:g,body:W.body}}:{step:"request_resource_metadata",timestamp:Date.now(),request:{method:W.method||"GET",url:Y,headers:g,body:W.body}};V=void 0,K.push(R);try{const E=await k(Y,{method:W.method||"GET",headers:g,body:W.body});R.response={status:E.status,statusText:E.statusText,headers:E.headers,body:E.body},R.duration=Date.now()-R.timestamp;const P={status:E.status,statusText:E.statusText,headers:E.headers},F=typeof E.body=="string"?E.body:JSON.stringify(E.body??{});return new Response(F,P)}catch(E){throw R.error=It(E),R.duration=Date.now()-R.timestamp,E}};try{const U=(p||cr(I.wwwAuthenticateHeader).resource_metadata)&&I.resourceMetadataUrl?{resourceMetadataUrl:I.resourceMetadataUrl}:void 0,W=await Jo(I.serverUrl,U,de),Y=[...y,...K],g=K[K.length-1],R=cu({authorizationServers:W.authorization_servers,fallbackServerUrl:i,protocolVersion:"2025-06-18"}),E=R.authorizationServerUrl;if(R.error&&w!=="observe"){n({resourceMetadata:W,resourceMetadataUrl:g?.request?.url||I.resourceMetadataUrl,lastRequest:g?.request,lastResponse:g?.response,httpHistory:Y,error:R.error,isInitiatingAuth:!1});return}let P=I.infoLogs??[];R.error&&(P=ne({...X(),infoLogs:P},"received_resource_metadata","authorization-server-substituted","Derived: Authorization Server (not advertised)",{Finding:R.error,"Using instead":E}));const{resourceIndicator:F,infoLogs:B}=hu({state:I,fallbackServerUrl:i,prmResource:W.resource,enforcement:_,infoLogs:P});n({currentStep:"received_resource_metadata",resourceMetadata:W,resourceIndicator:F,resourceMetadataUrl:g?.request?.url||I.resourceMetadataUrl,authorizationServerUrl:E,lastRequest:g?.request,lastResponse:g?.response,httpHistory:Y,infoLogs:B,isInitiatingAuth:!1})}catch(U){const W=pn([...y,...K],It(U));throw n({lastResponse:K[K.length-1]?.response,httpHistory:W}),new Error(Zo(U))}break;case"received_resource_metadata":if(!I.authorizationServerUrl)throw new Error("No authorization server URL available");const $e={method:"GET",url:Dd(I.authorizationServerUrl)[0],headers:at(d,{})};n({currentStep:"request_authorization_server_metadata",lastRequest:$e,lastResponse:void 0,httpHistory:[...I.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:$e}],isInitiatingAuth:!1}),Q(50);return;case"request_authorization_server_metadata":if(!I.authorizationServerUrl)throw new Error("No authorization server URL available");const Re=Dd(I.authorizationServerUrl);let _e=null;const ve=[];let Je={},Xe=null;for(const U of Re)try{const W=at(d,{}),Y=[...I.httpHistory||[]];Y.length>0&&(Y[Y.length-1].request={method:"GET",url:U,headers:W}),n({lastRequest:{method:"GET",url:U,headers:W},httpHistory:Y});const g=await k(U,{method:"GET",headers:at(d,{})});if(g.ok){_e=g.body,Je=g.headers,Xe=g,_e||ve.push({url:U,status:g.status});break}ve.push({url:U,status:g.status})}catch(W){ve.push({url:U,error:W});continue}if(!_e||!Xe)throw new Error(du(ve));if(!_e.issuer)throw new Error(ia);if(!_e.authorization_endpoint)throw new Error("Authorization server metadata missing 'authorization_endpoint'");if(!_e.token_endpoint)throw new Error("Authorization server metadata missing 'token_endpoint'");if(!_e.response_types_supported?.includes("code"))throw new Error("Authorization server does not support 'code' response type");const Pe={status:Xe.status,statusText:Xe.statusText,headers:Je,body:_e},z=[...I.httpHistory||[]];z.length>0&&(z[z.length-1].response=Pe);const se=_e.code_challenge_methods_supported||[];se.includes("S256")?n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:_e,lastResponse:Pe,httpHistory:z,isInitiatingAuth:!1}):(console.warn("Authorization server may not support S256 PKCE method. Supported methods:",se),n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:_e,lastResponse:Pe,httpHistory:z,error:"Warning: Authorization server may not support S256 PKCE method",isInitiatingAuth:!1}));break;case"received_authorization_server_metadata":if(!I.authorizationServerMetadata)throw new Error("No authorization server metadata available");if(S==="preregistered"){const{clientId:U,clientSecret:W}=await l?.({serverName:s,serverUrl:i})??{};if(!U){n({error:"Pre-registered client ID is required. Please configure OAuth credentials in the server settings.",isInitiatingAuth:!1});return}const Y=ie(W),g={"Client ID":U,"Client Secret":W||v?"Configured":"Not provided (public client)","Token Auth Method":Y,Note:"Using pre-registered client credentials from server config (skipped DCR)"},R=ne(X(),"received_client_credentials","dcr","Pre-registered Client",g);n({currentStep:"received_client_credentials",clientId:U,clientSecret:W||void 0,tokenEndpointAuthMethod:Y,infoLogs:R,isInitiatingAuth:!1})}else if(I.authorizationServerMetadata.registration_endpoint){const U=I.resourceMetadata?.scopes_supported||I.authorizationServerMetadata.scopes_supported,W=Nr(T,{customScopes:h,challengedScopes:I.challengedScopes,supportedScopes:U}),Y=aa({registrationEndpoint:I.authorizationServerMetadata.registration_endpoint,redirectUri:C,dynamicRegistrationDefaults:q,scope:W,customHeaders:d});n({currentStep:"request_client_registration",lastRequest:Y,lastResponse:void 0,httpHistory:[...I.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:Y}],isInitiatingAuth:!1}),Q(50);return}else{if(m){n({error:oa,isInitiatingAuth:!1});return}const U=await H("Authorization server did not advertise registration_endpoint; using pre-registered client credentials.");if(!U){n({error:sa,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:U.clientId,clientSecret:U.clientSecret,tokenEndpointAuthMethod:U.tokenEndpointAuthMethod,infoLogs:U.infoLogs,error:void 0,isInitiatingAuth:!1})}break;case"request_client_registration":{if(!I.authorizationServerMetadata?.registration_endpoint)throw new Error("No registration endpoint available");if(!I.lastRequest?.body)throw new Error("No client metadata in request");const U=await ca({request:I.lastRequest,requestExecutor:a,httpHistory:I.httpHistory});if(U.status!=="registered"){if(n({lastResponse:U.response,httpHistory:U.httpHistory,error:U.error}),m){U.status==="invalid_response"&&n({isInitiatingAuth:!1});return}const Y=await H(U.fallbackNote);if(!Y){n({error:U.errorWithFallbackHint,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:Y.clientId,clientSecret:Y.clientSecret,tokenEndpointAuthMethod:Y.tokenEndpointAuthMethod,infoLogs:Y.infoLogs,error:void 0,isInitiatingAuth:!1});break}if(U.missingClientId){n({lastResponse:U.response,httpHistory:U.httpHistory,error:"Dynamic Client Registration response is missing a client_id.",isInitiatingAuth:!1});return}const W=ne(X(),"received_client_credentials","dcr","Dynamic Client Registration",U.infoLogData);n({currentStep:"received_client_credentials",clientId:U.credentials.clientId,clientSecret:U.credentials.clientSecret,tokenEndpointAuthMethod:Yo(U.clientInfo),lastResponse:U.response,httpHistory:U.httpHistory,infoLogs:W,error:void 0,isInitiatingAuth:!1});break}case"received_client_credentials":const ae=Dr(43),he=await na(ae),Oe=ne(X(),"generate_pkce_parameters","pkce-generation","Generate PKCE Parameters",{code_challenge:he,method:"S256",...L?{resource:ee()||"Unknown"}:{resource:"(omitted — emulated client does not send RFC 8707 resource)"}});n({currentStep:"generate_pkce_parameters",codeVerifier:ae,codeChallenge:he,codeChallengeMethod:"S256",...L?{}:{resourceIndicatorSuppressed:!0},state:Dr(16),infoLogs:Oe,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!I.authorizationServerMetadata?.authorization_endpoint||!I.clientId)throw new Error("Missing authorization endpoint or client ID");const we=new URL(I.authorizationServerMetadata.authorization_endpoint);we.searchParams.set("response_type","code"),we.searchParams.set("client_id",I.clientId),we.searchParams.set("redirect_uri",C),we.searchParams.set("code_challenge",I.codeChallenge||""),we.searchParams.set("code_challenge_method","S256"),we.searchParams.set("state",I.state||"");const Se=ee();Se&&L&&we.searchParams.set("resource",Se);const pe=Nr(T,{customScopes:h,challengedScopes:I.challengedScopes,supportedScopes:I.resourceMetadata?.scopes_supported||I.authorizationServerMetadata.scopes_supported});pe&&we.searchParams.set("scope",pe);const me=ne(X(),"authorization_request","auth-url","Authorization URL",{url:we.toString()});n({currentStep:"authorization_request",authorizationUrl:we.toString(),authorizationCode:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,infoLogs:me,isInitiatingAuth:!1});break;case"authorization_request":n({currentStep:"received_authorization_code",isInitiatingAuth:!1});break;case"received_authorization_code":{if(!I.authorizationCode||I.authorizationCode.trim()===""){n({error:"Authorization code is required. Please paste the code you received from the authorization server.",isInitiatingAuth:!1});return}if(!I.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");const U=Mr({clientId:I.clientId,clientSecret:I.clientSecret,tokenEndpointAuthMethod:zr(T,I.tokenEndpointAuthMethod)}),W={grant_type:"authorization_code",code:I.authorizationCode,redirect_uri:C,...U.bodyParams};I.codeVerifier&&(W.code_verifier=I.codeVerifier);const Y=ee();Y&&L&&(W.resource=Y);const g={method:"POST",url:I.authorizationServerMetadata.token_endpoint,headers:{"Content-Type":"application/x-www-form-urlencoded",...U.headers},body:W};n({currentStep:"token_request",lastRequest:g,lastResponse:void 0,...L?{}:{resourceIndicatorSuppressed:!0},accessToken:void 0,refreshToken:void 0,httpHistory:[...I.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:g}],isInitiatingAuth:!1}),Q(50);return}case"token_request":if(!I.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!I.authorizationCode)throw new Error("Missing authorization code");if(!I.codeVerifier)throw new Error("PKCE code_verifier is missing - cannot exchange token");try{const U=Mr({clientId:I.clientId,clientSecret:I.clientSecret,tokenEndpointAuthMethod:zr(T,I.tokenEndpointAuthMethod)}),W=new URLSearchParams({grant_type:"authorization_code",code:I.authorizationCode,redirect_uri:C,code_verifier:I.codeVerifier||"",...U.bodyParams}),Y=ee();Y&&L&&W.set("resource",Y);const g=await k(I.authorizationServerMetadata.token_endpoint,{method:"POST",headers:{...at(d,{"Content-Type":"application/x-www-form-urlencoded"}),...U.headers},body:W.toString()}),R={status:g.status,statusText:g.statusText,headers:g.headers,body:g.body},E=[...I.httpHistory||[]];if(E.length>0){const B=E[E.length-1];B.response=R,B.duration=Date.now()-(B.timestamp||Date.now())}if(!g.ok){n({lastResponse:R,httpHistory:E,authorizationCode:void 0,error:Qo(g),isInitiatingAuth:!1});return}const P=g.body;let F=(X().infoLogs||[]).filter(B=>B.id!=="auth-code"&&B.id!=="oauth-tokens"&&B.id!=="token");if(I.authorizationCode&&(F=[...F,{id:"auth-code",step:"token_request",level:"info",label:"Authorization Code",data:{code:I.authorizationCode},timestamp:Date.now()}]),P.access_token){const B={access_token:P.access_token};P.refresh_token&&(B.refresh_token=P.refresh_token),F=[...F,{id:"oauth-tokens",step:"token_request",level:"info",label:"OAuth Tokens",data:B,timestamp:Date.now()}]}if(P.access_token){const B=Lr(P.access_token);if(B){const D={...B};D.exp&&(D.exp=`${D.exp} (${De(D.exp)})`),D.iat&&(D.iat=`${D.iat} (${De(D.iat)})`),D.nbf&&(D.nbf=`${D.nbf} (${De(D.nbf)})`);const G={...D};if(D.aud){const J=I.serverUrl,Ut=(Array.isArray(D.aud)?D.aud:[D.aud]).some(Vr=>Vr===J);G._validation={expected_audience:J,audience_matches:Ut,note:Ut?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else G._validation={note:"⚠ No audience claim found - server should validate token binding"};F=[...F,{id:"token",step:"token_request",level:"info",label:"Access Token (Decoded JWT)",data:G,timestamp:Date.now()}]}}if(P.id_token){const B=Lr(P.id_token);if(B){const D={...B};D.exp&&(D.exp=`${D.exp} (${De(D.exp)})`),D.iat&&(D.iat=`${D.iat} (${De(D.iat)})`),D.nbf&&(D.nbf=`${D.nbf} (${De(D.nbf)})`),D.auth_time&&(D.auth_time=`${D.auth_time} (${De(D.auth_time)})`),D._note="OIDC ID Token - Used for user identity verification",F=[...F,{id:"id-token",step:"token_request",level:"info",label:"ID Token (OIDC - Decoded JWT)",data:D,timestamp:Date.now()}]}}n({currentStep:"received_access_token",accessToken:P.access_token,refreshToken:P.refresh_token,tokenType:P.token_type||"Bearer",expiresIn:P.expires_in,lastResponse:R,httpHistory:E,infoLogs:F,error:void 0,isInitiatingAuth:!1})}catch(U){const W={status:0,statusText:"Network Error",headers:{},body:{error:U instanceof Error?U.message:String(U)}},Y=[...I.httpHistory||[]];if(Y.length>0){const g=Y[Y.length-1];g.response=W,g.duration=Date.now()-(g.timestamp||Date.now())}n({lastResponse:W,httpHistory:Y,error:`Token exchange failed: ${U instanceof Error?U.message:String(U)}`,isInitiatingAuth:!1})}break;case"received_access_token":if(!I.serverUrl||!I.accessToken)throw new Error("Missing server URL or access token");const Ee={method:"POST",url:I.serverUrl,headers:{Authorization:`Bearer ${I.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":$},body:Dt({protocolVersion:M,authMode:f,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:2})},Ge=ne(X(),"authenticated_mcp_request","authenticated-init","Authenticated MCP Initialize Request",{Request:"MCP initialize with OAuth bearer token","Protocol Version":"2025-06-18",Client:"MCPJam Inspector v1.0.0",Endpoint:I.serverUrl});n({currentStep:"authenticated_mcp_request",lastRequest:Ee,lastResponse:void 0,httpHistory:[...I.httpHistory||[],{step:"authenticated_mcp_request",timestamp:Date.now(),request:Ee}],infoLogs:Ge,isInitiatingAuth:!1}),Q(50);return;case"authenticated_mcp_request":if(!I.serverUrl||!I.accessToken)throw new Error("Missing server URL or access token");try{const U=await k(I.serverUrl,{method:"POST",headers:lt(d,{Authorization:`Bearer ${I.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":$}),body:JSON.stringify(Dt({protocolVersion:M,authMode:f,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:2}))}),W={status:U.status,statusText:U.statusText,headers:U.headers,body:U.body},Y=[...I.httpHistory||[]];if(Y.length>0){const F=Y[Y.length-1];F.response=W,F.duration=Date.now()-(F.timestamp||Date.now())}if(!U.ok){n({lastResponse:W,httpHistory:Y,error:Xo(U),isInitiatingAuth:!1});return}let g=X().infoLogs||[];const R=U.headers["content-type"]||"",E=R.includes("text/event-stream");let P=null;if(E&&U.body?.transport==="sse"?P=U.body.mcpResponse:P=U.body,E&&P?.result?.protocolVersion){const F={Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Protocol Version":P.result.protocolVersion};P.result.serverInfo&&(F["Server Name"]=P.result.serverInfo.name,F["Server Version"]=P.result.serverInfo.version),P.result.capabilities&&(F.Capabilities=P.result.capabilities),g=ne(X(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",F)}else if(E)g=ne(X(),"authenticated_mcp_request","mcp-transport","MCP Transport Detected",{Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Content-Type":R,Note:"Server returned streaming response. Initialize response delivered via SSE stream.",Events:U.body?.events?`${U.body.events.length} events parsed`:"No events parsed"});else if(P?.result?.protocolVersion){const F={Transport:"Streamable HTTP","Response Format":"JSON","Protocol Version":P.result.protocolVersion};P.result.serverInfo&&(F["Server Name"]=P.result.serverInfo.name,F["Server Version"]=P.result.serverInfo.version),P.result.capabilities&&(F.Capabilities=P.result.capabilities),g=ne(X(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",F)}n({currentStep:"complete",lastResponse:W,httpHistory:Y,infoLogs:g,error:void 0,isInitiatingAuth:!1})}catch(U){const W=It(U),Y={status:0,statusText:"Network Error",headers:{},body:{error:W.message,details:W.details}},g=[...I.httpHistory||[]];if(g.length>0){const P={...g[g.length-1],response:Y,duration:Date.now()-(g[g.length-1]?.timestamp||Date.now()),error:W};g[g.length-1]=P}const R=X(),E=ne(R,"authenticated_mcp_request",`error-authenticated_mcp_request-${Date.now()}`,"Authenticated MCP request failed",{request:R.lastRequest,error:W},{level:"error",error:W});n({lastResponse:Y,httpHistory:g,infoLogs:E,error:`Authenticated MCP request failed: ${W.message}`,isInitiatingAuth:!1})}break;case"complete":n({isInitiatingAuth:!1});break;default:n({isInitiatingAuth:!1})}}catch(y){const V=X(),K=It(y),le=ne(V,V.currentStep,`error-${V.currentStep}-${Date.now()}`,"Step failed",{step:V.currentStep,request:V.lastRequest,response:V.lastResponse,error:K},{level:"error",error:K}),de=pn(V.httpHistory,K),$e={error:K.message,infoLogs:le,isInitiatingAuth:!1};de&&($e.httpHistory=de),n($e)}},startGuidedFlow:async()=>{n({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{n(ea())}};return oe};function da(e){const t=e.replace(/^\[|\]$/g,"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)||t==="::1"}function bL(e){try{const{protocol:t,hostname:r}=new URL(e);return t==="http:"&&da(r)}catch{return!1}}function rg(e,t={}){let r;try{r=new URL(e)}catch{throw new Error("Client ID metadata URL must be a valid absolute URL")}const n=t.allowLoopback===!0&&r.protocol==="http:"&&da(r.hostname);if(!n&&(r.protocol!=="https:"||!r.hostname))throw new Error("Client ID metadata URL must be an absolute HTTPS URL");const i=n?/^http:\/\//i:/^https:\/\//i;if(!i.test(e))throw new Error(n?"Client ID metadata URL must use the http:// scheme (with two slashes)":"Client ID metadata URL must use the https:// scheme (with two slashes)");if(/[\u0000-\u0020\u007f\\]/.test(e))throw new Error("Client ID metadata URL must not contain control characters, whitespace, or backslashes");if(r.hash||e.includes("#"))throw new Error("Client ID metadata URL must not contain a fragment component");const s=e.split(/[?#]/,1)[0].replace(i,""),o=s.indexOf("/"),a=o===-1?s:s.slice(0,o),c=o===-1?"":s.slice(o);if(!a)throw new Error("Client ID metadata URL must contain a host immediately after https://");if(r.username||r.password||a.includes("@"))throw new Error("Client ID metadata URL must not contain a userinfo component");if(!c)throw new Error("Client ID metadata URL must contain a path component");const l=u=>{const h=u.replace(/%2e/gi,".");return h==="."||h===".."};if(c.split("/").some(l))throw new Error("Client ID metadata URL must not contain single-dot or double-dot path segments");return e}var YA=e=>ai(e);function XA(e,t){return ta(e,t,{protocolVersion:"2025-11-25",includesProtectedResourceMetadata:!0,initialMcpMethod:"initialize",authorizationServerMetadata:{label:"GET Authorization server metadata endpoint",description:"Try OAuth path insertion, OIDC path insertion, OIDC path appending"},pkce:{label:`Generate PKCE (REQUIRED)
92
+ Include resource parameter`,description:"Client generates code verifier and challenge (REQUIRED), includes resource parameter"},resourceValue:YA})}function Nd(e){const t=new URL(e),r=[];if(t.pathname==="/"||t.pathname==="")r.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString()),r.push(new URL("/.well-known/openid-configuration",t.origin).toString());else{const n=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;r.push(new URL(`/.well-known/oauth-authorization-server${n}`,t.origin).toString()),r.push(new URL(`/.well-known/openid-configuration${n}`,t.origin).toString()),r.push(new URL(`${n}/.well-known/openid-configuration`,t.origin).toString())}return r}var QA=e=>{const{state:t,getState:r,updateState:n,serverUrl:i,serverName:s,redirectUrl:o,requestExecutor:a,scheduleAutoAdvance:c,loadPreregisteredCredentials:l,dynamicRegistration:u,clientIdMetadataUrl:h,customScopes:d,customHeaders:p,resourceMetadataUrl:f,authMode:v,hasClientSecret:m=!1,strictConformance:_=!1,resourceIndicatorEnforcement:w="warn",requiredMetadataEnforcement:S="reject",registrationStrategy:T="cimd",emulation:C}=e,$=o,M=fn(C,"2025-11-25"),L=fn(C,lu("2025-11-25")),q=la(C),X=ua(u??{},C);let ee=h??"";if(T==="dcr"&&!X.client_name)throw new Error("Dynamic registration metadata must include client_name");if(T==="cimd"&&!ee)throw new Error("Client ID metadata URL is required for CIMD registration");T==="cimd"&&(ee=rg(ee));const k=()=>r?r():t,ie=()=>ai(k(),i),H=(y,V={})=>a({url:y,method:V.method||"GET",headers:Tr(V.headers),body:V.body}),oe=y=>{const V=Ko({authorizationServerMetadata:k().authorizationServerMetadata,hasClientSecret:!!(y||m)});if(!V.ok)throw new Error(V.message);return V.method},I=async y=>{const{clientId:V,clientSecret:K}=await l?.({serverName:s,serverUrl:i})??{};if(!V)return;const le=oe(K),de={"Client ID":V,"Client Secret":K||m?"Configured":"Not provided (public client)","Token Auth Method":le,Note:y};return{clientId:V,clientSecret:K||void 0,tokenEndpointAuthMethod:le,infoLogs:ne(k(),"received_client_credentials","preregistered-fallback","Pre-registered Client",de)}},Q={state:t,updateState:n,proceedToNextStep:async()=>{const y=k();n({isInitiatingAuth:!0});const V=K=>{c?.(()=>{Q.proceedToNextStep()},K)};try{switch(y.currentStep){case"idle":{const g=lt(p,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":M}),R=Dt({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}),E={method:"POST",url:i,headers:g,body:R};n({currentStep:"request_without_token",serverUrl:i,lastRequest:E,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_without_token",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),V(50);return}case"request_without_token":if(!y.serverUrl)throw new Error("No server URL available");try{const g=await H(y.serverUrl,{method:"POST",headers:lt(p,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":M}),body:JSON.stringify(Dt({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}))}),R={status:g.status,statusText:g.statusText,headers:g.headers,body:g.body},E=[...y.httpHistory||[]];if(E.length>0){const F=E[E.length-1];F.response=R,F.duration=Date.now()-(F.timestamp||Date.now())}const P=ls({status:g.status,statusText:g.statusText,wwwAuthenticateHeader:g.headers["www-authenticate"],serverMessage:g.body?.error?.message});if(P.kind==="challenged"){const F=g.headers["www-authenticate"],B=cr(F),D=su(B.scope);let G=F?ne(y,"received_401_unauthorized","www-authenticate","WWW-Authenticate Header",{header:F,...D&&D.length>0?{scope:D.join(" ")}:{},"Received from":y.serverUrl||"Unknown"}):y.infoLogs;P.specCompliant||(G=ra(y,G,"received_401_unauthorized",R)),n({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:F||void 0,challengedScopes:D,lastResponse:R,httpHistory:E,infoLogs:G,isInitiatingAuth:!1})}else if(P.kind==="anonymous_allowed"){const F=ne(y,"received_401_unauthorized","optional-auth","Optional Authentication Detected",{message:"Server allows anonymous access",note:"Proceeding with OAuth discovery for authenticated features"});n({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:void 0,lastResponse:R,httpHistory:E,infoLogs:F,isInitiatingAuth:!1})}else throw n({lastResponse:R,httpHistory:E}),new xr(P.message,g.status)}catch(g){throw g instanceof xr?g:new Error(`Failed to request MCP server: ${g instanceof Error?g.message:String(g)}`)}break;case"received_401_unauthorized":{const g=cr(y.wwwAuthenticateHeader);let R=f||g.resource_metadata;if(!R&&y.serverUrl&&(R=uu(y.serverUrl)),!R)throw new Error("Could not determine resource metadata URL");const E={method:"GET",url:R,headers:lt(p,{})};n({currentStep:"request_resource_metadata",resourceMetadataUrl:R,lastRequest:E,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_resource_metadata",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),V(50);return}case"request_resource_metadata":if(!y.serverUrl)throw new Error("No server URL available");const K=[...y.httpHistory||[]];let le=K.length>0&&K[K.length-1]?.step==="request_resource_metadata"&&!K[K.length-1]?.response?K.pop():void 0;const de=[],$e=async(g,R={})=>{const E=typeof g=="string"?g:g.toString(),P=au(i,E,p,Tr(R.headers)),F=le?{...le,timestamp:Date.now(),request:{method:R.method||"GET",url:E,headers:P,body:R.body}}:{step:"request_resource_metadata",timestamp:Date.now(),request:{method:R.method||"GET",url:E,headers:P,body:R.body}};le=void 0,de.push(F);try{const B=await H(E,{method:R.method||"GET",headers:P,body:R.body});F.response={status:B.status,statusText:B.statusText,headers:B.headers,body:B.body},F.duration=Date.now()-F.timestamp;const D={status:B.status,statusText:B.statusText,headers:B.headers},G=typeof B.body=="string"?B.body:JSON.stringify(B.body??{});return new Response(G,D)}catch(B){throw F.error=It(B),F.duration=Date.now()-F.timestamp,B}};try{const g=(f||cr(y.wwwAuthenticateHeader).resource_metadata)&&y.resourceMetadataUrl?{resourceMetadataUrl:y.resourceMetadataUrl}:void 0,R=await Jo(y.serverUrl,g,$e),E=[...K,...de],P=de[de.length-1],F=cu({authorizationServers:R.authorization_servers,fallbackServerUrl:i,protocolVersion:"2025-11-25"}),B=F.authorizationServerUrl;if(F.error&&S!=="observe"){n({resourceMetadata:R,resourceMetadataUrl:P?.request?.url||y.resourceMetadataUrl,lastRequest:P?.request,lastResponse:P?.response,httpHistory:E,error:F.error,isInitiatingAuth:!1});return}let D=y.infoLogs??[];F.error&&(D=ne({...k(),infoLogs:D},"received_resource_metadata","authorization-server-substituted","Derived: Authorization Server (not advertised)",{Finding:F.error,"Using instead":B}));const G=hu({state:y,fallbackServerUrl:i,prmResource:R.resource,enforcement:w,infoLogs:D}),J=G.resourceIndicator;D=G.infoLogs,n({currentStep:"received_resource_metadata",resourceMetadata:R,resourceIndicator:J,resourceMetadataUrl:P?.request?.url||y.resourceMetadataUrl,authorizationServerUrl:B,lastRequest:P?.request,lastResponse:P?.response,httpHistory:E,infoLogs:D,isInitiatingAuth:!1})}catch(g){const R=pn([...K,...de],It(g));throw n({lastResponse:de[de.length-1]?.response,httpHistory:R}),new Error(Zo(g))}break;case"received_resource_metadata":if(!y.authorizationServerUrl)throw new Error("No authorization server URL available");const Re={method:"GET",url:Nd(y.authorizationServerUrl)[0],headers:at(p,{})};n({currentStep:"request_authorization_server_metadata",lastRequest:Re,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:Re}],isInitiatingAuth:!1}),V(50);return;case"request_authorization_server_metadata":if(!y.authorizationServerUrl)throw new Error("No authorization server URL available");const _e=Nd(y.authorizationServerUrl);let ve=null;const Je=[];let Xe={},Pe=null;for(const g of _e)try{const R=at(p,{}),E=[...y.httpHistory||[]];E.length>0&&(E[E.length-1].request={method:"GET",url:g,headers:R}),n({lastRequest:{method:"GET",url:g,headers:R},httpHistory:E});const P=await H(g,{method:"GET",headers:at(p,{})});if(P.ok){ve=P.body,Xe=P.headers,Pe=P,ve||Je.push({url:g,status:P.status});break}Je.push({url:g,status:P.status})}catch(R){Je.push({url:g,error:R});continue}if(!ve||!Pe)throw new Error(du(Je));if(!ve.issuer)throw new Error(ia);if(!ve.authorization_endpoint)throw new Error("Authorization server metadata missing 'authorization_endpoint'");if(!ve.token_endpoint)throw new Error("Authorization server metadata missing 'token_endpoint'");if(!ve.response_types_supported?.includes("code"))throw new Error("Authorization server does not support 'code' response type");const z={status:Pe.status,statusText:Pe.statusText,headers:Xe,body:ve},se=[...y.httpHistory||[]];if(se.length>0){const g=se[se.length-1];g.response=z,g.duration=Date.now()-(g.timestamp||Date.now())}const ae=ve.code_challenge_methods_supported||[],he=eg(ae,"2025-11-25"),Oe=typeof ve.client_id_metadata_document_supported=="boolean"?ve.client_id_metadata_document_supported:"false (not advertised, defaults to false per spec)",we=ne(k(),"received_authorization_server_metadata","cimd-support","Derived: CIMD Support",{"CIMD Supported":Oe});if(he){if(_||S!=="observe"){n({lastResponse:z,httpHistory:se,infoLogs:we,error:he,isInitiatingAuth:!1});return}console.warn("Authorization server may not support S256 PKCE method. Supported methods:",ae),n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:ve,lastResponse:z,httpHistory:se,infoLogs:we,error:"Warning: Authorization server may not support S256 PKCE method",isInitiatingAuth:!1})}else n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:ve,lastResponse:z,httpHistory:se,infoLogs:we,isInitiatingAuth:!1});break;case"received_authorization_server_metadata":if(!y.authorizationServerMetadata)throw new Error("No authorization server metadata available");if(T==="cimd"){if(y.authorizationServerMetadata.client_id_metadata_document_supported!==!0){n({error:"The authorization server does not support Client ID Metadata Documents (client_id_metadata_document_supported is not advertised in AS metadata). Try using 'dcr' or 'preregistered' registration strategy instead.",isInitiatingAuth:!1});return}n({currentStep:"cimd_prepare",clientId:ee,isInitiatingAuth:!1}),V(800);return}else if(T==="preregistered"){const{clientId:g,clientSecret:R}=await l?.({serverName:s,serverUrl:i})??{};if(!g){n({error:"Pre-registered client ID is required. Please configure OAuth credentials in the server settings.",isInitiatingAuth:!1});return}const E=oe(R),P={"Client ID":g,"Client Secret":R||m?"Configured":"Not provided (public client)","Token Auth Method":E,Note:"Using pre-registered client credentials from server config (skipped DCR)"},F=ne(k(),"received_client_credentials","dcr","Pre-registered Client",P);n({currentStep:"received_client_credentials",clientId:g,clientSecret:R||void 0,tokenEndpointAuthMethod:E,infoLogs:F,isInitiatingAuth:!1})}else if(y.authorizationServerMetadata.registration_endpoint){const g=y.resourceMetadata?.scopes_supported||y.authorizationServerMetadata.scopes_supported,R=Nr(C,{customScopes:d,challengedScopes:y.challengedScopes,supportedScopes:g}),E=aa({registrationEndpoint:y.authorizationServerMetadata.registration_endpoint,redirectUri:$,dynamicRegistrationDefaults:X,scope:R,customHeaders:p});n({currentStep:"request_client_registration",lastRequest:E,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),V(50);return}else{if(_){n({error:oa,isInitiatingAuth:!1});return}const g=await I("Authorization server did not advertise registration_endpoint; using pre-registered client credentials.");if(!g){n({error:sa,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:g.clientId,clientSecret:g.clientSecret,tokenEndpointAuthMethod:g.tokenEndpointAuthMethod,infoLogs:g.infoLogs,error:void 0,isInitiatingAuth:!1})}break;case"request_client_registration":if(!y.authorizationServerMetadata?.registration_endpoint)throw new Error("No registration endpoint available");if(!y.lastRequest?.body)throw new Error("No client metadata in request");{const g=await ca({request:y.lastRequest,requestExecutor:a,httpHistory:y.httpHistory});if(g.status!=="registered"){if(n({lastResponse:g.response,httpHistory:g.httpHistory,error:g.error,isInitiatingAuth:!1}),_)return;const E=await I(g.fallbackNote);if(!E){n({error:g.errorWithFallbackHint,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:E.clientId,clientSecret:E.clientSecret,tokenEndpointAuthMethod:E.tokenEndpointAuthMethod,infoLogs:E.infoLogs,error:void 0,isInitiatingAuth:!1});break}if(g.missingClientId){n({lastResponse:g.response,httpHistory:g.httpHistory,error:"Dynamic Client Registration response is missing a client_id.",isInitiatingAuth:!1});return}const R=ne(k(),"received_client_credentials","dcr","Dynamic Client Registration",g.infoLogData);n({currentStep:"received_client_credentials",clientId:g.credentials.clientId,clientSecret:g.credentials.clientSecret,tokenEndpointAuthMethod:Yo(g.clientInfo),lastResponse:g.response,httpHistory:g.httpHistory,infoLogs:R,error:void 0,isInitiatingAuth:!1})}break;case"cimd_prepare":n({currentStep:"cimd_fetch_request",isInitiatingAuth:!1}),V(800);return;case"cimd_fetch_request":try{const g={method:"GET",url:ee,headers:Tr(void 0)},R=Date.now(),E=await H(ee,{method:"GET"});if(!E.ok)throw new Error(`CIMD endpoint returned HTTP ${E.status}`);const P={status:E.status,statusText:E.statusText,headers:E.headers,body:E.body};n({currentStep:"cimd_metadata_response",lastRequest:g,lastResponse:P,httpHistory:[...y.httpHistory||[],{step:"cimd_fetch_request",timestamp:R,duration:Date.now()-R,request:g,response:P}],isInitiatingAuth:!1}),V(800);return}catch(g){n({error:`CIMD metadata fetch failed: ${g instanceof Error?g.message:String(g)}. Try using 'dcr' or 'preregistered' registration strategy instead.`,isInitiatingAuth:!1});return}case"cimd_metadata_response":try{const g=y.lastResponse?.body;if(!g||typeof g!="object")throw new Error("CIMD metadata document was not available");if(g.client_id!==ee)throw new Error("CIMD client_id mismatch");const R=y.authorizationServerMetadata?.client_id_metadata_document_supported,E={"Client ID":ee,"Registration Method":"Client ID Metadata Document (CIMD)","Client Name":g.client_name||"MCPJam","Redirect URIs":g.redirect_uris||[],"Token Auth Method":g.token_endpoint_auth_method||"none",Validation:"✓ Metadata fetched and validated",Note:"Server fetched and validated client metadata from URL"};R?E["Server Support"]="✓ Advertised in metadata (client_id_metadata_document_supported: true)":E["Server Support"]="⚠ Not advertised (attempting anyway)";const P=ne(k(),"received_client_credentials","cimd","Client ID Metadata Document",E);n({currentStep:"received_client_credentials",clientId:ee,clientSecret:void 0,tokenEndpointAuthMethod:"none",infoLogs:P,isInitiatingAuth:!1})}catch(g){n({error:`CIMD validation failed: ${g instanceof Error?g.message:String(g)}. Try using 'dcr' or 'preregistered' registration strategy instead.`,isInitiatingAuth:!1});return}break;case"received_client_credentials":const Se=Dr(43),pe=await na(Se),me=ne(k(),"generate_pkce_parameters","pkce-generation","Generate PKCE Parameters",{code_challenge:pe,method:"S256",...q?{resource:ie()}:{resource:"(omitted — emulated client does not send RFC 8707 resource)"}});n({currentStep:"generate_pkce_parameters",codeVerifier:Se,codeChallenge:pe,codeChallengeMethod:"S256",...q?{}:{resourceIndicatorSuppressed:!0},state:Dr(16),infoLogs:me,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!y.authorizationServerMetadata?.authorization_endpoint||!y.clientId)throw new Error("Missing authorization endpoint or client ID");const Ee=new URL(y.authorizationServerMetadata.authorization_endpoint);Ee.searchParams.set("response_type","code"),Ee.searchParams.set("client_id",y.clientId),Ee.searchParams.set("redirect_uri",$),Ee.searchParams.set("code_challenge",y.codeChallenge||""),Ee.searchParams.set("code_challenge_method","S256"),Ee.searchParams.set("state",y.state||""),q&&Ee.searchParams.set("resource",ie());const Ge=Nr(C,{customScopes:d,challengedScopes:y.challengedScopes,supportedScopes:y.resourceMetadata?.scopes_supported||y.authorizationServerMetadata.scopes_supported});Ge&&Ee.searchParams.set("scope",Ge);const U=ne(k(),"authorization_request","auth-url","Authorization URL",{url:Ee.toString()});n({currentStep:"authorization_request",authorizationUrl:Ee.toString(),authorizationCode:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,infoLogs:U,isInitiatingAuth:!1});break;case"authorization_request":n({currentStep:"received_authorization_code",isInitiatingAuth:!1});break;case"received_authorization_code":{if(!y.authorizationCode||y.authorizationCode.trim()===""){n({error:"Authorization code is required. Please paste the code you received from the authorization server.",isInitiatingAuth:!1});return}if(!y.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");const g=Mr({clientId:y.clientId,clientSecret:y.clientSecret,tokenEndpointAuthMethod:zr(C,y.tokenEndpointAuthMethod)}),R={grant_type:"authorization_code",code:y.authorizationCode,redirect_uri:$,...g.bodyParams};y.codeVerifier&&(R.code_verifier=y.codeVerifier),q&&(R.resource=ie());const E={method:"POST",url:y.authorizationServerMetadata.token_endpoint,headers:{"Content-Type":"application/x-www-form-urlencoded",...g.headers},body:R};n({currentStep:"token_request",lastRequest:E,lastResponse:void 0,...q?{}:{resourceIndicatorSuppressed:!0},accessToken:void 0,refreshToken:void 0,httpHistory:[...y.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),V(50);return}case"token_request":if(!y.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!y.authorizationCode)throw new Error("Missing authorization code");if(!y.codeVerifier)throw new Error("PKCE code_verifier is missing - cannot exchange token");try{const g=Mr({clientId:y.clientId,clientSecret:y.clientSecret,tokenEndpointAuthMethod:zr(C,y.tokenEndpointAuthMethod)}),R=new URLSearchParams({grant_type:"authorization_code",code:y.authorizationCode,redirect_uri:$,code_verifier:y.codeVerifier||"",...g.bodyParams});q&&R.set("resource",ie());const E=await H(y.authorizationServerMetadata.token_endpoint,{method:"POST",headers:{...at(p,{"Content-Type":"application/x-www-form-urlencoded"}),...g.headers},body:R.toString()}),P={status:E.status,statusText:E.statusText,headers:E.headers,body:E.body},F=[...y.httpHistory||[]];if(F.length>0){const G=F[F.length-1];G.response=P,G.duration=Date.now()-(G.timestamp||Date.now())}if(!E.ok){n({lastResponse:P,httpHistory:F,authorizationCode:void 0,error:Qo(E),isInitiatingAuth:!1});return}const B=E.body;let D=(k().infoLogs||[]).filter(G=>G.id!=="auth-code"&&G.id!=="oauth-tokens"&&G.id!=="token");if(y.authorizationCode&&(D=[...D,{id:"auth-code",level:"info",step:"authorization_request",label:"Authorization Code",data:{code:y.authorizationCode},timestamp:Date.now()}]),B.access_token){const G={access_token:B.access_token};B.refresh_token&&(G.refresh_token=B.refresh_token),D=[...D,{id:"oauth-tokens",level:"info",step:"token_request",label:"OAuth Tokens",data:G,timestamp:Date.now()}]}if(B.access_token){const G=Lr(B.access_token);if(G){const J={...G};J.exp&&(J.exp=`${J.exp} (${De(J.exp)})`),J.iat&&(J.iat=`${J.iat} (${De(J.iat)})`),J.nbf&&(J.nbf=`${J.nbf} (${De(J.nbf)})`);const Ut={...J};if(J.aud){const Vr=y.serverUrl,ui=(Array.isArray(J.aud)?J.aud:[J.aud]).some(Ra=>Ra===Vr);Ut._validation={expected_audience:Vr,audience_matches:ui,note:ui?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else Ut._validation={note:"⚠ No audience claim found - server should validate token binding"};D=[...D,{id:"token",level:"info",step:"token_request",label:"Access Token (Decoded JWT)",data:Ut,timestamp:Date.now()}]}}if(B.id_token){const G=Lr(B.id_token);if(G){const J={...G};J.exp&&(J.exp=`${J.exp} (${De(J.exp)})`),J.iat&&(J.iat=`${J.iat} (${De(J.iat)})`),J.nbf&&(J.nbf=`${J.nbf} (${De(J.nbf)})`),J.auth_time&&(J.auth_time=`${J.auth_time} (${De(J.auth_time)})`),J._note="OIDC ID Token - Used for user identity verification",D=[...D,{id:"id-token",level:"info",step:"token_request",label:"ID Token (OIDC - Decoded JWT)",data:J,timestamp:Date.now()}]}}n({currentStep:"received_access_token",accessToken:B.access_token,refreshToken:B.refresh_token,tokenType:B.token_type||"Bearer",expiresIn:B.expires_in,lastResponse:P,httpHistory:F,infoLogs:D,error:void 0,isInitiatingAuth:!1})}catch(g){const R={status:0,statusText:"Network Error",headers:{},body:{error:g instanceof Error?g.message:String(g)}},E=[...y.httpHistory||[]];if(E.length>0){const P=E[E.length-1];P.response=R,P.duration=Date.now()-(P.timestamp||Date.now())}n({lastResponse:R,httpHistory:E,error:`Token exchange failed: ${g instanceof Error?g.message:String(g)}`,isInitiatingAuth:!1})}break;case"received_access_token":if(!y.serverUrl||!y.accessToken)throw new Error("Missing server URL or access token");const W={method:"POST",url:y.serverUrl,headers:{Authorization:`Bearer ${y.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":M},body:Dt({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:2})},Y=ne(k(),"authenticated_mcp_request","authenticated-init","Authenticated MCP Initialize Request",{Request:"MCP initialize with OAuth bearer token","Protocol Version":"2025-11-25",Client:"MCPJam Inspector v1.0.0",Endpoint:y.serverUrl});n({currentStep:"authenticated_mcp_request",lastRequest:W,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"authenticated_mcp_request",timestamp:Date.now(),request:W}],infoLogs:Y,isInitiatingAuth:!1}),V(50);return;case"authenticated_mcp_request":if(!y.serverUrl||!y.accessToken)throw new Error("Missing server URL or access token");try{const g=await H(y.serverUrl,{method:"POST",headers:lt(p,{Authorization:`Bearer ${y.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":M}),body:JSON.stringify(Dt({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:2}))}),R={status:g.status,statusText:g.statusText,headers:g.headers,body:g.body},E=[...y.httpHistory||[]];if(E.length>0){const G=E[E.length-1];G.response=R,G.duration=Date.now()-(G.timestamp||Date.now())}if(!g.ok){n({lastResponse:R,httpHistory:E,error:Xo(g),isInitiatingAuth:!1});return}let P=k().infoLogs||[];const F=g.headers["content-type"]||"",B=F.includes("text/event-stream");let D=null;if(B&&g.body?.transport==="sse"?D=g.body.mcpResponse:D=g.body,B&&D?.result?.protocolVersion){const G={Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Protocol Version":D.result.protocolVersion};D.result.serverInfo&&(G["Server Name"]=D.result.serverInfo.name,G["Server Version"]=D.result.serverInfo.version),D.result.capabilities&&(G.Capabilities=D.result.capabilities),P=ne(k(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",G)}else if(B)P=ne(k(),"authenticated_mcp_request","mcp-transport","MCP Transport Detected",{Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Content-Type":F,Note:"Server returned streaming response. Initialize response delivered via SSE stream.",Events:g.body?.events?`${g.body.events.length} events parsed`:"No events parsed"});else if(D?.result?.protocolVersion){const G={Transport:"Streamable HTTP","Response Format":"JSON","Protocol Version":D.result.protocolVersion};D.result.serverInfo&&(G["Server Name"]=D.result.serverInfo.name,G["Server Version"]=D.result.serverInfo.version),D.result.capabilities&&(G.Capabilities=D.result.capabilities),P=ne(k(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",G)}n({currentStep:"complete",lastResponse:R,httpHistory:E,infoLogs:P,error:void 0,isInitiatingAuth:!1})}catch(g){const R={status:0,statusText:"Network Error",headers:{},body:{error:g instanceof Error?g.message:String(g)}},E=[...y.httpHistory||[]];if(E.length>0){const P=E[E.length-1];P.response=R,P.duration=Date.now()-(P.timestamp||Date.now())}n({lastResponse:R,httpHistory:E,error:`Authenticated MCP request failed: ${g instanceof Error?g.message:String(g)}`,isInitiatingAuth:!1})}break;case"complete":n({isInitiatingAuth:!1});break;default:n({isInitiatingAuth:!1})}}catch(K){const le=k(),de=It(K),$e=ne(le,le.currentStep,`error-${le.currentStep}-${Date.now()}`,"Step failed",{step:le.currentStep,request:le.lastRequest,response:le.lastResponse,error:de},{level:"error",error:de}),Re=pn(le.httpHistory,de),_e={error:de.message,infoLogs:$e,isInitiatingAuth:!1};Re&&(_e.httpHistory=Re),n(_e)}},startGuidedFlow:async()=>{n({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{n(ea())}};return Q},eI=e=>ai(e);function tI(e){const t=e.requestedScopes??[],r=e.challengedScopes??[],n=[];if(t.length>0&&n.push({label:"requested scopes",value:t.join(" ")}),r.length>0){const i=aA(t,r);n.push({label:"challenged scopes",value:r.join(" ")}),n.push({label:"scope union",value:i.join(" ")})}return n}function rI(e){const t=e.recordedIssuer??e.authorizationServerMetadata?.issuer;return t?[{label:"bound to issuer",value:t}]:[]}function nI(e,t){return ta(e,t,{protocolVersion:"2026-07-28",includesProtectedResourceMetadata:!0,initialMcpMethod:"tools/list",authorizationServerMetadata:{label:"GET Authorization server metadata endpoint",description:"Try OAuth path insertion, OIDC path insertion, OIDC path appending"},pkce:{label:`Generate PKCE (REQUIRED)
93
+ Include resource parameter`,description:"Client generates code verifier and challenge (REQUIRED), includes resource parameter"},resourceValue:eI,dcrNotes:[{label:"Deprecated",value:"DCR is deprecated in 2026-07-28 (PR #2858). Prefer CIMD or a pre-registered client; DCR remains a compatibility fallback for authorization servers without CIMD support."}],clientCredentialsExtras:rI,authorizationRequestExtras:tI})}function zd(e){const t=new URL(e),r=[];if(t.pathname==="/"||t.pathname==="")r.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString()),r.push(new URL("/.well-known/openid-configuration",t.origin).toString());else{const n=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;r.push(new URL(`/.well-known/oauth-authorization-server${n}`,t.origin).toString()),r.push(new URL(`/.well-known/openid-configuration${n}`,t.origin).toString()),r.push(new URL(`${n}/.well-known/openid-configuration`,t.origin).toString())}return r}function Ud(e){const t=e.replace(/[\u0000-\u001f\u007f\u0085\u2028\u2029]+/g," ").trim();return`\`${t.length>256?`${t.slice(0,256)}…`:t}\``}function iI(e,t){let r,n;try{r=new URL(e),n=new URL(t)}catch{return!1}if(r.origin!==n.origin||r.search||r.hash||n.search||n.hash)return!1;const i=a=>a.endsWith("/")?a.slice(0,-1):a,s=i(r.pathname),o=i(n.pathname);return s===o?!1:s===""||s==="/"?o.length>0:o.startsWith(`${s}/`)}function sI(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}function Fd(e,t){return e==null?!1:typeof e!="string"?!0:!sI(e,t)}function qd(e){return typeof e=="string"?`"${e}"`:"a non-string value"}function oI(e){const{advertisedIssuer:t,discoveryUrl:r,tokenEndpoint:n,registrationEndpoint:i,allowPathScopedIssuer:s}=e,o=iI(t,r),a=s&&o,c=a&&Fd(n,t),l=a&&Fd(i,t);return a&&!c&&!l?{accepted:!0,hint:""}:{accepted:!1,hint:c?` The path-scoped authorization server's token endpoint (${qd(n)}) is not on the same origin as its issuer ("${t}"); refusing to send credentials off-origin.`:l?` The path-scoped authorization server's registration endpoint (${qd(i)}) is not on the same origin as its issuer ("${t}"); refusing dynamic registration off-origin.`:o?` The advertised issuer is the same-origin root of the discovery URL — a multi-tenant, path-scoped authorization server. Enable "Path-scoped authorization server" in the server's OAuth configuration (Advanced settings) to allow this.`:""}}function aI(e){const{recordedIssuer:t,returnedIss:r,issParameterSupported:n,enforcePresentIssMismatch:i=!0}=e;if(r!=null&&r!==""){if(t!==void 0&&r!==t){const s=`Authorization response \`iss\` does not match the issuer this flow started with. Recorded from authorization-server metadata: ${Ud(t)}; returned on the callback: ${Ud(r)}.`;return i?{ok:!1,reason:`${s} Refusing to exchange the authorization code; not displaying any server-supplied error parameters (RFC 9207).`}:{ok:!0,warning:`${s} This protocol version does not require RFC 9207 issuer validation, so the flow continues; on 2026-07-28 this stops the flow before the authorization code is redeemed.`}}return{ok:!0}}return n===!0?{ok:!1,reason:"Authorization server advertised `authorization_response_iss_parameter_supported: true` but the callback did not include an `iss` parameter (RFC 9207 requires it)."}:{ok:!0}}var cI=e=>{const{state:t,getState:r,updateState:n,serverUrl:i,serverName:s,redirectUrl:o,requestExecutor:a,scheduleAutoAdvance:c,loadPreregisteredCredentials:l,dynamicRegistration:u,clientIdMetadataUrl:h,customScopes:d,customHeaders:p,resourceMetadataUrl:f,authMode:v,hasClientSecret:m=!1,strictConformance:_=!1,allowPathScopedIssuer:w=!1,resourceIndicatorEnforcement:S="warn",requiredMetadataEnforcement:T="reject",registrationStrategy:C="cimd",emulation:$}=e,M=o,L=fn($,"2026-07-28"),q=la($),X=ua(u??{},$);let ee=h??"";if(C==="dcr"&&!X.client_name)throw new Error("Dynamic registration metadata must include client_name");if(C==="cimd"&&!ee)throw new Error("Client ID metadata URL is required for CIMD registration");C==="cimd"&&(ee=rg(ee));const k=()=>r?r():t,ie=()=>ai(k(),i),H=(y,V={})=>a({url:y,method:V.method||"GET",headers:Tr(V.headers),body:V.body}),oe=y=>{const V=Ko({authorizationServerMetadata:k().authorizationServerMetadata,hasClientSecret:!!(y||m)});if(!V.ok)throw new Error(V.message);return V.method},I=async y=>{const{clientId:V,clientSecret:K}=await l?.({serverName:s,serverUrl:i})??{};if(!V)return;const le=oe(K),de={"Client ID":V,"Client Secret":K||m?"Configured":"Not provided (public client)","Token Auth Method":le,Note:y};return{clientId:V,clientSecret:K||void 0,tokenEndpointAuthMethod:le,infoLogs:ne(k(),"received_client_credentials","preregistered-fallback","Pre-registered Client",de)}},Q={state:t,updateState:n,proceedToNextStep:async()=>{const y=k();n({isInitiatingAuth:!0});const V=K=>{c?.(()=>{Q.proceedToNextStep()},K)};try{switch(y.currentStep){case"idle":{const g=lt(p,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":L,"Mcp-Method":"tools/list"}),R=ks({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}),E={method:"POST",url:i,headers:g,body:R};n({currentStep:"request_without_token",serverUrl:i,lastRequest:E,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_without_token",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),V(50);return}case"request_without_token":if(!y.serverUrl)throw new Error("No server URL available");try{const g=await H(y.serverUrl,{method:"POST",headers:lt(p,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":L,"Mcp-Method":"tools/list"}),body:JSON.stringify(ks({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}))}),R={status:g.status,statusText:g.statusText,headers:g.headers,body:g.body},E=[...y.httpHistory||[]];if(E.length>0){const F=E[E.length-1];F.response=R,F.duration=Date.now()-(F.timestamp||Date.now())}const P=ls({status:g.status,statusText:g.statusText,wwwAuthenticateHeader:g.headers["www-authenticate"],serverMessage:g.body?.error?.message});if(P.kind==="challenged"){const F=g.headers["www-authenticate"],B=cr(F),D=su(B.scope);let G=F?ne(y,"received_401_unauthorized","www-authenticate","WWW-Authenticate Header",{header:F,...D&&D.length>0?{scope:D.join(" ")}:{},"Received from":y.serverUrl||"Unknown"}):y.infoLogs;P.specCompliant||(G=ra(y,G,"received_401_unauthorized",R)),n({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:F||void 0,challengedScopes:D,lastResponse:R,httpHistory:E,infoLogs:G,isInitiatingAuth:!1})}else if(P.kind==="anonymous_allowed"){const F=ne(y,"received_401_unauthorized","optional-auth","Optional Authentication Detected",{message:"Server allows anonymous access",note:"Proceeding with OAuth discovery for authenticated features"});n({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:void 0,lastResponse:R,httpHistory:E,infoLogs:F,isInitiatingAuth:!1})}else throw n({lastResponse:R,httpHistory:E}),new xr(P.message,g.status)}catch(g){throw g instanceof xr?g:new Error(`Failed to request MCP server: ${g instanceof Error?g.message:String(g)}`)}break;case"received_401_unauthorized":{const g=cr(y.wwwAuthenticateHeader);let R=f||g.resource_metadata;if(!R&&y.serverUrl&&(R=uu(y.serverUrl)),!R)throw new Error("Could not determine resource metadata URL");const E={method:"GET",url:R,headers:lt(p,{})};n({currentStep:"request_resource_metadata",resourceMetadataUrl:R,lastRequest:E,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_resource_metadata",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),V(50);return}case"request_resource_metadata":if(!y.serverUrl)throw new Error("No server URL available");const K=[...y.httpHistory||[]];let le=K.length>0&&K[K.length-1]?.step==="request_resource_metadata"&&!K[K.length-1]?.response?K.pop():void 0;const de=[],$e=async(g,R={})=>{const E=typeof g=="string"?g:g.toString(),P=au(i,E,p,Tr(R.headers)),F=le?{...le,timestamp:Date.now(),request:{method:R.method||"GET",url:E,headers:P,body:R.body}}:{step:"request_resource_metadata",timestamp:Date.now(),request:{method:R.method||"GET",url:E,headers:P,body:R.body}};le=void 0,de.push(F);try{const B=await H(E,{method:R.method||"GET",headers:P,body:R.body});F.response={status:B.status,statusText:B.statusText,headers:B.headers,body:B.body},F.duration=Date.now()-F.timestamp;const D={status:B.status,statusText:B.statusText,headers:B.headers},G=typeof B.body=="string"?B.body:JSON.stringify(B.body??{});return new Response(G,D)}catch(B){throw F.error=It(B),F.duration=Date.now()-F.timestamp,B}};try{const g=(f||cr(y.wwwAuthenticateHeader).resource_metadata)&&y.resourceMetadataUrl?{resourceMetadataUrl:y.resourceMetadataUrl}:void 0,R=await Jo(y.serverUrl,g,$e),E=[...K,...de],P=de[de.length-1],F=cu({authorizationServers:R.authorization_servers,fallbackServerUrl:i,protocolVersion:"2026-07-28"}),B=F.authorizationServerUrl;if(F.error&&T!=="observe"){n({resourceMetadata:R,resourceMetadataUrl:P?.request?.url||y.resourceMetadataUrl,lastRequest:P?.request,lastResponse:P?.response,httpHistory:E,error:F.error,isInitiatingAuth:!1});return}let D=y.infoLogs??[];F.error&&(D=ne({...k(),infoLogs:D},"received_resource_metadata","authorization-server-substituted","Derived: Authorization Server (not advertised)",{Finding:F.error,"Using instead":B}));const G=hu({state:y,fallbackServerUrl:i,prmResource:R.resource,enforcement:S,infoLogs:D}),J=G.resourceIndicator;D=G.infoLogs,n({currentStep:"received_resource_metadata",resourceMetadata:R,resourceIndicator:J,resourceMetadataUrl:P?.request?.url||y.resourceMetadataUrl,authorizationServerUrl:B,lastRequest:P?.request,lastResponse:P?.response,httpHistory:E,infoLogs:D,isInitiatingAuth:!1})}catch(g){const R=pn([...K,...de],It(g));throw n({lastResponse:de[de.length-1]?.response,httpHistory:R}),new Error(Zo(g))}break;case"received_resource_metadata":if(!y.authorizationServerUrl)throw new Error("No authorization server URL available");const Re={method:"GET",url:zd(y.authorizationServerUrl)[0],headers:at(p,{})};n({currentStep:"request_authorization_server_metadata",lastRequest:Re,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:Re}],isInitiatingAuth:!1}),V(50);return;case"request_authorization_server_metadata":if(!y.authorizationServerUrl)throw new Error("No authorization server URL available");const _e=zd(y.authorizationServerUrl);let ve=null;const Je=[];let Xe={},Pe=null;for(const g of _e)try{const R=at(p,{}),E=[...y.httpHistory||[]];E.length>0&&(E[E.length-1].request={method:"GET",url:g,headers:R}),n({lastRequest:{method:"GET",url:g,headers:R},httpHistory:E});const P=await H(g,{method:"GET",headers:at(p,{})});if(P.ok){ve=P.body,Xe=P.headers,Pe=P,ve||Je.push({url:g,status:P.status});break}Je.push({url:g,status:P.status})}catch(R){Je.push({url:g,error:R});continue}if(!ve||!Pe)throw new Error(du(Je));if(!ve.issuer)throw new Error(ia);if(ve.issuer!==y.authorizationServerUrl){const g=oI({advertisedIssuer:ve.issuer,discoveryUrl:y.authorizationServerUrl,tokenEndpoint:ve.token_endpoint,registrationEndpoint:ve.registration_endpoint,allowPathScopedIssuer:w});if(!g.accepted)throw new Error(`Authorization server metadata \`issuer\` does not match the authorization server URL it was discovered from (expected "${y.authorizationServerUrl}", got "${ve.issuer}"). RFC 8414 §3.3 requires an exact match; refusing to continue.`+g.hint)}if(!ve.authorization_endpoint)throw new Error("Authorization server metadata missing 'authorization_endpoint'");if(!ve.token_endpoint)throw new Error("Authorization server metadata missing 'token_endpoint'");if(!ve.response_types_supported?.includes("code"))throw new Error("Authorization server does not support 'code' response type");const z={status:Pe.status,statusText:Pe.statusText,headers:Xe,body:ve},se=[...y.httpHistory||[]];if(se.length>0){const g=se[se.length-1];g.response=z,g.duration=Date.now()-(g.timestamp||Date.now())}const ae=ve.code_challenge_methods_supported||[],he=eg(ae,"2026-07-28"),Oe=typeof ve.client_id_metadata_document_supported=="boolean"?ve.client_id_metadata_document_supported:"false (not advertised, defaults to false per spec)";let we=ne(k(),"received_authorization_server_metadata","cimd-support","Derived: CIMD Support",{"CIMD Supported":Oe});if(ve.issuer!==y.authorizationServerUrl&&(we=ne({...k(),infoLogs:we},"received_authorization_server_metadata","path-scoped-issuer","Path-scoped authorization server",{"Discovery URL":y.authorizationServerUrl,"Advertised issuer":ve.issuer,Note:'The advertised issuer is the same-origin root of the discovery URL. Accepted because "Path-scoped authorization server" is enabled for this server; strict RFC 8414 §3.3 conformance requires an exact issuer match, and strict MCP clients may refuse to connect.'},{level:"warning"})),he){if(_||T!=="observe"){n({lastResponse:z,httpHistory:se,infoLogs:we,error:he,isInitiatingAuth:!1});return}console.warn("Authorization server may not support S256 PKCE method. Supported methods:",ae),n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:ve,lastResponse:z,httpHistory:se,infoLogs:we,error:"Warning: Authorization server may not support S256 PKCE method",isInitiatingAuth:!1})}else n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:ve,lastResponse:z,httpHistory:se,infoLogs:we,isInitiatingAuth:!1});break;case"received_authorization_server_metadata":if(!y.authorizationServerMetadata)throw new Error("No authorization server metadata available");if(C==="cimd"){if(y.authorizationServerMetadata.client_id_metadata_document_supported!==!0){n({error:"The authorization server does not support Client ID Metadata Documents (client_id_metadata_document_supported is not advertised in AS metadata). Try using 'dcr' or 'preregistered' registration strategy instead.",isInitiatingAuth:!1});return}n({currentStep:"cimd_prepare",clientId:ee,isInitiatingAuth:!1}),V(800);return}else if(C==="preregistered"){const{clientId:g,clientSecret:R}=await l?.({serverName:s,serverUrl:i})??{};if(!g){n({error:"Pre-registered client ID is required. Please configure OAuth credentials in the server settings.",isInitiatingAuth:!1});return}const E=oe(R),P={"Client ID":g,"Client Secret":R||m?"Configured":"Not provided (public client)","Token Auth Method":E,Note:"Using pre-registered client credentials from server config (skipped DCR)"},F=ne(k(),"received_client_credentials","dcr","Pre-registered Client",P);n({currentStep:"received_client_credentials",clientId:g,clientSecret:R||void 0,tokenEndpointAuthMethod:E,infoLogs:F,isInitiatingAuth:!1})}else if(y.authorizationServerMetadata.registration_endpoint){const g=y.resourceMetadata?.scopes_supported||y.authorizationServerMetadata.scopes_supported,R=Nr($,{customScopes:d,challengedScopes:y.challengedScopes,supportedScopes:g}),E=aa({registrationEndpoint:y.authorizationServerMetadata.registration_endpoint,redirectUri:M,dynamicRegistrationDefaults:{...X,application_type:X.application_type??qA(X.redirect_uris??[M])},scope:R,customHeaders:p}),P=ne(k(),"request_client_registration","dcr-deprecated","DCR is deprecated in 2026-07-28",{Note:"Dynamic Client Registration (RFC 7591) is deprecated as a registration mechanism in 2026-07-28 (PR #2858). It remains a compatibility fallback; prefer CIMD or a pre-registered client where the authorization server supports it."},{level:"warning"});n({currentStep:"request_client_registration",lastRequest:E,lastResponse:void 0,infoLogs:P,httpHistory:[...y.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),V(50);return}else{if(_){n({error:oa,isInitiatingAuth:!1});return}const g=await I("Authorization server did not advertise registration_endpoint; using pre-registered client credentials.");if(!g){n({error:sa,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:g.clientId,clientSecret:g.clientSecret,tokenEndpointAuthMethod:g.tokenEndpointAuthMethod,infoLogs:g.infoLogs,error:void 0,isInitiatingAuth:!1})}break;case"request_client_registration":if(!y.authorizationServerMetadata?.registration_endpoint)throw new Error("No registration endpoint available");if(!y.lastRequest?.body)throw new Error("No client metadata in request");{const g=await ca({request:y.lastRequest,requestExecutor:a,httpHistory:y.httpHistory});if(g.status!=="registered"){if(n({lastResponse:g.response,httpHistory:g.httpHistory,error:g.error,isInitiatingAuth:!1}),_)return;const E=await I(g.fallbackNote);if(!E){n({error:g.errorWithFallbackHint,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:E.clientId,clientSecret:E.clientSecret,tokenEndpointAuthMethod:E.tokenEndpointAuthMethod,infoLogs:E.infoLogs,error:void 0,isInitiatingAuth:!1});break}if(g.missingClientId){n({lastResponse:g.response,httpHistory:g.httpHistory,error:"Dynamic Client Registration response is missing a client_id.",isInitiatingAuth:!1});return}const R=ne(k(),"received_client_credentials","dcr","Dynamic Client Registration",g.infoLogData);n({currentStep:"received_client_credentials",clientId:g.credentials.clientId,clientSecret:g.credentials.clientSecret,tokenEndpointAuthMethod:Yo(g.clientInfo),lastResponse:g.response,httpHistory:g.httpHistory,infoLogs:R,error:void 0,isInitiatingAuth:!1})}break;case"cimd_prepare":n({currentStep:"cimd_fetch_request",isInitiatingAuth:!1}),V(800);return;case"cimd_fetch_request":try{const g={method:"GET",url:ee,headers:Tr(void 0)},R=Date.now(),E=await H(ee,{method:"GET"});if(!E.ok)throw new Error(`CIMD endpoint returned HTTP ${E.status}`);const P={status:E.status,statusText:E.statusText,headers:E.headers,body:E.body};n({currentStep:"cimd_metadata_response",lastRequest:g,lastResponse:P,httpHistory:[...y.httpHistory||[],{step:"cimd_fetch_request",timestamp:R,duration:Date.now()-R,request:g,response:P}],isInitiatingAuth:!1}),V(800);return}catch(g){n({error:`CIMD metadata fetch failed: ${g instanceof Error?g.message:String(g)}. Try using 'dcr' or 'preregistered' registration strategy instead.`,isInitiatingAuth:!1});return}case"cimd_metadata_response":try{const g=y.lastResponse?.body;if(!g||typeof g!="object")throw new Error("CIMD metadata document was not available");if(g.client_id!==ee)throw new Error("CIMD client_id mismatch");const R=y.authorizationServerMetadata?.client_id_metadata_document_supported,E={"Client ID":ee,"Registration Method":"Client ID Metadata Document (CIMD)","Client Name":g.client_name||"MCPJam","Redirect URIs":g.redirect_uris||[],"Token Auth Method":g.token_endpoint_auth_method||"none",Validation:"✓ Metadata fetched and validated",Note:"Server fetched and validated client metadata from URL"};R?E["Server Support"]="✓ Advertised in metadata (client_id_metadata_document_supported: true)":E["Server Support"]="⚠ Not advertised (attempting anyway)";const P=ne(k(),"received_client_credentials","cimd","Client ID Metadata Document",E);n({currentStep:"received_client_credentials",clientId:ee,clientSecret:void 0,tokenEndpointAuthMethod:"none",infoLogs:P,isInitiatingAuth:!1})}catch(g){n({error:`CIMD validation failed: ${g instanceof Error?g.message:String(g)}. Try using 'dcr' or 'preregistered' registration strategy instead.`,isInitiatingAuth:!1});return}break;case"received_client_credentials":const Se=Dr(43),pe=await na(Se),me=ne(k(),"generate_pkce_parameters","pkce-generation","Generate PKCE Parameters",{code_challenge:pe,method:"S256",...q?{resource:ie()}:{resource:"(omitted — emulated client does not send RFC 8707 resource)"}});n({currentStep:"generate_pkce_parameters",codeVerifier:Se,codeChallenge:pe,codeChallengeMethod:"S256",...q?{}:{resourceIndicatorSuppressed:!0},state:Dr(16),recordedIssuer:k().authorizationServerMetadata?.issuer,infoLogs:me,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!y.authorizationServerMetadata?.authorization_endpoint||!y.clientId)throw new Error("Missing authorization endpoint or client ID");const Ee=new URL(y.authorizationServerMetadata.authorization_endpoint);Ee.searchParams.set("response_type","code"),Ee.searchParams.set("client_id",y.clientId),Ee.searchParams.set("redirect_uri",M),Ee.searchParams.set("code_challenge",y.codeChallenge||""),Ee.searchParams.set("code_challenge_method","S256"),Ee.searchParams.set("state",y.state||""),q&&Ee.searchParams.set("resource",ie());const Ge=Nr($,{customScopes:d,challengedScopes:y.challengedScopes,supportedScopes:y.resourceMetadata?.scopes_supported||y.authorizationServerMetadata.scopes_supported});Ge&&Ee.searchParams.set("scope",Ge);const U=ne(k(),"authorization_request","auth-url","Authorization URL",{url:Ee.toString()});n({currentStep:"authorization_request",authorizationUrl:Ee.toString(),authorizationCode:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,requestedScopes:Ge?Ge.split(/\s+/).filter(Boolean):void 0,infoLogs:U,isInitiatingAuth:!1});break;case"authorization_request":n({currentStep:"received_authorization_code",isInitiatingAuth:!1});break;case"received_authorization_code":{if(!y.authorizationCode||y.authorizationCode.trim()===""){n({error:"Authorization code is required. Please paste the code you received from the authorization server.",isInitiatingAuth:!1});return}if(!y.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");const g=aI({recordedIssuer:y.recordedIssuer,returnedIss:y.authorizationResponseIss,issParameterSupported:void 0,enforcePresentIssMismatch:!0});if(!g.ok){n({error:g.reason,isInitiatingAuth:!1});return}const R=Mr({clientId:y.clientId,clientSecret:y.clientSecret,tokenEndpointAuthMethod:zr($,y.tokenEndpointAuthMethod)}),E={grant_type:"authorization_code",code:y.authorizationCode,redirect_uri:M,...R.bodyParams};y.codeVerifier&&(E.code_verifier=y.codeVerifier),q&&(E.resource=ie());const P={method:"POST",url:y.authorizationServerMetadata.token_endpoint,headers:{"Content-Type":"application/x-www-form-urlencoded",...R.headers},body:E};n({currentStep:"token_request",lastRequest:P,lastResponse:void 0,...q?{}:{resourceIndicatorSuppressed:!0},accessToken:void 0,refreshToken:void 0,httpHistory:[...y.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:P}],isInitiatingAuth:!1}),V(50);return}case"token_request":if(!y.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!y.authorizationCode)throw new Error("Missing authorization code");if(!y.codeVerifier)throw new Error("PKCE code_verifier is missing - cannot exchange token");try{const g=Mr({clientId:y.clientId,clientSecret:y.clientSecret,tokenEndpointAuthMethod:zr($,y.tokenEndpointAuthMethod)}),R=new URLSearchParams({grant_type:"authorization_code",code:y.authorizationCode,redirect_uri:M,code_verifier:y.codeVerifier||"",...g.bodyParams});q&&R.set("resource",ie());const E=await H(y.authorizationServerMetadata.token_endpoint,{method:"POST",headers:{...at(p,{"Content-Type":"application/x-www-form-urlencoded"}),...g.headers},body:R.toString()}),P={status:E.status,statusText:E.statusText,headers:E.headers,body:E.body},F=[...y.httpHistory||[]];if(F.length>0){const G=F[F.length-1];G.response=P,G.duration=Date.now()-(G.timestamp||Date.now())}if(!E.ok){n({lastResponse:P,httpHistory:F,authorizationCode:void 0,error:Qo(E),isInitiatingAuth:!1});return}const B=E.body;let D=(k().infoLogs||[]).filter(G=>G.id!=="auth-code"&&G.id!=="oauth-tokens"&&G.id!=="token");if(y.authorizationCode&&(D=[...D,{id:"auth-code",level:"info",step:"authorization_request",label:"Authorization Code",data:{code:y.authorizationCode},timestamp:Date.now()}]),B.access_token){const G={access_token:B.access_token};B.refresh_token&&(G.refresh_token=B.refresh_token),D=[...D,{id:"oauth-tokens",level:"info",step:"token_request",label:"OAuth Tokens",data:G,timestamp:Date.now()}]}if(B.access_token){const G=Lr(B.access_token);if(G){const J={...G};J.exp&&(J.exp=`${J.exp} (${De(J.exp)})`),J.iat&&(J.iat=`${J.iat} (${De(J.iat)})`),J.nbf&&(J.nbf=`${J.nbf} (${De(J.nbf)})`);const Ut={...J};if(J.aud){const Vr=y.serverUrl,ui=(Array.isArray(J.aud)?J.aud:[J.aud]).some(Ra=>Ra===Vr);Ut._validation={expected_audience:Vr,audience_matches:ui,note:ui?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else Ut._validation={note:"⚠ No audience claim found - server should validate token binding"};D=[...D,{id:"token",level:"info",step:"token_request",label:"Access Token (Decoded JWT)",data:Ut,timestamp:Date.now()}]}}if(B.id_token){const G=Lr(B.id_token);if(G){const J={...G};J.exp&&(J.exp=`${J.exp} (${De(J.exp)})`),J.iat&&(J.iat=`${J.iat} (${De(J.iat)})`),J.nbf&&(J.nbf=`${J.nbf} (${De(J.nbf)})`),J.auth_time&&(J.auth_time=`${J.auth_time} (${De(J.auth_time)})`),J._note="OIDC ID Token - Used for user identity verification",D=[...D,{id:"id-token",level:"info",step:"token_request",label:"ID Token (OIDC - Decoded JWT)",data:J,timestamp:Date.now()}]}}n({currentStep:"received_access_token",accessToken:B.access_token,refreshToken:B.refresh_token,tokenType:B.token_type||"Bearer",expiresIn:B.expires_in,lastResponse:P,httpHistory:F,infoLogs:D,error:void 0,isInitiatingAuth:!1})}catch(g){const R={status:0,statusText:"Network Error",headers:{},body:{error:g instanceof Error?g.message:String(g)}},E=[...y.httpHistory||[]];if(E.length>0){const P=E[E.length-1];P.response=R,P.duration=Date.now()-(P.timestamp||Date.now())}n({lastResponse:R,httpHistory:E,error:`Token exchange failed: ${g instanceof Error?g.message:String(g)}`,isInitiatingAuth:!1})}break;case"received_access_token":if(!y.serverUrl||!y.accessToken)throw new Error("Missing server URL or access token");const W={method:"POST",url:y.serverUrl,headers:{Authorization:`Bearer ${y.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":L,"Mcp-Method":"tools/list"},body:ks({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:2})},Y=ne(k(),"authenticated_mcp_request","authenticated-verify","Authenticated MCP Verify Request (tools/list)",{Request:"Stateless tools/list with OAuth bearer token","Protocol Version":"2026-07-28",Client:"MCPJam Inspector v1.0.0",Endpoint:y.serverUrl});n({currentStep:"authenticated_mcp_request",lastRequest:W,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"authenticated_mcp_request",timestamp:Date.now(),request:W}],infoLogs:Y,isInitiatingAuth:!1}),V(50);return;case"authenticated_mcp_request":if(!y.serverUrl||!y.accessToken)throw new Error("Missing server URL or access token");try{const g=await H(y.serverUrl,{method:"POST",headers:lt(p,{Authorization:`Bearer ${y.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":L,"Mcp-Method":"tools/list"}),body:JSON.stringify(ks({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:2}))}),R={status:g.status,statusText:g.statusText,headers:g.headers,body:g.body},E=[...y.httpHistory||[]];if(E.length>0){const G=E[E.length-1];G.response=R,G.duration=Date.now()-(G.timestamp||Date.now())}if(!g.ok){n({lastResponse:R,httpHistory:E,error:Xo(g),isInitiatingAuth:!1});return}let P=k().infoLogs||[];const F=g.headers["content-type"]||"",B=F.includes("text/event-stream");let D=null;if(B&&g.body?.transport==="sse"?D=g.body.mcpResponse:D=g.body,B&&D?.result?.protocolVersion){const G={Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Protocol Version":D.result.protocolVersion};D.result.serverInfo&&(G["Server Name"]=D.result.serverInfo.name,G["Server Version"]=D.result.serverInfo.version),D.result.capabilities&&(G.Capabilities=D.result.capabilities),P=ne(k(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",G)}else if(B)P=ne(k(),"authenticated_mcp_request","mcp-transport","MCP Transport Detected",{Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Content-Type":F,Note:"Server returned streaming response. tools/list verify response delivered via SSE stream.",Events:g.body?.events?`${g.body.events.length} events parsed`:"No events parsed"});else if(D?.result?.protocolVersion){const G={Transport:"Streamable HTTP","Response Format":"JSON","Protocol Version":D.result.protocolVersion};D.result.serverInfo&&(G["Server Name"]=D.result.serverInfo.name,G["Server Version"]=D.result.serverInfo.version),D.result.capabilities&&(G.Capabilities=D.result.capabilities),P=ne(k(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",G)}else if(D?.result){const G=Array.isArray(D.result.tools)?D.result.tools.length:void 0;P=ne(k(),"authenticated_mcp_request","mcp-token-verified","Access token verified (tools/list)",{Transport:"Streamable HTTP","Response Format":"JSON",Result:"Bearer token accepted; tools/list succeeded",...G!==void 0?{"Tools listed":G}:{}})}n({currentStep:"complete",lastResponse:R,httpHistory:E,infoLogs:P,error:void 0,isInitiatingAuth:!1})}catch(g){const R={status:0,statusText:"Network Error",headers:{},body:{error:g instanceof Error?g.message:String(g)}},E=[...y.httpHistory||[]];if(E.length>0){const P=E[E.length-1];P.response=R,P.duration=Date.now()-(P.timestamp||Date.now())}n({lastResponse:R,httpHistory:E,error:`Authenticated MCP request failed: ${g instanceof Error?g.message:String(g)}`,isInitiatingAuth:!1})}break;case"complete":n({isInitiatingAuth:!1});break;default:n({isInitiatingAuth:!1})}}catch(K){const le=k(),de=It(K),$e=ne(le,le.currentStep,`error-${le.currentStep}-${Date.now()}`,"Step failed",{step:le.currentStep,request:le.lastRequest,response:le.lastResponse,error:de},{level:"error",error:de}),Re=pn(le.httpHistory,de),_e={error:de.message,infoLogs:$e,isInitiatingAuth:!1};Re&&(_e.httpHistory=Re),n(_e)}},startGuidedFlow:async()=>{n({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{n(ea())}};return Q};function wL({protocolVersion:e,registrationStrategy:t,flowState:r}){switch(e){case"2025-03-26":return VA(r,t==="cimd"?"dcr":t);case"2025-06-18":return JA(r,t==="cimd"?"dcr":t);case"2025-11-25":return XA(r,t);case"2026-07-28":return nI(r,t);default:throw new Error(`Unknown protocol version: ${e}`)}}function ha(e){return e.replace(/^\[|\]$/g,"").trim().toLowerCase().replace(/\.+$/,"")}function ng(e){const t=e.split(".").map(s=>parseInt(s,10));if(t.length!==4||t.some(s=>!Number.isInteger(s)||s<0||s>255))return!0;const[r,n,i]=t;return r===0||r===10||r===100&&n>=64&&n<=127||r===127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===0&&i===0||r===192&&n===0&&i===2||r===192&&n===88&&i===99||r===192&&n===168||r===198&&(n===18||n===19)||r===198&&n===51&&i===100||r===203&&n===0&&i===113||r>=224&&r<=239||r>=240}function ig(e){let t=e.trim().toLowerCase().split("%")[0];t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1));const r=t.match(/^(.*:)(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(r){const o=[r[2],r[3],r[4],r[5]].map(a=>parseInt(a,10));if(o.some(a=>a<0||a>255))return null;t=`${r[1]}${(o[0]<<8|o[1]).toString(16)}:${(o[2]<<8|o[3]).toString(16)}`}const n=o=>{if(o==="")return[];const a=[];for(const c of o.split(":")){if(!/^[0-9a-f]{1,4}$/.test(c))return null;a.push(parseInt(c,16))}return a},i=t.split("::");if(i.length>2)return null;if(i.length===2){const o=n(i[0]),a=n(i[1]);if(!o||!a)return null;const c=8-o.length-a.length;return c<1?null:[...o,...Array(c).fill(0),...a]}const s=n(t);return s&&s.length===8?s:null}function jd(e,t){return ng(`${e>>8}.${e&255}.${t>>8}.${t&255}`)}function lI(e){const t=ig(e);if(!t||t.slice(0,6).every(n=>n===0)&&t[6]===0&&(t[7]===0||t[7]===1))return!0;const r=t[0]>>8;return(r&254)===252||t[0]>=65152&&t[0]<=65215||r===255||t[0]===8193&&t[1]===3512||t[0]===256&&t[1]===0&&t[2]===0&&t[3]===0?!0:t[0]===100&&t[1]===65435?t[2]===1?!0:jd(t[6],t[7]):t[0]===0&&t[1]===0&&t[2]===0&&t[3]===0&&t[4]===0&&(t[5]===65535||t[5]===0)?jd(t[6],t[7]):!1}function uI(e){const t=ha(e);return/^\d+\.\d+\.\d+\.\d+$/.test(t)?ng(t):t.includes(":")?lI(t):!1}function dI(e){const t=ha(e);return t==="localhost"||t.endsWith(".localhost")?!0:uI(t)}function hI(e){const t=ha(e);return/^\d+\.\d+\.\d+\.\d+$/.test(t)?sg(t):t.includes(":")?pI(t):!1}function sg(e){const t=e.split(".").map(o=>parseInt(o,10));if(t.length!==4||t.some(o=>!Number.isInteger(o)||o<0||o>255))return!0;const[r,n,i,s]=t;return r===0||r===169&&n===254||r===100&&n===100&&i===100&&s===200||r>=224&&r<=239||r>=240}function Hd(e,t){return sg(`${e>>8}.${e&255}.${t>>8}.${t&255}`)}function pI(e){const t=ig(e);return t?t.slice(0,6).every(r=>r===0)&&t[6]===0&&(t[7]===0||t[7]===1)?t[7]===0:t[0]>=65152&&t[0]<=65215||t[0]>>8===255||t[0]===256&&t[1]===0&&t[2]===0&&t[3]===0||t[0]===64768&&t[1]===3778&&t[2]===0&&t[3]===0&&t[4]===0&&t[5]===0&&t[6]===0&&t[7]===596?!0:t[0]===100&&t[1]===65435||t[0]===0&&t[1]===0&&t[2]===0&&t[3]===0&&t[4]===0&&(t[5]===65535||t[5]===0)?Hd(t[6],t[7]):!1:!0}var fI=new Set(["metadata.google.internal","metadata.goog"]);function vI(e){const t=ha(e);return fI.has(t)?!0:hI(t)}function og(e){const t=e.replace(/^\[|\]$/g,"").toLowerCase(),r=t.match(/^::(?:ffff:)?(\d{1,3})\.\d{1,3}\.\d{1,3}\.\d{1,3}$/);if(r)return parseInt(r[1],10)===127;const n=t.match(/^::(?:ffff:)?([0-9a-f]{1,4}):[0-9a-f]{1,4}$/);return n?parseInt(n[1],16)>>8===127:!1}function SL(e){if(!e)return!1;try{const t=new URL(e).hostname;return da(t)||og(t)}catch{return!1}}var pi=class extends Error{url;reason;constructor(e,t,r){super(r),this.name="OAuthOutboundUrlBlockedError",this.url=e,this.reason=t}};function gI(e,t={}){let r;try{r=new URL(e)}catch{throw new pi(e,"invalid-url","Outbound OAuth fetch URL is not a valid absolute URL")}if(r.protocol!=="https:"&&r.protocol!=="http:")throw new pi(e,"invalid-scheme",`Outbound OAuth fetch must be http(s); got "${r.protocol}"`);const n=r.hostname;if(vI(n))throw new pi(e,"private-host",`Refusing outbound OAuth fetch to link-local or cloud-metadata host "${n}"`);if(t.allowPrivateNetwork===!0)return r;if(da(n)||og(n)){if(t.allowLoopback===!0)return r;throw new pi(e,"private-host",`Refusing outbound OAuth fetch to loopback host "${n}" (no loopback opt-in)`)}if(dI(n))throw new pi(e,"private-host",`Refusing outbound OAuth fetch to private/reserved host "${n}"`);return r}var mI=class extends Error{field;constructor(e,t){super(`OAuth response from ${t} carried a redacted \`${e}\`. Trace redaction was applied to data the OAuth flow consumes; a redaction sentinel is a non-empty string, so it would be sent upstream as a credential and rejected as invalid. Redaction belongs to the trace projection layer only.`),this.name="OAuthRedactedCredentialError",this.field=e}},_I=["access_token","refresh_token","id_token","client_secret"],yI=[/^\[redacted\]$/,/^[\s\S]{4}\.\.\.\[redacted\]\.\.\.[\s\S]{2}$/];function bI(e){try{const t=new URL(e.url);return`${t.origin}${t.pathname}`}catch{return"the authorization server"}}function wI(e,t){const r=e?.body;if(!r||typeof r!="object"||Array.isArray(r))return e;const n=r;for(const i of _I){const s=n[i];if(typeof s=="string"&&yI.some(o=>o.test(s)))throw new mI(i,bI(t))}return e}function SI(e){const{protocolVersion:t,allowLoopbackMetadataFetch:r,allowPrivateMetadataFetch:n,...i}=e,s=r??!1,o=n??!1,c={...i,requestExecutor:async l=>(gI(l.url,{allowLoopback:s,allowPrivateNetwork:o}),wI(await i.requestExecutor(l),l)),customHeaders:HA(i.customHeaders,i.emulation)};switch(t){case"2025-03-26":if(e.registrationStrategy==="cimd")throw new Error("CIMD registration is not supported in 2025-03-26 protocol. Use 'dcr' or 'preregistered' instead.");return GA(c);case"2025-06-18":if(e.registrationStrategy==="cimd")throw new Error("CIMD registration is not supported in 2025-06-18 protocol. Use 'dcr' or 'preregistered' instead.");return KA(c);case"2025-11-25":return QA(c);case"2026-07-28":return cI(c);default:throw new Error(`Unknown protocol version: ${t}`)}}function EL(e){switch(e){case"2025-03-26":return"dcr";case"2025-06-18":return"dcr";case"2025-11-25":return"cimd";case"2026-07-28":return"cimd";default:return"dcr"}}function kL(e){switch(e){case"2025-03-26":return["dcr","preregistered"];case"2025-06-18":return["dcr","preregistered"];case"2025-11-25":return["cimd","dcr","preregistered"];case"2026-07-28":return["cimd","dcr","preregistered"];default:return["dcr","preregistered"]}}var RL={"2025-03-26":{label:Es("2025-03-26"),description:"Original MCP OAuth specification with direct discovery",features:["Dynamic Client Registration (DCR) SHOULD be supported","Direct RFC8414 discovery from MCP server base URL","Fallback to default endpoints (/authorize, /token, /register)","PKCE is REQUIRED for all clients","No Protected Resource Metadata (RFC9728)"]},"2025-06-18":{label:Es("2025-06-18"),description:"MCP OAuth specification with resource metadata",features:["Dynamic Client Registration (DCR) SHOULD be supported","Protected Resource Metadata (RFC9728) required","RFC8414 discovery ONLY (no OIDC) with root fallback","PKCE recommended but not strictly enforced"]},"2025-11-25":{label:Es("2025-11-25"),description:"MCP OAuth specification with CIMD support",features:["Client ID Metadata Documents (CIMD) SHOULD be supported","Protected Resource Metadata (RFC9728) required","RFC8414 OR OIDC discovery without root fallback","PKCE strictly required and enforced","Enhanced security with URL-based client IDs"]},"2026-07-28":{label:Es("2026-07-28"),description:"Newest MCP OAuth specification: 2025-11-25 discovery plus OIDC application_type",features:["Client ID Metadata Documents (CIMD) SHOULD be supported","Protected Resource Metadata (RFC9728) required","RFC8414 OR OIDC discovery without root fallback","PKCE strictly required and enforced","SEP-837: OIDC application_type sent on Dynamic Client Registration"]}},EI=["idle","request_without_token","received_401_unauthorized","discovery_start","request_resource_metadata","received_resource_metadata","request_authorization_server_metadata","received_authorization_server_metadata","cimd_prepare","cimd_fetch_request","cimd_metadata_response","request_client_registration","received_client_credentials","generate_pkce_parameters","authorization_request","received_authorization_code","token_request","received_access_token","authenticated_mcp_request","complete","verify_list_tools","verify_call_tool"],kI={idle:{title:"Idle",summary:"The OAuth flow is ready to start.",teachableMoments:["Review your server selection and OAuth configuration before starting."]},request_without_token:{title:"Initial MCP Request",summary:"The client sends an unauthenticated initialize request to discover whether OAuth is required.",teachableMoments:["OAuth flows usually begin with a protected resource request that deliberately lacks credentials.","The response determines which discovery path the client must follow."]},received_401_unauthorized:{title:"401 Unauthorized Received",summary:"The MCP server indicates OAuth is required and often provides discovery hints in WWW-Authenticate.",teachableMoments:["Look for the resource metadata URL or realm in the header to understand where discovery begins."],tips:["If you get 200 instead, the server may allow optional OAuth or anonymous access."]},discovery_start:{title:"Start Discovery",summary:"The client derives authorization server endpoints from the MCP server URL.",teachableMoments:["Legacy servers rely on RFC8414 discovery directly from the MCP base URL.","Understanding how fallback URLs are constructed helps debug missing metadata issues."]},request_resource_metadata:{title:"Request Resource Metadata",summary:"The client requests RFC9728 resource metadata to learn which authorization server to use.",teachableMoments:["Protected resource metadata links the resource to one or more authorization servers.","If this step fails, check the MCP server's well-known configuration and headers."]},received_resource_metadata:{title:"Resource Metadata Received",summary:"The response describes supported authorization servers, scopes, and bearer method details.",teachableMoments:["Validate that the authorization server URL looks correct for the environment you're targeting."]},request_authorization_server_metadata:{title:"Request Authorization Server Metadata",summary:"The client requests the authorization server's well-known metadata endpoint (RFC8414 or OIDC).",teachableMoments:["Different protocol versions prioritize different discovery strategies (path insertion, appending, etc.).","Failure here often points to misconfigured issuer URLs or CORS/proxy issues."]},received_authorization_server_metadata:{title:"Authorization Server Metadata Received",summary:"Inspector validates the authorization, token, and optional registration endpoints.",teachableMoments:["Confirm PKCE methods include S256 for modern flows.","Check the available scopes and grant types to ensure the server supports what you need."]},cimd_prepare:{title:"Prepare CIMD",summary:"Draft protocol: the client prepares to use a Client ID Metadata Document (CIMD).",teachableMoments:["CIMD replaces static client IDs with an HTTPS URL that hosts client metadata."]},cimd_fetch_request:{title:"Authorization Server Fetches CIMD",summary:"The authorization server fetches the client's metadata document over HTTPS.",teachableMoments:["Monitor this step to diagnose TLS or hosting issues with your metadata document."]},cimd_metadata_response:{title:"CIMD Validated",summary:"The client confirms the authorization server successfully read the client metadata document.",teachableMoments:["Ensure redirect URIs declared in the document match the environment you're testing."]},request_client_registration:{title:"Request Dynamic Client Registration",summary:"The client submits metadata to register a public client with the authorization server.",teachableMoments:["Dynamic registration is optional in draft flows but required in earlier specs unless you pre-register.","Watch for HTTP 4xx responses that indicate validation failures."]},received_client_credentials:{title:"Client Credentials Received",summary:"The client stores client_id (and optionally client_secret) for the remainder of the flow.",teachableMoments:["Keep an eye on whether the server returned a secret; public clients should use PKCE instead."]},generate_pkce_parameters:{title:"Generate PKCE Parameters",summary:"The client creates a code verifier and challenge to protect the authorization code exchange.",teachableMoments:["PKCE S256 is required in draft specs and strongly recommended everywhere else."]},authorization_request:{title:"Authorization Request Ready",summary:"The client composes the authorization URL and waits for the user to approve access.",teachableMoments:["Inspect the URL to ensure scopes and redirect URI are what you expect."]},received_authorization_code:{title:"Authorization Code Received",summary:"The user completed consent and the client captured the returned authorization code.",teachableMoments:["State mismatches here usually indicate multiple concurrent authorizations or stale popups."]},token_request:{title:"Request Tokens with Authorization Code",summary:"The client calls the token endpoint with the authorization code and PKCE verifier.",teachableMoments:["Token endpoint errors often reveal scope or client configuration problems."]},received_access_token:{title:"Tokens Received",summary:"The client stores access and refresh tokens for subsequent authenticated MCP requests.",teachableMoments:["Check the token type and expiry to confirm the server honored offline access or refresh tokens."]},authenticated_mcp_request:{title:"Authenticated MCP Request",summary:"The client retries the MCP initialize call with the freshly issued access token.",teachableMoments:["Use this step to validate that MCP servers accept OAuth tokens and return capabilities."]},complete:{title:"Flow Complete",summary:"The client verified the server with OAuth credentials and recorded the final response.",teachableMoments:["Continue exploring with authenticated requests or reset to run the flow again."]},verify_list_tools:{title:"Verify: List Tools",summary:"Connect to the MCP server with the obtained token and list available tools.",teachableMoments:["This step confirms the OAuth token is actually usable for MCP operations."]},verify_call_tool:{title:"Verify: Call Tool",summary:"Execute a tool on the MCP server to confirm end-to-end functionality.",teachableMoments:["Calling a tool validates not just authentication but also authorization scopes."]}};function Vd(e){return kI[e]??{title:e,summary:"No additional information available for this step."}}function _r(e){const t=EI.indexOf(e);return t===-1?Number.MAX_SAFE_INTEGER:t}function RI(e){return JSON.parse(JSON.stringify(e))}function AI(e){return{...e,request:{...e.request,url:tu(e.request.url),headers:kd(e.request.headers),body:Wt(e.request.body)},...e.response?{response:{...e.response,headers:kd(e.response.headers),body:Wt(e.response.body)}}:{},...e.error?{error:{...e.error,...e.error.message?{message:Ir(e.error.message)}:{},details:Wt(e.error.details)}}:{}}}function II(...e){const t=e.filter(r=>r!=null);if(t.length!==0)return Math.max(...t)}function TI(){return{syntheticStepTimestamps:{},lastSyntheticTimestamp:0}}function CI(e,t,r){if(!e)return r;const n=e.syntheticStepTimestamps[t];return typeof n=="number"?n:r}function Bd(e,t,r,n){const i=CI(t,r,n),s=e.get(r);if(s)return s.startedAt=Math.min(s.startedAt,i),s.completedAt=Math.max(s.completedAt??i,n),s;const o={step:r,startedAt:i,completedAt:n};return e.set(r,o),o}function Br(e,t,r,n,i,s){if(!n||e.has(r))return;let o=Date.now();t&&(o=Math.max(o,t.lastSyntheticTimestamp+1),t.syntheticStepTimestamps[r]=o,t.lastSyntheticTimestamp=o);const a=i==null?void 0:s?Wt(i):JSON.parse(JSON.stringify(i));e.set(r,{step:r,startedAt:o,completedAt:o,details:a})}function $I(e,t){if(e!==t.currentStep)return!1;switch(e){case"authorization_request":return!!t.authorizationUrl;case"received_authorization_code":return!!t.authorizationCode;case"received_access_token":return!!t.accessToken;case"complete":return t.currentStep==="complete";default:return!1}}function PI(e){if(!(!e||e.status<400))return Xv(e.body)??`HTTP ${e.status} ${e.statusText}`}function OI(e){if(e.error?.message)return e.error.message;if(e.step==="request_client_registration")return PI(e.response)}function Gd(e){return!e.error||!e.clientId||_r(e.currentStep)<=_r("request_client_registration")?!1:e.error.startsWith("Dynamic Client Registration failed")||e.error.startsWith("Client registration failed:")}function xI(e){const{state:t,context:r,sanitize:n=!0}=e,i=t.error?n?Ir(t.error):t.error:void 0,s={version:1,currentStep:t.currentStep,steps:[],httpHistory:(t.httpHistory??[]).map(u=>n?AI(u):RI(u)),...i?{error:i}:{}},o=_r(t.currentStep),a=new Map;for(const u of t.httpHistory??[]){const h=Bd(a,r,u.step,u.timestamp);h.details||(h.details={request:n?Wt(u.request):u.request,...u.response?{response:n?Wt(u.response):u.response}:{}});const d=OI(u);d&&(h.error=Vc(n?Ir(d):d.slice(0,500)))}for(const u of t.infoLogs??[]){const h=Bd(a,r,u.step,u.timestamp);h.message=u.label;const d=n?Wt(u.data):u.data;d&&typeof d=="object"&&d!==null&&!Array.isArray(d)&&(h.details=d),u.error?.message&&(h.error=n?Ir(u.error.message):u.error.message)}const c=Math.max(Date.now(),...(t.httpHistory??[]).map(u=>u.timestamp),...(t.infoLogs??[]).map(u=>u.timestamp),r?.lastSyntheticTimestamp??0);r&&(r.lastSyntheticTimestamp=Math.max(r.lastSyntheticTimestamp,c)),Br(a,r,"received_client_credentials",!!t.clientId,{clientId:t.clientId},n),Br(a,r,"generate_pkce_parameters",!!t.codeVerifier,{codeVerifier:t.codeVerifier},n),Br(a,r,"authorization_request",!!t.authorizationUrl,{authorizationUrl:t.authorizationUrl},n),Br(a,r,"received_authorization_code",!!t.authorizationCode,t.authorizationCode?{code:t.authorizationCode}:void 0,n),Br(a,r,"received_access_token",!!t.accessToken,{tokenType:t.tokenType,expiresIn:t.expiresIn},n),Br(a,r,"complete",t.currentStep==="complete",void 0,n);const l=a.get("request_client_registration");if(l?.error&&_r(t.currentStep)>_r("request_client_registration")&&t.clientId&&(l.recovered=!0,l.recoveredAt=II(l.recoveredAt,l.completedAt,a.get("received_client_credentials")?.startedAt),l.recoveryMessage="Using pre-registered client credentials after registration failed."),t.error&&!Gd(t)&&!a.has(t.currentStep)){Br(a,r,t.currentStep,!0,void 0,n);const u=a.get(t.currentStep);u&&(u.error=i)}return s.steps=Array.from(a.values()).sort((u,h)=>u.startedAt-h.startedAt||_r(u.step)-_r(h.step)).map(u=>{const h=_r(u.step),d=u.step===t.currentStep&&!!t.error&&!Gd(t),p=u.error??(d?i:void 0),f=u.recovered?"success":p?"error":h<o||t.currentStep==="complete"||$I(u.step,t)?"success":u.step===t.currentStep?"pending":"success";return{step:u.step,title:Vd(u.step).title,status:f,message:u.message??Vd(u.step).summary,...p?{error:p}:{},...u.details?{details:u.details}:{},...u.recovered?{recovered:!0}:{},...u.recoveredAt?{recoveredAt:u.recoveredAt}:{},...u.recoveryMessage?{recoveryMessage:u.recoveryMessage}:{},startedAt:u.startedAt,completedAt:f==="pending"?void 0:u.completedAt}}),s}function Rs(e){return{message:e instanceof Error?e.message:String(e)}}async function AL(e){const{maxSteps:t=40,onAuthorizationRequest:r,onTraceUpdate:n,getState:i,sanitizeTrace:s=!0,...o}=e;let a=e.state;const c=TI(),l=i??(()=>a),u=(v,m=l(),_=c)=>{n?.({trace:xI({state:m,context:_,sanitize:s}),state:m,reason:v})},h=v=>{a={...a,...v},e.updateState(v),u("state_update",a)},d=SI({...o,getState:l,updateState:h});let p=0;for(;l().currentStep!=="complete"&&p<t;){p+=1;const v=l();if(v.currentStep==="authorization_request"){if(!v.authorizationUrl)return h({error:"Authorization URL was not generated."}),{completed:!1,redirected:!1,state:l(),error:{message:"Authorization URL was not generated."}};if(!r)return h({error:"Authorization request requires an authorization handler."}),{completed:!1,redirected:!1,authorizationUrl:v.authorizationUrl,state:l(),error:{message:"Authorization request requires an authorization handler."}};try{const w=await r({authorizationUrl:v.authorizationUrl,state:v});if(w.type==="redirect")return u("redirect"),{completed:!1,redirected:!0,authorizationUrl:v.authorizationUrl,state:l()};h({currentStep:"received_authorization_code",authorizationCode:w.authorizationCode,error:void 0});continue}catch(w){return h({error:Rs(w).message}),{completed:!1,redirected:!1,authorizationUrl:v.authorizationUrl,state:l(),error:Rs(w)}}}const m=v.currentStep;try{await d.proceedToNextStep()}catch(w){return l().error?u("error"):h({error:Rs(w).message}),{completed:!1,redirected:!1,state:l(),error:Rs(w)}}const _=l();if(_.currentStep===m)return _.error?u("error",_):h({error:`Step ${m} did not advance.`}),{completed:!1,redirected:!1,state:l(),error:{message:l().error||`Step ${m} did not advance.`}}}const f=l();return p>=t&&f.currentStep!=="complete"?(h({error:"OAuth login exceeded its step guard."}),{completed:!1,redirected:!1,state:l(),error:{message:"OAuth login exceeded its step guard."}}):(u(f.currentStep==="complete"?"complete":"state_update"),{completed:f.currentStep==="complete",redirected:!1,authorizationUrl:f.authorizationUrl,state:f,...f.error?{error:{message:f.error}}:{}})}function IL(e){const t=NI(e.endsWith(" Configure a pre-registered client or enable DCR on the authorization server.")?e.slice(0,-(Vs.length+1)):e).slice(0,LI);return kA(t)??qI(t)}var MI=160,LI=4e3,DI=46;function NI(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===DI;)t-=1;return t===e.length?e:e.slice(0,t)}var zI=[[/(\bCould not resolve (?:[a-z-]{1,63} ){0,8}?)[^\s"'();]{1,253}(?=[)"',]*(?:;|$))/g,"$1<host>"],[/[^\s"'()]{1,253}(?= resolves to a private or reserved address\b)/g,"<host>"],[/(\bhost \()[^\s)]{1,253}(\))/g,"$1<host>$2"],[/(\bconnection to ")[^\s"]{1,253}(")/g,"$1<host>$2"]],UI=/(?<![\w:.])(?:[0-9a-f]{0,4}:){2,7}[0-9a-f]{0,4}(?![\w:])/gi,FI=/\b(?:\d{1,3}\.){3}\d{1,3}\b/g;function qI(e){return zI.reduce((t,[r,n])=>t.replace(r,n),e.replace(/\bhttps?:\/\/[^\s"'<>)]+/g,"<url>")).replace(UI,"<ip>").replace(FI,"<ip>").replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,"<id>").replace(/\b[A-Za-z0-9_-]{16,}\b/g,t=>/\d/.test(t)?"<id>":t).replace(/\s+/g," ").trim().slice(0,MI)}var TL=["server-initialize","ping","logging-set-level","completion-complete","capabilities-consistent","tools-list","tools-input-schemas-valid","tools-x-mcp-header-declarations-valid","prompts-list","resources-list","protocol-invalid-method-error","localhost-host-rebinding-rejected","localhost-host-valid-accepted","server-sse-polling-session","server-accepts-multiple-post-streams","server-sse-streams-functional","notification-post-accepted","get-stream-or-405","session-id-visible-ascii","post-response-content-type","modern-client-handshake","modern-server-discover","modern-result-type-present","modern-cacheable-result-hints","modern-cache-hint-coverage","modern-cache-hint-values-valid","modern-cache-scope-stable-across-pages","modern-protocol-version-header-mismatch","modern-method-header-mismatch","modern-name-header-mismatch","modern-unsupported-version-error","modern-missing-method-header-rejected","modern-header-names-case-insensitive","modern-undeclared-capability-error","modern-no-session-id","modern-removed-methods-not-found","modern-resource-not-found-invalid-params","modern-resource-read-no-empty-contents","modern-tool-output-schema-conformant","modern-logs-require-log-level","modern-subscription-ack-precedes-notifications","modern-subscription-filter-and-tagging","modern-subscription-graceful-close","wire-schema-valid"],jI={"2025-03-26":"legacy","2025-06-18":"legacy","2025-11-25":"legacy","2026-07-28":"modern"},CL=Object.keys(jI),$L={"server-initialize":["legacy"],ping:["legacy"],"capabilities-consistent":["legacy","modern"],"server-sse-polling-session":["legacy"],"server-accepts-multiple-post-streams":["legacy"],"server-sse-streams-functional":["legacy"],"notification-post-accepted":["legacy"],"get-stream-or-405":["legacy"],"session-id-visible-ascii":["legacy"],"post-response-content-type":["legacy","modern"],"localhost-host-rebinding-rejected":["legacy"],"localhost-host-valid-accepted":["legacy"],"tools-list":["legacy","modern"],"tools-input-schemas-valid":["legacy","modern"],"tools-x-mcp-header-declarations-valid":["modern"],"prompts-list":["legacy","modern"],"resources-list":["legacy","modern"],"logging-set-level":["legacy","modern"],"completion-complete":["legacy","modern"],"protocol-invalid-method-error":["legacy","modern"],"modern-client-handshake":["modern"],"modern-server-discover":["modern"],"modern-result-type-present":["modern"],"modern-cacheable-result-hints":["modern"],"modern-cache-hint-coverage":["modern"],"modern-cache-hint-values-valid":["modern"],"modern-cache-scope-stable-across-pages":["modern"],"modern-protocol-version-header-mismatch":["modern"],"modern-method-header-mismatch":["modern"],"modern-name-header-mismatch":["modern"],"modern-unsupported-version-error":["modern"],"modern-missing-method-header-rejected":["modern"],"modern-header-names-case-insensitive":["modern"],"modern-undeclared-capability-error":["modern"],"modern-no-session-id":["modern"],"modern-removed-methods-not-found":["modern"],"modern-resource-not-found-invalid-params":["modern"],"modern-resource-read-no-empty-contents":["modern"],"modern-tool-output-schema-conformant":["modern"],"modern-logs-require-log-level":["modern"],"modern-subscription-ack-precedes-notifications":["modern"],"modern-subscription-filter-and-tagging":["modern"],"modern-subscription-graceful-close":["modern"],"wire-schema-valid":["legacy","modern"]};function HI(){return"8.19.0"}var PL=HI();function ag(e,t){if(!t||t.pendingCheckIds.length===0)return{scored:[...e],pending:[]};const r=new Set(t.pendingCheckIds),n=[],i=[];for(const s of e)(r.has(s.id)?i:n).push(s);return{scored:n,pending:i}}var VI=95,cg=5,BI={should:2,may:1};function GI(e){const t=e.reduce((r,n)=>r+BI[n.tier],0);return Math.min(t,cg)}function pu(e,t,r,n){const i=e.passed+e.failed+e.couldNotRun,s=GI(t);let o=null;if(i>0){const a=VI*e.passed/i,c=cg-s;o=Math.round(a+c),r!=="passed"?o=Math.min(o,94):t.length>0&&(o=Math.min(o,99))}return{score:o,outcome:r,applicable:i,...e,pending:e.pending??0,advisories:t,advicePointsLost:s,...n!==void 0?{protocolVersion:n}:{}}}function fu(e,t=[],r,n){const{scored:i,pending:s}=ag(e,n),o={passed:i.filter(c=>c.status==="passed").length,failed:i.filter(c=>c.status==="failed").length,couldNotRun:i.filter(Qp).length,notApplicable:i.filter(yy).length,pending:s.length},{outcome:a}=by(i);return pu(o,t,a,r)}function vu(e){const t={passed:fi(e,a=>a.passed),failed:fi(e,a=>a.failed),couldNotRun:fi(e,a=>a.couldNotRun),notApplicable:fi(e,a=>a.notApplicable),pending:fi(e,a=>a.pending??0)},r=e.flatMap(a=>a.advisories??[]),n=e.map(a=>a.outcome),i=n.includes("failed")?"failed":n.includes("incomplete")?"incomplete":"passed",s=e.filter(a=>a.applicable>0),o=new Set(s.map(a=>a.protocolVersion));return pu(t,r,i,s.length>0&&o.size===1?[...o][0]:void 0)}function fi(e,t){return e.reduce((r,n)=>r+t(n),0)}function OL(e){if(e.score===null)return`not scored — 0 applicable checks (${e.notApplicable} not applicable)`;const t=[`${e.passed}/${e.applicable} applicable checks passed`];e.failed>0&&t.push(`${e.failed} failed`),e.couldNotRun>0&&t.push(`${e.couldNotRun} could not run`),e.advisories.length>0&&t.push(`${e.advisories.length} advisor${e.advisories.length===1?"y":"ies"} (−${e.advicePointsLost})`),(e.pending??0)>0&&t.push(`${e.pending} pending (unscored by this profile)`);const r=e.protocolVersion?` [${e.protocolVersion}]`:"";return`${e.score}/100 — ${t.join(", ")}${r}`}function Wd(e){return fu(e.checks,(e.readiness??[]).filter(t=>t.informational!==!0).map(t=>({id:t.id,tier:t.specStrength==="MAY"?"may":"should"})),e.protocolVersion,e.profile)}function lg(e,t,r){const{scored:n}=ag(e,r);return fu(e,n.flatMap(i=>(i.warnings??[]).map((s,o)=>({id:`${i.id}-warning-${o+1}`,tier:"may"}))),t,r)}function Zd(e){return lg(e.checks,e.protocolVersion)}function WI(e){return lg(e.checks,e.discovery.protocolVersion,e.profile)}function Jd(e){return e.outcome==="not-applicable"?pu({passed:0,failed:0,couldNotRun:0,notApplicable:e.steps.length},[],"passed",e.protocolVersion):fu(e.steps.map(t=>({id:t.step,status:t.status,...t.skipReason?{skipReason:t.skipReason}:{},...t.error?.message?{error:{message:t.error.message}}:{}})),[],e.protocolVersion)}var ZI=8;function JI(e){return er(e,0,new WeakSet)}function er(e,t,r){if(e===null)return null;switch(typeof e){case"string":case"boolean":return e;case"number":return Number.isFinite(e)?e:String(e);case"bigint":return e.toString();case"undefined":case"function":case"symbol":return}const n=e;if(r.has(n))return"[circular]";if(t>=ZI)return"[max-depth]";if(n instanceof Date)return n.toISOString();if(n instanceof URL)return n.toString();r.add(n);try{if(Array.isArray(n))return n.map(s=>er(s,t+1,r)??null);if(n instanceof Map)return[...n.entries()].map(([s,o])=>[er(s,t+1,r)??null,er(o,t+1,r)??null]);if(n instanceof Set)return[...n].map(s=>er(s,t+1,r)??null);const i={};if(n instanceof Error){i.name=n.name,i.message=n.message;const s=n;s.code!==void 0&&(i.code=er(s.code,t+1,r)),s.statusCode!==void 0&&(i.statusCode=er(s.statusCode,t+1,r)),s.cause!==void 0&&(i.cause=er(s.cause,t+1,r))}for(const[s,o]of Object.entries(n)){const a=er(o,t+1,r);a!==void 0&&(i[s]=a)}return i}finally{r.delete(n)}}function ug(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Un(e){const t=Object.entries(e).filter(([,r])=>r===void 0?!1:Array.isArray(r)?r.length>0:ug(r)?Object.keys(r).length>0:!0);if(t.length!==0)return JI(Object.fromEntries(t))}function KI(e){if(e.httpAttempts.length!==0)return e.httpAttempts.map(t=>`${`${t.request.method} ${t.request.url}`} → ${t.response?`${t.response.status} ${t.response.statusText}`:"No response"}`).join(`
94
+ `)}function YI(e,t){return{id:e.id,title:e.title,category:e.category,status:e.status,...t?.has(e.id)?{pending:!0}:{},...e.skipReason?{skipReason:e.skipReason}:{},durationMs:e.durationMs,description:e.description,...e.error?.message?{error:e.error.message}:{},...e.details!==void 0||e.error?.details!==void 0?{details:Un({details:e.details,errorDetails:e.error?.details})}:{}}}function XI(e,t){return{id:e.id,title:e.title,category:e.category,status:e.status,...t?.has(e.id)?{pending:!0}:{},...e.skipReason?{skipReason:e.skipReason}:{},durationMs:e.durationMs,description:e.description,...e.error?.message?{error:e.error.message}:{},...e.details!==void 0||e.error?.details!==void 0||e.warnings?.length?{details:Un({details:e.details,errorDetails:e.error?.details,warnings:e.warnings})}:{}}}function QI(e){const t=KI(e);return{id:e.step,title:e.title||e.step,category:"oauth",status:e.status,durationMs:e.durationMs,description:e.summary,...e.error?.message?{error:e.error.message}:{},...e.error?.details!==void 0||e.warnings?.length||e.teachableMoments?.length?{details:Un({errorDetails:e.error?.details,warnings:e.warnings,teachableMoments:e.teachableMoments})}:{},...t?{output:t}:{}}}function Jn(e){const t=e.outcome;return t!=="passed"&&t!=="failed"&&t!=="incomplete"?{}:{outcome:t,...e.incompleteReason?{incompleteReason:e.incompleteReason}:{}}}function gu(e){const t=e.map(r=>Jn(r).outcome??(r.outcome==="not-applicable"||r.passed?"passed":"failed"));if(t.includes("failed"))return{outcome:"failed"};if(t.includes("incomplete")){const r=e.find(n=>Jn(n).outcome==="incomplete");return{outcome:"incomplete",...r?.incompleteReason?{incompleteReason:r.incompleteReason}:{}}}return{outcome:"passed"}}function Kd(e,t,r){return{id:`mcp-${r+1}`,title:t,target:e.serverUrl,passed:e.passed,durationMs:e.durationMs,summary:e.summary,cases:(()=>{const n=new Set(e.profile?.pendingCheckIds??[]);return e.checks.map(i=>YI(i,n))})()}}function Wc(e,t,r,n="apps"){const i=new Set(e.profile?.pendingCheckIds??[]);return{id:`${n}-${r+1}`,title:t,target:e.target,passed:e.passed,durationMs:e.durationMs,summary:e.summary,cases:e.checks.map(s=>XI(s,i))}}function Yd(e,t,r){return{id:`oauth-${r+1}`,title:t,target:e.serverUrl,passed:e.passed,durationMs:e.durationMs,summary:e.summary,cases:e.steps.map(QI)}}function eT(e){return"checks"in e&&!("results"in e)&&"serverUrl"in e&&!("target"in e)}function tT(e){return"checks"in e&&!("results"in e)&&"target"in e}function rT(e){return"checks"in e&&!("results"in e)&&"discovery"in e&&ug(e.discovery)&&"wire"in e.discovery}function nT(e){return"steps"in e&&!("results"in e)}function iT(e){return"results"in e&&"serverUrl"in e&&!("target"in e)&&e.results.length>0&&"checks"in e.results[0]}function sT(e){return"results"in e&&"target"in e}function oT(e){return"results"in e&&"serverUrl"in e&&!("target"in e)&&e.results.length>0&&"steps"in e.results[0]}function aT(e){const t=e[0]?.profile;return t?e.every(r=>r.profile?.profileId===t.profileId&&r.profile?.profileVersion===t.profileVersion&&r.profile?.manifestDigest===t.manifestDigest)?{profile:t}:{}:{}}function cT(e){return"results"in e?{schemaVersion:1,kind:"protocol-conformance",name:e.name,passed:e.passed,...gu(e.results),score:vu(e.results.map(Wd)),...aT(e.results),durationMs:e.durationMs,groups:e.results.map((t,r)=>Kd(t,t.label,r))}:{schemaVersion:1,kind:"protocol-conformance",name:"MCP Protocol Conformance",passed:e.passed,...Jn(e),score:Wd(e),...e.profile?{profile:e.profile}:{},durationMs:e.durationMs,groups:[Kd(e,"MCP Protocol Conformance",0)]}}function lT(e){return"results"in e?{schemaVersion:1,kind:"apps-conformance",name:e.name,passed:e.passed,...gu(e.results),score:vu(e.results.map(Zd)),durationMs:e.durationMs,groups:e.results.map((t,r)=>Wc(t,t.label,r))}:{schemaVersion:1,kind:"apps-conformance",name:"MCP Apps Conformance",passed:e.passed,...Jn(e),score:Zd(e),durationMs:e.durationMs,groups:[Wc(e,"MCP Apps Conformance",0)]}}function uT(e){return"results"in e?{schemaVersion:1,kind:"oauth-conformance",name:e.name,passed:e.passed,...gu(e.results),score:vu(e.results.map(Jd)),durationMs:e.durationMs,groups:e.results.map((t,r)=>Yd(t,t.label,r))}:{schemaVersion:1,kind:"oauth-conformance",name:"OAuth Conformance",passed:e.passed,...Jn(e),score:Jd(e),durationMs:e.durationMs,groups:[Yd(e,`${e.protocolVersion}/${e.registrationStrategy}`,0)]}}function dT(e){return"lanes"in e&&"findings"in e&&"badges"in e&&!("readinessKind"in e)}var hT={kind:"claude-directory-readiness",providerName:"Claude Directory Readiness",isResult:dT,isDispositive:e=>Iy(e)};function pT(e){return e.status==="violated"?"failed":e.status==="satisfied"?"passed":"skipped"}function fT(e,t){const r=t.isDispositive,n=[],i=new Set,s=e.lanes.map(o=>{const a=e.findings.filter(c=>c.lane===o.lane);for(const c of a)i.add(c),!r(c)&&n.push({id:c.id,title:c.title,group:o.lane,kind:c.class,status:c.status,message:c.remediation??c.notEvaluatedReason,details:Un({provenance:c.provenance,source:c.source,derivedFrom:c.derivedFrom,observed:c.details})});return{id:o.lane,title:o.lane,target:e.context.target,passed:o.status==="ready",durationMs:0,summary:o.summary,cases:a.filter(r).map(c=>({id:c.id,title:c.title,category:c.class,status:pT(c),skipReason:c.status==="not-evaluated"?"could-not-run":c.status==="not-applicable"?"not-applicable":void 0,durationMs:0,description:c.remediation,error:c.status==="violated"?c.remediation??"Requirement not satisfied":c.status==="not-evaluated"?c.notEvaluatedReason:void 0,details:Un({provenance:c.provenance,intrusiveness:c.intrusiveness,source:c.source,requiresCapabilities:c.requiresCapabilities,derivedFrom:c.derivedFrom,observed:c.details})}))}});for(const o of e.findings)i.has(o)||n.push({id:o.id,title:o.title,group:o.lane,kind:o.class,status:o.status,message:o.remediation??o.notEvaluatedReason??"reported outside any lane in this result",details:Un({provenance:o.provenance,source:o.source,orphanedLane:o.lane})});return{schemaVersion:1,kind:t.kind,name:t.providerName,passed:e.status==="ready",outcome:e.status==="ready"?"passed":e.status==="not-ready"?"failed":"incomplete",incompleteReason:e.status==="incomplete"?e.summary:void 0,durationMs:e.durationMs,groups:s,advisories:n}}var vT={kind:"openai-directory-readiness",providerName:"OpenAI Plugin Directory Readiness",isResult:e=>xy(e),isDispositive:e=>ef(e)},gT=[vT,hT];function mT(e){return gT.find(t=>t.isResult(e))}function xL(e){const t=mT(e);if(t)return fT(e,t);if(eT(e)||iT(e))return cT(e);if(rT(e))return{schemaVersion:1,kind:"tasks-conformance",name:"MCP Tasks Conformance",passed:e.passed,...Jn(e),score:WI(e),...e.profile?{profile:e.profile}:{},durationMs:e.durationMs,groups:[Wc(e,"MCP Tasks Conformance",0,"tasks")]};if(tT(e)||sT(e))return lT(e);if(nT(e)||oT(e))return uT(e);throw new Error("Unsupported conformance result shape")}var ML=Object.freeze({chatgpt:!0,copilot:!0,mcpjam:!0,claude:!1,"claude-desktop":!1,cursor:!1,codex:!1,goose:!1,slack:!1,vscode:!1,notion:!1}),_T="=?base64?";function yT(e){const t=e.toLowerCase();if(t==="mcp-protocol-version")return"protocol-version";if(t==="mcp-method")return"method";if(t==="mcp-name")return"name";if(t==="mcp-session-id")return"session";if(t==="last-event-id")return"resumption";if(t.startsWith("mcp-param-"))return"param"}function bT(e){const t=globalThis;if(typeof t.atob=="function"){const r=t.atob(e),n=new Uint8Array(r.length);for(let i=0;i<r.length;i+=1)n[i]=r.charCodeAt(i);return new TextDecoder("utf-8",{fatal:!0}).decode(n)}if(t.Buffer)return t.Buffer.from(e,"base64").toString("utf8");throw new Error("no base64 decoder available")}function Bs(e){if(!e.startsWith("=?base64?")||!e.endsWith("?=")||e.length<11)return{raw:e,encoded:!1,value:e};const t=e.slice(9,e.length-2);try{return{raw:e,encoded:!0,value:bT(t)}}catch(r){return{raw:e,encoded:!0,value:e,decodeError:r instanceof Error?r.message:String(r)}}}var wT=new Set(["tools/call","resources/read","prompts/get"]),dg=new Set(["tasks/get","tasks/update","tasks/cancel"]);function ST(e){return e===void 0?!1:wT.has(e)||dg.has(e)}var Xd=["protocol-version","method","name","param","session","resumption"];function ET(e){return e!==void 0&&dg.has(e)?".params.taskId":e==="resources/read"?".params.uri":".params.name"}function kT(e){const t=e.declarations??[],r=LT(t,e.arguments);return t.map(n=>{const i=`${hg}${n.headerName}`,s=r[i];return{header:i.toLowerCase(),displayName:i,expected:s===void 0?void 0:Bs(s).value,bodyField:`.params.arguments${n.path.map(o=>`.${o}`).join("")}`}})}function LL(e,t,r){const n=new Map;for(const[d,p]of Object.entries(e))n.set(d.toLowerCase(),{name:d,value:p});const i=n.get("mcp-protocol-version")?.value??t?.protocolVersion,s=!!i&&yk(i)&&bk(i)&&!!t,o=[],a=new Set,c=s&&t?[{header:"mcp-protocol-version",family:"protocol-version",bodyValue:t.protocolVersion,bodyField:"._meta protocolVersion",required:!0},{header:"mcp-method",family:"method",bodyValue:t.method,bodyField:".method",required:!0},{header:"mcp-name",family:"name",bodyValue:t.name,bodyField:ET(t.method),required:ST(t.method)}]:[];for(const d of c){a.add(d.header);const p=n.get(d.header);if(!p){d.required&&d.bodyValue!==void 0?o.push({name:d.header,family:d.family,status:"missing",bodyValue:d.bodyValue,bodyField:d.bodyField}):!d.required&&t?.method!==void 0&&o.push({name:d.header,family:d.family,status:"not-required"});continue}const f=Bs(p.value),v={name:p.name,family:d.family,raw:p.value,decoded:f.encoded&&!f.decodeError?f.value:void 0};f.decodeError?o.push({...v,status:"undecodable"}):d.bodyValue===void 0?o.push({...v,status:"unchecked"}):f.value===d.bodyValue?o.push({...v,status:"match",bodyField:d.bodyField}):o.push({...v,status:"mismatch",bodyValue:d.bodyValue,bodyField:d.bodyField})}const l=r!==void 0&&"arguments"in r,u=s&&r?kT(r):[],h=s&&r?.declarations!==void 0;for(const d of u){a.add(d.header);const p=n.get(d.header);if(!p){if(!l){o.push({name:d.displayName,family:"param",status:"unchecked"});continue}o.push(d.expected===void 0?{name:d.displayName,family:"param",status:"not-required"}:{name:d.displayName,family:"param",status:"missing",bodyValue:d.expected,bodyField:d.bodyField});continue}const f=Bs(p.value),v={name:p.name,family:"param",raw:p.value,decoded:f.encoded&&!f.decodeError?f.value:void 0};f.decodeError?o.push({...v,status:"undecodable"}):l?d.expected===void 0?o.push({...v,status:"mismatch",bodyValue:"(absent from arguments)",bodyField:d.bodyField}):f.value===d.expected?o.push({...v,status:"match",bodyField:d.bodyField}):o.push({...v,status:"mismatch",bodyValue:d.expected,bodyField:d.bodyField}):o.push({...v,status:"unchecked"})}for(const[d,p]of n){if(a.has(d))continue;const f=yT(p.name);if(!f)continue;const v=Bs(p.value),m=s&&f==="param"&&!!v.decodeError,_=h&&f==="param"&&!m;o.push({name:p.name,family:f,raw:p.value,decoded:v.encoded&&!v.decodeError?v.value:void 0,status:m?"undecodable":_?"undeclared":"unchecked"})}return o.sort((d,p)=>Xd.indexOf(d.family)-Xd.indexOf(p.family)||d.name.localeCompare(p.name))}var Qd="x-mcp-header",hg="Mcp-Param-",RT=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,AT=new Set(["string","integer","boolean","number"]),IT=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],TT=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function CT(e){return e.length===0?"<root>":e.join(".")}function DL(e){const t=[],r=new Map,n=(s,o,a)=>{if(s===null||typeof s!="object")return;const c=s;if(Qd in c){const u=CT(o);if(!a||o.length===0)return`${u}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;const h=c[Qd];if(typeof h!="string"||h.length===0)return`${u}: x-mcp-header MUST be a non-empty string`;if(!RT.test(h))return`${u}: x-mcp-header '${h}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;const d=typeof c.type=="string"?c.type:void 0;if(d===void 0||!AT.has(d))return`${u}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${d??"<none>"}`;const p=h.toLowerCase(),f=r.get(p);if(f!==void 0)return`x-mcp-header '${h}' is not case-insensitively unique (also declared as '${f}')`;r.set(p,h),t.push({path:o,headerName:h,type:d})}const l=c.properties;if(l!==null&&typeof l=="object")for(const[u,h]of Object.entries(l)){const d=n(h,[...o,u],a);if(d!==void 0)return d}for(const u of IT){const h=c[u];if(h===void 0)continue;const d=h!==null&&typeof h=="object"&&TT.has(u),p=Array.isArray(h)?h:d?Object.values(h):[h];for(const f of p){const v=n(f,[...o,`<${u}>`],!1);if(v!==void 0)return v}}},i=n(e,[],!0);return i===void 0?{valid:!0,declarations:t}:{valid:!1,reason:i}}function $T(e){const t=globalThis,r=new TextEncoder().encode(e);if(typeof t.btoa=="function"){let n="";for(const i of r)n+=String.fromCodePoint(i);return t.btoa(n)}if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");throw new Error("no base64 encoder available")}function PT(e){if(e.length===0||e.startsWith("=?base64?")&&e.endsWith("?=")||e!==e.trim())return!0;for(let t=0;t<e.length;t+=1){const r=e.codePointAt(t);if(!(r===9||r>=32&&r<=126))return!0}return!1}function OT(e){if(!PT(e))return e;const t=$T(e);return`${_T}${t}?=`}function xT(e){if(typeof e=="string")return e;if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e)?void 0:String(e)}function MT(e,t){let r=e;for(const n of t){if(r===null||typeof r!="object")return;r=r[n]}return r}function LT(e,t){const r={};for(const n of e){const i=MT(t,n.path);if(i==null)continue;const s=xT(i);s!==void 0&&(r[`${hg}${n.headerName}`]=OT(s))}return r}var DT="tracestate",NT="baggage",zT=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,UT="0".repeat(32),FT="0".repeat(16);function qT(e){if(typeof e!="string")return;const t=zT.exec(e);if(!t)return;const[,r,n,i,s]=t;if(!(r==="ff"||r!=="00")&&!(n===UT||i===FT))return{version:r,traceId:n,spanId:i,flags:s,sampled:(Number.parseInt(s,16)&1)===1}}function jT(e){return qT(e)!==void 0}var HT=32,VT=/^(?:[a-z][a-z0-9_\-*/]{0,255}|[a-z0-9][a-z0-9_\-*/]{0,240}@[a-z][a-z0-9_\-*/]{0,13})$/,BT=/^[\x20-\x2b\x2d-\x3c\x3e-\x7e]{0,255}[\x21-\x2b\x2d-\x3c\x3e-\x7e]$/;function GT(e){if(typeof e!="string"||e.length===0)return!1;const t=e.split(",");if(t.length>HT)return!1;let r=0;for(const n of t){const i=n.trim();if(i.length===0)continue;r+=1;const s=i.indexOf("=");if(s<=0||!VT.test(i.slice(0,s))||!BT.test(i.slice(s+1)))return!1}return r>0}var WT=180,ZT=8192,JT=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,eh=/^[\x21\x23-\x2b\x2d-\x3a\x3c-\x5b\x5d-\x7e]*$/;function KT(e){if(typeof e!="string"||e.length===0||e.length>ZT)return!1;const t=e.split(",");if(t.length>WT)return!1;for(const r of t){const n=r.trim();if(n.length===0)return!1;const[i,...s]=n.split(";"),o=i.indexOf("=");if(o<=0||!JT.test(i.slice(0,o).trim())||!eh.test(i.slice(o+1).trim()))return!1;for(const a of s)if(!eh.test(a.replace(/=/g,"").trim()))return!1}return!0}function YT(e){if(!(!e||!jT(e.traceparent)))return{traceparent:e.traceparent,...GT(e.tracestate)?{tracestate:e.tracestate}:{},...KT(e.baggage)?{baggage:e.baggage}:{}}}function NL(e){if(!e||typeof e!="object")return;const t=r=>{const n=e[r];return typeof n=="string"?n:void 0};return YT({traceparent:t("traceparent")??"",tracestate:t(DT),baggage:t(NT)})}var zL=Rt.MissingRequiredClientCapability,A="u">typeof window?window:void 0,ut="u">typeof globalThis?globalThis:A,rt=ut?.navigator,N=ut?.document,je=ut?.location,Yi=ut?.fetch,mu=ut?.XMLHttpRequest&&"withCredentials"in new ut.XMLHttpRequest?ut.XMLHttpRequest:void 0,th=ut?.AbortController,XT=ut?.CompressionStream,pt=rt?.userAgent;function pg(){return!(!A||A.navigator.onLine===!1)}var vi=typeof globalThis<"u"?globalThis:A;vi&&typeof self>"u"&&(vi.self=vi),vi&&typeof File>"u"&&(vi.File=function(){});var te=A??{},rh="0.9.0",ar={DEBUG:!1,LIB_VERSION:rh,LIB_NAME:"browser-common",JS_SDK_VERSION:rh},Ht=(function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.AiQueue="ai_queue",e.AiCaptureQueue="ai_capture_queue",e.LogsQueue="logs_queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.PushRegistered="push_registered",e.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysInProgress="surveys_in_progress",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e})({}),Zc=(function(e){return e.GZipJS="gzip-js",e.Base64="base64",e})({}),QT=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"],eC=["token"];function ue(e,t){return e.indexOf(t)!==-1}var pa=function(e){return e.trim()},Jc=function(e){return e.replace(/^\$/,"")};function fg(e){var t;const r=[];return(t=JSON.stringify(e,function(n,i){if(typeof i=="bigint")return i.toString();if(typeof i!="function"&&typeof i!="symbol"){if(i instanceof Error)return{name:i.name,message:i.message,stack:i.stack};if(i&&typeof i=="object"){for(;r.length>0&&r[r.length-1]!==this;)r.pop();if(r.includes(i))return"[Circular]";r.push(i)}return i}}))!==null&&t!==void 0?t:"null"}var vg=Object.prototype,_u=vg.hasOwnProperty,fa=vg.toString,ce=Array.isArray||function(e){return fa.call(e)==="[object Array]"},tt=e=>typeof e=="function",be=e=>e===Object(e)&&!ce(e),_t=e=>{if(be(e)){for(const t in e)if(_u.call(e,t))return!1;return!0}return!1},O=e=>e===void 0,ye=e=>fa.call(e)=="[object String]",Oi=e=>ye(e)&&e.trim().length===0,He=e=>e===null,ge=e=>O(e)||He(e),We=e=>fa.call(e)=="[object Number]"&&e==e,tr=e=>We(e)&&e>0,vt=e=>fa.call(e)==="[object Boolean]",tC=e=>ue(QT,e),rC=e=>ue(eC,e);function gg(e){return e===null||typeof e!="object"}function po(e,t){return{}.toString.call(e)===`[object ${t}]`}function ci(e){switch({}.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return mg(e,Error)}}function yu(e){return"u">typeof Event&&mg(e,Event)}function mg(e,t){try{return e instanceof t}catch{return!1}}var nC=[!0,"true",1,"1","yes"],Oa=e=>ue(nC,e),iC=[!1,"false",0,"0","no"];function nh(e,t,r,n,i,s,o){try{var a=e[s](o),c=a.value}catch(l){r(l);return}a.done?t(c):Promise.resolve(c).then(n,i)}function Ue(e){return function(){var t=this,r=arguments;return new Promise(function(n,i){var s=e.apply(t,r);function o(c){nh(s,n,i,o,a,"next",c)}function a(c){nh(s,n,i,o,a,"throw",c)}o(void 0)})}}var sC=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],ih=function(e,t=[]){if(!e)return!1;const r=e.toLowerCase();return sC.concat(t).some(n=>{const i=n.toLowerCase();return r.indexOf(i)!==-1})};function Bt(e,t,r,n,i){return t>r&&(n.warn("min cannot be greater than max."),t=r),We(e)?e>r?(n.warn(" cannot be greater than max: "+r+". Using max value instead."),r):t>e?(n.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(n.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+i),Bt(i??r,t,r,n))}var oC=class{constructor(e){this.C={},this.I=e.I,this.R=Bt(e.bucketSize,0,100,e.$),this.A=Bt(e.refillRate,0,this.R,e.$),this.O=Bt(e.refillInterval,0,864e5,e.$)}F(e,t){const r=Math.floor((t-e.lastAccess)/this.O);r>0&&(e.tokens=Math.min(e.tokens+r*this.A,this.R),e.lastAccess=e.lastAccess+r*this.O)}consumeRateLimit(e){var t;const r=Date.now(),n=String(e);let i=this.C[n];return i?this.F(i,r):(i={tokens:this.R,lastAccess:r},this.C[n]=i),i.tokens===0||(i.tokens--,i.tokens===0&&((t=this.I)===null||t===void 0||t.call(this,e)),i.tokens===0)}stop(){this.C={}}},Kn="Mobile",Xi="Android",fo="Tablet",_g="Android Tablet",yg="iPad",bg="Apple Watch",Gs="Safari",va="BlackBerry",wg="Samsung Internet",Ws="Chrome",Sg="Chrome iOS",Eg="Internet Explorer",kg="Internet Explorer Mobile",Rg="Opera",Ag="Microsoft Edge",Zs="Firefox",Ig="Firefox iOS",vo="Nintendo",go="PlayStation",ga="Xbox",Tg="Android Mobile",Cg="Mobile Safari",xa="Windows",$g="Windows Phone",sh="Nokia",Kc="Ouya",aC="Generic "+Kn.toLowerCase(),Pg="Generic "+fo.toLowerCase(),Yc="Konqueror",Og="Oculus Browser",xg="Vivaldi",Mg="Yandex",Lg="Whale",Dg="DuckDuckGo",Ng="Pale Moon",zg="Waterfox",Xc="Brave",Ug="Claude",Fg="Codex",qg="ChatGPT",jg="Google Search App",Ma=new RegExp("Version/(\\d+(\\.\\d+)?)"),La=new RegExp("(Claude|Codex|ChatGPT)\\/(\\d+(\\.\\d+)?)"),cC=new RegExp(ga,"i"),lC=new RegExp("PlayStation \\w+","i"),uC=new RegExp("Nintendo \\w+","i"),bu=new RegExp("BlackBerry|PlayBook|BB10","i"),dC={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"},Hg=function(e,t,r,n){return t=t||"",(function(i){return i?.brave?Xc:null})(r)||(n?.detectGoogleSearchApp&&ue(e,"GSA/")?jg:ue(e," OPR/")&&ue(e,"Mini")?"Opera Mini":ue(e," OPR/")?Rg:bu.test(e)?va:ue(e,"IEMobile")||ue(e,"WPDesktop")?kg:ue(e,"OculusBrowser")?Og:ue(e,"SamsungBrowser")?wg:ue(e,"Edge")||ue(e,"Edg/")?Ag:ue(e,"Vivaldi/")?xg:ue(e,"YaBrowser/")?Mg:ue(e,"Whale/")?Lg:ue(e,"DuckDuckGo/")||ue(e,"Ddg/")?Dg:ue(e,"Claude/")?Ug:ue(e,"Codex/")?Fg:ue(e,"ChatGPT/")?qg:ue(e,"FBIOS")?"Facebook Mobile":ue(e,"UCWEB")||ue(e,"UCBrowser")?"UC Browser":ue(e,"CriOS")?Sg:ue(e,"CrMo")||ue(e,Ws)?Ws:ue(e,Xi)&&ue(e,Gs)?Tg:ue(e,"FxiOS")?Ig:ue(e.toLowerCase(),Yc.toLowerCase())?Yc:ue(e,"Brave/")?Xc:((i,s)=>s&&ue(s,"Apple")||(function(o){return ue(o,Gs)&&!ue(o,Ws)&&!ue(o,Xi)})(i))(e,t)?ue(e,Kn)?Cg:Gs:ue(e,"PaleMoon/")?Ng:ue(e,"Waterfox/")?zg:ue(e,Zs)?Zs:ue(e,"MSIE")||ue(e,"Trident/")?Eg:ue(e,"Gecko")?Zs:"")},hC={[kg]:[new RegExp("rv:(\\d+(\\.\\d+)?)")],[Ag]:[new RegExp("Edge?\\/(\\d+(\\.\\d+)?)")],[Ws]:[new RegExp("(Chrome|CrMo)\\/(\\d+(\\.\\d+)?)")],[Sg]:[new RegExp("CriOS\\/(\\d+(\\.\\d+)?)")],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/(\\d+(\\.\\d+)?)")],[Gs]:[Ma],[Cg]:[Ma],[Rg]:[new RegExp("(Opera|OPR)\\/(\\d+(\\.\\d+)?)")],[Zs]:[new RegExp("Firefox\\/(\\d+(\\.\\d+)?)")],[Ig]:[new RegExp("FxiOS\\/(\\d+(\\.\\d+)?)")],[Yc]:[new RegExp("Konqueror[:/]?(\\d+(\\.\\d+)?)","i")],[va]:[new RegExp("BlackBerry (\\d+(\\.\\d+)?)"),Ma],[Tg]:[new RegExp("android\\s(\\d+(\\.\\d+)?)","i")],[wg]:[new RegExp("SamsungBrowser\\/(\\d+(\\.\\d+)?)")],[Og]:[new RegExp("OculusBrowser\\/(\\d+(\\.\\d+)?)")],[xg]:[new RegExp("Vivaldi\\/(\\d+(\\.\\d+)?)")],[Mg]:[new RegExp("YaBrowser\\/(\\d+(\\.\\d+)?)")],[Lg]:[new RegExp("Whale\\/(\\d+(\\.\\d+)?)")],[Xc]:[new RegExp("Brave\\/(\\d+(\\.\\d+)?)")],[Ug]:[La],[Fg]:[La],[qg]:[La],[Dg]:[new RegExp("(DuckDuckGo|Ddg)\\/(\\d+(\\.\\d+)?)")],[Ng]:[new RegExp("PaleMoon\\/(\\d+(\\.\\d+)?)")],[zg]:[new RegExp("Waterfox\\/(\\d+(\\.\\d+)?)")],[jg]:[new RegExp("GSA\\/(\\d+(\\.\\d+)?)")],[Eg]:[new RegExp("(rv:|MSIE )(\\d+(\\.\\d+)?)")],Mozilla:[new RegExp("rv:(\\d+(\\.\\d+)?)")]},pC=function(e,t,r,n){const i=Hg(e,t,r,n),s=hC[i];if(O(s))return null;for(let o=0;s.length>o;o++){const a=e.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},oh=[[new RegExp("Xbox; Xbox (.*?)[);]","i"),e=>[ga,e&&e[1]||""]],[new RegExp(vo,"i"),[vo,""]],[new RegExp(go,"i"),[go,""]],[bu,[va,""]],[new RegExp(xa,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[$g,""];if(new RegExp(Kn).test(t)&&!/IEMobile\b/.test(t))return["Windows Mobile",""];const r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=dC[r[1]]||"";return/arm/i.test(t)&&(n="RT"),[xa,n]}return[xa,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>e&&e[3]?["iOS",[e[3],e[4],e[5]||"0"].join(".")]:["iOS",""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=O(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("(Android (\\d+)\\.(\\d+)\\.?(\\d+)?|Android)","i"),e=>e&&e[2]?[Xi,[e[2],e[3],e[4]||"0"].join(".")]:[Xi,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{const t=["Mac OS X",""];return e&&e[1]&&(t[1]=[e[1],e[2],e[3]||"0"].join(".")),t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,["Chrome OS",""]],[/Linux|debian/i,["Linux",""]]],Vg=function(e){for(let t=0;oh.length>t;t++){const[r,n]=oh[t],i=r.exec(e),s=i&&(tt(n)?n(i,e):n);if(s)return s}return["",""]},Bg=function(e){return uC.test(e)?vo:lC.test(e)?go:cC.test(e)?ga:new RegExp(Kc,"i").test(e)?Kc:new RegExp("(Windows Phone|WPDesktop)","i").test(e)?$g:/iPad/.test(e)?yg:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?bg:bu.test(e)?va:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(sh,"i").test(e)?sh:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(e)||/(kf[a-z]+)( bui|\)).+silk\//i.test(e)?"Kindle Fire":/(Android|ZTE)/i.test(e)?new RegExp(Kn).test(e)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(e)||/pixel[\daxl ]{1,6}/i.test(e)&&!/pixel c/i.test(e)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(e)||/lmy47v/i.test(e)&&!/QTAQZ3/i.test(e)?Xi:_g:new RegExp("(pda|Mobile)","i").test(e)?aC:new RegExp(fo,"i").test(e)&&!new RegExp("Tablet pc","i").test(e)?Pg:""},fC=function(e,t){var r;const n=Bg(e);return n===yg||n===_g||n==="Kobo"||n==="Kindle Fire"||n===Pg?fo:n===vo||n===ga||n===go||n===Kc?"Console":n===bg?"Wearable":n?Kn:t?.userAgentDataPlatform==="Android"&&((r=t?.maxTouchPoints)!==null&&r!==void 0?r:0)>0?600>Math.min((i=t?.screenWidth)!==null&&i!==void 0?i:0,(s=t?.screenHeight)!==null&&s!==void 0?s:0)/((o=t?.devicePixelRatio)!==null&&o!==void 0?o:1)?Kn:fo:"Desktop";var i,s,o},Da=/\bFBAV\/(\d+(?:\.\d+)*)/i,ah=[[/\bInstagram(?:[ /](\d+(?:\.\d+)*))?\b/i,"Instagram"],[/\bBarcelona[ /](\d+(?:\.\d+)*)?/i,"Threads"],[/\b(?:MessengerForiOS|(?:FBAN|FB_IAB)\/Orca-Android)\b/i,"Messenger",Da],[/\bFBAN\/EMA\b/i,"Facebook Lite",Da],[/\b(?:FBIOS|(?:FBAN|FB_IAB)\/(?:FB4A|FBIOS))\b/i,"Facebook",Da],[/\bLinkedInApp(?:\]?\/(\d+(?:\.\d+)*))?\b/i,"LinkedIn"],[/\bTwitter(?:Android| for (?:iPhone|iPad|Android))(?:\/(\d+(?:\.\d+)*))?\b/i,"Twitter"],[/\b(?:musical_ly|trill)(?:[_/](\d+\.\d+(?:\.\d+)*))?(?=\b|_)/i,"TikTok",/\bapp_version\/(\d+(?:\.\d+)*)/i],[/\b(?:MicroMessenger|WeChat)\/(\d+(?:\.\d+)*)?/i,"WeChat"],[/\bLine\/(\d+(?:\.\d+)*)?/i,"Line"],[/\bGSA\/(\d+(?:\.\d+)*)?/i,"Google"],[/\[Pinterest\/(?:iOS|Android)\b|\bPinterest(?: for (?:Android(?: Tablet)?|iOS))?\/(\d+(?:\.\d+)*)/i,"Pinterest"],[/\b(?:WA4A|WAiOS)\/(\d+(?:\.\d+)*)?/i,"WhatsApp"],[/\bSnapchat[ /](\d+(?:\.\d+)*)?/i,"Snapchat"],[/\bBing(?:Web|Sapphire)\/(\d+(?:\.\d+)*)?/i,"Bing"],[/\bNAVER\(inapp; search;/i,"Naver",/\bNAVER\(inapp; search;[^;)]*; (\d+(?:\.\d+)*)/i],[/\bKAKAOTALK[ /](\d+\.\d+(?:\.\d+)*)?/i,"KakaoTalk"]],Qc="[Truncated]",us="[Unserializable]";function Fn(e){let t="";for(let r=0;e.length>r;r++){const n=e.charCodeAt(r);if(55296>n||n>56319)t+=56320>n||n>57343?e[r]:"�";else{const i=e.charCodeAt(r+1);56320>i||i>57343?t+="�":(t+=e[r]+e[r+1],r++)}}return t}function Gg(e,t){if(!t)return e;let r=[];try{r=Object.keys(t)}catch{r=[]}for(const n of r){let i;try{i=t[n]}catch{i=us}Object.defineProperty(e,n,{value:i,enumerable:!0,writable:!0,configurable:!0})}return e}var Js=3e5,Wg=class{record(e){if(e.kind==="too-large")return;if(e.kind!=="retry-later")return void this.reset();if(!e.retryAfterMs)return;const t=this.isOpen(),r=Date.now(),n=Math.min(e.retryAfterMs,Js);if(!t)return this.ts=r,void(this.es=r+n);this.es=Math.max(this.es,Math.min(r+n,this.ts+Js))}remainingMs(){const e=Date.now();if(this.ts-5e3>e)return this.reset(),0;const t=Math.min(Js,Math.max(0,this.es-e));return t===0&&this.reset(),t}isOpen(){return this.remainingMs()>0}reset(){this.es=0,this.ts=0}constructor(){this.es=0,this.ts=0}},vC=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ch(e,t){return typeof(r=e)=="string"&&vC.test(r)?e:t();var r}function Zg(e,t){const r=new Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function Ur(e){return e&&e.split("#")[0]}function lh(e){try{return e()}catch{return}}function Jg(e,t){const r=setTimeout(e,t);return r!=null&&r.unref&&r?.unref(),r}function uh(e,t,r){return Kg.apply(this,arguments)}function Kg(){return(Kg=Ue(function*(e,t,r){let n;try{return yield Promise.race([e,new Promise((i,s)=>{n=Jg(()=>{try{r?.(),i()}catch(o){s(o)}},t)})])}finally{clearTimeout(n)}})).apply(this,arguments)}var As,dh,Na;function gC(e){const t=globalThis._posthogChunkIds;if(!t)return;const r=Object.keys(t);return Na&&r.length===dh||(dh=r.length,Na=r.reduce((n,i)=>{As||(As={});const s=As[i];if(s)n[s[0]]=s[1];else{const o=e(i);for(let a=o.length-1;a>=0;a--){const c=o[a],l=c?.filename,u=t[i];if(l&&u){n[l]=u,As[i]=[l,u];break}}}return n},{})),Na}function xi(e){return xi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},xi(e)}function mC(e,t,r){return(t=(function(n){var i=(function(s){if(xi(s)!="object"||!s)return s;var o=s[Symbol.toPrimitive];if(o!==void 0){var a=o.call(s,"string");if(xi(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(s)})(n);return xi(i)=="symbol"?i:i+""})(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function hh(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function b(e){for(var t=1;arguments.length>t;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?hh(Object(r),!0).forEach(function(n){mC(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):hh(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}var _C=class{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){const r=t&&t.mechanism||{handled:!0,type:"generic"},n=this.buildCoercingContext(r,t,0).apply(e),i=this.buildParsingContext(t),s=this.parseStacktrace(n,i);return{$exception_list:this.convertToExceptionList(s,r),$exception_level:"error"}}modifyFrames(e){var t=this;return Ue(function*(){for(const r of e)r.stacktrace&&r.stacktrace.frames&&ce(r.stacktrace.frames)&&(r.stacktrace.frames=yield t.applyModifiers(r.stacktrace.frames));return e})()}coerceFallback(e){var t;return{type:"Error",value:"Unknown error",stack:(t=e.syntheticException)===null||t===void 0?void 0:t.stack,synthetic:!0}}parseStacktrace(e,t){var r;let n,i;if(e.cause!=null&&(n=this.parseStacktrace(e.cause,t)),e.stack!=""&&e.stack!=null)try{i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)}catch{}return b(b({},e),{},{cause:n,stack:i,errors:(r=e.errors)===null||r===void 0?void 0:r.map(s=>this.parseStacktrace(s,t))})}applyChunkIds(e,t){return e.map(r=>(r.filename&&t&&(r.chunk_id=t[r.filename]),r))}applyCoercers(e,t){for(const r of this.coercers)if(r.match(e))return r.coerce(e,t);return this.coerceFallback(t)}applyModifiers(e){var t=this;return Ue(function*(){let r=e;for(const n of t.modifiers)r=yield n(r);return r})()}convertToExceptionList(e,t){const r=[],n=(i,s,o)=>{var a;const c=r.length,l=s===void 0?b(b({type:typeof t.type=="string"&&t.type.length>0?t.type:"generic"},typeof t.handled=="boolean"?{handled:t.handled}:t.handled===void 0?{handled:!0}:{}),{},{synthetic:typeof t.synthetic=="boolean"?t.synthetic:i.synthetic,exception_id:c}):{type:"chained",source:o,synthetic:i.synthetic,exception_id:c,parent_id:s},u={type:i.type,value:i.value,mechanism:l};i.stack&&(u.stacktrace={type:"raw",frames:i.stack}),r.push(u),i.cause&&n(i.cause,c,"cause");for(const h of(a=i.errors)!==null&&a!==void 0?a:[])n(h,c,"member")};return n(e),r}buildParsingContext(e){var t;return{chunkIdMap:gC(this.stackParser),skipFirstLines:(t=e.skipFirstLines)!==null&&t!==void 0?t:1}}getAggregateErrors(e){try{if(ci(e)){let r=Object.getPrototypeOf(e);for(let n=0;r&&100>n;n++){var t;const i=(t=Object.getOwnPropertyDescriptor(r,"constructor"))===null||t===void 0?void 0:t.value;if(typeof i=="function"&&i.name==="AggregateError"){const s=e.errors;return ce(s)?s:void 0}r=Object.getPrototypeOf(r)}}}catch{}}buildCoercingContext(e,t,r=0){let n=0,i=0,s=!1;const o=new Set,a=[],c={},l=(d,p,f=0)=>{const v=u(p,f),m=v.apply;if(v.apply=$=>{a.push(d);try{return m($)}finally{a.pop()}},f>4||f>0&&a.indexOf(d)!==-1)return this.coerceFallback(v);const _=typeof d=="object"&&d!==null||typeof d=="function";if(f===0&&n>=50||_&&o.has(d))return;_&&o.add(d),f===0&&n++;const w=this.getAggregateErrors(d);let S,T;s||(s=!!w);try{if(S=this.applyCoercers(d,v),!S)throw c}catch($){if($===c)return void(f===0&&n--);if(!s)throw $;S=this.coerceFallback(v)}if(!w||n>=50)return S;try{T=w.length}catch{return S}if(!Number.isInteger(T)||0>T||T>4294967295)return S;const C=[];for(let $=0;50>n&&1e3>i&&T>$;$++){let M;i++;try{M=v.next(w[$])}catch{n++,M=this.coerceFallback(u(p+1))}M&&C.push(M)}return b(b({},S),{},{errors:C})},u=(d,p=0)=>b(b({},t),{},{syntheticException:d==0?t.syntheticException:void 0,mechanism:d==0?e:{},apply(f){const v=l(f,d,p+1);if(!v)throw c;return v},next:f=>l(f,d+1)}),h=u(r);return b(b({},h),{},{apply:d=>{var p;return(p=l(d,r))!==null&&p!==void 0?p:this.coerceFallback(h)}})}},yC=/^([a-z][a-z0-9.+-]+):/i,bC=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function wC(e){if(!e||e==="<anonymous>")return!1;const t=yC.exec(e);return!t||bC.includes(t[1].toLowerCase())}function el(e,t,r,n,i){const s={platform:e,filename:t,function:r==="<anonymous>"?"?":r,in_app:wC(t)};return O(n)||(s.lineno=n),O(i)||(s.colno=i),s}var Yg=(e,t)=>{const r=e.indexOf("safari-extension")!==-1,n=e.indexOf("safari-web-extension")!==-1;return r||n?[e.indexOf("@")!==-1?e.split("@")[0]:"?",r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},SC=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,EC=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,kC=/\((\S*)(?::(\d+))(?::(\d+))\)/,RC=(e,t)=>{const r=SC.exec(e);if(r){const[,i,s,o]=r;return el(t,i,"?",+s,+o)}const n=EC.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){const o=kC.exec(n[2]);o&&(n[2]=o[1],n[3]=o[2],n[4]=o[3])}const[i,s]=Yg(n[1]||"?",n[2]);return el(t,s,i,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}},AC=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,IC=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,TC=(e,t)=>{const r=AC.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){const s=IC.exec(r[3]);s&&(r[1]=r[1]||"eval",r[3]=s[1],r[4]=s[2],r[5]="")}let n=r[3],i=r[1]||"?";return[i,n]=Yg(i,n),el(t,n,i,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}},ph=/\(error: (.*)\)/;function wu(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function CC(e){for(let t=1;10>=t;t++){const r=e.length-2*t;if(0>r)break;let n=!0;for(let i=0;t>i;i++)if(!wu(e[r+i],e[r+t+i])){n=!1;break}if(n){for(let i=0;t>i;i++)e[r+i]=e[r+t+i];return e.length=r+t,{start:r,length:t}}}}function $C(e,t){const r=t.start+t.length,n=Qg(e,t);n&&e.splice(r+n===e.length?r:t.start,n)}function Xg(e,t){let r=t.start;for(;r>0&&wu(e[r-1],e[r-1+t.length]);)r--;return t.start-r}function Qg(e,t){const r=t.start+t.length;let n=r;for(;e.length>n&&wu(e[n],e[n-t.length]);)n++;return n-r}function PC(e,t){const r=t[0];let n=e.length-(r?Xg(e,r):0);for(const i of t)n-=Qg(e,i);return n}function OC(e,t,r){for(let n=0;e.length>n;n++){const i=e[(t+n)%e.length],s=e[(r+n)%e.length];if(i!==s)return s>i}return!1}var xC=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){const r=ye(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){const t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return po(e,"DOMException")}isDOMError(e){return po(e,"DOMError")}},MC=class{match(e){return ci(e)}coerce(e,t){var r;const n=this.getStack(e),i=n===void 0?(r=t.syntheticException)===null||r===void 0?void 0:r.stack:void 0,s=!!i;return{type:this.getType(e),value:this.getMessage(e,t),stack:n??i,cause:e.cause?t.next(e.cause):void 0,synthetic:s}}getType(e){return e.name||e.constructor.name}getMessage(e,t){const r=e.message;return String(r.error&&typeof r.error.message=="string"?r.error.message:r)}getStack(e){try{const t=e.stacktrace;if(typeof t=="string"&&t.length>0)return t;const r=e.stack;return typeof r=="string"&&r.length>0?r:void 0}catch{return}}},LC=class{match(e){return!!po(e,"ErrorEvent")&&(e.error!=null||this.ur(e))}coerce(e,t){var r;if(e.error!=null)return t.apply(e.error);const n=t.apply(e.message);return b(b({},n),{},{stack:(r=this.cr(e))!==null&&r!==void 0?r:n.stack,synthetic:!0})}ur(e){return ye(e.message)&&e.message.length>0}cr(e){var t,r;const n=e,i=(t=n.lineno)!==null&&t!==void 0?t:0,s=(r=n.colno)!==null&&r!==void 0?r:0;if(ye(n.filename)&&n.filename.length!==0&&i!==0)return`Error
95
+ at ${n.filename}:${i}:${s}`}},DC=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,NC=class{match(e){return typeof e=="string"}coerce(e,t){var r;const[n,i]=this.getInfos(e);return{type:n??"Error",value:i??e,stack:(r=t.syntheticException)===null||r===void 0?void 0:r.stack,synthetic:!0}}getInfos(e){let t="Error",r=e;const n=e.match(DC);return n&&(t=n[1],r=n[2]),[t,r]}},zC=["fatal","error","warning","log","info","debug"];function em(e,t=40){const r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){const i=r.slice(0,n).join(", ");if(t>=i.length)return n===r.length?i:i.length>t?`${i.slice(0,t)}...`:i}return""}var UC=class{match(e){return typeof e=="object"&&e!==null}coerce(e,t){var r,n;const i=this.getErrorPropertyFromObject(e);return i?t.apply(i):{type:this.getType(e),value:this.getValue(e),stack:(r=this.getStack(e))!==null&&r!==void 0?r:(n=t.syntheticException)===null||n===void 0?void 0:n.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(yu(e))return e.constructor.name;const t="name"in e?e.name:void 0;return ye(t)&&!Oi(t)?t:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let r=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(r+=` with message: '${e.message}'`),r}if("message"in e&&typeof e.message=="string")return e.message;const t=this.getObjectClassName(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${em(e)}`}isSeverityLevel(e){return ye(e)&&!Oi(e)&&zC.indexOf(e)>=0}getStack(e){try{return ye(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:ye(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(const t in e)if({}.hasOwnProperty.call(e,t)){const r=e[t];if(ci(r))return r}}getObjectClassName(e){try{const t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}},FC=class{match(e){return yu(e)}coerce(e,t){var r;const n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${em(e)}`,stack:(r=t.syntheticException)===null||r===void 0?void 0:r.stack,synthetic:!0}}},qC=class{match(e){return gg(e)}coerce(e,t){var r;return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:(r=t.syntheticException)===null||r===void 0?void 0:r.stack,synthetic:!0}}},jC=class{match(e){return po(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!yu(e))return!1;try{const t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){var r;const n=this.getUnhandledRejectionReason(e);return gg(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:(r=t.syntheticException)===null||r===void 0?void 0:r.stack,synthetic:!0}:t.apply(n)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}},mo="$message",_o="$timestamp",HC=new Set([mo,_o]),za={enabled:!0,max_bytes:32768};function yo(e){var t;return e?{enabled:(t=e.enabled)!==null&&t!==void 0?t:za.enabled,max_bytes:BC(e.max_bytes,za.max_bytes)}:b({},za)}var VC=class{constructor(e){this.ns=[],this.ss=0,this.Rr=yo(e)}setConfig(e){this.Rr=yo(e),this.rs()}add(e){const t=(function(n){let i;try{i=fg(n)}catch{return}try{const s=JSON.parse(i);if(!be(s))return;const o=s,a=o[mo],c=o[_o];return!ye(a)||a.trim().length===0||!ye(c)&&!We(c)?void 0:{step:o,json:i}}catch{return}})(e);if(!t)return;const r=(function(n){if("u">typeof TextEncoder)return new TextEncoder().encode(n).length;const i=encodeURIComponent(n);let s=0;for(let o=0;i.length>o;o++)i[o]==="%"?(s+=1,o+=2):s+=1;return s})(t.json);r>this.Rr.max_bytes||(this.ns.push({step:t.step,bytes:r}),this.ss+=r,this.rs())}getAttachable(){return this.ns.map(e=>e.step)}clear(){this.ns=[],this.ss=0}size(){return this.ns.length}rs(){for(;this.ss>this.Rr.max_bytes&&this.ns.length>0;){const e=this.ns.shift();e&&(this.ss-=e.bytes)}}};function BC(e,t){if(!We(e)||e===1/0||e===-1/0)return t;const r=Math.floor(e);return 0>r?t:r}var fh=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};function vh(e){return typeof e=="string"||e}function gh(e){return typeof e=="string"?e:void 0}var GC=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],tm="NativeGzipValidationError",tl=e=>e.length>=2&&e[0]===31&&e[1]===139,mh=(e,t)=>e===Zc.GZipJS||t===Zc.GZipJS||t==="gzip",_h=e=>!(!e||typeof e!="object")&&("name"in e?String(e.name):"")==="NotReadableError",gi,Is=e=>{throw Zg(tm,`Native gzip produced invalid output: ${e}`)},WC=(yh=Ue(function*(e,t){18>e.size&&Is("too-short");const r=new Uint8Array(yield e.slice(0,10).arrayBuffer());tl(r)&&r[2]===8||Is("invalid-header");const n=new DataView(yield e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==(s=>{const o=(()=>{if(gi)return gi;gi=[];for(let c=0;256>c;c++){let l=c;for(let u=0;8>u;u++)l=1&l?3988292384^l>>>1:l>>>1;gi[c]=l>>>0}return gi})();let a=4294967295;for(let c=0;s.length>c;c++)a=o[255&(a^s[c])]^a>>>8;return(4294967295^a)>>>0})(t)&&Is("invalid-crc");const i=t.length>>>0;n.getUint32(4,!0)!==i&&Is("invalid-size")}),function(e,t){return yh.apply(this,arguments)}),yh;function rl(){return rl=Ue(function*(e,t=!0,r){try{const i=new TextEncoder().encode(e),s=new globalThis.CompressionStream("gzip"),o=s.writable.getWriter(),a=o.write(i).then(()=>o.close()).catch((n=Ue(function*(u){try{yield o.abort(u)}catch{}throw u}),function(u){return n.apply(this,arguments)})),c=new Response(s.readable).blob(),[l]=yield Promise.all([c,a]);return yield WC(l,i),l}catch(i){if(r?.rethrow)throw i;return t&&console.error("Failed to gzip compress data",i),null}var n}),rl.apply(this,arguments)}function rm(e,t){if(e==null)return{};var r,n,i=(function(o,a){if(o==null)return{};var c={};for(var l in o)if({}.hasOwnProperty.call(o,l)){if(a.includes(l))continue;c[l]=o[l]}return c})(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(n=0;s.length>n;n++)t.includes(r=s[n])||{}.propertyIsEnumerable.call(e,r)&&(i[r]=e[r])}return i}var ZC={}.propertyIsEnumerable;function bo(e,t){try{return nm(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function Su(e,t,r,n){if(0>=r.remainingNodes)return{stringValue:Qc};if(r.remainingNodes--,vt(e))return{boolValue:e};if(typeof e=="bigint")return(function(i,s){const o=i.toString(),a=BigInt("9223372036854775808");return i>=a||-a>i?(s?.debug(`Attribute ${o} is outside the int64 range; encoding it as a string`),{stringValue:o}):{intValue:o}})(e,t);if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if(typeof BigInt>"u")return{stringValue:String(e)};const i=BigInt(e).toString();return e>=9223372036854776e3||-9223372036854776e3>e?(t?.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i}):{intValue:i}}return{doubleValue:e}}if(typeof e=="string")return{stringValue:Fn(e)};if(typeof e=="function")return{stringValue:"[Function]"};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(r.ancestors.has(e))return{stringValue:"[Circular]"};if(n>=20)return{stringValue:Qc};if(e instanceof Date){const i=e.getTime(),s=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof s=="string"?Fn(s):String(s)}}r.ancestors.add(e);try{try{const i=e.toJSON;if(typeof i=="function")return Su(i.call(e),t,r,n+1)}catch{}return ce(e)?{arrayValue:{values:JC(e,t,r,n+1)}}:{kvlistValue:{values:nm(e,t,r,n+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:Fn(String(e))}}function JC(e,t,r,n){const i=[],s=Math.min(e.length,1e3);let o=0;for(;s>o&&r.remainingNodes>0;o++)try{const a=o in e?e[o]:void 0;if(ge(a))continue;i.push(Su(a,t,r,n))}catch{i.push({stringValue:us})}return e.length>o&&i.push({stringValue:Qc}),i}function nm(e,t,r,n){const i=[];for(const s in e)if(ZC.call(e,s)){if(!s){t?.debug("Dropping an attribute with an empty key");continue}if(i.length>=1e3||0>=r.remainingNodes){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{const o=e[s];if(He(o)||O(o))continue;i.push({key:Fn(s),value:Su(o,t,r,n)})}catch{i.push({key:Fn(s),value:{stringValue:us}})}}return i}function im(e,t,r){return b(b(b(b({},Gg({},e.resourceAttributes)),{},{"service.name":e.serviceName||"unknown_service"},e.environment&&{"deployment.environment":e.environment}),e.serviceVersion&&{"service.version":e.serviceVersion}),{},{"telemetry.sdk.name":t,"telemetry.sdk.version":r})}var KC=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function sm(e,t){const r=Gg({},e),n={};for(const i of KC)({}).hasOwnProperty.call(r,i)&&(n[i]=r[i],delete r[i]);return[...bo(r,t),...bo(n,t)]}var bh={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"},om={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},YC=om.info;function XC(e){try{return Fn(String(e))}catch{return us}}function QC(e,t,r,n){const i=e.level||"info",{text:s,number:o}=om[i]||YC,a=(function(d=Date.now()){return String(d)+"000000"})(We(n)?n:void 0),c={};t.distinctId&&(c.posthogDistinctId=t.distinctId),t.sessionId&&(c.sessionId=t.sessionId),t.windowId&&(c["window.id"]=t.windowId),ge(t.sessionStartTimestamp)||(c.sessionStartTimestamp=String(t.sessionStartTimestamp)),ge(t.lastActivityTimestamp)||(c.lastActivityTimestamp=String(t.lastActivityTimestamp)),t.currentUrl&&(c["url.full"]=t.currentUrl),t.screenName&&(c["screen.name"]=t.screenName),t.appState&&(c["app.state"]=t.appState),t.activeFeatureFlags&&t.activeFeatureFlags.length>0&&(c.feature_flags=t.activeFeatureFlags);const l=b({},c),u=e.attributes;if(u){let d=[];try{d=Object.keys(u)}catch{d=[]}for(const p of d){let f;try{f=u[p]}catch{f=us}Object.defineProperty(l,p,{value:f,enumerable:!0,writable:!0,configurable:!0})}}const h={timeUnixNano:a,observedTimeUnixNano:a,severityNumber:o,severityText:s,body:{stringValue:XC(e.body)},attributes:bo(l,r)};return e.trace_id&&(h.traceId=e.trace_id),e.span_id&&(h.spanId=e.span_id),O(e.trace_flags)||(h.flags=e.trace_flags),h}function am(e,t,r){return im(e,t,r)}function cm(e,t,r,n){return{resourceLogs:[{resource:{attributes:sm(t)},scopeLogs:[{scope:{name:r,version:n},logRecords:e}]}]}}var lm=class{constructor(e){this.ls=e,this.us=0}get pending(){return!!this.hs}arm(e){this.clear(),this.us=Date.now()+e,this.hs=Jg(()=>{this.hs=void 0,this.ls()},e)}armNoEarlierThan(e){this.hs&&Date.now()+e<=this.us||this.arm(e)}clear(){this.hs&&(clearTimeout(this.hs),this.hs=void 0)}};function um(){return .75+.5*Math.random()}function dm(e,t,r,n){const i=Math.min(Math.max(0,t-1),6),s=e*Math.pow(2,i);return Math.round((n===void 0?s:Math.min(s,Math.max(n,e)))*r)}var e$=class{constructor(e,t,r,n,i,s=()=>Promise.resolve(),o){var a;this._instance=e,this.Rr=t,this.$=r,this.cs=n,this.ds=i,this.vs=s,this.fs=o,this.ps=new lm(()=>this.gs()),this.ys=null,this.bs=0,this._s=0,this.ws=new Wg,this.ks=0,this.Ss=1,this.xs=0,this.Cs=0,this.$s=!1,this.Ts=t.maxBufferSize,this.Is=Math.max((a=t.maxQueueSize)!==null&&a!==void 0?a:t.maxBufferSize,t.maxBufferSize),this.Ms=t.flushIntervalMs,this.Es=t.maxBatchRecordsPerPost,this.Ps=t.rateCapWindowMs,this.Rs=t.maxLogsPerInterval}clearQueue(){this._s++,this._instance.setPersistedProperty(Ht.LogsQueue,[])}reset(){this.ps.clear(),this.xs=0,this.Cs=0,this.$s=!1,this.ks=0,this.Ss=1,this.ws.reset(),this.Es=this.Rr.maxBatchRecordsPerPost}onReconnect(){this.ks=0,this.Ss=1,this.ws.isOpen()?this.As()&&this.Fs():this.gs()}captureLog(e,t){var r;if(this._instance.isDisabled||this._instance.optedOut||!e?.body)return;const n=this.Os(e);if(n===null)return;if(!n.body)return void this.$.info("Log was rejected in beforeSend function");if(!this.Ds())return;const i={record:QC(n,(r=t?.context)!==null&&r!==void 0?r:this.cs(),this.$,t?.occurredAtMs)};this.ds(()=>this.Ls(i))}Os(e){const t=this.Rr.beforeSend;if(!t)return e;const r=ce(t)?t:[t];let n=e;for(const i of r)try{const s=i(n);if(!s)return this.$.info("Log was rejected in beforeSend function"),null;n=s}catch(s){return this.$.error("Error in beforeSend function for log:",s),null}return n}Ds(){if(this.Rs===void 0)return!0;const e=Date.now(),t=e-this.xs;return this.Ps>t&&t>=0||(this.xs=e,this.Cs=0,this.$s=!1),this.Rs>this.Cs?(this.Cs++,!0):(this.$s||(this.$.warn(`captureLog dropping logs: exceeded ${this.Rs} logs per ${this.Ps}ms`),this.$s=!0),!1)}flush(){var e=this;return Ue(function*(){if(!e._instance.isDisabled)return e.ys||(e.ys=e.Ns().finally(()=>{e.ys=null})),e.ys})()}Ns(){var e=this;return Ue(function*(){var t;e.ps.clear();let r=(t=e._instance.getPersistedProperty(Ht.LogsQueue))!==null&&t!==void 0?t:[];if(r.length===0)return;const n=r.length;let i=0;for(;r.length>0&&n>i;){var s,o;const a=e._s;e.bs=0;const c=Math.min(r.length,e.Es),l=r.slice(0,c),u=cm(l.map(d=>d.record),e.qs(),(s=e.fs)!==null&&s!==void 0?s:e._instance.getLibraryId(),e._instance.getLibraryVersion()),h=yield e._instance.js(u);if(e._s!==a)return;if(h.kind==="too-large"&&l.length>1)e.Es=Math.max(1,Math.floor(l.length/2)),e.$.warn(`Logs batch of size ${l.length} was too large for the ingestion endpoint, reducing batch size to ${e.Es}`);else if(e.ws.record(h),e.ps.pending&&e.ps.arm(Math.max(e.Ms,e.ws.remainingMs())),h.kind==="retry-later"||(h.kind==="too-large"?e.$.warn("Dropping a single log record with batch size 1 — the record is larger than the server cap and cannot be split further."):h.kind==="ok"&&e.Rr.maxBatchRecordsPerPost>e.Es&&(e.Es=Math.min(e.Rr.maxBatchRecordsPerPost,e.Es+1)),yield e.Bs(l.length),r=(o=e._instance.getPersistedProperty(Ht.LogsQueue))!==null&&o!==void 0?o:[],i+=l.length,h.kind==="fatal"))throw h.error}})()}Bs(e){var t=this;return Ue(function*(){var r;const n=Math.max(0,e-t.bs),i=(r=t._instance.getPersistedProperty(Ht.LogsQueue))!==null&&r!==void 0?r:[];t._instance.setPersistedProperty(Ht.LogsQueue,i.slice(n)),yield t.vs()})()}qs(){return am(this.Rr,this._instance.getLibraryId(),this._instance.getLibraryVersion())}Ls(e){var t;if(this._instance.optedOut)return;const r=(t=this._instance.getPersistedProperty(Ht.LogsQueue))!==null&&t!==void 0?t:[];this.Is>r.length||(r.shift(),this.bs++,this.$.info("Logs queue is full, dropping oldest record.")),r.push(e),this._instance.setPersistedProperty(Ht.LogsQueue,r),this.Ts>r.length||this.ws.isOpen()?this.Fs():this.gs()}Fs(){this.ps.pending||this.ps.arm(Math.max(this.Ms,this.ws.remainingMs()))}Hs(){return Math.max(dm(this.Ms,this.ks,this.Ss,3e4),this.ws.remainingMs())}As(){const e=this._instance.getPersistedProperty(Ht.LogsQueue);return!!e&&e.length>0}shutdown(e){var t=this;return Ue(function*(){t.ps.clear();const r=t.flush().catch(()=>{});e!==void 0?yield uh(r,e):yield r})()}flushWithTimeout(e){var t=this;return Ue(function*(){const r=t.flush();yield uh(r,e,()=>{r.catch(()=>{})})})()}gs(){this.flush().then(()=>{this.ks=0,this.Ss=1},e=>{this.ks++,this.Ss=um(),this.$.error("PostHog logs flush failed:",e)}).finally(()=>{!this._instance.isDisabled&&this.As()&&this.ps.armNoEarlierThan(this.Hs())})}},Ua=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function wh(e){return String(e)+"000000"}function Sh(e,t,r,n){let i="";return n&&(i=Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(n[s])}`).join(",")),`${e}\0${t}\0${r??""}\0${i}`}var t$=class{constructor(e,t,r){this._instance=e,this.Rr=t,this.$=r,this.zs=new Map,this.ps=new lm(()=>this.flush().catch(n=>{this.$.error("Metrics flush failed:",n)})),this.ys=null,this.Us=!1,this.Ws=new Map,this.Vs=new Set,this.ws=new Wg,this.ks=0,this.Ss=1,this.Gs=0}count(e,t=1,r){this.Zs({name:e,type:"count",value:t,unit:r?.unit,attributes:r?.attributes})}gauge(e,t,r){this.Zs({name:e,type:"gauge",value:t,unit:r?.unit,attributes:r?.attributes})}histogram(e,t,r){this.Zs({name:e,type:"histogram",value:t,unit:r?.unit,attributes:r?.attributes})}flush(){var e=this;const t=this.ys,r=(function(){var n=Ue(function*(){t&&(yield t.catch(()=>{})),yield e.Qs()});return function(){return n.apply(this,arguments)}})()().finally(()=>{this.ys===r&&(this.ys=null)});return this.ys=r,r}drainWindow(){if(this.zs.size===0)return null;const e=this.zs;return this.zs=new Map,this.Us=!1,this.Ws=new Map,this.Vs=new Set,this.Js(e)}reset(){this.Gs++,this.ws.reset(),this.ks=0,this.Ss=1,this.ps.clear(),this.zs=new Map,this.ys=null,this.Us=!1,this.Ws=new Map,this.Vs=new Set}Zs(e){if(this._instance.isDisabled||this._instance.optedOut)return;const t=this.Os(e);if(t===null)return;if(!t.name||typeof t.name!="string")return void this.$.warn("Dropping metric with empty name");if(typeof t.value!="number"||!Number.isFinite(t.value))return void this.$.warn(`Dropping metric '${t.name}': value must be a finite number`);if(t.type==="count"&&0>t.value)return void this.$.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let r,n;try{r=t.attributes?b({},t.attributes):void 0,n=Sh(t.type,t.name,t.unit,r)}catch(o){this.$.warn(`Dropping metric '${t.name}': attributes could not be serialized`,o);return}let i=this.zs.get(n);if(!i){if(!this.Ks())return;i={name:t.name,type:t.type,unit:t.unit,attributes:r,windowStartMs:Date.now()},this.zs.set(n,i)}const s=this.Ws.get(t.name);s===void 0?this.Ws.set(t.name,t.type):s===t.type||this.Vs.has(t.name)||(this.Vs.add(t.name),this.$.warn(`Metric name '${t.name}' is already used as a ${s}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`)),this.Xs(i,t.value),this.Fs()}Ks(){return this.Rr.maxSeriesPerFlush>this.zs.size||(this.Us||(this.Us=!0,this.$.warn(`Metric series cap reached (${this.Rr.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}Xs(e,t){switch(e.type){case"count":var r;e.total=((r=e.total)!==null&&r!==void 0?r:0)+t;break;case"gauge":e.last=t;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:new Array(Ua.length+1).fill(0)});const n=e.hist;n.count+=1,n.sum+=t,n.min=Math.min(n.min,t),n.max=Math.max(n.max,t),n.bucketCounts[(function(i,s){for(let o=0;s.length>o;o++)if(s[o]>=i)return o;return s.length})(t,Ua)]+=1;break}}}Os(e){const t=this.Rr.beforeSend;if(!t)return e;const r=ce(t)?t:[t];let n=e;for(const i of r)try{const s=i(n);if(!s)return this.$.info("Metric was rejected in beforeSend function"),null;n=s}catch(s){return this.$.error("Error in beforeSend function for metric:",s),null}return n}Fs(){this.ps.pending||this.ps.arm(this.Hs())}Hs(){return Math.max(dm(this.Rr.flushIntervalMs,this.ks,this.Ss,3e4),this.ws.remainingMs())}Qs(){var e=this;return Ue(function*(){if(e.ps.clear(),e.zs.size===0)return;const t=e.zs;e.zs=new Map,e.Us=!1,e.Ws=new Map,e.Vs=new Set;const r=e.Gs,n=yield e._instance.Ys(e.Js(t));if(r===e.Gs)switch(e.ws.record(n),n.kind==="retry-later"?(e.ks++,e.Ss=um()):(e.ks=0,e.Ss=1),e.ps.pending&&e.ps.arm(e.Hs()),n.kind){case"ok":return;case"retry-later":e.ho(t),e.ps.armNoEarlierThan(e.Hs());return;case"too-large":e.$.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":e.$.error("Failed to send metrics batch:",n.error);return}})()}Js(e){return t=this.vo(e),r=(function(s,o,a){return im(s,o,a)})(this.Rr,this._instance.getLibraryId(),this._instance.getLibraryVersion()),n=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:sm(r)},scopeMetrics:[{scope:{name:n,version:i},metrics:t}]}]};var t,r,n,i}vo(e){const t=wh(Date.now()),r=new Map;for(const o of e.values()){var n;const a=Sh(o.type,o.name,o.unit,void 0);let c=r.get(a);c||(c=b({name:o.name},o.unit&&{unit:o.unit}),o.type==="count"?c.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:o.type==="gauge"?c.gauge={dataPoints:[]}:c.histogram={aggregationTemporality:1,dataPoints:[]},r.set(a,c));const l=bo((n=o.attributes)!==null&&n!==void 0?n:{},this.$),u=wh(o.windowStartMs);if(o.type==="count"){var i;const h={attributes:l,startTimeUnixNano:u,timeUnixNano:t,asDouble:(i=o.total)!==null&&i!==void 0?i:0};c.sum.dataPoints.push(h)}else if(o.type==="gauge"){var s;const h={attributes:l,timeUnixNano:t,asDouble:(s=o.last)!==null&&s!==void 0?s:0};c.gauge.dataPoints.push(h)}else o.hist&&c.histogram.dataPoints.push({attributes:l,startTimeUnixNano:u,timeUnixNano:t,count:o.hist.count,sum:o.hist.sum,min:o.hist.min,max:o.hist.max,bucketCounts:o.hist.bucketCounts,explicitBounds:Ua})}return Array.from(r.values())}ho(e){for(const[n,i]of e){const s=this.zs.get(n);if(s)switch(s.windowStartMs=Math.min(s.windowStartMs,i.windowStartMs),s.type){case"count":var t,r;s.total=((t=s.total)!==null&&t!==void 0?t:0)+((r=i.total)!==null&&r!==void 0?r:0);break;case"gauge":break;case"histogram":if(i.hist)if(s.hist){s.hist.count+=i.hist.count,s.hist.sum+=i.hist.sum,s.hist.min=Math.min(s.hist.min,i.hist.min),s.hist.max=Math.max(s.hist.max,i.hist.max);for(let o=0;s.hist.bucketCounts.length>o;o++)s.hist.bucketCounts[o]+=i.hist.bucketCounts[o]}else s.hist=i.hist}else this.Ks()&&this.zs.set(n,i)}}},hm=(e,{debugEnabled:t}={})=>{const r={N(n,...i){A&&(ar.DEBUG||A.POSTHOG_DEBUG||t)&&!O(A.console)&&A.console&&("__rrweb_original__"in A.console[n]?A.console[n].__rrweb_original__:A.console[n])(e,...i)},debug(...n){r.N("debug",...n)},info(...n){r.N("log",...n)},warn(...n){r.N("warn",...n)},error(...n){r.N("error",...n)},critical(...n){console.error(e,...n)},uninitializedWarning(n){r.error(`You must initialize PostHog before calling ${n}`)},createLogger:(n,i)=>hm(`${e} ${n}`,i)};return r},j=hm("[PostHog.js]"),Be=j.createLogger,r$=Be("[ExternalScriptsLoader]"),wo=e=>{const t=N?.querySelectorAll("script");if(t){for(let r=0;t.length>r;r++)if(t[r].src===e||t[r].getAttribute("src")===e)return t[r]}},Qr=(e,t,r)=>{if(e.config.disable_external_dependency_loading)return r$.warn(`${t} was requested but loading of external scripts is disabled.`),r("Loading of external scripts is disabled");const n=wo(t);if(n){if(n.__posthog_loading_callback_fired)return r();const s=n.__posthog_loading_error;return s?r(s):(n.addEventListener("load",o=>{n.__posthog_loading_callback_fired=!0,r(void 0,o)}),void n.addEventListener("error",o=>{n.__posthog_loading_error=o,r(o)}))}const i=()=>{if(!N)return r("document not found");if(wo(t))return Qr(e,t,r);let s=N.createElement("script");if(s.type="text/javascript",s.crossOrigin="anonymous",s.src=t,s.onload=a=>{s.__posthog_loading_callback_fired=!0,r(void 0,a)},s.onerror=a=>{s.__posthog_loading_error=a,r(a)},e.config.prepare_external_dependency_script&&(s=e.config.prepare_external_dependency_script(s)),!s)return r("prepare_external_dependency_script returned null");if(e.config.external_scripts_inject_target==="head")N.head.appendChild(s);else{const a=N.querySelectorAll("body > script");var o;a.length>0?(o=a[0].parentNode)===null||o===void 0||o.insertBefore(s,a[0]):N.body.appendChild(s)}};N?.body?i():N?.addEventListener("DOMContentLoaded",i)},Fa={},Eh=(e,t)=>{let r=`/static/${t}.js?v=${e.version}`;return t==="toolbar"&&(r=`${r}&t=${Math.floor(Date.now()/3e5)*3e5}`),e.requestRouter.endpointFor("assets",r)};te.__PosthogExtensions__=te.__PosthogExtensions__||{},te.__PosthogExtensions__.loadExternalDependency=(e,t,r)=>{if(t==="remote-config"){const i=e.requestRouter.endpointFor("assets",`/array/${e.config.token}/config.js`);Qr(e,i,r);return}const n=e.config.strict_script_versioning;if(n){const i=e.requestRouter.endpointFor("assets",`/static/${e.version}/${t}.js`),s=Fa[i];if(n==="fallback"&&s){if(wo(s))return void Qr(e,s,r);delete Fa[i]}Qr(e,i,n==="fallback"?(o,a)=>{if(o)if(typeof o=="string")r(o);else{var c;const l=Eh(e,t);Fa[i]=l;const u=wo(i);u==null||(c=u.parentNode)===null||c===void 0||c.removeChild(u),Qr(e,l,r)}else r(void 0,a)}:r);return}Qr(e,Eh(e,t),r)},te.__PosthogExtensions__.loadSiteApp=(e,t,r)=>{const n=e.requestRouter.endpointFor("api",t);Qr(e,n,r)},ar.DEBUG=!1,ar.LIB_VERSION="1.434.12",ar.LIB_NAME="web";var et=ar,n$="$people_distinct_id",Pt="distinct_id",Eu="$device_id",qa="$device_model",So="__alias",i$="__cmpns",kh="$fbc",qn="$fbc_persistence",Rh="$fbp",Mi="$fbp_persistence",nl="__timers",pm="$autocapture_disabled_server_side",il="$heatmaps_enabled_server_side",sl="$exception_capture_enabled_server_side",fm="$error_tracking_suppression_rules",ol="$error_tracking_capture_extension_exceptions",al="$web_vitals_enabled_server_side",ku="$dead_clicks_enabled_server_side",Ru="$product_tours_enabled_server_side",vm="$logs_capture_enabled_server_side",gm="$web_vitals_allowed_metrics",Li="$session_recording_remote_config",s$="$session_recording_enabled_server_side",o$="$replay_sample_rate",a$="$replay_override_sampling",c$="$replay_override_linked_flag",l$="$replay_override_url_trigger",u$="$replay_override_event_trigger",Mn="$sesid",mm="$session_is_sampled",d$="$session_past_minimum_duration",h$="$session_recording_url_trigger_activated_session",p$="$session_recording_event_trigger_activated_session",f$="$debug_first_full_snapshot_timestamp",v$="$sess_rec_flush_size",Mt="$enabled_feature_flags",ir="$active_feature_flags",cl="$early_access_features",ln="$feature_flag_details",wr="$feature_flag_payloads",un="$feature_flag_request_id",Di="$minimal_flag_called_events",qt="$override_feature_flags",en="$override_feature_flag_payloads",Sr="$stored_person_properties",Er="$stored_group_properties",_m="$groups",ll="$surveys",Eo="$surveys_loaded_at",ym="$surveys_activated",bm="$surveys_activated_session",wm="$surveys_activated_timestamps",ul="ph_product_tours",g$="$product_tours_activated",m$="$product_tours_activated_session",_$="$conversations_widget_session_id",y$="$conversations_ticket_id",b$="$conversations_widget_state",w$="$conversations_user_traits",kr="$flag_call_reported",Ti="$flag_call_reported_session_id",Qi="$feature_flag_errors",Cr="$feature_flag_evaluated_at",ft="$user_state",dl="$client_session_props",S$="$capture_rate_limit",Sm="$initial_campaign_params",Em="$initial_referrer_info",Ln="$initial_person_info",Au="$epp",ja="$posthog_cookieless",km="$cookieless_mode",Rm="$sdk_debug_extensions_init_method",Am="$sdk_debug_extensions_init_time_ms",Im="$sdk_debug_recording_script_not_loaded",Tm="$sdk_debug_replay_stale_config",E$="$sdk_debug_replay_event_trigger_status",k$="$sdk_debug_replay_linked_flag_trigger_status",R$="$sdk_debug_replay_matched_recording_trigger_groups",A$="$sdk_debug_replay_pending_trigger_conditions",I$="$sdk_debug_replay_remote_trigger_matching_config",T$="$sdk_debug_replay_trigger_groups_count",C$="$sdk_debug_replay_url_trigger_status",$$="$session_recording_start_reason",Iu="PostHog loadExternalDependency extension not found.",sr="anonymous",Ks="identified",Cm="identified_only",es="visibilitychange",ko="beforeunload",Tu="$pageview",Ah="$pageleave",$m="$identify",Ih="$groupidentify";function Dn(e,t){ce(e)&&e.forEach(t)}function Ce(e,t){if(!ge(e))if(ce(e))e.forEach(t);else if((r=>r instanceof FormData)(e))e.forEach((r,n)=>t(r,n));else for(const r in e)_u.call(e,r)&&t(e[r],r)}var Le=function(e,...t){for(const r of t)for(const n in r)r[n]!==void 0&&(e[n]=r[n]);return e};function Ys(e){const t=Object.keys(e);let r=t.length;const n=new Array(r);for(;r--;)n[r]=[t[r],e[t[r]]];return n}var P$=function(e){return function(...t){try{return e.apply(this,t)}catch(r){j.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),j.critical(r)}}},Cu=function(e){const t={};return Ce(e,function(r,n){(ye(r)&&r.length>0||We(r))&&(t[n]=r)}),t};function Pm(e){const t=b({},e);for(const r of["name","message","stack","cause","errors"])try{r in e&&(t[r]=e[r])}catch{}return t}var O$=["herokuapp.com","vercel.app","netlify.app"];function x$(e){const t=e?.hostname;if(!ye(t))return!1;const r=t.split(".").slice(-2).join(".");for(const n of O$)if(r===n)return!1;return!0}function Ie(e,t,r,n){const{capture:i=!1,passive:s=!0}=n??{};e?.addEventListener(t,r,{capture:i,passive:s})}function hl(e){return e.name==="ph_toolbar_internal"}var Ni=e=>{if(N){try{const t=e+"=",r=N.cookie.split(";").filter(n=>n.length);for(let n=0;r.length>n;n++){let i=r[n];for(;i.charAt(0)==" ";)i=i.substring(1,i.length);if(i.indexOf(t)===0)return decodeURIComponent(i.substring(t.length,i.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(e){return 0>e?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return We(e)&&isFinite(e)&&Math.floor(e)===e});var M$=class pl{constructor(t){if(this.bytes=t,t.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(t,r,n,i){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(n)||!Number.isInteger(i)||0>t||0>r||0>n||0>i||t>0xffffffffffff||r>4095||n>1073741823||i>4294967295)throw new RangeError("invalid field value");const s=new Uint8Array(16);return s[0]=t/Math.pow(2,40),s[1]=t/Math.pow(2,32),s[2]=t/Math.pow(2,24),s[3]=t/Math.pow(2,16),s[4]=t/256,s[5]=t,s[6]=112|r>>>8,s[7]=r,s[8]=128|n>>>24,s[9]=n>>>16,s[10]=n>>>8,s[11]=n,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new pl(s)}toString(){let t="";for(let r=0;this.bytes.length>r;r++)t=t+(this.bytes[r]>>>4).toString(16)+(15&this.bytes[r]).toString(16),r!==3&&r!==5&&r!==7&&r!==9||(t+="-");if(t.length!==36)throw new Error("Invalid UUIDv7 was generated");return t}clone(){return new pl(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;16>r;r++){const n=this.bytes[r]-t.bytes[r];if(n!==0)return Math.sign(n)}return 0}},L$=class{generate(){const e=this.generateOrAbort();if(!O(e))return e;{this.Ct=0;const t=this.generateOrAbort();if(O(t))throw new Error("Could not generate UUID after timestamp reset");return t}}generateOrAbort(){const e=(()=>{const t=Date.now();return We(t)&&isFinite(t)?Math.min(Math.max(Math.floor(t),0),0xffffffffffff):0})();if(e>this.Ct)this.Ct=e,this.Mt();else{if(this.Ct>=e+1e4)return;this.It++,this.It>4398046511103&&(this.Ct++,this.Mt())}return M$.fromFieldsV7(this.Ct,Math.trunc(this.It/Math.pow(2,30)),this.It&Math.pow(2,30)-1,this.Tt.nextUint32())}Mt(){this.It=1024*this.Tt.nextUint32()+(1023&this.Tt.nextUint32())}constructor(){this.Ct=0,this.It=0,this.Tt=new D$}},Om=e=>{if("u">typeof UUIDV7_DENY_WEAK_RNG&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(let t=0;e.length>t;t++)e[t]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return e};A&&!O(A.crypto)&&crypto.getRandomValues&&(Om=e=>crypto.getRandomValues(e));var D$=class{nextUint32(){return this.Rt.length>this.$t||(Om(this.Rt),this.$t=0),this.Rt[this.$t++]}constructor(){this.Rt=new Uint32Array(8),this.$t=1/0}},Th,Lt=()=>N$().toString(),N$=()=>(Th||(Th=new L$)).generate(),mi="",z$=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,yn=null,qe={Et(){if(!He(yn))return yn;if(yn=!1,N)try{const e=`__ph_cookie_support_${Lt()}`;qe.At(e,"xyz"),yn=Ni(e)==='"xyz"',qe.Lt(e)}catch{yn=!1}return yn},Pt(e){j.error("cookieStore error: "+e)},Ot:Ni,Dt(e){let t;try{t=JSON.parse(qe.Ot(e))||{}}catch{}return t},At(e,t,r,n,i){if(!N)return!1;try{let s="",o="";const a=(function(l,u){if(u){let h=(function(d,p=N){if(mi)return mi;if(!p||["localhost","127.0.0.1"].includes(d))return"";const f=d.split(".");let v=Math.min(f.length,8);const m="dmn_chk_"+Lt();for(;!mi&&v--;){const _=f.slice(v).join("."),w=m+"=1;domain=."+_+";path=/";p.cookie=w+";max-age=3",p.cookie.includes(m)&&(p.cookie=w+";max-age=0",mi=_)}return mi})(l);if(!h){const d=(p=>{const f=p.match(z$);return f?f[0]:""})(l);d!==h&&j.info("Warning: cookie subdomain discovery mismatch",d,h),h=d}return h?"; domain=."+h:""}return""})(N.location.hostname,n);if(r){const l=new Date;l.setTime(l.getTime()+864e5*r),s="; expires="+l.toUTCString()}i&&(o="; secure");const c=e+"="+encodeURIComponent(JSON.stringify(t))+s+"; SameSite=Lax; path=/"+a+o;return c.length>3686.4&&j.warn("cookieStore warning: large cookie, len="+c.length),N.cookie=c,!0}catch{return!1}},Lt(e,t){if(N?.cookie&&(!t||!He(Ni(e))))try{qe.At(e,"",-1,t)}catch{return}}},Ha=null,ke={Et(){if(!He(Ha))return Ha;let e=!0;if(O(A))e=!1;else try{const t="__mplssupport__";ke.At(t,"xyz"),ke.Ot(t)!=='"xyz"'&&(e=!1),ke.Lt(t)}catch{e=!1}return e||j.error("localStorage unsupported; falling back to cookie store"),Ha=e,e},Pt(e){j.error("localStorage error: "+e)},Ot(e){try{return A?.localStorage.getItem(e)}catch(t){ke.Pt(t)}return null},Dt(e){try{return JSON.parse(ke.Ot(e))||{}}catch{}return null},At(e,t){try{return A?.localStorage.setItem(e,JSON.stringify(t)),!0}catch(r){ke.Pt(r)}return!1},Lt(e){try{A?.localStorage.removeItem(e)}catch(t){ke.Pt(t)}}},Va=[Sr,ir,Mt,ln,wr,un,Cr,Qi,kr],tn=[Eu,Pt,Mn,mm,Au,Ln,qn,ft],Ro=e=>e+"_cpm",U$=["__proto__","constructor","prototype"],Ba=e=>{if(!be(e))return{};const t={};return Object.keys(e).forEach(r=>{U$.indexOf(r)===-1&&(t[r]=e[r])}),t},Ga=(e,t=[])=>{const r={};return[...tn,...t].forEach(n=>{const i=e[n];O(i)||He(i)||i===""||(r[n]=i)}),r},xm=e=>{let t=5381,r=2166136261;for(let n=0;e.length>n;n++){const i=e.charCodeAt(n);t=33*t^i,r=Math.imul(r^i,16777619)}return e.length.toString(36)+"."+(t>>>0).toString(36)+"."+(r>>>0).toString(36)},Ch=(e,t)=>({p:t,f:xm(JSON.stringify(e))}),$h=(e,t)=>{if(!t)return{properties:[],isValid:!1};try{const r=qe.Dt(Ro(e)),n=r?.f===xm(t)&&ce(r.p);return{properties:n?r.p:[],isValid:n}}catch{return{properties:[],isValid:!1}}},Wa=(e,t)=>t+"|"+(qe.Ot(Ro(e))||""),bn={},fl={Et:()=>!0,Pt(e){j.error("memoryStorage error: "+e)},Ot:e=>e in bn?bn[e]:null,Dt:e=>e in bn?bn[e]:null,At:(e,t)=>(bn[e]=t,!0),Lt(e){delete bn[e]}},Gr=null,xe={Et(){if(!He(Gr))return Gr;if(Gr=!0,O(A))Gr=!1;else try{const e="__support__";xe.At(e,"xyz"),xe.Ot(e)!=='"xyz"'&&(Gr=!1),xe.Lt(e)}catch{Gr=!1}return Gr},Pt(e){j.error("sessionStorage error: ",e)},Ot(e){try{return A?.sessionStorage.getItem(e)}catch(t){xe.Pt(t)}return null},Dt(e){try{return JSON.parse(xe.Ot(e))||null}catch{}return null},At(e,t){try{return A?.sessionStorage.setItem(e,JSON.stringify(t)),!0}catch(r){xe.Pt(r)}return!1},Lt(e){try{A?.sessionStorage.removeItem(e)}catch(t){xe.Pt(t)}}},F$=class{constructor(e){this._instance=e}get Rr(){return this._instance.config}get consent(){return this.Lo()?0:this.No}isOptedOut(){return this.Rr.cookieless_mode==="always"||this.isRejected()||this.consent===-1&&this.Rr.cookieless_mode==="on_reject"}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Rr.opt_out_capturing_by_default}optInOut(e){this.qo.At(this.jo,e?1:0,this.Rr.cookie_expiration,this.Rr.cross_subdomain_cookie,this.Rr.secure_cookie)}reset(){this.qo.Lt(this.jo,this.Rr.cross_subdomain_cookie)}get jo(){const{token:e,opt_out_capturing_cookie_prefix:t,consent_persistence_name:r}=this._instance.config;return r||(t?t+e:"__ph_opt_in_out_"+e)}get No(){const e=this.qo.Ot(this.jo);return Oa(e)?1:ue(iC,e)?0:-1}get qo(){const e=this.Rr.opt_out_capturing_persistence_type,t=e==="localStorage"?ke:qe,r=t.Et()?t:fl;if(!this.Bo||this.Bo!==r){this.Bo=r;const n=e==="localStorage"?qe:ke;n.Ot(this.jo)&&(this.Bo.Ot(this.jo)||this.optInOut(Oa(n.Ot(this.jo))),n.Lt(this.jo,this.Rr.cross_subdomain_cookie))}return this.Bo}Lo(){return!!this.Rr.respect_dnt&&[rt?.doNotTrack,rt?.msDoNotTrack,te.doNotTrack,rt?.globalPrivacyControl].some(e=>Oa(e))}};function Mm(e,t){var r;const n=e==null||(r=e.config)===null||r===void 0?void 0:r.get_current_url;if(!tt(n))return t;try{const i=n(t);return ye(i)&&i?i:t}catch(i){return j.error("Error in get_current_url, falling back to window.location.href",i),t}}function Ph(e){var t;return e instanceof Element&&(e.id==="__POSTHOG_TOOLBAR__"||!!(!((t=e.closest)===null||t===void 0)&&t.call(e,".toolbar-global-fade-container")))}function Zt(e){return!!e&&e.nodeType===1}function ct(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function Lm(e){return!!e&&e.nodeType===3}function $u(e){return!!e&&e.nodeType===11&&Zt(e.host)}function Pu(e){return e?pa(e).split(/\s+/):[]}function Oh(e,t){const r=(function(n){var i;const s=A==null||(i=A.location)===null||i===void 0?void 0:i.href;return O(s)?void 0:Mm(n,s)})(t);return!!(r&&e&&e.some(n=>r.match(n)))}function Yn(e){let t="";switch(typeof e.className){case"string":t=e.className;break;case"object":t=(e.className&&"baseVal"in e.className?e.className.baseVal:null)||e.getAttribute("class")||"";break;default:t=""}return Pu(t)}function Dm(e){return ge(e)?null:pa(e).split(/(\s+)/).filter(t=>Ui(t)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function ts(e){let t="";return jn(e)&&!rs(e)&&e.childNodes&&e.childNodes.length&&Ce(e.childNodes,function(r){var n;Lm(r)&&r.textContent&&(t+=(n=Dm(r.textContent))!==null&&n!==void 0?n:"")}),pa(t)}function zi(e){var t;return O(e.target)?e.srcElement||null:!((t=e.target)===null||t===void 0)&&t.shadowRoot?e.composedPath()[0]||null:e.target||null}var Ou=["a","button","form","input","select","textarea","label"];function vl(e,t){const r=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector;try{return!!r&&r.call(e,t)}catch{return!1}}function gl(e,t){if(O(t))return!0;for(const r of e)if(t.some(n=>vl(r,n)))return!0;return!1}function Nm(e){const t=e.parentNode;return!(!t||!Zt(t))&&t}var Za=[".ph-no-autocapture","[data-ph-no-autocapture]"],zm=["next","previous","prev",">","<"],q$=[...zm,"+","-","−","–"],xh=(e,t)=>/[a-z0-9]/i.test(t)?e.includes(t):e===t,Mh=[".ph-no-rageclick",".ph-no-capture"],j$=["","text","search","email","password","url","tel","number"];function Um(e,t){if(!A||xu(e))return!1;let r,n,i;var s,o;if(vt(t)?(r=!!t&&Mh,n=void 0,i=!1):(r=(s=t?.css_selector_ignorelist)!==null&&s!==void 0?s:Mh,n=t?.content_ignorelist,i=(o=t?.ignore_text_selection)!==null&&o!==void 0&&o),r===!1||i&&(function(c){return!(!c||!Zt(c))&&(!!ct(c,"textarea")||(ct(c,"input")?ue(j$,(c.getAttribute("type")||"").toLowerCase()):(function(l){var u;if(l.isContentEditable)return!0;const h=(u=l.getAttribute)===null||u===void 0?void 0:u.call(l,"contenteditable");return h==="true"||h===""})(c)))})(e))return!1;const{targetElementList:a}=Fm(e,!1);return!(function(c,l){if(c===!1||O(c))return!1;let u;if(c===!0)u=zm;else{if(!ce(c))return!1;if(c.length>10)return j.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;u=c.map(h=>h.toLowerCase())}return l.some(({safeText:h,ariaLabel:d})=>u.some(p=>xh(h,p)||xh(d,p)))})(n,a.map(c=>{var l;return{safeText:ts(c).toLowerCase(),ariaLabel:((l=c.getAttribute("aria-label"))===null||l===void 0?void 0:l.toLowerCase().trim())||""}}))&&!gl(a,r)}var xu=e=>!e||ct(e,"html")||!Zt(e),Fm=(e,t)=>{if(!A||xu(e))return{parentIsUsefulElement:!1,targetElementList:[]};let r=!1;const n=[e];let i=e;for(;i.parentNode&&!ct(i,"body");){if($u(i.parentNode)){n.push(i.parentNode.host),i=i.parentNode.host;continue}const s=Nm(i);if(!s)break;if(t||Ou.indexOf(s.tagName.toLowerCase())>-1)r=!0;else try{const o=A.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(r=!0)}catch{}n.push(s),i=s}return{parentIsUsefulElement:r,targetElementList:n}};function jn(e){const t=new Set;let r=0;for(let s=e;s.parentNode&&!ct(s,"body");s=s.parentNode){if(r++>=1e3||t.has(s))return!1;t.add(s);const o=Yn(s);if(ue(o,"ph-sensitive")||ue(o,"ph-no-capture"))return!1}if(ue(Yn(e),"ph-include"))return!0;const n=e.type||"";if(ye(n))switch(n.toLowerCase()){case"hidden":case"password":return!1}const i=e.name||e.id||"";return!ye(i)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(i.replace(/[^a-zA-Z0-9]/g,""))}function rs(e){return!!(ct(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||ct(e,"select")||ct(e,"textarea")||e.getAttribute("contenteditable")==="true")}var Lh=new RegExp("^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$"),Dh=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,H$=[16,15,14,13],V$=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Nh=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),zh=/[0-9A-Za-z_]/;function B$(e){let t=0,r=!1;for(let n=e.length-1;n>=0;n--){let i=e.charCodeAt(n)-48;r&&(i*=2,i>9&&(i-=9)),t+=i,r=!r}return t%10==0}function Ui(e,t=!0){return!(ge(e)||ye(e)&&(e=pa(e),(t?Lh.test((e||"").replace(/[- ]/g,"")):(function(r){let n;for(Dh.lastIndex=0;n=Dh.exec(r);){const i=n[2];if(!i)continue;const s=i.replace(/[- ]/g,"");for(let o=0;s.length>o;o++)for(const a of H$){const c=o+a;if(s.length>=c){const l=s.slice(o,c);if(Lh.test(l)&&B$(l))return!0}}}return!1})(e))||(t?V$.test(e):(function(r){let n;for(Nh.lastIndex=0;n=Nh.exec(r);){const i=n[1],s=n[3];if(!(i&&s&&zh.test(i)&&zh.test(s)))return!0}return!1})(e))))}function Uh(e){let t=ts(e);return t=`${t} ${qm(e)}`.trim(),Ui(t)?t:""}function qm(e){let t="";return e&&e.childNodes&&e.childNodes.length&&Ce(e.childNodes,function(r){var n;if(r&&((n=r.tagName)===null||n===void 0?void 0:n.toLowerCase())==="span")try{const i=ts(r);t=`${t} ${i}`.trim(),r.childNodes&&r.childNodes.length&&(t=`${t} ${qm(r)}`.trim())}catch(i){j.error("[AutoCapture]",i)}}),t}function Fh(e){return e.replace(/"|\\"/g,'\\"')}function G$(e){const t=e.attr__class;if(t)return ce(t)?t:Pu(t)}var Ts=Be("[Dead Clicks]"),W$=()=>!0,Z$=e=>{var t;const r=!!(!((t=e.instance.persistence)===null||t===void 0)&&t.get_property(ku)),n=e.instance.config.capture_dead_clicks;return vt(n)?n:!!be(n)||r},qh=class{get lazyLoadedDeadClicksAutocapture(){return this.Ho}constructor(e,t,r){this.instance=e,this.isEnabled=t,this.onCapture=r,this.startIfEnabledOrStop()}onRemoteConfig(e){if(!e.ok)return;const t=e.config;"captureDeadClicks"in t&&(this.instance.persistence&&this.instance.persistence.register({[ku]:t.captureDeadClicks}),this.startIfEnabledOrStop())}startIfEnabledOrStop(){this.isEnabled(this)?this.zo(()=>{this.Uo()}):this.stop()}zo(e){var t,r,n;!((t=te.__PosthogExtensions__)===null||t===void 0)&&t.initDeadClicksAutocapture?e():(r=te.__PosthogExtensions__)===null||r===void 0||(n=r.loadExternalDependency)===null||n===void 0||n.call(r,this.instance,"dead-clicks-autocapture",i=>{i?Ts.error("failed to load script",i):e()})}Uo(){var e;if(N){if(!this.Ho&&(!((e=te.__PosthogExtensions__)===null||e===void 0)&&e.initDeadClicksAutocapture)){const t=be(this.instance.config.capture_dead_clicks)?b({},this.instance.config.capture_dead_clicks):{};t.__onCapture=this.onCapture,this.onCapture&&(t.capture_dead_swipes=!1),this.Ho=te.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,t),this.Ho.start(N),Ts.info("starting...")}}else Ts.error("`document` not found. Cannot start.")}stop(){this.Ho&&(this.Ho.stop(),this.Ho=void 0,Ts.info("stopping..."))}},_i=Be("[SegmentIntegration]");function jh(e,t,r=!0){const n=e.config.segment;if(!n)return t();const{analytics:i,filterProperties:s}=(a=>tt(a.register))(o=n)?{analytics:o}:o;var o;(function(a,c,l,u){const h=p=>{const f=()=>p.anonymousId()||Lt();a.config.get_device_id=f,u&&p.id()&&(a.register({distinct_id:p.id(),$device_id:f()}),a.persistence.set_property(ft,Ks)),l(u?void 0:p.anonymousId()||void 0)},d=c.user();"then"in d&&tt(d.then)?d.then(h):h(d)})(e,i,a=>{i.register(((c,l,{filterProperties:u}={})=>{typeof Promise<"u"&&Promise.resolve||_i.warn("This browser does not have Promise support, and can not use the segment integration");const h=(d,p)=>{if(!p)return d;const f=!!l&&d.event.anonymousId===l&&!d.event.userId;f||d.event.userId||d.event.anonymousId===c.get_distinct_id()||(_i.info("No userId set, resetting PostHog"),c.reset()),f||(l=void 0),d.event.userId&&d.event.userId!==c.get_distinct_id()&&(_i.info("UserId set, identifying with PostHog"),c.identify(d.event.userId));let v=c.calculateEventProperties(p,d.event.properties);if(!ge(u)){const m=d.event.properties||{},_={};for(const S of Object.keys(v))_u.call(m,S)||(_[S]=v[S]);const w=((S,T)=>{const C=ce(S)?S:[S];let $=b({},T);for(const M of C)try{if($=M($),ge($))return null}catch(L){return _i.error("Error in Segment filterProperties:",L),null}return $})(u,_);if(ge(w))return d;v=w}return d.event.properties=Object.assign({},v,d.event.properties),d};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded(){return!0},load(){return Promise.resolve()},track(d){return h(d,d.event.event)},page(d){return h(d,Tu)},identify(d){return h(d,$m)},screen(d){return h(d,"$screen")}}})(e,a,{filterProperties:s})).then(()=>{t()},c=>{_i.error("Failed to register the Segment integration",c),t()})},r)}var jm="posthog-js";function Hm(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:s=!0}={}){return o=>{var a,c,l,u,h;if(i!=="*"&&!i.includes(o.level)||!e.__loaded)return o;o.tags||(o.tags={});const d=e.requestRouter.endpointFor("ui",`/project/${e.config.token}/person/${e.get_distinct_id()}`);o.tags["PostHog Person URL"]=d,e.sessionRecordingStarted()&&(o.tags["PostHog Recording URL"]=e.get_session_replay_url({withTimestamp:!0}));const p=((a=o.exception)===null||a===void 0?void 0:a.values)||[],f=p.map(_=>b(b({},_),{},{stacktrace:_.stacktrace?b(b({},_.stacktrace),{},{type:"raw",frames:(_.stacktrace.frames||[]).map(w=>b(b({},w),{},{platform:"web:javascript"}))}):void 0})),v={$exception_message:((c=p[0])===null||c===void 0?void 0:c.value)||o.message,$exception_type:(l=p[0])===null||l===void 0?void 0:l.type,$exception_level:o.level,$exception_list:f,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:((u=p[0])===null||u===void 0?void 0:u.value)||o.message,$sentry_exception_type:(h=p[0])===null||h===void 0?void 0:h.type,$sentry_tags:o.tags};var m;return t&&r&&(v.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),s&&((m=e.exceptions)===null||m===void 0||m.sendExceptionEvent(v)),o}}var J$=class{constructor(e,t,r,n,i,s){this.name=jm,this.setupOnce=function(o){o(Hm(e,{organization:t,projectId:r,prefix:n,severityAllowList:i,sendExceptionsToPostHog:s==null||s}))}}},Hh=class{constructor(e){this.Wo=(t,r,n)=>{n&&(n.noSessionId||n.activityTimeout||n.sessionPastMaximumLength||n.crossTabAdoption)&&(j.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:t,changeReason:n}),this.Vo=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.Go()}Go(){var e;this.Zo=(e=this._instance.sessionManager)===null||e===void 0?void 0:e.onSessionId(this.Wo)}destroy(){var e;(e=this.Zo)===null||e===void 0||e.call(this),this.Zo=void 0}doPageView(e,t){var r;const n=this.Qo(e,t);return this.Vo={pathname:(r=A?.location.pathname)!==null&&r!==void 0?r:"",pageViewId:t,timestamp:e},this._instance.scrollManager.resetContext(),n}doPageLeave(e){var t;return this.Qo(e,(t=this.Vo)===null||t===void 0?void 0:t.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.Vo)===null||e===void 0?void 0:e.pageViewId}}Qo(e,t){const r=this.Vo;if(!r)return{$pageview_id:t};let n={$pageview_id:t,$prev_pageview_id:r.pageViewId};const i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){let{maxScrollHeight:s,lastScrollY:o,maxScrollY:a,maxContentHeight:c,lastContentY:l,maxContentY:u}=i;if(!(O(s)||O(o)||O(a)||O(c)||O(l)||O(u))){s=Math.ceil(s),o=Math.ceil(o),a=Math.ceil(a),c=Math.ceil(c),l=Math.ceil(l),u=Math.ceil(u);const h=s>1?Bt(o/s,0,1,j):1,d=s>1?Bt(a/s,0,1,j):1,p=c>1?Bt(l/c,0,1,j):1,f=c>1?Bt(u/c,0,1,j):1;n=Le(n,{$prev_pageview_last_scroll:o,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:a,$prev_pageview_max_scroll_percentage:d,$prev_pageview_last_content:l,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:u,$prev_pageview_max_content_percentage:f})}}return r.pathname&&(n.$prev_pageview_pathname=r.pathname),r.timestamp&&(n.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),n}},yi=["flags","surveys"],K$={[n$]:{exposure:"hidden"},[So]:{exposure:"hidden"},[i$]:{exposure:"hidden"},[nl]:{exposure:"hidden"},[qn]:{exposure:"hidden"},[Mi]:{exposure:"hidden"},[pm]:{exposure:"event"},[il]:{exposure:"hidden"},[vm]:{exposure:"hidden"},[sl]:{exposure:"event"},[fm]:{exposure:"hidden"},[ol]:{exposure:"event"},[al]:{exposure:"event"},[ku]:{exposure:"event"},[Ru]:{exposure:"hidden"},[gm]:{exposure:"event"},[Li]:{exposure:"hidden"},[s$]:{exposure:"hidden"},[Mn]:{exposure:"hidden"},[mm]:{exposure:"event"},[o$]:{exposure:"event",shouldSkipFromEventProperties:e=>He(e)},[d$]:{exposure:"event"},[h$]:{exposure:"event"},[p$]:{exposure:"event"},[f$]:{exposure:"event"},[v$]:{exposure:"hidden"},[Mt]:{exposure:"hidden",storageGroup:"flags"},[ir]:{exposure:"hidden",storageGroup:"flags"},[cl]:{exposure:"hidden"},[ln]:{exposure:"hidden",storageGroup:"flags"},[wr]:{exposure:"hidden",storageGroup:"flags"},[un]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Di]:{exposure:"hidden",storageGroup:"flags"},[qt]:{exposure:"hidden"},[en]:{exposure:"hidden"},[Sr]:{exposure:"hidden"},[Er]:{exposure:"hidden"},[ll]:{exposure:"hidden",storageGroup:"surveys"},[Eo]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[ym]:{exposure:"event"},[bm]:{exposure:"hidden"},[wm]:{exposure:"hidden"},[ul]:{exposure:"hidden"},[g$]:{exposure:"hidden"},[m$]:{exposure:"hidden"},[_$]:{exposure:"event"},[y$]:{exposure:"event"},[b$]:{exposure:"event"},[w$]:{exposure:"event"},[kr]:{exposure:"hidden"},[Ti]:{exposure:"hidden"},[_m]:{exposure:"event"},[Qi]:{exposure:"hidden"},[Cr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ft]:{exposure:"hidden"},[dl]:{exposure:"hidden"},[S$]:{exposure:"hidden"},[Sm]:{exposure:"hidden"},[Em]:{exposure:"hidden"},[Ln]:{exposure:"hidden"},[Au]:{exposure:"hidden"},[a$]:{exposure:"event"},[c$]:{exposure:"event"},[l$]:{exposure:"event"},[u$]:{exposure:"event"},[Rm]:{exposure:"event"},[Am]:{exposure:"event"},[Im]:{exposure:"event"},[Tm]:{exposure:"event"},[E$]:{exposure:"event"},[k$]:{exposure:"event"},[R$]:{exposure:"event"},[A$]:{exposure:"event"},[I$]:{exposure:"event"},[T$]:{exposure:"event"},[C$]:{exposure:"event"},[$$]:{exposure:"event"}},Y$=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],ot=e=>{const t=K$[e];if(t)return t;for(const[r,n]of Y$)if(e.indexOf(r)===0)return n},Nn=(e,t)=>{try{let r;return JSON.stringify(e,(n,i)=>{var s;return ci(i)?((s=r)!==null&&s!==void 0||(r=new WeakMap),r.has(i)||r.set(i,Pm(i)),r.get(i)):typeof i=="bigint"?i.toString():i},t)}catch{return fg(e)}},Fr=e=>{const t=N?.createElement("a");return O(t)?null:(t.href=e,t)},Xn=function(e,t){const r=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&");let n;for(let i=0;r.length>i;i++){const s=r[i].split("=");if(s[0]===t){n=s;break}}if(!ce(n)||2>n.length)return"";{let i=n[1];try{i=decodeURIComponent(i)}catch{j.error("Skipping decoding for malformed query param: "+i)}return i.replace(/\+/g," ")}},ns=function(e,t,r){if(!e||!t||!t.length)return e;const n=e.split("#"),i=n[1],s=(n[0]||"").split("?"),o=s[1],a=s[0],c=(o||"").split("&"),l=[];for(let h=0;c.length>h;h++){const d=c[h].split("=");ce(d)&&(t.includes(d[0])?l.push(d[0]+"="+r):l.push(c[h]))}let u=a;return o!=null&&(u+="?"+l.join("&")),i!=null&&(u+="#"+i),u},Ao=function(e,t){const r=e.match(new RegExp(t+"=([^&]*)"));return r?r[1]:null},Vm=(e,t)=>e>=t&&pg(),Bm=(e,t,r,n)=>{if(e===0){if(pg()){const i=t+1;return i===r&&n(),i}return t}return 0},Qn=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],X$=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...Qn],is="<masked>",Q$=["li_fat_id"];function Gm(e,t,r){if(!N)return{};const n=t?[...Qn,...r||[]]:[],i=Wm(ns(N.URL,n,is),e),s=(function(){const o={};return Ce(Q$,function(a){const c=Ni(a);o[a]=c||null}),o})();return Le(s,i)}function Wm(e,t){const r=X$.concat(t||[]),n={};return Ce(r,function(i){const s=Xn(e,i);n[i]=s||null}),n}function Zm(e){const t=(function(i){return i?i.search("https?://(.*)google.([^/?]*)")===0?"google":i.search("https?://(.*)bing.com")===0?"bing":i.search("https?://(.*)yahoo.com")===0?"yahoo":i.search("https?://(.*)duckduckgo.com")===0?"duckduckgo":null:null})(e),r=t!="yahoo"?"q":"p",n={};if(!He(t)){n.$search_engine=t;const i=N?Xn(N.referrer,r):"";i.length&&(n.ph_keyword=i)}return n}function Jm(){return navigator.language||navigator.userLanguage}function eP(){const e=Jm();return typeof e=="string"?e.split("-")[0]:void 0}var Io="$direct";function Km(){return N?.referrer||Io}function Ym(e,t,r=!1){const n=e?[...Qn,...t||[]]:[],i=r?Ur(je?.href):je?.href,s=i?.substring(0,1e3);return{r:Km().substring(0,1e3),u:s?ns(s,n,is):void 0}}function Xm(e,t=!1){var r;const{r:n,u:i}=e,s=t?Ur(i):i,o={$referrer:n,$referring_domain:n==null?void 0:n==Io?Io:(r=Fr(n))===null||r===void 0?void 0:r.host};if(s){o.$current_url=s;const a=Fr(s);o.$host=a?.host,o.$pathname=a?.pathname;const c=Wm(s);Le(o,c)}if(n){const a=Zm(n);Le(o,a)}return o}function Qm(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function tP(){try{return new Date().getTimezoneOffset()}catch{return}}var rP={flags:Cr,surveys:Eo},nP=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Cs=e=>`${e}_cookie_identity_change_pending`,$s=e=>{let t="",r=0;for(const n of e){const i=encodeURIComponent(JSON.stringify(n).slice(1,-1)).length;if(r+i>1e3)break;t+=n,r+=i}return t},Qe="main",rr=[Mt,ir,ln,wr,un,Cr,Di,Sr],Ja=e=>rr.indexOf(e)!==-1,e_=[qn,Mi],Vh=e=>e_.indexOf(e)!==-1,ur=(e,t)=>{try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}},wn=e=>{if(!e)return{};const t=JSON.parse(e);return be(t)?t:{}},Bh=(e,t)=>{Ce(e,(r,n)=>{const i=ot(n);i&&i.exposure!=="event"||{}.hasOwnProperty.call(t,n)||delete e[n]})},Ka=class{constructor(e,t,r=!0){if(this.Jo={},this.Ko=!1,this.Xo=!1,this.Yo=!1,this.ta=!1,this.ea=!1,this.ia=new Map,this.na=!1,this.sa=!1,this.ra=!1,this.oa=new Set,this.aa=new Set,this.Rr=e,this.la=r,this.props={},this.ua=void 0,this.ha=(n=>{let i="";return n.token&&(i=n.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),n.persistence_name?"ph_"+n.persistence_name:"ph_"+i+"_posthog"})(e),this.qo=this.ca(e),this.Yo=this.da(e),this.load(),this.va(),e.debug&&j.info("Persistence loaded",e.persistence,b({},this.props)),this.update_config(e,e,t),this.save(),A){const n=()=>this.flush();Ie(A,"beforeunload",n,{capture:!1}),Ie(A,"pagehide",n,{capture:!1}),this.fa=i=>{if(this.Ko&&(!i.storageArea||i.storageArea===A?.localStorage)&&i.key)if(i.key!==this.ha){if(this.Yo){const s=yi.find(o=>i.key===this.pa(o));s&&this.ga(i.key,s)}}else this.ga(i.key,Qe)},Ie(A,"storage",this.fa)}}markCrossTabFeatureFlagChanges(e){Object.entries(e).forEach(([t,r])=>{const n=this.ia.get(t);if(!Ja(t)||n===!0)return;if(r===!0)return void this.ma(t,!0);const i=new Set(n||[]);r.forEach(s=>i.add(s)),i.size&&this.ma(t,i)})}onCrossTabFeatureFlagChange(e){return this.aa.add(e),()=>this.aa.delete(e)}destroy(){this.fa&&A&&(A.removeEventListener("storage",this.fa),this.fa=void 0),this.aa.clear()}ga(e,t,r=!0){if(this.mi)return!1;let n,i;try{if(i=ke.Ot(e),He(i)){const a=this.ya(t);return a.storageValue=null,t!==Qe&&(a.persisted=!1),!1}n=wn(i)}catch{return!1}const s=t===Qe?n:ke.Dt(this.ha);if(s&&this.ba(s))return!1;const o=this._a(n,t,r);return t===Qe&&this.Yo&&!ur(this.wa().main,n)||this.ka(n,t,!0,i),o}ba(e){const t=this.props[Pt],r=e[Pt];return!O(t)&&!O(r)&&t!==r}ka(e,t,r,n){const i=this.ya(t);i.storageValue=n,t!==Qe&&(i.persisted=r);try{i.fingerprint=this.Sa(e,t)}catch{i.fingerprint=void 0}}_a(e,t,r){let n=!1;return rr.forEach(i=>{var s;const o=(s=ot(i))===null||s===void 0?void 0:s.storageGroup;if(t===Qe&&this.Yo&&o||t!==Qe&&o!==t)return;const a=i in e,c=this.xa(i,a?e[i]:void 0),l=this.ia.has(i)?i in this.props:a;l===i in this.props&&ur(c,this.props[i])||(l?this.Ca(i,c,!1):this.$a(i,!1),n=!0)}),n&&r&&this.aa.forEach(i=>i()),n}Ta(){if(!this.Ko)return!1;try{this.ra=!1;const e=ke.Ot(this.ha),t=this.ya(Qe);let r,n=!1,i=!1;if(e!==t.storageValue)if(He(e))t.storageValue=null;else{if(r=wn(e),this.ra=!this.sa&&this.ba(r),this.ra)return!1;i=this._a(r,Qe,!1),!this.Yo||ur(this.wa().main,r)?this.ka(r,Qe,!0,e):t.storageValue=e,n=!0}return this.Yo&&yi.forEach(s=>{const o=ke.Ot(this.pa(s)),a=this.ya(s),c=r||{},l=n&&rr.some(h=>{var d;return((d=ot(h))===null||d===void 0?void 0:d.storageGroup)===s&&h in c});if(o===a.storageValue&&!l)return;if(He(o))return a.storageValue=null,a.persisted=!1,void(l&&(i=this._a(c,s,!1)||i));const u=wn(o);i=this._a(u,s,!1)||i,this.ka(u,s,!0,o)}),i}catch{return!1}}ma(e,t){this.ia.set(e,t);const r=ot(e);r!=null&&r.volatile||(this.ya((this.Yo?r?.storageGroup:void 0)||Qe).fingerprint=void 0,this.Ia(e))}Ma(){rr.forEach(e=>this.ia.set(e,!0))}va(){if(this.Ko)try{const e=ke.Ot(this.ha),t=wn(e);this.ya(Qe).storageValue=e,rr.forEach(r=>{var n;const i=this.Yo?(n=ot(r))===null||n===void 0?void 0:n.storageGroup:void 0,s=i?ke.Ot(this.pa(i)):null;if(i){const a=this.ya(i);a.storageValue=s,a.persisted=!He(s)}const o=i&&!He(s)?wn(s):t;r in this.props?this.Ea(r,o[r],this.props[r]):r in o&&this.ma(r,!0)})}catch{}}xa(e,t){const r=this.ia.get(e);if(!r)return t;if(r===!0)return this.props[e];if(e==="$active_feature_flags"){const s=new Set(ce(t)?t:[]),o=new Set(ce(this.props[e])?this.props[e]:[]);return r.forEach(a=>o.has(a)?s.add(a):s.delete(a)),Array.from(s)}const n=be(t)?b({},t):{},i=be(this.props[e])?this.props[e]:{};return r.forEach(s=>{s in i?n[s]=i[s]:delete n[s]}),n}Ea(e,t,r){if(!Ja(e))return;const n=this.ia.get(e);if(n===!0)return;let i=t;if(this.Ko)try{var s;const a=this.Yo?(s=ot(e))===null||s===void 0?void 0:s.storageGroup:void 0,c=a?this.pa(a):this.ha;i=wn(ke.Ot(c))[e]}catch{}const o=new Set(n||[]);if(e==="$active_feature_flags"){if(!O(t)&&!ce(t)||!O(i)&&!ce(i)||!ce(r))return void this.ma(e,!0);const a=new Set(t||[]),c=new Set(i||[]),l=new Set(r);new Set([...a,...l]).forEach(u=>{a.has(u)!==l.has(u)&&o.add(u)}),o.forEach(u=>{c.has(u)===l.has(u)&&o.delete(u)})}else{if(!be(r))return void(ur(i,r)?this.ia.delete(e):this.ma(e,!0));{if(!O(t)&&!be(t)||O(t)&&_t(r)&&O(i))return void this.ma(e,!0);const a=be(t)?t:{},c=be(i)?i:{};new Set([...Object.keys(a),...Object.keys(r)]).forEach(l=>{l in a==l in r&&ur(a[l],r[l])||o.add(l)}),o.forEach(l=>{l in c==l in r&&ur(c[l],r[l])&&o.delete(l)})}}o.size?this.ma(e,o):this.ia.delete(e)}Pa(){var e;const t=(e=this.Rr)===null||e===void 0?void 0:e.persistence_save_debounce_ms;return We(t)&&t>0?t:0}Ra(e){if(this.Rr.cookieWinsOnConflict&&this.Rr.persistence.toLowerCase()==="localstorage+cookie")if(e)try{const t=Ga(e,this.Rr.cookie_persisted_properties||[]),r=Ch(t,this.Rr.cookie_persisted_properties||[]),n=JSON.stringify(t)+"|"+JSON.stringify(r),i=qe.Ot(this.ha)||void 0;i&&Wa(this.ha,i)===n&&(this.Aa=n,this.Fa=i)}catch{}else try{const t=qe.Ot(this.ha)||void 0;this.Aa=t?Wa(this.ha,t):void 0,this.Fa=t}catch{}}syncCookieProperties(){return this.Oa(this.Rr)}Oa(e,t=!1){if(this.mi&&!t||this.ea||!e.cookieWinsOnConflict||e.persistence.toLowerCase()!=="localstorage+cookie")return!1;let r;try{r=qe.Ot(this.ha)||void 0}catch{}if(!r||r===this.Fa)return!1;const n=Wa(this.ha,r);let i;try{i=Ba(JSON.parse(r))}catch{return!1}if((qe.Ot(this.ha)||void 0)!==r)return!1;this.Aa=n,this.Fa=r;const s=$h(this.ha,r),o=[...tn,...s.properties],a={};if(Object.keys(i).forEach(v=>{const m=i[v];(O(m)||He(m)||m===""||v==="$user_state"&&m!=="anonymous"&&m!=="identified")&&(a[v]=!0,delete i[v])}),_t(i))return!1;const c="distinct_id"in i||i.$user_state==="anonymous"||i.$user_state==="identified",l=this.props,u=l[Pt],h=l[ft],d=Le({},l);[...tn,...e.cookie_persisted_properties||[]].forEach(v=>{if(o.indexOf(v)!==-1&&!(v in i)&&!a[v]&&(c||v!=="distinct_id"&&v!=="$user_state")){const m=d[v];(s.isValid||tn.indexOf(v)===-1||m!==!1&&m!==0)&&delete d[v]}}),this.props=Le(d,i),rr.forEach(v=>{const m=v in this.props;v in l===m&&ur(l[v],this.props[v])||(m?this.Ea(v,l[v],this.props[v]):this.ma(v,!0))}),!c||"$user_state"in i||"$user_state"in this.props||this.Ca(ft,sr);const p=this.props[Pt],f=this.props[ft];return!c||p===u&&f===h||(this.sa=!0,this.ta=!0,xe.At(Cs(this.ha),!0),this.$a(Sr),this.$a(ir),this.$a(Mt),this.$a(ln),this.$a(wr),this.$a(un),this.$a(Cr),this.$a(Qi),this.$a(kr),f!=="anonymous"||h!=="identified"&&i.$user_state!=="anonymous"&&(O(u)||p===u)||(Bh(this.props,i),this.$a(Er)),f==="identified"?this.props.$user_id=p:delete this.props.$user_id,this.$a(So)),!0}consumeCookieIdentityChange(){const e=Cs(this.ha),t=this.ta||!!xe.Ot(e);return this.ta=!1,t&&xe.Lt(e),t}Da(e=!1){return!(this.ea||this.mi&&!e||!this.Rr.cookieWinsOnConflict||this.Rr.persistence.toLowerCase()!=="localstorage+cookie"||(this.ea=!0,0))}La(){this.ea&&(O(this.Na)||(clearTimeout(this.Na),this.Na=void 0),delete this.Jo[Qe],this.qa(!0))}ja(e=!0){if(this.ea)try{e?this.La():O(this.Na)||(clearTimeout(this.Na),this.Na=void 0)}finally{this.ea=!1}}isDisabled(){return!!this.mi}ca(e){nP.indexOf(e.persistence.toLowerCase())===-1&&(j.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");const t=((o=[],a=!1)=>{const c=[...tn,...o];return b(b({},ke),{},{Dt(l){try{let h,d={};try{h=qe.Ot(l)||void 0,d=h?Ba(JSON.parse(h)):{}}catch{}const p=JSON.parse(ke.Ot(l)||"{}");let f;if(a){const v=$h(l,h),m=[...tn,...v.properties],_={};Object.keys(d).forEach(S=>{const T=d[S];He(T)||T===""||S==="$user_state"&&T!=="anonymous"&&T!=="identified"||(_[S]=T)});const w="distinct_id"in _||_.$user_state==="anonymous"||_.$user_state==="identified";if(Object.keys(_).length>0){var u;const S=p[Pt],T=(u=p.$user_state)!==null&&u!==void 0?u:sr;c.forEach(C=>{if(m.indexOf(C)!==-1&&!(C in d)&&(w||C!=="distinct_id"&&C!=="$user_state")){const $=p[C];(v.isValid||tn.indexOf(C)===-1||$!==!1&&$!==0)&&delete p[C]}}),!w||"$user_state"in d||"$user_state"in p||(p[ft]=sr),!w||("distinct_id"in _?_[Pt]:p[Pt])===S&&("$user_state"in _?_[ft]:p[ft])===T||(Va.forEach(C=>delete p[C]),_.$user_state==="identified"&&"distinct_id"in _?p.$user_id=_[Pt]:delete p.$user_id,_.$user_state!=="identified"&&(delete p[_m],delete p[Er]),delete p.__alias)}f=Le(p,_)}else f=Le(d,p);return ke.At(l,f),f}catch{}return null},At(l,u,h,d,p,f){const v=ke.At(l,u,void 0,void 0,f);try{const m=Ga(u,o);if(Object.keys(m).length){if(a){const _=Ro(l),w=Ch(m,o);if(qe.At(_,w,h,d,p,f),qe.Ot(_)!==JSON.stringify(w)){qe.Lt(_,d);const S=Ga(u);return qe.At(l,S,h,d,p,f),v}}qe.At(l,m,h,d,p,f)}}catch(m){ke.Pt(m)}return v},Lt(l,u){try{A?.localStorage.removeItem(l),qe.Lt(l,u),qe.Lt(Ro(l),u)}catch(h){ke.Pt(h)}}})})(e.cookie_persisted_properties||[],e.cookieWinsOnConflict);let r,n=!1,i=!1;const s=e.persistence.toLowerCase();return s==="localstorage"&&ke.Et()?(r=ke,i=!0):s==="localstorage+cookie"&&t.Et()?(r=t,i=!0,n=!0):s==="sessionstorage"&&xe.Et()?r=xe:s==="memory"?r=fl:s==="cookie"&&qe.Et()?(r=qe,n=!0):t.Et()?(r=t,i=!0,n=!0):qe.Et()?(r=qe,n=!0):r=fl,this.Ko=i,this.Xo=n,r}pa(e){return`${this.ha}__${e}`}da(e){return this.Ko&&!!e.split_storage}properties(){const e={};return Ce(this.props,(t,r)=>{const n=ot(r);if(!n||n.exposure==="event"){var i;if(!(n==null||(i=n.shouldSkipFromEventProperties)===null||i===void 0)&&i.call(n,t))return;e[r]=t}}),e}load(e=!1){if(this.mi&&!e)return;const t=this.Rr.cookieWinsOnConflict&&this.Rr.persistence.toLowerCase()==="localstorage+cookie",r=t?ke.Dt(this.ha):null;let n={};if(t)try{n=Ba(qe.Dt(this.ha)),Ce(n,(a,c)=>{(O(a)||He(a)||a==="")&&delete n[c]})}catch{}const i=this.qo.Dt(this.ha);if(i&&(this.props=Le({},i)),this.Yo&&this.Ba(),t&&i){var s,o;const a=r?.[Pt],c=(s=r?.$user_state)!==null&&s!==void 0?s:sr,l=i[Pt],u=(o=i.$user_state)!==null&&o!==void 0?o:sr;if(l!==a||u!==c){this.ta=!0,xe.At(Cs(this.ha),!0);const h=Le({},this.props);Va.forEach(p=>delete h[p]),u!=="anonymous"||c!=="identified"&&n.$user_state!=="anonymous"&&(O(a)||l===a)||(Bh(h,n),delete h[Er]),this.props=h;const d=new Set;Va.forEach(p=>{var f;const v=(f=ot(p))===null||f===void 0?void 0:f.storageGroup;v&&d.add(v)}),d.forEach(p=>{const f={};Ce(this.props,(v,m)=>{var _;((_=ot(m))===null||_===void 0?void 0:_.storageGroup)===p&&(f[m]=v)}),_t(f)?(ke.Lt(this.pa(p)),this.Jo[p]={}):ke.At(this.pa(p),f)&&(this.Jo[p]={persisted:!0,fingerprint:this.Sa(f,p)})})}}xe.Ot(Cs(this.ha))&&(this.ta=!0)}Ba(){for(const e of yi){const t=ke.Dt(this.pa(e));if(t&&!_t(t)){const r=this.ya(e);r.persisted=!0,this.Ha(e)||(r.fingerprint=this.Sa(t,e)),this.za(e,t)||Le(this.props,t)}}}Ha(e){return Object.keys(this.props).some(t=>{var r;return((r=ot(t))===null||r===void 0?void 0:r.storageGroup)===e})}za(e,t){const r=rP[e];if(!r)return!1;const n=t[r],i=this.props[r];return We(n)&&We(i)&&i>n}refreshKey(e){var t;if(this.mi||this.oa.has(e))return;const r=this.Yo?(t=ot(e))===null||t===void 0?void 0:t.storageGroup:void 0,n=r?ke.Dt(this.pa(r)):this.qo.Dt(this.ha);if(n&&e in n)this.Ca(e,n[e],!1);else{if(r){const i=this.qo.Dt(this.ha);if(i&&e in i)return void this.Ca(e,i[e],!1)}this.$a(e,!1)}}save(){if(this.mi)return;const e=this.Pa();e>0?O(this.Na)&&(this.Na=setTimeout(()=>{this.Na=void 0,this.qa()},e)):this.qa()}flush(){O(this.Na)||(clearTimeout(this.Na),this.Na=void 0,this.qa())}qa(e=!1){if(this.mi||this.ea&&!e)return;e||(this.syncCookieProperties(),this.Rr.cookieWinsOnConflict&&this.Rr.persistence.toLowerCase()==="localstorage+cookie"||e_.forEach(i=>this.refreshKey(i)));const t=!e&&!this.na;t||(this.ra=!1);const r=!!t&&this.Ta();if(this.ra)return void(this.Rr.debug&&j.warn("skipping persistence write because storage belongs to a different distinct ID"));if(this.Yo)return this.Ua(),void(r&&this.aa.forEach(i=>i()));const n=this.Wa(this.qo,this.ha,this.props,Qe);n==="written"&&this.Ra(this.props),n!=="failed"&&(this.ia.clear(),this.sa=!1,this.oa.clear()),r&&this.aa.forEach(i=>i())}Ua(){const{main:e,groups:t}=this.wa(),r=this.Wa(this.qo,this.ha,e,Qe);r==="written"&&this.Ra(e),r!=="failed"&&(this.sa=!1,this.oa.clear(),rr.forEach(i=>{var s;(s=ot(i))!==null&&s!==void 0&&s.storageGroup||this.ia.delete(i)}));for(const i of yi){var n;const s=t[i];if(_t(s)&&!(!((n=this.Jo[i])===null||n===void 0)&&n.persisted)){rr.forEach(a=>{var c;((c=ot(a))===null||c===void 0?void 0:c.storageGroup)===i&&this.ia.delete(a)});continue}const o=this.Wa(ke,this.pa(i),s,i);o!=="failed"&&rr.forEach(a=>{const c=ot(a);c?.storageGroup!==i||o!=="written"&&c.volatile||this.ia.delete(a)})}}wa(){const e={},t={flags:{},surveys:{}};return Ce(this.props,(r,n)=>{var i;const s=(i=ot(n))===null||i===void 0?void 0:i.storageGroup;s?t[s][n]=r:e[n]=r}),{main:e,groups:t}}Sa(e,t){if(t===Qe)return JSON.stringify(e)+"|"+this.Va+"|"+this.Ga+"|"+this.Za;const r={};return Ce(e,(n,i)=>{var s;r[i]=!((s=ot(i))===null||s===void 0)&&s.volatile?"__volatile__":n}),JSON.stringify(r)}Wa(e,t,r,n){const i=this.ya(n);if(n!==Qe&&!i.dirty&&!O(i.fingerprint))return"skipped";let s;try{if(s=this.Sa(r,n),s===i.fingerprint)return i.dirty=!1,"skipped"}catch{s=void 0}return e.At(t,r,this.Va,this.Ga,this.Za,this.Rr.debug)?(i.dirty=!1,n!==Qe&&(i.persisted=!0),O(s)||(i.fingerprint=s),this.Ko&&(i.storageValue=ke.Ot(t)),"written"):(this.Rr.debug&&j.warn(`failed to persist storage entry "${t}"; will retry on next save`),"failed")}remove({keepGroupEntries:e=!1}={}){if(this.Ma(),O(this.Na)||(clearTimeout(this.Na),this.Na=void 0),this.qo.Lt(this.ha,!1),this.qo.Lt(this.ha,!0),!e&&this.la)for(const t of yi)ke.Lt(this.pa(t));e?delete this.Jo[Qe]:this.Jo={},this.Aa=void 0,this.Fa=void 0}clear(){this.remove(),this.props={}}register_once(e,t,r){if(be(e)){this.syncCookieProperties(),O(t)&&(t="None"),this.Va=O(r)?this.Qa:r;let n=!1;if(Ce(e,(i,s)=>{this.props.hasOwnProperty(s)&&this.props[s]!==t||(this.Ca(s,i),n=!0)}),n)return this.save(),!0}return!1}register(e,t){if(be(e)){this.syncCookieProperties(),this.Va=O(t)?this.Qa:t;let r=!1;if(Ce(e,(n,i)=>{e.hasOwnProperty(i)&&(this.props[i]!==n||be(n)||ce(n))&&(this.Ca(i,n),r=!0)}),r)return this.save(),!0}return!1}unregister(e){this.syncCookieProperties();const t=typeof e=="string"?[e]:e;let r=!1;for(const n of t)n in this.props&&(this.$a(n),r=!0);r&&this.save()}update_campaign_params(){const e=N?.URL;if(e===this.ua)return;const t=Gm(this.Rr.custom_campaign_params,this.Rr.mask_personal_data_properties,this.Rr.custom_personal_data_properties),r=!_t(Cu(t));return r&&this.register(t),this.ua=e,r?t:void 0}update_search_keyword(){this.register((function(){const e=N?.referrer;return e?Zm(e):{}})())}update_referrer_info(){var e;this.register_once({$referrer:Km(),$referring_domain:N?.referrer&&((e=Fr(N.referrer))===null||e===void 0?void 0:e.host)||Io},void 0)}set_initial_person_info(){if(this.props.$initial_campaign_params||this.props.$initial_referrer_info)return;const e=Ym(this.Rr.mask_personal_data_properties,this.Rr.custom_personal_data_properties,this.Rr.disable_capture_url_hashes);this.register_once({[Ln]:this.Xo?{r:$s(e.r),u:e.u?$s(e.u):void 0}:e},void 0)}get_initial_props(){const e={};Ce([Em,Sm],r=>{const n=this.props[r];n&&Ce(n,function(i,s){e["$initial_"+Jc(s)]=i})});const t=this.props[Ln];if(t){const r=(function(n,i=!1){const s=Xm(n,i),o={};return Ce(s,function(a,c){o[`$initial_${Jc(c)}`]=a}),o})(t,this.Rr.disable_capture_url_hashes);Le(e,r)}return e}safe_merge(e){return Ce(this.props,function(t,r){r in e||(e[r]=t)}),e}update_config(e,t,r){const n=e.persistence!==t.persistence,i=!((p,f)=>{if(p.length!==f.length)return!1;const v=[...p].sort(),m=[...f].sort();return v.every((_,w)=>_===m[w])})(e.cookie_persisted_properties||[],t.cookie_persisted_properties||[]),s=n||i,o=e.cookieWinsOnConflict!==t.cookieWinsOnConflict,a=e.disable_persistence||!!r,c=!!this.mi&&!a;a||this.Oa(t,c),this.Rr=e,!a&&(n||i||o)&&(this.Aa=void 0,this.Fa=void 0,this.Oa(b(b({},e),{},{cookie_persisted_properties:t.cookie_persisted_properties}),c));const l=s||o?this.ca(e):this.qo;this.Ja();const u=this.da(e),h=s||u!==this.Yo,d=!a&&(h||e.cross_subdomain_cookie!==this.Ga||e.secure_cookie!==this.Za)&&this.Da(c);this.na=h;try{if(this.Qa=this.Va=e.cookie_expiration,this.set_disabled(a),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),h){const p=this.props;this.clear(),this.qo=l,this.Yo=u,this.props=p,this.save()}else o&&(this.qo=l,a||(delete this.Jo[Qe],this.qa()))}finally{this.na=!1,d&&this.ja()}}Ja(){const e=this.props[Ln];if(!this.Xo||!be(e)||typeof e.r!="string")return;const t=$s(e.r),r=typeof e.u=="string"?$s(e.u):e.u;t===e.r&&r===e.u||this.Ca(Ln,b(b({},e),{},{r:t,u:r}))}set_disabled(e){this.mi=e,this.mi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ga&&(this.Ga=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.Za&&(this.Za=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,t){const r=this.props.__timers||{};r[e]=t,this.Ca(nl,r),this.save()}remove_event_timer(e){const t=this.props.__timers||{},r=t[e];return O(r)||(delete t[e],this.Ca(nl,t),this.save()),r}get_property(e){return this.props[e]}set_property(e,t){this.Ca(e,t),this.save()}Ca(e,t,r=!0){var n;const i=this.props[e];this.props[e]=t,r&&(e!=="distinct_id"&&e!=="$user_state"||i===t||(this.sa=!0),Vh(e)&&!ur(i,t)&&this.oa.add(e),this.Ea(e,i,t),(n=ot(e))!==null&&n!==void 0&&n.volatile||this.Ia(e))}$a(e,t=!0){delete this.props[e],t&&(Ja(e)&&this.ma(e,!0),Vh(e)&&this.oa.add(e),this.Ia(e))}Ia(e){var t;const r=(t=ot(e))===null||t===void 0?void 0:t.storageGroup;r&&(this.ya(r).dirty=!0)}ya(e){return this.Jo[e]||(this.Jo[e]={})}},St={GZipJS:"gzip-js",Base64:"base64"},bi={Activation:"events",Cancellation:"cancelEvents"},Ya={Popover:"popover",API:"api",Widget:"widget",ExternalSurvey:"external_survey"},or={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent",ABANDONED:"survey abandoned"},Xa={SURVEY_ID:"$survey_id",SURVEY_NAME:"$survey_name",SURVEY_RESPONSE:"$survey_response",SURVEY_ITERATION:"$survey_iteration",SURVEY_ITERATION_START_DATE:"$survey_iteration_start_date",SURVEY_PARTIALLY_COMPLETED:"$survey_partially_completed",SURVEY_SUBMISSION_ID:"$survey_submission_id",SURVEY_QUESTIONS:"$survey_questions",SURVEY_COMPLETED:"$survey_completed",PRODUCT_TOUR_ID:"$product_tour_id",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date",SURVEY_LANGUAGE:"$survey_language"},ml={Popover:"popover",Inline:"inline"};function Ps(e){let t=!0;return{dispose(){if(t){t=!1;const r=e();r&&tt(r.then)&&r.then(void 0,()=>{})}}}}var iP={SHOWN:"product tour shown",DISMISSED:"product tour dismissed",COMPLETED:"product tour completed",STEP_SHOWN:"product tour step shown",STEP_COMPLETED:"product tour step completed",BUTTON_CLICKED:"product tour button clicked",STEP_SELECTOR_FAILED:"product tour step selector failed",BANNER_CONTAINER_SELECTOR_FAILED:"product tour banner container selector failed",BANNER_ACTION_CLICKED:"product tour banner action clicked"},Gh={TOUR_ID:"$product_tour_id",TOUR_NAME:"$product_tour_name",TOUR_ITERATION:"$product_tour_iteration",TOUR_RENDER_REASON:"$product_tour_render_reason",TOUR_STEP_ID:"$product_tour_step_id",TOUR_STEP_ORDER:"$product_tour_step_order",TOUR_STEP_TYPE:"$product_tour_step_type",TOUR_DISMISS_REASON:"$product_tour_dismiss_reason",TOUR_BUTTON_TEXT:"$product_tour_button_text",TOUR_BUTTON_ACTION:"$product_tour_button_action",TOUR_BUTTON_LINK:"$product_tour_button_link",TOUR_BUTTON_TOUR_ID:"$product_tour_button_tour_id",TOUR_STEPS_COUNT:"$product_tour_steps_count",TOUR_STEP_SELECTOR:"$product_tour_step_selector",TOUR_STEP_SELECTOR_FOUND:"$product_tour_step_selector_found",TOUR_STEP_ELEMENT_TAG:"$product_tour_step_element_tag",TOUR_STEP_ELEMENT_ID:"$product_tour_step_element_id",TOUR_STEP_ELEMENT_CLASSES:"$product_tour_step_element_classes",TOUR_STEP_ELEMENT_TEXT:"$product_tour_step_element_text",TOUR_ERROR:"$product_tour_error",TOUR_MATCHES_COUNT:"$product_tour_matches_count",TOUR_FAILURE_PHASE:"$product_tour_failure_phase",TOUR_WAITED_FOR_ELEMENT:"$product_tour_waited_for_element",TOUR_WAIT_DURATION_MS:"$product_tour_wait_duration_ms",TOUR_BANNER_SELECTOR:"$product_tour_banner_selector",TOUR_LINKED_SURVEY_ID:"$product_tour_linked_survey_id",USE_MANUAL_SELECTOR:"$use_manual_selector",INFERENCE_DATA_PRESENT:"$inference_data_present",TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Wh=Be("[RateLimiter]"),sP=class{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=t=>{const r=t.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach(n=>{Wh.info(`${n||"events"} is quota limited.`),this.serverLimits[n]=new Date().getTime()+6e4})}catch(n){Wh.warn(`could not rate limit - continuing. Error: "${n?.message}"`,{text:r});return}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)===null||e===void 0?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)===null||e===void 0?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e=!1){var t,r,n;const{captureEventsBurstLimit:i,captureEventsPerSecond:s}=this,o=new Date().getTime(),a=(t=(r=this.instance.persistence)===null||r===void 0?void 0:r.get_property("$capture_rate_limit"))!==null&&t!==void 0?t:{tokens:i,last:o};a.tokens+=(o-a.last)/1e3*s,a.last=o,a.tokens>i&&(a.tokens=i);const c=1>a.tokens;if(c||e||(a.tokens=Math.max(0,a.tokens-1)),c&&!e){const l=(We(a.dropped)?a.dropped:0)+1;a.dropped=l,!this.lastEventRateLimited&&this.Ka(l)&&(a.dropped=0)}return this.lastEventRateLimited=c,(n=this.instance.persistence)===null||n===void 0||n.set_property("$capture_rate_limit",a),{isRateLimited:c,remainingTokens:a.tokens}}Xa(e){const t=this.instance.config.property_denylist;return!ce(t)||!t.includes(e)}Ya(){var e;if(this.Xa("$current_url")&&this.Xa("$pathname")&&je?.pathname)return`${(e=je.origin)!==null&&e!==void 0?e:""}${je.pathname}`}Ka(e){var t,r;const{captureEventsBurstLimit:n,captureEventsPerSecond:i}=this,s=this.Ya(),o=this.Xa("$session_id")?(t=(r=this.instance).get_session_id)===null||t===void 0?void 0:t.call(r):void 0,a=[`${e} event(s) dropped since the last warning`,s?`triggered on ${s}`:void 0,o?`session ${o}`:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:`posthog-js client rate limited: ${a}. Config is set to ${i} events per second and ${n} events burst limit.`},{skip_client_rate_limiting:!0})}isServerRateLimited(e){const t=this.serverLimits[e||"events"]||!1;return t!==!1&&new Date().getTime()<t}},dr=Be("[RemoteConfig]"),t_=class{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=te._POSTHOG_REMOTE_CONFIG)===null||e===void 0||(e=e[this._instance.config.token])===null||e===void 0?void 0:e.config}tl(e){var t,r,n;!((t=te.__PosthogExtensions__)===null||t===void 0)&&t.loadExternalDependency?(r=te.__PosthogExtensions__)===null||r===void 0||(n=r.loadExternalDependency)===null||n===void 0||n.call(r,this._instance,"remote-config",()=>e(this.remoteConfig)):e()}el(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets",`/array/${this._instance.config.token}/config`),callback:e})}load(){try{if(this.remoteConfig)return dr.info("Using preloaded remote config",this.remoteConfig),void this.il(this.remoteConfig);if(this._instance.nl())return void dr.warn("Remote config is disabled. Falling back to local config.");this.tl(e=>{if(!e)return dr.info("No config found after loading remote JS config. Falling back to JSON."),void this.el(t=>{this.il(t.json,t)});this.il(e)})}catch(e){dr.error("Error loading remote config",e),this.il()}}il(e,t){!e&&t&&(t.statusCode===0?t.error||dr.warn("Failed to fetch remote config from PostHog."):dr.error("Failed to fetch remote config from PostHog."));try{this._instance.il(e?{ok:!0,config:e}:{ok:!1})}catch(n){dr.error("Error applying remote config",n)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var r;(r=this._instance.featureFlags)===null||r===void 0||r.ensureFlagsLoaded()}catch(n){dr.error("Error loading feature flags",n)}}},Et=Uint8Array,gt=Uint16Array,ei=Uint32Array,Mu=new Et([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Lu=new Et([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Zh=new Et([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),r_=function(e,t){for(var r=new gt(31),n=0;31>n;++n)r[n]=t+=1<<e[n-1];var i=new ei(r[30]);for(n=1;30>n;++n)for(var s=r[n];r[n+1]>s;++s)i[s]=s-r[n]<<5|n;return[r,i]},n_=r_(Mu,2),_l=n_[1];n_[0][28]=258,_l[258]=28;for(var Jh=r_(Lu,0)[1],yl=new gt(32768),Ve=0;32768>Ve;++Ve){var Sn=(43690&Ve)>>>1|(21845&Ve)<<1;yl[Ve]=((65280&(Sn=(61680&(Sn=(52428&Sn)>>>2|(13107&Sn)<<2))>>>4|(3855&Sn)<<4))>>>8|(255&Sn)<<8)>>>1}var Fi=function(e,t,r){for(var n=e.length,i=0,s=new gt(t);n>i;++i)++s[e[i]-1];var o,a=new gt(t);for(i=0;t>i;++i)a[i]=a[i-1]+s[i-1]<<1;if(r){o=new gt(1<<t);var c=15-t;for(i=0;n>i;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],h=a[e[i]-1]++<<u,d=h|(1<<u)-1;d>=h;++h)o[yl[h]>>>c]=l}else for(o=new gt(n),i=0;n>i;++i)o[i]=yl[a[e[i]-1]++]>>>15-e[i];return o},vn=new Et(288);for(Ve=0;144>Ve;++Ve)vn[Ve]=8;for(Ve=144;256>Ve;++Ve)vn[Ve]=9;for(Ve=256;280>Ve;++Ve)vn[Ve]=7;for(Ve=280;288>Ve;++Ve)vn[Ve]=8;var To=new Et(32);for(Ve=0;32>Ve;++Ve)To[Ve]=5;var oP=Fi(vn,9,0),aP=Fi(To,5,0),i_=function(e){return(e/8|0)+(7&e&&1)},s_=function(e,t,r){(t==null||0>t)&&(t=0),(r==null||r>e.length)&&(r=e.length);var n=new(e instanceof gt?gt:e instanceof ei?ei:Et)(r-t);return n.set(e.subarray(t,r)),n},Yt=function(e,t,r){var n=t/8|0;e[n]|=r<<=7&t,e[n+1]|=r>>>8},wi=function(e,t,r){var n=t/8|0;e[n]|=r<<=7&t,e[n+1]|=r>>>8,e[n+2]|=r>>>16},Qa=function(e,t){for(var r=[],n=0;e.length>n;++n)e[n]&&r.push({s:n,f:e[n]});var i=r.length,s=r.slice();if(!i)return[new Et(0),0];if(i==1){var o=new Et(r[0].s+1);return o[r[0].s]=1,[o,1]}r.sort(function(C,$){return C.f-$.f}),r.push({s:-1,f:25001});var a=r[0],c=r[1],l=0,u=1,h=2;for(r[0]={s:-1,f:a.f+c.f,l:a,r:c};u!=i-1;)a=r[r[h].f>r[l].f?l++:h++],c=r[l!=u&&r[h].f>r[l].f?l++:h++],r[u++]={s:-1,f:a.f+c.f,l:a,r:c};var d=s[0].s;for(n=1;i>n;++n)s[n].s>d&&(d=s[n].s);var p=new gt(d+1),f=bl(r[u-1],p,0);if(f>t){n=0;var v=0,m=f-t,_=1<<m;for(s.sort(function(C,$){return p[$.s]-p[C.s]||C.f-$.f});i>n;++n){var w=s[n].s;if(t>=p[w])break;v+=_-(1<<f-p[w]),p[w]=t}for(v>>>=m;v>0;){var S=s[n].s;t>p[S]?v-=1<<t-p[S]++-1:++n}for(;n>=0&&v;--n){var T=s[n].s;p[T]==t&&(--p[T],++v)}f=t}return[new Et(p),f]},bl=function(e,t,r){return e.s==-1?Math.max(bl(e.l,t,r+1),bl(e.r,t,r+1)):t[e.s]=r},Kh=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new gt(++t),n=0,i=e[0],s=1,o=function(c){r[n++]=c},a=1;t>=a;++a)if(e[a]==i&&a!=t)++s;else{if(!i&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(i),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(i);s=1,i=e[a]}return[r.subarray(0,n),t]},Si=function(e,t){for(var r=0,n=0;t.length>n;++n)r+=e[n]*t[n];return r},Xs=function(e,t,r){var n=r.length,i=i_(t+2);e[i]=255&n,e[i+1]=n>>>8,e[i+2]=255^e[i],e[i+3]=255^e[i+1];for(var s=0;n>s;++s)e[i+s+4]=r[s];return 8*(i+4+n)},Yh=function(e,t,r,n,i,s,o,a,c,l,u){Yt(t,u++,r),++i[256];for(var h=Qa(i,15),d=h[0],p=h[1],f=Qa(s,15),v=f[0],m=f[1],_=Kh(d),w=_[0],S=_[1],T=Kh(v),C=T[0],$=T[1],M=new gt(19),L=0;w.length>L;++L)M[31&w[L]]++;for(L=0;C.length>L;++L)M[31&C[L]]++;for(var q=Qa(M,7),X=q[0],ee=q[1],k=19;k>4&&!X[Zh[k-1]];--k);var ie,H,oe,I,Q=l+5<<3,y=Si(i,vn)+Si(s,To)+o,V=Si(i,d)+Si(s,v)+o+14+3*k+Si(M,X)+(2*M[16]+3*M[17]+7*M[18]);if(y>=Q&&V>=Q)return Xs(t,u,e.subarray(c,c+l));if(Yt(t,u,1+(y>V)),u+=2,y>V){ie=Fi(d,p,0),H=d,oe=Fi(v,m,0),I=v;var K=Fi(X,ee,0);for(Yt(t,u,S-257),Yt(t,u+5,$-1),Yt(t,u+10,k-4),u+=14,L=0;k>L;++L)Yt(t,u+3*L,X[Zh[L]]);u+=3*k;for(var le=[w,C],de=0;2>de;++de){var $e=le[de];for(L=0;$e.length>L;++L)Yt(t,u,K[Re=31&$e[L]]),u+=X[Re],Re>15&&(Yt(t,u,$e[L]>>>5&127),u+=$e[L]>>>12)}}else ie=oP,H=vn,oe=aP,I=To;for(L=0;a>L;++L)if(n[L]>255){var Re;wi(t,u,ie[257+(Re=n[L]>>>18&31)]),u+=H[Re+257],Re>7&&(Yt(t,u,n[L]>>>23&31),u+=Mu[Re]);var _e=31&n[L];wi(t,u,oe[_e]),u+=I[_e],_e>3&&(wi(t,u,n[L]>>>5&8191),u+=Lu[_e])}else wi(t,u,ie[n[L]]),u+=H[n[L]];return wi(t,u,ie[256]),u+H[256]},cP=new ei([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),lP=new Et(0),uP=(function(){for(var e=new ei(256),t=0;256>t;++t){for(var r=t,n=9;--n;)r=(1&r&&3988292384)^r>>>1;e[t]=r}return e})(),ec=function(e,t,r){for(;r;++t)e[t]=r,r>>>=8};function dP(e,t){t===void 0&&(t={});var r=(function(){var d=4294967295;return{p(p){for(var f=d,v=0;p.length>v;++v)f=uP[255&f^p[v]]^f>>>8;d=f},d(){return 4294967295^d}}})(),n=e.length;r.p(e);var i,s,o,a,c,l,u=(a=10+((i=t).filename&&i.filename.length+1||0),c=8,(function(d,p,f,v,m,_){var w=d.length,S=new Et(v+w+5*(1+Math.floor(w/7e3))+m),T=S.subarray(v,S.length-m),C=0;if(!p||8>w)for(var $=0;w>=$;$+=65535){var M=$+65535;w>M?C=Xs(T,C,d.subarray($,M)):(T[$]=_,C=Xs(T,C,d.subarray($,w)))}else{for(var L=cP[p-1],q=L>>>13,X=8191&L,ee=(1<<f)-1,k=new gt(32768),ie=new gt(ee+1),H=Math.ceil(f/3),oe=2*H,I=function(g){return(d[g]^d[g+1]<<H^d[g+2]<<oe)&ee},Q=new ei(25e3),y=new gt(288),V=new gt(32),K=0,le=0,de=($=0,0),$e=0,Re=0;w>$;++$){var _e=I($),ve=32767&$,Je=ie[_e];if(k[ve]=Je,ie[_e]=ve,$>=$e){var Xe=w-$;if((K>7e3||de>24576)&&Xe>423){C=Yh(d,T,0,Q,y,V,le,de,Re,$-Re,C),de=K=le=0,Re=$;for(var Pe=0;286>Pe;++Pe)y[Pe]=0;for(Pe=0;30>Pe;++Pe)V[Pe]=0}var z=2,se=0,ae=X,he=ve-Je&32767;if(Xe>2&&_e==I($-he))for(var Oe=Math.min(q,Xe)-1,we=Math.min(32767,$),Se=Math.min(258,Xe);we>=he&&--ae&&ve!=Je;){if(d[$+z]==d[$+z-he]){for(var pe=0;Se>pe&&d[$+pe]==d[$+pe-he];++pe);if(pe>z){if(z=pe,se=he,pe>Oe)break;var me=Math.min(he,pe-2),Ee=0;for(Pe=0;me>Pe;++Pe){var Ge=$-he+Pe+32768&32767,U=Ge-k[Ge]+32768&32767;U>Ee&&(Ee=U,Je=Ge)}}}he+=(ve=Je)-(Je=k[ve])+32768&32767}if(se){Q[de++]=268435456|_l[z]<<18|Jh[se];var W=31&_l[z],Y=31&Jh[se];le+=Mu[W]+Lu[Y],++y[257+W],++V[Y],$e=$+z,++K}else Q[de++]=d[$],++y[d[$]]}}C=Yh(d,T,_,Q,y,V,le,de,Re,$-Re,C),_||(C=Xs(T,C,lP))}return s_(S,0,v+i_(C)+m)})(s=e,(o=t).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,c,!l)),h=u.length;return(function(d,p){var f=p.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>p.level?4:p.level==9?2:0,d[9]=3,p.mtime!=0&&ec(d,4,Math.floor(new Date(p.mtime||Date.now())/1e3)),f){d[3]=8;for(var v=0;f.length>=v;++v)d[v+10]=f.charCodeAt(v)}})(u,t),ec(u,h-8,r.d()),ec(u,h-4,n),u}var hP=!!mu||!!Yi,o_=new WeakMap,a_="text/plain",tc=0,Qs=!1,c_=(e,t)=>{const[r,n]=e.split("#"),[i,s]=r.split("?");if(!s)return e;const o=s.split("&").filter(a=>a.split("=")[0]!==t).join("&");return`${i}${o?`?${o}`:""}${n?`#${n}`:""}`},ds=(e,t,r=!0)=>{var n;const[i,s]=e.split("?"),o=b({},t),a=(n=s?.split("&").map(l=>{var u;const[h,d]=l.split("="),p=r&&(u=o[h])!==null&&u!==void 0?u:d;return delete o[h],`${h}=${p}`}))!==null&&n!==void 0?n:[],c=(function(l,u="&"){let h,d;const p=[];return Ce(l,function(f,v){O(f)||O(v)||v==="undefined"||(h=encodeURIComponent((m=>m instanceof File)(f)?f.name:f.toString()),d=encodeURIComponent(v),p[p.length]=d+"="+h)}),p.join(u)})(o);return c&&a.push(c),a.length>0?`${i}?${a.join("&")}`:i},rc=e=>{if(e.sl)return e.sl;const{data:t,compression:r}=e;if(!t)return;if(r===St.GZipJS){const i=dP((function(s){var o=s.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(s);for(var a=new Et(s.length+(s.length>>>1)),c=0,l=function(p){a[c++]=p},u=0;o>u;++u){if(c+5>a.length){var h=new Et(c+8+(o-u<<1));h.set(a),a=h}var d=s.charCodeAt(u);128>d?l(d):2048>d?(l(192|d>>>6),l(128|63&d)):d>55295&&57344>d?(l(240|(d=65536+(1047552&d)|1023&s.charCodeAt(++u))>>>18),l(128|d>>>12&63),l(128|d>>>6&63),l(128|63&d)):(l(224|d>>>12),l(128|d>>>6&63),l(128|63&d))}return s_(a,0,c)})(Nn(t)),{mtime:0});return{contentType:a_,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(r===St.Base64){const i=(s=>"data="+encodeURIComponent(typeof s=="string"?s:Nn(s)))((function(s){return s&&btoa(encodeURIComponent(s).replace(/%([0-9A-F]{2})/g,(o,a)=>String.fromCharCode(parseInt(a,16))))})(Nn(t)));return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}const n=Nn(t);return{contentType:"application/json",body:n,estimatedSize:new Blob([n]).size}},l_=e=>{const t=()=>e.transport==="sendBeacon"?{url:ds(e.url,{compression:St.Base64}),encodedBody:rc(b(b({},e),{},{compression:St.Base64,sl:void 0}))}:{url:c_(e.url,"compression"),encodedBody:rc(b(b({},e),{},{compression:void 0,sl:void 0}))};let r;try{r=rc(e)}catch(i){if(mh(e.compression,Xn(e.url,"compression")))return j.error("Failed to gzip request body, sending uncompressed payload",i),t();throw i}return r&&mh(e.compression,Xn(e.url,"compression"))&&!((n=r.body)instanceof ArrayBuffer?tl(new Uint8Array(n)):ArrayBuffer.isView(n)&&tl(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(Qs=!0,t()):{url:e.url,encodedBody:r};var n},u_=e=>{try{return l_(e)}catch(r){var t;j.error(r),(t=e.callback)===null||t===void 0||t.call(e,{statusCode:0,error:r});return}},pP=(function(){var e=Ue(function*(t){const r=yield(function(i){return rl.apply(this,arguments)})(Nn(t.data),et.DEBUG,{rethrow:!0});if(!r)return t;const n=yield r.arrayBuffer();return b(b({},t),{},{sl:{contentType:a_,body:n,estimatedSize:n.byteLength}})});return function(t){return e.apply(this,arguments)}})(),fP=/Failed to fetch|NetworkError|Load failed/i,d_=e=>e?.name==="TypeError"&&fP.test(e?.message||""),h_=e=>{try{const t=(function(r,n=Date.now()){if(typeof r!="string"||!r)return;const i=r.trim(),s=/^\d+\s*,/.test(i)?i.slice(0,i.indexOf(",")).trim():i;if(/^\d+$/.test(s)){const c=1e3*Math.min(Number(s),300);return c>0?c:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(s))return;const o=/^\w{3} \w{3} /.test(s)?s+" GMT":s,a=Date.parse(o)-n;return Number.isFinite(a)&&a>0?Math.min(a,Js):void 0})(e());return O(t)?void 0:Math.min(t,3e4)}catch{return}},p_=e=>{const t=u_(e);if(!t)return;const r=new mu;o_.set(r,!0);const{url:n,encodedBody:i}=t;r.open(e.method||"GET",n,!0);const{contentType:s,body:o}=i??{};Ce(e.headers,function(a,c){r.setRequestHeader(c,a)}),s&&r.setRequestHeader("Content-Type",s),e.timeout&&(r.timeout=e.timeout),r.onreadystatechange=()=>{if(r.readyState===4){var a;const c={statusCode:r.status,text:r.responseText};if(r.status===200)try{c.json=JSON.parse(r.responseText)}catch{}(a=e.callback)===null||a===void 0||a.call(e,c,h_(()=>r.getResponseHeader("Retry-After")))}},r.send(o)},f_=e=>{const t=u_(e);if(!t)return;const{url:r,encodedBody:n}=t,{contentType:i,body:s,estimatedSize:o}=n??{},a=new Headers;Ce(e.headers,function(f,v){a.append(v,f)}),i&&a.append("Content-Type",i);let c=null,l=!1;if(th){const f=new th;c={signal:f.signal,timeout:setTimeout(()=>{l=!0;try{f.abort(Zg("AbortError","PostHog request timed out"+((v=e.timeout)?` after ${v}ms`:"")))}catch(m){h(m)}var v},e.timeout)}}let u=!1;const h=f=>{var v;u||(u=!0,l&&f?.name==="AbortError"||d_(f)?j.warn(f):j.error(f),(v=e.callback)===null||v===void 0||v.call(e,{statusCode:0,error:f}))};let d=0;const p=()=>{tc-=d,d=0,c&&clearTimeout(c.timeout)};try{const f=b({method:e?.method||"GET",headers:a,referrerPolicy:"strict-origin",body:s,signal:c?.signal},e.fetchOptions),v=o??(O(s)?0:void 0);f.keepalive=f.method==="POST"&&!e.rl&&f.keepalive!==!1&&f.body===s&&!O(v)&&v>=0&&52428.8>tc+v,f.keepalive&&(d=v,tc+=d),Yi(r,f).then(m=>m.text().then(_=>{var w;if(u)return;const S={statusCode:m.status,text:_};if(m.status===200)try{S.json=JSON.parse(_)}catch(T){j.error(T)}u=!0,p(),(w=e.callback)===null||w===void 0||w.call(e,S,h_(()=>m.headers.get("Retry-After")))})).catch(m=>{p(),h(m)}).finally(p)}catch(f){p(),h(f)}},wl=e=>{try{var t;const{url:r,encodedBody:n}=l_(e),{contentType:i,body:s,estimatedSize:o}=n??{};if(!s)return;const a=s instanceof Blob?s:new Blob([s],{type:i});if(rt.sendBeacon(r,a))return;const c=ce(e.data)?e.data:(t=e.data)===null||t===void 0?void 0:t.batch;if(ce(c)&&c.length>1&&(o??0)>16384){const l=Math.ceil(c.length/2),u=h=>ce(e.data)?h:b(b({},e.data),{},{batch:h});wl(b(b({},e),{},{data:u(c.slice(0,l))})),wl(b(b({},e),{},{data:u(c.slice(l))}));return}j.warn(`Beacon of ~${o??0} bytes was rejected by the browser, falling back to ${Yi?"fetch":"XHR"}`),Yi?f_(b(b({},e),{},{rl:!0})):p_(e)}catch(r){j.warn("Beacon send failed",r)}},Xh=(e,t,r,n)=>{const i=n==="query"?t==="POST"?"sent_at":"_":void 0;return ds(r===St.GZipJS?c_(e,"compression"):e,b(b({},i?{[i]:Date.now().toString()}:{}),r===St.GZipJS?{}:{compression:r}))},vP=(()=>{const e=[];return Yi&&e.push({transport:"fetch",method:f_}),mu&&e.push({transport:"XHR",method:p_}),rt!=null&&rt.sendBeacon&&e.push({transport:"sendBeacon",method:wl}),e})(),v_=!hP&&pt?.indexOf("MSIE")===-1&&pt?.indexOf("Mozilla")===-1;function g_(e,t,r){var n,i,s;r&&(t=b(b({},t),{},{callback:o=>r(o)})),e.__loaded?v_?e.__request_queue.push(t):e.rateLimiter.isServerRateLimited(t.batchKey)?t.fireCallbackOnDrop&&((i=t.callback)===null||i===void 0||i.call(t,{statusCode:429})):(t.transport=t.transport||e.config.api_transport,t.headers=b(b({},e.config.request_headers),t.headers),t.compression=t.compression==="best-available"?(n=e.compression)!==null&&n!==void 0?n:t.compressionFallback:t.compression,(O(e.config.disable_beacon)?e.config.__preview_disable_beacon:e.config.disable_beacon)&&(t.disableTransport=["sendBeacon"]),t.fetchOptions=t.fetchOptions||e.config.fetch_options,((o,a)=>{var c,l,u;const h=b(b({},o),{},{callback:a??(m=>{var _;return(_=o.callback)===null||_===void 0?void 0:_.call(o,m)})});h.timeout=h.timeout||6e4;const d=(c=h.transport)!==null&&c!==void 0?c:"fetch";d==="sendBeacon"&&O(h.compression)&&h.data&&(h.compression=St.Base64),h.method==="POST"&&h.data&&(h.timestampMode==="capture-body"?h.data=(m=>{var _,w;const S=(ce(m)?m:[m]).map(C=>b(b({},C),C.timestamp instanceof Date&&!isNaN(C.timestamp.getTime())?{timestamp:C.timestamp.toISOString()}:{})),T=S[0];return{api_key:(_=T==null||(w=T.properties)===null||w===void 0?void 0:w.token)!==null&&_!==void 0?_:T?.token,batch:S,sent_at:new Date().toISOString()}})(h.data):h.timestampMode==="body"&&(h.data=((m,_=new Date().toISOString())=>ce(m)?m.map(w=>b(b({},w),{},{sent_at:_})):b(b({},m),{},{sent_at:_}))(h.data))),h.url=Xh(h.url,h.method,h.compression,h.timestampMode);const p=vP.filter(m=>!h.disableTransport||!m.transport||!h.disableTransport.includes(m.transport)),f=(l=(u=(function(m,_){for(let w=0;m.length>w;w++)if(_(m[w]))return m[w]})(p,m=>m.transport===d))===null||u===void 0?void 0:u.method)!==null&&l!==void 0?l:p[0].method;if(!f)throw new Error("No available transport method");const v=m=>{try{f(m)}catch(w){var _;d_(w)?j.warn(w):j.error(w),(_=h.callback)===null||_===void 0||_.call(h,{statusCode:0,error:w})}};d!=="sendBeacon"&&!h.preferSyncCompression&&h.data&&h.compression===St.GZipJS&&XT&&typeof Promise<"u"&&!Qs?pP(h).then(m=>{v(m)}).catch(m=>{if(_h(m))return Qs=!0,void v(b(b({},h),{},{compression:void 0,url:Xh(o.url,o.method,void 0,o.timestampMode)}));(_=>{if(!_||typeof _!="object")return!1;const w="name"in _?String(_.name):"";return _h(_)||w===tm})(m)&&(Qs=!0),v(h)}):v(h)})(t,(o,a)=>{var c,l,u;e.rateLimiter.checkForLimiting(o),400>o.statusCode||(c=(l=e.config).on_request_error)===null||c===void 0||c.call(l,o),r?r(o,a):(u=t.callback)===null||u===void 0||u.call(t,o)})):t.fireCallbackOnDrop&&((s=t.callback)===null||s===void 0||s.call(t,{statusCode:0}))}var gP=class{constructor(e,t){this.ol=!0,this.al=[],this.ll=Bt(t?.flush_interval_ms||3e3,250,5e3,j.createLogger("flush interval"),3e3),this.ul=e}enqueue(e){this.al.push(e),this.hl||this.cl()}unload(){this.dl();const e=this.al.length>0?this.vl():{},t=Object.values(e);[...t.filter(r=>r.url.indexOf("/e")===0),...t.filter(r=>r.url.indexOf("/e")!==0)].map(r=>{this.fl(r,"sendBeacon")})}enable(){this.ol=!1,this.cl()}cl(){this.ol||(this.hl=setTimeout(()=>{if(this.dl(),this.al.length>0){const e=this.vl();for(const t in e)this.fl(e[t])}},this.ll))}fl(e,t){try{this.ul(e,t)}catch(r){j.error(r)}}dl(){clearTimeout(this.hl),this.hl=void 0}vl(){const e={};return Ce(this.al,t=>{var r;const n=t,i=((n?n.batchKey:null)||n.url)+(n.batchGroup?`:${n.batchGroup}`:"");O(e[i])&&(e[i]=b(b({},n),{},{data:[]})),(r=e[i].data)===null||r===void 0||r.push(n.data)}),this.al=[],e}},mP=["retriesPerformedSoFar"],_P=class{constructor(e){this._instance=e,this.pl=!1,this.gl=3e3,this.al=[],this.al=[],this.ml=!0,this.resume()}resume(){if(!O(A)&&"onLine"in A.navigator){if(this.ml=A.navigator.onLine,this.yl)return;this.yl=()=>{this.ml=!0,this.bl()},this._l=()=>{this.ml=!1},Ie(A,"online",this.yl),Ie(A,"offline",this._l)}}get length(){return this.al.length}retriableRequest(e,t){let{retriesPerformedSoFar:r}=e,n=rm(e,mP);tr(r)&&(n.url=ds(n.url,{retry_count:r})),g_(this._instance,t?b(b({},n),{},{transport:t}):n,(i,s)=>{var o;if(i.statusCode!==200&&(400>i.statusCode||i.statusCode>=500)){if((i.statusCode===0?3:10)>(r??0))return void this.Ls(b({retriesPerformedSoFar:r},n),s);i.statusCode===0&&j.warn(`Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after ${r??0} retries.`)}(o=n.callback)===null||o===void 0||o.call(n,i)})}Ls(e,t){const r=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=r+1;const n=Math.max((function(o){const a=3e3*Math.pow(2,o),c=a/2,l=Math.min(18e5,a),u=(Math.random()-.5)*(l-c);return Math.ceil(l+u)})(r),t??0),i=Date.now()+n;this.al.push({retryAt:i,requestOptions:e});let s=`Enqueued failed request for retry in ${n}`;navigator.onLine||(s+=" (Browser is offline)"),j.warn(s),this.pl||(this.pl=!0,this.wl())}wl(){if(this.kl&&clearTimeout(this.kl),this.al.length===0)return this.pl=!1,void(this.kl=void 0);this.kl=setTimeout(()=>{this.ml&&this.al.length>0&&this.bl(),this.wl()},this.gl)}bl(){const e=Date.now(),t=[],r=this.al.filter(n=>e>n.retryAt||(t.push(n),!1));if(this.al=t,r.length>0)for(const{requestOptions:n}of r)this.retriableRequest(n)}unload(){this.kl&&(clearTimeout(this.kl),this.kl=void 0),this.pl=!1,O(A)||(this.yl&&(A.removeEventListener("online",this.yl),this.yl=void 0),this._l&&(A.removeEventListener("offline",this._l),this._l=void 0));for(const{requestOptions:e}of this.al)try{this._instance._send_request(b(b({},e),{},{transport:"sendBeacon"}))}catch(t){j.error(t)}this.al=[]}},yP=class{constructor(e){this._instance=e,this.Sl=()=>{var t,r,n,i;this.xl||(this.xl={});const s=this.scrollElement(),o=this.scrollY(),a=s?Math.max(0,s.scrollHeight-s.clientHeight):0,c=o+(s?.clientHeight||0),l=s?.scrollHeight||0;this.xl.lastScrollY=Math.ceil(o),this.xl.maxScrollY=Math.max(o,(t=this.xl.maxScrollY)!==null&&t!==void 0?t:0),this.xl.maxScrollHeight=Math.max(a,(r=this.xl.maxScrollHeight)!==null&&r!==void 0?r:0),this.xl.lastContentY=c,this.xl.maxContentY=Math.max(c,(n=this.xl.maxContentY)!==null&&n!==void 0?n:0),this.xl.maxContentHeight=Math.max(l,(i=this.xl.maxContentHeight)!==null&&i!==void 0?i:0)}}get Cl(){return this._instance.config.scroll_root_selector}getContext(){return this.xl}resetContext(){const e=this.xl;return this.xl=void 0,setTimeout(this.Sl,0),e}startMeasuringScrollPosition(){Ie(A,"scroll",this.Sl,{capture:!0}),Ie(A,"scrollend",this.Sl,{capture:!0}),Ie(A,"resize",this.Sl)}scrollElement(){if(this.Cl){const r=ce(this.Cl)?this.Cl:[this.Cl];for(const n of r){var e;const i=A==null||(e=A.document)===null||e===void 0?void 0:e.querySelector(n);if(i)return i}return}var t;return A==null||(t=A.document)===null||t===void 0?void 0:t.documentElement}$l(e){var t,r;const n=e==="y"?"scrollTop":"scrollLeft";if(this.Cl){const i=this.scrollElement();return i&&i[n]||0}return A?e==="y"?A.scrollY||A.pageYOffset||((t=A.document)===null||t===void 0||(t=t.documentElement)===null||t===void 0?void 0:t.scrollTop)||0:A.scrollX||A.pageXOffset||((r=A.document)===null||r===void 0||(r=r.documentElement)===null||r===void 0?void 0:r.scrollLeft)||0:0}scrollY(){return this.$l("y")}scrollX(){return this.$l("x")}},bP=e=>Ym(e?.config.mask_personal_data_properties,e?.config.custom_personal_data_properties,e?.config.disable_capture_url_hashes),Qh=class{constructor(e,t,r,n){this.Be=i=>{const s=this.Tl();if(s&&s.sessionId===i)return;const o={sessionId:i,props:this.Il(this._instance)};this.Ml.register({[dl]:o})},this._instance=e,this.El=t,this.Ml=r,this.Il=n||bP,this.El.onSessionId(this.Be)}Tl(){return this.Ml.props[dl]}getSetOnceProps(){var e;const t=(e=this.Tl())===null||e===void 0?void 0:e.props;return t?"r"in t?Xm(t,this._instance.config.disable_capture_url_hashes):{$referring_domain:t.referringDomain,$pathname:t.initialPathName,utm_source:t.utm_source,utm_campaign:t.utm_campaign,utm_medium:t.utm_medium,utm_content:t.utm_content,utm_term:t.utm_term}:{}}getSessionProps(){const e={};return Ce(Cu(this.getSetOnceProps()),(t,r)=>{r==="$current_url"&&(r="url"),e[`$session_entry_${Jc(r)}`]=t}),e}},Co=class{on(e,t){return this.Pl[e]||(this.Pl[e]=[]),this.Pl[e].push(t),()=>{this.Pl[e]=this.Pl[e].filter(r=>r!==t)}}emit(e,t){for(const r of this.Pl[e]||[])r(t);for(const r of this.Pl["*"]||[])r(e,t)}constructor(){this.Pl={}}},En=Be("[SessionId]"),ep=864e5,tp=class{on(e,t){return this.Rl.on(e,t)}constructor(e,t,r){var n;if(this.Al=null,this.Fl=null,this.Ol=[],this.Dl=void 0,this.Ll=!1,this.Rl=new Co,this.Nl=(s,o)=>!(!tr(s)||!tr(o))&&Math.abs(s-o)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Rr=e.config,this.Ml=e.persistence,this.He=void 0,this.Xt=void 0,this._sessionStartTimestamp=null,this.ql=void 0,this._sessionActivityTimestamp=null,this.jl=t||Lt,this.Bl=r||Lt;const i=this.Rr.persistence_name||this.Rr.token;if(this._sessionTimeoutMs=1e3*Bt(this.Rr.session_idle_timeout_seconds||1800,60,36e3,En.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.Hl(),this.zl="ph_"+i+"_window_id",this.Ul="ph_"+i+"_primary_window_exists",this.Wl()){const s=xe.Dt(this.zl),o=xe.Dt(this.Ul);s&&!o?this.He=s:xe.Lt(this.zl),xe.At(this.Ul,!0)}(n=this.Rr.bootstrap)!==null&&n!==void 0&&n.sessionID&&this.setBootstrapSessionId(this.Rr.bootstrap.sessionID),this.Vl()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return O(this.Ol)&&(this.Ol=[]),this.Ol.push(e),this.Xt&&e(this.Xt,this.He),()=>{this.Ol=this.Ol.filter(t=>t!==e)}}Wl(){return this.Rr.persistence!=="memory"&&!this.Ml.mi&&xe.Et()}Gl(e){e!==this.He&&(this.He=e,this.Wl()&&xe.At(this.zl,e))}Zl(){return this.He?this.He:this.Wl()?xe.Dt(this.zl):null}Ql(e){const t=this.Al;return!He(t)&&!He(e)&&5e3>Math.abs(e-t)}Jl(e,t,r){const n=t!==this._sessionActivityTimestamp,i=!(e!==this.Xt||r!==this._sessionStartTimestamp);this._sessionStartTimestamp=r,this._sessionActivityTimestamp=t,this.Xt=e,i&&!n||i&&this.Ql(t)||(this.Al=t,this.Ml.register({[Mn]:[t,e,r]}))}Kl(){var e;const t=(e=this.Rr)===null||e===void 0?void 0:e.persistence_save_debounce_ms;return tr(t)&&t>0}Xl(){this.Kl()?this.Ml.refreshKey(Mn):(this.Ml.flush(),this.Ml.load())}Yl(){var e;if(He(this._sessionActivityTimestamp)||this._sessionActivityTimestamp===this.Al)return;this.Xl();const[,t,r]=this.tu();t===this.Xt&&r===this._sessionStartTimestamp&&(this.Al=this._sessionActivityTimestamp,this.Ml.register({[Mn]:[this._sessionActivityTimestamp,(e=this.Xt)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Ml.flush())}eu(){const[e]=this.tu(),t=tr(e)?e:0,r=tr(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(t,r)}iu(e){return this.Xl(),this.Nl(e,this.eu())}tu(){const e=this.Ml.props[Mn];return ce(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Al=null,this.ql=void 0,clearTimeout(this.nu),this.nu=void 0,this.Jl(null,null,null)}setBootstrapSessionId(e,t=!1){const r=((n,i=new Date().getTime())=>{try{const s=(o=>{const a=o.replace(/-/g,"");if(a.length!==32)throw new Error("Not a valid UUID");if(a[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(a.substring(0,12),16)})(n);return s>i+6e4?void En.error("Bootstrap sessionID cannot be in the future"):s}catch(s){En.error("Invalid sessionID in bootstrap",s);return}})(e);return!O(r)&&(t?this.ql={sessionId:e,sessionStartTimestamp:r}:this.Jl(e,new Date().getTime(),r),!0)}destroy(){this.Ll=!0,this.Yl(),clearTimeout(this.nu),this.nu=void 0,this.Dl&&A&&(A.removeEventListener(ko,this.Dl,{capture:!1}),this.Dl=void 0),this.Ol=[]}Vl(){this.Dl=()=>{this.Yl(),this.Wl()&&xe.Lt(this.Ul)},Ie(A,ko,this.Dl,{capture:!1})}checkAndGetSessionAndWindowId(e=!1,t=null,r=!1){if(this.Rr.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');const n=t||new Date().getTime(),i=this.Xt;if(r)this.Fl=n;else if(He(this.Fl)||this.Fl>n||n-this.Fl>=1e3){var s,o;(s=(o=this.Ml).syncCookieProperties)===null||s===void 0||s.call(o),this.Fl=n}let[,a,c]=this.tu();const l=!O(i)&&a!==i,u=this.eu();let h=this.Zl();const d=this.ql,p=!!d&&(d.sessionStartTimestamp>n+6e4||n-d.sessionStartTimestamp>ep),f=d?p:tr(c)&&Math.abs(n-c)>ep;let v=!1,m=l,_=!a||!!d;const w=a;let S=!_&&!e&&this.Nl(n,u);if(S&&(S=this.iu(n),S||En.info("cross-tab refresh kept the session alive",{sessionId:a}),[,a,c]=this.tu(),S||(_=!a||!!d)),_||S||f){m=!1;const M=d&&!p;a=M?d.sessionId:this.jl(),h=this.Bl(),En.info("new session ID assigned",{sessionId:a,windowId:h,bootstrapped:!!M,changeReason:{noSessionId:_,activityTimeout:S,sessionPastMaximumLength:f}}),c=M?d.sessionStartTimestamp:n,this.ql=void 0,v=!0}else h||(h=this.Bl(),v=!0),m=m||a!==w,m&&(En.info("adopted cross-tab session id",{sessionId:a,windowId:h}),v=!0);const T=tr(u)&&e&&!f?u:n,C=tr(c)?c:new Date().getTime();this.Gl(h),this.Jl(a,T,C),e||this.Hl();const $={noSessionId:_,activityTimeout:S,sessionPastMaximumLength:f,crossTabAdoption:m};return v&&this.Ol.forEach(M=>M(a,h,$)),{sessionId:a,windowId:h,sessionStartTimestamp:C,changeReason:v?$:void 0,lastActivityTimestamp:u}}Hl(){this.Ll||(clearTimeout(this.nu),this.nu=setTimeout(()=>{if(!this.Ll)if(this.iu(new Date().getTime())){const e=this.Xt;this.resetSessionId(),this.Rl.emit("forcedIdleReset",{idleSessionId:e})}else this.Hl()},1.1*this.sessionTimeoutMs))}},m_=function(e,t){if(!e)return!1;const r=e.userAgent;if(r&&ih(r,t))return!0;try{const n=e?.userAgentData;if(n?.brands&&n.brands.some(i=>ih(i?.brand,t)))return!0}catch{}return!!e.webdriver};function __(){return(__=Ue(function*(){const e=rt?.userAgentData;if(e?.getHighEntropyValues)try{const t=yield e.getHighEntropyValues(["model"]),r=t?.model;return ye(r)&&r.length>0?r:void 0}catch(t){j.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",t);return}})).apply(this,arguments)}function wP(e,t){let r=`$survey_${t}/${e.id}`;return e.current_iteration&&e.current_iteration>0&&(r=`$survey_${t}/${e.id}/${e.current_iteration}`),r}function y_(e){var t;return!!(!((t=e.conditions)===null||t===void 0||(t=t.events)===null||t===void 0||(t=t.values)===null||t===void 0)&&t.length)}var $o=(e,t)=>{if(!(r=>{try{new RegExp(r)}catch{return!1}return!0})(t))return!1;try{return new RegExp(t).test(e)}catch{return!1}},Os=e=>e.toLowerCase(),b_={exact:(e,t)=>t.some(r=>e.some(n=>r===n)),is_not:(e,t)=>t.every(r=>e.every(n=>r!==n)),regex:(e,t)=>t.some(r=>e.some(n=>$o(r,n))),not_regex:(e,t)=>t.every(r=>e.every(n=>!$o(r,n))),icontains:(e,t)=>t.map(Os).some(r=>e.map(Os).some(n=>r.includes(n))),not_icontains:(e,t)=>t.map(Os).every(r=>e.map(Os).every(n=>!r.includes(n))),gt:(e,t)=>t.some(r=>{const n=parseFloat(r);return!isNaN(n)&&e.some(i=>n>parseFloat(i))}),lt:(e,t)=>t.some(r=>{const n=parseFloat(r);return!isNaN(n)&&e.some(i=>n<parseFloat(i))})};function w_(e,t){return!e||Object.entries(e).every(([r,n])=>{const i=t?.[r];if(i==null)return!1;const s=b_[n.operator];return!!s&&s(n.values.map(String),[String(i)])})}function nc(e,t,r){return Nn({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:r})}var Sl="custom",rp="i.posthog.com",SP=/^\/static\//,EP=["/s/","/e/","/i/"],kP=class{constructor(e){this.su={},this.instance=e}get apiHost(){const e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){const e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e;let t=(e=this.instance.config.ui_host)===null||e===void 0?void 0:e.replace(/\/$/,"");return t||(t=this.apiHost.replace(`.${rp}`,".posthog.com")),t==="https://app.posthog.com"?"https://us.posthog.com":t}get region(){return this.su[this.apiHost]||(this.su[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":Sl),this.su[this.apiHost]}ru(e){if(!SP.test(e))return;const t=this.instance.config.asset_host;return typeof t=="string"&&t.trim().replace(/\/$/,"")||void 0}ou(e){const t=Fr(e);return t?t.protocol+"//"+t.host+t.pathname:void 0}au(e,t,r){if(e==="ui")return r;let n=r;const i=this.instance.config.rewriteRequestPath;if(i){var s;const o=((s=Fr(r))===null||s===void 0?void 0:s.href)||r;n=i(new URL(o)).toString()}if(i&&e==="api"&&EP.some(o=>t.indexOf(o)===0)){const o=this.ou(n);if(o){const a=this.apiHost;let c=this.lu;c?.apiHost===a&&c.rewriteRequestPath===i||(c={apiHost:a,rewriteRequestPath:i,urls:new Set},this.lu=c),c.urls.add(o)}}return n}isIngestionEndpoint(e){const t=this.lu,r=this.ou(e);return t?.apiHost===this.apiHost&&t.rewriteRequestPath===this.instance.config.rewriteRequestPath&&!!r&&t.urls.has(r)}endpointFor(e,t=""){if(t&&(t=t[0]==="/"?t:`/${t}`),e==="ui")return this.au(e,t,this.uiHost+t);if(e==="flags")return this.au(e,t,this.flagsApiHost+t);if(e==="assets"){const n=this.ru(t);if(n)return this.au(e,t,`${n}${t}`)}if(this.region===Sl)return this.au(e,t,this.apiHost+t);const r=rp+t;switch(e){case"assets":return this.au(e,t,`https://${this.region}-assets.${r}`);case"api":return this.au(e,t,`https://${this.region}.${r}`)}}},Te=Be("[Surveys]"),S_=e=>{try{const t=(r=>((n,i)=>`seenSurvey_${(function(s){return s.current_iteration&&s.current_iteration>0?`${s.id}_${s.current_iteration}`:s.id})(i)}`)(0,r))(e);if(localStorage.getItem(t))return;localStorage.setItem(t,"true")}catch(t){Te.error("Failed to persist survey seen state",t)}},RP=[Ya.Popover,Ya.Widget,Ya.API],AP={ignoreConditions:!1,ignoreDelay:!1,displayType:ml.Popover},IP=Be("[PostHog ExternalIntegrations]"),TP={intercom:"intercom-integration",crispChat:"crisp-chat-integration"},CP=class{constructor(e){this._instance=e}zo(e,t){var r,n;(r=te.__PosthogExtensions__)===null||r===void 0||(n=r.loadExternalDependency)===null||n===void 0||n.call(r,this._instance,e,i=>{if(i)return IP.error("failed to load script",i);t()})}startIfEnabledOrStop(){var e;for(const[i,s]of Object.entries((e=this._instance.config.integrations)!==null&&e!==void 0?e:{})){var t,r,n;s&&!((t=te.__PosthogExtensions__)!==null&&t!==void 0&&(t=t.integrations)!==null&&t!==void 0&&t[i])&&this.zo(TP[i],()=>{var o;(o=te.__PosthogExtensions__)===null||o===void 0||(o=o.integrations)===null||o===void 0||(o=o[i])===null||o===void 0||o.start(this._instance)}),!s&&(r=te.__PosthogExtensions__)!==null&&r!==void 0&&(r=r.integrations)!==null&&r!==void 0&&r[i]&&((n=te.__PosthogExtensions__)===null||n===void 0||(n=n.integrations)===null||n===void 0||(n=n[i])===null||n===void 0||n.stop())}}},$P=class{constructor(e,t){this.$=e,this.wo=t,this.uu=new Map,this.Io=!1}add(e){var t=this;return Ue(function*(){if(t.Io)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(t.uu.has(e.name))throw new Error(`Browser extension "${e.name}" is already registered`);t.uu.set(e.name,e);try{const r=e.setup(t.wo);r&&(yield r)}catch(r){const n=t.uu.get(e.name)===e;n&&t.uu.delete(e.name),t.$.error(`Failed to set up browser extension "${e.name}"`,r),n&&t.hu(e)}})()}getExtension(e){return this.uu.get(e)}dispose(){if(this.Io)return;this.Io=!0;const e=Array.from(this.uu.values()).reverse();this.uu.clear();for(const t of e)this.hu(t)}hu(e){try{var t;const r=(t=e.dispose)===null||t===void 0?void 0:t.call(e);r&&tt(r.then)&&r.then(void 0,n=>{this.$.error(`Failed to dispose browser extension "${e.name}"`,n)})}catch(r){this.$.error(`Failed to dispose browser extension "${e.name}"`,r)}}},PP=class{constructor(e){this._instance=e}initialize(){}get(e){const t=this._instance.persistence;if(typeof e=="string")return t?.get_property(e);const r={};for(const n of e){const i=t?.get_property(n);O(i)||(r[n]=i)}return r}set(e,t){var r;(r=this._instance.persistence)===null||r===void 0||r.register(typeof e=="string"?{[e]:t}:e)}remove(e){var t;(t=this._instance.persistence)===null||t===void 0||t.unregister(e)}},np="extensionsRemoteConfig",OP=class{constructor(e){this.instance=e,this.Io=!1,this.$=j,this.cu=e.du,this.kv=new PP(e),this.onEvent=t=>Ps(this.instance.on("eventCaptured",r=>{try{t({event:r.event,properties:r.properties})}catch(n){this.$.error("Browser extension event listener failed",n)}})),this.onRemoteConfig=t=>{if(this.Io)return Ps(()=>{});const r=i=>{try{t(i)}catch(s){this.$.error("Browser extension remote config listener failed",s)}},n=this.instance.vu.on(np,r);return this.cu&&r(this.cu),Ps(n)},this.fu=new $P(j.createLogger("[BrowserExtensions]"),this)}get logger(){return this.$}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property("$device_id"))!==null&&e!==void 0?e:this.distinctId}get deviceId(){const e=this.instance.get_property(Eu);return typeof e=="string"?e:void 0}get library(){return{name:et.LIB_NAME,version:et.LIB_VERSION}}get initialPersonProperties(){var e,t;return(e=(t=this.instance.persistence)===null||t===void 0?void 0:t.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,t,r,n;const i=(e=this.instance.sessionManager)===null||e===void 0?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(t=i?.sessionId)!==null&&t!==void 0?t:"",windowId:(r=i?.windowId)!==null&&r!==void 0?r:"",sessionStartTimestamp:(n=i?.sessionStartTimestamp)!==null&&n!==void 0?n:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get canCapture(){return this.instance.is_capturing()}get projectToken(){return this.instance.config.token}add(e){return this.fu.add(e)}getExtension(e){return this.fu.getExtension(e)}capture(e,t,r){r?this.instance.capture(e,t,{timestamp:r.timestamp,uuid:r.uuid,$set:r.set,$set_once:r.setOnce}):this.instance.capture(e,t)}registerDynamicEventProperties(e){return Ps(this.instance.pu(e))}handleRemoteConfig(e){this.Io||(this.cu=e,this.instance.vu.emit(np,e))}sendRequest(e){var t=this;return Ue(function*(r,n={}){var i;const s=t.instance.requestRouter.endpointFor((i=n.target)!==null&&i!==void 0?i:"api",r),o={method:n.method,url:n.query?ds(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,compressionFallback:n.target==="flags"&&n.compression==="best-available"?Zc.Base64:void 0,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(t.instance._send_request(o),{statusCode:202}):new Promise(a=>{o.callback=a,t.instance._send_request(o)})}).apply(this,arguments)}dispose(){this.Io||(this.Io=!0,this.fu.dispose())}},qi={},ic=0,ji=()=>{},ip='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ei="Surveys module not available",sp="sanitize_properties is deprecated. Use before_send instead",E_="Invalid value for property_denylist config: ",xP=/^[A-Za-z0-9_-]{1,400}$/,op=/^fb\.[0-9]+\.[0-9]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?$/,ap=/^fb\.[0-9]+\.[0-9]+\.[0-9]+$/,MP=["token","distinct_id",km],Ci="posthog",LP=e=>{const t={};return e&&e!=="unset"&&("2025-11-30">e||(t.strictMinimumDuration=!0),"2026-05-30">e||(t.canvasCapture={resolutionScale:.6}),"2026-06-25">e||(t.streamNetworkBody=!0),"2026-08-30">e||(t.captureJsonLd=!0)),t},sc=e=>{var t;return b({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:x$(N?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:ji,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:e??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:je&&ye(je?.search)&&je.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,reuseAnonymousId:!1,disable_external_dependency_loading:!1,strict_script_versioning:"fallback",enable_recording_console_log:void 0,secure_cookie:(A==null||(t=A.location)===null||t===void 0?void 0:t.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,feature_flag_request_max_retries:1,surveys_request_timeout_ms:1e4,on_request_error(r){j.error("Bad HTTP status: "+r.statusCode+" "+r.text)},get_device_id:r=>r,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:Cm,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:3e3},error_tracking:{},_onCapture:ji},(r=>({rageclick:r&&r>="2026-05-30"?{content_ignorelist:q$,ignore_text_selection:!0}:!r||"2025-11-30">r||{content_ignorelist:!0},capture_pageview:!r||"2025-05-24">r||"history_change",session_recording:LP(r),external_scripts_inject_target:r&&r>="2026-01-30"?"head":"body",internal_or_test_user_hostname:r&&r>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:r&&r>="2026-05-30"?250:0,split_storage:!(!r||"2026-05-30">r),detect_google_search_app:!(!r||"2026-05-30">r),disable_capture_url_hashes:!(!r||"2026-06-25">r),cookieWinsOnConflict:!(!r||r==="unset"||"2026-08-29">r)}))(e))},DP=[["process_person","person_profiles"],["xhr_headers","request_headers"],["cookie_name","persistence_name"],["disable_cookie","disable_persistence"],["__preview_disable_beacon","disable_beacon"],["store_google","save_campaign_params"],["verbose","debug"],["__preview_cookie_wins_on_conflict","cookieWinsOnConflict"]],cp=e=>{const t={};for(const[i,s]of DP)O(e[i])||(t[s]=e[i]);const r=Le({},t,e),n=e.__preview_external_dependency_versioned_paths;return O(n)||(O(e.strict_script_versioning)&&(r.strict_script_versioning=!!n),ye(n)&&O(e.asset_host)&&(r.asset_host=n)),ce(e.property_blacklist)&&(O(e.property_denylist)?r.property_denylist=e.property_blacklist:ce(e.property_denylist)?r.property_denylist=[...e.property_blacklist,...e.property_denylist]:j.error(E_+e.property_denylist)),r},NP=class{constructor(){this.__forceAllowLocalhost=!1}get gu(){return this.__forceAllowLocalhost}set gu(e){j.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},Hi=class fr{mu(t){if(!t)return;const r=this.uu.indexOf(t);r!==-1&&this.uu.splice(r,1)}yu(t,r){var n;return this.mu(t),this.uu.push(r),(n=r.initialize)===null||n===void 0||n.call(r),r}bu(){return this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isRejected()}_u(){if(this.wu||this.config.reuseAnonymousId||this.config.segment||this.bu())return;const t=this.config.persistence==="memory"||this.config.persistence==="sessionStorage";if(!t&&!this.config.disable_persistence||this.ku)return;let r,n,i;t?(r=`persistence is set to '${this.config.persistence}'`,n=this.config.persistence==="memory"?"on every page load":"for every new browser tab or window",i="Either set persistence to 'localStorage+cookie', keep this persistence and pass a stable ID through bootstrap.distinctID, or enable reuseAnonymousId."):(r="persistence is disabled (disable_persistence is true)",n="on every page load",i="Either set disable_persistence to false, keep persistence disabled and pass a stable ID through bootstrap.distinctID, or enable reuseAnonymousId."),this.wu=!0,console.warn("[PostHog.js]",`${r} but no bootstrap.distinctID was provided. PostHog will mint a new distinct ID ${n}, so calling identify() merges a new ID onto the person each time. A person can then pass the distinct-ID limit and its events stop appearing on person pages and the session tab. ${i}`)}Su(){if(this.bu()||this.get_distinct_id()!=="$posthog_cookieless")return;const t=this.persistence;if(!t)return;this.xu()||t.load(!0);const r=this.get_distinct_id();if(!r||r==="$posthog_cookieless"){const n=this.config.get_device_id(Lt());this.register({distinct_id:n,$device_id:n}),t.set_property(ft,sr)}this.Cu()}get decideEndpointWasHit(){var t,r;return(t=(r=this.featureFlags)===null||r===void 0?void 0:r.hasLoadedFlags)!==null&&t!==void 0&&t}get flagsEndpointWasHit(){var t,r;return(t=(r=this.featureFlags)===null||r===void 0?void 0:r.hasLoadedFlags)!==null&&t!==void 0&&t}constructor(){var t;this.$u=!1,this.Tu=!1,this.webPerformance=new NP,this.Iu=!1,this.version=et.LIB_VERSION,this.Mu=new Set,this.Eu="",this.vu=new Co,this.uu=[],this.Pu=[],this.ku=!1,this.wu=!1,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=sc(),this.SentryIntegration=J$,this.sentryIntegration=n=>(function(i,s){const o=Hm(i,s);return{name:jm,processEvent:a=>o(a)}})(this,n),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Ru=!1,this.Au=null,this.Fu=null,this.Ou=null,this.scrollManager=new yP(this),this.pageViewManager=new Hh(this),this.rateLimiter=new sP(this),this.requestRouter=new kP(this),this.consent=new F$(this),this.externalIntegrations=new CP(this);const r=(t=fr.__defaultExtensionClasses)!==null&&t!==void 0?t:{};this.featureFlags=r.featureFlags&&new r.featureFlags(this),this.toolbar=r.toolbar&&new r.toolbar(this),this.surveys=r.surveys&&new r.surveys(this),this.conversations=r.conversations&&new r.conversations(this),this.logs=r.logs&&new r.logs(this),this.metrics=r.metrics&&new r.metrics(this),this.experiments=r.experiments&&new r.experiments(this),this.exceptions=r.exceptions&&new r.exceptions(this),this.people={set:(n,i,s)=>{const o=ye(n)?{[n]:i}:n;this.setPersonProperties(o),s?.({})},set_once:(n,i,s)=>{const o=ye(n)?{[n]:i}:n;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",n=>j.info(`send "${n?.event}"`,n))}init(t,r,n){if(n&&n!==Ci){var i;const s=(i=qi[n])!==null&&i!==void 0?i:new fr;return s._init(t,r,n),qi[n]=s,qi[Ci][n]=s,s}return this._init(t,r,n)}_init(t,r={},n){var i,s,o;const a=ye(t)?t.trim():"";if(!a)return j.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;var c;if(this.__loaded)return a!==((c=this.config)===null||c===void 0?void 0:c.token)?console.warn("[PostHog.js]",`You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('${a}', { ... }, 'project2')`):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=sc(r.defaults),r.debug=this.Du(r.debug),this.Lu=r,this.Nu=[],r.person_profiles?this.Fu=r.person_profiles:r.process_person&&(this.Fu=r.process_person);const l=sc(r.defaults),u=cp(r),h=Le({},l,u,{name:n,token:a});be(l.rageclick)&&be(u.rageclick)&&(h.rageclick=Le({},l.rageclick,u.rageclick)),be(l.session_recording)&&be(u.session_recording)&&(h.session_recording=Le({},l.session_recording,u.session_recording)),this.set_config(h),this.config.on_xhr_error&&j.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=r.disable_compression?void 0:St.GZipJS;const d=this.xu();if(this.persistence=new Ka(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Ka(b(b({},this.config),{},{persistence:"sessionStorage"}),d,!1),this.Eu="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&xe.Et()){const _=xe.Dt(this.Eu);ce(_)&&_.forEach(w=>{ye(w)&&this.Mu.add(w)})}else xe.Lt(this.Eu);const p=b({},this.persistence.props),f=b({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.qu=new gP((_,w)=>this.ju(_,w),this.config.request_queue_config),this.Bu=new _P(this),this.__request_queue=[];const v=this.bu();v||(this.sessionManager=new tp(this),this.sessionPropsManager=new Qh(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId((_,w,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.crossTabAdoption)&&this.Hu()})),this.zu(),this.config.__preview_deferred_init_extensions?(j.info("Deferring extension initialization to improve startup performance"),setTimeout(()=>{this.Uu(v)},0)):(j.info("Initializing extensions synchronously"),this.Uu(v)),et.DEBUG=et.DEBUG||this.config.debug,et.DEBUG&&j.info("Starting in debug mode",{this:this,config:r,thisC:b({},this.config),p,s:f}),this.config.identity_distinct_id&&!((i=r.bootstrap)!==null&&i!==void 0&&i.distinctID)&&(r.bootstrap=b(b({},r.bootstrap),{},{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0}));const m=(s=r.bootstrap)===null||s===void 0?void 0:s.distinctID;if(this.ku=!!m&&!Oi(m),(o=r.bootstrap)===null||o===void 0?void 0:o.distinctID){const _=r.bootstrap.distinctID,w=this.get_distinct_id(),S=this.persistence.get_property(ft);if(r.bootstrap.isIdentifiedID&&w!=null&&w!==_&&S==="anonymous")this.identify(_);else if(r.bootstrap.isIdentifiedID&&w!=null&&w!==_&&S==="identified")j.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{const T=this.config.get_device_id(Lt()),C=r.bootstrap.isIdentifiedID?T:_;this.persistence.set_property(ft,r.bootstrap.isIdentifiedID?Ks:sr),this.register({distinct_id:_,$device_id:C})}}if(v)this.register_once({distinct_id:ja,$device_id:null},"");else if(!this.get_distinct_id()){const _=this.config.get_device_id(Lt());this.register_once({distinct_id:_,$device_id:_},""),this.persistence.set_property(ft,sr)}return Ie(A,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),Ie(A,"pageshow",()=>{var _;this.$u=!1,this.Tu||(_=this.Bu)===null||_===void 0||_.resume()}),r.segment?jh(this,()=>this.Wu()):this.Wu(),tt(this.config._onCapture)&&this.config._onCapture!==ji&&(j.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",_=>this.config._onCapture(_.event,_))),this.config.ip&&j.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return __.apply(this,arguments)})().then(_=>{_&&this.register({[qa]:_})}).catch(ji),this}Vu(t){const r=t;return ye(r.name)&&tt(r.setup)}Gu(t,r){this.Vu(t)?r.push(()=>{this.Zu().add(t).catch(()=>{var n;return(n=t.dispose)===null||n===void 0?void 0:n.call(t)}).catch(n=>{j.error(`Failed to dispose browser extension "${t.name}"`,n)})}):this.uu.push(t)}zu(){var t,r,n;const i=(t=(r=this.config.__extensionClasses)===null||r===void 0?void 0:r.featureFlags)!==null&&t!==void 0?t:(n=fr.__defaultExtensionClasses)===null||n===void 0?void 0:n.featureFlags;var s,o,a;i&&(this.featureFlags&&this.featureFlags instanceof i||((s=this.Qu)===null||s===void 0||s.call(this),this.Qu=void 0,this.featureFlags=new i(this)),tt(this.featureFlags.onReloading)&&tt(this.featureFlags.setup)?this.Qu||(this.Qu=this.featureFlags.onReloading(()=>{this.vu.emit("featureFlagsReloading",!0)}),this.Zu().add(this.featureFlags)):(o=(a=this.featureFlags).initialize)===null||o===void 0||o.call(a))}Uu(t){const r=performance.now(),n=b(b({},fr.__defaultExtensionClasses),this.config.__extensionClasses),i=[];var s,o,a,c,l,u,h;n.exceptions&&this.uu.push(this.exceptions=(s=this.exceptions)!==null&&s!==void 0?s:new n.exceptions(this)),n.historyAutocapture&&this.uu.push(this.historyAutocapture=new n.historyAutocapture(this)),n.tracingHeaders&&this.uu.push(this.tracingHeaders=new n.tracingHeaders(this)),n.siteApps&&this.uu.push(this.siteApps=new n.siteApps(this)),n.sessionRecording&&!t&&this.uu.push(this.sessionRecording=new n.sessionRecording(this)),this.config.disable_scroll_properties||i.push(()=>{this.scrollManager.startMeasuringScrollPosition()}),n.autocapture&&this.Gu(this.autocapture=new n.autocapture(this),i),n.surveys&&this.Gu(this.surveys=(o=this.surveys)!==null&&o!==void 0?o:new n.surveys(this),i),n.logs&&this.Gu(this.logs=(a=this.logs)!==null&&a!==void 0?a:new n.logs(this),i),n.metrics&&this.uu.push(this.metrics=(c=this.metrics)!==null&&c!==void 0?c:new n.metrics(this)),n.conversations&&this.uu.push(this.conversations=(l=this.conversations)!==null&&l!==void 0?l:new n.conversations(this)),n.productTours&&this.uu.push(this.productTours=new n.productTours(this)),n.heatmaps&&this.uu.push(this.heatmaps=new n.heatmaps(this)),n.webVitalsAutocapture&&this.uu.push(this.webVitalsAutocapture=new n.webVitalsAutocapture(this)),n.exceptionObserver&&this.uu.push(this.exceptionObserver=new n.exceptionObserver(this)),n.deadClicksAutocapture&&this.uu.push(this.deadClicksAutocapture=new n.deadClicksAutocapture(this,Z$)),n.toolbar&&this.uu.push(this.toolbar=(u=this.toolbar)!==null&&u!==void 0?u:new n.toolbar(this)),n.experiments&&this.uu.push(this.experiments=(h=this.experiments)!==null&&h!==void 0?h:new n.experiments(this)),this.uu.forEach(d=>{d.initialize&&i.push(()=>{var p;(p=d.initialize)===null||p===void 0||p.call(d)})}),i.push(()=>{if(this.Ju){const d=this.Ju;this.Ju=void 0,this.uu.forEach(p=>{var f;return(f=p.onRemoteConfig)===null||f===void 0?void 0:f.call(p,d)})}}),this.Ku(i,r)}Ku(t,r){for(;t.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-r>=30&&t.length>0)return void setTimeout(()=>{this.Ku(t,r)},0);const i=t.shift();if(i)try{i()}catch(s){j.error("Error initializing extension:",s)}}const n=Math.round(performance.now()-r);this.register_for_session({[Rm]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Am]:n}),this.config.__preview_deferred_init_extensions&&j.info(`PostHog extensions initialized (${n}ms)`)}il(t){var r;if(!N||!N.body)return j.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this.il(t)},500);if(this.config.__preview_deferred_init_extensions&&(this.Ju=t),this.du=t,this.compression=void 0,t.ok){var n;const i=t.config;i.supportedCompression&&!this.config.disable_compression&&(this.compression=ue(i.supportedCompression,St.GZipJS)?St.GZipJS:ue(i.supportedCompression,St.Base64)?St.Base64:void 0),(n=i.analytics)!==null&&n!==void 0&&n.endpoint&&(this.analyticsDefaultEndpoint=i.analytics.endpoint)}this.set_config({person_profiles:this.Fu?this.Fu:Cm}),(r=this.Xu)===null||r===void 0||r.handleRemoteConfig(t),this.uu.forEach(i=>{var s;return(s=i.onRemoteConfig)===null||s===void 0?void 0:s.call(i,t)})}Wu(){try{this.config.loaded(this)}catch(t){j.critical("`loaded` function failed",t)}if(this.Yu(),this.config.internal_or_test_user_hostname&&je?.hostname){const t=je.hostname,r=this.config.internal_or_test_user_hostname;(typeof r=="string"?t===r:r.test(t))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this.bu())&&this.th()},1),this.eh=new t_(this),this.eh.load()}Yu(){var t;this.is_capturing()&&this.config.request_batching&&((t=this.qu)===null||t===void 0||t.enable())}_dom_loaded(){this.is_capturing()&&Dn(this.__request_queue,t=>this.ju(t)),this.__request_queue=[],this.Yu()}_handle_unload(){var t,r,n,i,s,o;this.$u=!0,(t=this.surveys)===null||t===void 0||(r=t.handlePageUnload)===null||r===void 0||r.call(t),(n=this.metrics)===null||n===void 0||n.flush("sendBeacon"),this.config.request_batching?(this.ih()&&this.capture(Ah),(i=this.logs)===null||i===void 0||i.flushLogs("sendBeacon"),(s=this.qu)===null||s===void 0||s.unload(),(o=this.Bu)===null||o===void 0||o.unload()):this.ih()&&this.capture(Ah,null,{transport:"sendBeacon"})}_send_request(t){g_(this,t)}ju(t,r){this.Bu?this.Bu.retriableRequest(t,r):this._send_request(r?b(b({},t),{},{transport:r}):t)}_execute_array(t){ic++;try{let r;const n=[],i=[],s=[];Dn(t,a=>{if(a)if(r=a[0],ce(r))s.push(a);else if(tt(a))try{a.call(this)}catch(c){j.error("Error executing queued PostHog call",a,c)}else ce(a)&&r==="alias"?n.push(a):ce(a)&&r.indexOf("capture")!==-1&&tt(this[r])?s.push(a):i.push(a)});const o=function(a,c){Dn(a,function(l){try{if(ce(l[0])){let u=c;Ce(l,function(h){u=u[h[0]].apply(u,h.slice(1))})}else c[l[0]].apply(c,l.slice(1))}catch(u){j.error("Error executing queued PostHog call",l,u)}})};o(n,this),o(i,this),o(s,this)}finally{ic--}}push(t){if(ic>0&&ce(t)&&ye(t[0])){const r=fr.prototype[t[0]];tt(r)&&r.apply(this,t.slice(1));return}this._execute_array([t])}get nh(){return{property:kh,persistenceKey:qn,cookieName:"_fbc",pattern:op,register:(t,r)=>{var n;return(n=this.persistence)===null||n===void 0?void 0:n.register({[qn]:{value:t,delivered:r}})},unregister:()=>{var t;return(t=this.persistence)===null||t===void 0?void 0:t.unregister(qn)}}}get sh(){return{property:Rh,persistenceKey:Mi,cookieName:"_fbp",pattern:ap,register:(t,r)=>{var n;return(n=this.persistence)===null||n===void 0?void 0:n.register({[Mi]:{value:t,delivered:r}})},unregister:()=>{var t;return(t=this.persistence)===null||t===void 0?void 0:t.unregister(Mi)}}}rh(t){var r;const n=(r=this.persistence)===null||r===void 0?void 0:r.get_property(t.persistenceKey);return ye(n)&&t.pattern.test(n)?{value:n,delivered:!1}:be(n)&&ye(n.value)&&t.pattern.test(n.value)?{value:n.value,delivered:n.delivered===!0}:void 0}oh(t,r,n){return r===n?.value?{value:r,pending:!n.delivered}:(t.register(r,!1),{value:r,pending:!0})}ah(t){if(!this.config.save_campaign_params||this.bu())return;const r=Ni(t.cookieName);return ye(r)&&t.pattern.test(r)?r:void 0}uh(t,r,n,i){if(!this.persistence)return;const s=this.nh;this.persistence.refreshKey(s.persistenceKey);const o=this.rh(s);if(i)return void s.unregister();if(n)return ye(r)&&op.test(r)?this.oh(s,r,o):void s.unregister();const a=ye(t)&&xP.test(t)?t:void 0,c=this.ah(s);return c&&((l,u,h)=>{const d=l.split(".");if(u)return d[3]===u;if(!h)return!0;const p=h.value.split(".");return d[3]===p[3]||Number(d[2])>Number(p[2])})(c,a,o)?this.oh(s,c,o):a?o?.value.split(".")[3]===a?{value:o.value,pending:!o.delivered}:this.oh(s,`fb.1.${Date.now()}.${a}`,o):o?{value:o.value,pending:!o.delivered}:void 0}hh(t,r,n){if(!this.persistence)return;const i=this.sh;this.persistence.refreshKey(i.persistenceKey);const s=this.rh(i);if(n)return void i.unregister();if(r)return ye(t)&&ap.test(t)?this.oh(i,t,s):void i.unregister();const o=this.ah(i);return o?this.oh(i,o,s):s?{value:s.value,pending:!s.delivered}:void 0}dh(t,r){if(!this.persistence)return;this.persistence.refreshKey(t.persistenceKey);const n=this.rh(t);n?.value!==r||n.delivered||t.register(r,!0)}capture(t,r,n){var i,s;if(!(this.__loaded&&this.persistence&&this.sessionPersistence&&this.qu))return void j.uninitializedWarning("posthog.capture");if(!this.is_capturing())return;if(O(t)||!ye(t))return void j.error("No event name provided to posthog.capture");this.Su();const o=!this.config.opt_out_useragent_filter&&this._is_bot();if(o&&!this.config.__preview_capture_bot_pageviews)return;const a=n?.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(a?.isRateLimited)return void j.critical("This capture call is ignored due to client rate limiting.");let c;r!=null&&r.$current_url&&!ye(r?.$current_url)&&(j.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),r==null||delete r.$current_url),t!=="$exception"||n!=null&&n.fh||j.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&(c=this.sessionPersistence.update_campaign_params()),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();const l=new Date,u=n?.timestamp||l,h=ch(n?.uuid,Lt);let d={uuid:h,event:t,properties:this.calculateEventProperties(t,r||{},u,h)};t==="$pageview"&&this.config.__preview_capture_bot_pageviews&&o&&(d.event="$bot_pageview",d.properties.$browser_type="bot"),a&&(d.properties.$lib_rate_limit_remaining_tokens=a.remainingTokens);const p=t==="$feature_flag_called"&&d.properties.$feature_flag_has_experiment===!1&&this.get_property("$minimal_flag_called_events")===!0;n!=null&&n.$set&&!p&&(d.$set=n?.$set);const f=be(r?.$set)?r.$set:void 0,v=ce(r?.$unset)?r.$unset:[],m=n?.$unset||[],_=H=>{var oe;const I=!!n?.$set&&H in n.$set;return{hasProvided:I||!!f&&H in f,provided:I?n==null||(oe=n.$set)===null||oe===void 0?void 0:oe[H]:f?.[H],unset:v.indexOf(H)!==-1||m.indexOf(H)!==-1}},w=_(kh),S=_(Rh),T=[{channel:this.nh,hasProvided:w.hasProvided,update:this.uh(c?.fbclid,w.provided,w.hasProvided,w.unset)},{channel:this.sh,hasProvided:S.hasProvided,update:this.hh(S.provided,S.hasProvided,S.unset)}];for(const{channel:H,hasProvided:oe,update:I}of T)I&&d.properties.$process_person_profile===!0&&I.pending&&!oe&&!p&&(d.$set=b({[H.property]:I.value},d.$set));const C=n?.$unset;C&&(d.$unset=C);const $=p?void 0:this.ph(n?.$set_once,t!==Ih,t===$m);if($&&(d.$set_once=$),n!=null&&n._noTruncate||(M=this.config.properties_string_max_length,d=(function(H,oe){const I=new Set;return(function Q(y,V){if(y!==Object(y))return oe?oe(y):y;if(I.has(y))return;let K;if(I.add(y),ce(y))K=[],Dn(y,le=>{K.push(Q(le))});else{const le={};Ce(ci(y)?Pm(y):y,(de,$e)=>{I.has(de)||(le[$e]=Q(de,$e))}),K=le}return K})(H)})(d,H=>ye(H)?H.slice(0,M):H)),d.timestamp=u,O(n?.timestamp)||(d.properties.$event_time_override_provided=!0,d.properties.$event_time_override_system_time=l),p&&(d.properties=((H,oe=[])=>{const I={},Q=y=>{H[y]!==void 0&&(I[y]=H[y])};return GC.forEach(Q),oe.forEach(Q),I})(d.properties,MP)),t===or.DISMISSED||t===or.SENT){const H=r?.[Xa.SURVEY_ID],oe=r?.[Xa.SURVEY_ITERATION];S_({id:H,current_iteration:oe}),d.$set=b(b({},d.$set),{},{[wP({id:H,current_iteration:oe},t===or.SENT?"responded":"dismissed")]:!0})}else t===or.SHOWN&&(d.$set=b(b({},d.$set),{},{[Xa.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));var M;if(t===iP.SHOWN){const H=r?.[Gh.TOUR_TYPE];H&&(d.$set=b(b({},d.$set),{},{[`${Gh.TOUR_LAST_SEEN_DATE}/${H}`]:new Date().toISOString()}))}const L=b(b({},d.properties.$set),d.$set);if(_t(L)||this.setPersonPropertiesForFlags(L),!ge(this.config.before_send)){const H=this.Os(d);if(!H)return;d=H,d.uuid=ch(d.uuid,Lt)}const q=T.filter(({channel:H,update:oe})=>{var I,Q,y;const V=(I=(Q=d.$set)===null||Q===void 0?void 0:Q[H.property])!==null&&I!==void 0?I:be((y=d.properties)===null||y===void 0?void 0:y.$set)?d.properties.$set[H.property]:void 0;return oe?.pending&&V===oe.value});this.vu.emit("eventCaptured",d);const X=(i=n?._url)!==null&&i!==void 0?i:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),ee=n?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(X),k=b(b(b({method:"POST",url:X,data:d,compression:"best-available",preferSyncCompression:n?.send_instantly,timestampMode:ee?"body":"capture-body",batchKey:n?._batchKey},ee&&(!((s=d.properties)===null||s===void 0)&&s.$session_id)?{batchGroup:d.properties.$session_id+(d.properties.$window_id?`-${d.properties.$window_id}`:"")}:{}),n?.transport?{transport:n.transport}:{}),q.length?{fireCallbackOnDrop:!0,callback:H=>{if(H.statusCode>=200&&300>H.statusCode)for(const{channel:oe,update:I}of q)this.dh(oe,I.value)}}:{});if(!this.config.request_batching||n&&!n?._batchKey||n?.send_instantly||q.length){var ie;let H;!k.transport&&!k.callback&&_t((ie=this.config.request_headers)!==null&&ie!==void 0?ie:{})&&this.$u&&(H="sendBeacon"),this.ju(k,H)}else this.qu.enqueue(k);return d}_addCaptureHook(t){return this.on("eventCaptured",r=>t(r.event,r))}getExtension(t){var r;return(r=this.Xu)===null||r===void 0?void 0:r.getExtension(t)}Zu(){var t;return(t=this.Xu)!==null&&t!==void 0?t:this.Xu=new OP(this)}pu(t){this.Pu.push(t);let r=!0;return()=>{if(!r)return;r=!1;const n=this.Pu.indexOf(t);n!==-1&&this.Pu.splice(n,1)}}gh(t=!0){var r,n,i;return!!(!((r=this.persistence)===null||r===void 0)&&r.consumeCookieIdentityChange())&&(this.Ou=null,this.persistence.get_property("$user_state")==="anonymous"&&((i=this.sessionPersistence)===null||i===void 0||i.clear(),this.Mu.clear(),this.mh()),(n=this.featureFlags)===null||n===void 0||n.reset(),t&&this.reloadFeatureFlags(),!0)}calculateEventProperties(t,r,n,i,s){if(n=n||new Date,!this.persistence||!this.sessionPersistence)return r;this.persistence.syncCookieProperties(),this.gh();const o=s?void 0:this.persistence.remove_event_timer(t);let a=b({},r);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.bu()&&(a[km]=!0),t==="$snapshot"){const w=b(b({},this.persistence.properties()),this.sessionPersistence.properties());return a.distinct_id=w.distinct_id,(!ye(a.distinct_id)&&!We(a.distinct_id)||Oi(a.distinct_id))&&j.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}const c=(function(w,S,T,C=!1){var $,M,L,q;if(!pt)return{};const X=w?[...Qn,...S||[]]:[],[ee,k]=Vg(pt),[ie,H]=(function(Re){for(let _e=0;ah.length>_e;_e++){const[ve,Je,Xe]=ah[_e],Pe=Re.match(ve);if(Pe){const z=Xe&&Re.match(Xe)||Pe;return[Je,z?.[1]||""]}}return["",""]})(pt),oe=(function(){const Re="u">typeof navigator?navigator:void 0;return Re?.brave?{brave:!0}:{}})(),I={};O(T)||(I.detectGoogleSearchApp=T);const Q={},y=($=navigator)===null||$===void 0||($=$.userAgentData)===null||$===void 0?void 0:$.platform,V=(M=navigator)===null||M===void 0?void 0:M.maxTouchPoints,K=A==null||(L=A.screen)===null||L===void 0?void 0:L.width,le=A==null||(q=A.screen)===null||q===void 0?void 0:q.height,de=A?.devicePixelRatio;O(y)||(Q.userAgentDataPlatform=y),O(V)||(Q.maxTouchPoints=V),O(K)||(Q.screenWidth=K),O(le)||(Q.screenHeight=le),O(de)||(Q.devicePixelRatio=de);const $e=Le(Cu({$os:ee,$os_version:k,$browser:Hg(pt,navigator.vendor,oe,I),$webview_app:ie,$webview_app_version:H,$device:Bg(pt),$device_type:fC(pt,Q),$timezone:Qm(),$timezone_offset:tP()}),{$current_url:ns(C?Ur(je?.href):je?.href,X,is),$host:je?.host,$pathname:je?.pathname,$raw_user_agent:pt.length>1e3?pt.substring(0,997)+"...":pt,$browser_version:pC(pt,navigator.vendor,oe,I),$browser_language:Jm(),$browser_language_prefix:eP(),$screen_height:A?.screen.height,$screen_width:A?.screen.width,$viewport_height:A?.innerHeight,$viewport_width:A?.innerWidth,$lib:ar.LIB_NAME,$lib_version:ar.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ar.SDK_DIST_CHANNEL&&($e.$sdk_dist_channel=ar.SDK_DIST_CHANNEL),$e})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){const{sessionId:w,windowId:S}=this.sessionManager.checkAndGetSessionAndWindowId(s,n.getTime(),!0);a.$session_id=w,a.$window_id=S}this.sessionPropsManager&&Le(a,this.sessionPropsManager.getSessionProps());try{var l;this.sessionRecording&&Le(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(l=this.Bu)===null||l===void 0?void 0:l.length}catch(w){a.$sdk_debug_error_capturing_properties=String(w)}let u;if(this.requestRouter.region===Sl&&(a.$lib_custom_api_host=this.config.api_host),u=t!=="$pageview"||s?t!=="$pageleave"||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(n):this.pageViewManager.doPageView(n,i),a=Le(a,u),t==="$pageview"&&N&&(a.title=N.title),!O(o)){const w=n.getTime()-o;a.$duration=parseFloat((w/1e3).toFixed(3))}pt&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");const h=this.persistence.properties(),d=this.sessionPersistence.properties(),p=a.$groups,f=h.$groups;be(p)&&!_t(p)&&(a.$groups=b(b({},be(f)?f:{}),p)),Ce(["$referrer","$referring_domain"],w=>{w in h&&delete d[w]});const v={};if(this.Pu.length>0)for(const w of this.Pu.slice())try{Le(v,w())}catch(S){j.error("Failed to produce browser extension event properties",S)}a=Le({},c,h,d,b(b({},v),a)),a.$is_identified=this._isIdentified(),ce(this.config.property_denylist)?Ce(this.config.property_denylist,function(w){delete a[w]}):j.error(E_+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);const m=this.config.sanitize_properties;m&&(j.error(sp),a=m(a,t));const _=this.yh();return a.$process_person_profile=_,_&&!s&&this.bh("_calculate_event_properties"),a}ph(t,r=!0,n=!1){var i;if(!this.persistence||!this.yh()||this.Iu&&!n)return t;const s=this.persistence.get_initial_props(),o=(i=this.sessionPropsManager)===null||i===void 0?void 0:i.getSetOnceProps();let a=Le({},s,o||{},t||{});const c=this.config.sanitize_properties;return c&&(j.error(sp),a=c(a,"$set_once")),r&&(this.Iu=!0),_t(a)?void 0:a}register(t,r){var n;(n=this.persistence)===null||n===void 0||n.register(t,r)}register_once(t,r,n){var i;(i=this.persistence)===null||i===void 0||i.register_once(t,r,n)}register_for_session(t){var r,n;(r=this.persistence)===null||r===void 0||r.syncCookieProperties(),this.gh(),(n=this.sessionPersistence)===null||n===void 0||n.register(t),Object.keys(t).forEach(i=>this.Mu.add(i)),this.mh()}unregister(t){var r;(r=this.persistence)===null||r===void 0||r.unregister(t)}unregister_for_session(t){var r;(r=this.sessionPersistence)===null||r===void 0||r.unregister(t),this.Mu.delete(t),this.mh()}_h(t,r){this.register({[t]:r})}Hu(){this.Mu.forEach(t=>{var r;(r=this.sessionPersistence)===null||r===void 0||r.unregister(t)}),this.Mu.clear(),this.mh()}mh(){var t;if(!this.Eu)return;if(this.config.persistence==="memory"||!((t=this.sessionPersistence)===null||t===void 0)&&t.mi||!xe.Et())return void xe.Lt(this.Eu);const r=[];this.Mu.forEach(n=>r.push(n)),r.length>0?xe.At(this.Eu,r):xe.Lt(this.Eu)}getFeatureFlag(t,r){var n;return(n=this.featureFlags)===null||n===void 0?void 0:n.getFeatureFlag(t,r)}getFeatureFlagPayload(t){var r;return(r=this.featureFlags)===null||r===void 0?void 0:r.getFeatureFlagPayload(t)}getFeatureFlagResult(t,r){var n;return(n=this.featureFlags)===null||n===void 0?void 0:n.getFeatureFlagResult(t,r)}getAllFeatureFlags(){var t,r;return(t=(r=this.featureFlags)===null||r===void 0?void 0:r.getAllFeatureFlags())!==null&&t!==void 0?t:[]}isFeatureEnabled(t,r){var n,i;return(n=(i=this.featureFlags)===null||i===void 0?void 0:i.isFeatureEnabled(t,r))!==null&&n!==void 0?n:r?.defaultValue}reloadFeatureFlags(){var t;(t=this.featureFlags)===null||t===void 0||t.reloadFeatureFlags()}updateFlags(t,r,n){var i;(i=this.featureFlags)===null||i===void 0||i.updateFlags(t,r,n)}updateEarlyAccessFeatureEnrollment(t,r,n){var i;(i=this.featureFlags)===null||i===void 0||i.updateEarlyAccessFeatureEnrollment(t,r,n)}getEarlyAccessFeatures(t,r=!1,n){var i;return(i=this.featureFlags)===null||i===void 0?void 0:i.getEarlyAccessFeatures(t,r,n)}on(t,r){return this.vu.on(t,r)}onFeatureFlags(t){return this.featureFlags?this.featureFlags.onFeatureFlags(t):(t([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(t){return this.surveys?this.surveys.onSurveysLoaded(t):(t([],{isLoaded:!1,error:Ei}),()=>{})}onSessionId(t){var r,n;return(r=(n=this.sessionManager)===null||n===void 0?void 0:n.onSessionId(t))!==null&&r!==void 0?r:()=>{}}getSurveys(t,r=!1){this.surveys?this.surveys.getSurveys(t,r):t([],{isLoaded:!1,error:Ei})}getActiveMatchingSurveys(t,r=!1){this.surveys?this.surveys.getActiveMatchingSurveys(t,r):t([],{isLoaded:!1,error:Ei})}renderSurvey(t,r){var n;(n=this.surveys)===null||n===void 0||n.renderSurvey(t,r)}displaySurvey(t,r=AP){var n;(n=this.surveys)===null||n===void 0||n.displaySurvey(t,r)}cancelPendingSurvey(t){var r;(r=this.surveys)===null||r===void 0||r.cancelPendingSurvey(t)}canRenderSurvey(t){var r,n;return(r=(n=this.surveys)===null||n===void 0?void 0:n.canRenderSurvey(t))!==null&&r!==void 0?r:{visible:!1,disabledReason:Ei}}canRenderSurveyAsync(t,r=!1){var n,i;return(n=(i=this.surveys)===null||i===void 0?void 0:i.canRenderSurveyAsync(t,r))!==null&&n!==void 0?n:Promise.resolve({visible:!1,disabledReason:Ei})}wh(t){return!t||Oi(t)?(j.critical("Unique user id has not been set in posthog.identify"),!1):t==="$posthog_cookieless"?(j.critical(`The string "${t}" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.`),!1):!["distinct_id","distinctid"].includes(t.toLowerCase())&&!["undefined","null"].includes(t.toLowerCase())||(j.critical(`The string "${t}" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.`),!1)}identify(t,r,n){if(!this.__loaded||!this.persistence)return j.uninitializedWarning("posthog.identify");if(We(t)&&(t=t.toString(),j.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),!this.wh(t)||!this.bh("posthog.identify"))return;this.Su();const i=this.get_distinct_id(),s=this.persistence.syncCookieProperties()&&this.get_distinct_id()!==i,o=this.gh(!1),a=this.persistence.Da();let c=!1;try{const u=this.get_distinct_id();this.register({$user_id:t}),this.get_property("$device_id")||this.register_once({$had_persisted_distinct_id:!0,$device_id:u},""),t!==u&&t!==this.get_property("__alias")&&(this.unregister(So),this.register({distinct_id:t}));const h=(this.persistence.get_property("$user_state")||"anonymous")===sr,d=t!==u,p=!d&&h;if(d&&h){var l;const f=this.config.reuseAnonymousId?{distinct_id:t}:{distinct_id:t,$anon_distinct_id:u};this.persistence.set_property(ft,Ks),this.setPersonPropertiesForFlags({$set:r||{},$set_once:n||{}},!1),this.config.cookieWinsOnConflict&&this.persistence.La(),this.capture("$identify",f,{$set:r||{},$set_once:n||{}})&&(this.Ou=nc(t,r,n)),(l=this.featureFlags)===null||l===void 0||l.setAnonymousDistinctId(this.config.reuseAnonymousId?void 0:u)}else if(p){this.persistence.set_property(ft,Ks);const f=r||{},v=n||{};this.setPersonPropertiesForFlags({$set:f,$set_once:v},!1),this.config.cookieWinsOnConflict&&this.persistence.La(),this.capture("$set",{$set:f,$set_once:v})&&(this.Ou=nc(t,r,n))}else(r||n)&&this.setPersonProperties(r,n);d||s||o?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(kr)):p&&(r||n)&&this.reloadFeatureFlags(),c=!0}finally{a&&this.persistence.ja(c)}}setPersonProperties(t,r){if(!t&&!r||!this.bh("posthog.setPersonProperties"))return;const n=nc(this.get_distinct_id(),t,r);this.Ou!==n?(this.setPersonPropertiesForFlags({$set:t||{},$set_once:r||{}},!0),this.capture("$set",{$set:t||{},$set_once:r||{}})&&(this.Ou=n)):j.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}unsetPersonProperties(t){var r;const n=(ce(t)?t:[t]).filter(i=>ye(i)&&i.length>0);n.length!==0&&this.bh("posthog.unsetPersonProperties")&&((r=this.featureFlags)===null||r===void 0||r.unsetPersonPropertiesForFlags(n,!0),this.capture("$set",{$unset:n}),this.Ou=null)}group(t,r,n){var i;if(!t||!r)return void j.error("posthog.group requires a group type and group key");(i=this.persistence)===null||i===void 0||i.syncCookieProperties(),this.gh();const s=this.getGroups(),o=s[t]!==r;if(o&&this.resetGroupPropertiesForFlags(t),this.register({$groups:b(b({},s),{},{[t]:r})}),(o||n)&&this.yh()){const a={$group_type:t,$group_key:r};n&&(a.$group_set=n),this.capture(Ih,a)}n&&this.setGroupPropertiesForFlags({[t]:n}),o&&!n&&this.reloadFeatureFlags()}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(t,r=!0){var n;(n=this.featureFlags)===null||n===void 0||n.setPersonPropertiesForFlags(t,r)}resetPersonPropertiesForFlags(t=!0){var r;(r=this.featureFlags)===null||r===void 0||r.resetPersonPropertiesForFlags(t)}setGroupPropertiesForFlags(t,r=!0){var n;this.bh("posthog.setGroupPropertiesForFlags")&&((n=this.featureFlags)===null||n===void 0||n.setGroupPropertiesForFlags(t,r))}resetGroupPropertiesForFlags(t){var r;(r=this.featureFlags)===null||r===void 0||r.resetGroupPropertiesForFlags(t)}reset(t){const r=vt(t)?t:t?.resetDeviceID,n=vt(t)||t==null?void 0:t.bootstrap;this.kh(r,!1,n)}kh(t,r=!1,n){var i,s,o,a,c,l;if(j.info("reset"),!this.__loaded)return j.uninitializedWarning("posthog.reset");const u=n?.sessionID;this.config.bootstrap=n||((i=this.Lu)===null||i===void 0?void 0:i.bootstrap)||{},(s=this.featureFlags)===null||s===void 0||(o=s.updateConfig)===null||o===void 0||o.call(s,this.config,this.nl());const h=this.get_property(Eu),d=this.get_property(qa),p=this.get_property(Li);(a=this.sessionRecording)===null||a===void 0||a.flushBeforeIdentityReset();const f=this.is_capturing();this.consent.reset(),r||!f||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after.");const v=(c=this.persistence)===null||c===void 0||(l=c.Da)===null||l===void 0?void 0:l.call(c);let m=!1;try{var _,w,S,T,C,$,M,L,q,X,ee,k,ie;if((_=this.persistence)===null||_===void 0||_.clear(),(w=this.sessionPersistence)===null||w===void 0||w.clear(),this.Mu.clear(),this.mh(),O(p)||(X=this.persistence)===null||X===void 0||X.register({$session_recording_remote_config:p}),(S=this.surveys)===null||S===void 0||S.reset(),(T=this.featureFlags)===null||T===void 0||T.reset(),(C=this.conversations)===null||C===void 0||C.reset(),($=this.logs)===null||$===void 0||$.reset(),(M=this.metrics)===null||M===void 0||M.reset(),(L=this.persistence)===null||L===void 0||L.set_property("$user_state","anonymous"),(q=this.sessionManager)===null||q===void 0||q.resetSessionId(),this.Ou=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:ja,$device_id:null},"");else{const I=this.config.get_device_id(Lt());this.register_once({distinct_id:I,$device_id:t?I:h},""),t||O(d)||this.register({[qa]:d})}if(this.register({$last_posthog_reset:new Date().toISOString()},1),n&&(n.distinctID&&!this.bu()&&((ie=this.persistence)===null||ie===void 0||ie.set_property("$user_state",n.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:n.distinctID})),(ee=this.featureFlags)===null||ee===void 0||ee.initialize(),!ge(u)&&!(!((k=this.sessionManager)===null||k===void 0)&&k.setBootstrapSessionId(u,!0)))){const I=b({},n);delete I.sessionID,this.config.bootstrap=I}delete this.config.identity_distinct_id,delete this.config.identity_hash,delete this.config.identity_claims,m=!0}finally{var H,oe;v&&((H=this.persistence)===null||H===void 0||(oe=H.ja)===null||oe===void 0||oe.call(H,m))}this.reloadFeatureFlags()}shutdown(t){var r=this;return Ue(function*(){var n,i,s,o,a,c,l,u;if(r.__loaded){r.Tu=!0,r.Zu().dispose(),(n=r.sessionRecording)===null||n===void 0||n.dispose(),(i=r.logs)===null||i===void 0||i.flushLogs("sendBeacon"),(s=r.metrics)===null||s===void 0||s.flush("sendBeacon"),(o=r.metrics)===null||o===void 0||o.dispose(),(a=r.qu)===null||a===void 0||a.unload(),(c=r.Bu)===null||c===void 0||c.unload();try{var h;(h=r.featureFlags)===null||h===void 0||h.destroy()}catch(d){j.error("Error while destroying feature flags",d)}(l=r.persistence)===null||l===void 0||l.destroy(),(u=r.sessionPersistence)===null||u===void 0||u.destroy()}else j.uninitializedWarning("posthog.shutdown")})()}setIdentity(t,r){var n;delete this.config.identity_claims,this.config.identity_distinct_id=t,this.config.identity_hash=r,this.alias(t),(n=this.conversations)===null||n===void 0||n.Sh()}clearIdentity(){var t;delete this.config.identity_distinct_id,delete this.config.identity_hash,delete this.config.identity_claims,(t=this.conversations)===null||t===void 0||t.xh()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var t,r;return(t=(r=this.sessionManager)===null||r===void 0?void 0:r.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&t!==void 0?t:""}get_session_replay_url(t){if(!this.sessionManager)return"";const{sessionId:r,sessionStartTimestamp:n}=this.sessionManager.checkAndGetSessionAndWindowId(!0);let i=this.requestRouter.endpointFor("ui",`/project/${this.config.token}/replay/${r}`);if(t?.withTimestamp&&n){var s;const o=(s=t.timestampLookBack)!==null&&s!==void 0?s:10;if(!n)return i;i+=`?t=${Math.max(Math.floor((new Date().getTime()-n)/1e3)-o,0)}`}return i}alias(t,r){return t===this.get_property("$people_distinct_id")?(j.critical("Attempting to create alias for existing People user - aborting."),-2):this.bh("posthog.alias")?(O(r)&&(r=this.get_distinct_id()),t!==r?(this._h(So,t),this.capture("$create_alias",{alias:t,distinct_id:r})):(j.warn("alias matches current distinct_id - skipping api call."),this.identify(t),-1)):void 0}set_config(t){const r=b({},this.config);if(be(t)){var n,i,s,o,a,c,l,u,h,d,p,f,v,m;Le(this.config,cp(t));const w=this.xu();(n=this.persistence)===null||n===void 0||n.update_config(this.config,r,w),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Ka(b(b({},this.config),{},{persistence:"sessionStorage"}),w,!1);const S=this.Du(this.config.debug);var _;vt(S)&&(this.config.debug=S),vt(this.config.debug)&&(this.config.debug?(et.DEBUG=!0,ke.Et()&&ke.At("ph_debug",!0),j.info("set_config",{config:t,oldConfig:r,newConfig:b({},this.config)})):(et.DEBUG=!1,ke.Et()&&ke.Lt("ph_debug"))),(i=this.featureFlags)===null||i===void 0||(s=i.updateConfig)===null||s===void 0||s.call(i,this.config,this.nl()),(o=this.exceptionObserver)===null||o===void 0||o.onConfigChange(),(a=this.exceptions)===null||a===void 0||a.onConfigChange(),(c=this.metrics)===null||c===void 0||c.onConfigChange(),(l=this.sessionRecording)===null||l===void 0||l.startIfEnabledOrStop(),(u=this.tracingHeaders)===null||u===void 0||u.startIfEnabledOrStop(),(h=this.autocapture)===null||h===void 0||h.startIfEnabled(),(d=this.heatmaps)===null||d===void 0||d.startIfEnabled(),("capture_pageview"in t||"disable_capture_url_hashes"in t)&&((_=this.historyAutocapture)===null||_===void 0||_.startIfEnabledOrStop()),(p=this.exceptionObserver)===null||p===void 0||p.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)===null||f===void 0||f.startIfEnabledOrStop(),(v=this.surveys)===null||v===void 0||v.loadIfEnabled(),this.Cu(),(m=this.externalIntegrations)===null||m===void 0||m.startIfEnabledOrStop(),!r.segment&&this.config.segment&&this.persistence&&jh(this,ji,!1)}}_overrideSDKInfo(t,r){et.LIB_NAME=t,et.LIB_VERSION=r}startSessionRecording(t){const r=t===!0,n={sampling:r||!!t?.sampling,linked_flag:r||!!t?.linked_flag,url_trigger:r||!!t?.url_trigger,event_trigger:r||!!t?.event_trigger};var i,s,o,a,c;Object.values(n).some(Boolean)&&((i=this.sessionManager)===null||i===void 0||i.checkAndGetSessionAndWindowId(),n.sampling&&((s=this.sessionRecording)===null||s===void 0||s.overrideSampling()),n.linked_flag&&((o=this.sessionRecording)===null||o===void 0||o.overrideLinkedFlag()),n.url_trigger&&((a=this.sessionRecording)===null||a===void 0||a.overrideTrigger("url")),n.event_trigger&&((c=this.sessionRecording)===null||c===void 0||c.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var t;return!!(!((t=this.sessionRecording)===null||t===void 0)&&t.started)}captureException(t,r){try{if(!this.exceptions)return;const n=this.exceptions.buildProperties(t,{handled:!0,syntheticException:new Error("PostHog syntheticException")});return this.exceptions.sendExceptionEvent(b(b({},n),r))}catch{return}}addExceptionStep(t,r){var n;(n=this.exceptions)===null||n===void 0||n.addExceptionStep(t,r)}captureLog(t){var r;(r=this.logs)===null||r===void 0||r.captureLog(t)}get logger(){var t,r;return(t=(r=this.logs)===null||r===void 0?void 0:r.logger)!==null&&t!==void 0?t:fr.Ch}startExceptionAutocapture(t){this.set_config({capture_exceptions:t==null||t})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(t){var r,n;return(r=(n=this.toolbar)===null||n===void 0?void 0:n.loadToolbar(t))!==null&&r!==void 0&&r}get_property(t){var r;return(r=this.persistence)===null||r===void 0?void 0:r.props[t]}getSessionProperty(t){var r;return(r=this.sessionPersistence)===null||r===void 0?void 0:r.props[t]}toString(){var t;let r=(t=this.config.name)!==null&&t!==void 0?t:Ci;return r!==Ci&&(r="posthog."+r),r}_isIdentified(){var t,r;return((t=this.persistence)===null||t===void 0?void 0:t.get_property("$user_state"))==="identified"||((r=this.sessionPersistence)===null||r===void 0?void 0:r.get_property("$user_state"))==="identified"}yh(){var t,r;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&_t(this.getGroups())&&!(!((t=this.persistence)===null||t===void 0||(t=t.props)===null||t===void 0)&&t.__alias)&&!(!((r=this.persistence)===null||r===void 0||(r=r.props)===null||r===void 0)&&r.$epp))}ih(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&!!this.config.capture_pageview}createPersonProfile(){this.yh()||this.bh("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.bh("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}bh(t){return this.config.person_profiles==="never"?(j.error(t+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this._u(),this._h(Au,!0),!0)}xu(){if(this.config.cookieless_mode==="always")return!0;const t=this.consent.isOptedOut();return this.config.disable_persistence||t&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!=="on_reject")}Cu(){var t,r;const n=this.xu();var i,s,o;return this.is_capturing()||(i=this.logs)===null||i===void 0||i.$h(),((t=this.persistence)===null||t===void 0?void 0:t.mi)!==n&&((s=this.persistence)===null||s===void 0||s.set_disabled(n)),((r=this.sessionPersistence)===null||r===void 0?void 0:r.mi)!==n&&((o=this.sessionPersistence)===null||o===void 0||o.set_disabled(n)),n&&(this.Mu.clear(),this.mh()),n}opt_in_capturing(t){var r;if(this.config.cookieless_mode!=="always"){if(this.bu()){var n,i,s,o,a,c;(n=this.sessionRecording)===null||n===void 0||n.dispose({discardBufferedEvents:!0}),this.kh(!0,!0),(i=this.sessionManager)===null||i===void 0||i.destroy(),(s=this.pageViewManager)===null||s===void 0||s.destroy(),this.sessionManager=new tp(this),this.pageViewManager=new Hh(this),this.persistence&&(this.sessionPropsManager=new Qh(this,this.sessionManager,this.persistence));const p=(o=(a=this.config.__extensionClasses)===null||a===void 0?void 0:a.sessionRecording)!==null&&o!==void 0?o:(c=fr.__defaultExtensionClasses)===null||c===void 0?void 0:c.sessionRecording;var l,u;p&&(this.sessionRecording=this.yu(this.sessionRecording,new p(this)),this.du&&((l=this.sessionRecording)===null||l===void 0||(u=l.onRemoteConfig)===null||u===void 0||u.call(l,this.du)))}var h,d;this.consent.optInOut(!0),this.Cu(),this.Yu(),(r=this.sessionRecording)===null||r===void 0||r.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&((h=this.surveys)===null||h===void 0||h.loadIfEnabled()),(O(t?.captureEventName)||t!=null&&t.captureEventName)&&this.capture((d=t?.captureEventName)!==null&&d!==void 0?d:"$opt_in",t?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.th()}else j.warn(ip)}opt_out_capturing(){if(this.config.cookieless_mode==="always")return void j.warn(ip);const t=this.config.cookieless_mode==="on_reject"?this.sessionRecording:void 0;var r,n;t?.dispose({discardBufferedEvents:!0}),this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.kh(!0,!0),this.consent.optInOut(!1),this.Cu(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:ja,$device_id:null}),this.mu(t),this.sessionRecording=void 0,(r=this.sessionManager)===null||r===void 0||r.destroy(),(n=this.pageViewManager)===null||n===void 0||n.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.th(),this.Yu())}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){const t=this.consent.consent;return t===1?"granted":t===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.Cu()}_is_bot(){return rt?m_(rt,this.config.custom_blocked_useragents):void 0}th(){N&&(N.visibilityState==="visible"?this.Ru||(this.Ru=!0,this.capture(Tu,{title:N.title},{send_instantly:!0}),this.Au&&(N.removeEventListener(es,this.Au),this.Au=null)):this.Au||(this.Au=this.th.bind(this),Ie(N,es,this.Au)))}debug(t){t===!1?(A?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(A?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}nl(){const t=this.Lu||{};return"advanced_disable_flags"in t?!!t.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(j.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(r,n,i,s,o){const a=n in r&&!ge(r[n]),c=i in r&&!ge(r[i]);return a?r[n]:!!c&&(o&&o.warn(`Config field '${i}' is deprecated. Please use '${n}' instead. The old field will be removed in a future major version.`),r[i])})(t,"advanced_disable_flags","advanced_disable_decide",0,j)}Os(t){var r;if(ge(this.config.before_send))return t;const n=Object.keys((r=t.properties)!==null&&r!==void 0?r:{}).filter(rC),i=ce(this.config.before_send)?this.config.before_send:[this.config.before_send];let s=t;for(const o of i)try{if(s=o(s),ge(s)){const a=`Event '${t.event}' was rejected in beforeSend function`;return tC(t.event)?j.warn(`${a}. This can cause unexpected behavior.`):j.info(a),null}s.properties&&!_t(s.properties)||j.warn(`Event '${t.event}' has no properties after beforeSend function, this is likely an error.`)}catch(a){return j.error(`Error in beforeSend function for event '${t.event}':`,a),null}for(const o of n)if(s.properties&&ge(s.properties[o]))return j.warn(`Event '${t.event}' had its '${o}' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped.`),null;return s}getPageViewId(){var t;return(t=this.pageViewManager.Vo)===null||t===void 0?void 0:t.pageViewId}captureTraceFeedback(t,r){this.capture("$ai_feedback",{$ai_trace_id:String(t),$ai_feedback_text:r})}captureTraceMetric(t,r,n){this.capture("$ai_metric",{$ai_trace_id:String(t),$ai_metric_name:r,$ai_metric_value:String(n)})}Du(t){const r=vt(t)&&!t,n=ke.Et()&&ke.Ot("ph_debug")==="true";return!r&&(!!n||t)}};Hi.__defaultExtensionClasses={},Hi.Ch=(()=>{const e=()=>{};return{trace:e,debug:e,info:e,warn:e,error:e,fatal:e}})(),(function(e,t){for(let r=0;t.length>r;r++)e.prototype[t[r]]=P$(e.prototype[t[r]])})(Hi,["identify"]);var k_=class{constructor(e){this.disabled=e===!1;const t=be(e)?e:{};this.thresholdPx=t.threshold_px||30,this.timeoutMs=t.timeout_ms||1e3,this.clickCount=t.click_count||3,this.clicks=[]}isRageClick(e,t,r){if(this.disabled)return!1;const n=this.clicks[this.clicks.length-1];if(n&&Math.abs(e-n.x)+Math.abs(t-n.y)<this.thresholdPx&&this.timeoutMs>r-n.timestamp){if(this.clicks.push({x:e,y:t,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:t,timestamp:r}];return!1}},oc="$copy_autocapture",ac=Be("[AutoCapture]");function cc(e,t){return t.length>e?t.slice(0,e)+"...":t}function zP(e){if(e.previousElementSibling)return e.previousElementSibling;let t=e;do t=t.previousSibling;while(t&&!Zt(t));return t}function UP(e,{e:t,maskAllElementAttributes:r,maskAllText:n,elementAttributeIgnoreList:i,elementsChainAsString:s,disableCaptureUrlHashes:o}){var a,c;if(!Zt(e))return{props:{}};const l=[e],u=new Set([e]);let h=e;for(;h.parentNode&&!ct(h,"body")&&1e3>l.length;){if($u(h.parentNode)){const $=h.parentNode.host;if(u.has($))break;u.add($),l.push($),h=$;continue}if(!Zt(h.parentNode)||u.has(h.parentNode))break;u.add(h.parentNode),l.push(h.parentNode),h=h.parentNode}const d=t.type==="click"&&e.namespaceURI==="http://www.w3.org/2000/svg"?l.findIndex($=>ct($,"button")||ct($,"a")):-1;d>0&&(n=n||l.slice(0,d+1).some($=>!jn($)||rs($)));const p=[],f={};let v,m=!1,_=!1;if(Ce(l,$=>{const M=jn($);if(ct($,"a")&&!r&&!i?.includes("href")){const L=$.getAttribute("href");m=!!(M&&L&&Ui(L))&&(o?Ur(L):L)}ue(Yn($),"ph-no-capture")&&(_=!0),p.push((function(L,q,X,ee,k=!1){const ie=L.tagName.toLowerCase(),H={tag_name:ie};Ou.indexOf(ie)>-1&&!X&&(H.$el_text=ie.toLowerCase()==="a"||ie.toLowerCase()==="button"?cc(1024,Uh(L)):cc(1024,ts(L)));const oe=Yn(L);q||ee!=null&&ee.includes("class")||0>=oe.length||(H.classes=oe.filter(function(V){return V!==""})),Ce(L.attributes,function(V){var K;if((!rs(L)||["name","id","class","aria-label"].indexOf(V.name)!==-1)&&!ee?.includes(V.name)&&!q&&Ui(V.value)&&(!ye(K=V.name)||K.substring(0,10)!=="_ngcontent"&&K.substring(0,7)!=="_nghost")){let le=V.value;V.name==="class"&&(le=Pu(le).join(" ")),H["attr__"+V.name]=cc(1024,V.name==="href"&&k?Ur(le):le)}});let I=1,Q=1,y=L;for(;y=zP(y);)I++,y.tagName===L.tagName&&Q++;return H.nth_child=I,H.nth_of_type=Q,H})($,r,n,i,o)),Ce((function(L){if(!jn(L))return{};const q={};return Ce(L.attributes,function(X){if(X.name&&X.name.indexOf("data-ph-capture-attribute")===0){const ee=X.name.replace("data-ph-capture-attribute-",""),k=X.value;ee&&k&&Ui(k)&&(q[ee]=k)}}),q})($),(L,q)=>{({}).hasOwnProperty.call(f,q)||(f[q]=L)})}),_)return{props:{},explicitNoCapture:_};if(d>0&&(e=l[d],p.splice(0,d)),n||(p[0].$el_text=ct(e,"a")||ct(e,"button")?Uh(e):ts(e)),m){var w,S;p[0].attr__href=m;const $=(w=Fr(m))===null||w===void 0?void 0:w.host,M=A==null||(S=A.location)===null||S===void 0?void 0:S.host;$&&M&&$!==M&&(v=m)}return{props:Le((C=t.type,{$event_type:C,$ce_version:1}),s?{}:{$elements:p},{$elements_chain:(T=p,ce(T)?(function($){return $.map(M=>{var L,q;let X="";if(M.tag_name&&(X+=M.tag_name),M.attr_class){M.attr_class.sort();for(const ie of M.attr_class)X+=`.${ie.replace(/"/g,"")}`}const ee=b(b(b(b({},M.text?{text:M.text}:{}),{},{"nth-child":(L=M.nth_child)!==null&&L!==void 0?L:0,"nth-of-type":(q=M.nth_of_type)!==null&&q!==void 0?q:0},M.href?{href:M.href}:{}),M.attr_id?{attr_id:M.attr_id}:{}),M.attributes),k={};return Ys(ee).sort(([ie],[H])=>(function(oe,I){return I>oe?-1:oe>I?1:0})(ie,H)).forEach(([ie,H])=>k[Fh(ie.toString())]=Fh(H.toString())),X+=":",X+=Ys(k).map(([ie,H])=>`${ie}="${H}"`).join(""),X}).join(";")})((function($){return $.map(M=>{var L,q;const X={text:(L=M.$el_text)===null||L===void 0?void 0:L.slice(0,400),tag_name:M.tag_name,href:(q=M.attr__href)===null||q===void 0?void 0:q.slice(0,2048),attr_class:G$(M),attr_id:M.attr__id,nth_child:M.nth_child,nth_of_type:M.nth_of_type,attributes:{}};return Ys(M).filter(([ee])=>ee.indexOf("attr__")===0).forEach(([ee,k])=>X.attributes[ee]=k),X})})(T)):"")},!((a=p[0])===null||a===void 0)&&a.$el_text?{$el_text:(c=p[0])===null||c===void 0?void 0:c.$el_text}:{},v&&t.type==="click"?{$external_click_url:v}:{},f),target:e};var T,C}var FP=class{fo(){this.po=void 0,clearTimeout(this.mo),this.mo=void 0}yo(e){var t;if(!jn(e))return!0;const r=(t=this.bo().css_selector_ignorelist)!==null&&t!==void 0?t:Za,n=new Set;let i=e;for(;i;){if(n.size>=1e3||n.has(i))return!0;n.add(i);const s=i,o=Yn(s);if(ue(o,"ph-no-capture")||ue(o,"ph-sensitive")||rs(s)||r.some(c=>vl(s,c)))return!0;const a=i.parentNode;i=$u(a)?a.host:a&&Zt(a)?a:null}return!1}_o(e){if(!this.isEnabled||e.type==="pointercancel")return void this.fo();if(e.type==="pointerdown"){this.fo();const n=zi(e);var t;e.isPrimary&&e.button===0&&!e.ctrlKey&&n&&Zt(n)&&(this.po={target:n,excluded:this.yo(n),id:e.pointerId,x:e.clientX,y:e.clientY,released:!1,distinctId:(t=this.wo)===null||t===void 0?void 0:t.distinctId});return}const r=this.po;r&&(e.pointerId!==r.id||Math.abs(e.clientX-r.x)>5||Math.abs(e.clientY-r.y)>5?this.fo():e.type==="pointerup"&&(r.released=!0,this.mo=setTimeout(()=>this.fo(),0)))}ko(e){var t;const r=this.po;this.fo();const n=zi(e);if(r?.released&&r.target.isConnected&&r.distinctId===((t=this.wo)===null||t===void 0?void 0:t.distinctId)&&e.pointerId===r.id&&(e.detail>0||e.pointerType==="touch"||e.pointerType==="pen")&&e.button===0&&5>=Math.abs(e.clientX-r.x)&&5>=Math.abs(e.clientY-r.y)&&n&&(ct(n,"html")||ct(n,"body"))){var i;if(r.excluded)return null;const s=(i=this.bo().css_selector_ignorelist)!==null&&i!==void 0?i:Za;return[n,N?.documentElement,N?.body].some(o=>{if(!o)return!1;const a=Yn(o);return ue(a,"ph-no-capture")||ue(a,"ph-sensitive")||!jn(o)||rs(o)||s.some(c=>vl(o,c))})?null:r.target}}constructor(e){this.So=e,this.name="autocapture",this.xo=!1,this.Co=null,this.$o=!1,this.To=!1,this.Rr={enabled:!1,rageclick:!1,maskAllElementAttributes:!1,maskAllText:!1,disableCaptureUrlHashes:!1,remoteRequestsDisabled:!1},this.Io=!1,this.So.refresh(this.Rr),this.rageclicks=new k_(this.Rr.rageclick),this.Mo=null}setup(e){this.Eo(),this.wo=e;const t=e.onRemoteConfig(this.onRemoteConfig.bind(this));this.Io?t.dispose():(this.Po=t,this.startIfEnabled())}dispose(){var e;this.Io||(this.Io=!0,this.wo=void 0,(e=this.Po)===null||e===void 0||e.dispose(),this.Po=void 0,this.Ro())}bo(){return this.So.refresh(this.Rr),this.Rr}Eo(){var e,t;return this.bo(),this.Rr.url_allowlist=(e=this.Rr.url_allowlist)===null||e===void 0?void 0:e.map(r=>new RegExp(r)),this.Rr.url_ignorelist=(t=this.Rr.url_ignorelist)===null||t===void 0?void 0:t.map(r=>new RegExp(r)),this.Rr}Ao(){if(!this.isBrowserSupported())return void ac.info("Disabling Automatic Event Collection because this browser is not supported");if(!A||!N)return;const e=this.Fo=t=>{t=t||A?.event;try{if(t.type==="blur")return void this.fo();if(t.type.indexOf("pointer")===0)return void this._o(t);const r=t.type==="click"?this.ko(t):void 0;if(He(r))return;this.Oo(t,"$autocapture",r)}catch(r){ac.error("Failed to capture event",r)}};if(Ie(A,"blur",e),Ie(N,"submit",e,{capture:!0}),Ie(N,"change",e,{capture:!0}),Ie(N,"click",e,{capture:!0}),Ce(["pointerdown","pointermove","pointerup","pointercancel"],t=>{Ie(N,t,e,{capture:!0})}),this.bo().capture_copied_text){const t=this.Do=r=>{r=r||A?.event;try{this.Oo(r,oc)}catch(n){ac.error("Failed to capture clipboard event",n)}};Ie(N,"copy",t,{capture:!0}),Ie(N,"cut",t,{capture:!0}),Ie(N,"paste",t,{capture:!0})}}Ro(){this.fo(),this.Fo&&(A?.removeEventListener("blur",this.Fo),Ce(["pointerdown","pointermove","pointerup","pointercancel"],e=>{N?.removeEventListener(e,this.Fo,!0)}),N?.removeEventListener("submit",this.Fo,!0),N?.removeEventListener("change",this.Fo,!0),N?.removeEventListener("click",this.Fo,!0),this.Fo=void 0),this.Do&&(N?.removeEventListener("copy",this.Do,!0),N?.removeEventListener("cut",this.Do,!0),N?.removeEventListener("paste",this.Do,!0),this.Do=void 0),this.xo=!1}startIfEnabled(){this.isEnabled||this.fo(),!this.Io&&this.wo&&this.isEnabled&&!this.xo&&(this.Ao(),this.xo=!0)}onRemoteConfig(e){if(this.Io)return;if(this.$o=!0,!e.ok)return void this.startIfEnabled();const t=e.config;t.elementsChainAsString&&(this.To=t.elementsChainAsString);const r=t.autocapture_opt_out;var n;vt(r)&&((n=this.wo)===null||n===void 0||n.kv.set("$autocapture_disabled_server_side",r),this.Co=r),this.startIfEnabled()}setElementSelectors(e){this.Mo=e}getElementSelectors(e,t){var r;const n=[];return(r=this.Mo)===null||r===void 0||r.forEach(i=>{N?.querySelectorAll(i)?.forEach(s=>{e!==s&&t!==s||ue(n,i)||n.push(i)})}),n}get isEnabled(){var e,t;if(this.Io)return!1;const r=(e=this.wo)===null||e===void 0?void 0:e.kv.get(pm),n=this.Co,i=this.bo();if(!i.remoteRequestsDisabled&&!this.$o)return!1;const s=i.remoteRequestsDisabled&&!this.$o;if(He(n)&&!vt(r)&&!s)return!1;const o=(t=this.Co)!==null&&t!==void 0?t:!!r;return!!i.enabled&&!o}Oo(e,t="$autocapture",r){if(!this.isEnabled)return void this.fo();let n=r||zi(e);Lm(n)&&(n=n.parentNode||null);const i=this.Eo();var s;t==="$autocapture"&&e.type==="click"&&e instanceof MouseEvent&&i.rageclick&&(s=this.rageclicks)!==null&&s!==void 0&&s.isRageClick(e.clientX,e.clientY,e.timeStamp||new Date().getTime())&&Um(n,i.rageclick)&&this.Oo(e,"$rageclick",r);const o=t===oc,a=o?b(b({},i),{},{dom_event_allowlist:void 0}):i;if(n&&(function(h,d,p,f,v,m){var _;if(!A||xu(h)||p?.url_allowlist&&!Oh(p.url_allowlist,m)||p?.url_ignorelist&&Oh(p.url_ignorelist,m))return!1;if(p?.dom_event_allowlist){const C=p.dom_event_allowlist;if(C&&!C.some($=>d.type===$))return!1}const{parentIsUsefulElement:w,targetElementList:S}=Fm(h,f);if(!(function(C,$){const M=$?.element_allowlist;if(O(M))return!0;for(const L of C)if(M.some(q=>L.tagName.toLowerCase()===q))return!0;return!1})(S,p)||!gl(S,p?.css_selector_allowlist)||gl(S,(_=p?.css_selector_ignorelist)!==null&&_!==void 0?_:Za))return!1;try{const C=A.getComputedStyle(h);if(C&&C.getPropertyValue("cursor")==="pointer"&&d.type==="click")return!0}catch{}const T=h.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(v||["submit"]).indexOf(d.type)>=0;case"input":case"select":case"textarea":return(v||["change","click"]).indexOf(d.type)>=0;default:return w?(v||["click"]).indexOf(d.type)>=0:(v||["click"]).indexOf(d.type)>=0&&(Ou.indexOf(T)>-1||h.getAttribute("contenteditable")==="true")}})(n,e,a,o,o?["copy","cut","paste"]:void 0,{config:{get_current_url:i.getCurrentUrl}})){var c;const{props:h,explicitNoCapture:d,target:p}=UP(n,{e,maskAllElementAttributes:i.maskAllElementAttributes,maskAllText:i.maskAllText,elementAttributeIgnoreList:i.element_attribute_ignorelist,elementsChainAsString:this.To,disableCaptureUrlHashes:i.disableCaptureUrlHashes});if(d)return!1;const f=this.getElementSelectors(n,p);if(f&&f.length>0&&(h.$element_selectors=f),t===oc){const v=e.type||"clipboard";if(v!=="paste"){var l,u;const m=A==null||(l=A.getSelection())===null||l===void 0?void 0:l.toString(),_=Dm(m);if(!_)return!1;h.$selected_content=_,h.$clipboard_text_length=(u=m?.length)!==null&&u!==void 0?u:0}h.$copy_type=v}return(c=this.wo)===null||c===void 0||c.capture(t,h),!0}}isBrowserSupported(){return tt(N?.querySelectorAll)}},qP=class{constructor(e){this._instance=e}refresh(e){const t=this._instance.config,r=be(t.autocapture)?t.autocapture:void 0;e.enabled=!!t.autocapture,e.rageclick=t.rageclick,e.maskAllElementAttributes=t.mask_all_element_attributes,e.maskAllText=t.mask_all_text,e.disableCaptureUrlHashes=t.disable_capture_url_hashes,e.getCurrentUrl=t.get_current_url,e.remoteRequestsDisabled=this._instance.nl(),e.url_allowlist=r?.url_allowlist,e.url_ignorelist=r?.url_ignorelist,e.dom_event_allowlist=r?.dom_event_allowlist,e.element_allowlist=r?.element_allowlist,e.css_selector_allowlist=r?.css_selector_allowlist,e.css_selector_ignorelist=r?.css_selector_ignorelist,e.element_attribute_ignorelist=r?.element_attribute_ignorelist,e.capture_copied_text=r?.capture_copied_text}},ki=Be("[ExceptionAutocapture]"),lp=()=>{},up=e=>{var t;if(tt(e))return(t=e.__posthog_layer__)!==null&&t!==void 0?t:e.__rrweb_layer__};function ss(e,t,r){try{if(!(t in e))return lp;const n={next:e[t]},i=r(function(...s){return n.next.apply(this,s)});return tt(i)&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:n}})),e[t]=i,()=>{if(e[t]===i)return void(e[t]=n.next);let s=e[t],o=up(s);for(;o;){if(o.next===i)return void(o.next=n.next);s=o.next,o=up(s)}}}catch{return lp}}var jP=Be("[TracingHeaders]"),Wr=Be("[Web Vitals]"),dp=9e5,hp=["CLS","FCP","INP","LCP"],HP=["INP","LCP"],VP=["interactionTarget","interactionType","inputDelay","processingDuration","presentationDelay","loadState","target","url","timeToFirstByte","resourceLoadDelay","resourceLoadDuration","elementRenderDelay","largestShiftTarget","largestShiftTime","largestShiftValue","firstByteToFCP"],lc="disabled",pp="lazy_loading",Xt=Be("[SessionRecording]"),BP=Be("[Heatmaps]");function uc(e){return be(e)&&"clientX"in e&&"clientY"in e&&We(e.clientX)&&We(e.clientY)}var xs=Be("[Product Tours]"),dc=e=>{var t;return!e.config.disable_product_tours&&!!(!((t=e.persistence)===null||t===void 0)&&t.get_property(Ru))},GP=["$set_once","$set"],Ft=Be("[SiteApps]"),fp="Error while initializing PostHog app with config id ",R_=(e,t)=>e?.then?e.then(t):t(e),kn="SDK is not enabled or survey functionality is not yet loaded",vp="Disabled. Not loading surveys.",WP=class{constructor(e,t){this.So=e,this.Th=t,this.name="surveys",this._surveyEventReceiver=null,this._surveyManager=null,this.Ih=!1,this.Mh=[],this.Eh=null,this.Ph=null,this.Io=!1,this.Rh=new Set,this.onRemoteConfig=r=>{if(this.Io||this.Rr.disableSurveys)return;if(!r.ok)return Te.warn("Remote config unavailable. Not loading surveys.");const n=r.config.surveys;if(ge(n))return Te.warn("Flags not loaded yet. Not loading surveys.");this.Ah=vt(n)?n:n.length>0,Te.info(`flags response received, isSurveysEnabled: ${this.Ah}`),this.loadIfEnabled()}}setup(e){if(!this.Io)return this.Fh=e,R_(e.kv.initialize(),()=>{if(this.Fh!==e||this.Io)return;this.Fh=void 0,this.wo=e;const t=e.onRemoteConfig(this.onRemoteConfig);this.Io?t.dispose():(this.Po=t,this.loadIfEnabled())})}dispose(){var e,t,r,n;this.Io||(this.Io=!0,this.Fh=void 0,this.wo=void 0,(e=this.Po)===null||e===void 0||e.dispose(),this.Po=void 0,(t=this._surveyEventReceiver)===null||t===void 0||t.dispose(),this._surveyEventReceiver=null,(r=this._surveyManager)===null||r===void 0||(n=r.dispose)===null||n===void 0||n.call(r),this._surveyManager=null,this.Mh=[],this.Eh=null,this.Rh.forEach(i=>clearTimeout(i)),this.Rh.clear())}get Rr(){return this.So.get()}initialize(){this.loadIfEnabled()}reset(){var e,t;(e=this._surveyManager)===null||e===void 0||(t=e.clearInMemoryInProgressSurveyState)===null||t===void 0||t.call(e);try{var r;(r=this._surveyEventReceiver)===null||r===void 0||r.reset(),localStorage.removeItem("lastSeenSurveyDate");const n=[];for(let i=0;i<localStorage.length;i++){const s=localStorage.key(i);(s!=null&&s.startsWith("seenSurvey_")||s!=null&&s.startsWith("inProgressSurvey_"))&&n.push(s)}n.forEach(i=>localStorage.removeItem(i))}catch{}}loadIfEnabled(){if(this.Io||!this.wo)return;const e=this.Rr;if(this._surveyManager)return;if(this.Ih)return void Te.info("Already initializing surveys, skipping...");if(e.disableSurveys)return void Te.info(vp);if(e.cookielessMode&&this.So.isOptedOut())return void Te.info("Not loading surveys in cookieless mode without consent.");const t=this.So.getExtensions();if(!t)return void Te.error("PostHog Extensions not found.");if(O(this.Ah)&&!e.advancedEnableSurveys)return;const r=this.Ah||e.advancedEnableSurveys;this.Ih=!0;try{const n=t.generateSurveys;if(n)return this.Oh(n,r),void(this.Ih=!1);const i=t.loadExternalDependency;if(!i)return this.Dh(Iu),void(this.Ih=!1);i(s=>{try{if(this.Io)return;const o=this.So.getExtensions();s||!o?.generateSurveys?this.Dh("Could not load surveys script",s):this.Oh(o.generateSurveys,r)}finally{this.Ih=!1}})}catch(n){throw this.Ih=!1,this.Dh("Error initializing surveys",n),n}}Oh(e,t){this.Io||(this._surveyManager=e(t),this._surveyEventReceiver=this.So.createEventReceiver(),Te.info("Surveys loaded successfully"),this.Lh({isLoaded:!0}))}Dh(e,t){Te.error(e,t),this.Lh({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.Mh.push(e),this._surveyManager&&this.Lh({isLoaded:!0}),()=>{this.Mh=this.Mh.filter(t=>t!==e)}}getSurveys(e,t=!1){var r;const n=(r=this.wo)!==null&&r!==void 0?r:this.Th;if(!n||this.Io)return;if(this.Rr.disableSurveys)return Te.info(vp),e([]);const i=n.kv.get(ll);if(i&&!t)return e(i,{isLoaded:!0}),void(this.Nh()&&this.getSurveys(()=>{},!0));if(this.Eh)return void this.Eh.then(({surveys:a,context:c})=>{this.Io||e(a,c)}).catch(a=>Te.error("Error in survey callback",a));const s=this.qh("/api/surveys/",{method:"GET",query:{token:n.projectToken},sentAt:"query",timeoutMs:this.Rr.requestTimeoutMs}).then(a=>{try{return this.jh(n,a)}catch(c){return Te.error("Error processing surveys response",c),this.jh(n,{statusCode:0,error:c})}},a=>this.jh(n,{statusCode:0,error:a}));this.Eh=s;const o=()=>{this.Eh===s&&(this.Eh=null)};s.then(a=>{o(),this.Io||e(a.surveys,a.context)},o).catch(a=>Te.error("Error in survey callback",a))}qh(e,t){const r=this.wo;return r?r.sendRequest(e,t):new Promise(n=>n({statusCode:0,error:new Error(kn)}))}jh(e,t){if(this.Io)return{surveys:[],context:{isLoaded:!1,error:kn}};const r=t.statusCode;if(r!==200||!t.json){const o=`Surveys API could not be loaded, status: ${r}`;return r!==0?Te.error(o):t.error||Te.warn(o),this.Ph=Date.now(),{surveys:[],context:{isLoaded:!1,error:o}}}this.Ph=null;const n=t.json.surveys||[],i=n.filter(o=>(function(a){return!(!a.start_date||a.end_date)})(o)&&(y_(o)||(function(a){var c;return!!(!((c=a.conditions)===null||c===void 0||(c=c.actions)===null||c===void 0||(c=c.values)===null||c===void 0)&&c.length)})(o)));var s;return i.length>0&&((s=this._surveyEventReceiver)===null||s===void 0||s.register(i)),e.kv.set({[ll]:n,[Eo]:Date.now()}),{surveys:n,context:{isLoaded:!0}}}Nh(){return this.Bh()&&!this.Eh&&!this.Hh()}Bh(){var e,t;const r=(e=(t=this.wo)!==null&&t!==void 0?t:this.Th)===null||e===void 0?void 0:e.kv.get(Eo);return We(r)&&Date.now()-r>3e5}Hh(){return We(this.Ph)&&3e5>Date.now()-this.Ph}markSurveyAsSeen(e,t){var r;const n={id:e,current_iteration:(r=t?.iteration)!==null&&r!==void 0?r:null};S_(n);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Lh(e){for(const t of this.Mh)try{if(!e.isLoaded)return t([],e);this.getSurveys(t)}catch(r){Te.error("Error in survey callback",r)}}getActiveMatchingSurveys(e,t=!1){if(!ge(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);Te.warn("init was not called")}zh(e){let t=null;return this.getSurveys(r=>{var n;t=(n=r.find(i=>i.id===e))!==null&&n!==void 0?n:null}),t}Uh(e){if(ge(this._surveyManager))return{eligible:!1,reason:kn};const t=typeof e=="string"?this.zh(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}Wh(e){if(!this.So.isCapturing())return{eligible:!1,reason:"PostHog is not capturing, so a survey response cannot be recorded"};if(ge(this._surveyManager))return{eligible:!1,reason:kn};const t=typeof e=="string"?this.zh(e):e;return t?this._surveyManager.checkSurveyRenderability(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(ge(this._surveyManager))return Te.warn("init was not called"),{visible:!1,disabledReason:kn};const t=this.Wh(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return ge(this._surveyManager)?(Te.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:kn})):new Promise(r=>{this.getSurveys(n=>{var i;const s=(i=n.find(o=>o.id===e))!==null&&i!==void 0?i:null;if(s){const o=this.Wh(s);r({visible:o.eligible,disabledReason:o.reason})}else r({visible:!1,disabledReason:"Survey not found"})},t)})}renderSurvey(e,t,r){var n;if(!this.So.isCapturing())return;if(ge(this._surveyManager))return void Te.warn("init was not called");const i=typeof e=="string"?this.zh(e):e;if(!i?.id)return void Te.warn("Survey not found");if(!RP.includes(i.type))return void Te.warn(`Surveys of type ${i.type} cannot be rendered in the app`);const s=N?.querySelector(t);if(s){if(!((n=i.appearance)===null||n===void 0)&&n.surveyPopupDelaySeconds){Te.info(`Rendering survey ${i.id} with delay of ${i.appearance.surveyPopupDelaySeconds} seconds`);const o=setTimeout(()=>{var a,c;this.Rh.delete(o),!this.Io&&this.So.isCapturing()&&(Te.info(`Rendering survey ${i.id} with delay of ${(a=i.appearance)===null||a===void 0?void 0:a.surveyPopupDelaySeconds} seconds`),(c=this._surveyManager)===null||c===void 0||c.renderSurvey(i,s,r),Te.info(`Survey ${i.id} rendered`))},1e3*i.appearance.surveyPopupDelaySeconds);this.Rh.add(o);return}this._surveyManager.renderSurvey(i,s,r)}else Te.warn("Survey element not found")}displaySurvey(e,t){var r;if(!this.So.isCapturing())return;if(ge(this._surveyManager))return void Te.warn("init was not called");const n=this.zh(e);if(!n)return void Te.warn("Survey not found");let i=n;if((r=n.appearance)!==null&&r!==void 0&&r.surveyPopupDelaySeconds&&t.ignoreDelay&&(i=b(b({},n),{},{appearance:b(b({},n.appearance),{},{surveyPopupDelaySeconds:0})})),t.displayType!==ml.Popover&&t.initialResponses&&Te.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),t.ignoreConditions===!1){const s=this.Uh(n);if(!s.eligible)return void Te.warn("Survey is not eligible to be displayed: ",s.reason)}t.displayType!==ml.Inline?this._surveyManager.handlePopoverSurvey(i,t):this.renderSurvey(i,t.selector,t.properties)}cancelPendingSurvey(e){ge(this._surveyManager)?Te.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e,t;(e=this._surveyManager)===null||e===void 0||(t=e.handlePageUnload)===null||t===void 0||t.call(e)}};function Rn(e,t,r){if(ge(e))return!1;switch(r){case"exact":return e===t;case"contains":{const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(n,"i").test(e)}case"regex":try{return new RegExp(t).test(e)}catch{return!1}default:return!1}}var ZP=class{constructor(e){this._instance=e,this.Vh=new Set,this.Gh=new Set,this.Zh=new Co,this.Qh=(t,r)=>this.Jh(t,r)&&this.Kh(t,r)&&this.Xh(t,r)&&this.Yh(t,r),this.Jh=(t,r)=>!r?.event||t?.event===r?.event}init(){var e,t;O((e=this._instance)===null||e===void 0?void 0:e._addCaptureHook)||(this.tc=(t=this._instance)===null||t===void 0?void 0:t._addCaptureHook((r,n)=>{this.on(r,n)}))}dispose(){var e;(e=this.tc)===null||e===void 0||e.call(this),this.tc=void 0,this.Zh=new Co}register(e){var t,r;if(!O((t=this._instance)===null||t===void 0?void 0:t._addCaptureHook)&&(e.forEach(n=>{var i;this.Vh.add(n),(i=n.steps)===null||i===void 0||i.forEach(s=>{this.Gh.add(s?.event||"")})}),(r=this._instance)===null||r===void 0?void 0:r.autocapture)){const n=new Set;this.Vh.forEach(i=>{var s;(s=i.steps)===null||s===void 0||s.forEach(o=>{o!=null&&o.selector&&n.add(o.selector)})}),this._instance.autocapture.setElementSelectors(n)}}replace(e){this.Vh.clear(),this.Gh.clear(),this.register(e)}on(e,t){t!=null&&e.length!=0&&(this.Gh.has(e)||this.Gh.has(t.event))&&this.Vh.forEach(r=>{this.ec(t,r)&&this.Zh.emit("actionCaptured",r.name)})}nc(e){this.onAction("actionCaptured",t=>e(t))}ec(e,t){if(t?.steps==null)return!1;for(const r of t.steps)if(this.Qh(e,r))return!0;return!1}onAction(e,t){return this.Zh.on(e,t)}Kh(e,t){if(t?.url){var r;const n=e==null||(r=e.properties)===null||r===void 0?void 0:r.$current_url;if(!n||typeof n!="string"||!Rn(n,t.url,t.url_matching||"contains"))return!1}return!0}Xh(e,t){return!!this.sc(e,t)&&!!this.rc(e,t)&&!!this.oc(e,t)}sc(e,t){var r;if(!t?.href)return!0;const n=this.ac(e);if(n.length>0)return n.some(s=>Rn(s.href,t.href,t.href_matching||"exact"));const i=(e==null||(r=e.properties)===null||r===void 0?void 0:r.$elements_chain)||"";return!!i&&Rn((function(s){const o=s.match(/(?::|")href="(.*?)"/);return o?o[1]:""})(i),t.href,t.href_matching||"exact")}rc(e,t){var r;if(!t?.text)return!0;const n=this.ac(e);if(n.length>0)return n.some(c=>Rn(c.text,t.text,t.text_matching||"exact")||Rn(c.$el_text,t.text,t.text_matching||"exact"));const i=(e==null||(r=e.properties)===null||r===void 0?void 0:r.$elements_chain)||"";return!!i&&(s=(function(c){const l=[],u=/(?::|")text="(.*?)"/g;let h;for(;!ge(h=u.exec(c));)l.includes(h[1])||l.push(h[1]);return l})(i),o=t.text,a=t.text_matching||"exact",s.some(c=>Rn(c,o,a)));var s,o,a}oc(e,t){var r,n;if(!t?.selector)return!0;const i=e==null||(r=e.properties)===null||r===void 0?void 0:r.$element_selectors;if(i?.includes(t.selector))return!0;const s=(e==null||(n=e.properties)===null||n===void 0?void 0:n.$elements_chain)||"";if(t.selector_regex&&s)try{return new RegExp(t.selector_regex).test(s)}catch{return!1}return!1}ac(e){var t;return(e==null||(t=e.properties)===null||t===void 0?void 0:t.$elements)==null?[]:e?.properties.$elements}Yh(e,t){return!t?.properties||t.properties.length===0||w_(t.properties.reduce((r,n)=>{const i=ce(n.value)?n.value.map(String):n.value!=null?[String(n.value)]:[];return r[n.key]={values:i,operator:n.operator||"exact"},r},{}),e?.properties)}},JP=class{constructor(e){var t,r;this.lc=[],this._instance=e,this.uc=new Map,this.hc=new Map,this.cc=new Map,this.dc=(t=this._instance)===null||t===void 0||(r=t.onSessionId)===null||r===void 0?void 0:r.call(t,n=>this.vc(n))}fc(e){return!1}gc(){return null}mc(e){}yc(){}bc(e,t){return!!e&&w_(e.propertyFilters,t?.properties)}_c(e,t){const r=new Map;return e.forEach(n=>{var i;(i=n.conditions)===null||i===void 0||(i=i[t])===null||i===void 0||(i=i.values)===null||i===void 0||i.forEach(s=>{if(s?.name){const o=r.get(s.name)||[];o.push(n.id),r.set(s.name,o)}})}),r}wc(e,t,r){const n=(r===bi.Activation?this.uc:this.hc).get(e);let i=[];return this.kc(s=>{i=s.filter(o=>n?.includes(o.id))}),i.filter(s=>{var o;const a=(o=s.conditions)===null||o===void 0||(o=o[r])===null||o===void 0||(o=o.values)===null||o===void 0?void 0:o.find(c=>c.name===e);return this.bc(a,t)})}register(e){this.Sc(e,!1)}replace(e){this.Sc(e,!0)}Sc(e,t){var r;O((r=this._instance)===null||r===void 0?void 0:r._addCaptureHook)||(this.xc(e,t),this.Cc(e,t))}Cc(e,t){const r=e.filter(s=>{var o;return(o=s.conditions)===null||o===void 0||(o=o.actions)===null||o===void 0||(o=o.values)===null||o===void 0?void 0:o.length});var n;if(t&&this.cc.clear(),r.length===0)return void(t&&((n=this.$c)===null||n===void 0||n.replace([])));this.$c||(this.$c=new ZP(this._instance),this.$c.init(),this.$c.nc(s=>this.onAction(s)));const i=[];r.forEach(s=>{var o;(o=s.conditions)===null||o===void 0||(o=o.actions)===null||o===void 0||o.values.forEach(a=>{if(i.push(a),a.name){var c;const l=(c=this.cc.get(a.name))!==null&&c!==void 0?c:[];l.includes(s.id)||l.push(s.id),this.cc.set(a.name,l)}})}),t?this.$c.replace(i):this.$c.register(i)}Tc(e,t){t.forEach((r,n)=>{var i;const s=(i=e.get(n))!==null&&i!==void 0?i:[];r.forEach(o=>{s.includes(o)||s.push(o)}),e.set(n,s)})}xc(e,t){var r,n;const i=e.filter(c=>{var l,u;return((l=c.conditions)===null||l===void 0?void 0:l.events)&&((u=c.conditions)===null||u===void 0||(u=u.events)===null||u===void 0||(u=u.values)===null||u===void 0?void 0:u.length)>0}),s=e.filter(c=>{var l,u;return((l=c.conditions)===null||l===void 0?void 0:l.cancelEvents)&&((u=c.conditions)===null||u===void 0||(u=u.cancelEvents)===null||u===void 0||(u=u.values)===null||u===void 0?void 0:u.length)>0}),o=this._c(e,bi.Activation),a=this._c(e,bi.Cancellation);t?(this.uc=o,this.hc=a):(this.Tc(this.uc,o),this.Tc(this.hc,a)),(i.length!==0||s.length!==0)&&((r=this.tc)!==null&&r!==void 0||(this.tc=(n=this._instance)===null||n===void 0?void 0:n._addCaptureHook((c,l)=>{this.onEvent(c,l)})))}onEvent(e,t){var r,n;const i=this.Ic(),s=(t==null||(r=t.properties)===null||r===void 0?void 0:r.$survey_id)||(t==null||(n=t.properties)===null||n===void 0?void 0:n.$product_tour_id);if(s&&this.getActivatedIds().includes(s)){const a=this.Mc(e,s);if(a==="consume")return i.info("event consumed activated item, removing it",{event:e,itemId:s}),void this.Ec([s]);if(a==="persist")return i.info("shown item promoted to persisted activation",{event:e,itemId:s}),this.Pc(s),void this.Rc([s])}if(this.hc.has(e)){const a=this.wc(e,t,bi.Cancellation);a.length>0&&(i.info("cancel event matched, cancelling items",{event:e,itemsToCancel:a.map(c=>c.id)}),this.Ec(a.map(c=>c.id)),a.forEach(c=>this.Ac(c.id)))}if(!this.uc.has(e))return;i.info("event name matched",{event:e,eventPayload:t,items:this.uc.get(e)});const o=this.wc(e,t,bi.Activation);this.Fc(o.map(a=>a.id))}onAction(e){this.cc.has(e)&&this.Fc(this.cc.get(e)||[])}Fc(e){var t,r;if(e.length===0)return;const n=!!(!((t=this._instance)===null||t===void 0||(r=t.get_session_id)===null||r===void 0)&&r.call(t)),i=[];for(const s of e)n&&this.fc(s)?this.Pc(s)&&this.Oc(s):i.push(s);i.length>0&&(this.lc=[...new Set([...this.lc,...i])]),this.Ic().info("updating activated items",{activatedItems:this.getActivatedIds()})}Pc(e){this.lc=this.lc.filter(r=>r!==e);const t=this.Dc();return!t.includes(e)&&(this.Lc([...t,e]),this.Nc(),!0)}Ec(e){const t=new Set(e);this.lc=this.lc.filter(i=>!t.has(i));const r=this.qc(),n=r.filter(i=>!t.has(i));n.length!==r.length&&(this.Lc(n),n.length===0&&this.jc()),this.Rc(e)}Bc(){var e;const t=this.gc();if(!t)return{};const r=(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0?void 0:e.props[t];return r&&typeof r=="object"?r:{}}Oc(e){if(!this.gc())return;const t=this.Bc();this.mc(b(b({},t),{},{[e]:Date.now()}))}Rc(e){if(!this.gc())return;const t=this.Bc(),r={};let n=!1;for(const[i,s]of Object.entries(t))e.includes(i)?n=!0:r[i]=s;n&&(_t(r)?this.yc():this.mc(r))}Hc(){this.gc()&&this.yc()}getActivationTimestamp(e){if(!this.Dc().includes(e))return;const t=this.Bc()[e];return We(t)?t:void 0}qc(){var e;const t=this.zc();return((e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0?void 0:e.props[t])||[]}Dc(){var e,t,r;const n=this.qc();if(n.length===0)return[];const i=(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0?void 0:e.props[this.Uc()],s=(t=this._instance)===null||t===void 0||(r=t.get_session_id)===null||r===void 0?void 0:r.call(t);return s&&i===s?n:[]}Nc(){var e,t;const r=(e=this._instance)===null||e===void 0||(t=e.get_session_id)===null||t===void 0?void 0:t.call(e);r&&this.Wc(r)}jc(){this.Vc()}vc(e){var t;const r=(t=this._instance)===null||t===void 0||(t=t.persistence)===null||t===void 0?void 0:t.props[this.Uc()];if(r&&r!==e){const n=this.qc(),i=this.Bc();n.length>0&&(this.Lc([]),n.filter(s=>We(i[s])).forEach(s=>this.Ac(s))),this.jc(),this.Hc()}}getActivatedIds(){return[...new Set([...this.Dc(),...this.lc])].filter(e=>!this.Gc(e))}dispose(){var e,t,r;(e=this.dc)===null||e===void 0||e.call(this),this.dc=void 0,(t=this.tc)===null||t===void 0||t.call(this),this.tc=void 0,(r=this.$c)===null||r===void 0||r.dispose(),this.$c=void 0}reset(){this.lc=[],this.qc().length>0&&this.Lc([]),this.jc(),this.Hc()}getEventToItemsMap(){return this.uc}Zc(){return this.$c}},KP=class extends JP{constructor(e){super(e)}zc(){return ym}Uc(){return bm}gc(){return wm}mc(e){var t;(t=this._instance)===null||t===void 0||(t=t.persistence)===null||t===void 0||t.register({$surveys_activated_timestamps:e})}yc(){var e;(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0||e.unregister("$surveys_activated_timestamps")}fc(e){var t;let r;this.kc(i=>{r=i.find(s=>s.id===e)});const n=r==null||(t=r.appearance)===null||t===void 0?void 0:t.surveyPopupDelaySeconds;return We(n)&&n>0}Qc(){return or.SHOWN}kc(e){var t;(t=this._instance)===null||t===void 0||t.getSurveys(e)}Ac(e){var t;(t=this._instance)===null||t===void 0||t.cancelPendingSurvey(e)}Ic(){return Te}Lc(e){var t;(t=this._instance)===null||t===void 0||(t=t.persistence)===null||t===void 0||t.register({$surveys_activated:e})}Wc(e){var t;(t=this._instance)===null||t===void 0||(t=t.persistence)===null||t===void 0||t.register({$surveys_activated_session:e})}Vc(){var e;(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0||e.unregister("$surveys_activated_session")}Gc(){return!1}Mc(e,t){let r;return this.kc(n=>{r=n.find(i=>i.id===t)}),!r||(function(n){var i;return y_(n)&&!!(!((i=n.conditions)===null||i===void 0||(i=i.events)===null||i===void 0)&&i.repeatedActivation)||n.schedule==="always"})(r)?e===or.SHOWN?"consume":"ignore":e===or.SHOWN?"persist":e===or.DISMISSED||e===or.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}},YP=class{constructor(e){this._instance=e}initialize(){}get(e){if(typeof e=="string")return this._instance.get_property(e);const t={};for(const r of e){const n=this._instance.get_property(r);O(n)||(t[r]=n)}return t}set(e,t){this._instance.register(typeof e=="string"?{[e]:t}:e)}remove(e){typeof e!="string"?e.forEach(t=>this._instance.unregister(t)):this._instance.unregister(e)}},XP=class{constructor(e){this._instance=e}get(){const e=this._instance.config;return{disableSurveys:e.disable_surveys,cookielessMode:!!e.cookieless_mode,advancedEnableSurveys:e.advanced_enable_surveys,requestTimeoutMs:e.surveys_request_timeout_ms}}isOptedOut(){return this._instance.consent.isOptedOut()}isCapturing(){return this._instance.is_capturing()}getExtensions(){const e=te?.__PosthogExtensions__;if(!e)return;const{generateSurveys:t,loadExternalDependency:r}=e;return{generateSurveys:t?n=>t(this._instance,n):void 0,loadExternalDependency:r?n=>r(this._instance,"surveys",n):void 0}}createEventReceiver(){return new KP(this._instance)}},QP=A?.location?Ao(A.location.hash,"__posthog")||Ao(location.hash,"state"):null,gp="_postHogToolbarParams",mp=Be("[Toolbar]"),_p=Be("[FeatureFlags]"),eO=class{constructor(e,t=!1){this.Jc=!1,this.update(e,t)}update(e,t){this.Kc=((r,n)=>{var i,s,o,a,c,l,u,h;return{bootstrap:{featureFlags:(i=(s=r.bootstrap)===null||s===void 0?void 0:s.featureFlags)!==null&&i!==void 0?i:void 0,featureFlagPayloads:(o=(a=r.bootstrap)===null||a===void 0?void 0:a.featureFlagPayloads)!==null&&o!==void 0?o:void 0},remoteRequestsDisabled:n,featureFlagsDisabled:!!r.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!r.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!r.advanced_feature_flags_dedup_per_session,cacheTtlMs:r.feature_flag_cache_ttl_ms,refreshIntervalMs:(c=r.remote_config_refresh_interval_ms)!==null&&c!==void 0?c:3e5,idleRefreshBackoff:O(r.remote_config_refresh_interval_ms),requestTimeoutMs:r.feature_flag_request_timeout_ms,requestMaxRetries:Math.max(0,(l=r.feature_flag_request_max_retries)!==null&&l!==void 0?l:1),compression:r.disable_compression?void 0:"best-available",evaluationContexts:(u=(h=r.evaluation_contexts)!==null&&h!==void 0?h:r.evaluation_environments)!==null&&u!==void 0?u:[],flagKeys:ce(r.flag_keys)?r.flag_keys:void 0}})(e,t),!e.evaluation_environments||e.evaluation_contexts||this.Jc||(_p.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.Jc=!0),O(e.flag_keys)||ce(e.flag_keys)||_p.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.Kc}},yp=Be("[FeatureFlags]"),Zr=Be("[FeatureFlags]",{debugEnabled:!0}),hc=`" failed. Feature flags didn't load in time.`,tO=[502,504],bp=["click","keydown","wheel","touchstart","pointerdown"],wp="connection_error",Sp=e=>{const t={};for(let r=0;e.length>r;r++)t[e[r]]=!0;return t},Ep=e=>{const t={};for(const[r,n]of Ys(e||{}))n&&(t[r]=n);return t},kp=e=>ci(e)&&(e.name==="RangeError"&&e.message.indexOf("Maximum call stack size exceeded")===0||e.name==="InternalError"&&e.message==="too much recursion"),$t=Be("[Error tracking]"),El="webkit-masked-url:",rO=[{value:"isolatedAPI.contexts.topHostname",exact:!1},{value:"No response from target",exact:!0}],nO=["chrome-extension://","moz-extension://","safari-extension:","safari-web-extension:",El],iO=["__firefox__","__gCrWeb"],Rp="Refusing to render web experiment since the viewer is a likely bot",sO={icontains:(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())>-1,not_icontains:(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())===-1,regex:(e,t)=>$o(t,e),not_regex:(e,t)=>!$o(t,e),exact:(e,t)=>t===e,is_not:(e,t)=>t!==e},kt=Be("[Conversations]"),Jr="Conversations not available yet.";function Ap(e,t){var r,n,i,s,o,a,c;const l=(r=e?.flushIntervalMs)!==null&&r!==void 0?r:3e3,u=(n=e?.maxBufferSize)!==null&&n!==void 0?n:100,h=t?.consoleCapture?void 0:(i=e?.maxLogsPerInterval)!==null&&i!==void 0?i:1e3,d=O(h)?Math.max(u,2048):Math.max(u,h),p=b(b({},(function(){let f="",v="";try{const m=rt?.userAgent;m&&([f,v]=Vg(m))}catch{}return(function(m,_){const w=(function(S){if(S)return{}.hasOwnProperty.call(bh,S)?bh[S]:S})(m);return b(b({},w?{"os.name":w}:{}),_?{"os.version":_}:{})})(f,v)})()),e?.resourceAttributes);return{serviceName:(s=(o=p?.["service.name"])!==null&&o!==void 0?o:e?.serviceName)!==null&&s!==void 0?s:t?.serviceNameDefault,serviceVersion:(a=p?.["service.version"])!==null&&a!==void 0?a:e?.serviceVersion,environment:(c=p?.["deployment.environment"])!==null&&c!==void 0?c:e?.environment,resourceAttributes:p,beforeSend:e?.beforeSend,flushIntervalMs:l,maxBufferSize:u,maxQueueSize:d,maxBatchRecordsPerPost:100,rateCapWindowMs:l,maxLogsPerInterval:h,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}}var oO=["debug","log","warn","error","info"],aO=e=>{for(;e?.__rrweb_original__;)e=e.__rrweb_original__;return e},Ip="console",A_="__posthogHandledLogsRequestError",pc=(e,t)=>{const r=e instanceof Error?e:new Error(t);return r[A_]=!0,r},Tp=e=>!!e&&typeof e=="object"&&e[A_]===!0,Po=Be("[NetworkMetrics]"),Du=()=>{var e;return!(A==null||(e=A.performance)===null||e===void 0)&&e.now?A.performance.now():Date.now()},cO={"http:":80,"https:":443},lO=new Set(["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"]),I_=(e,t)=>{var r;const n=String(t);return{method:String(e).toUpperCase(),url:((r=Fr(n))===null||r===void 0?void 0:r.href)||n}},kl=(e,t,r,n,i,s,o=!1)=>{try{var a,c;const l=i();if(!l)return;const u=r||void 0,h=Du()-n,d=Fr(t.url);if(d&&d.protocol!=="http:"&&d.protocol!=="https:")return;const p={url:d?.href||t.url,method:t.method},f=tt(l.name)?l.name(p):ye(l.name)?l.name:"http.client.request.duration";if(!f)return;const v=o&&!u?void 0:((_,w)=>_?400>_?void 0:String(_):w?.name||"_OTHER")(u,s),m=b(b(b(b(b({},(_=>{const w=lO.has(_)?_:"_OTHER";return b({"http.request.method":w},w==="_OTHER"&&_!==w?{"http.request.method_original":_}:{})})(p.method)),d?(_=>{return{"server.address":_.hostname.startsWith("[")&&_.hostname.endsWith("]")?_.hostname.slice(1,-1):_.hostname,"server.port":Number(_.port)||cO[_.protocol],"url.scheme":_.protocol.slice(0,-1),"url.template":(w=_.pathname,w.split("/").map(S=>(T=>/^\d+$/.test(T)||T.length>=8&&/^[0-9a-f-]*\d[0-9a-f-]*$/i.test(T))(S)?":id":S).join("/"))};var w})(d):{}),u?{"http.response.status_code":u}:{}),v?{"error.type":v}:{}),(a=l.attributes)===null||a===void 0?void 0:a.call(l,p,{status:u,durationMs:h}));(c=e.metrics)===null||c===void 0||c.histogram(f,h,{unit:"ms",attributes:m})}catch(l){Po.error("Failed to record network metric",l)}},T_=()=>{},uO=(e,t)=>tt(A?.fetch)?ss(A,"fetch",r=>function(...n){const i=Du(),s=r.apply(this,n);if(!t())return s;try{var o,a,c;const[l,u]=n,h=I_((o=(a=u?.method)!==null&&a!==void 0?a:l?.method)!==null&&o!==void 0?o:"GET",(c=l?.url)!==null&&c!==void 0?c:l);return s.then(d=>(kl(e,h,d?.status,i,t,void 0,!0),d),d=>{throw kl(e,h,void 0,i,t,d),d})}catch(l){return Po.error("Failed to observe fetch",l),s}}):T_,dO=(e,t)=>{var r;const n=A==null||(r=A.XMLHttpRequest)===null||r===void 0?void 0:r.prototype;if(!n)return T_;const i=new WeakMap,s=ss(n,"open",a=>function(...c){try{o_.has(this)||i.set(this,I_(c[0],c[1]))}catch(l){Po.error("Failed to observe XHR open",l)}return a.apply(this,c)}),o=ss(n,"send",a=>function(...c){let l;try{const u=i.get(this);if(u&&t()){const h=Du();l=()=>{this.removeEventListener("loadend",l),kl(e,u,this.status,h,t)},Ie(this,"loadend",l)}}catch(u){Po.error("Failed to observe XHR send",u)}try{return a.apply(this,c)}catch(u){throw l&&this.removeEventListener("loadend",l),u}});return()=>{s(),o()}},ma={featureFlags:class{constructor(e){this.name="featureFlags",this.Xc=!1,this.featureFlagEventHandlers=[],this.$=yp,this.Yc={},this.td={},this.ed=[],this.nd=!1,this.sd=!1,this.rd=0,this.od=!1,this.ad=!1,this.ld=!1,this.ud=!1,this.hd=0,this.dd=!1,this.an=()=>{const t=this.vd();this.hd=0,t&&this.reloadFeatureFlags()},this.fd=()=>{var t,r;const n=this.pd,i=(t=this.gd)!==null&&t!==void 0?t:n;O(n)||O(i)||this.Rr.remoteRequestsDisabled||!N||N.visibilityState==="hidden"||Date.now()-((r=this.md)!==null&&r!==void 0?r:0)<i||(this.gd=this.dd||!this.Rr.idleRefreshBackoff?n:Math.min(2*i,36e5),this.dd=!1,this.reloadFeatureFlags(),this.yd())},this.bd=()=>{this.dd&&this.gd===this.pd||this._d()},this.ln=()=>{N?.visibilityState==="visible"&&this._d()},"get"in e?this.So=e:(this._instance=e,this.wd=new eO(e.config,e.nl()),this.So=this.wd)}updateConfig(e,t){var r;(r=this.wd)===null||r===void 0||r.update(e,t),this.wo&&this.kd()}setup(e){return this.Fh=e,this.$=e.logger.createLogger("[FeatureFlags]"),R_(e.kv.initialize(),()=>{this.Fh===e&&(this.Fh=void 0,this.wo=e,this.Sd(e))})}Sd(e){var t;if(this.wo===e)return A&&Ie(A,"online",this.an),this.kd(),this.xd=e.registerDynamicEventProperties(()=>this.Cd()?this.Yc:this.td),this.$d=(t=this._instance)===null||t===void 0||(t=t.persistence)===null||t===void 0?void 0:t.onCrossTabFeatureFlagChange(()=>{this.Td(),this.Id(),this.Md()}),this.Id(),this.initialize()}_d(){this.dd=!0,this.gd=this.pd,this.fd()}kd(){const e=this.Rr.refreshIntervalMs,t=!this.Rr.remoteRequestsDisabled&&N&&!O(e)&&e>0?e:void 0;this.Rr.idleRefreshBackoff||(this.gd=t),t!==this.pd&&(this.Ed(),O(t)||(this.pd=t,this.gd=t,this.yd(),N!=null&&N.addEventListener&&(Ie(N,es,this.ln),Dn(bp,r=>{Ie(N,r,this.bd,{capture:!0})}))))}yd(){O(this.pd)||(O(this.Pd)||clearInterval(this.Pd),this.md=Date.now(),this.Pd=setInterval(this.fd,this.pd))}Ed(){var e;O(this.Pd)||(clearInterval(this.Pd),this.Pd=void 0,N==null||(e=N.removeEventListener)===null||e===void 0||e.call(N,"visibilitychange",this.ln),Dn(bp,t=>{var r;N==null||(r=N.removeEventListener)===null||r===void 0||r.call(N,t,this.bd,{capture:!0})})),this.pd=void 0,this.gd=void 0,this.dd=!1,this.md=void 0}destroy(){this.Rd()}dispose(){this.Rd()}Rd(){var e,t;this.Ed(),this.rd++,this.ad=!1,this.Fh=void 0,this.wo&&(this.Ad(),(e=this.xd)===null||e===void 0||e.dispose(),this.xd=void 0,(t=this.$d)===null||t===void 0||t.call(this),this.$d=void 0,this.ed=[],A?.removeEventListener("online",this.an),this.wo=void 0)}get Rr(){return this.So.get()}Fd(e){var t;return this.Od&&e in this.Od?this.Od[e]:(t=this.wo)===null||t===void 0?void 0:t.kv.get(e)}Td(){return!!this.Od&&(this.Od=void 0,!0)}Dd(){var e;return!O((e=this.wo)===null||e===void 0?void 0:e.kv.get("$enabled_feature_flags"))&&this.Td()}At(e){this.Ld(()=>{var t;return(t=this.wo)===null||t===void 0?void 0:t.kv.set(e)})}Nd(e,t,r){var n;if(!(!((n=this._instance)===null||n===void 0)&&n.persistence)||!e.$enabled_feature_flags)return;const i=this.Fd("$enabled_feature_flags")||{},s=e.$enabled_feature_flags||{},o=t.flags||t.featureFlags,a=t.flags?Object.entries(t.flags).filter(([,_])=>!_?.failed).map(([_])=>_):[],c=!!t.errorsWhileComputingFlags&&!!t.flags,l=c?a:r&&!ce(o)?Object.keys(o||{}):Array.from(new Set([...Object.keys(i),...Object.keys(s)])),u=this.Fd("$feature_flag_payloads")||{},h=e.$feature_flag_payloads||{},d=c||r?l:Array.from(new Set([...Object.keys(u),...Object.keys(h)])),p=!c&&!r,f=!!p||l,v=!!p||d,m={[ir]:f,[Mt]:f,[wr]:v};e.$feature_flag_details&&(m[ln]=f);for(const _ of[un,Cr,Di])O(e[_])||(m[_]=!0);this._instance.persistence.markCrossTabFeatureFlagChanges(m)}Lt(e){this.Ld(()=>{var t;return(t=this.wo)===null||t===void 0?void 0:t.kv.remove(e)})}Ld(e){try{e()}catch(t){this.$.error("Failed to update feature flag persistence",t)}}Id(){const e={};for(const n of[ir,wr,un,qt]){const i=this.Fd(n);O(i)||(e[n]=i)}this.Yc=e;const t=b({},e),r=this.Fd(Mt);if(r)for(const[n,i]of Object.entries(r))t[`$feature/${n}`]=i;this.td=t}Cd(){const e=this.Rr.cacheTtlMs;if(!e||0>=e)return!1;const t=this.Fd(Cr);return typeof t!="number"||Date.now()-t>e}qd(){return!!this.Cd()&&(this.ud||this.sd||(this.ud=!0,this.$.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}jd(){const e=this.Rr.evaluationContexts;return e?.length?e.filter(t=>{const r=t&&typeof t=="string"&&t.trim().length>0;return r||this.$.error("Invalid evaluation context found:",t,"Expected non-empty string"),r}):[]}Bd(){const e=this.Rr.flagKeys;if(!O(e))return e.filter(t=>{const r=t&&typeof t=="string"&&t.trim().length>0;return r||this.$.error("Invalid flag key found:",t,"Expected non-empty string"),r})}initialize(){var e,t;const r=this.Rr,n=(e=(t=r.bootstrap)===null||t===void 0?void 0:t.featureFlags)!==null&&e!==void 0?e:{};if(Object.keys(n).length){var i,s;const o=(i=(s=r.bootstrap)===null||s===void 0?void 0:s.featureFlagPayloads)!==null&&i!==void 0?i:{},a=Object.keys(n).filter(l=>!O(n[l])).reduce((l,u)=>(l[u]=n[u],l),{}),c=Object.keys(o).filter(l=>a[l]).reduce((l,u)=>(l[u]=o[u],l),{});return this.Hd({featureFlags:a,featureFlagPayloads:c},void 0,{persist:!1})}}updateFlags(e,t,r){var n,i;const s=r?.merge&&(n=this.Fd("$enabled_feature_flags"))!==null&&n!==void 0?n:{},o=r?.merge&&(i=this.Fd("$feature_flag_payloads"))!==null&&i!==void 0?i:{},a=b(b({},s),e),c=b(b({},o),t),l={};for(const[u,h]of Object.entries(a))l[u]={key:u,enabled:vh(h),variant:gh(h),reason:void 0,metadata:O(c?.[u])?void 0:{id:0,version:void 0,description:void 0,payload:c[u]}};this.Hd({flags:l})}get hasLoadedFlags(){return this.nd}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){const e=this.Fd(ln),t=this.Fd(qt),r=this.Fd(en);if(!r&&!t)return e||{};const n=Le({},e||{}),i=[...new Set([...Object.keys(r||{}),...Object.keys(t||{})])];for(const a of i){var s;const c=n[a],l=t?.[a],u=O(l)?(s=c?.enabled)!==null&&s!==void 0&&s:!!l,h=O(l)?c?.variant:typeof l=="string"?l:void 0,d=r?.[a],p=b(b({},c),{},{enabled:u,variant:u?h??c?.variant:void 0});var o;u!==c?.enabled&&(p.original_enabled=c?.enabled),h!==c?.variant&&(p.original_variant=c?.variant),d&&(p.metadata=b(b({},c?.metadata),{},{payload:d,original_payload:c==null||(o=c.metadata)===null||o===void 0?void 0:o.payload})),n[a]=p}return this.Xc||(this.$.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:r,finalDetails:n}),this.Xc=!0),n}getAllFeatureFlags(){const e=this.getFlagVariants(),t=this.getFlagPayloads();return Object.keys(e).map(r=>{const n=e[r];return{key:r,enabled:vh(n),variant:gh(n),payload:fh(t[r])}})}getFlagVariants(){const e=this.Fd(Mt),t=this.Fd(qt);if(!t)return e||{};const r=Le({},e||{}),n=Object.keys(t);for(let i=0;n.length>i;i++)r[n[i]]=t[n[i]];return this.Xc||(this.$.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:t,finalFlags:r}),this.Xc=!0),r}getFlagPayloads(){const e=this.Fd(wr),t=this.Fd(en);if(!t)return e||{};const r=Le({},e||{}),n=Object.keys(t);for(let i=0;n.length>i;i++)r[n[i]]=t[n[i]];return this.Xc||(this.$.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:t,finalPayloads:r}),this.Xc=!0),r}reloadFeatureFlags(){this.od||this.Rr.featureFlagsDisabled||this.vd()||(this.sd&&(this.ad=!0),this.zd||(this.ed.slice().forEach(e=>{try{e()}catch(t){this.$.error("Error while running feature flags reloading callback",t)}}),this.zd=setTimeout(()=>{this.Ud()},5)))}Ad(){clearTimeout(this.zd),this.zd=void 0}onReloading(e){return this.ed.push(e),()=>{this.ed=this.ed.filter(t=>t!==e)}}ensureFlagsLoaded(){this.nd||this.sd||this.zd||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.od=e}resetFlagCallReported(){this.Lt(kr)}Ud(e){this.Ad();const t=this.wo;if(!t||this.Rr.remoteRequestsDisabled||this.vd())return;if(this.sd)return void(this.ad=!0);const r={token:t.projectToken,distinct_id:t.distinctId,groups:t.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:b(b(b({},t.initialPersonProperties),this.Fd("$stored_person_properties")||{}),{},{$lib:t.library.name,$lib_version:t.library.version}),group_properties:this.Fd(Er),timezone:Qm()};O(t.deviceId)||(r.$device_id=t.deviceId),(e!=null&&e.disableFlags||this.Rr.featureFlagsDisabled)&&(r.disable_flags=!0);const n=this.jd();n.length&&(r.evaluation_contexts=n);const i=this.Bd();O(i)||(r.flag_keys=i);const s=this.Rr.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.rd;this.sd=!0;const c=()=>{this.ad&&(this.ad=!1,this.Ud())},l=f=>{var v,m;const _=(v=f.json)!==null&&v!==void 0?v:{},w=f.statusCode!==200;if(this.sd=!1,a!==this.rd)return void c();if(this.Wd(f.statusCode),w||this.ad||(this.$anon_distinct_id=void 0),r.disable_flags&&!this.ad)return;this.ld=!w;const S=[];f.error?S.push(f.error instanceof Error&&f.error.name==="AbortError"?"timeout":f.error instanceof Error?wp:"unknown_error"):f.statusCode!==200&&S.push(`api_error_${f.statusCode}`),_.errorsWhileComputingFlags&&S.push("errors_while_computing_flags");const T=!!(!((m=_.quotaLimited)===null||m===void 0)&&m.includes("feature_flags"));T&&S.push("quota_limited"),this.At({[Qi]:S}),T?this.$.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):r.disable_flags||this.Hd(_,w,{partialResponse:s}),c()},u=f=>{this.sd=!1,a===this.rd&&(this.At({[Qi]:[wp]}),this.$.error("Feature flag request failed",f),this.Dd()&&this.Md(!0)),c()};let h=this.Rr.requestMaxRetries;const d=()=>h>0&&a===this.rd,p=()=>{if(a!==this.rd||!this.wo||this.Rr.remoteRequestsDisabled)return this.sd=!1,void c();try{t.sendRequest(o,{target:"flags",method:"POST",body:r,compression:this.Rr.compression,sentAt:"body",timeoutMs:this.Rr.requestTimeoutMs}).then(f=>{if((v=>tO.includes(v.statusCode)||(m=>m.statusCode===0&&m.error instanceof Error&&m.error.name==="AbortError")(v))(f)&&d())return h--,void setTimeout(p,500);l(f)}).catch(u)}catch(f){u(f)}};p()}vd(){return Vm(this.hd,3)}Wd(e){this.hd=Bm(e,this.hd,3,()=>this.$.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes."))}getFeatureFlag(e,t={}){var r;if(t.fresh&&!this.ld)return;if(!(this.nd||this.getFlags()&&this.getFlags().length>0))return void this.$.warn('getFeatureFlag for key "'+e+hc);if(this.qd())return;const n=this.getFeatureFlagResult(e,t);return(r=n?.variant)!==null&&r!==void 0?r:n?.enabled}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){const t=this.getFeatureFlagResult(e,{send_event:!1});return t?.payload}getFeatureFlagResult(e,t={}){if(t.fresh&&!this.ld)return;if(!(this.nd||this.getFlags()&&this.getFlags().length>0))return void this.$.warn('getFeatureFlagResult for key "'+e+hc);if(this.qd())return;const r=this.getFlagVariants(),n=e in r,i=r[e],s=this.getFlagPayloads()[e],o=String(i),a=this.Fd("$feature_flag_request_id")||void 0,c=this.Fd("$feature_flag_evaluated_at")||void 0;let l,u=this.Fd("$flag_call_reported")||{};if(this.Rr.deduplicateCallsPerSession){var h;const q=(h=this.wo)===null||h===void 0?void 0:h.session.sessionId,X=this.Fd(Ti);q&&q!==X&&(u={},l=q)}if(t.send_event||!("send_event"in t))if(e in u&&u[e].includes(o))l&&this.At({[kr]:u,[Ti]:l});else{var d,p,f,v,m,_,w,S,T,C,$,M;ce(u[e])?u[e].push(o):u[e]=[o],this.At(b({[kr]:u},l?{[Ti]:l}:{}));const q=this.getFeatureFlagDetails(e),X=[...(d=this.Fd("$feature_flag_errors"))!==null&&d!==void 0?d:[]];O(i)&&X.push("flag_missing");const ee={$feature_flag:e,$feature_flag_response:i,$feature_flag_payload:s??null,$feature_flag_request_id:a,$feature_flag_evaluated_at:c,$feature_flag_bootstrapped_response:(p=(f=this.Rr.bootstrap)===null||f===void 0||(f=f.featureFlags)===null||f===void 0?void 0:f[e])!==null&&p!==void 0?p:null,$feature_flag_bootstrapped_payload:(v=(m=this.Rr.bootstrap)===null||m===void 0||(m=m.featureFlagPayloads)===null||m===void 0?void 0:m[e])!==null&&v!==void 0?v:null,$used_bootstrap_value:!this.ld};O(q==null||(_=q.metadata)===null||_===void 0?void 0:_.has_experiment)||(ee.$feature_flag_has_experiment=q.metadata.has_experiment),O(q==null||(w=q.metadata)===null||w===void 0?void 0:w.version)||(ee.$feature_flag_version=q.metadata.version);const k=(S=q==null||(T=q.reason)===null||T===void 0?void 0:T.description)!==null&&S!==void 0?S:q==null||(C=q.reason)===null||C===void 0?void 0:C.code;var L;k&&(ee.$feature_flag_reason=k),q!=null&&($=q.metadata)!==null&&$!==void 0&&$.id&&(ee.$feature_flag_id=q.metadata.id),O(q?.original_variant)&&O(q?.original_enabled)||(ee.$feature_flag_original_response=O(q.original_variant)?q.original_enabled:q.original_variant),q!=null&&(M=q.metadata)!==null&&M!==void 0&&M.original_payload&&(ee.$feature_flag_original_payload=q==null||(L=q.metadata)===null||L===void 0?void 0:L.original_payload),X.length&&(ee.$feature_flag_error=X.join(",")),this.Vd(ee)}else l&&this.At({[kr]:u,[Ti]:l});return n?{key:e,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:fh(s)}:void 0}Vd(e){try{var t;(t=this.wo)===null||t===void 0||t.capture("$feature_flag_called",e)}catch(r){this.$.error("Failed to capture feature flag call",r)}}getRemoteConfigPayload(e,t){this.Gd(e,t)}Gd(e,t){var r=this;return Ue(function*(){const n=r.wo;if(!n)return;const i={distinct_id:n.distinctId,token:n.projectToken,person_properties:{$lib:n.library.name,$lib_version:n.library.version}},s=r.jd();s.length&&(i.evaluation_contexts=s);const o=r.Bd();let a;O(o)||(i.flag_keys=o);try{var c;const l=(c=(yield n.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:i,compression:r.Rr.compression,sentAt:"body",timeoutMs:r.Rr.requestTimeoutMs})).json)===null||c===void 0?void 0:c.featureFlagPayloads;a=l?.[e]||void 0}catch(l){r.$.error("Remote config feature flag request failed",l);return}try{t(a)}catch(l){r.$.error("Remote config feature flag callback failed",l)}})()}isFeatureEnabled(e,t={}){if(t.fresh&&!this.ld)return t.defaultValue;if(!(this.nd||this.getFlags()&&this.getFlags().length>0))return this.$.warn('isFeatureEnabled for key "'+e+hc),t.defaultValue;const r=this.getFeatureFlag(e,t);return O(r)?t.defaultValue:!!r}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(t=>t!==e)}receivedFeatureFlags(e,t,r){this.Hd(e,t,r)}Hd(e,t,r){if(!this.wo)return;this.nd=!0;const n=((i,s={},o={},a={},c,l=yp)=>{const u=((S,T)=>{const C=S.flags;if(C){const $=Object.fromEntries(Object.keys(C).map(L=>{var q;return[L,(q=C[L].variant)!==null&&q!==void 0?q:C[L].enabled]})),M=Object.fromEntries(Object.keys(C).filter(L=>C[L].enabled).filter(L=>{var q;return!O((q=C[L].metadata)===null||q===void 0?void 0:q.payload)}).map(L=>{var q;return[L,(q=C[L].metadata)===null||q===void 0?void 0:q.payload]}));return b(b({},S),{},{featureFlags:$,featureFlagPayloads:M})}return S.featureFlags&&T.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),S})(i,l),h=u.flags,d=u.featureFlags,p=u.featureFlagPayloads;if(!d)return;const f=i.requestId,v=i.evaluatedAt;if(ce(d)){l.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");const S={};if(d)for(let T=0;d.length>T;T++)S[d[T]]=!0;return{[ir]:d,[Mt]:S,[Di]:!1}}let m=d,_=p,w=h;if(c?.partialResponse){const S=Object.keys(m),T=_||{};m=b(b({},s),m),_=b(b({},o),T),S.forEach(C=>{C in T||_==null||delete _[C]}),w=b(b({},a),w)}else if(i.errorsWhileComputingFlags)if(h){const S=new Set(Object.keys(h).filter(C=>{var $;return!(!(($=h[C])===null||$===void 0)&&$.failed)}));m=b(b({},s),Object.fromEntries(Object.entries(m).filter(([C])=>S.has(C))));const T=Object.fromEntries(Object.entries(_||{}).filter(([C])=>S.has(C)));_=b(b({},o),T),S.forEach(C=>{C in T||_==null||delete _[C]}),w=b(b({},a),Object.fromEntries(Object.entries(w||{}).filter(([C])=>S.has(C))))}else m=b(b({},s),m),_=b(b({},o),_),w=b(b({},a),w);return b(b({[ir]:Object.keys(Ep(m)),[Mt]:m||{},[wr]:_||{},[ln]:w||{},[Di]:i.minimalFlagCalledEvents===!0},f?{[un]:f}:{}),v?{[Cr]:v}:{})})(e,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),r,this.$);if(n)if(r?.persist===!1){const i=!O(this.wo.kv.get(Mt));this.Od=n,i||this.At(n)}else this.Td(),this.Nd(n,e,!!r?.partialResponse),this.At(n);else t&&this.Dd();t||(this.ud=!1),this.Md(t)}override(e,t=!1){this.$.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:t})}overrideFeatureFlags(e){this.Zd(e)}Zd(e){if(this.wo){if(e===!1)return this.Lt([qt,en]),this.Md(),void Zr.info("All overrides cleared");if(ce(e))return this.At({[qt]:Sp(e)}),this.Md(),void Zr.info("Flag overrides set",{flags:e});if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var t;const r=e;this.Xc=!!((t=r.suppressWarning)!==null&&t!==void 0&&t);const n={},i=r.flags,s=r.payloads;i&&(n[qt]=ce(i)?Sp(i):i),s&&(n[en]=s),Object.keys(n).length&&this.At(n),i===!1&&s===!1?this.Lt([qt,en]):i===!1?this.Lt(qt):s===!1&&this.Lt(en),this.Md(),i===!1?Zr.info("Flag overrides cleared"):i&&Zr.info("Flag overrides set",{flags:i}),s===!1?Zr.info("Payload overrides cleared"):s&&Zr.info("Payload overrides set",{payloads:s});return}if(e&&typeof e=="object")return this.At({[qt]:e}),this.Md(),void Zr.info("Flag overrides set",{flags:e});this.$.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:e})}else this.$.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.nd){const{flags:t,flagVariants:r}=this.Qd();try{e(t,r)}catch(n){this.$.error("Error while running feature flags callback",n)}}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,r){var n;const i=(this.Fd("$early_access_features")||[]).find(l=>l.flagKey===e),s={[`$feature_enrollment/${e}`]:t},o={$feature_flag:e,$feature_enrollment:t,$set:s};i&&(o.$early_access_feature_name=i.name),r&&(o.$feature_enrollment_stage=r);const a=b(b({},this.getFlagVariants()),{},{[e]:t});(n=this._instance)===null||n===void 0||(n=n.persistence)===null||n===void 0||n.markCrossTabFeatureFlagChanges({$active_feature_flags:[e],$enabled_feature_flags:[e],$stored_person_properties:Object.keys(s)}),this.At({[ir]:Object.keys(Ep(a)),[Mt]:a,[Sr]:b(b({},this.Fd("$stored_person_properties")||{}),s)}),this.Md();try{var c;(c=this.wo)===null||c===void 0||c.capture("$feature_enrollment_update",o)}catch(l){this.$.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(e,t=!1,r){const n=this.Fd(cl);!n||t?this.Jd(e,r):e(n)}Jd(e,t){var r=this;return Ue(function*(){const n=r.wo;if(!n)return;const i=t?`&${t.map(o=>`stage=${o}`).join("&")}`:"";let s;try{const o=yield n.sendRequest(`/api/early_access_features/?token=${n.projectToken}${i}`,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;s=o.json.earlyAccessFeatures,r.At({[cl]:s})}catch(o){r.$.error("Early access feature request failed",o);return}try{e(s)}catch(o){r.$.error("Early access feature callback failed",o)}})()}Qd(){const e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter(r=>t[r]),flagVariants:Object.keys(t).filter(r=>t[r]).reduce((r,n)=>(r[n]=t[n],r),{})}}Md(e){this.Id();const{flags:t,flagVariants:r}=this.Qd();this.featureFlagEventHandlers.forEach(n=>{try{n(t,r,{errorsLoading:e})}catch(i){this.$.error("Error while running feature flags callback",i)}})}setPersonPropertiesForFlags(e,t=!0){this.Kd(e,t)}Kd(e,t=!0){const r=this.Fd("$stored_person_properties")||{},n=e?.$set||(e?.$set_once?{}:e),i=e?.$set_once,s={};if(i)for(const o in i)({}).hasOwnProperty.call(i,o)&&(o in r||(s[o]=i[o]));this.At({[Sr]:b(b(b({},r),s),n)}),t&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(e,t=!0){const r=b({},this.Fd("$stored_person_properties")||{});e.forEach(n=>{delete r[n]}),this.At({[Sr]:r}),t&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(e=!0){this.Lt(Sr),e&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(e,t=!0){const r=this.Fd("$stored_group_properties")||{},n=b({},r);for(const i of Object.keys(e))n[i]=b(b({},r[i]),e[i]);this.At({[Er]:n}),t&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){const t=this.Fd("$stored_group_properties")||{};this.At({[Er]:b(b({},t),{},{[e]:{}})})}else this.Lt(Er)}reset(){this.rd++,this.ad=!1,this.Yc={},this.td={},this.Od=void 0,this.nd=!1,this.od=!1,this.ld=!1,this.$anon_distinct_id=void 0,this.Ad(),this.Xc=!1,this.hd=0}}},hO={sessionRecording:class{get Rr(){return this._instance.config}get Ml(){return this._instance.persistence}get started(){var e;return!!(!((e=this.Xd)===null||e===void 0)&&e.isStarted)}get status(){var e,t;return this.Yd==="awaiting_config"||this.Yd==="missing_config"?this.Yd:(e=(t=this.Xd)===null||t===void 0?void 0:t.status)!==null&&e!==void 0?e:this.Yd}constructor(e){if(this._instance=e,this._forceAllowLocalhostNetworkCapture=!1,this.Yd=lc,this.tv=void 0,this.ev=!1,this.Xe=(()=>{var t,r;if(!N?.visibilityState||N.visibilityState==="visible")return!0;const n=A==null||(t=A.performance)===null||t===void 0||(r=t.getEntriesByType)===null||r===void 0?void 0:r.call(t,"visibility-state");return!n?.length||n.some(i=>i.name==="visible")})(),this.ln=()=>{var t,r;N?.visibilityState==="visible"&&(this.Xe=!0,(t=this.Xd)===null||t===void 0||(r=t.setDocumentWasEverVisible)===null||r===void 0||r.call(t,!0))},!this._instance.sessionManager)throw Xt.error("started without valid sessionManager"),new Error("[SessionRecording] started without valid sessionManager. This is a bug.");if(this.Rr.cookieless_mode==="always")throw new Error('[SessionRecording] cannot be used with cookieless_mode="always"');N!=null&&N.addEventListener&&Ie(N,"visibilitychange",this.ln)}initialize(){this.startIfEnabledOrStop()}dispose({discardBufferedEvents:e=!1}={}){var t;this.ev=!0,N==null||(t=N.removeEventListener)===null||t===void 0||t.call(N,"visibilitychange",this.ln),e?this.iv(!0):this.stopRecording()}get nv(){var e;const t=!!(!((e=this._instance.get_property("$session_recording_remote_config"))===null||e===void 0)&&e.enabled),r=!this.Rr.disable_session_recording,n=this.Rr.disable_session_recording||this._instance.consent.isOptedOut();return A&&t&&r&&!n}startIfEnabledOrStop(e){var t;if(this.ev||this.nv&&(!((t=this.Xd)===null||t===void 0)&&t.isStarted))return;const r=!O(Object.assign)&&!O(Array.from);this.nv&&r?(this.sv(e),Xt.info("starting")):(this.Yd=lc,this.stopRecording())}sv(e){var t,r;if(this.nv)if(this.Yd!=="awaiting_config"&&this.Yd!=="missing_config"&&(this.Yd=pp),(te==null||(t=te.__PosthogExtensions__)===null||t===void 0||(t=t.rrweb)===null||t===void 0?void 0:t.record)&&((r=te.__PosthogExtensions__)===null||r===void 0?void 0:r.initSessionRecording))this.rv(e);else{var n,i;const s=this._instance.sessionManager;(n=te.__PosthogExtensions__)===null||n===void 0||(i=n.loadExternalDependency)===null||i===void 0||i.call(n,this._instance,this.ov,o=>{if(!this.ev&&this.nv&&this._instance.sessionManager===s)return o?(this._instance.register_for_session({$sdk_debug_recording_script_not_loaded:!0}),Xt.error("could not load recorder",o)):void this.rv(e);this.Yd="disabled"})}}stopRecording(){var e,t;(e=this.tv)===null||e===void 0||e.call(this),this.tv=void 0,(t=this.Xd)===null||t===void 0||t.stop()}iv(e=!1){var t,r;(t=this.tv)===null||t===void 0||t.call(this),this.tv=void 0,(r=this.Xd)===null||r===void 0||r.discard({discardProducerEvents:e})}av(){var e,t;(e=this.Ml)===null||e===void 0||e.unregister("$session_is_sampled"),(t=this.Ml)===null||t===void 0||t.unregister("$replay_sample_rate")}lv(e,t){if(ge(e))return null;const r=We(e)?e:parseFloat(e);return typeof(n=r)!="number"||!Number.isFinite(n)||0>n||n>1?(Xt.warn(`${t} must be between 0 and 1. Ignoring invalid value:`,e),null):r;var n}uv(e){if(this.Ml){var t,r;const n=this.Ml,i=()=>{var s;const o=e.sessionRecording===!1?void 0:e.sessionRecording,a=this.lv((s=this.Rr.session_recording)===null||s===void 0?void 0:s.sampleRate,"session_recording.sampleRate"),c=this.lv(o?.sampleRate,"remote config sampleRate"),l=a??c;ge(l)&&this.av();const u=o?.minimumDurationMilliseconds;n.register({[Li]:b(b({cache_timestamp:Date.now(),enabled:!!o},o),{},{networkPayloadCapture:b({capturePerformance:e.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:l,minimumDurationMilliseconds:O(u)?null:u,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};i(),(t=this.tv)===null||t===void 0||t.call(this),this.tv=(r=this._instance.sessionManager)===null||r===void 0?void 0:r.onSessionId(i)}}onRemoteConfig(e){const t=e.ok?e.config:void 0;t&&"sessionRecording"in t?t.sessionRecording===!1?(this.uv(t),this.iv()):(this.uv(t),this.startIfEnabledOrStop()):(this.Yd==="awaiting_config"&&(this.Yd="missing_config",this._instance.register_for_session({[Tm]:!0}),Xt.warn("config refresh failed, recording will not start until page reload")),this.startIfEnabledOrStop())}log(e,t="log"){var r;!((r=this.Xd)===null||r===void 0)&&r.log?this.Xd.log(e,t):Xt.warn("log called before recorder was ready")}get ov(){var e,t;const r=(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0?void 0:e.get_property(Li);return(r==null||(t=r.scriptConfig)===null||t===void 0?void 0:t.script)||"lazy-recorder"}hv(){const e=this._instance.get_property(Li);if(!e)return!1;let t;try{t=typeof e=="object"?e:JSON.parse(e)}catch(r){return Xt.warn("persisted remote config for session recording is invalid and will be ignored",r),!1}return!ge(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}rv(e){var t,r,n;if(!this.ev&&this.nv&&this._instance.sessionManager){if(!(!((t=te.__PosthogExtensions__)===null||t===void 0)&&t.initSessionRecording))return Xt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[Im]:!0});var i;if(this.Xd||(this.Xd=(i=te.__PosthogExtensions__)===null||i===void 0?void 0:i.initSessionRecording(this._instance,this.Xe),this.Xd._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.hv()){if(this.Yd==="missing_config"||this.Yd==="awaiting_config")return;this.Yd="awaiting_config",Xt.info("persisted remote config is stale, requesting fresh config before starting"),new t_(this._instance).load();return}this.Yd=pp,(r=(n=this.Xd).setDocumentWasEverVisible)===null||r===void 0||r.call(n,this.Xe),this.Xd.start(e)}else this.Yd=lc}onRRwebEmit(e){var t,r;(t=this.Xd)===null||t===void 0||(r=t.onRRwebEmit)===null||r===void 0||r.call(t,e)}overrideLinkedFlag(){var e,t;this.Xd||(t=this.Ml)===null||t===void 0||t.register({$replay_override_linked_flag:!0}),(e=this.Xd)===null||e===void 0||e.overrideLinkedFlag()}overrideSampling(){var e,t;this.Xd||(t=this.Ml)===null||t===void 0||t.register({$replay_override_sampling:!0}),(e=this.Xd)===null||e===void 0||e.overrideSampling()}overrideTrigger(e){var t,r;this.Xd||(r=this.Ml)===null||r===void 0||r.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(t=this.Xd)===null||t===void 0||t.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.Xd)===null||e===void 0?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,t){var r;return!!(!((r=this.Xd)===null||r===void 0)&&r.tryAddCustomEvent(e,t))}flushBeforeIdentityReset(){var e,t;(e=this.Xd)===null||e===void 0||(t=e.flushBeforeIdentityReset)===null||t===void 0||t.call(e)}}},pO={autocapture:class extends FP{constructor(e){super(new qP(e)),this.instance=e}},historyAutocapture:class{constructor(e){this._instance=e,this.dv=this.vv()}initialize(){this.startIfEnabled()}get isEnabled(){const e=this.fv();return!!(e.path||e.search||this.pv(e))}startIfEnabled(){this.isEnabled&&(j.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}startIfEnabledOrStop(){this.stop(),this.dv=this.vv(),this.startIfEnabled()}stop(){this.gv&&this.gv(),this.gv=void 0,this.mv&&this.mv(),this.mv=void 0,j.info("History API monitoring stopped")}monitorHistoryChanges(){A&&A.history&&(this.yv("pushState"),this.yv("replaceState"),this.bv(),this.pv()&&this._v())}yv(e){var t;if(!A||!((t=A.history[e])===null||t===void 0)&&t.__posthog_wrapped__)return;const r=this;ss(A.history,e,n=>function(i,s,o){n.call(this,i,s,o),r.wv(e)})}vv(){const e=A?.location;if(e?.pathname)return{pathname:e.pathname,search:e.search,hash:e.hash}}fv(){const e=this._instance.config.capture_pageview;return e==="history_change"?{path:!0}:be(e)?e:{}}pv(e=this.fv()){return!!e.hash&&!this._instance.config.disable_capture_url_hashes}Sv(e){const t=this.fv(),r=this.dv;return!(!r||!(t.path&&e.pathname!==r.pathname||t.search&&e.search!==r.search||this.pv(t)&&e.hash!==r.hash))}wv(e){try{const t=this.vv();if(!t)return;this.Sv(t)&&this._instance.capture(Tu,{navigation_type:e}),this.dv=t}catch(t){j.error(`Error capturing ${e} pageview`,t)}}bv(){if(this.gv)return;const e=()=>{this.wv("popstate")};Ie(A,"popstate",e),this.gv=()=>{A&&A.removeEventListener("popstate",e)}}_v(){if(this.mv)return;const e=()=>{this.wv("hashchange")};Ie(A,"hashchange",e),this.mv=()=>{A&&A.removeEventListener("hashchange",e)}}},heatmaps:class{get Rr(){return this.instance.config}constructor(e){var t;this.xv=!1,this.xo=!1,this.Cv=null,this.instance=e,this.xv=!!(!((t=this.instance.persistence)===null||t===void 0)&&t.props[il]),this.rageclicks=new k_(e.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){let e=5e3;return be(this.Rr.capture_heatmaps)&&this.Rr.capture_heatmaps.flush_interval_milliseconds&&(e=this.Rr.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return ge(this.Rr.capture_heatmaps)?ge(this.Rr.enable_heatmaps)?this.xv:this.Rr.enable_heatmaps:this.Rr.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.xo)return;BP.info("starting..."),this.$v(),this.ln()}else{var e;clearInterval((e=this.Cv)!==null&&e!==void 0?e:void 0),this.Tv(),this.getAndClearBuffer()}}onRemoteConfig(e){if(!e.ok)return;const t=e.config;if(!("heatmaps"in t))return;const r=!!t.heatmaps;this.instance.persistence&&this.instance.persistence.register({[il]:r}),this.xv=r,this.startIfEnabled()}getAndClearBuffer(){const e=this.Rt;return this.Rt=void 0,e}Iv(e){uc(e.originalEvent)&&this.Tr(e.originalEvent,"deadclick")}ln(){this.Cv&&clearInterval(this.Cv),this.Cv=N?.visibilityState==="visible"?setInterval(this.bl.bind(this),this.flushIntervalMilliseconds):null}$v(){A&&N&&(this.Mv=this.bl.bind(this),Ie(A,ko,this.Mv),this.Ev=e=>this.Tr(e||A?.event),Ie(N,"click",this.Ev,{capture:!0}),this.Pv=e=>this.Rv(e||A?.event),Ie(N,"mousemove",this.Pv,{capture:!0}),this.Av=new qh(this.instance,W$,this.Iv.bind(this)),this.Av.startIfEnabledOrStop(),this.Fv=this.ln.bind(this),Ie(N,es,this.Fv),this.xo=!0)}Tv(){var e;A&&N&&(this.Mv&&A.removeEventListener(ko,this.Mv),this.Ev&&N.removeEventListener("click",this.Ev,{capture:!0}),this.Pv&&N.removeEventListener("mousemove",this.Pv,{capture:!0}),this.Fv&&N.removeEventListener(es,this.Fv),clearTimeout(this.Ov),(e=this.Av)===null||e===void 0||e.stop(),this.xo=!1)}Dv(e,t){const r=this.instance.scrollManager.scrollY(),n=this.instance.scrollManager.scrollX(),i=this.instance.scrollManager.scrollElement(),s=(function(o,a,c){let l=o;for(;l&&Zt(l)&&!ct(l,"body");){if(l===c)return!1;let p;try{var u,h,d;p=(u=(h=(d=l.ownerDocument)===null||d===void 0?void 0:d.defaultView)!==null&&h!==void 0?h:A)===null||u===void 0?void 0:u.getComputedStyle(l).position}catch{return!1}if(ue(a,p))return!0;l=Nm(l)}return!1})(zi(e),["fixed","sticky"],i);return{x:e.clientX+(s?0:n),y:e.clientY+(s?0:r),target_fixed:s,type:t}}Tr(e,t="click"){var r;if(Ph(e.target)||!uc(e))return;const n=this.Dv(e,t);(r=this.rageclicks)!==null&&r!==void 0&&r.isRageClick(e.clientX,e.clientY,new Date().getTime())&&Um(zi(e),this.instance.config.rageclick)&&this.Zs(b(b({},n),{},{type:"rageclick"})),this.Zs(n)}Rv(e){!Ph(e.target)&&uc(e)&&(clearTimeout(this.Ov),this.Ov=setTimeout(()=>{this.Zs(this.Dv(e,"mousemove"))},500))}Zs(e){if(!A)return;const t=this.Rr.disable_capture_url_hashes?Ur(A.location.href):A.location.href,r=this.Rr.custom_personal_data_properties,n=this.Rr.mask_personal_data_properties?[...Qn,...r||[]]:[],i=ns(t,n,is);this.Rt=this.Rt||{},this.Rt[i]||(this.Rt[i]=[]),this.Rt[i].push(e)}bl(){this.Rt&&!_t(this.Rt)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:qh,webVitalsAutocapture:class{constructor(e){var t;this._instance=e,this.xv=!1,this.xo=!1,this.Rt={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.Lv=()=>{clearTimeout(this.Nv),this.Nv=void 0,this.Rt.metrics.length!==0&&(this._instance.capture("$web_vitals",b({$current_url:this.Rt.url},this.Rt.metrics.reduce((r,n)=>b(b({},r),{},{[`$web_vitals_${n.name}_event`]:b({},n),[`$web_vitals_${n.name}_value`]:n.value}),{}))),this.Rt={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.qv=r=>{var n;if(this.Rt=this.Rt||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},ge(r?.name)||ge(r?.value))return void Wr.error("Invalid metric received",r);const i=typeof r.navigationURL=="string"?r.navigationURL:void 0,s=this.jv(i);if(O(s))return;const o=We(r.navigationId)||typeof r.navigationId=="string"?`navigation:${r.navigationId}`:`url:${s}`;if(this.Bv&&r.value>=this.Bv)return void Wr.error("Ignoring metric with value >= "+this.Bv,r);this.Rt.navigationKey!==o&&(this.Lv(),this.Nv=setTimeout(this.Lv,this.flushToCaptureTimeoutMs)),O(this.Rt.navigationKey)&&(this.Rt.navigationKey=o,this.Rt.url=s),this.Rt.firstMetricTimestamp=O(this.Rt.firstMetricTimestamp)?Date.now():this.Rt.firstMetricTimestamp;const a=(n=this._instance.sessionManager)===null||n===void 0?void 0:n.checkAndGetSessionAndWindowId(!0),c=b(b(b({},r),i?{navigationURL:s}:{}),{},{$current_url:s,timestamp:Date.now()});if(delete c.entries,be(r.attribution)&&this.attributionMetrics.indexOf(r.name)>-1){const l={};for(const u of VP){const h=u==="url"&&typeof r.attribution[u]=="string"?this.jv(r.attribution[u]):r.attribution[u];O(h)||(l[u]=h)}c.attribution=l}else delete c.attribution;O(a)||(c.$session_id=a.sessionId,c.$window_id=a.windowId),this.Rt.metrics.push(c),this.Rt.metrics.length===this.allowedMetrics.length&&this.Lv()},this.Hv=()=>{if(this.xo)return;let r,n,i,s,o=!1;const a=te.__PosthogExtensions__,c=a?.postHogWebVitalsCallbacksByFlavor,l=c?.[this.zv]||(this.zv==="web-vitals"&&O(c)?a?.postHogWebVitalsCallbacks:void 0);if(!O(l)){const d=l.withoutAttribution,p=this.attributionMetrics;o=!O(d),r=p.indexOf("LCP")>-1?l.onLCP:d?.onLCP||l.onLCP,n=p.indexOf("CLS")>-1?l.onCLS:d?.onCLS||l.onCLS,i=p.indexOf("FCP")>-1?l.onFCP:d?.onFCP||l.onFCP,s=p.indexOf("INP")>-1?l.onINP:d?.onINP||l.onINP}if(!(r&&n&&i&&s))return void Wr.error("web vitals callbacks not loaded - not starting");const u={reportSoftNavs:this.useSoftNavs},h=o&&this.attributionMetrics.indexOf("INP")>-1?b(b({},u),{},{includeProcessedEventEntries:!1}):u;this.allowedMetrics.indexOf("LCP")>-1&&r(this.qv.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&n(this.qv.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&i(this.qv.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&s(this.qv.bind(this),h),this.xo=!0},this.xv=!!(!((t=this._instance.persistence)===null||t===void 0)&&t.props[al]),this.startIfEnabled()}get Uv(){return this._instance.config.capture_performance}get allowedMetrics(){var e,t;const r=be(this.Uv)?(e=this.Uv)===null||e===void 0?void 0:e.web_vitals_allowed_metrics:void 0;return ge(r)?((t=this._instance.persistence)===null||t===void 0?void 0:t.props.$web_vitals_allowed_metrics)||hp:r}get flushToCaptureTimeoutMs(){return(be(this.Uv)?this.Uv.web_vitals_delayed_flush_ms:void 0)||5e3}get attributionMetrics(){const e=be(this.Uv)?this.Uv.web_vitals_attribution:void 0;return vt(e)?e?hp:[]:ce(e)?e:HP}get useAttribution(){return this.attributionMetrics.length>0}get useSoftNavs(){const e=be(this.Uv)?this.Uv.__preview_web_vitals_soft_navs:void 0;return e!=null&&e}get Bv(){const e=be(this.Uv)&&We(this.Uv.__web_vitals_max_value)?this.Uv.__web_vitals_max_value:dp;return e>0&&6e4>=e?dp:e}get isEnabled(){const e=je?.protocol;if(e!=="http:"&&e!=="https:")return Wr.info("Web Vitals are disabled on non-http/https protocols"),!1;const t=be(this.Uv)?this.Uv.web_vitals:vt(this.Uv)?this.Uv:void 0;return vt(t)?t:this.xv}startIfEnabled(){this.isEnabled&&!this.xo&&(Wr.info("enabled, starting..."),this.zo(this.Hv))}onRemoteConfig(e){if(!e.ok)return;const t=e.config;if(!("capturePerformance"in t))return;const r=be(t.capturePerformance)&&!!t.capturePerformance.web_vitals,n=be(t.capturePerformance)?t.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[al]:r}),this._instance.persistence.register({[gm]:n})),this.xv=r,this.startIfEnabled()}get zv(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}zo(e){var t;const r=te.__PosthogExtensions__,n=this.zv,i=r?.postHogWebVitalsCallbacksByFlavor;i?.[n]||n==="web-vitals"&&O(i)&&r?.postHogWebVitalsCallbacks?e():r==null||(t=r.loadExternalDependency)===null||t===void 0||t.call(r,this._instance,n,s=>{s?Wr.error("failed to load script",s):e()})}jv(e){const t=e||A?.location.href;if(!t)return void Wr.error("Could not determine current URL");const r=this._instance.config.disable_capture_url_hashes?Ur(t):t,n=this._instance.config.custom_personal_data_properties,i=this._instance.config.mask_personal_data_properties?[...Qn,...n||[]]:[];return ns(r,i,is)}}},fO={exceptionObserver:class{constructor(e){var t;this.Hv=()=>{var r;if(!A||!this.isEnabled||!(!((r=te.__PosthogExtensions__)===null||r===void 0)&&r.errorWrappingFunctions))return;const n=te.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,i=te.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=te.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Wv&&this.Rr.capture_unhandled_errors&&(this.Wv=n(this.captureException.bind(this))),!this.Vv&&this.Rr.capture_unhandled_rejections&&(this.Vv=i(this.captureException.bind(this))),!this.Gv&&this.Rr.capture_console_errors&&(this.Gv=s(this.captureException.bind(this)))}catch(o){ki.error("failed to start",o),this.Zv()}},this._instance=e,this.Qv=!!(!((t=this._instance.persistence)===null||t===void 0)&&t.props[sl]),this.wt=new oC(b(b({},(function(r={}){var n,i,s,o;return{refillRate:(n=(i=r.exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:r.__exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:1,bucketSize:(s=(o=r.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:r.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking)),{},{refillInterval:1e4,$:ki})),this.Rr=this.Jv(),this.startIfEnabledOrStop()}Jv(){const e=this._instance.config.capture_exceptions;let t={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return be(e)?t=b(b({},t),e):(O(e)?this.Qv:e)&&(t=b(b({},t),{},{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),t}get isEnabled(){return this.Rr.capture_console_errors||this.Rr.capture_unhandled_errors||this.Rr.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(ki.info("enabled"),this.Zv(),this.zo(this.Hv)):this.Zv()}zo(e){var t,r,n;!((t=te.__PosthogExtensions__)===null||t===void 0)&&t.errorWrappingFunctions?e():(r=te.__PosthogExtensions__)===null||r===void 0||(n=r.loadExternalDependency)===null||n===void 0||n.call(r,this._instance,"exception-autocapture",i=>{if(i)return ki.error("failed to load script",i);e()})}Zv(){var e,t,r;(e=this.Wv)===null||e===void 0||e.call(this),this.Wv=void 0,(t=this.Vv)===null||t===void 0||t.call(this),this.Vv=void 0,(r=this.Gv)===null||r===void 0||r.call(this),this.Gv=void 0}onRemoteConfig(e){if(!e.ok)return;const t=e.config;"autocaptureExceptions"in t&&(this.Qv=!!t.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[sl]:this.Qv}),this.Rr=this.Jv(),this.startIfEnabledOrStop())}onConfigChange(){this.Rr=this.Jv()}captureException(e){try{var t,r,n;const i=(t=e==null||(r=e.$exception_list)===null||r===void 0||(r=r[0])===null||r===void 0?void 0:r.type)!==null&&t!==void 0?t:"Exception";if(this.wt.consumeRateLimit(i))return void ki.info("Skipping exception capture because of client rate limiting.",{exception:i});(n=this._instance.exceptions)===null||n===void 0||n.sendExceptionEvent(e)}catch{}}},exceptions:class{constructor(e){var t,r;this.Kv=[],this.Xv=new _C([new xC,new jC,new LC,new MC,new FC,new UC,new NC,new qC],(function(n,...i){return(s,o=0)=>{const a=[],c=s.split(`
96
+ `),l=Math.min(c.length,o+1e3),u=[];for(let p=o;l>p;p++){const f=c[p];if(f.length>1024)continue;const v=ph.test(f)?f.replace(ph,"$1"):f;if(!v.match(/\S*Error: /)){for(const m of i){const _=m(v,n);if(_){a.push(_);const w=CC(a);if(w){for(let S=u.length-1;S>=0;S--){const T=u[S];if(w.start>=T.start+T.length)break;u.pop()}u.push(w)}break}}if(PC(a,u)>=50)break}}const h=[...u].sort((p,f)=>f.start-p.start),d=h[h.length-1];if(d){const p=Xg(a,d);a.splice(d.start-p,p);for(const f of h)f.start-=p}for(const p of h)$C(a,p);return u.some(p=>p.start===0&&a.length===p.length)&&(function(p){const f=p.map(m=>`${m.function}|${m.filename}|${m.lineno}|${m.colno}|${m.module}`);let v=0;for(let m=1;f.length>m;m++)OC(f,m,v)&&(v=m);p.push(...p.splice(0,v))})(a),(function(p){if(!p.length)return[];const f=Array.from(p);return f.reverse(),f.slice(0,50).map(v=>{return b(b({},v),{},{filename:v.filename||(m=f,m[m.length-1]||{}).filename,function:v.function||"?"});var m})})(a)}})("web:javascript",RC,TC)),this._instance=e,this.Kv=(t=(r=this._instance.persistence)===null||r===void 0?void 0:r.get_property("$error_tracking_suppression_rules"))!==null&&t!==void 0?t:[],this.Yv=yo(this.tf()),this.ef=new VC(this.Yv)}onConfigChange(){this.Yv=yo(this.tf()),this.ef.setConfig(this.Yv)}onRemoteConfig(e){var t,r,n;if(!e.ok)return;const i=e.config;if(!("errorTracking"in i))return;const s=(t=(r=i.errorTracking)===null||r===void 0?void 0:r.suppressionRules)!==null&&t!==void 0?t:[],o=(n=i.errorTracking)===null||n===void 0?void 0:n.captureExtensionExceptions;this.Kv=s,this._instance.persistence&&this._instance.persistence.register({[fm]:this.Kv,[ol]:o})}get if(){var e;const t=!!this._instance.get_property(ol),r=this._instance.config.error_tracking.captureExtensionExceptions;return(e=r??t)!==null&&e!==void 0&&e}buildProperties(e,t){return this.Xv.buildFromUnknown(e,{syntheticException:t?.syntheticException,mechanism:{handled:t?.handled}})}addExceptionStep(e,t){if(this.Yv.enabled)try{if(!ye(e)||e.trim().length===0)return void $t.warn("Ignoring exception step because message must be a non-empty string");const{sanitizedProperties:r,droppedKeys:n}=(function(i){if(!i)return{sanitizedProperties:{},droppedKeys:[]};const s=[];return{sanitizedProperties:Object.keys(i).reduce((o,a)=>HC.has(a)?(s.push(a),o):(o[a]=i[a],o),{}),droppedKeys:s}})(this.nf(t));n.length>0&&$t.warn("Ignoring reserved exception step fields",{droppedKeys:n}),this.ef.add(b({[mo]:e,[_o]:new Date().toISOString()},r))}catch(r){$t.error("Failed to add exception step. Ignoring breadcrumb.",r)}}sendExceptionEvent(e){try{const t=e.$exception_list;if(this.sf(t)){if(this.rf(t))return this.af("Exception dropped: matched a suppression rule"),void $t.info("Skipping exception capture because a suppression rule matched");if(!this.if&&this.lf(t))return this.af("Exception dropped: thrown by a browser extension"),void $t.info("Skipping exception capture because it was thrown by an extension");if(!this.if&&this.uf(t))return this.af("Exception dropped: thrown by an injected browser script"),void $t.info("Skipping exception capture because it was thrown by an injected browser script");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hf(t))return this.af("Exception dropped: thrown by the PostHog SDK"),void $t.info("Skipping exception capture because it was thrown by the PostHog SDK")}const r=this.Yv.enabled&&ge(e.$exception_steps)?this.cf(e):e,n=(function(){const i=globalThis._posthogReleaseId;return typeof i=="string"&&i.length>0?i:void 0})();n&&(r.$release_id=n);try{const i=this._instance.capture("$exception",r,{_noTruncate:!0,_batchKey:"exceptionEvent",fh:!0});return i&&this.ef.clear(),i}catch(i){kp(i)||$t.error("Failed to capture exception event. Dropping this exception.",i),this.ef.clear();return}}catch(t){kp(t)||$t.error("Failed to process exception event. Ignoring this exception.",t);return}}cf(e){try{const t=this.ef.getAttachable();return t.length===0?e:b(b({},e),{},{$exception_steps:t})}catch(t){return $t.error("Failed to read buffered exception steps. Capturing exception without steps.",t),e}}af(e){this.Yv.enabled&&this.ef.add({[mo]:e,[_o]:new Date().toISOString()})}nf(e){return be(e)?b({},e):{}}tf(){var e,t;return(e=(t=this._instance.config.error_tracking)===null||t===void 0?void 0:t.exception_steps)!==null&&e!==void 0?e:{}}rf(e){if(e.length===0)return!1;try{const t=e.reduce((r,{type:n,value:i})=>(ye(n)&&n.length>0&&r.$exception_types.push(n),ye(i)&&i.length>0&&r.$exception_values.push(i),r),{$exception_types:[],$exception_values:[]});return this.Kv.some(r=>{const n=r.values.map(i=>{const s=b_[i.operator],o=t[i.key];if(!s||!o)return!1;const a=ce(i.value)?i.value:[i.value];return a.length>0&&s(a,o)});return r.type==="OR"?n.some(Boolean):n.every(Boolean)})}catch(t){return $t.warn("Failed to evaluate suppression rules. Capturing the exception.",t),!1}}lf(e){const t=e.flatMap(n=>{var i,s;return(i=(s=n.stacktrace)===null||s===void 0?void 0:s.frames)!==null&&i!==void 0?i:[]}),r=t.filter(({filename:n})=>!!n&&nO.some(i=>n.startsWith(i)));return r.length!==0&&(!r.every(({filename:n})=>!!n&&n.startsWith(El))||e.some(({type:n,value:i})=>n==="NoResponse"||ye(i)&&rO.some(({value:s,exact:o})=>o?i===s:i.includes(s)))&&!t.some(({in_app:n,filename:i})=>n&&!i?.startsWith(El)))}uf(e){return e.some(({value:t})=>ye(t)&&iO.some(r=>t.includes(r)))}hf(e){if(e.length>0){var t,r,n,i;const s=(t=(r=e[0].stacktrace)===null||r===void 0?void 0:r.frames)!==null&&t!==void 0?t:[],o=s[s.length-1];return(n=o==null||(i=o.filename)===null||i===void 0?void 0:i.includes("posthog.com/static"))!==null&&n!==void 0&&n}return!1}sf(e){return!ge(e)&&ce(e)}}},vO=b({productTours:class{get Ml(){return this._instance.persistence}constructor(e){this.df=null,this.vf=null,this._instance=e}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(!e.ok)return;const t=e.config;if("productTours"in t){var r,n;if(this.Ml&&this.Ml.register({[Ru]:!!t.productTours}),!dc(this._instance))return!this.df&&ge((r=this.Ml)===null||r===void 0?void 0:r.props.ph_product_tours)||xs.info("product tours disabled; stopping and clearing cached tours"),(n=this.df)===null||n===void 0||n.stop(),this.df=null,void this.clearCache();this.loadIfEnabled()}}loadIfEnabled(){!this.df&&dc(this._instance)&&this.zo(()=>this.ff())}zo(e){var t,r,n;!((t=te.__PosthogExtensions__)===null||t===void 0)&&t.generateProductTours?e():(r=te.__PosthogExtensions__)===null||r===void 0||(n=r.loadExternalDependency)===null||n===void 0||n.call(r,this._instance,"product-tours",i=>{i?xs.error("Could not load product tours script",i):e()})}ff(){var e;!this.df&&(e=te.__PosthogExtensions__)!==null&&e!==void 0&&e.generateProductTours&&(this.df=te.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t=!1){if(ce(this.vf)&&!t)return void e(this.vf,{isLoaded:!0});const r=this.Ml;if(r){const n=r.props[ul];if(ce(n)&&!t)return this.vf=n,void e(n,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api",`/api/product_tours/?token=${this._instance.config.token}`),method:"GET",timestampMode:"query",callback:n=>{if(!dc(this._instance))return void e([],{isLoaded:!0});const i=n.statusCode;if(i!==200||!n.json){const o=`Product Tours API could not be loaded, status: ${i}`;i===0?n.error||xs.warn(o):xs.error(o),e([],{isLoaded:!1,error:o});return}const s=ce(n.json.product_tours)?n.json.product_tours:[];this.vf=s,r&&r.register({[ul]:s}),e(s,{isLoaded:!0})}})}getActiveProductTours(e){ge(this.df)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this.df.getActiveProductTours(e)}showProductTour(e){var t;(t=this.df)===null||t===void 0||t.showTourById(e)}previewTour(e){this.df?this.df.previewTour(e):this.zo(()=>{var t;this.ff(),(t=this.df)===null||t===void 0||t.previewTour(e)})}dismissProductTour(){var e;(e=this.df)===null||e===void 0||e.dismissTour("user_clicked_skip")}nextStep(){var e;(e=this.df)===null||e===void 0||e.nextStep()}previousStep(){var e;(e=this.df)===null||e===void 0||e.previousStep()}clearCache(){var e;this.vf=null,(e=this.Ml)===null||e===void 0||e.unregister("ph_product_tours")}resetTour(e){var t;(t=this.df)===null||t===void 0||t.resetTour(e)}resetAllTours(){var e;(e=this.df)===null||e===void 0||e.resetAllTours()}cancelPendingTour(e){var t;(t=this.df)===null||t===void 0||t.cancelPendingTour(e)}}},ma),gO={siteApps:class{constructor(e){this._instance=e,this.pf=0,this.gf=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}mf(e,t){if(!t)return;const r=this.globalsForEvent(t);this.gf.push(r),this.gf.length>1e3&&(this.gf=this.gf.slice(10))}get siteAppLoaders(){var e;return(e=te._POSTHOG_REMOTE_CONFIG)===null||e===void 0||(e=e[this._instance.config.token])===null||e===void 0?void 0:e.siteApps}initialize(){if(this.isEnabled){const e=this._instance._addCaptureHook(this.mf.bind(this));this.yf=()=>{e(),this.gf=[],this.yf=void 0}}}globalsForEvent(e){var t,r,n,i,s,o,a;if(!e)throw new Error("Event payload is required");const c={},l=this._instance.get_property("$groups")||[],u=this._instance.get_property("$stored_group_properties")||{};for(const[p,f]of Object.entries(u))c[p]={id:l[p],type:p,properties:f};const{$set_once:h,$set:d}=e;return{event:b(b({},rm(e,GP)),{},{properties:b(b(b({},e.properties),d?{$set:b(b({},(t=(r=e.properties)===null||r===void 0?void 0:r.$set)!==null&&t!==void 0?t:{}),d)}:{}),h?{$set_once:b(b({},(n=(i=e.properties)===null||i===void 0?void 0:i.$set_once)!==null&&n!==void 0?n:{}),h)}:{}),elements_chain:(s=(o=e.properties)===null||o===void 0?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=e.properties)===null||a===void 0?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:c}}bf(e){var t;const r=(t=e.tagName)===null||t===void 0?void 0:t.toLowerCase();return r==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(e)||(Ft.error("prepare_external_dependency_stylesheet returned null"),null):r==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(e)||(Ft.error("prepare_external_dependency_script returned null"),null):e}_f(){var e,t,r,n,i,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};const c=N?.defaultView,l=c==null||(e=c.Node)===null||e===void 0?void 0:e.prototype;if(!c||!l)return()=>{};if(this.pf++,this.wf)return this.kf();const u=[],h=this,d=new WeakSet,p=(m,_,w)=>{if(!m?.[_])return;const S=m[_];m[_]=w(S),u.push(()=>{m[_]=S})},f=m=>{if(d.has(m))return m;const _=h.bf(m);return _&&d.add(_),_},v=m=>m.map(_=>typeof _=="string"?_:f(_)).filter(_=>!He(_));return p(l,"appendChild",m=>function(_){const w=f(_);return w?m.call(this,w):_}),p(l,"insertBefore",m=>function(_,w){const S=f(_);return S?m.call(this,S,w):_}),p(l,"replaceChild",m=>function(_,w){const S=f(_);return S?m.call(this,S,w):w}),[(t=c.Element)===null||t===void 0?void 0:t.prototype,(r=c.Document)===null||r===void 0?void 0:r.prototype,(n=c.DocumentFragment)===null||n===void 0?void 0:n.prototype].forEach(m=>{p(m,"append",_=>function(...w){return _.apply(this,v(w))}),p(m,"prepend",_=>function(...w){return _.apply(this,v(w))})}),[(i=c.Element)===null||i===void 0?void 0:i.prototype,(s=c.CharacterData)===null||s===void 0?void 0:s.prototype,(o=c.DocumentType)===null||o===void 0?void 0:o.prototype].forEach(m=>{p(m,"before",_=>function(...w){return _.apply(this,v(w))}),p(m,"after",_=>function(...w){return _.apply(this,v(w))}),p(m,"replaceWith",_=>function(...w){const S=v(w);return w.length&&!S.length?void 0:_.apply(this,S)})}),p((a=c.Element)===null||a===void 0?void 0:a.prototype,"insertAdjacentElement",m=>function(_,w){const S=f(w);return S?m.call(this,_,S):null}),this.wf=()=>{u.forEach(m=>m()),this.wf=void 0},this.kf()}kf(){let e=!1;return()=>{var t;e||(e=!0,this.pf--,this.pf===0&&((t=this.wf)===null||t===void 0||t.call(this)))}}Sf(e,t=!0){const r=this._f();try{const n=e(r);return t&&r(),n}catch(n){throw r(),n}}setupSiteApp(e){const t=this.apps[e.id],r=()=>{var s;!t.errored&&this.gf.length&&(Ft.info(`Processing ${this.gf.length} events for site app with id ${e.id}`),this.gf.forEach(o=>this.Sf(()=>{var a;return(a=t.processEvent)===null||a===void 0?void 0:a.call(t,o)})),t.processedBuffer=!0),Object.values(this.apps).every(o=>o.processedBuffer||o.errored)&&((s=this.yf)===null||s===void 0||s.call(this))};let n=!1;const i=s=>{t.errored=!s,t.loaded=!0,Ft.info(`Site app with id ${e.id} ${s?"loaded":"errored"}`),n&&r()};try{const{processEvent:s}=this.Sf(o=>e.init({posthog:this._instance,callback(a){o(),i(a)}}),!1);s&&(t.processEvent=s),n=!0}catch(s){Ft.error(fp+e.id,s),i(!1)}if(n&&t.loaded)try{r()}catch(s){Ft.error(`Error while processing buffered events PostHog app with config id ${e.id}`,s),t.errored=!0}}xf(){const e=this.siteAppLoaders||[];for(const t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(const t of e)this.setupSiteApp(t)}Cf(e){if(Object.keys(this.apps).length===0)return;const t=this.globalsForEvent(e);for(const r of Object.values(this.apps))try{this.Sf(()=>{var n;return(n=r.processEvent)===null||n===void 0?void 0:n.call(r,t)})}catch(n){Ft.error(`Error while processing event ${e.event} for site app ${r.id}`,n)}}onRemoteConfig(e){var t,r,n;if(!((t=this.siteAppLoaders)===null||t===void 0)&&t.length)return this.isEnabled?(this.xf(),void this._instance.on("eventCaptured",a=>this.Cf(a))):void Ft.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((r=this.yf)===null||r===void 0||r.call(this),!e.ok)return;const i=e.config;if(!((n=i.siteApps)===null||n===void 0)&&n.length)if(this.isEnabled)for(const{id:a,url:c}of i.siteApps){var s,o;te[`__$$ph_site_app_${a}`]=this._instance,(s=te.__PosthogExtensions__)===null||s===void 0||(o=s.loadSiteApp)===null||o===void 0||o.call(s,this._instance,c,l=>{if(l)return Ft.error(fp+a,l)})}else Ft.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}},mO={tracingHeaders:class{constructor(e){this._instance=e,this.$f=void 0,this.Tf=void 0,this.If=void 0,this.Hv=()=>{const t=this.Mf();var r,n;t?(O(this.$f)&&(this.$f=(r=te.__PosthogExtensions__)===null||r===void 0||(r=r.tracingHeadersPatchFns)===null||r===void 0?void 0:r._patchXHR(t,()=>this._instance.get_distinct_id(),this._instance.sessionManager)),O(this.Tf)&&(this.Tf=(n=te.__PosthogExtensions__)===null||n===void 0||(n=n.tracingHeadersPatchFns)===null||n===void 0?void 0:n._patchFetch(t,()=>this._instance.get_distinct_id(),this._instance.sessionManager))):this.Zv()}}initialize(){this.startIfEnabledOrStop()}zo(e){var t,r,n;!((t=te.__PosthogExtensions__)===null||t===void 0)&&t.tracingHeadersPatchFns?e():(r=te.__PosthogExtensions__)===null||r===void 0||(n=r.loadExternalDependency)===null||n===void 0||n.call(r,this._instance,"tracing-headers",i=>{if(i)return jP.error("failed to load script",i);e()})}Ef(){var e,t;return(e=(t=this._instance.config.tracing_headers)!==null&&t!==void 0?t:this._instance.config.addTracingHeaders)!==null&&e!==void 0?e:this._instance.config.__add_tracing_headers}Mf(){const e=this.Ef();return ce(e)?(ce(this.If)?this.If.splice(0,this.If.length,...e):this.If=[...e],e.length>0?this.If:void 0):(ce(this.If)&&this.If.splice(0),this.If=e||void 0,this.If)}Zv(){var e,t;(e=this.$f)===null||e===void 0||e.call(this),(t=this.Tf)===null||t===void 0||t.call(this),this.$f=void 0,this.Tf=void 0}startIfEnabledOrStop(){this.Mf()?this.zo(this.Hv):this.Zv()}}},_O=b({surveys:class extends WP{constructor(e){var t;super(new XP(e),(t=e,{get projectToken(){return t.config.token},kv:new YP(t)})),this._instance=e}qh(e,t){const r=t.query?ds(e,t.query):e;return new Promise(n=>{var i;this._instance._send_request({method:t.method,url:this._instance.requestRouter.endpointFor((i=t.target)!==null&&i!==void 0?i:"api",r),data:t.body,headers:t.headers,timeout:t.timeoutMs,fireCallbackOnDrop:!0,transport:t.transport,compression:t.compression,timestampMode:t.sentAt,callback:n})})}}},ma),yO={toolbar:class{constructor(e){this.instance=e}Pf(e){te.ph_toolbar_state=e}Rf(){var e;return(e=te.ph_toolbar_state)!==null&&e!==void 0?e:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(e=void 0,t=void 0,r=void 0){var n,i;if(hl(this.instance.config)||!A||!N)return!1;e=(n=e)!==null&&n!==void 0?n:A.location,r=(i=r)!==null&&i!==void 0?i:A.history;try{if(!t){try{A.localStorage.setItem("test","test"),A.localStorage.removeItem("test")}catch{return!1}t=A?.localStorage}const s=QP||Ao(e.hash,"__posthog")||Ao(e.hash,"state");let o;const a=s?lh(()=>JSON.parse(atob(decodeURIComponent(s))))||lh(()=>JSON.parse(decodeURIComponent(s))):null;return a&&a.action==="ph_authorize"?(o=a,o.source="url",o&&Object.keys(o).length>0&&(a.desiredHash?e.hash=a.desiredHash:r?r.replaceState(r.state,"",e.pathname+e.search):e.hash="")):(o=JSON.parse(t.getItem(gp)||"{}"),o.source="localstorage",delete o.userIntent),!(!o.token||this.instance.config.token!==o.token||(this.loadToolbar(o),0))}catch{return!1}}Af(e){const t=te.ph_load_toolbar||te.ph_load_editor;!ge(t)&&tt(t)?t(e,this.instance):mp.warn("No toolbar load function found")}loadToolbar(e){const t=!!N?.getElementById("__POSTHOG_TOOLBAR__");if(!A||t)return!1;const r=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,n=b(b({token:this.instance.config.token},e),{},{apiURL:this.instance.requestRouter.endpointFor("ui")},r?{instrument:!1}:{});if(A.localStorage.setItem(gp,JSON.stringify(b(b({},n),{},{source:void 0}))),this.Rf()===2)this.Af(n);else if(this.Rf()===0){var i,s;this.Pf(1),(i=te.__PosthogExtensions__)===null||i===void 0||(s=i.loadExternalDependency)===null||s===void 0||s.call(i,this.instance,"toolbar",o=>{if(o)return mp.error("[Toolbar] Failed to load",o),void this.Pf(0);this.Pf(2),this.Af(n)}),Ie(A,"turbolinks:load",()=>{this.Pf(0),this.loadToolbar(n)})}return!0}Ff(e){return this.loadToolbar(e)}maybeLoadEditor(e=void 0,t=void 0,r=void 0){return this.maybeLoadToolbar(e,t,r)}}},bO=b({experiments:class ht{get Rr(){return this._instance.config}constructor(t){this._instance=t,this.getWebExperimentsAndEvaluateDisplayLogic=(r=!1)=>{this.getWebExperiments(n=>{ht.Of("retrieved web experiments from the server"),this.Df=new Map,n.forEach(i=>{if(i.feature_flag_key){var s;this.Df&&(ht.Of("setting flag key ",i.feature_flag_key," to web experiment ",i),(s=this.Df)===null||s===void 0||s.set(i.feature_flag_key,i));const o=this._instance.getFeatureFlag(i.feature_flag_key);ye(o)&&i.variants[o]&&this.Lf(i.name,o,i.variants[o].transforms)}else if(i.variants)for(const o in i.variants){const a=i.variants[o];ht.Nf(a,this._instance)&&this.Lf(i.name,o,a.transforms)}})},r)},this._instance.onFeatureFlags(r=>{this.onFeatureFlags(r)})}initialize(){}onFeatureFlags(t){if(this._is_bot())ht.Of(Rp);else if(!this.Rr.disable_web_experiments){if(ge(this.Df))return this.Df=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ht.Of("applying feature flags",t),t.forEach(r=>{var n;if(this.Df&&(!((n=this.Df)===null||n===void 0)&&n.has(r))){var i;const s=this._instance.getFeatureFlag(r),o=(i=this.Df)===null||i===void 0?void 0:i.get(r);s&&o!=null&&o.variants[s]&&this.Lf(o.name,s,o.variants[s].transforms)}})}}previewWebExperiment(){const t=ht.getWindowLocation();if(t?.search){const r=Xn(t?.search,"__experiment_id"),n=Xn(t?.search,"__experiment_variant");r&&n&&(ht.Of(`previewing web experiments ${r} && ${n}`),this.getWebExperiments(i=>{this.qf(parseInt(r),n,i)},!1,!0))}}loadIfEnabled(){this.Rr.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(t,r,n){if(this.Rr.disable_web_experiments&&!n)return t([]);const i=this._instance.get_property("$web_experiments");if(i&&!r)return t(i);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api",`/api/web_experiments/?token=${this.Rr.token}`),method:"GET",timestampMode:"query",callback:s=>t(s.statusCode===200&&s.json&&s.json.experiments||[])})}qf(t,r,n){const i=n.filter(s=>s.id===t);i&&i.length>0&&(ht.Of(`Previewing web experiment [${i[0].name}] with variant [${r}]`),this.Lf(i[0].name,r,i[0].variants[r].transforms))}static Nf(t,r){return!ge(t.conditions)&&ht.jf(t,r)&&ht.Bf(t)}static jf(t,r){var n;if(ge(t.conditions)||ge((n=t.conditions)===null||n===void 0?void 0:n.url))return!0;const i=ht.getWindowLocation();if(i){var s,o,a;const c=Mm(r,i.href);return!(!((s=t.conditions)===null||s===void 0)&&s.url)||sO[(o=(a=t.conditions)===null||a===void 0?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](t.conditions.url,c)}return!1}static getWindowLocation(){return A?.location}static Bf(t){var r;if(ge(t.conditions)||ge((r=t.conditions)===null||r===void 0?void 0:r.utm))return!0;const n=Gm();if(n.utm_source){var i,s,o,a,c,l,u,h;const d=!(!((i=t.conditions)===null||i===void 0||(i=i.utm)===null||i===void 0)&&i.utm_campaign)||((s=t.conditions)===null||s===void 0||(s=s.utm)===null||s===void 0?void 0:s.utm_campaign)==n.utm_campaign,p=!(!((o=t.conditions)===null||o===void 0||(o=o.utm)===null||o===void 0)&&o.utm_source)||((a=t.conditions)===null||a===void 0||(a=a.utm)===null||a===void 0?void 0:a.utm_source)==n.utm_source,f=!(!((c=t.conditions)===null||c===void 0||(c=c.utm)===null||c===void 0)&&c.utm_medium)||((l=t.conditions)===null||l===void 0||(l=l.utm)===null||l===void 0?void 0:l.utm_medium)==n.utm_medium,v=!(!((u=t.conditions)===null||u===void 0||(u=u.utm)===null||u===void 0)&&u.utm_term)||((h=t.conditions)===null||h===void 0||(h=h.utm)===null||h===void 0?void 0:h.utm_term)==n.utm_term;return d&&f&&v&&p}return!1}static Of(t,...r){j.info(`[WebExperiments] ${t}`,r)}Lf(t,r,n){this._is_bot()?ht.Of(Rp):r!=="control"?n.forEach(i=>{if(i.selector){var s;ht.Of(`applying transform of variant ${r} for experiment ${t} `,i),((s=document)===null||s===void 0?void 0:s.querySelectorAll(i.selector))?.forEach(o=>{const a=o;i.html&&(a.innerHTML=i.html),i.css&&a.setAttribute("style",i.css)})}}):ht.Of("Control variants leave the page unmodified.")}_is_bot(){return rt&&this._instance?m_(rt,this.Rr.custom_blocked_useragents):void 0}}},ma),wO={conversations:class{constructor(e){this._instance=e,this.Hf=void 0,this._conversationsManager=null,this.zf=!1,this.ne=null,this.Uf=!1}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(this._instance.config.disable_conversations||(this.Wf=e.ok,!e.ok))return;const t=e.config.conversations;ge(t)||(vt(t)?this.Hf=t:(this.Hf=t.enabled,this.ne=t),this.loadIfEnabled())}reset(){var e;(e=this._conversationsManager)===null||e===void 0||e.reset(),this._conversationsManager=null,this.Hf=void 0,this.ne=null,this.Wf=void 0,this.Uf=!1}loadIfEnabled(){if(this._conversationsManager||this.zf||this._instance.config.disable_conversations||hl(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())return;const e=te?.__PosthogExtensions__;if(e&&!O(this.Hf)&&this.Hf)if(this.ne&&this.ne.token){this.zf=!0;try{const t=e.initConversations;if(t)return this.Vf(t),void(this.zf=!1);const r=e.loadExternalDependency;if(!r)return void this.Gf(Iu);r(this._instance,"conversations",n=>{n||!e.initConversations?this.Gf("Could not load conversations script",n):this.Vf(e.initConversations),this.zf=!1})}catch(t){this.Gf("Error initializing conversations",t),this.zf=!1}}else kt.error("Conversations enabled but missing token in remote config.")}Vf(e){if(this.ne)try{this._conversationsManager=e(this.ne,this._instance),this.Uf=!1,kt.info("Conversations loaded successfully")}catch(t){this.Gf("Error completing conversations initialization",t)}else kt.error("Cannot complete initialization: remote config is null")}Gf(e,t){kt.error(e,t),this._conversationsManager=null,this.zf=!1,this.Uf=!0}show(){this._conversationsManager?this._conversationsManager.show():kt.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Hf===!0&&!He(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":hl(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Wf===!1?"remote_config_failed":O(this.Hf)?this.Wf?"disabled_in_project":"remote_config_pending":this.Hf?ge(this.ne)||!this.ne.token?"missing_token":te?.__PosthogExtensions__?this.zf?"initializing":this.Uf?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var e,t;return(e=(t=this._conversationsManager)===null||t===void 0?void 0:t.isVisible())!==null&&e!==void 0&&e}sendMessage(e,t,r){var n=this;return Ue(function*(){return n._conversationsManager?n._conversationsManager.sendMessage(e,t,r):(kt.warn(Jr),null)})()}getMessages(e,t){var r=this;return Ue(function*(){return r._conversationsManager?r._conversationsManager.getMessages(e,t):(kt.warn(Jr),null)})()}markAsRead(e){var t=this;return Ue(function*(){return t._conversationsManager?t._conversationsManager.markAsRead(e):(kt.warn(Jr),null)})()}getTickets(e){var t=this;return Ue(function*(){return t._conversationsManager?t._conversationsManager.getTickets(e):(kt.warn(Jr),null)})()}requestRestoreLink(e){var t=this;return Ue(function*(){return t._conversationsManager?t._conversationsManager.requestRestoreLink(e):(kt.warn(Jr),null)})()}restoreFromToken(e){var t=this;return Ue(function*(){return t._conversationsManager?t._conversationsManager.restoreFromToken(e):(kt.warn(Jr),null)})()}restoreFromUrlToken(){var e=this;return Ue(function*(){return e._conversationsManager?e._conversationsManager.restoreFromUrlToken():(kt.warn(Jr),null)})()}getCurrentTicketId(){var e,t;return(e=(t=this._conversationsManager)===null||t===void 0?void 0:t.getCurrentTicketId())!==null&&e!==void 0?e:null}getWidgetSessionId(){var e,t;return(e=(t=this._conversationsManager)===null||t===void 0?void 0:t.getWidgetSessionId())!==null&&e!==void 0?e:null}Sh(){var e;(e=this._conversationsManager)===null||e===void 0||e.setIdentity()}xh(){var e;(e=this._conversationsManager)===null||e===void 0||e.clearIdentity()}}},SO={logs:class{constructor(e){var t;this._instance=e,this.name="logs",this.Zf=!1,this.Qf=!1,this.Jf=!1,this.$=Be("[logs]"),this.Kf=b(b({},this.$),{},{error:(...r)=>{r.some(Tp)||this.$.error(...r)}}),this.al=[],this.Xf=[],this.hd=0,this.Io=!1,this.Yf=[],this.tp=[],this.ep=!1,this.np=!1,this.sp=()=>{var r,n;this.Io||(this.hd=0,(r=this.rp)===null||r===void 0||r.onReconnect(),(n=this.op)===null||n===void 0||n.onReconnect())},this._instance&&(t=this._instance.config.logs)!==null&&t!==void 0&&t.captureConsoleLogs&&(this.Zf=!0),A&&Ie(A,"online",this.sp)}ap(e,t,r,n){var i;const s=Ap((i=this._instance)===null||i===void 0||(i=i.config)===null||i===void 0?void 0:i.logs,r);return[new e$(this.lp(e,t),s,this.Kf,()=>this.up(),o=>o(),void 0,n),s]}hp(){var e;const t=(e=this._instance)===null||e===void 0||(e=e.config)===null||e===void 0?void 0:e.logs;var r;return this.rp&&this.cp===t||((r=this.rp)===null||r===void 0||r.reset(),this.cp=t,[this.rp,this.dp]=this.ap(()=>this.al,n=>{this.al=n})),this.rp}vp(){var e;const t=(e=this._instance)===null||e===void 0||(e=e.config)===null||e===void 0?void 0:e.logs;var r;return this.op&&this.fp===t||((r=this.op)===null||r===void 0||r.reset(),this.fp=t,[this.op,this.pp]=this.ap(()=>this.Xf,n=>{this.Xf=n},{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},Ip)),this.op}setup(e){var t;if(this.Io)return;this.wo=e,(t=this._instance)!==null&&t!==void 0&&(t=t.config)!==null&&t!==void 0&&(t=t.logs)!==null&&t!==void 0&&t.captureConsoleLogs&&(this.Zf=!0),(this.Zf||this.gp()&&this.mp())&&this.yp();let r=!1;const n=e.onRemoteConfig(i=>{var s;r=i.ok&&((s=i.config.logs)===null||s===void 0?void 0:s.captureConsoleLogs)===!0,this.onRemoteConfig(i)});this.Io?n.dispose():(this.Po=n,r||this.loadIfEnabled())}dispose(){var e,t,r,n;this.Io||(this.Io=!0,this.bp(),(e=this.Po)===null||e===void 0||e.dispose(),this.Po=void 0,this.wo=void 0,this.Jf=!1,A?.removeEventListener("online",this.sp),(t=this._p)===null||t===void 0||t.call(this),this._p=void 0,(r=this.rp)===null||r===void 0||r.reset(),(n=this.op)===null||n===void 0||n.reset())}onRemoteConfig(e){var t,r;if(this.Io)return;const n=e.ok?(t=e.config.logs)===null||t===void 0?void 0:t.captureConsoleLogs:void 0;ge(n)?this.wp():((r=this._instance)===null||r===void 0||(r=r.persistence)===null||r===void 0||r.register({$logs_capture_enabled_server_side:!!n}),n?(this.Zf=!0,this.Qf||this.yp(),this.loadIfEnabled()):this.wp())}reset(){var e,t,r,n;this.bp(),(e=this.rp)===null||e===void 0||e.clearQueue(),this.al=[],(t=this.rp)===null||t===void 0||t.reset(),(r=this.op)===null||r===void 0||r.clearQueue(),this.Xf=[],(n=this.op)===null||n===void 0||n.reset(),this.hd=0}captureLog(e){this.Io||this.hp().captureLog(e)}captureConsoleLog(e){this.Io||this.vp().captureLog(e)}captureBufferedConsoleLog(e,t,r){this.Io||this.vp().captureLog(e,{context:t,occurredAtMs:r})}mp(){var e;return!!(!((e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0||(e=e.props)===null||e===void 0)&&e[vm])}gp(){var e,t,r;return!(!((e=this._instance)===null||e===void 0||(t=e.nl)===null||t===void 0)&&t.call(e))||!!(!((r=te._POSTHOG_REMOTE_CONFIG)===null||r===void 0||(r=r[this._instance.config.token])===null||r===void 0)&&r.config)}$h(){var e;this.bp(),(e=this.op)===null||e===void 0||e.clearQueue(),this.Xf=[]}wp(){this.Zf||this.bp()}yp(){var e;if(this.ep||!te?.console)return;const t=Ap((e=this._instance)===null||e===void 0||(e=e.config)===null||e===void 0?void 0:e.logs).maxBufferSize;let r=!0;this.tp.push(()=>{r=!1});for(const n of oO){let i;try{i=aO(te.console[n])}catch{continue}i&&this.tp.push(ss(te.console,n,s=>{const o=(...a)=>{try{r&&this.kp(n,a,t)}catch{}return s.apply(te.console,a)};return o.__rrweb_original__=i,o}))}this.ep=!0,this.Sp=setTimeout(()=>{this.bp()},3e4)}kp(e,t,r){var n;if(this.ep&&!this.np&&t.length!==0)if(!((n=this._instance)===null||n===void 0)&&n.is_capturing()){if(r>this.Yf.length){this.np=!0;try{this.Yf.push({level:e,args:t,occurredAtMs:Date.now(),context:this.up()})}finally{this.np=!1}}}else this.bp()}bp(){if(this.Yf=[],this.ep){this.ep=!1,this.Sp&&(clearTimeout(this.Sp),this.Sp=void 0);for(const e of this.tp)e();this.tp=[]}}xp(){const e=this.Yf;return this.bp(),e}get logger(){return this.Cp||(this.Cp={trace:(e,t)=>this.captureLog({body:e,level:"trace",attributes:t}),debug:(e,t)=>this.captureLog({body:e,level:"debug",attributes:t}),info:(e,t)=>this.captureLog({body:e,level:"info",attributes:t}),warn:(e,t)=>this.captureLog({body:e,level:"warn",attributes:t}),error:(e,t)=>this.captureLog({body:e,level:"error",attributes:t}),fatal:(e,t)=>this.captureLog({body:e,level:"fatal",attributes:t})}),this.Cp}flushLogs(e){e?this.$p(e):(this.rp&&this.rp.flush().catch(t=>this.Tp(t)),this.op&&this.op.flush().catch(t=>this.Tp(t)))}Tp(e){Tp(e)||this.$.error("PostHog logs flush failed:",e)}loadIfEnabled(){if(this.Io||!this.Zf||this.Qf||this.Jf)return;const e=te?.__PosthogExtensions__;if(!e)return this.$.error("PostHog Extensions not found."),void this.bp();const t=e.loadExternalDependency;if(!t)return this.$.error(Iu),void this.bp();this.Jf=!0;try{t(this._instance,"logs",r=>{if(this.Jf=!1,this.Io||!this.Zf)return;const n=e.logs;if(r||!n?.initializeLogs)this.$.error("Could not load logs script",r),this.bp();else{var i;const a=this.xp();var s,o;this._p=n.initializeLogs((i=this.wo)!==null&&i!==void 0?i:this._instance),this.Qf=!0,a.length>0&&((s=n.replayConsoleBuffer)===null||s===void 0||s.call(n,(o=this.wo)!==null&&o!==void 0?o:this._instance,a))}})}catch(r){throw this.Jf=!1,r}}lp(e,t){const r=this._instance;return{get isDisabled(){return!1},get optedOut(){return!r.is_capturing()},getPersistedProperty:n=>n===Ht.LogsQueue?e():void 0,setPersistedProperty(n,i){var s;n===Ht.LogsQueue&&t((s=i)!==null&&s!==void 0?s:[])},js:n=>this.js(n),getLibraryId:()=>et.LIB_NAME,getLibraryVersion:()=>et.LIB_VERSION}}js(e){return new Promise(t=>{if(Vm(this.hd,3))return void t({kind:"fatal",error:pc(void 0,"logs endpoint is unreachable, dropping batch")});let r=!1;const n=s=>{r||(r=!0,clearTimeout(i),t(s))},i=setTimeout(()=>{this.$.warn("Logs request timed out before receiving a response"),n({kind:"retry-later",error:pc(void 0,"logs request timed out")})},9e4);this._instance._send_request({method:"POST",url:this.Ip(),data:e,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{const o=s.statusCode;if(this.Mp(o),o>=200&&300>o)n({kind:"ok"});else if(o===413)n({kind:"too-large"});else if(o!==0&&o!==408&&o!==429&&500>o)n({kind:"fatal",error:new Error(`logs request failed with status ${o}`)});else{var a;o===0?(s.error||this.$.warn("Logs request failed before receiving an HTTP response"),n({kind:"retry-later",error:pc(s.error,"logs request failed before receiving an HTTP response")})):n({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error(`logs request failed with status ${o}`)})}}})})}Mp(e){(e!==0||this._instance.__loaded)&&(this.hd=Bm(e,this.hd,3,()=>this.$.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes.")))}$p(e){this.al.length>0&&this.Ep(e,this.al,this.dp,et.LIB_NAME,t=>{this.al=t}),this.Xf.length>0&&this.Ep(e,this.Xf,this.pp,Ip,t=>{this.Xf=t})}Ep(e,t,r,n,i){if(t.length===0)return;const s=t.map(a=>a.record);i([]);const o=cm(s,am(r,et.LIB_NAME,et.LIB_VERSION),n,et.LIB_VERSION);this._instance._send_request({method:"POST",url:this.Ip(),data:o,compression:"best-available",batchKey:"logs",transport:e})}Ip(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}up(){var e;const t={};if(t.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){const{sessionId:r,windowId:n,sessionStartTimestamp:i,lastActivityTimestamp:s}=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0);t.sessionId=r,t.windowId=n,ge(i)||(t.sessionStartTimestamp=i),ge(s)||(t.lastActivityTimestamp=s)}if(te!=null&&(e=te.location)!==null&&e!==void 0&&e.href&&(t.currentUrl=this._instance.config.disable_capture_url_hashes?Ur(te.location.href):te.location.href),this._instance.featureFlags){const r=this._instance.featureFlags.getFlags();r&&r.length>0&&(t.activeFeatureFlags=r)}return t}}},EO={metrics:class{constructor(e){this._instance=e,this.$=Be("[metrics]"),this.Io=!1}initialize(){this.onConfigChange()}onConfigChange(){var e;if(this.Io)return;const t=!!(!((e=this._instance.config.metrics)===null||e===void 0)&&e.network);t&&!this.Pp?this.Pp=(r=>{let n=!0;const i=()=>n?(a=>{var c;const l=(c=a.config.metrics)===null||c===void 0?void 0:c.network;return l===!0?{}:l||void 0})(r):void 0,s=uO(r,i),o=dO(r,i);return()=>{n=!1,s(),o()}})(this._instance):!t&&this.Pp&&(this.Pp(),this.Pp=void 0)}hp(){var e;const t=(e=this._instance)===null||e===void 0||(e=e.config)===null||e===void 0?void 0:e.metrics;var r;return this.rp&&this.cp===t||((r=this.rp)===null||r===void 0||r.reset(),this.cp=t,this.rp=new t$(this.lp(),(function(n){var i,s,o,a,c;const l=n?.resourceAttributes;return{serviceName:(i=l?.["service.name"])!==null&&i!==void 0?i:n?.serviceName,serviceVersion:(s=l?.["service.version"])!==null&&s!==void 0?s:n?.serviceVersion,environment:(o=l?.["deployment.environment"])!==null&&o!==void 0?o:n?.environment,resourceAttributes:l,beforeSend:n?.beforeSend,flushIntervalMs:(a=n?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(c=n?.maxSeriesPerFlush)!==null&&c!==void 0?c:1e3}})(t),this.$)),this.rp}count(e,t=1,r){this.hp().count(e,t,r)}gauge(e,t,r){this.hp().gauge(e,t,r)}histogram(e,t,r){this.hp().histogram(e,t,r)}flush(e){if(!this.rp)return Promise.resolve();if(e){const t=this.rp.drainWindow();return t&&this.Ys(t,e),Promise.resolve()}return this.rp.flush().catch(t=>this.$.error("PostHog metrics flush failed:",t))}reset(){var e;(e=this.rp)===null||e===void 0||e.reset()}dispose(){var e,t;this.Io=!0,(e=this.Pp)===null||e===void 0||e.call(this),this.Pp=void 0,(t=this.rp)===null||t===void 0||t.reset()}lp(){const e=this._instance,t=this;return{get isDisabled(){return!1},get optedOut(){return!e.is_capturing()},Ys:r=>t.Ys(r),getLibraryId:()=>et.LIB_NAME,getLibraryVersion:()=>et.LIB_VERSION}}Ys(e,t){return new Promise(r=>{let n=!1;const i=o=>{n||(n=!0,clearTimeout(s),r(o))},s=setTimeout(()=>i({kind:"retry-later",error:new Error("metrics request timed out")}),9e4);this._instance._send_request(b(b({method:"POST",url:this.Rp(),data:e,compression:"best-available",batchKey:"metrics"},t&&{transport:t}),{},{fireCallbackOnDrop:!0,callback(o){const a=o.statusCode;if(a>=200&&300>a)i({kind:"ok"});else if(a===413)i({kind:"too-large"});else if(a!==0&&a!==408&&a!==429&&500>a)i({kind:"fatal",error:new Error(`metrics request failed with status ${a}`)});else{var c;i({kind:"retry-later",error:(c=o.error)!==null&&c!==void 0?c:new Error(`metrics request failed with status ${a}`)})}}}))})}Rp(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}};Hi.__defaultExtensionClasses=b({},b(b(b(b(b(b(b(b(b(b(b(b(b({},ma),hO),pO),fO),vO),gO),_O),mO),yO),bO),wO),SO),EO));var kO=(function(){et.SDK_DIST_CHANNEL="npm";const e=qi[Ci]=new Hi;return(function(){function t(){t.done||(t.done=!0,v_=!1,Ce(qi,function(r){r._dom_loaded()}))}N?.addEventListener?N.readyState==="complete"?t():Ie(N,"DOMContentLoaded",t,{capture:!1}):A&&j.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),e})(),RO=kO,AO=/\.[cm]?[jt]sx?$/,IO=/^(?:[a-z][a-z0-9+.-]*:\/\/|\/)/i;function TO(e,t){if(typeof e!="string"||!IO.test(e))return!1;let r;try{r=new URL(e,t)}catch{return!1}return r.origin!==t?!1:!AO.test(r.pathname)}function CO(e,t){return e.length===0?!1:e.every(r=>TO(r,t))}function $O(e,t){return e.length===0?!1:e.every(r=>CO(r,t))}var C_=new Set(["caniuse.dev","www.caniuse.dev"]),PO=new Set(["score.mcpjam.com","www.score.mcpjam.com"]),OO=new Set([...C_,...PO]),UL="https://app.mcpjam.com";function xO(e){return C_.has(e.toLowerCase())}function FL(e=typeof window>"u"?void 0:window.location.hostname){return!!e&&xO(e)}var MO="phc_dTOPniyUNU2kD8Jx8yHMXSqiZHM8I91uWopTMX6EBE9",LO="https://us.i.posthog.com";function DO(){return typeof window<"u"&&window.location?.origin?.startsWith("http")?`${window.location.origin}/tlm`:LO}function $_(e){const t=Sc()?.guestId,r=e&&Object.keys(e).length>0?e:void 0;return!t&&!r?{}:{bootstrap:{...t?{distinctID:t,isIdentifiedID:!1}:{},...r?{featureFlags:r}:{}}}}var NO={advanced_disable_feature_flags:!0,advanced_disable_feature_flags_on_first_load:!0},zO=["/results/","/conformance/shared/","/evals/shared/"];function P_(e){let t=e;for(const r of zO){const n=r.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&");t=t.replace(new RegExp(`(${n})[^/?#]+`,"g"),"$1[redacted]")}return t=t.replace(/(\/organizations\/)[^/?#]+/g,"$1[redacted]"),t}var UO=new Set(["Load failed","Failed to fetch","NetworkError when attempting to fetch resource."]),FO=/^'TypeError' captured as exception with message: '([\s\S]*)'$/;function qO(e){const t=FO.exec(e.value),r=t?t[1]:e.type==="TypeError"?e.value:void 0;return r===void 0?!1:UO.has(r)||r.startsWith("Failed to fetch (")&&r.endsWith(")")}var jO=1e4;function HO(e){const t=e.$exception_list;if(!(Array.isArray(t)&&t.some(i=>typeof i?.value=="string"&&qO(i))))return;const r=ty();if(!r)return;const n=Date.now()-r.at;n>jO||(e.failed_request=`${r.method} ${P_(r.target)}`,e.failed_request_age_ms=n)}function VO(e,t){for(const r of["$current_url","$referrer","$pathname","$session_entry_url","$session_entry_pathname","$session_entry_referrer","$initial_current_url","$initial_pathname","$initial_referrer"])typeof e[r]=="string"&&(e[r]=P_(e[r]));return t==="$exception"&&HO(e),e}function BO(e){if(e?.event!=="$exception"||typeof window>"u")return e;const t=e.properties?.$exception_list;if(!Array.isArray(t))return e;const r=t.map(n=>{const i=n?.stacktrace?.frames;return Array.isArray(i)?i.map(s=>s?.filename):[]});return $O(r,window.location.origin)?null:e}var GO=OO;function hs(){return WO()}function WO(){return typeof window<"u"&&window.isElectron===!0}var ZO="data-ph-no-capture",JO={maskAllInputs:!0,maskInputOptions:{password:!0},maskTextSelector:`[${ZO}]`};function Nu(e=typeof window>"u"?void 0:window.location?.pathname){return!!e&&(e.startsWith("/results/")||e.startsWith("/conformance/shared/")||e.startsWith("/evals/shared/"))}function KO(){return hs()&&!Nu()}var fc=!1;function qL(e,t){try{if(!hs())return;if(Nu(t)){e.sessionRecordingStarted?.()&&(fc=!0),e.stopSessionRecording?.();return}fc&&(fc=!1,e.startSessionRecording?.())}catch{}}function YO(e=typeof window>"u"?void 0:window.location?.hostname){const t=!!e&&GO.has(e.toLowerCase());return{capture_pageview:t?"history_change":!1,capture_pageleave:t}}var Cp={api_host:DO(),ui_host:"https://us.posthog.com",...$_(),...YO(),...NO,person_profiles:"always",sanitize_properties:VO,before_send:BO,capture_dead_clicks:!0,get capture_exceptions(){return hs()},get disable_session_recording(){return!KO()},session_recording:JO,loaded:e=>{e.register({environment:"production",platform:Rl(),version:"3.12.5",deployment:"self_hosted",source:"client"}),e.setPersonPropertiesForFlags?.({local_browser_security_version:"1",deployment:"self_hosted",platform:Rl()})}};function XO(e){const t=$_(e);return"bootstrap"in t?Object.defineProperties({},{...Object.getOwnPropertyDescriptors(Cp),bootstrap:{value:t.bootstrap,enumerable:!0,configurable:!0,writable:!0}}):Cp}var jL=()=>MO,HL=e=>XO(e);function Rl(){if(window?.isElectron){const e=navigator.userAgent.toLowerCase();return e.includes("mac")||e.includes("darwin")?"mac":e.includes("win")?"win":"electron"}return"npm"}function QO(){return"production"}function VL(e){const t=QO();return{location:e,platform:Rl(),...t!==void 0?{environment:t}:{}}}var Vt=[],At=[],e1=Uint8Array,vc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var An=0,t1=vc.length;An<t1;++An)Vt[An]=vc[An],At[vc.charCodeAt(An)]=An;At[45]=62;At[95]=63;function r1(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function n1(e,t,r){return(t+r)*3/4-r}function Oo(e){for(var t,r=r1(e),n=r[0],i=r[1],s=new e1(n1(e,n,i)),o=0,a=i>0?n-4:n,c=0;c<a;c+=4)t=At[e.charCodeAt(c)]<<18|At[e.charCodeAt(c+1)]<<12|At[e.charCodeAt(c+2)]<<6|At[e.charCodeAt(c+3)],s[o++]=t>>16&255,s[o++]=t>>8&255,s[o++]=t&255;return i===2&&(t=At[e.charCodeAt(c)]<<2|At[e.charCodeAt(c+1)]>>4,s[o++]=t&255),i===1&&(t=At[e.charCodeAt(c)]<<10|At[e.charCodeAt(c+1)]<<4|At[e.charCodeAt(c+2)]>>2,s[o++]=t>>8&255,s[o++]=t&255),s}function i1(e){return Vt[e>>18&63]+Vt[e>>12&63]+Vt[e>>6&63]+Vt[e&63]}function s1(e,t,r){for(var n,i=[],s=t;s<r;s+=3)n=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),i.push(i1(n));return i.join("")}function xo(e){for(var t,r=e.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(s1(e,o,o+s>a?a:o+s));return n===1?(t=e[r-1],i.push(Vt[t>>2]+Vt[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],i.push(Vt[t>>10]+Vt[t>>4&63]+Vt[t<<2&63]+"=")),i.join("")}function BL(e){if(e===void 0)return{};if(!O_(e))throw new Error(`The arguments to a Convex function must be an object. Received: ${e}`);return e}function GL(e){if(typeof e>"u")throw new Error("Client created with undefined deployment address. If you used an environment variable, check that it's set.");if(typeof e!="string")throw new Error(`Invalid deployment address: found ${e}".`);if(!(e.startsWith("http:")||e.startsWith("https:")))throw new Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${e}".`);try{new URL(e)}catch{throw new Error(`Invalid deployment address: "${e}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(e.endsWith(".convex.site"))throw new Error(`Invalid deployment address: "${e}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}function O_(e){const t=typeof e=="object",r=Object.getPrototypeOf(e),n=r===null||r===Object.prototype||r?.constructor?.name==="Object";return t&&n}var x_=!0,ti=BigInt("-9223372036854775808"),zu=BigInt("9223372036854775807"),Al=BigInt("0"),o1=BigInt("8"),a1=BigInt("256"),gc="This commit timestamp is unresolved: its value is assigned when the mutation commits. Read the document after the mutation completes to get its value.",M_=class{[Symbol.toPrimitive](e){if(e==="string")return this.toString();throw new Error(gc)}valueOf(){throw new Error(gc)}toJSON(){throw new Error(gc)}toString(){return"[unresolved commit timestamp]"}},c1=new M_;function L_(e){return Number.isNaN(e)||!Number.isFinite(e)||Object.is(e,-0)}function l1(e){e<Al&&(e-=ti+ti);let t=e.toString(16);t.length%2===1&&(t="0"+t);const r=new Uint8Array(new ArrayBuffer(8));let n=0;for(const i of t.match(/.{2}/g).reverse())r.set([parseInt(i,16)],n++),e>>=o1;return xo(r)}function u1(e){const t=Oo(e);if(t.byteLength!==8)throw new Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let r=Al,n=Al;for(const i of t)r+=BigInt(i)*a1**n,n++;return r>zu&&(r+=ti+ti),r}function d1(e){if(e<ti||zu<e)throw new Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);const t=new ArrayBuffer(8);return new DataView(t).setBigInt64(0,e,!0),xo(new Uint8Array(t))}function h1(e){const t=Oo(e);if(t.byteLength!==8)throw new Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);return new DataView(t.buffer).getBigInt64(0,!0)}var p1=DataView.prototype.setBigInt64?d1:l1,f1=DataView.prototype.getBigInt64?h1:u1,$p=1024;function Il(e){if(e.length>$p)throw new Error(`Field name ${e} exceeds maximum field name length ${$p}.`);if(e.startsWith("$"))throw new Error(`Field name ${e} starts with a '$', which is reserved.`);for(let t=0;t<e.length;t+=1){const r=e.charCodeAt(t);if(r<32||r>=127)throw new Error(`Field name ${e} has invalid character '${e[t]}': Field names can only contain non-control ASCII characters`)}}function Pp(e){if(e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string")return e;if(Array.isArray(e))return e.map(n=>Pp(n));if(typeof e!="object")throw new Error(`Unexpected type of ${e}`);const t=Object.entries(e);if(t.length===1){const n=t[0][0];if(n==="$bytes"){if(typeof e.$bytes!="string")throw new Error(`Malformed $bytes field on ${e}`);return Oo(e.$bytes).buffer}if(n==="$integer"){if(typeof e.$integer!="string")throw new Error(`Malformed $integer field on ${e}`);return f1(e.$integer)}if(n==="$float"){if(typeof e.$float!="string")throw new Error(`Malformed $float field on ${e}`);const i=Oo(e.$float);if(i.byteLength!==8)throw new Error(`Received ${i.byteLength} bytes, expected 8 for $float`);const s=new DataView(i.buffer).getFloat64(0,x_);if(!L_(s))throw new Error(`Float ${s} should be encoded as a number`);return s}if(n==="$commitTs"){if(e.$commitTs!==null)throw new Error(`Malformed $commitTs field on ${e}`);return c1}if(n==="$set")throw new Error("Received a Set which is no longer supported as a Convex type.");if(n==="$map")throw new Error("Received a Map which is no longer supported as a Convex type.")}const r={};for(const[n,i]of Object.entries(e))Il(n),r[n]=Pp(i);return r}var v1=16384;function Hn(e){const t=JSON.stringify(e,(r,n)=>n===void 0?"undefined":typeof n=="bigint"?`${n.toString()}n`:n);if(t.length>v1){const r="[...truncated]";let n=16370;const i=t.codePointAt(n-1);return i!==void 0&&i>65535&&(n-=1),t.substring(0,n)+r}return t}function Mo(e,t,r,n){if(e===void 0){const o=r&&` (present at path ${r} in original object ${Hn(t)})`;throw new Error(`undefined is not a valid Convex value${o}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(e===null)return e;if(typeof e=="bigint"){if(e<ti||zu<e)throw new Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);return{$integer:p1(e)}}if(typeof e=="number")if(L_(e)){const o=new ArrayBuffer(8);return new DataView(o).setFloat64(0,e,x_),{$float:xo(new Uint8Array(o))}}else return e;if(typeof e=="boolean"||typeof e=="string")return e;if(e instanceof ArrayBuffer)return{$bytes:xo(new Uint8Array(e))};if(e instanceof M_)return{$commitTs:null};if(Array.isArray(e))return e.map((o,a)=>Mo(o,t,r+`[${a}]`,!1));if(e instanceof Set)throw new Error(mc(r,"Set",[...e],t));if(e instanceof Map)throw new Error(mc(r,"Map",[...e],t));if(!O_(e)){const o=e?.constructor?.name,a=o?`${o} `:"";throw new Error(mc(r,a,e,t))}const i={},s=Object.entries(e);s.sort(([o,a],[c,l])=>o===c?0:o<c?-1:1);for(const[o,a]of s)a!==void 0?(Il(o),i[o]=Mo(a,t,r+`.${o}`,!1)):n&&(Il(o),i[o]=g1(a,t,r+`.${o}`));return i}function mc(e,t,r,n){return e?`${t}${Hn(r)} is not a supported Convex type (present at path ${e} in original object ${Hn(n)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${Hn(r)} is not a supported Convex type.`}function g1(e,t,r){if(e===void 0)return{$undefined:null};if(t===void 0)throw new Error(`Programming error. Current value is ${Hn(e)} but original value is undefined`);return Mo(e,t,r,!1)}function WL(e){return Mo(e,e,"",!1)}var m1=Object.defineProperty,_1=(e,t,r)=>t in e?m1(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,_c=(e,t,r)=>_1(e,typeof t!="symbol"?t+"":t,r),Op,xp,y1=Symbol.for("ConvexError"),D_=class extends(xp=Error,Op=y1,xp){constructor(e){super(typeof e=="string"?e:Hn(e)),_c(this,"name","ConvexError"),_c(this,"data"),_c(this,Op,!0),this.data=e}};function Uu(e){if(!(e instanceof D_))return!1;const t=e.data;return typeof t=="object"&&t!==null&&t.kind==="forbidden"}function Fu(e){if(!(e instanceof D_))return!1;const t=e.data;return typeof t=="object"&&t!==null&&t.kind==="session_revoked"}var Lo;function ZL(e){try{Lo=new URL(e).hostname}catch{Lo=void 0}}function Tl(e){try{const t=new URL(e);if(!/^https?:$/.test(t.protocol))return;const r=t.pathname.replace(/(\/(?:results|conformance\/shared|evals\/shared|organizations)\/)[^/]+/g,"$1[redacted]").replace(/(\/(?:user-testing|chatbox)\/[^/]+\/)[^/]+/g,"$1[redacted]");return`${t.origin}${r}`}catch{return}}function Vi(e){const t=/^\[CONVEX Q\(([\w/.-]+:[\w.-]+)\)\]/.exec(e);if(!t)return;const r=/\[Request ID: ([a-f\d]+)\]/i.exec(e)?.[1],n=`${t[0]}${r?` [Request ID: ${r}]`:""} ${/\bServer Error\b/.test(e)?"Server Error":"Query failed"}`;return{functionName:t[1],requestId:r,safeMessage:n}}function N_(e){const t=Vi(e);if(t)return{convex_function:t.functionName,...t.requestId?{request_id:t.requestId}:{},...Lo?{convex_backend:Lo}:{}}}function b1(e){const t=Vi(e.message);if(!t)return e;const r=new Error(t.safeMessage);if(r.name=e.name,e.stack){const n=e.stack.split(`
97
+ `).filter(i=>/^(\s+at |[^@]*@(?:https?|file|webpack|vite):)/.test(i));r.stack=`${r.name}: ${r.message}
98
+ ${n.join(`
99
+ `)}`}return r}function z_(e=500){const t=new Set;return(r,n)=>{if(!r||!n)return!1;const i=`${r}:${n}`;return t.has(i)?!0:(t.add(i),t.size>e&&t.delete(t.values().next().value),!1)}}function JL(e=500){const t=z_(e);return(r,n={})=>{try{const i=r.exception?.values,s=i?.find(u=>Vi(u.value??"")),o=Vi(s?.value??"");if(!o)return r;if(Uu(n.originalException)||Fu(n.originalException))return null;const a=N_(s.value),c=typeof r.tags?.convex_backend=="string"?r.tags.convex_backend:a.convex_backend;if(t(c,o.requestId))return null;s.value=o.safeMessage,r.message&&(r.message=o.safeMessage),r.tags={...r.tags,...a,...c?{convex_backend:c}:{}};const l=Tl((typeof r.extra?.page_location=="string"?r.extra.page_location:void 0)??r.request?.url??(typeof window<"u"?window.location.href:""));r.request=l?{url:l}:void 0,r.breadcrumbs=void 0,r.extra={...typeof r.extra?.boundary=="string"?{boundary:r.extra.boundary}:{},...typeof r.extra?.componentStack=="string"?{componentStack:r.extra.componentStack}:{},...l?{page_location:l}:{}};for(const u of i??[])if(u!==s&&u.value&&(u.value=Vi(u.value)?.safeMessage??"Query failure cause"),u.stacktrace)for(const h of u.stacktrace.frames??[])delete h.vars;return r.transaction?.includes("/")&&(r.transaction=Tl(`https://route.invalid${r.transaction}`)?.replace("https://route.invalid","")),r}catch{return null}}}var w1=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,U_="8.55.1",Tt=globalThis;function _a(e,t,r){const n=r||Tt,i=n.__SENTRY__=n.__SENTRY__||{},s=i[U_]=i["8.55.1"]||{};return s[e]||(s[e]=t())}var ya=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,S1="Sentry Logger ",Mp=["debug","info","warn","error","log","assert","trace"],Lp={};function F_(e){if(!("console"in Tt))return e();const t=Tt.console,r={},n=Object.keys(Lp);n.forEach(i=>{const s=Lp[i];r[i]=t[i],t[i]=s});try{return e()}finally{n.forEach(i=>{t[i]=r[i]})}}function E1(){let e=!1;const t={enable:()=>{e=!0},disable:()=>{e=!1},isEnabled:()=>e};return ya?Mp.forEach(r=>{t[r]=(...n)=>{e&&F_(()=>{Tt.console[r](`${S1}[${r}]:`,...n)})}}):Mp.forEach(r=>{t[r]=()=>{}}),t}var dn=_a("logger",E1),q_=50;var Dp=/\(error: (.*)\)/,Np=/captureMessage|captureException/;function k1(...e){const t=e.sort((r,n)=>r[0]-n[0]).map(r=>r[1]);return(r,n=0,i=0)=>{const s=[],o=r.split(`
100
+ `);for(let a=n;a<o.length;a++){const c=o[a];if(c.length>1024)continue;const l=Dp.test(c)?c.replace(Dp,"$1"):c;if(!l.match(/\S*Error: /)){for(const u of t){const h=u(l);if(h){s.push(h);break}}if(s.length>=q_+i)break}}return R1(s.slice(i))}}function KL(e){return Array.isArray(e)?k1(...e):e}function R1(e){if(!e.length)return[];const t=Array.from(e);return/sentryWrapped/.test(Ms(t).function||"")&&t.pop(),t.reverse(),Np.test(Ms(t).function||"")&&(t.pop(),Np.test(Ms(t).function||"")&&t.pop()),t.slice(0,q_).map(r=>({...r,filename:r.filename||Ms(t).filename,function:r.function||"?"}))}function Ms(e){return e[e.length-1]||{}}var yc="<anonymous>";function A1(e){try{return!e||typeof e!="function"?yc:e.name||yc}catch{return yc}}function YL(e){const t=e.exception;if(t){const r=[];try{return t.values.forEach(n=>{n.stacktrace.frames&&r.push(...n.stacktrace.frames)}),r}catch{return}}}function ps(){return qu(Tt),Tt}function qu(e){const t=e.__SENTRY__=e.__SENTRY__||{};return t.version=t.version||"8.55.1",t[U_]=t["8.55.1"]||{}}var j_=Object.prototype.toString;function I1(e){switch(j_.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return ba(e,Error)}}function li(e,t){return j_.call(e)===`[object ${t}]`}function XL(e){return li(e,"ErrorEvent")}function QL(e){return li(e,"DOMError")}function eD(e){return li(e,"DOMException")}function Do(e){return li(e,"String")}function T1(e){return typeof e=="object"&&e!==null&&"__sentry_template_string__"in e&&"__sentry_template_values__"in e}function tD(e){return e===null||T1(e)||typeof e!="object"&&typeof e!="function"}function ju(e){return li(e,"Object")}function C1(e){return typeof Event<"u"&&ba(e,Event)}function $1(e){return typeof Element<"u"&&ba(e,Element)}function P1(e){return li(e,"RegExp")}function Hu(e){return!!(e&&e.then&&typeof e.then=="function")}function O1(e){return ju(e)&&"nativeEvent"in e&&"preventDefault"in e&&"stopPropagation"in e}function ba(e,t){try{return e instanceof t}catch{return!1}}function H_(e){return!!(typeof e=="object"&&e!==null&&(e.__isVue||e._isVue))}var Vn=Tt,x1=80;function M1(e,t={}){if(!e)return"<unknown>";try{let r=e;const n=5,i=[];let s=0,o=0;const a=" > ",c=3;let l;const u=Array.isArray(t)?t:t.keyAttrs,h=!Array.isArray(t)&&t.maxStringLength||x1;for(;r&&s++<n&&(l=L1(r,u),!(l==="html"||s>1&&o+i.length*c+l.length>=h));)i.push(l),o+=l.length,r=r.parentNode;return i.reverse().join(a)}catch{return"<unknown>"}}function L1(e,t){const r=e,n=[];if(!r||!r.tagName)return"";if(Vn.HTMLElement&&r instanceof HTMLElement&&r.dataset){if(r.dataset.sentryComponent)return r.dataset.sentryComponent;if(r.dataset.sentryElement)return r.dataset.sentryElement}n.push(r.tagName.toLowerCase());const i=t&&t.length?t.filter(s=>r.getAttribute(s)).map(s=>[s,r.getAttribute(s)]):null;if(i&&i.length)i.forEach(s=>{n.push(`[${s[0]}="${s[1]}"]`)});else{r.id&&n.push(`#${r.id}`);const s=r.className;if(s&&Do(s)){const o=s.split(/\s+/);for(const a of o)n.push(`.${a}`)}}for(const s of["aria-label","type","name","title","alt"]){const o=r.getAttribute(s);o&&n.push(`[${s}="${o}"]`)}return n.join("")}function rD(){try{return Vn.document.location.href}catch{return""}}function nD(e){return Vn.document&&Vn.document.querySelector?Vn.document.querySelector(e):null}function iD(e){if(!Vn.HTMLElement)return null;let t=e;const r=5;for(let n=0;n<r;n++){if(!t)return null;if(t instanceof HTMLElement){if(t.dataset.sentryComponent)return t.dataset.sentryComponent;if(t.dataset.sentryElement)return t.dataset.sentryElement}t=t.parentNode}return null}function Bi(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function sD(e,t){if(!Array.isArray(e))return"";const r=[];for(let n=0;n<e.length;n++){const i=e[n];try{H_(i)?r.push("[VueViewModel]"):r.push(String(i))}catch{r.push("[value cannot be serialized]")}}return r.join(t)}function D1(e,t,r=!1){return Do(e)?P1(t)?t.test(e):Do(t)?r?e===t:e.includes(t):!1:!1}function oD(e,t=[],r=!1){return t.some(n=>D1(e,n,r))}function aD(e,t,r){if(!(t in e))return;const n=e[t],i=r(n);typeof i=="function"&&N1(i,n);try{e[t]=i}catch{ya&&dn.log(`Failed to replace method "${t}" in object`,e)}}function ri(e,t,r){try{Object.defineProperty(e,t,{value:r,writable:!0,configurable:!0})}catch{ya&&dn.log(`Failed to add non-enumerable property "${t}" to object`,e)}}function N1(e,t){try{e.prototype=t.prototype=t.prototype||{},ri(e,"__sentry_original__",t)}catch{}}function cD(e){return e.__sentry_original__}function V_(e){if(I1(e))return{message:e.message,name:e.name,stack:e.stack,...Up(e)};if(C1(e)){const t={type:e.type,target:zp(e.target),currentTarget:zp(e.currentTarget),...Up(e)};return typeof CustomEvent<"u"&&ba(e,CustomEvent)&&(t.detail=e.detail),t}else return e}function zp(e){try{return $1(e)?M1(e):Object.prototype.toString.call(e)}catch{return"<unknown>"}}function Up(e){if(typeof e=="object"&&e!==null){const t={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t}else return{}}function lD(e,t=40){const r=Object.keys(V_(e));r.sort();const n=r[0];if(!n)return"[object has no keys]";if(n.length>=t)return Bi(n,t);for(let i=r.length;i>0;i--){const s=r.slice(0,i).join(", ");if(!(s.length>t))return i===r.length?s:Bi(s,t)}return""}function Nt(e){return Cl(e,new Map)}function Cl(e,t){if(z1(e)){const r=t.get(e);if(r!==void 0)return r;const n={};t.set(e,n);for(const i of Object.getOwnPropertyNames(e))typeof e[i]<"u"&&(n[i]=Cl(e[i],t));return n}if(Array.isArray(e)){const r=t.get(e);if(r!==void 0)return r;const n=[];return t.set(e,n),e.forEach(i=>{n.push(Cl(i,t))}),n}return e}function z1(e){if(!ju(e))return!1;try{const t=Object.getPrototypeOf(e).constructor.name;return!t||t==="Object"}catch{return!0}}var B_=1e3;function Vu(){return Date.now()/B_}function U1(){const{performance:e}=Tt;if(!e||!e.now)return Vu;const t=Date.now()-e.now(),r=e.timeOrigin==null?t:e.timeOrigin;return()=>(r+e.now())/B_}var Bu=U1(),Ls,uD=(()=>{const{performance:e}=Tt;if(!e||!e.now){Ls="none";return}const t=36e5,r=e.now(),n=Date.now(),i=e.timeOrigin?Math.abs(e.timeOrigin+r-n):t,s=i<t,o=e.timing&&e.timing.navigationStart,a=typeof o=="number"?Math.abs(o+r-n):t;return s||a<t?i<=a?(Ls="timeOrigin",e.timeOrigin):(Ls="navigationStart",o):(Ls="dateNow",n)})();function $r(){const e=Tt,t=e.crypto||e.msCrypto;let r=()=>Math.random()*16;try{if(t&&t.randomUUID)return t.randomUUID().replace(/-/g,"");t&&t.getRandomValues&&(r=()=>{const n=new Uint8Array(1);return t.getRandomValues(n),n[0]})}catch{}return"10000000100040008000100000000000".replace(/[018]/g,n=>(n^(r()&15)>>n/4).toString(16))}function G_(e){return e.exception&&e.exception.values?e.exception.values[0]:void 0}function dD(e){const{message:t,event_id:r}=e;if(t)return t;const n=G_(e);return n?n.type&&n.value?`${n.type}: ${n.value}`:n.type||n.value||r||"<unknown>":r||"<unknown>"}function hD(e,t,r){const n=e.exception=e.exception||{},i=n.values=n.values||[],s=i[0]=i[0]||{};s.value||(s.value=t||""),s.type||(s.type=r||"Error")}function F1(e,t){const r=G_(e);if(!r)return;const n={type:"generic",handled:!0},i=r.mechanism;if(r.mechanism={...n,...i,...t},t&&"data"in t){const s={...i&&i.data,...t.data};r.mechanism.data=s}}function pD(e){if(q1(e))return!0;try{ri(e,"__sentry_captured__",!0)}catch{}return!1}function q1(e){try{return e.__sentry_captured__}catch{}}var nr;(function(e){e[e.PENDING=0]="PENDING";const r=1;e[e.RESOLVED=r]="RESOLVED";const n=2;e[e.REJECTED=n]="REJECTED"})(nr||(nr={}));function fD(e){return new Gu(t=>{t(e)})}function vD(e){return new Gu((t,r)=>{r(e)})}var Gu=class rn{constructor(t){rn.prototype.__init.call(this),rn.prototype.__init2.call(this),rn.prototype.__init3.call(this),rn.prototype.__init4.call(this),this._state=nr.PENDING,this._handlers=[];try{t(this._resolve,this._reject)}catch(r){this._reject(r)}}then(t,r){return new rn((n,i)=>{this._handlers.push([!1,s=>{if(!t)n(s);else try{n(t(s))}catch(o){i(o)}},s=>{if(!r)i(s);else try{n(r(s))}catch(o){i(o)}}]),this._executeHandlers()})}catch(t){return this.then(r=>r,t)}finally(t){return new rn((r,n)=>{let i,s;return this.then(o=>{s=!1,i=o,t&&t()},o=>{s=!0,i=o,t&&t()}).then(()=>{if(s){n(i);return}r(i)})})}__init(){this._resolve=t=>{this._setResult(nr.RESOLVED,t)}}__init2(){this._reject=t=>{this._setResult(nr.REJECTED,t)}}__init3(){this._setResult=(t,r)=>{if(this._state===nr.PENDING){if(Hu(r)){r.then(this._resolve,this._reject);return}this._state=t,this._value=r,this._executeHandlers()}}}__init4(){this._executeHandlers=()=>{if(this._state===nr.PENDING)return;const t=this._handlers.slice();this._handlers=[],t.forEach(r=>{r[0]||(this._state===nr.RESOLVED&&r[1](this._value),this._state===nr.REJECTED&&r[2](this._value),r[0]=!0)})}}};function j1(e){const t=Bu(),r={sid:$r(),init:!0,timestamp:t,started:t,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>V1(r)};return e&&wa(r,e),r}function wa(e,t={}){if(t.user&&(!e.ipAddress&&t.user.ip_address&&(e.ipAddress=t.user.ip_address),!e.did&&!t.did&&(e.did=t.user.id||t.user.email||t.user.username)),e.timestamp=t.timestamp||Bu(),t.abnormal_mechanism&&(e.abnormal_mechanism=t.abnormal_mechanism),t.ignoreDuration&&(e.ignoreDuration=t.ignoreDuration),t.sid&&(e.sid=t.sid.length===32?t.sid:$r()),t.init!==void 0&&(e.init=t.init),!e.did&&t.did&&(e.did=`${t.did}`),typeof t.started=="number"&&(e.started=t.started),e.ignoreDuration)e.duration=void 0;else if(typeof t.duration=="number")e.duration=t.duration;else{const r=e.timestamp-e.started;e.duration=r>=0?r:0}t.release&&(e.release=t.release),t.environment&&(e.environment=t.environment),!e.ipAddress&&t.ipAddress&&(e.ipAddress=t.ipAddress),!e.userAgent&&t.userAgent&&(e.userAgent=t.userAgent),typeof t.errors=="number"&&(e.errors=t.errors),t.status&&(e.status=t.status)}function H1(e,t){let r={};t?r={status:t}:e.status==="ok"&&(r={status:"exited"}),wa(e,r)}function V1(e){return Nt({sid:`${e.sid}`,init:e.init,started:new Date(e.started*1e3).toISOString(),timestamp:new Date(e.timestamp*1e3).toISOString(),status:e.status,errors:e.errors,did:typeof e.did=="number"||typeof e.did=="string"?`${e.did}`:void 0,duration:e.duration,abnormal_mechanism:e.abnormal_mechanism,attrs:{release:e.release,environment:e.environment,ip_address:e.ipAddress,user_agent:e.userAgent}})}function No(){return $r()}function ni(){return $r().substring(16)}function Sa(e,t,r=2){if(!t||typeof t!="object"||r<=0)return t;if(e&&t&&Object.keys(t).length===0)return e;const n={...e};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[i]=Sa(n[i],t[i],r-1));return n}var $l="_sentrySpan";function Fp(e,t){t?ri(e,$l,t):delete e[$l]}function Pl(e){return e[$l]}var B1=100,G1=class W_{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:No(),spanId:ni()}}clone(){const t=new W_;return t._breadcrumbs=[...this._breadcrumbs],t._tags={...this._tags},t._extra={...this._extra},t._contexts={...this._contexts},this._contexts.flags&&(t._contexts.flags={values:[...this._contexts.flags.values]}),t._user=this._user,t._level=this._level,t._session=this._session,t._transactionName=this._transactionName,t._fingerprint=this._fingerprint,t._eventProcessors=[...this._eventProcessors],t._requestSession=this._requestSession,t._attachments=[...this._attachments],t._sdkProcessingMetadata={...this._sdkProcessingMetadata},t._propagationContext={...this._propagationContext},t._client=this._client,t._lastEventId=this._lastEventId,Fp(t,Pl(this)),t}setClient(t){this._client=t}setLastEventId(t){this._lastEventId=t}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(t){this._scopeListeners.push(t)}addEventProcessor(t){return this._eventProcessors.push(t),this}setUser(t){return this._user=t||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&wa(this._session,{user:t}),this._notifyScopeListeners(),this}getUser(){return this._user}getRequestSession(){return this._requestSession}setRequestSession(t){return this._requestSession=t,this}setTags(t){return this._tags={...this._tags,...t},this._notifyScopeListeners(),this}setTag(t,r){return this._tags={...this._tags,[t]:r},this._notifyScopeListeners(),this}setExtras(t){return this._extra={...this._extra,...t},this._notifyScopeListeners(),this}setExtra(t,r){return this._extra={...this._extra,[t]:r},this._notifyScopeListeners(),this}setFingerprint(t){return this._fingerprint=t,this._notifyScopeListeners(),this}setLevel(t){return this._level=t,this._notifyScopeListeners(),this}setTransactionName(t){return this._transactionName=t,this._notifyScopeListeners(),this}setContext(t,r){return r===null?delete this._contexts[t]:this._contexts[t]=r,this._notifyScopeListeners(),this}setSession(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(t){if(!t)return this;const r=typeof t=="function"?t(this):t,[n,i]=r instanceof qr?[r.getScopeData(),r.getRequestSession()]:ju(r)?[t,t.requestSession]:[],{tags:s,extra:o,user:a,contexts:c,level:l,fingerprint:u=[],propagationContext:h}=n||{};return this._tags={...this._tags,...s},this._extra={...this._extra,...o},this._contexts={...this._contexts,...c},a&&Object.keys(a).length&&(this._user=a),l&&(this._level=l),u.length&&(this._fingerprint=u),h&&(this._propagationContext=h),i&&(this._requestSession=i),this}clear(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._session=void 0,Fp(this,void 0),this._attachments=[],this.setPropagationContext({traceId:No()}),this._notifyScopeListeners(),this}addBreadcrumb(t,r){const n=typeof r=="number"?r:B1;if(n<=0)return this;const i={timestamp:Vu(),...t};return this._breadcrumbs.push(i),this._breadcrumbs.length>n&&(this._breadcrumbs=this._breadcrumbs.slice(-n),this._client&&this._client.recordDroppedEvent("buffer_overflow","log_item")),this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(t){return this._attachments.push(t),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:Pl(this)}}setSDKProcessingMetadata(t){return this._sdkProcessingMetadata=Sa(this._sdkProcessingMetadata,t,2),this}setPropagationContext(t){return this._propagationContext={spanId:ni(),...t},this}getPropagationContext(){return this._propagationContext}captureException(t,r){const n=r&&r.event_id?r.event_id:$r();if(!this._client)return dn.warn("No client configured on scope - will not capture exception!"),n;const i=new Error("Sentry syntheticException");return this._client.captureException(t,{originalException:t,syntheticException:i,...r,event_id:n},this),n}captureMessage(t,r,n){const i=n&&n.event_id?n.event_id:$r();if(!this._client)return dn.warn("No client configured on scope - will not capture message!"),i;const s=new Error(t);return this._client.captureMessage(t,r,{originalException:t,syntheticException:s,...n,event_id:i},this),i}captureEvent(t,r){const n=r&&r.event_id?r.event_id:$r();return this._client?(this._client.captureEvent(t,{...r,event_id:n},this),n):(dn.warn("No client configured on scope - will not capture event!"),n)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach(t=>{t(this)}),this._notifyingListeners=!1)}},qr=G1;function W1(){return _a("defaultCurrentScope",()=>new qr)}function Z1(){return _a("defaultIsolationScope",()=>new qr)}var J1=class{constructor(e,t){let r;e?r=e:r=new qr;let n;t?n=t:n=new qr,this._stack=[{scope:r}],this._isolationScope=n}withScope(e){const t=this._pushScope();let r;try{r=e(t)}catch(n){throw this._popScope(),n}return Hu(r)?r.then(n=>(this._popScope(),n),n=>{throw this._popScope(),n}):(this._popScope(),r)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){const e=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:e}),e}_popScope(){return this._stack.length<=1?!1:!!this._stack.pop()}};function ii(){const e=ps(),t=qu(e);return t.stack=t.stack||new J1(W1(),Z1())}function K1(e){return ii().withScope(e)}function Y1(e,t){const r=ii();return r.withScope(()=>(r.getStackTop().scope=e,t(e)))}function qp(e){return ii().withScope(()=>e(ii().getIsolationScope()))}function X1(){return{withIsolationScope:qp,withScope:K1,withSetScope:Y1,withSetIsolationScope:(e,t)=>qp(t),getCurrentScope:()=>ii().getScope(),getIsolationScope:()=>ii().getIsolationScope()}}function Ea(e){const t=qu(e);return t.acs?t.acs:X1()}function Hr(){const e=ps();return Ea(e).getCurrentScope()}function mn(){const e=ps();return Ea(e).getIsolationScope()}function Q1(){return _a("globalScope",()=>new qr)}function gD(...e){const t=ps(),r=Ea(t);if(e.length===2){const[n,i]=e;return n?r.withSetScope(n,i):r.withScope(i)}return r.withScope(e[0])}function fs(){return Hr().getClient()}function mD(e){const{traceId:t,spanId:r,parentSpanId:n}=e.getPropagationContext();return Nt({trace_id:t,span_id:r,parent_span_id:n})}var ex="_sentryMetrics";function tx(e){const t=e[ex];if(!t)return;const r={};for(const[,[n,i]]of t)(r[n]||(r[n]=[])).push(Nt(i));return r}var rx="sentry.source",nx="sentry.sample_rate",ix="sentry.op",sx="sentry.origin",_D="sentry.idle_span_finish_reason",yD="sentry.measurement_unit",bD="sentry.measurement_value",wD="sentry.custom_span_name",SD="sentry.profile_id",ED="sentry.exclusive_time";function ox(e){if(e<400&&e>=100)return{code:1};if(e>=400&&e<500)switch(e){case 401:return{code:2,message:"unauthenticated"};case 403:return{code:2,message:"permission_denied"};case 404:return{code:2,message:"not_found"};case 409:return{code:2,message:"already_exists"};case 413:return{code:2,message:"failed_precondition"};case 429:return{code:2,message:"resource_exhausted"};case 499:return{code:2,message:"cancelled"};default:return{code:2,message:"invalid_argument"}}if(e>=500&&e<600)switch(e){case 501:return{code:2,message:"unimplemented"};case 503:return{code:2,message:"unavailable"};case 504:return{code:2,message:"deadline_exceeded"};default:return{code:2,message:"internal_error"}}return{code:2,message:"unknown_error"}}function kD(e,t){e.setAttribute("http.response.status_code",t);const r=ox(t);r.message!=="unknown_error"&&e.setStatus(r)}var ax="sentry-",cx=/^sentry-/;function Z_(e){const t=lx(e);if(!t)return;const r=Object.entries(t).reduce((n,[i,s])=>{if(i.match(cx)){const o=i.slice(7);n[o]=s}return n},{});if(Object.keys(r).length>0)return r}function RD(e){if(e)return ux(Object.entries(e).reduce((t,[r,n])=>(n&&(t[`${ax}${r}`]=n),t),{}))}function lx(e){if(!(!e||!Do(e)&&!Array.isArray(e)))return Array.isArray(e)?e.reduce((t,r)=>{const n=jp(r);return Object.entries(n).forEach(([i,s])=>{t[i]=s}),t},{}):jp(e)}function jp(e){return e.split(",").map(t=>t.split("=").map(r=>decodeURIComponent(r.trim()))).reduce((t,[r,n])=>(r&&n&&(t[r]=n),t),{})}function ux(e){if(Object.keys(e).length!==0)return Object.entries(e).reduce((t,[r,n],i)=>{const s=`${encodeURIComponent(r)}=${encodeURIComponent(n)}`,o=i===0?s:`${t},${s}`;return o.length>8192?(ya&&dn.warn(`Not adding key: ${r} with val: ${n} to baggage header due to exceeding baggage size limits.`),t):o},"")}var dx=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$");function hx(e){if(!e)return;const t=e.match(dx);if(!t)return;let r;return t[3]==="1"?r=!0:t[3]==="0"&&(r=!1),{traceId:t[1],parentSampled:r,parentSpanId:t[2]}}function AD(e,t){const r=hx(e),n=Z_(t);if(!r||!r.traceId)return{traceId:No(),spanId:ni()};const{traceId:i,parentSpanId:s,parentSampled:o}=r;return{traceId:i,parentSpanId:s,spanId:ni(),sampled:o,dsc:n||{}}}function px(e=No(),t=ni(),r){let n="";return r!==void 0&&(n=r?"-1":"-0"),`${e}-${t}${n}`}var Hp=!1;function ID(e){const{spanId:t,traceId:r}=e.spanContext(),{data:n,op:i,parent_span_id:s,status:o,origin:a}=ka(e);return Nt({parent_span_id:s,span_id:t,trace_id:r,data:n,op:i,status:o,origin:a})}function fx(e){const{spanId:t,traceId:r,isRemote:n}=e.spanContext(),i=n?t:ka(e).parent_span_id,s=n?ni():t;return Nt({parent_span_id:i,span_id:s,trace_id:r})}function TD(e){const{traceId:t,spanId:r}=e.spanContext(),n=Wu(e);return px(t,r,n)}function Vp(e){return typeof e=="number"?Bp(e):Array.isArray(e)?e[0]+e[1]/1e9:e instanceof Date?Bp(e.getTime()):Bu()}function Bp(e){return e>9999999999?e/1e3:e}function ka(e){if(gx(e))return e.getSpanJSON();try{const{spanId:t,traceId:r}=e.spanContext();if(vx(e)){const{attributes:n,startTime:i,name:s,endTime:o,parentSpanId:a,status:c}=e;return Nt({span_id:t,trace_id:r,data:n,description:s,parent_span_id:a,start_timestamp:Vp(i),timestamp:Vp(o)||void 0,status:mx(c),op:n[ix],origin:n[sx],_metrics_summary:tx(e)})}return{span_id:t,trace_id:r}}catch{return{}}}function vx(e){const t=e;return!!t.attributes&&!!t.startTime&&!!t.name&&!!t.endTime&&!!t.status}function gx(e){return typeof e.getSpanJSON=="function"}function Wu(e){const{traceFlags:t}=e.spanContext();return t===1}function mx(e){if(!(!e||e.code===0))return e.code===1?"ok":e.message||"unknown_error"}var hn="_sentryChildSpans",Ol="_sentryRootSpan";function CD(e,t){const r=e[Ol]||e;ri(t,Ol,r),e[hn]?e[hn].add(t):ri(e,hn,new Set([t]))}function $D(e,t){e[hn]&&e[hn].delete(t)}function PD(e){const t=new Set;function r(n){if(!t.has(n)&&Wu(n)){t.add(n);const i=n[hn]?Array.from(n[hn]):[];for(const s of i)r(s)}}return r(e),Array.from(t)}function J_(e){return e[Ol]||e}function OD(){const e=ps(),t=Ea(e);return t.getActiveSpan?t.getActiveSpan():Pl(Hr())}function xD(){Hp||(F_(()=>{console.warn("[Sentry] Deprecation warning: Returning null from `beforeSendSpan` will be disallowed from SDK version 9.0.0 onwards. The callback will only support mutating spans. To drop certain spans, configure the respective integrations directly.")}),Hp=!0)}function _x(e){if(typeof __SENTRY_TRACING__=="boolean"&&!__SENTRY_TRACING__)return!1;const t=fs(),r=e||t&&t.getOptions();return!!r&&(r.enableTracing||"tracesSampleRate"in r||"tracesSampler"in r)}var yx="production",K_="_frozenDsc";function MD(e,t){ri(e,K_,t)}function Y_(e,t){const r=t.getOptions(),{publicKey:n}=t.getDsn()||{},i=Nt({environment:r.environment||"production",release:r.release,public_key:n,trace_id:e});return t.emit("createDsc",i),i}function LD(e,t){const r=t.getPropagationContext();return r.dsc||Y_(r.traceId,e)}function bx(e){const t=fs();if(!t)return{};const r=J_(e),n=r[K_];if(n)return n;const i=r.spanContext().traceState,s=i&&i.get("sentry.dsc"),o=s&&Z_(s);if(o)return o;const a=Y_(e.spanContext().traceId,t),c=ka(r),l=c.data||{},u=l[nx];u!=null&&(a.sample_rate=`${u}`);const h=l[rx],d=c.description;return h!=="url"&&d&&(a.transaction=d),_x()&&(a.sampled=String(Wu(r))),t.emit("createDsc",a,r),a}function wx(){const e=typeof WeakSet=="function",t=e?new WeakSet:[];function r(i){if(e)return t.has(i)?!0:(t.add(i),!1);for(let s=0;s<t.length;s++)if(t[s]===i)return!0;return t.push(i),!1}function n(i){if(e)t.delete(i);else for(let s=0;s<t.length;s++)if(t[s]===i){t.splice(s,1);break}}return[r,n]}function vr(e,t=100,r=1/0){try{return xl("",e,t,r)}catch(n){return{ERROR:`**non-serializable** (${n})`}}}function Sx(e,t=3,r=102400){const n=vr(e,t);return Ax(n)>r?Sx(e,t-1,r):n}function xl(e,t,r=1/0,n=1/0,i=wx()){const[s,o]=i;if(t==null||["boolean","string"].includes(typeof t)||typeof t=="number"&&Number.isFinite(t))return t;const a=Ex(e,t);if(!a.startsWith("[object "))return a;if(t.__sentry_skip_normalization__)return t;const c=typeof t.__sentry_override_normalization_depth__=="number"?t.__sentry_override_normalization_depth__:r;if(c===0)return a.replace("object ","");if(s(t))return"[Circular ~]";const l=t;if(l&&typeof l.toJSON=="function")try{return xl("",l.toJSON(),c-1,n,i)}catch{}const u=Array.isArray(t)?[]:{};let h=0;const d=V_(t);for(const p in d){if(!Object.prototype.hasOwnProperty.call(d,p))continue;if(h>=n){u[p]="[MaxProperties ~]";break}const f=d[p];u[p]=xl(p,f,c-1,n,i),h++}return o(t),u}function Ex(e,t){try{if(e==="domain"&&t&&typeof t=="object"&&t._events)return"[Domain]";if(e==="domainEmitter")return"[DomainEmitter]";if(typeof global<"u"&&t===global)return"[Global]";if(typeof window<"u"&&t===window)return"[Window]";if(typeof document<"u"&&t===document)return"[Document]";if(H_(t))return"[VueViewModel]";if(O1(t))return"[SyntheticEvent]";if(typeof t=="number"&&!Number.isFinite(t))return`[${t}]`;if(typeof t=="function")return`[Function: ${A1(t)}]`;if(typeof t=="symbol")return`[${String(t)}]`;if(typeof t=="bigint")return`[BigInt: ${String(t)}]`;const r=kx(t);return/^HTML(\w*)Element$/.test(r)?`[HTMLElement: ${r}]`:`[object ${r}]`}catch(r){return`**non-serializable** (${r})`}}function kx(e){const t=Object.getPrototypeOf(e);return t?t.constructor.name:"null prototype"}function Rx(e){return~-encodeURI(e).split(/%..|./).length}function Ax(e){return Rx(JSON.stringify(e))}function Ml(e,t,r,n=0){return new Gu((i,s)=>{const o=e[n];if(t===null||typeof o!="function")i(t);else{const a=o({...t},r);w1&&o.id&&a===null&&dn.log(`Event processor "${o.id}" dropped event`),Hu(a)?a.then(c=>Ml(e,c,r,n+1).then(i)).then(null,s):Ml(e,a,r,n+1).then(i).then(null,s)}})}var Ds,Gp,Ns;function Ix(e){const t=Tt._sentryDebugIds;if(!t)return{};const r=Object.keys(t);return Ns&&r.length===Gp||(Gp=r.length,Ns=r.reduce((n,i)=>{Ds||(Ds={});const s=Ds[i];if(s)n[s[0]]=s[1];else{const o=e(i);for(let a=o.length-1;a>=0;a--){const c=o[a],l=c&&c.filename,u=t[i];if(l&&u){n[l]=u,Ds[i]=[l,u];break}}}return n},{})),Ns}function Tx(e,t){const{fingerprint:r,span:n,breadcrumbs:i,sdkProcessingMetadata:s}=t;Cx(e,t),n&&Ox(e,n),xx(e,r),$x(e,i),Px(e,s)}function Wp(e,t){const{extra:r,tags:n,user:i,contexts:s,level:o,sdkProcessingMetadata:a,breadcrumbs:c,fingerprint:l,eventProcessors:u,attachments:h,propagationContext:d,transactionName:p,span:f}=t;zs(e,"extra",r),zs(e,"tags",n),zs(e,"user",i),zs(e,"contexts",s),e.sdkProcessingMetadata=Sa(e.sdkProcessingMetadata,a,2),o&&(e.level=o),p&&(e.transactionName=p),f&&(e.span=f),c.length&&(e.breadcrumbs=[...e.breadcrumbs,...c]),l.length&&(e.fingerprint=[...e.fingerprint,...l]),u.length&&(e.eventProcessors=[...e.eventProcessors,...u]),h.length&&(e.attachments=[...e.attachments,...h]),e.propagationContext={...e.propagationContext,...d}}function zs(e,t,r){e[t]=Sa(e[t],r,1)}function Cx(e,t){const{extra:r,tags:n,user:i,contexts:s,level:o,transactionName:a}=t,c=Nt(r);c&&Object.keys(c).length&&(e.extra={...c,...e.extra});const l=Nt(n);l&&Object.keys(l).length&&(e.tags={...l,...e.tags});const u=Nt(i);u&&Object.keys(u).length&&(e.user={...u,...e.user});const h=Nt(s);h&&Object.keys(h).length&&(e.contexts={...h,...e.contexts}),o&&(e.level=o),a&&e.type!=="transaction"&&(e.transaction=a)}function $x(e,t){const r=[...e.breadcrumbs||[],...t];e.breadcrumbs=r.length?r:void 0}function Px(e,t){e.sdkProcessingMetadata={...e.sdkProcessingMetadata,...t}}function Ox(e,t){e.contexts={trace:fx(t),...e.contexts},e.sdkProcessingMetadata={dynamicSamplingContext:bx(t),...e.sdkProcessingMetadata};const r=J_(t),n=ka(r).description;n&&!e.transaction&&e.type==="transaction"&&(e.transaction=n)}function xx(e,t){e.fingerprint=e.fingerprint?Array.isArray(e.fingerprint)?e.fingerprint:[e.fingerprint]:[],t&&(e.fingerprint=e.fingerprint.concat(t)),e.fingerprint&&!e.fingerprint.length&&delete e.fingerprint}function DD(e,t,r,n,i,s){const{normalizeDepth:o=3,normalizeMaxBreadth:a=1e3}=e,c={...t,event_id:t.event_id||r.event_id||$r(),timestamp:t.timestamp||Vu()},l=r.integrations||e.integrations.map(v=>v.name);Mx(c,e),Nx(c,l),i&&i.emit("applyFrameMetadata",t),t.type===void 0&&Lx(c,e.stackParser);const u=Ux(n,r.captureContext);r.mechanism&&F1(c,r.mechanism);const h=i?i.getEventProcessors():[],d=Q1().getScopeData();if(s){const v=s.getScopeData();Wp(d,v)}if(u){const v=u.getScopeData();Wp(d,v)}const p=[...r.attachments||[],...d.attachments];p.length&&(r.attachments=p),Tx(c,d);const f=[...h,...d.eventProcessors];return Ml(f,c,r).then(v=>(v&&Dx(v),typeof o=="number"&&o>0?zx(v,o,a):v))}function Mx(e,t){const{environment:r,release:n,dist:i,maxValueLength:s=250}=t;e.environment=e.environment||r||"production",!e.release&&n&&(e.release=n),!e.dist&&i&&(e.dist=i),e.message&&(e.message=Bi(e.message,s));const o=e.exception&&e.exception.values&&e.exception.values[0];o&&o.value&&(o.value=Bi(o.value,s));const a=e.request;a&&a.url&&(a.url=Bi(a.url,s))}function Lx(e,t){const r=Ix(t);try{e.exception.values.forEach(n=>{n.stacktrace.frames.forEach(i=>{r&&i.filename&&(i.debug_id=r[i.filename])})})}catch{}}function Dx(e){const t={};try{e.exception.values.forEach(n=>{n.stacktrace.frames.forEach(i=>{i.debug_id&&(i.abs_path?t[i.abs_path]=i.debug_id:i.filename&&(t[i.filename]=i.debug_id),delete i.debug_id)})})}catch{}if(Object.keys(t).length===0)return;e.debug_meta=e.debug_meta||{},e.debug_meta.images=e.debug_meta.images||[];const r=e.debug_meta.images;Object.entries(t).forEach(([n,i])=>{r.push({type:"sourcemap",code_file:n,debug_id:i})})}function Nx(e,t){t.length>0&&(e.sdk=e.sdk||{},e.sdk.integrations=[...e.sdk.integrations||[],...t])}function zx(e,t,r){if(!e)return null;const n={...e,...e.breadcrumbs&&{breadcrumbs:e.breadcrumbs.map(i=>({...i,...i.data&&{data:vr(i.data,t,r)}}))},...e.user&&{user:vr(e.user,t,r)},...e.contexts&&{contexts:vr(e.contexts,t,r)},...e.extra&&{extra:vr(e.extra,t,r)}};return e.contexts&&e.contexts.trace&&n.contexts&&(n.contexts.trace=e.contexts.trace,e.contexts.trace.data&&(n.contexts.trace.data=vr(e.contexts.trace.data,t,r))),e.spans&&(n.spans=e.spans.map(i=>({...i,...i.data&&{data:vr(i.data,t,r)}}))),e.contexts&&e.contexts.flags&&n.contexts&&(n.contexts.flags=vr(e.contexts.flags,3,r)),n}function Ux(e,t){if(!t)return e;const r=e?e.clone():new qr;return r.update(t),r}function Fx(e){if(e)return qx(e)?{captureContext:e}:Hx(e)?{captureContext:e}:e}function qx(e){return e instanceof qr||typeof e=="function"}var jx=["user","level","extra","contexts","tags","fingerprint","requestSession","propagationContext"];function Hx(e){return Object.keys(e).some(t=>jx.includes(t))}function Vx(e,t){return Hr().captureException(e,Fx(t))}function ND(e,t){const r=typeof t=="string"?t:void 0,n=typeof t!="string"?{captureContext:t}:void 0;return Hr().captureMessage(e,r,n)}function zD(e,t){return Hr().captureEvent(e,t)}function UD(e,t){mn().setContext(e,t)}function FD(e,t){mn().setTag(e,t)}function qD(e){mn().setUser(e)}function jD(){const e=fs();return!!e&&e.getOptions().enabled!==!1&&!!e.getTransport()}function HD(e){mn().addEventProcessor(e)}function VD(e){const t=fs(),r=mn(),n=Hr(),{release:i,environment:s=yx}=t&&t.getOptions()||{},{userAgent:o}=Tt.navigator||{},a=j1({release:i,environment:s,user:n.getUser()||r.getUser(),...o&&{userAgent:o},...e}),c=r.getSession();return c&&c.status==="ok"&&wa(c,{status:"exited"}),X_(),r.setSession(a),n.setSession(a),a}function X_(){const e=mn(),t=Hr(),r=t.getSession()||e.getSession();r&&H1(r),Q_(),e.setSession(),t.setSession()}function Q_(){const e=mn(),t=Hr(),r=fs(),n=t.getSession()||e.getSession();n&&r&&r.captureSession(n)}function BD(e=!1){if(e){X_();return}Q_()}function Bx(e){try{if(typeof e!="object"||e===null)return;const t=e.normalized;return OR(t)?t:void 0}catch{return}}function GD(e,t){try{if(!hs()||Uu(e)||Fu(e))return!1;const r=Bx(e)??nA(e),n=tA(r);return n!=="mcpjam"?!1:(ey(e,{...t,extra:{...t.extra??{},slug:r.slug,origin:n}}),!0)}catch{return!1}}var Gx=z_();function Wx(e){if(e instanceof Error)return e;try{return new Error(typeof e=="string"?e:JSON.stringify(e))}catch{return new Error(String(e))}}function ey(e,t){if(Uu(e)||Fu(e))return;const r=b1(Wx(e)),n=N_(r.message);if(n&&t.queryBackend&&(n.convex_backend=t.queryBackend),n&&Gx(n.convex_backend,n.request_id))return;const i=n&&typeof window<"u"?Tl(window.location.href):void 0;try{Vx(r,{level:t.level??"error",tags:{source:t.source,...n},...n?{extra:{boundary:t.extra?.boundary,componentStack:t.extra?.componentStack,page_location:i}}:t.extra?{extra:t.extra}:{}})}catch{}try{hs()&&!Nu()&&RO.captureException(r,{source:t.source,level:t.level??"error",...n?{...n,page_location:i}:t.extra??{}})}catch{}}function WD(e,t,r){ey(e,{source:r?`react_boundary:${r}`:"react_boundary",extra:{componentStack:t?.componentStack??void 0,boundary:r??"unnamed"}})}export{mD as $,Kx as $i,vI as $n,jM as $r,U_ as $t,ka as A,dS as Ai,yT as An,Dv as Ar,M1 as At,SD as B,gy as Bi,HI as Bn,iL as Br,Do as Bt,J_ as C,Ic as Ci,UL as Cn,vL as Cr,N1 as Ct,xD as D,rE as Di,NL as Dn,sA as Dr,iD as Dt,$D as E,CM as Ei,RO as En,OR as Er,Bi as Et,AD as F,cM as Fi,vu as Fn,Ir as Fr,C1 as Ft,ix as G,vy as Gi,AL as Gn,rL as Gr,A1 as Gt,_D as H,tM as Hi,TL as Hn,sL as Hr,ps as Ht,ax as I,my as Ii,Zd as In,aL as Ir,ba as It,rx as J,Qx as Ji,Vd as Jn,eL as Jr,F_ as Jt,sx as K,fy as Ki,xI as Kn,nL as Kr,KL as Kt,RD as L,sM as Li,Jd as Ln,cL as Lr,T1 as Lt,ID as M,n0 as Mi,DL as Mn,kd as Mr,eD as Mt,dx as N,fM as Ni,xL as Nn,Wt as Nr,I1 as Nt,Wu as O,Ac as Oi,qT as On,tA as Or,nD as Ot,px as P,xy as Pi,OL as Pn,tu as Pr,XL as Pt,mn as Q,Jx as Qi,SL as Qn,HM as Qr,Tt as Qt,kD as R,_y as Ri,Wd as Rn,lL as Rr,ju as Rt,OD as S,MM as Si,qL as Sn,pL as Sr,cD as St,mx as T,ze as Ti,$O as Tn,nA as Tr,oD as Tt,yD as U,iM as Ui,jI as Un,oL as Ur,k1 as Ut,wD as V,rM as Vi,$L as Vn,Xk as Vr,Hu as Vt,bD as W,cy as Wi,IL as Wn,tL as Wr,YL as Wt,fs as X,Xx as Xi,EL as Xn,XM as Xr,Lp as Xt,tx as Y,nM as Yi,SI as Yn,QM as Yr,dn as Yt,Hr as Z,oy as Zi,kL as Zn,Hk as Zr,ya as Zt,MD as _,IM as _i,Nu as _n,pA as _r,Bu as _t,zD as a,br as ai,Fu as an,sa as ar,No as at,_x as b,on as bi,KO as bn,aA as br,lD as bt,BD as c,EM as ci,Pp as cn,ia as cr,vD as ct,FD as d,Yr as di,xo as dn,RA as dr,hD as dt,Yx as ea,qM as ei,w1 as en,dI as er,gD as et,qD as f,OM as fi,Oo as fn,De as fr,pD as ft,Sx as g,$M as gi,HL as gn,mL as gr,Vu as gt,vr as h,PM as hi,jL as hn,wA as hr,uD as ht,HD as i,Es as ii,Uu as in,rg as ir,ni as it,TD as j,wM as ji,LL as jn,fR as jr,QL as jt,Vp as k,wS as ki,dg as kn,dL as kr,rD as kt,jD as l,RM as li,BL as ln,yL as lr,fD as lt,DD as m,sE as mi,Rl as mn,Ko as mr,$r as mt,ey as n,yk as ni,JL as nn,aI as nr,Pl as nt,Vx as o,xM as oi,D_ as on,oa as or,wa as ot,VD as p,TM as pi,MO as pn,_L as pr,dD as pt,nx as q,eM as qi,_r as qn,Vk as qr,Mp as qt,GD as r,bk as ri,b1 as rn,bL as rr,Fp as rt,ND as s,kM as si,WL as sn,ca as sr,Gu as st,WD as t,Mc as ti,ZL as tn,wL as tr,Ea as tt,UD as u,Ot as ui,GL as un,Lr as ur,F1 as ut,LD as v,tv as vi,hs as vn,Hc as vr,ri as vt,PD as w,AM as wi,FL as wn,hL as wr,sD as wt,CD as x,md as xi,VL as xn,fL as xr,aD as xt,bx as y,ao as yi,P_ as yn,gL as yr,Nt as yt,ED as z,Sc as zi,WI as zn,Yk as zr,tD as zt};
101
101
 
102
- //# sourceMappingURL=error-reporting-6uZvG5HZ.js.map
102
+ //# sourceMappingURL=error-reporting-DGP36KLx.js.map