@mcpjam/inspector 3.12.0 → 3.12.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{OAuthDesktopReturnNotice-iYC9JwKS.js → OAuthDesktopReturnNotice-BvaAi4cq.js} +2 -2
- package/dist/client/assets/OAuthDesktopReturnNotice-C95FI7VH.css +2 -0
- package/dist/client/assets/{app-bootstrap-CFIJ9N6G.js → app-bootstrap-BW4kwx2v.js} +373 -364
- package/dist/client/assets/{button-BPKzBERq.js → button-DnQ-Tv1N.js} +2 -2
- package/dist/client/assets/{chunk-YOKDWASO-BBgLTb-C.js → chunk-YOKDWASO-D9rkUgct.js} +5 -5
- package/dist/client/assets/{dead-clicks-autocapture-vzk4B4ag.js → dead-clicks-autocapture-DmzB74X1.js} +2 -2
- package/dist/client/assets/{error-reporting-DiPgrWbD.js → error-reporting-C6hkRPpb.js} +1 -1
- package/dist/client/assets/error-reporting-fkIkUpXy.js +102 -0
- package/dist/client/assets/{exception-autocapture-CbirCY_N.js → exception-autocapture-BJuba1BH.js} +2 -2
- package/dist/client/assets/{failed-request-tracker-mpVBJT24.js → failed-request-tracker-Biouu9sg.js} +2 -2
- package/dist/client/assets/{highlighted-body-KPVGNVTW-D71DU577.js → highlighted-body-KPVGNVTW-C5fdYDQ6.js} +2 -2
- package/dist/client/assets/{index-foMfZA46.js → index-DcaDaXoT.js} +3 -3
- package/dist/client/assets/{jszip.min-DP15U89q.js → jszip.min-DbcCjjhc.js} +2 -2
- package/dist/client/assets/{mermaid-HWGCJPDP-GcLzqiVf.js → mermaid-HWGCJPDP-C0opeW_Z.js} +1 -1
- package/dist/client/assets/{posthog-recorder-ChO49lxL.js → posthog-recorder-C0Eve_v2.js} +2 -2
- package/dist/client/assets/{preload-helper-CzPH2rtr.js → preload-helper-6yXzl-We.js} +2 -2
- package/dist/client/assets/{rolldown-runtime-C3dIJScy.js → rolldown-runtime-aO8ZncHb.js} +1 -1
- package/dist/client/assets/{surveys-Cr5c_q1f.js → surveys-CYgi8qEu.js} +2 -2
- package/dist/client/assets/{trace-timeline-D2HsPXC-.js → trace-timeline-BQ5wej-R.js} +39 -39
- package/dist/client/assets/{trace-timeline-CLFYdXi8.js → trace-timeline-BipssVoa.js} +1 -1
- package/dist/client/assets/{web-vitals-CdUasvTy.js → web-vitals-O0au_1Qc.js} +2 -2
- package/dist/client/index.html +7 -7
- package/dist/server/{chunk-RGDNQUHE.js → chunk-KML2Y7FH.js} +2 -2
- package/dist/server/{chunk-KOQ26LF3.js → chunk-PPGJCZNJ.js} +5 -3
- package/dist/server/{consent-lifetime-T4A66FLH.js → consent-lifetime-DYWG3A3P.js} +2 -2
- package/dist/server/harness-install-cli.js +1 -1
- package/dist/server/index.js +46953 -38191
- package/package.json +3 -2
- package/dist/client/assets/OAuthDesktopReturnNotice-BeDakGgb.css +0 -2
- package/dist/client/assets/error-reporting-B2Nfbu05.js +0 -102
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import{t as iy}from"./failed-request-tracker-Biouu9sg.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.2"};var t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5d44395f-285e-4586-bcd3-e2e00cbc9a8e",e._sentryDebugIdIdentifier="sentry-dbid-5d44395f-285e-4586-bcd3-e2e00cbc9a8e")}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(`
|
|
8
|
+
`).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(`
|
|
10
|
+
if (${T}.issues.length) {
|
|
11
|
+
if (${I} in input) {
|
|
12
|
+
payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
|
|
13
|
+
...iss,
|
|
14
|
+
path: iss.path ? [${I}, ...iss.path] : [${I}]
|
|
15
|
+
})));
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
if (${T}.value === undefined) {
|
|
20
|
+
if (${I} in input) {
|
|
21
|
+
newResult[${I}] = undefined;
|
|
22
|
+
}
|
|
23
|
+
} else {
|
|
24
|
+
newResult[${I}] = ${T}.value;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
`):p.write(`
|
|
28
|
+
if (${T}.issues.length) {
|
|
29
|
+
payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
|
|
30
|
+
...iss,
|
|
31
|
+
path: iss.path ? [${I}, ...iss.path] : [${I}]
|
|
32
|
+
})));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (${T}.value === undefined) {
|
|
36
|
+
if (${I} in input) {
|
|
37
|
+
newResult[${I}] = undefined;
|
|
38
|
+
}
|
|
39
|
+
} else {
|
|
40
|
+
newResult[${I}] = ${T}.value;
|
|
41
|
+
}
|
|
42
|
+
|
|
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>
|
|
44
|
+
|
|
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(`
|
|
48
|
+
`)?`
|
|
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!==`
|
|
51
|
+
`&&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)+`
|
|
57
|
+
|
|
58
|
+
`;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(`(^|(?<!
|
|
62
|
+
))
|
|
63
|
+
+(?!
|
|
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?`|
|
|
65
|
+
`:`>
|
|
66
|
+
`;let h,d;for(d=r.length;d>0;--d){const T=r[d-1];if(T!==`
|
|
67
|
+
`&&T!==" "&&T!==" ")break}let p=r.substring(d);const f=p.indexOf(`
|
|
68
|
+
`);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===`
|
|
70
|
+
`)_=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}
|
|
72
|
+
${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=`
|
|
83
|
+
|
|
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?`
|
|
89
|
+
${c}${v}`:`
|
|
90
|
+
`}}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?`
|
|
93
|
+
${s}${i}${v}`:`
|
|
94
|
+
`;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(`
|
|
96
|
+
`):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.17.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.2",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};
|
|
101
|
+
|
|
102
|
+
//# sourceMappingURL=error-reporting-fkIkUpXy.js.map
|