@mwillbanks/ast-mcp 0.6.5 → 0.6.6
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/ast-mcp.js +3 -3
- package/dist/ast-mcp.js.map +1 -1
- package/package.json +1 -1
package/dist/ast-mcp.js
CHANGED
|
@@ -338,12 +338,12 @@ ${KLn}`)}async function cnr(e){return Bun.file(e).text().catch((t)=>{if(t.code==
|
|
|
338
338
|
`),m(1)})};d.set(y,S),t.on(y,S)}return()=>{clearTimeout(u);for(let[y,S]of d)t.off(y,S)}}function oFe(e,t=process,n=5000,s){let c=!1,u=!1,d,m=()=>{if(u)return;u=!0,clearTimeout(d),t.exit(1)},y=new Map;for(let S of["uncaughtException","unhandledRejection"]){let T=(C)=>{if(t.exitCode=1,t.stderr.write(`ast-mcp fatal ${S}: ${C instanceof Error?C.message:String(C)}
|
|
339
339
|
`),c){m();return}c=!0;try{s?.(C)}catch{}d=setTimeout(()=>{t.stderr.write(`ast-mcp fatal shutdown timed out
|
|
340
340
|
`),m()},n);let D=(L)=>{t.stderr.write(`ast-mcp fatal cleanup failed: ${L instanceof Error?L.message:String(L)}
|
|
341
|
-
`),m()};try{Promise.resolve(e()).then(m,D)}catch(L){D(L)}};y.set(S,T),t.on(S,T)}return()=>{clearTimeout(d);for(let[S,T]of y)t.off(S,T)}}var D3n,N3n,R3n;var xnr=We(()=>{D3n=["SIGTERM","SIGINT","SIGHUP"],N3n=["SIGINT","SIGBREAK"];R3n=O3n()});var aFe;var Hdt=We(()=>{aFe={author:"Mike Willbanks",bin:{"ast-mcp":"dist/ast-mcp.js"},bugs:{url:"https://github.com/mwillbanks/ast-mcp/issues"},dependencies:{"@ast-grep/lang-bash":"0.0.8","@ast-grep/lang-c":"0.0.6","@ast-grep/lang-cpp":"0.0.6","@ast-grep/lang-csharp":"0.0.6","@ast-grep/lang-dart":"0.0.7","@ast-grep/lang-elixir":"0.0.7","@ast-grep/lang-go":"0.0.6","@ast-grep/lang-java":"0.0.7","@ast-grep/lang-kotlin":"0.0.7","@ast-grep/lang-lua":"0.0.7","@ast-grep/lang-markdown":"0.0.6","@ast-grep/lang-php":"0.0.7","@ast-grep/lang-python":"0.0.6","@ast-grep/lang-ruby":"0.0.7","@ast-grep/lang-rust":"0.0.7","@ast-grep/lang-scala":"0.0.7","@ast-grep/lang-sql":"0.0.8","@ast-grep/lang-swift":"0.0.8","@ast-grep/lang-toml":"0.0.9","@ast-grep/lang-yaml":"0.0.6","@ast-grep/napi":"0.51.0","@huggingface/transformers":"4.3.1","@modelcontextprotocol/client":"2.3.1","@modelcontextprotocol/server":"2.3.1","@posthog/mcp":"0.23.0","apache-arrow":"21.2.0","diff-match-patch-ts":"^2.0.0","onnxruntime-common":"1.30.0",parse5:"8.0.1","posthog-node":"5.56.4","tree-sitter-systemverilog":"0.4.1","tree-sitter-wasm":"2.0.4","typescript-strada":"npm:@typescript/typescript6@6.0.2",unbash:"^6.0.1","web-tree-sitter":"0.27.1",zod:"^4.6.7"},description:"Zero-trust MCP file writes, native code intelligence, graph retrieval, hooks, and agent skills",devDependencies:{"@lancedb/lancedb":"0.40.0","@modelcontextprotocol/inspector":"^2.11.0","@types/bun":"^1.4.3","@types/node":"^26.6.5","apache-arrow-18":"npm:apache-arrow@18.1.0",fallow:"^3.34.1",typescript:"^7.0.2"},engines:{bun:">=1.4.3"},files:["dist","src","templates","README.md","CONTRIBUTING.md","logo.svg","LICENSE"],homepage:"https://mwillbanks.github.io/ast-mcp/",keywords:["ast","ast-grep","coding-agents","mcp","model-context-protocol","secure-code-editing"],license:"MIT",name:"@mwillbanks/ast-mcp",optionalDependencies:{"@lancedb/lancedb-darwin-arm64":"0.40.0","@lancedb/lancedb-linux-arm64-gnu":"0.40.0","@lancedb/lancedb-linux-arm64-musl":"0.40.0","@lancedb/lancedb-linux-x64-gnu":"0.40.0","@lancedb/lancedb-linux-x64-musl":"0.40.0","@lancedb/lancedb-win32-arm64-msvc":"0.40.0","@lancedb/lancedb-win32-x64-msvc":"0.40.0"},overrides:{sharp:"0.35.5"},packageManager:"bun@1.4.4",preferUnplugged:!0,publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/mwillbanks/ast-mcp.git"},scripts:{build:"bun run scripts/build/build.ts",check:"bun run tools:check && bun run templates:check && bun run prose:check && bun run lint && bun run test","check:coverage":"bun run tools:check && bun run templates:check && bun run prose:check && bun run lint && bun run test:coverage",dev:"bun run --watch src/index.ts","dev:http":"bun run --watch src/http/entry.ts","evals:check":"bun run templates/skills/ast-mcp/evals/validate.ts","evals:measure":"bun run templates/skills/ast-mcp/evals/measure.ts","evals:score":"bun run templates/skills/ast-mcp/evals/measure.ts --strict",fallow:"fallow --skip health","fallow:health":"fallow health",format:"bun fmt .","format:check":"bun fmt --check .","format:files":"bun fmt",inspect:"bunx @modelcontextprotocol/inspector bun run src/index.ts","inspect:http":"bunx @modelcontextprotocol/inspector","intelligence:measure":"bun run scripts/benchmark/benchmark-intelligence-baseline.ts","intelligence:qualify":"bun run scripts/validation/qualify-intelligence-deps.ts",lint:"bun run format:check && bun run typecheck && bun run boundaries:check",prepack:"bun run build","prose:check":"bun run scripts/validation/check-prose-cli.ts","skill:check":"bunx skills-ref validate templates/skills/ast-mcp","smoke:hosts":"bun run scripts/testing/host-smoke.ts",start:"bun run src/index.ts","start:http":"bun run src/http/entry.ts","templates:check":"bun run scripts/validation/check-template-drift.ts","templates:sync":"bun run scripts/validation/check-template-drift.ts --write",test:"bun test --dots --bail --max-concurrency=1 --timeout=30000","test:coverage":"bun test --coverage --dots --bail --max-concurrency=1 --timeout=30000","tools:check":"bun run scripts/validation/verify-tools.ts",typecheck:"bun check --no-script","boundaries:check":"bun run scripts/validation/check-runtime-imports.ts"},sideEffects:!1,type:"module",version:"0.6.5"}});var Gdt=()=>{};var Enr=We(()=>{Gdt()});var Rz=()=>{};var fye=()=>{};function Ydt(e){return e===null||typeof e!="object"}function dG(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Anr(e,Error)}}function pye(e){return"u">typeof Event&&Anr(e,Event)}function Anr(e,t){try{return e instanceof t}catch{return!1}}var L3n,Cnr,fQi,Inr,BB,dye=(e)=>e===void 0,FR=(e)=>Inr.call(e)=="[object String]",Xdt=(e)=>FR(e)&&e.trim().length===0;var Mz=We(()=>{Rz();fye();L3n=Array.isArray,Cnr=Object.prototype,fQi=Cnr.hasOwnProperty,Inr=Cnr.toString,BB=L3n||function(e){return Inr.call(e)==="[object Array]"}});var Pnr=()=>{};var Dnr=We(()=>{fye()});var Qdt=We(()=>{Mz()});var Onr=We(()=>{Qdt()});class pG{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new pG(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,n,s){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(s)||e<0||t<0||n<0||s<0||e>281474976710655||t>4095||n>1073741823||s>4294967295)throw RangeError("invalid field value");let c=new Uint8Array(16);return c[0]=e/1099511627776,c[1]=e/4294967296,c[2]=e/16777216,c[3]=e/65536,c[4]=e/256,c[5]=e,c[6]=112|t>>>8,c[7]=t,c[8]=128|n>>>24,c[9]=n>>>16,c[10]=n>>>8,c[11]=n,c[12]=s>>>24,c[13]=s>>>16,c[14]=s>>>8,c[15]=s,new pG(c)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;default:break}if(t){let n=new Uint8Array(16);for(let s=0;s<16;s+=4){let c=parseInt(t.substring(2*s,2*s+8),16);n[s+0]=c>>>24,n[s+1]=c>>>16,n[s+2]=c>>>8,n[s+3]=c}return new pG(n)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)if(e+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".charAt(15&this.bytes[t]),t===3||t===5||t===7||t===9)e+="-";return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw Error("unreachable");if(e<=7)return this.bytes.every((t)=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every((t)=>t===255)?"MAX":"VAR_RESERVED";else throw Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new pG(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let n=this.bytes[t]-e.bytes[t];if(n!==0)return Math.sign(n)}return 0}}class Mnr{constructor(e){this.timestamp=0,this.counter=0,this.random=e??B3n()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let n=this.generateOrAbortCore(e,t);if(n===void 0)this.timestamp=0,n=this.generateOrAbortCore(e,t);return n}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>281474976710655)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>281474976710655)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;if(this.counter++,this.counter>4398046511103)this.timestamp++,this.resetCounter()}return pG.fromFieldsV7(this.timestamp,Math.trunc(this.counter/1073741824),this.counter&1073741823,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,pG.ofInner(e)}}var B3n=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),Rnr,LR=()=>j3n().toString(),j3n=()=>(Rnr||(Rnr=new Mnr)).generate();var yne=We(()=>{/*! LICENSE: uuidv7.mjs.LICENSE.txt */});var Fnr=We(()=>{yne()});var Lnr=()=>{};var bne="Mobile",lFe="iOS",vne="Android",Unr="Tablet",CQi,$3n="Apple",IQi,qnr="Safari",uFe="BlackBerry",Vnr="Samsung",U3n,q3n,fFe="Chrome",V3n,J3n,Jnr="Internet Explorer",W3n,ept="Opera",AQi,Wnr="Edge",H3n,tpt="Firefox",G3n,rpt="Nintendo",npt="PlayStation",cFe="Xbox",X3n,Y3n,_ye="Windows",Q3n,Hnr="Generic",PQi,DQi,K3n="Konqueror",Z3n="Oculus Browser",Bnr="Vivaldi",e8n="Yandex",jnr="Whale",t8n="DuckDuckGo",r8n="Pale Moon",znr="Waterfox",$nr="Brave",Gnr="Claude",Xnr="Codex",Ynr="ChatGPT",n8n="Google Search App",fy="(\\d+(\\.\\d+)?)",Kdt,Zdt,NQi,OQi,RQi,i8n,s8n,MQi,FQi;var Qnr=We(()=>{fye();Mz();CQi=vne+" "+Unr,IQi=$3n+" Watch",U3n=Vnr+"Browser",q3n=Vnr+" Internet",V3n=fFe+" OS",J3n=fFe+" "+lFe,W3n=Jnr+" "+bne,AQi=ept+" Mini",H3n="Microsoft "+Wnr,G3n=tpt+" "+lFe,X3n=vne+" "+bne,Y3n=bne+" "+qnr,Q3n=_ye+" Phone",PQi=Hnr+" "+bne.toLowerCase(),DQi=Hnr+" "+Unr.toLowerCase(),Kdt=new RegExp("Version/"+fy),Zdt=new RegExp("("+Gnr+"|"+Xnr+"|"+Ynr+")\\/"+fy),NQi=new RegExp(cFe,"i"),OQi=new RegExp(npt+" \\w+","i"),RQi=new RegExp(rpt+" \\w+","i"),i8n=new RegExp(uFe+"|PlayBook|BB10","i"),s8n={"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"},MQi={[W3n]:[new RegExp("rv:"+fy)],[H3n]:[new RegExp(Wnr+"?\\/"+fy)],[fFe]:[new RegExp("("+fFe+"|CrMo)\\/"+fy)],[J3n]:[new RegExp("CriOS\\/"+fy)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+fy)],[qnr]:[Kdt],[Y3n]:[Kdt],[ept]:[new RegExp("("+ept+"|OPR)\\/"+fy)],[tpt]:[new RegExp(tpt+"\\/"+fy)],[G3n]:[new RegExp("FxiOS\\/"+fy)],[K3n]:[new RegExp("Konqueror[:/]?"+fy,"i")],[uFe]:[new RegExp(uFe+" "+fy),Kdt],[X3n]:[new RegExp("android\\s"+fy,"i")],[q3n]:[new RegExp(U3n+"\\/"+fy)],[Z3n]:[new RegExp("OculusBrowser\\/"+fy)],[Bnr]:[new RegExp(Bnr+"\\/"+fy)],[e8n]:[new RegExp("YaBrowser\\/"+fy)],[jnr]:[new RegExp(jnr+"\\/"+fy)],[$nr]:[new RegExp($nr+"\\/"+fy)],[Gnr]:[Zdt],[Xnr]:[Zdt],[Ynr]:[Zdt],[t8n]:[new RegExp("(DuckDuckGo|Ddg)\\/"+fy)],[r8n]:[new RegExp("PaleMoon\\/"+fy)],[znr]:[new RegExp(znr+"\\/"+fy)],[n8n]:[new RegExp("GSA\\/"+fy)],[Jnr]:[new RegExp("(rv:|MSIE )"+fy)],Mozilla:[new RegExp("rv:"+fy)]},FQi=[[new RegExp(cFe+"; "+cFe+" (.*?)[);]","i"),(e)=>[cFe,e&&e[1]||""]],[new RegExp(rpt,"i"),[rpt,""]],[new RegExp(npt,"i"),[npt,""]],[i8n,[uFe,""]],[new RegExp(_ye,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[Q3n,""];if(new RegExp(bne).test(t)&&!/IEMobile\b/.test(t))return[_ye+" "+bne,""];let n=/Windows NT ([0-9.]+)/i.exec(t);if(n&&n[1]){let s=n[1],c=s8n[s]||"";if(/arm/i.test(t))c="RT";return[_ye,c]}return[_ye,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(e)=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[lFe,t.join(".")]}return[lFe,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(e)=>{let t="";if(e&&e.length>=3)t=dye(e[2])?e[3]:e[2];return["watchOS",t]}],[new RegExp("("+vne+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+vne+")","i"),(e)=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[vne,t.join(".")]}return[vne,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,(e)=>{let t=["Mac OS X",""];if(e&&e[1]){let n=[e[1],e[2],e[3]||"0"];t[1]=n.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[V3n,""]],[/Linux|debian/i,["Linux",""]]]});var Knr=()=>{};var jQi,zQi;var jB=We(()=>{jQi=Date.prototype.getTime,zQi=Date.prototype.toISOString});var wne=()=>{};var jv=We(()=>{Mz();jB();wne();Pnr();Dnr();Onr();Qdt();fye();Mz();Fnr();Lnr();Qnr();Knr()});function rir(e){let{_posthogChunkIds:t,_debugIds:n}=globalThis;if(!t&&!n)return;let s=t?Object.keys(t):[],c=n?Object.keys(n):[];if(Sne&&tir(t,s,Znr)&&tir(n,c,eir))return Sne;Znr=t?{...t}:void 0,eir=n?{...n}:void 0,Sne={},ipt??={};let u=(d,m)=>{for(let y of d){let S=m[y];if(!S)continue;let T=ipt?.[y];if(T){Sne[T]=S;continue}let C=e(y);for(let D=C.length-1;D>=0;D--){let L=C[D]?.filename;if(L){Sne[L]=S,ipt[y]=L;break}}}};if(n)u(c,n);if(t)u(s,t);return Sne}function tir(e,t,n){if(!e||!n)return e===n;return t.length===Object.keys(n).length&&t.every((s)=>e[s]===n[s])}var ipt,Znr,eir,Sne;var nir=()=>{};class opt{constructor(e,t,n=[]){this.coercers=e,this.stackParser=t,this.modifiers=n}buildFromUnknown(e,t={}){let s=t&&t.mechanism||{handled:!0,type:"generic"},u=this.buildCoercingContext(s,t,0).apply(e),d=this.buildParsingContext(t),m=this.parseStacktrace(u,d);return{$exception_list:this.convertToExceptionList(m,s),$exception_level:"error"}}async modifyFrames(e){for(let t of e)if(t.stacktrace&&t.stacktrace.frames&&BB(t.stacktrace.frames))t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames);return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let n;if(e.cause!=null)n=this.parseStacktrace(e.cause,t);let s;if(e.stack!=""&&e.stack!=null)try{s=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)}catch{}return{...e,cause:n,stack:s,errors:e.errors?.map((c)=>this.parseStacktrace(c,t))}}applyChunkIds(e,t){return e.map((n)=>{if(n.filename&&t)n.chunk_id=t[n.filename];return n})}applyCoercers(e,t){for(let n of this.coercers)if(n.match(e))return n.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let n of this.modifiers)t=await n(t);return t}convertToExceptionList(e,t){let n=[],s=(c,u,d)=>{let m=n.length,y=u===void 0?{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:c.synthetic,exception_id:m}:{type:"chained",source:d,synthetic:c.synthetic,exception_id:m,parent_id:u},S={type:c.type,value:c.value,mechanism:y};if(c.stack)S.stacktrace={type:"raw",frames:c.stack};if(n.push(S),c.cause)s(c.cause,m,"cause");for(let T of c.errors??[])s(T,m,"member")};return s(e),n}buildParsingContext(e){return{chunkIdMap:rir(this.stackParser),skipFirstLines:e.skipFirstLines??1}}getAggregateErrors(e){try{if(dG(e)){let t=Object.getPrototypeOf(e);for(let n=0;t&&n<c8n;n++){let s=Object.getOwnPropertyDescriptor(t,"constructor")?.value;if(typeof s=="function"&&s.name==="AggregateError"){let c=e.errors;return BB(c)?c:void 0}t=Object.getPrototypeOf(t)}}}catch{}}buildCoercingContext(e,t,n=0){let s=0,c=0,u=!1,d=new Set,m=[],y={},S=(D,L,B=0)=>{let z=T(L,B),X=z.apply;if(z.apply=(he)=>{m.push(D);try{return X(he)}finally{m.pop()}},B>l8n||B>0&&m.indexOf(D)!==-1)return this.coerceFallback(z);let K=typeof D=="object"&&D!==null||typeof D=="function";if(B===0&&s>=spt||K&&d.has(D))return;if(K)d.add(D);if(B===0)s++;let ie=this.getAggregateErrors(D);u||=!!ie;let ye;try{if(ye=this.applyCoercers(D,z),!ye)throw y}catch(he){if(he===y){if(B===0)s--;return}if(!u)throw he;ye=this.coerceFallback(z)}if(!ie||s>=spt)return ye;let Te;try{Te=ie.length}catch{return ye}if(!Number.isInteger(Te)||Te<0||Te>4294967295)return ye;let Ce=[];for(let he=0;s<spt&&c<a8n&&he<Te;he++){c++;let re;try{re=z.next(ie[he])}catch{s++,re=this.coerceFallback(T(L+1))}if(re)Ce.push(re)}return{...ye,errors:Ce}},T=(D,L=0)=>({...t,syntheticException:D==0?t.syntheticException:void 0,mechanism:D==0?e:{},apply:(B)=>{let z=S(B,D,L+1);if(!z)throw y;return z},next:(B)=>S(B,D+1)}),C=T(n);return{...C,apply:(D)=>S(D,n)??this.coerceFallback(C)}}}var spt=50,a8n=1000,c8n=100,l8n=4;var iir=We(()=>{jv();nir()});var zB="?";var Fz=We(()=>{jv()});var apt=We(()=>{Fz()});var sir=We(()=>{Fz();apt()});var oir=We(()=>{Fz();apt()});var air=We(()=>{Fz()});var cir=We(()=>{Fz()});function h8n(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&e!==void 0&&!e.includes("node_modules/")}function lir(e){return parseInt(e||"",10)||void 0}var f8n,d8n,p8n,_8n,m8n="node:internal/promise",uir=(e,t)=>{let n=e.match(d8n);if(n){let s,c,u,d,m;if(n[1]){u=n[1];let T=u.lastIndexOf(".");if(u[T-1]===".")T--;if(T>0){s=u.slice(0,T),c=u.slice(T+1);let C=s.indexOf(".Module");if(C>0)u=u.slice(C+1),s=s.slice(0,C)}d=void 0}if(c)d=s,m=c;if(c==="<anonymous>")m=void 0,u=void 0;if(u===void 0)m=m||zB,u=d?`${d}.${m}`:m;let y=n[2]?.startsWith("file://")?n[2].slice(7):n[2],S=n[5]==="native";if(y?.match(/\/[A-Z]:/))y=y.slice(1);if(!y&&n[5]&&!S)y=n[5];if(p8n.test(u)&&_8n.test(y||""))y=m8n;return{filename:y?decodeURI(y):void 0,module:void 0,function:u,lineno:lir(n[3]),colno:lir(n[4]),in_app:h8n(y||"",S),platform:t}}if(e.match(f8n))return{filename:e,platform:t}};var fir=We(()=>{Fz();f8n=/^\s*[-]{4,}$/,d8n=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,p8n=/^Promise\.(?:all|any)$/,_8n=/^index \d+$/});function lpt(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function v8n(e){for(let t=1;t<=g8n;t++){let n=e.length-2*t;if(n<0)break;let s=!0;for(let c=0;c<t;c++){let u=e[n+c];if(!lpt(u,e[n+t+c])){s=!1;break}}if(s){for(let c=0;c<t;c++)e[n+c]=e[n+t+c];return e.length=n+t,{start:n,length:t}}}}function b8n(e,t){let n=t.start+t.length,s=mir(e,t);if(s)e.splice(n+s===e.length?n:t.start,s)}function _ir(e,t){let n=t.start;while(n>0&&lpt(e[n-1],e[n-1+t.length]))n--;return t.start-n}function mir(e,t){let n=t.start+t.length,s=n;while(s<e.length&&lpt(e[s],e[s-t.length]))s++;return s-n}function w8n(e,t){let n=t[0],s=e.length-(n?_ir(e,n):0);for(let c of t)s-=mir(e,c);return s}function S8n(e){let t=e.map((s)=>`${s.function}|${s.filename}|${s.lineno}|${s.colno}|${s.module}`),n=0;for(let s=1;s<t.length;s++)if(T8n(t,s,n))n=s;e.push(...e.splice(0,n))}function T8n(e,t,n){for(let s=0;s<e.length;s++){let c=e[(t+s)%e.length],u=e[(n+s)%e.length];if(c!==u)return c<u}return!1}function x8n(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,pir).map((n)=>({...n,filename:n.filename||E8n(t).filename,function:n.function||zB}))}function E8n(e){return e[e.length-1]||{}}function k8n(e,...t){return(n,s=0)=>{let c=[],u=n.split(`
|
|
341
|
+
`),m()};try{Promise.resolve(e()).then(m,D)}catch(L){D(L)}};y.set(S,T),t.on(S,T)}return()=>{clearTimeout(d);for(let[S,T]of y)t.off(S,T)}}var D3n,N3n,R3n;var xnr=We(()=>{D3n=["SIGTERM","SIGINT","SIGHUP"],N3n=["SIGINT","SIGBREAK"];R3n=O3n()});var aFe;var Hdt=We(()=>{aFe={author:"Mike Willbanks",bin:{"ast-mcp":"dist/ast-mcp.js"},bugs:{url:"https://github.com/mwillbanks/ast-mcp/issues"},dependencies:{"@ast-grep/lang-bash":"0.0.8","@ast-grep/lang-c":"0.0.6","@ast-grep/lang-cpp":"0.0.6","@ast-grep/lang-csharp":"0.0.6","@ast-grep/lang-dart":"0.0.7","@ast-grep/lang-elixir":"0.0.7","@ast-grep/lang-go":"0.0.6","@ast-grep/lang-java":"0.0.7","@ast-grep/lang-kotlin":"0.0.7","@ast-grep/lang-lua":"0.0.7","@ast-grep/lang-markdown":"0.0.6","@ast-grep/lang-php":"0.0.7","@ast-grep/lang-python":"0.0.6","@ast-grep/lang-ruby":"0.0.7","@ast-grep/lang-rust":"0.0.7","@ast-grep/lang-scala":"0.0.7","@ast-grep/lang-sql":"0.0.8","@ast-grep/lang-swift":"0.0.8","@ast-grep/lang-toml":"0.0.9","@ast-grep/lang-yaml":"0.0.6","@ast-grep/napi":"0.51.0","@huggingface/transformers":"4.3.1","@modelcontextprotocol/client":"2.3.1","@modelcontextprotocol/server":"2.3.1","@posthog/mcp":"0.23.0","apache-arrow":"21.2.0","diff-match-patch-ts":"^2.0.0","onnxruntime-common":"1.30.0",parse5:"8.0.1","posthog-node":"5.56.4","tree-sitter-systemverilog":"0.4.1","tree-sitter-wasm":"2.0.4","typescript-strada":"npm:@typescript/typescript6@6.0.2",unbash:"^6.0.1","web-tree-sitter":"0.27.1",zod:"^4.6.7"},description:"Zero-trust MCP file writes, native code intelligence, graph retrieval, hooks, and agent skills",devDependencies:{"@lancedb/lancedb":"0.40.0","@modelcontextprotocol/inspector":"^2.11.0","@types/bun":"^1.4.3","@types/node":"^26.6.5","apache-arrow-18":"npm:apache-arrow@18.1.0",fallow:"^3.34.1",typescript:"^7.0.2"},engines:{bun:">=1.4.3"},files:["dist","src","templates","README.md","CONTRIBUTING.md","logo.svg","LICENSE"],homepage:"https://mwillbanks.github.io/ast-mcp/",keywords:["ast","ast-grep","coding-agents","mcp","model-context-protocol","secure-code-editing"],license:"MIT",name:"@mwillbanks/ast-mcp",optionalDependencies:{"@lancedb/lancedb-darwin-arm64":"0.40.0","@lancedb/lancedb-linux-arm64-gnu":"0.40.0","@lancedb/lancedb-linux-arm64-musl":"0.40.0","@lancedb/lancedb-linux-x64-gnu":"0.40.0","@lancedb/lancedb-linux-x64-musl":"0.40.0","@lancedb/lancedb-win32-arm64-msvc":"0.40.0","@lancedb/lancedb-win32-x64-msvc":"0.40.0"},overrides:{sharp:"0.35.5"},packageManager:"bun@1.4.4",preferUnplugged:!0,publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/mwillbanks/ast-mcp.git"},scripts:{build:"bun run scripts/build/build.ts",check:"bun run tools:check && bun run templates:check && bun run prose:check && bun run lint && bun run test","check:coverage":"bun run tools:check && bun run templates:check && bun run prose:check && bun run lint && bun run test:coverage",dev:"bun run --watch src/index.ts","dev:http":"bun run --watch src/http/entry.ts","evals:check":"bun run templates/skills/ast-mcp/evals/validate.ts","evals:measure":"bun run templates/skills/ast-mcp/evals/measure.ts","evals:score":"bun run templates/skills/ast-mcp/evals/measure.ts --strict",fallow:"fallow --skip health","fallow:health":"fallow health",format:"bun fmt .","format:check":"bun fmt --check .","format:files":"bun fmt",inspect:"bunx @modelcontextprotocol/inspector bun run src/index.ts","inspect:http":"bunx @modelcontextprotocol/inspector","intelligence:measure":"bun run scripts/benchmark/benchmark-intelligence-baseline.ts","intelligence:qualify":"bun run scripts/validation/qualify-intelligence-deps.ts",lint:"bun run format:check && bun run typecheck && bun run boundaries:check",prepack:"bun run build","prose:check":"bun run scripts/validation/check-prose-cli.ts","skill:check":"bunx skills-ref validate templates/skills/ast-mcp","smoke:hosts":"bun run scripts/testing/host-smoke.ts",start:"bun run src/index.ts","start:http":"bun run src/http/entry.ts","templates:check":"bun run scripts/validation/check-template-drift.ts","templates:sync":"bun run scripts/validation/check-template-drift.ts --write",test:"bun test --dots --bail --max-concurrency=1 --timeout=30000","test:coverage":"bun test --coverage --dots --bail --max-concurrency=1 --timeout=30000","tools:check":"bun run scripts/validation/verify-tools.ts",typecheck:"bun check --no-script","boundaries:check":"bun run scripts/validation/check-runtime-imports.ts"},sideEffects:!1,type:"module",version:"0.6.6"}});var Gdt=()=>{};var Enr=We(()=>{Gdt()});var Rz=()=>{};var fye=()=>{};function Ydt(e){return e===null||typeof e!="object"}function dG(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Anr(e,Error)}}function pye(e){return"u">typeof Event&&Anr(e,Event)}function Anr(e,t){try{return e instanceof t}catch{return!1}}var L3n,Cnr,fQi,Inr,BB,dye=(e)=>e===void 0,FR=(e)=>Inr.call(e)=="[object String]",Xdt=(e)=>FR(e)&&e.trim().length===0;var Mz=We(()=>{Rz();fye();L3n=Array.isArray,Cnr=Object.prototype,fQi=Cnr.hasOwnProperty,Inr=Cnr.toString,BB=L3n||function(e){return Inr.call(e)==="[object Array]"}});var Pnr=()=>{};var Dnr=We(()=>{fye()});var Qdt=We(()=>{Mz()});var Onr=We(()=>{Qdt()});class pG{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new pG(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,n,s){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(s)||e<0||t<0||n<0||s<0||e>281474976710655||t>4095||n>1073741823||s>4294967295)throw RangeError("invalid field value");let c=new Uint8Array(16);return c[0]=e/1099511627776,c[1]=e/4294967296,c[2]=e/16777216,c[3]=e/65536,c[4]=e/256,c[5]=e,c[6]=112|t>>>8,c[7]=t,c[8]=128|n>>>24,c[9]=n>>>16,c[10]=n>>>8,c[11]=n,c[12]=s>>>24,c[13]=s>>>16,c[14]=s>>>8,c[15]=s,new pG(c)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;default:break}if(t){let n=new Uint8Array(16);for(let s=0;s<16;s+=4){let c=parseInt(t.substring(2*s,2*s+8),16);n[s+0]=c>>>24,n[s+1]=c>>>16,n[s+2]=c>>>8,n[s+3]=c}return new pG(n)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)if(e+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".charAt(15&this.bytes[t]),t===3||t===5||t===7||t===9)e+="-";return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw Error("unreachable");if(e<=7)return this.bytes.every((t)=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every((t)=>t===255)?"MAX":"VAR_RESERVED";else throw Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new pG(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let n=this.bytes[t]-e.bytes[t];if(n!==0)return Math.sign(n)}return 0}}class Mnr{constructor(e){this.timestamp=0,this.counter=0,this.random=e??B3n()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let n=this.generateOrAbortCore(e,t);if(n===void 0)this.timestamp=0,n=this.generateOrAbortCore(e,t);return n}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>281474976710655)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>281474976710655)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;if(this.counter++,this.counter>4398046511103)this.timestamp++,this.resetCounter()}return pG.fromFieldsV7(this.timestamp,Math.trunc(this.counter/1073741824),this.counter&1073741823,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,pG.ofInner(e)}}var B3n=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),Rnr,LR=()=>j3n().toString(),j3n=()=>(Rnr||(Rnr=new Mnr)).generate();var yne=We(()=>{/*! LICENSE: uuidv7.mjs.LICENSE.txt */});var Fnr=We(()=>{yne()});var Lnr=()=>{};var bne="Mobile",lFe="iOS",vne="Android",Unr="Tablet",CQi,$3n="Apple",IQi,qnr="Safari",uFe="BlackBerry",Vnr="Samsung",U3n,q3n,fFe="Chrome",V3n,J3n,Jnr="Internet Explorer",W3n,ept="Opera",AQi,Wnr="Edge",H3n,tpt="Firefox",G3n,rpt="Nintendo",npt="PlayStation",cFe="Xbox",X3n,Y3n,_ye="Windows",Q3n,Hnr="Generic",PQi,DQi,K3n="Konqueror",Z3n="Oculus Browser",Bnr="Vivaldi",e8n="Yandex",jnr="Whale",t8n="DuckDuckGo",r8n="Pale Moon",znr="Waterfox",$nr="Brave",Gnr="Claude",Xnr="Codex",Ynr="ChatGPT",n8n="Google Search App",fy="(\\d+(\\.\\d+)?)",Kdt,Zdt,NQi,OQi,RQi,i8n,s8n,MQi,FQi;var Qnr=We(()=>{fye();Mz();CQi=vne+" "+Unr,IQi=$3n+" Watch",U3n=Vnr+"Browser",q3n=Vnr+" Internet",V3n=fFe+" OS",J3n=fFe+" "+lFe,W3n=Jnr+" "+bne,AQi=ept+" Mini",H3n="Microsoft "+Wnr,G3n=tpt+" "+lFe,X3n=vne+" "+bne,Y3n=bne+" "+qnr,Q3n=_ye+" Phone",PQi=Hnr+" "+bne.toLowerCase(),DQi=Hnr+" "+Unr.toLowerCase(),Kdt=new RegExp("Version/"+fy),Zdt=new RegExp("("+Gnr+"|"+Xnr+"|"+Ynr+")\\/"+fy),NQi=new RegExp(cFe,"i"),OQi=new RegExp(npt+" \\w+","i"),RQi=new RegExp(rpt+" \\w+","i"),i8n=new RegExp(uFe+"|PlayBook|BB10","i"),s8n={"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"},MQi={[W3n]:[new RegExp("rv:"+fy)],[H3n]:[new RegExp(Wnr+"?\\/"+fy)],[fFe]:[new RegExp("("+fFe+"|CrMo)\\/"+fy)],[J3n]:[new RegExp("CriOS\\/"+fy)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+fy)],[qnr]:[Kdt],[Y3n]:[Kdt],[ept]:[new RegExp("("+ept+"|OPR)\\/"+fy)],[tpt]:[new RegExp(tpt+"\\/"+fy)],[G3n]:[new RegExp("FxiOS\\/"+fy)],[K3n]:[new RegExp("Konqueror[:/]?"+fy,"i")],[uFe]:[new RegExp(uFe+" "+fy),Kdt],[X3n]:[new RegExp("android\\s"+fy,"i")],[q3n]:[new RegExp(U3n+"\\/"+fy)],[Z3n]:[new RegExp("OculusBrowser\\/"+fy)],[Bnr]:[new RegExp(Bnr+"\\/"+fy)],[e8n]:[new RegExp("YaBrowser\\/"+fy)],[jnr]:[new RegExp(jnr+"\\/"+fy)],[$nr]:[new RegExp($nr+"\\/"+fy)],[Gnr]:[Zdt],[Xnr]:[Zdt],[Ynr]:[Zdt],[t8n]:[new RegExp("(DuckDuckGo|Ddg)\\/"+fy)],[r8n]:[new RegExp("PaleMoon\\/"+fy)],[znr]:[new RegExp(znr+"\\/"+fy)],[n8n]:[new RegExp("GSA\\/"+fy)],[Jnr]:[new RegExp("(rv:|MSIE )"+fy)],Mozilla:[new RegExp("rv:"+fy)]},FQi=[[new RegExp(cFe+"; "+cFe+" (.*?)[);]","i"),(e)=>[cFe,e&&e[1]||""]],[new RegExp(rpt,"i"),[rpt,""]],[new RegExp(npt,"i"),[npt,""]],[i8n,[uFe,""]],[new RegExp(_ye,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[Q3n,""];if(new RegExp(bne).test(t)&&!/IEMobile\b/.test(t))return[_ye+" "+bne,""];let n=/Windows NT ([0-9.]+)/i.exec(t);if(n&&n[1]){let s=n[1],c=s8n[s]||"";if(/arm/i.test(t))c="RT";return[_ye,c]}return[_ye,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(e)=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[lFe,t.join(".")]}return[lFe,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(e)=>{let t="";if(e&&e.length>=3)t=dye(e[2])?e[3]:e[2];return["watchOS",t]}],[new RegExp("("+vne+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+vne+")","i"),(e)=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[vne,t.join(".")]}return[vne,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,(e)=>{let t=["Mac OS X",""];if(e&&e[1]){let n=[e[1],e[2],e[3]||"0"];t[1]=n.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[V3n,""]],[/Linux|debian/i,["Linux",""]]]});var Knr=()=>{};var jQi,zQi;var jB=We(()=>{jQi=Date.prototype.getTime,zQi=Date.prototype.toISOString});var wne=()=>{};var jv=We(()=>{Mz();jB();wne();Pnr();Dnr();Onr();Qdt();fye();Mz();Fnr();Lnr();Qnr();Knr()});function rir(e){let{_posthogChunkIds:t,_debugIds:n}=globalThis;if(!t&&!n)return;let s=t?Object.keys(t):[],c=n?Object.keys(n):[];if(Sne&&tir(t,s,Znr)&&tir(n,c,eir))return Sne;Znr=t?{...t}:void 0,eir=n?{...n}:void 0,Sne={},ipt??={};let u=(d,m)=>{for(let y of d){let S=m[y];if(!S)continue;let T=ipt?.[y];if(T){Sne[T]=S;continue}let C=e(y);for(let D=C.length-1;D>=0;D--){let L=C[D]?.filename;if(L){Sne[L]=S,ipt[y]=L;break}}}};if(n)u(c,n);if(t)u(s,t);return Sne}function tir(e,t,n){if(!e||!n)return e===n;return t.length===Object.keys(n).length&&t.every((s)=>e[s]===n[s])}var ipt,Znr,eir,Sne;var nir=()=>{};class opt{constructor(e,t,n=[]){this.coercers=e,this.stackParser=t,this.modifiers=n}buildFromUnknown(e,t={}){let s=t&&t.mechanism||{handled:!0,type:"generic"},u=this.buildCoercingContext(s,t,0).apply(e),d=this.buildParsingContext(t),m=this.parseStacktrace(u,d);return{$exception_list:this.convertToExceptionList(m,s),$exception_level:"error"}}async modifyFrames(e){for(let t of e)if(t.stacktrace&&t.stacktrace.frames&&BB(t.stacktrace.frames))t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames);return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let n;if(e.cause!=null)n=this.parseStacktrace(e.cause,t);let s;if(e.stack!=""&&e.stack!=null)try{s=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)}catch{}return{...e,cause:n,stack:s,errors:e.errors?.map((c)=>this.parseStacktrace(c,t))}}applyChunkIds(e,t){return e.map((n)=>{if(n.filename&&t)n.chunk_id=t[n.filename];return n})}applyCoercers(e,t){for(let n of this.coercers)if(n.match(e))return n.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let n of this.modifiers)t=await n(t);return t}convertToExceptionList(e,t){let n=[],s=(c,u,d)=>{let m=n.length,y=u===void 0?{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:c.synthetic,exception_id:m}:{type:"chained",source:d,synthetic:c.synthetic,exception_id:m,parent_id:u},S={type:c.type,value:c.value,mechanism:y};if(c.stack)S.stacktrace={type:"raw",frames:c.stack};if(n.push(S),c.cause)s(c.cause,m,"cause");for(let T of c.errors??[])s(T,m,"member")};return s(e),n}buildParsingContext(e){return{chunkIdMap:rir(this.stackParser),skipFirstLines:e.skipFirstLines??1}}getAggregateErrors(e){try{if(dG(e)){let t=Object.getPrototypeOf(e);for(let n=0;t&&n<c8n;n++){let s=Object.getOwnPropertyDescriptor(t,"constructor")?.value;if(typeof s=="function"&&s.name==="AggregateError"){let c=e.errors;return BB(c)?c:void 0}t=Object.getPrototypeOf(t)}}}catch{}}buildCoercingContext(e,t,n=0){let s=0,c=0,u=!1,d=new Set,m=[],y={},S=(D,L,B=0)=>{let z=T(L,B),X=z.apply;if(z.apply=(he)=>{m.push(D);try{return X(he)}finally{m.pop()}},B>l8n||B>0&&m.indexOf(D)!==-1)return this.coerceFallback(z);let K=typeof D=="object"&&D!==null||typeof D=="function";if(B===0&&s>=spt||K&&d.has(D))return;if(K)d.add(D);if(B===0)s++;let ie=this.getAggregateErrors(D);u||=!!ie;let ye;try{if(ye=this.applyCoercers(D,z),!ye)throw y}catch(he){if(he===y){if(B===0)s--;return}if(!u)throw he;ye=this.coerceFallback(z)}if(!ie||s>=spt)return ye;let Te;try{Te=ie.length}catch{return ye}if(!Number.isInteger(Te)||Te<0||Te>4294967295)return ye;let Ce=[];for(let he=0;s<spt&&c<a8n&&he<Te;he++){c++;let re;try{re=z.next(ie[he])}catch{s++,re=this.coerceFallback(T(L+1))}if(re)Ce.push(re)}return{...ye,errors:Ce}},T=(D,L=0)=>({...t,syntheticException:D==0?t.syntheticException:void 0,mechanism:D==0?e:{},apply:(B)=>{let z=S(B,D,L+1);if(!z)throw y;return z},next:(B)=>S(B,D+1)}),C=T(n);return{...C,apply:(D)=>S(D,n)??this.coerceFallback(C)}}}var spt=50,a8n=1000,c8n=100,l8n=4;var iir=We(()=>{jv();nir()});var zB="?";var Fz=We(()=>{jv()});var apt=We(()=>{Fz()});var sir=We(()=>{Fz();apt()});var oir=We(()=>{Fz();apt()});var air=We(()=>{Fz()});var cir=We(()=>{Fz()});function h8n(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&e!==void 0&&!e.includes("node_modules/")}function lir(e){return parseInt(e||"",10)||void 0}var f8n,d8n,p8n,_8n,m8n="node:internal/promise",uir=(e,t)=>{let n=e.match(d8n);if(n){let s,c,u,d,m;if(n[1]){u=n[1];let T=u.lastIndexOf(".");if(u[T-1]===".")T--;if(T>0){s=u.slice(0,T),c=u.slice(T+1);let C=s.indexOf(".Module");if(C>0)u=u.slice(C+1),s=s.slice(0,C)}d=void 0}if(c)d=s,m=c;if(c==="<anonymous>")m=void 0,u=void 0;if(u===void 0)m=m||zB,u=d?`${d}.${m}`:m;let y=n[2]?.startsWith("file://")?n[2].slice(7):n[2],S=n[5]==="native";if(y?.match(/\/[A-Z]:/))y=y.slice(1);if(!y&&n[5]&&!S)y=n[5];if(p8n.test(u)&&_8n.test(y||""))y=m8n;return{filename:y?decodeURI(y):void 0,module:void 0,function:u,lineno:lir(n[3]),colno:lir(n[4]),in_app:h8n(y||"",S),platform:t}}if(e.match(f8n))return{filename:e,platform:t}};var fir=We(()=>{Fz();f8n=/^\s*[-]{4,}$/,d8n=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,p8n=/^Promise\.(?:all|any)$/,_8n=/^index \d+$/});function lpt(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function v8n(e){for(let t=1;t<=g8n;t++){let n=e.length-2*t;if(n<0)break;let s=!0;for(let c=0;c<t;c++){let u=e[n+c];if(!lpt(u,e[n+t+c])){s=!1;break}}if(s){for(let c=0;c<t;c++)e[n+c]=e[n+t+c];return e.length=n+t,{start:n,length:t}}}}function b8n(e,t){let n=t.start+t.length,s=mir(e,t);if(s)e.splice(n+s===e.length?n:t.start,s)}function _ir(e,t){let n=t.start;while(n>0&&lpt(e[n-1],e[n-1+t.length]))n--;return t.start-n}function mir(e,t){let n=t.start+t.length,s=n;while(s<e.length&&lpt(e[s],e[s-t.length]))s++;return s-n}function w8n(e,t){let n=t[0],s=e.length-(n?_ir(e,n):0);for(let c of t)s-=mir(e,c);return s}function S8n(e){let t=e.map((s)=>`${s.function}|${s.filename}|${s.lineno}|${s.colno}|${s.module}`),n=0;for(let s=1;s<t.length;s++)if(T8n(t,s,n))n=s;e.push(...e.splice(0,n))}function T8n(e,t,n){for(let s=0;s<e.length;s++){let c=e[(t+s)%e.length],u=e[(n+s)%e.length];if(c!==u)return c<u}return!1}function x8n(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,pir).map((n)=>({...n,filename:n.filename||E8n(t).filename,function:n.function||zB}))}function E8n(e){return e[e.length-1]||{}}function k8n(e,...t){return(n,s=0)=>{let c=[],u=n.split(`
|
|
342
342
|
`),d=Math.min(u.length,s+y8n),m=[];for(let T=s;T<d;T++){let C=u[T];if(C.length>1024)continue;let D=dir.test(C)?C.replace(dir,"$1"):C;if(!D.match(/\S*Error: /)){for(let L of t){let B=L(D,e);if(B){c.push(B);let z=v8n(c);if(z){for(let X=m.length-1;X>=0;X--){let K=m[X];if(K.start+K.length<=z.start)break;m.pop()}m.push(z)}break}}if(w8n(c,m)>=pir)break}}let y=[...m].sort((T,C)=>C.start-T.start),S=y[y.length-1];if(S){let T=_ir(c,S);c.splice(S.start-T,T);for(let C of y)C.start-=T}for(let T of y)b8n(c,T);if(m.some((T)=>T.start===0&&c.length===T.length))S8n(c);return x8n(c)}}var dir,pir=50,g8n=10,y8n=1000;var hir=We(()=>{Fz();sir();oir();air();cir();fir();dir=/\(error: (.*)\)/});var gir=We(()=>{jv()});class upt{match(e){return dG(e)}coerce(e,t){let n=this.getStack(e),s=n===void 0?t.syntheticException?.stack:void 0,c=!!s;return{type:this.getType(e),value:this.getMessage(e,t),stack:n??s,cause:e.cause?t.next(e.cause):void 0,synthetic:c}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let n=e.message;if(n.error&&typeof n.error.message=="string")return String(n.error.message);return String(n)}getStack(e){try{let t=e.stacktrace;if(typeof t=="string"&&t.length>0)return t;let n=e.stack;return typeof n=="string"&&n.length>0?n:void 0}catch{return}}}var yir=We(()=>{Mz()});var vir=We(()=>{jv()});class fpt{match(e){return typeof e=="string"}coerce(e,t){let[n,s]=this.getInfos(e);return{type:n??"Error",value:s??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",n=e,s=e.match(I8n);if(s)t=s[1],n=s[2];return[t,n]}}var I8n;var bir=We(()=>{I8n=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i});var wir;var Sir=We(()=>{wir=["fatal","error","warning","log","info","debug"]});function dFe(e,t=40){let n=Object.keys(e);if(n.sort(),!n.length)return"[object has no keys]";for(let s=n.length;s>0;s--){let c=n.slice(0,s).join(", ");if(!(c.length>t)){if(s===n.length)return c;return c.length<=t?c:`${c.slice(0,t)}...`}}return""}var dpt=()=>{};class ppt{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let n=this.getErrorPropertyFromObject(e);if(n)return t.apply(n);return{type:this.getType(e),value:this.getValue(e),stack:this.getStack(e)??t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(pye(e))return e.constructor.name;let t="name"in e?e.name:void 0;return FR(t)&&!Xdt(t)?t:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let s=`'${e.name}' captured as exception`;if("message"in e&&typeof e.message=="string")s+=` with message: '${e.message}'`;return s}if("message"in e&&typeof e.message=="string")return e.message;let t=this.getObjectClassName(e),n=dFe(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(e){return FR(e)&&!Xdt(e)&&wir.indexOf(e)>=0}getStack(e){try{if(FR(e.stacktrace)&&e.stacktrace.length>0)return e.stacktrace;return FR(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];if(dG(n))return n}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(t){return}}}var Tir=We(()=>{jv();Sir();dpt()});class xir{match(e){return pye(e)}coerce(e,t){let n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${dFe(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}var Eir=We(()=>{jv();dpt()});class _pt{match(e){return Ydt(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}var kir=We(()=>{jv()});var Cir=We(()=>{jv()});var Iir=We(()=>{gir();yir();vir();bir();Tir();Eir();kir();Cir()});var Air=()=>{};var Pir,_Zi;var Dir=We(()=>{jv();Pir={MESSAGE:"$message",TIMESTAMP:"$timestamp"},_Zi=new Set([Pir.MESSAGE,Pir.TIMESTAMP])});var Nir=()=>{};var mpt=We(()=>{iir();hir();Iir();Air();Dir();Nir()});var Rir=We(()=>{jv();yne()});var Mir,CZi;var mye=We(()=>{Mir=["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","oppref","bfcid","irclid","_kx"],CZi=["$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",...Mir,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"]});var Fir=()=>{};var hpt=We(()=>{Rz();jv()});var gpt=We(()=>{Fir();mye();hpt();Rz();jv();wne();yne();mpt()});var zir=We(()=>{mye();Rz();gpt();yne();jv()});function Jir(e){return X8n.test(e)}function wpt(e){return Jir(e)||Z8n.test(e)||eBn.test(e)}function lBn(e){let t=W8n.exec(e);if(!t)return!1;let n;try{n=decodeURIComponent(e.slice(t[0].length))}catch{return!1}return H8n.test(n.replace(/[\r\n]/g,""))}function vpt(e){return e.split("&",129).length>128}function uBn(e){return e.split(";").some((t)=>wpt(t.split("=",1)[0]))}function fBn(e,t,n){if(wpt(e))return"[redacted]";if(t.includes(";")&&uBn(t))return"[redacted]";if(!qir.test(t))return t;return n?Spt(t,{allowNestedUrls:!1,stripPunctuation:!0}):"[redacted]"}function Wir(e,t){let n=new URLSearchParams,s=!1,c=!1;for(let[u,d]of new URLSearchParams(e)){let m=hye(u),y=hye(d);s||=m!==u||y!==d;let S=fBn(m,y,t);s||=S!==y,c=wpt(m)||S!==y,n.append(m,S)}return{changed:s,lastFieldSensitive:c,serialized:n.toString()}}function dBn(e){let t=e.length;while(t>0&&".,;:!?)]}'".includes(e[t-1]))t--;return{address:e.slice(0,t),suffix:e.slice(t)}}function pBn(e,t,n){if(!t)return Hir(e,n);return{value:e===""?"":"[redacted]",lastFieldSensitive:!0}}function _Bn(e){let t=e.slice(1),n=t.indexOf("?");if(n<0)return{head:t,tail:null};return{head:t.slice(0,n),tail:t.slice(n+1)}}function Hir(e,t){if(!e.includes("="))return{value:mBn(e,t),lastFieldSensitive:!1};let n=Wir(e,t);return{value:n.changed?n.serialized:e,lastFieldSensitive:n.lastFieldSensitive}}function mBn(e,t){if(!t)return qir.test(e)?"[redacted]":e;return Spt(e,{allowNestedUrls:!1,stripPunctuation:!0})}function hBn(e){if(!e.includes("://"))return[];let t=[...e.matchAll(K8n)].map((m)=>m.index),n=[],s={query:!1,fragment:!1,fragmentQuery:!1},c=0,u=!1,d="";for(let m=0;m<e.length&&c<t.length;m++){if(t[c]===m){if(m>0&&d!=="=")n.push(m);c++}let y=e[m];if(gBn(y,s,d))d=y,u=!0;else if(u&&"=&".includes(y))d=y}return n}function gBn(e,t,n){if(e==="#")return t.fragment?!1:t.fragment=!0;if(e!=="?")return!1;if(t.fragment){if(n==="=")return!1;return t.fragmentQuery?!1:t.fragmentQuery=!0}return t.query?!1:t.query=!0}function yBn(e,t){let n=hBn(e);if(n.length===0)return bpt(e,t);let s="",c=0;for(let u of n)s+=bpt(e.slice(c,u),{...t,stripPunctuation:!1}),c=u;return s+bpt(e.slice(c),t)}function bpt(e,t){if(e.length>8192&&Q8n.test(e))return"[redacted]";let{address:n,suffix:s}=t.stripPunctuation?dBn(e):{address:e,suffix:""},c;try{c=new URL(n)}catch{return"[redacted]"+s}let u=c.search.slice(1),d=c.hash!=="",m=_Bn(c.hash);if(vpt(u)||vpt(m.head)||vpt(m.tail??""))return"[redacted]"+s;let y=!1;if(c.username||c.password)c.username="[redacted]",c.password="",y=!0;let S=Wir(u,t.allowNestedUrls);if(S.changed)c.search=S.serialized,y=!0;let T=Hir(m.head,t.allowNestedUrls),C=m.tail===null?null:pBn(m.tail,T.lastFieldSensitive,t.allowNestedUrls),D=C===null?T.value:`${T.value}?${C.value}`;if(D!==c.hash.slice(1))c.hash=D,y=!0;let L=d?C??T:S;return(y?hye(c.toString()):n)+(L.lastFieldSensitive?"":s)}function Spt(e,t){return e.replace(Uir,(n)=>yBn(n,{...t,stripPunctuation:t.stripPunctuation&&n.length!==e.length}))}function Gir(e){return e.length>=10240&&(q8n.test(e)||lBn(e)||J8n.test(e)&&V8n.test(e))}function hye(e){return e.replace(G8n,"[redacted]")}function Xir(e){return Spt(e,{allowNestedUrls:!0,stripPunctuation:!0})}function Yir(e,t,n){let s=4*n.maxStringLength;if(e.length>s){let c=t(e.slice(0,vBn(e,s)));if(c.length>=2*n.maxStringLength)return c+n.truncationSuffix}return t(e)}function vBn(e,t){let n=t;while(n>0&&!Y8n.test(e[n-1]))n--;return n}function bBn(e,t){return Gir(e)?"[binary data redacted - not supported by PostHog MCP analytics]":Yir(e,(n)=>Xir(hye(n)),t)}function Tpt(e,t){if(Gir(e))return"[binary data redacted - not supported by PostHog MCP analytics]";return Yir(e,(n)=>Xir(Qir(hye(n))),t)}function wBn(e){let t=0,n=!1;for(let s=e.length-1;s>=0;s--){let c=e.charCodeAt(s)-48;if(c<0||c>9)return!1;if(n){if(c*=2,c>9)c-=9}t+=c,n=!n}return t%10===0}function SBn(e){let t=[];for(let u=$ir.exec(e);u!==null;u=$ir.exec(e))t.push({digits:u[0],start:u.index,end:u.index+u[0].length});let n="",s=0,c=0;while(c<t.length){let u="",d=-1;for(let m=c;m<t.length;m++){if(u+=t[m].digits,u.length>19)break;if(u.length>=13&&wBn(u))d=m}if(d>=0)n+=e.slice(s,t[c].start)+"[redacted]",s=t[d].end,c=d+1;else c++}return n+e.slice(s)}function Qir(e){let t=e.replace(tBn," ");return t=t.replace(rBn,"[redacted]"),t=t.replace(nBn,"[redacted]"),t=t.replace(iBn,"$1[redacted]"),t=t.replace(oBn,SBn),t=t.replace(sBn,"[redacted]"),t=t.replace(aBn,"$1[redacted]"),t=t.replace(cBn,"$1[redacted]"),t}function Kir(e,t){return pFe(e,(n)=>bBn(n,t))}function Zir(e,t){return pFe(e,(n)=>Tpt(n,t))}function pFe(e,t){if(e==null)return e;if(typeof e=="string")return t(e);if(Array.isArray(e))return e.map((s)=>pFe(s,t));if(e instanceof Date)return e;if(typeof e!="object")return e;let n={};for(let[s,c]of Object.entries(e))n[s]=Jir(s)?"[redacted]":pFe(c,t);return n}var q8n,V8n,J8n,W8n,H8n,G8n,X8n,Uir,Y8n,qir,Vir,Q8n,K8n,Z8n,eBn,tBn,rBn,nBn,iBn,sBn,oBn,$ir,aBn,cBn;var esr=We(()=>{q8n=/^[A-Za-z0-9+/\n\r]+=*$/,V8n=/^[A-Za-z0-9_-]+={0,2}$/,J8n=/[-_]/,W8n=/^data:[^,\s]*;base64,/i,H8n=/^[A-Za-z0-9+/_-]+={0,2}$/,G8n=/\bph[a-z]_[A-Za-z0-9_-]{20,}\b/g,X8n=/^(authorization|cookie|set-cookie|x-api-key|api[-_]?key|api[-_]?token|access[-_]?token|refresh[-_]?token|token|password|secret|client[-_]?secret|private[-_]?key)$/i,Uir=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi,Y8n=/[\s<>"]/,qir=new RegExp(Uir.source,"i"),Vir=/[a-z][a-z0-9+.-]{0,63}:\/\//i,Q8n=new RegExp(`^${Vir.source}`,"i"),K8n=new RegExp(Vir.source,"gi"),Z8n=/(^|[-_./;])(auth|token|secret|password|passwd|pwd|credential|signature|sig|key|hmac|sas|bearer|jwt|session|sessionid)([-_./;]|$)/i,eBn=/^(code|AWSAccessKeyId|GoogleAccessId|Policy)$/i,tBn=/[\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]/g,rBn=/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,nBn=/\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b/g,iBn=/(^|[^\w:])((?:(?:[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}){0,5}|::(?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4}){0,6})))(?=$|[^\w:])/g,sBn=/\b\d{3}[ .-]\d{2}[ .-]\d{4}\b/g,oBn=/\b\d(?:[ ./-]?\d){12,}\b/g,$ir=/\d+/g,aBn=/(^|[^\w+])((?:\+?1[ ./-]?)?(?:\(\d{3}\)[ ./-]?|\d{3}[ ./-])\d{3}[ ./-]\d{4})(?![\w])/g,cBn=/(^|[^\w])(\+\d{1,3}(?:[ ./()-]{0,2}\d){7,13})(?![\w])/g});var tsr=We(()=>{Mz()});var rsr=We(()=>{mye()});var Tne=We(()=>{Mz();jB()});var gye=We(()=>{jB();Tne()});var CBn,Nes;var kpt=We(()=>{jv();jB();Tne();gye();CBn={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}},Nes=CBn.info});var mFe=We(()=>{jv()});var hFe=()=>{};var dsr=We(()=>{kpt();Rz();jv();mFe();wne();hFe()});var Cpt=()=>{};var gFe=We(()=>{Cpt()});var psr=We(()=>{gye()});var _sr=()=>{};var msr=We(()=>{jv();mFe();wne();hFe();Tne();gFe();psr();_sr()});var Ipt=()=>{};var yFe=We(()=>{gFe();Ipt();jv();jB()});var hsr=We(()=>{yFe();Tne();jB();gye()});var gsr=We(()=>{yFe();Cpt();gFe();Ipt();jB();hsr();jv();mFe();wne();hFe()});var ysr=()=>{};var vsr=We(()=>{jB()});var bsr=We(()=>{Rz()});var xne=We(()=>{mpt();mye();rsr();hpt();kpt();Tne();gye();dsr();msr();gsr();ysr();yFe();vsr();yne();bsr();jv();Rir();zir();gpt();esr();tsr();Rz()});function JBn(e,t){if(e)try{e(t)}catch{}}function zv(e){JBn(VBn,e)}var VBn;var BR=()=>{};var wsr=`Explain in 15-25 words, in third person, why this tool is called and how it supports the user's goal. For analytics only. You MUST describe only the abstract purpose of the tool call. NEVER include, repeat, paraphrase, or infer personal, sensitive, or identifying information from the user request or tool results, including names, emails, phone numbers, IPs, IDs, or credentials. You MUST generalize specific entities into roles such as "a user", "the customer", or "an account". Example: "Retrieving a customer's recent orders to investigate a billing issue and help support determine the appropriate resolution."`,Ssr='The exact model identifier you (the assistant) are running as, taken from your system prompt or environment (e.g. "claude-opus-4-8", "gpt-5.2"). Used for analytics only. If you do not know your model identifier with certainty, pass "unknown" \u2014 never guess.',Tsr="Pass the exact conversation_id from the server's previous response, unchanged. The server provides it on the first call \u2014 never invent one, and do not issue parallel tool calls until you have it. Keep passing the same conversation_id for the rest of the conversation, including after later user messages or on a different task; do not reset it when the user starts a new request.",Apt="posthog_mcp_analytics",xsr="posthog-node-mcp",B2,ou;var jR=We(()=>{B2={Custom:"$mcp_custom",Exception:"$exception",Feedback:"$mcp_feedback",Identify:"$identify",Initialize:"$mcp_initialize",MissingCapability:"$mcp_missing_capability",PromptGet:"$mcp_prompt_get",PromptsList:"$mcp_prompts_list",ResourceRead:"$mcp_resource_read",ResourcesList:"$mcp_resources_list",ToolCall:"$mcp_tool_call",ToolsList:"$mcp_tools_list"},ou={ClientName:"$mcp_client_name",ClientUserAgent:"$mcp_client_user_agent",ClientVersion:"$mcp_client_version",ConversationId:"$mcp_conversation_id",DurationMs:"$mcp_duration_ms",ErrorMessage:"$mcp_error_message",ErrorType:"$mcp_error_type",FeedbackDetails:"$mcp_feedback_details",FeedbackFrictionPoints:"$mcp_feedback_friction_points",FeedbackSentiment:"$mcp_feedback_sentiment",FeedbackSuggestedImprovement:"$mcp_feedback_suggested_improvement",FeedbackSummary:"$mcp_feedback_summary",FeedbackTaskCompleted:"$mcp_feedback_task_completed",FeedbackTool:"$mcp_feedback_tool",FeedbackType:"$mcp_feedback_type",Interface:"$mcp_interface",IsError:"$mcp_is_error",InputAliasesUsed:"$mcp_input_aliases_used",InputKeys:"$mcp_input_keys",Intent:"$mcp_intent",IntentSource:"$mcp_intent_source",ListedToolNames:"$mcp_listed_tool_names",LlmModel:"$mcp_llm_model",LlmModelSource:"$mcp_llm_model_source",Parameters:"$mcp_parameters",ProtocolVersion:"$mcp_protocol_version",ResourceName:"$mcp_resource_name",Response:"$mcp_response",ServerBuild:"$mcp_server_build",ServerName:"$mcp_server_name",ServerVersion:"$mcp_server_version",SessionId:"$session_id",Source:"$mcp_source",ToolCategory:"$mcp_tool_category",ToolDescription:"$mcp_tool_description",ToolName:"$mcp_tool_name",VendorClient:"$mcp_vendor_client"}});var th;var Lz=We(()=>{th={custom:"posthog:custom",mcpFeedback:"mcp:feedback",mcpMissingCapability:"mcp:missing_capability",mcpInitialize:"mcp:initialize",mcpPromptsGet:"mcp:prompts/get",mcpPromptsList:"mcp:prompts/list",mcpResourcesList:"mcp:resources/list",mcpResourcesRead:"mcp:resources/read",mcpToolsCall:"mcp:tools/call",mcpToolsList:"mcp:tools/list"}});function Esr(e){return e.identifyActorGivenId||e.sessionId||"anonymous"}function ksr(e){return e.timestamp?e.timestamp.toISOString():new Date().toISOString()}function Csr(e,t={}){let n=[HBn(e)];if(e.isError&&e.error&&t.enableExceptionAutocapture!==!1)n.push(XBn(e));return n}function HBn(e){let t=Esr(e),n=ksr(e),s={[ou.Interface]:"mcp",[ou.Source]:Apt};return Isr(e,s),Asr(e,s),Dsr(e,s),Psr(e,s),GBn(e,s),Nsr(e,s),Osr(e,s),{event:e.eventName??WBn[e.eventType],distinct_id:t,properties:s,timestamp:n,type:"capture"}}function Isr(e,t){if(typeof e.sessionId=="string"&&e.sessionId.length>0)t[ou.SessionId]=e.sessionId}function Asr(e,t){if(e.conversationId!==void 0&&e.conversationId!=="")t[ou.ConversationId]=e.conversationId}function Psr(e,t){if(e.groups&&Object.keys(e.groups).length>0)t.$groups=e.groups}function Dsr(e,t){if(!e.identifyActorGivenId)t.$process_person_profile=!1}function GBn(e,t){if(e.resourceName){if(t[ou.ResourceName]=e.resourceName,e.eventType===th.mcpToolsCall)t[ou.ToolName]=e.resourceName}if(e.toolDescription&&e.eventType===th.mcpToolsCall)t[ou.ToolDescription]=e.toolDescription;if(e.toolCategory&&e.eventType===th.mcpToolsCall)t[ou.ToolCategory]=e.toolCategory;if(e.listedToolNames&&e.listedToolNames.length>0&&e.eventType===th.mcpToolsList)t[ou.ListedToolNames]=e.listedToolNames;if(e.duration!==void 0)t[ou.DurationMs]=e.duration;if(e.serverName)t[ou.ServerName]=e.serverName;if(e.serverVersion)t[ou.ServerVersion]=e.serverVersion;if(e.clientName)t[ou.ClientName]=e.clientName;if(e.clientVersion)t[ou.ClientVersion]=e.clientVersion;if(e.clientUserAgent)t[ou.ClientUserAgent]=e.clientUserAgent;if(e.vendorClient)t[ou.VendorClient]=e.vendorClient;if(e.protocolVersion)t[ou.ProtocolVersion]=e.protocolVersion;if(e.userIntent)t[ou.Intent]=e.userIntent;if(e.userIntentSource)t[ou.IntentSource]=e.userIntentSource;if(e.llmModel)t[ou.LlmModel]=e.llmModel;if(e.llmModelSource)t[ou.LlmModelSource]=e.llmModelSource;if(e.isError!==void 0)t[ou.IsError]=e.isError;if(e.isError){let n=e.error?.$exception_list?.[0],s=e.errorType??n?.type;if(s)t[ou.ErrorType]=s;if(n?.value)t[ou.ErrorMessage]=n.value}if(e.parameters!==void 0)t[ou.Parameters]=e.parameters;if(e.response!==void 0)t[ou.Response]=e.response;if(e.identifyActorData&&Object.keys(e.identifyActorData).length>0)t.$set={...e.identifyActorData}}function Nsr(e,t){if(e.properties)for(let[n,s]of Object.entries(e.properties))t[n]=s}function Osr(e,t){if(e.serverBuild)t[ou.ServerBuild]=e.serverBuild}function XBn(e){let t=Esr(e),n=ksr(e),s={[ou.Interface]:"mcp"};if(Isr(e,s),Asr(e,s),Dsr(e,s),Psr(e,s),e.error)Object.assign(s,e.error);if(e.resourceName){if(s[ou.ResourceName]=e.resourceName,e.eventType===th.mcpToolsCall)s[ou.ToolName]=e.resourceName}if(e.toolDescription&&e.eventType===th.mcpToolsCall)s[ou.ToolDescription]=e.toolDescription;if(e.toolCategory&&e.eventType===th.mcpToolsCall)s[ou.ToolCategory]=e.toolCategory;if(e.serverName)s[ou.ServerName]=e.serverName;if(e.serverVersion)s[ou.ServerVersion]=e.serverVersion;if(e.clientName)s[ou.ClientName]=e.clientName;if(e.clientVersion)s[ou.ClientVersion]=e.clientVersion;if(e.clientUserAgent)s[ou.ClientUserAgent]=e.clientUserAgent;if(e.vendorClient)s[ou.VendorClient]=e.vendorClient;if(e.protocolVersion)s[ou.ProtocolVersion]=e.protocolVersion;return Nsr(e,s),Osr(e,s),{event:B2.Exception,distinct_id:t,properties:s,timestamp:n,type:"capture"}}var WBn;var Rsr=We(()=>{jR();Lz();WBn={[th.custom]:B2.Custom,[th.mcpFeedback]:B2.Feedback,[th.mcpMissingCapability]:B2.MissingCapability,[th.mcpInitialize]:B2.Initialize,[th.mcpPromptsGet]:B2.PromptGet,[th.mcpPromptsList]:B2.PromptsList,[th.mcpResourcesList]:B2.ResourcesList,[th.mcpResourcesRead]:B2.ResourceRead,[th.mcpToolsCall]:B2.ToolCall,[th.mcpToolsList]:B2.ToolsList}});function Ppt(e){return`${e}_${LR()}`}function Fsr(e,t){return`${e}_${Msr(t)}${Msr(`${t}::salt`)}`}function Msr(e){let t=2216829733,n=3421674724;for(let s=0;s<e.length;s++){let c=e.charCodeAt(s);t=Math.imul(t^c,435),n=Math.imul(n^c,403)}return(t>>>0).toString(16).padStart(8,"0")+(n>>>0).toString(16).padStart(8,"0")}var Dpt=We(()=>{xne()});function yye(e,t=10,n=100,s=32768){return Rpt(e,t,n,s,new WeakSet)}function Rpt(e,t,n,s,c){if(e===null)return null;if(e===void 0)return"[undefined]";if(typeof e=="boolean")return e;if(typeof e=="number"){if(Number.isNaN(e))return"[NaN]";if(!Number.isFinite(e))return e>0?"[Infinity]":"[-Infinity]";return e}if(typeof e=="bigint")return`[BigInt: ${e}]`;if(typeof e=="string"){if(e.length>s)return e.slice(0,s)+"...";return e}if(typeof e=="symbol"){let u=e.description;return u?`[Symbol(${u})]`:"[Symbol()]"}if(typeof e=="function")return`[Function: ${e.name||"<anonymous>"}]`;if(e instanceof Date)return Number.isNaN(e.getTime())?"[Invalid Date]":e.toISOString();if(typeof e=="object"){if(c.has(e))return"[Circular ~]";if(t<=0)return Array.isArray(e)?"[Array]":"[Object]";c.add(e);let u;return u=Array.isArray(e)?YBn(e,t-1,n,s,c):QBn(e,t-1,n,s,c),c.delete(e),u}return String(e)}function YBn(e,t,n,s,c){let u=[];for(let d=0;d<e.length;d++){if(d>=n){u.push("[MaxProperties ~]");break}u.push(Rpt(e[d],t,n,s,c))}return u}function QBn(e,t,n,s,c){let u={},d=Object.keys(e),m=0;for(let y of d){if(m>=n){u["..."]="[MaxProperties ~]";break}if(e[y]!==void 0)u[y]=Rpt(e[y],t,n,s,c),m++}return u}function zR(e,t){if(e==null)return e;if(e.length<=t)return e;return e.slice(0,t)+"..."}function KBn(e){if(!e||e.length<=50)return e;let t=Math.floor(25);return[...e.slice(0,t),...e.slice(-t)]}function ZBn(e){if(!Array.isArray(e.$exception_list))return e;return{...e,$exception_list:e.$exception_list.map((t)=>{let n={...t};if(typeof n.value=="string")n.value=zR(n.value,2048);if(n.stacktrace?.frames)n.stacktrace={...n.stacktrace,frames:KBn(n.stacktrace.frames)};return n})}}function e5n(e){if(e==null||typeof e!="object")return e;let t={...e};if(Array.isArray(t.content))t.content=t.content.map((n)=>{if(n!=null&&typeof n=="object"&&"type"in n&&"text"in n&&n?.type==="text"&&typeof n.text=="string"&&n.text.length>32768)return{...n,text:n.text.slice(0,32768)+"..."};return n});return t}function Npt(e){return t5n.encode(JSON.stringify(e)).length}function r5n(e,t){let n=structuredClone(e);for(let s=0;s<10;s++){let c=Npt(n);if(c<=t)break;let u=c-t,d=[];if(Opt(n,[],d),d.sort((S,T)=>T.length-S.length),d.length===0)break;let m=u+200,y=!1;for(let{path:S,length:T}of d){if(m<=0)break;let C=Math.min(m,Math.floor(0.5*T));if(C<10)continue;let D=T-C,L=n5n(n,S);if(typeof L=="string")i5n(n,S,L.slice(0,D)+"..."),m-=C,y=!0}if(!y)break}return n}function Opt(e,t,n){if(t.length===1&&t[0]==="serverBuild")return;if(typeof e=="string"&&e.length>100)return void n.push({path:[...t],length:e.length});if(Array.isArray(e)){for(let[s,c]of e.entries())Opt(c,[...t,String(s)],n);return}if(e!=null&&typeof e=="object")for(let[s,c]of Object.entries(e))Opt(c,[...t,s],n)}function n5n(e,t){let n=e;for(let s of t){if(n==null||typeof n!="object")return;n=n[s]}return n}function i5n(e,t,n){let s=e;for(let u=0;u<t.length-1;u++){if(s==null||typeof s!="object")return;s=s[t[u]]}let c=t.at(-1);if(c!==void 0&&s!=null&&typeof s=="object")s[c]=n}function s5n(e){if(Npt(e)<=102400)return e;let t=Math.max(...jsr.map((s)=>zsr(e[s]))),n;for(let s=t-1;s>=1;s--){let c=Lsr(e,s);if(Npt(c)<=102400)return c;if(s===1)n=c}return r5n(n??Lsr(e,1),102400)}function zsr(e,t=10){if(t===0||e===null||typeof e!="object")return 0;let n=0;for(let s of Array.isArray(e)?e:Object.values(e))if(n=Math.max(n,zsr(s,t-1)),n===t-1)break;return n+1}function Lsr(e,t){let n={...e};for(let s of jsr)if(n[s]!=null)n[s]=yye(n[s],t);return n}function $sr(e){let t={...e};if(t.userIntent=zR(t.userIntent,2048),t.resourceName=zR(t.resourceName,256),t.serverName=zR(t.serverName,256),t.serverVersion=zR(t.serverVersion,256),t.clientName=zR(t.clientName,256),t.clientVersion=zR(t.clientVersion,256),t.clientUserAgent=zR(t.clientUserAgent,256),t.vendorClient=zR(t.vendorClient,256),t.errorType=zR(t.errorType,256),t.llmModel=zR(t.llmModel,256),t.error!=null&&typeof t.error=="object")t.error=ZBn(t.error);if(t.response=e5n(t.response),t.parameters!=null)t.parameters=yye(t.parameters);if(t.response!=null)t.response=yye(t.response);if(t.identifyActorData!=null)t.identifyActorData=yye(t.identifyActorData);if(t.error!=null)t.error=yye(t.error);return s5n(t)}var Bsr=32768,vFe="...",t5n,jsr;var bFe=We(()=>{t5n=new TextEncoder;jsr=["parameters","response","identifyActorData","error"]});function vye(e){return Tpt(e,Mpt)}function $R(e){return Kir(e,Mpt)}function Usr(e){return Zir(e,Mpt)}var Mpt;var wFe=We(()=>{xne();bFe();Mpt={maxStringLength:Bsr,truncationSuffix:vFe}});function Fpt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function qsr(e){let t={...e};if(t.response!=null)t.response=a5n(t.response);if(t.parameters!=null)t.parameters=u5n(t.parameters);if(t.resourceName!=null)t.resourceName=$R(t.resourceName);if(t.userIntent!=null)t.userIntent=vye(t.userIntent);if(t.llmModel!=null)t.llmModel=$R(t.llmModel);if(t.error!=null)t.error=o5n(t.error);return t}function o5n(e){if(!Array.isArray(e.$exception_list))return e;return{...e,$exception_list:e.$exception_list.map((t)=>({...t,value:$R(t.value)}))}}function a5n(e){if(Fpt(e)&&Array.isArray(e.content)){let t=$R({...e,content:[]});return t.content=e.content.map(c5n),t}return $R(e)}function c5n(e){if(!Fpt(e))return $R(e);switch(e.type){case"text":case"resource_link":return $R(e);case"image":return{type:"text",text:"[image content redacted - not supported by PostHog MCP analytics]"};case"audio":return{type:"text",text:"[audio content redacted - not supported by PostHog MCP analytics]"};case"resource":return l5n(e);default:return{type:"text",text:`[unsupported content type "${$R(e.type)}" redacted - not supported by PostHog MCP analytics]`}}}function l5n(e){if(Fpt(e.resource)&&"blob"in e.resource)return{type:"text",text:"[binary resource content redacted - not supported by PostHog MCP analytics]"};return $R(e)}function u5n(e){return $R(e)}var Vsr=We(()=>{wFe()});async function f5n(e,t,n=zv){let s=e;try{s=qsr(s)}catch(m){return n(`Failed to sanitize event: ${m}`),null}try{s=$sr(s)}catch(m){return n(`Failed to truncate event: ${m}`),null}s.id=s.id||Ppt("evt");let c=s,u=Csr(c,{enableExceptionAutocapture:t.enableExceptionAutocapture}),d=await d5n(u,t.beforeSend,n);return{event:c,captures:d}}async function d5n(e,t,n){if(!t)return e;let s=[];for(let c of e)try{let u=await t(c);if(u)s.push(u)}catch(u){n(`beforeSend threw for event ${c.event}; dropping it: ${u}`)}return s}class SFe{constructor(e,t=zv){this.posthog=e,this.logger=t}async capture(e,t){let n=await f5n(e,t,this.logger);if(!n)return;let{event:s,captures:c}=n;try{for(let u of c){let d=u.properties.$groups;this.posthog.capture({distinctId:u.distinct_id,event:u.event,properties:u.properties,...d?{groups:d}:{},timestamp:new Date(u.timestamp),uuid:LR()})}this.logger(`Captured PostHog event ${s.id} | ${s.eventType} | ${s.duration} ms | ${s.identifyActorGivenId?"identified":"anonymous"}`)}catch(u){this.logger(`Failed to capture PostHog event ${s.id}: ${u}`)}}}var Lpt=We(()=>{xne();BR();Rsr();Dpt();Vsr();bFe()});var Bz=()=>{};var Bpt="0.23.0";var jpt=()=>{};function zpt(e){let t=Array.isArray(e)?e[0]:e;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0}var bye=()=>{};var Ene=()=>{};var $pt=We(()=>{Gdt();bye();Ene()});var xFe=We(()=>{bye()});function Gsr(e){return Fsr("ses",e)}var Sye=We(()=>{jpt();jR();Dpt();$pt();Bz();Ene();xFe()});var Upt=We(()=>{Lz();Bz();Sye()});function qpt(e){e.getLibraryId=()=>xsr,e.getLibraryVersion=()=>Bpt}var Vpt=We(()=>{jpt();jR()});function Jpt(e){if(e===void 0)return;if(typeof e!="string"||e.length===0)throw TypeError("serverBuild must be a non-empty string.");if(e.length>256)throw RangeError("serverBuild must not exceed 256 characters.");return e}var Wpt=()=>{};function kne(e){if(!e)return;return e===!0?{}:e}function mG(e={}){let t=e.extraProperties??{},n=e.extraRequired??[];for(let c of Object.keys(t))if(h5n.has(c))throw Error(`collectFeedback.extraProperties key "${c}" collides with a core or SDK-reserved send_feedback field. Rename it.`);for(let c of n)if(!Object.prototype.hasOwnProperty.call(t,c))throw Error(`collectFeedback.extraRequired key "${c}" is not declared in extraProperties.`);let s=Object.keys(t).length>0?JSON.parse(JSON.stringify(t)):void 0;return{name:e.toolName??_G,description:e.description??m5n,inputSchema:{type:"object",properties:{...JSON.parse(JSON.stringify(Ksr)),...s},required:["feedback_type","summary",...n]},annotations:{title:"Send feedback",readOnlyHint:!0,openWorldHint:!0,idempotentHint:!0,destructiveHint:!1}}}function Tye(e){return typeof e=="string"&&e.trim()?e:void 0}function g5n(e){return Ysr.includes(e)?e:"other"}function y5n(e){return Qsr.includes(e)?e:void 0}function v5n(e,t){let n=Array.isArray(e)?"array":e===null?"null":typeof e;if(t.type==="integer"){if(!Number.isInteger(e))return!1}else if(t.type!==n)return!1;return!Array.isArray(t.enum)||t.enum.includes(e)}function CFe(e,t={}){let n=e??{},s={};for(let[c,u]of Object.entries(t.extraProperties??{}))if(n[c]!==void 0&&v5n(n[c],u))s[c]=n[c];return{feedbackType:g5n(n.feedback_type),summary:Tye(n.summary)??"",sentiment:y5n(n.sentiment),frictionPoints:Tye(n.friction_points),suggestedImprovement:Tye(n.suggested_improvement),details:Tye(n.details),toolName:Tye(n.tool_name),taskCompleted:typeof n.task_completed=="boolean"?n.task_completed:void 0,extras:s,raw:n}}function IFe(e){return[e.summary,e.details].filter(Boolean).join(`
|
|
343
343
|
|
|
344
344
|
`)}function kFe(e,t){return e.length>t?e.slice(0,t)+vFe:e}function EFe(e){return kFe(vye(e),Hpt)}function b5n(e){let t=Usr(e);if(typeof t=="string")return kFe(t,Hpt);if(t==null||typeof t=="number"||typeof t=="boolean")return t;try{return kFe(JSON.stringify(t),Hpt)}catch{return}}function AFe(e){let t={[ou.FeedbackType]:e.feedbackType};if(e.summary)t[ou.FeedbackSummary]=EFe(e.summary);if(e.sentiment)t[ou.FeedbackSentiment]=e.sentiment;if(e.frictionPoints)t[ou.FeedbackFrictionPoints]=EFe(e.frictionPoints);if(e.suggestedImprovement)t[ou.FeedbackSuggestedImprovement]=EFe(e.suggestedImprovement);if(e.details)t[ou.FeedbackDetails]=EFe(e.details);if(e.toolName)t[ou.FeedbackTool]=kFe(vye(e.toolName),_5n);if(e.taskCompleted!==void 0)t[ou.FeedbackTaskCompleted]=e.taskCompleted;for(let[n,s]of Object.entries(e.extras)){let c=b5n(s);if(c!==void 0)t[`$mcp_feedback_${n}`]=c}return t}var _G="send_feedback",Ysr,Qsr,Hpt=2048,_5n=256,m5n='Send feedback about this server to its developers. Most important: report a missing capability whenever no available tool fits your task, even if you can work around it (feedback_type "missing_capability"). Also welcome: a tool that failed or confused you, an unhelpful error, or something that worked well. This records the feedback; it does not add or change tools. Do not include user PII or sensitive content.',Ksr,h5n;var Cne=We(()=>{jR();BR();wFe();bFe();Ysr=["missing_capability","issue","praise","other"],Qsr=["positive","neutral","negative","mixed"],Ksr={feedback_type:{type:"string",enum:[...Ysr],description:"What kind of feedback this is. Use 'missing_capability' when the tool you needed does not exist in the tool list - nothing failed, the capability is absent (this is the most valuable report; send it even if you found a workaround). Use 'issue' when an existing tool behaved badly: it failed, returned a confusing error, or its description or schema misled you. Use 'praise' when something worked notably well. Use 'other' for anything else."},summary:{type:"string",description:"One self-contained sentence. For 'missing_capability': the capability you needed, e.g. 'No tool to delete multiple cohorts in one call.' For 'issue': the tool and the problem, e.g. 'query-trends rejects relative date ranges with an unclear error.'"},details:{type:"string",description:"Optional longer context: what you tried, exact parameter values, the error text you saw, and any workaround you used. Omit when the summary says it all."},friction_points:{type:"string",description:"Optional: the specific moments that slowed you down, as short bullet-like sentences, quoting exact tool names, parameters, or error text."},suggested_improvement:{type:"string",description:"Optional: the concrete change that would have helped, e.g. the tool to add, the description to reword, or the error message to improve."},tool_name:{type:"string",description:"Optional: the existing tool this feedback is about (for 'issue' or 'praise'). Leave empty for 'missing_capability' - the point is that no tool fits."},sentiment:{type:"string",enum:[...Qsr],description:"Optional: how the experience felt overall."},task_completed:{type:"boolean",description:"Optional: whether you still completed the user's task despite the problem."}},h5n=new Set([...Object.keys(Ksr),"type","tool","context","conversation_id","llm_model"])});function w5n(e){if(!e||typeof e!="object")return!1;return!!e._zod}function Zsr(e){return!!e&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function Gpt(e){return!!e&&typeof e=="object"&&!Zsr(e)&&Object.values(e).some(Zsr)}function Xpt(e){if(!e||typeof e!="object")return;let t;if(w5n(e))t=e._zod?.def?.shape;else{let n=e;t=n.shape??n._def?.shape}if(!t)return;if(typeof t=="function")try{return t()}catch{return}return t}var xye=()=>{};function Qpt(e){if(!e||typeof e!="object")return!1;if(E5n(e))return!1;let t=e;if(t.$ref||t.oneOf||t.allOf||t.anyOf)return!1;let{properties:n}=t;if(n!==void 0&&(typeof n!="object"||n===null||Array.isArray(n)))return!1;return!n||!Object.prototype.hasOwnProperty.call(n,hG)}function Ypt(e){return!!e&&typeof e=="object"&&(("_def"in e)||("_zod"in e)||("~standard"in e))}function x5n(e){if(typeof e.type=="string"||typeof e.$ref=="string")return!0;if(Array.isArray(e.oneOf)||Array.isArray(e.allOf)||Array.isArray(e.anyOf))return!0;let{properties:t}=e;return!!t&&typeof t=="object"&&!Ypt(t)}function E5n(e){let t=e;if(Ypt(t))return!0;if(x5n(t))return!1;return Object.values(t).some(Ypt)}function k5n(e,t=zv){let n=e.name||"unknown",s=e.outputSchema;if(!s||typeof s!="object")return e;if(!Qpt(s)){let d=s;return t(d.properties&&Object.prototype.hasOwnProperty.call(d.properties,hG)?`WARN: Tool "${n}" already declares '${hG}' in its output schema. Leaving it alone.`:`WARN: Tool "${n}" has a complex output schema (oneOf/allOf/anyOf/$ref). Skipping '${hG}' declaration; its session handle stays content-only.`),e}let c={...e},u=JSON.parse(JSON.stringify(s));if(!u.properties)u.properties={};return u.properties[hG]={type:"object",description:S5n,properties:{conversation_id:{type:"string",description:T5n}}},c.outputSchema=u,c}function Kpt(e,t=zv){return e.map((n)=>k5n(n,t))}function C5n(e){return{conversation_id:e}}function Zpt(e,t){if(!e||typeof e!="object")return e;let n=e.structuredContent;if(!n||typeof n!="object"||Array.isArray(n))return e;if(Object.prototype.hasOwnProperty.call(n,hG))return e;return{...e,structuredContent:{...n,[hG]:C5n(t)}}}var hG="_mcp_instructions",S5n="Server-issued metadata for this conversation.",T5n="The server-issued conversation identifier.";var PFe=We(()=>{BR()});function NFe(e,t){return!!e?.properties&&Object.prototype.hasOwnProperty.call(e.properties,t)}function $B(e,t){return!NFe(e,t)&&!e?.$ref&&!e?.oneOf&&!e?.allOf&&!e?.anyOf}function OFe(e,t,n,s,c=zv){let u={...e},d=e.name||"unknown",m=u.inputSchema;if(!$B(m,t))return c(NFe(m,t)?`WARN: Tool "${d}" already has '${t}' parameter. Skipping ${s} injection.`:`WARN: Tool "${d}" has complex schema (oneOf/allOf/anyOf/$ref). Skipping ${s} injection.`),u;if(!u.inputSchema)u.inputSchema={type:"object",properties:{},required:[]};u.inputSchema=JSON.parse(JSON.stringify(u.inputSchema));let y=u.inputSchema;if(!y.properties)y.properties={};if(y.additionalProperties===!1)y.additionalProperties=void 0;if(y.properties[t]={type:"string",description:n},Array.isArray(y.required)){if(!y.required.includes(t))y.required.push(t)}else y.required=[t];return u}function DFe(e,t){if(!e||typeof e!="object")return $B(void 0,t);if(Gpt(e))return $B({properties:e},t);let n=Xpt(e);if(n)return $B({properties:n},t);let s=e;if(I5n.some((c)=>Object.prototype.hasOwnProperty.call(s,c)))return $B(s,t);if("_def"in s||"_zod"in s||"~standard"in s)return $B(void 0,t);return $B(s,t)}function Ine(e,t){return{context:DFe(e,"context"),conversationId:DFe(e,"conversation_id"),llmModel:DFe(e,"llm_model"),outputInstructions:Qpt(t)}}function RFe(e,t){let n=e;if(t.context&&n&&typeof n=="object"&&"context"in n){let{context:s,...c}=n;n=c}if(t.conversationId&&n&&typeof n=="object"&&"conversation_id"in n){let{conversation_id:s,...c}=n;n=c}if(t.llmModel&&n&&typeof n=="object"&&"llm_model"in n){let{llm_model:s,...c}=n;n=c}return n}var I5n;var jz=We(()=>{BR();xye();PFe();I5n=["$defs","$ref","additionalProperties","allOf","anyOf","definitions","oneOf","properties","required","type"]});function Eye(e=e_t){return{name:e,description:"Check for additional tools whenever your task might benefit from specialized capabilities - even if existing tools could work as a fallback.",inputSchema:{type:"object",properties:{context:{type:"string",description:"A description of your goal and what kind of tool would help accomplish it."}},required:["context"]},annotations:{title:"Get More Tools",readOnlyHint:!0,openWorldHint:!0,idempotentHint:!0,destructiveHint:!1}}}var e_t="get_more_tools";var Ane=We(()=>{BR()});function kye(e){return e!==!1}function t_t(e){return typeof e=="object"?e.description:void 0}function A5n(e,t,n=zv){return OFe(e,"context",t||wsr,"context",n)}function r_t(e,t,n=zv){return e.map((s)=>A5n(s,t,n))}var Cye=We(()=>{jz();jR();BR()});function Pne(e){return e===void 0||e===!0||typeof e=="object"&&e!==null}function n_t(e){return typeof e=="object"&&e!==null?e.description:void 0}function eor(e,t,n=zv){return OFe(e,"llm_model",t||Ssr,"model",n)}function P5n(e){return s_t(e.params?.arguments?.llm_model)}function i_t(e,t){let n=e.params?._meta?.[D5n];if(N5n(n)&&Object.prototype.hasOwnProperty.call(n,"model")){let s=s_t(n.model);if(s)return{model:s,source:"client_metadata"}}if(t){let s=P5n(e);if(s)return{model:s,source:"self_reported"}}}function N5n(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function s_t(e){if(typeof e!="string")return;let t=e.trim();if(!t||t.toLowerCase()==="unknown")return;return t}function Iye(e,t,n="self_reported"){let s=s_t(t);if(!s)return;e.llmModel=s,e.llmModelSource=n}var D5n="x-codex-turn-metadata";var MFe=We(()=>{jz();jR();BR()});function O5n(e,t=zv){let n={...e},s=e.name||"unknown",c=n.inputSchema;if(!$B(c,Aye))return t(NFe(c,Aye)?`WARN: Tool "${s}" already has '${Aye}' parameter. Skipping conversation_id injection.`:`WARN: Tool "${s}" has complex schema (oneOf/allOf/anyOf/$ref). Skipping conversation_id injection.`),n;if(!n.inputSchema)n.inputSchema={type:"object",properties:{},required:[]};n.inputSchema=JSON.parse(JSON.stringify(n.inputSchema));let u=n.inputSchema;if(!u.properties)u.properties={};if(u.additionalProperties===!1)u.additionalProperties=void 0;return u.properties[Aye]={type:"string",description:Tsr},n}function o_t(e,t=zv){return e.map((n)=>O5n(n,t))}function a_t(e,t){if(!e)return{minted:!1,conversationId:void 0};let n=M5n(t);if(n&&R5n.test(n))return{minted:!1,conversationId:n.toLowerCase()};return{minted:!0,conversationId:LR()}}function FFe(e){if(!(e&&typeof e=="object"))return!1;return Array.isArray(e.content)}function M5n(e){if(!(e&&typeof e=="object"))return;let t=e[Aye];if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0}function F5n(e){return{type:"text",text:JSON.stringify({conversation_id:e})}}function c_t(e,t){if(!FFe(e))return e;let n=e;return{...n,content:[...n.content,F5n(t)]}}var Aye="conversation_id",R5n;var l_t=We(()=>{xne();jz();jR();BR();R5n=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i});var tor=We(()=>{bye();Ene()});function LFe(e){let t=B5n(e)?z5n(e):e;return L5n.buildFromUnknown(t)}function B5n(e){return e!==null&&typeof e=="object"&&"isError"in e&&"content"in e&&Array.isArray(e.content)}function j5n(e){if(e===null||typeof e!="object")return!1;let t=e;return t.type==="text"&&typeof t.text=="string"}function z5n(e){return e.content.filter(j5n).map((t)=>t.text).join(" ").trim()||"Unknown error"}var L5n;var u_t=We(()=>{xne();L5n=new opt([new xir,new upt,new ppt,new fpt,new _pt],k8n("node:javascript",uir))});var ror=We(()=>{Cye()});var BFe=We(()=>{Bz()});var f_t=We(()=>{jR();xye()});var d_t=We(()=>{jz();Cye();MFe();l_t();$pt();tor();PFe();Upt();Lz();u_t();ror();Bz();wFe();xye();Ene();Sye();xFe();Cne();Ane();BFe();f_t()});var ior=We(()=>{Cne();jz();Lz();Bz();Ane();d_t();BFe()});var Bss;var sor=We(()=>{Cne();jz();Cye();MFe();Lz();Bz();xye();Ane();d_t();BFe();Bss=Symbol("__posthog_mcp_analytics_processed__")});import{dirname as t7n,posix as r7n,sep as n7n}from"path";function aor(){let e=i7n();return async(t)=>{for(let n of t)n.module=e(n.filename);return t}}function i7n(e=process.argv[1]?t7n(process.argv[1]):process.cwd(),t=n7n==="\\"){let n=t?oor(e):e;return(s)=>{if(!s)return;let c=t?oor(s):s,{dir:u,base:d,ext:m}=r7n.parse(c);if(m===".js"||m===".mjs"||m===".cjs")d=d.slice(0,-1*m.length);let y=decodeURIComponent(d);if(!u)u=".";let S=u.lastIndexOf("/node_modules");if(S>-1)return`${u.slice(S+14).replace(/\//g,".")}:${y}`;if(u.startsWith(n)){let T=u.slice(n.length+1).replace(/\//g,".");return T?`${T}:${y}`:y}return y}}function oor(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var cor=()=>{};var EC;var zz=We(()=>{EC=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}({})});function gG(e){let t=[];return JSON.stringify(e,function(n,s){if(typeof s=="bigint")return s.toString();if(typeof s=="function"||typeof s=="symbol")return;if(s instanceof Error)return{name:s.name,message:s.message,stack:s.stack};if(s&&typeof s=="object"){while(t.length>0&&t[t.length-1]!==this)t.pop();if(t.includes(s))return"[Circular]";t.push(s)}return s})??"null"}var Pye=()=>{};function m_t(e){return e===null||typeof e!="object"}function h_t(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function $z(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return _or(e,Error)}}function Dye(e){return"u">typeof Event&&_or(e,Event)}function por(e){return h_t(e,"Object")}function _or(e,t){try{return e instanceof t}catch{return!1}}var s7n,uor,Gss,jFe,j2,zFe=(e)=>e===Object(e)&&!j2(e),UB=(e)=>e===void 0,UR=(e)=>jFe.call(e)=="[object String]",p_t=(e)=>UR(e)&&e.trim().length===0,__t=(e)=>e===null,qR=(e)=>UB(e)||__t(e),$Fe=(e)=>jFe.call(e)=="[object Number]"&&e===e,dor=(e)=>jFe.call(e)==="[object Boolean]";var Uz=We(()=>{zz();Pye();s7n=Array.isArray,uor=Object.prototype,Gss=uor.hasOwnProperty,jFe=uor.toString,j2=s7n||function(e){return jFe.call(e)==="[object Array]"}});function a7n(e,t){let n="";for(let s=0;s<t.length;s++){let c=t[s];n+=c.length+":"+c}return e.length+":"+e+"|"+t.length+":"+n}var o7n,UFe,mor=function(e,t=[]){if(!e)return!1;let n=a7n(e,t),s=UFe.get(n);if(s!==void 0)return s;let c=e.toLowerCase(),u=o7n.concat(t).some((d)=>c.indexOf(d.toLowerCase())!==-1);if(UFe.size>=256)UFe.clear();return UFe.set(n,u),u};var hor=We(()=>{o7n=["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"],UFe=new Map});var gor=We(()=>{Pye()});function Nye(e,t,n,s,c){if(t>n)s.warn("min cannot be greater than max."),t=n;if($Fe(e))if(e>n)return s.warn(" cannot be greater than max: "+n+". Using max value instead."),n;else{if(!(e<t))return e;return s.warn(" cannot be less than min: "+t+". Using min value instead."),t}return s.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+c),Nye(c??n,t,n,s)}var g_t=We(()=>{Uz()});function yor(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??l7n,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??u7n}}class y_t{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Nye(e.bucketSize,0,100,e._logger),this._refillRate=Nye(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Nye(e.refillInterval,0,c7n,e._logger)}_applyRefill(e,t){let n=t-e.lastAccess,s=Math.floor(n/this._refillInterval);if(s>0){let c=s*this._refillRate;e.tokens=Math.min(e.tokens+c,this._bucketSize),e.lastAccess=e.lastAccess+s*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),n=String(e),s=this._buckets[n];if(s)this._applyRefill(s,t);else s={tokens:this._bucketSize,lastAccess:t},this._buckets[n]=s;if(s.tokens===0)return!0;if(s.tokens--,s.tokens===0)this._onBucketRateLimited?.(e);return s.tokens===0}stop(){this._buckets={}}}var c7n=86400000,l7n=1,u7n=10;var vor=We(()=>{g_t()});class yG{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new yG(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,n,s){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(s)||e<0||t<0||n<0||s<0||e>281474976710655||t>4095||n>1073741823||s>4294967295)throw RangeError("invalid field value");let c=new Uint8Array(16);return c[0]=e/1099511627776,c[1]=e/4294967296,c[2]=e/16777216,c[3]=e/65536,c[4]=e/256,c[5]=e,c[6]=112|t>>>8,c[7]=t,c[8]=128|n>>>24,c[9]=n>>>16,c[10]=n>>>8,c[11]=n,c[12]=s>>>24,c[13]=s>>>16,c[14]=s>>>8,c[15]=s,new yG(c)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;default:break}if(t){let n=new Uint8Array(16);for(let s=0;s<16;s+=4){let c=parseInt(t.substring(2*s,2*s+8),16);n[s+0]=c>>>24,n[s+1]=c>>>16,n[s+2]=c>>>8,n[s+3]=c}return new yG(n)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)if(e+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".charAt(15&this.bytes[t]),t===3||t===5||t===7||t===9)e+="-";return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+="0123456789abcdef".charAt(this.bytes[t]>>>4),e+="0123456789abcdef".charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw Error("unreachable");if(e<=7)return this.bytes.every((t)=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every((t)=>t===255)?"MAX":"VAR_RESERVED";else throw Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new yG(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let n=this.bytes[t]-e.bytes[t];if(n!==0)return Math.sign(n)}return 0}}class wor{constructor(e){this.timestamp=0,this.counter=0,this.random=e??f7n()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let n=this.generateOrAbortCore(e,t);if(n===void 0)this.timestamp=0,n=this.generateOrAbortCore(e,t);return n}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>281474976710655)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>281474976710655)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;if(this.counter++,this.counter>4398046511103)this.timestamp++,this.resetCounter()}return yG.fromFieldsV7(this.timestamp,Math.trunc(this.counter/1073741824),this.counter&1073741823,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,yG.ofInner(e)}}var f7n=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),bor,OE=()=>d7n().toString(),d7n=()=>(bor||(bor=new wor)).generate();var Dne=We(()=>{/*! LICENSE: uuidv7.mjs.LICENSE.txt */});class v_t{add(e){let t=OE(),n=++this.nextId;return this.promiseByIds[t]={id:n,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map((n)=>n.promise),t=e.length;while(t>0)await Promise.all(e),e=Object.values(this.promiseByIds).map((n)=>n.promise),t=e.length}getPromises(e=[],t=this.nextId){let n=new Set(e);return Object.values(this.promiseByIds).filter((s)=>s.id<=t&&!n.has(s.promise)).map((s)=>s.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}var Sor=We(()=>{Dne()});function p7n(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}function xor(e,t=_7n){return Tor(e,t,p7n())}var Tor=(e,t,n)=>{function s(u,...d){t(()=>{let m=n[u];m(e,...d)})}return{debug:(...u)=>{s("debug",...u)},info:(...u)=>{s("log",...u)},warn:(...u)=>{s("warn",...u)},error:(...u)=>{s("error",...u)},critical:(...u)=>{n.error(e,...u)},createLogger:(u)=>Tor(`${e} ${u}`,t,n)}},_7n=(e)=>e();var Eor=()=>{};var One="Mobile",VFe="iOS",Nne="Android",Por="Tablet",los,h7n="Apple",uos,Dor="Safari",JFe="BlackBerry",Nor="Samsung",g7n,y7n,WFe="Chrome",v7n,b7n,Oor="Internet Explorer",w7n,S_t="Opera",fos,Ror="Edge",S7n,T_t="Firefox",T7n,x_t="Nintendo",E_t="PlayStation",qFe="Xbox",x7n,E7n,Oye="Windows",k7n,Mor="Generic",dos,pos,C7n="Konqueror",I7n="Oculus Browser",kor="Vivaldi",A7n="Yandex",Cor="Whale",P7n="DuckDuckGo",D7n="Pale Moon",Ior="Waterfox",Aor="Brave",For="Claude",Lor="Codex",Bor="ChatGPT",N7n="Google Search App",dy="(\\d+(\\.\\d+)?)",b_t,w_t,_os,mos,hos,O7n,R7n,gos,yos;var jor=We(()=>{Pye();Uz();los=Nne+" "+Por,uos=h7n+" Watch",g7n=Nor+"Browser",y7n=Nor+" Internet",v7n=WFe+" OS",b7n=WFe+" "+VFe,w7n=Oor+" "+One,fos=S_t+" Mini",S7n="Microsoft "+Ror,T7n=T_t+" "+VFe,x7n=Nne+" "+One,E7n=One+" "+Dor,k7n=Oye+" Phone",dos=Mor+" "+One.toLowerCase(),pos=Mor+" "+Por.toLowerCase(),b_t=new RegExp("Version/"+dy),w_t=new RegExp("("+For+"|"+Lor+"|"+Bor+")\\/"+dy),_os=new RegExp(qFe,"i"),mos=new RegExp(E_t+" \\w+","i"),hos=new RegExp(x_t+" \\w+","i"),O7n=new RegExp(JFe+"|PlayBook|BB10","i"),R7n={"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"},gos={[w7n]:[new RegExp("rv:"+dy)],[S7n]:[new RegExp(Ror+"?\\/"+dy)],[WFe]:[new RegExp("("+WFe+"|CrMo)\\/"+dy)],[b7n]:[new RegExp("CriOS\\/"+dy)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+dy)],[Dor]:[b_t],[E7n]:[b_t],[S_t]:[new RegExp("("+S_t+"|OPR)\\/"+dy)],[T_t]:[new RegExp(T_t+"\\/"+dy)],[T7n]:[new RegExp("FxiOS\\/"+dy)],[C7n]:[new RegExp("Konqueror[:/]?"+dy,"i")],[JFe]:[new RegExp(JFe+" "+dy),b_t],[x7n]:[new RegExp("android\\s"+dy,"i")],[y7n]:[new RegExp(g7n+"\\/"+dy)],[I7n]:[new RegExp("OculusBrowser\\/"+dy)],[kor]:[new RegExp(kor+"\\/"+dy)],[A7n]:[new RegExp("YaBrowser\\/"+dy)],[Cor]:[new RegExp(Cor+"\\/"+dy)],[Aor]:[new RegExp(Aor+"\\/"+dy)],[For]:[w_t],[Lor]:[w_t],[Bor]:[w_t],[P7n]:[new RegExp("(DuckDuckGo|Ddg)\\/"+dy)],[D7n]:[new RegExp("PaleMoon\\/"+dy)],[Ior]:[new RegExp(Ior+"\\/"+dy)],[N7n]:[new RegExp("GSA\\/"+dy)],[Oor]:[new RegExp("(rv:|MSIE )"+dy)],Mozilla:[new RegExp("rv:"+dy)]},yos=[[new RegExp(qFe+"; "+qFe+" (.*?)[);]","i"),(e)=>[qFe,e&&e[1]||""]],[new RegExp(x_t,"i"),[x_t,""]],[new RegExp(E_t,"i"),[E_t,""]],[O7n,[JFe,""]],[new RegExp(Oye,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[k7n,""];if(new RegExp(One).test(t)&&!/IEMobile\b/.test(t))return[Oye+" "+One,""];let n=/Windows NT ([0-9.]+)/i.exec(t);if(n&&n[1]){let s=n[1],c=R7n[s]||"";if(/arm/i.test(t))c="RT";return[Oye,c]}return[Oye,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(e)=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[VFe,t.join(".")]}return[VFe,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(e)=>{let t="";if(e&&e.length>=3)t=UB(e[2])?e[3]:e[2];return["watchOS",t]}],[new RegExp("("+Nne+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Nne+")","i"),(e)=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[Nne,t.join(".")]}return[Nne,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,(e)=>{let t=["Mac OS X",""];if(e&&e[1]){let n=[e[1],e[2],e[3]||"0"];t[1]=n.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[v7n,""]],[/Linux|debian/i,["Linux",""]]]});var zor=()=>{};function m4(e){let t="";for(let n=0;n<e.length;n++){let s=e.charCodeAt(n);if(s>=55296&&s<=56319){let c=e.charCodeAt(n+1);if(c>=56320&&c<=57343)t+=e[n]+e[n+1],n++;else t+="\uFFFD"}else t+=s>=56320&&s<=57343?"\uFFFD":e[n]}return t}function qB(e,t){if(!t)return e;let n=[];try{n=Object.keys(t)}catch{n=[]}for(let s of n){let c;try{c=t[s]}catch{c="[Unserializable]"}Object.defineProperty(e,s,{value:c,enumerable:!0,writable:!0,configurable:!0})}return e}var HFe=20,Rne=1000,GFe=1e4,XFe="[Circular]",YFe="[Truncated]",VR="[Unserializable]",$or="[Function]",wos,Sos;var VB=We(()=>{wos=Date.prototype.getTime,Sos=Date.prototype.toISOString});function k_t(e,t=Date.now()){if(typeof e!="string"||!e)return;let n=e.trim(),s=/^\d+\s*,/.test(n)?n.slice(0,n.indexOf(",")).trim():n;if(/^\d+$/.test(s)){let d=1000*Math.min(Number(s),300);return d>0?d:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(s))return;let c=/^\w{3} \w{3} /.test(s)?s+" GMT":s,u=Date.parse(c)-t;if(!Number.isFinite(u)||u<=0)return;return Math.min(u,300000)}class Mne{record(e){if(e.kind==="too-large")return;if(e.kind!=="retry-later")return void this.reset();if(!e.retryAfterMs)return;let t=this.isOpen(),n=Date.now(),s=Math.min(e.retryAfterMs,300000);if(!t){this._installedAt=n,this._until=n+s;return}this._until=Math.max(this._until,Math.min(n+s,this._installedAt+300000))}remainingMs(){let e=Date.now();if(e<this._installedAt-5000)return this.reset(),0;let t=Math.min(300000,Math.max(0,this._until-e));if(t===0)this.reset();return t}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}}var Fne=()=>{};function F7n(e){return typeof e=="string"&&M7n.test(e)}function vG(e,t){return F7n(e)?e:t()}function Lne(e,t){let n=Error(t);try{Object.defineProperty(n,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return n}function qor(e){return e?.replace(/\/+$/,"")}async function Vor(e,t){let n=null;for(let s=0;s<t.retryCount+1;s++){if(s>0)await new Promise((c)=>setTimeout(c,t.retryDelay));try{return await e()}catch(c){if(n=c,!t.retryCheck(c))throw c}}throw n}function C_t(){return new Date().toISOString()}function RE(e,t){let n=setTimeout(e,t);return n?.unref&&n?.unref(),n}async function qz(e,t,n){let s;try{return await Promise.race([e,new Promise((c,u)=>{s=RE(()=>{try{n?.(),c()}catch(d){u(d)}},t)})])}finally{clearTimeout(s)}}function Rye(e){return Promise.all(e.map((t)=>(t??Promise.resolve()).then((n)=>({status:"fulfilled",value:n}),(n)=>({status:"rejected",reason:n}))))}var Uor="utf8",M7n,Jor=(e)=>e&&typeof e.then=="function";var $v=We(()=>{Uz();VB();Fne();hor();gor();vor();g_t();Pye();Uz();Sor();Eor();jor();zor();M7n=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i});function Xor(e){let{_posthogChunkIds:t,_debugIds:n}=globalThis;if(!t&&!n)return;let s=t?Object.keys(t):[],c=n?Object.keys(n):[];if(Bne&&Gor(t,s,Wor)&&Gor(n,c,Hor))return Bne;Wor=t?{...t}:void 0,Hor=n?{...n}:void 0,Bne={},I_t??={};let u=(d,m)=>{for(let y of d){let S=m[y];if(!S)continue;let T=I_t?.[y];if(T){Bne[T]=S;continue}let C=e(y);for(let D=C.length-1;D>=0;D--){let L=C[D]?.filename;if(L){Bne[L]=S,I_t[y]=L;break}}}};if(n)u(c,n);if(t)u(s,t);return Bne}function Gor(e,t,n){if(!e||!n)return e===n;return t.length===Object.keys(n).length&&t.every((s)=>e[s]===n[s])}var I_t,Wor,Hor,Bne;var Yor=()=>{};class QFe{constructor(e,t,n=[]){this.coercers=e,this.stackParser=t,this.modifiers=n}buildFromUnknown(e,t={}){let s=t&&t.mechanism||{handled:!0,type:"generic"},u=this.buildCoercingContext(s,t,0).apply(e),d=this.buildParsingContext(t),m=this.parseStacktrace(u,d);return{$exception_list:this.convertToExceptionList(m,s),$exception_level:"error"}}async modifyFrames(e){for(let t of e)if(t.stacktrace&&t.stacktrace.frames&&j2(t.stacktrace.frames))t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames);return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let n;if(e.cause!=null)n=this.parseStacktrace(e.cause,t);let s;if(e.stack!=""&&e.stack!=null)try{s=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)}catch{}return{...e,cause:n,stack:s,errors:e.errors?.map((c)=>this.parseStacktrace(c,t))}}applyChunkIds(e,t){return e.map((n)=>{if(n.filename&&t)n.chunk_id=t[n.filename];return n})}applyCoercers(e,t){for(let n of this.coercers)if(n.match(e))return n.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let n of this.modifiers)t=await n(t);return t}convertToExceptionList(e,t){let n=[],s=(c,u,d)=>{let m=n.length,y=u===void 0?{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:c.synthetic,exception_id:m}:{type:"chained",source:d,synthetic:c.synthetic,exception_id:m,parent_id:u},S={type:c.type,value:c.value,mechanism:y};if(c.stack)S.stacktrace={type:"raw",frames:c.stack};if(n.push(S),c.cause)s(c.cause,m,"cause");for(let T of c.errors??[])s(T,m,"member")};return s(e),n}buildParsingContext(e){return{chunkIdMap:Xor(this.stackParser),skipFirstLines:e.skipFirstLines??1}}getAggregateErrors(e){try{if($z(e)){let t=Object.getPrototypeOf(e);for(let n=0;t&&n<B7n;n++){let s=Object.getOwnPropertyDescriptor(t,"constructor")?.value;if(typeof s=="function"&&s.name==="AggregateError"){let c=e.errors;return j2(c)?c:void 0}t=Object.getPrototypeOf(t)}}}catch{}}buildCoercingContext(e,t,n=0){let s=0,c=0,u=!1,d=new Set,m=[],y={},S=(D,L,B=0)=>{let z=T(L,B),X=z.apply;if(z.apply=(he)=>{m.push(D);try{return X(he)}finally{m.pop()}},B>j7n||B>0&&m.indexOf(D)!==-1)return this.coerceFallback(z);let K=typeof D=="object"&&D!==null||typeof D=="function";if(B===0&&s>=A_t||K&&d.has(D))return;if(K)d.add(D);if(B===0)s++;let ie=this.getAggregateErrors(D);u||=!!ie;let ye;try{if(ye=this.applyCoercers(D,z),!ye)throw y}catch(he){if(he===y){if(B===0)s--;return}if(!u)throw he;ye=this.coerceFallback(z)}if(!ie||s>=A_t)return ye;let Te;try{Te=ie.length}catch{return ye}if(!Number.isInteger(Te)||Te<0||Te>4294967295)return ye;let Ce=[];for(let he=0;s<A_t&&c<L7n&&he<Te;he++){c++;let re;try{re=z.next(ie[he])}catch{s++,re=this.coerceFallback(T(L+1))}if(re)Ce.push(re)}return{...ye,errors:Ce}},T=(D,L=0)=>({...t,syntheticException:D==0?t.syntheticException:void 0,mechanism:D==0?e:{},apply:(B)=>{let z=S(B,D,L+1);if(!z)throw y;return z},next:(B)=>S(B,D+1)}),C=T(n);return{...C,apply:(D)=>S(D,n)??this.coerceFallback(C)}}}var A_t=50,L7n=1000,B7n=100,j7n=4;var Qor=We(()=>{$v();Yor()});function q7n(e){if(!e||e===z7n)return!1;let t=$7n.exec(e);return!t||U7n.includes(t[1].toLowerCase())}function bG(e,t,n,s,c){let u={platform:e,filename:t,function:n==="<anonymous>"?kC:n,in_app:q7n(t)};if(!UB(s))u.lineno=s;if(!UB(c))u.colno=c;return u}var kC="?",z7n="<anonymous>",$7n,U7n;var Vz=We(()=>{$v();$7n=/^([a-z][a-z0-9.+-]+):/i,U7n=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"]});var KFe=(e,t)=>{let n=e.indexOf("safari-extension")!==-1,s=e.indexOf("safari-web-extension")!==-1;return n||s?[e.indexOf("@")!==-1?e.split("@")[0]:kC,n?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var P_t=We(()=>{Vz()});var V7n,J7n,W7n,Kor=(e,t)=>{let n=V7n.exec(e);if(n){let[,c,u,d]=n;return bG(t,c,kC,+u,+d)}let s=J7n.exec(e);if(s){if(s[2]&&s[2].indexOf("eval")===0){let m=W7n.exec(s[2]);if(m)s[2]=m[1],s[3]=m[2],s[4]=m[3]}let[u,d]=KFe(s[1]||kC,s[2]);return bG(t,d,u,s[3]?+s[3]:void 0,s[4]?+s[4]:void 0)}};var Zor=We(()=>{Vz();P_t();V7n=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,J7n=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,W7n=/\((\S*)(?::(\d+))(?::(\d+))\)/});var H7n,G7n,ear=(e,t)=>{let n=H7n.exec(e);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){let d=G7n.exec(n[3]);if(d)n[1]=n[1]||"eval",n[3]=d[1],n[4]=d[2],n[5]=""}let c=n[3],u=n[1]||kC;return[u,c]=KFe(u,c),bG(t,c,u,n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}};var tar=We(()=>{Vz();P_t();H7n=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,G7n=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i});var rar=We(()=>{Vz()});var nar=We(()=>{Vz()});function ejn(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&e!==void 0&&!e.includes("node_modules/")}function iar(e){return parseInt(e||"",10)||void 0}var X7n,Y7n,Q7n,K7n,Z7n="node:internal/promise",sar=(e,t)=>{let n=e.match(Y7n);if(n){let s,c,u,d,m;if(n[1]){u=n[1];let T=u.lastIndexOf(".");if(u[T-1]===".")T--;if(T>0){s=u.slice(0,T),c=u.slice(T+1);let C=s.indexOf(".Module");if(C>0)u=u.slice(C+1),s=s.slice(0,C)}d=void 0}if(c)d=s,m=c;if(c==="<anonymous>")m=void 0,u=void 0;if(u===void 0)m=m||kC,u=d?`${d}.${m}`:m;let y=n[2]?.startsWith("file://")?n[2].slice(7):n[2],S=n[5]==="native";if(y?.match(/\/[A-Z]:/))y=y.slice(1);if(!y&&n[5]&&!S)y=n[5];if(Q7n.test(u)&&K7n.test(y||""))y=Z7n;return{filename:y?decodeURI(y):void 0,module:void 0,function:u,lineno:iar(n[3]),colno:iar(n[4]),in_app:ejn(y||"",S),platform:t}}if(e.match(X7n))return{filename:e,platform:t}};var oar=We(()=>{Vz();X7n=/^\s*[-]{4,}$/,Y7n=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,Q7n=/^Promise\.(?:all|any)$/,K7n=/^index \d+$/});function D_t(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function njn(e){for(let t=1;t<=tjn;t++){let n=e.length-2*t;if(n<0)break;let s=!0;for(let c=0;c<t;c++){let u=e[n+c];if(!D_t(u,e[n+t+c])){s=!1;break}}if(s){for(let c=0;c<t;c++)e[n+c]=e[n+t+c];return e.length=n+t,{start:n,length:t}}}}function ijn(e,t){let n=t.start+t.length,s=uar(e,t);if(s)e.splice(n+s===e.length?n:t.start,s)}function lar(e,t){let n=t.start;while(n>0&&D_t(e[n-1],e[n-1+t.length]))n--;return t.start-n}function uar(e,t){let n=t.start+t.length,s=n;while(s<e.length&&D_t(e[s],e[s-t.length]))s++;return s-n}function sjn(e,t){let n=t[0],s=e.length-(n?lar(e,n):0);for(let c of t)s-=uar(e,c);return s}function ojn(e){let t=e.map((s)=>`${s.function}|${s.filename}|${s.lineno}|${s.colno}|${s.module}`),n=0;for(let s=1;s<t.length;s++)if(ajn(t,s,n))n=s;e.push(...e.splice(0,n))}function ajn(e,t,n){for(let s=0;s<e.length;s++){let c=e[(t+s)%e.length],u=e[(n+s)%e.length];if(c!==u)return c<u}return!1}function cjn(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,car).map((n)=>({...n,filename:n.filename||ljn(t).filename,function:n.function||kC}))}function ljn(e){return e[e.length-1]||{}}function far(){return dar("web:javascript",Kor,ear)}function dar(e,...t){return(n,s=0)=>{let c=[],u=n.split(`
|
|
345
345
|
`),d=Math.min(u.length,s+rjn),m=[];for(let T=s;T<d;T++){let C=u[T];if(C.length>1024)continue;let D=aar.test(C)?C.replace(aar,"$1"):C;if(!D.match(/\S*Error: /)){for(let L of t){let B=L(D,e);if(B){c.push(B);let z=njn(c);if(z){for(let X=m.length-1;X>=0;X--){let K=m[X];if(K.start+K.length<=z.start)break;m.pop()}m.push(z)}break}}if(sjn(c,m)>=car)break}}let y=[...m].sort((T,C)=>C.start-T.start),S=y[y.length-1];if(S){let T=lar(c,S);c.splice(S.start-T,T);for(let C of y)C.start-=T}for(let T of y)ijn(c,T);if(m.some((T)=>T.start===0&&c.length===T.length))ojn(c);return cjn(c)}}var aar,car=50,tjn=10,rjn=1000;var par=We(()=>{Vz();Zor();tar();rar();nar();oar();aar=/\(error: (.*)\)/});var _ar=We(()=>{$v()});class ZFe{match(e){return $z(e)}coerce(e,t){let n=this.getStack(e),s=n===void 0?t.syntheticException?.stack:void 0,c=!!s;return{type:this.getType(e),value:this.getMessage(e,t),stack:n??s,cause:e.cause?t.next(e.cause):void 0,synthetic:c}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let n=e.message;if(n.error&&typeof n.error.message=="string")return String(n.error.message);return String(n)}getStack(e){try{let t=e.stacktrace;if(typeof t=="string"&&t.length>0)return t;let n=e.stack;return typeof n=="string"&&n.length>0?n:void 0}catch{return}}}var mar=We(()=>{Uz()});var har=We(()=>{$v()});class e6e{match(e){return typeof e=="string"}coerce(e,t){let[n,s]=this.getInfos(e);return{type:n??"Error",value:s??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",n=e,s=e.match(ujn);if(s)t=s[1],n=s[2];return[t,n]}}var ujn;var gar=We(()=>{ujn=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i});var yar;var bar=We(()=>{yar=["fatal","error","warning","log","info","debug"]});function t6e(e,t=40){let n=Object.keys(e);if(n.sort(),!n.length)return"[object has no keys]";for(let s=n.length;s>0;s--){let c=n.slice(0,s).join(", ");if(!(c.length>t)){if(s===n.length)return c;return c.length<=t?c:`${c.slice(0,t)}...`}}return""}var N_t=()=>{};class r6e{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let n=this.getErrorPropertyFromObject(e);if(n)return t.apply(n);return{type:this.getType(e),value:this.getValue(e),stack:this.getStack(e)??t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(Dye(e))return e.constructor.name;let t="name"in e?e.name:void 0;return UR(t)&&!p_t(t)?t:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let s=`'${e.name}' captured as exception`;if("message"in e&&typeof e.message=="string")s+=` with message: '${e.message}'`;return s}if("message"in e&&typeof e.message=="string")return e.message;let t=this.getObjectClassName(e),n=t6e(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(e){return UR(e)&&!p_t(e)&&yar.indexOf(e)>=0}getStack(e){try{if(UR(e.stacktrace)&&e.stacktrace.length>0)return e.stacktrace;return UR(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];if($z(n))return n}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(t){return}}}var war=We(()=>{$v();bar();N_t()});class Sar{match(e){return Dye(e)}coerce(e,t){let n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${t6e(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}var Tar=We(()=>{$v();N_t()});class n6e{match(e){return m_t(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}var xar=We(()=>{$v()});var Ear=We(()=>{$v()});var kar=We(()=>{_ar();mar();har();gar();war();Tar();xar();Ear()});class O_t{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(t===void 0)return;return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){while(this._cache.size>=this._maxSize){let e=this._cache.keys().next().value;if(e)this._cache.delete(e)}}}var Car=()=>{};var Iar,Gas;var Aar=We(()=>{$v();Iar={MESSAGE:"$message",TIMESTAMP:"$timestamp"},Gas=new Set([Iar.MESSAGE,Iar.TIMESTAMP])});function Par(){if("u">typeof process){let t=process.env.POSTHOG_RELEASE_ID?.trim();if(t)return t}let e=globalThis._posthogReleaseId;return typeof e=="string"&&e.length>0?e:void 0}var Dar=()=>{};var R_t=We(()=>{Qor();par();kar();Car();Aar();Dar()});var Nar=We(()=>{$v();Dne()});function fjn(e,t,n){return{key:e,enabled:typeof t=="string"?!0:t,variant:typeof t=="string"?t:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:n?JSON.stringify(n):void 0,description:void 0}}}var M_t=(e)=>{if("flags"in e){let t=Oar(e.flags),n=Rar(e.flags);return{...e,featureFlags:t,featureFlagPayloads:n}}{let t=e.featureFlags??{},n=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([c,u])=>[c,jne(u)])),s=Object.fromEntries(Object.entries(t).map(([c,u])=>[c,fjn(c,u,n[c])]));return{...e,featureFlags:t,featureFlagPayloads:n,flags:s}}},Oar=(e)=>Object.fromEntries(Object.entries(e??{}).map(([t,n])=>[t,Fye(n)]).filter(([,t])=>t!==void 0)),Rar=(e)=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter((n)=>{let s=t[n];return s.enabled&&s.metadata&&s.metadata.payload!==void 0}).map((n)=>{let s=t[n].metadata?.payload;return[n,s?jne(s):void 0]}))},Fye=(e)=>e===void 0?void 0:e.variant??e.enabled,jne=(e)=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},Mar,djn,Lye=(e,t=[])=>{let n={},s=(c)=>{if(e[c]!==void 0)n[c]=e[c]};return djn.forEach(s),t.forEach(s),n};var Bye=We(()=>{Mar=["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","oppref","bfcid","irclid","_kx"],djn=["$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",...Mar,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"]});class F_t{constructor(){this.events={},this.events={}}on(e,t){if(!this.events[e])this.events[e]=[];return this.events[e].push(t),()=>{this.events[e]=this.events[e].filter((n)=>n!==t)}}emit(e,t){for(let n of this.events[e]||[])n(t);for(let n of this.events["*"]||[])n(e,t)}}var Far=()=>{};function L_t(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}async function zye(e,t=!0,n){try{let s=new TextEncoder().encode(e),c=new globalThis.CompressionStream("gzip"),u=c.writable.getWriter(),d=u.write(s).then(()=>u.close()).catch(async(S)=>{try{await u.abort(S)}catch{}throw S}),m=new Response(c.readable).blob(),[y]=await Promise.all([m,d]);return await wjn(y,s),y}catch(s){if(n?.rethrow)throw s;if(t)console.error("Failed to gzip compress data",s);return null}}var _jn="NativeGzipValidationError",mjn=31,hjn=139,gjn=8,yjn=(e)=>e.length>=2&&e[0]===mjn&&e[1]===hjn,jye,vjn=()=>{if(jye)return jye;jye=[];for(let e=0;e<256;e++){let t=e;for(let n=0;n<8;n++)t=1&t?3988292384^t>>>1:t>>>1;jye[e]=t>>>0}return jye},bjn=(e)=>{let t=vjn(),n=4294967295;for(let s=0;s<e.length;s++)n=t[(n^e[s])&255]^n>>>8;return(4294967295^n)>>>0},i6e=(e)=>{throw Lne(_jn,`Native gzip produced invalid output: ${e}`)},wjn=async(e,t)=>{if(e.size<18)i6e("too-short");let n=new Uint8Array(await e.slice(0,10).arrayBuffer());if(!yjn(n)||n[2]!==gjn)i6e("invalid-header");let s=new DataView(await e.slice(e.size-8).arrayBuffer());if(s.getUint32(0,!0)!==bjn(t))i6e("invalid-crc");let c=t.length>>>0;if(s.getUint32(4,!0)!==c)i6e("invalid-size")};var B_t=We(()=>{zz();$v()});async function Lar(e){if(e instanceof JR){let t="";try{t=await e.text}catch{if(e.bodyReadTimedOut)t="<response body read timed out>"}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function Tjn(e){return typeof e=="object"&&(e instanceof JR||$ar(e))}function $ar(e){return e instanceof Jz}function xjn(e){if(e instanceof JR)return e.status===502||e.status===504;if(!(e instanceof Jz))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}function jar(e){try{if(typeof e!="string")return e instanceof Uint8Array?e.byteLength:e.size;if("u">typeof Buffer)return Buffer.byteLength(e,Uor);return new TextEncoder().encode(e).length}catch{return 0}}function zne(e){return typeof e=="object"&&e instanceof JR&&e.status===413}function s6e(e){if(e instanceof JR)return e.status===408||e.status===429||e.status>=500;return $ar(e)}function zar(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}class o6e{getErrorPropertiesBuilder(){if(!this._errorPropertiesBuilder)this._errorPropertiesBuilder=this.createErrorPropertiesBuilder();return this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new QFe([new ZFe,new r6e,new e6e,new n6e],far())}getEvaluationRuntime(){}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new v_t,this._events=new F_t,this._isInitialized=!1;let n=typeof e=="string"?e.trim():"",s=typeof t.host=="string"?t.host.trim():"",c=!n;if(this._logger=xor("[PostHog]",this.logMsgIfDebug.bind(this)),c)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=n,this.host=qor(s||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1000),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3000,retryCheck:s6e},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3000,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3000,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||c,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts)this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");this.disableCompression=!L_t()||(t?.disableCompression??!1)}logMsgIfDebug(e){if(this.isDebug)e()}wrap(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return e();this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(EC.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(EC.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(EC.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(n,s)=>this._logger.info(n,s));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},n=this.mergeCommonEventProperties(t);if(Sjn(n,t),e.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled())n=Lye(n);return{distinct_id:e.distinct_id,event:e.event,properties:n}}mergeCommonEventProperties(e){return{...e,...this.getCommonEventProperties()}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,n){this.wrap(()=>{let s={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",s,n)})}async identifyStatelessImmediate(e,t,n){let s={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",s,n)}captureStateless(e,t,n,s){this.wrap(()=>{let c=this.buildPayload({distinct_id:e,event:t,properties:n});this.enqueue("capture",c,s)})}async captureStatelessImmediate(e,t,n,s){let c=this.buildPayload({distinct_id:e,event:t,properties:n});await this.sendImmediate("capture",c,s)}aliasStateless(e,t,n,s){this.wrap(()=>{let c=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});this.enqueue("alias",c,s)})}async aliasStatelessImmediate(e,t,n,s){let c=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",c,s)}groupIdentifyStateless(e,t,n,s,c,u){this.wrap(()=>{let d=this.buildPayload({distinct_id:c||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{},...u||{}}});this.enqueue("capture",d,s)})}async groupIdentifyStatelessImmediate(e,t,n,s,c,u){let d=this.buildPayload({distinct_id:c||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{},...u||{}}});await this.sendImmediate("capture",d,s)}async getRemoteConfig(){await this._initPromise;let e=this.host;if(e==="https://us.i.posthog.com")e="https://us-assets.i.posthog.com";else if(e==="https://eu.i.posthog.com")e="https://eu-assets.i.posthog.com";let t=`${e}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,n,{type:"required",consume:(s)=>s.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch((s)=>{this._logger.error("Remote config could not be loaded",s),this._events.emit("error",s)})}async getFlags(e,t={},n={},s={},c={},u=!1){await this._initPromise;let d=u?"&config=true":"",m=`${this.host}/flags/?v=2${d}`,y={token:this.apiKey,distinct_id:e,groups:t,person_properties:n,group_properties:s,...c};if(n.$device_id)y.$device_id=n.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)y.evaluation_contexts=this.evaluationContexts;let S=this.getEvaluationRuntime();if(S)y.evaluation_runtime=S;let T={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(y)};return this._logger.info("Flags URL",m),this.fetchWithRetry(m,T,{type:"required",consume:(C)=>C.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:xjn},this.featureFlagsRequestTimeoutMs).then((C)=>({success:!0,response:M_t(C)})).catch((C)=>(this._events.emit("error",C),{success:!1,error:this.categorizeRequestError(C)}))}categorizeRequestError(e){if(e instanceof JR)return{type:"api_error",statusCode:e.status};if(e instanceof Jz){let t=e.error;if(t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError"))return{type:"timeout"};return{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,n={},s={},c={},u){await this._initPromise;let d=await this.getFeatureFlagDetailStateless(e,t,n,s,c,u);if(d===void 0)return{response:void 0,requestId:void 0};let m=Fye(d.response);if(m===void 0)m=!1;return{response:m,requestId:d.requestId}}async getFeatureFlagDetailStateless(e,t,n={},s={},c={},u){await this._initPromise;let d=await this.getFeatureFlagDetailsStateless(t,n,s,c,u,[e]);if(d===void 0)return;return{response:d.flags[e],requestId:d.requestId,evaluatedAt:d.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,n={},s={},c={},u){await this._initPromise;let d=await this.getFeatureFlagPayloadsStateless(t,n,s,c,u,[e]);if(!d)return;let m=d[e];if(m===void 0)return null;return m}async getFeatureFlagPayloadsStateless(e,t={},n={},s={},c,u){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,n,s,c,u)).payloads}async getFeatureFlagsStateless(e,t={},n={},s={},c,u){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,n,s,c,u)}async getFeatureFlagsAndPayloadsStateless(e,t={},n={},s={},c,u){await this._initPromise;let d=await this.getFeatureFlagDetailsStateless(e,t,n,s,c,u);if(!d)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:d.featureFlags,payloads:d.featureFlagPayloads,requestId:d.requestId}}async getFeatureFlagDetailsStateless(e,t={},n={},s={},c,u){await this._initPromise;let d={geoip_disable:c??this.disableGeoip};if(u)d.flag_keys_to_evaluate=u;let m=await this.getFlags(e,t,n,s,d);if(!m.success)return;let y=m.response;if(y.errorsWhileComputingFlags)console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices");if(y.quotaLimited?.includes("feature_flags"))return console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:y?.requestId,quotaLimited:y.quotaLimited};return y}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},s=(await this.fetchWithRetry(e,t,{type:"required",consume:(c)=>{if(c.status!==200||!c.json){let u=`Surveys API could not be loaded: ${c.status}`,d=Error(u);return this._logger.error(d),this._events.emit("error",Error(u)),Promise.resolve(void 0)}return c.json()}}).catch((c)=>{this._logger.error("Surveys API could not be loaded",c),this._events.emit("error",c)}))?.surveys;if(s)this._logger.info("Surveys fetched from API: ",JSON.stringify(s));return s??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(EC.Props);return this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(EC.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(EC.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return j_t}persistedQueueKeyForRoute(e){return EC.Queue}getActiveQueueRoutes(){return[j_t]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,n,s){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let c=this.prepareMessage(t,n);if(c=this.processBeforeEnqueue(c),c===null)return;c=this.normalizeMessage(c);let u=this.persistedQueueKeyForRoute(s??this.getQueueRouteKey(c)),d=this.getPersistedProperty(u)||[];if(d.length>=this.maxQueueSize)d.shift(),this._logger.warn("Queue is full, the oldest event is dropped.");if(d.push({message:c}),this.setPersistedProperty(u,d),this._events.emit(e,c),d.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=RE(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(e,t,n,s){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this._isInitialized)await this._initPromise;if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let c=this.prepareMessage(t,n);if(c=this.processBeforeEnqueue(c),c===null)return;c=this.normalizeMessage(c);try{await this.sendBatch([c],void 0,s??this.getQueueRouteKey(c))}catch(u){this._events.emit("error",u)}}normalizeMessage(e){let{type:t,library:n,library_version:s,...c}=e,u=zar(c.properties)?c.properties:void 0;if(n!==void 0&&u?.$lib===void 0)u={...u||{},$lib:n};if(s!==void 0&&u?.$lib_version===void 0)u={...u||{},$lib_version:s};if(u)c.properties=u;return c.uuid=vG(c.uuid,OE),c}normalizeTimestampForWire(e){let t=e instanceof Date?e:typeof e=="string"?new Date(e):null;if(!t||Number.isNaN(t.getTime()))return e;let n=t.toISOString(),s=typeof e=="string"?e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return s&&s.length>3?n.replace(/\.\d{3}Z$/,`.${s}Z`):n}prepareMessage(e,t){let n={...e,timestamp:t?.timestamp?t?.timestamp:C_t(),uuid:vG(t?.uuid,OE)};if(t?.disableGeoip??this.disableGeoip){if(!zar(n.properties))n.properties={};n.properties.$geoip_disable=!0}if(n.distinctId)n.distinct_id=n.distinctId,delete n.distinctId;return n}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){if(this.pendingFlushPromise)return;this.flushAutomatic().catch(async(e)=>{await Lar(e)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(e,t=[]){let n=t.filter((c)=>!!c),s=0;while(!0){let c=this.promiseQueue.getPromises([...n,...this.flushPromises],e);if(c.length===0)return;if(s>0)this._logger.debug(`flush() re-checking ${c.length} pending promise(s) before flushing`);await Promise.all(c.map((u)=>u.catch(()=>{}))),s++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,n=this.promiseQueue.maxId,s=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(n,[t,s])}).then(()=>Rye([t])).then(()=>{if(this.pendingFlushPromise===s)this.pendingFlushPromise=null;return this._flush()});return this.pendingFlushPromise=s,this.flushPromise=s,this.flushPromises.add(s),this.addPendingPromise(s),Rye([s]).then(()=>{if(this.flushPromises.delete(s),this.pendingFlushPromise===s)this.pendingFlushPromise=null;if(this.flushPromise===s)this.flushPromise=null}),s}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};if(e&&e!=="")t["User-Agent"]=e;return t}compressPayload(e){return zye(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,t,n=j_t){let s={api_key:this.apiKey,batch:e.map((y)=>{if(!y)return y;let S=this.normalizeTimestampForWire(y.timestamp);return S===y.timestamp?y:{...y,timestamp:S}}),sent_at:C_t()};if(this.historicalMigration)s.historical_migration=!0;let c=gG(s),u=`${this.host}${this.getBatchEndpointPath(n)}`,d=this.disableCompression?null:await this.compressPayload(c),m={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...d!==null&&{"Content-Encoding":"gzip"}},body:d||c};await this.fetchWithRetry(u,m,{type:"successful-write"},t)}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some((s)=>this.getRouteQueue(s).length>0))return;let t=[],n;for(let s of e)try{await this._flushRoute(s,t)}catch(c){if(n===void 0)n=c}if(n!==void 0)throw n;this._events.emit("flush",t)}async _flushRoute(e,t){let n=this.persistedQueueKeyForRoute(e),s=this.getPersistedProperty(n)||[];if(!s.length)return;let c=s.length,u=0;while(s.length>0&&u<c){let d=s.slice(0,this.maxBatchSize),m=d.map((T)=>T.message===void 0?T.message:this.normalizeMessage(T.message)),y=async()=>{let T=this.getPersistedProperty(n)||[],C=[...d],D=T.filter((L)=>{let B=L.message?.uuid,z=C.findIndex((X)=>X===L||typeof B=="string"&&B.length>0&&X.message?.uuid===B);if(z===-1)return!0;return C.splice(z,1),!1});this.setPersistedProperty(n,D),s=D,this._dequeuedMessagesCount+=d.length,await this.flushStorage()},S={retryCheck:(T)=>{if(zne(T))return!1;return s6e(T)}};try{await this.sendBatch(m,S,e)}catch(T){if(zne(T)&&m.length>1){this.maxBatchSize=Math.max(1,Math.floor(m.length/2)),this._logger.warn(`Received 413 when sending batch of size ${m.length}, reducing batch size to ${this.maxBatchSize}`);continue}if(!(T instanceof Jz))await y();throw this._events.emit("error",T),T}await y(),t.push(...m),u+=m.length}}async _sendOtlpBatch({path:e,auth:t,payload:n}){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let s;try{s=JSON.stringify(n)}catch(S){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${e} batch; reporting it as too large`,S)),{kind:"too-large",measuredLocally:!0}}let c=jar(s);if(c>Bar)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${c} bytes: the endpoint accepts at most ${Bar}`)),{kind:"too-large",measuredLocally:!0};let u=t==="bearer"?`${this.host}/i/v1/${e}`:`${this.host}/i/v1/${e}?token=${encodeURIComponent(this.apiKey)}`,d=this.disableCompression?null:await this.compressPayload(s),m=d||s,y={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...t==="bearer"&&{Authorization:`Bearer ${this.apiKey}`},...d!==null&&{"Content-Encoding":"gzip"}},body:m};try{return await this.fetchWithRetry(u,y,{type:"successful-write"},{retryCheck:(S)=>{if(zne(S))return!1;if(S instanceof JR&&S.retryAfterMs!==void 0)return!1;return s6e(S)}}),{kind:"ok"}}catch(S){if(zne(S))return{kind:"too-large"};if(s6e(S)){let T=S instanceof JR?S.retryAfterMs:void 0;return{kind:"retry-later",error:S,...T!==void 0&&{retryAfterMs:T}}}return{kind:"fatal",error:S}}}async _sendLogsBatch(e){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:e})}async _sendMetricsBatch(e){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:e})}async _sendTracesBatch(e){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:e})}async fetchWithRetry(e,t,n,s,c){let u=t.body?t.body:"",d=jar(u),m={...this._retryOptions,...s},y=0;return await Vor(async()=>{y++;let S=new AbortController,T=c??this.requestTimeout,C=Date.now()+T,D,L=new Promise((ie,ye)=>{D=RE(()=>{let Te=Lne("AbortError",`Request timed out after ${T}ms`);ye(Te),S.abort(Te)},T)}),B,z=!1,X,K=()=>X??=(async()=>{try{await B?.body?.cancel()}catch{}})();try{let ie;try{ie=this.fetch(e,{signal:S.signal,...t})}catch(Ce){throw new Jz(Ce)}ie.then((Ce)=>{if(S.signal.aborted&&!z)Promise.resolve(Ce.body?.cancel()).catch(()=>{})}).catch(()=>{});try{B=await Promise.race([ie,L]),z=!0}catch(Ce){throw new Jz(Ce)}let ye=t.mode==="no-cors",Te=n.type==="successful-write"?300:400;if(!ye&&(B.status<200||B.status>=Te))throw new JR(B,d,C,S);if(n.type==="successful-write"){try{await Promise.race([K(),L])}catch{}return}try{return await Promise.race([n.consume(B),L])}catch(Ce){if(S.signal.aborted)throw new Jz(Ce);throw Ce}}finally{if(clearTimeout(D),S.signal.aborted&&B)K()}},{...m,retryCheck:(S)=>{let T=m.retryCheck(S);if(T&&y<=m.retryCount&&S instanceof JR)S.cancelResponseBody();return T}})}async _shutdown(e=30000){await this._initPromise;let t=!1;if(this.clearFlushTimer(),this.disabled)return;return qz((async()=>{try{await this.promiseQueue.join();while(!0){if(!this.getActiveQueueRoutes().some((u)=>this.getRouteQueue(u).length>0))break;let c=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===c){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(s){if(!Tjn(s))throw s;await Lar(s)}})(),e,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:e}),t=!0})}async shutdown(e=30000){if(this.shutdownPromise)this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");else this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null});return this.shutdownPromise}}var JR,Jz,Sjn=(e,t)=>{for(let n of Object.keys(t))if(n.startsWith("$feature/")||n==="$active_feature_flags")e[n]=t[n]},Bar=10485760,j_t="default";var z_t=We(()=>{Far();Bye();B_t();zz();$v();Fne();Dne();R_t();JR=class JR extends Error{constructor(e,t,n,s){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.responseBodyDeadline=n,this.abortController=s,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return k_t(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let e=Lne("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e=new Promise((n,s)=>{this.responseBodyTimer=RE(()=>{this._bodyReadTimedOut=!0;let c=Lne("AbortError","Response body read timed out");s(c),this.cancelResponseBody(c)},this.responseBodyDeadline-Date.now())}),t;try{t=Promise.resolve(this.response.text())}catch(n){t=Promise.reject(n)}this.responseBodyTextPromise=Promise.race([t,e]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then((e)=>JSON.parse(e))}cancelResponseBody(e){if(clearTimeout(this.responseBodyTimer),!this.abortController.signal.aborted)this.abortController.abort(e);(async()=>{try{await this.response.body?.cancel()}catch{}})()}};Jz=class Jz extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}});var Uar=We(()=>{Bye();zz();z_t();Dne();$v()});var Ajn,Ocs,qar,Rcs,Mcs;var Var=We(()=>{Ajn=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi,Ocs=new RegExp(Ajn.source,"i"),qar=/[a-z][a-z0-9+.-]{0,63}:\/\//i,Rcs=new RegExp(`^${qar.source}`,"i"),Mcs=new RegExp(qar.source,"gi")});var Jar=We(()=>{Uz()});function $ne(e){try{return e()}catch(t){if(t instanceof wu)throw new wu(t.message,"missing_context");throw t}}function U_t(e){if(typeof e=="boolean")return!0;if(typeof e=="string"){let t=e.toLowerCase();return t==="true"||t==="false"}if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!U_t(t in e?e[t]:null))return!1;return!0}function q_t(e){if(typeof e=="boolean")return e;if(typeof e=="string")return e.toLowerCase()==="true";if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!q_t(t in e?e[t]:null))return!1;return!0}function qye(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n>=55296&&n<=56319){let s=e.charCodeAt(t+1);if(t+1>=e.length||s<56320||s>57343)throw new wu("Cannot stringify an unpaired surrogate like the flags service");t++}else if(n>=56320&&n<=57343)throw new wu("Cannot stringify an unpaired surrogate like the flags service")}}function a6e(e,t=new Set){if(e===null||typeof e=="boolean")return;if(typeof e=="string")return void qye(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new wu(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new wu("Cannot represent a circular array during local evaluation");t.add(e);try{for(let n=0;n<e.length;n++)if(n in e)a6e(e[n],t)}finally{t.delete(e)}return}if(typeof e=="object"){let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new wu("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new wu("Cannot represent a circular object during local evaluation");t.add(e);try{for(let s of Object.keys(e))qye(s),a6e(e[s],t)}finally{t.delete(e)}return}throw new wu(`Cannot represent ${typeof e} like the flags service`)}function Njn(e,t){let n=0,s=0;while(n<e.length&&s<t.length){let c=e.charCodeAt(n),u=t.charCodeAt(s),d=c>=55296&&c<=56319,m=u>=55296&&u<=56319,y=d?e.charCodeAt(n+1):0,S=m?t.charCodeAt(s+1):0,T=d?(c-55296)*1024+y-56320+65536:c,C=m?(u-55296)*1024+S-56320+65536:u;if(T!==C)return T-C;n+=d?2:1,s+=m?2:1}return e.length-t.length}function V_t(e,t=new Set){if(e===null)return"null";if(typeof e=="string")return qye(e),JSON.stringify(e);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))throw new wu(`Cannot stringify non-finite number ${e} like the flags service`);if(Number.isInteger(e))throw new wu(`Cannot distinguish integer ${e} from an integral JSON float during local evaluation`);return String(e)}if(Array.isArray(e)){if(t.has(e))throw new wu("Cannot stringify a circular array during local evaluation");t.add(e);try{let n=[];for(let s=0;s<e.length;s++)n.push(s in e?V_t(e[s],t):"null");return`[${n.join(",")}]`}finally{t.delete(e)}}if(typeof e=="object"){let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new wu("Cannot stringify a non-JSON object like the flags service");if(t.has(e))throw new wu("Cannot stringify a circular object during local evaluation");t.add(e);try{let s=Object.keys(e);return s.forEach(qye),`{${s.sort(Njn).map((c)=>`${JSON.stringify(c)}:${V_t(e[c],t)}`).join(",")}}`}finally{t.delete(e)}}throw new wu(`Cannot stringify ${typeof e} like the flags service`)}function Uye(e){if(typeof e=="string")return qye(e),e;return V_t(e)}function Rjn(e){let t=[],n=-1,s="";for(let c=0;c<e.length;c++){let u=e[c];if(u.charCodeAt(0)>127)return null;if(u==="\\"){let d=e[++c];if(d===void 0)break;if(d==="x"){if(!/^[\da-f]{2}$/i.test(e.slice(c+1,c+3)))return null;c+=2}else if(!"dDsSwWbBfnrtv".includes(d)&&!Ojn.test(d))return null;if(n===-1&&"bB".includes(d))return null;s="literal";continue}if(u==="["){if(n!==-1)return null;n=c}else if(u==="]"&&n!==-1){let d=n+(e[n+1]==="^"?2:1);if(c===d)return null;t.push(e.slice(n,c+1)),n=-1,s="literal";continue}else if(n!==-1){if(["&&","--","~~"].includes(e.slice(c,c+2)))return null;continue}else if(u==="("&&e[c+1]==="?"){if(e[c+2]!==":")return null;c+=2}else if(u==="{"){let d=/^\{(\d+)(?:,(\d*))?\}/.exec(e.slice(c));if(!d||["","|","("].includes(s)||d.slice(1).some((m)=>Number(m)>4294967295))return null}else if("*+?}".includes(u)&&(e[c+1]==="+"||e[c+1]==="{"))return null;if("*+?{".includes(u)&&["^","$","empty group"].includes(s))return null;s=u===")"&&["(","empty group"].includes(s)?"empty group":u}return t}function $ye(e){let t=new wu(e);return Object.defineProperty(t,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),t}function Mjn(e,t){if(e==="")return!0;let n=Rjn(e);if(n===null)throw $ye("Regex syntax requires server evaluation");let s;try{s=new RegExp(e)}catch(c){if(c instanceof SyntaxError)return null;throw $ye("Regex compilation requires server evaluation")}for(let c of n)try{new RegExp(c,"u")}catch{throw $ye("Regex character class syntax requires server evaluation")}for(let c=0;c<t.length;c++){let u=t[c];if(u.charCodeAt(0)>127||u==="\r")throw $ye("Regex matching for Unicode or carriage returns requires server evaluation")}try{return s.test(t)}catch{throw $ye("Regex execution requires server evaluation")}}function wD(e){return String(e).replace(/[A-Z]/g,(t)=>t.toLowerCase())}function War(e,t,n){if(!/^\d+$/.test(e)||n==="strict"&&e.length>1&&e[0]==="0")throw new wu(`Invalid semver: ${t}`);return parseInt(e,10)}function wG(e,t="strict"){let s=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!s||s.startsWith("."))throw new wu(`Invalid semver: ${e}`);let c=s.split("."),u=(d)=>{if(d===void 0||d==="")return 0;return War(d,e,t)};return[u(c[0]),u(c[1]),u(c[2])]}function $_t(e,t){for(let n=0;n<3;n++){if(e[n]<t[n])return-1;if(e[n]>t[n])return 1}return 0}function Har(e,t){let n=wG(e,t);return{lower:[n[0],n[1],n[2]],upper:[n[0],n[1]+1,0]}}function Gar(e,t){let[n,s,c]=wG(e,t),u=[n,s,c],d;return d=n>0?[n+1,0,0]:s>0?[0,s+1,0]:[0,0,c+1],{lower:u,upper:d}}function Xar(e,t){let s=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!s)throw new wu(`Invalid wildcard semver: ${e}`);let c=s.split("."),u=(y)=>{if(t==="legacy-permissive"){let S=parseInt(y,10);if(!isNaN(S))return S}else try{return War(y,e,t)}catch{}throw new wu(`Invalid wildcard semver: ${e}`)},d=u(c[0]);if(c.length===1)return{lower:[d,0,0],upper:[d+1,0,0]};let m=u(c[1]);return{lower:[d,m,0],upper:[d,m+1,0]}}function Yar(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new wu(`${e} is in an invalid date format`)}throw new wu(`The date provided ${e} must be a string, number, or date object`)}function J_t(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,n=e.match(t),s=new Date(new Date().toISOString());if(!n||!n.groups)return null;let c=parseInt(n.groups.number);if(c>=1e4)return null;let u=n.groups.interval;if(u==="h")s.setUTCHours(s.getUTCHours()-c);else if(u==="d")s.setUTCDate(s.getUTCDate()-c);else if(u==="w")s.setUTCDate(s.getUTCDate()-7*c);else if(u==="m")s.setUTCMonth(s.getUTCMonth()-c);else{if(u!=="y")return null;s.setUTCFullYear(s.getUTCFullYear()-c)}return s}function Qar(e){if(typeof e=="boolean")throw new wu("Date operations cannot be performed on boolean values");return J_t(String(e))??Yar(e)}function Kar(e,t={}){let n=e.value,s=t.semverParsingPolicy??"strict";switch(e.operator||"exact"){case"exact":case"is_not":for(let c of Array.isArray(n)?n:[n])Uye(c);return;case"is_set":case"is_not_set":case"icontains":case"not_icontains":case"starts_with":case"not_starts_with":case"ends_with":case"not_ends_with":case"regex":case"not_regex":case"gt":case"gte":case"lt":case"lte":return;case"is_date_after":case"is_date_before":Qar(n);return;case"semver_eq":case"semver_neq":case"semver_gt":case"semver_gte":case"semver_lt":case"semver_lte":wG(String(n),s);return;case"semver_tilde":Har(String(n),s);return;case"semver_caret":Gar(String(n),s);return;case"semver_wildcard":Xar(String(n),s);return;default:throw new wu(`Unknown operator: ${e.operator}`)}}function W_t(e,t,n={}){try{return Fjn(e,t,n)}catch(s){if(s instanceof wu&&s.reason==="missing_context")Kar(e,n);throw s}}function Fjn(e,t,n){let{key:s,value:c}=e,u=e.operator||"exact",d=n.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,s)){if(u==="is_not_set")return!1;else if(u==="is_set")return!0}else throw new wu(`Property ${s} not found in propertyValues`,"missing_context");let y=t[s];if(y===void 0)throw n.warnFunction?.(`Property ${s} cannot have a value of undefined with the ${u} operator`),new wu(`Property ${s} is undefined in propertyValues`);if(y===null&&!Pjn.includes(u))return n.warnFunction?.(`Property ${s} cannot have a value of null with the ${u} operator`),!1;let S=(B,z)=>{if(n.propertyMatchingVersion!==2&&U_t(B)||Array.isArray(B)&&B.length===0)return $ne(()=>a6e(z)),q_t(B)===q_t(z);if(n.propertyMatchingVersion===2&&typeof z=="number"&&U_t(B))return $ne(()=>a6e(z)),!1;if(Array.isArray(B)){let K=$ne(()=>Uye(z)).toLowerCase();return B.some((ie)=>Uye(ie).toLowerCase()===K)}return Uye(B).toLowerCase()===$ne(()=>Uye(z)).toLowerCase()},T=(B,z,X)=>{if(X==="gt")return B>z;if(X==="gte")return B>=z;if(X==="lt")return B<z;if(X==="lte")return B<=z;throw Error(`Invalid operator: ${X}`)},C=()=>$ne(()=>wG(String(y),d)),D=()=>{let B=wG(String(c),d);return $_t(C(),B)},L=({lower:B,upper:z})=>{let X=C();return $_t(X,B)>=0&&$_t(X,z)<0};switch(u){case"exact":return S(c,y);case"is_not":return!S(c,y);case"is_set":return!0;case"icontains":return wD(y).includes(wD(c));case"not_icontains":return!wD(y).includes(wD(c));case"starts_with":return wD(y).startsWith(wD(c));case"not_starts_with":return!wD(y).startsWith(wD(c));case"ends_with":return wD(y).endsWith(wD(c));case"not_ends_with":return!wD(y).endsWith(wD(c));case"regex":case"not_regex":{let B=Mjn(String(c),String(y));if(B===null)return!1;return u==="regex"?B:!B}case"gt":case"gte":case"lt":case"lte":{let B=typeof c=="number"?c:parseFloat(String(c)),z=typeof y=="number"?y:y!=null?parseFloat(String(y)):NaN;if(Number.isFinite(B)&&Number.isFinite(z))return T(z,B,u);return T(String(y),String(c),u)}case"is_date_after":case"is_date_before":{let B=Qar(c),z=$ne(()=>Yar(y));return u==="is_date_before"?z<B:z>B}case"semver_eq":return D()===0;case"semver_neq":return D()!==0;case"semver_gt":return D()>0;case"semver_gte":return D()>=0;case"semver_lt":return D()<0;case"semver_lte":return D()<=0;case"semver_tilde":return L(Har(String(c),d));case"semver_caret":return L(Gar(String(c),d));case"semver_wildcard":return L(Xar(String(c),d));default:throw new wu(`Unknown operator: ${u}`)}}async function Zar(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");let n=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map((s)=>s.toString(16).padStart(2,"0")).join("")}async function Vye(e,t,n="",s="."){let c=await Zar(`${e}${s}${t}${n}`);return parseInt(c.slice(0,15),16)/Djn}async function H_t(e,t){if(e==null||e.id==null||e.exclusion_percentage==null)return;let n=Number(e.exclusion_percentage);if(!Number.isFinite(n))return;let s=Math.min(Math.max(n,0),100);if(s!==100){if(await Vye("holdout",t,"","-")>s/100)return}return`holdout-${e.id}`}function c6e(e){let t=[],n=0;for(let s of e){let c=n+s.rollout_percentage/100;t.push({valueMin:n,valueMax:c,key:s.key}),n=c}return t}async function G_t(e,t,n){let s=await Vye(e,t,"variant");return c6e(n).find((c)=>s>=c.valueMin&&s<c.valueMax)?.key}function X_t(e,t){if(t===!1||t==null||!e)return null;let n=typeof t=="boolean"?t.toString():t,s=e[n]||null;return s==null?null:jne(s)}var Pjn,Djn=1152921504606847000,wu,Ojn;var ecr=We(()=>{Bye();Pjn=["exact","is_not","icontains","not_icontains","starts_with","not_starts_with","ends_with","not_ends_with","regex","not_regex"];wu=class wu extends Error{constructor(e,t="unsupported_definition"){super(e);this.name=this.constructor.name,this.reason=t,Object.setPrototypeOf(this,wu.prototype)}};Ojn=/[\x20-\x2f:;=?@\x5b-\x60\x7b-\x7e]/});function jjn(){return{ancestors:new WeakSet,remainingNodes:GFe}}function h4(e,t){try{return rcr(e,t,jjn(),0)}catch{return[]}}function zjn(e,t){let n=e.toString(),s=BigInt(Ljn);if(e>=s||e<-s)return t?.debug(`Attribute ${n} is outside the int64 range; encoding it as a string`),{stringValue:n};return{intValue:n}}function Y_t(e,t,n,s){if(n.remainingNodes<=0)return{stringValue:YFe};if(n.remainingNodes--,dor(e))return{boolValue:e};if(typeof e=="bigint")return zjn(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("u"<typeof BigInt)return{stringValue:String(e)};let c=BigInt(e).toString();if(e>=tcr||e<-tcr)return t?.debug(`Attribute ${c} is outside the int64 range; encoding it as a string`),{stringValue:c};return{intValue:c}}return{doubleValue:e}}if(typeof e=="string")return{stringValue:m4(e)};if(typeof e=="function")return{stringValue:$or};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(n.ancestors.has(e))return{stringValue:XFe};if(s>=HFe)return{stringValue:YFe};if(e instanceof Date){let c=e.getTime(),u=Number.isFinite(c)?e.toISOString():String(e);return{stringValue:typeof u=="string"?m4(u):String(u)}}n.ancestors.add(e);try{try{let c=e.toJSON;if(typeof c=="function")return Y_t(c.call(e),t,n,s+1)}catch{}if(j2(e))return{arrayValue:{values:$jn(e,t,n,s+1)}};return{kvlistValue:{values:rcr(e,t,n,s+1)}}}finally{n.ancestors.delete(e)}}return{stringValue:m4(String(e))}}function $jn(e,t,n,s){let c=[],u=Math.min(e.length,Rne),d=0;for(;d<u&&n.remainingNodes>0;d++)try{let m=d in e?e[d]:void 0;if(qR(m))continue;c.push(Y_t(m,t,n,s))}catch{c.push({stringValue:VR})}if(e.length>d)c.push({stringValue:YFe});return c}function rcr(e,t,n,s){let c=[];for(let u in e)if(Bjn.call(e,u)){if(!u){t?.debug("Dropping an attribute with an empty key");continue}if(c.length>=Rne||n.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let d=e[u];if(__t(d)||UB(d))continue;c.push({key:m4(u),value:Y_t(d,t,n,s)})}catch{c.push({key:m4(u),value:{stringValue:VR}})}}return c}var tcr=9223372036854776000,Ljn="9223372036854775808",Bjn;var Une=We(()=>{Uz();VB();Bjn=Object.prototype.propertyIsEnumerable});function Jye(e,t,n){return{...qB({},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":n}}function Wye(e,t){let n=qB({},e),s={};for(let c of Ujn)if(Object.prototype.hasOwnProperty.call(n,c))s[c]=n[c],delete n[c];return[...h4(n,t),...h4(s,t)]}function qjn(e){if(!e)return;return Object.prototype.hasOwnProperty.call(ncr,e)?ncr[e]:e}function Q_t(e,t){let n=qjn(e);return{...n?{"os.name":n}:{},...t?{"os.version":t}:{}}}var Ujn,ncr;var Hye=We(()=>{VB();Une();Ujn=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];ncr={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"}});var Vjn,Qcs;var K_t=We(()=>{$v();VB();Une();Hye();Vjn={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}},Qcs=Vjn.info});class qne{constructor(e){this._onFire=e,this._firesAt=0}get pending(){return!!this._timer}arm(e){this.clear(),this._firesAt=Date.now()+e,this._timer=RE(()=>{this._timer=void 0,this._onFire()},e)}armNoEarlierThan(e){if(this._timer&&Date.now()+e<=this._firesAt)return;this.arm(e)}clear(){if(this._timer)clearTimeout(this._timer),this._timer=void 0}}var l6e=We(()=>{$v()});function Xye(){return 0.75+Math.random()*0.25*2}function Yye(e,t,n,s){let c=Math.min(Math.max(0,t-1),6),u=e*2**c,d=s===void 0?u:Math.min(u,Math.max(s,e));return Math.round(d*n)}var Gye=30000,SD=1;var u6e=()=>{};var icr=We(()=>{K_t();zz();$v();l6e();Fne();u6e()});function Yjn(e){let t=new Uint8Array(e),n=globalThis.crypto;if(n&&typeof n.getRandomValues=="function")try{return n.getRandomValues(t),t}catch{}for(let s=0;s<e;s++)t[s]=Math.floor(256*Math.random());return t}function Qjn(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}function scr(e){let t=Qjn(Yjn(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function ocr(){return scr(16)}function acr(){return scr(8)}function ccr(e,t,n){return typeof e=="string"&&e.length===t&&e!==n&&Xjn.test(e)}function lcr(e){return ccr(e,32,Gjn)}function ucr(e){return ccr(e,16,"0000000000000000")}var Gjn="00000000000000000000000000000000",Xjn;var Z_t=We(()=>{Xjn=/^[0-9a-f]+$/});function f6e(e){let t=fcr(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:Zjn(t.flags)}}function Zjn(e){return 1&parseInt(e,16)?Vne:e9n}function fcr(e){if(typeof e!="string")return;let t=Kjn.exec(e.trim());if(!t)return;let[,n,s,c,u,d]=t;if(n==="ff")return;if(n==="00"&&d)return;if(!lcr(s)||!ucr(c))return;return{version:n,traceId:s,spanId:c,flags:u}}function dcr(e){return fcr(e)&&e.trim()}function d6e(e){return Array.isArray(e)&&e.length===1?e[0]:e}function pcr(e,t,n=Vne){return`00-${e}-${t}-${n}`}function p6e(e){if(typeof e!="string")return;let t=e.trim();if(!t)return;if(/[^\x20-\x7e\t]/.test(t))return;let n=t.split(",");if(n.length>t9n)return;for(let s of n)if(s.trim()&&!s.includes("="))return;if(t.length<=emt)return t;return n9n(n)}function n9n(e){let t=[...e],n=()=>t.reduce((s,c)=>s+c.length,0)+t.length-1;for(let s=t.length-1;s>=0&&n()>emt;s--)if(t[s].length>r9n)t.splice(s,1);while(t.length&&n()>emt)t.pop();return t.length?t.join(","):void 0}var Kjn,Vne="01",e9n="00",t9n=32,emt=512,r9n=128;var _6e=We(()=>{Z_t();Kjn=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/});function m6e(e){return String(e)+"000000"}function tmt(e,t,n,s){let c="";if(s)c=Object.keys(s).sort().map((d)=>`${JSON.stringify(d)}:${JSON.stringify(s[d])}`).join(",");return`${e}\x00${t}\x00${n??""}\x00${c}`}function _cr(e,t){for(let n=0;n<t.length;n++)if(e<=t[n])return n;return t.length}function rmt(e,t,n){return Jye(e,t,n)}function nmt(e,t,n,s){return{resourceMetrics:[{resource:{attributes:Wye(t)},scopeMetrics:[{scope:{name:n,version:s},metrics:e}]}]}}var Qye;var mcr=We(()=>{Hye();Qye=[0,5,10,25,50,75,100,250,500,750,1000,2500,5000,7500,1e4]});function h6e(e){let t=e?.resourceAttributes;return{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1000}}var hcr=()=>{};class g6e{constructor(e,t,n){this._instance=e,this._config=t,this._logger=n,this._series=new Map,this._flushTimer=new qne(()=>this.flush().catch((s)=>{this._logger.error("Metrics flush failed:",s)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new Mne,this._consecutiveFlushFailures=0,this._flushJitter=SD,this._generation=0}count(e,t=1,n){this._capture({name:e,type:"count",value:t,unit:n?.unit,attributes:n?.attributes})}gauge(e,t,n){this._capture({name:e,type:"gauge",value:t,unit:n?.unit,attributes:n?.attributes})}histogram(e,t,n){this._capture({name:e,type:"histogram",value:t,unit:n?.unit,attributes:n?.attributes})}flush(){let e=this._flushPromise,n=(async()=>{if(e)await e.catch(()=>{});await this._doFlush()})().finally(()=>{if(this._flushPromise===n)this._flushPromise=null});return this._flushPromise=n,n}drainWindow(){if(this._series.size===0)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=SD,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){if(this._instance.isDisabled||this._instance.optedOut)return;let t=this._runBeforeSend(e);if(t===null)return;if(!t.name||typeof t.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof t.value!="number"||!Number.isFinite(t.value))return void this._logger.warn(`Dropping metric '${t.name}': value must be a finite number`);if(t.type==="count"&&t.value<0)return void this._logger.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let n,s;try{n=t.attributes?{...t.attributes}:void 0,s=tmt(t.type,t.name,t.unit,n)}catch(m){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,m);return}let c=this._series.get(s);if(!c){if(!this._admitNewSeries())return;c={name:t.name,type:t.type,unit:t.unit,attributes:n,windowStartMs:Date.now()},this._series.set(s,c)}let u=this._typeByName.get(t.name);if(u===void 0)this._typeByName.set(t.name,t.type);else if(u!==t.type&&!this._typeCollisionWarned.has(t.name))this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${u}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`);this._fold(c,t.value);let d=this._activeTraceContext();if(d)c.exemplar={...d,value:t.value,timeMs:Date.now()};this._armFlushTimer()}_activeTraceContext(){try{let e=f6e(this._instance.getActiveSpan?.()?.traceparent());if(e&&e.flags===Vne)return{traceId:e.traceId,spanId:e.spanId}}catch{}}_admitNewSeries(){if(this._series.size<this._config.maxSeriesPerFlush)return!0;if(!this._seriesCapWarned)this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);return!1}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{if(!e.hist)e.hist={count:0,sum:0,min:t,max:t,bucketCounts:Array(Qye.length+1).fill(0)};let 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[_cr(t,Qye)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let n=j2(t)?t:[t],s=e;for(let c of n)try{let u=c(s);if(!u)return this._logger.info("Metric was rejected in beforeSend function"),null;s=u}catch(u){return this._logger.error("Error in beforeSend function for metric:",u),null}return s}_armFlushTimer(){if(this._flushTimer.pending)return;this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(Yye(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,Gye),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),this._series.size===0)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t!==this._generation)return;if(this._retryAfter.record(n),n.kind==="retry-later")this._consecutiveFlushFailures++,this._flushJitter=Xye();else this._consecutiveFlushFailures=0,this._flushJitter=SD;if(this._flushTimer.pending)this._flushTimer.arm(this._nextFlushDelay());switch(n.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",n.error);return}}_buildPayload(e){return nmt(this._buildMetrics(e),rmt(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=m6e(Date.now()),n=new Map;for(let s of e.values()){let c=tmt(s.type,s.name,s.unit,void 0),u=n.get(c);if(!u){if(u={name:s.name,...s.unit&&{unit:s.unit}},s.type==="count")u.sum={aggregationTemporality:gcr,isMonotonic:!0,dataPoints:[]};else if(s.type==="gauge")u.gauge={dataPoints:[]};else u.histogram={aggregationTemporality:gcr,dataPoints:[]};n.set(c,u)}let d=h4(s.attributes??{},this._logger),m=m6e(s.windowStartMs),y=i9n(s.exemplar);if(s.type==="count"){let S={attributes:d,startTimeUnixNano:m,timeUnixNano:t,asDouble:s.total??0,...y};u.sum.dataPoints.push(S)}else if(s.type==="gauge"){let S={attributes:d,timeUnixNano:t,asDouble:s.last??0,...y};u.gauge.dataPoints.push(S)}else if(s.hist){let S={attributes:d,startTimeUnixNano:m,timeUnixNano:t,count:s.hist.count,sum:s.hist.sum,min:s.hist.min,max:s.hist.max,bucketCounts:s.hist.bucketCounts,explicitBounds:Qye,...y};u.histogram.dataPoints.push(S)}}return Array.from(n.values())}_mergeWindowBack(e){for(let[t,n]of e){let s=this._series.get(t);if(!s){if(this._admitNewSeries())this._series.set(t,n);continue}switch(s.windowStartMs=Math.min(s.windowStartMs,n.windowStartMs),s.exemplar=s.exemplar??n.exemplar,s.type){case"count":s.total=(s.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(s.hist){s.hist.count+=n.hist.count,s.hist.sum+=n.hist.sum,s.hist.min=Math.min(s.hist.min,n.hist.min),s.hist.max=Math.max(s.hist.max,n.hist.max);for(let c=0;c<s.hist.bucketCounts.length;c++)s.hist.bucketCounts[c]+=n.hist.bucketCounts[c]}else s.hist=n.hist;break}}}}function i9n(e){if(!e)return{};return{exemplars:[{filteredAttributes:[],timeUnixNano:m6e(e.timeMs),asDouble:e.value,traceId:e.traceId,spanId:e.spanId}]}}var gcr=1;var ycr=We(()=>{$v();l6e();Fne();u6e();Une();_6e();mcr();hcr()});function SG(e,t,n,s){if(typeof e=="string"&&e.trim())return e.length>n?e.slice(0,n):e;return s?.debug(`${t} must be a non-empty string; using "unknown"`),"unknown"}function Jne(e){if(e==null)return;let t=e;if(e instanceof Date)try{t=e.getTime()}catch{return}if(typeof t!="number"||!Number.isFinite(t))return;if(t<0||t>9223372036854)return;return t}function vcr(e,t,n){let s=Jne(e);if(s===void 0){if(e!==void 0)n?.debug("Span startTime is out of range or not a valid time; using the current time");return t}if(t-s>86400000)n?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp");else if(s>t)n?.debug("Span startTime is in the future; the span may export with a zero duration");return s}function y6e(e,t){return e<t?t:e}function Kye(e,t,n,s){let c=Jne(e);if(c===void 0){if(e!==void 0)s?.debug(`Span ${n} is out of range or not a valid time; using the derived time`);return t}return c}var imt=()=>{};function b6e(){let e=globalThis.performance;return typeof e?.now=="function"?e.now():void 0}class Zye{constructor(e,t,n){this._onEnd=t,this._logger=n,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=e.traceId,this._spanId=e.spanId,this._parentSpanId=e.parentSpanId,this._traceState=e.traceState,this._traceFlags=e.traceFlags??Vne,this._parentIsRemote=e.parentIsRemote??!1,this._name=e.name,this._kind=e.kind,this._autoKeys=new Set(e.autoAttributeKeys),this._maxAttributes=e.maxAttributes,this._maxEvents=e.maxEvents,this._maxAttributesPerEvent=e.maxAttributesPerEvent,this._maxAttributeValueLength=e.maxAttributeValueLength,this._attributes=Object.create(null);for(let s of Object.keys(e.attributes))this._writeAttribute(s,e.attributes[s]);if(this._startMono=e.backdated?void 0:b6e(),this._startTime=e.clockAnchor&&this._startMono!==void 0?e.clockAnchor.wall+(this._startMono-e.clockAnchor.mono):e.startTime,this._startMono!==void 0)this._clockAnchor=e.clockAnchor??{wall:this._startTime,mono:this._startMono}}_now(){if(this._startMono!==void 0){let e=b6e();if(e!==void 0)return this._startTime+Math.max(0,e-this._startMono)}return Date.now()}_mutable(e){if(this._ended)return this._logger?.debug(`Ignoring ${e} on a span that has already ended`),!1;return!0}_writeAttribute(e,t){if(qR(t)){if(e in this._attributes&&!this._autoKeys.has(e))this._userAttributeCount--;delete this._attributes[e];return}if(!this._autoKeys.has(e)&&!(e in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[e]=S6e(t,this._maxAttributeValueLength)}setAttribute(e,t){if(this._mutable("setAttribute"))this._writeAttribute(e,t);return this}setAttributes(e){if(this._mutable("setAttributes")){let t=qB({},e);for(let n of Object.keys(t))this._writeAttribute(n,t[n])}return this}addEvent(e,t,n){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let s=t&&Tcr(t,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:SG(e,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:Kye(n,this._now(),"event timestamp",this._logger),...s&&{attributes:s.attributes,...s.dropped&&{droppedAttributesCount:s.dropped}}})}return this}setStatus(e,t){if(this._mutable("setStatus")){if(e!=="ok"&&e!=="error")return this._logger?.debug(`Ignoring unknown span status "${String(e)}"; expected "ok" or "error"`),this;this._status={code:e,...t&&{message:omt(t,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(e){if(!this._mutable("recordException"))return this;let{type:t,message:n,stack:s}=amt(e);return this.addEvent(s9n,{"exception.type":t,"exception.message":n,...s&&{"exception.stacktrace":s}}),this.setStatus("error",n)}updateName(e){if(this._mutable("updateName"))this._name=SG(e,"Span name",this._maxAttributeValueLength,this._logger);return this}traceparent(){return pcr(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(e){if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let t=this._now(),n=Kye(e,t,"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:y6e(n,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}}function a9n(e){try{return typeof e=="string"?e:String(e)}catch{return VR}}function TG(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return 0;return Math.min(Math.floor(e),o9n)}function c9n(e,t){if(!t.length)return Object.keys(e);let n=t.filter((c)=>Object.prototype.propertyIsEnumerable.call(e,c)),s=new Set(n);return[...n,...Object.keys(e).filter((c)=>!s.has(c))]}function wcr(e,t,n,s,c,u,d=[]){let m=0,y=0,S={};for(let L of c9n(e.attributes,d)){let B=e.attributes[L];if(!qR(B)){if(!t.has(L)){if(m>=n){y++;continue}m++}Object.defineProperty(S,L,{value:S6e(B,u),enumerable:!0,writable:!0,configurable:!0})}}if(e.attributes=S,y)e.droppedAttributesCount=TG(e.droppedAttributesCount)+y;let T=0,C=0,D=[];for(let L of e.events){if(T>=s){C++;continue}if(T++,L.attributes){let B=Tcr(L.attributes,c,u);if(L.attributes=B.attributes,B.dropped)L.droppedAttributesCount=TG(L.droppedAttributesCount)+B.dropped}D.push(L)}if(e.events=D,C)e.droppedEventsCount=TG(e.droppedEventsCount)+C;if(e.status?.message)e.status={...e.status,message:omt(a9n(e.status.message),u)}}class smt{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}}function l9n(e){try{let t=e.stack;return typeof t=="string"&&t?{stack:t}:{}}catch{return{}}}function Wz(e,t){let n=d6e(e?.parent)??t,s=typeof n=="string"||n==null?n:bcr(n,"traceparent"),c=dcr(s);if(!c)return Scr;let u=typeof n=="string"||n==null?e?.tracestate:bcr(n,"tracestate");return new w6e(c,p6e(u))}function bcr(e,t){try{let n=e[t];return typeof n=="function"?n.call(e):void 0}catch{return}}function omt(e,t){return e.length>t?e.slice(0,t):e}function S6e(e,t){return v6e(e,t,{ancestors:new WeakSet,remainingNodes:GFe},0)}function v6e(e,t,n,s){if(e===null||typeof e!="object"){if(qR(e))return e;if(n.remainingNodes<=0)return e;return n.remainingNodes--,typeof e=="string"?omt(e,t):e}if(n.ancestors.has(e))return XFe;if(n.remainingNodes<=0||s>=HFe)return e;n.remainingNodes--,n.ancestors.add(e);try{if(e instanceof Date)return e;let c=u9n(e);if(c.selfDescribed)return qR(c.value)?String(c.value):v6e(c.value,t,n,s+1);if(j2(e)){let m=Math.min(e.length,Rne),y=[];for(let S=0;S<m;S++)try{y.push(v6e(e[S],t,n,s+1))}catch{y.push(VR)}if(e.length>m)y.length=e.length;return y}let u={},d=0;for(let m of Object.keys(e)){if(d>=Rne)break;let y;try{y=v6e(e[m],t,n,s+1)}catch{y=VR}if(m&&!qR(y))d++;Object.defineProperty(u,m,{value:y,enumerable:!0,writable:!0,configurable:!0})}return u}catch{return e}finally{n.ancestors.delete(e)}}function u9n(e){try{let t=e.toJSON;if(typeof t=="function")return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}function Tcr(e,t,n){let s;try{s=Object.keys(e)}catch{return{attributes:{},dropped:0}}let c={},u=0,d=0;for(let m of s){if(u>=t){d++;continue}let y;try{y=S6e(e[m],n)}catch{y=VR}if(!qR(y))u++,Object.defineProperty(c,m,{value:y,enumerable:!0,writable:!0,configurable:!0})}return{attributes:c,dropped:d}}function xcr(e,t){for(let n of Object.keys(e))e[n]=S6e(e[n],t);return e}function e0e(e,t,n){return t===Scr?n(t):e.with(t,()=>n(t))}function amt(e){try{let t=l9n(e);if($z(e))return{type:e.name||"Error",message:e.message||"",...t};if(typeof e=="string")return{type:"string",message:e};if(e&&typeof e=="object"){let n=e;if(typeof n.message=="string")return{type:typeof n.name=="string"?n.name:"Object",message:n.message,...t}}return{type:typeof e,message:String(e)}}catch{return{type:typeof e,message:""}}}var s9n="exception",o9n=4294967295,Scr,w6e;var T6e=We(()=>{_6e();imt();$v();VB();Scr=new smt;w6e=class w6e extends smt{constructor(e,t){super(),this._traceparent=e,this._tracestate=t}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}}});function m9n(e){let t=parseInt(e.traceFlags,16);return(Number.isFinite(t)?255&t:d9n)|p9n|(e.parentIsRemote?_9n:0)}function x6e(e){if(typeof e=="string")return m4(e);try{return m4(String(e))}catch{return VR}}function h9n(e){if(e&&Object.prototype.hasOwnProperty.call(cmt,e))return cmt[e];return cmt.internal}function lmt(e){let t=Math.floor(e),n=Math.round((e-t)*1e6);if(n>=1e6)t+=1,n=0;return String(t)+String(n).padStart(6,"0")}function g9n(e,t){let n={name:x6e(e.name),timeUnixNano:lmt(e.timestamp)};if(e.attributes){let c=h4(e.attributes,t);if(c.length)n.attributes=c}let s=TG(e.droppedAttributesCount);if(s)n.droppedAttributesCount=s;return n}function Ecr(e,t){let n={traceId:e.traceId,spanId:e.spanId,name:x6e(e.name),kind:h9n(e.kind),startTimeUnixNano:lmt(e.startTime),endTimeUnixNano:lmt(e.endTime),flags:m9n(e)};if(e.parentSpanId)n.parentSpanId=e.parentSpanId;if(e.traceState)n.traceState=x6e(e.traceState);let s=h4(e.attributes,t);if(s.length)n.attributes=s;if(e.events.length)n.events=e.events.map((d)=>g9n(d,t));let c=TG(e.droppedAttributesCount);if(c)n.droppedAttributesCount=c;let u=TG(e.droppedEventsCount);if(u)n.droppedEventsCount=u;if(e.status)n.status={code:f9n[e.status.code],...e.status.message&&{message:x6e(e.status.message)}};return n}function kcr(e,t,n){return Jye(e,t,n)}function Ccr(e,t,n,s,c){return{resourceSpans:[{resource:{attributes:Wye(t,c)},scopeSpans:[{scope:{name:n,version:s},spans:e}]}]}}var cmt,f9n,d9n=1,p9n=256,_9n=512;var Icr=We(()=>{T6e();Une();VB();Hye();cmt={internal:1,server:2,client:3,producer:4,consumer:5},f9n={ok:1,error:2}});function E6e(){return b6e()??Date.now()}function umt(e){try{return e instanceof Zye}catch{return!1}}function Pcr(e,t){let n=f6e(e);if(!n)return;return{traceId:n.traceId,parentSpanId:n.spanId,traceState:p6e(t),traceFlags:n.flags,isRemote:!0}}function y9n(e){try{return typeof e.traceparent=="function"}catch{return!1}}function v9n(e){return!!e.attributes&&typeof e.attributes=="object"&&!Array.isArray(e.attributes)&&Array.isArray(e.events)&&e.name!==void 0&&e.kind!==void 0&&e.startTime!==void 0&&e.endTime!==void 0}function k6e(e,t,n){if(e[t]!==n)e[t]=n}function b9n(e,t){try{let n=Object.getOwnPropertyDescriptors(e);for(let s of["traceId","spanId","parentSpanId","traceState"])n[s]={value:t[s],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(e),n)}catch{return e}}class C6e{constructor(e,t,n,s,c,u){this._instance=e,this._config=t,this._logger=n,this._getContext=s,this._contextManager=c,this._onSpanQueued=u,this._queue=[],this._flushTimer=new qne(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=SD,this._retryAfter=new Mne,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=t.maxExportBatchSize}startSpan(e,t){if(this._instance.isDisabled||this._instance.optedOut)return Wz(t,this._contextManager.active());let n=d6e(t?.parent);if(n&&typeof n!="string"&&!umt(n)){if(y9n(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),Wz(t,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let s=this._resolveParent(n,t);if(this._liveSpans.size>=this._config.maxLiveSpans)this._evictAgedSpans();if(this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached \u2014 spans are being started and never ended`),Wz(t,this._contextManager.active());let c=Date.now(),u=vcr(t?.startTime,c,this._logger),d=acr();this._liveSpans.set(d,E6e());let m=this._autoContextAttributes();return new Zye({traceId:s?.traceId??ocr(),spanId:d,parentSpanId:s?.parentSpanId,traceState:s?.traceState,traceFlags:s?.traceFlags,parentIsRemote:s?.isRemote,name:SG(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:t?.kind??"internal",attributes:qB({...m},t?.attributes),autoAttributeKeys:Object.keys(m),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:u,backdated:u!==c,clockAnchor:Jne(t?.startTime)===void 0?s?.clockAnchor:void 0},(y,S)=>this._onSpanEnd(y,S),this._logger)}withSpan(e,t,n){let s=typeof t=="function"?void 0:t,c=typeof t=="function"?t:n,u=this.startSpan(e,s);try{let d=e0e(this._contextManager,u,c);if(Jor(d))return d.then((m)=>(u.end(),m),(m)=>{throw this._recordCallbackError(u,m),u.end(),m});return u.end(),d}catch(d){throw this._recordCallbackError(u,d),u.end(),d}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;){if(!this._queue.length)return;if(!await(this._flushPromise??this._startFlush()))return}}_startFlush(){this._flushTimer.clear();let e=this._generation,t=Promise.resolve().then(()=>e===this._generation?this._flushInner():0).finally(()=>{if(this._flushPromise===t)this._flushPromise=null;this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=t,t}reset(){if(this._flushTimer.clear(),this._queue.length)this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`);this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=SD,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(e,t){if(typeof e=="string"){let s=Pcr(e,t?.tracestate);if(!s)this._logger.debug("Ignoring malformed traceparent; starting a new trace");return s}if(umt(e))return e.childContext();let n=this._contextManager.active();if(umt(n))return n.childContext();if(n instanceof w6e)return Pcr(n.traceparent(),n.tracestate()??void 0)}_autoContextAttributes(){let e;try{e=this._getContext()}catch(n){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",n),{}}let t={};if(e.distinctId)t.posthogDistinctId=e.distinctId;if(e.sessionId)t.sessionId=e.sessionId;if(e.currentUrl)t["url.full"]=e.currentUrl;if(e.screenName)t["screen.name"]=e.screenName;if(e.appState)t["app.state"]=e.appState;return t}_recordCallbackError(e,t){if(!(e instanceof Zye))return;let{type:n,message:s,stack:c}=amt(t);if(e.addEvent("exception",{"exception.type":n,"exception.message":s,...c&&{"exception.stacktrace":c}}),!e.statusIsExplicitlyOk)e.setStatus("error",s)}_evictAgedSpans(){let e=E6e()-this._config.maxSpanAgeMs,t=0;for(let[n,s]of this._liveSpans){if(s>e)break;this._liveSpans.delete(n),t++}if(t)this._recordDrop(t,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(e,t){if(!this._liveSpans.delete(e.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let n=this._runBeforeSpanSend(e,t);if(!n)return;if(this._reportLimitDrops(n),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) \u2014 raise the flush frequency or reduce span volume`);this._queue.push(n);try{this._onSpanQueued?.()}catch(s){this._logger.debug("Span queue notification failed",s)}if(!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen())this._armFlushTimerIfQueued();else this._flushInBackground()}_reportLimitDrops(e){let t=e.droppedAttributesCount??0,n=e.droppedEventsCount??0,s=0;for(let c of e.events)s+=c.droppedAttributesCount??0;if(t||n||s)this._logger.debug(`Span limits discarded data from "${e.name}": ${t} attributes, ${n} events, ${s} event attributes`)}_runBeforeSpanSend(e,t){if(!this._config.beforeSpanSend.length)return e;let n={traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,traceState:e.traceState},s={startTime:e.startTime,endTime:e.endTime},c={attributes:e.droppedAttributesCount,events:e.droppedEventsCount},u=Object.keys(e.attributes),d={traceFlags:e.traceFlags,parentIsRemote:e.parentIsRemote},m=e.status&&{...e.status},y=e,S=e;try{for(let D of this._config.beforeSpanSend){let L=D(y);if(!L)return this._recordDrop(1,"beforeSpanSend dropped it"),null;y=this._keepSpanIdentity(L,n)}if(S={traceId:n.traceId,spanId:n.spanId,parentSpanId:n.parentSpanId,traceState:n.traceState,name:y.name,kind:y.kind,status:y.status,attributes:y.attributes,events:y.events,startTime:y.startTime,endTime:y.endTime,traceFlags:d.traceFlags,parentIsRemote:d.parentIsRemote,droppedAttributesCount:c.attributes,droppedEventsCount:c.events},!v9n(S))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;if(S.name=SG(S.name,"Span name",this._config.maxAttributeValueLength,this._logger),S.status&&S.status.code!=="ok"&&S.status.code!=="error")this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),S.status=m;S.startTime=Jne(S.startTime)??s.startTime,S.endTime=y6e(Jne(S.endTime)??s.endTime,S.startTime);let C=[];for(let D of S.events)try{C.push({...D,name:SG(D.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:Kye(D.timestamp,S.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return S.events=C,wcr(S,t,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,u),S}catch(T){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",T),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(e,t){if(e.traceId!==t.traceId||e.spanId!==t.spanId||e.parentSpanId!==t.parentSpanId)this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{k6e(e,"traceId",t.traceId),k6e(e,"spanId",t.spanId),k6e(e,"parentSpanId",t.parentSpanId),k6e(e,"traceState",t.traceState)}catch{return b9n(e,t)}return e}_recordDrop(e,t){if(this._droppedSinceWarning+=e,this._dropReasons.add(t),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs)this._warnAboutDrops()}_warnAboutDrops(){if(!this._droppedSinceWarning)return;this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear()}_encodeBatch(e){let t=[];for(let n of e)try{t.push(Ecr(n,this._logger))}catch(s){this._logger.debug("Failed to encode a span; dropping it",s),this._recordDrop(1,"its attributes could not be encoded")}return t}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let e=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(e,"the user has opted out"),this._warnAboutDrops(),e}async _flushInner(){if(!this._queue.length)return 0;let e=this._discardQueueIfConsentWithdrawn();if(e)return e;let t=xcr(kcr(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._config.maxAttributeValueLength),n=this._instance.getLibraryId(),s=this._instance.getLibraryVersion(),c=this._queue.length,u=0,d=1/0,m=this._generation;try{while(c>0&&this._queue.length>0){let y=this._discardQueueIfConsentWithdrawn();if(y)return u+y;let S=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,T=Math.max(1,Math.min(S,d,c,this._queue.length)),C=this._queue.slice(0,T),D=this._encodeBatch(C);if(!D.length){this._queue.splice(0,T),c-=T,u+=T,this._resetHeadBatchBudget();continue}let L=E6e()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),B=await this._instance._sendTracesBatch(Ccr(D,t,n,s,this._logger));if(m!==this._generation)break;if(this._retryAfter.record(B),B.kind==="ok"){if(this._consecutiveFlushFailures=0,this._flushJitter=SD,this._resetHeadBatchBudget(),this._queue.splice(0,T),c-=T,u+=T,this._maxExportBatchSize<this._config.maxExportBatchSize)this._maxExportBatchSize++;continue}if(B.kind==="too-large"){if(T===1){this._queue.splice(0,1),c-=1,u+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=SD,this._resetHeadBatchBudget();continue}let z=Math.max(1,Math.floor(T/2));if(B.measuredLocally)d=z;else this._maxExportBatchSize=z;this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${z}`);continue}if(B.kind==="retry-later"){if(this._consecutiveFlushFailures++,this._flushJitter=Xye(),this._headBatchSize=T,L)this._headBatchFailures++,this._headBatchChargeableAt=E6e()+this._nextFlushDelay();if(this._headBatchFailures<Acr)return this._logger.debug("Span export failed; retrying on the next flush",B.error),u;if(this._queue.splice(0,T),c-=T,u+=T,this._consecutiveFlushFailures=0,this._flushJitter=SD,this._resetHeadBatchBudget(),this._recordDrop(T,`the ingestion endpoint failed ${Acr} times in a row`),this._retryAfter.isOpen())return u;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",B.error),this._queue.splice(0,T),c-=T,u+=T,this._consecutiveFlushFailures=0,this._flushJitter=SD,this._resetHeadBatchBudget(),this._recordDrop(T,"the ingestion endpoint rejected the batch")}return u}finally{this._warnAboutDrops()}}_flushInBackground(){if(this._backgroundFlush)return;this._backgroundFlush=this.flush().catch((e)=>{this._logger.debug("Background span flush failed",e)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()})}_armFlushTimerIfQueued(){if(this._flushTimer.pending||!this._queue.length)return;this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){if(!this._queue.length)return;this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(Yye(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,Gye),this._retryAfter.remainingMs())}}var Acr=8;var Dcr=We(()=>{T6e();Z_t();_6e();imt();VB();Icr();$v();l6e();Fne();u6e()});class I6e{active(){return this._active}with(e,t){let n=this._active;this._active=e;try{return t()}finally{this._active=n}}}var Ncr=()=>{};function Hz(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=1?e:t}function P9n(e){if(!e||typeof e!="object"||Array.isArray(e))return;try{if(Ocr.every((n)=>!(n in e)||typeof e[n]=="string"))return e;let t={...e};for(let n of Ocr)if(n in t&&typeof t[n]!="string")delete t[n];return t}catch{return}}function D9n(e,t){if(!e)return[];let n=[e].flat().filter((c)=>Boolean(c)),s=n.filter((c)=>typeof c=="function");if(s.length!==n.length)t?.critical(`beforeSpanSend: ignoring ${n.length-s.length} of ${n.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`);return s}function fmt(e,t,n){let s=qB({...t},P9n(e?.resourceAttributes)),c=Hz(e?.maxExportBatchSize,S9n);return{serviceName:s?.["service.name"]??e?.serviceName,serviceVersion:s?.["service.version"]??e?.serviceVersion,environment:s?.["deployment.environment"]??e?.environment,resourceAttributes:s,beforeSpanSend:D9n(e?.beforeSpanSend,n),maxAttributesPerSpan:Hz(e?.maxAttributesPerSpan,x9n),maxEventsPerSpan:Hz(e?.maxEventsPerSpan,E9n),maxAttributesPerEvent:k9n,maxAttributeValueLength:Hz(e?.maxAttributeValueLength,C9n),flushIntervalMs:Hz(e?.flushIntervalMs,w9n),maxExportBatchSize:c,maxQueueSize:Math.max(Hz(e?.maxQueueSize,T9n),c),maxLiveSpans:Hz(e?.maxLiveSpans,I9n),maxSpanAgeMs:Hz(e?.maxSpanAgeMs,A9n)}}var w9n=5000,S9n=512,T9n=2048,x9n=128,E9n=128,k9n=128,C9n=8192,I9n=1e4,A9n=3600000,Ocr;var Rcr=We(()=>{VB();Ocr=["service.name","service.version","deployment.environment"]});var Mcr=We(()=>{zz()});var TD=We(()=>{R_t();Bye();ecr();B_t();K_t();Une();Hye();icr();ycr();Dcr();Ncr();T6e();Rcr();Dne();Mcr();$v();Nar();Uar();z_t();Var();Jar();zz()});import{constants as Fcr}from"fs";import{open as N9n}from"fs/promises";import{isAbsolute as jcr}from"path";import{createInterface as O9n}from"readline";async function zcr(e,t=N9n,n){let s={},c;try{c=process.cwd()}catch{}for(let m=e.length-1;m>=0;m--){let y=e[m],S=y?.filename;if(!y||typeof S!="string"||typeof y.lineno!="number"||z9n(S)||$9n(y))continue;if(!jcr(S)&&c===void 0)continue;if(!s[S])s[S]=[];s[S].push(y.lineno)}let u=Object.keys(s);if(u.length==0)return e;let d=[];for(let m of u){let y=$cr(m,c);if(y===void 0)continue;if(t0e.get(y))continue;let S=s[m];if(!S)continue;S.sort((D,L)=>D-L);let T=q9n(S);if(T.every((D)=>U9n(y,D)))continue;let C=V9n(A6e,y,{});d.push(L9n(m,T,C,y,t,n))}if(await Promise.all(d).catch(()=>{}),e&&e.length>0)B9n(e,A6e,c);return A6e.reduce(),e}async function F9n(e,t,n){let s,c=!1;try{s=await t(e,Fcr.O_RDONLY|Fcr.O_NONBLOCK);let u=await s.stat();if(!u.isFile())return;if(u.size>dmt)return void n?.debug(`Skipping source context for oversized file ${e}: ${u.size} bytes exceeds ${dmt}`);return c=!0,s}catch{return}finally{if(s&&!c)await s.close().catch(()=>{})}}async function L9n(e,t,n,s,c,u){let d=await F9n(e,c,u);if(d===void 0)return void t0e.set(s,1);let m=d;return new Promise((y)=>{let S=!1;function T(ye){if(S)return;S=!0,ye?.destroy(),m.close().then(y,y)}let C;try{C=m.createReadStream({autoClose:!1,start:0,end:dmt-1})}catch{t0e.set(s,1),T();return}let D;try{D=O9n({input:C})}catch{t0e.set(s,1),T(C);return}let L=0,B=0,z=t[B];if(z===void 0)return void T(C);let X=z[0],K=z[1];function ie(){t0e.set(s,1),D.close(),D.removeAllListeners(),T(C)}C.on("error",ie),D.on("error",ie),D.on("close",()=>T(C)),D.on("line",(ye)=>{if(L++,L<X)return;if(n[L]=J9n(ye,0),L>=K){if(B===t.length-1){D.close(),D.removeAllListeners();return}B++;let Te=t[B];if(Te===void 0){D.close(),D.removeAllListeners();return}X=Te[0],K=Te[1]}})})}function B9n(e,t,n){for(let s of e)if(s.filename&&s.context_line===void 0&&typeof s.lineno=="number"){let c=$cr(s.filename,n),u=c===void 0?void 0:t.get(c);if(u===void 0)continue;j9n(s.lineno,s,u)}}function j9n(e,t,n){if(t.lineno===void 0||n===void 0)return;t.pre_context=[];for(let c=Ucr(e);c<e;c++){let u=n[c];if(u===void 0)return void Lcr(t);t.pre_context.push(u)}if(n[e]===void 0)return void Lcr(t);t.context_line=n[e];let s=qcr(e);t.post_context=[];for(let c=e+1;c<=s;c++){let u=n[c];if(u===void 0)break;t.post_context.push(u)}}function Lcr(e){delete e.pre_context,delete e.context_line,delete e.post_context}function z9n(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function $9n(e){if(e.lineno!==void 0&&e.lineno>M9n)return!0;if(e.colno!==void 0&&e.colno>R9n)return!0;return!1}function $cr(e,t){if(jcr(e))return JSON.stringify([null,e]);return t===void 0?void 0:JSON.stringify([t,e])}function U9n(e,t){let n=A6e.get(e);if(n===void 0)return!1;for(let s=t[0];s<=t[1];s++)if(n[s]===void 0)return!1;return!0}function q9n(e){if(!e.length)return[];let t=0,n=e[0];if(typeof n!="number")return[];let s=Bcr(n),c=[];while(!0){if(t===e.length-1){c.push(s);break}let u=e[t+1];if(typeof u!="number")break;if(u<=s[1])s[1]=u+pmt;else c.push(s),s=Bcr(u);t++}return c}function Bcr(e){return[Ucr(e),qcr(e)]}function Ucr(e){return Math.max(1,e-pmt)}function qcr(e){return e+pmt}function V9n(e,t,n){let s=e.get(t);if(s===void 0)return e.set(t,n),n;return s}function J9n(e,t){let n=e,s=n.length;if(s<=150)return n;if(t>s)t=s;let c=Math.max(t-60,0);if(c<5)c=0;let u=Math.min(c+140,s);if(u>s-5)u=s;if(u===s)c=Math.max(u-140,0);if(n=n.slice(c,u),c>0)n=`...${n}`;if(u<s)n+="...";return n}var A6e,t0e,pmt=7,R9n=1000,M9n=1e4,dmt=10485760;var Vcr=We(()=>{TD();A6e=new O_t(25),t0e=new O_t(20)});import{isAbsolute as W9n,relative as H9n,sep as G9n}from"path";function Jcr(e=process.cwd()){let t=G9n==="\\",n=(c)=>t?c.replace(/\\/g,"/"):c,s=n(e);return async(c)=>{for(let u of c)if(!(!u.filename||u.filename.startsWith("node:")||u.filename.startsWith("data:"))){if(W9n(u.filename))u.filename=n(H9n(s,n(u.filename)))}return c}}var Wcr=()=>{};var Hcr="5.56.4";var Gcr=()=>{};var JB;var P6e=We(()=>{JB={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"}});class Gz{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e,t={}){let n=this._flags[e];return this._recordAccess(e),n?.enabled??t.defaultValue??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),!t)return;if(!t.enabled)return!1;return t.variant??!0}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let n=this._flags[t];if(n)e[t]=n}return this._cloneWith(e)}only(e){let t={},n=[];for(let s of e){let c=this._flags[s];if(c)t[s]=c;else n.push(s)}if(n.length>0)this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`);return this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[n,s]of Object.entries(this._flags)){let c=s.enabled===!1?!1:s.variant??!0;if(e[`$feature/${n}`]=c,s.enabled)t.push(n)}if(t.length>0)t.sort(),e.$active_feature_flags=t;return e}_cloneWith(e){return new Gz({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),this._distinctId==="")return;if(this._isSlice&&!(e in this._flags))return;let t=this._flags[e],n=t===void 0?void 0:t.enabled===!1?!1:t.variant??!0,s={$feature_flag:e,$feature_flag_response:n,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};if(t?.hasExperiment!==void 0)s.$feature_flag_has_experiment=t.hasExperiment;if(t?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0)s.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt;let c=[];if(this._errorsWhileComputing)c.push(JB.ERRORS_WHILE_COMPUTING);if(this._quotaLimited)c.push(JB.QUOTA_LIMITED);if(t===void 0)c.push(JB.FLAG_MISSING);if(c.length>0)s.$feature_flag_error=c.join(",");this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:s})}}var _mt=We(()=>{P6e()});function Xcr(e){return e==="client"||e==="server"?e:"all"}function Y9n(e,t){return e===t||e==="all"||t==="all"}function Q9n(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class mmt{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:n,timeout:s,host:c,customHeaders:u,...d}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=s,this.projectApiKey=n,this.host=c,this.poller=void 0,this.fetch=d.fetch||fetch,this.onError=d.onError,this.customHeaders=u,this.onLoad=d.onLoad,this.onMinimalFlagCalledEvents=d.onMinimalFlagCalledEvents,this.cacheProvider=d.cacheProvider,this.strictLocalEvaluation=d.strictLocalEvaluation??!1,this.evaluationContexts=d.evaluationContexts,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){if(this.debugMode)e()}withEvaluationSnapshot(e){if(e.definitions)return e;return{...e,evaluationCache:{},definitions:{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}}createEvaluationContext(e,t={},n={},s={},c={}){return{distinctId:e,groups:t,personProperties:n,groupProperties:s,evaluationCache:c}}async getFeatureFlag(e,t,n={},s={},c={}){await this.loadFeatureFlags();let u,d;if(!this.loadedSuccessfullyOnce)return u;if(d=this.featureFlagsByKey[e],d!==void 0){let m=this.createEvaluationContext(t,n,s,c);try{u=(await this.computeFlagAndPayloadLocally(d,m)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${u}`))}catch(y){if(y instanceof g4||y instanceof wu)this.logMsgIfDebug(()=>console.debug(`${y.name} when computing flag locally: ${e}: ${y.message}`));else if(y instanceof Error)this.onError?.(Error(`Error computing flag locally: ${e}: ${y}`))}}return u}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let n={},s={},c=this.featureFlags.length==0,u=t?t.map((m)=>this.featureFlagsByKey[m]).filter(Boolean):this.featureFlags,d=this.withEvaluationSnapshot({...e,definitions:void 0});return await Promise.all(u.map(async(m)=>{try{let{value:y,payload:S}=await this.computeFlagAndPayloadLocally(m,d,{skipLoadCheck:!0});if(n[m.key]=y,S)s[m.key]=S}catch(y){if(y instanceof g4||y instanceof wu)this.logMsgIfDebug(()=>console.debug(`${y.name} when computing flag locally: ${m.key}: ${y.message}`));else if(y instanceof Error)this.onError?.(Error(`Error computing flag locally: ${m.key}: ${y}`));c=!0}})),{response:n,payloads:s,fallbackToFlags:c}}async computeFlagAndPayloadLocally(e,t,n={}){let{matchValue:s,skipLoadCheck:c=!1}=n;if(this.loadedSuccessfullyOnce)t=this.withEvaluationSnapshot(t);if(!c)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};t=this.withEvaluationSnapshot(t),e=t.definitions.featureFlagsByKey[e.key]??e;let u;u=s!==void 0?s:await this.computeFlagValueLocally(e,t);let d=X_t(e.filters?.payloads,u);return{value:u,payload:d}}async computeFlagValueLocally(e,t){let{distinctId:n,groups:s,personProperties:c,groupProperties:u}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new wu("Flag has experience continuity enabled");let m=(e.filters||{}).aggregation_group_type_index;if(m!=null){let y=t.definitions.groupTypeMapping[String(m)];if(!y)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${m} for feature flag ${e.key}`)),new wu("Flag has unknown group type index");if(!(y in s))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;if(e.bucketing_identifier==="device_id"&&(c?.$device_id===void 0||c?.$device_id===null||c?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let S=u[y];return await this.matchFeatureFlagProperties(e,s[y],S,t)}{let y=this.getBucketingValueForFlag(e,n,c);if(y===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new wu(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,y,c,t)}}getBucketingValueForFlag(e,t,n){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let s=n?.$device_id;if(s==null||s==="")return;return s}return t}async evaluateFlagDependency(e,t,n){let{evaluationCache:s}=n,c=e.key;if(!n.definitions.featureFlagsByKey)throw new wu("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new wu(`Flag dependency property for '${c}' is missing required 'dependency_chain' field`);let u=e.dependency_chain;if(!Array.isArray(u))throw new wu(`Flag dependency property for '${c}' has an invalid 'dependency_chain' (expected array, got ${typeof u})`);if(u.length===0)throw new wu(`Circular dependency detected for flag '${c}' (empty dependency chain)`);for(let m of u){if(!(m in s)){let S=n.definitions.featureFlagsByKey[m];if(S)if(S.active)try{let T=await this.computeFlagValueLocally(S,n);s[m]=T}catch(T){throw new wu(`Error evaluating flag dependency '${m}' for flag '${c}': ${T}`)}else s[m]=!1;else if(n.definitions.filteredOutFlagKeys.has(m))s[m]=!1;else throw new wu(`Missing flag dependency '${m}' for flag '${c}'`)}if(s[m]==null)throw new wu(`Dependency '${m}' could not be evaluated`)}let d=s[c];return this.flagEvaluatesToExpectedValue(e.value,d)}flagEvaluatesToExpectedValue(e,t){if(typeof e=="boolean")return e===t||typeof t=="string"&&t!==""&&e===!0;if(typeof e=="string")return t===e;return!1}async matchFeatureFlagProperties(e,t,n,s){s=this.withEvaluationSnapshot(s);let c=e.filters||{},u=await H_t(c.holdout,t);if(u!==void 0)return u;let d=c.groups||[],m=c.aggregation_group_type_index,y=c.early_exit??!1,{groups:S,groupProperties:T}=s,C=!1,D;for(let L of d)try{let B=L.aggregation_group_type_index!==void 0?L.aggregation_group_type_index:m,z=n,X=t;if(B!==m){if(B!=null){let ie=s.definitions.groupTypeMapping[String(B)];if(!ie||!(ie in S)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${B} not available`));continue}if(!(ie in T)){C=!0;continue}z=T[ie],X=S[ie]}}let K=await this.isConditionMatch(e,X,L,z,s);if(K==="match"){let ie=L.variant,ye=c.multivariate?.variants||[];D=ie&&ye.some((Te)=>Te.key===ie)?ie:await this.getMatchingVariant(e,X)||!0;break}if(y&&K==="out_of_rollout_bound"){if(C)break;return!1}}catch(B){if(B instanceof g4)throw B;if(B instanceof wu)C=!0;else throw B}if(D!==void 0)return D;if(C)throw new wu("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,n,s,c){c=this.withEvaluationSnapshot(c);let u=c.definitions,d=n.rollout_percentage,m=(y)=>{this.logMsgIfDebug(()=>console.warn(y))};if((n.properties||[]).length>0){for(let y of n.properties){let S=y.type,T=!1;if(S==="cohort"){let C=await Qcr(y,s,u.cohorts,this.debugMode,(D)=>this.evaluateFlagDependency(D,s,c),u.propertyMatchingVersion);T=y.operator==="not_in"?!C:C}else T=S==="flag"?await this.evaluateFlagDependency(y,s,c):Ycr(y,s,m,u.propertyMatchingVersion);if(!T)return"no_match"}if(d==null)return"match"}if(d!=null&&await Vye(e.key,t)>d/100)return"out_of_rollout_bound";return"match"}async getMatchingVariant(e,t){return G_t(e.key,t,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return c6e(e.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(e){if(!this.evaluationContexts||this.evaluationContexts.length===0)return e;let t=new Set(this.evaluationContexts);return e.filter((n)=>{let s=n.evaluation_contexts??n.evaluation_tags;if(!s||s.length===0)return!0;return s.some((c)=>t.has(c))})}getEvaluationRuntimeForFlag(e){let t=this.featureFlagsByKey[e];return t?Xcr(t.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(e){return this.featureFlags.filter((t)=>Y9n(Xcr(t.evaluation_runtime),e)).map((t)=>t.key)}updateFlagState(e){let t=this.filterFlagsByEvaluationContexts(e.flags),n=t.reduce((u,d)=>(u[d.key]=d,u),{}),s=new Set(t.map((u)=>u.key)),c=new Set(e.flags.filter((u)=>!s.has(u.key)).map((u)=>u.key));this.featureFlags=t,this.featureFlagsByKey=n,this.filteredOutFlagKeys=c,this.groupTypeMapping=e.group_type_mapping??e.groupTypeMapping??{},this.cohorts=e.cohorts,this.propertyMatchingVersion=e.property_matching_version??e.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((e.minimal_flag_called_events??e.minimalFlagCalledEvents)===!0)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter((n)=>n.ensure_experience_continuity);if(t.length>0)console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map((n)=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();if(t)return this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags),!0;return!1}catch(t){return this.onError?.(Error(`Failed to load from cache: ${t}`)),!1}}async loadFeatureFlags(e=!1){if(this.loadedSuccessfullyOnce&&!e)return;if(!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt)return void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period"));if(!this.loadingPromise)this.loadingPromise=this._loadFeatureFlags().catch((t)=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${t}`))).finally(()=>{this.loadingPromise=void 0});return this.loadingPromise}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let e=this.pollingInterval??30000;if(!this.shouldBeginExponentialBackoff)return e;return Math.min(X9n,e*2**this.backOffCount)}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){if(this.poller)clearTimeout(this.poller),this.poller=void 0;try{if(this.cacheProvider&&!this.personalApiKey)return void await this.loadFromCache("Loaded flags from cache (cache-only reader)");let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!e){if(await this.loadFromCache("Loaded flags from cache (skipped fetch)"))return;if(this.loadedSuccessfullyOnce)return}let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new xG(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new xG(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new xG(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await t.json()??{};if(!("flags"in n))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let s=n.group_type_mapping||{},c=n.minimal_flag_called_events===!0,u={flags:n.flags??[],group_type_mapping:s,cohorts:n.cohorts||{},minimal_flag_called_events:c,property_matching_version:n.property_matching_version,propertyMatchingVersion:n.property_matching_version,groupTypeMapping:s,minimalFlagCalledEvents:c};if(this.updateFlagState(u),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(u)}catch(d){this.onError?.(Error(`Failed to store in cache: ${d}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(e){if(e instanceof xG)this.onError?.(e)}finally{if(!this.pollerStopped&&this.pollingInterval!==null)this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval())}}getPersonalApiKeyRequestOptions(e="GET",t){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};if(t)n["If-None-Match"]=t;return{method:e,headers:n}}async _requestFeatureFlagDefinitions(){if(!this.personalApiKey)throw new xG("A secretKey or personalApiKey is required to fetch feature flag definitions from PostHog.");let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let c=new AbortController;n=RE(()=>{c.abort()},this.timeout),t.signal=c.signal}let s=()=>clearTimeout(n);try{let c=this.fetch,u=await c(e,t);if(u.status!==200)return s(),u;return{status:u.status,headers:u.headers,body:u.body,text:async()=>{try{return await u.text()}finally{s()}},json:async()=>{try{return await u.json()}finally{s()}}}}catch(c){throw s(),c}}async stopPoller(e=30000){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let t=this.cacheProvider.shutdown();if(t instanceof Promise)await qz(t,e,()=>{throw Error(`Cache shutdown timeout after ${e}ms`)})}catch(t){this.onError?.(Error(`Error during cache shutdown: ${t}`))}}}function Ycr(e,t,n,s){return W_t(e,t,{warnFunction:n,propertyMatchingVersion:s})}function K9n(e,t){if(!(e in t))throw new g4(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Qcr(e,t,n,s=!1,c,u){let d=String(e.value);K9n(d,n);let m=n[d];return Kcr(m,t,n,s,c,u)}async function Kcr(e,t,n,s=!1,c,u){if(!e)return!0;let{type:d,values:m}=e;if(!m||m.length===0)return!0;let y=!1;if("values"in m[0]){for(let S of m)try{let T=await Kcr(S,t,n,s,c,u);if(d==="AND"){if(!T)return!1}else if(T)return!0}catch(T){if(T instanceof g4)throw T;if(T instanceof wu){if(s)console.debug(`Failed to compute property ${S} locally: ${T}`);y=!0}else throw T}if(y)throw new wu("Can't match cohort without a given cohort property value");return d==="AND"}for(let S of m)try{let T;if(S.type==="cohort")T=await Qcr(S,t,n,s,c,u);else if(S.type==="flag"){if(!c)throw new wu(`Flag dependency '${S.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);T=await c(S)}else T=Ycr(S,t,void 0,u);let C=S.negation||!1;if(d==="AND"){if(!T&&!C)return!1;if(T&&C)return!1}else{if(T&&!C)return!0;if(!T&&C)return!0}}catch(T){if(T instanceof g4)throw T;if(T instanceof wu){if(s)console.debug(`Failed to compute property ${S} locally: ${T}`);y=!0}else throw T}if(y)throw new wu("can't match cohort without a given cohort property value");return d==="AND"}var X9n=60000,xG,g4;var Zcr=We(()=>{TD();xG=class xG extends Error{constructor(e){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,xG.prototype)}};g4=class g4 extends Error{constructor(e){super(e);Q9n(this,g4)}}});function nzn(e){let t=[],n="",s=!1;for(let c=0;c<e.length;c++){let u=e[c];if(u==="\\"&&s&&c+1<e.length)n+=e[++c];else if(u!==" "||s)if(u==='"')s=!s;else n+=u;else if(n)t.push(n),n=""}if(n)t.push(n);return t}function elr(e){let t;for(let n=0;n<e.length;n++){let s=e[n],c=Z9n.find((d)=>s===d||s.startsWith(`${d}=`));if(!c)continue;let u=s===c?e[++n]:s.slice(c.length+1);if(ezn.has(u))t=u}return t}function izn(e=tzn,t=rzn){return elr(e)??elr(nzn(t??""))??"throw"}function rlr(e,t,n){e(t,{mechanism:{type:n==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function szn(e,t){let n=!1;return Object.assign((s,c)=>{let u=global.process.listeners("uncaughtException").filter((d)=>d.name!=="domainUncaughtExceptionClear"&&d._posthogErrorHandler!==!0).length;if(rlr(e,s,c),!n&&u===0)n=!0,t(s)},{_posthogErrorHandler:!0})}function nlr(e,t,n=tlr){let s=globalThis.process;if(!s)return;if(n==="strict")return void s.on("uncaughtExceptionMonitor",(c,u)=>rlr(e,c,u));s.on("uncaughtException",szn(e,t))}function ilr(e,t=tlr){let n=globalThis.process;if(!n||t==="throw"||t==="strict"||t==="warn-with-error-code")return;n.on("unhandledRejection",(s)=>{e(s,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var Z9n,ezn,tzn,rzn,tlr;var slr=We(()=>{Z9n=["--unhandled-rejections","--unhandled_rejections"],ezn=new Set(["throw","strict","warn","warn-with-error-code","none"]),tzn=[...globalThis.process?.execArgv??[]],rzn=globalThis.process?.env?.NODE_OPTIONS;tlr=izn()});class D6e{constructor(e,t,n){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new y_t({...yor(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return zFe(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,n,s,c){let u={...c},d=e.buildFromUnknown(t,n);d.$exception_list=await e.modifyFrames(d.$exception_list);let m=Par();if(m)u.$release_id=m;return{event:"$exception",distinctId:s,properties:{...d,...u},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled())nlr(this.onException.bind(this),this.onFatalError.bind(this)),ilr(this.onException.bind(this))}onException(e,t){this.client.addPendingPromise((async()=>{if(!D6e.isPreviouslyCapturedError(e)){let n=await D6e.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),c=n.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(c))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:c});return this.client._capturePreparedEvent(n,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(ozn),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}var ozn=2000,EG;var hmt=We(()=>{slr();TD();EG=D6e});var olr;var alr=We(()=>{olr=function(e){return e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL",e}({})});var Xz="1.10.0";var gmt=()=>{};function azn(e){let t=new Set([e]),n=new Set,s=e.match(clr);if(!s)return()=>!1;let c={major:+s[1],minor:+s[2],patch:+s[3],prerelease:s[4]};if(c.prerelease!=null)return function(y){return y===e};function u(m){return n.add(m),!1}function d(m){return t.add(m),!0}return function(y){if(t.has(y))return!0;if(n.has(y))return!1;let S=y.match(clr);if(!S)return u(y);let T={major:+S[1],minor:+S[2],patch:+S[3],prerelease:S[4]};if(T.prerelease!=null)return u(y);if(c.major!==T.major)return u(y);if(c.major===0){if(c.minor===T.minor&&c.patch<=T.patch)return d(y);return u(y)}if(c.minor<=T.minor)return d(y);return u(y)}}var clr,llr;var ulr=We(()=>{gmt();clr=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;llr=azn(Xz)});function lzn(){return Object.defineProperty({},"version",{value:Xz,enumerable:!0,writable:!1,configurable:!1})}function xD(e,t,n,s=!1){var c;let u=O6e[N6e]=(c=O6e[N6e])!==null&&c!==void 0?c:lzn();if(!s&&u[e]){let d=Error(`@opentelemetry/api: Attempted duplicate registration of API: ${e}`);return n.error(d.stack||d.message),!1}if(u.version!=="1.10.0"){let d=Error(`@opentelemetry/api: Registration of version v${u.version} for ${e} does not match previously registered API v${Xz}`);return n.error(d.stack||d.message),!1}return u[e]=t,n.debug(`@opentelemetry/api: Registered a global for ${e} v${Xz}.`),!0}function ME(e){let t=O6e[N6e];if(t==null)return;if(t!==flr){if(!t.version||!llr(t.version))return;flr=t}return t[e]}function ED(e,t){t.debug(`@opentelemetry/api: Unregistering a global for ${e} v${Xz}.`);let n=O6e[N6e];if(n)delete n[e]}var czn,N6e,O6e,flr;var Yz=We(()=>{gmt();ulr();czn=Xz.split(".")[0],N6e=Symbol.for(`opentelemetry.js.api.${czn}`),O6e=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{}});function r0e(e,t,n){let s=ME("diag");if(!s)return;return s[e](t,...n)}var dlr=class{constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return r0e("debug",this._namespace,e)}error(...e){return r0e("error",this._namespace,e)}info(...e){return r0e("info",this._namespace,e)}warn(...e){return r0e("warn",this._namespace,e)}verbose(...e){return r0e("verbose",this._namespace,e)}};var plr=We(()=>{Yz()});function _lr(e,t){if(e<0)e=0;else if(e>9999)e=9999;t=t||{};function n(s,c){let u=t[s];if(typeof u==="function"&&e>=c)return u.bind(t);return function(){}}return{error:n("error",30),warn:n("warn",50),info:n("info",60),debug:n("debug",70),verbose:n("verbose",80)}}var mlr=()=>{};var uzn="diag",bb=class e{static instance(){if(!this._instance)this._instance=new e;return this._instance}constructor(){function t(c){return function(...u){let d=ME("diag");if(!d)return;return d[c](...u)}}let n=this,s=(c,u={logLevel:60})=>{var d;if(c===n){var m;let C=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((m=C.stack)!==null&&m!==void 0?m:C.message),!1}if(typeof u==="number")u={logLevel:u};let y=ME("diag"),S=_lr((d=u.logLevel)!==null&&d!==void 0?d:60,c);if(y&&!u.suppressOverrideMessage){var T;let C=(T=Error().stack)!==null&&T!==void 0?T:"<failed to generate stacktrace>";y.warn(`Current logger will be overwritten from ${C}`),S.warn(`Current logger will overwrite one already registered from ${C}`)}return xD("diag",S,n,!0)};n.setLogger=s,n.disable=()=>{ED(uzn,n)},n.createComponentLogger=(c)=>new dlr(c),n.verbose=t("verbose"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error")}};var Qz=We(()=>{Yz();plr();mlr()});var hlr=class e{constructor(t){this._entries=t?new Map(t):new Map}getEntry(t){let n=this._entries.get(t);if(!n)return;return Object.assign({},n)}getAllEntries(){return Array.from(this._entries.entries())}setEntry(t,n){let s=new e(this._entries);return s._entries.set(t,n),s}removeEntry(t){let n=new e(this._entries);return n._entries.delete(t),n}removeEntries(...t){let n=new e(this._entries);for(let s of t)n._entries.delete(s);return n}clear(){return new e}};var glr=()=>{};var ylr;var vlr=We(()=>{ylr=Symbol("BaggageEntryMetadata")});function blr(e={}){return new hlr(new Map(Object.entries(e)))}function wlr(e){if(typeof e!=="string")fzn.error(`Cannot create baggage metadata from unknown type: ${typeof e}`),e="";return{__TYPE__:ylr,toString(){return e}}}var fzn;var ymt=We(()=>{Qz();glr();vlr();fzn=bb.instance()});function Wne(e){return Symbol.for(e)}var R6e;var n0e=We(()=>{R6e=new class e{constructor(t){let n=this;n._currentContext=t?new Map(t):new Map,n.getValue=(s)=>n._currentContext.get(s),n.setValue=(s,c)=>{let u=new e(n._currentContext);return u._currentContext.set(s,c),u},n.deleteValue=(s)=>{let c=new e(n._currentContext);return c._currentContext.delete(s),c}}}});var vmt,bmt,Slr=class{constructor(){function e(t){return function(...n){let s=bmt[t];if(typeof s!=="function")s=bmt.log;if(typeof s!=="function"&&console){if(s=console[t],typeof s!=="function")s=console.log}if(typeof s==="function")return s.apply(console,n)}}for(let t=0;t<vmt.length;t++)this[vmt[t].n]=e(vmt[t].c)}};var Tlr=We(()=>{vmt=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}],bmt={};if(typeof console<"u"){for(let e of["error","warn","info","debug","trace","log"])if(typeof console[e]==="function")bmt[e]=console[e]}});function xlr(){return Smt}var dzn=class{constructor(){}createGauge(e,t){return wzn}createHistogram(e,t){return Szn}createCounter(e,t){return bzn}createUpDownCounter(e,t){return Tzn}createObservableGauge(e,t){return Ezn}createObservableCounter(e,t){return xzn}createObservableUpDownCounter(e,t){return kzn}addBatchObservableCallback(e,t){}removeBatchObservableCallback(e){}},M6e=class{},pzn,_zn,mzn,hzn,wmt=class{addCallback(e){}removeCallback(e){}},gzn,yzn,vzn,Smt,bzn,wzn,Szn,Tzn,xzn,Ezn,kzn;var Tmt=We(()=>{pzn=class extends M6e{add(e,t){}},_zn=class extends M6e{add(e,t){}},mzn=class extends M6e{record(e,t){}},hzn=class extends M6e{record(e,t){}},gzn=class extends wmt{},yzn=class extends wmt{},vzn=class extends wmt{},Smt=new dzn,bzn=new pzn,wzn=new mzn,Szn=new hzn,Tzn=new _zn,xzn=new gzn,Ezn=new yzn,kzn=new vzn});var Elr;var klr=We(()=>{Elr=function(e){return e[e.INT=0]="INT",e[e.DOUBLE=1]="DOUBLE",e}({})});function Clr(){return Emt}var xmt=class{emit(e){}enabled(){return!1}},Emt;var F6e=We(()=>{Emt=new xmt});var Ilr;var Alr=We(()=>{Ilr=function(e){return e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.TRACE=1]="TRACE",e[e.TRACE2=2]="TRACE2",e[e.TRACE3=3]="TRACE3",e[e.TRACE4=4]="TRACE4",e[e.DEBUG=5]="DEBUG",e[e.DEBUG2=6]="DEBUG2",e[e.DEBUG3=7]="DEBUG3",e[e.DEBUG4=8]="DEBUG4",e[e.INFO=9]="INFO",e[e.INFO2=10]="INFO2",e[e.INFO3=11]="INFO3",e[e.INFO4=12]="INFO4",e[e.WARN=13]="WARN",e[e.WARN2=14]="WARN2",e[e.WARN3=15]="WARN3",e[e.WARN4=16]="WARN4",e[e.ERROR=17]="ERROR",e[e.ERROR2=18]="ERROR2",e[e.ERROR3=19]="ERROR3",e[e.ERROR4=20]="ERROR4",e[e.FATAL=21]="FATAL",e[e.FATAL2=22]="FATAL2",e[e.FATAL3=23]="FATAL3",e[e.FATAL4=24]="FATAL4",e}({})});var L6e,B6e;var kmt=We(()=>{L6e={get(e,t){if(e==null)return;return e[t]},keys(e){if(e==null)return[];return Object.keys(e)}},B6e={set(e,t,n){if(e==null)return;e[t]=n}}});var Plr;var Dlr=We(()=>{Plr=function(e){return e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED",e}({})});var Cmt="0000000000000000",Imt="00000000000000000000000000000000",j6e;var Amt=We(()=>{j6e={traceId:Imt,spanId:Cmt,traceFlags:0}});var Kz=class{constructor(e=j6e){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,t){return this}setAttributes(e){return this}addEvent(e,t){return this}addLink(e){return this}addLinks(e){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,t){}};var z6e=We(()=>{Amt()});function Nlr(e,t){if(typeof e!=="string"||e.length!==t)return!1;let n=0;for(let s=0;s<e.length;s+=4)n+=($6e[e.charCodeAt(s)]|0)+($6e[e.charCodeAt(s+1)]|0)+($6e[e.charCodeAt(s+2)]|0)+($6e[e.charCodeAt(s+3)]|0);return n===t}function Pmt(e){return Nlr(e,32)&&e!=="00000000000000000000000000000000"}function Dmt(e){return Nlr(e,16)&&e!=="0000000000000000"}function Hne(e){return Pmt(e.traceId)&&Dmt(e.spanId)}function Olr(e){return new Kz(e)}var $6e;var U6e=We(()=>{z6e();$6e=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1])});var Rlr=class{active(){return R6e}with(e,t,n,...s){return t.call(n,...s)}bind(e,t){return t}enable(){return this}disable(){return this}attach(e){return{dispose(){}}}};var Mlr=We(()=>{n0e()});var Nmt="context",Czn,Izn,Zz=class e{constructor(){this._attachUnsupportedWarned=!1}static getInstance(){if(!this._instance)this._instance=new e;return this._instance}setGlobalContextManager(t){return xD(Nmt,t,bb.instance())}active(){return this._getContextManager().active()}with(t,n,s,...c){return this._getContextManager().with(t,n,s,...c)}bind(t,n){return this._getContextManager().bind(t,n)}attach(t){let n=this._getContextManager();if(n.attach)return n.attach(t);if(!this._attachUnsupportedWarned)this._attachUnsupportedWarned=!0,bb.instance().warn("The current ContextManager does not implement attach(). The context will not be attached. Use a ContextManager that supports attach() (e.g. AsyncLocalStorageContextManager) or use with()/bind() instead.");return Izn}_getContextManager(){return ME(Nmt)||Czn}disable(){this._getContextManager().disable(),ED(Nmt,bb.instance())}};var i0e=We(()=>{Yz();Qz();Mlr();Czn=new Rlr,Izn=Object.freeze({dispose:()=>{}})});function q6e(e){return e.getValue(Omt)||void 0}function Flr(){return q6e(Zz.getInstance().active())}function s0e(e,t){return e.setValue(Omt,t)}function Llr(e){return e.deleteValue(Omt)}function Blr(e,t){return s0e(e,new Kz(t))}function V6e(e){var t;return(t=q6e(e))===null||t===void 0?void 0:t.spanContext()}var Omt;var Rmt=We(()=>{n0e();i0e();z6e();Omt=Wne("OpenTelemetry Context Key SPAN")});function Azn(e){return e!==null&&typeof e==="object"&&"spanId"in e&&typeof e.spanId==="string"&&"traceId"in e&&typeof e.traceId==="string"&&"traceFlags"in e&&typeof e.traceFlags==="number"}var Mmt,J6e=class{startSpan(e,t,n=Mmt.active()){if(Boolean(t===null||t===void 0?void 0:t.root))return new Kz;let s=n&&V6e(n);if(Azn(s)&&Hne(s))return new Kz(s);else return new Kz}startActiveSpan(e,t,n,s){var c;let u,d,m;if(arguments.length<2)return;else if(arguments.length===2)m=t;else if(arguments.length===3)u=t,m=n;else u=t,d=n,m=s;let y=(c=d)!==null&&c!==void 0?c:Mmt.active(),S=this.startSpan(e,u,y),T=s0e(y,S);return Mmt.with(T,m,void 0,S)}};var Fmt=We(()=>{i0e();z6e();Rmt();U6e();Mmt=Zz.getInstance()});var Pzn,W6e=class{constructor(e,t,n,s){this._provider=e,this.name=t,this.version=n,this.options=s}startSpan(e,t,n){return this._getTracer().startSpan(e,t,n)}startActiveSpan(e,t,n,s){let c=this._getTracer();return Reflect.apply(c.startActiveSpan,c,arguments)}_getTracer(){if(this._delegate)return this._delegate;let e=this._provider.getDelegateTracer(this.name,this.version,this.options);if(!e)return Pzn;return this._delegate=e,this._delegate}};var Lmt=We(()=>{Fmt();Pzn=new J6e});var jlr;var zlr=We(()=>{jlr=function(e){return e[e.INTERNAL=0]="INTERNAL",e[e.SERVER=1]="SERVER",e[e.CLIENT=2]="CLIENT",e[e.PRODUCER=3]="PRODUCER",e[e.CONSUMER=4]="CONSUMER",e}({})});var $lr;var Ulr=We(()=>{$lr=function(e){return e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR",e}({})});function qlr(e){return Dzn.test(e)}function Vlr(e){return Nzn.test(e)&&!Ozn.test(e)}var Dzn,Nzn,Ozn;var Jlr=We(()=>{Dzn=new RegExp("^(?:[a-z][_0-9a-z-*/]{0,255}|[a-z0-9][_0-9a-z-*/]{0,240}@[a-z][_0-9a-z-*/]{0,13})$"),Nzn=/^[ -~]{0,255}[!-~]$/,Ozn=/,|=/});var Bmt=32,Wlr=512,Hlr=",",Glr="=",Xlr=class e{constructor(t){if(this._internalState=new Map,t)this._parse(t)}set(t,n){let s=this._internalState.get(t),c=this.serialize().length;if(typeof s==="string")c+=n.length-s.length;else{if(this._internalState.size>=Bmt)return this;c+=t.length+n.length+(this._internalState.size>0?2:1)}if(c>Wlr)return this;let u=this._clone();if(u._internalState.has(t))u._internalState.delete(t);return u._internalState.set(t,n),u}unset(t){let n=this._clone();return n._internalState.delete(t),n}get(t){return this._internalState.get(t)}serialize(){return Array.from(this._internalState.keys()).reduceRight((t,n)=>(t.push(n+Glr+this.get(n)),t),[]).join(Hlr)}_parse(t){if(t.length>Wlr)return;if(this._internalState=t.split(Hlr).reduceRight((n,s)=>{let c=s.trim(),u=c.indexOf(Glr);if(u!==-1){let d=c.slice(0,u),m=c.slice(u+1,s.length);if(qlr(d)&&Vlr(m))n.set(d,m)}return n},new Map),this._internalState.size>Bmt)this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,Bmt))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let t=new e;return t._internalState=new Map(this._internalState),t}};var Ylr=We(()=>{Jlr()});function Qlr(e){return new Xlr(e)}var Klr=We(()=>{Ylr()});var Zlr=class{getTracer(e,t,n){return new J6e}};var eur=We(()=>{Fmt()});var Rzn,o0e=class{getTracer(e,t,n){var s;return(s=this.getDelegateTracer(e,t,n))!==null&&s!==void 0?s:new W6e(this,e,t,n)}getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:Rzn}setDelegate(e){this._delegate=e}getDelegateTracer(e,t,n){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(e,t,n)}};var jmt=We(()=>{Lmt();eur();Rzn=new Zlr});var tur;var rur=We(()=>{tur=function(e){return e[e.NOT_RECORD=0]="NOT_RECORD",e[e.RECORD=1]="RECORD",e[e.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED",e}({})});var zmt;var nur=We(()=>{i0e();zmt=Zz.getInstance()});var $mt;var iur=We(()=>{Qz();$mt=bb.instance()});var Mzn=class{getLogger(e,t,n){return new xmt}},sur;var our=We(()=>{F6e();sur=new Mzn});var aur=class{constructor(e,t,n,s){this._provider=e,this.name=t,this.version=n,this.options=s}emit(e){this._getLogger().emit(e)}enabled(e){return this._getLogger().enabled(e)}_getLogger(){if(this._delegate)return this._delegate;let e=this._provider._getDelegateLogger(this.name,this.version,this.options);if(!e)return Emt;return this._delegate=e,this._delegate}};var cur=We(()=>{F6e()});var Umt=class{getLogger(e,t,n){var s;return(s=this._getDelegateLogger(e,t,n))!==null&&s!==void 0?s:new aur(this,e,t,n)}_getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:sur}_setDelegate(e){this._delegate=e}_getDelegateLogger(e,t,n){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getLogger(e,t,n)}};var lur=We(()=>{our();cur()});var qmt="logs",uur=class e{constructor(){this._proxyLoggerProvider=new Umt}static getInstance(){if(!this._instance)this._instance=new e;return this._instance}setGlobalLoggerProvider(t){let n=xD(qmt,t,bb.instance());if(n)this._proxyLoggerProvider._setDelegate(t);return n}getLoggerProvider(){return ME(qmt)||this._proxyLoggerProvider}getLogger(t,n,s){return this.getLoggerProvider().getLogger(t,n,s)}disable(){ED(qmt,bb.instance()),this._proxyLoggerProvider=new Umt}};var fur=We(()=>{Yz();Qz();lur()});var Vmt;var dur=We(()=>{fur();Vmt=uur.getInstance()});var Fzn=class{getMeter(e,t,n){return Smt}},pur;var _ur=We(()=>{Tmt();pur=new Fzn});var Jmt="metrics",mur=class e{constructor(){}static getInstance(){if(!this._instance)this._instance=new e;return this._instance}setGlobalMeterProvider(t){return xD(Jmt,t,bb.instance())}getMeterProvider(){return ME(Jmt)||pur}getMeter(t,n,s){return this.getMeterProvider().getMeter(t,n,s)}disable(){ED(Jmt,bb.instance())}};var hur=We(()=>{Yz();Qz();_ur()});var Wmt;var gur=We(()=>{hur();Wmt=mur.getInstance()});var yur=class{inject(e,t){}extract(e,t){return e}fields(){return[]}};var vur=()=>{};function Gmt(e){return e.getValue(Hmt)||void 0}function bur(){return Gmt(Zz.getInstance().active())}function wur(e,t){return e.setValue(Hmt,t)}function Sur(e){return e.deleteValue(Hmt)}var Hmt;var Tur=We(()=>{n0e();i0e();Hmt=Wne("OpenTelemetry Baggage Key")});var Xmt="propagation",Lzn,xur=class e{constructor(){this.createBaggage=blr,this.getBaggage=Gmt,this.getActiveBaggage=bur,this.setBaggage=wur,this.deleteBaggage=Sur}static getInstance(){if(!this._instance)this._instance=new e;return this._instance}setGlobalPropagator(t){return xD(Xmt,t,bb.instance())}inject(t,n,s=B6e){return this._getGlobalPropagator().inject(t,n,s)}extract(t,n,s=L6e){return this._getGlobalPropagator().extract(t,n,s)}fields(){return this._getGlobalPropagator().fields()}disable(){ED(Xmt,bb.instance())}_getGlobalPropagator(){return ME(Xmt)||Lzn}};var Eur=We(()=>{Yz();Qz();ymt();kmt();vur();Tur();Lzn=new yur});var Ymt;var kur=We(()=>{Eur();Ymt=xur.getInstance()});var Qmt="trace",Cur=class e{constructor(){this._proxyTracerProvider=new o0e,this.wrapSpanContext=Olr,this.isSpanContextValid=Hne,this.deleteSpan=Llr,this.getSpan=q6e,this.getActiveSpan=Flr,this.getSpanContext=V6e,this.setSpan=s0e,this.setSpanContext=Blr}static getInstance(){if(!this._instance)this._instance=new e;return this._instance}setGlobalTracerProvider(t){let n=xD(Qmt,this._proxyTracerProvider,bb.instance());if(n)this._proxyTracerProvider.setDelegate(t);return n}getTracerProvider(){return ME(Qmt)||this._proxyTracerProvider}getTracer(t,n){return this.getTracerProvider().getTracer(t,n)}disable(){ED(Qmt,bb.instance()),this._proxyTracerProvider=new o0e}};var Iur=We(()=>{Yz();Qz();Rmt();U6e();jmt()});var Kmt;var Aur=We(()=>{Iur();Kmt=Cur.getInstance()});var Pur={};oD(Pur,{DiagConsoleLogger:()=>Slr,DiagLogLevel:()=>olr,INVALID_SPANID:()=>Cmt,INVALID_SPAN_CONTEXT:()=>j6e,INVALID_TRACEID:()=>Imt,ProxyTracer:()=>W6e,ProxyTracerProvider:()=>o0e,ROOT_CONTEXT:()=>R6e,SamplingDecision:()=>tur,SeverityNumber:()=>Ilr,SpanKind:()=>jlr,SpanStatusCode:()=>$lr,TraceFlags:()=>Plr,ValueType:()=>Elr,baggageEntryMetadataFromString:()=>wlr,context:()=>zmt,createContextKey:()=>Wne,createNoopLogger:()=>Clr,createNoopMeter:()=>xlr,createTraceState:()=>Qlr,default:()=>Bzn,defaultTextMapGetter:()=>L6e,defaultTextMapSetter:()=>B6e,diag:()=>$mt,isSpanContextValid:()=>Hne,isValidSpanId:()=>Dmt,isValidTraceId:()=>Pmt,logs:()=>Vmt,metrics:()=>Wmt,propagation:()=>Ymt,trace:()=>Kmt});var Bzn;var Dur=We(()=>{alr();ymt();n0e();Tlr();Tmt();klr();F6e();Alr();kmt();Dlr();Amt();U6e();Lmt();zlr();Ulr();Klr();jmt();rur();nur();iur();dur();gur();kur();Aur();Bzn={context:zmt,diag:$mt,logs:Vmt,metrics:Wmt,propagation:Ymt,trace:Kmt}});async function Nur(){try{let t=(await($zn??=Promise.resolve().then(() => (Dur(),Pur)))).trace.getActiveSpan()?.spanContext(),n=t?.traceId,s=t?.spanId;if(typeof n=="string"&&typeof s=="string"&&jzn.test(n)&&zzn.test(s)&&!/^0+$/.test(n)&&!/^0+$/.test(s))return{$trace_id:n.toLowerCase(),$span_id:s.toLowerCase()}}catch{}return{}}var jzn,zzn,$zn;var Our=We(()=>{jzn=/^[0-9a-f]{32}$/i,zzn=/^[0-9a-f]{16}$/i});class Zmt{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}}var Rur=()=>{};function Uzn(e){return e==="v0"||e==="v1"}function Mur(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return Uzn(e)?e:"v0"}var Fur=()=>{};function Lur(e){return typeof e.event=="string"&&e.event.startsWith("$ai_")}var a0e="analytics",c0e="ai";var Bur=()=>{};var Gne;var jur=We(()=>{Gne=class Gne extends Error{constructor({requestId:e,drops:t,retryExhausted:n,cause:s}){super(Gne.buildMessage(e,t,n,s)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=n,this.cause=s}static buildMessage(e,t,n,s){let c=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${n.length} undelivered`;if(s instanceof Error)c+=` (${s.message})`;return c}}});function eht(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}}function qzn(e){return typeof e=="string"?e:void 0}function Wzn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Hzn(e){if(typeof e=="string"){let n=new Date(e);if(Number.isNaN(n.getTime()))return new Date().toISOString();let s=n.toISOString(),c=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return c&&c.length>3?s.replace(/\.\d{3}Z$/,`.${c}Z`):s}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=e==null?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}function zur(e,t,n){if(n!==void 0&&!(t in e))e[t]=n}function Gzn(e){let n={...Wzn(e.properties)?e.properties:{}},s={};for(let{property:u,optionKey:d,coerce:m}of Vzn)if(u in n){let y=m(n[u]);if(y!==void 0)s[d]=y;delete n[u]}let c={};for(let{property:u,field:d}of Jzn)if(u in n){let m=n[u];if(typeof m=="string")c[d]=m;delete n[u]}return delete n.$lib,delete n.$lib_version,zur(n,"$set",e.$set),zur(n,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:Hzn(e.timestamp),...c,options:s,properties:n}}function $ur(e,{createdAt:t,historicalMigration:n}){let s={created_at:t,batch:e.map(Gzn)};if(n)s.historical_migration=!0;return s}var Vzn,Jzn;var Uur=We(()=>{Vzn=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:eht},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:eht},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:eht},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:qzn}],Jzn=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}]});class tht{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??Yzn,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??((n)=>new Promise((s)=>RE(s,n))),this.generateRequestId=t.generateRequestId??OE,this.compress=t.compress??zye}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:s}=$ur(e,{createdAt:n,historicalMigration:this.config.historicalMigration}),c=`${this.config.host}${Xzn}`,u=[],d=s,m=Math.max(1,this.config.maxAttempts);for(let y=1;y<=m;y++){let S=y===m,T=gG({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:d}),C,D;try{C=await this.sendOnce(c,T,y,t);let{response:L,signal:B}=C,{status:z}=L;if(z<200||z>=300)if(!S&&Qzn.has(z)){let X=this.parseRetryAfter(L);await C.waitFor(C.cancelBody()).catch(()=>{}),D=this.backoffDelay(y,X)}else{let X=await this.buildHttpError(L,z,C.waitFor);return this.surfaceBatchFailure(t,u,d,X)}else{let X;try{X=await C.waitFor(this.parseResponse(L))}catch(ye){if(B.aborted)throw ye;return this.surfaceBatchFailure(t,u,d,Error(`Capture V1 returned an unparseable ${z} response body`))}let K=this.classify(d,X,u);if(K.length===0)return this.surfacePartialDrops(t,u);if(S)return void this.onError(new Gne({requestId:t,drops:u,retryExhausted:K.map((ye)=>ye.uuid)}));d=K;let ie=this.parseRetryAfter(L);D=this.backoffDelay(y,ie)}}catch(L){if(C&&!C.signal.aborted)throw L;if(S)return this.surfaceBatchFailure(t,u,d,L);D=this.backoffDelay(y)}finally{C?.cleanup()}if(D!==void 0)await this.sleep(D)}}async sendOnce(e,t,n,s){let c=this.buildHeaders(n,s),u=t;if(this.config.compressionEnabled){let T=await this.compress(t,this.config.isDebug);if(T!==null)u=T,c["Content-Encoding"]="gzip"}let d=new AbortController,m="waiting for response headers",y,S=new Promise((T,C)=>{y=RE(()=>{let D=Error(`Capture V1 request timed out ${m} after ${this.config.requestTimeoutMs}ms`);D.name="AbortError",C(D),d.abort(D)},this.config.requestTimeoutMs)});try{let T=this.fetchFn(e,{method:"POST",headers:c,body:u,signal:d.signal}),C=!1;T.then((X)=>{if(d.signal.aborted&&!C)this.cancelBody(X)}).catch(()=>{});let D=await Promise.race([T,S]);C=!0,m="while reading the response body";let L=!1,B,z=()=>B??=this.cancelBody(D);return{response:D,signal:d.signal,waitFor:(X)=>Promise.race([X,S]),cancelBody:z,cleanup:()=>{if(L)return;if(L=!0,clearTimeout(y),d.signal.aborted)z()}}}catch(T){throw clearTimeout(y),T}}buildHeaders(e,t){let n=`${this.config.libraryId}/${this.config.libraryVersion}`,s={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":n,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};if(this.config.userAgent)s["User-Agent"]=this.config.userAgent;return s}classify(e,t,n){let s=t.results??{},c=[];for(let u of e){let d=s[u.uuid];if(d){if(d.result==="drop")n.push({uuid:u.uuid,details:d.details??void 0});else if(d.result==="retry")c.push(u)}}return c}backoffDelay(e,t){let n=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);if(t===void 0)return n;return Math.max(n,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let n=t.trim();if(/^\d+$/.test(n)){let u=parseInt(n,10);return Number.isFinite(u)&&u>0?1000*u:void 0}let s=Date.parse(n);if(Number.isNaN(s))return;let c=s-this.now();return c>0?c:void 0}async parseResponse(e){let t=await e.text(),n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))throw Error("unexpected response shape");let s=n.results;if(s!==void 0&&(typeof s!="object"||s===null||Array.isArray(s)))throw Error("unexpected results shape");return{results:s??{}}}async buildHttpError(e,t,n){let s="";try{s=(await n(e.text())).slice(0,512)}catch{}let c=s?`: ${s}`:"";return Error(`Capture V1 request failed with HTTP ${t}${c}`)}surfaceBatchFailure(e,t,n,s){this.onError(new Gne({requestId:e,drops:t,retryExhausted:n.map((c)=>c.uuid),cause:s}))}surfacePartialDrops(e,t){if(t.length>0)this.onError(new Gne({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}}var Xzn="/i/v1/analytics/events",Yzn=30000,Qzn;var qur=We(()=>{TD();jur();Uur();Qzn=new Set([408,500,502,503,504])});var kG="ai-capture",H6e="/i/v0/ai/batch/",G6e=8388608,Vur=5242880;var rht=()=>{};function nht(e){return Kzn.encode(gG(e)).length}function Jur(e,t=G6e,n=Vur){let s=[],c=[],u=[],d=0;for(let m of e){if(m===void 0)continue;let y=nht(m);if(y>t){c.push({event:typeof m.event=="string"?m.event:"unknown",bytes:y});continue}if(u.length>0&&d+y>n)s.push(u),u=[],d=0;u.push(m),d+=y}if(u.length>0)s.push(u);return{batches:s,dropped:c}}var Kzn;var Wur=We(()=>{TD();rht();Kzn=new TextEncoder});function X6e(e,t){if(Gur.has(e))return;Gur.add(e),console.warn(`[PostHog] ${t}`)}function i$n(e){return typeof e=="string"?e.trim():""}function s$n(e){return(typeof e=="string"?e.trim():"")||void 0}function o$n(e){return(typeof e=="string"?e.trim():"")||n$n}function a$n(e){return(Array.isArray(e)?e:[e]).filter((n)=>typeof n=="string"&&n.trim().length>0)}function c$n(e){if(!e)return{};let t={};for(let[s,c]of Object.entries(e))t[`$feature/${s}`]=c;let n=Object.keys(e).filter((s)=>e[s]!==!1).sort();if(n.length>0)t.$active_feature_flags=n;return t}var Zzn=100,Hur=30000,e$n=50000,t$n=50,r$n=500,n$n="https://us.i.posthog.com",Gur,iht;var Xur=We(()=>{Gcr();TD();P6e();_mt();Zcr();hmt();Our();Rur();Fur();Bur();qur();Wur();rht();Gur=new Set;iht=class iht extends o6e{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(e){this._distinctIdHasSentFlagCalls=new Map(Object.entries(e??{}))}constructor(e,t={}){let n=i$n(e),s={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5000,host:o$n(t.host),personalApiKey:s$n(t.secretKey??t.personalApiKey)};if(super(n,s),this._memoryStorage=new Zmt,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=s,this.captureMode=Mur(),this.enableFullAiCapture=s.enableFullAiCapture===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof s.featureFlagsPollingInterval=="number"?Math.max(s.featureFlagsPollingInterval,Zzn):s.featureFlagsPollingInterval===null?null:Hur,typeof s.waitUntilDebounceMs=="number")this.options.waitUntilDebounceMs=Math.max(s.waitUntilDebounceMs,0);if(typeof s.waitUntilMaxWaitMs=="number")this.options.waitUntilMaxWaitMs=Math.max(s.waitUntilMaxWaitMs,0);if(!this.disabled&&(s.personalApiKey||s.flagDefinitionCacheProvider)){if(s.personalApiKey?.includes("phc_"))throw Error('A project API key ("phc_...") was provided as secretKey or personalApiKey. Pass the project API key as the first constructor argument. For local evaluation, set secretKey (or the deprecated personalApiKey alias) to a server-only Project Secret API Key ("phs_...") or Personal API Key ("phx_...") with feature flag read access.');if(s.enableLocalEvaluation!==!1)this.featureFlagsPoller=new mmt({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:s.personalApiKey,projectApiKey:n,timeout:s.requestTimeout??1e4,host:this.host,fetch:s.fetch,onError:(u)=>{this._events.emit("error",u)},onLoad:(u)=>{this._events.emit("localEvaluationFlagsLoaded",u)},onMinimalFlagCalledEvents:(u)=>{this._minimalFlagCalledEvents=u},customHeaders:this.getCustomHeaders(),cacheProvider:s.flagDefinitionCacheProvider,strictLocalEvaluation:s.strictLocalEvaluation,evaluationContexts:s.evaluationContexts??s.evaluationEnvironments})}this.errorTracking=new EG(this,s,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=s.maxCacheSize||e$n}enqueue(e,t,n,s){super.enqueue(e,t,n,s),this.scheduleDebouncedFlush()}_flushEventsAndSpans(e=!1){let t=this.flushWithPendingPromises();if(!this._traces||e&&this._traces.throttled)return t;return Rye([t,this._traces.flush().catch(()=>{})]).then(([n])=>{if(n.status==="rejected")throw n.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(e){let t=this._flushEventsAndSpans(e),n=this.options.waitUntil;if(n&&!this._waitUntilCycle)try{n(t.catch(()=>{}))}catch{}return t}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e)return;if(this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let u,d=new Promise((m)=>{u=m});try{e(d)}catch{return}this._waitUntilCycle={resolve:u,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??r$n,s=t>=n;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(s)return void this.resolveWaitUntilFlush();let c=this.options.waitUntilDebounceMs??t$n;this._waitUntilCycle.timer=RE(()=>{this.resolveWaitUntilFlush()},c)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;if(e)clearTimeout(e.timer),this._waitUntilCycle=void 0;return e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){return this.captureMode==="v1"&&Lur(e)?c0e:a0e}persistedQueueKeyForRoute(e){if(e===kG)return EC.AiCaptureQueue;return e===c0e?EC.AiQueue:EC.Queue}getActiveQueueRoutes(){let e=this.captureMode==="v1"?[a0e,c0e]:[a0e];if(this._aiCaptureRouteActive)e.push(kG);return e}getBatchEndpointPath(e){return e===kG?H6e:super.getBatchEndpointPath(e)}async sendBatch(e,t,n=a0e){if(n===kG)return this.sendAiCaptureBatch(e,t);if(this.captureMode!=="v1"||n===c0e)return super.sendBatch(e,t,n);let s=e.filter((c)=>c!==void 0);await this.getV1Sender().sendV1Batch(s)}async sendAiCaptureBatch(e,t){let{batches:n,dropped:s}=Jur(e);for(let{event:c,bytes:u}of s){let d=`Event ${c} (${u} bytes) exceeds the ${G6e/1048576}MiB limit for ${H6e}, dropping.`;this._logger.error(d),this._events.emit("error",Error(d))}for(let c of n)await this.sendAiSubBatch(c,t)}async sendAiSubBatch(e,t){try{await super.sendBatch(e,t,kG)}catch(n){if(!zne(n))throw n;if(e.length===1){let[c]=e,d=`Event ${typeof c.event=="string"?c.event:"unknown"} (${nht(c)} bytes) was rejected with 413 by ${H6e} on its own, dropping.`;this._logger.error(d),this._events.emit("error",Error(d));return}let s=Math.ceil(e.length/2);await this.sendAiSubBatch(e.slice(0,s),t),await this.sendAiSubBatch(e.slice(s),t)}}getV1Sender(){if(!this._v1Sender)this._v1Sender=new tht({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3000,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:(e)=>this._events.emit("error",e),compress:(e)=>this.compressPayload(e)});return this._v1Sender}getLibraryVersion(){return Hcr}get metrics(){if(!this._metrics)this._metrics=new g6e(this,h6e(this.options.metrics),this._logger);return this._metrics}initializeSpanContextManager(){return new I6e}hostResourceAttributes(){return{}}get _spanContextManager(){if(!this._spanContext)this._spanContext=this.initializeSpanContextManager();return this._spanContext}get _tracesPipeline(){if(!this.options.traces)return;if(!this._traces)this._traces=new C6e(this,fmt(this.options.traces,this.hostResourceAttributes(),this._logger),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush());return this._traces}_tracingContext(){let e=this.context?.get();return{distinctId:e?.distinctId,sessionId:e?.sessionId}}startSpan(e,t){return this._tracesPipeline?.startSpan(e,t)??Wz(t,this._spanContextManager.active())}withSpan(e,t,n){let s=typeof t=="function"?void 0:t,c=typeof t=="function"?t:n,u=this._tracesPipeline;if(!u)return e0e(this._spanContextManager,Wz(s,this._spanContextManager.active()),c);return s?u.withSpan(e,s,c):u.withSpan(e,c)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let e=super.getCommonEventProperties();if(this.options.isServer??!0)e.$is_server=!0;return e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,n){if(typeof e=="string")this._logger.warn(t);if(e.event==="$exception"&&!e._originatedFromCaptureException)this._logger.warn(n)}_sendPreparedEvent(e,t,n,s,c){return this.addPendingPromise(this._prepareEventMessage(t,s).then(({distinctId:u,event:d,properties:m,options:y})=>{let S={timestamp:y.timestamp,disableGeoip:y.disableGeoip,uuid:y.uuid},T={distinctId:u,event:d,properties:{...m,...this.getCommonEventProperties()}};return n?this.sendImmediate(e,T,S,c):this.enqueue(e,T,S,c)}).catch((u)=>{if(u)console.error(u)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}captureAi(e){if(this.disabled)return;let t=vG(e.uuid,OE);return this._sendPreparedAiEvent({...e,uuid:t},!1),t}async captureAiImmediate(e){if(this.disabled)return;let t=vG(e.uuid,OE);return await this._sendPreparedAiEvent({...e,uuid:t},!0),t}_sendPreparedAiEvent(e,t){if(typeof e?.event=="string"&&!e.event.startsWith("$ai_"))this._logger.debug(`captureAi called with non-AI event ${e.event}; routing it to the AI endpoint anyway.`);return this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",e,t,void 0,kG)}identify({distinctId:e,properties:t={},disableGeoip:n}){let{$set:s,$set_once:c,$anon_distinct_id:u,...d}=t,S={$set:s||d,$set_once:c||{},$anon_distinct_id:u??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:S,disableGeoip:n},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:n}){let{$set:s,$set_once:c,$anon_distinct_id:u,...d}=t,S={$set:s||d,$set_once:c||{},$anon_distinct_id:u??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:S,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:n={}}){if(Object.keys(t).length===0&&Object.keys(n).length===0)return;let s={};if(Object.keys(t).length>0)s.$set=t;if(Object.keys(n).length>0)s.$set_once=n;this.capture({distinctId:e,event:"$set",properties:s})}unsetPersonProperties({distinctId:e,properties:t}){let n=a$n(t);if(n.length===0)return;this.capture({distinctId:e,event:"$set",properties:{$unset:n}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(e){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(e)}getFeatureFlagKeysByEvaluationRuntime(e){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(e)??[]}async waitForLocalEvaluationReady(e=Hur){if(this.isLocalEvaluationReady())return!0;if(this.featureFlagsPoller===void 0)return!1;return new Promise((t)=>{let n=setTimeout(()=>{s(),t(!1)},e),s=this._events.on("localEvaluationFlagsLoaded",(c)=>{clearTimeout(n),s(),t(c>0)})})}_resolveDistinctId(e,t){if(typeof e=="string")return{distinctId:e,options:t};return{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,n={},s){if(this.disabled)return void this._logger.warn("The client is disabled");let c=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let he=this._flagOverrides[e];if(he===void 0)return;let re=this._payloadOverrides?.[e];return{key:e,enabled:he!==!1,variant:typeof he=="string"?he:void 0,payload:re}}let{groups:u,disableGeoip:d}=n,{onlyEvaluateLocally:m,personProperties:y,groupProperties:S}=n,T=this.addLocalPersonAndGroupProperties(t,u,y,S);y=T.allPersonProperties,S=T.allGroupProperties;let C=this.createFeatureFlagEvaluationContext(t,u,this.personPropertiesForLocalEvaluation(t,y),S);if(m==null)m=this.options.strictLocalEvaluation??!1;let D,L=!1,B,z,X,K,ie,ye,Te;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let he=this.featureFlagsPoller?.featureFlagsByKey[e];if(he)try{let re=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(he,C,{matchValue:s});if(re){L=!0;let Fe=re.value;K=he.id,ye="Evaluated locally",Te=he.has_experiment,D={key:e,enabled:Fe!==!1,variant:typeof Fe=="string"?Fe:void 0,payload:re.payload??void 0,reason:ye,reasonCode:he.active===!1?"flag_disabled":void 0}}}catch(re){if(re instanceof g4||re instanceof wu)this._logger?.info(`${re.name} when computing flag locally: ${e}: ${re.message}`);else throw re}}if(!L&&!m){let he=await super.getFeatureFlagDetailsStateless(C.distinctId,C.groups,y,S,d,[e]);if(he===void 0)X=JB.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=he.minimalFlagCalledEvents===!0,B=he.requestId,z=he.evaluatedAt;let re=[];if(he.errorsWhileComputingFlags)re.push(JB.ERRORS_WHILE_COMPUTING);if(he.quotaLimited?.includes("feature_flags"))re.push(JB.QUOTA_LIMITED);let Fe=he.flags[e];if(Fe===void 0)re.push(JB.FLAG_MISSING);else{K=Fe.metadata?.id,ie=Fe.metadata?.version,ye=Fe.reason?.description??Fe.reason?.code,Te=Fe.metadata?.has_experiment;let tt;if(Fe.metadata?.payload!==void 0)try{tt=JSON.parse(Fe.metadata.payload)}catch{tt=Fe.metadata.payload}D={key:e,enabled:Fe.enabled,variant:Fe.variant??void 0,payload:tt,reason:ye,reasonCode:Fe.reason?.code}}if(re.length>0)X=re.join(",")}}if(c){let he=D===void 0?void 0:D.enabled===!1?!1:D.variant??!0,re={$feature_flag:e,$feature_flag_response:he,$feature_flag_id:K,$feature_flag_version:ie,$feature_flag_reason:ye,locally_evaluated:L,[`$feature/${e}`]:he,$feature_flag_request_id:B,$feature_flag_evaluated_at:L?Date.now():z};if(Te!==void 0)re.$feature_flag_has_experiment=Te;if(L&&this.featureFlagsPoller){let Fe=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(Fe!==void 0)re.$feature_flag_definitions_loaded_at=Fe}if(X)re.$feature_flag_error=X;this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:he,groups:u,disableGeoip:d,properties:re})}if(D!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides)D={...D,payload:this._payloadOverrides[e]};return D}async getFeatureFlag(e,t,n){X6e("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let s=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(s===void 0)return;if(s.enabled===!1)return!1;return s.variant??!0}async getFeatureFlagPayload(e,t,n,s){if(X6e("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let c=await this._getFeatureFlagResult(e,t,{...s,sendFeatureFlagEvents:!1},n);if(c===void 0)return;return c.payload??null}async getFeatureFlagResult(e,t,n){let{distinctId:s,options:c}=this._resolveDistinctId(t,n);if(!s)return void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()");return this._getFeatureFlagResult(e,s,{...c,sendFeatureFlagEvents:c?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let n=await t.json();if(typeof n=="string")try{return JSON.parse(n)}catch(s){}return n}async isFeatureEnabled(e,t,n){X6e("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let s=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(s===void 0)return;if(s.enabled===!1)return!1;return!!(s.variant??!0)||!1}async getAllFlags(e,t){let{distinctId:n,options:s}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{};return(await this.getAllFlagsAndPayloads(n,s)).featureFlags||{}}async getAllFlagsAndPayloads(e,t){let{distinctId:n,options:s}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:c,disableGeoip:u,flagKeys:d}=s||{},{onlyEvaluateLocally:m,personProperties:y,groupProperties:S}=s||{},T=this.addLocalPersonAndGroupProperties(n,c,y,S);y=T.allPersonProperties,S=T.allGroupProperties;let C=this.createFeatureFlagEvaluationContext(n,c,this.personPropertiesForLocalEvaluation(n,y),S);if(m==null)m=this.options.strictLocalEvaluation??!1;let D=await this.featureFlagsPoller?.getAllFlagsAndPayloads(C,d),L={},B={},z=!0;if(D)L=D.response,B=D.payloads,z=D.fallbackToFlags;if(z&&!m){let X=await super.getFeatureFlagsAndPayloadsStateless(C.distinctId,C.groups,y,S,u,d);L={...L,...X.flags||{}},B={...B,...X.payloads||{}}}if(this._flagOverrides!==void 0)L={...L,...this._flagOverrides};if(this._payloadOverrides!==void 0)B={...B,...this._payloadOverrides};return{featureFlags:L,featureFlagPayloads:B}}async evaluateFlags(e,t){let{distinctId:n,options:s}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new Gz({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new Gz({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:c,disableGeoip:u}=s||{},d=s?.flagKeys??void 0;if(d?.length===0)return new Gz({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:c,disableGeoip:u,flags:{}});let{onlyEvaluateLocally:m,personProperties:y,groupProperties:S}=s||{},T=this.addLocalPersonAndGroupProperties(n,c,y,S);y=T.allPersonProperties,S=T.allGroupProperties;let C=this.createFeatureFlagEvaluationContext(n,c,this.personPropertiesForLocalEvaluation(n,y),S);if(m==null)m=this.options.strictLocalEvaluation??!1;let D=d?new Set(d):void 0,L={},B,z,X=!1,K=!1,ie=await this.featureFlagsPoller?.getAllFlagsAndPayloads(C,d),ye=new Set;if(ie)for(let[he,re]of Object.entries(ie.response)){let Fe=this.featureFlagsPoller?.featureFlagsByKey[he];L[he]={key:he,enabled:re!==!1,variant:typeof re=="string"?re:void 0,payload:ie.payloads[he],id:Fe?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:Fe?.has_experiment},ye.add(he)}let Te=D!==void 0&&Array.from(D).some((he)=>this.featureFlagsPoller?.featureFlagsByKey[he]===void 0);if((ie?ie.fallbackToFlags||Te:!0)&&!m){let he=await super.getFeatureFlagDetailsStateless(C.distinctId,C.groups,y,S,u,d);if(he){this._minimalFlagCalledEvents=he.minimalFlagCalledEvents===!0,B=he.requestId,z=he.evaluatedAt,X=Boolean(he.errorsWhileComputingFlags),K=Array.isArray(he.quotaLimited)&&he.quotaLimited.includes("feature_flags");for(let[re,Fe]of Object.entries(he.flags)){if(ye.has(re))continue;let tt;if(Fe.metadata?.payload!==void 0)try{tt=JSON.parse(Fe.metadata.payload)}catch{tt=Fe.metadata.payload}L[re]={key:re,enabled:Fe.enabled,variant:Fe.variant,payload:tt,id:Fe.metadata?.id,version:Fe.metadata?.version,reason:Fe.reason?.description??Fe.reason?.code,locallyEvaluated:!1,hasExperiment:Fe.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[he,re]of Object.entries(this._flagOverrides)){if(re===void 0){delete L[he];continue}let Fe=L[he];L[he]={key:he,enabled:re!==!1,variant:typeof re=="string"?re:void 0,payload:Fe?.payload,id:Fe?.id,version:Fe?.version,reason:Fe?.reason,locallyEvaluated:Fe?.locallyEvaluated??!1,hasExperiment:Fe?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[he,re]of Object.entries(this._payloadOverrides)){let Fe=L[he];if(Fe)L[he]={...Fe,payload:re}}if(D!==void 0){for(let he of Object.keys(L))if(!D.has(he))delete L[he]}return new Gz({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:c,disableGeoip:u,flags:L,requestId:B,evaluatedAt:z,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:X,quotaLimited:K})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:n,response:s,groups:c,disableGeoip:u,properties:d}=e,m=c&&Object.keys(c).length>0?`_${JSON.stringify(Object.entries(c).sort(([T],[C])=>T<C?-1:T>C?1:0))}`:"",y=`${n}_${s}${m}`,S=this._distinctIdHasSentFlagCalls.get(t)??new Set;if(this._distinctIdHasSentFlagCalls.delete(t),this._distinctIdHasSentFlagCalls.set(t,S),S.has(y))return;S.add(y);while(this._distinctIdHasSentFlagCalls.size>Math.max(this.maxCacheSize,1)){let T=this._distinctIdHasSentFlagCalls.keys().next().value;if(T===void 0)break;this._distinctIdHasSentFlagCalls.delete(T)}this.capture({distinctId:t,event:"$feature_flag_called",properties:d,groups:c,disableGeoip:u})}_getFeatureFlagEvaluationsHost(){if(!this._featureFlagEvaluationsHost)this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:(e)=>this._captureFlagCalledEventIfNeeded(e),logWarning:(e)=>{if(this.options.featureFlagsLogWarnings!==!1)console.warn(`[PostHog] ${e}`)}};return this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:n,distinctId:s,disableGeoip:c}){this._sendPreparedEvent("capture",{distinctId:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{}},disableGeoip:c},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:n,distinctId:s,disableGeoip:c}){await this._sendPreparedEvent("capture",{distinctId:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{}},disableGeoip:c},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=(n)=>Object.fromEntries(n.map((s)=>[s,!0]));if(e===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){if("flags"in e){if(e.flags===!1)this._flagOverrides=void 0;else if(Array.isArray(e.flags))this._flagOverrides=t(e.flags);else if(e.flags!==void 0)this._flagOverrides={...e.flags}}if("payloads"in e){if(e.payloads===!1)this._payloadOverrides=void 0;else if(e.payloads!==void 0)this._payloadOverrides={...e.payloads}}return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if("flags"in t){let n=t.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in t){let n=t.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(e,t,n){if(!this.context)return t();return this.context.run(e,t,n)}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??30000),n=this._consumeWaitUntilCycle();if(await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics)await qz(this._metrics.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._metrics.reset();if(this._traces)await qz(this._traces.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._traces.reset();try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this._distinctIdHasSentFlagCalls.clear(),n?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},s=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let c=new AbortController;s=RE(()=>{c.abort()},this.options.requestTimeout),n.signal=c.signal}try{return await this.fetch(t,n)}catch(c){this._events.emit("error",c);return}finally{if(s)clearTimeout(s)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let n={},s={};for(let[c,u]of Object.entries(e))if(por(u)&&t&&c in t){let d={};for(let[m,y]of Object.entries(u))d[String(m)]=String(y);s[String(c)]=d}else n[String(c)]=String(u);return{personProperties:n,groupProperties:s}}async getFeatureFlagsForEvent(e,t,n,s){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let c=s?.personProperties||{},u=s?.groupProperties||{},d=s?.flagKeys;if(s?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let y={};for(let[S,T]of Object.entries(t||{}))y[S]=String(T);return await this.getAllFlags(e,{groups:y,personProperties:c,groupProperties:u,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:d})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let y={};for(let[S,T]of Object.entries(t||{}))y[S]=String(T);return await this.getAllFlags(e,{groups:y,personProperties:c,groupProperties:u,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:d})}return(await super.getFeatureFlagsStateless(e,t,c,u,n)).flags}addLocalPersonAndGroupProperties(e,t,n,s){let c={...n||{}},u={};if(t)for(let d of Object.keys(t))u[d]={$group_key:t[d],...s?.[d]||{}};return{allPersonProperties:c,allGroupProperties:u}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,n,s){return{distinctId:e,groups:t||{},personProperties:n||{},groupProperties:s||{},evaluationCache:{}}}captureException(e,t,n,s,c){if(!EG.isPreviouslyCapturedError(e)){let u=Error("PostHog syntheticException");this.addPendingPromise(EG.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:u},t,n).then((d)=>this._capturePreparedEvent({...d,uuid:s,flags:c},!1)))}}async captureExceptionImmediate(e,t,n,s){if(!EG.isPreviouslyCapturedError(e)){let c=Error("PostHog syntheticException");return this.addPendingPromise(EG.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:c},t,n).then((u)=>this.captureImmediate({...u,flags:s})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:n,event:s,properties:c,groups:u,flags:d,sendFeatureFlags:m,timestamp:y,disableGeoip:S,uuid:T}=e,C=this.context?.get(),D=t.includeContextProperties??!0,L=n||C?.distinctId,B=D?{...this.props,...C?.properties||{},...c||{}}:{...c||{}};if(s==="$exception"&&!(("$trace_id"in B)||("$span_id"in B)))Object.assign(B,await Nur());if(!L)L=OE(),B.$process_person_profile=!1;if(D&&C?.sessionId&&!B.$session_id)B.$session_id=C.sessionId;let z=this._shouldSendMinimalFlagCalledEvent(s,B)?Lye(B):B,X=this._runBeforeSend({distinctId:L,event:s,properties:z,groups:u,flags:d,sendFeatureFlags:m,timestamp:y,disableGeoip:S,uuid:T});if(!X)return Promise.reject(null);let K=await Promise.resolve().then(async()=>{if(d){if(m)console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.");return d._getEventProperties()}if(m){X6e("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let ie=typeof m=="object"?m:void 0,ye=await this.getFeatureFlagsForEvent(X.distinctId,u,S,ie);return c$n(ye)}return{}}).catch(()=>({})).then((ie)=>{let ye=X.groups||u;return{...ie,...X.properties||{},...ye!==void 0&&Object.keys(ye).length>0?{$groups:ye}:{}}});if(X.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof K.$raw_user_agent=="string"){if(mor(K.$raw_user_agent,this.options.custom_blocked_useragents||[]))X.event="$bot_pageview",K.$browser_type="bot"}return{distinctId:X.distinctId,event:X.event,properties:K,options:{timestamp:X.timestamp,disableGeoip:X.disableGeoip,uuid:X.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let n=Array.isArray(t)?t:[t],s=e;for(let c of n)try{if(s=c(s),!s)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!s.properties||Object.keys(s.properties).length===0){let u=`Event '${s.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(u)}}catch(u){return this._logger.error(`Error in before_send function for event '${e.event}':`,u),null}return s}}});import{AsyncLocalStorage as l$n}from"async_hooks";class sht{constructor(){this.storage=new l$n}get(){return this.storage.getStore()}run(e,t,n){return this.storage.run(this.resolve(e,n),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let n=this.get()||{};return{distinctId:e.distinctId??n.distinctId,sessionId:e.sessionId??n.sessionId,properties:{...n.properties||{},...e.properties||{}}}}}var Yur=()=>{};import{AsyncLocalStorage as u$n}from"async_hooks";class oht{active(){return this._storage.getStore()}with(e,t){return this._storage.run(e,t)}constructor(){this._storage=new u$n}}var Qur=()=>{};import{gzip as f$n}from"zlib";import{promisify as d$n}from"util";async function Kur(e,t=!0){try{let n=await p$n(e);return new Uint8Array(n)}catch(n){if(t)console.error("Failed to gzip compress data",n);return null}}var p$n;var Zur=We(()=>{p$n=d$n(f$n)});import{platform as _$n,release as m$n}from"os";function efr(){let e,t;try{e=_$n(),t=m$n()}catch{}return Q_t(e,t)}var tfr=We(()=>{TD()});function h$n(e,{organization:t,projectId:n,prefix:s,severityAllowList:c=["error"],sendExceptionsToPostHog:u=!0}={}){return(d)=>{if(!(c==="*"||c.includes(d.level)))return d;if(!d.tags)d.tags={};let y=d.tags[nfr.POSTHOG_ID_TAG];if(y===void 0)return d;let S=e.options.host??"https://us.i.posthog.com",T=new URL(`/project/${e.apiKey}/person/${y}`,S).toString();d.tags["PostHog Person URL"]=T;let C=d.exception?.values||[],D=C.map((z)=>({...z,stacktrace:z.stacktrace?{...z.stacktrace,type:"raw",frames:(z.stacktrace.frames||[]).map((X)=>({...X,platform:"node:javascript"}))}:void 0})),L={$exception_message:C[0]?.value||d.message,$exception_type:C[0]?.type,$exception_level:d.level,$exception_list:D,$sentry_event_id:d.event_id,$sentry_exception:d.exception,$sentry_exception_message:C[0]?.value||d.message,$sentry_exception_type:C[0]?.type,$sentry_tags:d.tags},B=Par();if(B)L.$release_id=B;if(t&&n)L.$sentry_url=(s||"https://sentry.io/organizations/")+t+"/issues/?project="+n+"&query="+d.event_id;if(u)e.capture({event:"$exception",distinctId:y,properties:L});return d}}var rfr="posthog-node",nfr;var ifr=We(()=>{TD();nfr=class nfr{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,t,n,s,c){this.name=rfr,this.name=rfr,this.setupOnce=function(u,d){let m=d()?.getClient()?.getDsn()?.projectId;u(h$n(e,{organization:t,projectId:m,prefix:n,severityAllowList:s,sendExceptionsToPostHog:c??!0}))}}}});var sfr=()=>{};var ofr=We(()=>{TD()});var afr=We(()=>{hmt();sfr();ofr()});var cfr=We(()=>{_mt();TD();ifr();afr();P6e()});var Y6e;var aht=We(()=>{cor();Vcr();Wcr();Xur();TD();Yur();Qur();Zur();tfr();cfr();Y6e=class Y6e extends iht{getLibraryId(){return"posthog-node"}compressPayload(e){return Kur(e,this.isDebug)}initializeContext(){return new sht}initializeSpanContextManager(){return new oht}hostResourceAttributes(){return efr()}createErrorPropertiesBuilder(){return new QFe([new Sar,new ZFe,new r6e,new e6e,new n6e],dar("node:javascript",sar),[aor(),(e)=>zcr(e,void 0,this._logger),Jcr()])}}});function l0e(e,t){let n={eventType:e,sessionId:t.sessionId,conversationId:t.conversationId,protocolVersion:t.protocolVersion,clientUserAgent:zpt(t.clientUserAgent),vendorClient:zpt(t.vendorClient),timestamp:t.timestamp??new Date,properties:t.properties,groups:t.groups};if(t.distinctId)n.identifyActorGivenId=t.distinctId;if(t.setProperties&&Object.keys(t.setProperties).length>0)n.identifyActorData=t.setProperties;return n}function g$n(e){let t=new Map;for(let n of e){if(typeof n.name!="string")continue;let s=Ine(n.inputSchema,n.outputSchema),c=t.get(n.name);t.set(n.name,c?{context:c.context&&s.context,conversationId:c.conversationId&&s.conversationId,llmModel:c.llmModel&&s.llmModel,outputInstructions:c.outputInstructions&&s.outputInstructions}:s)}return t}function cht(e,t,n){let s=typeof t=="string"?t.trim():"";if(!s)return;e.userIntent=s,e.userIntentSource=n??"context_parameter"}function y$n(e){if(!e||!("context"in e))return e;let{context:t,...n}=e;return n}var lfr="__posthogMcpConversationState",Q6e;var ufr=We(()=>{aht();Cne();jz();l_t();Cye();jR();Lz();u_t();bye();Vpt();BR();MFe();Lpt();PFe();Sye();Wpt();Ane();Q6e=class Q6e extends Y6e{#e;#t;#r;#n;#i;#o;#s;constructor(e,t={}){let n=Jpt(t.serverBuild);if(super(e,t),this.#e=new SFe(this),this.#s=new Map,this.#t=t.missingCapabilityToolName??e_t,this.#r=kne(t.collectFeedback),mG(this.#r),this.#r?.onFeedback)zv("Warning: collectFeedback.onFeedback is ignored on the PostHogMCP path - route reports from your dispatcher via prepareToolCall().feedbackReport instead.");this.#n=t.captureModel,this.#i=t.enableConversationId??!0,this.#o=n,qpt(this)}get#a(){return this.#r?.toolName??_G}capture(e){super.capture(this.#c(e))}captureImmediate(e){return super.captureImmediate(this.#c(e))}captureToolCall(e){let t=l0e(th.mcpToolsCall,e);if(t.resourceName=e.toolName,t.toolDescription=e.toolDescription,t.toolCategory=e.category,t.parameters=e.parameters,t.response=e.response,t.duration=e.durationMs,t.isError=e.isError,t.errorType=e.errorType,cht(t,e.intent,e.intentSource),Iye(t,e.llmModel,e.llmModelSource),e.isError)t.error=LFe(e.error??`Tool ${e.toolName} returned an error`);this.#u(t)}captureInitialize(e){let t=l0e(th.mcpInitialize,e);t.clientName=e.clientName,t.clientVersion=e.clientVersion,t.parameters=e.parameters,t.response=e.response,t.duration=e.durationMs,this.#u(t)}captureToolsList(e){let t=l0e(th.mcpToolsList,e);if(t.listedToolNames=e.toolNames,t.parameters=e.parameters,t.response=e.response,t.duration=e.durationMs,t.isError=e.isError,t.errorType=e.errorType,e.isError)t.error=LFe(e.error??"tools/list failed");this.#u(t)}prepareToolList(e,t={}){let n=t.context??!0,s=kye(n)?r_t(e,t_t(n)):[...e],c=[...e];if(t.reportMissing&&!s.some((d)=>d?.name===this.#t)){let d=Eye(this.#t);s=[...s,d],c.push(d)}if(t.collectFeedback&&this.#r!==void 0&&!s.some((d)=>d?.name===this.#a)){let d=mG(this.#r);s=[...s,d],c.push(d)}this.#s.clear();let u=g$n(c);for(let[d,m]of u)this.#s.set(d,m);if(Pne(this.#n)){let d=n_t(this.#n);s=s.map((m)=>typeof m.name=="string"&&u.get(m.name)?.llmModel===!1?m:eor(m,d))}if(this.#i)s=s.map((d)=>typeof d.name=="string"&&u.get(d.name)?.conversationId===!1?d:o_t([d])[0]),s=s.map((d)=>typeof d.name=="string"&&u.get(d.name)?.outputInstructions===!1?d:Kpt([d])[0]);return s}prepareToolCall(e,t,n={}){let s=t?.context,c=typeof s=="string"&&s.trim()?s.trim():void 0,u=n.originalTool?Ine(n.originalTool.inputSchema,n.originalTool.outputSchema):this.#s.get(e),d=Pne(this.#n)&&u?.llmModel===!0,m=Pne(this.#n)?i_t({params:{arguments:t,_meta:n.requestMeta}},d):void 0,y=y$n(t),S=this.#i&&(u?.conversationId??!0),T=a_t(S,t),C=T.minted&&n.sessionId?{minted:!1,conversationId:void 0}:T,D=C.conversationId,L=D?Gsr(D):n.sessionId,B=this.#r!==void 0&&e===this.#a&&n.originalTool==null;return{intent:c,intentSource:c?"context_parameter":void 0,llmModel:m?.model,llmModelSource:m?.source,args:RFe(y,{context:!1,conversationId:this.#i&&u?.conversationId===!0,llmModel:d}),sessionId:L,conversationId:D,isMissingCapability:e===this.#t,isFeedback:B,feedbackReport:B?CFe(t,this.#r):void 0,[lfr]:{minted:C.minted,outputInstructions:this.#i&&u?.outputInstructions===!0}}}prepareToolResult(e,t){let n=t[lfr],s=t.conversationId;if(!s)return{result:e,sessionId:t.sessionId,conversationId:s};if(!n)return{result:e,sessionId:t.sessionId,conversationId:void 0};let c=e,u=!1;if(n.outputInstructions){let d=Zpt(c,s);u=d!==c,c=d}if(n.minted&&FFe(c))c=c_t(c,s),u=!0;return{result:c,sessionId:t.sessionId,conversationId:n.minted&&!u?void 0:s}}captureMissingCapability(e){let t=l0e(th.mcpMissingCapability,e);t.resourceName=this.#t,t.parameters=e.parameters,cht(t,e.context,"context_parameter"),Iye(t,e.llmModel,e.llmModelSource),this.#u(t)}captureFeedback(e){let t=l0e(th.mcpFeedback,e);t.resourceName=this.#a,t.properties={...t.properties,...AFe(e.report)},cht(t,IFe(e.report),"context_parameter"),Iye(t,e.llmModel,e.llmModelSource),this.#u(t)}#u(e){e.serverBuild=this.#o,this.#e.capture(e,{enableExceptionAutocapture:this.options.enableExceptionAutocapture??!0}).catch((t)=>zv(`Warning: PostHogMCP failed to capture event - ${t}`))}#c(e){if(!this.#o)return e;return{...e,properties:{...e.properties,[ou.ServerBuild]:e.properties?.[ou.ServerBuild]??this.#o}}}}});var ffr=We(()=>{Enr();Lpt();Lz();Bz();BR();Upt();Vpt();Sye();Wpt();ior();sor();Cne();xFe();jR();Ene();f_t();ufr();Ane();aht()});import{AsyncLocalStorage as v$n}from"async_hooks";import K6e from"path";function _fr(e){return S$n.has(e)}function y4(e){return e!==null&&typeof e==="object"?e:{}}function T$n(e){let t=y4(e),n=typeof t.code==="string"?t.code:t.name;return typeof n==="string"&&mfr.has(n)?{code:n,outcome:"operational_error"}:{code:"unexpected_error",outcome:"unexpected_error"}}function x$n(e){let t=y4(e),n=typeof t.name==="string"&&hfr.has(t.name)?t.name:"Error",s=[];if(typeof t.stack==="string")for(let c of t.stack.split(`
|
|
346
|
-
`).slice(1,65)){let u=c.match(/(?:\(|at )(?:file:\/\/)?([^()]+):(\d+):(\d+)\)?$/);if(!u)continue;let d=K6e.relative($p(w$n),$p(u[1])).split(K6e.sep).join("/");if(!_fr(d))continue;if(s.push({filename:"ast-mcp/"+d,function:"<anonymous>",lineno:Number(u[2]),colno:Number(u[3]),in_app:!0,platform:"node:javascript"}),s.length===20)break}return{$exception_level:"error",$exception_list:[{type:n,value:"Unexpected AST MCP failure",mechanism:{type:"generic",handled:!0},stacktrace:{type:"raw",frames:s}}]}}function pfr(e,t,n){if(e.event!=="$mcp_tool_call"&&e.event!=="$mcp_tool_stalled"&&e.event!=="$exception")return null;let s=y4(e.properties),c=s.outcome;if(c!=="success"&&c!=="operational_error"&&c!=="unexpected_error")return null;if(e.event==="$exception"&&c!=="unexpected_error")return null;let u=typeof s.$mcp_tool_name==="string"&&n.has(s.$mcp_tool_name)?s.$mcp_tool_name:"unknown",d=typeof s.$mcp_duration_ms==="number"&&Number.isFinite(s.$mcp_duration_ms)?Math.max(0,Math.min(s.$mcp_duration_ms,86400000)):0,m={$mcp_source:"posthog_mcp_analytics",$mcp_tool_name:u,$mcp_duration_ms:d,$mcp_is_error:c!=="success",$mcp_server_name:"ast-mcp",$mcp_server_version:aFe.version,$mcp_server_build:b$n,$session_id:t,$process_person_profile:!1,$geoip_disable:!0,outcome:c};if(typeof s.error_code==="string"&&(mfr.has(s.error_code)||s.error_code==="unexpected_error"))m.error_code=s.error_code,m.$mcp_error_type=s.error_code;if(e.event==="$exception"){let y=y4(Array.isArray(s.$exception_list)?s.$exception_list[0]:void 0),S=y4(y.stacktrace),T=Array.isArray(S.frames)?S.frames:[];m.$exception_level="error",m.$exception_list=[{type:typeof y.type==="string"&&hfr.has(y.type)?y.type:"Error",value:"Unexpected AST MCP failure",mechanism:{type:"generic",handled:!0},stacktrace:{type:"raw",frames:T.slice(0,20).flatMap((C)=>{let D=y4(C);return typeof D.filename==="string"&&D.filename.startsWith("ast-mcp/")&&_fr(D.filename.slice(8))&&Number.isSafeInteger(D.lineno)&&Number.isSafeInteger(D.colno)?[{filename:D.filename,function:"<anonymous>",lineno:D.lineno,colno:D.colno,in_app:!0,platform:"node:javascript"}]:[]})}}]}return{event:e.event,distinctId:t,properties:m,disableGeoip:!0}}class uht{options;#e=new v$n;#t=new Set;#r=Bun.randomUUIDv7();#n;#i=new Set;#o=new Set;#s;#a;#u=!1;#c=!1;#l;constructor(e={}){this.options=e;this.#s=e.globalEnabled??CKt,this.#n=(e.now??Date.now)()}#f(){let e=(this.options.now??Date.now)();if(e-this.#n>=82800000)this.#r=Bun.randomUUIDv7(),this.#n=e}register(e){this.#t.add(e)}select(e){let t=this.#e.getStore();if(t)t.policy=t.policy?{enabled:t.policy.enabled&&e.telemetry.enabled,globalEnabled:t.policy.globalEnabled&&e.telemetry.globalEnabled}:e.telemetry}async run(e,t){let n={},s=performance.now();return this.#e.run(n,async()=>{let c=setTimeout(()=>{this.#o.delete(c),this.#m(e,performance.now()-s,n.policy,{error:Object.assign(Error("Tool is still running"),{code:"tool_stalled"}),stalled:!0})},this.options.slowToolMs??15000);c.unref?.(),this.#o.add(c);try{let u=await t(),d=e==="file_delete"?y4(y4(u).cleanup):{},m=d.status==="failed"||d.status==="deferred",y=typeof d.code==="string"&&["EACCES","EPERM","lock_deadline","lock_fenced"].includes(d.code)?d.code:"cleanup_failed";return this.#m(e,performance.now()-s,n.policy,m?{error:Object.assign(Error("File deletion committed with incomplete directory cleanup"),{code:y})}:void 0),u}catch(u){throw this.#m(e,performance.now()-s,n.policy,{error:u}),u}finally{clearTimeout(c),this.#o.delete(c)}})}reportException(e,t=!1){let n=this.#e.getStore()?.policy;if(n||!t){this.#m("unknown",0,n,{error:e});return}if(this.#u||this.#i.size>=(this.options.maxPending??64))return;let s=(async()=>{let c=await(this.options.startupConfig??Mw)();if(c.telemetry.enabled&&c.telemetry.globalEnabled)await this.#y("unknown",0,{error:e})})().catch(()=>{return});this.#i.add(s),s.finally(()=>this.#i.delete(s))}#m(e,t,n,s){if(this.#u||!n?.enabled||!n.globalEnabled||this.#i.size>=(this.options.maxPending??64))return;let c=this.#y(e,t,s).catch(()=>{return});this.#i.add(c),c.finally(()=>this.#i.delete(c))}async#y(e,t,n){if(this.#c||!await this.#s()||this.#c)return;this.#a??=this.#_();let s=await this.#a;if(!s||this.#c||!await this.#s()||this.#c)return;this.#f();let c=n===void 0?{outcome:"success",code:void 0}:T$n(n.error),u={outcome:c.outcome,error_code:c.code,...c.outcome==="unexpected_error"?x$n(n?.error):{}};if(n?.stalled)s.capture({event:"$mcp_tool_stalled",distinctId:this.#r,properties:{...u,$mcp_tool_name:this.#t.has(e)?e:"unknown",$mcp_duration_ms:t}});else s.captureToolCall({toolName:this.#t.has(e)?e:"unknown",durationMs:t,isError:n!==void 0,errorType:c.code,sessionId:this.#r,properties:u});if(c.outcome==="unexpected_error")s.capture({event:"$exception",distinctId:this.#r,properties:{...u,$mcp_tool_name:this.#t.has(e)?e:"unknown",$mcp_duration_ms:t},_originatedFromCaptureException:!0});await new Promise((d)=>setImmediate(d))}async#_(){try{if(this.#c||!await this.#s()||this.#c)return;let e=this.options.loadSdk?await this.options.loadSdk():await Promise.resolve().then(() => (ffr(),{})).then(({})=>(n,s)=>new Q6e(n,s));if(this.#c||!await this.#s()||this.#c)return;return e(dfr,{host:lht,captureModel:!1,enableConversationId:!1,enableExceptionAutocapture:!1,disableCompression:!0,disableGeoip:!0,enableLocalEvaluation:!1,featureFlagsPollingInterval:null,preloadFeatureFlags:!1,personProfiles:"never",persistence:"memory",flushAt:20,maxBatchSize:40,maxQueueSize:128,flushInterval:1e4,fetchRetryCount:0,requestTimeout:this.options.requestTimeoutMs??1000,before_send:(t)=>pfr(t,this.#r,this.#t),fetch:(t,n)=>this.#d(t,n)})}catch{return}}async#d(e,t){let n=()=>new Response('{"status":1}',{status:200});if(this.#c||e!==lht+"/batch/"||!await this.#s()||this.#c)return n();try{let s=JSON.parse(typeof t.body==="string"?t.body:"");if(!Array.isArray(s.batch)||s.batch.length>128)return n();this.#f();let c=s.batch.flatMap((u)=>{let d=y4(u),m=pfr({event:String(d.event),properties:y4(d.properties)},this.#r,this.#t);return m?[{event:m.event,distinct_id:this.#r,properties:m.properties}]:[]});if(!c.length||this.#c||!await this.#s()||this.#c)return n();return await(this.options.fetch??globalThis.fetch)(lht+"/batch/",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:dfr,batch:c}),signal:AbortSignal.timeout(this.options.requestTimeoutMs??1000)})}catch{return n()}}close(){this.#u=!0;for(let e of this.#o)clearTimeout(e);return this.#o.clear(),this.#l??=this.#v(),this.#l}async#v(){let e;await Promise.race([(async()=>{await Promise.allSettled([...this.#i]);let t=await this.#a;if(t)await t.shutdown(this.options.shutdownMs??1500)})().catch(()=>{return}),new Promise((t)=>{e=setTimeout(t,this.options.shutdownMs??1500)})]),this.#c=!0,clearTimeout(e)}}var b$n="923e89e737fc8aaf3ae76fa92011f159debfb7ce",lht="https://us.i.posthog.com",dfr="phc_usiY5ZV4ZV4G2NALf4dif826qU4qjLNi8Hc53m6Jb67t",w$n,S$n,mfr,hfr;var gfr=We(()=>{Hdt();Oy();Rw();w$n=K6e.resolve(import.meta.dir,import.meta.dir.endsWith(K6e.sep+"dist")?"..":"../.."),S$n=new Set(typeof["dist/ast-mcp.js","dist/workers/code-intelligence-worker.js","dist/workers/dynamic-wasm-worker.js","dist/workers/embedding-model-worker.js","dist/workers/infra-wasm-worker.js","dist/workers/jvm-wasm-worker.js","dist/workers/legacy-wasm-worker.js","dist/workers/parser-worker.js","dist/workers/patch-strategy-worker.js","dist/workers/systems-wasm-worker.js","src/cli/config.ts","src/cli/index.ts","src/cli/mcp.ts","src/cli/output.ts","src/cli/skills.ts","src/config/edit.ts","src/config/index.ts","src/config/migrate.ts","src/config/registry.ts","src/config/schema-common.ts","src/config/transaction.ts","src/config/v2-schema.ts","src/helpers/aider.ts","src/helpers/config.ts","src/helpers/hook.ts","src/helpers/installer.ts","src/helpers/mcp-schema.ts","src/helpers/process.ts","src/helpers/string.ts","src/hooks/index.ts","src/hooks/managed.ts","src/hooks/shell-policy.ts","src/http/entry.ts","src/http/index.ts","src/index.ts","src/installer/codex.ts","src/installer/health.ts","src/installer/index.ts","src/installer/service.ts","src/installer/transport.ts","src/intelligence/analytics/analytics.ts","src/intelligence/analytics/index.ts","src/intelligence/analytics/repository.ts","src/intelligence/analytics/types.ts","src/intelligence/contracts/artifacts.ts","src/intelligence/contracts/common.ts","src/intelligence/contracts/graph.ts","src/intelligence/contracts/index.ts","src/intelligence/contracts/language.ts","src/intelligence/contracts/result.ts","src/intelligence/contracts/storage.ts","src/intelligence/contracts/workspace.ts","src/intelligence/documents/core.ts","src/intelligence/documents/index.ts","src/intelligence/documents/manifest.ts","src/intelligence/documents/rewrite.ts","src/intelligence/documents/types.ts","src/intelligence/generation/index.ts","src/intelligence/generation/providers.ts","src/intelligence/generation/service.ts","src/intelligence/generation/types.ts","src/intelligence/graph/algorithms/algorithms.ts","src/intelligence/graph/algorithms/index.ts","src/intelligence/graph/algorithms/types.ts","src/intelligence/graph/diff.ts","src/intelligence/graph/from-resolution.ts","src/intelligence/graph/index.ts","src/intelligence/graph/materializer.ts","src/intelligence/graph/repository.ts","src/intelligence/graph/resolution-schema.ts","src/intelligence/graph/shared.ts","src/intelligence/graph/types.ts","src/intelligence/languages/dynamic/analyzer.ts","src/intelligence/languages/dynamic/index.ts","src/intelligence/languages/dynamic/manifest.ts","src/intelligence/languages/dynamic/protocol.ts","src/intelligence/languages/dynamic/types.ts","src/intelligence/languages/dynamic/wasm-worker.ts","src/intelligence/languages/immutable.ts","src/intelligence/languages/infra/analyzer.ts","src/intelligence/languages/infra/index.ts","src/intelligence/languages/infra/manifest.ts","src/intelligence/languages/infra/types.ts","src/intelligence/languages/infra/wasm-worker.ts","src/intelligence/languages/infra/worker-client.ts","src/intelligence/languages/jvm/analyzer.ts","src/intelligence/languages/jvm/index.ts","src/intelligence/languages/jvm/manifest.ts","src/intelligence/languages/jvm/types.ts","src/intelligence/languages/jvm/wasm-worker.ts","src/intelligence/languages/jvm/worker-client.ts","src/intelligence/languages/legacy/analyzer.ts","src/intelligence/languages/legacy/index.ts","src/intelligence/languages/legacy/manifest.ts","src/intelligence/languages/legacy/protocol.ts","src/intelligence/languages/legacy/types.ts","src/intelligence/languages/legacy/wasm-worker.ts","src/intelligence/languages/manifest-builders.ts","src/intelligence/languages/project/core.ts","src/intelligence/languages/project/evidence.ts","src/intelligence/languages/project/index.ts","src/intelligence/languages/project/manifest.ts","src/intelligence/languages/project/types.ts","src/intelligence/languages/shared/language-loader.ts","src/intelligence/languages/shared/language-worker-client.ts","src/intelligence/languages/shared/wasm-assets.ts","src/intelligence/languages/shared/wasm-dynamic-worker.ts","src/intelligence/languages/shared/wasm-fact-assembly.ts","src/intelligence/languages/shared/wasm-infra-worker.ts","src/intelligence/languages/shared/wasm-jvm-worker.ts","src/intelligence/languages/shared/wasm-legacy-worker.ts","src/intelligence/languages/shared/wasm-mainstream-worker.ts","src/intelligence/languages/shared/wasm-systems-worker.ts","src/intelligence/languages/shared/wasm-tree-sitter-support.ts","src/intelligence/languages/shared/wasm-worker-runtime.ts","src/intelligence/languages/shared/wasm-worker-validation.ts","src/intelligence/languages/shared/worker-client.ts","src/intelligence/languages/shared/worker-protocol-validator.ts","src/intelligence/languages/systems/analyzer.ts","src/intelligence/languages/systems/index.ts","src/intelligence/languages/systems/manifest.ts","src/intelligence/languages/systems/types.ts","src/intelligence/languages/systems/wasm-worker.ts","src/intelligence/languages/systems/worker-client.ts","src/intelligence/languages/web/compiler-project.ts","src/intelligence/languages/web/compiler.ts","src/intelligence/languages/web/index.ts","src/intelligence/languages/web/manifest.ts","src/intelligence/languages/web/templates.ts","src/intelligence/languages/web/types.ts","src/intelligence/languages/worker-client-validation.ts","src/intelligence/lifecycle/dispatcher.ts","src/intelligence/lifecycle/service.ts","src/intelligence/manifest-registry.ts","src/intelligence/mutation/freshness.ts","src/intelligence/mutation/index.ts","src/intelligence/mutation/journal.ts","src/intelligence/mutation/lifecycle.ts","src/intelligence/mutation/locks.ts","src/intelligence/mutation/service.ts","src/intelligence/mutation/types.ts","src/intelligence/parser/coordinates.ts","src/intelligence/parser/index.ts","src/intelligence/parser/language-catalog.ts","src/intelligence/parser/parser.ts","src/intelligence/parser/pool.ts","src/intelligence/parser/registry.ts","src/intelligence/parser/source-map.ts","src/intelligence/parser/structural.ts","src/intelligence/parser/structured.ts","src/intelligence/parser/transport.ts","src/intelligence/parser/types.ts","src/intelligence/parser/worker.ts","src/intelligence/resolution/index.ts","src/intelligence/resolution/resolver.ts","src/intelligence/resolution/types.ts","src/intelligence/retrieval/benchmark.ts","src/intelligence/retrieval/context.ts","src/intelligence/retrieval/embedding.ts","src/intelligence/retrieval/index.ts","src/intelligence/retrieval/model-provider.ts","src/intelligence/retrieval/model-worker.ts","src/intelligence/retrieval/publication.ts","src/intelligence/retrieval/query.ts","src/intelligence/retrieval/types.ts","src/intelligence/retrieval/worker-session.ts","src/intelligence/storage/arrow.ts","src/intelligence/storage/coordinator.ts","src/intelligence/storage/errors.ts","src/intelligence/storage/index.ts","src/intelligence/storage/relocation.ts","src/intelligence/storage/schemas.ts","src/intelligence/storage/store.ts","src/intelligence/workspace/context.ts","src/intelligence/workspace/errors.ts","src/intelligence/workspace/git.ts","src/intelligence/workspace/index.ts","src/intelligence/workspace/registry.ts","src/intelligence/workspace/storage.ts","src/intelligence/workspace/tools.ts","src/patch/aider.ts","src/patch/engine.ts","src/patch/languages.ts","src/patch/strategy.ts","src/patch/strategy/aiderBlock.ts","src/patch/strategy/ast.ts","src/patch/strategy/inline.ts","src/patch/strategy/worker-client.ts","src/patch/strategy/worker.ts","src/runtime/approval.ts","src/runtime/atomic.ts","src/runtime/attributes.ts","src/runtime/binary-resolution.ts","src/runtime/config-write.ts","src/runtime/dependencies.ts","src/runtime/document-inspection.ts","src/runtime/file-capabilities.ts","src/runtime/file-delete.ts","src/runtime/file-read.ts","src/runtime/file-rename.ts","src/runtime/file-snapshot.ts","src/runtime/format.ts","src/runtime/git-worktrees.ts","src/runtime/hash.ts","src/runtime/locks.ts","src/runtime/parent-directories.ts","src/runtime/path-policy.ts","src/runtime/path-utils.ts","src/runtime/paths.ts","src/runtime/policy.ts","src/runtime/private-lock-directory.ts","src/runtime/process-input.ts","src/runtime/reference-target-index.ts","src/runtime/signals.ts","src/runtime/snapshot-blob.ts","src/runtime/subprocess.ts","src/runtime/telemetry.ts","src/runtime/transaction-lock.ts","src/server/index.ts","src/server/lifecycle.ts","src/server/stdio.ts","src/skills/export.ts","src/skills/index.ts","src/tools/code-intelligence-compute.ts","src/tools/code-intelligence-worker.ts","src/tools/code-intelligence.ts","src/tools/configuration.ts","src/tools/configured.ts","src/tools/files.ts","src/tools/index.ts","src/tools/intelligence-output.ts","src/tools/intelligence.ts","src/tools/lifecycle.ts"]<"u"?["dist/ast-mcp.js","dist/workers/code-intelligence-worker.js","dist/workers/dynamic-wasm-worker.js","dist/workers/embedding-model-worker.js","dist/workers/infra-wasm-worker.js","dist/workers/jvm-wasm-worker.js","dist/workers/legacy-wasm-worker.js","dist/workers/parser-worker.js","dist/workers/patch-strategy-worker.js","dist/workers/systems-wasm-worker.js","src/cli/config.ts","src/cli/index.ts","src/cli/mcp.ts","src/cli/output.ts","src/cli/skills.ts","src/config/edit.ts","src/config/index.ts","src/config/migrate.ts","src/config/registry.ts","src/config/schema-common.ts","src/config/transaction.ts","src/config/v2-schema.ts","src/helpers/aider.ts","src/helpers/config.ts","src/helpers/hook.ts","src/helpers/installer.ts","src/helpers/mcp-schema.ts","src/helpers/process.ts","src/helpers/string.ts","src/hooks/index.ts","src/hooks/managed.ts","src/hooks/shell-policy.ts","src/http/entry.ts","src/http/index.ts","src/index.ts","src/installer/codex.ts","src/installer/health.ts","src/installer/index.ts","src/installer/service.ts","src/installer/transport.ts","src/intelligence/analytics/analytics.ts","src/intelligence/analytics/index.ts","src/intelligence/analytics/repository.ts","src/intelligence/analytics/types.ts","src/intelligence/contracts/artifacts.ts","src/intelligence/contracts/common.ts","src/intelligence/contracts/graph.ts","src/intelligence/contracts/index.ts","src/intelligence/contracts/language.ts","src/intelligence/contracts/result.ts","src/intelligence/contracts/storage.ts","src/intelligence/contracts/workspace.ts","src/intelligence/documents/core.ts","src/intelligence/documents/index.ts","src/intelligence/documents/manifest.ts","src/intelligence/documents/rewrite.ts","src/intelligence/documents/types.ts","src/intelligence/generation/index.ts","src/intelligence/generation/providers.ts","src/intelligence/generation/service.ts","src/intelligence/generation/types.ts","src/intelligence/graph/algorithms/algorithms.ts","src/intelligence/graph/algorithms/index.ts","src/intelligence/graph/algorithms/types.ts","src/intelligence/graph/diff.ts","src/intelligence/graph/from-resolution.ts","src/intelligence/graph/index.ts","src/intelligence/graph/materializer.ts","src/intelligence/graph/repository.ts","src/intelligence/graph/resolution-schema.ts","src/intelligence/graph/shared.ts","src/intelligence/graph/types.ts","src/intelligence/languages/dynamic/analyzer.ts","src/intelligence/languages/dynamic/index.ts","src/intelligence/languages/dynamic/manifest.ts","src/intelligence/languages/dynamic/protocol.ts","src/intelligence/languages/dynamic/types.ts","src/intelligence/languages/dynamic/wasm-worker.ts","src/intelligence/languages/immutable.ts","src/intelligence/languages/infra/analyzer.ts","src/intelligence/languages/infra/index.ts","src/intelligence/languages/infra/manifest.ts","src/intelligence/languages/infra/types.ts","src/intelligence/languages/infra/wasm-worker.ts","src/intelligence/languages/infra/worker-client.ts","src/intelligence/languages/jvm/analyzer.ts","src/intelligence/languages/jvm/index.ts","src/intelligence/languages/jvm/manifest.ts","src/intelligence/languages/jvm/types.ts","src/intelligence/languages/jvm/wasm-worker.ts","src/intelligence/languages/jvm/worker-client.ts","src/intelligence/languages/legacy/analyzer.ts","src/intelligence/languages/legacy/index.ts","src/intelligence/languages/legacy/manifest.ts","src/intelligence/languages/legacy/protocol.ts","src/intelligence/languages/legacy/types.ts","src/intelligence/languages/legacy/wasm-worker.ts","src/intelligence/languages/manifest-builders.ts","src/intelligence/languages/project/core.ts","src/intelligence/languages/project/evidence.ts","src/intelligence/languages/project/index.ts","src/intelligence/languages/project/manifest.ts","src/intelligence/languages/project/types.ts","src/intelligence/languages/shared/language-loader.ts","src/intelligence/languages/shared/language-worker-client.ts","src/intelligence/languages/shared/wasm-assets.ts","src/intelligence/languages/shared/wasm-dynamic-worker.ts","src/intelligence/languages/shared/wasm-fact-assembly.ts","src/intelligence/languages/shared/wasm-infra-worker.ts","src/intelligence/languages/shared/wasm-jvm-worker.ts","src/intelligence/languages/shared/wasm-legacy-worker.ts","src/intelligence/languages/shared/wasm-mainstream-worker.ts","src/intelligence/languages/shared/wasm-systems-worker.ts","src/intelligence/languages/shared/wasm-tree-sitter-support.ts","src/intelligence/languages/shared/wasm-worker-runtime.ts","src/intelligence/languages/shared/wasm-worker-validation.ts","src/intelligence/languages/shared/worker-client.ts","src/intelligence/languages/shared/worker-protocol-validator.ts","src/intelligence/languages/systems/analyzer.ts","src/intelligence/languages/systems/index.ts","src/intelligence/languages/systems/manifest.ts","src/intelligence/languages/systems/types.ts","src/intelligence/languages/systems/wasm-worker.ts","src/intelligence/languages/systems/worker-client.ts","src/intelligence/languages/web/compiler-project.ts","src/intelligence/languages/web/compiler.ts","src/intelligence/languages/web/index.ts","src/intelligence/languages/web/manifest.ts","src/intelligence/languages/web/templates.ts","src/intelligence/languages/web/types.ts","src/intelligence/languages/worker-client-validation.ts","src/intelligence/lifecycle/dispatcher.ts","src/intelligence/lifecycle/service.ts","src/intelligence/manifest-registry.ts","src/intelligence/mutation/freshness.ts","src/intelligence/mutation/index.ts","src/intelligence/mutation/journal.ts","src/intelligence/mutation/lifecycle.ts","src/intelligence/mutation/locks.ts","src/intelligence/mutation/service.ts","src/intelligence/mutation/types.ts","src/intelligence/parser/coordinates.ts","src/intelligence/parser/index.ts","src/intelligence/parser/language-catalog.ts","src/intelligence/parser/parser.ts","src/intelligence/parser/pool.ts","src/intelligence/parser/registry.ts","src/intelligence/parser/source-map.ts","src/intelligence/parser/structural.ts","src/intelligence/parser/structured.ts","src/intelligence/parser/transport.ts","src/intelligence/parser/types.ts","src/intelligence/parser/worker.ts","src/intelligence/resolution/index.ts","src/intelligence/resolution/resolver.ts","src/intelligence/resolution/types.ts","src/intelligence/retrieval/benchmark.ts","src/intelligence/retrieval/context.ts","src/intelligence/retrieval/embedding.ts","src/intelligence/retrieval/index.ts","src/intelligence/retrieval/model-provider.ts","src/intelligence/retrieval/model-worker.ts","src/intelligence/retrieval/publication.ts","src/intelligence/retrieval/query.ts","src/intelligence/retrieval/types.ts","src/intelligence/retrieval/worker-session.ts","src/intelligence/storage/arrow.ts","src/intelligence/storage/coordinator.ts","src/intelligence/storage/errors.ts","src/intelligence/storage/index.ts","src/intelligence/storage/relocation.ts","src/intelligence/storage/schemas.ts","src/intelligence/storage/store.ts","src/intelligence/workspace/context.ts","src/intelligence/workspace/errors.ts","src/intelligence/workspace/git.ts","src/intelligence/workspace/index.ts","src/intelligence/workspace/registry.ts","src/intelligence/workspace/storage.ts","src/intelligence/workspace/tools.ts","src/patch/aider.ts","src/patch/engine.ts","src/patch/languages.ts","src/patch/strategy.ts","src/patch/strategy/aiderBlock.ts","src/patch/strategy/ast.ts","src/patch/strategy/inline.ts","src/patch/strategy/worker-client.ts","src/patch/strategy/worker.ts","src/runtime/approval.ts","src/runtime/atomic.ts","src/runtime/attributes.ts","src/runtime/binary-resolution.ts","src/runtime/config-write.ts","src/runtime/dependencies.ts","src/runtime/document-inspection.ts","src/runtime/file-capabilities.ts","src/runtime/file-delete.ts","src/runtime/file-read.ts","src/runtime/file-rename.ts","src/runtime/file-snapshot.ts","src/runtime/format.ts","src/runtime/git-worktrees.ts","src/runtime/hash.ts","src/runtime/locks.ts","src/runtime/parent-directories.ts","src/runtime/path-policy.ts","src/runtime/path-utils.ts","src/runtime/paths.ts","src/runtime/policy.ts","src/runtime/private-lock-directory.ts","src/runtime/process-input.ts","src/runtime/reference-target-index.ts","src/runtime/signals.ts","src/runtime/snapshot-blob.ts","src/runtime/subprocess.ts","src/runtime/telemetry.ts","src/runtime/transaction-lock.ts","src/server/index.ts","src/server/lifecycle.ts","src/server/stdio.ts","src/skills/export.ts","src/skills/index.ts","src/tools/code-intelligence-compute.ts","src/tools/code-intelligence-worker.ts","src/tools/code-intelligence.ts","src/tools/configuration.ts","src/tools/configured.ts","src/tools/files.ts","src/tools/index.ts","src/tools/intelligence-output.ts","src/tools/intelligence.ts","src/tools/lifecycle.ts"]:["src/server/index.ts","src/config/index.ts","src/http/index.ts","src/server/stdio.ts","src/tools/configured.ts","src/runtime/paths.ts","src/runtime/format.ts","src/runtime/policy.ts","src/runtime/approval.ts","src/patch/engine.ts","dist/ast-mcp.js","dist/workers/code-intelligence-worker.js","dist/workers/dynamic-wasm-worker.js","dist/workers/infra-wasm-worker.js","dist/workers/jvm-wasm-worker.js","dist/workers/legacy-wasm-worker.js","dist/workers/systems-wasm-worker.js"]);mfr=new Set(["approval_required","approval_denied","path_denied","path_outside_root","workspace_mismatch","workspace_required","intelligence_budget_exceeded","intelligence_refresh_timeout","reference_verification_failed","graph_budget_exhausted","document_too_large","document_not_regular","deprecated_root_environment","aborted","timeout","tool_stalled","use_file_patch","generation_unavailable","cross_repository_federation_required","graph_node_not_found","invalid_graph_cursor","patch_strategy_unavailable","patch_strategy_arguments","patch_strategy_required","ast_match_count","ast_rewrite_overlap","ast_preview_error","aider_matcher_disabled","invalid_text_encoding","lock_aborted","lock_deadline","lock_fenced","cross_root_ast_request","configuration_path_missing","configuration_missing","configuration_path_duplicate","configuration_empty_patch","configuration_invalid","document_format_unsupported","invalid_document_selector","document_result_too_large","document_source_too_large","read_mode_unavailable","ast_capability_unavailable","candidate_parse_error","approval_persistence_required","approval_persistence_busy","approval_persistence_conflict","approval_challenge_limit","workspace_ambiguous","stale_hash","missing_hash","stale_preview_receipt","preview_receipt_expired","preview_receipt_invalid","preview_receipt_mismatch","permission_denied","file_not_found","formatter_unavailable","formatter_rejected","formatter_cleanup_failed","command_timeout","command_invalid_output","aider_ambiguous","preview_receipt_unknown","preview_receipt_file_mismatch","preview_receipt_session_mismatch","preview_receipt_workspace_changed","preview_receipt_configuration_changed","preview_receipt_integrity","preview_receipt_limit","workspace_not_found","workspace_revision_invalid","workspace_read_only","InputRequiredSignal","formatter_missing","formatter_timeout","formatter_failed","formatter_invalid_output","formatting_rejected","ambiguous_match","patch_ambiguous","patch_no_match","immutable_revision","revision_immutable","configuration_mcp_disabled","configuration_migration_required","cancelled","operation_aborted","EACCES","EPERM","ENOENT","AbortError"]),hfr=new Set(["Error","TypeError","RangeError","SyntaxError","ReferenceError"])});import{AsyncLocalStorage as E$n}from"async_hooks";import{createHash as bfr,randomUUID as dht}from"crypto";import{chmodSync as k$n,existsSync as wfr,mkdirSync as Sfr,readFileSync as C$n,renameSync as I$n,statSync as A$n,unlinkSync as P$n,writeFileSync as D$n}from"fs";import u0e from"path";function xfr(e){Tfr=e}function vfr(e){Sfr(u0e.dirname(e),{mode:448,recursive:!0});let t=wfr(e)?C$n(e,"utf8"):"";if(!t)return t;if(Bun.TOML.parse(t).version===2)return t;throw Object.assign(Error("Persistent approvals require a version 2 user-global ast-mcp.toml; migrate it explicitly first"),{code:"approval_persistence_required",retryable:!0,suggestedNextCall:"config_status"})}function M$n(e,t){if(!e)return[];return(Bun.TOML.parse(e).paths??[]).filter((s)=>s.id?.startsWith("approval-")&&s.path===t)}function F$n(e,t=[]){let n=new Set([e]);for(let s of t)for(let c of["read","write","delete"])if(s.policies?.[c]==="allow")n.add(c);return{delete:n.has("delete")?"allow":"deny",read:n.has("read")?"allow":"deny",write:n.has("write")?"allow":"deny"}}function Efr(e){return`policies = { read = ${JSON.stringify(e.read)}, write = ${JSON.stringify(e.write)}, delete = ${JSON.stringify(e.delete)} }`}function L$n(e,t,n){let s=new Set(t.flatMap((u)=>u.id?[u.id]:[])),c=Efr(n);return e.split(/(?=^\[\[paths\]\]\s*$)/m).map((u)=>[...s].some((d)=>u.includes(`id = ${JSON.stringify(d)}`))?u.replace(/^policies = \{.*\}$/m,c):u).join("")}function B$n(e){return`approval-${bfr("sha256").update(`${e.operation}\x00${e.canonicalPath}`).digest("hex").slice(0,16)}`}function j$n(e,t){Sfr(u0e.dirname(e),{mode:448,recursive:!0});let n=xre(e),s=u0e.join(u0e.dirname(n),`.${u0e.basename(n)}.approval-${dht()}`);try{Ere(n,()=>{try{cz(e,n);let c=vfr(n),u=wfr(n)?A$n(n).mode&4095:384,d=t(c);if(d===void 0)return;if(D$n(s,d,{flag:"wx",mode:u}),k$n(s,u),cz(e,n),vfr(n)!==c)throw Object.assign(Error("User-global configuration changed during approval; retry"),{code:"approval_persistence_conflict",retryable:!0});cz(e,n),I$n(s,n)}finally{try{P$n(s)}catch{}}})}catch(c){if(c.code==="configuration_busy")Object.assign(c,{code:"approval_persistence_busy"});throw c}}function z$n(e){let t=dD(),n=B$n(e),s=!1,c=!1;if(j$n(t,(u)=>{let d=M$n(u,e.canonicalPath),m=F$n(e.operation,d);if(d.length>0){let T=L$n(u,d,m);if(T===u)return;return s=!0,T}let y=["[[paths]]",`id = ${JSON.stringify(n)}`,`path = ${JSON.stringify(e.canonicalPath)}`,Efr(m),"follow_symlinks = false",'includes = ["**/*"]',"excludes = []"].join(`
|
|
346
|
+
`).slice(1,65)){let u=c.match(/(?:\(|at )(?:file:\/\/)?([^()]+):(\d+):(\d+)\)?$/);if(!u)continue;let d=K6e.relative($p(w$n),$p(u[1])).split(K6e.sep).join("/");if(!_fr(d))continue;if(s.push({filename:"ast-mcp/"+d,function:"<anonymous>",lineno:Number(u[2]),colno:Number(u[3]),in_app:!0,platform:"node:javascript"}),s.length===20)break}return{$exception_level:"error",$exception_list:[{type:n,value:"Unexpected AST MCP failure",mechanism:{type:"generic",handled:!0},stacktrace:{type:"raw",frames:s}}]}}function pfr(e,t,n){if(e.event!=="$mcp_tool_call"&&e.event!=="$mcp_tool_stalled"&&e.event!=="$exception")return null;let s=y4(e.properties),c=s.outcome;if(c!=="success"&&c!=="operational_error"&&c!=="unexpected_error")return null;if(e.event==="$exception"&&c!=="unexpected_error")return null;let u=typeof s.$mcp_tool_name==="string"&&n.has(s.$mcp_tool_name)?s.$mcp_tool_name:"unknown",d=typeof s.$mcp_duration_ms==="number"&&Number.isFinite(s.$mcp_duration_ms)?Math.max(0,Math.min(s.$mcp_duration_ms,86400000)):0,m={$mcp_source:"posthog_mcp_analytics",$mcp_tool_name:u,$mcp_duration_ms:d,$mcp_is_error:c!=="success",$mcp_server_name:"ast-mcp",$mcp_server_version:aFe.version,$mcp_server_build:b$n,$session_id:t,$process_person_profile:!1,$geoip_disable:!0,outcome:c};if(typeof s.error_code==="string"&&(mfr.has(s.error_code)||s.error_code==="unexpected_error"))m.error_code=s.error_code,m.$mcp_error_type=s.error_code;if(e.event==="$exception"){let y=y4(Array.isArray(s.$exception_list)?s.$exception_list[0]:void 0),S=y4(y.stacktrace),T=Array.isArray(S.frames)?S.frames:[];m.$exception_level="error",m.$exception_list=[{type:typeof y.type==="string"&&hfr.has(y.type)?y.type:"Error",value:"Unexpected AST MCP failure",mechanism:{type:"generic",handled:!0},stacktrace:{type:"raw",frames:T.slice(0,20).flatMap((C)=>{let D=y4(C);return typeof D.filename==="string"&&D.filename.startsWith("ast-mcp/")&&_fr(D.filename.slice(8))&&Number.isSafeInteger(D.lineno)&&Number.isSafeInteger(D.colno)?[{filename:D.filename,function:"<anonymous>",lineno:D.lineno,colno:D.colno,in_app:!0,platform:"node:javascript"}]:[]})}}]}return{event:e.event,distinctId:t,properties:m,disableGeoip:!0}}class uht{options;#e=new v$n;#t=new Set;#r=Bun.randomUUIDv7();#n;#i=new Set;#o=new Set;#s;#a;#u=!1;#c=!1;#l;constructor(e={}){this.options=e;this.#s=e.globalEnabled??CKt,this.#n=(e.now??Date.now)()}#f(){let e=(this.options.now??Date.now)();if(e-this.#n>=82800000)this.#r=Bun.randomUUIDv7(),this.#n=e}register(e){this.#t.add(e)}select(e){let t=this.#e.getStore();if(t)t.policy=t.policy?{enabled:t.policy.enabled&&e.telemetry.enabled,globalEnabled:t.policy.globalEnabled&&e.telemetry.globalEnabled}:e.telemetry}async run(e,t){let n={},s=performance.now();return this.#e.run(n,async()=>{let c=setTimeout(()=>{this.#o.delete(c),this.#m(e,performance.now()-s,n.policy,{error:Object.assign(Error("Tool is still running"),{code:"tool_stalled"}),stalled:!0})},this.options.slowToolMs??15000);c.unref?.(),this.#o.add(c);try{let u=await t(),d=e==="file_delete"?y4(y4(u).cleanup):{},m=d.status==="failed"||d.status==="deferred",y=typeof d.code==="string"&&["EACCES","EPERM","lock_deadline","lock_fenced"].includes(d.code)?d.code:"cleanup_failed";return this.#m(e,performance.now()-s,n.policy,m?{error:Object.assign(Error("File deletion committed with incomplete directory cleanup"),{code:y})}:void 0),u}catch(u){throw this.#m(e,performance.now()-s,n.policy,{error:u}),u}finally{clearTimeout(c),this.#o.delete(c)}})}reportException(e,t=!1){let n=this.#e.getStore()?.policy;if(n||!t){this.#m("unknown",0,n,{error:e});return}if(this.#u||this.#i.size>=(this.options.maxPending??64))return;let s=(async()=>{let c=await(this.options.startupConfig??Mw)();if(c.telemetry.enabled&&c.telemetry.globalEnabled)await this.#y("unknown",0,{error:e})})().catch(()=>{return});this.#i.add(s),s.finally(()=>this.#i.delete(s))}#m(e,t,n,s){if(this.#u||!n?.enabled||!n.globalEnabled||this.#i.size>=(this.options.maxPending??64))return;let c=this.#y(e,t,s).catch(()=>{return});this.#i.add(c),c.finally(()=>this.#i.delete(c))}async#y(e,t,n){if(this.#c||!await this.#s()||this.#c)return;this.#a??=this.#_();let s=await this.#a;if(!s||this.#c||!await this.#s()||this.#c)return;this.#f();let c=n===void 0?{outcome:"success",code:void 0}:T$n(n.error),u={outcome:c.outcome,error_code:c.code,...c.outcome==="unexpected_error"?x$n(n?.error):{}};if(n?.stalled)s.capture({event:"$mcp_tool_stalled",distinctId:this.#r,properties:{...u,$mcp_tool_name:this.#t.has(e)?e:"unknown",$mcp_duration_ms:t}});else s.captureToolCall({toolName:this.#t.has(e)?e:"unknown",durationMs:t,isError:n!==void 0,errorType:c.code,sessionId:this.#r,properties:u});if(c.outcome==="unexpected_error")s.capture({event:"$exception",distinctId:this.#r,properties:{...u,$mcp_tool_name:this.#t.has(e)?e:"unknown",$mcp_duration_ms:t},_originatedFromCaptureException:!0});await new Promise((d)=>setImmediate(d))}async#_(){try{if(this.#c||!await this.#s()||this.#c)return;let e=this.options.loadSdk?await this.options.loadSdk():await Promise.resolve().then(() => (ffr(),{})).then(({})=>(n,s)=>new Q6e(n,s));if(this.#c||!await this.#s()||this.#c)return;return e(dfr,{host:lht,captureModel:!1,enableConversationId:!1,enableExceptionAutocapture:!1,disableCompression:!0,disableGeoip:!0,enableLocalEvaluation:!1,featureFlagsPollingInterval:null,preloadFeatureFlags:!1,personProfiles:"never",persistence:"memory",flushAt:20,maxBatchSize:40,maxQueueSize:128,flushInterval:1e4,fetchRetryCount:0,requestTimeout:this.options.requestTimeoutMs??1000,before_send:(t)=>pfr(t,this.#r,this.#t),fetch:(t,n)=>this.#d(t,n)})}catch{return}}async#d(e,t){let n=()=>new Response('{"status":1}',{status:200});if(this.#c||e!==lht+"/batch/"||!await this.#s()||this.#c)return n();try{let s=JSON.parse(typeof t.body==="string"?t.body:"");if(!Array.isArray(s.batch)||s.batch.length>128)return n();this.#f();let c=s.batch.flatMap((u)=>{let d=y4(u),m=pfr({event:String(d.event),properties:y4(d.properties)},this.#r,this.#t);return m?[{event:m.event,distinct_id:this.#r,properties:m.properties}]:[]});if(!c.length||this.#c||!await this.#s()||this.#c)return n();return await(this.options.fetch??globalThis.fetch)(lht+"/batch/",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:dfr,batch:c}),signal:AbortSignal.timeout(this.options.requestTimeoutMs??1000)})}catch{return n()}}close(){this.#u=!0;for(let e of this.#o)clearTimeout(e);return this.#o.clear(),this.#l??=this.#v(),this.#l}async#v(){let e;await Promise.race([(async()=>{await Promise.allSettled([...this.#i]);let t=await this.#a;if(t)await t.shutdown(this.options.shutdownMs??1500)})().catch(()=>{return}),new Promise((t)=>{e=setTimeout(t,this.options.shutdownMs??1500)})]),this.#c=!0,clearTimeout(e)}}var b$n="b184066a03e82e65df50cc9bb176cd9780f2bc02",lht="https://us.i.posthog.com",dfr="phc_usiY5ZV4ZV4G2NALf4dif826qU4qjLNi8Hc53m6Jb67t",w$n,S$n,mfr,hfr;var gfr=We(()=>{Hdt();Oy();Rw();w$n=K6e.resolve(import.meta.dir,import.meta.dir.endsWith(K6e.sep+"dist")?"..":"../.."),S$n=new Set(typeof["dist/ast-mcp.js","dist/workers/code-intelligence-worker.js","dist/workers/dynamic-wasm-worker.js","dist/workers/embedding-model-worker.js","dist/workers/infra-wasm-worker.js","dist/workers/jvm-wasm-worker.js","dist/workers/legacy-wasm-worker.js","dist/workers/parser-worker.js","dist/workers/patch-strategy-worker.js","dist/workers/systems-wasm-worker.js","src/cli/config.ts","src/cli/index.ts","src/cli/mcp.ts","src/cli/output.ts","src/cli/skills.ts","src/config/edit.ts","src/config/index.ts","src/config/migrate.ts","src/config/registry.ts","src/config/schema-common.ts","src/config/transaction.ts","src/config/v2-schema.ts","src/helpers/aider.ts","src/helpers/config.ts","src/helpers/hook.ts","src/helpers/installer.ts","src/helpers/mcp-schema.ts","src/helpers/process.ts","src/helpers/string.ts","src/hooks/index.ts","src/hooks/managed.ts","src/hooks/shell-policy.ts","src/http/entry.ts","src/http/index.ts","src/index.ts","src/installer/codex.ts","src/installer/health.ts","src/installer/index.ts","src/installer/service.ts","src/installer/transport.ts","src/intelligence/analytics/analytics.ts","src/intelligence/analytics/index.ts","src/intelligence/analytics/repository.ts","src/intelligence/analytics/types.ts","src/intelligence/contracts/artifacts.ts","src/intelligence/contracts/common.ts","src/intelligence/contracts/graph.ts","src/intelligence/contracts/index.ts","src/intelligence/contracts/language.ts","src/intelligence/contracts/result.ts","src/intelligence/contracts/storage.ts","src/intelligence/contracts/workspace.ts","src/intelligence/documents/core.ts","src/intelligence/documents/index.ts","src/intelligence/documents/manifest.ts","src/intelligence/documents/rewrite.ts","src/intelligence/documents/types.ts","src/intelligence/generation/index.ts","src/intelligence/generation/providers.ts","src/intelligence/generation/service.ts","src/intelligence/generation/types.ts","src/intelligence/graph/algorithms/algorithms.ts","src/intelligence/graph/algorithms/index.ts","src/intelligence/graph/algorithms/types.ts","src/intelligence/graph/diff.ts","src/intelligence/graph/from-resolution.ts","src/intelligence/graph/index.ts","src/intelligence/graph/materializer.ts","src/intelligence/graph/repository.ts","src/intelligence/graph/resolution-schema.ts","src/intelligence/graph/shared.ts","src/intelligence/graph/types.ts","src/intelligence/languages/dynamic/analyzer.ts","src/intelligence/languages/dynamic/index.ts","src/intelligence/languages/dynamic/manifest.ts","src/intelligence/languages/dynamic/protocol.ts","src/intelligence/languages/dynamic/types.ts","src/intelligence/languages/dynamic/wasm-worker.ts","src/intelligence/languages/immutable.ts","src/intelligence/languages/infra/analyzer.ts","src/intelligence/languages/infra/index.ts","src/intelligence/languages/infra/manifest.ts","src/intelligence/languages/infra/types.ts","src/intelligence/languages/infra/wasm-worker.ts","src/intelligence/languages/infra/worker-client.ts","src/intelligence/languages/jvm/analyzer.ts","src/intelligence/languages/jvm/index.ts","src/intelligence/languages/jvm/manifest.ts","src/intelligence/languages/jvm/types.ts","src/intelligence/languages/jvm/wasm-worker.ts","src/intelligence/languages/jvm/worker-client.ts","src/intelligence/languages/legacy/analyzer.ts","src/intelligence/languages/legacy/index.ts","src/intelligence/languages/legacy/manifest.ts","src/intelligence/languages/legacy/protocol.ts","src/intelligence/languages/legacy/types.ts","src/intelligence/languages/legacy/wasm-worker.ts","src/intelligence/languages/manifest-builders.ts","src/intelligence/languages/project/core.ts","src/intelligence/languages/project/evidence.ts","src/intelligence/languages/project/index.ts","src/intelligence/languages/project/manifest.ts","src/intelligence/languages/project/types.ts","src/intelligence/languages/shared/language-loader.ts","src/intelligence/languages/shared/language-worker-client.ts","src/intelligence/languages/shared/wasm-assets.ts","src/intelligence/languages/shared/wasm-dynamic-worker.ts","src/intelligence/languages/shared/wasm-fact-assembly.ts","src/intelligence/languages/shared/wasm-infra-worker.ts","src/intelligence/languages/shared/wasm-jvm-worker.ts","src/intelligence/languages/shared/wasm-legacy-worker.ts","src/intelligence/languages/shared/wasm-mainstream-worker.ts","src/intelligence/languages/shared/wasm-systems-worker.ts","src/intelligence/languages/shared/wasm-tree-sitter-support.ts","src/intelligence/languages/shared/wasm-worker-runtime.ts","src/intelligence/languages/shared/wasm-worker-validation.ts","src/intelligence/languages/shared/worker-client.ts","src/intelligence/languages/shared/worker-protocol-validator.ts","src/intelligence/languages/systems/analyzer.ts","src/intelligence/languages/systems/index.ts","src/intelligence/languages/systems/manifest.ts","src/intelligence/languages/systems/types.ts","src/intelligence/languages/systems/wasm-worker.ts","src/intelligence/languages/systems/worker-client.ts","src/intelligence/languages/web/compiler-project.ts","src/intelligence/languages/web/compiler.ts","src/intelligence/languages/web/index.ts","src/intelligence/languages/web/manifest.ts","src/intelligence/languages/web/templates.ts","src/intelligence/languages/web/types.ts","src/intelligence/languages/worker-client-validation.ts","src/intelligence/lifecycle/dispatcher.ts","src/intelligence/lifecycle/service.ts","src/intelligence/manifest-registry.ts","src/intelligence/mutation/freshness.ts","src/intelligence/mutation/index.ts","src/intelligence/mutation/journal.ts","src/intelligence/mutation/lifecycle.ts","src/intelligence/mutation/locks.ts","src/intelligence/mutation/service.ts","src/intelligence/mutation/types.ts","src/intelligence/parser/coordinates.ts","src/intelligence/parser/index.ts","src/intelligence/parser/language-catalog.ts","src/intelligence/parser/parser.ts","src/intelligence/parser/pool.ts","src/intelligence/parser/registry.ts","src/intelligence/parser/source-map.ts","src/intelligence/parser/structural.ts","src/intelligence/parser/structured.ts","src/intelligence/parser/transport.ts","src/intelligence/parser/types.ts","src/intelligence/parser/worker.ts","src/intelligence/resolution/index.ts","src/intelligence/resolution/resolver.ts","src/intelligence/resolution/types.ts","src/intelligence/retrieval/benchmark.ts","src/intelligence/retrieval/context.ts","src/intelligence/retrieval/embedding.ts","src/intelligence/retrieval/index.ts","src/intelligence/retrieval/model-provider.ts","src/intelligence/retrieval/model-worker.ts","src/intelligence/retrieval/publication.ts","src/intelligence/retrieval/query.ts","src/intelligence/retrieval/types.ts","src/intelligence/retrieval/worker-session.ts","src/intelligence/storage/arrow.ts","src/intelligence/storage/coordinator.ts","src/intelligence/storage/errors.ts","src/intelligence/storage/index.ts","src/intelligence/storage/relocation.ts","src/intelligence/storage/schemas.ts","src/intelligence/storage/store.ts","src/intelligence/workspace/context.ts","src/intelligence/workspace/errors.ts","src/intelligence/workspace/git.ts","src/intelligence/workspace/index.ts","src/intelligence/workspace/registry.ts","src/intelligence/workspace/storage.ts","src/intelligence/workspace/tools.ts","src/patch/aider.ts","src/patch/engine.ts","src/patch/languages.ts","src/patch/strategy.ts","src/patch/strategy/aiderBlock.ts","src/patch/strategy/ast.ts","src/patch/strategy/inline.ts","src/patch/strategy/worker-client.ts","src/patch/strategy/worker.ts","src/runtime/approval.ts","src/runtime/atomic.ts","src/runtime/attributes.ts","src/runtime/binary-resolution.ts","src/runtime/config-write.ts","src/runtime/dependencies.ts","src/runtime/document-inspection.ts","src/runtime/file-capabilities.ts","src/runtime/file-delete.ts","src/runtime/file-read.ts","src/runtime/file-rename.ts","src/runtime/file-snapshot.ts","src/runtime/format.ts","src/runtime/git-worktrees.ts","src/runtime/hash.ts","src/runtime/locks.ts","src/runtime/parent-directories.ts","src/runtime/path-policy.ts","src/runtime/path-utils.ts","src/runtime/paths.ts","src/runtime/policy.ts","src/runtime/private-lock-directory.ts","src/runtime/process-input.ts","src/runtime/reference-target-index.ts","src/runtime/signals.ts","src/runtime/snapshot-blob.ts","src/runtime/subprocess.ts","src/runtime/telemetry.ts","src/runtime/transaction-lock.ts","src/server/index.ts","src/server/lifecycle.ts","src/server/stdio.ts","src/skills/export.ts","src/skills/index.ts","src/tools/code-intelligence-compute.ts","src/tools/code-intelligence-worker.ts","src/tools/code-intelligence.ts","src/tools/configuration.ts","src/tools/configured.ts","src/tools/files.ts","src/tools/index.ts","src/tools/intelligence-output.ts","src/tools/intelligence.ts","src/tools/lifecycle.ts"]<"u"?["dist/ast-mcp.js","dist/workers/code-intelligence-worker.js","dist/workers/dynamic-wasm-worker.js","dist/workers/embedding-model-worker.js","dist/workers/infra-wasm-worker.js","dist/workers/jvm-wasm-worker.js","dist/workers/legacy-wasm-worker.js","dist/workers/parser-worker.js","dist/workers/patch-strategy-worker.js","dist/workers/systems-wasm-worker.js","src/cli/config.ts","src/cli/index.ts","src/cli/mcp.ts","src/cli/output.ts","src/cli/skills.ts","src/config/edit.ts","src/config/index.ts","src/config/migrate.ts","src/config/registry.ts","src/config/schema-common.ts","src/config/transaction.ts","src/config/v2-schema.ts","src/helpers/aider.ts","src/helpers/config.ts","src/helpers/hook.ts","src/helpers/installer.ts","src/helpers/mcp-schema.ts","src/helpers/process.ts","src/helpers/string.ts","src/hooks/index.ts","src/hooks/managed.ts","src/hooks/shell-policy.ts","src/http/entry.ts","src/http/index.ts","src/index.ts","src/installer/codex.ts","src/installer/health.ts","src/installer/index.ts","src/installer/service.ts","src/installer/transport.ts","src/intelligence/analytics/analytics.ts","src/intelligence/analytics/index.ts","src/intelligence/analytics/repository.ts","src/intelligence/analytics/types.ts","src/intelligence/contracts/artifacts.ts","src/intelligence/contracts/common.ts","src/intelligence/contracts/graph.ts","src/intelligence/contracts/index.ts","src/intelligence/contracts/language.ts","src/intelligence/contracts/result.ts","src/intelligence/contracts/storage.ts","src/intelligence/contracts/workspace.ts","src/intelligence/documents/core.ts","src/intelligence/documents/index.ts","src/intelligence/documents/manifest.ts","src/intelligence/documents/rewrite.ts","src/intelligence/documents/types.ts","src/intelligence/generation/index.ts","src/intelligence/generation/providers.ts","src/intelligence/generation/service.ts","src/intelligence/generation/types.ts","src/intelligence/graph/algorithms/algorithms.ts","src/intelligence/graph/algorithms/index.ts","src/intelligence/graph/algorithms/types.ts","src/intelligence/graph/diff.ts","src/intelligence/graph/from-resolution.ts","src/intelligence/graph/index.ts","src/intelligence/graph/materializer.ts","src/intelligence/graph/repository.ts","src/intelligence/graph/resolution-schema.ts","src/intelligence/graph/shared.ts","src/intelligence/graph/types.ts","src/intelligence/languages/dynamic/analyzer.ts","src/intelligence/languages/dynamic/index.ts","src/intelligence/languages/dynamic/manifest.ts","src/intelligence/languages/dynamic/protocol.ts","src/intelligence/languages/dynamic/types.ts","src/intelligence/languages/dynamic/wasm-worker.ts","src/intelligence/languages/immutable.ts","src/intelligence/languages/infra/analyzer.ts","src/intelligence/languages/infra/index.ts","src/intelligence/languages/infra/manifest.ts","src/intelligence/languages/infra/types.ts","src/intelligence/languages/infra/wasm-worker.ts","src/intelligence/languages/infra/worker-client.ts","src/intelligence/languages/jvm/analyzer.ts","src/intelligence/languages/jvm/index.ts","src/intelligence/languages/jvm/manifest.ts","src/intelligence/languages/jvm/types.ts","src/intelligence/languages/jvm/wasm-worker.ts","src/intelligence/languages/jvm/worker-client.ts","src/intelligence/languages/legacy/analyzer.ts","src/intelligence/languages/legacy/index.ts","src/intelligence/languages/legacy/manifest.ts","src/intelligence/languages/legacy/protocol.ts","src/intelligence/languages/legacy/types.ts","src/intelligence/languages/legacy/wasm-worker.ts","src/intelligence/languages/manifest-builders.ts","src/intelligence/languages/project/core.ts","src/intelligence/languages/project/evidence.ts","src/intelligence/languages/project/index.ts","src/intelligence/languages/project/manifest.ts","src/intelligence/languages/project/types.ts","src/intelligence/languages/shared/language-loader.ts","src/intelligence/languages/shared/language-worker-client.ts","src/intelligence/languages/shared/wasm-assets.ts","src/intelligence/languages/shared/wasm-dynamic-worker.ts","src/intelligence/languages/shared/wasm-fact-assembly.ts","src/intelligence/languages/shared/wasm-infra-worker.ts","src/intelligence/languages/shared/wasm-jvm-worker.ts","src/intelligence/languages/shared/wasm-legacy-worker.ts","src/intelligence/languages/shared/wasm-mainstream-worker.ts","src/intelligence/languages/shared/wasm-systems-worker.ts","src/intelligence/languages/shared/wasm-tree-sitter-support.ts","src/intelligence/languages/shared/wasm-worker-runtime.ts","src/intelligence/languages/shared/wasm-worker-validation.ts","src/intelligence/languages/shared/worker-client.ts","src/intelligence/languages/shared/worker-protocol-validator.ts","src/intelligence/languages/systems/analyzer.ts","src/intelligence/languages/systems/index.ts","src/intelligence/languages/systems/manifest.ts","src/intelligence/languages/systems/types.ts","src/intelligence/languages/systems/wasm-worker.ts","src/intelligence/languages/systems/worker-client.ts","src/intelligence/languages/web/compiler-project.ts","src/intelligence/languages/web/compiler.ts","src/intelligence/languages/web/index.ts","src/intelligence/languages/web/manifest.ts","src/intelligence/languages/web/templates.ts","src/intelligence/languages/web/types.ts","src/intelligence/languages/worker-client-validation.ts","src/intelligence/lifecycle/dispatcher.ts","src/intelligence/lifecycle/service.ts","src/intelligence/manifest-registry.ts","src/intelligence/mutation/freshness.ts","src/intelligence/mutation/index.ts","src/intelligence/mutation/journal.ts","src/intelligence/mutation/lifecycle.ts","src/intelligence/mutation/locks.ts","src/intelligence/mutation/service.ts","src/intelligence/mutation/types.ts","src/intelligence/parser/coordinates.ts","src/intelligence/parser/index.ts","src/intelligence/parser/language-catalog.ts","src/intelligence/parser/parser.ts","src/intelligence/parser/pool.ts","src/intelligence/parser/registry.ts","src/intelligence/parser/source-map.ts","src/intelligence/parser/structural.ts","src/intelligence/parser/structured.ts","src/intelligence/parser/transport.ts","src/intelligence/parser/types.ts","src/intelligence/parser/worker.ts","src/intelligence/resolution/index.ts","src/intelligence/resolution/resolver.ts","src/intelligence/resolution/types.ts","src/intelligence/retrieval/benchmark.ts","src/intelligence/retrieval/context.ts","src/intelligence/retrieval/embedding.ts","src/intelligence/retrieval/index.ts","src/intelligence/retrieval/model-provider.ts","src/intelligence/retrieval/model-worker.ts","src/intelligence/retrieval/publication.ts","src/intelligence/retrieval/query.ts","src/intelligence/retrieval/types.ts","src/intelligence/retrieval/worker-session.ts","src/intelligence/storage/arrow.ts","src/intelligence/storage/coordinator.ts","src/intelligence/storage/errors.ts","src/intelligence/storage/index.ts","src/intelligence/storage/relocation.ts","src/intelligence/storage/schemas.ts","src/intelligence/storage/store.ts","src/intelligence/workspace/context.ts","src/intelligence/workspace/errors.ts","src/intelligence/workspace/git.ts","src/intelligence/workspace/index.ts","src/intelligence/workspace/registry.ts","src/intelligence/workspace/storage.ts","src/intelligence/workspace/tools.ts","src/patch/aider.ts","src/patch/engine.ts","src/patch/languages.ts","src/patch/strategy.ts","src/patch/strategy/aiderBlock.ts","src/patch/strategy/ast.ts","src/patch/strategy/inline.ts","src/patch/strategy/worker-client.ts","src/patch/strategy/worker.ts","src/runtime/approval.ts","src/runtime/atomic.ts","src/runtime/attributes.ts","src/runtime/binary-resolution.ts","src/runtime/config-write.ts","src/runtime/dependencies.ts","src/runtime/document-inspection.ts","src/runtime/file-capabilities.ts","src/runtime/file-delete.ts","src/runtime/file-read.ts","src/runtime/file-rename.ts","src/runtime/file-snapshot.ts","src/runtime/format.ts","src/runtime/git-worktrees.ts","src/runtime/hash.ts","src/runtime/locks.ts","src/runtime/parent-directories.ts","src/runtime/path-policy.ts","src/runtime/path-utils.ts","src/runtime/paths.ts","src/runtime/policy.ts","src/runtime/private-lock-directory.ts","src/runtime/process-input.ts","src/runtime/reference-target-index.ts","src/runtime/signals.ts","src/runtime/snapshot-blob.ts","src/runtime/subprocess.ts","src/runtime/telemetry.ts","src/runtime/transaction-lock.ts","src/server/index.ts","src/server/lifecycle.ts","src/server/stdio.ts","src/skills/export.ts","src/skills/index.ts","src/tools/code-intelligence-compute.ts","src/tools/code-intelligence-worker.ts","src/tools/code-intelligence.ts","src/tools/configuration.ts","src/tools/configured.ts","src/tools/files.ts","src/tools/index.ts","src/tools/intelligence-output.ts","src/tools/intelligence.ts","src/tools/lifecycle.ts"]:["src/server/index.ts","src/config/index.ts","src/http/index.ts","src/server/stdio.ts","src/tools/configured.ts","src/runtime/paths.ts","src/runtime/format.ts","src/runtime/policy.ts","src/runtime/approval.ts","src/patch/engine.ts","dist/ast-mcp.js","dist/workers/code-intelligence-worker.js","dist/workers/dynamic-wasm-worker.js","dist/workers/infra-wasm-worker.js","dist/workers/jvm-wasm-worker.js","dist/workers/legacy-wasm-worker.js","dist/workers/systems-wasm-worker.js"]);mfr=new Set(["approval_required","approval_denied","path_denied","path_outside_root","workspace_mismatch","workspace_required","intelligence_budget_exceeded","intelligence_refresh_timeout","reference_verification_failed","graph_budget_exhausted","document_too_large","document_not_regular","deprecated_root_environment","aborted","timeout","tool_stalled","use_file_patch","generation_unavailable","cross_repository_federation_required","graph_node_not_found","invalid_graph_cursor","patch_strategy_unavailable","patch_strategy_arguments","patch_strategy_required","ast_match_count","ast_rewrite_overlap","ast_preview_error","aider_matcher_disabled","invalid_text_encoding","lock_aborted","lock_deadline","lock_fenced","cross_root_ast_request","configuration_path_missing","configuration_missing","configuration_path_duplicate","configuration_empty_patch","configuration_invalid","document_format_unsupported","invalid_document_selector","document_result_too_large","document_source_too_large","read_mode_unavailable","ast_capability_unavailable","candidate_parse_error","approval_persistence_required","approval_persistence_busy","approval_persistence_conflict","approval_challenge_limit","workspace_ambiguous","stale_hash","missing_hash","stale_preview_receipt","preview_receipt_expired","preview_receipt_invalid","preview_receipt_mismatch","permission_denied","file_not_found","formatter_unavailable","formatter_rejected","formatter_cleanup_failed","command_timeout","command_invalid_output","aider_ambiguous","preview_receipt_unknown","preview_receipt_file_mismatch","preview_receipt_session_mismatch","preview_receipt_workspace_changed","preview_receipt_configuration_changed","preview_receipt_integrity","preview_receipt_limit","workspace_not_found","workspace_revision_invalid","workspace_read_only","InputRequiredSignal","formatter_missing","formatter_timeout","formatter_failed","formatter_invalid_output","formatting_rejected","ambiguous_match","patch_ambiguous","patch_no_match","immutable_revision","revision_immutable","configuration_mcp_disabled","configuration_migration_required","cancelled","operation_aborted","EACCES","EPERM","ENOENT","AbortError"]),hfr=new Set(["Error","TypeError","RangeError","SyntaxError","ReferenceError"])});import{AsyncLocalStorage as E$n}from"async_hooks";import{createHash as bfr,randomUUID as dht}from"crypto";import{chmodSync as k$n,existsSync as wfr,mkdirSync as Sfr,readFileSync as C$n,renameSync as I$n,statSync as A$n,unlinkSync as P$n,writeFileSync as D$n}from"fs";import u0e from"path";function xfr(e){Tfr=e}function vfr(e){Sfr(u0e.dirname(e),{mode:448,recursive:!0});let t=wfr(e)?C$n(e,"utf8"):"";if(!t)return t;if(Bun.TOML.parse(t).version===2)return t;throw Object.assign(Error("Persistent approvals require a version 2 user-global ast-mcp.toml; migrate it explicitly first"),{code:"approval_persistence_required",retryable:!0,suggestedNextCall:"config_status"})}function M$n(e,t){if(!e)return[];return(Bun.TOML.parse(e).paths??[]).filter((s)=>s.id?.startsWith("approval-")&&s.path===t)}function F$n(e,t=[]){let n=new Set([e]);for(let s of t)for(let c of["read","write","delete"])if(s.policies?.[c]==="allow")n.add(c);return{delete:n.has("delete")?"allow":"deny",read:n.has("read")?"allow":"deny",write:n.has("write")?"allow":"deny"}}function Efr(e){return`policies = { read = ${JSON.stringify(e.read)}, write = ${JSON.stringify(e.write)}, delete = ${JSON.stringify(e.delete)} }`}function L$n(e,t,n){let s=new Set(t.flatMap((u)=>u.id?[u.id]:[])),c=Efr(n);return e.split(/(?=^\[\[paths\]\]\s*$)/m).map((u)=>[...s].some((d)=>u.includes(`id = ${JSON.stringify(d)}`))?u.replace(/^policies = \{.*\}$/m,c):u).join("")}function B$n(e){return`approval-${bfr("sha256").update(`${e.operation}\x00${e.canonicalPath}`).digest("hex").slice(0,16)}`}function j$n(e,t){Sfr(u0e.dirname(e),{mode:448,recursive:!0});let n=xre(e),s=u0e.join(u0e.dirname(n),`.${u0e.basename(n)}.approval-${dht()}`);try{Ere(n,()=>{try{cz(e,n);let c=vfr(n),u=wfr(n)?A$n(n).mode&4095:384,d=t(c);if(d===void 0)return;if(D$n(s,d,{flag:"wx",mode:u}),k$n(s,u),cz(e,n),vfr(n)!==c)throw Object.assign(Error("User-global configuration changed during approval; retry"),{code:"approval_persistence_conflict",retryable:!0});cz(e,n),I$n(s,n)}finally{try{P$n(s)}catch{}}})}catch(c){if(c.code==="configuration_busy")Object.assign(c,{code:"approval_persistence_busy"});throw c}}function z$n(e){let t=dD(),n=B$n(e),s=!1,c=!1;if(j$n(t,(u)=>{let d=M$n(u,e.canonicalPath),m=F$n(e.operation,d);if(d.length>0){let T=L$n(u,d,m);if(T===u)return;return s=!0,T}let y=["[[paths]]",`id = ${JSON.stringify(n)}`,`path = ${JSON.stringify(e.canonicalPath)}`,Efr(m),"follow_symlinks = false",'includes = ["**/*"]',"excludes = []"].join(`
|
|
347
347
|
`),S=u||`version = 2
|
|
348
348
|
`;return s=!0,c=!0,`${S.trimEnd()}
|
|
349
349
|
|
|
@@ -969,4 +969,4 @@ Additional information: BADCLIENT: Bad error code, ${M} not found in range ${h}.
|
|
|
969
969
|
`),s}var qQr=We(()=>{Fdt()});await Promise.resolve().then(() => eKt());try{let e=await ZQt(process.argv.slice(2),{config:async(t)=>{await Promise.resolve().then(() => cZt());return await aZt(t)},skills:async(t)=>{await Promise.resolve().then(() => Ltr());await Ftr(t)},hook:async()=>{await Trr();return Srr()},installer:async(t)=>{await vnr();await ynr(t)},mcp:async(t)=>{await Promise.resolve().then(() => qQr());await UQr(t)}});if(e!==void 0)process.exitCode=e}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`ast-mcp: ${t}
|
|
970
970
|
`),process.exitCode=1}
|
|
971
971
|
|
|
972
|
-
//# debugId=
|
|
972
|
+
//# debugId=5F9EA2959B66C08264756E2164756E21
|