@mcpjam/inspector 3.12.1 → 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-DrCSUffX.js → OAuthDesktopReturnNotice-BvaAi4cq.js} +2 -2
- package/dist/client/assets/OAuthDesktopReturnNotice-C95FI7VH.css +2 -0
- package/dist/client/assets/{app-bootstrap-C0wjVteM.js → app-bootstrap-BW4kwx2v.js} +373 -364
- package/dist/client/assets/{button-DQ9bR46C.js → button-DnQ-Tv1N.js} +2 -2
- package/dist/client/assets/{chunk-YOKDWASO-Cpy4vQY8.js → chunk-YOKDWASO-D9rkUgct.js} +5 -5
- package/dist/client/assets/{dead-clicks-autocapture-D3WNuKsf.js → dead-clicks-autocapture-DmzB74X1.js} +2 -2
- package/dist/client/assets/{error-reporting-DmfwQkBP.js → error-reporting-C6hkRPpb.js} +1 -1
- package/dist/client/assets/error-reporting-fkIkUpXy.js +102 -0
- package/dist/client/assets/{exception-autocapture-D0Qfhhbc.js → exception-autocapture-BJuba1BH.js} +2 -2
- package/dist/client/assets/{failed-request-tracker-DyZB_Nfp.js → failed-request-tracker-Biouu9sg.js} +2 -2
- package/dist/client/assets/{highlighted-body-KPVGNVTW-QEEOJH_y.js → highlighted-body-KPVGNVTW-C5fdYDQ6.js} +2 -2
- package/dist/client/assets/{index-pxVGER4l.js → index-DcaDaXoT.js} +3 -3
- package/dist/client/assets/{jszip.min-DPr4_u5f.js → jszip.min-DbcCjjhc.js} +2 -2
- package/dist/client/assets/{mermaid-HWGCJPDP-DNAzcUbW.js → mermaid-HWGCJPDP-C0opeW_Z.js} +1 -1
- package/dist/client/assets/{posthog-recorder-dQnAa9ak.js → posthog-recorder-C0Eve_v2.js} +2 -2
- package/dist/client/assets/{preload-helper-DsxBH8kv.js → preload-helper-6yXzl-We.js} +2 -2
- package/dist/client/assets/{rolldown-runtime-DeZZUx0l.js → rolldown-runtime-aO8ZncHb.js} +1 -1
- package/dist/client/assets/{surveys-CdlQJ0hc.js → surveys-CYgi8qEu.js} +2 -2
- package/dist/client/assets/{trace-timeline-2WCodaTP.js → trace-timeline-BQ5wej-R.js} +39 -39
- package/dist/client/assets/{trace-timeline-Ix3CoQw4.js → trace-timeline-BipssVoa.js} +1 -1
- package/dist/client/assets/{web-vitals-DdK10Etm.js → web-vitals-O0au_1Qc.js} +2 -2
- package/dist/client/index.html +7 -7
- package/dist/server/{chunk-R5EHY55H.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 +27248 -18501
- package/package.json +2 -2
- package/dist/client/assets/OAuthDesktopReturnNotice-BeDakGgb.css +0 -2
- package/dist/client/assets/error-reporting-BHW3WviX.js +0 -102
|
@@ -1,102 +0,0 @@
|
|
|
1
|
-
import{t as j_}from"./failed-request-tracker-DyZB_Nfp.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.1"};var t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="60e5e38b-510f-4c49-823b-2e88fcb113b3",e._sentryDebugIdIdentifier="sentry-dbid-60e5e38b-510f-4c49-823b-2e88fcb113b3")}catch{}})();var Vt=[],At=[],H_=Uint8Array,wa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var mn=0,V_=wa.length;mn<V_;++mn)Vt[mn]=wa[mn],At[wa.charCodeAt(mn)]=mn;At[45]=62;At[95]=63;function B_(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 G_(e,t,r){return(t+r)*3/4-r}function Js(e){for(var t,r=B_(e),n=r[0],i=r[1],s=new H_(G_(e,n,i)),o=0,a=i>0?n-4:n,c=0;c<a;c+=4)t=At[e.charCodeAt(c)]<<18|At[e.charCodeAt(c+1)]<<12|At[e.charCodeAt(c+2)]<<6|At[e.charCodeAt(c+3)],s[o++]=t>>16&255,s[o++]=t>>8&255,s[o++]=t&255;return i===2&&(t=At[e.charCodeAt(c)]<<2|At[e.charCodeAt(c+1)]>>4,s[o++]=t&255),i===1&&(t=At[e.charCodeAt(c)]<<10|At[e.charCodeAt(c+1)]<<4|At[e.charCodeAt(c+2)]>>2,s[o++]=t>>8&255,s[o++]=t&255),s}function W_(e){return Vt[e>>18&63]+Vt[e>>12&63]+Vt[e>>6&63]+Vt[e&63]}function Z_(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(W_(n));return i.join("")}function Ks(e){for(var t,r=e.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(Z_(e,o,o+s>a?a:o+s));return n===1?(t=e[r-1],i.push(Vt[t>>2]+Vt[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],i.push(Vt[t>>10]+Vt[t>>4&63]+Vt[t<<2&63]+"=")),i.join("")}function dx(e){if(e===void 0)return{};if(!Up(e))throw new Error(`The arguments to a Convex function must be an object. Received: ${e}`);return e}function hx(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 Up(e){const t=typeof e=="object",r=Object.getPrototypeOf(e),n=r===null||r===Object.prototype||r?.constructor?.name==="Object";return t&&n}var Fp=!0,Vn=BigInt("-9223372036854775808"),Pl=BigInt("9223372036854775807"),gc=BigInt("0"),J_=BigInt("8"),K_=BigInt("256"),Sa="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(Sa)}valueOf(){throw new Error(Sa)}toJSON(){throw new Error(Sa)}toString(){return"[unresolved commit timestamp]"}},Y_=new qp;function jp(e){return Number.isNaN(e)||!Number.isFinite(e)||Object.is(e,-0)}function X_(e){e<gc&&(e-=Vn+Vn);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>>=J_;return Ks(r)}function Q_(e){const t=Js(e);if(t.byteLength!==8)throw new Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let r=gc,n=gc;for(const i of t)r+=BigInt(i)*K_**n,n++;return r>Pl&&(r+=Vn+Vn),r}function ey(e){if(e<Vn||Pl<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),Ks(new Uint8Array(t))}function ty(e){const t=Js(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 ry=DataView.prototype.setBigInt64?ey:X_,ny=DataView.prototype.getBigInt64?ty:Q_,qu=1024;function mc(e){if(e.length>qu)throw new Error(`Field name ${e} exceeds maximum field name length ${qu}.`);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 ju(e){if(e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string")return e;if(Array.isArray(e))return e.map(n=>ju(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 Js(e.$bytes).buffer}if(n==="$integer"){if(typeof e.$integer!="string")throw new Error(`Malformed $integer field on ${e}`);return ny(e.$integer)}if(n==="$float"){if(typeof e.$float!="string")throw new Error(`Malformed $float field on ${e}`);const i=Js(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,Fp);if(!jp(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 Y_}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))mc(n),r[n]=ju(i);return r}var iy=16384;function zn(e){const t=JSON.stringify(e,(r,n)=>n===void 0?"undefined":typeof n=="bigint"?`${n.toString()}n`:n);if(t.length>iy){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 Ys(e,t,r,n){if(e===void 0){const o=r&&` (present at path ${r} in original object ${zn(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<Vn||Pl<e)throw new Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);return{$integer:ry(e)}}if(typeof e=="number")if(jp(e)){const o=new ArrayBuffer(8);return new DataView(o).setFloat64(0,e,Fp),{$float:Ks(new Uint8Array(o))}}else return e;if(typeof e=="boolean"||typeof e=="string")return e;if(e instanceof ArrayBuffer)return{$bytes:Ks(new Uint8Array(e))};if(e instanceof qp)return{$commitTs:null};if(Array.isArray(e))return e.map((o,a)=>Ys(o,t,r+`[${a}]`,!1));if(e instanceof Set)throw new Error(Ea(r,"Set",[...e],t));if(e instanceof Map)throw new Error(Ea(r,"Map",[...e],t));if(!Up(e)){const o=e?.constructor?.name,a=o?`${o} `:"";throw new Error(Ea(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?(mc(o),i[o]=Ys(a,t,r+`.${o}`,!1)):n&&(mc(o),i[o]=sy(a,t,r+`.${o}`));return i}function Ea(e,t,r,n){return e?`${t}${zn(r)} is not a supported Convex type (present at path ${e} in original object ${zn(n)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${zn(r)} is not a supported Convex type.`}function sy(e,t,r){if(e===void 0)return{$undefined:null};if(t===void 0)throw new Error(`Programming error. Current value is ${zn(e)} but original value is undefined`);return Ys(e,t,r,!1)}function px(e){return Ys(e,e,"",!1)}var oy=Object.defineProperty,ay=(e,t,r)=>t in e?oy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ka=(e,t,r)=>ay(e,typeof t!="symbol"?t+"":t,r),Hu,Vu,cy=Symbol.for("ConvexError"),ly=class extends(Vu=Error,Hu=cy,Vu){constructor(e){super(typeof e=="string"?e:zn(e)),ka(this,"name","ConvexError"),ka(this,"data"),ka(this,Hu,!0),this.data=e}};function Ol(e){if(!(e instanceof ly))return!1;const t=e.data;return typeof t=="object"&&t!==null&&t.kind==="forbidden"}var Xs;function fx(e){try{Xs=new URL(e).hostname}catch{Xs=void 0}}function _c(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 Ci(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 Hp(e){const t=Ci(e);if(t)return{convex_function:t.functionName,...t.requestId?{request_id:t.requestId}:{},...Xs?{convex_backend:Xs}:{}}}function uy(e){const t=Ci(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 Vp(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 vx(e=500){const t=Vp(e);return(r,n={})=>{try{const i=r.exception?.values,s=i?.find(u=>Ci(u.value??"")),o=Ci(s?.value??"");if(!o)return r;if(Ol(n.originalException))return null;const a=Hp(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=_c((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=Ci(u.value)?.safeMessage??"Query failure cause"),u.stacktrace)for(const h of u.stacktrace.frames??[])delete h.vars;return r.transaction?.includes("/")&&(r.transaction=_c(`https://route.invalid${r.transaction}`)?.replace("https://route.invalid","")),r}catch{return null}}}var dy=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,Bp="8.55.1",It=globalThis;function xo(e,t,r){const n=r||It,i=n.__SENTRY__=n.__SENTRY__||{},s=i[Bp]=i["8.55.1"]||{};return s[e]||(s[e]=t())}var Mo=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,hy="Sentry Logger ",Bu=["debug","info","warn","error","log","assert","trace"],Gu={};function Gp(e){if(!("console"in It))return e();const t=It.console,r={},n=Object.keys(Gu);n.forEach(i=>{const s=Gu[i];r[i]=t[i],t[i]=s});try{return e()}finally{n.forEach(i=>{t[i]=r[i]})}}function py(){let e=!1;const t={enable:()=>{e=!0},disable:()=>{e=!1},isEnabled:()=>e};return Mo?Bu.forEach(r=>{t[r]=(...n)=>{e&&Gp(()=>{It.console[r](`${hy}[${r}]:`,...n)})}}):Bu.forEach(r=>{t[r]=()=>{}}),t}var sn=xo("logger",py),Wp=50;var Wu=/\(error: (.*)\)/,Zu=/captureMessage|captureException/;function fy(...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=Wu.test(c)?c.replace(Wu,"$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>=Wp+i)break}}return vy(s.slice(i))}}function gx(e){return Array.isArray(e)?fy(...e):e}function vy(e){if(!e.length)return[];const t=Array.from(e);return/sentryWrapped/.test(ds(t).function||"")&&t.pop(),t.reverse(),Zu.test(ds(t).function||"")&&(t.pop(),Zu.test(ds(t).function||"")&&t.pop()),t.slice(0,Wp).map(r=>({...r,filename:r.filename||ds(t).filename,function:r.function||"?"}))}function ds(e){return e[e.length-1]||{}}var Ra="<anonymous>";function gy(e){try{return!e||typeof e!="function"?Ra:e.name||Ra}catch{return Ra}}function mx(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 rs(){return xl(It),It}function xl(e){const t=e.__SENTRY__=e.__SENTRY__||{};return t.version=t.version||"8.55.1",t[Bp]=t["8.55.1"]||{}}var Zp=Object.prototype.toString;function my(e){switch(Zp.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return Lo(e,Error)}}function ii(e,t){return Zp.call(e)===`[object ${t}]`}function _x(e){return ii(e,"ErrorEvent")}function yx(e){return ii(e,"DOMError")}function bx(e){return ii(e,"DOMException")}function Qs(e){return ii(e,"String")}function _y(e){return typeof e=="object"&&e!==null&&"__sentry_template_string__"in e&&"__sentry_template_values__"in e}function wx(e){return e===null||_y(e)||typeof e!="object"&&typeof e!="function"}function Ml(e){return ii(e,"Object")}function yy(e){return typeof Event<"u"&&Lo(e,Event)}function by(e){return typeof Element<"u"&&Lo(e,Element)}function wy(e){return ii(e,"RegExp")}function Ll(e){return!!(e&&e.then&&typeof e.then=="function")}function Sy(e){return Ml(e)&&"nativeEvent"in e&&"preventDefault"in e&&"stopPropagation"in e}function Lo(e,t){try{return e instanceof t}catch{return!1}}function Jp(e){return!!(typeof e=="object"&&e!==null&&(e.__isVue||e._isVue))}var Nn=It,Ey=80;function ky(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||Ey;for(;r&&s++<n&&(l=Ry(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 Ry(e,t){const r=e,n=[];if(!r||!r.tagName)return"";if(Nn.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&&Qs(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 Sx(){try{return Nn.document.location.href}catch{return""}}function Ex(e){return Nn.document&&Nn.document.querySelector?Nn.document.querySelector(e):null}function kx(e){if(!Nn.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 $i(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function Rx(e,t){if(!Array.isArray(e))return"";const r=[];for(let n=0;n<e.length;n++){const i=e[n];try{Jp(i)?r.push("[VueViewModel]"):r.push(String(i))}catch{r.push("[value cannot be serialized]")}}return r.join(t)}function Ay(e,t,r=!1){return Qs(e)?wy(t)?t.test(e):Qs(t)?r?e===t:e.includes(t):!1:!1}function Ax(e,t=[],r=!1){return t.some(n=>Ay(e,n,r))}function Tx(e,t,r){if(!(t in e))return;const n=e[t],i=r(n);typeof i=="function"&&Ty(i,n);try{e[t]=i}catch{Mo&&sn.log(`Failed to replace method "${t}" in object`,e)}}function Bn(e,t,r){try{Object.defineProperty(e,t,{value:r,writable:!0,configurable:!0})}catch{Mo&&sn.log(`Failed to add non-enumerable property "${t}" to object`,e)}}function Ty(e,t){try{e.prototype=t.prototype=t.prototype||{},Bn(e,"__sentry_original__",t)}catch{}}function Ix(e){return e.__sentry_original__}function Kp(e){if(my(e))return{message:e.message,name:e.name,stack:e.stack,...Ku(e)};if(yy(e)){const t={type:e.type,target:Ju(e.target),currentTarget:Ju(e.currentTarget),...Ku(e)};return typeof CustomEvent<"u"&&Lo(e,CustomEvent)&&(t.detail=e.detail),t}else return e}function Ju(e){try{return by(e)?ky(e):Object.prototype.toString.call(e)}catch{return"<unknown>"}}function Ku(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 Cx(e,t=40){const r=Object.keys(Kp(e));r.sort();const n=r[0];if(!n)return"[object has no keys]";if(n.length>=t)return $i(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:$i(s,t)}return""}function Dt(e){return yc(e,new Map)}function yc(e,t){if(Iy(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]=yc(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(yc(i,t))}),n}return e}function Iy(e){if(!Ml(e))return!1;try{const t=Object.getPrototypeOf(e).constructor.name;return!t||t==="Object"}catch{return!0}}var Yp=1e3;function Dl(){return Date.now()/Yp}function Cy(){const{performance:e}=It;if(!e||!e.now)return Dl;const t=Date.now()-e.now(),r=e.timeOrigin==null?t:e.timeOrigin;return()=>(r+e.now())/Yp}var zl=Cy(),hs,$x=(()=>{const{performance:e}=It;if(!e||!e.now){hs="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?(hs="timeOrigin",e.timeOrigin):(hs="navigationStart",o):(hs="dateNow",n)})();function Rr(){const e=It,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 Xp(e){return e.exception&&e.exception.values?e.exception.values[0]:void 0}function Px(e){const{message:t,event_id:r}=e;if(t)return t;const n=Xp(e);return n?n.type&&n.value?`${n.type}: ${n.value}`:n.type||n.value||r||"<unknown>":r||"<unknown>"}function Ox(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 $y(e,t){const r=Xp(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 xx(e){if(Py(e))return!0;try{Bn(e,"__sentry_captured__",!0)}catch{}return!1}function Py(e){try{return e.__sentry_captured__}catch{}}var nr;(function(e){e[e.PENDING=0]="PENDING";const r=1;e[e.RESOLVED=r]="RESOLVED";const n=2;e[e.REJECTED=n]="REJECTED"})(nr||(nr={}));function Mx(e){return new Nl(t=>{t(e)})}function Lx(e){return new Nl((t,r)=>{r(e)})}var Nl=class Jr{constructor(t){Jr.prototype.__init.call(this),Jr.prototype.__init2.call(this),Jr.prototype.__init3.call(this),Jr.prototype.__init4.call(this),this._state=nr.PENDING,this._handlers=[];try{t(this._resolve,this._reject)}catch(r){this._reject(r)}}then(t,r){return new Jr((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 Jr((r,n)=>{let i,s;return this.then(o=>{s=!1,i=o,t&&t()},o=>{s=!0,i=o,t&&t()}).then(()=>{if(s){n(i);return}r(i)})})}__init(){this._resolve=t=>{this._setResult(nr.RESOLVED,t)}}__init2(){this._reject=t=>{this._setResult(nr.REJECTED,t)}}__init3(){this._setResult=(t,r)=>{if(this._state===nr.PENDING){if(Ll(r)){r.then(this._resolve,this._reject);return}this._state=t,this._value=r,this._executeHandlers()}}}__init4(){this._executeHandlers=()=>{if(this._state===nr.PENDING)return;const t=this._handlers.slice();this._handlers=[],t.forEach(r=>{r[0]||(this._state===nr.RESOLVED&&r[1](this._value),this._state===nr.REJECTED&&r[2](this._value),r[0]=!0)})}}};function Oy(e){const t=zl(),r={sid:Rr(),init:!0,timestamp:t,started:t,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>My(r)};return e&&Do(r,e),r}function Do(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||zl(),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:Rr()),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 xy(e,t){let r={};t?r={status:t}:e.status==="ok"&&(r={status:"exited"}),Do(e,r)}function My(e){return Dt({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 eo(){return Rr()}function Gn(){return Rr().substring(16)}function zo(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]=zo(n[i],t[i],r-1));return n}var bc="_sentrySpan";function Yu(e,t){t?Bn(e,bc,t):delete e[bc]}function wc(e){return e[bc]}var Ly=100,Dy=class Qp{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:eo(),spanId:Gn()}}clone(){const t=new Qp;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,Yu(t,wc(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&&Do(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 $r?[r.getScopeData(),r.getRequestSession()]:Ml(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,Yu(this,void 0),this._attachments=[],this.setPropagationContext({traceId:eo()}),this._notifyScopeListeners(),this}addBreadcrumb(t,r){const n=typeof r=="number"?r:Ly;if(n<=0)return this;const i={timestamp:Dl(),...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:wc(this)}}setSDKProcessingMetadata(t){return this._sdkProcessingMetadata=zo(this._sdkProcessingMetadata,t,2),this}setPropagationContext(t){return this._propagationContext={spanId:Gn(),...t},this}getPropagationContext(){return this._propagationContext}captureException(t,r){const n=r&&r.event_id?r.event_id:Rr();if(!this._client)return sn.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:Rr();if(!this._client)return sn.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:Rr();return this._client?(this._client.captureEvent(t,{...r,event_id:n},this),n):(sn.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)}},$r=Dy;function zy(){return xo("defaultCurrentScope",()=>new $r)}function Ny(){return xo("defaultIsolationScope",()=>new $r)}var Uy=class{constructor(e,t){let r;e?r=e:r=new $r;let n;t?n=t:n=new $r,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 Ll(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 Wn(){const e=rs(),t=xl(e);return t.stack=t.stack||new Uy(zy(),Ny())}function Fy(e){return Wn().withScope(e)}function qy(e,t){const r=Wn();return r.withScope(()=>(r.getStackTop().scope=e,t(e)))}function Xu(e){return Wn().withScope(()=>e(Wn().getIsolationScope()))}function jy(){return{withIsolationScope:Xu,withScope:Fy,withSetScope:qy,withSetIsolationScope:(e,t)=>Xu(t),getCurrentScope:()=>Wn().getScope(),getIsolationScope:()=>Wn().getIsolationScope()}}function No(e){const t=xl(e);return t.acs?t.acs:jy()}function qr(){const e=rs();return No(e).getCurrentScope()}function vn(){const e=rs();return No(e).getIsolationScope()}function Hy(){return xo("globalScope",()=>new $r)}function Dx(...e){const t=rs(),r=No(t);if(e.length===2){const[n,i]=e;return n?r.withSetScope(n,i):r.withScope(i)}return r.withScope(e[0])}function ns(){return qr().getClient()}function zx(e){const{traceId:t,spanId:r,parentSpanId:n}=e.getPropagationContext();return Dt({trace_id:t,span_id:r,parent_span_id:n})}var Vy="_sentryMetrics";function By(e){const t=e[Vy];if(!t)return;const r={};for(const[,[n,i]]of t)(r[n]||(r[n]=[])).push(Dt(i));return r}var Gy="sentry.source",Wy="sentry.sample_rate",Zy="sentry.op",Jy="sentry.origin",Nx="sentry.idle_span_finish_reason",Ux="sentry.measurement_unit",Fx="sentry.measurement_value",qx="sentry.custom_span_name",jx="sentry.profile_id",Hx="sentry.exclusive_time";function Ky(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 Vx(e,t){e.setAttribute("http.response.status_code",t);const r=Ky(t);r.message!=="unknown_error"&&e.setStatus(r)}var Yy="sentry-",Xy=/^sentry-/;function ef(e){const t=Qy(e);if(!t)return;const r=Object.entries(t).reduce((n,[i,s])=>{if(i.match(Xy)){const o=i.slice(7);n[o]=s}return n},{});if(Object.keys(r).length>0)return r}function Bx(e){if(e)return e0(Object.entries(e).reduce((t,[r,n])=>(n&&(t[`${Yy}${r}`]=n),t),{}))}function Qy(e){if(!(!e||!Qs(e)&&!Array.isArray(e)))return Array.isArray(e)?e.reduce((t,r)=>{const n=Qu(r);return Object.entries(n).forEach(([i,s])=>{t[i]=s}),t},{}):Qu(e)}function Qu(e){return e.split(",").map(t=>t.split("=").map(r=>decodeURIComponent(r.trim()))).reduce((t,[r,n])=>(r&&n&&(t[r]=n),t),{})}function e0(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?(Mo&&sn.warn(`Not adding key: ${r} with val: ${n} to baggage header due to exceeding baggage size limits.`),t):o},"")}var t0=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$");function r0(e){if(!e)return;const t=e.match(t0);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 Gx(e,t){const r=r0(e),n=ef(t);if(!r||!r.traceId)return{traceId:eo(),spanId:Gn()};const{traceId:i,parentSpanId:s,parentSampled:o}=r;return{traceId:i,parentSpanId:s,spanId:Gn(),sampled:o,dsc:n||{}}}function n0(e=eo(),t=Gn(),r){let n="";return r!==void 0&&(n=r?"-1":"-0"),`${e}-${t}${n}`}var ed=!1;function Wx(e){const{spanId:t,traceId:r}=e.spanContext(),{data:n,op:i,parent_span_id:s,status:o,origin:a}=Uo(e);return Dt({parent_span_id:s,span_id:t,trace_id:r,data:n,op:i,status:o,origin:a})}function i0(e){const{spanId:t,traceId:r,isRemote:n}=e.spanContext(),i=n?t:Uo(e).parent_span_id,s=n?Gn():t;return Dt({parent_span_id:i,span_id:s,trace_id:r})}function Zx(e){const{traceId:t,spanId:r}=e.spanContext(),n=Ul(e);return n0(t,r,n)}function td(e){return typeof e=="number"?rd(e):Array.isArray(e)?e[0]+e[1]/1e9:e instanceof Date?rd(e.getTime()):zl()}function rd(e){return e>9999999999?e/1e3:e}function Uo(e){if(o0(e))return e.getSpanJSON();try{const{spanId:t,traceId:r}=e.spanContext();if(s0(e)){const{attributes:n,startTime:i,name:s,endTime:o,parentSpanId:a,status:c}=e;return Dt({span_id:t,trace_id:r,data:n,description:s,parent_span_id:a,start_timestamp:td(i),timestamp:td(o)||void 0,status:a0(c),op:n[Zy],origin:n[Jy],_metrics_summary:By(e)})}return{span_id:t,trace_id:r}}catch{return{}}}function s0(e){const t=e;return!!t.attributes&&!!t.startTime&&!!t.name&&!!t.endTime&&!!t.status}function o0(e){return typeof e.getSpanJSON=="function"}function Ul(e){const{traceFlags:t}=e.spanContext();return t===1}function a0(e){if(!(!e||e.code===0))return e.code===1?"ok":e.message||"unknown_error"}var on="_sentryChildSpans",Sc="_sentryRootSpan";function Jx(e,t){const r=e[Sc]||e;Bn(t,Sc,r),e[on]?e[on].add(t):Bn(e,on,new Set([t]))}function Kx(e,t){e[on]&&e[on].delete(t)}function Yx(e){const t=new Set;function r(n){if(!t.has(n)&&Ul(n)){t.add(n);const i=n[on]?Array.from(n[on]):[];for(const s of i)r(s)}}return r(e),Array.from(t)}function tf(e){return e[Sc]||e}function Xx(){const e=rs(),t=No(e);return t.getActiveSpan?t.getActiveSpan():wc(qr())}function Qx(){ed||(Gp(()=>{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.")}),ed=!0)}function c0(e){if(typeof __SENTRY_TRACING__=="boolean"&&!__SENTRY_TRACING__)return!1;const t=ns(),r=e||t&&t.getOptions();return!!r&&(r.enableTracing||"tracesSampleRate"in r||"tracesSampler"in r)}var l0="production",rf="_frozenDsc";function eM(e,t){Bn(e,rf,t)}function nf(e,t){const r=t.getOptions(),{publicKey:n}=t.getDsn()||{},i=Dt({environment:r.environment||"production",release:r.release,public_key:n,trace_id:e});return t.emit("createDsc",i),i}function tM(e,t){const r=t.getPropagationContext();return r.dsc||nf(r.traceId,e)}function u0(e){const t=ns();if(!t)return{};const r=tf(e),n=r[rf];if(n)return n;const i=r.spanContext().traceState,s=i&&i.get("sentry.dsc"),o=s&&ef(s);if(o)return o;const a=nf(e.spanContext().traceId,t),c=Uo(r),l=c.data||{},u=l[Wy];u!=null&&(a.sample_rate=`${u}`);const h=l[Gy],d=c.description;return h!=="url"&&d&&(a.transaction=d),c0()&&(a.sampled=String(Ul(r))),t.emit("createDsc",a,r),a}function d0(){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 hr(e,t=100,r=1/0){try{return Ec("",e,t,r)}catch(n){return{ERROR:`**non-serializable** (${n})`}}}function h0(e,t=3,r=102400){const n=hr(e,t);return g0(n)>r?h0(e,t-1,r):n}function Ec(e,t,r=1/0,n=1/0,i=d0()){const[s,o]=i;if(t==null||["boolean","string"].includes(typeof t)||typeof t=="number"&&Number.isFinite(t))return t;const a=p0(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 Ec("",l.toJSON(),c-1,n,i)}catch{}const u=Array.isArray(t)?[]:{};let h=0;const d=Kp(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]=Ec(p,f,c-1,n,i),h++}return o(t),u}function p0(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(Jp(t))return"[VueViewModel]";if(Sy(t))return"[SyntheticEvent]";if(typeof t=="number"&&!Number.isFinite(t))return`[${t}]`;if(typeof t=="function")return`[Function: ${gy(t)}]`;if(typeof t=="symbol")return`[${String(t)}]`;if(typeof t=="bigint")return`[BigInt: ${String(t)}]`;const r=f0(t);return/^HTML(\w*)Element$/.test(r)?`[HTMLElement: ${r}]`:`[object ${r}]`}catch(r){return`**non-serializable** (${r})`}}function f0(e){const t=Object.getPrototypeOf(e);return t?t.constructor.name:"null prototype"}function v0(e){return~-encodeURI(e).split(/%..|./).length}function g0(e){return v0(JSON.stringify(e))}function kc(e,t,r,n=0){return new Nl((i,s)=>{const o=e[n];if(t===null||typeof o!="function")i(t);else{const a=o({...t},r);dy&&o.id&&a===null&&sn.log(`Event processor "${o.id}" dropped event`),Ll(a)?a.then(c=>kc(e,c,r,n+1).then(i)).then(null,s):kc(e,a,r,n+1).then(i).then(null,s)}})}var ps,nd,fs;function m0(e){const t=It._sentryDebugIds;if(!t)return{};const r=Object.keys(t);return fs&&r.length===nd||(nd=r.length,fs=r.reduce((n,i)=>{ps||(ps={});const s=ps[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,ps[i]=[l,u];break}}}return n},{})),fs}function _0(e,t){const{fingerprint:r,span:n,breadcrumbs:i,sdkProcessingMetadata:s}=t;y0(e,t),n&&S0(e,n),E0(e,r),b0(e,i),w0(e,s)}function id(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;vs(e,"extra",r),vs(e,"tags",n),vs(e,"user",i),vs(e,"contexts",s),e.sdkProcessingMetadata=zo(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 vs(e,t,r){e[t]=zo(e[t],r,1)}function y0(e,t){const{extra:r,tags:n,user:i,contexts:s,level:o,transactionName:a}=t,c=Dt(r);c&&Object.keys(c).length&&(e.extra={...c,...e.extra});const l=Dt(n);l&&Object.keys(l).length&&(e.tags={...l,...e.tags});const u=Dt(i);u&&Object.keys(u).length&&(e.user={...u,...e.user});const h=Dt(s);h&&Object.keys(h).length&&(e.contexts={...h,...e.contexts}),o&&(e.level=o),a&&e.type!=="transaction"&&(e.transaction=a)}function b0(e,t){const r=[...e.breadcrumbs||[],...t];e.breadcrumbs=r.length?r:void 0}function w0(e,t){e.sdkProcessingMetadata={...e.sdkProcessingMetadata,...t}}function S0(e,t){e.contexts={trace:i0(t),...e.contexts},e.sdkProcessingMetadata={dynamicSamplingContext:u0(t),...e.sdkProcessingMetadata};const r=tf(t),n=Uo(r).description;n&&!e.transaction&&e.type==="transaction"&&(e.transaction=n)}function E0(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 rM(e,t,r,n,i,s){const{normalizeDepth:o=3,normalizeMaxBreadth:a=1e3}=e,c={...t,event_id:t.event_id||r.event_id||Rr(),timestamp:t.timestamp||Dl()},l=r.integrations||e.integrations.map(v=>v.name);k0(c,e),T0(c,l),i&&i.emit("applyFrameMetadata",t),t.type===void 0&&R0(c,e.stackParser);const u=C0(n,r.captureContext);r.mechanism&&$y(c,r.mechanism);const h=i?i.getEventProcessors():[],d=Hy().getScopeData();if(s){const v=s.getScopeData();id(d,v)}if(u){const v=u.getScopeData();id(d,v)}const p=[...r.attachments||[],...d.attachments];p.length&&(r.attachments=p),_0(c,d);const f=[...h,...d.eventProcessors];return kc(f,c,r).then(v=>(v&&A0(v),typeof o=="number"&&o>0?I0(v,o,a):v))}function k0(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=$i(e.message,s));const o=e.exception&&e.exception.values&&e.exception.values[0];o&&o.value&&(o.value=$i(o.value,s));const a=e.request;a&&a.url&&(a.url=$i(a.url,s))}function R0(e,t){const r=m0(t);try{e.exception.values.forEach(n=>{n.stacktrace.frames.forEach(i=>{r&&i.filename&&(i.debug_id=r[i.filename])})})}catch{}}function A0(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 T0(e,t){t.length>0&&(e.sdk=e.sdk||{},e.sdk.integrations=[...e.sdk.integrations||[],...t])}function I0(e,t,r){if(!e)return null;const n={...e,...e.breadcrumbs&&{breadcrumbs:e.breadcrumbs.map(i=>({...i,...i.data&&{data:hr(i.data,t,r)}}))},...e.user&&{user:hr(e.user,t,r)},...e.contexts&&{contexts:hr(e.contexts,t,r)},...e.extra&&{extra:hr(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=hr(e.contexts.trace.data,t,r))),e.spans&&(n.spans=e.spans.map(i=>({...i,...i.data&&{data:hr(i.data,t,r)}}))),e.contexts&&e.contexts.flags&&n.contexts&&(n.contexts.flags=hr(e.contexts.flags,3,r)),n}function C0(e,t){if(!t)return e;const r=e?e.clone():new $r;return r.update(t),r}function $0(e){if(e)return P0(e)?{captureContext:e}:x0(e)?{captureContext:e}:e}function P0(e){return e instanceof $r||typeof e=="function"}var O0=["user","level","extra","contexts","tags","fingerprint","requestSession","propagationContext"];function x0(e){return Object.keys(e).some(t=>O0.includes(t))}function M0(e,t){return qr().captureException(e,$0(t))}function nM(e,t){const r=typeof t=="string"?t:void 0,n=typeof t!="string"?{captureContext:t}:void 0;return qr().captureMessage(e,r,n)}function iM(e,t){return qr().captureEvent(e,t)}function sM(e,t){vn().setContext(e,t)}function oM(e,t){vn().setTag(e,t)}function aM(e){vn().setUser(e)}function cM(){const e=ns();return!!e&&e.getOptions().enabled!==!1&&!!e.getTransport()}function lM(e){vn().addEventProcessor(e)}function uM(e){const t=ns(),r=vn(),n=qr(),{release:i,environment:s=l0}=t&&t.getOptions()||{},{userAgent:o}=It.navigator||{},a=Oy({release:i,environment:s,user:n.getUser()||r.getUser(),...o&&{userAgent:o},...e}),c=r.getSession();return c&&c.status==="ok"&&Do(c,{status:"exited"}),sf(),r.setSession(a),n.setSession(a),a}function sf(){const e=vn(),t=qr(),r=t.getSession()||e.getSession();r&&xy(r),of(),e.setSession(),t.setSession()}function of(){const e=vn(),t=qr(),r=ns(),n=t.getSession()||e.getSession();n&&r&&r.captureSession(n)}function dM(e=!1){if(e){sf();return}of()}var A="u">typeof window?window:void 0,lt="u">typeof globalThis?globalThis:A,rt=lt?.navigator,z=lt?.document,He=lt?.location,Vi=lt?.fetch,Fl=lt?.XMLHttpRequest&&"withCredentials"in new lt.XMLHttpRequest?lt.XMLHttpRequest:void 0,sd=lt?.AbortController,L0=lt?.CompressionStream,pt=rt?.userAgent;function af(){return!(!A||A.navigator.onLine===!1)}var ui=typeof globalThis<"u"?globalThis:A;ui&&typeof self>"u"&&(ui.self=ui),ui&&typeof File>"u"&&(ui.File=function(){});var te=A??{},od="0.9.0",ar={DEBUG:!1,LIB_VERSION:od,LIB_NAME:"browser-common",JS_SDK_VERSION:od},jt=(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})({}),Rc=(function(e){return e.GZipJS="gzip-js",e.Base64="base64",e})({}),D0=["$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"],z0=["token"];function ue(e,t){return e.indexOf(t)!==-1}var Fo=function(e){return e.trim()},Ac=function(e){return e.replace(/^\$/,"")};function cf(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 lf=Object.prototype,ql=lf.hasOwnProperty,qo=lf.toString,ce=Array.isArray||function(e){return qo.call(e)==="[object Array]"},tt=e=>typeof e=="function",be=e=>e===Object(e)&&!ce(e),mt=e=>{if(be(e)){for(const t in e)if(ql.call(e,t))return!1;return!0}return!1},O=e=>e===void 0,ye=e=>qo.call(e)=="[object String]",Pi=e=>ye(e)&&e.trim().length===0,Ve=e=>e===null,fe=e=>O(e)||Ve(e),Ze=e=>qo.call(e)=="[object Number]"&&e==e,Qt=e=>Ze(e)&&e>0,vt=e=>qo.call(e)==="[object Boolean]",N0=e=>ue(D0,e),U0=e=>ue(z0,e);function uf(e){return e===null||typeof e!="object"}function to(e,t){return{}.toString.call(e)===`[object ${t}]`}function si(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 df(e,Error)}}function jl(e){return"u">typeof Event&&df(e,Event)}function df(e,t){try{return e instanceof t}catch{return!1}}var F0=[!0,"true",1,"1","yes"],Aa=e=>ue(F0,e),q0=[!1,"false",0,"0","no"];function ad(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){ad(s,n,i,o,a,"next",c)}function a(c){ad(s,n,i,o,a,"throw",c)}o(void 0)})}}var j0=["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"],cd=function(e,t=[]){if(!e)return!1;const r=e.toLowerCase();return j0.concat(t).some(n=>{const i=n.toLowerCase();return r.indexOf(i)!==-1})};function Bt(e,t,r,n,i){return t>r&&(n.warn("min cannot be greater than max."),t=r),Ze(e)?e>r?(n.warn(" cannot be greater than max: "+r+". Using max value instead."),r):t>e?(n.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(n.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+i),Bt(i??r,t,r,n))}var H0=class{constructor(e){this.C={},this.I=e.I,this.R=Bt(e.bucketSize,0,100,e.$),this.A=Bt(e.refillRate,0,this.R,e.$),this.O=Bt(e.refillInterval,0,864e5,e.$)}F(e,t){const r=Math.floor((t-e.lastAccess)/this.O);r>0&&(e.tokens=Math.min(e.tokens+r*this.A,this.R),e.lastAccess=e.lastAccess+r*this.O)}consumeRateLimit(e){var t;const r=Date.now(),n=String(e);let i=this.C[n];return i?this.F(i,r):(i={tokens:this.R,lastAccess:r},this.C[n]=i),i.tokens===0||(i.tokens--,i.tokens===0&&((t=this.I)===null||t===void 0||t.call(this,e)),i.tokens===0)}stop(){this.C={}}},Zn="Mobile",Bi="Android",ro="Tablet",hf="Android Tablet",pf="iPad",ff="Apple Watch",Ls="Safari",jo="BlackBerry",vf="Samsung Internet",Ds="Chrome",gf="Chrome iOS",mf="Internet Explorer",_f="Internet Explorer Mobile",yf="Opera",bf="Microsoft Edge",zs="Firefox",wf="Firefox iOS",no="Nintendo",io="PlayStation",Ho="Xbox",Sf="Android Mobile",Ef="Mobile Safari",Ta="Windows",kf="Windows Phone",ld="Nokia",Tc="Ouya",V0="Generic "+Zn.toLowerCase(),Rf="Generic "+ro.toLowerCase(),Ic="Konqueror",Af="Oculus Browser",Tf="Vivaldi",If="Yandex",Cf="Whale",$f="DuckDuckGo",Pf="Pale Moon",Of="Waterfox",Cc="Brave",xf="Claude",Mf="Codex",Lf="ChatGPT",Df="Google Search App",Ia=new RegExp("Version/(\\d+(\\.\\d+)?)"),Ca=new RegExp("(Claude|Codex|ChatGPT)\\/(\\d+(\\.\\d+)?)"),B0=new RegExp(Ho,"i"),G0=new RegExp("PlayStation \\w+","i"),W0=new RegExp("Nintendo \\w+","i"),Hl=new RegExp("BlackBerry|PlayBook|BB10","i"),Z0={"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"},zf=function(e,t,r,n){return t=t||"",(function(i){return i?.brave?Cc:null})(r)||(n?.detectGoogleSearchApp&&ue(e,"GSA/")?Df:ue(e," OPR/")&&ue(e,"Mini")?"Opera Mini":ue(e," OPR/")?yf:Hl.test(e)?jo:ue(e,"IEMobile")||ue(e,"WPDesktop")?_f:ue(e,"OculusBrowser")?Af:ue(e,"SamsungBrowser")?vf:ue(e,"Edge")||ue(e,"Edg/")?bf:ue(e,"Vivaldi/")?Tf:ue(e,"YaBrowser/")?If:ue(e,"Whale/")?Cf:ue(e,"DuckDuckGo/")||ue(e,"Ddg/")?$f:ue(e,"Claude/")?xf:ue(e,"Codex/")?Mf:ue(e,"ChatGPT/")?Lf:ue(e,"FBIOS")?"Facebook Mobile":ue(e,"UCWEB")||ue(e,"UCBrowser")?"UC Browser":ue(e,"CriOS")?gf:ue(e,"CrMo")||ue(e,Ds)?Ds:ue(e,Bi)&&ue(e,Ls)?Sf:ue(e,"FxiOS")?wf:ue(e.toLowerCase(),Ic.toLowerCase())?Ic:ue(e,"Brave/")?Cc:((i,s)=>s&&ue(s,"Apple")||(function(o){return ue(o,Ls)&&!ue(o,Ds)&&!ue(o,Bi)})(i))(e,t)?ue(e,Zn)?Ef:Ls:ue(e,"PaleMoon/")?Pf:ue(e,"Waterfox/")?Of:ue(e,zs)?zs:ue(e,"MSIE")||ue(e,"Trident/")?mf:ue(e,"Gecko")?zs:"")},J0={[_f]:[new RegExp("rv:(\\d+(\\.\\d+)?)")],[bf]:[new RegExp("Edge?\\/(\\d+(\\.\\d+)?)")],[Ds]:[new RegExp("(Chrome|CrMo)\\/(\\d+(\\.\\d+)?)")],[gf]:[new RegExp("CriOS\\/(\\d+(\\.\\d+)?)")],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/(\\d+(\\.\\d+)?)")],[Ls]:[Ia],[Ef]:[Ia],[yf]:[new RegExp("(Opera|OPR)\\/(\\d+(\\.\\d+)?)")],[zs]:[new RegExp("Firefox\\/(\\d+(\\.\\d+)?)")],[wf]:[new RegExp("FxiOS\\/(\\d+(\\.\\d+)?)")],[Ic]:[new RegExp("Konqueror[:/]?(\\d+(\\.\\d+)?)","i")],[jo]:[new RegExp("BlackBerry (\\d+(\\.\\d+)?)"),Ia],[Sf]:[new RegExp("android\\s(\\d+(\\.\\d+)?)","i")],[vf]:[new RegExp("SamsungBrowser\\/(\\d+(\\.\\d+)?)")],[Af]:[new RegExp("OculusBrowser\\/(\\d+(\\.\\d+)?)")],[Tf]:[new RegExp("Vivaldi\\/(\\d+(\\.\\d+)?)")],[If]:[new RegExp("YaBrowser\\/(\\d+(\\.\\d+)?)")],[Cf]:[new RegExp("Whale\\/(\\d+(\\.\\d+)?)")],[Cc]:[new RegExp("Brave\\/(\\d+(\\.\\d+)?)")],[xf]:[Ca],[Mf]:[Ca],[Lf]:[Ca],[$f]:[new RegExp("(DuckDuckGo|Ddg)\\/(\\d+(\\.\\d+)?)")],[Pf]:[new RegExp("PaleMoon\\/(\\d+(\\.\\d+)?)")],[Of]:[new RegExp("Waterfox\\/(\\d+(\\.\\d+)?)")],[Df]:[new RegExp("GSA\\/(\\d+(\\.\\d+)?)")],[mf]:[new RegExp("(rv:|MSIE )(\\d+(\\.\\d+)?)")],Mozilla:[new RegExp("rv:(\\d+(\\.\\d+)?)")]},K0=function(e,t,r,n){const i=zf(e,t,r,n),s=J0[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},ud=[[new RegExp("Xbox; Xbox (.*?)[);]","i"),e=>[Ho,e&&e[1]||""]],[new RegExp(no,"i"),[no,""]],[new RegExp(io,"i"),[io,""]],[Hl,[jo,""]],[new RegExp(Ta,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[kf,""];if(new RegExp(Zn).test(t)&&!/IEMobile\b/.test(t))return["Windows Mobile",""];const r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=Z0[r[1]]||"";return/arm/i.test(t)&&(n="RT"),[Ta,n]}return[Ta,""]}],[/((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]?[Bi,[e[2],e[3],e[4]||"0"].join(".")]:[Bi,""]],[/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",""]]],Nf=function(e){for(let t=0;ud.length>t;t++){const[r,n]=ud[t],i=r.exec(e),s=i&&(tt(n)?n(i,e):n);if(s)return s}return["",""]},Uf=function(e){return W0.test(e)?no:G0.test(e)?io:B0.test(e)?Ho:new RegExp(Tc,"i").test(e)?Tc:new RegExp("(Windows Phone|WPDesktop)","i").test(e)?kf:/iPad/.test(e)?pf:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?ff:Hl.test(e)?jo:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(ld,"i").test(e)?ld:/(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(Zn).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)?Bi:hf:new RegExp("(pda|Mobile)","i").test(e)?V0:new RegExp(ro,"i").test(e)&&!new RegExp("Tablet pc","i").test(e)?Rf:""},Y0=function(e,t){var r;const n=Uf(e);return n===pf||n===hf||n==="Kobo"||n==="Kindle Fire"||n===Rf?ro:n===no||n===Ho||n===io||n===Tc?"Console":n===ff?"Wearable":n?Zn: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)?Zn:ro:"Desktop";var i,s,o},$a=/\bFBAV\/(\d+(?:\.\d+)*)/i,dd=[[/\bInstagram(?:[ /](\d+(?:\.\d+)*))?\b/i,"Instagram"],[/\bBarcelona[ /](\d+(?:\.\d+)*)?/i,"Threads"],[/\b(?:MessengerForiOS|(?:FBAN|FB_IAB)\/Orca-Android)\b/i,"Messenger",$a],[/\bFBAN\/EMA\b/i,"Facebook Lite",$a],[/\b(?:FBIOS|(?:FBAN|FB_IAB)\/(?:FB4A|FBIOS))\b/i,"Facebook",$a],[/\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"]],$c="[Truncated]",is="[Unserializable]";function Un(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 Ff(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=is}Object.defineProperty(e,n,{value:i,enumerable:!0,writable:!0,configurable:!0})}return e}var Ns=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,Ns);if(!t)return this.ts=r,void(this.es=r+n);this.es=Math.max(this.es,Math.min(r+n,this.ts+Ns))}remainingMs(){const e=Date.now();if(this.ts-5e3>e)return this.reset(),0;const t=Math.min(Ns,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}},X0=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function hd(e,t){return typeof(r=e)=="string"&&X0.test(r)?e:t();var r}function jf(e,t){const r=new Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function Pr(e){return e&&e.split("#")[0]}function pd(e){try{return e()}catch{return}}function Hf(e,t){const r=setTimeout(e,t);return r!=null&&r.unref&&r?.unref(),r}function fd(e,t,r){return Vf.apply(this,arguments)}function Vf(){return(Vf=Ue(function*(e,t,r){let n;try{return yield Promise.race([e,new Promise((i,s)=>{n=Hf(()=>{try{r?.(),i()}catch(o){s(o)}},t)})])}finally{clearTimeout(n)}})).apply(this,arguments)}var gs,vd,Pa;function Q0(e){const t=globalThis._posthogChunkIds;if(!t)return;const r=Object.keys(t);return Pa&&r.length===vd||(vd=r.length,Pa=r.reduce((n,i)=>{gs||(gs={});const s=gs[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,gs[i]=[l,u];break}}}return n},{})),Pa}function Oi(e){return Oi=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},Oi(e)}function eb(e,t,r){return(t=(function(n){var i=(function(s){if(Oi(s)!="object"||!s)return s;var o=s[Symbol.toPrimitive];if(o!==void 0){var a=o.call(s,"string");if(Oi(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(s)})(n);return Oi(i)=="symbol"?i:i+""})(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function gd(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?gd(Object(r),!0).forEach(function(n){eb(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):gd(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}var tb=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:Q0(this.stackParser),skipFirstLines:(t=e.skipFirstLines)!==null&&t!==void 0?t:1}}getAggregateErrors(e){try{if(si(e)){let r=Object.getPrototypeOf(e);for(let n=0;r&&100>n;n++){var t;const i=(t=Object.getOwnPropertyDescriptor(r,"constructor"))===null||t===void 0?void 0:t.value;if(typeof i=="function"&&i.name==="AggregateError"){const s=e.errors;return ce(s)?s:void 0}r=Object.getPrototypeOf(r)}}}catch{}}buildCoercingContext(e,t,r=0){let n=0,i=0,s=!1;const o=new Set,a=[],c={},l=(d,p,f=0)=>{const v=u(p,f),m=v.apply;if(v.apply=$=>{a.push(d);try{return m($)}finally{a.pop()}},f>4||f>0&&a.indexOf(d)!==-1)return this.coerceFallback(v);const _=typeof d=="object"&&d!==null||typeof d=="function";if(f===0&&n>=50||_&&o.has(d))return;_&&o.add(d),f===0&&n++;const w=this.getAggregateErrors(d);let S,I;s||(s=!!w);try{if(S=this.applyCoercers(d,v),!S)throw c}catch($){if($===c)return void(f===0&&n--);if(!s)throw $;S=this.coerceFallback(v)}if(!w||n>=50)return S;try{I=w.length}catch{return S}if(!Number.isInteger(I)||0>I||I>4294967295)return S;const C=[];for(let $=0;50>n&&1e3>i&&I>$;$++){let M;i++;try{M=v.next(w[$])}catch{n++,M=this.coerceFallback(u(p+1))}M&&C.push(M)}return b(b({},S),{},{errors:C})},u=(d,p=0)=>b(b({},t),{},{syntheticException:d==0?t.syntheticException:void 0,mechanism:d==0?e:{},apply(f){const v=l(f,d,p+1);if(!v)throw c;return v},next:f=>l(f,d+1)}),h=u(r);return b(b({},h),{},{apply:d=>{var p;return(p=l(d,r))!==null&&p!==void 0?p:this.coerceFallback(h)}})}},rb=/^([a-z][a-z0-9.+-]+):/i,nb=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function ib(e){if(!e||e==="<anonymous>")return!1;const t=rb.exec(e);return!t||nb.includes(t[1].toLowerCase())}function Pc(e,t,r,n,i){const s={platform:e,filename:t,function:r==="<anonymous>"?"?":r,in_app:ib(t)};return O(n)||(s.lineno=n),O(i)||(s.colno=i),s}var Bf=(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]},sb=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ob=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ab=/\((\S*)(?::(\d+))(?::(\d+))\)/,cb=(e,t)=>{const r=sb.exec(e);if(r){const[,i,s,o]=r;return Pc(t,i,"?",+s,+o)}const n=ob.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){const o=ab.exec(n[2]);o&&(n[2]=o[1],n[3]=o[2],n[4]=o[3])}const[i,s]=Bf(n[1]||"?",n[2]);return Pc(t,s,i,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}},lb=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ub=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,db=(e,t)=>{const r=lb.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){const s=ub.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]=Bf(i,n),Pc(t,n,i,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}},md=/\(error: (.*)\)/;function Vl(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function hb(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(!Vl(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 pb(e,t){const r=t.start+t.length,n=Wf(e,t);n&&e.splice(r+n===e.length?r:t.start,n)}function Gf(e,t){let r=t.start;for(;r>0&&Vl(e[r-1],e[r-1+t.length]);)r--;return t.start-r}function Wf(e,t){const r=t.start+t.length;let n=r;for(;e.length>n&&Vl(e[n],e[n-t.length]);)n++;return n-r}function fb(e,t){const r=t[0];let n=e.length-(r?Gf(e,r):0);for(const i of t)n-=Wf(e,i);return n}function vb(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 gb=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 to(e,"DOMException")}isDOMError(e){return to(e,"DOMError")}},mb=class{match(e){return si(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}}},_b=class{match(e){return!!to(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}`}},yb=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,bb=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(yb);return n&&(t=n[1],r=n[2]),[t,r]}},wb=["fatal","error","warning","log","info","debug"];function Zf(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 Sb=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(jl(e))return e.constructor.name;const t="name"in e?e.name:void 0;return ye(t)&&!Pi(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: ${Zf(e)}`}isSeverityLevel(e){return ye(e)&&!Pi(e)&&wb.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(si(r))return r}}getObjectClassName(e){try{const t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}},Eb=class{match(e){return jl(e)}coerce(e,t){var r;const n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${Zf(e)}`,stack:(r=t.syntheticException)===null||r===void 0?void 0:r.stack,synthetic:!0}}},kb=class{match(e){return uf(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}}},Rb=class{match(e){return to(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!jl(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 uf(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}},so="$message",oo="$timestamp",Ab=new Set([so,oo]),Oa={enabled:!0,max_bytes:32768};function ao(e){var t;return e?{enabled:(t=e.enabled)!==null&&t!==void 0?t:Oa.enabled,max_bytes:Ib(e.max_bytes,Oa.max_bytes)}:b({},Oa)}var Tb=class{constructor(e){this.ns=[],this.ss=0,this.Rr=ao(e)}setConfig(e){this.Rr=ao(e),this.rs()}add(e){const t=(function(n){let i;try{i=cf(n)}catch{return}try{const s=JSON.parse(i);if(!be(s))return;const o=s,a=o[so],c=o[oo];return!ye(a)||a.trim().length===0||!ye(c)&&!Ze(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 Ib(e,t){if(!Ze(e)||e===1/0||e===-1/0)return t;const r=Math.floor(e);return 0>r?t:r}var _d=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};function yd(e){return typeof e=="string"||e}function bd(e){return typeof e=="string"?e:void 0}var Cb=["$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"],Jf="NativeGzipValidationError",Oc=e=>e.length>=2&&e[0]===31&&e[1]===139,wd=(e,t)=>e===Rc.GZipJS||t===Rc.GZipJS||t==="gzip",Sd=e=>!(!e||typeof e!="object")&&("name"in e?String(e.name):"")==="NotReadableError",di,ms=e=>{throw jf(Jf,`Native gzip produced invalid output: ${e}`)},$b=(Ed=Ue(function*(e,t){18>e.size&&ms("too-short");const r=new Uint8Array(yield e.slice(0,10).arrayBuffer());Oc(r)&&r[2]===8||ms("invalid-header");const n=new DataView(yield e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==(s=>{const o=(()=>{if(di)return di;di=[];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;di[c]=l>>>0}return di})();let a=4294967295;for(let c=0;s.length>c;c++)a=o[255&(a^s[c])]^a>>>8;return(4294967295^a)>>>0})(t)&&ms("invalid-crc");const i=t.length>>>0;n.getUint32(4,!0)!==i&&ms("invalid-size")}),function(e,t){return Ed.apply(this,arguments)}),Ed;function xc(){return xc=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 $b(l,i),l}catch(i){if(r?.rethrow)throw i;return t&&console.error("Failed to gzip compress data",i),null}var n}),xc.apply(this,arguments)}function Kf(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 Pb={}.propertyIsEnumerable;function co(e,t){try{return Yf(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function Bl(e,t,r,n){if(0>=r.remainingNodes)return{stringValue:$c};if(r.remainingNodes--,vt(e))return{boolValue:e};if(typeof e=="bigint")return(function(i,s){const o=i.toString(),a=BigInt("9223372036854775808");return i>=a||-a>i?(s?.debug(`Attribute ${o} is outside the int64 range; encoding it as a string`),{stringValue:o}):{intValue:o}})(e,t);if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if(typeof BigInt>"u")return{stringValue:String(e)};const i=BigInt(e).toString();return e>=9223372036854776e3||-9223372036854776e3>e?(t?.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i}):{intValue:i}}return{doubleValue:e}}if(typeof e=="string")return{stringValue:Un(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:$c};if(e instanceof Date){const i=e.getTime(),s=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof s=="string"?Un(s):String(s)}}r.ancestors.add(e);try{try{const i=e.toJSON;if(typeof i=="function")return Bl(i.call(e),t,r,n+1)}catch{}return ce(e)?{arrayValue:{values:Ob(e,t,r,n+1)}}:{kvlistValue:{values:Yf(e,t,r,n+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:Un(String(e))}}function Ob(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(fe(a))continue;i.push(Bl(a,t,r,n))}catch{i.push({stringValue:is})}return e.length>o&&i.push({stringValue:$c}),i}function Yf(e,t,r,n){const i=[];for(const s in e)if(Pb.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(Ve(o)||O(o))continue;i.push({key:Un(s),value:Bl(o,t,r,n)})}catch{i.push({key:Un(s),value:{stringValue:is}})}}return i}function Xf(e,t,r){return b(b(b(b({},Ff({},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 xb=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function Qf(e,t){const r=Ff({},e),n={};for(const i of xb)({}).hasOwnProperty.call(r,i)&&(n[i]=r[i],delete r[i]);return[...co(r,t),...co(n,t)]}var kd={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"},ev={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}},Mb=ev.info;function Lb(e){try{return Un(String(e))}catch{return is}}function Db(e,t,r,n){const i=e.level||"info",{text:s,number:o}=ev[i]||Mb,a=(function(d=Date.now()){return String(d)+"000000"})(Ze(n)?n:void 0),c={};t.distinctId&&(c.posthogDistinctId=t.distinctId),t.sessionId&&(c.sessionId=t.sessionId),t.windowId&&(c["window.id"]=t.windowId),fe(t.sessionStartTimestamp)||(c.sessionStartTimestamp=String(t.sessionStartTimestamp)),fe(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=is}Object.defineProperty(l,p,{value:f,enumerable:!0,writable:!0,configurable:!0})}}const h={timeUnixNano:a,observedTimeUnixNano:a,severityNumber:o,severityText:s,body:{stringValue:Lb(e.body)},attributes:co(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 tv(e,t,r){return Xf(e,t,r)}function rv(e,t,r,n){return{resourceLogs:[{resource:{attributes:Qf(t)},scopeLogs:[{scope:{name:r,version:n},logRecords:e}]}]}}var nv=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=Hf(()=>{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 iv(){return .75+.5*Math.random()}function sv(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 zb=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 nv(()=>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(jt.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:Db(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(jt.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=rv(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(jt.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(jt.LogsQueue))!==null&&r!==void 0?r:[];t._instance.setPersistedProperty(jt.LogsQueue,i.slice(n)),yield t.vs()})()}qs(){return tv(this.Rr,this._instance.getLibraryId(),this._instance.getLibraryVersion())}Ls(e){var t;if(this._instance.optedOut)return;const r=(t=this._instance.getPersistedProperty(jt.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(jt.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(sv(this.Ms,this.ks,this.Ss,3e4),this.ws.remainingMs())}As(){const e=this._instance.getPersistedProperty(jt.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 fd(r,e):yield r})()}flushWithTimeout(e){var t=this;return Ue(function*(){const r=t.flush();yield fd(r,e,()=>{r.catch(()=>{})})})()}gs(){this.flush().then(()=>{this.ks=0,this.Ss=1},e=>{this.ks++,this.Ss=iv(),this.$.error("PostHog logs flush failed:",e)}).finally(()=>{!this._instance.isDisabled&&this.As()&&this.ps.armNoEarlierThan(this.Hs())})}},xa=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Rd(e){return String(e)+"000000"}function Ad(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 Nb=class{constructor(e,t,r){this._instance=e,this.Rr=t,this.$=r,this.zs=new Map,this.ps=new nv(()=>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=Ad(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(xa.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,xa)]+=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(sv(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=iv()):(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 Xf(s,o,a)})(this.Rr,this._instance.getLibraryId(),this._instance.getLibraryVersion()),n=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Qf(r)},scopeMetrics:[{scope:{name:n,version:i},metrics:t}]}]};var t,r,n,i}vo(e){const t=Rd(Date.now()),r=new Map;for(const o of e.values()){var n;const a=Ad(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=co((n=o.attributes)!==null&&n!==void 0?n:{},this.$),u=Rd(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:xa})}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)}}},ov=(e,{debugEnabled:t}={})=>{const r={N(n,...i){A&&(ar.DEBUG||A.POSTHOG_DEBUG||t)&&!O(A.console)&&A.console&&("__rrweb_original__"in A.console[n]?A.console[n].__rrweb_original__:A.console[n])(e,...i)},debug(...n){r.N("debug",...n)},info(...n){r.N("log",...n)},warn(...n){r.N("warn",...n)},error(...n){r.N("error",...n)},critical(...n){console.error(e,...n)},uninitializedWarning(n){r.error(`You must initialize PostHog before calling ${n}`)},createLogger:(n,i)=>ov(`${e} ${n}`,i)};return r},j=ov("[PostHog.js]"),Ge=j.createLogger,Ub=Ge("[ExternalScriptsLoader]"),lo=e=>{const t=z?.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]}},Kr=(e,t,r)=>{if(e.config.disable_external_dependency_loading)return Ub.warn(`${t} was requested but loading of external scripts is disabled.`),r("Loading of external scripts is disabled");const n=lo(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(!z)return r("document not found");if(lo(t))return Kr(e,t,r);let s=z.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")z.head.appendChild(s);else{const a=z.querySelectorAll("body > script");var o;a.length>0?(o=a[0].parentNode)===null||o===void 0||o.insertBefore(s,a[0]):z.body.appendChild(s)}};z?.body?i():z?.addEventListener("DOMContentLoaded",i)},Ma={},Td=(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`);Kr(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=Ma[i];if(n==="fallback"&&s){if(lo(s))return void Kr(e,s,r);delete Ma[i]}Kr(e,i,n==="fallback"?(o,a)=>{if(o)if(typeof o=="string")r(o);else{var c;const l=Td(e,t);Ma[i]=l;const u=lo(i);u==null||(c=u.parentNode)===null||c===void 0||c.removeChild(u),Kr(e,l,r)}else r(void 0,a)}:r);return}Kr(e,Td(e,t),r)},te.__PosthogExtensions__.loadSiteApp=(e,t,r)=>{const n=e.requestRouter.endpointFor("api",t);Kr(e,n,r)},ar.DEBUG=!1,ar.LIB_VERSION="1.434.12",ar.LIB_NAME="web";var et=ar,Fb="$people_distinct_id",Pt="distinct_id",Gl="$device_id",La="$device_model",uo="__alias",qb="__cmpns",Id="$fbc",Fn="$fbc_persistence",Cd="$fbp",xi="$fbp_persistence",Mc="__timers",av="$autocapture_disabled_server_side",Lc="$heatmaps_enabled_server_side",Dc="$exception_capture_enabled_server_side",cv="$error_tracking_suppression_rules",zc="$error_tracking_capture_extension_exceptions",Nc="$web_vitals_enabled_server_side",Wl="$dead_clicks_enabled_server_side",Zl="$product_tours_enabled_server_side",lv="$logs_capture_enabled_server_side",uv="$web_vitals_allowed_metrics",Mi="$session_recording_remote_config",jb="$session_recording_enabled_server_side",Hb="$replay_sample_rate",Vb="$replay_override_sampling",Bb="$replay_override_linked_flag",Gb="$replay_override_url_trigger",Wb="$replay_override_event_trigger",An="$sesid",dv="$session_is_sampled",Zb="$session_past_minimum_duration",Jb="$session_recording_url_trigger_activated_session",Kb="$session_recording_event_trigger_activated_session",Yb="$debug_first_full_snapshot_timestamp",Xb="$sess_rec_flush_size",Ot="$enabled_feature_flags",ir="$active_feature_flags",Uc="$early_access_features",an="$feature_flag_details",br="$feature_flag_payloads",cn="$feature_flag_request_id",Li="$minimal_flag_called_events",qt="$override_feature_flags",Yr="$override_feature_flag_payloads",wr="$stored_person_properties",Sr="$stored_group_properties",hv="$groups",Fc="$surveys",ho="$surveys_loaded_at",pv="$surveys_activated",fv="$surveys_activated_session",vv="$surveys_activated_timestamps",qc="ph_product_tours",Qb="$product_tours_activated",ew="$product_tours_activated_session",tw="$conversations_widget_session_id",rw="$conversations_ticket_id",nw="$conversations_widget_state",iw="$conversations_user_traits",Er="$flag_call_reported",ki="$flag_call_reported_session_id",Gi="$feature_flag_errors",Ar="$feature_flag_evaluated_at",ft="$user_state",jc="$client_session_props",sw="$capture_rate_limit",gv="$initial_campaign_params",mv="$initial_referrer_info",Tn="$initial_person_info",Jl="$epp",Da="$posthog_cookieless",_v="$cookieless_mode",yv="$sdk_debug_extensions_init_method",bv="$sdk_debug_extensions_init_time_ms",wv="$sdk_debug_recording_script_not_loaded",Sv="$sdk_debug_replay_stale_config",ow="$sdk_debug_replay_event_trigger_status",aw="$sdk_debug_replay_linked_flag_trigger_status",cw="$sdk_debug_replay_matched_recording_trigger_groups",lw="$sdk_debug_replay_pending_trigger_conditions",uw="$sdk_debug_replay_remote_trigger_matching_config",dw="$sdk_debug_replay_trigger_groups_count",hw="$sdk_debug_replay_url_trigger_status",pw="$session_recording_start_reason",Kl="PostHog loadExternalDependency extension not found.",sr="anonymous",Us="identified",Ev="identified_only",Wi="visibilitychange",po="beforeunload",Yl="$pageview",$d="$pageleave",kv="$identify",Pd="$groupidentify";function In(e,t){ce(e)&&e.forEach(t)}function Ce(e,t){if(!fe(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)ql.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 Fs(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 fw=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)}}},Xl=function(e){const t={};return Ce(e,function(r,n){(ye(r)&&r.length>0||Ze(r))&&(t[n]=r)}),t};function Rv(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 vw=["herokuapp.com","vercel.app","netlify.app"];function gw(e){const t=e?.hostname;if(!ye(t))return!1;const r=t.split(".").slice(-2).join(".");for(const n of vw)if(r===n)return!1;return!0}function Te(e,t,r,n){const{capture:i=!1,passive:s=!0}=n??{};e?.addEventListener(t,r,{capture:i,passive:s})}function Hc(e){return e.name==="ph_toolbar_internal"}var Di=e=>{if(z){try{const t=e+"=",r=z.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 Ze(e)&&isFinite(e)&&Math.floor(e)===e});var mw=class Vc{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 Vc(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 Vc(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}},_w=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 Ze(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 mw.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 yw}},Av=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&&(Av=e=>crypto.getRandomValues(e));var yw=class{nextUint32(){return this.Rt.length>this.$t||(Av(this.Rt),this.$t=0),this.Rt[this.$t++]}constructor(){this.Rt=new Uint32Array(8),this.$t=1/0}},Od,Lt=()=>bw().toString(),bw=()=>(Od||(Od=new _w)).generate(),hi="",ww=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,_n=null,je={Et(){if(!Ve(_n))return _n;if(_n=!1,z)try{const e=`__ph_cookie_support_${Lt()}`;je.At(e,"xyz"),_n=Di(e)==='"xyz"',je.Lt(e)}catch{_n=!1}return _n},Pt(e){j.error("cookieStore error: "+e)},Ot:Di,Dt(e){let t;try{t=JSON.parse(je.Ot(e))||{}}catch{}return t},At(e,t,r,n,i){if(!z)return!1;try{let s="",o="";const a=(function(l,u){if(u){let h=(function(d,p=z){if(hi)return hi;if(!p||["localhost","127.0.0.1"].includes(d))return"";const f=d.split(".");let v=Math.min(f.length,8);const m="dmn_chk_"+Lt();for(;!hi&&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",hi=_)}return hi})(l);if(!h){const d=(p=>{const f=p.match(ww);return f?f[0]:""})(l);d!==h&&j.info("Warning: cookie subdomain discovery mismatch",d,h),h=d}return h?"; domain=."+h:""}return""})(z.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),z.cookie=c,!0}catch{return!1}},Lt(e,t){if(z?.cookie&&(!t||!Ve(Di(e))))try{je.At(e,"",-1,t)}catch{return}}},za=null,ke={Et(){if(!Ve(za))return za;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"),za=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)}}},Na=[wr,ir,Ot,an,br,cn,Ar,Gi,Er],Xr=[Gl,Pt,An,dv,Jl,Tn,Fn,ft],fo=e=>e+"_cpm",Sw=["__proto__","constructor","prototype"],Ua=e=>{if(!be(e))return{};const t={};return Object.keys(e).forEach(r=>{Sw.indexOf(r)===-1&&(t[r]=e[r])}),t},Fa=(e,t=[])=>{const r={};return[...Xr,...t].forEach(n=>{const i=e[n];O(i)||Ve(i)||i===""||(r[n]=i)}),r},Tv=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)},xd=(e,t)=>({p:t,f:Tv(JSON.stringify(e))}),Md=(e,t)=>{if(!t)return{properties:[],isValid:!1};try{const r=je.Dt(fo(e)),n=r?.f===Tv(t)&&ce(r.p);return{properties:n?r.p:[],isValid:n}}catch{return{properties:[],isValid:!1}}},qa=(e,t)=>t+"|"+(je.Ot(fo(e))||""),yn={},Bc={Et:()=>!0,Pt(e){j.error("memoryStorage error: "+e)},Ot:e=>e in yn?yn[e]:null,Dt:e=>e in yn?yn[e]:null,At:(e,t)=>(yn[e]=t,!0),Lt(e){delete yn[e]}},Vr=null,xe={Et(){if(!Ve(Vr))return Vr;if(Vr=!0,O(A))Vr=!1;else try{const e="__support__";xe.At(e,"xyz"),xe.Ot(e)!=='"xyz"'&&(Vr=!1),xe.Lt(e)}catch{Vr=!1}return Vr},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)}}},Ew=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 Aa(e)?1:ue(q0,e)?0:-1}get qo(){const e=this.Rr.opt_out_capturing_persistence_type,t=e==="localStorage"?ke:je,r=t.Et()?t:Bc;if(!this.Bo||this.Bo!==r){this.Bo=r;const n=e==="localStorage"?je:ke;n.Ot(this.jo)&&(this.Bo.Ot(this.jo)||this.optInOut(Aa(n.Ot(this.jo))),n.Lt(this.jo,this.Rr.cross_subdomain_cookie))}return this.Bo}Lo(){return!!this.Rr.respect_dnt&&[rt?.doNotTrack,rt?.msDoNotTrack,te.doNotTrack,rt?.globalPrivacyControl].some(e=>Aa(e))}};function Iv(e,t){var r;const n=e==null||(r=e.config)===null||r===void 0?void 0:r.get_current_url;if(!tt(n))return t;try{const i=n(t);return ye(i)&&i?i:t}catch(i){return j.error("Error in get_current_url, falling back to window.location.href",i),t}}function Ld(e){var t;return e instanceof Element&&(e.id==="__POSTHOG_TOOLBAR__"||!!(!((t=e.closest)===null||t===void 0)&&t.call(e,".toolbar-global-fade-container")))}function Zt(e){return!!e&&e.nodeType===1}function ct(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function Cv(e){return!!e&&e.nodeType===3}function Ql(e){return!!e&&e.nodeType===11&&Zt(e.host)}function eu(e){return e?Fo(e).split(/\s+/):[]}function Dd(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:Iv(n,s)})(t);return!!(r&&e&&e.some(n=>r.match(n)))}function Jn(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 eu(t)}function $v(e){return fe(e)?null:Fo(e).split(/(\s+)/).filter(t=>Ni(t)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Zi(e){let t="";return qn(e)&&!Ji(e)&&e.childNodes&&e.childNodes.length&&Ce(e.childNodes,function(r){var n;Cv(r)&&r.textContent&&(t+=(n=$v(r.textContent))!==null&&n!==void 0?n:"")}),Fo(t)}function zi(e){var t;return O(e.target)?e.srcElement||null:!((t=e.target)===null||t===void 0)&&t.shadowRoot?e.composedPath()[0]||null:e.target||null}var tu=["a","button","form","input","select","textarea","label"];function Gc(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 Wc(e,t){if(O(t))return!0;for(const r of e)if(t.some(n=>Gc(r,n)))return!0;return!1}function Pv(e){const t=e.parentNode;return!(!t||!Zt(t))&&t}var ja=[".ph-no-autocapture","[data-ph-no-autocapture]"],Ov=["next","previous","prev",">","<"],kw=[...Ov,"+","-","−","–"],zd=(e,t)=>/[a-z0-9]/i.test(t)?e.includes(t):e===t,Nd=[".ph-no-rageclick",".ph-no-capture"],Rw=["","text","search","email","password","url","tel","number"];function xv(e,t){if(!A||ru(e))return!1;let r,n,i;var s,o;if(vt(t)?(r=!!t&&Nd,n=void 0,i=!1):(r=(s=t?.css_selector_ignorelist)!==null&&s!==void 0?s:Nd,n=t?.content_ignorelist,i=(o=t?.ignore_text_selection)!==null&&o!==void 0&&o),r===!1||i&&(function(c){return!(!c||!Zt(c))&&(!!ct(c,"textarea")||(ct(c,"input")?ue(Rw,(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}=Mv(e,!1);return!(function(c,l){if(c===!1||O(c))return!1;let u;if(c===!0)u=Ov;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=>zd(h,p)||zd(d,p)))})(n,a.map(c=>{var l;return{safeText:Zi(c).toLowerCase(),ariaLabel:((l=c.getAttribute("aria-label"))===null||l===void 0?void 0:l.toLowerCase().trim())||""}}))&&!Wc(a,r)}var ru=e=>!e||ct(e,"html")||!Zt(e),Mv=(e,t)=>{if(!A||ru(e))return{parentIsUsefulElement:!1,targetElementList:[]};let r=!1;const n=[e];let i=e;for(;i.parentNode&&!ct(i,"body");){if(Ql(i.parentNode)){n.push(i.parentNode.host),i=i.parentNode.host;continue}const s=Pv(i);if(!s)break;if(t||tu.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 qn(e){const t=new Set;let r=0;for(let s=e;s.parentNode&&!ct(s,"body");s=s.parentNode){if(r++>=1e3||t.has(s))return!1;t.add(s);const o=Jn(s);if(ue(o,"ph-sensitive")||ue(o,"ph-no-capture"))return!1}if(ue(Jn(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 Ji(e){return!!(ct(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||ct(e,"select")||ct(e,"textarea")||e.getAttribute("contenteditable")==="true")}var Ud=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}))$"),Fd=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Aw=[16,15,14,13],Tw=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),qd=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),jd=/[0-9A-Za-z_]/;function Iw(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 Ni(e,t=!0){return!(fe(e)||ye(e)&&(e=Fo(e),(t?Ud.test((e||"").replace(/[- ]/g,"")):(function(r){let n;for(Fd.lastIndex=0;n=Fd.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 Aw){const c=o+a;if(s.length>=c){const l=s.slice(o,c);if(Ud.test(l)&&Iw(l))return!0}}}return!1})(e))||(t?Tw.test(e):(function(r){let n;for(qd.lastIndex=0;n=qd.exec(r);){const i=n[1],s=n[3];if(!(i&&s&&jd.test(i)&&jd.test(s)))return!0}return!1})(e))))}function Hd(e){let t=Zi(e);return t=`${t} ${Lv(e)}`.trim(),Ni(t)?t:""}function Lv(e){let t="";return e&&e.childNodes&&e.childNodes.length&&Ce(e.childNodes,function(r){var n;if(r&&((n=r.tagName)===null||n===void 0?void 0:n.toLowerCase())==="span")try{const i=Zi(r);t=`${t} ${i}`.trim(),r.childNodes&&r.childNodes.length&&(t=`${t} ${Lv(r)}`.trim())}catch(i){j.error("[AutoCapture]",i)}}),t}function Vd(e){return e.replace(/"|\\"/g,'\\"')}function Cw(e){const t=e.attr__class;if(t)return ce(t)?t:eu(t)}var _s=Ge("[Dead Clicks]"),$w=()=>!0,Pw=e=>{var t;const r=!!(!((t=e.instance.persistence)===null||t===void 0)&&t.get_property(Wl)),n=e.instance.config.capture_dead_clicks;return vt(n)?n:!!be(n)||r},Bd=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({[Wl]: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?_s.error("failed to load script",i):e()})}Uo(){var e;if(z){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(z),_s.info("starting...")}}else _s.error("`document` not found. Cannot start.")}stop(){this.Ho&&(this.Ho.stop(),this.Ho=void 0,_s.info("stopping..."))}},pi=Ge("[SegmentIntegration]");function Gd(e,t,r=!0){const n=e.config.segment;if(!n)return t();const{analytics:i,filterProperties:s}=(a=>tt(a.register))(o=n)?{analytics:o}:o;var o;(function(a,c,l,u){const h=p=>{const f=()=>p.anonymousId()||Lt();a.config.get_device_id=f,u&&p.id()&&(a.register({distinct_id:p.id(),$device_id:f()}),a.persistence.set_property(ft,Us)),l(u?void 0:p.anonymousId()||void 0)},d=c.user();"then"in d&&tt(d.then)?d.then(h):h(d)})(e,i,a=>{i.register(((c,l,{filterProperties:u}={})=>{typeof Promise<"u"&&Promise.resolve||pi.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()||(pi.info("No userId set, resetting PostHog"),c.reset()),f||(l=void 0),d.event.userId&&d.event.userId!==c.get_distinct_id()&&(pi.info("UserId set, identifying with PostHog"),c.identify(d.event.userId));let v=c.calculateEventProperties(p,d.event.properties);if(!fe(u)){const m=d.event.properties||{},_={};for(const S of Object.keys(v))ql.call(m,S)||(_[S]=v[S]);const w=((S,I)=>{const C=ce(S)?S:[S];let $=b({},I);for(const M of C)try{if($=M($),fe($))return null}catch(L){return pi.error("Error in Segment filterProperties:",L),null}return $})(u,_);if(fe(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,Yl)},identify(d){return h(d,kv)},screen(d){return h(d,"$screen")}}})(e,a,{filterProperties:s})).then(()=>{t()},c=>{pi.error("Failed to register the Segment integration",c),t()})},r)}var Dv="posthog-js";function zv(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 Ow=class{constructor(e,t,r,n,i,s){this.name=Dv,this.setupOnce=function(o){o(zv(e,{organization:t,projectId:r,prefix:n,severityAllowList:i,sendExceptionsToPostHog:s==null||s}))}}},Wd=class{constructor(e){this.Wo=(t,r,n)=>{n&&(n.noSessionId||n.activityTimeout||n.sessionPastMaximumLength||n.crossTabAdoption)&&(j.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:t,changeReason:n}),this.Vo=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.Go()}Go(){var e;this.Zo=(e=this._instance.sessionManager)===null||e===void 0?void 0:e.onSessionId(this.Wo)}destroy(){var e;(e=this.Zo)===null||e===void 0||e.call(this),this.Zo=void 0}doPageView(e,t){var r;const n=this.Qo(e,t);return this.Vo={pathname:(r=A?.location.pathname)!==null&&r!==void 0?r:"",pageViewId:t,timestamp:e},this._instance.scrollManager.resetContext(),n}doPageLeave(e){var t;return this.Qo(e,(t=this.Vo)===null||t===void 0?void 0:t.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.Vo)===null||e===void 0?void 0:e.pageViewId}}Qo(e,t){const r=this.Vo;if(!r)return{$pageview_id:t};let n={$pageview_id:t,$prev_pageview_id:r.pageViewId};const i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){let{maxScrollHeight:s,lastScrollY:o,maxScrollY:a,maxContentHeight:c,lastContentY:l,maxContentY:u}=i;if(!(O(s)||O(o)||O(a)||O(c)||O(l)||O(u))){s=Math.ceil(s),o=Math.ceil(o),a=Math.ceil(a),c=Math.ceil(c),l=Math.ceil(l),u=Math.ceil(u);const h=s>1?Bt(o/s,0,1,j):1,d=s>1?Bt(a/s,0,1,j):1,p=c>1?Bt(l/c,0,1,j):1,f=c>1?Bt(u/c,0,1,j):1;n=Le(n,{$prev_pageview_last_scroll:o,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:a,$prev_pageview_max_scroll_percentage:d,$prev_pageview_last_content:l,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:u,$prev_pageview_max_content_percentage:f})}}return r.pathname&&(n.$prev_pageview_pathname=r.pathname),r.timestamp&&(n.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),n}},fi=["flags","surveys"],xw={[Fb]:{exposure:"hidden"},[uo]:{exposure:"hidden"},[qb]:{exposure:"hidden"},[Mc]:{exposure:"hidden"},[Fn]:{exposure:"hidden"},[xi]:{exposure:"hidden"},[av]:{exposure:"event"},[Lc]:{exposure:"hidden"},[lv]:{exposure:"hidden"},[Dc]:{exposure:"event"},[cv]:{exposure:"hidden"},[zc]:{exposure:"event"},[Nc]:{exposure:"event"},[Wl]:{exposure:"event"},[Zl]:{exposure:"hidden"},[uv]:{exposure:"event"},[Mi]:{exposure:"hidden"},[jb]:{exposure:"hidden"},[An]:{exposure:"hidden"},[dv]:{exposure:"event"},[Hb]:{exposure:"event",shouldSkipFromEventProperties:e=>Ve(e)},[Zb]:{exposure:"event"},[Jb]:{exposure:"event"},[Kb]:{exposure:"event"},[Yb]:{exposure:"event"},[Xb]:{exposure:"hidden"},[Ot]:{exposure:"hidden",storageGroup:"flags"},[ir]:{exposure:"hidden",storageGroup:"flags"},[Uc]:{exposure:"hidden"},[an]:{exposure:"hidden",storageGroup:"flags"},[br]:{exposure:"hidden",storageGroup:"flags"},[cn]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Li]:{exposure:"hidden",storageGroup:"flags"},[qt]:{exposure:"hidden"},[Yr]:{exposure:"hidden"},[wr]:{exposure:"hidden"},[Sr]:{exposure:"hidden"},[Fc]:{exposure:"hidden",storageGroup:"surveys"},[ho]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[pv]:{exposure:"event"},[fv]:{exposure:"hidden"},[vv]:{exposure:"hidden"},[qc]:{exposure:"hidden"},[Qb]:{exposure:"hidden"},[ew]:{exposure:"hidden"},[tw]:{exposure:"event"},[rw]:{exposure:"event"},[nw]:{exposure:"event"},[iw]:{exposure:"event"},[Er]:{exposure:"hidden"},[ki]:{exposure:"hidden"},[hv]:{exposure:"event"},[Gi]:{exposure:"hidden"},[Ar]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ft]:{exposure:"hidden"},[jc]:{exposure:"hidden"},[sw]:{exposure:"hidden"},[gv]:{exposure:"hidden"},[mv]:{exposure:"hidden"},[Tn]:{exposure:"hidden"},[Jl]:{exposure:"hidden"},[Vb]:{exposure:"event"},[Bb]:{exposure:"event"},[Gb]:{exposure:"event"},[Wb]:{exposure:"event"},[yv]:{exposure:"event"},[bv]:{exposure:"event"},[wv]:{exposure:"event"},[Sv]:{exposure:"event"},[ow]:{exposure:"event"},[aw]:{exposure:"event"},[cw]:{exposure:"event"},[lw]:{exposure:"event"},[uw]:{exposure:"event"},[dw]:{exposure:"event"},[hw]:{exposure:"event"},[pw]:{exposure:"event"}},Mw=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],ot=e=>{const t=xw[e];if(t)return t;for(const[r,n]of Mw)if(e.indexOf(r)===0)return n},Cn=(e,t)=>{try{let r;return JSON.stringify(e,(n,i)=>{var s;return si(i)?((s=r)!==null&&s!==void 0||(r=new WeakMap),r.has(i)||r.set(i,Rv(i)),r.get(i)):typeof i=="bigint"?i.toString():i},t)}catch{return cf(e)}},Or=e=>{const t=z?.createElement("a");return O(t)?null:(t.href=e,t)},Kn=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," ")}},Ki=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},vo=function(e,t){const r=e.match(new RegExp(t+"=([^&]*)"));return r?r[1]:null},Nv=(e,t)=>e>=t&&af(),Uv=(e,t,r,n)=>{if(e===0){if(af()){const i=t+1;return i===r&&n(),i}return t}return 0},Yn=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Lw=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...Yn],Yi="<masked>",Dw=["li_fat_id"];function Fv(e,t,r){if(!z)return{};const n=t?[...Yn,...r||[]]:[],i=qv(Ki(z.URL,n,Yi),e),s=(function(){const o={};return Ce(Dw,function(a){const c=Di(a);o[a]=c||null}),o})();return Le(s,i)}function qv(e,t){const r=Lw.concat(t||[]),n={};return Ce(r,function(i){const s=Kn(e,i);n[i]=s||null}),n}function jv(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(!Ve(t)){n.$search_engine=t;const i=z?Kn(z.referrer,r):"";i.length&&(n.ph_keyword=i)}return n}function Hv(){return navigator.language||navigator.userLanguage}function zw(){const e=Hv();return typeof e=="string"?e.split("-")[0]:void 0}var go="$direct";function Vv(){return z?.referrer||go}function Bv(e,t,r=!1){const n=e?[...Yn,...t||[]]:[],i=r?Pr(He?.href):He?.href,s=i?.substring(0,1e3);return{r:Vv().substring(0,1e3),u:s?Ki(s,n,Yi):void 0}}function Gv(e,t=!1){var r;const{r:n,u:i}=e,s=t?Pr(i):i,o={$referrer:n,$referring_domain:n==null?void 0:n==go?go:(r=Or(n))===null||r===void 0?void 0:r.host};if(s){o.$current_url=s;const a=Or(s);o.$host=a?.host,o.$pathname=a?.pathname;const c=qv(s);Le(o,c)}if(n){const a=jv(n);Le(o,a)}return o}function Wv(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Nw(){try{return new Date().getTimezoneOffset()}catch{return}}var Uw={flags:Ar,surveys:ho},Fw=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],ys=e=>`${e}_cookie_identity_change_pending`,bs=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",er=[Ot,ir,an,br,cn,Ar,Li,wr],Ha=e=>er.indexOf(e)!==-1,Zv=[Fn,xi],Zd=e=>Zv.indexOf(e)!==-1,ur=(e,t)=>{try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}},bn=e=>{if(!e)return{};const t=JSON.parse(e);return be(t)?t:{}},Jd=(e,t)=>{Ce(e,(r,n)=>{const i=ot(n);i&&i.exposure!=="event"||{}.hasOwnProperty.call(t,n)||delete e[n]})},Va=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();Te(A,"beforeunload",n,{capture:!1}),Te(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=fi.find(o=>i.key===this.pa(o));s&&this.ga(i.key,s)}}else this.ga(i.key,Qe)},Te(A,"storage",this.fa)}}markCrossTabFeatureFlagChanges(e){Object.entries(e).forEach(([t,r])=>{const n=this.ia.get(t);if(!Ha(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),Ve(i)){const a=this.ya(t);return a.storageValue=null,t!==Qe&&(a.persisted=!1),!1}n=bn(i)}catch{return!1}const s=t===Qe?n:ke.Dt(this.ha);if(s&&this.ba(s))return!1;const o=this._a(n,t,r);return t===Qe&&this.Yo&&!ur(this.wa().main,n)||this.ka(n,t,!0,i),o}ba(e){const t=this.props[Pt],r=e[Pt];return!O(t)&&!O(r)&&t!==r}ka(e,t,r,n){const i=this.ya(t);i.storageValue=n,t!==Qe&&(i.persisted=r);try{i.fingerprint=this.Sa(e,t)}catch{i.fingerprint=void 0}}_a(e,t,r){let n=!1;return er.forEach(i=>{var s;const o=(s=ot(i))===null||s===void 0?void 0:s.storageGroup;if(t===Qe&&this.Yo&&o||t!==Qe&&o!==t)return;const a=i in e,c=this.xa(i,a?e[i]:void 0),l=this.ia.has(i)?i in this.props:a;l===i in this.props&&ur(c,this.props[i])||(l?this.Ca(i,c,!1):this.$a(i,!1),n=!0)}),n&&r&&this.aa.forEach(i=>i()),n}Ta(){if(!this.Ko)return!1;try{this.ra=!1;const e=ke.Ot(this.ha),t=this.ya(Qe);let r,n=!1,i=!1;if(e!==t.storageValue)if(Ve(e))t.storageValue=null;else{if(r=bn(e),this.ra=!this.sa&&this.ba(r),this.ra)return!1;i=this._a(r,Qe,!1),!this.Yo||ur(this.wa().main,r)?this.ka(r,Qe,!0,e):t.storageValue=e,n=!0}return this.Yo&&fi.forEach(s=>{const o=ke.Ot(this.pa(s)),a=this.ya(s),c=r||{},l=n&&er.some(h=>{var d;return((d=ot(h))===null||d===void 0?void 0:d.storageGroup)===s&&h in c});if(o===a.storageValue&&!l)return;if(Ve(o))return a.storageValue=null,a.persisted=!1,void(l&&(i=this._a(c,s,!1)||i));const u=bn(o);i=this._a(u,s,!1)||i,this.ka(u,s,!0,o)}),i}catch{return!1}}ma(e,t){this.ia.set(e,t);const r=ot(e);r!=null&&r.volatile||(this.ya((this.Yo?r?.storageGroup:void 0)||Qe).fingerprint=void 0,this.Ia(e))}Ma(){er.forEach(e=>this.ia.set(e,!0))}va(){if(this.Ko)try{const e=ke.Ot(this.ha),t=bn(e);this.ya(Qe).storageValue=e,er.forEach(r=>{var n;const i=this.Yo?(n=ot(r))===null||n===void 0?void 0:n.storageGroup:void 0,s=i?ke.Ot(this.pa(i)):null;if(i){const a=this.ya(i);a.storageValue=s,a.persisted=!Ve(s)}const o=i&&!Ve(s)?bn(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(!Ha(e))return;const n=this.ia.get(e);if(n===!0)return;let i=t;if(this.Ko)try{var s;const a=this.Yo?(s=ot(e))===null||s===void 0?void 0:s.storageGroup:void 0,c=a?this.pa(a):this.ha;i=bn(ke.Ot(c))[e]}catch{}const o=new Set(n||[]);if(e==="$active_feature_flags"){if(!O(t)&&!ce(t)||!O(i)&&!ce(i)||!ce(r))return void this.ma(e,!0);const a=new Set(t||[]),c=new Set(i||[]),l=new Set(r);new Set([...a,...l]).forEach(u=>{a.has(u)!==l.has(u)&&o.add(u)}),o.forEach(u=>{c.has(u)===l.has(u)&&o.delete(u)})}else{if(!be(r))return void(ur(i,r)?this.ia.delete(e):this.ma(e,!0));{if(!O(t)&&!be(t)||O(t)&&mt(r)&&O(i))return void this.ma(e,!0);const a=be(t)?t:{},c=be(i)?i:{};new Set([...Object.keys(a),...Object.keys(r)]).forEach(l=>{l in a==l in r&&ur(a[l],r[l])||o.add(l)}),o.forEach(l=>{l in c==l in r&&ur(c[l],r[l])&&o.delete(l)})}}o.size?this.ma(e,o):this.ia.delete(e)}Pa(){var e;const t=(e=this.Rr)===null||e===void 0?void 0:e.persistence_save_debounce_ms;return Ze(t)&&t>0?t:0}Ra(e){if(this.Rr.cookieWinsOnConflict&&this.Rr.persistence.toLowerCase()==="localstorage+cookie")if(e)try{const t=Fa(e,this.Rr.cookie_persisted_properties||[]),r=xd(t,this.Rr.cookie_persisted_properties||[]),n=JSON.stringify(t)+"|"+JSON.stringify(r),i=je.Ot(this.ha)||void 0;i&&qa(this.ha,i)===n&&(this.Aa=n,this.Fa=i)}catch{}else try{const t=je.Ot(this.ha)||void 0;this.Aa=t?qa(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=je.Ot(this.ha)||void 0}catch{}if(!r||r===this.Fa)return!1;const n=qa(this.ha,r);let i;try{i=Ua(JSON.parse(r))}catch{return!1}if((je.Ot(this.ha)||void 0)!==r)return!1;this.Aa=n,this.Fa=r;const s=Md(this.ha,r),o=[...Xr,...s.properties],a={};if(Object.keys(i).forEach(v=>{const m=i[v];(O(m)||Ve(m)||m===""||v==="$user_state"&&m!=="anonymous"&&m!=="identified")&&(a[v]=!0,delete i[v])}),mt(i))return!1;const c="distinct_id"in i||i.$user_state==="anonymous"||i.$user_state==="identified",l=this.props,u=l[Pt],h=l[ft],d=Le({},l);[...Xr,...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||Xr.indexOf(v)===-1||m!==!1&&m!==0)&&delete d[v]}}),this.props=Le(d,i),er.forEach(v=>{const m=v in this.props;v in l===m&&ur(l[v],this.props[v])||(m?this.Ea(v,l[v],this.props[v]):this.ma(v,!0))}),!c||"$user_state"in i||"$user_state"in this.props||this.Ca(ft,sr);const p=this.props[Pt],f=this.props[ft];return!c||p===u&&f===h||(this.sa=!0,this.ta=!0,xe.At(ys(this.ha),!0),this.$a(wr),this.$a(ir),this.$a(Ot),this.$a(an),this.$a(br),this.$a(cn),this.$a(Ar),this.$a(Gi),this.$a(Er),f!=="anonymous"||h!=="identified"&&i.$user_state!=="anonymous"&&(O(u)||p===u)||(Jd(this.props,i),this.$a(Sr)),f==="identified"?this.props.$user_id=p:delete this.props.$user_id,this.$a(uo)),!0}consumeCookieIdentityChange(){const e=ys(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){Fw.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=[...Xr,...o];return b(b({},ke),{},{Dt(l){try{let h,d={};try{h=je.Ot(l)||void 0,d=h?Ua(JSON.parse(h)):{}}catch{}const p=JSON.parse(ke.Ot(l)||"{}");let f;if(a){const v=Md(l,h),m=[...Xr,...v.properties],_={};Object.keys(d).forEach(S=>{const I=d[S];Ve(I)||I===""||S==="$user_state"&&I!=="anonymous"&&I!=="identified"||(_[S]=I)});const w="distinct_id"in _||_.$user_state==="anonymous"||_.$user_state==="identified";if(Object.keys(_).length>0){var u;const S=p[Pt],I=(u=p.$user_state)!==null&&u!==void 0?u:sr;c.forEach(C=>{if(m.indexOf(C)!==-1&&!(C in d)&&(w||C!=="distinct_id"&&C!=="$user_state")){const $=p[C];(v.isValid||Xr.indexOf(C)===-1||$!==!1&&$!==0)&&delete p[C]}}),!w||"$user_state"in d||"$user_state"in p||(p[ft]=sr),!w||("distinct_id"in _?_[Pt]:p[Pt])===S&&("$user_state"in _?_[ft]:p[ft])===I||(Na.forEach(C=>delete p[C]),_.$user_state==="identified"&&"distinct_id"in _?p.$user_id=_[Pt]:delete p.$user_id,_.$user_state!=="identified"&&(delete p[hv],delete p[Sr]),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=Fa(u,o);if(Object.keys(m).length){if(a){const _=fo(l),w=xd(m,o);if(je.At(_,w,h,d,p,f),je.Ot(_)!==JSON.stringify(w)){je.Lt(_,d);const S=Fa(u);return je.At(l,S,h,d,p,f),v}}je.At(l,m,h,d,p,f)}}catch(m){ke.Pt(m)}return v},Lt(l,u){try{A?.localStorage.removeItem(l),je.Lt(l,u),je.Lt(fo(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=Bc:s==="cookie"&&je.Et()?(r=je,n=!0):t.Et()?(r=t,i=!0,n=!0):je.Et()?(r=je,n=!0):r=Bc,this.Ko=i,this.Xo=n,r}pa(e){return`${this.ha}__${e}`}da(e){return this.Ko&&!!e.split_storage}properties(){const e={};return Ce(this.props,(t,r)=>{const n=ot(r);if(!n||n.exposure==="event"){var i;if(!(n==null||(i=n.shouldSkipFromEventProperties)===null||i===void 0)&&i.call(n,t))return;e[r]=t}}),e}load(e=!1){if(this.mi&&!e)return;const t=this.Rr.cookieWinsOnConflict&&this.Rr.persistence.toLowerCase()==="localstorage+cookie",r=t?ke.Dt(this.ha):null;let n={};if(t)try{n=Ua(je.Dt(this.ha)),Ce(n,(a,c)=>{(O(a)||Ve(a)||a==="")&&delete n[c]})}catch{}const i=this.qo.Dt(this.ha);if(i&&(this.props=Le({},i)),this.Yo&&this.Ba(),t&&i){var s,o;const a=r?.[Pt],c=(s=r?.$user_state)!==null&&s!==void 0?s:sr,l=i[Pt],u=(o=i.$user_state)!==null&&o!==void 0?o:sr;if(l!==a||u!==c){this.ta=!0,xe.At(ys(this.ha),!0);const h=Le({},this.props);Na.forEach(p=>delete h[p]),u!=="anonymous"||c!=="identified"&&n.$user_state!=="anonymous"&&(O(a)||l===a)||(Jd(h,n),delete h[Sr]),this.props=h;const d=new Set;Na.forEach(p=>{var f;const v=(f=ot(p))===null||f===void 0?void 0:f.storageGroup;v&&d.add(v)}),d.forEach(p=>{const f={};Ce(this.props,(v,m)=>{var _;((_=ot(m))===null||_===void 0?void 0:_.storageGroup)===p&&(f[m]=v)}),mt(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(ys(this.ha))&&(this.ta=!0)}Ba(){for(const e of fi){const t=ke.Dt(this.pa(e));if(t&&!mt(t)){const r=this.ya(e);r.persisted=!0,this.Ha(e)||(r.fingerprint=this.Sa(t,e)),this.za(e,t)||Le(this.props,t)}}}Ha(e){return Object.keys(this.props).some(t=>{var r;return((r=ot(t))===null||r===void 0?void 0:r.storageGroup)===e})}za(e,t){const r=Uw[e];if(!r)return!1;const n=t[r],i=this.props[r];return Ze(n)&&Ze(i)&&i>n}refreshKey(e){var t;if(this.mi||this.oa.has(e))return;const r=this.Yo?(t=ot(e))===null||t===void 0?void 0:t.storageGroup:void 0,n=r?ke.Dt(this.pa(r)):this.qo.Dt(this.ha);if(n&&e in n)this.Ca(e,n[e],!1);else{if(r){const i=this.qo.Dt(this.ha);if(i&&e in i)return void this.Ca(e,i[e],!1)}this.$a(e,!1)}}save(){if(this.mi)return;const e=this.Pa();e>0?O(this.Na)&&(this.Na=setTimeout(()=>{this.Na=void 0,this.qa()},e)):this.qa()}flush(){O(this.Na)||(clearTimeout(this.Na),this.Na=void 0,this.qa())}qa(e=!1){if(this.mi||this.ea&&!e)return;e||(this.syncCookieProperties(),this.Rr.cookieWinsOnConflict&&this.Rr.persistence.toLowerCase()==="localstorage+cookie"||Zv.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(),er.forEach(i=>{var s;(s=ot(i))!==null&&s!==void 0&&s.storageGroup||this.ia.delete(i)}));for(const i of fi){var n;const s=t[i];if(mt(s)&&!(!((n=this.Jo[i])===null||n===void 0)&&n.persisted)){er.forEach(a=>{var c;((c=ot(a))===null||c===void 0?void 0:c.storageGroup)===i&&this.ia.delete(a)});continue}const o=this.Wa(ke,this.pa(i),s,i);o!=="failed"&&er.forEach(a=>{const c=ot(a);c?.storageGroup!==i||o!=="written"&&c.volatile||this.ia.delete(a)})}}wa(){const e={},t={flags:{},surveys:{}};return Ce(this.props,(r,n)=>{var i;const s=(i=ot(n))===null||i===void 0?void 0:i.storageGroup;s?t[s][n]=r:e[n]=r}),{main:e,groups:t}}Sa(e,t){if(t===Qe)return JSON.stringify(e)+"|"+this.Va+"|"+this.Ga+"|"+this.Za;const r={};return Ce(e,(n,i)=>{var s;r[i]=!((s=ot(i))===null||s===void 0)&&s.volatile?"__volatile__":n}),JSON.stringify(r)}Wa(e,t,r,n){const i=this.ya(n);if(n!==Qe&&!i.dirty&&!O(i.fingerprint))return"skipped";let s;try{if(s=this.Sa(r,n),s===i.fingerprint)return i.dirty=!1,"skipped"}catch{s=void 0}return e.At(t,r,this.Va,this.Ga,this.Za,this.Rr.debug)?(i.dirty=!1,n!==Qe&&(i.persisted=!0),O(s)||(i.fingerprint=s),this.Ko&&(i.storageValue=ke.Ot(t)),"written"):(this.Rr.debug&&j.warn(`failed to persist storage entry "${t}"; will retry on next save`),"failed")}remove({keepGroupEntries:e=!1}={}){if(this.Ma(),O(this.Na)||(clearTimeout(this.Na),this.Na=void 0),this.qo.Lt(this.ha,!1),this.qo.Lt(this.ha,!0),!e&&this.la)for(const t of fi)ke.Lt(this.pa(t));e?delete this.Jo[Qe]:this.Jo={},this.Aa=void 0,this.Fa=void 0}clear(){this.remove(),this.props={}}register_once(e,t,r){if(be(e)){this.syncCookieProperties(),O(t)&&(t="None"),this.Va=O(r)?this.Qa:r;let n=!1;if(Ce(e,(i,s)=>{this.props.hasOwnProperty(s)&&this.props[s]!==t||(this.Ca(s,i),n=!0)}),n)return this.save(),!0}return!1}register(e,t){if(be(e)){this.syncCookieProperties(),this.Va=O(t)?this.Qa:t;let r=!1;if(Ce(e,(n,i)=>{e.hasOwnProperty(i)&&(this.props[i]!==n||be(n)||ce(n))&&(this.Ca(i,n),r=!0)}),r)return this.save(),!0}return!1}unregister(e){this.syncCookieProperties();const t=typeof e=="string"?[e]:e;let r=!1;for(const n of t)n in this.props&&(this.$a(n),r=!0);r&&this.save()}update_campaign_params(){const e=z?.URL;if(e===this.ua)return;const t=Fv(this.Rr.custom_campaign_params,this.Rr.mask_personal_data_properties,this.Rr.custom_personal_data_properties),r=!mt(Xl(t));return r&&this.register(t),this.ua=e,r?t:void 0}update_search_keyword(){this.register((function(){const e=z?.referrer;return e?jv(e):{}})())}update_referrer_info(){var e;this.register_once({$referrer:Vv(),$referring_domain:z?.referrer&&((e=Or(z.referrer))===null||e===void 0?void 0:e.host)||go},void 0)}set_initial_person_info(){if(this.props.$initial_campaign_params||this.props.$initial_referrer_info)return;const e=Bv(this.Rr.mask_personal_data_properties,this.Rr.custom_personal_data_properties,this.Rr.disable_capture_url_hashes);this.register_once({[Tn]:this.Xo?{r:bs(e.r),u:e.u?bs(e.u):void 0}:e},void 0)}get_initial_props(){const e={};Ce([mv,gv],r=>{const n=this.props[r];n&&Ce(n,function(i,s){e["$initial_"+Ac(s)]=i})});const t=this.props[Tn];if(t){const r=(function(n,i=!1){const s=Gv(n,i),o={};return Ce(s,function(a,c){o[`$initial_${Ac(c)}`]=a}),o})(t,this.Rr.disable_capture_url_hashes);Le(e,r)}return e}safe_merge(e){return Ce(this.props,function(t,r){r in e||(e[r]=t)}),e}update_config(e,t,r){const n=e.persistence!==t.persistence,i=!((p,f)=>{if(p.length!==f.length)return!1;const v=[...p].sort(),m=[...f].sort();return v.every((_,w)=>_===m[w])})(e.cookie_persisted_properties||[],t.cookie_persisted_properties||[]),s=n||i,o=e.cookieWinsOnConflict!==t.cookieWinsOnConflict,a=e.disable_persistence||!!r,c=!!this.mi&&!a;a||this.Oa(t,c),this.Rr=e,!a&&(n||i||o)&&(this.Aa=void 0,this.Fa=void 0,this.Oa(b(b({},e),{},{cookie_persisted_properties:t.cookie_persisted_properties}),c));const l=s||o?this.ca(e):this.qo;this.Ja();const u=this.da(e),h=s||u!==this.Yo,d=!a&&(h||e.cross_subdomain_cookie!==this.Ga||e.secure_cookie!==this.Za)&&this.Da(c);this.na=h;try{if(this.Qa=this.Va=e.cookie_expiration,this.set_disabled(a),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),h){const p=this.props;this.clear(),this.qo=l,this.Yo=u,this.props=p,this.save()}else o&&(this.qo=l,a||(delete this.Jo[Qe],this.qa()))}finally{this.na=!1,d&&this.ja()}}Ja(){const e=this.props[Tn];if(!this.Xo||!be(e)||typeof e.r!="string")return;const t=bs(e.r),r=typeof e.u=="string"?bs(e.u):e.u;t===e.r&&r===e.u||this.Ca(Tn,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(Mc,r),this.save()}remove_event_timer(e){const t=this.props.__timers||{},r=t[e];return O(r)||(delete t[e],this.Ca(Mc,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),Zd(e)&&!ur(i,t)&&this.oa.add(e),this.Ea(e,i,t),(n=ot(e))!==null&&n!==void 0&&n.volatile||this.Ia(e))}$a(e,t=!0){delete this.props[e],t&&(Ha(e)&&this.ma(e,!0),Zd(e)&&this.oa.add(e),this.Ia(e))}Ia(e){var t;const r=(t=ot(e))===null||t===void 0?void 0:t.storageGroup;r&&(this.ya(r).dirty=!0)}ya(e){return this.Jo[e]||(this.Jo[e]={})}},St={GZipJS:"gzip-js",Base64:"base64"},vi={Activation:"events",Cancellation:"cancelEvents"},Ba={Popover:"popover",API:"api",Widget:"widget",ExternalSurvey:"external_survey"},or={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent",ABANDONED:"survey abandoned"},Ga={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"},Zc={Popover:"popover",Inline:"inline"};function ws(e){let t=!0;return{dispose(){if(t){t=!1;const r=e();r&&tt(r.then)&&r.then(void 0,()=>{})}}}}var qw={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"},Kd={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"},Yd=Ge("[RateLimiter]"),jw=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=>{Yd.info(`${n||"events"} is quota limited.`),this.serverLimits[n]=new Date().getTime()+6e4})}catch(n){Yd.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=(Ze(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")&&He?.pathname)return`${(e=He.origin)!==null&&e!==void 0?e:""}${He.pathname}`}Ka(e){var t,r;const{captureEventsBurstLimit:n,captureEventsPerSecond:i}=this,s=this.Ya(),o=this.Xa("$session_id")?(t=(r=this.instance).get_session_id)===null||t===void 0?void 0:t.call(r):void 0,a=[`${e} event(s) dropped since the last warning`,s?`triggered on ${s}`:void 0,o?`session ${o}`:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:`posthog-js client rate limited: ${a}. Config is set to ${i} events per second and ${n} events burst limit.`},{skip_client_rate_limiting:!0})}isServerRateLimited(e){const t=this.serverLimits[e||"events"]||!1;return t!==!1&&new Date().getTime()<t}},dr=Ge("[RemoteConfig]"),Jv=class{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=te._POSTHOG_REMOTE_CONFIG)===null||e===void 0||(e=e[this._instance.config.token])===null||e===void 0?void 0:e.config}tl(e){var t,r,n;!((t=te.__PosthogExtensions__)===null||t===void 0)&&t.loadExternalDependency?(r=te.__PosthogExtensions__)===null||r===void 0||(n=r.loadExternalDependency)===null||n===void 0||n.call(r,this._instance,"remote-config",()=>e(this.remoteConfig)):e()}el(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets",`/array/${this._instance.config.token}/config`),callback:e})}load(){try{if(this.remoteConfig)return dr.info("Using preloaded remote config",this.remoteConfig),void this.il(this.remoteConfig);if(this._instance.nl())return void dr.warn("Remote config is disabled. Falling back to local config.");this.tl(e=>{if(!e)return dr.info("No config found after loading remote JS config. Falling back to JSON."),void this.el(t=>{this.il(t.json,t)});this.il(e)})}catch(e){dr.error("Error loading remote config",e),this.il()}}il(e,t){!e&&t&&(t.statusCode===0?t.error||dr.warn("Failed to fetch remote config from PostHog."):dr.error("Failed to fetch remote config from PostHog."));try{this._instance.il(e?{ok:!0,config:e}:{ok:!1})}catch(n){dr.error("Error applying remote config",n)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var r;(r=this._instance.featureFlags)===null||r===void 0||r.ensureFlagsLoaded()}catch(n){dr.error("Error loading feature flags",n)}}},Et=Uint8Array,gt=Uint16Array,Xn=Uint32Array,nu=new Et([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),iu=new Et([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Xd=new Et([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Kv=function(e,t){for(var r=new gt(31),n=0;31>n;++n)r[n]=t+=1<<e[n-1];var i=new Xn(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]},Yv=Kv(nu,2),Jc=Yv[1];Yv[0][28]=258,Jc[258]=28;for(var Qd=Kv(iu,0)[1],Kc=new gt(32768),Be=0;32768>Be;++Be){var wn=(43690&Be)>>>1|(21845&Be)<<1;Kc[Be]=((65280&(wn=(61680&(wn=(52428&wn)>>>2|(13107&wn)<<2))>>>4|(3855&wn)<<4))>>>8|(255&wn)<<8)>>>1}var Ui=function(e,t,r){for(var n=e.length,i=0,s=new gt(t);n>i;++i)++s[e[i]-1];var o,a=new gt(t);for(i=0;t>i;++i)a[i]=a[i-1]+s[i-1]<<1;if(r){o=new gt(1<<t);var c=15-t;for(i=0;n>i;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],h=a[e[i]-1]++<<u,d=h|(1<<u)-1;d>=h;++h)o[Kc[h]>>>c]=l}else for(o=new gt(n),i=0;n>i;++i)o[i]=Kc[a[e[i]-1]++]>>>15-e[i];return o},hn=new Et(288);for(Be=0;144>Be;++Be)hn[Be]=8;for(Be=144;256>Be;++Be)hn[Be]=9;for(Be=256;280>Be;++Be)hn[Be]=7;for(Be=280;288>Be;++Be)hn[Be]=8;var mo=new Et(32);for(Be=0;32>Be;++Be)mo[Be]=5;var Hw=Ui(hn,9,0),Vw=Ui(mo,5,0),Xv=function(e){return(e/8|0)+(7&e&&1)},Qv=function(e,t,r){(t==null||0>t)&&(t=0),(r==null||r>e.length)&&(r=e.length);var n=new(e instanceof gt?gt:e instanceof Xn?Xn:Et)(r-t);return n.set(e.subarray(t,r)),n},Kt=function(e,t,r){var n=t/8|0;e[n]|=r<<=7&t,e[n+1]|=r>>>8},gi=function(e,t,r){var n=t/8|0;e[n]|=r<<=7&t,e[n+1]|=r>>>8,e[n+2]|=r>>>16},Wa=function(e,t){for(var r=[],n=0;e.length>n;++n)e[n]&&r.push({s:n,f:e[n]});var i=r.length,s=r.slice();if(!i)return[new Et(0),0];if(i==1){var o=new Et(r[0].s+1);return o[r[0].s]=1,[o,1]}r.sort(function(C,$){return C.f-$.f}),r.push({s:-1,f:25001});var a=r[0],c=r[1],l=0,u=1,h=2;for(r[0]={s:-1,f:a.f+c.f,l:a,r:c};u!=i-1;)a=r[r[h].f>r[l].f?l++:h++],c=r[l!=u&&r[h].f>r[l].f?l++:h++],r[u++]={s:-1,f:a.f+c.f,l:a,r:c};var d=s[0].s;for(n=1;i>n;++n)s[n].s>d&&(d=s[n].s);var p=new gt(d+1),f=Yc(r[u-1],p,0);if(f>t){n=0;var v=0,m=f-t,_=1<<m;for(s.sort(function(C,$){return p[$.s]-p[C.s]||C.f-$.f});i>n;++n){var w=s[n].s;if(t>=p[w])break;v+=_-(1<<f-p[w]),p[w]=t}for(v>>>=m;v>0;){var S=s[n].s;t>p[S]?v-=1<<t-p[S]++-1:++n}for(;n>=0&&v;--n){var I=s[n].s;p[I]==t&&(--p[I],++v)}f=t}return[new Et(p),f]},Yc=function(e,t,r){return e.s==-1?Math.max(Yc(e.l,t,r+1),Yc(e.r,t,r+1)):t[e.s]=r},eh=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new gt(++t),n=0,i=e[0],s=1,o=function(c){r[n++]=c},a=1;t>=a;++a)if(e[a]==i&&a!=t)++s;else{if(!i&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(i),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(i);s=1,i=e[a]}return[r.subarray(0,n),t]},mi=function(e,t){for(var r=0,n=0;t.length>n;++n)r+=e[n]*t[n];return r},qs=function(e,t,r){var n=r.length,i=Xv(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)},th=function(e,t,r,n,i,s,o,a,c,l,u){Kt(t,u++,r),++i[256];for(var h=Wa(i,15),d=h[0],p=h[1],f=Wa(s,15),v=f[0],m=f[1],_=eh(d),w=_[0],S=_[1],I=eh(v),C=I[0],$=I[1],M=new gt(19),L=0;w.length>L;++L)M[31&w[L]]++;for(L=0;C.length>L;++L)M[31&C[L]]++;for(var q=Wa(M,7),X=q[0],ee=q[1],k=19;k>4&&!X[Xd[k-1]];--k);var ie,H,oe,T,Q=l+5<<3,y=mi(i,hn)+mi(s,mo)+o,V=mi(i,d)+mi(s,v)+o+14+3*k+mi(M,X)+(2*M[16]+3*M[17]+7*M[18]);if(y>=Q&&V>=Q)return qs(t,u,e.subarray(c,c+l));if(Kt(t,u,1+(y>V)),u+=2,y>V){ie=Ui(d,p,0),H=d,oe=Ui(v,m,0),T=v;var K=Ui(X,ee,0);for(Kt(t,u,S-257),Kt(t,u+5,$-1),Kt(t,u+10,k-4),u+=14,L=0;k>L;++L)Kt(t,u+3*L,X[Xd[L]]);u+=3*k;for(var le=[w,C],de=0;2>de;++de){var $e=le[de];for(L=0;$e.length>L;++L)Kt(t,u,K[Re=31&$e[L]]),u+=X[Re],Re>15&&(Kt(t,u,$e[L]>>>5&127),u+=$e[L]>>>12)}}else ie=Hw,H=hn,oe=Vw,T=mo;for(L=0;a>L;++L)if(n[L]>255){var Re;gi(t,u,ie[257+(Re=n[L]>>>18&31)]),u+=H[Re+257],Re>7&&(Kt(t,u,n[L]>>>23&31),u+=nu[Re]);var _e=31&n[L];gi(t,u,oe[_e]),u+=T[_e],_e>3&&(gi(t,u,n[L]>>>5&8191),u+=iu[_e])}else gi(t,u,ie[n[L]]),u+=H[n[L]];return gi(t,u,ie[256]),u+H[256]},Bw=new Xn([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Gw=new Et(0),Ww=(function(){for(var e=new Xn(256),t=0;256>t;++t){for(var r=t,n=9;--n;)r=(1&r&&3988292384)^r>>>1;e[t]=r}return e})(),Za=function(e,t,r){for(;r;++t)e[t]=r,r>>>=8};function Zw(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=Ww[255&f^p[v]]^f>>>8;d=f},d(){return 4294967295^d}}})(),n=e.length;r.p(e);var i,s,o,a,c,l,u=(a=10+((i=t).filename&&i.filename.length+1||0),c=8,(function(d,p,f,v,m,_){var w=d.length,S=new Et(v+w+5*(1+Math.floor(w/7e3))+m),I=S.subarray(v,S.length-m),C=0;if(!p||8>w)for(var $=0;w>=$;$+=65535){var M=$+65535;w>M?C=qs(I,C,d.subarray($,M)):(I[$]=_,C=qs(I,C,d.subarray($,w)))}else{for(var L=Bw[p-1],q=L>>>13,X=8191&L,ee=(1<<f)-1,k=new gt(32768),ie=new gt(ee+1),H=Math.ceil(f/3),oe=2*H,T=function(g){return(d[g]^d[g+1]<<H^d[g+2]<<oe)&ee},Q=new Xn(25e3),y=new gt(288),V=new gt(32),K=0,le=0,de=($=0,0),$e=0,Re=0;w>$;++$){var _e=T($),ve=32767&$,qe=ie[_e];if(k[ve]=qe,ie[_e]=ve,$>=$e){var Xe=w-$;if((K>7e3||de>24576)&&Xe>423){C=th(d,I,0,Q,y,V,le,de,Re,$-Re,C),de=K=le=0,Re=$;for(var Pe=0;286>Pe;++Pe)y[Pe]=0;for(Pe=0;30>Pe;++Pe)V[Pe]=0}var N=2,se=0,ae=X,he=ve-qe&32767;if(Xe>2&&_e==T($-he))for(var Oe=Math.min(q,Xe)-1,we=Math.min(32767,$),Se=Math.min(258,Xe);we>=he&&--ae&&ve!=qe;){if(d[$+N]==d[$+N-he]){for(var pe=0;Se>pe&&d[$+pe]==d[$+pe-he];++pe);if(pe>N){if(N=pe,se=he,pe>Oe)break;var me=Math.min(he,pe-2),Ee=0;for(Pe=0;me>Pe;++Pe){var We=$-he+Pe+32768&32767,U=We-k[We]+32768&32767;U>Ee&&(Ee=U,qe=We)}}}he+=(ve=qe)-(qe=k[ve])+32768&32767}if(se){Q[de++]=268435456|Jc[N]<<18|Qd[se];var W=31&Jc[N],Y=31&Qd[se];le+=nu[W]+iu[Y],++y[257+W],++V[Y],$e=$+N,++K}else Q[de++]=d[$],++y[d[$]]}}C=th(d,I,_,Q,y,V,le,de,Re,$-Re,C),_||(C=qs(I,C,Gw))}return Qv(S,0,v+Xv(C)+m)})(s=e,(o=t).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,c,!l)),h=u.length;return(function(d,p){var f=p.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>p.level?4:p.level==9?2:0,d[9]=3,p.mtime!=0&&Za(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),Za(u,h-8,r.d()),Za(u,h-4,n),u}var Jw=!!Fl||!!Vi,eg=new WeakMap,tg="text/plain",Ja=0,js=!1,rg=(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}`:""}`},ss=(e,t,r=!0)=>{var n;const[i,s]=e.split("?"),o=b({},t),a=(n=s?.split("&").map(l=>{var u;const[h,d]=l.split("="),p=r&&(u=o[h])!==null&&u!==void 0?u:d;return delete o[h],`${h}=${p}`}))!==null&&n!==void 0?n:[],c=(function(l,u="&"){let h,d;const p=[];return Ce(l,function(f,v){O(f)||O(v)||v==="undefined"||(h=encodeURIComponent((m=>m instanceof File)(f)?f.name:f.toString()),d=encodeURIComponent(v),p[p.length]=d+"="+h)}),p.join(u)})(o);return c&&a.push(c),a.length>0?`${i}?${a.join("&")}`:i},Ka=e=>{if(e.sl)return e.sl;const{data:t,compression:r}=e;if(!t)return;if(r===St.GZipJS){const i=Zw((function(s){var o=s.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(s);for(var a=new Et(s.length+(s.length>>>1)),c=0,l=function(p){a[c++]=p},u=0;o>u;++u){if(c+5>a.length){var h=new Et(c+8+(o-u<<1));h.set(a),a=h}var d=s.charCodeAt(u);128>d?l(d):2048>d?(l(192|d>>>6),l(128|63&d)):d>55295&&57344>d?(l(240|(d=65536+(1047552&d)|1023&s.charCodeAt(++u))>>>18),l(128|d>>>12&63),l(128|d>>>6&63),l(128|63&d)):(l(224|d>>>12),l(128|d>>>6&63),l(128|63&d))}return Qv(a,0,c)})(Cn(t)),{mtime:0});return{contentType:tg,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(r===St.Base64){const i=(s=>"data="+encodeURIComponent(typeof s=="string"?s:Cn(s)))((function(s){return s&&btoa(encodeURIComponent(s).replace(/%([0-9A-F]{2})/g,(o,a)=>String.fromCharCode(parseInt(a,16))))})(Cn(t)));return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}const n=Cn(t);return{contentType:"application/json",body:n,estimatedSize:new Blob([n]).size}},ng=e=>{const t=()=>e.transport==="sendBeacon"?{url:ss(e.url,{compression:St.Base64}),encodedBody:Ka(b(b({},e),{},{compression:St.Base64,sl:void 0}))}:{url:rg(e.url,"compression"),encodedBody:Ka(b(b({},e),{},{compression:void 0,sl:void 0}))};let r;try{r=Ka(e)}catch(i){if(wd(e.compression,Kn(e.url,"compression")))return j.error("Failed to gzip request body, sending uncompressed payload",i),t();throw i}return r&&wd(e.compression,Kn(e.url,"compression"))&&!((n=r.body)instanceof ArrayBuffer?Oc(new Uint8Array(n)):ArrayBuffer.isView(n)&&Oc(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(js=!0,t()):{url:e.url,encodedBody:r};var n},ig=e=>{try{return ng(e)}catch(r){var t;j.error(r),(t=e.callback)===null||t===void 0||t.call(e,{statusCode:0,error:r});return}},Kw=(function(){var e=Ue(function*(t){const r=yield(function(i){return xc.apply(this,arguments)})(Cn(t.data),et.DEBUG,{rethrow:!0});if(!r)return t;const n=yield r.arrayBuffer();return b(b({},t),{},{sl:{contentType:tg,body:n,estimatedSize:n.byteLength}})});return function(t){return e.apply(this,arguments)}})(),Yw=/Failed to fetch|NetworkError|Load failed/i,sg=e=>e?.name==="TypeError"&&Yw.test(e?.message||""),og=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,Ns):void 0})(e());return O(t)?void 0:Math.min(t,3e4)}catch{return}},ag=e=>{const t=ig(e);if(!t)return;const r=new Fl;eg.set(r,!0);const{url:n,encodedBody:i}=t;r.open(e.method||"GET",n,!0);const{contentType:s,body:o}=i??{};Ce(e.headers,function(a,c){r.setRequestHeader(c,a)}),s&&r.setRequestHeader("Content-Type",s),e.timeout&&(r.timeout=e.timeout),r.onreadystatechange=()=>{if(r.readyState===4){var a;const c={statusCode:r.status,text:r.responseText};if(r.status===200)try{c.json=JSON.parse(r.responseText)}catch{}(a=e.callback)===null||a===void 0||a.call(e,c,og(()=>r.getResponseHeader("Retry-After")))}},r.send(o)},cg=e=>{const t=ig(e);if(!t)return;const{url:r,encodedBody:n}=t,{contentType:i,body:s,estimatedSize:o}=n??{},a=new Headers;Ce(e.headers,function(f,v){a.append(v,f)}),i&&a.append("Content-Type",i);let c=null,l=!1;if(sd){const f=new sd;c={signal:f.signal,timeout:setTimeout(()=>{l=!0;try{f.abort(jf("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"||sg(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=()=>{Ja-=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>Ja+v,f.keepalive&&(d=v,Ja+=d),Vi(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(I){j.error(I)}u=!0,p(),(w=e.callback)===null||w===void 0||w.call(e,S,og(()=>m.headers.get("Retry-After")))})).catch(m=>{p(),h(m)}).finally(p)}catch(f){p(),h(f)}},Xc=e=>{try{var t;const{url:r,encodedBody:n}=ng(e),{contentType:i,body:s,estimatedSize:o}=n??{};if(!s)return;const a=s instanceof Blob?s:new Blob([s],{type:i});if(rt.sendBeacon(r,a))return;const c=ce(e.data)?e.data:(t=e.data)===null||t===void 0?void 0:t.batch;if(ce(c)&&c.length>1&&(o??0)>16384){const l=Math.ceil(c.length/2),u=h=>ce(e.data)?h:b(b({},e.data),{},{batch:h});Xc(b(b({},e),{},{data:u(c.slice(0,l))})),Xc(b(b({},e),{},{data:u(c.slice(l))}));return}j.warn(`Beacon of ~${o??0} bytes was rejected by the browser, falling back to ${Vi?"fetch":"XHR"}`),Vi?cg(b(b({},e),{},{rl:!0})):ag(e)}catch(r){j.warn("Beacon send failed",r)}},rh=(e,t,r,n)=>{const i=n==="query"?t==="POST"?"sent_at":"_":void 0;return ss(r===St.GZipJS?rg(e,"compression"):e,b(b({},i?{[i]:Date.now().toString()}:{}),r===St.GZipJS?{}:{compression:r}))},Xw=(()=>{const e=[];return Vi&&e.push({transport:"fetch",method:cg}),Fl&&e.push({transport:"XHR",method:ag}),rt!=null&&rt.sendBeacon&&e.push({transport:"sendBeacon",method:Xc}),e})(),lg=!Jw&&pt?.indexOf("MSIE")===-1&&pt?.indexOf("Mozilla")===-1;function ug(e,t,r){var n,i,s;r&&(t=b(b({},t),{},{callback:o=>r(o)})),e.__loaded?lg?e.__request_queue.push(t):e.rateLimiter.isServerRateLimited(t.batchKey)?t.fireCallbackOnDrop&&((i=t.callback)===null||i===void 0||i.call(t,{statusCode:429})):(t.transport=t.transport||e.config.api_transport,t.headers=b(b({},e.config.request_headers),t.headers),t.compression=t.compression==="best-available"?(n=e.compression)!==null&&n!==void 0?n:t.compressionFallback:t.compression,(O(e.config.disable_beacon)?e.config.__preview_disable_beacon:e.config.disable_beacon)&&(t.disableTransport=["sendBeacon"]),t.fetchOptions=t.fetchOptions||e.config.fetch_options,((o,a)=>{var c,l,u;const h=b(b({},o),{},{callback:a??(m=>{var _;return(_=o.callback)===null||_===void 0?void 0:_.call(o,m)})});h.timeout=h.timeout||6e4;const d=(c=h.transport)!==null&&c!==void 0?c:"fetch";d==="sendBeacon"&&O(h.compression)&&h.data&&(h.compression=St.Base64),h.method==="POST"&&h.data&&(h.timestampMode==="capture-body"?h.data=(m=>{var _,w;const S=(ce(m)?m:[m]).map(C=>b(b({},C),C.timestamp instanceof Date&&!isNaN(C.timestamp.getTime())?{timestamp:C.timestamp.toISOString()}:{})),I=S[0];return{api_key:(_=I==null||(w=I.properties)===null||w===void 0?void 0:w.token)!==null&&_!==void 0?_:I?.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=rh(h.url,h.method,h.compression,h.timestampMode);const p=Xw.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 _;sg(w)?j.warn(w):j.error(w),(_=h.callback)===null||_===void 0||_.call(h,{statusCode:0,error:w})}};d!=="sendBeacon"&&!h.preferSyncCompression&&h.data&&h.compression===St.GZipJS&&L0&&typeof Promise<"u"&&!js?Kw(h).then(m=>{v(m)}).catch(m=>{if(Sd(m))return js=!0,void v(b(b({},h),{},{compression:void 0,url:rh(o.url,o.method,void 0,o.timestampMode)}));(_=>{if(!_||typeof _!="object")return!1;const w="name"in _?String(_.name):"";return Sd(_)||w===Jf})(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 Qw=class{constructor(e,t){this.ol=!0,this.al=[],this.ll=Bt(t?.flush_interval_ms||3e3,250,5e3,j.createLogger("flush interval"),3e3),this.ul=e}enqueue(e){this.al.push(e),this.hl||this.cl()}unload(){this.dl();const e=this.al.length>0?this.vl():{},t=Object.values(e);[...t.filter(r=>r.url.indexOf("/e")===0),...t.filter(r=>r.url.indexOf("/e")!==0)].map(r=>{this.fl(r,"sendBeacon")})}enable(){this.ol=!1,this.cl()}cl(){this.ol||(this.hl=setTimeout(()=>{if(this.dl(),this.al.length>0){const e=this.vl();for(const t in e)this.fl(e[t])}},this.ll))}fl(e,t){try{this.ul(e,t)}catch(r){j.error(r)}}dl(){clearTimeout(this.hl),this.hl=void 0}vl(){const e={};return Ce(this.al,t=>{var r;const n=t,i=((n?n.batchKey:null)||n.url)+(n.batchGroup?`:${n.batchGroup}`:"");O(e[i])&&(e[i]=b(b({},n),{},{data:[]})),(r=e[i].data)===null||r===void 0||r.push(n.data)}),this.al=[],e}},eS=["retriesPerformedSoFar"],tS=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},Te(A,"online",this.yl),Te(A,"offline",this._l)}}get length(){return this.al.length}retriableRequest(e,t){let{retriesPerformedSoFar:r}=e,n=Kf(e,eS);Qt(r)&&(n.url=ss(n.url,{retry_count:r})),ug(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=[]}},rS=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(){Te(A,"scroll",this.Sl,{capture:!0}),Te(A,"scrollend",this.Sl,{capture:!0}),Te(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")}},nS=e=>Bv(e?.config.mask_personal_data_properties,e?.config.custom_personal_data_properties,e?.config.disable_capture_url_hashes),nh=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({[jc]:o})},this._instance=e,this.El=t,this.Ml=r,this.Il=n||nS,this.El.onSessionId(this.Be)}Tl(){return this.Ml.props[jc]}getSetOnceProps(){var e;const t=(e=this.Tl())===null||e===void 0?void 0:e.props;return t?"r"in t?Gv(t,this._instance.config.disable_capture_url_hashes):{$referring_domain:t.referringDomain,$pathname:t.initialPathName,utm_source:t.utm_source,utm_campaign:t.utm_campaign,utm_medium:t.utm_medium,utm_content:t.utm_content,utm_term:t.utm_term}:{}}getSessionProps(){const e={};return Ce(Xl(this.getSetOnceProps()),(t,r)=>{r==="$current_url"&&(r="url"),e[`$session_entry_${Ac(r)}`]=t}),e}},_o=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={}}},Sn=Ge("[SessionId]"),ih=864e5,sh=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 _o,this.Nl=(s,o)=>!(!Qt(s)||!Qt(o))&&Math.abs(s-o)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Rr=e.config,this.Ml=e.persistence,this.He=void 0,this.Xt=void 0,this._sessionStartTimestamp=null,this.ql=void 0,this._sessionActivityTimestamp=null,this.jl=t||Lt,this.Bl=r||Lt;const i=this.Rr.persistence_name||this.Rr.token;if(this._sessionTimeoutMs=1e3*Bt(this.Rr.session_idle_timeout_seconds||1800,60,36e3,Sn.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!Ve(t)&&!Ve(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({[An]:[t,e,r]}))}Kl(){var e;const t=(e=this.Rr)===null||e===void 0?void 0:e.persistence_save_debounce_ms;return Qt(t)&&t>0}Xl(){this.Kl()?this.Ml.refreshKey(An):(this.Ml.flush(),this.Ml.load())}Yl(){var e;if(Ve(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({[An]:[this._sessionActivityTimestamp,(e=this.Xt)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Ml.flush())}eu(){const[e]=this.tu(),t=Qt(e)?e:0,r=Qt(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[An];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 Sn.error("Bootstrap sessionID cannot be in the future"):s}catch(s){Sn.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(po,this.Dl,{capture:!1}),this.Dl=void 0),this.Ol=[]}Vl(){this.Dl=()=>{this.Yl(),this.Wl()&&xe.Lt(this.Ul)},Te(A,po,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(Ve(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>ih),f=d?p:Qt(c)&&Math.abs(n-c)>ih;let v=!1,m=l,_=!a||!!d;const w=a;let S=!_&&!e&&this.Nl(n,u);if(S&&(S=this.iu(n),S||Sn.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(),Sn.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&&(Sn.info("adopted cross-tab session id",{sessionId:a,windowId:h}),v=!0);const I=Qt(u)&&e&&!f?u:n,C=Qt(c)?c:new Date().getTime();this.Gl(h),this.Jl(a,I,C),e||this.Hl();const $={noSessionId:_,activityTimeout:S,sessionPastMaximumLength:f,crossTabAdoption:m};return v&&this.Ol.forEach(M=>M(a,h,$)),{sessionId:a,windowId:h,sessionStartTimestamp:C,changeReason:v?$:void 0,lastActivityTimestamp:u}}Hl(){this.Ll||(clearTimeout(this.nu),this.nu=setTimeout(()=>{if(!this.Ll)if(this.iu(new Date().getTime())){const e=this.Xt;this.resetSessionId(),this.Rl.emit("forcedIdleReset",{idleSessionId:e})}else this.Hl()},1.1*this.sessionTimeoutMs))}},dg=function(e,t){if(!e)return!1;const r=e.userAgent;if(r&&cd(r,t))return!0;try{const n=e?.userAgentData;if(n?.brands&&n.brands.some(i=>cd(i?.brand,t)))return!0}catch{}return!!e.webdriver};function hg(){return(hg=Ue(function*(){const e=rt?.userAgentData;if(e?.getHighEntropyValues)try{const t=yield e.getHighEntropyValues(["model"]),r=t?.model;return ye(r)&&r.length>0?r:void 0}catch(t){j.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",t);return}})).apply(this,arguments)}function iS(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 pg(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 yo=(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}},Ss=e=>e.toLowerCase(),fg={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=>yo(r,n))),not_regex:(e,t)=>t.every(r=>e.every(n=>!yo(r,n))),icontains:(e,t)=>t.map(Ss).some(r=>e.map(Ss).some(n=>r.includes(n))),not_icontains:(e,t)=>t.map(Ss).every(r=>e.map(Ss).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 vg(e,t){return!e||Object.entries(e).every(([r,n])=>{const i=t?.[r];if(i==null)return!1;const s=fg[n.operator];return!!s&&s(n.values.map(String),[String(i)])})}function Ya(e,t,r){return Cn({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:r})}var Qc="custom",oh="i.posthog.com",sS=/^\/static\//,oS=["/s/","/e/","/i/"],aS=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(`.${oh}`,".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":Qc),this.su[this.apiHost]}ru(e){if(!sS.test(e))return;const t=this.instance.config.asset_host;return typeof t=="string"&&t.trim().replace(/\/$/,"")||void 0}ou(e){const t=Or(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=Or(r))===null||s===void 0?void 0:s.href)||r;n=i(new URL(o)).toString()}if(i&&e==="api"&&oS.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===Qc)return this.au(e,t,this.apiHost+t);const r=oh+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}`)}}},Ie=Ge("[Surveys]"),gg=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){Ie.error("Failed to persist survey seen state",t)}},cS=[Ba.Popover,Ba.Widget,Ba.API],lS={ignoreConditions:!1,ignoreDelay:!1,displayType:Zc.Popover},uS=Ge("[PostHog ExternalIntegrations]"),dS={intercom:"intercom-integration",crispChat:"crisp-chat-integration"},hS=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 uS.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(dS[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())}}},pS=class{constructor(e,t){this.$=e,this.wo=t,this.uu=new Map,this.Io=!1}add(e){var t=this;return Ue(function*(){if(t.Io)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(t.uu.has(e.name))throw new Error(`Browser extension "${e.name}" is already registered`);t.uu.set(e.name,e);try{const r=e.setup(t.wo);r&&(yield r)}catch(r){const n=t.uu.get(e.name)===e;n&&t.uu.delete(e.name),t.$.error(`Failed to set up browser extension "${e.name}"`,r),n&&t.hu(e)}})()}getExtension(e){return this.uu.get(e)}dispose(){if(this.Io)return;this.Io=!0;const e=Array.from(this.uu.values()).reverse();this.uu.clear();for(const t of e)this.hu(t)}hu(e){try{var t;const r=(t=e.dispose)===null||t===void 0?void 0:t.call(e);r&&tt(r.then)&&r.then(void 0,n=>{this.$.error(`Failed to dispose browser extension "${e.name}"`,n)})}catch(r){this.$.error(`Failed to dispose browser extension "${e.name}"`,r)}}},fS=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)}},ah="extensionsRemoteConfig",vS=class{constructor(e){this.instance=e,this.Io=!1,this.$=j,this.cu=e.du,this.kv=new fS(e),this.onEvent=t=>ws(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 ws(()=>{});const r=i=>{try{t(i)}catch(s){this.$.error("Browser extension remote config listener failed",s)}},n=this.instance.vu.on(ah,r);return this.cu&&r(this.cu),ws(n)},this.fu=new pS(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(Gl);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 ws(this.instance.pu(e))}handleRemoteConfig(e){this.Io||(this.cu=e,this.instance.vu.emit(ah,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?ss(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"?Rc.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())}},Fi={},Xa=0,qi=()=>{},ch='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',_i="Surveys module not available",lh="sanitize_properties is deprecated. Use before_send instead",mg="Invalid value for property_denylist config: ",gS=/^[A-Za-z0-9_-]{1,400}$/,uh=/^fb\.[0-9]+\.[0-9]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?$/,dh=/^fb\.[0-9]+\.[0-9]+\.[0-9]+$/,mS=["token","distinct_id",_v],Ri="posthog",_S=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},Qa=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:gw(z?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:qi,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:He&&ye(He?.search)&&He.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:Ev,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:3e3},error_tracking:{},_onCapture:qi},(r=>({rageclick:r&&r>="2026-05-30"?{content_ignorelist:kw,ignore_text_selection:!0}:!r||"2025-11-30">r||{content_ignorelist:!0},capture_pageview:!r||"2025-05-24">r||"history_change",session_recording:_S(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))},yS=[["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"]],hh=e=>{const t={};for(const[i,s]of yS)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(mg+e.property_denylist)),r},bS=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}},ji=class pr{mu(t){if(!t)return;const r=this.uu.indexOf(t);r!==-1&&this.uu.splice(r,1)}yu(t,r){var n;return this.mu(t),this.uu.push(r),(n=r.initialize)===null||n===void 0||n.call(r),r}bu(){return this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isRejected()}_u(){if(this.wu||this.config.reuseAnonymousId||this.config.segment||this.bu())return;const t=this.config.persistence==="memory"||this.config.persistence==="sessionStorage";if(!t&&!this.config.disable_persistence||this.ku)return;let r,n,i;t?(r=`persistence is set to '${this.config.persistence}'`,n=this.config.persistence==="memory"?"on every page load":"for every new browser tab or window",i="Either set persistence to 'localStorage+cookie', keep this persistence and pass a stable ID through bootstrap.distinctID, or enable reuseAnonymousId."):(r="persistence is disabled (disable_persistence is true)",n="on every page load",i="Either set disable_persistence to false, keep persistence disabled and pass a stable ID through bootstrap.distinctID, or enable reuseAnonymousId."),this.wu=!0,console.warn("[PostHog.js]",`${r} but no bootstrap.distinctID was provided. PostHog will mint a new distinct ID ${n}, so calling identify() merges a new ID onto the person each time. A person can then pass the distinct-ID limit and its events stop appearing on person pages and the session tab. ${i}`)}Su(){if(this.bu()||this.get_distinct_id()!=="$posthog_cookieless")return;const t=this.persistence;if(!t)return;this.xu()||t.load(!0);const r=this.get_distinct_id();if(!r||r==="$posthog_cookieless"){const n=this.config.get_device_id(Lt());this.register({distinct_id:n,$device_id:n}),t.set_property(ft,sr)}this.Cu()}get decideEndpointWasHit(){var t,r;return(t=(r=this.featureFlags)===null||r===void 0?void 0:r.hasLoadedFlags)!==null&&t!==void 0&&t}get flagsEndpointWasHit(){var t,r;return(t=(r=this.featureFlags)===null||r===void 0?void 0:r.hasLoadedFlags)!==null&&t!==void 0&&t}constructor(){var t;this.$u=!1,this.Tu=!1,this.webPerformance=new bS,this.Iu=!1,this.version=et.LIB_VERSION,this.Mu=new Set,this.Eu="",this.vu=new _o,this.uu=[],this.Pu=[],this.ku=!1,this.wu=!1,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Qa(),this.SentryIntegration=Ow,this.sentryIntegration=n=>(function(i,s){const o=zv(i,s);return{name:Dv,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 rS(this),this.pageViewManager=new Wd(this),this.rateLimiter=new jw(this),this.requestRouter=new aS(this),this.consent=new Ew(this),this.externalIntegrations=new hS(this);const r=(t=pr.__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!==Ri){var i;const s=(i=Fi[n])!==null&&i!==void 0?i:new pr;return s._init(t,r,n),Fi[n]=s,Fi[Ri][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=Qa(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=Qa(r.defaults),u=hh(r),h=Le({},l,u,{name:n,token:a});be(l.rageclick)&&be(u.rageclick)&&(h.rageclick=Le({},l.rageclick,u.rageclick)),be(l.session_recording)&&be(u.session_recording)&&(h.session_recording=Le({},l.session_recording,u.session_recording)),this.set_config(h),this.config.on_xhr_error&&j.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=r.disable_compression?void 0:St.GZipJS;const d=this.xu();if(this.persistence=new Va(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Va(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 Qw((_,w)=>this.ju(_,w),this.config.request_queue_config),this.Bu=new tS(this),this.__request_queue=[];const v=this.bu();v||(this.sessionManager=new sh(this),this.sessionPropsManager=new nh(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&&!Pi(m),(o=r.bootstrap)===null||o===void 0?void 0:o.distinctID){const _=r.bootstrap.distinctID,w=this.get_distinct_id(),S=this.persistence.get_property(ft);if(r.bootstrap.isIdentifiedID&&w!=null&&w!==_&&S==="anonymous")this.identify(_);else if(r.bootstrap.isIdentifiedID&&w!=null&&w!==_&&S==="identified")j.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{const I=this.config.get_device_id(Lt()),C=r.bootstrap.isIdentifiedID?I:_;this.persistence.set_property(ft,r.bootstrap.isIdentifiedID?Us:sr),this.register({distinct_id:_,$device_id:C})}}if(v)this.register_once({distinct_id:Da,$device_id:null},"");else if(!this.get_distinct_id()){const _=this.config.get_device_id(Lt());this.register_once({distinct_id:_,$device_id:_},""),this.persistence.set_property(ft,sr)}return Te(A,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),Te(A,"pageshow",()=>{var _;this.$u=!1,this.Tu||(_=this.Bu)===null||_===void 0||_.resume()}),r.segment?Gd(this,()=>this.Wu()):this.Wu(),tt(this.config._onCapture)&&this.config._onCapture!==qi&&(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 hg.apply(this,arguments)})().then(_=>{_&&this.register({[La]:_})}).catch(qi),this}Vu(t){const r=t;return ye(r.name)&&tt(r.setup)}Gu(t,r){this.Vu(t)?r.push(()=>{this.Zu().add(t).catch(()=>{var n;return(n=t.dispose)===null||n===void 0?void 0:n.call(t)}).catch(n=>{j.error(`Failed to dispose browser extension "${t.name}"`,n)})}):this.uu.push(t)}zu(){var t,r,n;const i=(t=(r=this.config.__extensionClasses)===null||r===void 0?void 0:r.featureFlags)!==null&&t!==void 0?t:(n=pr.__defaultExtensionClasses)===null||n===void 0?void 0:n.featureFlags;var s,o,a;i&&(this.featureFlags&&this.featureFlags instanceof i||((s=this.Qu)===null||s===void 0||s.call(this),this.Qu=void 0,this.featureFlags=new i(this)),tt(this.featureFlags.onReloading)&&tt(this.featureFlags.setup)?this.Qu||(this.Qu=this.featureFlags.onReloading(()=>{this.vu.emit("featureFlagsReloading",!0)}),this.Zu().add(this.featureFlags)):(o=(a=this.featureFlags).initialize)===null||o===void 0||o.call(a))}Uu(t){const r=performance.now(),n=b(b({},pr.__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,Pw)),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({[yv]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[bv]:n}),this.config.__preview_deferred_init_extensions&&j.info(`PostHog extensions initialized (${n}ms)`)}il(t){var r;if(!z||!z.body)return j.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this.il(t)},500);if(this.config.__preview_deferred_init_extensions&&(this.Ju=t),this.du=t,this.compression=void 0,t.ok){var n;const i=t.config;i.supportedCompression&&!this.config.disable_compression&&(this.compression=ue(i.supportedCompression,St.GZipJS)?St.GZipJS:ue(i.supportedCompression,St.Base64)?St.Base64:void 0),(n=i.analytics)!==null&&n!==void 0&&n.endpoint&&(this.analyticsDefaultEndpoint=i.analytics.endpoint)}this.set_config({person_profiles:this.Fu?this.Fu:Ev}),(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&&He?.hostname){const t=He.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 Jv(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()&&In(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($d),(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($d,null,{transport:"sendBeacon"})}_send_request(t){ug(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){Xa++;try{let r;const n=[],i=[],s=[];In(t,a=>{if(a)if(r=a[0],ce(r))s.push(a);else if(tt(a))try{a.call(this)}catch(c){j.error("Error executing queued PostHog call",a,c)}else ce(a)&&r==="alias"?n.push(a):ce(a)&&r.indexOf("capture")!==-1&&tt(this[r])?s.push(a):i.push(a)});const o=function(a,c){In(a,function(l){try{if(ce(l[0])){let u=c;Ce(l,function(h){u=u[h[0]].apply(u,h.slice(1))})}else c[l[0]].apply(c,l.slice(1))}catch(u){j.error("Error executing queued PostHog call",l,u)}})};o(n,this),o(i,this),o(s,this)}finally{Xa--}}push(t){if(Xa>0&&ce(t)&&ye(t[0])){const r=pr.prototype[t[0]];tt(r)&&r.apply(this,t.slice(1));return}this._execute_array([t])}get nh(){return{property:Id,persistenceKey:Fn,cookieName:"_fbc",pattern:uh,register:(t,r)=>{var n;return(n=this.persistence)===null||n===void 0?void 0:n.register({[Fn]:{value:t,delivered:r}})},unregister:()=>{var t;return(t=this.persistence)===null||t===void 0?void 0:t.unregister(Fn)}}}get sh(){return{property:Cd,persistenceKey:xi,cookieName:"_fbp",pattern:dh,register:(t,r)=>{var n;return(n=this.persistence)===null||n===void 0?void 0:n.register({[xi]:{value:t,delivered:r}})},unregister:()=>{var t;return(t=this.persistence)===null||t===void 0?void 0:t.unregister(xi)}}}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=Di(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)&&uh.test(r)?this.oh(s,r,o):void s.unregister();const a=ye(t)&&gS.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)&&dh.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=hd(n?.uuid,Lt);let d={uuid:h,event:t,properties:this.calculateEventProperties(t,r||{},u,h)};t==="$pageview"&&this.config.__preview_capture_bot_pageviews&&o&&(d.event="$bot_pageview",d.properties.$browser_type="bot"),a&&(d.properties.$lib_rate_limit_remaining_tokens=a.remainingTokens);const p=t==="$feature_flag_called"&&d.properties.$feature_flag_has_experiment===!1&&this.get_property("$minimal_flag_called_events")===!0;n!=null&&n.$set&&!p&&(d.$set=n?.$set);const f=be(r?.$set)?r.$set:void 0,v=ce(r?.$unset)?r.$unset:[],m=n?.$unset||[],_=H=>{var oe;const T=!!n?.$set&&H in n.$set;return{hasProvided:T||!!f&&H in f,provided:T?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=_(Id),S=_(Cd),I=[{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:T}of I)T&&d.properties.$process_person_profile===!0&&T.pending&&!oe&&!p&&(d.$set=b({[H.property]:T.value},d.$set));const C=n?.$unset;C&&(d.$unset=C);const $=p?void 0:this.ph(n?.$set_once,t!==Pd,t===kv);if($&&(d.$set_once=$),n!=null&&n._noTruncate||(M=this.config.properties_string_max_length,d=(function(H,oe){const T=new Set;return(function Q(y,V){if(y!==Object(y))return oe?oe(y):y;if(T.has(y))return;let K;if(T.add(y),ce(y))K=[],In(y,le=>{K.push(Q(le))});else{const le={};Ce(si(y)?Rv(y):y,(de,$e)=>{T.has(de)||(le[$e]=Q(de,$e))}),K=le}return K})(H)})(d,H=>ye(H)?H.slice(0,M):H)),d.timestamp=u,O(n?.timestamp)||(d.properties.$event_time_override_provided=!0,d.properties.$event_time_override_system_time=l),p&&(d.properties=((H,oe=[])=>{const T={},Q=y=>{H[y]!==void 0&&(T[y]=H[y])};return Cb.forEach(Q),oe.forEach(Q),T})(d.properties,mS)),t===or.DISMISSED||t===or.SENT){const H=r?.[Ga.SURVEY_ID],oe=r?.[Ga.SURVEY_ITERATION];gg({id:H,current_iteration:oe}),d.$set=b(b({},d.$set),{},{[iS({id:H,current_iteration:oe},t===or.SENT?"responded":"dismissed")]:!0})}else t===or.SHOWN&&(d.$set=b(b({},d.$set),{},{[Ga.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));var M;if(t===qw.SHOWN){const H=r?.[Kd.TOUR_TYPE];H&&(d.$set=b(b({},d.$set),{},{[`${Kd.TOUR_LAST_SEEN_DATE}/${H}`]:new Date().toISOString()}))}const L=b(b({},d.properties.$set),d.$set);if(mt(L)||this.setPersonPropertiesForFlags(L),!fe(this.config.before_send)){const H=this.Os(d);if(!H)return;d=H,d.uuid=hd(d.uuid,Lt)}const q=I.filter(({channel:H,update:oe})=>{var T,Q,y;const V=(T=(Q=d.$set)===null||Q===void 0?void 0:Q[H.property])!==null&&T!==void 0?T: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:T}of q)this.dh(oe,T.value)}}:{});if(!this.config.request_batching||n&&!n?._batchKey||n?.send_instantly||q.length){var ie;let H;!k.transport&&!k.callback&&mt((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 vS(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[_v]=!0),t==="$snapshot"){const w=b(b({},this.persistence.properties()),this.sessionPersistence.properties());return a.distinct_id=w.distinct_id,(!ye(a.distinct_id)&&!Ze(a.distinct_id)||Pi(a.distinct_id))&&j.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}const c=(function(w,S,I,C=!1){var $,M,L,q;if(!pt)return{};const X=w?[...Yn,...S||[]]:[],[ee,k]=Nf(pt),[ie,H]=(function(Re){for(let _e=0;dd.length>_e;_e++){const[ve,qe,Xe]=dd[_e],Pe=Re.match(ve);if(Pe){const N=Xe&&Re.match(Xe)||Pe;return[qe,N?.[1]||""]}}return["",""]})(pt),oe=(function(){const Re="u">typeof navigator?navigator:void 0;return Re?.brave?{brave:!0}:{}})(),T={};O(I)||(T.detectGoogleSearchApp=I);const Q={},y=($=navigator)===null||$===void 0||($=$.userAgentData)===null||$===void 0?void 0:$.platform,V=(M=navigator)===null||M===void 0?void 0:M.maxTouchPoints,K=A==null||(L=A.screen)===null||L===void 0?void 0:L.width,le=A==null||(q=A.screen)===null||q===void 0?void 0:q.height,de=A?.devicePixelRatio;O(y)||(Q.userAgentDataPlatform=y),O(V)||(Q.maxTouchPoints=V),O(K)||(Q.screenWidth=K),O(le)||(Q.screenHeight=le),O(de)||(Q.devicePixelRatio=de);const $e=Le(Xl({$os:ee,$os_version:k,$browser:zf(pt,navigator.vendor,oe,T),$webview_app:ie,$webview_app_version:H,$device:Uf(pt),$device_type:Y0(pt,Q),$timezone:Wv(),$timezone_offset:Nw()}),{$current_url:Ki(C?Pr(He?.href):He?.href,X,Yi),$host:He?.host,$pathname:He?.pathname,$raw_user_agent:pt.length>1e3?pt.substring(0,997)+"...":pt,$browser_version:K0(pt,navigator.vendor,oe,T),$browser_language:Hv(),$browser_language_prefix:zw(),$screen_height:A?.screen.height,$screen_width:A?.screen.width,$viewport_height:A?.innerHeight,$viewport_width:A?.innerWidth,$lib:ar.LIB_NAME,$lib_version:ar.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return ar.SDK_DIST_CHANNEL&&($e.$sdk_dist_channel=ar.SDK_DIST_CHANNEL),$e})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){const{sessionId:w,windowId:S}=this.sessionManager.checkAndGetSessionAndWindowId(s,n.getTime(),!0);a.$session_id=w,a.$window_id=S}this.sessionPropsManager&&Le(a,this.sessionPropsManager.getSessionProps());try{var l;this.sessionRecording&&Le(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(l=this.Bu)===null||l===void 0?void 0:l.length}catch(w){a.$sdk_debug_error_capturing_properties=String(w)}let u;if(this.requestRouter.region===Qc&&(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"&&z&&(a.title=z.title),!O(o)){const w=n.getTime()-o;a.$duration=parseFloat((w/1e3).toFixed(3))}pt&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");const h=this.persistence.properties(),d=this.sessionPersistence.properties(),p=a.$groups,f=h.$groups;be(p)&&!mt(p)&&(a.$groups=b(b({},be(f)?f:{}),p)),Ce(["$referrer","$referring_domain"],w=>{w in h&&delete d[w]});const v={};if(this.Pu.length>0)for(const w of this.Pu.slice())try{Le(v,w())}catch(S){j.error("Failed to produce browser extension event properties",S)}a=Le({},c,h,d,b(b({},v),a)),a.$is_identified=this._isIdentified(),ce(this.config.property_denylist)?Ce(this.config.property_denylist,function(w){delete a[w]}):j.error(mg+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);const m=this.config.sanitize_properties;m&&(j.error(lh),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(lh),a=c(a,"$set_once")),r&&(this.Iu=!0),mt(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:_i}),()=>{})}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:_i})}getActiveMatchingSurveys(t,r=!1){this.surveys?this.surveys.getActiveMatchingSurveys(t,r):t([],{isLoaded:!1,error:_i})}renderSurvey(t,r){var n;(n=this.surveys)===null||n===void 0||n.renderSurvey(t,r)}displaySurvey(t,r=lS){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:_i}}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:_i})}wh(t){return!t||Pi(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(Ze(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(uo),this.register({distinct_id:t}));const h=(this.persistence.get_property("$user_state")||"anonymous")===sr,d=t!==u,p=!d&&h;if(d&&h){var l;const f=this.config.reuseAnonymousId?{distinct_id:t}:{distinct_id:t,$anon_distinct_id:u};this.persistence.set_property(ft,Us),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=Ya(t,r,n)),(l=this.featureFlags)===null||l===void 0||l.setAnonymousDistinctId(this.config.reuseAnonymousId?void 0:u)}else if(p){this.persistence.set_property(ft,Us);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=Ya(t,r,n))}else(r||n)&&this.setPersonProperties(r,n);d||s||o?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Er)):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=Ya(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(Pd,a)}n&&this.setGroupPropertiesForFlags({[t]:n}),o&&!n&&this.reloadFeatureFlags()}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(t,r=!0){var n;(n=this.featureFlags)===null||n===void 0||n.setPersonPropertiesForFlags(t,r)}resetPersonPropertiesForFlags(t=!0){var r;(r=this.featureFlags)===null||r===void 0||r.resetPersonPropertiesForFlags(t)}setGroupPropertiesForFlags(t,r=!0){var n;this.bh("posthog.setGroupPropertiesForFlags")&&((n=this.featureFlags)===null||n===void 0||n.setGroupPropertiesForFlags(t,r))}resetGroupPropertiesForFlags(t){var r;(r=this.featureFlags)===null||r===void 0||r.resetGroupPropertiesForFlags(t)}reset(t){const r=vt(t)?t:t?.resetDeviceID,n=vt(t)||t==null?void 0:t.bootstrap;this.kh(r,!1,n)}kh(t,r=!1,n){var i,s,o,a,c,l;if(j.info("reset"),!this.__loaded)return j.uninitializedWarning("posthog.reset");const u=n?.sessionID;this.config.bootstrap=n||((i=this.Lu)===null||i===void 0?void 0:i.bootstrap)||{},(s=this.featureFlags)===null||s===void 0||(o=s.updateConfig)===null||o===void 0||o.call(s,this.config,this.nl());const h=this.get_property(Gl),d=this.get_property(La),p=this.get_property(Mi);(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,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(),(I=this.featureFlags)===null||I===void 0||I.reset(),(C=this.conversations)===null||C===void 0||C.reset(),($=this.logs)===null||$===void 0||$.reset(),(M=this.metrics)===null||M===void 0||M.reset(),(L=this.persistence)===null||L===void 0||L.set_property("$user_state","anonymous"),(q=this.sessionManager)===null||q===void 0||q.resetSessionId(),this.Ou=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:Da,$device_id:null},"");else{const T=this.config.get_device_id(Lt());this.register_once({distinct_id:T,$device_id:t?T:h},""),t||O(d)||this.register({[La]: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(),!fe(u)&&!(!((k=this.sessionManager)===null||k===void 0)&&k.setBootstrapSessionId(u,!0)))){const T=b({},n);delete T.sessionID,this.config.bootstrap=T}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(uo,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,hh(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 Va(b(b({},this.config),{},{persistence:"sessionStorage"}),w,!1);const S=this.Du(this.config.debug);var _;vt(S)&&(this.config.debug=S),vt(this.config.debug)&&(this.config.debug?(et.DEBUG=!0,ke.Et()&&ke.At("ph_debug",!0),j.info("set_config",{config:t,oldConfig:r,newConfig:b({},this.config)})):(et.DEBUG=!1,ke.Et()&&ke.Lt("ph_debug"))),(i=this.featureFlags)===null||i===void 0||(s=i.updateConfig)===null||s===void 0||s.call(i,this.config,this.nl()),(o=this.exceptionObserver)===null||o===void 0||o.onConfigChange(),(a=this.exceptions)===null||a===void 0||a.onConfigChange(),(c=this.metrics)===null||c===void 0||c.onConfigChange(),(l=this.sessionRecording)===null||l===void 0||l.startIfEnabledOrStop(),(u=this.tracingHeaders)===null||u===void 0||u.startIfEnabledOrStop(),(h=this.autocapture)===null||h===void 0||h.startIfEnabled(),(d=this.heatmaps)===null||d===void 0||d.startIfEnabled(),("capture_pageview"in t||"disable_capture_url_hashes"in t)&&((_=this.historyAutocapture)===null||_===void 0||_.startIfEnabledOrStop()),(p=this.exceptionObserver)===null||p===void 0||p.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)===null||f===void 0||f.startIfEnabledOrStop(),(v=this.surveys)===null||v===void 0||v.loadIfEnabled(),this.Cu(),(m=this.externalIntegrations)===null||m===void 0||m.startIfEnabledOrStop(),!r.segment&&this.config.segment&&this.persistence&&Gd(this,qi,!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:pr.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:Ri;return r!==Ri&&(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()&&mt(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(Jl,!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 sh(this),this.pageViewManager=new Wd(this),this.persistence&&(this.sessionPropsManager=new nh(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=pr.__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(ch)}opt_out_capturing(){if(this.config.cookieless_mode==="always")return void j.warn(ch);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:Da,$device_id:null}),this.mu(t),this.sessionRecording=void 0,(r=this.sessionManager)===null||r===void 0||r.destroy(),(n=this.pageViewManager)===null||n===void 0||n.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.th(),this.Yu())}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){const t=this.consent.consent;return t===1?"granted":t===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.Cu()}_is_bot(){return rt?dg(rt,this.config.custom_blocked_useragents):void 0}th(){z&&(z.visibilityState==="visible"?this.Ru||(this.Ru=!0,this.capture(Yl,{title:z.title},{send_instantly:!0}),this.Au&&(z.removeEventListener(Wi,this.Au),this.Au=null)):this.Au||(this.Au=this.th.bind(this),Te(z,Wi,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&&!fe(r[n]),c=i in r&&!fe(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(fe(this.config.before_send))return t;const n=Object.keys((r=t.properties)!==null&&r!==void 0?r:{}).filter(U0),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),fe(s)){const a=`Event '${t.event}' was rejected in beforeSend function`;return N0(t.event)?j.warn(`${a}. This can cause unexpected behavior.`):j.info(a),null}s.properties&&!mt(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&&fe(s.properties[o]))return j.warn(`Event '${t.event}' had its '${o}' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped.`),null;return s}getPageViewId(){var t;return(t=this.pageViewManager.Vo)===null||t===void 0?void 0:t.pageViewId}captureTraceFeedback(t,r){this.capture("$ai_feedback",{$ai_trace_id:String(t),$ai_feedback_text:r})}captureTraceMetric(t,r,n){this.capture("$ai_metric",{$ai_trace_id:String(t),$ai_metric_name:r,$ai_metric_value:String(n)})}Du(t){const r=vt(t)&&!t,n=ke.Et()&&ke.Ot("ph_debug")==="true";return!r&&(!!n||t)}};ji.__defaultExtensionClasses={},ji.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]]=fw(e.prototype[t[r]])})(ji,["identify"]);var _g=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}},ec="$copy_autocapture",tc=Ge("[AutoCapture]");function rc(e,t){return t.length>e?t.slice(0,e)+"...":t}function wS(e){if(e.previousElementSibling)return e.previousElementSibling;let t=e;do t=t.previousSibling;while(t&&!Zt(t));return t}function SS(e,{e:t,maskAllElementAttributes:r,maskAllText:n,elementAttributeIgnoreList:i,elementsChainAsString:s,disableCaptureUrlHashes:o}){var a,c;if(!Zt(e))return{props:{}};const l=[e],u=new Set([e]);let h=e;for(;h.parentNode&&!ct(h,"body")&&1e3>l.length;){if(Ql(h.parentNode)){const $=h.parentNode.host;if(u.has($))break;u.add($),l.push($),h=$;continue}if(!Zt(h.parentNode)||u.has(h.parentNode))break;u.add(h.parentNode),l.push(h.parentNode),h=h.parentNode}const d=t.type==="click"&&e.namespaceURI==="http://www.w3.org/2000/svg"?l.findIndex($=>ct($,"button")||ct($,"a")):-1;d>0&&(n=n||l.slice(0,d+1).some($=>!qn($)||Ji($)));const p=[],f={};let v,m=!1,_=!1;if(Ce(l,$=>{const M=qn($);if(ct($,"a")&&!r&&!i?.includes("href")){const L=$.getAttribute("href");m=!!(M&&L&&Ni(L))&&(o?Pr(L):L)}ue(Jn($),"ph-no-capture")&&(_=!0),p.push((function(L,q,X,ee,k=!1){const ie=L.tagName.toLowerCase(),H={tag_name:ie};tu.indexOf(ie)>-1&&!X&&(H.$el_text=ie.toLowerCase()==="a"||ie.toLowerCase()==="button"?rc(1024,Hd(L)):rc(1024,Zi(L)));const oe=Jn(L);q||ee!=null&&ee.includes("class")||0>=oe.length||(H.classes=oe.filter(function(V){return V!==""})),Ce(L.attributes,function(V){var K;if((!Ji(L)||["name","id","class","aria-label"].indexOf(V.name)!==-1)&&!ee?.includes(V.name)&&!q&&Ni(V.value)&&(!ye(K=V.name)||K.substring(0,10)!=="_ngcontent"&&K.substring(0,7)!=="_nghost")){let le=V.value;V.name==="class"&&(le=eu(le).join(" ")),H["attr__"+V.name]=rc(1024,V.name==="href"&&k?Pr(le):le)}});let T=1,Q=1,y=L;for(;y=wS(y);)T++,y.tagName===L.tagName&&Q++;return H.nth_child=T,H.nth_of_type=Q,H})($,r,n,i,o)),Ce((function(L){if(!qn(L))return{};const q={};return Ce(L.attributes,function(X){if(X.name&&X.name.indexOf("data-ph-capture-attribute")===0){const ee=X.name.replace("data-ph-capture-attribute-",""),k=X.value;ee&&k&&Ni(k)&&(q[ee]=k)}}),q})($),(L,q)=>{({}).hasOwnProperty.call(f,q)||(f[q]=L)})}),_)return{props:{},explicitNoCapture:_};if(d>0&&(e=l[d],p.splice(0,d)),n||(p[0].$el_text=ct(e,"a")||ct(e,"button")?Hd(e):Zi(e)),m){var w,S;p[0].attr__href=m;const $=(w=Or(m))===null||w===void 0?void 0:w.host,M=A==null||(S=A.location)===null||S===void 0?void 0:S.host;$&&M&&$!==M&&(v=m)}return{props:Le((C=t.type,{$event_type:C,$ce_version:1}),s?{}:{$elements:p},{$elements_chain:(I=p,ce(I)?(function($){return $.map(M=>{var L,q;let X="";if(M.tag_name&&(X+=M.tag_name),M.attr_class){M.attr_class.sort();for(const ie of M.attr_class)X+=`.${ie.replace(/"/g,"")}`}const ee=b(b(b(b({},M.text?{text:M.text}:{}),{},{"nth-child":(L=M.nth_child)!==null&&L!==void 0?L:0,"nth-of-type":(q=M.nth_of_type)!==null&&q!==void 0?q:0},M.href?{href:M.href}:{}),M.attr_id?{attr_id:M.attr_id}:{}),M.attributes),k={};return Fs(ee).sort(([ie],[H])=>(function(oe,T){return T>oe?-1:oe>T?1:0})(ie,H)).forEach(([ie,H])=>k[Vd(ie.toString())]=Vd(H.toString())),X+=":",X+=Fs(k).map(([ie,H])=>`${ie}="${H}"`).join(""),X}).join(";")})((function($){return $.map(M=>{var L,q;const X={text:(L=M.$el_text)===null||L===void 0?void 0:L.slice(0,400),tag_name:M.tag_name,href:(q=M.attr__href)===null||q===void 0?void 0:q.slice(0,2048),attr_class:Cw(M),attr_id:M.attr__id,nth_child:M.nth_child,nth_of_type:M.nth_of_type,attributes:{}};return Fs(M).filter(([ee])=>ee.indexOf("attr__")===0).forEach(([ee,k])=>X.attributes[ee]=k),X})})(I)):"")},!((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 I,C}var ES=class{fo(){this.po=void 0,clearTimeout(this.mo),this.mo=void 0}yo(e){var t;if(!qn(e))return!0;const r=(t=this.bo().css_selector_ignorelist)!==null&&t!==void 0?t:ja,n=new Set;let i=e;for(;i;){if(n.size>=1e3||n.has(i))return!0;n.add(i);const s=i,o=Jn(s);if(ue(o,"ph-no-capture")||ue(o,"ph-sensitive")||Ji(s)||r.some(c=>Gc(s,c)))return!0;const a=i.parentNode;i=Ql(a)?a.host:a&&Zt(a)?a:null}return!1}_o(e){if(!this.isEnabled||e.type==="pointercancel")return void this.fo();if(e.type==="pointerdown"){this.fo();const n=zi(e);var t;e.isPrimary&&e.button===0&&!e.ctrlKey&&n&&Zt(n)&&(this.po={target:n,excluded:this.yo(n),id:e.pointerId,x:e.clientX,y:e.clientY,released:!1,distinctId:(t=this.wo)===null||t===void 0?void 0:t.distinctId});return}const r=this.po;r&&(e.pointerId!==r.id||Math.abs(e.clientX-r.x)>5||Math.abs(e.clientY-r.y)>5?this.fo():e.type==="pointerup"&&(r.released=!0,this.mo=setTimeout(()=>this.fo(),0)))}ko(e){var t;const r=this.po;this.fo();const n=zi(e);if(r?.released&&r.target.isConnected&&r.distinctId===((t=this.wo)===null||t===void 0?void 0:t.distinctId)&&e.pointerId===r.id&&(e.detail>0||e.pointerType==="touch"||e.pointerType==="pen")&&e.button===0&&5>=Math.abs(e.clientX-r.x)&&5>=Math.abs(e.clientY-r.y)&&n&&(ct(n,"html")||ct(n,"body"))){var i;if(r.excluded)return null;const s=(i=this.bo().css_selector_ignorelist)!==null&&i!==void 0?i:ja;return[n,z?.documentElement,z?.body].some(o=>{if(!o)return!1;const a=Jn(o);return ue(a,"ph-no-capture")||ue(a,"ph-sensitive")||!qn(o)||Ji(o)||s.some(c=>Gc(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 _g(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 tc.info("Disabling Automatic Event Collection because this browser is not supported");if(!A||!z)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(Ve(r))return;this.Oo(t,"$autocapture",r)}catch(r){tc.error("Failed to capture event",r)}};if(Te(A,"blur",e),Te(z,"submit",e,{capture:!0}),Te(z,"change",e,{capture:!0}),Te(z,"click",e,{capture:!0}),Ce(["pointerdown","pointermove","pointerup","pointercancel"],t=>{Te(z,t,e,{capture:!0})}),this.bo().capture_copied_text){const t=this.Do=r=>{r=r||A?.event;try{this.Oo(r,ec)}catch(n){tc.error("Failed to capture clipboard event",n)}};Te(z,"copy",t,{capture:!0}),Te(z,"cut",t,{capture:!0}),Te(z,"paste",t,{capture:!0})}}Ro(){this.fo(),this.Fo&&(A?.removeEventListener("blur",this.Fo),Ce(["pointerdown","pointermove","pointerup","pointercancel"],e=>{z?.removeEventListener(e,this.Fo,!0)}),z?.removeEventListener("submit",this.Fo,!0),z?.removeEventListener("change",this.Fo,!0),z?.removeEventListener("click",this.Fo,!0),this.Fo=void 0),this.Do&&(z?.removeEventListener("copy",this.Do,!0),z?.removeEventListener("cut",this.Do,!0),z?.removeEventListener("paste",this.Do,!0),this.Do=void 0),this.xo=!1}startIfEnabled(){this.isEnabled||this.fo(),!this.Io&&this.wo&&this.isEnabled&&!this.xo&&(this.Ao(),this.xo=!0)}onRemoteConfig(e){if(this.Io)return;if(this.$o=!0,!e.ok)return void this.startIfEnabled();const t=e.config;t.elementsChainAsString&&(this.To=t.elementsChainAsString);const r=t.autocapture_opt_out;var n;vt(r)&&((n=this.wo)===null||n===void 0||n.kv.set("$autocapture_disabled_server_side",r),this.Co=r),this.startIfEnabled()}setElementSelectors(e){this.Mo=e}getElementSelectors(e,t){var r;const n=[];return(r=this.Mo)===null||r===void 0||r.forEach(i=>{z?.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(av),n=this.Co,i=this.bo();if(!i.remoteRequestsDisabled&&!this.$o)return!1;const s=i.remoteRequestsDisabled&&!this.$o;if(Ve(n)&&!vt(r)&&!s)return!1;const o=(t=this.Co)!==null&&t!==void 0?t:!!r;return!!i.enabled&&!o}Oo(e,t="$autocapture",r){if(!this.isEnabled)return void this.fo();let n=r||zi(e);Cv(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())&&xv(n,i.rageclick)&&this.Oo(e,"$rageclick",r);const o=t===ec,a=o?b(b({},i),{},{dom_event_allowlist:void 0}):i;if(n&&(function(h,d,p,f,v,m){var _;if(!A||ru(h)||p?.url_allowlist&&!Dd(p.url_allowlist,m)||p?.url_ignorelist&&Dd(p.url_ignorelist,m))return!1;if(p?.dom_event_allowlist){const C=p.dom_event_allowlist;if(C&&!C.some($=>d.type===$))return!1}const{parentIsUsefulElement:w,targetElementList:S}=Mv(h,f);if(!(function(C,$){const M=$?.element_allowlist;if(O(M))return!0;for(const L of C)if(M.some(q=>L.tagName.toLowerCase()===q))return!0;return!1})(S,p)||!Wc(S,p?.css_selector_allowlist)||Wc(S,(_=p?.css_selector_ignorelist)!==null&&_!==void 0?_:ja))return!1;try{const C=A.getComputedStyle(h);if(C&&C.getPropertyValue("cursor")==="pointer"&&d.type==="click")return!0}catch{}const I=h.tagName.toLowerCase();switch(I){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&&(tu.indexOf(I)>-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}=SS(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===ec){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(),_=$v(m);if(!_)return!1;h.$selected_content=_,h.$clipboard_text_length=(u=m?.length)!==null&&u!==void 0?u:0}h.$copy_type=v}return(c=this.wo)===null||c===void 0||c.capture(t,h),!0}}isBrowserSupported(){return tt(z?.querySelectorAll)}},kS=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}},yi=Ge("[ExceptionAutocapture]"),ph=()=>{},fh=e=>{var t;if(tt(e))return(t=e.__posthog_layer__)!==null&&t!==void 0?t:e.__rrweb_layer__};function Xi(e,t,r){try{if(!(t in e))return ph;const n={next:e[t]},i=r(function(...s){return n.next.apply(this,s)});return tt(i)&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:n}})),e[t]=i,()=>{if(e[t]===i)return void(e[t]=n.next);let s=e[t],o=fh(s);for(;o;){if(o.next===i)return void(o.next=n.next);s=o.next,o=fh(s)}}}catch{return ph}}var RS=Ge("[TracingHeaders]"),Br=Ge("[Web Vitals]"),vh=9e5,gh=["CLS","FCP","INP","LCP"],AS=["INP","LCP"],TS=["interactionTarget","interactionType","inputDelay","processingDuration","presentationDelay","loadState","target","url","timeToFirstByte","resourceLoadDelay","resourceLoadDuration","elementRenderDelay","largestShiftTarget","largestShiftTime","largestShiftValue","firstByteToFCP"],nc="disabled",mh="lazy_loading",Yt=Ge("[SessionRecording]"),IS=Ge("[Heatmaps]");function ic(e){return be(e)&&"clientX"in e&&"clientY"in e&&Ze(e.clientX)&&Ze(e.clientY)}var Es=Ge("[Product Tours]"),sc=e=>{var t;return!e.config.disable_product_tours&&!!(!((t=e.persistence)===null||t===void 0)&&t.get_property(Zl))},CS=["$set_once","$set"],Ft=Ge("[SiteApps]"),_h="Error while initializing PostHog app with config id ",yg=(e,t)=>e?.then?e.then(t):t(e),En="SDK is not enabled or survey functionality is not yet loaded",yh="Disabled. Not loading surveys.",$S=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 Ie.warn("Remote config unavailable. Not loading surveys.");const n=r.config.surveys;if(fe(n))return Ie.warn("Flags not loaded yet. Not loading surveys.");this.Ah=vt(n)?n:n.length>0,Ie.info(`flags response received, isSurveysEnabled: ${this.Ah}`),this.loadIfEnabled()}}setup(e){if(!this.Io)return this.Fh=e,yg(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 Ie.info("Already initializing surveys, skipping...");if(e.disableSurveys)return void Ie.info(yh);if(e.cookielessMode&&this.So.isOptedOut())return void Ie.info("Not loading surveys in cookieless mode without consent.");const t=this.So.getExtensions();if(!t)return void Ie.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(Kl),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(),Ie.info("Surveys loaded successfully"),this.Lh({isLoaded:!0}))}Dh(e,t){Ie.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 Ie.info(yh),e([]);const i=n.kv.get(Fc);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=>Ie.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 Ie.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=>Ie.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(En)}))}jh(e,t){if(this.Io)return{surveys:[],context:{isLoaded:!1,error:En}};const r=t.statusCode;if(r!==200||!t.json){const o=`Surveys API could not be loaded, status: ${r}`;return r!==0?Ie.error(o):t.error||Ie.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)&&(pg(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({[Fc]:n,[ho]: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(ho);return Ze(r)&&Date.now()-r>3e5}Hh(){return Ze(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};gg(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){Ie.error("Error in survey callback",r)}}getActiveMatchingSurveys(e,t=!1){if(!fe(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);Ie.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(fe(this._surveyManager))return{eligible:!1,reason:En};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(fe(this._surveyManager))return{eligible:!1,reason:En};const t=typeof e=="string"?this.zh(e):e;return t?this._surveyManager.checkSurveyRenderability(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(fe(this._surveyManager))return Ie.warn("init was not called"),{visible:!1,disabledReason:En};const t=this.Wh(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return fe(this._surveyManager)?(Ie.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:En})):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(fe(this._surveyManager))return void Ie.warn("init was not called");const i=typeof e=="string"?this.zh(e):e;if(!i?.id)return void Ie.warn("Survey not found");if(!cS.includes(i.type))return void Ie.warn(`Surveys of type ${i.type} cannot be rendered in the app`);const s=z?.querySelector(t);if(s){if(!((n=i.appearance)===null||n===void 0)&&n.surveyPopupDelaySeconds){Ie.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()&&(Ie.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),Ie.info(`Survey ${i.id} rendered`))},1e3*i.appearance.surveyPopupDelaySeconds);this.Rh.add(o);return}this._surveyManager.renderSurvey(i,s,r)}else Ie.warn("Survey element not found")}displaySurvey(e,t){var r;if(!this.So.isCapturing())return;if(fe(this._surveyManager))return void Ie.warn("init was not called");const n=this.zh(e);if(!n)return void Ie.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!==Zc.Popover&&t.initialResponses&&Ie.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 Ie.warn("Survey is not eligible to be displayed: ",s.reason)}t.displayType!==Zc.Inline?this._surveyManager.handlePopoverSurvey(i,t):this.renderSurvey(i,t.selector,t.properties)}cancelPendingSurvey(e){fe(this._surveyManager)?Ie.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 kn(e,t,r){if(fe(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 PS=class{constructor(e){this._instance=e,this.Vh=new Set,this.Gh=new Set,this.Zh=new _o,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 _o}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"||!kn(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=>kn(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&&kn((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=>kn(c.text,t.text,t.text_matching||"exact")||kn(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(;!fe(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=>kn(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||vg(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)}},OS=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&&vg(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===vi.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 PS(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,vi.Activation),a=this._c(e,vi.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,vi.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,vi.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&&(mt(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 Ze(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=>Ze(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}},xS=class extends OS{constructor(e){super(e)}zc(){return pv}Uc(){return fv}gc(){return vv}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 Ze(n)&&n>0}Qc(){return or.SHOWN}kc(e){var t;(t=this._instance)===null||t===void 0||t.getSurveys(e)}Ac(e){var t;(t=this._instance)===null||t===void 0||t.cancelPendingSurvey(e)}Ic(){return Ie}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 pg(n)&&!!(!((i=n.conditions)===null||i===void 0||(i=i.events)===null||i===void 0)&&i.repeatedActivation)||n.schedule==="always"})(r)?e===or.SHOWN?"consume":"ignore":e===or.SHOWN?"persist":e===or.DISMISSED||e===or.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}},MS=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)}},LS=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 xS(this._instance)}},DS=A?.location?vo(A.location.hash,"__posthog")||vo(location.hash,"state"):null,bh="_postHogToolbarParams",wh=Ge("[Toolbar]"),Sh=Ge("[FeatureFlags]"),zS=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||(Sh.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)||Sh.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.Kc}},Eh=Ge("[FeatureFlags]"),Gr=Ge("[FeatureFlags]",{debugEnabled:!0}),oc=`" failed. Feature flags didn't load in time.`,NS=[502,504],kh=["click","keydown","wheel","touchstart","pointerdown"],Rh="connection_error",Ah=e=>{const t={};for(let r=0;e.length>r;r++)t[e[r]]=!0;return t},Th=e=>{const t={};for(const[r,n]of Fs(e||{}))n&&(t[r]=n);return t},Ih=e=>si(e)&&(e.name==="RangeError"&&e.message.indexOf("Maximum call stack size exceeded")===0||e.name==="InternalError"&&e.message==="too much recursion"),$t=Ge("[Error tracking]"),el="webkit-masked-url:",US=[{value:"isolatedAPI.contexts.topHostname",exact:!1},{value:"No response from target",exact:!0}],FS=["chrome-extension://","moz-extension://","safari-extension:","safari-web-extension:",el],qS=["__firefox__","__gCrWeb"],Ch="Refusing to render web experiment since the viewer is a likely bot",jS={icontains:(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())>-1,not_icontains:(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())===-1,regex:(e,t)=>yo(t,e),not_regex:(e,t)=>!yo(t,e),exact:(e,t)=>t===e,is_not:(e,t)=>t!==e},kt=Ge("[Conversations]"),Wr="Conversations not available yet.";function $h(e,t){var r,n,i,s,o,a,c;const l=(r=e?.flushIntervalMs)!==null&&r!==void 0?r:3e3,u=(n=e?.maxBufferSize)!==null&&n!==void 0?n:100,h=t?.consoleCapture?void 0:(i=e?.maxLogsPerInterval)!==null&&i!==void 0?i:1e3,d=O(h)?Math.max(u,2048):Math.max(u,h),p=b(b({},(function(){let f="",v="";try{const m=rt?.userAgent;m&&([f,v]=Nf(m))}catch{}return(function(m,_){const w=(function(S){if(S)return{}.hasOwnProperty.call(kd,S)?kd[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 HS=["debug","log","warn","error","info"],VS=e=>{for(;e?.__rrweb_original__;)e=e.__rrweb_original__;return e},Ph="console",bg="__posthogHandledLogsRequestError",ac=(e,t)=>{const r=e instanceof Error?e:new Error(t);return r[bg]=!0,r},Oh=e=>!!e&&typeof e=="object"&&e[bg]===!0,bo=Ge("[NetworkMetrics]"),su=()=>{var e;return!(A==null||(e=A.performance)===null||e===void 0)&&e.now?A.performance.now():Date.now()},BS={"http:":80,"https:":443},GS=new Set(["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"]),wg=(e,t)=>{var r;const n=String(t);return{method:String(e).toUpperCase(),url:((r=Or(n))===null||r===void 0?void 0:r.href)||n}},tl=(e,t,r,n,i,s,o=!1)=>{try{var a,c;const l=i();if(!l)return;const u=r||void 0,h=su()-n,d=Or(t.url);if(d&&d.protocol!=="http:"&&d.protocol!=="https:")return;const p={url:d?.href||t.url,method:t.method},f=tt(l.name)?l.name(p):ye(l.name)?l.name:"http.client.request.duration";if(!f)return;const v=o&&!u?void 0:((_,w)=>_?400>_?void 0:String(_):w?.name||"_OTHER")(u,s),m=b(b(b(b(b({},(_=>{const w=GS.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)||BS[_.protocol],"url.scheme":_.protocol.slice(0,-1),"url.template":(w=_.pathname,w.split("/").map(S=>(I=>/^\d+$/.test(I)||I.length>=8&&/^[0-9a-f-]*\d[0-9a-f-]*$/i.test(I))(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){bo.error("Failed to record network metric",l)}},Sg=()=>{},WS=(e,t)=>tt(A?.fetch)?Xi(A,"fetch",r=>function(...n){const i=su(),s=r.apply(this,n);if(!t())return s;try{var o,a,c;const[l,u]=n,h=wg((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=>(tl(e,h,d?.status,i,t,void 0,!0),d),d=>{throw tl(e,h,void 0,i,t,d),d})}catch(l){return bo.error("Failed to observe fetch",l),s}}):Sg,ZS=(e,t)=>{var r;const n=A==null||(r=A.XMLHttpRequest)===null||r===void 0?void 0:r.prototype;if(!n)return Sg;const i=new WeakMap,s=Xi(n,"open",a=>function(...c){try{eg.has(this)||i.set(this,wg(c[0],c[1]))}catch(l){bo.error("Failed to observe XHR open",l)}return a.apply(this,c)}),o=Xi(n,"send",a=>function(...c){let l;try{const u=i.get(this);if(u&&t()){const h=su();l=()=>{this.removeEventListener("loadend",l),tl(e,u,this.status,h,t)},Te(this,"loadend",l)}}catch(u){bo.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()}},Vo={featureFlags:class{constructor(e){this.name="featureFlags",this.Xc=!1,this.featureFlagEventHandlers=[],this.$=Eh,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||!z||z.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=()=>{z?.visibilityState==="visible"&&this._d()},"get"in e?this.So=e:(this._instance=e,this.wd=new zS(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]"),yg(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&&Te(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&&z&&!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(),z!=null&&z.addEventListener&&(Te(z,Wi,this.ln),In(kh,r=>{Te(z,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,z==null||(e=z.removeEventListener)===null||e===void 0||e.call(z,"visibilitychange",this.ln),In(kh,t=>{var r;z==null||(r=z.removeEventListener)===null||r===void 0||r.call(z,t,this.bd,{capture:!0})})),this.pd=void 0,this.gd=void 0,this.dd=!1,this.md=void 0}destroy(){this.Rd()}dispose(){this.Rd()}Rd(){var e,t;this.Ed(),this.rd++,this.ad=!1,this.Fh=void 0,this.wo&&(this.Ad(),(e=this.xd)===null||e===void 0||e.dispose(),this.xd=void 0,(t=this.$d)===null||t===void 0||t.call(this),this.$d=void 0,this.ed=[],A?.removeEventListener("online",this.an),this.wo=void 0)}get Rr(){return this.So.get()}Fd(e){var t;return this.Od&&e in this.Od?this.Od[e]:(t=this.wo)===null||t===void 0?void 0:t.kv.get(e)}Td(){return!!this.Od&&(this.Od=void 0,!0)}Dd(){var e;return!O((e=this.wo)===null||e===void 0?void 0:e.kv.get("$enabled_feature_flags"))&&this.Td()}At(e){this.Ld(()=>{var t;return(t=this.wo)===null||t===void 0?void 0:t.kv.set(e)})}Nd(e,t,r){var n;if(!(!((n=this._instance)===null||n===void 0)&&n.persistence)||!e.$enabled_feature_flags)return;const i=this.Fd("$enabled_feature_flags")||{},s=e.$enabled_feature_flags||{},o=t.flags||t.featureFlags,a=t.flags?Object.entries(t.flags).filter(([,_])=>!_?.failed).map(([_])=>_):[],c=!!t.errorsWhileComputingFlags&&!!t.flags,l=c?a:r&&!ce(o)?Object.keys(o||{}):Array.from(new Set([...Object.keys(i),...Object.keys(s)])),u=this.Fd("$feature_flag_payloads")||{},h=e.$feature_flag_payloads||{},d=c||r?l:Array.from(new Set([...Object.keys(u),...Object.keys(h)])),p=!c&&!r,f=!!p||l,v=!!p||d,m={[ir]:f,[Ot]:f,[br]:v};e.$feature_flag_details&&(m[an]=f);for(const _ of[cn,Ar,Li])O(e[_])||(m[_]=!0);this._instance.persistence.markCrossTabFeatureFlagChanges(m)}Lt(e){this.Ld(()=>{var t;return(t=this.wo)===null||t===void 0?void 0:t.kv.remove(e)})}Ld(e){try{e()}catch(t){this.$.error("Failed to update feature flag persistence",t)}}Id(){const e={};for(const n of[ir,br,cn,qt]){const i=this.Fd(n);O(i)||(e[n]=i)}this.Yc=e;const t=b({},e),r=this.Fd(Ot);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(Ar);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:yd(h),variant:bd(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(an),t=this.Fd(qt),r=this.Fd(Yr);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:yd(n),variant:bd(n),payload:_d(t[r])}})}getFlagVariants(){const e=this.Fd(Ot),t=this.Fd(qt);if(!t)return e||{};const r=Le({},e||{}),n=Object.keys(t);for(let i=0;n.length>i;i++)r[n[i]]=t[n[i]];return this.Xc||(this.$.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:t,finalFlags:r}),this.Xc=!0),r}getFlagPayloads(){const e=this.Fd(br),t=this.Fd(Yr);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(Er)}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(Sr),timezone:Wv()};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?Rh:"unknown_error"):f.statusCode!==200&&S.push(`api_error_${f.statusCode}`),_.errorsWhileComputingFlags&&S.push("errors_while_computing_flags");const I=!!(!((m=_.quotaLimited)===null||m===void 0)&&m.includes("feature_flags"));I&&S.push("quota_limited"),this.At({[Gi]:S}),I?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({[Gi]:[Rh]}),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=>NS.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 Nv(this.hd,3)}Wd(e){this.hd=Uv(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+oc);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+oc);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(ki);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({[Er]:u,[ki]:l});else{var d,p,f,v,m,_,w,S,I,C,$,M;ce(u[e])?u[e].push(o):u[e]=[o],this.At(b({[Er]:u},l?{[ki]: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||(I=q.reason)===null||I===void 0?void 0:I.description)!==null&&S!==void 0?S:q==null||(C=q.reason)===null||C===void 0?void 0:C.code;var L;k&&(ee.$feature_flag_reason=k),q!=null&&($=q.metadata)!==null&&$!==void 0&&$.id&&(ee.$feature_flag_id=q.metadata.id),O(q?.original_variant)&&O(q?.original_enabled)||(ee.$feature_flag_original_response=O(q.original_variant)?q.original_enabled:q.original_variant),q!=null&&(M=q.metadata)!==null&&M!==void 0&&M.original_payload&&(ee.$feature_flag_original_payload=q==null||(L=q.metadata)===null||L===void 0?void 0:L.original_payload),X.length&&(ee.$feature_flag_error=X.join(",")),this.Vd(ee)}else l&&this.At({[Er]:u,[ki]:l});return n?{key:e,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:_d(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+oc),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=Eh)=>{const u=((S,I)=>{const C=S.flags;if(C){const $=Object.fromEntries(Object.keys(C).map(L=>{var q;return[L,(q=C[L].variant)!==null&&q!==void 0?q:C[L].enabled]})),M=Object.fromEntries(Object.keys(C).filter(L=>C[L].enabled).filter(L=>{var q;return!O((q=C[L].metadata)===null||q===void 0?void 0:q.payload)}).map(L=>{var q;return[L,(q=C[L].metadata)===null||q===void 0?void 0:q.payload]}));return b(b({},S),{},{featureFlags:$,featureFlagPayloads:M})}return S.featureFlags&&I.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 I=0;d.length>I;I++)S[d[I]]=!0;return{[ir]:d,[Ot]:S,[Li]:!1}}let m=d,_=p,w=h;if(c?.partialResponse){const S=Object.keys(m),I=_||{};m=b(b({},s),m),_=b(b({},o),I),S.forEach(C=>{C in I||_==null||delete _[C]}),w=b(b({},a),w)}else if(i.errorsWhileComputingFlags)if(h){const S=new Set(Object.keys(h).filter(C=>{var $;return!(!(($=h[C])===null||$===void 0)&&$.failed)}));m=b(b({},s),Object.fromEntries(Object.entries(m).filter(([C])=>S.has(C))));const I=Object.fromEntries(Object.entries(_||{}).filter(([C])=>S.has(C)));_=b(b({},o),I),S.forEach(C=>{C in I||_==null||delete _[C]}),w=b(b({},a),Object.fromEntries(Object.entries(w||{}).filter(([C])=>S.has(C))))}else m=b(b({},s),m),_=b(b({},o),_),w=b(b({},a),w);return b(b({[ir]:Object.keys(Th(m)),[Ot]:m||{},[br]:_||{},[an]:w||{},[Li]:i.minimalFlagCalledEvents===!0},f?{[cn]:f}:{}),v?{[Ar]:v}:{})})(e,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),r,this.$);if(n)if(r?.persist===!1){const i=!O(this.wo.kv.get(Ot));this.Od=n,i||this.At(n)}else this.Td(),this.Nd(n,e,!!r?.partialResponse),this.At(n);else t&&this.Dd();t||(this.ud=!1),this.Md(t)}override(e,t=!1){this.$.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:t})}overrideFeatureFlags(e){this.Zd(e)}Zd(e){if(this.wo){if(e===!1)return this.Lt([qt,Yr]),this.Md(),void Gr.info("All overrides cleared");if(ce(e))return this.At({[qt]:Ah(e)}),this.Md(),void Gr.info("Flag overrides set",{flags:e});if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var t;const r=e;this.Xc=!!((t=r.suppressWarning)!==null&&t!==void 0&&t);const n={},i=r.flags,s=r.payloads;i&&(n[qt]=ce(i)?Ah(i):i),s&&(n[Yr]=s),Object.keys(n).length&&this.At(n),i===!1&&s===!1?this.Lt([qt,Yr]):i===!1?this.Lt(qt):s===!1&&this.Lt(Yr),this.Md(),i===!1?Gr.info("Flag overrides cleared"):i&&Gr.info("Flag overrides set",{flags:i}),s===!1?Gr.info("Payload overrides cleared"):s&&Gr.info("Payload overrides set",{payloads:s});return}if(e&&typeof e=="object")return this.At({[qt]:e}),this.Md(),void Gr.info("Flag overrides set",{flags:e});this.$.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:e})}else this.$.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.nd){const{flags:t,flagVariants:r}=this.Qd();try{e(t,r)}catch(n){this.$.error("Error while running feature flags callback",n)}}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,r){var n;const i=(this.Fd("$early_access_features")||[]).find(l=>l.flagKey===e),s={[`$feature_enrollment/${e}`]:t},o={$feature_flag:e,$feature_enrollment:t,$set:s};i&&(o.$early_access_feature_name=i.name),r&&(o.$feature_enrollment_stage=r);const a=b(b({},this.getFlagVariants()),{},{[e]:t});(n=this._instance)===null||n===void 0||(n=n.persistence)===null||n===void 0||n.markCrossTabFeatureFlagChanges({$active_feature_flags:[e],$enabled_feature_flags:[e],$stored_person_properties:Object.keys(s)}),this.At({[ir]:Object.keys(Th(a)),[Ot]:a,[wr]: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(Uc);!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({[Uc]: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({[wr]: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({[wr]:r}),t&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(e=!0){this.Lt(wr),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({[Sr]:n}),t&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){const t=this.Fd("$stored_group_properties")||{};this.At({[Sr]:b(b({},t),{},{[e]:{}})})}else this.Lt(Sr)}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}}},JS={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=nc,this.tv=void 0,this.ev=!1,this.Xe=(()=>{var t,r;if(!z?.visibilityState||z.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;z?.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 Yt.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"');z!=null&&z.addEventListener&&Te(z,"visibilitychange",this.ln)}initialize(){this.startIfEnabledOrStop()}dispose({discardBufferedEvents:e=!1}={}){var t;this.ev=!0,z==null||(t=z.removeEventListener)===null||t===void 0||t.call(z,"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),Yt.info("starting")):(this.Yd=nc,this.stopRecording())}sv(e){var t,r;if(this.nv)if(this.Yd!=="awaiting_config"&&this.Yd!=="missing_config"&&(this.Yd=mh),(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}),Yt.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(fe(e))return null;const r=Ze(e)?e:parseFloat(e);return typeof(n=r)!="number"||!Number.isFinite(n)||0>n||n>1?(Yt.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;fe(l)&&this.av();const u=o?.minimumDurationMilliseconds;n.register({[Mi]: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({[Sv]:!0}),Yt.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):Yt.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(Mi);return(r==null||(t=r.scriptConfig)===null||t===void 0?void 0:t.script)||"lazy-recorder"}hv(){const e=this._instance.get_property(Mi);if(!e)return!1;let t;try{t=typeof e=="object"?e:JSON.parse(e)}catch(r){return Yt.warn("persisted remote config for session recording is invalid and will be ignored",r),!1}return!fe(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 Yt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[wv]:!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",Yt.info("persisted remote config is stale, requesting fresh config before starting"),new Jv(this._instance).load();return}this.Yd=mh,(r=(n=this.Xd).setDocumentWasEverVisible)===null||r===void 0||r.call(n,this.Xe),this.Xd.start(e)}else this.Yd=nc}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)}}},KS={autocapture:class extends ES{constructor(e){super(new kS(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;Xi(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(Yl,{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")};Te(A,"popstate",e),this.gv=()=>{A&&A.removeEventListener("popstate",e)}}_v(){if(this.mv)return;const e=()=>{this.wv("hashchange")};Te(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[Lc]),this.rageclicks=new _g(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 fe(this.Rr.capture_heatmaps)?fe(this.Rr.enable_heatmaps)?this.xv:this.Rr.enable_heatmaps:this.Rr.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.xo)return;IS.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({[Lc]:r}),this.xv=r,this.startIfEnabled()}getAndClearBuffer(){const e=this.Rt;return this.Rt=void 0,e}Iv(e){ic(e.originalEvent)&&this.Tr(e.originalEvent,"deadclick")}ln(){this.Cv&&clearInterval(this.Cv),this.Cv=z?.visibilityState==="visible"?setInterval(this.bl.bind(this),this.flushIntervalMilliseconds):null}$v(){A&&z&&(this.Mv=this.bl.bind(this),Te(A,po,this.Mv),this.Ev=e=>this.Tr(e||A?.event),Te(z,"click",this.Ev,{capture:!0}),this.Pv=e=>this.Rv(e||A?.event),Te(z,"mousemove",this.Pv,{capture:!0}),this.Av=new Bd(this.instance,$w,this.Iv.bind(this)),this.Av.startIfEnabledOrStop(),this.Fv=this.ln.bind(this),Te(z,Wi,this.Fv),this.xo=!0)}Tv(){var e;A&&z&&(this.Mv&&A.removeEventListener(po,this.Mv),this.Ev&&z.removeEventListener("click",this.Ev,{capture:!0}),this.Pv&&z.removeEventListener("mousemove",this.Pv,{capture:!0}),this.Fv&&z.removeEventListener(Wi,this.Fv),clearTimeout(this.Ov),(e=this.Av)===null||e===void 0||e.stop(),this.xo=!1)}Dv(e,t){const r=this.instance.scrollManager.scrollY(),n=this.instance.scrollManager.scrollX(),i=this.instance.scrollManager.scrollElement(),s=(function(o,a,c){let l=o;for(;l&&Zt(l)&&!ct(l,"body");){if(l===c)return!1;let p;try{var u,h,d;p=(u=(h=(d=l.ownerDocument)===null||d===void 0?void 0:d.defaultView)!==null&&h!==void 0?h:A)===null||u===void 0?void 0:u.getComputedStyle(l).position}catch{return!1}if(ue(a,p))return!0;l=Pv(l)}return!1})(zi(e),["fixed","sticky"],i);return{x:e.clientX+(s?0:n),y:e.clientY+(s?0:r),target_fixed:s,type:t}}Tr(e,t="click"){var r;if(Ld(e.target)||!ic(e))return;const n=this.Dv(e,t);(r=this.rageclicks)!==null&&r!==void 0&&r.isRageClick(e.clientX,e.clientY,new Date().getTime())&&xv(zi(e),this.instance.config.rageclick)&&this.Zs(b(b({},n),{},{type:"rageclick"})),this.Zs(n)}Rv(e){!Ld(e.target)&&ic(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?Pr(A.location.href):A.location.href,r=this.Rr.custom_personal_data_properties,n=this.Rr.mask_personal_data_properties?[...Yn,...r||[]]:[],i=Ki(t,n,Yi);this.Rt=this.Rt||{},this.Rt[i]||(this.Rt[i]=[]),this.Rt[i].push(e)}bl(){this.Rt&&!mt(this.Rt)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Bd,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},fe(r?.name)||fe(r?.value))return void Br.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=Ze(r.navigationId)||typeof r.navigationId=="string"?`navigation:${r.navigationId}`:`url:${s}`;if(this.Bv&&r.value>=this.Bv)return void Br.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 TS){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 Br.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[Nc]),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 fe(r)?((t=this._instance.persistence)===null||t===void 0?void 0:t.props.$web_vitals_allowed_metrics)||gh:r}get flushToCaptureTimeoutMs(){return(be(this.Uv)?this.Uv.web_vitals_delayed_flush_ms:void 0)||5e3}get attributionMetrics(){const e=be(this.Uv)?this.Uv.web_vitals_attribution:void 0;return vt(e)?e?gh:[]:ce(e)?e:AS}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)&&Ze(this.Uv.__web_vitals_max_value)?this.Uv.__web_vitals_max_value:vh;return e>0&&6e4>=e?vh:e}get isEnabled(){const e=He?.protocol;if(e!=="http:"&&e!=="https:")return Br.info("Web Vitals are disabled on non-http/https protocols"),!1;const t=be(this.Uv)?this.Uv.web_vitals:vt(this.Uv)?this.Uv:void 0;return vt(t)?t:this.xv}startIfEnabled(){this.isEnabled&&!this.xo&&(Br.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({[Nc]:r}),this._instance.persistence.register({[uv]: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?Br.error("failed to load script",s):e()})}jv(e){const t=e||A?.location.href;if(!t)return void Br.error("Could not determine current URL");const r=this._instance.config.disable_capture_url_hashes?Pr(t):t,n=this._instance.config.custom_personal_data_properties,i=this._instance.config.mask_personal_data_properties?[...Yn,...n||[]]:[];return Ki(r,i,Yi)}}},YS={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){yi.error("failed to start",o),this.Zv()}},this._instance=e,this.Qv=!!(!((t=this._instance.persistence)===null||t===void 0)&&t.props[Dc]),this.wt=new H0(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,$:yi})),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?(yi.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 yi.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({[Dc]: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 yi.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 tb([new gb,new Rb,new _b,new mb,new Eb,new Sb,new bb,new kb],(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=md.test(f)?f.replace(md,"$1"):f;if(!v.match(/\S*Error: /)){for(const m of i){const _=m(v,n);if(_){a.push(_);const w=hb(a);if(w){for(let S=u.length-1;S>=0;S--){const I=u[S];if(w.start>=I.start+I.length)break;u.pop()}u.push(w)}break}}if(fb(a,u)>=50)break}}const h=[...u].sort((p,f)=>f.start-p.start),d=h[h.length-1];if(d){const p=Gf(a,d);a.splice(d.start-p,p);for(const f of h)f.start-=p}for(const p of h)pb(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++)vb(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",cb,db)),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=ao(this.tf()),this.ef=new Tb(this.Yv)}onConfigChange(){this.Yv=ao(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({[cv]:this.Kv,[zc]:o})}get if(){var e;const t=!!this._instance.get_property(zc),r=this._instance.config.error_tracking.captureExtensionExceptions;return(e=r??t)!==null&&e!==void 0&&e}buildProperties(e,t){return this.Xv.buildFromUnknown(e,{syntheticException:t?.syntheticException,mechanism:{handled:t?.handled}})}addExceptionStep(e,t){if(this.Yv.enabled)try{if(!ye(e)||e.trim().length===0)return void $t.warn("Ignoring exception step because message must be a non-empty string");const{sanitizedProperties:r,droppedKeys:n}=(function(i){if(!i)return{sanitizedProperties:{},droppedKeys:[]};const s=[];return{sanitizedProperties:Object.keys(i).reduce((o,a)=>Ab.has(a)?(s.push(a),o):(o[a]=i[a],o),{}),droppedKeys:s}})(this.nf(t));n.length>0&&$t.warn("Ignoring reserved exception step fields",{droppedKeys:n}),this.ef.add(b({[so]:e,[oo]:new Date().toISOString()},r))}catch(r){$t.error("Failed to add exception step. Ignoring breadcrumb.",r)}}sendExceptionEvent(e){try{const t=e.$exception_list;if(this.sf(t)){if(this.rf(t))return this.af("Exception dropped: matched a suppression rule"),void $t.info("Skipping exception capture because a suppression rule matched");if(!this.if&&this.lf(t))return this.af("Exception dropped: thrown by a browser extension"),void $t.info("Skipping exception capture because it was thrown by an extension");if(!this.if&&this.uf(t))return this.af("Exception dropped: thrown by an injected browser script"),void $t.info("Skipping exception capture because it was thrown by an injected browser script");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hf(t))return this.af("Exception dropped: thrown by the PostHog SDK"),void $t.info("Skipping exception capture because it was thrown by the PostHog SDK")}const r=this.Yv.enabled&&fe(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){Ih(i)||$t.error("Failed to capture exception event. Dropping this exception.",i),this.ef.clear();return}}catch(t){Ih(t)||$t.error("Failed to process exception event. Ignoring this exception.",t);return}}cf(e){try{const t=this.ef.getAttachable();return t.length===0?e:b(b({},e),{},{$exception_steps:t})}catch(t){return $t.error("Failed to read buffered exception steps. Capturing exception without steps.",t),e}}af(e){this.Yv.enabled&&this.ef.add({[so]:e,[oo]: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=fg[i.operator],o=t[i.key];if(!s||!o)return!1;const a=ce(i.value)?i.value:[i.value];return a.length>0&&s(a,o)});return r.type==="OR"?n.some(Boolean):n.every(Boolean)})}catch(t){return $t.warn("Failed to evaluate suppression rules. Capturing the exception.",t),!1}}lf(e){const t=e.flatMap(n=>{var i,s;return(i=(s=n.stacktrace)===null||s===void 0?void 0:s.frames)!==null&&i!==void 0?i:[]}),r=t.filter(({filename:n})=>!!n&&FS.some(i=>n.startsWith(i)));return r.length!==0&&(!r.every(({filename:n})=>!!n&&n.startsWith(el))||e.some(({type:n,value:i})=>n==="NoResponse"||ye(i)&&US.some(({value:s,exact:o})=>o?i===s:i.includes(s)))&&!t.some(({in_app:n,filename:i})=>n&&!i?.startsWith(el)))}uf(e){return e.some(({value:t})=>ye(t)&&qS.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!fe(e)&&ce(e)}}},XS=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({[Zl]:!!t.productTours}),!sc(this._instance))return!this.df&&fe((r=this.Ml)===null||r===void 0?void 0:r.props.ph_product_tours)||Es.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&&sc(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?Es.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[qc];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(!sc(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||Es.warn(o):Es.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({[qc]:s}),e(s,{isLoaded:!0})}})}getActiveProductTours(e){fe(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)}}},Vo),QS={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({},Kf(e,CS)),{},{properties:b(b(b({},e.properties),d?{$set:b(b({},(t=(r=e.properties)===null||r===void 0?void 0:r.$set)!==null&&t!==void 0?t:{}),d)}:{}),h?{$set_once:b(b({},(n=(i=e.properties)===null||i===void 0?void 0:i.$set_once)!==null&&n!==void 0?n:{}),h)}:{}),elements_chain:(s=(o=e.properties)===null||o===void 0?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=e.properties)===null||a===void 0?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:c}}bf(e){var t;const r=(t=e.tagName)===null||t===void 0?void 0:t.toLowerCase();return r==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(e)||(Ft.error("prepare_external_dependency_stylesheet returned null"),null):r==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(e)||(Ft.error("prepare_external_dependency_script returned null"),null):e}_f(){var e,t,r,n,i,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};const c=z?.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(_=>!Ve(_));return p(l,"appendChild",m=>function(_){const w=f(_);return w?m.call(this,w):_}),p(l,"insertBefore",m=>function(_,w){const S=f(_);return S?m.call(this,S,w):_}),p(l,"replaceChild",m=>function(_,w){const S=f(_);return S?m.call(this,S,w):w}),[(t=c.Element)===null||t===void 0?void 0:t.prototype,(r=c.Document)===null||r===void 0?void 0:r.prototype,(n=c.DocumentFragment)===null||n===void 0?void 0:n.prototype].forEach(m=>{p(m,"append",_=>function(...w){return _.apply(this,v(w))}),p(m,"prepend",_=>function(...w){return _.apply(this,v(w))})}),[(i=c.Element)===null||i===void 0?void 0:i.prototype,(s=c.CharacterData)===null||s===void 0?void 0:s.prototype,(o=c.DocumentType)===null||o===void 0?void 0:o.prototype].forEach(m=>{p(m,"before",_=>function(...w){return _.apply(this,v(w))}),p(m,"after",_=>function(...w){return _.apply(this,v(w))}),p(m,"replaceWith",_=>function(...w){const S=v(w);return w.length&&!S.length?void 0:_.apply(this,S)})}),p((a=c.Element)===null||a===void 0?void 0:a.prototype,"insertAdjacentElement",m=>function(_,w){const S=f(w);return S?m.call(this,_,S):null}),this.wf=()=>{u.forEach(m=>m()),this.wf=void 0},this.kf()}kf(){let e=!1;return()=>{var t;e||(e=!0,this.pf--,this.pf===0&&((t=this.wf)===null||t===void 0||t.call(this)))}}Sf(e,t=!0){const r=this._f();try{const n=e(r);return t&&r(),n}catch(n){throw r(),n}}setupSiteApp(e){const t=this.apps[e.id],r=()=>{var s;!t.errored&&this.gf.length&&(Ft.info(`Processing ${this.gf.length} events for site app with id ${e.id}`),this.gf.forEach(o=>this.Sf(()=>{var a;return(a=t.processEvent)===null||a===void 0?void 0:a.call(t,o)})),t.processedBuffer=!0),Object.values(this.apps).every(o=>o.processedBuffer||o.errored)&&((s=this.yf)===null||s===void 0||s.call(this))};let n=!1;const i=s=>{t.errored=!s,t.loaded=!0,Ft.info(`Site app with id ${e.id} ${s?"loaded":"errored"}`),n&&r()};try{const{processEvent:s}=this.Sf(o=>e.init({posthog:this._instance,callback(a){o(),i(a)}}),!1);s&&(t.processEvent=s),n=!0}catch(s){Ft.error(_h+e.id,s),i(!1)}if(n&&t.loaded)try{r()}catch(s){Ft.error(`Error while processing buffered events PostHog app with config id ${e.id}`,s),t.errored=!0}}xf(){const e=this.siteAppLoaders||[];for(const t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(const t of e)this.setupSiteApp(t)}Cf(e){if(Object.keys(this.apps).length===0)return;const t=this.globalsForEvent(e);for(const r of Object.values(this.apps))try{this.Sf(()=>{var n;return(n=r.processEvent)===null||n===void 0?void 0:n.call(r,t)})}catch(n){Ft.error(`Error while processing event ${e.event} for site app ${r.id}`,n)}}onRemoteConfig(e){var t,r,n;if(!((t=this.siteAppLoaders)===null||t===void 0)&&t.length)return this.isEnabled?(this.xf(),void this._instance.on("eventCaptured",a=>this.Cf(a))):void Ft.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((r=this.yf)===null||r===void 0||r.call(this),!e.ok)return;const i=e.config;if(!((n=i.siteApps)===null||n===void 0)&&n.length)if(this.isEnabled)for(const{id:a,url:c}of i.siteApps){var s,o;te[`__$$ph_site_app_${a}`]=this._instance,(s=te.__PosthogExtensions__)===null||s===void 0||(o=s.loadSiteApp)===null||o===void 0||o.call(s,this._instance,c,l=>{if(l)return Ft.error(_h+a,l)})}else Ft.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}},eE={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 RS.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()}}},tE=b({surveys:class extends $S{constructor(e){var t;super(new LS(e),(t=e,{get projectToken(){return t.config.token},kv:new MS(t)})),this._instance=e}qh(e,t){const r=t.query?ss(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})})}}},Vo),rE={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(Hc(this.instance.config)||!A||!z)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=DS||vo(e.hash,"__posthog")||vo(e.hash,"state");let o;const a=s?pd(()=>JSON.parse(atob(decodeURIComponent(s))))||pd(()=>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(bh)||"{}"),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;!fe(t)&&tt(t)?t(e,this.instance):wh.warn("No toolbar load function found")}loadToolbar(e){const t=!!z?.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(bh,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 wh.error("[Toolbar] Failed to load",o),void this.Pf(0);this.Pf(2),this.Af(n)}),Te(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)}}},nE=b({experiments:class dt{get Rr(){return this._instance.config}constructor(t){this._instance=t,this.getWebExperimentsAndEvaluateDisplayLogic=(r=!1)=>{this.getWebExperiments(n=>{dt.Of("retrieved web experiments from the server"),this.Df=new Map,n.forEach(i=>{if(i.feature_flag_key){var s;this.Df&&(dt.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];dt.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())dt.Of(Ch);else if(!this.Rr.disable_web_experiments){if(fe(this.Df))return this.Df=new Map,this.loadIfEnabled(),void this.previewWebExperiment();dt.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=dt.getWindowLocation();if(t?.search){const r=Kn(t?.search,"__experiment_id"),n=Kn(t?.search,"__experiment_variant");r&&n&&(dt.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&&(dt.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!fe(t.conditions)&&dt.jf(t,r)&&dt.Bf(t)}static jf(t,r){var n;if(fe(t.conditions)||fe((n=t.conditions)===null||n===void 0?void 0:n.url))return!0;const i=dt.getWindowLocation();if(i){var s,o,a;const c=Iv(r,i.href);return!(!((s=t.conditions)===null||s===void 0)&&s.url)||jS[(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(fe(t.conditions)||fe((r=t.conditions)===null||r===void 0?void 0:r.utm))return!0;const n=Fv();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()?dt.Of(Ch):r!=="control"?n.forEach(i=>{if(i.selector){var s;dt.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)})}}):dt.Of("Control variants leave the page unmodified.")}_is_bot(){return rt&&this._instance?dg(rt,this.Rr.custom_blocked_useragents):void 0}}},Vo),iE={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;fe(t)||(vt(t)?this.Hf=t:(this.Hf=t.enabled,this.ne=t),this.loadIfEnabled())}reset(){var e;(e=this._conversationsManager)===null||e===void 0||e.reset(),this._conversationsManager=null,this.Hf=void 0,this.ne=null,this.Wf=void 0,this.Uf=!1}loadIfEnabled(){if(this._conversationsManager||this.zf||this._instance.config.disable_conversations||Hc(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(Kl);r(this._instance,"conversations",n=>{n||!e.initConversations?this.Gf("Could not load conversations script",n):this.Vf(e.initConversations),this.zf=!1})}catch(t){this.Gf("Error initializing conversations",t),this.zf=!1}}else kt.error("Conversations enabled but missing token in remote config.")}Vf(e){if(this.ne)try{this._conversationsManager=e(this.ne,this._instance),this.Uf=!1,kt.info("Conversations loaded successfully")}catch(t){this.Gf("Error completing conversations initialization",t)}else kt.error("Cannot complete initialization: remote config is null")}Gf(e,t){kt.error(e,t),this._conversationsManager=null,this.zf=!1,this.Uf=!0}show(){this._conversationsManager?this._conversationsManager.show():kt.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Hf===!0&&!Ve(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":Hc(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?fe(this.ne)||!this.ne.token?"missing_token":te?.__PosthogExtensions__?this.zf?"initializing":this.Uf?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var e,t;return(e=(t=this._conversationsManager)===null||t===void 0?void 0:t.isVisible())!==null&&e!==void 0&&e}sendMessage(e,t,r){var n=this;return Ue(function*(){return n._conversationsManager?n._conversationsManager.sendMessage(e,t,r):(kt.warn(Wr),null)})()}getMessages(e,t){var r=this;return Ue(function*(){return r._conversationsManager?r._conversationsManager.getMessages(e,t):(kt.warn(Wr),null)})()}markAsRead(e){var t=this;return Ue(function*(){return t._conversationsManager?t._conversationsManager.markAsRead(e):(kt.warn(Wr),null)})()}getTickets(e){var t=this;return Ue(function*(){return t._conversationsManager?t._conversationsManager.getTickets(e):(kt.warn(Wr),null)})()}requestRestoreLink(e){var t=this;return Ue(function*(){return t._conversationsManager?t._conversationsManager.requestRestoreLink(e):(kt.warn(Wr),null)})()}restoreFromToken(e){var t=this;return Ue(function*(){return t._conversationsManager?t._conversationsManager.restoreFromToken(e):(kt.warn(Wr),null)})()}restoreFromUrlToken(){var e=this;return Ue(function*(){return e._conversationsManager?e._conversationsManager.restoreFromUrlToken():(kt.warn(Wr),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()}}},sE={logs:class{constructor(e){var t;this._instance=e,this.name="logs",this.Zf=!1,this.Qf=!1,this.Jf=!1,this.$=Ge("[logs]"),this.Kf=b(b({},this.$),{},{error:(...r)=>{r.some(Oh)||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&&Te(A,"online",this.sp)}ap(e,t,r,n){var i;const s=$h((i=this._instance)===null||i===void 0||(i=i.config)===null||i===void 0?void 0:i.logs,r);return[new zb(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},Ph)),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;fe(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[lv])}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=$h((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 HS){let i;try{i=VS(te.console[n])}catch{continue}i&&this.tp.push(Xi(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){Oh(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(Kl),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===jt.LogsQueue?e():void 0,setPersistedProperty(n,i){var s;n===jt.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(Nv(this.hd,3))return void t({kind:"fatal",error:ac(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:ac(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:ac(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=Uv(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,Ph,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=rv(s,tv(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,fe(i)||(t.sessionStartTimestamp=i),fe(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?Pr(te.location.href):te.location.href),this._instance.featureFlags){const r=this._instance.featureFlags.getFlags();r&&r.length>0&&(t.activeFeatureFlags=r)}return t}}},oE={metrics:class{constructor(e){this._instance=e,this.$=Ge("[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=WS(r,i),o=ZS(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 Nb(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)}}};ji.__defaultExtensionClasses=b({},b(b(b(b(b(b(b(b(b(b(b(b(b({},Vo),JS),KS),YS),XS),QS),tE),eE),rE),nE),iE),sE),oE));var aE=(function(){et.SDK_DIST_CHANNEL="npm";const e=Fi[Ri]=new ji;return(function(){function t(){t.done||(t.done=!0,lg=!1,Ce(Fi,function(r){r._dom_loaded()}))}z?.addEventListener?z.readyState==="complete"?t():Te(z,"DOMContentLoaded",t,{capture:!1}):A&&j.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),e})(),cE=aE,hM=Object.freeze({maxObservations:24,maxSummaryChars:400,maxEvidenceRefs:8,maxEvidenceRefChars:200,maxModelIdChars:128,maxVersionChars:64}),pM=Object.freeze({status:"not-requested",reason:"not_requested",detail:"this run did not request model-backed observations, so nothing was charged"});function Eg(e){return e.status==="skipped"&&e.skipReason==="could-not-run"}function lE(e){return e.status==="skipped"&&e.skipReason!=="could-not-run"}function uE(e){if(e.some(n=>n.status==="failed"))return{outcome:"failed"};const t=e.filter(Eg);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 dE="2026-08-19",hE="https://docs.claude.com/en/docs/mcp",pE=["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"],fE={},vE=pE.map(e=>({page:e,url:`${hE}/${e}`,revision:fE[e]??null,snapshotDate:dE})),gE=Object.freeze(Object.fromEntries(vE.map(e=>[e.page,e])));function fr(e,t){const r=gE[e];return{page:r.page,section:t,url:r.url,revision:r.revision,snapshotDate:r.snapshotDate}}function kg(e){return e.class==="required"||e.class==="runtime-blocker"}var fM=["runtime-compatibility","directory-policy","optional-features","submission-artifacts","experience-insights"];function mE(e){return kg(e)}var _E=["experience"];var yE=["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"],vM=Object.freeze({readinessKind:"claude-directory-readiness",observationKinds:_E,knownIds:yE,schemaVersion:"1"}),bE=[{id:"claude.experience.tool-descriptions-uninformative",title:"Tool descriptions may not tell Claude when to use the tool",lane:"experience-insights",class:"heuristic",source:fr("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:fr("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:fr("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:fr("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:fr("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:fr("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:fr("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."}],gM=Object.freeze({experienceLane:"experience-insights",engineVersion:"1",mappings:bE}),xh="2026-08-19",wo="https://developers.openai.com/plugins",mM=`${wo}/llms.txt`,_M=`${wo}/changelog`,Rg=["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"],Ag=[{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"}],yM=[...Rg,...Ag.map(e=>e.page)],Mh={},wE=[...Rg.map(e=>({page:e,url:`${wo}/${e}`,revisionUrl:`${wo}/${e}.md`,format:"markdown",revision:Mh[e]??null,snapshotDate:xh})),...Ag.map(e=>({page:e.page,url:e.url,revisionUrl:e.url,format:"html",revision:Mh[e.page]??null,snapshotDate:xh}))],SE=Object.freeze(Object.fromEntries(wE.map(e=>[e.page,e])));function Ht(e,t){const r=SE[e];return{page:r.page,section:t,url:r.url,revision:r.revision,snapshotDate:r.snapshotDate}}var bM=["runtime-compatibility","directory-policy","plugin-package","release-contract","optional-features","submission-artifacts","experience-insights"],Rn={serverUrl:"serverUrl",pluginBundle:"pluginBundle",submissionProfile:"submissionProfile",draftSnapshot:"draftSnapshot",publishedSnapshot:"publishedSnapshot",toolListing:"toolListing",importedSkills:"importedSkills"},wM=Object.freeze({"skills-only":{hasMcpServer:!1,hasUploadedPackage:!0,hasImportedSkills:!1,requiredInputs:[Rn.pluginBundle],summary:"a skills package with no MCP server"},"mcp-only":{hasMcpServer:!0,hasUploadedPackage:!1,hasImportedSkills:!1,requiredInputs:[Rn.serverUrl],summary:"an MCP endpoint with no uploaded package"},"mcp-imported-skills":{hasMcpServer:!0,hasUploadedPackage:!1,hasImportedSkills:!0,requiredInputs:[Rn.serverUrl,Rn.importedSkills],summary:"an MCP endpoint whose skills are imported at scan time"},"mcp-uploaded-skills":{hasMcpServer:!0,hasUploadedPackage:!0,hasImportedSkills:!1,requiredInputs:[Rn.serverUrl,Rn.pluginBundle],summary:"an MCP endpoint plus an uploaded skills package"}}),SM=Object.freeze({"technical-preflight":["runtime-compatibility","directory-policy","plugin-package"],"submission-ready":["runtime-compatibility","directory-policy","plugin-package","submission-artifacts","release-contract"]});function EE(e){return typeof e=="object"&&e!==null&&e.readinessKind==="openai-directory-readiness"}var kE=["experience"];var RE=["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"],EM=Object.freeze({readinessKind:"openai-directory-readiness",observationKinds:kE,knownIds:RE,schemaVersion:"1"}),AE=[{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:Ht("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:Ht("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:Ht("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:Ht("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:Ht("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:Ht("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:Ht("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:Ht("build/auth","§Consent"),remediation:"State which account is connected and what scope it grants, in the copy the user sees at consent time."}],kM=Object.freeze({experienceLane:"experience-insights",engineVersion:"2",mappings:AE}),TE=["https://claude.ai/api/mcp/auth_callback","https://claude.com/api/mcp/auth_callback"];var IE=".claudemcpcontent.com";var CE="text/html;profile=mcp-app",$E={toolListingMs:5e3,handshakeMs:3e3,widgetFirstPaintMs:3e3},PE={minViewportWidthPx:320,minTouchTargetPx:44},vr={nameMaxLength:100,taglineMaxLength:55,descriptionMaxLength:2e3,categoriesMin:1,categoriesMax:5,screenshotsMin:3,screenshotsMax:5,screenshotMinWidthPx:1e3,toolNameMaxLength:64},RM={callbackUrls:TE,loopbackRedirectIgnoresPort:!0,appContentDomainSuffix:IE,appContentDomainHashLength:32,appHtmlMime:CE,latencyBudgets:$E,appDesignBudgets:PE,submissionLimits:vr,source:fr("directory","Host profile constants")},AM=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 jn=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Tg=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}},rl={};function xr(e){return e&&Object.assign(rl,e),rl}function Ig(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 nl(e,t){return typeof t=="bigint"?t.toString():t}function Bo(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function ou(e){return e==null}function au(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function OE(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 Lh=Symbol("evaluating");function Ae(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==Lh)return n===void 0&&(n=Lh,n=r()),n},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function gn(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function jr(...e){const t={};for(const r of e){const n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function Dh(e){return JSON.stringify(e)}function xE(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Cg="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Qi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var ME=Bo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch{return!1}});function Qn(e){if(Qi(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(Qi(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function $g(e){return Qn(e)?{...e}:Array.isArray(e)?[...e]:e}var LE=new Set(["string","number","symbol"]);function ei(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function lr(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function re(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function DE(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var zE={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 NE(e,t){const r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return lr(e,jr(e._zod.def,{get shape(){const i={};for(const s in t){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&(i[s]=r.shape[s])}return gn(this,"shape",i),i},checks:[]}))}function UE(e,t){const r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");return lr(e,jr(e._zod.def,{get shape(){const i={...e._zod.def.shape};for(const s in t){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&delete i[s]}return gn(this,"shape",i),i},checks:[]}))}function FE(e,t){if(!Qn(t))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0){const n=e._zod.def.shape;for(const i in t)if(Object.getOwnPropertyDescriptor(n,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return lr(e,jr(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return gn(this,"shape",n),n}}))}function qE(e,t){if(!Qn(t))throw new Error("Invalid input to safeExtend: expected a plain object");return lr(e,jr(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return gn(this,"shape",r),r}}))}function jE(e,t){return lr(e,jr(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return gn(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:[]}))}function HE(e,t,r){const n=t._zod.def.checks;if(n&&n.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");return lr(t,jr(t._zod.def,{get shape(){const i=t._zod.def.shape,s={...i};if(r)for(const o in r){if(!(o in i))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=e?new e({type:"optional",innerType:i[o]}):i[o])}else for(const o in i)s[o]=e?new e({type:"optional",innerType:i[o]}):i[o];return gn(this,"shape",s),s},checks:[]}))}function VE(e,t,r){return lr(t,jr(t._zod.def,{get shape(){const n=t._zod.def.shape,i={...n};if(r)for(const s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(const s in n)i[s]=new e({type:"nonoptional",innerType:n[s]});return gn(this,"shape",i),i}}))}function $n(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 rn(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function ks(e){return typeof e=="string"?e:e?.message}function Mr(e,t,r){const n={...e,path:e.path??[]};return e.message||(n.message=ks(e.inst?._zod.def?.error?.(e))??ks(t?.error?.(e))??ks(r.customError?.(e))??ks(r.localeError?.(e))??"Invalid input"),delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function cu(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function es(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}var Pg=(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,nl,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Og=x("$ZodError",Pg),xg=x("$ZodError",Pg,{Parent:Error});function BE(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 GE(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 lu=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 jn;if(o.issues.length){const a=new(i?.Err??e)(o.issues.map(c=>Mr(c,s,xr())));throw Cg(a,i?.callee),a}return o.value},uu=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=>Mr(c,s,xr())));throw Cg(a,i?.callee),a}return o.value},Go=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 jn;return s.issues.length?{success:!1,error:new(e??Og)(s.issues.map(o=>Mr(o,i,xr())))}:{success:!0,data:s.value}},WE=Go(xg),Wo=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=>Mr(o,i,xr())))}:{success:!0,data:s.value}},ZE=Wo(xg),JE=e=>(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return lu(e)(t,r,i)},KE=e=>(t,r,n)=>lu(e)(t,r,n),YE=e=>async(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return uu(e)(t,r,i)},XE=e=>async(t,r,n)=>uu(e)(t,r,n),QE=e=>(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Go(e)(t,r,i)},ek=e=>(t,r,n)=>Go(e)(t,r,n),tk=e=>async(t,r,n)=>{const i=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return Wo(e)(t,r,i)},rk=e=>async(t,r,n)=>Wo(e)(t,r,n),nk=/^[cC][^\s-]{8,}$/,ik=/^[0-9a-z]+$/,sk=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ok=/^[0-9a-vA-V]{20}$/,ak=/^[A-Za-z0-9]{27}$/,ck=/^[a-zA-Z0-9_-]{21}$/,lk=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,uk=/^([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})$/,zh=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)$/,dk=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,hk="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function pk(){return new RegExp(hk,"u")}var fk=/^(?:(?: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])$/,vk=/^(([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}|:))$/,gk=/^((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])$/,mk=/^(([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])$/,_k=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Mg=/^[A-Za-z0-9_-]*$/,yk=/^\+[1-9]\d{6,14}$/,Lg="(?:(?:\\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])))",bk=new RegExp(`^${Lg}$`);function Dg(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 wk(e){return new RegExp(`^${Dg(e)}$`)}function Sk(e){const t=Dg({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(`^${Lg}T(?:${n})$`)}var Ek=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},kk=/^-?\d+$/,zg=/^-?\d+(?:\.\d+)?$/,Rk=/^(?:true|false)$/i,Ak=/^null$/i,Tk=/^undefined$/i,Ik=/^[^A-Z]*$/,Ck=/^[^a-z]*$/,wt=x("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Ng={number:"number",bigint:"bigint",object:"date"},Ug=x("$ZodCheckLessThan",(e,t)=>{wt.init(e,t);const r=Ng[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})}}),Fg=x("$ZodCheckGreaterThan",(e,t)=>{wt.init(e,t);const r=Ng[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})}}),$k=x("$ZodCheckMultipleOf",(e,t)=>{wt.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):OE(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})}}),Pk=x("$ZodCheckNumberFormat",(e,t)=>{wt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[i,s]=zE[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=kk)}),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})}}),Ok=x("$ZodCheckMaxLength",(e,t)=>{var r;wt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const i=n.value;return!ou(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=cu(i);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),xk=x("$ZodCheckMinLength",(e,t)=>{var r;wt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const i=n.value;return!ou(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=cu(i);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Mk=x("$ZodCheckLengthEquals",(e,t)=>{var r;wt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const i=n.value;return!ou(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=cu(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})}}),Zo=x("$ZodCheckStringFormat",(e,t)=>{var r,n;wt.init(e,t),e._zod.onattach.push(i=>{const s=i._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Lk=x("$ZodCheckRegex",(e,t)=>{Zo.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})}}),Dk=x("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ik),Zo.init(e,t)}),zk=x("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ck),Zo.init(e,t)}),Nk=x("$ZodCheckIncludes",(e,t)=>{wt.init(e,t);const r=ei(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})}}),Uk=x("$ZodCheckStartsWith",(e,t)=>{wt.init(e,t);const r=new RegExp(`^${ei(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})}}),Fk=x("$ZodCheckEndsWith",(e,t)=>{wt.init(e,t);const r=new RegExp(`.*${ei(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})}}),qk=x("$ZodCheckOverwrite",(e,t)=>{wt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}}),jk=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
|
-
`))}},Hk={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=Hk;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=$n(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 jn;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,o.issues.length!==d&&(l||(l=$n(o,d)))});else{if(o.issues.length===d)continue;l||(l=$n(o,d))}}return u?u.then(()=>o):o},s=(o,a,c)=>{if($n(o))return o.aborted=!0,o;const l=i(a,n,c);if(l instanceof Promise){if(c.async===!1)throw new jn;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 jn;return c.then(l=>i(l,n,a))}return i(c,n,a)}}Ae(e,"~standard",()=>({validate:i=>{try{const s=WE(e,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return ZE(e,i).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}))}),du=x("$ZodString",(e,t)=>{Me.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Ek(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}}),Je=x("$ZodStringFormat",(e,t)=>{Zo.init(e,t),du.init(e,t)}),Vk=x("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=uk),Je.init(e,t)}),Bk=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=zh(r))}else t.pattern??(t.pattern=zh());Je.init(e,t)}),Gk=x("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=dk),Je.init(e,t)}),Wk=x("$ZodURL",(e,t)=>{Je.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})}}}),Zk=x("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=pk()),Je.init(e,t)}),Jk=x("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=ck),Je.init(e,t)}),Kk=x("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=nk),Je.init(e,t)}),Yk=x("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ik),Je.init(e,t)}),Xk=x("$ZodULID",(e,t)=>{t.pattern??(t.pattern=sk),Je.init(e,t)}),Qk=x("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ok),Je.init(e,t)}),eR=x("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ak),Je.init(e,t)}),tR=x("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Sk(t)),Je.init(e,t)}),rR=x("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=bk),Je.init(e,t)}),nR=x("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=wk(t)),Je.init(e,t)}),iR=x("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=lk),Je.init(e,t)}),sR=x("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=fk),Je.init(e,t),e._zod.bag.format="ipv4"}),oR=x("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=vk),Je.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})}}}),aR=x("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=gk),Je.init(e,t)}),cR=x("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=mk),Je.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 lR=x("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=_k),Je.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 uR(e){if(!Mg.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/");return qg(t.padEnd(Math.ceil(t.length/4)*4,"="))}var dR=x("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Mg),Je.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{uR(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),hR=x("$ZodE164",(e,t)=>{t.pattern??(t.pattern=yk),Je.init(e,t)});function pR(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 fR=x("$ZodJWT",(e,t)=>{Je.init(e,t),e._zod.check=r=>{pR(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),jg=x("$ZodNumber",(e,t)=>{Me.init(e,t),e._zod.pattern=e._zod.bag.pattern??zg,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}}),vR=x("$ZodNumberFormat",(e,t)=>{Pk.init(e,t),jg.init(e,t)}),gR=x("$ZodBoolean",(e,t)=>{Me.init(e,t),e._zod.pattern=Rk,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}}),mR=x("$ZodUndefined",(e,t)=>{Me.init(e,t),e._zod.pattern=Tk,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}}),_R=x("$ZodNull",(e,t)=>{Me.init(e,t),e._zod.pattern=Ak,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}}),yR=x("$ZodAny",(e,t)=>{Me.init(e,t),e._zod.parse=r=>r}),bR=x("$ZodUnknown",(e,t)=>{Me.init(e,t),e._zod.parse=r=>r}),wR=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 Nh(e,t,r){e.issues.length&&t.issues.push(...rn(r,e.issues)),t.value[r]=e.value}var SR=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=>Nh(l,r,o))):Nh(c,r,o)}return s.length?Promise.all(s).then(()=>r):r}});function So(e,t,r,n,i){if(e.issues.length){if(i&&!(r in n))return;t.issues.push(...rn(r,e.issues))}e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}function Hg(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=DE(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function Vg(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=>So(p,r,h,t,u))):So(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 ER=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=Bo(()=>Hg(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=Qi,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=>So(v,o,h,c,p))):So(f,o,h,c,p)}return i?Vg(l,c,o,a,r.value,e):l.length?Promise.all(l).then(()=>o):o}}),kR=x("$ZodObjectJIT",(e,t)=>{ER.init(e,t);const r=e._zod.parse,n=Bo(()=>Hg(t)),i=d=>{const p=new jk(["shape","payload","ctx"]),f=n.value,v=S=>{const I=Dh(S);return`shape[${I}]._zod.run({ value: input[${I}], 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 I=m[S],C=Dh(S),$=d[S]?._zod?.optout==="optional";p.write(`const ${I} = ${v(S)};`),$?p.write(`
|
|
10
|
-
if (${I}.issues.length) {
|
|
11
|
-
if (${C} in input) {
|
|
12
|
-
payload.issues = payload.issues.concat(${I}.issues.map(iss => ({
|
|
13
|
-
...iss,
|
|
14
|
-
path: iss.path ? [${C}, ...iss.path] : [${C}]
|
|
15
|
-
})));
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
if (${I}.value === undefined) {
|
|
20
|
-
if (${C} in input) {
|
|
21
|
-
newResult[${C}] = undefined;
|
|
22
|
-
}
|
|
23
|
-
} else {
|
|
24
|
-
newResult[${C}] = ${I}.value;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
`):p.write(`
|
|
28
|
-
if (${I}.issues.length) {
|
|
29
|
-
payload.issues = payload.issues.concat(${I}.issues.map(iss => ({
|
|
30
|
-
...iss,
|
|
31
|
-
path: iss.path ? [${C}, ...iss.path] : [${C}]
|
|
32
|
-
})));
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
if (${I}.value === undefined) {
|
|
36
|
-
if (${C} in input) {
|
|
37
|
-
newResult[${C}] = undefined;
|
|
38
|
-
}
|
|
39
|
-
} else {
|
|
40
|
-
newResult[${C}] = ${I}.value;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
`)}p.write("payload.value = newResult;"),p.write("return payload;");const w=p.compile();return(S,I)=>w(d,S,I)};let s;const o=Qi,a=!rl.jitless,l=a&&ME.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?Vg([],f,d,p,h,e):d):r(d,p):(d.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),d)}});function Uh(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=>!$n(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=>Mr(o,n,xr())))}),t)}var Bg=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=>au(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=>Uh(c,i,e,s)):Uh(a,i,e,s)}}),RR=x("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Bg.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=Bo(()=>{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(!Qi(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)}}),AR=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])=>Fh(r,a,c)):Fh(r,s,o)}});function il(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(Qn(e)&&Qn(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=il(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=il(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 Fh(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}),$n(e))return e;const o=il(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 TR=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=>Rs(d,n,l))):Rs(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=>Rs(p,n,l))):Rs(d,n,l)}}return o.length?Promise.all(o).then(()=>n):n}});function Rs(e,t,r){e.issues.length&&t.issues.push(...rn(r,e.issues)),t.value[r]=e.value}var IR=x("$ZodRecord",(e,t)=>{Me.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!Qn(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(...rn(l,h.issues)),r.value[l]=h.value})):(u.issues.length&&r.issues.push(...rn(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"&&zg.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=>Mr(u,n,xr())),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(...rn(a,u.issues)),r.value[c.value]=u.value})):(l.issues.length&&r.issues.push(...rn(a,l.issues)),r.value[c.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),CR=x("$ZodEnum",(e,t)=>{Me.init(e,t);const r=Ig(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(i=>LE.has(typeof i)).map(i=>typeof i=="string"?ei(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}}),$R=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"?ei(n):n?ei(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}}),PR=x("$ZodTransform",(e,t)=>{Me.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Tg(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 jn;return r.value=i,r}});function qh(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var Gg=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(`^(${au(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=>qh(s,r.value)):qh(i,r.value)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),OR=x("$ZodExactOptional",(e,t)=>{Gg.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)}),xR=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(`^(${au(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)}),MR=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=>jh(s,t)):jh(i,t)}});function jh(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var LR=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))}),DR=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=>Hh(s,e)):Hh(i,e)}});function Hh(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 zR=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=>Mr(o,n,xr()))},input:r.value}),r.issues=[]),r)):(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(s=>Mr(s,n,xr()))},input:r.value}),r.issues=[]),r)}}),NR=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=>As(o,t.in,n)):As(s,t.in,n)}const i=t.in._zod.run(r,n);return i instanceof Promise?i.then(s=>As(s,t.out,n)):As(i,t.out,n)}});function As(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}var UR=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(Vh):Vh(i)}});function Vh(e){return e.value=Object.freeze(e.value),e}var FR=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)}),qR=x("$ZodCustom",(e,t)=>{wt.init(e,t),Me.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then(s=>Bh(s,r,n,e));Bh(i,r,n,e)}});function Bh(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(es(i))}}var Gh,jR=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 HR(){return new jR}(Gh=globalThis).__zod_globalRegistry??(Gh.__zod_globalRegistry=HR());var Ai=globalThis.__zod_globalRegistry;function VR(e,t){return new e({type:"string",...re(t)})}function BR(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...re(t)})}function Wh(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...re(t)})}function GR(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...re(t)})}function WR(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...re(t)})}function ZR(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...re(t)})}function JR(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...re(t)})}function KR(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...re(t)})}function YR(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...re(t)})}function XR(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...re(t)})}function QR(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...re(t)})}function eA(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...re(t)})}function tA(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...re(t)})}function rA(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...re(t)})}function nA(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...re(t)})}function iA(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...re(t)})}function sA(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...re(t)})}function oA(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...re(t)})}function aA(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...re(t)})}function cA(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...re(t)})}function lA(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...re(t)})}function uA(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...re(t)})}function dA(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...re(t)})}function hA(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...re(t)})}function pA(e,t){return new e({type:"string",format:"date",check:"string_format",...re(t)})}function fA(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...re(t)})}function vA(e,t){return new e({type:"string",format:"duration",check:"string_format",...re(t)})}function gA(e,t){return new e({type:"number",checks:[],...re(t)})}function mA(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...re(t)})}function _A(e,t){return new e({type:"boolean",...re(t)})}function yA(e,t){return new e({type:"undefined",...re(t)})}function bA(e,t){return new e({type:"null",...re(t)})}function wA(e){return new e({type:"any"})}function SA(e){return new e({type:"unknown"})}function EA(e,t){return new e({type:"never",...re(t)})}function Zh(e,t){return new Ug({check:"less_than",...re(t),value:e,inclusive:!1})}function cc(e,t){return new Ug({check:"less_than",...re(t),value:e,inclusive:!0})}function Jh(e,t){return new Fg({check:"greater_than",...re(t),value:e,inclusive:!1})}function lc(e,t){return new Fg({check:"greater_than",...re(t),value:e,inclusive:!0})}function Kh(e,t){return new $k({check:"multiple_of",...re(t),value:e})}function Wg(e,t){return new Ok({check:"max_length",...re(t),maximum:e})}function Eo(e,t){return new xk({check:"min_length",...re(t),minimum:e})}function Zg(e,t){return new Mk({check:"length_equals",...re(t),length:e})}function kA(e,t){return new Lk({check:"string_format",format:"regex",...re(t),pattern:e})}function RA(e){return new Dk({check:"string_format",format:"lowercase",...re(e)})}function AA(e){return new zk({check:"string_format",format:"uppercase",...re(e)})}function TA(e,t){return new Nk({check:"string_format",format:"includes",...re(t),includes:e})}function IA(e,t){return new Uk({check:"string_format",format:"starts_with",...re(t),prefix:e})}function CA(e,t){return new Fk({check:"string_format",format:"ends_with",...re(t),suffix:e})}function oi(e){return new qk({check:"overwrite",tx:e})}function $A(e){return oi(t=>t.normalize(e))}function PA(){return oi(e=>e.trim())}function OA(){return oi(e=>e.toLowerCase())}function xA(){return oi(e=>e.toUpperCase())}function MA(){return oi(e=>xE(e))}function LA(e,t,r){return new e({type:"array",element:t,...re(r)})}function DA(e,t,r){const n=re(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function zA(e,t,r){return new e({type:"custom",check:"custom",fn:t,...re(r)})}function NA(e){const t=UA(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(es(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(es(i))}},e(r.value,r)));return t}function UA(e,t){const r=new wt({check:"custom",...re(t)});return r._zod.check=e,r}function ko(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Ai,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Fe(e,t,r={path:[],schemaPath:[]}){var n;const i=e._zod.def,s=t.seen.get(e);if(s)return s.count++,r.schemaPath.includes(e)&&(s.cycle=r.path),s.schema;const o={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,o);const a=e._zod.toJSONSchema?.();if(a)o.schema=a;else{const l={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,l);else{const h=o.schema,d=t.processors[i.type];if(!d)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);d(e,t,h,l)}const u=e._zod.parent;u&&(o.ref||(o.ref=u),Fe(u,t,l),t.seen.get(u).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io==="input"&&ht(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 Ro(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 Ao(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:To(t,"input",e.processors),output:To(t,"output",e.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function ht(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 ht(n.element,r);if(n.type==="set")return ht(n.valueType,r);if(n.type==="lazy")return ht(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 ht(n.innerType,r);if(n.type==="intersection")return ht(n.left,r)||ht(n.right,r);if(n.type==="record"||n.type==="map")return ht(n.keyType,r)||ht(n.valueType,r);if(n.type==="pipe")return ht(n.in,r)||ht(n.out,r);if(n.type==="object"){for(const i in n.shape)if(ht(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(const i of n.options)if(ht(i,r))return!0;return!1}if(n.type==="tuple"){for(const i of n.items)if(ht(i,r))return!0;return!!(n.rest&&ht(n.rest,r))}return!1}var FA=(e,t={})=>r=>{const n=ko({...r,processors:t});return Fe(e,n),Ro(n,e),Ao(n,e)},To=(e,t,r={})=>n=>{const{libraryOptions:i,target:s}=n??{},o=ko({...i??{},target:s,io:t,processors:r});return Fe(e,o),Ro(o,e),Ao(o,e)},qA={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Jg=(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=qA[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}))])}},Kg=(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)},Yg=(e,t,r,n)=>{r.type="boolean"},jA=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},HA=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},Xg=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Qg=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},VA=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},em=(e,t,r,n)=>{r.not={}},tm=(e,t,r,n)=>{},rm=(e,t,r,n)=>{},BA=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},nm=(e,t,r,n)=>{const i=e._zod.def,s=Ig(i.entries);s.every(o=>typeof o=="number")&&(r.type="number"),s.every(o=>typeof o=="string")&&(r.type="string"),r.enum=s},im=(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},GA=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},WA=(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},ZA=(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)},JA=(e,t,r,n)=>{r.type="boolean"},sm=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},KA=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},om=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},YA=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},XA=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},am=(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"]})},cm=(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)},lm=(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},um=(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]]},dm=(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)},hm=(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)}},pm=(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"}]},fm=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType},vm=(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))},gm=(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)))},mm=(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},_m=(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},ym=(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},QA=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType},hu=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType},bm=(e,t,r,n)=>{const i=e._zod.innerType;Fe(i,t,n);const s=t.seen.get(e);s.ref=i},Yh={string:Jg,number:Kg,boolean:Yg,bigint:jA,symbol:HA,null:Xg,undefined:Qg,void:VA,never:em,any:tm,unknown:rm,date:BA,enum:nm,literal:im,nan:GA,template_literal:WA,file:ZA,success:JA,custom:sm,function:KA,transform:om,map:YA,set:XA,array:am,object:cm,union:lm,intersection:um,tuple:dm,record:hm,nullable:pm,nonoptional:fm,default:vm,prefault:gm,catch:mm,pipe:_m,readonly:ym,promise:QA,optional:hu,lazy:bm};function TM(e,t){if("_idmap"in e){const n=e,i=ko({...t,processors:Yh}),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;Ro(i,l),o[c]=Ao(i,l)}return Object.keys(s).length>0&&(o.__shared={[i.target==="draft-2020-12"?"$defs":"definitions"]:s}),{schemas:o}}const r=ko({...t,processors:Yh});return Fe(e,r),Ro(r,e),Ao(r,e)}var eT=x("ZodISODateTime",(e,t)=>{tR.init(e,t),Ye.init(e,t)});function tT(e){return hA(eT,e)}var rT=x("ZodISODate",(e,t)=>{rR.init(e,t),Ye.init(e,t)});function nT(e){return pA(rT,e)}var iT=x("ZodISOTime",(e,t)=>{nR.init(e,t),Ye.init(e,t)});function sT(e){return fA(iT,e)}var oT=x("ZodISODuration",(e,t)=>{iR.init(e,t),Ye.init(e,t)});function aT(e){return vA(oT,e)}var wm=(e,t)=>{Og.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>GE(e,r)},flatten:{value:r=>BE(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,nl,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,nl,2)}},isEmpty:{get(){return e.issues.length===0}}})},IM=x("ZodError",wm),Ct=x("ZodError",wm,{Parent:Error}),cT=lu(Ct),lT=uu(Ct),uT=Go(Ct),dT=Wo(Ct),hT=JE(Ct),pT=KE(Ct),fT=YE(Ct),vT=XE(Ct),gT=QE(Ct),mT=ek(Ct),_T=tk(Ct),yT=rk(Ct),ze=x("ZodType",(e,t)=>(Me.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:To(e,"input"),output:To(e,"output")}}),e.toJSONSchema=FA(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(jr(t,{checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),e.with=e.check,e.clone=(r,n)=>lr(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>cT(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>uT(e,r,n),e.parseAsync=async(r,n)=>lT(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>dT(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>hT(e,r,n),e.decode=(r,n)=>pT(e,r,n),e.encodeAsync=async(r,n)=>fT(e,r,n),e.decodeAsync=async(r,n)=>vT(e,r,n),e.safeEncode=(r,n)=>gT(e,r,n),e.safeDecode=(r,n)=>mT(e,r,n),e.safeEncodeAsync=async(r,n)=>_T(e,r,n),e.safeDecodeAsync=async(r,n)=>yT(e,r,n),e.refine=(r,n)=>e.check(fI(r,n)),e.superRefine=r=>e.check(vI(r)),e.overwrite=r=>e.check(oi(r)),e.optional=()=>ep(e),e.exactOptional=()=>tI(e),e.nullable=()=>tp(e),e.nullish=()=>ep(tp(e)),e.nonoptional=r=>aI(e,r),e.array=()=>xt(e),e.or=r=>GT([e,r]),e.and=r=>JT(e,r),e.transform=r=>cl(e,Tm(r)),e.default=r=>iI(e,r),e.prefault=r=>oI(e,r),e.catch=r=>lI(e,r),e.pipe=r=>cl(e,r),e.readonly=()=>hI(e),e.describe=r=>{const n=e.clone();return Ai.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Ai.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Ai.get(e);const n=e.clone();return Ai.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=r=>r(e),e)),Sm=x("_ZodString",(e,t)=>{du.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(n,i,s)=>Jg(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(kA(...n)),e.includes=(...n)=>e.check(TA(...n)),e.startsWith=(...n)=>e.check(IA(...n)),e.endsWith=(...n)=>e.check(CA(...n)),e.min=(...n)=>e.check(Eo(...n)),e.max=(...n)=>e.check(Wg(...n)),e.length=(...n)=>e.check(Zg(...n)),e.nonempty=(...n)=>e.check(Eo(1,...n)),e.lowercase=n=>e.check(RA(n)),e.uppercase=n=>e.check(AA(n)),e.trim=()=>e.check(PA()),e.normalize=(...n)=>e.check($A(...n)),e.toLowerCase=()=>e.check(OA()),e.toUpperCase=()=>e.check(xA()),e.slugify=()=>e.check(MA())}),bT=x("ZodString",(e,t)=>{du.init(e,t),Sm.init(e,t),e.email=r=>e.check(BR(wT,r)),e.url=r=>e.check(KR(ST,r)),e.jwt=r=>e.check(dA(zT,r)),e.emoji=r=>e.check(YR(ET,r)),e.guid=r=>e.check(Wh(Xh,r)),e.uuid=r=>e.check(GR(Ts,r)),e.uuidv4=r=>e.check(WR(Ts,r)),e.uuidv6=r=>e.check(ZR(Ts,r)),e.uuidv7=r=>e.check(JR(Ts,r)),e.nanoid=r=>e.check(XR(kT,r)),e.guid=r=>e.check(Wh(Xh,r)),e.cuid=r=>e.check(QR(RT,r)),e.cuid2=r=>e.check(eA(AT,r)),e.ulid=r=>e.check(tA(TT,r)),e.base64=r=>e.check(cA(MT,r)),e.base64url=r=>e.check(lA(LT,r)),e.xid=r=>e.check(rA(IT,r)),e.ksuid=r=>e.check(nA(CT,r)),e.ipv4=r=>e.check(iA($T,r)),e.ipv6=r=>e.check(sA(PT,r)),e.cidrv4=r=>e.check(oA(OT,r)),e.cidrv6=r=>e.check(aA(xT,r)),e.e164=r=>e.check(uA(DT,r)),e.datetime=r=>e.check(tT(r)),e.date=r=>e.check(nT(r)),e.time=r=>e.check(sT(r)),e.duration=r=>e.check(aT(r))});function Ne(e){return VR(bT,e)}var Ye=x("ZodStringFormat",(e,t)=>{Je.init(e,t),Sm.init(e,t)}),wT=x("ZodEmail",(e,t)=>{Gk.init(e,t),Ye.init(e,t)}),Xh=x("ZodGUID",(e,t)=>{Vk.init(e,t),Ye.init(e,t)}),Ts=x("ZodUUID",(e,t)=>{Bk.init(e,t),Ye.init(e,t)}),ST=x("ZodURL",(e,t)=>{Wk.init(e,t),Ye.init(e,t)}),ET=x("ZodEmoji",(e,t)=>{Zk.init(e,t),Ye.init(e,t)}),kT=x("ZodNanoID",(e,t)=>{Jk.init(e,t),Ye.init(e,t)}),RT=x("ZodCUID",(e,t)=>{Kk.init(e,t),Ye.init(e,t)}),AT=x("ZodCUID2",(e,t)=>{Yk.init(e,t),Ye.init(e,t)}),TT=x("ZodULID",(e,t)=>{Xk.init(e,t),Ye.init(e,t)}),IT=x("ZodXID",(e,t)=>{Qk.init(e,t),Ye.init(e,t)}),CT=x("ZodKSUID",(e,t)=>{eR.init(e,t),Ye.init(e,t)}),$T=x("ZodIPv4",(e,t)=>{sR.init(e,t),Ye.init(e,t)}),PT=x("ZodIPv6",(e,t)=>{oR.init(e,t),Ye.init(e,t)}),OT=x("ZodCIDRv4",(e,t)=>{aR.init(e,t),Ye.init(e,t)}),xT=x("ZodCIDRv6",(e,t)=>{cR.init(e,t),Ye.init(e,t)}),MT=x("ZodBase64",(e,t)=>{lR.init(e,t),Ye.init(e,t)}),LT=x("ZodBase64URL",(e,t)=>{dR.init(e,t),Ye.init(e,t)}),DT=x("ZodE164",(e,t)=>{hR.init(e,t),Ye.init(e,t)}),zT=x("ZodJWT",(e,t)=>{fR.init(e,t),Ye.init(e,t)}),Em=x("ZodNumber",(e,t)=>{jg.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(n,i,s)=>Kg(e,n,i,s),e.gt=(n,i)=>e.check(Jh(n,i)),e.gte=(n,i)=>e.check(lc(n,i)),e.min=(n,i)=>e.check(lc(n,i)),e.lt=(n,i)=>e.check(Zh(n,i)),e.lte=(n,i)=>e.check(cc(n,i)),e.max=(n,i)=>e.check(cc(n,i)),e.int=n=>e.check(Qh(n)),e.safe=n=>e.check(Qh(n)),e.positive=n=>e.check(Jh(0,n)),e.nonnegative=n=>e.check(lc(0,n)),e.negative=n=>e.check(Zh(0,n)),e.nonpositive=n=>e.check(cc(0,n)),e.multipleOf=(n,i)=>e.check(Kh(n,i)),e.step=(n,i)=>e.check(Kh(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 Io(e){return gA(Em,e)}var NT=x("ZodNumberFormat",(e,t)=>{vR.init(e,t),Em.init(e,t)});function Qh(e){return mA(NT,e)}var UT=x("ZodBoolean",(e,t)=>{gR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Yg(e,r,n,i)});function Qr(e){return _A(UT,e)}var FT=x("ZodUndefined",(e,t)=>{mR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Qg(e,r,n,i)});function CM(e){return yA(FT,e)}var qT=x("ZodNull",(e,t)=>{_R.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Xg(e,r,n,i)});function $M(e){return bA(qT,e)}var jT=x("ZodAny",(e,t)=>{yR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>tm(e,r,n,i)});function PM(){return wA(jT)}var HT=x("ZodUnknown",(e,t)=>{bR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>rm(e,r,n,i)});function sl(){return SA(HT)}var VT=x("ZodNever",(e,t)=>{wR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>em(e,r,n,i)});function km(e){return EA(VT,e)}var BT=x("ZodArray",(e,t)=>{SR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>am(e,r,n,i),e.element=t.element,e.min=(r,n)=>e.check(Eo(r,n)),e.nonempty=r=>e.check(Eo(1,r)),e.max=(r,n)=>e.check(Wg(r,n)),e.length=(r,n)=>e.check(Zg(r,n)),e.unwrap=()=>e.element});function xt(e,t){return LA(BT,e,t)}var pu=x("ZodObject",(e,t)=>{kR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>cm(e,r,n,i),Ae(e,"shape",()=>t.shape),e.keyof=()=>kr(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:sl()}),e.loose=()=>e.clone({...e._zod.def,catchall:sl()}),e.strict=()=>e.clone({...e._zod.def,catchall:km()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>FE(e,r),e.safeExtend=r=>qE(e,r),e.merge=r=>jE(e,r),e.pick=r=>NE(e,r),e.omit=r=>UE(e,r),e.partial=(...r)=>HE(Im,e,r[0]),e.required=(...r)=>VE(Cm,e,r[0])});function ln(e,t){const r={type:"object",shape:e??{},...re(t)};return new pu(r)}function OM(e,t){return new pu({type:"object",shape:e,catchall:km(),...re(t)})}function xM(e,t){return new pu({type:"object",shape:e,catchall:sl(),...re(t)})}var Rm=x("ZodUnion",(e,t)=>{Bg.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>lm(e,r,n,i),e.options=t.options});function GT(e,t){return new Rm({type:"union",options:e,...re(t)})}var WT=x("ZodDiscriminatedUnion",(e,t)=>{Rm.init(e,t),RR.init(e,t)});function MM(e,t,r){return new WT({type:"union",options:t,discriminator:e,...re(r)})}var ZT=x("ZodIntersection",(e,t)=>{AR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>um(e,r,n,i)});function JT(e,t){return new ZT({type:"intersection",left:e,right:t})}var KT=x("ZodTuple",(e,t)=>{TR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>dm(e,r,n,i),e.rest=r=>e.clone({...e._zod.def,rest:r})});function LM(e,t,r){const n=t instanceof Me,i=n?r:t;return new KT({type:"tuple",items:e,rest:n?t:null,...re(i)})}var Am=x("ZodRecord",(e,t)=>{IR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>hm(e,r,n,i),e.keyType=t.keyType,e.valueType=t.valueType});function ol(e,t,r){return new Am({type:"record",keyType:e,valueType:t,...re(r)})}function YT(e,t,r){const n=lr(e);return n._zod.values=void 0,new Am({type:"record",keyType:n,valueType:t,...re(r)})}var al=x("ZodEnum",(e,t)=>{CR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(n,i,s)=>nm(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 al({...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 al({...t,checks:[],...re(i),entries:s})}});function kr(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new al({type:"enum",entries:r,...re(t)})}var XT=x("ZodLiteral",(e,t)=>{$R.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>im(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 DM(e,t){return new XT({type:"literal",values:Array.isArray(e)?e:[e],...re(t)})}var QT=x("ZodTransform",(e,t)=>{PR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>om(e,r,n,i),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Tg(e.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(es(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(es(o))}};const i=t.transform(r.value,r);return i instanceof Promise?i.then(s=>(r.value=s,r)):(r.value=i,r)}});function Tm(e){return new QT({type:"transform",transform:e})}var Im=x("ZodOptional",(e,t)=>{Gg.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>hu(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function ep(e){return new Im({type:"optional",innerType:e})}var eI=x("ZodExactOptional",(e,t)=>{OR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>hu(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function tI(e){return new eI({type:"optional",innerType:e})}var rI=x("ZodNullable",(e,t)=>{xR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>pm(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function tp(e){return new rI({type:"nullable",innerType:e})}var nI=x("ZodDefault",(e,t)=>{MR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>vm(e,r,n,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function iI(e,t){return new nI({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():$g(t)}})}var sI=x("ZodPrefault",(e,t)=>{LR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>gm(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function oI(e,t){return new sI({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():$g(t)}})}var Cm=x("ZodNonOptional",(e,t)=>{DR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>fm(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function aI(e,t){return new Cm({type:"nonoptional",innerType:e,...re(t)})}var cI=x("ZodCatch",(e,t)=>{zR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>mm(e,r,n,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function lI(e,t){return new cI({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var uI=x("ZodPipe",(e,t)=>{NR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>_m(e,r,n,i),e.in=t.in,e.out=t.out});function cl(e,t){return new uI({type:"pipe",in:e,out:t})}var dI=x("ZodReadonly",(e,t)=>{UR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>ym(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function hI(e){return new dI({type:"readonly",innerType:e})}var pI=x("ZodLazy",(e,t)=>{FR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>bm(e,r,n,i),e.unwrap=()=>e._zod.def.getter()});function zM(e){return new pI({type:"lazy",getter:e})}var fu=x("ZodCustom",(e,t)=>{qR.init(e,t),ze.init(e,t),e._zod.processJSONSchema=(r,n,i)=>sm(e,r,n,i)});function NM(e,t){return DA(fu,e??(()=>!0),t)}function fI(e,t={}){return zA(fu,e,t)}function vI(e){return NA(e)}function UM(e,t={}){const r=new fu({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 FM(e,t){return cl(Tm(e),t)}var gI=["oauth-dcr","oauth-cimd","oauth-preregistered","static-header","authless","custom-connection"],mI=["no-user-data","processes-user-data","stores-user-data","shares-with-third-parties"],_I=["ownsOrIsAuthorizedForService","accurateDataHandlingDisclosure","compliesWithUsagePolicies","noProhibitedContent","maintainsSecurityPractices","respondsToSecurityReports","keepsListingAccurate"],Is=Ne().url().refine(e=>e.startsWith("https://"),{message:"must be an https:// URL"}),yI=ln({url:Ne().min(1),mimeType:Ne().min(1),widthPx:Io().int().positive(),heightPx:Io().int().positive(),prompt:Ne().min(1)}),qM=ln({name:Ne().min(1).max(vr.nameMaxLength),tagline:Ne().min(1).max(vr.taglineMaxLength),description:Ne().min(1).max(vr.descriptionMaxLength),categories:xt(Ne().min(1)).min(vr.categoriesMin).max(vr.categoriesMax),slug:Ne().min(1).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"must be a lowercase kebab-case slug"),documentationUrl:Is,privacyPolicyUrl:Is,supportUrl:Is,iconUrl:Is,declaredAuthMode:kr(gI),dataHandling:xt(kr(mI)).min(1),screenshots:xt(yI).min(vr.screenshotsMin).max(vr.screenshotsMax),attestations:ol(kr(_I),Qr())}),Hs={maxCompressedBytes:104857600,maxUncompressedBytes:536870912,maxEntries:5e3},bI={canonical:".codex-plugin/plugin.json",accepted:[".agent-plugin/plugin.json",".claude-plugin/plugin.json"]},Mt={nameMaxLength:100,displayNameMaxLength:100,shortDescriptionMaxLength:255,descriptionMaxLength:2e3,defaultPromptMaxLength:255,toolNameMaxLength:64,skillNameMaxLength:64},$m=["productivity","education","developer-tools","design","writing","research","data-analysis","marketing","sales","finance","health","travel","entertainment"],Vs={minEdgePx:48,maxEdgePx:4096,mustBeSquare:!0,maxBytes:5242880,acceptedMimeTypes:["image/png","image/jpeg","image/webp","image/svg+xml"]},wI={lightBackground:"#FFFFFF",darkBackground:"#212121",minRatio:2},en={maxSkillMarkdownBytes:262144,maxPageBytes:1048576,maxSkillTotalBytes:5242880,maxImportedTotalBytes:8388608,maxSkills:5,maxPagesPerSkill:10},SI="/.well-known/openai-apps-challenge",EI="text/html;profile=mcp-app",kI="/mcp",RI=["readOnlyHint","destructiveHint","openWorldHint"],ll={successCount:5,failureCount:3},AI={originChangeRequiresNewPlugin:!0,uiContentChangesStayLive:!0,uiContentCacheSeconds:3600},jM={archiveLimits:Hs,manifestLocations:bI,fieldLimits:Mt,listingCategories:$m,imageConstraints:Vs,brandColorContrast:wI,mcpSkillLimits:en,domainVerificationPath:SI,appHtmlMime:EI,expectedMcpPath:kI,requiredToolAnnotations:RI,submissionTestCases:ll,releaseRules:AI,source:Ht("deploy/submission","Host profile constants")},Z=e=>Ht("deploy/submission-errors",e),TI=[{id:"archive-too-large",category:"package-archive",severity:"blocking",message:"The uploaded archive exceeds the maximum compressed size.",limit:{name:"archiveLimits.maxCompressedBytes",value:Hs.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:Hs.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:Hs.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:Mt.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:Mt.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:Mt.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:Mt.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:Mt.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:Vs.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:Vs.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:Vs.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:Mt.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:Mt.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:en.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:en.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:en.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:en.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:en.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:en.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:ll.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:ll.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")}],HM=Object.freeze(Object.fromEntries(TI.map(e=>[e.id,e]))),II=["ownsOrIsAuthorizedForService","accurateDataDisclosure","compliesWithUsagePolicies","noProhibitedContent","maintainsSecurityPractices","respondsToSecurityReports","keepsListingAccurate"],CI=["none","account-identifiers","user-content","usage-analytics","payment-information","location","health","shared-with-third-parties"],$I=["in-submission-form","shared-out-of-band","not-required-authless"],uc=Ne().url().refine(e=>e.startsWith("https://"),{message:"must be an https:// URL"}),rp=ln({prompt:Ne().min(1),expectation:Ne().min(1)}),PI=ln({reference:Ne().min(1),mimeType:Ne().min(1),widthPx:Io().int().positive(),heightPx:Io().int().positive(),prompt:Ne().min(1)}),VM=ln({name:Ne().min(1).max(Mt.nameMaxLength),shortDescription:Ne().min(1).max(Mt.shortDescriptionMaxLength),description:Ne().min(1).max(Mt.descriptionMaxLength),categories:xt(kr($m)).min(1),privacyPolicyUrl:uc,supportUrl:uc,documentationUrl:uc.optional(),testCases:ln({successful:xt(rp),gracefulFailure:xt(rp)}),demoCredentials:ln({provided:Qr(),delivery:kr($I)}),demoRecordingProvided:Qr(),screenshots:xt(PI).default([]),releaseNotes:Ne().min(1).optional(),identityVerified:Qr(),accountPermissions:xt(Ne().min(1)).default([]),availableCountries:xt(Ne().length(2)).default([]),dataResidencyEligible:Qr().optional(),privacyPolicyDataTypes:xt(kr(CI)).default([]),annotationJustifications:ol(Ne(),Ne().min(1)).default({}),frameDomainExplanations:ol(Ne(),Ne().min(1)).default({}),domainVerificationToken:Ne().min(1).optional(),lastScanAt:Ne().datetime().optional(),hasPublishedVersion:Qr().optional(),attestations:YT(kr(II),Qr())}),BM=new TextDecoder("utf-8",{fatal:!1}),vu=Symbol.for("yaml.alias"),OI=Symbol.for("yaml.document"),un=Symbol.for("yaml.map"),Pm=Symbol.for("yaml.pair"),gu=Symbol.for("yaml.scalar"),os=Symbol.for("yaml.seq"),Jt=Symbol.for("yaml.node.type"),ai=e=>!!e&&typeof e=="object"&&e[Jt]===vu,as=e=>!!e&&typeof e=="object"&&e[Jt]===OI,mu=e=>!!e&&typeof e=="object"&&e[Jt]===un,it=e=>!!e&&typeof e=="object"&&e[Jt]===Pm,st=e=>!!e&&typeof e=="object"&&e[Jt]===gu,Jo=e=>!!e&&typeof e=="object"&&e[Jt]===os;function yt(e){if(e&&typeof e=="object")switch(e[Jt]){case un:case os:return!0}return!1}function nt(e){if(e&&typeof e=="object")switch(e[Jt]){case vu:case un:case gu:case os:return!0}return!1}var Om=e=>(st(e)||yt(e))&&!!e.anchor,_t=Symbol("break visit"),xm=Symbol("skip children"),Gt=Symbol("remove node");function cs(e,t){const r=Mm(t);as(e)?Pn(null,e.contents,r,Object.freeze([e]))===Gt&&(e.contents=null):Pn(null,e,r,Object.freeze([]))}cs.BREAK=_t;cs.SKIP=xm;cs.REMOVE=Gt;function Pn(e,t,r,n){const i=Lm(e,t,r,n);if(nt(i)||it(i))return Dm(e,n,i),Pn(e,i,r,n);if(typeof i!="symbol"){if(yt(t)){n=Object.freeze(n.concat(t));for(let s=0;s<t.items.length;++s){const o=Pn(s,t.items[s],r,n);if(typeof o=="number")s=o-1;else{if(o===_t)return _t;o===Gt&&(t.items.splice(s,1),s-=1)}}}else if(it(t)){n=Object.freeze(n.concat(t));const s=Pn("key",t.key,r,n);if(s===_t)return _t;s===Gt&&(t.key=null);const o=Pn("value",t.value,r,n);if(o===_t)return _t;o===Gt&&(t.value=null)}}return i}async function _u(e,t){const r=Mm(t);as(e)?await On(null,e.contents,r,Object.freeze([e]))===Gt&&(e.contents=null):await On(null,e,r,Object.freeze([]))}_u.BREAK=_t;_u.SKIP=xm;_u.REMOVE=Gt;async function On(e,t,r,n){const i=await Lm(e,t,r,n);if(nt(i)||it(i))return Dm(e,n,i),On(e,i,r,n);if(typeof i!="symbol"){if(yt(t)){n=Object.freeze(n.concat(t));for(let s=0;s<t.items.length;++s){const o=await On(s,t.items[s],r,n);if(typeof o=="number")s=o-1;else{if(o===_t)return _t;o===Gt&&(t.items.splice(s,1),s-=1)}}}else if(it(t)){n=Object.freeze(n.concat(t));const s=await On("key",t.key,r,n);if(s===_t)return _t;s===Gt&&(t.key=null);const o=await On("value",t.value,r,n);if(o===_t)return _t;o===Gt&&(t.value=null)}}return i}function Mm(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 Lm(e,t,r,n){if(typeof r=="function")return r(e,t,n);if(mu(t))return r.Map?.(e,t,n);if(Jo(t))return r.Seq?.(e,t,n);if(it(t))return r.Pair?.(e,t,n);if(st(t))return r.Scalar?.(e,t,n);if(ai(t))return r.Alias?.(e,t,n)}function Dm(e,t,r){const n=t[t.length-1];if(yt(n))n.items[e]=r;else if(it(n))e==="key"?n.key=r:n.value=r;else if(as(n))n.contents=r;else{const i=ai(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}var xI={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},MI=e=>e.replace(/[!,[\]{}]/g,t=>xI[t]),zm=class tr{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},tr.defaultYaml,t),this.tags=Object.assign({},tr.defaultTags,r)}clone(){const t=new tr(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){const t=new tr(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:tr.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},tr.defaultTags)}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:tr.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},tr.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+MI(t.substring(n.length));return t[0]==="!"?t:`!<${t}>`}toString(t){const r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let i;if(t&&n.length>0&&nt(t.contents)){const s={};cs(t.contents,(o,a)=>{nt(a)&&a.tag&&(s[a.tag]=!0)}),i=Object.keys(s)}else i=[];for(const[s,o]of n)s==="!!"&&o==="tag:yaml.org,2002:"||(!t||i.some(a=>a.startsWith(o)))&&r.push(`%TAG ${s} ${o}`);return r.join(`
|
|
46
|
-
`)}};zm.defaultYaml={explicit:!1,version:"1.2"};zm.defaultTags={"!!":"tag:yaml.org,2002:"};function Nm(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 Ti(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=Ti(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=Ti(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=Ti(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=Ti(e,n,i,s);o===void 0?delete n[i]:o!==s&&(n[i]=o)}return e.call(t,r,n)}function Nt(e,t,r){if(Array.isArray(e))return e.map((n,i)=>Nt(n,String(i),r));if(e&&typeof e.toJSON=="function"){if(!r||!Om(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 yu=class{constructor(e){Object.defineProperty(this,Jt,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:r,onAnchor:n,reviver:i}={}){if(!as(e))throw new TypeError("A document argument is required");const s={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},o=Nt(this,"",s);if(typeof n=="function")for(const{count:a,res:c}of s.anchors.values())n(c,a);return typeof i=="function"?Ti(i,{"":o},"",o):o}},LI=class extends yu{constructor(e){super(vu),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if(t?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;t?.aliasResolveCache?r=t.aliasResolveCache:(r=[],cs(e,{Node:(i,s)=>{(ai(s)||Om(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||(Nt(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=Bs(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(Nm(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 Bs(e,t,r){if(ai(t)){const n=t.resolve(e),i=r&&n&&r.get(n);return i?i.count*i.aliasCount:0}else if(yt(t)){let n=0;for(const i of t.items){const s=Bs(e,i,r);s>n&&(n=s)}return n}else if(it(t)){const n=Bs(e,t.key,r),i=Bs(e,t.value,r);return Math.max(n,i)}return 1}var Um=e=>!e||typeof e!="function"&&typeof e!="object",Ke=class extends yu{constructor(e){super(gu),this.value=e}toJSON(e,t){return t?.keep?this.value:Nt(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 DI="tag:yaml.org,2002:";function zI(e,t,r){if(t){const n=r.filter(s=>s.tag===t),i=n.find(s=>!s.format)??n[0];if(!i)throw new Error(`Tag ${t} not found`);return i}return r.find(n=>n.identify?.(e)&&!n.format)}function Co(e,t,r){if(as(e)&&(e=e.contents),nt(e))return e;if(it(e)){const h=r.schema[un].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 LI(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t=DI+t.slice(2));let l=zI(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[un]:Symbol.iterator in Object(e)?o[os]:o[un]}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 np(e,t,r){let n=r;for(let i=t.length-1;i>=0;--i){const s=t[i];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){const o=[];o[s]=n,n=o}else n=new Map([[s,n]])}return Co(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var NI=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Fm=class extends yu{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(r=>nt(r)||it(r)?r.clone(e):r),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(NI(e))this.add(t);else{const[r,...n]=e,i=this.get(r,!0);if(yt(i))i.addIn(n,t);else if(i===void 0&&this.schema)this.set(r,np(this.schema,n,t));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(e){const[t,...r]=e;if(r.length===0)return this.delete(t);const n=this.get(t,!0);if(yt(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){const[r,...n]=e,i=this.get(r,!0);return n.length===0?!t&&st(i)?i.value:i:yt(i)?i.getIn(n,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!it(t))return!1;const r=t.value;return r==null||e&&st(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){const[t,...r]=e;if(r.length===0)return this.has(t);const n=this.get(t,!0);return yt(n)?n.hasIn(r):!1}setIn(e,t){const[r,...n]=e;if(n.length===0)this.set(r,t);else{const i=this.get(r,!0);if(yt(i))i.setIn(n,t);else if(i===void 0&&this.schema)this.set(r,np(this.schema,n,t));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}},UI=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function ts(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var xn=(e,t,r)=>e.endsWith(`
|
|
47
|
-
`)?ts(r,t):r.includes(`
|
|
48
|
-
`)?`
|
|
49
|
-
`+ts(r,t):(e.endsWith(" ")?"":" ")+r,qm="flow",FI="block",qI="quoted";function Ko(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=ip(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=ip(e,v,t.length)),h=v+t.length+c,d=void 0;else{if(S===" "&&p&&p!==" "&&p!==`
|
|
51
|
-
`&&p!==" "){const I=e[v+1];I&&I!==" "&&I!==`
|
|
52
|
-
`&&I!==" "&&(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 I=v>_+1?v-2:m-1;if(u[I])return e;l.push(I),u[I]=!0,h=I+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 I=l[S],C=l[S+1]||e.length;I===0?w=`
|
|
53
|
-
${t}${e.slice(0,C)}`:(r==="quoted"&&u[I]&&(w+=`${e[I]}\\`),w+=`
|
|
54
|
-
${t}${e.slice(I+1,C)}`)}return w}function ip(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 Yo=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Xo=e=>/^(%|---|\.\.\.)/m.test(e);function jI(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 Hi(e,t){const r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;const{implicitKey:n}=t,i=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(Xo(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:Ko(o,s,qI,Yo(t,!1))}function ul(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
60
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return Hi(e,t);const r=t.indent||(Xo(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
61
|
-
${r}`)+"'";return t.implicitKey?n:Ko(n,r,qm,Yo(t,!1))}function Mn(e,t){const{singleQuote:r}=t.options;let n;if(r===!1)n=Hi;else{const i=e.includes('"'),s=e.includes("'");i&&!s?n=ul:s&&!i?n=Hi:n=r?ul:Hi}return n(e,t)}var dl;try{dl=new RegExp(`(^|(?<!
|
|
62
|
-
))
|
|
63
|
-
+(?!
|
|
64
|
-
|$)`,"g")}catch{dl=/\n+(?!\n|$)/g}function Gs({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 Mn(r,n);const l=n.indent||(n.forceBlockIndent||Xo(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===Ke.BLOCK_FOLDED?!1:t===Ke.BLOCK_LITERAL?!0:!jI(r,c,l.length);if(!r)return u?`|
|
|
65
|
-
`:`>
|
|
66
|
-
`;let h,d;for(d=r.length;d>0;--d){const I=r[d-1];if(I!==`
|
|
67
|
-
`&&I!==" "&&I!==" ")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(dl,`$&${l}`));let v=!1,m,_=-1;for(m=0;m<r.length;++m){const I=r[m];if(I===" ")v=!0;else if(I===`
|
|
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 I=r.replace(/\n+/g,`
|
|
71
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`);let C=!1;const $=Yo(n,!0);o!=="folded"&&t!==Ke.BLOCK_FOLDED&&($.onOverflow=()=>{C=!0});const M=Ko(`${w}${I}${p}`,l,FI,$);if(!C)return`>${S}
|
|
72
|
-
${l}${M}`}return r=r.replace(/\n+/g,`$&${l}`),`|${S}
|
|
73
|
-
${l}${w}${r}${p}`}function HI(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 Mn(s,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes(`
|
|
75
|
-
`)?Mn(s,t):Gs(e,t,r,n);if(!a&&!u&&i!==Ke.PLAIN&&s.includes(`
|
|
76
|
-
`))return Gs(e,t,r,n);if(Xo(s)){if(c==="")return t.forceBlockIndent=!0,Gs(e,t,r,n);if(a&&c===l)return Mn(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 Mn(s,t)}return a?h:Ko(h,c,qm,Yo(t,!1))}function VI(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?Mn(o.value,t):Gs(o,t,r,n);case Ke.QUOTE_DOUBLE:return Hi(o.value,t);case Ke.QUOTE_SINGLE:return ul(o.value,t);case Ke.PLAIN:return HI(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 BI(e,t){const r=Object.assign({blockQuote:!0,commentString:UI,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 GI(e,t){if(t.tag){const i=e.filter(s=>s.tag===t.tag);if(i.length>0)return i.find(s=>s.format===t.format)??i[0]}let r,n;if(st(t)){n=t.value;let i=e.filter(s=>s.identify?.(n));if(i.length>1){const s=i.filter(o=>o.test);s.length>0&&(i=s)}r=i.find(s=>s.format===t.format)??i.find(s=>!s.format)}else n=t,r=e.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!r){const i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return r}function WI(e,t,{anchors:r,doc:n}){if(!n.directives)return"";const i=[],s=(st(e)||yt(e))&&e.anchor;s&&Nm(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 $o(e,t,r,n){if(it(e))return e.toString(t,r,n);if(ai(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i;const s=nt(e)?e:t.doc.createNode(e,{onTagObj:c=>i=c});i??(i=GI(t.doc.schema.tags,s));const o=WI(s,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);const a=typeof i.stringify=="function"?i.stringify(s,t,r,n):st(s)?VI(s,t,r,n):s.toString(t,r,n);return o?st(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
78
|
-
${t.indent}${a}`:a}function ZI({key:e,value:t},r,n,i){const{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:h}}=r;let d=nt(e)&&e.comment||null;if(h){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(yt(e)||!nt(e)&&typeof e=="object")throw new Error("With simple keys, collection cannot be used as a key value")}let p=!h&&(!e||d&&t==null&&!r.inFlow||yt(e)||(st(e)?e.type===Ke.BLOCK_FOLDED||e.type===Ke.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(h||!s),indent:a+c});let f=!1,v=!1,m=$o(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+=xn(m,r.indent,l(d)):v&&i&&i(),m;f&&(d=null),p?(d&&(m+=xn(m,r.indent,l(d))),m=`? ${m}
|
|
79
|
-
${a}:`):(m=`${m}:`,d&&(m+=xn(m,r.indent,l(d))));let _,w,S;nt(t)?(_=!!t.spaceBefore,w=t.commentBefore,S=t.comment):(_=!1,w=null,S=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!p&&!d&&st(t)&&(r.indentAtStart=m.length+1),v=!1,!u&&c.length>=2&&!r.inFlow&&!p&&Jo(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let I=!1;const C=$o(t,r,()=>I=!0,()=>v=!0);let $=" ";if(d||_||w){if($=_?`
|
|
80
|
-
`:"",w){const M=l(w);$+=`
|
|
81
|
-
${ts(M,r.indent)}`}C===""&&!r.inFlow?$===`
|
|
82
|
-
`&&S&&($=`
|
|
83
|
-
|
|
84
|
-
`):$+=`
|
|
85
|
-
${r.indent}`}else if(!p&&yt(t)){const M=C[0],L=C.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=C.indexOf(" ");M==="&"&&k!==-1&&k<L&&C[k+1]==="!"&&(k=C.indexOf(" ",k+1)),(k===-1||L<k)&&(ee=!0)}ee||($=`
|
|
87
|
-
${r.indent}`)}}else(C===""||C[0]===`
|
|
88
|
-
`)&&($="");return m+=$+C,r.inFlow?I&&n&&n():S&&!I?m+=xn(m,r.indent,l(S)):v&&i&&i(),m}function JI(e,t){(e==="debug"||e==="warn")&&console.warn(t)}var Cs="<<",dc={identify:e=>e===Cs||typeof e=="symbol"&&e.description===Cs,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Ke(Symbol(Cs)),{addToJSMap:jm}),stringify:()=>Cs},KI=(e,t)=>(dc.identify(t)||st(t)&&(!t.type||t.type===Ke.PLAIN)&&dc.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===dc.tag&&r.default);function jm(e,t,r){const n=Hm(e,r);if(Jo(n))for(const i of n.items)hc(e,t,i);else if(Array.isArray(n))for(const i of n)hc(e,t,i);else hc(e,t,n)}function hc(e,t,r){const n=Hm(e,r);if(!mu(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 Hm(e,t){return e&&ai(t)?t.resolve(e.doc,e):t}function Vm(e,t,{key:r,value:n}){if(nt(r)&&r.addToJSMap)r.addToJSMap(e,t,n);else if(KI(e,r))jm(e,t,n);else{const i=Nt(r,"",e);if(t instanceof Map)t.set(i,Nt(n,i,e));else if(t instanceof Set)t.add(i);else{const s=YI(r,i,e),o=Nt(n,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}function YI(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(nt(e)&&r?.doc){const n=BI(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)+'..."'),JI(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 bu(e,t,r){const n=Co(e,void 0,r),i=Co(t,void 0,r);return new dn(n,i)}var dn=class Bm{constructor(t,r=null){Object.defineProperty(this,Jt,{value:Pm}),this.key=t,this.value=r}clone(t){let{key:r,value:n}=this;return nt(r)&&(r=r.clone(t)),nt(n)&&(n=n.clone(t)),new Bm(r,n)}toJSON(t,r){const n=r?.mapAsMap?new Map:{};return Vm(r,n,this)}toString(t,r,n){return t?.doc?ZI(this,t,r,n):JSON.stringify(this)}};function Gm(e,t,r){return(t.inFlow??e.flow?QI:XI)(e,t,r)}function XI({comment:e,items:t},r,{blockItemPrefix:n,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){const{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:s,type:null});let h=!1;const d=[];for(let f=0;f<t.length;++f){const v=t[f];let m=null;if(nt(v))!h&&v.spaceBefore&&d.push(""),Po(r,d,v.commentBefore,h),v.comment&&(m=v.comment);else if(it(v)){const w=nt(v.key)?v.key:null;w&&(!h&&w.spaceBefore&&d.push(""),Po(r,d,w.commentBefore,h))}h=!1;let _=$o(v,u,()=>m=null,()=>h=!0);m&&(_+=xn(_,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
|
-
`+ts(l(e),c),a&&a()):h&&o&&o(),p}function QI({items:e},t,{flowChars:r,itemIndent:n}){const{indent:i,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=t;n+=s;const c=Object.assign({},t,{indent:n,inFlow:!0,type:null});let l=!1,u=0;const h=[];for(let f=0;f<e.length;++f){const v=e[f];let m=null;if(nt(v))v.spaceBefore&&h.push(""),Po(t,h,v.commentBefore,!1),v.comment&&(m=v.comment);else if(it(v)){const w=nt(v.key)?v.key:null;w&&(w.spaceBefore&&h.push(""),Po(t,h,w.commentBefore,!1),w.comment&&(l=!0));const S=nt(v.value)?v.value:null;S?(S.comment&&(m=S.comment),S.commentBefore&&(l=!0)):v.value==null&&w?.comment&&(m=w.comment)}m&&(l=!0);let _=$o(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&&(_+=xn(_,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 Po({indent:e,options:{commentString:t}},r,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){const s=ts(t(n),e);r.push(s.trimStart())}}function nn(e,t){const r=st(t)?t.value:t;for(const n of e)if(it(n)&&(n.key===t||n.key===r||st(n.key)&&n.key.value===r))return n}var yr=class extends Fm{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(un,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(bu(a,c,r))};if(t instanceof Map)for(const[a,c]of t)o(a,c);else if(t&&typeof t=="object")for(const a of Object.keys(t))o(a,t[a]);return typeof e.sortMapEntries=="function"&&s.items.sort(e.sortMapEntries),s}add(e,t){let r;it(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new dn(e,e?.value):r=new dn(e.key,e.value);const n=nn(this.items,r.key),i=this.schema?.sortMapEntries;if(n){if(!t)throw new Error(`Key ${r.key} already set`);st(n.value)&&Um(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=nn(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const r=nn(this.items,e)?.value;return(!t&&st(r)?r.value:r)??void 0}has(e){return!!nn(this.items,e)}set(e,t){this.add(new dn(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)Vm(t,n,i);return n}toString(e,t,r){if(!e)return JSON.stringify(this);for(const n of this.items)if(!it(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Gm(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:t})}},eC={collection:"map",default:!0,nodeClass:yr,tag:"tag:yaml.org,2002:map",resolve(e,t){return mu(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>yr.from(e,t,r)},Oo=class extends Fm{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(os,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=$s(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const r=$s(e);if(typeof r!="number")return;const n=this.items[r];return!t&&st(n)?n.value:n}has(e){const t=$s(e);return typeof t=="number"&&t<this.items.length}set(e,t){const r=$s(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);const n=this.items[r];st(n)&&Um(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(Nt(i,String(n++),t));return r}toString(e,t,r){return e?Gm(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:r,onComment:t}):JSON.stringify(this)}static from(e,t,r){const{replacer:n}=r,i=new this(e);if(t&&Symbol.iterator in Object(t)){let s=0;for(let o of t){if(typeof n=="function"){const a=t instanceof Set?o:String(s++);o=n.call(t,a,o)}i.items.push(Co(o,void 0,r))}}return i}};function $s(e){let t=st(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}var tC={collection:"seq",default:!0,nodeClass:Oo,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Jo(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Oo.from(e,t,r)};function sp(e){return typeof e=="bigint"||Number.isInteger(e)}var Ps=({value:e})=>JSON.stringify(e),rC=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Ps},{identify:e=>e==null,createNode:()=>new Ke(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ps},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Ps},{identify:sp,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})=>sp(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:Ps}],GM=[eC,tC].concat(rC,{default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}});function nC(e,t,r){const{replacer:n}=r,i=new Oo(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(bu(a,c,r))}return i}var iC=class Wm extends Oo{constructor(){super(),this.add=yr.prototype.add.bind(this),this.delete=yr.prototype.delete.bind(this),this.get=yr.prototype.get.bind(this),this.has=yr.prototype.has.bind(this),this.set=yr.prototype.set.bind(this),this.tag=Wm.tag}toJSON(t,r){if(!r)return super.toJSON(t);const n=new Map;r?.onCreate&&r.onCreate(n);for(const i of this.items){let s,o;if(it(i)?(s=Nt(i.key,"",r),o=Nt(i.value,s,r)):s=Nt(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=nC(t,r,n),s=new this;return s.items=i.items,s}};iC.tag="tag:yaml.org,2002:omap";var sC=class Zm extends yr{constructor(t){super(t),this.tag=Zm.tag}add(t){let r;it(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new dn(t.key,null):r=new dn(t,null),nn(this.items,r.key)||this.items.push(r)}get(t,r){const n=nn(this.items,t);return!r&&it(n)?st(n.key)?n.key.value:n.key:n}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);const n=nn(this.items,t);n&&!r?this.items.splice(this.items.indexOf(n),1):!n&&r&&this.items.push(new dn(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(bu(o,null,n));return s}};sC.tag="tag:yaml.org,2002:set";var hl=Symbol("break visit"),oC=Symbol("skip children"),Jm=Symbol("remove item");function ti(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Km(Object.freeze([]),e,t)}ti.BREAK=hl;ti.SKIP=oC;ti.REMOVE=Jm;ti.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};ti.parentCollection=(e,t)=>{const r=ti.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 Km(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=Km(Object.freeze(e.concat([[i,o]])),s.items[o],r);if(typeof a=="number")o=a-1;else{if(a===hl)return hl;a===Jm&&(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 pl=["2025-03-26","2025-06-18","2025-11-25","2026-07-28"],aC=pl[pl.length-1];function Os(e){return e===aC?`Latest (${e})`:e}var cC=new Set(["2024-10-07","2024-11-05","2025-03-26","2025-06-18","2025-11-25"]);function lC(e){return pl.includes(e)}function uC(e){return e.length>0&&!cC.has(e)}var dC=["verified","refuted","unverifiable"],hC=["oauth2-dcr","oauth2-cimd","oauth2-preregistered","api-key","none"],pC=["omit","fixed","challenge","all-supported"],fC=["none","client_secret_basic","client_secret_post"],vC=["inline","fullscreen","pip"],WM=new Set(vC),Ws=["mode","originAllowlist"],ZM={allow_all:new Set(Ws),read_only:new Set(Ws),allowlist:new Set([...Ws,"toolAllowlist"])},JM=new Set([...Ws,"toolAllowlist"]),KM=new Set(pC),YM=new Set(fC),XM=new Set(dC),QM=new Set(hC),gC=["clientName","redirectUris","userAgent"],eL=new Set(gC);function mC(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 Ym(e){const t=new TextEncoder().encode(e);return mC(await crypto.subtle.digest("SHA-256",t))}function fl(e){return Array.isArray(e)?e.map(fl):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>[t,fl(r)])):e}function _C(e){return JSON.stringify(fl(e))}function tL(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 rL(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 nL(e){return Ym(_C(e))}async function yC(e){const t=[...e].sort((r,n)=>r.path<n.path?-1:r.path>n.path?1:0);return Ym(t.map(r=>`${r.path}\0${r.contentHash}\0`).join(""))}var bC=/^[A-Za-z]:[\\/]/,wC=/[\u0000-\u001f\u007f]/,SC=new TextEncoder;function EC(e){return SC.encode(e).length}function kC(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 Xm(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(wC.test(e))return{ok:!1,code:"PATH_INVALID_CHARACTER",message:"path contains control characters"};if(e.startsWith("/")||e.startsWith("\\")||bC.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=kC(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 RC(e){return e.normalize("NFKC").toLowerCase()}function iL(e,t){return t===e||t.startsWith(`${e}/`)}function sL(e,t){const r=Xm(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 oL(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=Xm(c.path);if(!l.ok){r.error(l.code,l.message,{path:c.path});continue}const u=l.path;if(EC(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=RC(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 AC=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}},aL=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 AC(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 TC=/(secret|token|password|passwd|api[-_]?key|private[-_]?key|credential)/i,Qm=/(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 cL(e){return Qm.test(e)}var bi=Symbol("drop");function vl(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)),bi;if(typeof e=="string")return Qm.test(e)?(n.issues.warn(n.secretCode,`${n.label}: value of "${t}" looks secret-bearing and is not stored`,n.context),bi):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=vl(e[o],`${t}[${o}]`,r+1,n,i);a!==bi&&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(TC.test(o)){n.issues.warn(n.secretCode,`${n.label}: field "${c}" looks secret-bearing and is not stored`,n.context);continue}const l=vl(a,c,r+1,n,i);l!==bi&&(s[o]=l)}return s}return bi}function lL(e,t){return vl(e,"",0,t,{reportedTooDeep:!1})}var uL="skills",dL="SKILL.md",e_=64,op=1024;function IC(e){return e.length<1||e.length>e_||e.includes("--")?!1:/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(e)}var gl=class extends Error{constructor(){super("yaml value nests too deeply"),this.name="YamlValueTooDeepError"}};function ml(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 gl;const n=r.slice(1,-1).trim();return n===""?[]:n.split(",").map(i=>ml(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(ml(p[1]))}catch(f){if(!(f instanceof gl))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]=ml(l)}catch(u){if(!(u instanceof gl))throw u;n.push(o)}s++}return{data:t,unparsed:r,tooDeep:n}}function $C(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 PC(e){return!Array.isArray(e)||e.some(t=>typeof t!="string")?null:e}async function hL(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=$C(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(!IC(v))return c.error("SKILL_INVALID_NAME",`skill name "${v}" must be kebab-case ([a-z0-9-], 1-${e_} 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>op)return c.error("SKILL_DESCRIPTION_TOO_LONG",`skill "${n}" description exceeds ${op} 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=[],I=d.mcp_tools;if(I!==void 0){const M=PC(I);if(M===null)c.warn("SKILL_INVALID_METADATA",`skill "${n}": "mcp_tools" must be a list of strings`,u);else for(const L of M)S.includes(L)||S.push(L)}const C=a.filter(M=>M.path!==i).map(M=>({path:M.path,relativePath:M.path.slice(r.length+1),size:M.size,contentHash:M.contentHash})),$=await yC(a.map(M=>({path:M.path.slice(r.length+1),contentHash:M.contentHash})));return{componentKey:l,directory:r,directoryName:n,skillFilePath:i,name:v,description:m,modelRef:`${t}/${v}`,instructions:h.body.trim(),frontmatter:d,frontmatterRaw:h.frontmatter,..._!==void 0?{allowImplicitInvocation:_}:{},mcpToolDependencies:S,supportingFiles:C,contentHash:o,aggregateHash:$}}var pL=new TextDecoder("utf-8",{fatal:!1}),OC=new Set(["access_token","refresh_token","id_token","client_secret","code","code_verifier","authorization_code","authorization","state","cookie","set_cookie","api_key"]),xC=[/^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 wu(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").toLowerCase()}var MC=["_type","_types","_endpoint","_endpoints","_supported","_method","_methods","_uri","_uris","_url","_urls","_alg","_algs","_values","_in"];function LC(e){return MC.some(t=>e.endsWith(t))}function Su(e){return OC.has(e)?!0:LC(e)?!1:/(^|_)(token|secret|password|credential|cookie|auth)(_|$)/.test(e)||/(^|_)api_?key(_|$)/.test(e)}function DC(e){return Su(wu(e))}function zC(e){return Su(wu(e))||xC.some(t=>t.test(e))}function NC(e){return Su(wu(e))}function Eu(e){return typeof e!="string"||e.length<=8?"[redacted]":`${e.slice(0,4)}...[redacted]...${e.slice(-2)}`}var t_="client_secret|access_token|refresh_token|id_token|code_verifier|code|assertion|password|api[-_]?key|token|secret|state",r_=new RegExp(`(^|[^\\w-])((?:[\\w-]*[_-])?(?:${t_}))=[^&\\s"'<>]+`,"gi"),n_=`(?:(?:[\\w-]*[_-])?(?:${t_}))`,UC=new RegExp(`("${n_}"\\s*:\\s*)"(?:\\\\.|[^"\\\\])*"`,"gi"),FC=new RegExp(`("${n_}"\\s*:\\s*)"(?:\\\\[\\s\\S]?|[^"\\\\])*$`,"gi");var qC=new RegExp(`\\b((?:[\\w-]*[_-])?(?:client[-_]?secret|access[-_]?token|refresh[-_]?token|id[-_]?token|code[-_]?verifier))(\\s*[:=]\\s*)("(?:\\\\.|[^"\\\\])*"|[^&\\s"'<>,;]+)`,"gi");function i_(e){const t=e.replace(/[.,;:!?)\]}]+$/,"");return!/^[a-z]{1,20}$/.test(t)}function jC(e,t,r,n){return i_(n)?`${t}${r}[redacted]`:e}function Tr(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(qC,(o,a,c,l)=>`${a}${c}${l.startsWith('"')?'"[redacted]"':"[redacted]"}`).replace(r_,"$1$2=[redacted]").replace(/\b((?:proxy-)?authorization\s*[:=]\s*)(bearer|basic)\s+\S+/gi,"$1$2 [redacted]").replace(/\b(bearer|basic)(\s+)(\S+)/gi,jC).replace(UC,'$1"[redacted]"');return(i?s.replace(FC,'$1"[redacted]').replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/?#]*$/gi,"$1[redacted]"):s).slice(0,n)}function HC(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 VC(e){return Object.keys(e).every(t=>t.length<=64&&/^[A-Za-z0-9_.\-[\]]+$/.test(t))}var BC=3;function GC(e,t){return/^https?:\/\//i.test(e)?t>=BC?"[redacted]":ku(e,t+1):e.replace(r_,"$1$2=[redacted]")}function ku(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=NC(s)?"[redacted]":GC(o,t);n||=a!==o,i.append(s,a)}return n&&(r.search=i.toString()),r.hash&&(r.hash="#[redacted]"),r.toString()}catch{return Tr(e)}}function s_(e){const t=e.trim();if(!t)return e;if(/^https?:\/\//i.test(t))return ku(t);if(t.includes("=")||t.includes("&")||t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")){const r=HC(t);if(r&&VC(r))return Wt(r)}return Tr(t)}function Wt(e){return Array.isArray(e)?e.map(t=>Wt(t)):typeof e=="string"?s_(e):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).map(([t,r])=>DC(t)?[t,Eu(r)]:[t,Wt(r)]))}function WC(e){const t=s_(e);return typeof t=="string"?t:Eu(e)}function ap(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>zC(t)?[t,Eu(r)]:[t,WC(r)]))}function fL(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 ZC(e){return _l(e,[])}function _l(e,t){return Array.isArray(e)?e.map(r=>_l(r,t)):!e||typeof e!="object"?typeof e=="string"?JC(e):e:Object.fromEntries(Object.entries(e).map(([r,n])=>[r,YC(r,n,t)?"[REDACTED]":_l(n,[...t,r])]))}function JC(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,KC).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 KC(e,t,r){return/^[A-Za-z_][A-Za-z0-9_-]*=/u.test(r)?e:i_(r)?`Bearer${t}[REDACTED]`:e}function YC(e,t,r){const n=e.toLowerCase().replace(/[^a-z0-9]/gu,"");return n==="code"?QC(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"))&&XC(t)||n==="apikey"||n==="xapikey"}function XC(e){return typeof e=="string"&&e.length>0}function QC(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 e$="ERA_NEGOTIATION_FAILED";function t$(e){return!!e&&typeof e=="object"&&e.code===e$}function r$(e){const t=new Set;let r=e;for(;t$(r)&&!t.has(r);){t.add(r);const n=r.data,i=(n&&typeof n=="object"?n.cause:void 0)??r.cause;if(i===void 0||i===r)break;r=i}return r}var Rt={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022,ResourceNotFound:-32602,ConnectionClosed:-32e3,RequestTimeout:-32001,UrlElicitationRequired:-32042},n$={HeaderMismatch:-32001,MissingRequiredClientCapability:-32003,UnsupportedProtocolVersion:-32004},i$="/troubleshooting/error-codes",cp={"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","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","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 ge(e,t,r,n,i,s,o="error"){return{slug:e,title:t,oneLine:r,likelyCauses:n,nextSteps:i,docsAnchor:`${i$}#${s}`,severity:o,...cp[e]?{origin:cp[e]}:{}}}var yl={"jsonrpc/parse_error":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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/mcpjam_limit_daily":ge("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":ge("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":ge("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/mcpjam_platform_budget":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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":ge("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 o_(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&&s$(n))return n;const i=e.cause;if(i!==void 0&&i!==e){const s=o_(i,t+1);if(s!==void 0)return s}return n}function s$(e){return o$.has(e)||e.startsWith("UND_ERR_")}var o$=new Set(["ECONNREFUSED","ECONNRESET","EAI_AGAIN","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET"]);function a$(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 ri(e){const t=ZC(e);return typeof t=="string"?t:String(e)}function c$(e){if(!e||typeof e!="object")return;const t=e.name;return typeof t=="string"?t:void 0}function Ru(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function a_(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 l$(e){if(!e||typeof e!="object")return;const t=e.code;return typeof t=="string"?t:void 0}function u$(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 c_(e){return yl[e]??yl["internal/unknown"]}var d$=200;function bl(e){const t=e.replace(/\s+/g," ").trim();return t.length<=d$?t:`${t.slice(0,199).trimEnd()}…`}function l_(e,t,r){if(t==="provider/mcpjam_limit_insufficient"){const n=Tu(r);return n?{...e,oneLine:n}:e}return t!=="internal/unknown"||!r?e:{...e,oneLine:bl(r)}}var h$=["Backend step returned no content (stream error or empty response)","Backend step returned no messages (stream error or empty response)"];function p$(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 f$={[Rt.ParseError]:"jsonrpc/parse_error",[Rt.InvalidRequest]:"jsonrpc/invalid_request",[Rt.MethodNotFound]:"jsonrpc/method_not_found",[Rt.InvalidParams]:"jsonrpc/invalid_params",[Rt.InternalError]:"jsonrpc/internal_error",[Rt.ConnectionClosed]:"jsonrpc/connection_closed",[Rt.HeaderMismatch]:"jsonrpc/header_mismatch",[Rt.MissingRequiredClientCapability]:"jsonrpc/missing_required_client_capability",[Rt.UnsupportedProtocolVersion]:"jsonrpc/unsupported_protocol_version",[n$.UnsupportedProtocolVersion]:"jsonrpc/unsupported_protocol_version",[Rt.UrlElicitationRequired]:"jsonrpc/url_elicitation_required"};function v$(e){return/header[^a-z]*mismatch/i.test(e)||/MCP-Protocol-Version/i.test(e)?"jsonrpc/header_mismatch":"jsonrpc/request_timeout"}var g$=/^(?:MCP error -32603:\s*)?invalid response format$/i;function u_(e){return g$.test(e.trim())}function m$(e){return u_(e)?"jsonrpc/invalid_response_format":"jsonrpc/internal_error"}function d_(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 _$(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=d_(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(u_(e))return"jsonrpc/invalid_response_format"}function y$(e){const t=w$(e);if(!t)return;const r=b$(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 b$(e){if(!e||typeof e!="object"||e.name!=="OAuthResponseError")return;const t=e.code;return typeof t=="string"&&t?t:void 0}function w$(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 h_(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"?ri(t.message):"";if(n)return{name:r,message:n}}var lp={AUTH_ERROR:"auth/http_401",OAUTH_REQUIRED:"auth/http_401"};function S$(e){const t=c$(e);if(t==="MCPAuthError"||t==="UnauthorizedError")return"auth/http_401";const r=l$(e);if(r&&lp[r])return lp[r]}function up(e){if(e===401)return"auth/http_401";if(e===403)return"auth/http_403";if(e===429)return"provider/quota"}function E$(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 k$(e){const t=Ru(e),r=e&&typeof e=="object"?e:null,n=r?.data?.code??r?.code;if(n==="platform_free_budget_exhausted")return{slug:"provider/mcpjam_platform_budget",rawCode:n};if(n==="account_suspended")return{slug:"account/suspended",rawCode:n};if(h$.some(p=>t.startsWith(p)))return{slug:"provider/empty_response"};const i=p$(t);if(i)return{slug:i};const s=S$(e);if(s)return{slug:s};const o=a_(e);if(o!==void 0){if(o===-32001)return{slug:v$(t),rawCode:o};if(o===Rt.InternalError)return{slug:m$(t),rawCode:o};const p=f$[o];if(p)return{slug:p,rawCode:o};const f=up(o);if(f)return{slug:f,rawCode:o}}const a=o_(e);if(a){const p=d_(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(Tu(t))return{slug:"provider/mcpjam_limit_insufficient"};if(/\bout of MCPJam credits\b/i.test(t))return{slug:"provider/mcpjam_limit"};const c=M$(t);if(c)return{slug:c};const l=Au(e);if(l!==void 0){const p=up(l);if(p)return{slug:p,rawCode:l}}const u=y$(e);if(u)return{slug:u};const h=E$(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=_$(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 R$=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 Au(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=u$(r);if(i!==void 0)return i;const s=a_(r);if(s!==void 0&&s>=100&&s<=599)return s;if(r.name==="UnauthorizedError")return 401;const o=r$(r);r=o!==r?o:r.cause}}function A$(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=Au(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 T$(e,t,r){if(t==="auth/insufficient_scope"&&r?.challenge?.scopes?.length)return{...e,oneLine:bl(ri(`${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:bl(ri(`${e.oneLine} The server reported \`${n}\`.`))}}var I$=new Set(["user_server","user_config","mcpjam","ambiguous"]);function C$(e){return typeof e=="string"&&I$.has(e)}function $$(e){const t=e?.origin;return C$(t)?t:"ambiguous"}function p_(e,t,r){return r?.credentialOwner==="mcpjam"&&R$.has(t)?{...e,origin:"mcpjam"}:e}function P$(e,t){return e==="provider/quota"&&t?.surface==="mcpServer"?"server/rate_limited":e}function O$(e,t){try{const r=ri(Ru(e)),n=A$(e,t),i=n?{slug:n}:k$(e),s=P$(i.slug,t),o=i.rawCode??(n?Au(e):void 0),a=p_(T$(l_(c_(s),s,r),s,t),s,t),c=h_(e);return{...a,rawMessage:r,...o!==void 0?{rawCode:o}:{},...c?{cause:c}:{}}}catch{return f_(e,"Unknown")}}function vL(e,t,r){try{const n=p_(c_(e),e,r),i=t!==void 0?ri(Ru(t)):"",s=h_(t);return{...n,rawMessage:i,...s?{cause:s}:{}}}catch{return f_(t,"")}}function f_(e,t){const r=yl["internal/unknown"];let n=t;try{n=ri(e instanceof Error?e.message:String(e??t))}catch{n=t}return{...l_(r,"internal/unknown",n),rawMessage:n}}var x$=/\bThis request needs about (\d+) MCPJam credits; your organization has (\d+) left[^.]{0,40}\./i;function Tu(e){const t=x$.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 M$(e){if(Tu(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 wl="[A-Za-z0-9!#$%&'*+.^_`|~-]+";function L$(e){const t={},r=new RegExp(`(${wl})\\s*=\\s*(?:"((?:\\\\.|[^"\\\\])*)"|([^,\\s]+))`,"g");for(let n=r.exec(e);n;n=r.exec(e)){const i=n[2];t[n[1].toLowerCase()]=i!==void 0?i.replace(/\\([\s\S])/g,"$1"):n[3]??""}return t}function cr(e){return v_(e)[0]??{}}function Iu(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 D$(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 v_(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(`^(${wl})\\s+(?!\\s*=)(.+)$`,"s"),o=new RegExp(`^(${wl})$`);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=>L$(a.params.join(", ")))}function z$(e){return v_(e).length>0}var Lr=class extends Error{status;constructor(e,t){super(e),this.name="UnexpectedProbeStatusError",this.status=t}};function ls(e){if(e.status===401)return{kind:"challenged",specCompliant:!0};if(e.status===200)return{kind:"anonymous_allowed"};if(e.status===403&&z$(e.wwwAuthenticateHeader))return{kind:"challenged",specCompliant:!1};const t=e.serverMessage||e.statusText,r=`HTTP ${e.status}${t?` ${t}`:""}`;return e.status===403?e.wwwAuthenticateHeader?.trim()?{kind:"unexpected",message:`MCP server returned ${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:`MCP server returned ${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:`MCP server returned ${r} where MCP requires 401 Unauthorized (or 200, if the server allows anonymous access).`}}function gL(e){return e.step!=="request_without_token"||e.status===void 0?!1:ls({status:e.status,statusText:e.statusText,wwwAuthenticateHeader:e.wwwAuthenticateHeader}).kind==="challenged"}function mL(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 N$(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 U$;U$=globalThis.crypto;var F$="Resource server does not implement OAuth 2.0 Protected Resource Metadata.",dp="No response while loading OAuth protected resource metadata.",q$="Failed to request resource metadata";function Qo(e){const t=e instanceof Error?e.message:String(e);return`${q$}: ${t}`}function _L(e){return e==="Resource server does not implement OAuth 2.0 Protected Resource Metadata."||e===Qo(new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata."))}function j$(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 H$(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 V$(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=H$(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 B$(e){return e.resolved?e.resolved.value:e.serverUrl===void 0?e.prmResource:Sl({serverUrl:e.serverUrl,prmResource:e.prmResource}).value}function Sl(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 V$(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:j$(e.serverUrl),source:"server",status:"valid",strictClientCompatible:!0,rfc9728Compliant:r===void 0,...r?{rfc9728Reason:r}:{}}}var g_="2025-11-25";async function m_(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 G$(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 hp(e,t,r=fetch){return m_(e,{"MCP-Protocol-Version":t,Accept:"application/json"},r)}function W$(e,t){return e?t==="/"?!1:e.status>=400&&e.status<500||e.status===502:!0}async function Z$(e,t,r,n){const i=new URL(e),s=n?.protocolVersion??g_;let o;if(n?.metadataUrl)o=new URL(n.metadataUrl);else{const l=G$(t,i.pathname);o=new URL(l,n?.metadataServerUrl??i),o.search=i.search}let a=await hp(o,s,r),c=!a;return!n?.metadataUrl&&W$(a,i.pathname)&&(a=await hp(new URL(`/.well-known/${t}`,i),s,r),c||=!a),{response:a,sawNoResponse:c}}function J$(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 ea(e,t,r=fetch){const{response:n,sawNoResponse:i}=await Z$(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n)throw new Error(dp);if(n.status===404)throw await n.text().catch(()=>{}),new Error(i?dp:F$);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 K$(e,{fetchFn:t=fetch,protocolVersion:r=g_}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"};for(const{url:i,type:s}of J$(e)){const o=await m_(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 yL(e,t){let r,n;try{r=await ea(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 K$(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:String(n),authorizationServerMetadata:i,resourceMetadata:r}}function Y$(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 ta(e){const t=Y$(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 pp(e){return new URLSearchParams([["v",e]]).toString().slice(2)}function Dr(e){const{clientId:t,clientSecret:r,tokenEndpointAuthMethod:n}=e;if(r&&n==="client_secret_basic")return{headers:{Authorization:`Basic ${btoa(`${pp(t??"")}:${pp(r)}`)}`},bodyParams:{}};const i={};return t&&(i.client_id=t),r&&n!=="none"&&(i.client_secret=r),{headers:{},bodyParams:i}}function ra(e){const t=e.token_endpoint_auth_method;if(!(e.client_secret&&(!t||t==="none")))return t||"none"}var fp=300,__="Authenticated request failed";function bL(e){return e.startsWith(`${__}: `)}function Xt(e){if(typeof e!="string")return;const t=e.trim();return t||void 0}function El(e){return e.replace(/\s+/g," ").trim()}function y_(e){if(typeof e=="string")return Xt(e);if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,r=Xt(t.error_type),n=Xt(t.error_description),i=Xt(t.error_message)??n??Xt(t.message),s=Xt(t.error);if(r&&i)return Xt(`${r}: ${i}`);if(s&&n)return Xt(`${s}: ${n}`);if(s)return s;const o=t.error;if(o&&typeof o=="object"&&!Array.isArray(o)){const a=Xt(o.message);if(a)return a}return i}function b_(e,t){const r=El(Tr(t.statusText??"",{maxLength:fp})),n=y_(t.body),i=n?El(Tr(n,{maxLength:fp})):void 0;return`${e}: ${t.status}${r?` ${r}`:""}${i?`: ${i}`:""}`}function na(e){return b_(__,e)}function ia(e){return b_("Token request failed",e)}function vp(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 X$(e){const t=e.split(".");return t.length!==3?null:{header:vp(t[0]),payload:vp(t[1]),signature:t[2]}}function zr(e){return X$(e)?.payload??null}function De(e){try{return new Date(e*1e3).toLocaleString()}catch{return String(e)}}var wL={isInitiatingAuth:!1,currentStep:"idle",httpHistory:[],infoLogs:[],tokenEndpointAuthMethod:void 0};function sa(){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 Ln(e,t){return`${e.substring(0,t)}...`}function kl(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 pc(e,t,r){return e.resourceIndicatorSuppressed?"omitted (emulation)":t.resourceValue(e)||r}function Q$(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:kl(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 eP(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 tP(e,t,r){if(r==="cimd")return eP(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:Ln(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:Ln(e.clientId,20)},{label:"Note",value:"Pre-registered (no DCR needed)"},...n]:[{label:"Note",value:"Pre-registered client credentials"}]}]}function oa(e,t,r){return[...r.includesProtectedResourceMetadata?Q$(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:kl(e.authorizationServerMetadata.token_endpoint)},{label:"Auth",value:kl(e.authorizationServerMetadata.authorization_endpoint)}]:void 0},...tP(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:Ln(e.codeChallenge,15)},{label:"method",value:e.codeChallengeMethod||"S256"},{label:"resource",value:pc(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:pc(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:Ln(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:Ln(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:pc(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 ${Ln(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 rP(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 aa(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 pn(e,t){if(!e||e.length===0)return e||void 0;const r=[...e],n={...r[r.length-1]};return r[r.length-1]={...n,error:t,duration:n.duration!==void 0?n.duration:Date.now()-n.timestamp},r}function ut(e,t={}){const r={},n=new Map,i=s=>{if(s)for(const[o,a]of Object.entries(s)){const c=o.toLowerCase(),l=n.get(c);l&&l!==o&&delete r[l],n.set(c,o),r[o]=a}};return i(e),i(t),r}function at(e,t={}){const r=ut(e,t);for(const n of Object.keys(r))n.toLowerCase()==="authorization"&&delete r[n];return r}function Cu(e,t,r,n={}){try{const i=new URL(e).origin;return new URL(t,e).origin===i?ut(r,n):at(r,n)}catch{return at(r,n)}}function Ir(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 nP(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 Nr(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=new Uint8Array(e);return crypto.getRandomValues(r),Array.from(r,n=>t[n%66]).join("")}async function ca(e){const t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return nP(new Uint8Array(r))}var la="Authorization server metadata missing required 'issuer' field",iP=new Set(["2025-03-26"]),sP=new Set(["2025-03-26","2025-06-18"]);function oP(e){return!iP.has(e)}function aP(e){return!sP.has(e)}function w_(e,t){if(aP(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 $u(e){const t=e.authorizationServers?.find(r=>typeof r=="string"&&r.trim()!=="")?.trim();return t?{authorizationServerUrl:t,substituted:!1}:oP(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 cP="io.modelcontextprotocol/oauth-client-credentials",lP="io.modelcontextprotocol/protocolVersion",uP="io.modelcontextprotocol/clientCapabilities",dP="io.modelcontextprotocol/clientInfo";function Pu(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 S_(e){return e!=="client_credentials"?{}:{extensions:{[cP]:{}}}}function zt(e){return{jsonrpc:"2.0",method:"initialize",params:{protocolVersion:e.protocolVersion,capabilities:S_(e.authMode),clientInfo:{name:e.clientName,version:e.clientVersion}},id:e.id}}function xs(e){return{jsonrpc:"2.0",method:"tools/list",params:{_meta:{[lP]:e.protocolVersion,[uP]:S_(e.authMode),[dP]:{name:e.clientName,version:e.clientVersion}}},id:e.id}}var hP="***REDACTED***",pP=new Set(["client_secret","registration_access_token","access_token","refresh_token"]),ua="Authorization server metadata does not include a registration_endpoint. Configure a pre-registered client or use a different registration strategy.",da="Authorization server metadata does not include a registration_endpoint required for DCR conformance.";function fP(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 ha(e){const{dynamicRegistrationDefaults:t}=e,r={...t,redirect_uris:t.redirect_uris??[e.redirectUri],grant_types:t.grant_types??["authorization_code","refresh_token"],response_types:t.response_types??["code"],token_endpoint_auth_method:t.token_endpoint_auth_method??"none"};return e.scope&&(r.scope=e.scope),{method:"POST",url:e.registrationEndpoint,headers:at(e.customHeaders,{"Content-Type":"application/json"}),body:r}}function Rl(e){if(Array.isArray(e))return e.map(Rl);if(e&&typeof e=="object"){const t={};for(const[r,n]of Object.entries(e))t[r]=pP.has(r.toLowerCase())?hP:Rl(n);return t}return e}function vP(e){return{status:e.status,statusText:e.statusText,headers:{...e.headers},body:Rl(e.body)}}function gp(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 fc="Configure a pre-registered client or enable DCR on the authorization server.";async function pa(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:gp(e.httpHistory,c),error:l,fallbackNote:"Client registration failed; using pre-registered client credentials.",errorWithFallbackHint:`${l}. ${fc}`}}const r=vP({status:t.status,statusText:t.statusText,headers:t.headers,body:t.body}),n=gp(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} ${fc}`}}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}. ${fc}`}}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 fa(e){return e?.sendResourceIndicator!==!1}function Ur(e,t){const r=e?.scopeRequest;if(!r)return N$(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 va(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 Fr(e,t){return e?.tokenEndpointAuthMethod??t}function gP(e,t){return t?.userAgent?{...e??{},"User-Agent":t.userAgent}:e}function fn(e,t){return e?.mcpProtocolVersion??t}function mP(e,t){return oa(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 _P(e){return new URL(e).origin}function mp(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 yP=e=>{const{state:t,getState:r,updateState:n,serverUrl:i,serverName:s,redirectUrl:o,requestExecutor:a,scheduleAutoAdvance:c,loadPreregisteredCredentials:l,dynamicRegistration:u,customScopes:h,customHeaders:d,authMode:p,hasClientSecret:f=!1,strictConformance:v=!1,registrationStrategy:m="dcr",emulation:_}=e,w=o,S=fn(_,"2025-03-26"),I=fn(_,Pu("2025-03-26")),C=fa(_),$=va(u??{},_);if(m==="dcr"&&!$.client_name)throw new Error("Dynamic registration metadata must include client_name");const M=()=>r?r():t,L=(k,ie={})=>a({url:k,method:ie.method||"GET",headers:Ir(ie.headers),body:ie.body}),q=k=>{const ie=ta({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),T={"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",T)}},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 N=await L(k.serverUrl,{method:"POST",headers:ut(d,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":S}),body:JSON.stringify(zt({protocolVersion:I,authMode:p,clientName:"MCP Inspector",clientVersion:"1.0.0",id:1}))}),se={status:N.status,statusText:N.statusText,headers:N.headers,body:N.body},ae=[...k.httpHistory||[]];if(ae.length>0){const Oe=ae[ae.length-1];Oe.response=se,Oe.duration=Date.now()-(Oe.timestamp||Date.now())}const he=ls({status:N.status,statusText:N.statusText,wwwAuthenticateHeader:N.headers["www-authenticate"],serverMessage:N.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=aa(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 Lr(he.message,N.status)}catch(N){throw N instanceof Lr?N:new Error(`Failed to request MCP server: ${N instanceof Error?N.message:String(N)}`)}break;case"discovery_start":const H=k.serverUrl,oe={method:"GET",url:mp(H)[0],headers:at(d,{})};n({currentStep:"request_authorization_server_metadata",authorizationServerUrl:H,lastRequest:oe,lastResponse:void 0,httpHistory:[...k.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:oe}],isInitiatingAuth:!1}),ie(50);return;case"request_authorization_server_metadata":if(!k.authorizationServerUrl)throw new Error("No authorization server URL available");const T=mp(k.authorizationServerUrl);let Q=null,y=null;for(const N of T)try{const se=at(d,{"MCP-Protocol-Version":"2025-03-26"}),ae=[...k.httpHistory||[]];ae.length>0&&(ae[ae.length-1].request={method:"GET",url:N,headers:se}),n({lastRequest:{method:"GET",url:N,headers:se},httpHistory:ae});const he=await L(N,{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 N=_P(k.authorizationServerUrl);Q={issuer:N,authorization_endpoint:`${N}/authorize`,token_endpoint:`${N}/token`,registration_endpoint:`${N}/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(la);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 N=K[K.length-1];N.response=V,N.duration=Date.now()-(N.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:N,clientSecret:se}=await l?.({serverName:s,serverUrl:i})??{};if(!N){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":N,"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:N,clientSecret:se||void 0,tokenEndpointAuthMethod:ae,infoLogs:Oe,isInitiatingAuth:!1})}else if(k.authorizationServerMetadata.registration_endpoint){const N=k.authorizationServerMetadata.scopes_supported,se=Ur(_,{customScopes:h,supportedScopes:N}),ae=ha({registrationEndpoint:k.authorizationServerMetadata.registration_endpoint,redirectUri:w,dynamicRegistrationDefaults:$,scope:se,customHeaders:d});n({currentStep:"request_client_registration",lastRequest:ae,lastResponse:void 0,httpHistory:[...k.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:ae}],isInitiatingAuth:!1}),ie(50);return}else{if(v){n({error:da,isInitiatingAuth:!1});return}const N=await X("Authorization server did not advertise registration_endpoint; using pre-registered client credentials.");if(!N){n({error:ua,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:N.clientId,clientSecret:N.clientSecret,tokenEndpointAuthMethod:N.tokenEndpointAuthMethod,infoLogs:N.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 N=await pa({request:k.lastRequest,requestExecutor:a,httpHistory:k.httpHistory});if(N.status!=="registered"){if(n({lastResponse:N.response,httpHistory:N.httpHistory,error:N.error}),v){N.status==="invalid_response"&&n({isInitiatingAuth:!1});return}const ae=await X(N.fallbackNote);if(!ae){n({error:N.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(N.missingClientId){n({lastResponse:N.response,httpHistory:N.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",N.infoLogData);n({currentStep:"received_client_credentials",clientId:N.credentials.clientId,clientSecret:N.credentials.clientSecret,tokenEndpointAuthMethod:ra(N.clientInfo),lastResponse:N.response,httpHistory:N.httpHistory,infoLogs:se,error:void 0,isInitiatingAuth:!1})}break;case"received_client_credentials":const de=Nr(43),$e=await ca(de),Re=ne(M(),"generate_pkce_parameters","pkce-generation","Generate PKCE Parameters (REQUIRED)",{code_challenge:$e,method:"S256",...C?{resource:k.serverUrl||"Unknown"}:{resource:"(omitted — emulated client does not send RFC 8707 resource)"},note:"PKCE is REQUIRED for all clients in 2025-03-26 spec"});n({currentStep:"generate_pkce_parameters",codeVerifier:de,codeChallenge:$e,codeChallengeMethod:"S256",...C?{}:{resourceIndicatorSuppressed:!0},state:Nr(16),infoLogs:Re,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!k.authorizationServerMetadata?.authorization_endpoint||!k.clientId)throw new Error("Missing authorization endpoint or client ID");const _e=new URL(k.authorizationServerMetadata.authorization_endpoint);_e.searchParams.set("response_type","code"),_e.searchParams.set("client_id",k.clientId),_e.searchParams.set("redirect_uri",w),_e.searchParams.set("code_challenge",k.codeChallenge||""),_e.searchParams.set("code_challenge_method","S256"),_e.searchParams.set("state",k.state||""),k.serverUrl&&C&&_e.searchParams.set("resource",k.serverUrl);const ve=Ur(_,{customScopes:h,supportedScopes:k.authorizationServerMetadata.scopes_supported});ve&&_e.searchParams.set("scope",ve);const qe=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:qe,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 N=Dr({clientId:k.clientId,clientSecret:k.clientSecret,tokenEndpointAuthMethod:Fr(_,k.tokenEndpointAuthMethod)}),se={grant_type:"authorization_code",code:k.authorizationCode,redirect_uri:w,...N.bodyParams};k.codeVerifier&&(se.code_verifier=k.codeVerifier),k.serverUrl&&C&&(se.resource=k.serverUrl);const ae={method:"POST",url:k.authorizationServerMetadata.token_endpoint,headers:{"Content-Type":"application/x-www-form-urlencoded",...N.headers},body:se};n({currentStep:"token_request",lastRequest:ae,lastResponse:void 0,...C?{}:{resourceIndicatorSuppressed:!0},accessToken:void 0,refreshToken:void 0,httpHistory:[...k.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:ae}],isInitiatingAuth:!1}),ie(50);return}case"token_request":if(!k.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!k.authorizationCode)throw new Error("Missing authorization code");if(!k.codeVerifier)throw new Error("PKCE code_verifier is missing - REQUIRED by 2025-03-26 spec for token exchange");try{const N=Dr({clientId:k.clientId,clientSecret:k.clientSecret,tokenEndpointAuthMethod:Fr(_,k.tokenEndpointAuthMethod)}),se=new URLSearchParams({grant_type:"authorization_code",code:k.authorizationCode,redirect_uri:w,code_verifier:k.codeVerifier||"",...N.bodyParams});k.serverUrl&&C&&se.set("resource",k.serverUrl);const ae=await L(k.authorizationServerMetadata.token_endpoint,{method:"POST",headers:{...at(d,{"Content-Type":"application/x-www-form-urlencoded"}),...N.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:ia(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=zr(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 We=k.serverUrl,U=(Array.isArray(me.aud)?me.aud:[me.aud]).some(W=>W===We);Ee._validation={expected_audience:We,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=zr(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(N){const se={status:0,statusText:"Network Error",headers:{},body:{error:N instanceof Error?N.message:String(N)}},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: ${N instanceof Error?N.message:String(N)}`,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:zt({protocolVersion:I,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 N=await L(k.serverUrl,{method:"POST",headers:ut(d,{Authorization:`Bearer ${k.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(zt({protocolVersion:I,authMode:p,clientName:"MCP Inspector",clientVersion:"1.0.0",id:2}))}),se={status:N.status,statusText:N.statusText,headers:N.headers,body:N.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(!N.ok){if(N.status>=400&&N.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 We=Ee.body;if(We&&typeof We=="object"&&We.isOldTransport&&We.endpoint){const U=We.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":We.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:We.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:na(N),isInitiatingAuth:!1});return}let he=M().infoLogs||[];const Oe=N.headers["content-type"]||"",we=Oe.includes("text/event-stream");let Se=null;if(we&&N.body?.transport==="sse"?Se=N.body.mcpResponse:Se=N.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:N.body?.events?`${N.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(N){const se=Tt(N),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(),T=Tt(H),Q=ne(oe,oe.currentStep,`error-${oe.currentStep}-${Date.now()}`,"Step failed",{step:oe.currentStep,request:oe.lastRequest,response:oe.lastResponse,error:T},{level:"error",error:T}),y=pn(oe.httpHistory,T),V={error:T.message,infoLogs:Q,isInitiatingAuth:!1};y&&(V.httpHistory=y),n(V)}},startGuidedFlow:async()=>{n({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{n(sa())}};return ee};function Ou(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()}function ci(e,t){return B$({serverUrl:e.serverUrl??t,prmResource:e.resourceMetadata?.resource,resolved:e.resourceIndicator})}function xu(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:Sl({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=Sl({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:rP(e.state,e.infoLogs,n,t)}}var bP=e=>ci(e);function wP(e,t){return oa(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:bP})}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 SP=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:I}=e,C=o,$=fn(I,"2025-06-18"),M=fn(I,Pu("2025-06-18")),L=fa(I),q=va(u??{},I);if(S==="dcr"&&!q.client_name)throw new Error("Dynamic registration metadata must include client_name");const X=()=>r?r():t,ee=()=>ci(X(),i),k=(T,Q={})=>a({url:T,method:Q.method||"GET",headers:Ir(Q.headers),body:Q.body}),ie=T=>{const Q=ta({authorizationServerMetadata:X().authorizationServerMetadata,hasClientSecret:!!(T||v)});if(!Q.ok)throw new Error(Q.message);return Q.method},H=async T=>{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:T};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 T=X();n({isInitiatingAuth:!0});const Q=y=>{c?.(()=>{oe.proceedToNextStep()},y)};try{switch(T.currentStep){case"idle":{const U=ut(d,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":$}),W=zt({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:[...T.httpHistory||[],{step:"request_without_token",timestamp:Date.now(),request:Y}],isInitiatingAuth:!1}),Q(50);return}case"request_without_token":if(!T.serverUrl)throw new Error("No server URL available");try{const U=await k(T.serverUrl,{method:"POST",headers:ut(d,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":$}),body:JSON.stringify(zt({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=[...T.httpHistory||[]];if(Y.length>0){const R=Y[Y.length-1];R.response=W,R.duration=Date.now()-(R.timestamp||Date.now())}const g=ls({status:U.status,statusText:U.statusText,wwwAuthenticateHeader:U.headers["www-authenticate"],serverMessage:U.body?.error?.message});if(g.kind==="challenged"){const R=U.headers["www-authenticate"],E=cr(R),P=Iu(E.scope);let F=R?ne(T,"received_401_unauthorized","www-authenticate","WWW-Authenticate Header",{header:R,...P&&P.length>0?{scope:P.join(" ")}:{},"Received from":T.serverUrl||"Unknown"}):T.infoLogs;g.specCompliant||(F=aa(T,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(T,"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 Lr(g.message,U.status)}catch(U){throw U instanceof Lr?U:new Error(`Failed to request MCP server: ${U instanceof Error?U.message:String(U)}`)}break;case"received_401_unauthorized":{const U=cr(T.wwwAuthenticateHeader);let W=p||U.resource_metadata;if(!W&&T.serverUrl&&(W=Ou(T.serverUrl)),!W)throw new Error("Could not determine resource metadata URL");const Y={method:"GET",url:W,headers:ut(d,{})};n({currentStep:"request_resource_metadata",resourceMetadataUrl:W,lastRequest:Y,lastResponse:void 0,httpHistory:[...T.httpHistory||[],{step:"request_resource_metadata",timestamp:Date.now(),request:Y}],isInitiatingAuth:!1}),Q(50);return}case"request_resource_metadata":if(!T.serverUrl)throw new Error("No server URL available");const y=[...T.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=Cu(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||cr(T.wwwAuthenticateHeader).resource_metadata)&&T.resourceMetadataUrl?{resourceMetadataUrl:T.resourceMetadataUrl}:void 0,W=await ea(T.serverUrl,U,de),Y=[...y,...K],g=K[K.length-1],R=$u({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||T.resourceMetadataUrl,lastRequest:g?.request,lastResponse:g?.response,httpHistory:Y,error:R.error,isInitiatingAuth:!1});return}let P=T.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}=xu({state:T,fallbackServerUrl:i,prmResource:W.resource,enforcement:_,infoLogs:P});n({currentStep:"received_resource_metadata",resourceMetadata:W,resourceIndicator:F,resourceMetadataUrl:g?.request?.url||T.resourceMetadataUrl,authorizationServerUrl:E,lastRequest:g?.request,lastResponse:g?.response,httpHistory:Y,infoLogs:B,isInitiatingAuth:!1})}catch(U){const W=pn([...y,...K],Tt(U));throw n({lastResponse:K[K.length-1]?.response,httpHistory:W}),new Error(Qo(U))}break;case"received_resource_metadata":if(!T.authorizationServerUrl)throw new Error("No authorization server URL available");const $e={method:"GET",url:_p(T.authorizationServerUrl)[0],headers:at(d,{})};n({currentStep:"request_authorization_server_metadata",lastRequest:$e,lastResponse:void 0,httpHistory:[...T.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:$e}],isInitiatingAuth:!1}),Q(50);return;case"request_authorization_server_metadata":if(!T.authorizationServerUrl)throw new Error("No authorization server URL available");const Re=_p(T.authorizationServerUrl);let _e=null,ve=null,qe={},Xe=null;for(const U of Re)try{const W=at(d,{}),Y=[...T.httpHistory||[]];Y.length>0&&(Y[Y.length-1].request={method:"GET",url:U,headers:W}),n({lastRequest:{method:"GET",url:U,headers:W},httpHistory:Y});const g=await k(U,{method:"GET",headers:at(d,{})});if(g.ok){_e=g.body,qe=g.headers,Xe=g;break}else{if(g.status>=400&&g.status<500)continue;ve=new Error(`HTTP ${g.status} from ${U}`)}}catch(W){ve=W;continue}if(!_e||!Xe)throw new Error(`Could not discover authorization server metadata. Last error: ${ve instanceof Error?ve.message:String(ve)}`);if(!_e.issuer)throw new Error(la);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:qe,body:_e},N=[...T.httpHistory||[]];N.length>0&&(N[N.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:N,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:N,error:"Warning: Authorization server may not support S256 PKCE method",isInitiatingAuth:!1}));break;case"received_authorization_server_metadata":if(!T.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(T.authorizationServerMetadata.registration_endpoint){const U=T.resourceMetadata?.scopes_supported||T.authorizationServerMetadata.scopes_supported,W=Ur(I,{customScopes:h,challengedScopes:T.challengedScopes,supportedScopes:U}),Y=ha({registrationEndpoint:T.authorizationServerMetadata.registration_endpoint,redirectUri:C,dynamicRegistrationDefaults:q,scope:W,customHeaders:d});n({currentStep:"request_client_registration",lastRequest:Y,lastResponse:void 0,httpHistory:[...T.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:Y}],isInitiatingAuth:!1}),Q(50);return}else{if(m){n({error:da,isInitiatingAuth:!1});return}const U=await H("Authorization server did not advertise registration_endpoint; using pre-registered client credentials.");if(!U){n({error:ua,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(!T.authorizationServerMetadata?.registration_endpoint)throw new Error("No registration endpoint available");if(!T.lastRequest?.body)throw new Error("No client metadata in request");const U=await pa({request:T.lastRequest,requestExecutor:a,httpHistory:T.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:ra(U.clientInfo),lastResponse:U.response,httpHistory:U.httpHistory,infoLogs:W,error:void 0,isInitiatingAuth:!1});break}case"received_client_credentials":const ae=Nr(43),he=await ca(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:Nr(16),infoLogs:Oe,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!T.authorizationServerMetadata?.authorization_endpoint||!T.clientId)throw new Error("Missing authorization endpoint or client ID");const we=new URL(T.authorizationServerMetadata.authorization_endpoint);we.searchParams.set("response_type","code"),we.searchParams.set("client_id",T.clientId),we.searchParams.set("redirect_uri",C),we.searchParams.set("code_challenge",T.codeChallenge||""),we.searchParams.set("code_challenge_method","S256"),we.searchParams.set("state",T.state||"");const Se=ee();Se&&L&&we.searchParams.set("resource",Se);const pe=Ur(I,{customScopes:h,challengedScopes:T.challengedScopes,supportedScopes:T.resourceMetadata?.scopes_supported||T.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(!T.authorizationCode||T.authorizationCode.trim()===""){n({error:"Authorization code is required. Please paste the code you received from the authorization server.",isInitiatingAuth:!1});return}if(!T.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");const U=Dr({clientId:T.clientId,clientSecret:T.clientSecret,tokenEndpointAuthMethod:Fr(I,T.tokenEndpointAuthMethod)}),W={grant_type:"authorization_code",code:T.authorizationCode,redirect_uri:C,...U.bodyParams};T.codeVerifier&&(W.code_verifier=T.codeVerifier);const Y=ee();Y&&L&&(W.resource=Y);const g={method:"POST",url:T.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:[...T.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:g}],isInitiatingAuth:!1}),Q(50);return}case"token_request":if(!T.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!T.authorizationCode)throw new Error("Missing authorization code");if(!T.codeVerifier)throw new Error("PKCE code_verifier is missing - cannot exchange token");try{const U=Dr({clientId:T.clientId,clientSecret:T.clientSecret,tokenEndpointAuthMethod:Fr(I,T.tokenEndpointAuthMethod)}),W=new URLSearchParams({grant_type:"authorization_code",code:T.authorizationCode,redirect_uri:C,code_verifier:T.codeVerifier||"",...U.bodyParams}),Y=ee();Y&&L&&W.set("resource",Y);const g=await k(T.authorizationServerMetadata.token_endpoint,{method:"POST",headers:{...at(d,{"Content-Type":"application/x-www-form-urlencoded"}),...U.headers},body:W.toString()}),R={status:g.status,statusText:g.statusText,headers:g.headers,body:g.body},E=[...T.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:ia(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(T.authorizationCode&&(F=[...F,{id:"auth-code",step:"token_request",level:"info",label:"Authorization Code",data:{code:T.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=zr(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=T.serverUrl,Ut=(Array.isArray(D.aud)?D.aud:[D.aud]).some(Hr=>Hr===J);G._validation={expected_audience:J,audience_matches:Ut,note:Ut?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else G._validation={note:"⚠ No audience claim found - server should validate token binding"};F=[...F,{id:"token",step:"token_request",level:"info",label:"Access Token (Decoded JWT)",data:G,timestamp:Date.now()}]}}if(P.id_token){const B=zr(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=[...T.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(!T.serverUrl||!T.accessToken)throw new Error("Missing server URL or access token");const Ee={method:"POST",url:T.serverUrl,headers:{Authorization:`Bearer ${T.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":$},body:zt({protocolVersion:M,authMode:f,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:2})},We=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:T.serverUrl});n({currentStep:"authenticated_mcp_request",lastRequest:Ee,lastResponse:void 0,httpHistory:[...T.httpHistory||[],{step:"authenticated_mcp_request",timestamp:Date.now(),request:Ee}],infoLogs:We,isInitiatingAuth:!1}),Q(50);return;case"authenticated_mcp_request":if(!T.serverUrl||!T.accessToken)throw new Error("Missing server URL or access token");try{const U=await k(T.serverUrl,{method:"POST",headers:ut(d,{Authorization:`Bearer ${T.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":$}),body:JSON.stringify(zt({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=[...T.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:na(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=[...T.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=pn(V.httpHistory,K),$e={error:K.message,infoLogs:le,isInitiatingAuth:!1};de&&($e.httpHistory=de),n($e)}},startGuidedFlow:async()=>{n({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{n(sa())}};return oe};function ga(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 SL(e){try{const{protocol:t,hostname:r}=new URL(e);return t==="http:"&&ga(r)}catch{return!1}}function E_(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:"&&ga(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 EP=e=>ci(e);function kP(e,t){return oa(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:EP})}function yp(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 RP=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:I="cimd",emulation:C}=e,$=o,M=fn(C,"2025-11-25"),L=fn(C,Pu("2025-11-25")),q=fa(C),X=va(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=E_(ee));const k=()=>r?r():t,ie=()=>ci(k(),i),H=(y,V={})=>a({url:y,method:V.method||"GET",headers:Ir(V.headers),body:V.body}),oe=y=>{const V=ta({authorizationServerMetadata:k().authorizationServerMetadata,hasClientSecret:!!(y||m)});if(!V.ok)throw new Error(V.message);return V.method},T=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=ut(p,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":M}),R=zt({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:ut(p,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":M}),body:JSON.stringify(zt({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}))}),R={status:g.status,statusText:g.statusText,headers:g.headers,body:g.body},E=[...y.httpHistory||[]];if(E.length>0){const F=E[E.length-1];F.response=R,F.duration=Date.now()-(F.timestamp||Date.now())}const P=ls({status:g.status,statusText:g.statusText,wwwAuthenticateHeader:g.headers["www-authenticate"],serverMessage:g.body?.error?.message});if(P.kind==="challenged"){const F=g.headers["www-authenticate"],B=cr(F),D=Iu(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=aa(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 Lr(P.message,g.status)}catch(g){throw g instanceof Lr?g:new Error(`Failed to request MCP server: ${g instanceof Error?g.message:String(g)}`)}break;case"received_401_unauthorized":{const g=cr(y.wwwAuthenticateHeader);let R=f||g.resource_metadata;if(!R&&y.serverUrl&&(R=Ou(y.serverUrl)),!R)throw new Error("Could not determine resource metadata URL");const E={method:"GET",url:R,headers:ut(p,{})};n({currentStep:"request_resource_metadata",resourceMetadataUrl:R,lastRequest:E,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_resource_metadata",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),V(50);return}case"request_resource_metadata":if(!y.serverUrl)throw new Error("No server URL available");const K=[...y.httpHistory||[]];let le=K.length>0&&K[K.length-1]?.step==="request_resource_metadata"&&!K[K.length-1]?.response?K.pop():void 0;const de=[],$e=async(g,R={})=>{const E=typeof g=="string"?g:g.toString(),P=Cu(i,E,p,Ir(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||cr(y.wwwAuthenticateHeader).resource_metadata)&&y.resourceMetadataUrl?{resourceMetadataUrl:y.resourceMetadataUrl}:void 0,R=await ea(y.serverUrl,g,$e),E=[...K,...de],P=de[de.length-1],F=$u({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=xu({state:y,fallbackServerUrl:i,prmResource:R.resource,enforcement:w,infoLogs:D}),J=G.resourceIndicator;D=G.infoLogs,n({currentStep:"received_resource_metadata",resourceMetadata:R,resourceIndicator:J,resourceMetadataUrl:P?.request?.url||y.resourceMetadataUrl,authorizationServerUrl:B,lastRequest:P?.request,lastResponse:P?.response,httpHistory:E,infoLogs:D,isInitiatingAuth:!1})}catch(g){const R=pn([...K,...de],Tt(g));throw n({lastResponse:de[de.length-1]?.response,httpHistory:R}),new Error(Qo(g))}break;case"received_resource_metadata":if(!y.authorizationServerUrl)throw new Error("No authorization server URL available");const Re={method:"GET",url:yp(y.authorizationServerUrl)[0],headers:at(p,{})};n({currentStep:"request_authorization_server_metadata",lastRequest:Re,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:Re}],isInitiatingAuth:!1}),V(50);return;case"request_authorization_server_metadata":if(!y.authorizationServerUrl)throw new Error("No authorization server URL available");const _e=yp(y.authorizationServerUrl);let ve=null,qe=null,Xe={},Pe=null;for(const g of _e)try{const R=at(p,{}),E=[...y.httpHistory||[]];E.length>0&&(E[E.length-1].request={method:"GET",url:g,headers:R}),n({lastRequest:{method:"GET",url:g,headers:R},httpHistory:E});const P=await H(g,{method:"GET",headers:at(p,{})});if(P.ok){ve=P.body,Xe=P.headers,Pe=P;break}else{if(P.status>=400&&P.status<500)continue;qe=new Error(`HTTP ${P.status} from ${g}`)}}catch(R){qe=R;continue}if(!ve||!Pe)throw new Error(`Could not discover authorization server metadata. Last error: ${qe instanceof Error?qe.message:String(qe)}`);if(!ve.issuer)throw new Error(la);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 N={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=N,g.duration=Date.now()-(g.timestamp||Date.now())}const ae=ve.code_challenge_methods_supported||[],he=w_(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:N,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:N,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:N,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=Ur(C,{customScopes:d,challengedScopes:y.challengedScopes,supportedScopes:g}),E=ha({registrationEndpoint:y.authorizationServerMetadata.registration_endpoint,redirectUri:$,dynamicRegistrationDefaults:X,scope:R,customHeaders:p});n({currentStep:"request_client_registration",lastRequest:E,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),V(50);return}else{if(_){n({error:da,isInitiatingAuth:!1});return}const g=await T("Authorization server did not advertise registration_endpoint; using pre-registered client credentials.");if(!g){n({error:ua,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 pa({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 T(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:ra(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:Ir(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=Nr(43),pe=await ca(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:Nr(16),infoLogs:me,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!y.authorizationServerMetadata?.authorization_endpoint||!y.clientId)throw new Error("Missing authorization endpoint or client ID");const Ee=new URL(y.authorizationServerMetadata.authorization_endpoint);Ee.searchParams.set("response_type","code"),Ee.searchParams.set("client_id",y.clientId),Ee.searchParams.set("redirect_uri",$),Ee.searchParams.set("code_challenge",y.codeChallenge||""),Ee.searchParams.set("code_challenge_method","S256"),Ee.searchParams.set("state",y.state||""),q&&Ee.searchParams.set("resource",ie());const We=Ur(C,{customScopes:d,challengedScopes:y.challengedScopes,supportedScopes:y.resourceMetadata?.scopes_supported||y.authorizationServerMetadata.scopes_supported});We&&Ee.searchParams.set("scope",We);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=Dr({clientId:y.clientId,clientSecret:y.clientSecret,tokenEndpointAuthMethod:Fr(C,y.tokenEndpointAuthMethod)}),R={grant_type:"authorization_code",code:y.authorizationCode,redirect_uri:$,...g.bodyParams};y.codeVerifier&&(R.code_verifier=y.codeVerifier),q&&(R.resource=ie());const E={method:"POST",url:y.authorizationServerMetadata.token_endpoint,headers:{"Content-Type":"application/x-www-form-urlencoded",...g.headers},body:R};n({currentStep:"token_request",lastRequest:E,lastResponse:void 0,...q?{}:{resourceIndicatorSuppressed:!0},accessToken:void 0,refreshToken:void 0,httpHistory:[...y.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),V(50);return}case"token_request":if(!y.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!y.authorizationCode)throw new Error("Missing authorization code");if(!y.codeVerifier)throw new Error("PKCE code_verifier is missing - cannot exchange token");try{const g=Dr({clientId:y.clientId,clientSecret:y.clientSecret,tokenEndpointAuthMethod:Fr(C,y.tokenEndpointAuthMethod)}),R=new URLSearchParams({grant_type:"authorization_code",code:y.authorizationCode,redirect_uri:$,code_verifier:y.codeVerifier||"",...g.bodyParams});q&&R.set("resource",ie());const E=await H(y.authorizationServerMetadata.token_endpoint,{method:"POST",headers:{...at(p,{"Content-Type":"application/x-www-form-urlencoded"}),...g.headers},body:R.toString()}),P={status:E.status,statusText:E.statusText,headers:E.headers,body:E.body},F=[...y.httpHistory||[]];if(F.length>0){const G=F[F.length-1];G.response=P,G.duration=Date.now()-(G.timestamp||Date.now())}if(!E.ok){n({lastResponse:P,httpHistory:F,authorizationCode:void 0,error:ia(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=zr(B.access_token);if(G){const J={...G};J.exp&&(J.exp=`${J.exp} (${De(J.exp)})`),J.iat&&(J.iat=`${J.iat} (${De(J.iat)})`),J.nbf&&(J.nbf=`${J.nbf} (${De(J.nbf)})`);const Ut={...J};if(J.aud){const Hr=y.serverUrl,li=(Array.isArray(J.aud)?J.aud:[J.aud]).some(ba=>ba===Hr);Ut._validation={expected_audience:Hr,audience_matches:li,note:li?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else Ut._validation={note:"⚠ No audience claim found - server should validate token binding"};D=[...D,{id:"token",level:"info",step:"token_request",label:"Access Token (Decoded JWT)",data:Ut,timestamp:Date.now()}]}}if(B.id_token){const G=zr(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:zt({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:ut(p,{Authorization:`Bearer ${y.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":M}),body:JSON.stringify(zt({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:na(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),$e=ne(le,le.currentStep,`error-${le.currentStep}-${Date.now()}`,"Step failed",{step:le.currentStep,request:le.lastRequest,response:le.lastResponse,error:de},{level:"error",error:de}),Re=pn(le.httpHistory,de),_e={error:de.message,infoLogs:$e,isInitiatingAuth:!1};Re&&(_e.httpHistory=Re),n(_e)}},startGuidedFlow:async()=>{n({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{n(sa())}};return Q},AP=e=>ci(e);function TP(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=D$(t,r);n.push({label:"challenged scopes",value:r.join(" ")}),n.push({label:"scope union",value:i.join(" ")})}return n}function IP(e){const t=e.recordedIssuer??e.authorizationServerMetadata?.issuer;return t?[{label:"bound to issuer",value:t}]:[]}function CP(e,t){return oa(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:AP,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:IP,authorizationRequestExtras:TP})}function bp(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 wp(e){const t=e.replace(/[\u0000-\u001f\u007f\u0085\u2028\u2029]+/g," ").trim();return`\`${t.length>256?`${t.slice(0,256)}…`:t}\``}function $P(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 PP(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}function Sp(e,t){return e==null?!1:typeof e!="string"?!0:!PP(e,t)}function Ep(e){return typeof e=="string"?`"${e}"`:"a non-string value"}function OP(e){const{advertisedIssuer:t,discoveryUrl:r,tokenEndpoint:n,registrationEndpoint:i,allowPathScopedIssuer:s}=e,o=$P(t,r),a=s&&o,c=a&&Sp(n,t),l=a&&Sp(i,t);return a&&!c&&!l?{accepted:!0,hint:""}:{accepted:!1,hint:c?` The path-scoped authorization server's token endpoint (${Ep(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 (${Ep(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 xP(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: ${wp(t)}; returned on the callback: ${wp(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 MP=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:I="reject",registrationStrategy:C="cimd",emulation:$}=e,M=o,L=fn($,"2026-07-28"),q=fa($),X=va(u??{},$);let ee=h??"";if(C==="dcr"&&!X.client_name)throw new Error("Dynamic registration metadata must include client_name");if(C==="cimd"&&!ee)throw new Error("Client ID metadata URL is required for CIMD registration");C==="cimd"&&(ee=E_(ee));const k=()=>r?r():t,ie=()=>ci(k(),i),H=(y,V={})=>a({url:y,method:V.method||"GET",headers:Ir(V.headers),body:V.body}),oe=y=>{const V=ta({authorizationServerMetadata:k().authorizationServerMetadata,hasClientSecret:!!(y||m)});if(!V.ok)throw new Error(V.message);return V.method},T=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=ut(p,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":L,"Mcp-Method":"tools/list"}),R=xs({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:ut(p,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":L,"Mcp-Method":"tools/list"}),body:JSON.stringify(xs({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}))}),R={status:g.status,statusText:g.statusText,headers:g.headers,body:g.body},E=[...y.httpHistory||[]];if(E.length>0){const F=E[E.length-1];F.response=R,F.duration=Date.now()-(F.timestamp||Date.now())}const P=ls({status:g.status,statusText:g.statusText,wwwAuthenticateHeader:g.headers["www-authenticate"],serverMessage:g.body?.error?.message});if(P.kind==="challenged"){const F=g.headers["www-authenticate"],B=cr(F),D=Iu(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=aa(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 Lr(P.message,g.status)}catch(g){throw g instanceof Lr?g:new Error(`Failed to request MCP server: ${g instanceof Error?g.message:String(g)}`)}break;case"received_401_unauthorized":{const g=cr(y.wwwAuthenticateHeader);let R=f||g.resource_metadata;if(!R&&y.serverUrl&&(R=Ou(y.serverUrl)),!R)throw new Error("Could not determine resource metadata URL");const E={method:"GET",url:R,headers:ut(p,{})};n({currentStep:"request_resource_metadata",resourceMetadataUrl:R,lastRequest:E,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_resource_metadata",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),V(50);return}case"request_resource_metadata":if(!y.serverUrl)throw new Error("No server URL available");const K=[...y.httpHistory||[]];let le=K.length>0&&K[K.length-1]?.step==="request_resource_metadata"&&!K[K.length-1]?.response?K.pop():void 0;const de=[],$e=async(g,R={})=>{const E=typeof g=="string"?g:g.toString(),P=Cu(i,E,p,Ir(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||cr(y.wwwAuthenticateHeader).resource_metadata)&&y.resourceMetadataUrl?{resourceMetadataUrl:y.resourceMetadataUrl}:void 0,R=await ea(y.serverUrl,g,$e),E=[...K,...de],P=de[de.length-1],F=$u({authorizationServers:R.authorization_servers,fallbackServerUrl:i,protocolVersion:"2026-07-28"}),B=F.authorizationServerUrl;if(F.error&&I!=="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=xu({state:y,fallbackServerUrl:i,prmResource:R.resource,enforcement:S,infoLogs:D}),J=G.resourceIndicator;D=G.infoLogs,n({currentStep:"received_resource_metadata",resourceMetadata:R,resourceIndicator:J,resourceMetadataUrl:P?.request?.url||y.resourceMetadataUrl,authorizationServerUrl:B,lastRequest:P?.request,lastResponse:P?.response,httpHistory:E,infoLogs:D,isInitiatingAuth:!1})}catch(g){const R=pn([...K,...de],Tt(g));throw n({lastResponse:de[de.length-1]?.response,httpHistory:R}),new Error(Qo(g))}break;case"received_resource_metadata":if(!y.authorizationServerUrl)throw new Error("No authorization server URL available");const Re={method:"GET",url:bp(y.authorizationServerUrl)[0],headers:at(p,{})};n({currentStep:"request_authorization_server_metadata",lastRequest:Re,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:Re}],isInitiatingAuth:!1}),V(50);return;case"request_authorization_server_metadata":if(!y.authorizationServerUrl)throw new Error("No authorization server URL available");const _e=bp(y.authorizationServerUrl);let ve=null,qe=null,Xe={},Pe=null;for(const g of _e)try{const R=at(p,{}),E=[...y.httpHistory||[]];E.length>0&&(E[E.length-1].request={method:"GET",url:g,headers:R}),n({lastRequest:{method:"GET",url:g,headers:R},httpHistory:E});const P=await H(g,{method:"GET",headers:at(p,{})});if(P.ok){ve=P.body,Xe=P.headers,Pe=P;break}else{if(P.status>=400&&P.status<500)continue;qe=new Error(`HTTP ${P.status} from ${g}`)}}catch(R){qe=R;continue}if(!ve||!Pe)throw new Error(`Could not discover authorization server metadata. Last error: ${qe instanceof Error?qe.message:String(qe)}`);if(!ve.issuer)throw new Error(la);if(ve.issuer!==y.authorizationServerUrl){const g=OP({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 N={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=N,g.duration=Date.now()-(g.timestamp||Date.now())}const ae=ve.code_challenge_methods_supported||[],he=w_(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(_||I!=="observe"){n({lastResponse:N,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:N,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:N,httpHistory:se,infoLogs:we,isInitiatingAuth:!1});break;case"received_authorization_server_metadata":if(!y.authorizationServerMetadata)throw new Error("No authorization server metadata available");if(C==="cimd"){if(y.authorizationServerMetadata.client_id_metadata_document_supported!==!0){n({error:"The authorization server does not support Client ID Metadata Documents (client_id_metadata_document_supported is not advertised in AS metadata). Try using 'dcr' or 'preregistered' registration strategy instead.",isInitiatingAuth:!1});return}n({currentStep:"cimd_prepare",clientId:ee,isInitiatingAuth:!1}),V(800);return}else if(C==="preregistered"){const{clientId:g,clientSecret:R}=await l?.({serverName:s,serverUrl:i})??{};if(!g){n({error:"Pre-registered client ID is required. Please configure OAuth credentials in the server settings.",isInitiatingAuth:!1});return}const E=oe(R),P={"Client ID":g,"Client Secret":R||m?"Configured":"Not provided (public client)","Token Auth Method":E,Note:"Using pre-registered client credentials from server config (skipped DCR)"},F=ne(k(),"received_client_credentials","dcr","Pre-registered Client",P);n({currentStep:"received_client_credentials",clientId:g,clientSecret:R||void 0,tokenEndpointAuthMethod:E,infoLogs:F,isInitiatingAuth:!1})}else if(y.authorizationServerMetadata.registration_endpoint){const g=y.resourceMetadata?.scopes_supported||y.authorizationServerMetadata.scopes_supported,R=Ur($,{customScopes:d,challengedScopes:y.challengedScopes,supportedScopes:g}),E=ha({registrationEndpoint:y.authorizationServerMetadata.registration_endpoint,redirectUri:M,dynamicRegistrationDefaults:{...X,application_type:X.application_type??fP(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:da,isInitiatingAuth:!1});return}const g=await T("Authorization server did not advertise registration_endpoint; using pre-registered client credentials.");if(!g){n({error:ua,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 pa({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 T(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:ra(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:Ir(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=Nr(43),pe=await ca(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:Nr(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 We=Ur($,{customScopes:d,challengedScopes:y.challengedScopes,supportedScopes:y.resourceMetadata?.scopes_supported||y.authorizationServerMetadata.scopes_supported});We&&Ee.searchParams.set("scope",We);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:We?We.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=xP({recordedIssuer:y.recordedIssuer,returnedIss:y.authorizationResponseIss,issParameterSupported:void 0,enforcePresentIssMismatch:!0});if(!g.ok){n({error:g.reason,isInitiatingAuth:!1});return}const R=Dr({clientId:y.clientId,clientSecret:y.clientSecret,tokenEndpointAuthMethod:Fr($,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=Dr({clientId:y.clientId,clientSecret:y.clientSecret,tokenEndpointAuthMethod:Fr($,y.tokenEndpointAuthMethod)}),R=new URLSearchParams({grant_type:"authorization_code",code:y.authorizationCode,redirect_uri:M,code_verifier:y.codeVerifier||"",...g.bodyParams});q&&R.set("resource",ie());const E=await H(y.authorizationServerMetadata.token_endpoint,{method:"POST",headers:{...at(p,{"Content-Type":"application/x-www-form-urlencoded"}),...g.headers},body:R.toString()}),P={status:E.status,statusText:E.statusText,headers:E.headers,body:E.body},F=[...y.httpHistory||[]];if(F.length>0){const G=F[F.length-1];G.response=P,G.duration=Date.now()-(G.timestamp||Date.now())}if(!E.ok){n({lastResponse:P,httpHistory:F,authorizationCode:void 0,error:ia(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=zr(B.access_token);if(G){const J={...G};J.exp&&(J.exp=`${J.exp} (${De(J.exp)})`),J.iat&&(J.iat=`${J.iat} (${De(J.iat)})`),J.nbf&&(J.nbf=`${J.nbf} (${De(J.nbf)})`);const Ut={...J};if(J.aud){const Hr=y.serverUrl,li=(Array.isArray(J.aud)?J.aud:[J.aud]).some(ba=>ba===Hr);Ut._validation={expected_audience:Hr,audience_matches:li,note:li?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else Ut._validation={note:"⚠ No audience claim found - server should validate token binding"};D=[...D,{id:"token",level:"info",step:"token_request",label:"Access Token (Decoded JWT)",data:Ut,timestamp:Date.now()}]}}if(B.id_token){const G=zr(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:xs({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:ut(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(xs({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:na(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),$e=ne(le,le.currentStep,`error-${le.currentStep}-${Date.now()}`,"Step failed",{step:le.currentStep,request:le.lastRequest,response:le.lastResponse,error:de},{level:"error",error:de}),Re=pn(le.httpHistory,de),_e={error:de.message,infoLogs:$e,isInitiatingAuth:!1};Re&&(_e.httpHistory=Re),n(_e)}},startGuidedFlow:async()=>{n({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{n(sa())}};return Q};function EL({protocolVersion:e,registrationStrategy:t,flowState:r}){switch(e){case"2025-03-26":return mP(r,t==="cimd"?"dcr":t);case"2025-06-18":return wP(r,t==="cimd"?"dcr":t);case"2025-11-25":return kP(r,t);case"2026-07-28":return CP(r,t);default:throw new Error(`Unknown protocol version: ${e}`)}}function ma(e){return e.replace(/^\[|\]$/g,"").trim().toLowerCase().replace(/\.+$/,"")}function k_(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 R_(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 kp(e,t){return k_(`${e>>8}.${e&255}.${t>>8}.${t&255}`)}function LP(e){const t=R_(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:kp(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)?kp(t[6],t[7]):!1}function DP(e){const t=ma(e);return/^\d+\.\d+\.\d+\.\d+$/.test(t)?k_(t):t.includes(":")?LP(t):!1}function zP(e){const t=ma(e);return t==="localhost"||t.endsWith(".localhost")?!0:DP(t)}function NP(e){const t=ma(e);return/^\d+\.\d+\.\d+\.\d+$/.test(t)?A_(t):t.includes(":")?UP(t):!1}function A_(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 Rp(e,t){return A_(`${e>>8}.${e&255}.${t>>8}.${t&255}`)}function UP(e){const t=R_(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)?Rp(t[6],t[7]):!1:!0}var FP=new Set(["metadata.google.internal","metadata.goog"]);function qP(e){const t=ma(e);return FP.has(t)?!0:NP(t)}function T_(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 kL(e){if(!e)return!1;try{const t=new URL(e).hostname;return ga(t)||T_(t)}catch{return!1}}var wi=class extends Error{url;reason;constructor(e,t,r){super(r),this.name="OAuthOutboundUrlBlockedError",this.url=e,this.reason=t}};function jP(e,t={}){let r;try{r=new URL(e)}catch{throw new wi(e,"invalid-url","Outbound OAuth fetch URL is not a valid absolute URL")}if(r.protocol!=="https:"&&r.protocol!=="http:")throw new wi(e,"invalid-scheme",`Outbound OAuth fetch must be http(s); got "${r.protocol}"`);const n=r.hostname;if(qP(n))throw new wi(e,"private-host",`Refusing outbound OAuth fetch to link-local or cloud-metadata host "${n}"`);if(t.allowPrivateNetwork===!0)return r;if(ga(n)||T_(n)){if(t.allowLoopback===!0)return r;throw new wi(e,"private-host",`Refusing outbound OAuth fetch to loopback host "${n}" (no loopback opt-in)`)}if(zP(n))throw new wi(e,"private-host",`Refusing outbound OAuth fetch to private/reserved host "${n}"`);return r}var HP=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}},VP=["access_token","refresh_token","id_token","client_secret"],BP=[/^\[redacted\]$/,/^[\s\S]{4}\.\.\.\[redacted\]\.\.\.[\s\S]{2}$/];function GP(e){try{const t=new URL(e.url);return`${t.origin}${t.pathname}`}catch{return"the authorization server"}}function WP(e,t){const r=e?.body;if(!r||typeof r!="object"||Array.isArray(r))return e;const n=r;for(const i of VP){const s=n[i];if(typeof s=="string"&&BP.some(o=>o.test(s)))throw new HP(i,GP(t))}return e}function ZP(e){const{protocolVersion:t,allowLoopbackMetadataFetch:r,allowPrivateMetadataFetch:n,...i}=e,s=r??!1,o=n??!1,c={...i,requestExecutor:async l=>(jP(l.url,{allowLoopback:s,allowPrivateNetwork:o}),WP(await i.requestExecutor(l),l)),customHeaders:gP(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 yP(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 SP(c);case"2025-11-25":return RP(c);case"2026-07-28":return MP(c);default:throw new Error(`Unknown protocol version: ${t}`)}}function RL(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 AL(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 TL={"2025-03-26":{label:Os("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:Os("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:Os("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:Os("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"]}},JP=["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"],KP={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 Ap(e){return KP[e]??{title:e,summary:"No additional information available for this step."}}function gr(e){const t=JP.indexOf(e);return t===-1?Number.MAX_SAFE_INTEGER:t}function YP(e){return JSON.parse(JSON.stringify(e))}function XP(e){return{...e,request:{...e.request,url:ku(e.request.url),headers:ap(e.request.headers),body:Wt(e.request.body)},...e.response?{response:{...e.response,headers:ap(e.response.headers),body:Wt(e.response.body)}}:{},...e.error?{error:{...e.error,...e.error.message?{message:Tr(e.error.message)}:{},details:Wt(e.error.details)}}:{}}}function QP(...e){const t=e.filter(r=>r!=null);if(t.length!==0)return Math.max(...t)}function eO(){return{syntheticStepTimestamps:{},lastSyntheticTimestamp:0}}function tO(e,t,r){if(!e)return r;const n=e.syntheticStepTimestamps[t];return typeof n=="number"?n:r}function Tp(e,t,r,n){const i=tO(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 Zr(e,t,r,n,i,s){if(!n||e.has(r))return;let o=Date.now();t&&(o=Math.max(o,t.lastSyntheticTimestamp+1),t.syntheticStepTimestamps[r]=o,t.lastSyntheticTimestamp=o);const a=i==null?void 0:s?Wt(i):JSON.parse(JSON.stringify(i));e.set(r,{step:r,startedAt:o,completedAt:o,details:a})}function rO(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 y_(e.body)??`HTTP ${e.status} ${e.statusText}`}function iO(e){if(e.error?.message)return e.error.message;if(e.step==="request_client_registration")return nO(e.response)}function Ip(e){return!e.error||!e.clientId||gr(e.currentStep)<=gr("request_client_registration")?!1:e.error.startsWith("Dynamic Client Registration failed")||e.error.startsWith("Client registration failed:")}function sO(e){const{state:t,context:r,sanitize:n=!0}=e,i=t.error?n?Tr(t.error):t.error:void 0,s={version:1,currentStep:t.currentStep,steps:[],httpHistory:(t.httpHistory??[]).map(u=>n?XP(u):YP(u)),...i?{error:i}:{}},o=gr(t.currentStep),a=new Map;for(const u of t.httpHistory??[]){const h=Tp(a,r,u.step,u.timestamp);h.details||(h.details={request:n?Wt(u.request):u.request,...u.response?{response:n?Wt(u.response):u.response}:{}});const d=iO(u);d&&(h.error=El(n?Tr(d):d.slice(0,500)))}for(const u of t.infoLogs??[]){const h=Tp(a,r,u.step,u.timestamp);h.message=u.label;const d=n?Wt(u.data):u.data;d&&typeof d=="object"&&d!==null&&!Array.isArray(d)&&(h.details=d),u.error?.message&&(h.error=n?Tr(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)),Zr(a,r,"received_client_credentials",!!t.clientId,{clientId:t.clientId},n),Zr(a,r,"generate_pkce_parameters",!!t.codeVerifier,{codeVerifier:t.codeVerifier},n),Zr(a,r,"authorization_request",!!t.authorizationUrl,{authorizationUrl:t.authorizationUrl},n),Zr(a,r,"received_authorization_code",!!t.authorizationCode,t.authorizationCode?{code:t.authorizationCode}:void 0,n),Zr(a,r,"received_access_token",!!t.accessToken,{tokenType:t.tokenType,expiresIn:t.expiresIn},n),Zr(a,r,"complete",t.currentStep==="complete",void 0,n);const l=a.get("request_client_registration");if(l?.error&&gr(t.currentStep)>gr("request_client_registration")&&t.clientId&&(l.recovered=!0,l.recoveredAt=QP(l.recoveredAt,l.completedAt,a.get("received_client_credentials")?.startedAt),l.recoveryMessage="Using pre-registered client credentials after registration failed."),t.error&&!Ip(t)&&!a.has(t.currentStep)){Zr(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||gr(u.step)-gr(h.step)).map(u=>{const h=gr(u.step),d=u.step===t.currentStep&&!!t.error&&!Ip(t),p=u.error??(d?i:void 0),f=u.recovered?"success":p?"error":h<o||t.currentStep==="complete"||rO(u.step,t)?"success":u.step===t.currentStep?"pending":"success";return{step:u.step,title:Ap(u.step).title,status:f,message:u.message??Ap(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 Ms(e){return{message:e instanceof Error?e.message:String(e)}}async function IL(e){const{maxSteps:t=40,onAuthorizationRequest:r,onTraceUpdate:n,getState:i,sanitizeTrace:s=!0,...o}=e;let a=e.state;const c=eO(),l=i??(()=>a),u=(v,m=l(),_=c)=>{n?.({trace:sO({state:m,context:_,sanitize:s}),state:m,reason:v})},h=v=>{a={...a,...v},e.updateState(v),u("state_update",a)},d=ZP({...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:Ms(w).message}),{completed:!1,redirected:!1,authorizationUrl:v.authorizationUrl,state:l(),error:Ms(w)}}}const m=v.currentStep;try{await d.proceedToNextStep()}catch(w){return l().error?u("error"):h({error:Ms(w).message}),{completed:!1,redirected:!1,state:l(),error:Ms(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 CL=["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"],oO={"2025-03-26":"legacy","2025-06-18":"legacy","2025-11-25":"legacy","2026-07-28":"modern"},$L=Object.keys(oO),PL={"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 aO(){return"8.16.1"}var OL=aO();function I_(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 cO=95,C_=5,lO={should:2,may:1};function uO(e){const t=e.reduce((r,n)=>r+lO[n.tier],0);return Math.min(t,C_)}function Mu(e,t,r,n){const i=e.passed+e.failed+e.couldNotRun,s=uO(t);let o=null;if(i>0){const a=cO*e.passed/i,c=C_-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 Lu(e,t=[],r,n){const{scored:i,pending:s}=I_(e,n),o={passed:i.filter(c=>c.status==="passed").length,failed:i.filter(c=>c.status==="failed").length,couldNotRun:i.filter(Eg).length,notApplicable:i.filter(lE).length,pending:s.length},{outcome:a}=uE(i);return Mu(o,t,a,r)}function Du(e){const t={passed:Si(e,a=>a.passed),failed:Si(e,a=>a.failed),couldNotRun:Si(e,a=>a.couldNotRun),notApplicable:Si(e,a=>a.notApplicable),pending:Si(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 Mu(t,r,i,s.length>0&&o.size===1?[...o][0]:void 0)}function Si(e,t){return e.reduce((r,n)=>r+t(n),0)}function xL(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 Cp(e){return Lu(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 $_(e,t,r){const{scored:n}=I_(e,r);return Lu(e,n.flatMap(i=>(i.warnings??[]).map((s,o)=>({id:`${i.id}-warning-${o+1}`,tier:"may"}))),t,r)}function $p(e){return $_(e.checks,e.protocolVersion)}function dO(e){return $_(e.checks,e.discovery.protocolVersion,e.profile)}function Pp(e){return e.outcome==="not-applicable"?Mu({passed:0,failed:0,couldNotRun:0,notApplicable:e.steps.length},[],"passed",e.protocolVersion):Lu(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 hO=8;function pO(e){return rr(e,0,new WeakSet)}function rr(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>=hO)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=>rr(s,t+1,r)??null);if(n instanceof Map)return[...n.entries()].map(([s,o])=>[rr(s,t+1,r)??null,rr(o,t+1,r)??null]);if(n instanceof Set)return[...n].map(s=>rr(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=rr(s.code,t+1,r)),s.statusCode!==void 0&&(i.statusCode=rr(s.statusCode,t+1,r)),s.cause!==void 0&&(i.cause=rr(s.cause,t+1,r))}for(const[s,o]of Object.entries(n)){const a=rr(o,t+1,r);a!==void 0&&(i[s]=a)}return i}finally{r.delete(n)}}function P_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Hn(e){const t=Object.entries(e).filter(([,r])=>r===void 0?!1:Array.isArray(r)?r.length>0:P_(r)?Object.keys(r).length>0:!0);if(t.length!==0)return pO(Object.fromEntries(t))}function fO(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 vO(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:Hn({details:e.details,errorDetails:e.error?.details})}:{}}}function gO(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:Hn({details:e.details,errorDetails:e.error?.details,warnings:e.warnings})}:{}}}function mO(e){const t=fO(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:Hn({errorDetails:e.error?.details,warnings:e.warnings,teachableMoments:e.teachableMoments})}:{},...t?{output:t}:{}}}function ni(e){const t=e.outcome;return t!=="passed"&&t!=="failed"&&t!=="incomplete"?{}:{outcome:t,...e.incompleteReason?{incompleteReason:e.incompleteReason}:{}}}function zu(e){const t=e.map(r=>ni(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=>ni(n).outcome==="incomplete");return{outcome:"incomplete",...r?.incompleteReason?{incompleteReason:r.incompleteReason}:{}}}return{outcome:"passed"}}function Op(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=>vO(i,n))})()}}function Al(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=>gO(s,i))}}function xp(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(mO)}}function _O(e){return"checks"in e&&!("results"in e)&&"serverUrl"in e&&!("target"in e)}function yO(e){return"checks"in e&&!("results"in e)&&"target"in e}function bO(e){return"checks"in e&&!("results"in e)&&"discovery"in e&&P_(e.discovery)&&"wire"in e.discovery}function wO(e){return"steps"in e&&!("results"in e)}function SO(e){return"results"in e&&"serverUrl"in e&&!("target"in e)&&e.results.length>0&&"checks"in e.results[0]}function EO(e){return"results"in e&&"target"in e}function kO(e){return"results"in e&&"serverUrl"in e&&!("target"in e)&&e.results.length>0&&"steps"in e.results[0]}function RO(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 AO(e){return"results"in e?{schemaVersion:1,kind:"protocol-conformance",name:e.name,passed:e.passed,...zu(e.results),score:Du(e.results.map(Cp)),...RO(e.results),durationMs:e.durationMs,groups:e.results.map((t,r)=>Op(t,t.label,r))}:{schemaVersion:1,kind:"protocol-conformance",name:"MCP Protocol Conformance",passed:e.passed,...ni(e),score:Cp(e),...e.profile?{profile:e.profile}:{},durationMs:e.durationMs,groups:[Op(e,"MCP Protocol Conformance",0)]}}function TO(e){return"results"in e?{schemaVersion:1,kind:"apps-conformance",name:e.name,passed:e.passed,...zu(e.results),score:Du(e.results.map($p)),durationMs:e.durationMs,groups:e.results.map((t,r)=>Al(t,t.label,r))}:{schemaVersion:1,kind:"apps-conformance",name:"MCP Apps Conformance",passed:e.passed,...ni(e),score:$p(e),durationMs:e.durationMs,groups:[Al(e,"MCP Apps Conformance",0)]}}function IO(e){return"results"in e?{schemaVersion:1,kind:"oauth-conformance",name:e.name,passed:e.passed,...zu(e.results),score:Du(e.results.map(Pp)),durationMs:e.durationMs,groups:e.results.map((t,r)=>xp(t,t.label,r))}:{schemaVersion:1,kind:"oauth-conformance",name:"OAuth Conformance",passed:e.passed,...ni(e),score:Pp(e),durationMs:e.durationMs,groups:[xp(e,`${e.protocolVersion}/${e.registrationStrategy}`,0)]}}function CO(e){return"lanes"in e&&"findings"in e&&"badges"in e&&!("readinessKind"in e)}var $O={kind:"claude-directory-readiness",providerName:"Claude Directory Readiness",isResult:CO,isDispositive:e=>mE(e)};function PO(e){return e.status==="violated"?"failed":e.status==="satisfied"?"passed":"skipped"}function OO(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:Hn({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:PO(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:Hn({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:Hn({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 xO={kind:"openai-directory-readiness",providerName:"OpenAI Plugin Directory Readiness",isResult:e=>EE(e),isDispositive:e=>kg(e)},MO=[xO,$O];function LO(e){return MO.find(t=>t.isResult(e))}function ML(e){const t=LO(e);if(t)return OO(e,t);if(_O(e)||SO(e))return AO(e);if(bO(e))return{schemaVersion:1,kind:"tasks-conformance",name:"MCP Tasks Conformance",passed:e.passed,...ni(e),score:dO(e),...e.profile?{profile:e.profile}:{},durationMs:e.durationMs,groups:[Al(e,"MCP Tasks Conformance",0,"tasks")]};if(yO(e)||EO(e))return TO(e);if(wO(e)||kO(e))return IO(e);throw new Error("Unsupported conformance result shape")}var LL=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}),DO="=?base64?";function zO(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 NO(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 Zs(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:NO(t)}}catch(r){return{raw:e,encoded:!0,value:e,decodeError:r instanceof Error?r.message:String(r)}}}var UO=new Set(["tools/call","resources/read","prompts/get"]),O_=new Set(["tasks/get","tasks/update","tasks/cancel"]);function FO(e){return e===void 0?!1:UO.has(e)||O_.has(e)}var Mp=["protocol-version","method","name","param","session","resumption"];function qO(e){return e!==void 0&&O_.has(e)?".params.taskId":e==="resources/read"?".params.uri":".params.name"}function jO(e){const t=e.declarations??[],r=QO(t,e.arguments);return t.map(n=>{const i=`${x_}${n.headerName}`,s=r[i];return{header:i.toLowerCase(),displayName:i,expected:s===void 0?void 0:Zs(s).value,bodyField:`.params.arguments${n.path.map(o=>`.${o}`).join("")}`}})}function DL(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&&lC(i)&&uC(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:qO(t.method),required:FO(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=Zs(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?jO(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=Zs(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=zO(p.name);if(!f)continue;const v=Zs(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)=>Mp.indexOf(d.family)-Mp.indexOf(p.family)||d.name.localeCompare(p.name))}var Lp="x-mcp-header",x_="Mcp-Param-",HO=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,VO=new Set(["string","integer","boolean","number"]),BO=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],GO=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function WO(e){return e.length===0?"<root>":e.join(".")}function zL(e){const t=[],r=new Map,n=(s,o,a)=>{if(s===null||typeof s!="object")return;const c=s;if(Lp in c){const u=WO(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[Lp];if(typeof h!="string"||h.length===0)return`${u}: x-mcp-header MUST be a non-empty string`;if(!HO.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||!VO.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 BO){const h=c[u];if(h===void 0)continue;const d=h!==null&&typeof h=="object"&&GO.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 ZO(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 JO(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 KO(e){if(!JO(e))return e;const t=ZO(e);return`${DO}${t}?=`}function YO(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 XO(e,t){let r=e;for(const n of t){if(r===null||typeof r!="object")return;r=r[n]}return r}function QO(e,t){const r={};for(const n of e){const i=XO(t,n.path);if(i==null)continue;const s=YO(i);s!==void 0&&(r[`${x_}${n.headerName}`]=KO(s))}return r}var e1="tracestate",t1="baggage",r1=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,n1="0".repeat(32),i1="0".repeat(16);function s1(e){if(typeof e!="string")return;const t=r1.exec(e);if(!t)return;const[,r,n,i,s]=t;if(!(r==="ff"||r!=="00")&&!(n===n1||i===i1))return{version:r,traceId:n,spanId:i,flags:s,sampled:(Number.parseInt(s,16)&1)===1}}function o1(e){return s1(e)!==void 0}var a1=32,c1=/^(?:[a-z][a-z0-9_\-*/]{0,255}|[a-z0-9][a-z0-9_\-*/]{0,240}@[a-z][a-z0-9_\-*/]{0,13})$/,l1=/^[\x20-\x2b\x2d-\x3c\x3e-\x7e]{0,255}[\x21-\x2b\x2d-\x3c\x3e-\x7e]$/;function u1(e){if(typeof e!="string"||e.length===0)return!1;const t=e.split(",");if(t.length>a1)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||!c1.test(i.slice(0,s))||!l1.test(i.slice(s+1)))return!1}return r>0}var d1=180,h1=8192,p1=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Dp=/^[\x21\x23-\x2b\x2d-\x3a\x3c-\x5b\x5d-\x7e]*$/;function f1(e){if(typeof e!="string"||e.length===0||e.length>h1)return!1;const t=e.split(",");if(t.length>d1)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||!p1.test(i.slice(0,o).trim())||!Dp.test(i.slice(o+1).trim()))return!1;for(const a of s)if(!Dp.test(a.replace(/=/g,"").trim()))return!1}return!0}function v1(e){if(!(!e||!o1(e.traceparent)))return{traceparent:e.traceparent,...u1(e.tracestate)?{tracestate:e.tracestate}:{},...f1(e.baggage)?{baggage:e.baggage}:{}}}function NL(e){if(!e||typeof e!="object")return;const t=r=>{const n=e[r];return typeof n=="string"?n:void 0};return v1({traceparent:t("traceparent")??"",tracestate:t(e1),baggage:t(t1)})}var UL=Rt.MissingRequiredClientCapability,g1=/\.[cm]?[jt]sx?$/,m1=/^(?:[a-z][a-z0-9+.-]*:\/\/|\/)/i;function _1(e,t){if(typeof e!="string"||!m1.test(e))return!1;let r;try{r=new URL(e,t)}catch{return!1}return r.origin!==t?!1:!g1.test(r.pathname)}function y1(e,t){return e.length===0?!1:e.every(r=>_1(r,t))}function b1(e,t){return e.length===0?!1:e.every(r=>y1(r,t))}var w1=["timeout","network","upstream_status","bad_json","bad_payload","provisioning"],S1=/^[A-Z][A-Z0-9_]{1,63}$/;function E1(e){return typeof e=="string"&&w1.includes(e)}function k1(e){if(!e||typeof e!="object")return;const{reason:t,upstreamStatus:r,networkCode:n}=e;if(!E1(t))return;const i={reason:t};return typeof r=="number"&&Number.isInteger(r)&&r>=100&&r<=599&&(i.upstreamStatus=r),typeof n=="string"&&S1.test(n)&&(i.networkCode=n),i}var M_="mcpjam_guest_session_v1",Tl="mcpjam_guest_activated",_a=3e5,bt=null,mr=null,_r=null,tn=null,L_=!1,Cr=0,Il=new Set,R1=6e5,Dn=null,Ei=null;function D_(){for(const e of Il)e()}function z_(e){Ei!==null&&(clearTimeout(Ei),Ei=null),Dn=e,e&&(Ei=setTimeout(()=>{Ei=null,Dn===e&&z_(null)},Math.max(0,e.until-Date.now()))),D_()}function A1(){return Dn&&Dn.until<=Date.now()&&(Dn=null),Dn}function ya(e){const t=bt?.guestId??null;bt=e,t!==(bt?.guestId??null)&&D_()}function FL(e){return Il.add(e),()=>{Il.delete(e)}}function qL(e){if(e)try{localStorage.getItem(Tl)!==e&&localStorage.setItem(Tl,e)}catch{}}function jL(e){if(!e)return!1;try{return localStorage.getItem(Tl)===e}catch{return!1}}function T1(){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-_a<=Date.now()||(bt={guestId:e.guestId,token:e.token,expiresAt:e.expiresAt}))}T1();function Nu(){if(L_)return null;try{const e=localStorage.getItem(M_);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(M_)}catch{}L_=!0}var Ii=class extends Error{status;upstreamFailure;constructor(e,t,r){super(e),this.name="GuestSessionRequestError",this.status=t,this.upstreamFailure=r}},N_=class extends Ii{retryAfterMs;constructor(e){super("guest-session creation refused (429)"),this.name="GuestSessionRefusedError",this.retryAfterMs=e}},I1=1e3;async function C1(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),I1)})]);return k1(r?.details)}catch{return}finally{t!==void 0&&clearTimeout(t)}}function $1(e){if(!e)return"";const t=e.networkCode??(e.upstreamStatus!==void 0?String(e.upstreamStatus):void 0);return` (${e.reason}${t?` ${t}`:""})`}function P1(e){const t=e?Number.parseInt(e,10):NaN;return Number.isFinite(t)&&t>0?t*1e3:R1}async function Uu(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 Ii(s instanceof Error?s.message:"network error")}if(n.status===204)return t&&zp(),null;if(n.status===429)throw new N_(P1(n.headers?.get?.("retry-after")));if(!n.ok){const s=await C1(n);throw new Ii(`guest-session request failed: ${n.status} ${n.statusText}${$1(s)}`,n.status,s)}let i;try{i=await n.json()}catch(s){throw new Ii(`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 Ii("guest-session response missing token or expiresAt");return t&&zp(),i}async function O1(){if(bt&&bt.expiresAt-_a>Date.now())return bt;if(A1())return null;if(mr)return mr;const e=Nu(),t=Cr;let r=Promise.resolve(null);return r=(async()=>{try{const n=await Uu("lookup_or_create",e);return n&&t===Cr&&ya(n),n}catch(n){if(n instanceof N_)return z_({until:Date.now()+n.retryAfterMs}),null;throw console.error("Failed to create guest session:",n),n}finally{mr===r&&(mr=null)}})(),mr=r,r.catch(()=>{}),mr}async function x1(){try{return await O1()}catch{return null}}async function HL(){return(await x1())?.token??null}function Cl(){return bt&&bt.expiresAt-_a>Date.now()?bt:null}async function M1(){if(bt&&bt.expiresAt-_a>Date.now())return bt.token;if(_r)return(await _r)?.token??null;const e=Nu(),t=Cr;let r=Promise.resolve(null);return r=(async()=>{try{const n=await Uu("lookup_only",e);return n&&t===Cr&&ya(n),n}finally{_r===r&&(_r=null)}})(),_r=r,(await _r)?.token??null}async function VL(){const e=Cl();if(e?.guestId)return e.guestId;try{await M1()}catch{return null}return Cl()?.guestId??null}function L1(){Cr+=1,ya(null),mr=null,_r=null,tn=null}async function BL(){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{L1()}return e}async function GL(){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 D1(){if(tn)return(await tn)?.token??null;Cr+=1;const e=Cr;bt=null,mr=null,_r=null,tn=(async()=>{try{const t=await Uu("lookup_or_create",Nu());return t&&e===Cr&&ya(t),t}catch(t){throw console.error("Failed to refresh guest session:",t),t}})(),tn.catch(()=>{});try{return(await tn)?.token??null}finally{tn=null}}async function WL(){try{return await D1()}catch{return null}}var U_=new Set(["caniuse.dev","www.caniuse.dev"]),z1=new Set(["score.mcpjam.com","www.score.mcpjam.com"]),N1=new Set([...U_,...z1]),ZL="https://app.mcpjam.com";function U1(e){return U_.has(e.toLowerCase())}function JL(e=typeof window>"u"?void 0:window.location.hostname){return!!e&&U1(e)}var KL=null,YL="write",Np=null,F1=String(101376);function XL(){return Np?`https://discord.com/oauth2/authorize?${new URLSearchParams({client_id:Np,scope:"bot applications.commands",permissions:F1}).toString()}`:null}var q1="phc_dTOPniyUNU2kD8Jx8yHMXSqiZHM8I91uWopTMX6EBE9",j1="https://us.i.posthog.com";function H1(){return typeof window<"u"&&window.location?.origin?.startsWith("http")?`${window.location.origin}/tlm`:j1}function V1(){const e=Cl()?.guestId;return e?{bootstrap:{distinctID:e,isIdentifiedID:!1}}:{}}var B1=["/results/","/conformance/shared/","/evals/shared/"];function F_(e){let t=e;for(const r of B1){const n=r.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&");t=t.replace(new RegExp(`(${n})[^/?#]+`,"g"),"$1[redacted]")}return t=t.replace(/(\/organizations\/)[^/?#]+/g,"$1[redacted]"),t}var G1=new Set(["Load failed","Failed to fetch","NetworkError when attempting to fetch resource."]),W1=/^'TypeError' captured as exception with message: '([\s\S]*)'$/;function Z1(e){const t=W1.exec(e.value),r=t?t[1]:e.type==="TypeError"?e.value:void 0;return r===void 0?!1:G1.has(r)||r.startsWith("Failed to fetch (")&&r.endsWith(")")}var J1=1e4;function K1(e){const t=e.$exception_list;if(!(Array.isArray(t)&&t.some(i=>typeof i?.value=="string"&&Z1(i))))return;const r=j_();if(!r)return;const n=Date.now()-r.at;n>J1||(e.failed_request=`${r.method} ${F_(r.target)}`,e.failed_request_age_ms=n)}function Y1(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]=F_(e[r]));return t==="$exception"&&K1(e),e}function X1(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 b1(r,window.location.origin)?null:e}var Q1=N1;function us(){return ex()}function ex(){return typeof window<"u"&&window.isElectron===!0}var tx="data-ph-no-capture",rx={maskAllInputs:!0,maskInputOptions:{password:!0},maskTextSelector:`[${tx}]`};function Fu(e=typeof window>"u"?void 0:window.location?.pathname){return!!e&&(e.startsWith("/results/")||e.startsWith("/conformance/shared/")||e.startsWith("/evals/shared/"))}function nx(){return us()&&!Fu()}var vc=!1;function QL(e,t){try{if(!us())return;if(Fu(t)){e.sessionRecordingStarted?.()&&(vc=!0),e.stopSessionRecording?.();return}vc&&(vc=!1,e.startSessionRecording?.())}catch{}}function ix(e=typeof window>"u"?void 0:window.location?.hostname){const t=!!e&&Q1.has(e.toLowerCase());return{capture_pageview:t?"history_change":!1,capture_pageleave:t}}var sx={api_host:H1(),ui_host:"https://us.posthog.com",...V1(),...ix(),person_profiles:"always",sanitize_properties:Y1,before_send:X1,capture_dead_clicks:!0,get capture_exceptions(){return us()},get disable_session_recording(){return!nx()},session_recording:rx,loaded:e=>{e.register({environment:"production",platform:$l(),version:"3.12.1",deployment:"self_hosted",source:"client"}),e.setPersonPropertiesForFlags?.({local_browser_security_version:"1",deployment:"self_hosted",platform:$l()})}},eD=()=>q1,tD=()=>sx;function $l(){if(window?.isElectron){const e=navigator.userAgent.toLowerCase();return e.includes("mac")||e.includes("darwin")?"mac":e.includes("win")?"win":"electron"}return"npm"}function ox(){return"production"}function rD(e){const t=ox();return{location:e,platform:$l(),...t!==void 0?{environment:t}:{}}}function ax(e){try{if(typeof e!="object"||e===null)return;const t=e.normalized;return a$(t)?t:void 0}catch{return}}function nD(e,t){try{if(!us()||Ol(e))return!1;const r=ax(e)??O$(e),n=$$(r);return n!=="mcpjam"?!1:(q_(e,{...t,extra:{...t.extra??{},slug:r.slug,origin:n}}),!0)}catch{return!1}}var cx=Vp();function lx(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 q_(e,t){if(Ol(e))return;const r=uy(lx(e)),n=Hp(r.message);if(n&&t.queryBackend&&(n.convex_backend=t.queryBackend),n&&cx(n.convex_backend,n.request_id))return;const i=n&&typeof window<"u"?_c(window.location.href):void 0;try{M0(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{us()&&!Fu()&&cE.captureException(r,{source:t.source,level:t.level??"error",...n?{...n,page_location:i}:t.extra??{}})}catch{}}function iD(e,t,r){q_(e,{source:r?`react_boundary:${r}`:"react_boundary",extra:{componentStack:t?.componentStack??void 0,boundary:r??"unnamed"}})}export{sO as $,eM as $n,zl as $r,yC as $t,qL as A,Gp as Ai,GT as An,Gy as Ar,vL as At,zL as B,Ol as Bi,lM as Bn,Gn as Br,ku as Bt,VL as C,Ll as Ci,ln as Cn,qx as Cr,yL as Ct,x1 as D,gy as Di,OM as Dn,Zy as Dr,D$ as Dt,A1 as E,mx as Ei,ol as En,Fx as Er,_L as Et,NL as F,Bp as Fi,WE as Fn,zx as Fr,fL as Ft,Pp as G,hx as Gi,cM as Gn,Mx as Gr,AC as Gt,xL as H,px as Hi,M0 as Hn,Do as Hr,uL as Ht,s1 as I,dy as Ii,bM as In,Dx as Ir,i_ as It,aO as J,aM as Jn,xx as Jr,cL as Jt,Cp as K,Ks as Ki,sM as Kn,$y as Kr,aL as Kt,O_ as L,fx as Li,EE as Ln,No as Lr,HC as Lt,FL as M,Gu as Mi,dT as Mn,ns as Mr,a$ as Mt,k1 as N,Mo as Ni,tT as Nn,qr as Nr,M$ as Nt,O1 as O,gx as Oi,Ne as On,Jy as Or,gL as Ot,b1 as P,It as Pi,TM as Pn,vn as Pr,$$ as Pt,IL as Q,h0 as Qn,Dl as Qr,oL as Qt,zO as R,vx as Ri,fM as Rn,wc as Rr,ap as Rt,M1 as S,Qs as Si,Io as Sn,jx as Sr,K$ as St,GL as T,fy as Ti,FM as Tn,Ux as Tr,Sl as Tt,Du as U,ju as Ui,nM as Un,Nl as Ur,dL as Ut,ML as V,ly as Vi,iM as Vn,eo as Vr,Tr as Vt,$p as W,dx as Wi,dM as Wn,Lx as Wr,hL as Wt,CL as X,rM as Xn,Rr as Xr,iL as Xt,PL as Y,uM as Yn,Px as Yr,lL as Yt,oO as Z,hr as Zn,$x as Zr,sL as Zt,JL as _,yy as _i,JT as _n,Gx as _r,zr as _t,eD as a,Ty as ai,lC as an,tf as ar,kL as at,D1 as b,Ml as bi,xM as bn,Vx as br,bL as bt,us as c,$i as ci,kr as cn,Kx as cr,EL as ct,rD as d,Sx as di,CM as dn,td as dr,E_ as dt,Bn as ei,nL as en,tM as er,gr as et,QL as f,ky as fi,PM as fn,Uo as fr,ua as ft,ZL as g,_x as gi,MM as gn,n0 as gr,wL as gt,XL as h,my as hi,NM as hn,t0 as hr,la as ht,$l as i,Ix as ii,pl as in,Xx as ir,AL as it,BL as j,sn as ji,sl as jn,By as jr,O$ as jt,jL as k,Bu as ki,LM as kn,Wy as kr,mL as kt,F_ as l,kx as li,UM as ln,Qx as lr,xP as lt,YL as m,bx as mi,Qr as mn,Wx as mr,pa as mt,q_ as n,Cx as ni,tL as nn,c0 as nr,ZP as nt,tD as o,Rx as oi,uC as on,Yx as or,qP as ot,KL as p,yx as pi,xt as pn,Zx as pr,da as pt,dO as q,Js as qi,oM as qn,Ox as qr,TC as qt,nD as r,Tx as ri,_C as rn,Jx as rr,RL as rt,Fu as s,Ax as si,Os as sn,a0 as sr,zP as st,iD as t,Dt as ti,rL as tn,u0 as tr,Ap as tt,nx as u,Ex as ui,$M as un,Ul as ur,SL as ut,L1 as v,Lo as vi,zM as vn,Yy as vr,X$ as vt,HL as w,rs as wi,ep as wn,Nx as wr,j$ as wt,Cl as x,wx as xi,km as xn,Hx as xr,ta as xt,WL as y,_y as yi,DM as yn,Bx as yr,De as yt,DL as z,uy as zi,cE as zn,Yu as zr,Wt as zt};
|
|
101
|
-
|
|
102
|
-
//# sourceMappingURL=error-reporting-BHW3WviX.js.map
|