@cline/core 0.0.95 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/dist/ClineCore.d.ts +6 -1
  2. package/dist/account/rpc.d.ts +3 -1
  3. package/dist/cline-core/runtime-services.d.ts +4 -2
  4. package/dist/cloud/controller.d.ts +5 -2
  5. package/dist/cloud/hub-client.d.ts +51 -0
  6. package/dist/cloud/hub-protocol.d.ts +18 -0
  7. package/dist/cloud/index.d.ts +2 -0
  8. package/dist/cloud/index.js +16 -16
  9. package/dist/cloud/types.d.ts +4 -1
  10. package/dist/extensions/context/compaction-shared.d.ts +1 -0
  11. package/dist/extensions/context/compaction.d.ts +7 -0
  12. package/dist/extensions/context/summarize-conversation.d.ts +7 -0
  13. package/dist/extensions/context/summary-generation.d.ts +14 -0
  14. package/dist/extensions/mcp/apps.d.ts +16 -0
  15. package/dist/extensions/mcp/client.d.ts +1 -0
  16. package/dist/extensions/mcp/index.d.ts +5 -1
  17. package/dist/extensions/mcp/manager.d.ts +2 -1
  18. package/dist/extensions/mcp/session-apps.d.ts +28 -0
  19. package/dist/extensions/mcp/types.d.ts +22 -0
  20. package/dist/extensions/plugin/plugin-command-origin.d.ts +8 -0
  21. package/dist/extensions/plugin/plugin-registry.d.ts +1 -0
  22. package/dist/extensions/plugin/plugin-runtime.d.ts +7 -0
  23. package/dist/hub/client/index.d.ts +6 -0
  24. package/dist/hub/client/managed-hub-build-watcher.d.ts +2 -0
  25. package/dist/hub/client/plugin-commands.d.ts +4 -0
  26. package/dist/hub/client/session-client.d.ts +2 -0
  27. package/dist/hub/daemon/entry.js +241 -228
  28. package/dist/hub/index.d.ts +1 -0
  29. package/dist/hub/index.js +231 -218
  30. package/dist/hub/runtime-host/hub-runtime-host.d.ts +6 -0
  31. package/dist/hub/server/cloud-session-service.d.ts +50 -0
  32. package/dist/hub/server/handlers/capability-handlers.d.ts +18 -1
  33. package/dist/hub/server/handlers/context.d.ts +13 -2
  34. package/dist/hub/server/handlers/mcp-apps-handlers.d.ts +5 -0
  35. package/dist/hub/server/hub-server-options.d.ts +3 -0
  36. package/dist/hub/server/hub-server-transport.d.ts +2 -0
  37. package/dist/index.d.ts +8 -4
  38. package/dist/index.js +278 -258
  39. package/dist/plugin-runtime/node_modules/@cline/agents/dist/index.js +76 -0
  40. package/dist/plugin-runtime/node_modules/@cline/agents/package.json +1 -0
  41. package/dist/plugin-runtime/node_modules/@cline/core/dist/ai-sdk-b1d8eb67.js +1 -0
  42. package/dist/plugin-runtime/node_modules/@cline/core/dist/anthropic-33qvrctr.js +1 -0
  43. package/dist/plugin-runtime/node_modules/@cline/core/dist/bedrock-paabhz8w.js +1 -0
  44. package/dist/plugin-runtime/node_modules/@cline/core/dist/cline-yhsfqcy1.js +1 -0
  45. package/dist/plugin-runtime/node_modules/@cline/core/dist/cloud/index.js +21 -0
  46. package/dist/plugin-runtime/node_modules/@cline/core/dist/community-gqgs7446.js +1 -0
  47. package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-embedding-model-strategy-SAVQFBF4-822304b0.js +1 -0
  48. package/dist/plugin-runtime/node_modules/@cline/core/dist/foundation-models-language-model-strategy-BPQO66W7-hky2m2yx.js +1 -0
  49. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-sqf1kd37.js +1 -0
  50. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-bsd-tx1kp6xn.js +1 -0
  51. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-6cpgjxme.js +2 -0
  52. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-darwin-fxchqbze.js +2 -0
  53. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-m3bzwmzc.js +1 -0
  54. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-linux-pr9sb5fr.js +1 -0
  55. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-nckraycx.js +1 -0
  56. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-unsupported-w91yq3tm.js +1 -0
  57. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-xdyxc2tf.js +1 -0
  58. package/dist/plugin-runtime/node_modules/@cline/core/dist/getMachineId-win-yxsvs11a.js +1 -0
  59. package/dist/plugin-runtime/node_modules/@cline/core/dist/google-pgdk2dm9.js +1 -0
  60. package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/daemon/entry.js +1160 -0
  61. package/dist/plugin-runtime/node_modules/@cline/core/dist/hub/index.js +1147 -0
  62. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-02jpyn9y.js +85 -0
  63. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-0cb4390m.js +137 -0
  64. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-0f8xrhgt.js +209 -0
  65. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-1f8vb421.js +2 -0
  66. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-28c7m0fv.js +16 -0
  67. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-2em3jg4q.js +1 -0
  68. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-4n1zpzbe.js +2 -0
  69. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-54eea0ex.js +2 -0
  70. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-5j92dtg5.js +16 -0
  71. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-6akf3a5d.js +2 -0
  72. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-6k6ep10s.js +136 -0
  73. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-71ym4q6s.js +2 -0
  74. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-91p1ghfk.js +14 -0
  75. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-9qkpjy7x.js +2 -0
  76. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-9swk4nej.js +3 -0
  77. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-aa2s5myc.js +1 -0
  78. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ae0ajw38.js +13 -0
  79. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bxvyzjhc.js +1 -0
  80. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-bzy863k0.js +6 -0
  81. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-d96n0s70.js +20 -0
  82. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-dsd6vt8c.js +1 -0
  83. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-e2q4azd9.js +119 -0
  84. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-egd18jj2.js +4 -0
  85. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-eh83hr16.js +2 -0
  86. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-ev9r2dy3.js +1204 -0
  87. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-f2mvvryf.js +190 -0
  88. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-h7gn5v3f.js +2 -0
  89. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-h7s1a560.js +12 -0
  90. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-hkhq3jtz.js +21 -0
  91. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-j8r18nfg.js +15 -0
  92. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-jhny555h.js +6 -0
  93. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m1gpa2eg.js +146 -0
  94. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m2ad6tgj.js +1 -0
  95. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-m7mks2jq.js +4 -0
  96. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-mcnngj50.js +62 -0
  97. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-n2srkkh0.js +39 -0
  98. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-nbs1tsny.js +142 -0
  99. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-nqjnz7m4.js +9 -0
  100. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-rmhzyxr8.js +3 -0
  101. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-rtzf3vvk.js +6 -0
  102. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-sw74pcm3.js +2 -0
  103. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-t3eanyjj.js +3 -0
  104. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-tseksj1v.js +1 -0
  105. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v0ctpcdr.js +12 -0
  106. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v4-dx8bd4wq.js +1 -0
  107. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v695918t.js +14 -0
  108. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-v96yy1pw.js +1 -0
  109. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-vfm7r9wk.js +65 -0
  110. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-xecthgrg.js +9 -0
  111. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-xn1xhp06.js +9 -0
  112. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-yfdscfdx.js +1 -0
  113. package/dist/plugin-runtime/node_modules/@cline/core/dist/index-yrnwqsdt.js +2 -0
  114. package/dist/plugin-runtime/node_modules/@cline/core/dist/index.js +1 -0
  115. package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-static-3mgy2y9y.js +473 -0
  116. package/dist/plugin-runtime/node_modules/@cline/core/dist/jiti-w1xrs0vd.js +1 -0
  117. package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-stream-telemetry-9tppg77c.js +1 -0
  118. package/dist/plugin-runtime/node_modules/@cline/core/dist/langfuse-telemetry-y658kpzy.js +1 -0
  119. package/dist/plugin-runtime/node_modules/@cline/core/dist/mistral-cmhqd91b.js +1 -0
  120. package/dist/plugin-runtime/node_modules/@cline/core/dist/multipart-parser-qkjjf8mm.js +2 -0
  121. package/dist/plugin-runtime/node_modules/@cline/core/dist/ollama-8z6y9d1h.js +1 -0
  122. package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-cfmja1ez.js +1 -0
  123. package/dist/plugin-runtime/node_modules/@cline/core/dist/openai-compatible-1t7n5sxj.js +1 -0
  124. package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-embedding-model-strategy-GT27AFII-k6yqgnyd.js +1 -0
  125. package/dist/plugin-runtime/node_modules/@cline/core/dist/orchestration-language-model-strategy-YEQPUCOT-6rdyebbq.js +1 -0
  126. package/dist/plugin-runtime/node_modules/@cline/core/dist/services/feature-flags/posthog.js +2 -0
  127. package/dist/plugin-runtime/node_modules/@cline/core/dist/services/telemetry/index.js +1 -0
  128. package/dist/plugin-runtime/node_modules/@cline/core/dist/token-1h068py9.js +1 -0
  129. package/dist/plugin-runtime/node_modules/@cline/core/dist/token-util-7jchft51.js +1 -0
  130. package/dist/plugin-runtime/node_modules/@cline/core/dist/vertex-qfxfsrn4.js +1 -0
  131. package/dist/plugin-runtime/node_modules/@cline/core/package.json +1 -0
  132. package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.browser.js +16 -0
  133. package/dist/plugin-runtime/node_modules/@cline/llms/dist/index.js +1 -0
  134. package/dist/plugin-runtime/node_modules/@cline/llms/package.json +1 -0
  135. package/dist/plugin-runtime/node_modules/@cline/sdk/dist/index.js +1 -0
  136. package/dist/plugin-runtime/node_modules/@cline/sdk/package.json +1 -0
  137. package/dist/plugin-runtime/node_modules/@cline/shared/dist/automation/index.js +57 -0
  138. package/dist/plugin-runtime/node_modules/@cline/shared/dist/db/index.js +127 -0
  139. package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.browser.js +110 -0
  140. package/dist/plugin-runtime/node_modules/@cline/shared/dist/index.js +1 -0
  141. package/dist/plugin-runtime/node_modules/@cline/shared/dist/node.js +1 -0
  142. package/dist/plugin-runtime/node_modules/@cline/shared/dist/remote-config/index.js +68 -0
  143. package/dist/plugin-runtime/node_modules/@cline/shared/dist/storage/index.js +1 -0
  144. package/dist/plugin-runtime/node_modules/@cline/shared/dist/types/index.js +1 -0
  145. package/dist/plugin-runtime/node_modules/@cline/shared/package.json +1 -0
  146. package/dist/plugin-runtime/package.json +1 -0
  147. package/dist/{extensions → plugin-runtime}/plugin-sandbox-bootstrap.js +129 -129
  148. package/dist/remote/remote-environments.d.ts +1 -0
  149. package/dist/runtime/config/agent-runtime-config-builder.d.ts +2 -0
  150. package/dist/runtime/host/local-runtime-host.d.ts +10 -0
  151. package/dist/runtime/host/runtime-host.d.ts +6 -0
  152. package/dist/runtime/orchestration/runtime-oauth-token-manager.d.ts +3 -0
  153. package/dist/runtime/orchestration/session-runtime-orchestrator.d.ts +10 -1
  154. package/dist/runtime/orchestration/session-runtime.d.ts +2 -0
  155. package/dist/runtime/tools/subprocess-sandbox.d.ts +22 -0
  156. package/dist/services/llms/cline-recommended-models.d.ts +2 -0
  157. package/dist/services/local-runtime-bootstrap.d.ts +1 -0
  158. package/dist/services/plugin-command-api.d.ts +47 -0
  159. package/dist/services/plugin-commands.d.ts +25 -27
  160. package/dist/services/skills-cli.d.ts +2 -0
  161. package/dist/services/telemetry/core-events.d.ts +26 -0
  162. package/dist/services/telemetry/index.js +1 -1
  163. package/dist/services/telemetry/run-health.d.ts +40 -0
  164. package/dist/services/telemetry/stall-signals.d.ts +12 -0
  165. package/dist/types/config.d.ts +1 -0
  166. package/dist/types/session.d.ts +7 -0
  167. package/package.json +6 -5
@@ -0,0 +1 @@
1
+ import{Jp}from"./index-hkhq3jtz.js";import{v}from"./index-mcnngj50.js";var i=v(Jp(),1);import{createRequire as o}from"node:module";function n(r){throw r}var a=(r)=>import(r),e;function f(...r){if(!e)e=o(import.meta.url)("../dist/babel.cjs");return e(...r)}function m(r,t={}){if(!t.transform)t={...t,transform:f};return i.default(r,t,{onError:n,nativeImport:a,createRequire:o})}var l=m;export{m as createJiti,l as default};
@@ -0,0 +1 @@
1
+ import{pp}from"./index-v0ctpcdr.js";import{Me,xc}from"./index-6k6ep10s.js";import{Ho}from"./index-28c7m0fv.js";class o extends pp{attempts=new Map;completedAttempts=new Map;startingCallId;constructor(t){super({tracer:{startSpan:(e,a,n)=>{let l=t.startSpan(e,a,n);if(this.startingCallId)this.attempts.set(this.startingCallId,l);return l},startActiveSpan:t.startActiveSpan.bind(t)}})}onLanguageModelCallStart(t){this.endAttempt(t.callId),this.startingCallId=t.callId;try{super.onLanguageModelCallStart(t)}finally{this.startingCallId=void 0}}async executeLanguageModelCall(t){try{return await super.executeLanguageModelCall(t)}catch(e){throw this.onLanguageModelCallError({callId:t.callId,error:e}),this.endAttempt(t.callId),e}}onLanguageModelCallEnd(t){if(this.completedAttempts.set(t.callId,t),t.finishReason!=="error")this.endAttempt(t.callId)}endAttempt(t){let e=this.completedAttempts.get(t);if(e)super.onLanguageModelCallEnd(e);else this.attempts.get(t)?.end();this.completedAttempts.delete(t),this.attempts.delete(t)}onStepEnd(t){this.endAttempt(t.callId),super.onStepEnd(t)}onLanguageModelCallError({callId:t,error:e}){if(Me(e)&&!Ho(e))return;let a=this.attempts.get(t);if(!a)return;let n=e instanceof Error?e.message:typeof e==="object"&&e!==null&&("message"in e)&&typeof e.message==="string"?e.message:"Provider stream failed";a.recordException(e instanceof Error?e:{message:n}),a.setStatus({code:xc.ERROR,message:n})}onError(t){if(typeof t==="object"&&t!==null&&"callId"in t&&typeof t.callId==="string"){let e="error"in t?t.error:t;if(Me(e)&&!Ho(e)){this.endAttempt(t.callId);return}this.onLanguageModelCallError({callId:t.callId,error:e}),this.endAttempt(t.callId)}super.onError(t)}onEnd(t){this.endAttempt(t.callId),super.onEnd(t)}onAbort(t){this.endAttempt(t.callId),super.onAbort(t)}}export{o as LangfuseStreamTelemetry};
@@ -0,0 +1 @@
1
+ import{zv,PS,Qg}from"./index-28c7m0fv.js";export{Qg as disposeLangfuseTelemetry,PS as resolveAiSdkTelemetry,zv as withLangfuseTraceAttributes};
@@ -0,0 +1 @@
1
+ import{Ne}from"./index-6k6ep10s.js";import"./index-f2mvvryf.js";import{ct,Qo}from"./index-28c7m0fv.js";import{ml}from"./index-egd18jj2.js";async function s(e){let r=ml({apiKey:await ct(e),baseURL:e.baseUrl,headers:e.headers,fetch:e.fetch});return{operations:{language:(o)=>Ne({model:r(o),middleware:Qo})}}}export{s as createMistralProviderModule};
@@ -0,0 +1,2 @@
1
+ import{tu,Vr,iu,dd}from"./index-h7s1a560.js";import{bt}from"./index-mcnngj50.js";class k{constructor(i){this.index=0,this.flags=0,this.onHeaderEnd=_,this.onHeaderField=_,this.onHeadersEnd=_,this.onHeaderValue=_,this.onPartBegin=_,this.onPartData=_,this.onPartEnd=_,this.boundaryChars={},i=`\r
2
+ --`+i;let r=new Uint8Array(i.length);for(let E=0;E<i.length;E++)r[E]=i.charCodeAt(E),this.boundaryChars[r[E]]=!0;this.boundary=r,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=t.START_BOUNDARY}write(i){let r=0,E=i.length,o=this.index,{lookbehind:d,boundary:A,boundaryChars:L,index:e,state:s,flags:l}=this,R=this.boundary.length,u=R-1,g=i.length,a,S,H=(c)=>{this[c+"Mark"]=r},T=(c)=>{delete this[c+"Mark"]},n=(c,P,f,N)=>{if(P===void 0||P!==f)this[c](N&&N.subarray(P,f))},b=(c,P)=>{let f=c+"Mark";if(!(f in this))return;if(P)n(c,this[f],r,i),delete this[f];else n(c,this[f],i.length,i),this[f]=0};for(r=0;r<E;r++)switch(a=i[r],s){case t.START_BOUNDARY:if(e===A.length-2){if(a===m)l|=D.LAST_BOUNDARY;else if(a!==O)return;e++;break}else if(e-1===A.length-2){if(l&D.LAST_BOUNDARY&&a===m)s=t.END,l=0;else if(!(l&D.LAST_BOUNDARY)&&a===p)e=0,n("onPartBegin"),s=t.HEADER_FIELD_START;else return;break}if(a!==A[e+2])e=-2;if(a===A[e+2])e++;break;case t.HEADER_FIELD_START:s=t.HEADER_FIELD,H("onHeaderField"),e=0;case t.HEADER_FIELD:if(a===O){T("onHeaderField"),s=t.HEADERS_ALMOST_DONE;break}if(e++,a===m)break;if(a===U){if(e===1)return;b("onHeaderField",!0),s=t.HEADER_VALUE_START;break}if(S=V(a),S<w||S>B)return;break;case t.HEADER_VALUE_START:if(a===F)break;H("onHeaderValue"),s=t.HEADER_VALUE;case t.HEADER_VALUE:if(a===O)b("onHeaderValue",!0),n("onHeaderEnd"),s=t.HEADER_VALUE_ALMOST_DONE;break;case t.HEADER_VALUE_ALMOST_DONE:if(a!==p)return;s=t.HEADER_FIELD_START;break;case t.HEADERS_ALMOST_DONE:if(a!==p)return;n("onHeadersEnd"),s=t.PART_DATA_START;break;case t.PART_DATA_START:s=t.PART_DATA,H("onPartData");case t.PART_DATA:if(o=e,e===0){r+=u;while(r<g&&!(i[r]in L))r+=R;r-=u,a=i[r]}if(e<A.length)if(A[e]===a){if(e===0)b("onPartData",!0);e++}else e=0;else if(e===A.length)if(e++,a===O)l|=D.PART_BOUNDARY;else if(a===m)l|=D.LAST_BOUNDARY;else e=0;else if(e-1===A.length)if(l&D.PART_BOUNDARY){if(e=0,a===p){l&=~D.PART_BOUNDARY,n("onPartEnd"),n("onPartBegin"),s=t.HEADER_FIELD_START;break}}else if(l&D.LAST_BOUNDARY)if(a===m)n("onPartEnd"),s=t.END,l=0;else e=0;else e=0;if(e>0)d[e-1]=a;else if(o>0){let c=new Uint8Array(d.buffer,d.byteOffset,d.byteLength);n("onPartData",0,o,c),o=0,H("onPartData"),r--}break;case t.END:break;default:throw Error(`Unexpected state entered: ${s}`)}b("onHeaderField"),b("onHeaderValue"),b("onPartData"),this.index=e,this.state=s,this.flags=l}end(){if(this.state===t.HEADER_FIELD_START&&this.index===0||this.state===t.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==t.END)throw Error("MultipartParser.end(): stream ended unexpectedly")}}function Y(i){let r=i.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!r)return;let E=r[2]||r[3]||"",o=E.slice(E.lastIndexOf("\\")+1);return o=o.replace(/%22/g,'"'),o=o.replace(/&#(\d{4});/g,(d,A)=>String.fromCharCode(A)),o}async function M(i,r){if(!/multipart/i.test(r))throw TypeError("Failed to fetch");let E=r.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!E)throw TypeError("no or bad content-type header, no multipart boundary");let o=new k(E[1]||E[2]),d,A,L,e,s,l,R=[],u=new Vr,g=(n)=>{L+=T.decode(n,{stream:!0})},a=(n)=>{R.push(n)},S=()=>{let n=new tu(R,l,{type:s});u.append(e,n)},H=()=>{u.append(e,L)},T=new TextDecoder("utf-8");T.decode(),o.onPartBegin=function(){o.onPartData=g,o.onPartEnd=H,d="",A="",L="",e="",s="",l=null,R.length=0},o.onHeaderField=function(n){d+=T.decode(n,{stream:!0})},o.onHeaderValue=function(n){A+=T.decode(n,{stream:!0})},o.onHeaderEnd=function(){if(A+=T.decode(),d=d.toLowerCase(),d==="content-disposition"){let n=A.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);if(n)e=n[2]||n[3]||"";if(l=Y(A),l)o.onPartData=a,o.onPartEnd=S}else if(d==="content-type")s=A;A="",d=""};for await(let n of i)o.write(n);return o.end(),u}var h=0,t,y=1,D,p=10,O=13,F=32,m=45,U=58,w=97,B=122,V=(i)=>i|32,_=()=>{};var x=bt(()=>{dd();iu();t={START_BOUNDARY:h++,HEADER_FIELD_START:h++,HEADER_FIELD:h++,HEADER_VALUE_START:h++,HEADER_VALUE:h++,HEADER_VALUE_ALMOST_DONE:h++,HEADERS_ALMOST_DONE:h++,PART_DATA_START:h++,PART_DATA:h++,END:h++},D={PART_BOUNDARY:y,LAST_BOUNDARY:y*=2}});x();export{M as toFormData};
@@ -0,0 +1 @@
1
+ import{Ne}from"./index-6k6ep10s.js";import"./index-f2mvvryf.js";import{uo,ct,Qo}from"./index-28c7m0fv.js";import{dl}from"./index-ae0ajw38.js";function l(e){let t=e?.trim().replace(/\/+$/,"");if(!t)return;return`${t.replace(/\/(?:v1|api)$/,"")}/api`}var m=300000;function u(e){let t=e.timeoutMs;if(typeof t==="number"&&Number.isFinite(t)&&t>0)return Math.floor(t);return m}function c(e,t){return async(a,o)=>{let r=new AbortController,n=setTimeout(()=>r.abort(Error(`Ollama request timed out after ${t/1000} seconds`)),t),i=o?.signal,s=i?AbortSignal.any([i,r.signal]):r.signal;try{return await e(a,{...o,signal:s})}finally{clearTimeout(n)}}}async function h(e,t){let a=await ct(e),o=l(e.baseUrl),r={...a?{Authorization:`Bearer ${a}`}:{},...e.headers},n=dl({...o?{baseURL:o}:{},...Object.keys(r).length>0?{headers:r}:{},compatibility:"strict",fetch:c(uo(e.fetch),u(e))});return{operations:{language:(i)=>Ne({model:n.chat(i),middleware:Qo})}}}export{h as createOllamaProviderModule};
@@ -0,0 +1 @@
1
+ import{ct}from"./index-28c7m0fv.js";import{oo}from"./index-6k6ep10s.js";function u(t){if(!t)return!1;try{let{hostname:r}=new URL(t);return r==="chatgpt.com"||r.endsWith(".chatgpt.com")}catch{return!1}}async function c(t,r){let d=await ct(t),o=oo({apiKey:d,baseURL:t.baseUrl,headers:t.headers,fetch:t.fetch,name:r.provider.id}),l=u(t.baseUrl);return{buildModelTools:(e)=>{let n={};for(let i of e)switch(i.name){case"web_search":n.web_search={tool:o.tools.webSearch()};break;case"image_generation":n.image_generation={tool:o.tools.imageGeneration({outputFormat:i.outputFormat??"png"}),projectResult:(a)=>{let s=a&&typeof a==="object"&&!Array.isArray(a)?a:void 0;if(typeof s?.result!=="string"||s.result.length===0)throw Error("OpenAI image generation tool returned no supported image output");return{media:[{modality:"image",mediaType:`image/${i.outputFormat??"png"}`,source:{type:"base64",data:s.result}}]}}};break}return n},operations:{language:(e)=>o.responses(e),imageGeneration:(e)=>o.image(e)},buildStreamConfig:(e)=>({...!l&&e.maxTokens!==void 0&&e.defaultedMaxTokens!==!0?{maxOutputTokens:e.maxTokens}:{},temperature:e.temperature})}}export{c as createOpenAIProviderModule};
@@ -0,0 +1 @@
1
+ import{Jg,Yg,DS}from"./index-28c7m0fv.js";import"./index-f2mvvryf.js";import"./index-6k6ep10s.js";export{DS as createOpenAICompatibleProviderModule,Yg as createSuccessDataResponseFetch,Jg as withMaxCompletionTokensForReasoningModels};
@@ -0,0 +1 @@
1
+ import{Xl}from"./index-0f8xrhgt.js";import{zr,Rn,Jl}from"./index-yrnwqsdt.js";import{Vl}from"./index-6akf3a5d.js";import{createRequire as s}from"module";var i=s(import.meta.url),p=class extends Vl{ClientClass;constructor(e){super();this.ClientClass=e}createClient(e,r,n){let t=this.mergeModelParams(r,n),o={embeddings:{model:{name:e.modelId,...Rn(t)?{params:t}:{},...r.modelVersion?{version:r.modelVersion}:{}}},...r.masking&&Rn(r.masking)?{masking:r.masking}:{}};return new this.ClientClass(o,e.deploymentConfig,e.destination)}async executeCall(e,r,n,t){return e.embed({input:r,type:n},t)}extractEmbeddings(e){return[...e.getEmbeddings()].sort((t,a)=>t.index-a.index).map((t)=>Jl(t.embedding))}extractResponseMetadata(e){return zr(e,"response")}extractTokenCount(e){return e.getTokenUsage().total_tokens}getUrl(){return"sap-ai:orchestration/embeddings"}resolveWarnings(e,r){Xl(e,r)}};export{p as OrchestrationEmbeddingModelStrategy};
@@ -0,0 +1 @@
1
+ import{Nh,Lh,co,Xl}from"./index-0f8xrhgt.js";import{Hl,Ql,Rn}from"./index-yrnwqsdt.js";import{Gs}from"./index-sw74pcm3.js";import{createRequire as g}from"module";var S=g(import.meta.url);function h(e){return C(e)?{id:e.id,...e.scope&&{scope:e.scope}}:{name:e.name,scenario:e.scenario,version:e.version,...e.scope&&{scope:e.scope}}}function C(e){return"id"in e}function u(e,t){let o=co(e.placeholderValues,t?.placeholderValues);return Rn(o)?o:void 0}var f=["masking","filtering","grounding","translation"],R=[...f,"fallbackModuleConfigs","promptTemplateRef","responseFormat","tools","modelParams","modelVersion"],v=["promptTemplateRef","modelParams"];function T(e,t){for(let o of f){let r=t[o];if(r&&Rn(r))e[o]=r}}function d(e){return Lh.safeParse(e).success}var O=[...Gs.COMMON_PARAM_MAPPINGS,{camelCaseKey:"topK",optionKey:"topK",outputKey:"top_k"}],I=class extends Gs{ClientClass;constructor(e){super();this.ClientClass=e}buildRequest(e,t,o,r){let s=[],{configRef:n}=r.resolvedState;if(n)return this.buildConfigRefRequest(t,o,r,s);return this.buildStandardRequest(t,r,s)}collectStreamWarnings(e,t){let o=[],r=t?.orchestrationConfigRef??e.orchestrationConfigRef;if(r&&d(r)){if(e.streamOptions&&Rn(e.streamOptions))o.push({message:"orchestrationConfigRef is set; local streamOptions are ignored. Configure streaming in the referenced configuration or its overrideConfig.",type:"other"});return o}if(e.translation&&Rn(e.translation)){if(!e.streamOptions?.delimiters||e.streamOptions.delimiters.length===0)o.push({message:"Translation module is configured but streamOptions.delimiters is not set. For proper sentence boundary detection during streaming with translation, consider setting delimiters (e.g., ['.', '!', '?', '\\n']).",type:"other"})}return o}createClient(e,t,o){let{configRef:r,promptTemplateRef:s,responseFormat:n,tools:i}=o.resolvedState;if(r)return new this.ClientClass(r,e.deploymentConfig,e.destination);let a=this.buildOrchestrationModuleConfig(e,t,{modelParams:o.modelParams,promptTemplateRef:s,responseFormat:n,toolChoice:o.toolChoice,tools:i});if(t.fallbackModuleConfigs&&t.fallbackModuleConfigs.length>0){let l=[a,...t.fallbackModuleConfigs];return new this.ClientClass(l,e.deploymentConfig,e.destination)}return new this.ClientClass(a,e.deploymentConfig,e.destination)}async executeApiCall(e,t,o){let r=await e.chatCompletion(t,o),{requestId:s,responseMetadata:n}=this.extractMetadata(r);return{getCitations:()=>r.getCitations(),getContent:()=>r.getContent(),getFinishReason:()=>r.getFinishReason(),getIntermediateFailures:()=>r.getIntermediateFailures(),getTokenUsage:()=>r.getTokenUsage(),getToolCalls:()=>r.getToolCalls(),rawResponse:{headers:r.rawResponse.headers},requestId:s,responseMetadata:n}}async executeStreamCall(e,t,o,r,s,n){let{configRef:i}=n.resolvedState,a=i?void 0:this.buildSdkStreamOptions(r.streamOptions),l=await e.stream(t,o,a,s),{requestId:p,responseHeaders:c,responseMetadata:m}=this.extractMetadata(l);return{cancel:()=>{l.stream.controller.abort()},getCitations:()=>l.getCitations(),getFinishReason:()=>l.getFinishReason(),getIntermediateFailures:()=>l.getIntermediateFailures(),requestId:p,responseHeaders:c,responseMetadata:m,stream:l.stream}}getCompletionDataPath(){return["final_result"]}getEscapeTemplatePlaceholders(e,t){return e?.escapeTemplatePlaceholders??t.escapeTemplatePlaceholders??!0}getParamMappings(){return O}getPartProviderOptionsParser(){return Nh}getUrl(){return"sap-ai:orchestration"}resolveAdditionalState(e,t,o,r,s){let n=this.resolveConfigRef(o,t,s),i=this.resolvePromptTemplateRef(o,t),a;if(n===void 0){Xl(t,s);let p=Hl(r.responseFormat,t.responseFormat);if(a=p.responseFormat,p.warning)s.push(p.warning)}let l=this.resolveTools(t,r,s);return{configRef:n,promptTemplateRef:i,responseFormat:a,tools:l}}buildConfigRefRequest(e,t,o,r){r.push(...this.collectConfigRefIgnoredWarnings(e,t,o.sapOptions));let s=u(e,o.sapOptions);return{request:{messagesHistory:o.messages,...s?{placeholderValues:s}:{}},warnings:r}}buildInlineTemplateConfig(e,t){return{template:[],...e&&e.length>0?{tools:e}:{},...t?{response_format:t}:{}}}buildOrchestrationModuleConfig(e,t,o){let{modelParams:r,promptTemplateRef:s,responseFormat:n,toolChoice:i,tools:a}=o,l=s?this.buildTemplateRefPromptConfig(s,a,n):this.buildInlineTemplateConfig(a,n),p=i?{...r,tool_choice:i}:r,c={promptTemplating:{model:{name:e.modelId,params:p,...t.modelVersion?{version:t.modelVersion}:{}},prompt:l}};return T(c,t),c}buildSdkStreamOptions(e){let t=e?.delimiters,o=Array.isArray(t)&&t.length>0,r=e?.chunkSize!==void 0||o;return{promptTemplating:{include_usage:!0},...r&&{global:{...e?.chunkSize!==void 0&&{chunk_size:e.chunkSize},...o&&{delimiters:Array.from(t)}}},...e?.outputFilteringOverlap!==void 0&&{outputFiltering:{overlap:e.outputFilteringOverlap}}}}buildStandardRequest(e,t,o){let{promptTemplateRef:r}=t.resolvedState,s=u(e,t.sapOptions);return{request:{...r?{messagesHistory:t.messages}:{messages:t.messages},...s?{placeholderValues:s}:{}},warnings:o}}buildTemplateRefPromptConfig(e,t,o){return{template_ref:h(e),...t&&t.length>0?{tools:t}:{},...o?{response_format:o}:{}}}collectConfigRefIgnoredWarnings(e,t,o){let r=[],s=[];for(let i of R){let a=e[i];if(a!==void 0){if(typeof a==="object"&&Object.keys(a).length===0)continue;s.push(i)}}for(let i of v)if(o?.[i]&&!e[i])s.push(`providerOptions.${i}`);let n=t;for(let{optionKey:i}of this.getParamMappings())if(i&&n[i]!==void 0)s.push(`options.${i}`);if(t.stopSequences&&t.stopSequences.length>0)s.push("options.stopSequences");if(t.tools&&t.tools.length>0)s.push("options.tools");if(t.responseFormat)s.push("options.responseFormat");if(t.toolChoice)s.push("options.toolChoice");if(s.length>0)r.push({message:`orchestrationConfigRef is set; the following local settings are ignored: ${s.join(", ")}. The full configuration is managed by the referenced config.`,type:"other"});return r}resolveConfigRef(e,t,o){let r=e?.orchestrationConfigRef??t.orchestrationConfigRef;if(!r)return;if(d(r))return r;o.push({message:"orchestrationConfigRef is invalid and was ignored; falling back to local module settings.",type:"other"});return}resolvePromptTemplateRef(e,t){let o=e?.promptTemplateRef??t.promptTemplateRef;if(o&&typeof o==="object"&&(("id"in o)||("name"in o)))return o;return}resolveTools(e,t,o){let r=e.tools,s=t.tools;if(r&&r.length>0&&s&&s.length>0)o.push({message:"Both settings.tools and call options.tools were provided; preferring call options.tools.",type:"other"});if(r&&r.length>0&&(!s||s.length===0))return r;if(s&&s.length>0){let n=Ql(s,{parser:Nh,warnings:o});return o.push(...n.warnings),n.tools}return}};export{I as OrchestrationLanguageModelStrategy};
@@ -0,0 +1,2 @@
1
+ import{dirname as ln,posix as cn,sep as un}from"path";function zr(){let e=fn();return async(t)=>{for(let r of t)r.module=e(r.filename);return t}}function fn(e=process.argv[1]?ln(process.argv[1]):process.cwd(),t=un==="\\"){let r=t?Vr(e):e;return(s)=>{if(!s)return;let i=t?Vr(s):s,{dir:n,base:o,ext:l}=cn.parse(i);if(l===".js"||l===".mjs"||l===".cjs")o=o.slice(0,-1*l.length);let a=decodeURIComponent(o);if(!n)n=".";let c=n.lastIndexOf("/node_modules");if(c>-1)return`${n.slice(c+14).replace(/\//g,".")}:${a}`;if(n.startsWith(r)){let u=n.slice(r.length+1).replace(/\//g,".");return u?`${u}:${a}`:a}return a}}function Vr(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var R=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 Y(e){let t=[];return JSON.stringify(e,function(r,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 dn=Array.isArray,Gr=Object.prototype,{hasOwnProperty:sc,toString:Xe}=Gr,O=dn||function(e){return Xe.call(e)==="[object Array]"};var Qe=(e)=>e===Object(e)&&!O(e);var q=(e)=>e===void 0,M=(e)=>Xe.call(e)=="[object String]",jt=(e)=>M(e)&&e.trim().length===0,Vt=(e)=>e===null,D=(e)=>q(e)||Vt(e),Je=(e)=>Xe.call(e)=="[object Number]"&&e===e;var Kr=(e)=>Xe.call(e)==="[object Boolean]";function zt(e){return e===null||typeof e!="object"}function qt(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function K(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 Wr(e,Error)}}function Se(e){return"u">typeof Event&&Wr(e,Event)}function Hr(e){return qt(e,"Object")}function Wr(e,t){try{return e instanceof t}catch{return!1}}var hn=["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"],Ye=new Map;function pn(e,t){let r="";for(let s=0;s<t.length;s++){let i=t[s];r+=i.length+":"+i}return e.length+":"+e+"|"+t.length+":"+r}var Xr=function(e,t=[]){if(!e)return!1;let r=pn(e,t),s=Ye.get(r);if(s!==void 0)return s;let i=e.toLowerCase(),n=hn.concat(t).some((o)=>i.indexOf(o.toLowerCase())!==-1);if(Ye.size>=256)Ye.clear();return Ye.set(r,n),n};function Ae(e,t,r,s,i){if(t>r)s.warn("min cannot be greater than max."),t=r;if(Je(e))if(e>r)return s.warn(" cannot be greater than max: "+r+". Using max value instead."),r;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: "+r+", fallback: "+i),Ae(i??r,t,r,s)}var gn=86400000,mn=1,_n=10;function Qr(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??mn,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??_n}}class Gt{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Ae(e.bucketSize,0,100,e._logger),this._refillRate=Ae(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Ae(e.refillInterval,0,gn,e._logger)}_applyRefill(e,t){let r=t-e.lastAccess,s=Math.floor(r/this._refillInterval);if(s>0){let i=s*this._refillRate;e.tokens=Math.min(e.tokens+i,this._bucketSize),e.lastAccess=e.lastAccess+s*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),r=String(e),s=this._buckets[r];if(s)this._applyRefill(s,t);else s={tokens:this._bucketSize,lastAccess:t},this._buckets[r]=s;if(s.tokens===0)return!0;if(s.tokens--,s.tokens===0)this._onBucketRateLimited?.(e);return s.tokens===0}stop(){this._buckets={}}}/*! LICENSE: uuidv7.mjs.LICENSE.txt */class Z{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new Z(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,r,s){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(s)||e<0||t<0||r<0||s<0||e>281474976710655||t>4095||r>1073741823||s>4294967295)throw RangeError("invalid field value");let i=new Uint8Array(16);return i[0]=e/1099511627776,i[1]=e/4294967296,i[2]=e/16777216,i[3]=e/65536,i[4]=e/256,i[5]=e,i[6]=112|t>>>8,i[7]=t,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=s>>>24,i[13]=s>>>16,i[14]=s>>>8,i[15]=s,new Z(i)}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 r=new Uint8Array(16);for(let s=0;s<16;s+=4){let i=parseInt(t.substring(2*s,2*s+8),16);r[s+0]=i>>>24,r[s+1]=i>>>16,r[s+2]=i>>>8,r[s+3]=i}return new Z(r)}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 Z(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let r=this.bytes[t]-e.bytes[t];if(r!==0)return Math.sign(r)}return 0}}class Yr{constructor(e){this.timestamp=0,this.counter=0,this.random=e??yn()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);if(r===void 0)this.timestamp=0,r=this.generateOrAbortCore(e,t);return r}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 Z.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,Z.ofInner(e)}}var yn=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),Jr,I=()=>bn().toString(),bn=()=>(Jr||(Jr=new Yr)).generate();class Kt{add(e){let t=I(),r=++this.nextId;return this.promiseByIds[t]={id:r,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map((r)=>r.promise),t=e.length;while(t>0)await Promise.all(e),e=Object.values(this.promiseByIds).map((r)=>r.promise),t=e.length}getPromises(e=[],t=this.nextId){let r=new Set(e);return Object.values(this.promiseByIds).filter((s)=>s.id<=t&&!r.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}}function En(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}var Zr=(e,t,r)=>{function s(n,...o){t(()=>{let l=r[n];l(e,...o)})}return{debug:(...n)=>{s("debug",...n)},info:(...n)=>{s("log",...n)},warn:(...n)=>{s("warn",...n)},error:(...n)=>{s("error",...n)},critical:(...n)=>{r.error(e,...n)},createLogger:(n)=>Zr(`${e} ${n}`,t,r)}},vn=(e)=>e();function es(e,t=vn){return Zr(e,t,En())}var ue="Mobile",et="iOS",ce="Android",ns="Tablet",yc=ce+" "+ns;var Sn="Apple",bc=Sn+" Watch",os="Safari",tt="BlackBerry",as="Samsung",An=as+"Browser",wn=as+" Internet",rt="Chrome",Pn=rt+" OS",xn=rt+" "+et,ls="Internet Explorer",In=ls+" "+ue,Xt="Opera",Ec=Xt+" Mini",cs="Edge",Tn="Microsoft "+cs,Qt="Firefox",Rn=Qt+" "+et,Jt="Nintendo",Yt="PlayStation",Ze="Xbox",Cn=ce+" "+ue,On=ue+" "+os,we="Windows",Ln=we+" Phone";var us="Generic",vc=us+" "+ue.toLowerCase(),Fc=us+" "+ns.toLowerCase(),Nn="Konqueror",Mn="Oculus Browser",ts="Vivaldi",Dn="Yandex",rs="Whale",$n="DuckDuckGo",kn="Pale Moon",ss="Waterfox",is="Brave",fs="Claude",ds="Codex",hs="ChatGPT",Un="Google Search App",P="(\\d+(\\.\\d+)?)",Ht=new RegExp("Version/"+P),Wt=new RegExp("("+fs+"|"+ds+"|"+hs+")\\/"+P);var Sc=new RegExp(Ze,"i"),Ac=new RegExp(Yt+" \\w+","i"),wc=new RegExp(Jt+" \\w+","i"),Bn=new RegExp(tt+"|PlayBook|BB10","i"),jn={"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"};var Pc={[In]:[new RegExp("rv:"+P)],[Tn]:[new RegExp(cs+"?\\/"+P)],[rt]:[new RegExp("("+rt+"|CrMo)\\/"+P)],[xn]:[new RegExp("CriOS\\/"+P)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+P)],[os]:[Ht],[On]:[Ht],[Xt]:[new RegExp("("+Xt+"|OPR)\\/"+P)],[Qt]:[new RegExp(Qt+"\\/"+P)],[Rn]:[new RegExp("FxiOS\\/"+P)],[Nn]:[new RegExp("Konqueror[:/]?"+P,"i")],[tt]:[new RegExp(tt+" "+P),Ht],[Cn]:[new RegExp("android\\s"+P,"i")],[wn]:[new RegExp(An+"\\/"+P)],[Mn]:[new RegExp("OculusBrowser\\/"+P)],[ts]:[new RegExp(ts+"\\/"+P)],[Dn]:[new RegExp("YaBrowser\\/"+P)],[rs]:[new RegExp(rs+"\\/"+P)],[is]:[new RegExp(is+"\\/"+P)],[fs]:[Wt],[ds]:[Wt],[hs]:[Wt],[$n]:[new RegExp("(DuckDuckGo|Ddg)\\/"+P)],[kn]:[new RegExp("PaleMoon\\/"+P)],[ss]:[new RegExp(ss+"\\/"+P)],[Un]:[new RegExp("GSA\\/"+P)],[ls]:[new RegExp("(rv:|MSIE )"+P)],Mozilla:[new RegExp("rv:"+P)]};var xc=[[new RegExp(Ze+"; "+Ze+" (.*?)[);]","i"),(e)=>[Ze,e&&e[1]||""]],[new RegExp(Jt,"i"),[Jt,""]],[new RegExp(Yt,"i"),[Yt,""]],[Bn,[tt,""]],[new RegExp(we,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[Ln,""];if(new RegExp(ue).test(t)&&!/IEMobile\b/.test(t))return[we+" "+ue,""];let r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let s=r[1],i=jn[s]||"";if(/arm/i.test(t))i="RT";return[we,i]}return[we,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(e)=>{if(e&&e[3]){let t=[e[3],e[4],e[5]||"0"];return[et,t.join(".")]}return[et,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(e)=>{let t="";if(e&&e.length>=3)t=q(e[2])?e[3]:e[2];return["watchOS",t]}],[new RegExp("("+ce+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+ce+")","i"),(e)=>{if(e&&e[2]){let t=[e[2],e[3],e[4]||"0"];return[ce,t.join(".")]}return[ce,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,(e)=>{let t=["Mac OS X",""];if(e&&e[1]){let r=[e[1],e[2],e[3]||"0"];t[1]=r.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Pn,""]],[/Linux|debian/i,["Linux",""]]];var st=20,fe=1000,it=1e4,nt="[Circular]",ot="[Truncated]",k="[Unserializable]",ps="[Function]",Rc=Date.prototype.getTime,Cc=Date.prototype.toISOString;function j(e){let t="";for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);if(s>=55296&&s<=56319){let i=e.charCodeAt(r+1);if(i>=56320&&i<=57343)t+=e[r]+e[r+1],r++;else t+="�"}else t+=s>=56320&&s<=57343?"�":e[r]}return t}function G(e,t){if(!t)return e;let r=[];try{r=Object.keys(t)}catch{r=[]}for(let s of r){let i;try{i=t[s]}catch{i="[Unserializable]"}Object.defineProperty(e,s,{value:i,enumerable:!0,writable:!0,configurable:!0})}return e}function Zt(e,t=Date.now()){if(typeof e!="string"||!e)return;let r=e.trim(),s=/^\d+\s*,/.test(r)?r.slice(0,r.indexOf(",")).trim():r;if(/^\d+$/.test(s)){let o=1000*Math.min(Number(s),300);return o>0?o:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(s))return;let i=/^\w{3} \w{3} /.test(s)?s+" GMT":s,n=Date.parse(i)-t;if(!Number.isFinite(n)||n<=0)return;return Math.min(n,300000)}class de{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(),r=Date.now(),s=Math.min(e.retryAfterMs,300000);if(!t){this._installedAt=r,this._until=r+s;return}this._until=Math.max(this._until,Math.min(r+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 gs="utf8",Vn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function zn(e){return typeof e=="string"&&Vn.test(e)}function ee(e,t){return zn(e)?e:t()}function he(e,t){let r=Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function ms(e){return e?.replace(/\/+$/,"")}async function _s(e,t){let r=null;for(let s=0;s<t.retryCount+1;s++){if(s>0)await new Promise((i)=>setTimeout(i,t.retryDelay));try{return await e()}catch(i){if(r=i,!t.retryCheck(i))throw i}}throw r}function er(){return new Date().toISOString()}function T(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}async function H(e,t,r){let s;try{return await Promise.race([e,new Promise((i,n)=>{s=T(()=>{try{r?.(),i()}catch(o){n(o)}},t)})])}finally{clearTimeout(s)}}var ys=(e)=>e&&typeof e.then=="function";function Pe(e){return Promise.all(e.map((t)=>(t??Promise.resolve()).then((r)=>({status:"fulfilled",value:r}),(r)=>({status:"rejected",reason:r}))))}var tr,bs,Es,pe;function Fs(e){let{_posthogChunkIds:t,_debugIds:r}=globalThis;if(!t&&!r)return;let s=t?Object.keys(t):[],i=r?Object.keys(r):[];if(pe&&vs(t,s,bs)&&vs(r,i,Es))return pe;bs=t?{...t}:void 0,Es=r?{...r}:void 0,pe={},tr??={};let n=(o,l)=>{for(let a of o){let c=l[a];if(!c)continue;let u=tr?.[a];if(u){pe[u]=c;continue}let f=e(a);for(let h=f.length-1;h>=0;h--){let p=f[h]?.filename;if(p){pe[p]=c,tr[a]=p;break}}}};if(r)n(i,r);if(t)n(s,t);return pe}function vs(e,t,r){if(!e||!r)return e===r;return t.length===Object.keys(r).length&&t.every((s)=>e[s]===r[s])}var rr=50,qn=1000,Gn=100,Kn=4;class at{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){let s=t&&t.mechanism||{handled:!0,type:"generic"},n=this.buildCoercingContext(s,t,0).apply(e),o=this.buildParsingContext(t),l=this.parseStacktrace(n,o);return{$exception_list:this.convertToExceptionList(l,s),$exception_level:"error"}}async modifyFrames(e){for(let t of e)if(t.stacktrace&&t.stacktrace.frames&&O(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 r;if(e.cause!=null)r=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:r,stack:s,errors:e.errors?.map((i)=>this.parseStacktrace(i,t))}}applyChunkIds(e,t){return e.map((r)=>{if(r.filename&&t)r.chunk_id=t[r.filename];return r})}applyCoercers(e,t){for(let r of this.coercers)if(r.match(e))return r.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let r of this.modifiers)t=await r(t);return t}convertToExceptionList(e,t){let r=[],s=(i,n,o)=>{let l=r.length,a=n===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:i.synthetic,exception_id:l}:{type:"chained",source:o,synthetic:i.synthetic,exception_id:l,parent_id:n},c={type:i.type,value:i.value,mechanism:a};if(i.stack)c.stacktrace={type:"raw",frames:i.stack};if(r.push(c),i.cause)s(i.cause,l,"cause");for(let u of i.errors??[])s(u,l,"member")};return s(e),r}buildParsingContext(e){return{chunkIdMap:Fs(this.stackParser),skipFirstLines:e.skipFirstLines??1}}getAggregateErrors(e){try{if(K(e)){let t=Object.getPrototypeOf(e);for(let r=0;t&&r<Gn;r++){let s=Object.getOwnPropertyDescriptor(t,"constructor")?.value;if(typeof s=="function"&&s.name==="AggregateError"){let i=e.errors;return O(i)?i:void 0}t=Object.getPrototypeOf(t)}}}catch{}}buildCoercingContext(e,t,r=0){let s=0,i=0,n=!1,o=new Set,l=[],a={},c=(h,p,d=0)=>{let g=u(p,d),m=g.apply;if(g.apply=(v)=>{l.push(h);try{return m(v)}finally{l.pop()}},d>Kn||d>0&&l.indexOf(h)!==-1)return this.coerceFallback(g);let b=typeof h=="object"&&h!==null||typeof h=="function";if(d===0&&s>=rr||b&&o.has(h))return;if(b)o.add(h);if(d===0)s++;let S=this.getAggregateErrors(h);n||=!!S;let E;try{if(E=this.applyCoercers(h,g),!E)throw a}catch(v){if(v===a){if(d===0)s--;return}if(!n)throw v;E=this.coerceFallback(g)}if(!S||s>=rr)return E;let A;try{A=S.length}catch{return E}if(!Number.isInteger(A)||A<0||A>4294967295)return E;let x=[];for(let v=0;s<rr&&i<qn&&v<A;v++){i++;let _;try{_=g.next(S[v])}catch{s++,_=this.coerceFallback(u(p+1))}if(_)x.push(_)}return{...E,errors:x}},u=(h,p=0)=>({...t,syntheticException:h==0?t.syntheticException:void 0,mechanism:h==0?e:{},apply:(d)=>{let g=c(d,h,p+1);if(!g)throw a;return g},next:(d)=>c(d,h+1)}),f=u(r);return{...f,apply:(h)=>c(h,r)??this.coerceFallback(f)}}}var C="?",Hn="<anonymous>",Wn=/^([a-z][a-z0-9.+-]+):/i,Xn=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function Qn(e){if(!e||e===Hn)return!1;let t=Wn.exec(e);return!t||Xn.includes(t[1].toLowerCase())}function te(e,t,r,s,i){let n={platform:e,filename:t,function:r==="<anonymous>"?C:r,in_app:Qn(t)};if(!q(s))n.lineno=s;if(!q(i))n.colno=i;return n}var lt=(e,t)=>{let r=e.indexOf("safari-extension")!==-1,s=e.indexOf("safari-web-extension")!==-1;return r||s?[e.indexOf("@")!==-1?e.split("@")[0]:C,r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]};var Jn=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Yn=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Zn=/\((\S*)(?::(\d+))(?::(\d+))\)/,Ss=(e,t)=>{let r=Jn.exec(e);if(r){let[,i,n,o]=r;return te(t,i,C,+n,+o)}let s=Yn.exec(e);if(s){if(s[2]&&s[2].indexOf("eval")===0){let l=Zn.exec(s[2]);if(l)s[2]=l[1],s[3]=l[2],s[4]=l[3]}let[n,o]=lt(s[1]||C,s[2]);return te(t,o,n,s[3]?+s[3]:void 0,s[4]?+s[4]:void 0)}};var eo=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,to=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,As=(e,t)=>{let r=eo.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let o=to.exec(r[3]);if(o)r[1]=r[1]||"eval",r[3]=o[1],r[4]=o[2],r[5]=""}let i=r[3],n=r[1]||C;return[n,i]=lt(n,i),te(t,i,n,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}};var ro=/^\s*[-]{4,}$/,so=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,io=/^Promise\.(?:all|any)$/,no=/^index \d+$/,oo="node:internal/promise",Ps=(e,t)=>{let r=e.match(so);if(r){let s,i,n,o,l;if(r[1]){n=r[1];let u=n.lastIndexOf(".");if(n[u-1]===".")u--;if(u>0){s=n.slice(0,u),i=n.slice(u+1);let f=s.indexOf(".Module");if(f>0)n=n.slice(f+1),s=s.slice(0,f)}o=void 0}if(i)o=s,l=i;if(i==="<anonymous>")l=void 0,n=void 0;if(n===void 0)l=l||C,n=o?`${o}.${l}`:l;let a=r[2]?.startsWith("file://")?r[2].slice(7):r[2],c=r[5]==="native";if(a?.match(/\/[A-Z]:/))a=a.slice(1);if(!a&&r[5]&&!c)a=r[5];if(io.test(n)&&no.test(a||""))a=oo;return{filename:a?decodeURI(a):void 0,module:void 0,function:n,lineno:ws(r[3]),colno:ws(r[4]),in_app:ao(a||"",c),platform:t}}if(e.match(ro))return{filename:e,platform:t}};function ao(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 ws(e){return parseInt(e||"",10)||void 0}var xs=/\(error: (.*)\)/,Is=50,lo=10,co=1000;function sr(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function uo(e){for(let t=1;t<=lo;t++){let r=e.length-2*t;if(r<0)break;let s=!0;for(let i=0;i<t;i++){let n=e[r+i];if(!sr(n,e[r+t+i])){s=!1;break}}if(s){for(let i=0;i<t;i++)e[r+i]=e[r+t+i];return e.length=r+t,{start:r,length:t}}}}function fo(e,t){let r=t.start+t.length,s=Rs(e,t);if(s)e.splice(r+s===e.length?r:t.start,s)}function Ts(e,t){let r=t.start;while(r>0&&sr(e[r-1],e[r-1+t.length]))r--;return t.start-r}function Rs(e,t){let r=t.start+t.length,s=r;while(s<e.length&&sr(e[s],e[s-t.length]))s++;return s-r}function ho(e,t){let r=t[0],s=e.length-(r?Ts(e,r):0);for(let i of t)s-=Rs(e,i);return s}function po(e){let t=e.map((s)=>`${s.function}|${s.filename}|${s.lineno}|${s.colno}|${s.module}`),r=0;for(let s=1;s<t.length;s++)if(go(t,s,r))r=s;e.push(...e.splice(0,r))}function go(e,t,r){for(let s=0;s<e.length;s++){let i=e[(t+s)%e.length],n=e[(r+s)%e.length];if(i!==n)return i<n}return!1}function mo(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,Is).map((r)=>({...r,filename:r.filename||_o(t).filename,function:r.function||C}))}function _o(e){return e[e.length-1]||{}}function Cs(){return Os("web:javascript",Ss,As)}function Os(e,...t){return(r,s=0)=>{let i=[],n=r.split(`
2
+ `),o=Math.min(n.length,s+co),l=[];for(let u=s;u<o;u++){let f=n[u];if(f.length>1024)continue;let h=xs.test(f)?f.replace(xs,"$1"):f;if(!h.match(/\S*Error: /)){for(let p of t){let d=p(h,e);if(d){i.push(d);let g=uo(i);if(g){for(let m=l.length-1;m>=0;m--){let b=l[m];if(b.start+b.length<=g.start)break;l.pop()}l.push(g)}break}}if(ho(i,l)>=Is)break}}let a=[...l].sort((u,f)=>f.start-u.start),c=a[a.length-1];if(c){let u=Ts(i,c);i.splice(c.start-u,u);for(let f of a)f.start-=u}for(let u of a)fo(i,u);if(l.some((u)=>u.start===0&&i.length===u.length))po(i);return mo(i)}}class ct{match(e){return K(e)}coerce(e,t){let r=this.getStack(e),s=r===void 0?t.syntheticException?.stack:void 0,i=!!s;return{type:this.getType(e),value:this.getMessage(e,t),stack:r??s,cause:e.cause?t.next(e.cause):void 0,synthetic:i}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let r=e.message;if(r.error&&typeof r.error.message=="string")return String(r.error.message);return String(r)}getStack(e){try{let t=e.stacktrace;if(typeof t=="string"&&t.length>0)return t;let r=e.stack;return typeof r=="string"&&r.length>0?r:void 0}catch{return}}}var yo=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class ut{match(e){return typeof e=="string"}coerce(e,t){let[r,s]=this.getInfos(e);return{type:r??"Error",value:s??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",r=e,s=e.match(yo);if(s)t=s[1],r=s[2];return[t,r]}}var Ls=["fatal","error","warning","log","info","debug"];function ft(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let s=r.length;s>0;s--){let i=r.slice(0,s).join(", ");if(!(i.length>t)){if(s===r.length)return i;return i.length<=t?i:`${i.slice(0,t)}...`}}return""}class dt{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let r=this.getErrorPropertyFromObject(e);if(r)return t.apply(r);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(Se(e))return e.constructor.name;let t="name"in e?e.name:void 0;return M(t)&&!jt(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),r=ft(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return M(e)&&!jt(e)&&Ls.indexOf(e)>=0}getStack(e){try{if(M(e.stacktrace)&&e.stacktrace.length>0)return e.stacktrace;return M(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 r=e[t];if(K(r))return r}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(t){return}}}class Ns{match(e){return Se(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${ft(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class ht{match(e){return zt(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}class ir{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 Ms={MESSAGE:"$message",TIMESTAMP:"$timestamp"},sf=new Set([Ms.MESSAGE,Ms.TIMESTAMP]);function Ds(){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 nr=(e)=>{if("flags"in e){let t=$s(e.flags),r=ks(e.flags);return{...e,featureFlags:t,featureFlagPayloads:r}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([i,n])=>[i,ge(n)])),s=Object.fromEntries(Object.entries(t).map(([i,n])=>[i,bo(i,n,r[i])]));return{...e,featureFlags:t,featureFlagPayloads:r,flags:s}}};function bo(e,t,r){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:r?JSON.stringify(r):void 0,description:void 0}}}var $s=(e)=>Object.fromEntries(Object.entries(e??{}).map(([t,r])=>[t,Ie(r)]).filter(([,t])=>t!==void 0)),ks=(e)=>{let t=e??{};return Object.fromEntries(Object.keys(t).filter((r)=>{let s=t[r];return s.enabled&&s.metadata&&s.metadata.payload!==void 0}).map((r)=>{let s=t[r].metadata?.payload;return[r,s?ge(s):void 0]}))},Ie=(e)=>e===void 0?void 0:e.variant??e.enabled,ge=(e)=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};var Us=["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"],Eo=["$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",...Us,"$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Te=(e,t=[])=>{let r={},s=(i)=>{if(e[i]!==void 0)r[i]=e[i]};return Eo.forEach(s),t.forEach(s),r};class or{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((r)=>r!==t)}}emit(e,t){for(let r of this.events[e]||[])r(t);for(let r of this.events["*"]||[])r(e,t)}}function ar(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var Fo="NativeGzipValidationError",So=31,Ao=139,wo=8,Po=(e)=>e.length>=2&&e[0]===So&&e[1]===Ao;var Re,xo=()=>{if(Re)return Re;Re=[];for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;Re[e]=t>>>0}return Re},Io=(e)=>{let t=xo(),r=4294967295;for(let s=0;s<e.length;s++)r=t[(r^e[s])&255]^r>>>8;return(4294967295^r)>>>0},pt=(e)=>{throw he(Fo,`Native gzip produced invalid output: ${e}`)},To=async(e,t)=>{if(e.size<18)pt("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());if(!Po(r)||r[2]!==wo)pt("invalid-header");let s=new DataView(await e.slice(e.size-8).arrayBuffer());if(s.getUint32(0,!0)!==Io(t))pt("invalid-crc");let i=t.length>>>0;if(s.getUint32(4,!0)!==i)pt("invalid-size")};async function Ce(e,t=!0,r){try{let s=new TextEncoder().encode(e),i=new globalThis.CompressionStream("gzip"),n=i.writable.getWriter(),o=n.write(s).then(()=>n.close()).catch(async(c)=>{try{await n.abort(c)}catch{}throw c}),l=new Response(i.readable).blob(),[a]=await Promise.all([l,o]);return await To(a,s),a}catch(s){if(r?.rethrow)throw s;if(t)console.error("Failed to gzip compress data",s);return null}}class U extends Error{constructor(e,t,r,s){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.responseBodyDeadline=r,this.abortController=s,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return Zt(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=he("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e=new Promise((r,s)=>{this.responseBodyTimer=T(()=>{this._bodyReadTimedOut=!0;let i=he("AbortError","Response body read timed out");s(i),this.cancelResponseBody(i)},this.responseBodyDeadline-Date.now())}),t;try{t=Promise.resolve(this.response.text())}catch(r){t=Promise.reject(r)}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{}})()}}class W extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}var Ro=(e,t)=>{for(let r of Object.keys(t))if(r.startsWith("$feature/")||r==="$active_feature_flags")e[r]=t[r]};async function Bs(e){if(e instanceof U){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 Co(e){return typeof e=="object"&&(e instanceof U||qs(e))}function qs(e){return e instanceof W}function Oo(e){if(e instanceof U)return e.status===502||e.status===504;if(!(e instanceof W))return!1;let t=e.error;return(t?.code??t?.cause?.code)!=="ECONNREFUSED"}var js=10485760;function Vs(e){try{if(typeof e!="string")return e instanceof Uint8Array?e.byteLength:e.size;if("u">typeof Buffer)return Buffer.byteLength(e,gs);return new TextEncoder().encode(e).length}catch{return 0}}function me(e){return typeof e=="object"&&e instanceof U&&e.status===413}function gt(e){if(e instanceof U)return e.status===408||e.status===429||e.status>=500;return qs(e)}function zs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var lr="default";class mt{getErrorPropertiesBuilder(){if(!this._errorPropertiesBuilder)this._errorPropertiesBuilder=this.createErrorPropertiesBuilder();return this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new at([new ct,new dt,new ut,new ht],Cs())}getEvaluationRuntime(){}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Kt,this._events=new or,this._isInitialized=!1;let r=typeof e=="string"?e.trim():"",s=typeof t.host=="string"?t.host.trim():"",i=!r;if(this._logger=es("[PostHog]",this.logMsgIfDebug.bind(this)),i)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=r,this.host=ms(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:gt},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)||i,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=!ar()||(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(R.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(R.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(R.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(r,s)=>this._logger.info(r,s));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},r=this.mergeCommonEventProperties(t);if(Ro(r,t),e.event==="$feature_flag_called"&&r.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled())r=Te(r);return{distinct_id:e.distinct_id,event:e.event,properties:r}}mergeCommonEventProperties(e){return{...e,...this.getCommonEventProperties()}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,r){this.wrap(()=>{let s={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",s,r)})}async identifyStatelessImmediate(e,t,r){let s={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",s,r)}captureStateless(e,t,r,s){this.wrap(()=>{let i=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",i,s)})}async captureStatelessImmediate(e,t,r,s){let i=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",i,s)}aliasStateless(e,t,r,s){this.wrap(()=>{let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",i,s)})}async aliasStatelessImmediate(e,t,r,s){let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",i,s)}groupIdentifyStateless(e,t,r,s,i,n){this.wrap(()=>{let o=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...n||{}}});this.enqueue("capture",o,s)})}async groupIdentifyStatelessImmediate(e,t,r,s,i,n){let o=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...n||{}}});await this.sendImmediate("capture",o,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`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,r,{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={},r={},s={},i={},n=!1){await this._initPromise;let o=n?"&config=true":"",l=`${this.host}/flags/?v=2${o}`,a={token:this.apiKey,distinct_id:e,groups:t,person_properties:r,group_properties:s,...i};if(r.$device_id)a.$device_id=r.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)a.evaluation_contexts=this.evaluationContexts;let c=this.getEvaluationRuntime();if(c)a.evaluation_runtime=c;let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(a)};return this._logger.info("Flags URL",l),this.fetchWithRetry(l,u,{type:"required",consume:(f)=>f.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:Oo},this.featureFlagsRequestTimeoutMs).then((f)=>({success:!0,response:nr(f)})).catch((f)=>(this._events.emit("error",f),{success:!1,error:this.categorizeRequestError(f)}))}categorizeRequestError(e){if(e instanceof U)return{type:"api_error",statusCode:e.status};if(e instanceof W){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,r={},s={},i={},n){await this._initPromise;let o=await this.getFeatureFlagDetailStateless(e,t,r,s,i,n);if(o===void 0)return{response:void 0,requestId:void 0};let l=Ie(o.response);if(l===void 0)l=!1;return{response:l,requestId:o.requestId}}async getFeatureFlagDetailStateless(e,t,r={},s={},i={},n){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(t,r,s,i,n,[e]);if(o===void 0)return;return{response:o.flags[e],requestId:o.requestId,evaluatedAt:o.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,r={},s={},i={},n){await this._initPromise;let o=await this.getFeatureFlagPayloadsStateless(t,r,s,i,n,[e]);if(!o)return;let l=o[e];if(l===void 0)return null;return l}async getFeatureFlagPayloadsStateless(e,t={},r={},s={},i,n){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,s,i,n)).payloads}async getFeatureFlagsStateless(e,t={},r={},s={},i,n){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,s,i,n)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},s={},i,n){await this._initPromise;let o=await this.getFeatureFlagDetailsStateless(e,t,r,s,i,n);if(!o)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:o.featureFlags,payloads:o.featureFlagPayloads,requestId:o.requestId}}async getFeatureFlagDetailsStateless(e,t={},r={},s={},i,n){await this._initPromise;let o={geoip_disable:i??this.disableGeoip};if(n)o.flag_keys_to_evaluate=n;let l=await this.getFlags(e,t,r,s,o);if(!l.success)return;let a=l.response;if(a.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(a.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:a?.requestId,quotaLimited:a.quotaLimited};return a}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:(i)=>{if(i.status!==200||!i.json){let n=`Surveys API could not be loaded: ${i.status}`,o=Error(n);return this._logger.error(o),this._events.emit("error",Error(n)),Promise.resolve(void 0)}return i.json()}}).catch((i)=>{this._logger.error("Surveys API could not be loaded",i),this._events.emit("error",i)}))?.surveys;if(s)this._logger.info("Surveys fetched from API: ",JSON.stringify(s));return s??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(R.Props);return this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(R.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(R.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return lr}persistedQueueKeyForRoute(e){return R.Queue}getActiveQueueRoutes(){return[lr]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,r,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 i=this.prepareMessage(t,r);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);let n=this.persistedQueueKeyForRoute(s??this.getQueueRouteKey(i)),o=this.getPersistedProperty(n)||[];if(o.length>=this.maxQueueSize)o.shift(),this._logger.warn("Queue is full, the oldest event is dropped.");if(o.push({message:i}),this.setPersistedProperty(n,o),this._events.emit(e,i),o.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=T(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(e,t,r,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 i=this.prepareMessage(t,r);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);try{await this.sendBatch([i],void 0,s??this.getQueueRouteKey(i))}catch(n){this._events.emit("error",n)}}normalizeMessage(e){let{type:t,library:r,library_version:s,...i}=e,n=zs(i.properties)?i.properties:void 0;if(r!==void 0&&n?.$lib===void 0)n={...n||{},$lib:r};if(s!==void 0&&n?.$lib_version===void 0)n={...n||{},$lib_version:s};if(n)i.properties=n;return i.uuid=ee(i.uuid,I),i}normalizeTimestampForWire(e){let t=e instanceof Date?e:typeof e=="string"?new Date(e):null;if(!t||Number.isNaN(t.getTime()))return e;let r=t.toISOString(),s=typeof e=="string"?e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return s&&s.length>3?r.replace(/\.\d{3}Z$/,`.${s}Z`):r}prepareMessage(e,t){let r={...e,timestamp:t?.timestamp?t?.timestamp:er(),uuid:ee(t?.uuid,I)};if(t?.disableGeoip??this.disableGeoip){if(!zs(r.properties))r.properties={};r.properties.$geoip_disable=!0}if(r.distinctId)r.distinct_id=r.distinctId,delete r.distinctId;return r}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){if(this.pendingFlushPromise)return;this.flushAutomatic().catch(async(e)=>{await Bs(e)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(e,t=[]){let r=t.filter((i)=>!!i),s=0;while(!0){let i=this.promiseQueue.getPromises([...r,...this.flushPromises],e);if(i.length===0)return;if(s>0)this._logger.debug(`flush() re-checking ${i.length} pending promise(s) before flushing`);await Promise.all(i.map((n)=>n.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,r=this.promiseQueue.maxId,s=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(r,[t,s])}).then(()=>Pe([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),Pe([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 Ce(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,t,r=lr){let s={api_key:this.apiKey,batch:e.map((a)=>{if(!a)return a;let c=this.normalizeTimestampForWire(a.timestamp);return c===a.timestamp?a:{...a,timestamp:c}}),sent_at:er()};if(this.historicalMigration)s.historical_migration=!0;let i=Y(s),n=`${this.host}${this.getBatchEndpointPath(r)}`,o=this.disableCompression?null:await this.compressPayload(i),l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...o!==null&&{"Content-Encoding":"gzip"}},body:o||i};await this.fetchWithRetry(n,l,{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=[],r;for(let s of e)try{await this._flushRoute(s,t)}catch(i){if(r===void 0)r=i}if(r!==void 0)throw r;this._events.emit("flush",t)}async _flushRoute(e,t){let r=this.persistedQueueKeyForRoute(e),s=this.getPersistedProperty(r)||[];if(!s.length)return;let i=s.length,n=0;while(s.length>0&&n<i){let o=s.slice(0,this.maxBatchSize),l=o.map((u)=>u.message===void 0?u.message:this.normalizeMessage(u.message)),a=async()=>{let u=this.getPersistedProperty(r)||[],f=[...o],h=u.filter((p)=>{let d=p.message?.uuid,g=f.findIndex((m)=>m===p||typeof d=="string"&&d.length>0&&m.message?.uuid===d);if(g===-1)return!0;return f.splice(g,1),!1});this.setPersistedProperty(r,h),s=h,this._dequeuedMessagesCount+=o.length,await this.flushStorage()},c={retryCheck:(u)=>{if(me(u))return!1;return gt(u)}};try{await this.sendBatch(l,c,e)}catch(u){if(me(u)&&l.length>1){this.maxBatchSize=Math.max(1,Math.floor(l.length/2)),this._logger.warn(`Received 413 when sending batch of size ${l.length}, reducing batch size to ${this.maxBatchSize}`);continue}if(!(u instanceof W))await a();throw this._events.emit("error",u),u}await a(),t.push(...l),n+=l.length}}async _sendOtlpBatch({path:e,auth:t,payload:r}){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let s;try{s=JSON.stringify(r)}catch(c){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${e} batch; reporting it as too large`,c)),{kind:"too-large",measuredLocally:!0}}let i=Vs(s);if(i>js)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${i} bytes: the endpoint accepts at most ${js}`)),{kind:"too-large",measuredLocally:!0};let n=t==="bearer"?`${this.host}/i/v1/${e}`:`${this.host}/i/v1/${e}?token=${encodeURIComponent(this.apiKey)}`,o=this.disableCompression?null:await this.compressPayload(s),l=o||s,a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...t==="bearer"&&{Authorization:`Bearer ${this.apiKey}`},...o!==null&&{"Content-Encoding":"gzip"}},body:l};try{return await this.fetchWithRetry(n,a,{type:"successful-write"},{retryCheck:(c)=>{if(me(c))return!1;if(c instanceof U&&c.retryAfterMs!==void 0)return!1;return gt(c)}}),{kind:"ok"}}catch(c){if(me(c))return{kind:"too-large"};if(gt(c)){let u=c instanceof U?c.retryAfterMs:void 0;return{kind:"retry-later",error:c,...u!==void 0&&{retryAfterMs:u}}}return{kind:"fatal",error:c}}}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,r,s,i){let n=t.body?t.body:"",o=Vs(n),l={...this._retryOptions,...s},a=0;return await _s(async()=>{a++;let c=new AbortController,u=i??this.requestTimeout,f=Date.now()+u,h,p=new Promise((S,E)=>{h=T(()=>{let A=he("AbortError",`Request timed out after ${u}ms`);E(A),c.abort(A)},u)}),d,g=!1,m,b=()=>m??=(async()=>{try{await d?.body?.cancel()}catch{}})();try{let S;try{S=this.fetch(e,{signal:c.signal,...t})}catch(x){throw new W(x)}S.then((x)=>{if(c.signal.aborted&&!g)Promise.resolve(x.body?.cancel()).catch(()=>{})}).catch(()=>{});try{d=await Promise.race([S,p]),g=!0}catch(x){throw new W(x)}let E=t.mode==="no-cors",A=r.type==="successful-write"?300:400;if(!E&&(d.status<200||d.status>=A))throw new U(d,o,f,c);if(r.type==="successful-write"){try{await Promise.race([b(),p])}catch{}return}try{return await Promise.race([r.consume(d),p])}catch(x){if(c.signal.aborted)throw new W(x);throw x}}finally{if(clearTimeout(h),c.signal.aborted&&d)b()}},{...l,retryCheck:(c)=>{let u=l.retryCheck(c);if(u&&a<=l.retryCount&&c instanceof U)c.cancelResponseBody();return u}})}async _shutdown(e=30000){await this._initPromise;let t=!1;if(this.clearFlushTimer(),this.disabled)return;return H((async()=>{try{await this.promiseQueue.join();while(!0){if(!this.getActiveQueueRoutes().some((n)=>this.getRouteQueue(n).length>0))break;let i=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===i){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(s){if(!Co(s))throw s;await Bs(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 $o=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi;var zf=new RegExp($o.source,"i"),Gs=/[a-z][a-z0-9+.-]{0,63}:\/\//i,qf=new RegExp(`^${Gs.source}`,"i"),Gf=new RegExp(Gs.source,"gi");var ko=["exact","is_not","icontains","not_icontains","starts_with","not_starts_with","ends_with","not_ends_with","regex","not_regex"],Uo=1152921504606847000;class y extends Error{constructor(e,t="unsupported_definition"){super(e);this.name=this.constructor.name,this.reason=t,Object.setPrototypeOf(this,y.prototype)}}function _e(e){try{return e()}catch(t){if(t instanceof y)throw new y(t.message,"missing_context");throw t}}function ur(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(!ur(t in e?e[t]:null))return!1;return!0}function fr(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(!fr(t in e?e[t]:null))return!1;return!0}function Ne(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let s=e.charCodeAt(t+1);if(t+1>=e.length||s<56320||s>57343)throw new y("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new y("Cannot stringify an unpaired surrogate like the flags service")}}function _t(e,t=new Set){if(e===null||typeof e=="boolean")return;if(typeof e=="string")return void Ne(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new y(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new y("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)if(r in e)_t(e[r],t)}finally{t.delete(e)}return}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new y("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new y("Cannot represent a circular object during local evaluation");t.add(e);try{for(let s of Object.keys(e))Ne(s),_t(e[s],t)}finally{t.delete(e)}return}throw new y(`Cannot represent ${typeof e} like the flags service`)}function Bo(e,t){let r=0,s=0;while(r<e.length&&s<t.length){let i=e.charCodeAt(r),n=t.charCodeAt(s),o=i>=55296&&i<=56319,l=n>=55296&&n<=56319,a=o?e.charCodeAt(r+1):0,c=l?t.charCodeAt(s+1):0,u=o?(i-55296)*1024+a-56320+65536:i,f=l?(n-55296)*1024+c-56320+65536:n;if(u!==f)return u-f;r+=o?2:1,s+=l?2:1}return e.length-t.length}function dr(e,t=new Set){if(e===null)return"null";if(typeof e=="string")return Ne(e),JSON.stringify(e);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))throw new y(`Cannot stringify non-finite number ${e} like the flags service`);if(Number.isInteger(e))throw new y(`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 y("Cannot stringify a circular array during local evaluation");t.add(e);try{let r=[];for(let s=0;s<e.length;s++)r.push(s in e?dr(e[s],t):"null");return`[${r.join(",")}]`}finally{t.delete(e)}}if(typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new y("Cannot stringify a non-JSON object like the flags service");if(t.has(e))throw new y("Cannot stringify a circular object during local evaluation");t.add(e);try{let s=Object.keys(e);return s.forEach(Ne),`{${s.sort(Bo).map((i)=>`${JSON.stringify(i)}:${dr(e[i],t)}`).join(",")}}`}finally{t.delete(e)}}throw new y(`Cannot stringify ${typeof e} like the flags service`)}function Le(e){if(typeof e=="string")return Ne(e),e;return dr(e)}var jo=/[\x20-\x2f:;=?@\x5b-\x60\x7b-\x7e]/;function Vo(e){let t=[],r=-1,s="";for(let i=0;i<e.length;i++){let n=e[i];if(n.charCodeAt(0)>127)return null;if(n==="\\"){let o=e[++i];if(o===void 0)break;if(o==="x"){if(!/^[\da-f]{2}$/i.test(e.slice(i+1,i+3)))return null;i+=2}else if(!"dDsSwWbBfnrtv".includes(o)&&!jo.test(o))return null;if(r===-1&&"bB".includes(o))return null;s="literal";continue}if(n==="["){if(r!==-1)return null;r=i}else if(n==="]"&&r!==-1){let o=r+(e[r+1]==="^"?2:1);if(i===o)return null;t.push(e.slice(r,i+1)),r=-1,s="literal";continue}else if(r!==-1){if(["&&","--","~~"].includes(e.slice(i,i+2)))return null;continue}else if(n==="("&&e[i+1]==="?"){if(e[i+2]!==":")return null;i+=2}else if(n==="{"){let o=/^\{(\d+)(?:,(\d*))?\}/.exec(e.slice(i));if(!o||["","|","("].includes(s)||o.slice(1).some((l)=>Number(l)>4294967295))return null}else if("*+?}".includes(n)&&(e[i+1]==="+"||e[i+1]==="{"))return null;if("*+?{".includes(n)&&["^","$","empty group"].includes(s))return null;s=n===")"&&["(","empty group"].includes(s)?"empty group":n}return t}function Oe(e){let t=new y(e);return Object.defineProperty(t,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),t}function zo(e,t){if(e==="")return!0;let r=Vo(e);if(r===null)throw Oe("Regex syntax requires server evaluation");let s;try{s=new RegExp(e)}catch(i){if(i instanceof SyntaxError)return null;throw Oe("Regex compilation requires server evaluation")}for(let i of r)try{new RegExp(i,"u")}catch{throw Oe("Regex character class syntax requires server evaluation")}for(let i=0;i<t.length;i++){let n=t[i];if(n.charCodeAt(0)>127||n==="\r")throw Oe("Regex matching for Unicode or carriage returns requires server evaluation")}try{return s.test(t)}catch{throw Oe("Regex execution requires server evaluation")}}function L(e){return String(e).replace(/[A-Z]/g,(t)=>t.toLowerCase())}function Ks(e,t,r){if(!/^\d+$/.test(e)||r==="strict"&&e.length>1&&e[0]==="0")throw new y(`Invalid semver: ${t}`);return parseInt(e,10)}function re(e,t="strict"){let s=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!s||s.startsWith("."))throw new y(`Invalid semver: ${e}`);let i=s.split("."),n=(o)=>{if(o===void 0||o==="")return 0;return Ks(o,e,t)};return[n(i[0]),n(i[1]),n(i[2])]}function cr(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function Hs(e,t){let r=re(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function Ws(e,t){let[r,s,i]=re(e,t),n=[r,s,i],o;return o=r>0?[r+1,0,0]:s>0?[0,s+1,0]:[0,0,i+1],{lower:n,upper:o}}function Xs(e,t){let s=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!s)throw new y(`Invalid wildcard semver: ${e}`);let i=s.split("."),n=(a)=>{if(t==="legacy-permissive"){let c=parseInt(a,10);if(!isNaN(c))return c}else try{return Ks(a,e,t)}catch{}throw new y(`Invalid wildcard semver: ${e}`)},o=n(i[0]);if(i.length===1)return{lower:[o,0,0],upper:[o+1,0,0]};let l=n(i[1]);return{lower:[o,l,0],upper:[o,l+1,0]}}function Qs(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 y(`${e} is in an invalid date format`)}throw new y(`The date provided ${e} must be a string, number, or date object`)}function hr(e){let t=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,r=e.match(t),s=new Date(new Date().toISOString());if(!r||!r.groups)return null;let i=parseInt(r.groups.number);if(i>=1e4)return null;let n=r.groups.interval;if(n==="h")s.setUTCHours(s.getUTCHours()-i);else if(n==="d")s.setUTCDate(s.getUTCDate()-i);else if(n==="w")s.setUTCDate(s.getUTCDate()-7*i);else if(n==="m")s.setUTCMonth(s.getUTCMonth()-i);else{if(n!=="y")return null;s.setUTCFullYear(s.getUTCFullYear()-i)}return s}function Js(e){if(typeof e=="boolean")throw new y("Date operations cannot be performed on boolean values");return hr(String(e))??Qs(e)}function Me(e,t={}){let r=e.value,s=t.semverParsingPolicy??"strict";switch(e.operator||"exact"){case"exact":case"is_not":for(let i of Array.isArray(r)?r:[r])Le(i);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":Js(r);return;case"semver_eq":case"semver_neq":case"semver_gt":case"semver_gte":case"semver_lt":case"semver_lte":re(String(r),s);return;case"semver_tilde":Hs(String(r),s);return;case"semver_caret":Ws(String(r),s);return;case"semver_wildcard":Xs(String(r),s);return;default:throw new y(`Unknown operator: ${e.operator}`)}}function pr(e,t,r={}){try{return qo(e,t,r)}catch(s){if(s instanceof y&&s.reason==="missing_context")Me(e,r);throw s}}function qo(e,t,r){let{key:s,value:i}=e,n=e.operator||"exact",o=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,s)){if(n==="is_not_set")return!1;else if(n==="is_set")return!0}else throw new y(`Property ${s} not found in propertyValues`,"missing_context");let a=t[s];if(a===void 0)throw r.warnFunction?.(`Property ${s} cannot have a value of undefined with the ${n} operator`),new y(`Property ${s} is undefined in propertyValues`);if(a===null&&!ko.includes(n))return r.warnFunction?.(`Property ${s} cannot have a value of null with the ${n} operator`),!1;let c=(d,g)=>{if(r.propertyMatchingVersion!==2&&ur(d)||Array.isArray(d)&&d.length===0)return _e(()=>_t(g)),fr(d)===fr(g);if(r.propertyMatchingVersion===2&&typeof g=="number"&&ur(d))return _e(()=>_t(g)),!1;if(Array.isArray(d)){let b=_e(()=>Le(g)).toLowerCase();return d.some((S)=>Le(S).toLowerCase()===b)}return Le(d).toLowerCase()===_e(()=>Le(g)).toLowerCase()},u=(d,g,m)=>{if(m==="gt")return d>g;if(m==="gte")return d>=g;if(m==="lt")return d<g;if(m==="lte")return d<=g;throw Error(`Invalid operator: ${m}`)},f=()=>_e(()=>re(String(a),o)),h=()=>{let d=re(String(i),o);return cr(f(),d)},p=({lower:d,upper:g})=>{let m=f();return cr(m,d)>=0&&cr(m,g)<0};switch(n){case"exact":return c(i,a);case"is_not":return!c(i,a);case"is_set":return!0;case"icontains":return L(a).includes(L(i));case"not_icontains":return!L(a).includes(L(i));case"starts_with":return L(a).startsWith(L(i));case"not_starts_with":return!L(a).startsWith(L(i));case"ends_with":return L(a).endsWith(L(i));case"not_ends_with":return!L(a).endsWith(L(i));case"regex":case"not_regex":{let d=zo(String(i),String(a));if(d===null)return!1;return n==="regex"?d:!d}case"gt":case"gte":case"lt":case"lte":{let d=typeof i=="number"?i:parseFloat(String(i)),g=typeof a=="number"?a:a!=null?parseFloat(String(a)):NaN;if(Number.isFinite(d)&&Number.isFinite(g))return u(g,d,n);return u(String(a),String(i),n)}case"is_date_after":case"is_date_before":{let d=Js(i),g=_e(()=>Qs(a));return n==="is_date_before"?g<d:g>d}case"semver_eq":return h()===0;case"semver_neq":return h()!==0;case"semver_gt":return h()>0;case"semver_gte":return h()>=0;case"semver_lt":return h()<0;case"semver_lte":return h()<=0;case"semver_tilde":return p(Hs(String(i),o));case"semver_caret":return p(Ws(String(i),o));case"semver_wildcard":return p(Xs(String(i),o));default:throw new y(`Unknown operator: ${n}`)}}async function Ys(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");let r=await t.digest("SHA-1",new TextEncoder().encode(e));return Array.from(new Uint8Array(r)).map((s)=>s.toString(16).padStart(2,"0")).join("")}async function ye(e,t,r="",s="."){let i=await Ys(`${e}${s}${t}${r}`);return parseInt(i.slice(0,15),16)/Uo}async function gr(e,t){if(e==null||e.id==null||e.exclusion_percentage==null)return;let r=Number(e.exclusion_percentage);if(!Number.isFinite(r))return;let s=Math.min(Math.max(r,0),100);if(s!==100){if(await ye("holdout",t,"","-")>s/100)return}return`holdout-${e.id}`}function yt(e){let t=[],r=0;for(let s of e){let i=r+s.rollout_percentage/100;t.push({valueMin:r,valueMax:i,key:s.key}),r=i}return t}async function mr(e,t,r){let s=await ye(e,t,"variant");return yt(r).find((i)=>s>=i.valueMin&&s<i.valueMax)?.key}function _r(e,t){if(t===!1||t==null||!e)return null;let r=typeof t=="boolean"?t.toString():t,s=e[r]||null;return s==null?null:ge(s)}var Zs=9223372036854776000,Go="9223372036854775808",Ko=Object.prototype.propertyIsEnumerable;function Ho(){return{ancestors:new WeakSet,remainingNodes:it}}function V(e,t){try{return ei(e,t,Ho(),0)}catch{return[]}}function Wo(e,t){let r=e.toString(),s=BigInt(Go);if(e>=s||e<-s)return t?.debug(`Attribute ${r} is outside the int64 range; encoding it as a string`),{stringValue:r};return{intValue:r}}function yr(e,t,r,s){if(r.remainingNodes<=0)return{stringValue:ot};if(r.remainingNodes--,Kr(e))return{boolValue:e};if(typeof e=="bigint")return Wo(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 i=BigInt(e).toString();if(e>=Zs||e<-Zs)return t?.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i};return{intValue:i}}return{doubleValue:e}}if(typeof e=="string")return{stringValue:j(e)};if(typeof e=="function")return{stringValue:ps};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(r.ancestors.has(e))return{stringValue:nt};if(s>=st)return{stringValue:ot};if(e instanceof Date){let i=e.getTime(),n=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof n=="string"?j(n):String(n)}}r.ancestors.add(e);try{try{let i=e.toJSON;if(typeof i=="function")return yr(i.call(e),t,r,s+1)}catch{}if(O(e))return{arrayValue:{values:Xo(e,t,r,s+1)}};return{kvlistValue:{values:ei(e,t,r,s+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:j(String(e))}}function Xo(e,t,r,s){let i=[],n=Math.min(e.length,fe),o=0;for(;o<n&&r.remainingNodes>0;o++)try{let l=o in e?e[o]:void 0;if(D(l))continue;i.push(yr(l,t,r,s))}catch{i.push({stringValue:k})}if(e.length>o)i.push({stringValue:ot});return i}function ei(e,t,r,s){let i=[];for(let n in e)if(Ko.call(e,n)){if(!n){t?.debug("Dropping an attribute with an empty key");continue}if(i.length>=fe||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let o=e[n];if(Vt(o)||q(o))continue;i.push({key:j(n),value:yr(o,t,r,s)})}catch{i.push({key:j(n),value:{stringValue:k}})}}return i}function De(e,t,r){return{...G({},e.resourceAttributes),"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":r}}var Qo=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function $e(e,t){let r=G({},e),s={};for(let i of Qo)if(Object.prototype.hasOwnProperty.call(r,i))s[i]=r[i],delete r[i];return[...V(r,t),...V(s,t)]}var ti={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"};function Jo(e){if(!e)return;return Object.prototype.hasOwnProperty.call(ti,e)?ti[e]:e}function br(e,t){let r=Jo(e);return{...r?{"os.name":r}:{},...t?{"os.version":t}:{}}}var Yo={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}},ad=Yo.info;class be{constructor(e){this._onFire=e,this._firesAt=0}get pending(){return!!this._timer}arm(e){this.clear(),this._firesAt=Date.now()+e,this._timer=T(()=>{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 ke=30000;function Ue(){return 0.75+Math.random()*0.25*2}var N=1;function Be(e,t,r,s){let i=Math.min(Math.max(0,t-1),6),n=e*2**i,o=s===void 0?n:Math.min(n,Math.max(s,e));return Math.round(o*r)}var ra="00000000000000000000000000000000",sa=/^[0-9a-f]+$/;function ia(e){let t=new Uint8Array(e),r=globalThis.crypto;if(r&&typeof r.getRandomValues=="function")try{return r.getRandomValues(t),t}catch{}for(let s=0;s<e;s++)t[s]=Math.floor(256*Math.random());return t}function na(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}function ri(e){let t=na(ia(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function si(){return ri(16)}function ii(){return ri(8)}function ni(e,t,r){return typeof e=="string"&&e.length===t&&e!==r&&sa.test(e)}function oi(e){return ni(e,32,ra)}function ai(e){return ni(e,16,"0000000000000000")}var oa=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function bt(e){let t=li(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:aa(t.flags)}}function aa(e){return 1&parseInt(e,16)?Ee:la}function li(e){if(typeof e!="string")return;let t=oa.exec(e.trim());if(!t)return;let[,r,s,i,n,o]=t;if(r==="ff")return;if(r==="00"&&o)return;if(!oi(s)||!ai(i))return;return{version:r,traceId:s,spanId:i,flags:n}}function ci(e){return li(e)&&e.trim()}function Et(e){return Array.isArray(e)&&e.length===1?e[0]:e}var Ee="01",la="00";function ui(e,t,r=Ee){return`00-${e}-${t}-${r}`}var ca=32,Er=512;function vt(e){if(typeof e!="string")return;let t=e.trim();if(!t)return;if(/[^\x20-\x7e\t]/.test(t))return;let r=t.split(",");if(r.length>ca)return;for(let s of r)if(s.trim()&&!s.includes("="))return;if(t.length<=Er)return t;return fa(r)}var ua=128;function fa(e){let t=[...e],r=()=>t.reduce((s,i)=>s+i.length,0)+t.length-1;for(let s=t.length-1;s>=0&&r()>Er;s--)if(t[s].length>ua)t.splice(s,1);while(t.length&&r()>Er)t.pop();return t.length?t.join(","):void 0}var je=[0,5,10,25,50,75,100,250,500,750,1000,2500,5000,7500,1e4];function Ft(e){return String(e)+"000000"}function vr(e,t,r,s){let i="";if(s)i=Object.keys(s).sort().map((o)=>`${JSON.stringify(o)}:${JSON.stringify(s[o])}`).join(",");return`${e}\x00${t}\x00${r??""}\x00${i}`}function fi(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}function Fr(e,t,r){return De(e,t,r)}function Sr(e,t,r,s){return{resourceMetrics:[{resource:{attributes:$e(t)},scopeMetrics:[{scope:{name:r,version:s},metrics:e}]}]}}function St(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 di=1;class At{constructor(e,t,r){this._instance=e,this._config=t,this._logger=r,this._series=new Map,this._flushTimer=new be(()=>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 de,this._consecutiveFlushFailures=0,this._flushJitter=N,this._generation=0}count(e,t=1,r){this._capture({name:e,type:"count",value:t,unit:r?.unit,attributes:r?.attributes})}gauge(e,t,r){this._capture({name:e,type:"gauge",value:t,unit:r?.unit,attributes:r?.attributes})}histogram(e,t,r){this._capture({name:e,type:"histogram",value:t,unit:r?.unit,attributes:r?.attributes})}flush(){let e=this._flushPromise,r=(async()=>{if(e)await e.catch(()=>{});await this._doFlush()})().finally(()=>{if(this._flushPromise===r)this._flushPromise=null});return this._flushPromise=r,r}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=N,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 r,s;try{r=t.attributes?{...t.attributes}:void 0,s=vr(t.type,t.name,t.unit,r)}catch(l){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,l);return}let i=this._series.get(s);if(!i){if(!this._admitNewSeries())return;i={name:t.name,type:t.type,unit:t.unit,attributes:r,windowStartMs:Date.now()},this._series.set(s,i)}let n=this._typeByName.get(t.name);if(n===void 0)this._typeByName.set(t.name,t.type);else if(n!==t.type&&!this._typeCollisionWarned.has(t.name))this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${n}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`);this._fold(i,t.value);let o=this._activeTraceContext();if(o)i.exemplar={...o,value:t.value,timeMs:Date.now()};this._armFlushTimer()}_activeTraceContext(){try{let e=bt(this._instance.getActiveSpan?.()?.traceparent());if(e&&e.flags===Ee)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(je.length+1).fill(0)};let r=e.hist;r.count+=1,r.sum+=t,r.min=Math.min(r.min,t),r.max=Math.max(r.max,t),r.bucketCounts[fi(t,je)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=O(t)?t:[t],s=e;for(let i of r)try{let n=i(s);if(!n)return this._logger.info("Metric was rejected in beforeSend function"),null;s=n}catch(n){return this._logger.error("Error in beforeSend function for metric:",n),null}return s}_armFlushTimer(){if(this._flushTimer.pending)return;this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(Be(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,ke),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,r=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t!==this._generation)return;if(this._retryAfter.record(r),r.kind==="retry-later")this._consecutiveFlushFailures++,this._flushJitter=Ue();else this._consecutiveFlushFailures=0,this._flushJitter=N;if(this._flushTimer.pending)this._flushTimer.arm(this._nextFlushDelay());switch(r.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:",r.error);return}}_buildPayload(e){return Sr(this._buildMetrics(e),Fr(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=Ft(Date.now()),r=new Map;for(let s of e.values()){let i=vr(s.type,s.name,s.unit,void 0),n=r.get(i);if(!n){if(n={name:s.name,...s.unit&&{unit:s.unit}},s.type==="count")n.sum={aggregationTemporality:di,isMonotonic:!0,dataPoints:[]};else if(s.type==="gauge")n.gauge={dataPoints:[]};else n.histogram={aggregationTemporality:di,dataPoints:[]};r.set(i,n)}let o=V(s.attributes??{},this._logger),l=Ft(s.windowStartMs),a=da(s.exemplar);if(s.type==="count"){let c={attributes:o,startTimeUnixNano:l,timeUnixNano:t,asDouble:s.total??0,...a};n.sum.dataPoints.push(c)}else if(s.type==="gauge"){let c={attributes:o,timeUnixNano:t,asDouble:s.last??0,...a};n.gauge.dataPoints.push(c)}else if(s.hist){let c={attributes:o,startTimeUnixNano:l,timeUnixNano:t,count:s.hist.count,sum:s.hist.sum,min:s.hist.min,max:s.hist.max,bucketCounts:s.hist.bucketCounts,explicitBounds:je,...a};n.histogram.dataPoints.push(c)}}return Array.from(r.values())}_mergeWindowBack(e){for(let[t,r]of e){let s=this._series.get(t);if(!s){if(this._admitNewSeries())this._series.set(t,r);continue}switch(s.windowStartMs=Math.min(s.windowStartMs,r.windowStartMs),s.exemplar=s.exemplar??r.exemplar,s.type){case"count":s.total=(s.total??0)+(r.total??0);break;case"gauge":break;case"histogram":if(r.hist)if(s.hist){s.hist.count+=r.hist.count,s.hist.sum+=r.hist.sum,s.hist.min=Math.min(s.hist.min,r.hist.min),s.hist.max=Math.max(s.hist.max,r.hist.max);for(let i=0;i<s.hist.bucketCounts.length;i++)s.hist.bucketCounts[i]+=r.hist.bucketCounts[i]}else s.hist=r.hist;break}}}}function da(e){if(!e)return{};return{exemplars:[{filteredAttributes:[],timeUnixNano:Ft(e.timeMs),asDouble:e.value,traceId:e.traceId,spanId:e.spanId}]}}function se(e,t,r,s){if(typeof e=="string"&&e.trim())return e.length>r?e.slice(0,r):e;return s?.debug(`${t} must be a non-empty string; using "unknown"`),"unknown"}function ve(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 hi(e,t,r){let s=ve(e);if(s===void 0){if(e!==void 0)r?.debug("Span startTime is out of range or not a valid time; using the current time");return t}if(t-s>86400000)r?.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)r?.debug("Span startTime is in the future; the span may export with a zero duration");return s}function wt(e,t){return e<t?t:e}function Ve(e,t,r,s){let i=ve(e);if(i===void 0){if(e!==void 0)s?.debug(`Span ${r} is out of range or not a valid time; using the derived time`);return t}return i}function xt(){let e=globalThis.performance;return typeof e?.now=="function"?e.now():void 0}class ze{constructor(e,t,r){this._onEnd=t,this._logger=r,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??Ee,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:xt(),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=xt();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(D(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]=Tt(t,this._maxAttributeValueLength)}setAttribute(e,t){if(this._mutable("setAttribute"))this._writeAttribute(e,t);return this}setAttributes(e){if(this._mutable("setAttributes")){let t=G({},e);for(let r of Object.keys(t))this._writeAttribute(r,t[r])}return this}addEvent(e,t,r){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let s=t&&_i(t,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:se(e,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:Ve(r,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:wr(t,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(e){if(!this._mutable("recordException"))return this;let{type:t,message:r,stack:s}=Pr(e);return this.addEvent(ha,{"exception.type":t,"exception.message":r,...s&&{"exception.stacktrace":s}}),this.setStatus("error",r)}updateName(e){if(this._mutable("updateName"))this._name=se(e,"Span name",this._maxAttributeValueLength,this._logger);return this}traceparent(){return ui(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(),r=Ve(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:wt(r,this._startTime),...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}}var ha="exception",pa=4294967295;function ga(e){try{return typeof e=="string"?e:String(e)}catch{return k}}function ie(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return 0;return Math.min(Math.floor(e),pa)}function ma(e,t){if(!t.length)return Object.keys(e);let r=t.filter((i)=>Object.prototype.propertyIsEnumerable.call(e,i)),s=new Set(r);return[...r,...Object.keys(e).filter((i)=>!s.has(i))]}function gi(e,t,r,s,i,n,o=[]){let l=0,a=0,c={};for(let p of ma(e.attributes,o)){let d=e.attributes[p];if(!D(d)){if(!t.has(p)){if(l>=r){a++;continue}l++}Object.defineProperty(c,p,{value:Tt(d,n),enumerable:!0,writable:!0,configurable:!0})}}if(e.attributes=c,a)e.droppedAttributesCount=ie(e.droppedAttributesCount)+a;let u=0,f=0,h=[];for(let p of e.events){if(u>=s){f++;continue}if(u++,p.attributes){let d=_i(p.attributes,i,n);if(p.attributes=d.attributes,d.dropped)p.droppedAttributesCount=ie(p.droppedAttributesCount)+d.dropped}h.push(p)}if(e.events=h,f)e.droppedEventsCount=ie(e.droppedEventsCount)+f;if(e.status?.message)e.status={...e.status,message:wr(ga(e.status.message),n)}}class Ar{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(){}}var mi=new Ar;class It extends Ar{constructor(e,t){super(),this._traceparent=e,this._tracestate=t}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}}function _a(e){try{let t=e.stack;return typeof t=="string"&&t?{stack:t}:{}}catch{return{}}}function X(e,t){let r=Et(e?.parent)??t,s=typeof r=="string"||r==null?r:pi(r,"traceparent"),i=ci(s);if(!i)return mi;let n=typeof r=="string"||r==null?e?.tracestate:pi(r,"tracestate");return new It(i,vt(n))}function pi(e,t){try{let r=e[t];return typeof r=="function"?r.call(e):void 0}catch{return}}function wr(e,t){return e.length>t?e.slice(0,t):e}function Tt(e,t){return Pt(e,t,{ancestors:new WeakSet,remainingNodes:it},0)}function Pt(e,t,r,s){if(e===null||typeof e!="object"){if(D(e))return e;if(r.remainingNodes<=0)return e;return r.remainingNodes--,typeof e=="string"?wr(e,t):e}if(r.ancestors.has(e))return nt;if(r.remainingNodes<=0||s>=st)return e;r.remainingNodes--,r.ancestors.add(e);try{if(e instanceof Date)return e;let i=ya(e);if(i.selfDescribed)return D(i.value)?String(i.value):Pt(i.value,t,r,s+1);if(O(e)){let l=Math.min(e.length,fe),a=[];for(let c=0;c<l;c++)try{a.push(Pt(e[c],t,r,s+1))}catch{a.push(k)}if(e.length>l)a.length=e.length;return a}let n={},o=0;for(let l of Object.keys(e)){if(o>=fe)break;let a;try{a=Pt(e[l],t,r,s+1)}catch{a=k}if(l&&!D(a))o++;Object.defineProperty(n,l,{value:a,enumerable:!0,writable:!0,configurable:!0})}return n}catch{return e}finally{r.ancestors.delete(e)}}function ya(e){try{let t=e.toJSON;if(typeof t=="function")return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}function _i(e,t,r){let s;try{s=Object.keys(e)}catch{return{attributes:{},dropped:0}}let i={},n=0,o=0;for(let l of s){if(n>=t){o++;continue}let a;try{a=Tt(e[l],r)}catch{a=k}if(!D(a))n++,Object.defineProperty(i,l,{value:a,enumerable:!0,writable:!0,configurable:!0})}return{attributes:i,dropped:o}}function yi(e,t){for(let r of Object.keys(e))e[r]=Tt(e[r],t);return e}function qe(e,t,r){return t===mi?r(t):e.with(t,()=>r(t))}function Pr(e){try{let t=_a(e);if(K(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 r=e;if(typeof r.message=="string")return{type:typeof r.name=="string"?r.name:"Object",message:r.message,...t}}return{type:typeof e,message:String(e)}}catch{return{type:typeof e,message:""}}}var xr={internal:1,server:2,client:3,producer:4,consumer:5},ba={ok:1,error:2},Ea=1,va=256,Fa=512;function Sa(e){let t=parseInt(e.traceFlags,16);return(Number.isFinite(t)?255&t:Ea)|va|(e.parentIsRemote?Fa:0)}function Rt(e){if(typeof e=="string")return j(e);try{return j(String(e))}catch{return k}}function Aa(e){if(e&&Object.prototype.hasOwnProperty.call(xr,e))return xr[e];return xr.internal}function Ir(e){let t=Math.floor(e),r=Math.round((e-t)*1e6);if(r>=1e6)t+=1,r=0;return String(t)+String(r).padStart(6,"0")}function wa(e,t){let r={name:Rt(e.name),timeUnixNano:Ir(e.timestamp)};if(e.attributes){let i=V(e.attributes,t);if(i.length)r.attributes=i}let s=ie(e.droppedAttributesCount);if(s)r.droppedAttributesCount=s;return r}function bi(e,t){let r={traceId:e.traceId,spanId:e.spanId,name:Rt(e.name),kind:Aa(e.kind),startTimeUnixNano:Ir(e.startTime),endTimeUnixNano:Ir(e.endTime),flags:Sa(e)};if(e.parentSpanId)r.parentSpanId=e.parentSpanId;if(e.traceState)r.traceState=Rt(e.traceState);let s=V(e.attributes,t);if(s.length)r.attributes=s;if(e.events.length)r.events=e.events.map((o)=>wa(o,t));let i=ie(e.droppedAttributesCount);if(i)r.droppedAttributesCount=i;let n=ie(e.droppedEventsCount);if(n)r.droppedEventsCount=n;if(e.status)r.status={code:ba[e.status.code],...e.status.message&&{message:Rt(e.status.message)}};return r}function Ei(e,t,r){return De(e,t,r)}function vi(e,t,r,s,i){return{resourceSpans:[{resource:{attributes:$e(t,i)},scopeSpans:[{scope:{name:r,version:s},spans:e}]}]}}var Fi=8;function Ct(){return xt()??Date.now()}function Tr(e){try{return e instanceof ze}catch{return!1}}function Si(e,t){let r=bt(e);if(!r)return;return{traceId:r.traceId,parentSpanId:r.spanId,traceState:vt(t),traceFlags:r.flags,isRemote:!0}}function Pa(e){try{return typeof e.traceparent=="function"}catch{return!1}}function xa(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 Ot(e,t,r){if(e[t]!==r)e[t]=r}function Ia(e,t){try{let r=Object.getOwnPropertyDescriptors(e);for(let s of["traceId","spanId","parentSpanId","traceState"])r[s]={value:t[s],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(e),r)}catch{return e}}class Lt{constructor(e,t,r,s,i,n){this._instance=e,this._config=t,this._logger=r,this._getContext=s,this._contextManager=i,this._onSpanQueued=n,this._queue=[],this._flushTimer=new be(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=N,this._retryAfter=new de,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 X(t,this._contextManager.active());let r=Et(t?.parent);if(r&&typeof r!="string"&&!Tr(r)){if(Pa(r))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),X(t,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let s=this._resolveParent(r,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 — spans are being started and never ended`),X(t,this._contextManager.active());let i=Date.now(),n=hi(t?.startTime,i,this._logger),o=ii();this._liveSpans.set(o,Ct());let l=this._autoContextAttributes();return new ze({traceId:s?.traceId??si(),spanId:o,parentSpanId:s?.parentSpanId,traceState:s?.traceState,traceFlags:s?.traceFlags,parentIsRemote:s?.isRemote,name:se(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:t?.kind??"internal",attributes:G({...l},t?.attributes),autoAttributeKeys:Object.keys(l),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:n,backdated:n!==i,clockAnchor:ve(t?.startTime)===void 0?s?.clockAnchor:void 0},(a,c)=>this._onSpanEnd(a,c),this._logger)}withSpan(e,t,r){let s=typeof t=="function"?void 0:t,i=typeof t=="function"?t:r,n=this.startSpan(e,s);try{let o=qe(this._contextManager,n,i);if(ys(o))return o.then((l)=>(n.end(),l),(l)=>{throw this._recordCallbackError(n,l),n.end(),l});return n.end(),o}catch(o){throw this._recordCallbackError(n,o),n.end(),o}}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=N,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(e,t){if(typeof e=="string"){let s=Si(e,t?.tracestate);if(!s)this._logger.debug("Ignoring malformed traceparent; starting a new trace");return s}if(Tr(e))return e.childContext();let r=this._contextManager.active();if(Tr(r))return r.childContext();if(r instanceof It)return Si(r.traceparent(),r.tracestate()??void 0)}_autoContextAttributes(){let e;try{e=this._getContext()}catch(r){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",r),{}}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 ze))return;let{type:r,message:s,stack:i}=Pr(t);if(e.addEvent("exception",{"exception.type":r,"exception.message":s,...i&&{"exception.stacktrace":i}}),!e.statusIsExplicitlyOk)e.setStatus("error",s)}_evictAgedSpans(){let e=Ct()-this._config.maxSpanAgeMs,t=0;for(let[r,s]of this._liveSpans){if(s>e)break;this._liveSpans.delete(r),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 r=this._runBeforeSpanSend(e,t);if(!r)return;if(this._reportLimitDrops(r),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) — raise the flush frequency or reduce span volume`);this._queue.push(r);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,r=e.droppedEventsCount??0,s=0;for(let i of e.events)s+=i.droppedAttributesCount??0;if(t||r||s)this._logger.debug(`Span limits discarded data from "${e.name}": ${t} attributes, ${r} events, ${s} event attributes`)}_runBeforeSpanSend(e,t){if(!this._config.beforeSpanSend.length)return e;let r={traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,traceState:e.traceState},s={startTime:e.startTime,endTime:e.endTime},i={attributes:e.droppedAttributesCount,events:e.droppedEventsCount},n=Object.keys(e.attributes),o={traceFlags:e.traceFlags,parentIsRemote:e.parentIsRemote},l=e.status&&{...e.status},a=e,c=e;try{for(let h of this._config.beforeSpanSend){let p=h(a);if(!p)return this._recordDrop(1,"beforeSpanSend dropped it"),null;a=this._keepSpanIdentity(p,r)}if(c={traceId:r.traceId,spanId:r.spanId,parentSpanId:r.parentSpanId,traceState:r.traceState,name:a.name,kind:a.kind,status:a.status,attributes:a.attributes,events:a.events,startTime:a.startTime,endTime:a.endTime,traceFlags:o.traceFlags,parentIsRemote:o.parentIsRemote,droppedAttributesCount:i.attributes,droppedEventsCount:i.events},!xa(c))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;if(c.name=se(c.name,"Span name",this._config.maxAttributeValueLength,this._logger),c.status&&c.status.code!=="ok"&&c.status.code!=="error")this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),c.status=l;c.startTime=ve(c.startTime)??s.startTime,c.endTime=wt(ve(c.endTime)??s.endTime,c.startTime);let f=[];for(let h of c.events)try{f.push({...h,name:se(h.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:Ve(h.timestamp,c.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return c.events=f,gi(c,t,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,n),c}catch(u){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",u),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{Ot(e,"traceId",t.traceId),Ot(e,"spanId",t.spanId),Ot(e,"parentSpanId",t.parentSpanId),Ot(e,"traceState",t.traceState)}catch{return Ia(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 r of e)try{t.push(bi(r,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=yi(Ei(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._config.maxAttributeValueLength),r=this._instance.getLibraryId(),s=this._instance.getLibraryVersion(),i=this._queue.length,n=0,o=1/0,l=this._generation;try{while(i>0&&this._queue.length>0){let a=this._discardQueueIfConsentWithdrawn();if(a)return n+a;let c=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,u=Math.max(1,Math.min(c,o,i,this._queue.length)),f=this._queue.slice(0,u),h=this._encodeBatch(f);if(!h.length){this._queue.splice(0,u),i-=u,n+=u,this._resetHeadBatchBudget();continue}let p=Ct()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),d=await this._instance._sendTracesBatch(vi(h,t,r,s,this._logger));if(l!==this._generation)break;if(this._retryAfter.record(d),d.kind==="ok"){if(this._consecutiveFlushFailures=0,this._flushJitter=N,this._resetHeadBatchBudget(),this._queue.splice(0,u),i-=u,n+=u,this._maxExportBatchSize<this._config.maxExportBatchSize)this._maxExportBatchSize++;continue}if(d.kind==="too-large"){if(u===1){this._queue.splice(0,1),i-=1,n+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=N,this._resetHeadBatchBudget();continue}let g=Math.max(1,Math.floor(u/2));if(d.measuredLocally)o=g;else this._maxExportBatchSize=g;this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${g}`);continue}if(d.kind==="retry-later"){if(this._consecutiveFlushFailures++,this._flushJitter=Ue(),this._headBatchSize=u,p)this._headBatchFailures++,this._headBatchChargeableAt=Ct()+this._nextFlushDelay();if(this._headBatchFailures<Fi)return this._logger.debug("Span export failed; retrying on the next flush",d.error),n;if(this._queue.splice(0,u),i-=u,n+=u,this._consecutiveFlushFailures=0,this._flushJitter=N,this._resetHeadBatchBudget(),this._recordDrop(u,`the ingestion endpoint failed ${Fi} times in a row`),this._retryAfter.isOpen())return n;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",d.error),this._queue.splice(0,u),i-=u,n+=u,this._consecutiveFlushFailures=0,this._flushJitter=N,this._resetHeadBatchBudget(),this._recordDrop(u,"the ingestion endpoint rejected the batch")}return n}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(Be(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,ke),this._retryAfter.remainingMs())}}class Nt{active(){return this._active}with(e,t){let r=this._active;this._active=e;try{return t()}finally{this._active=r}}}var Ta=5000,Ra=512,Ca=2048,Oa=128,La=128,Na=128,Ma=8192,Da=1e4,$a=3600000;function Q(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=1?e:t}var Ai=["service.name","service.version","deployment.environment"];function ka(e){if(!e||typeof e!="object"||Array.isArray(e))return;try{if(Ai.every((r)=>!(r in e)||typeof e[r]=="string"))return e;let t={...e};for(let r of Ai)if(r in t&&typeof t[r]!="string")delete t[r];return t}catch{return}}function Ua(e,t){if(!e)return[];let r=[e].flat().filter((i)=>Boolean(i)),s=r.filter((i)=>typeof i=="function");if(s.length!==r.length)t?.critical(`beforeSpanSend: ignoring ${r.length-s.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`);return s}function Rr(e,t,r){let s=G({...t},ka(e?.resourceAttributes)),i=Q(e?.maxExportBatchSize,Ra);return{serviceName:s?.["service.name"]??e?.serviceName,serviceVersion:s?.["service.version"]??e?.serviceVersion,environment:s?.["deployment.environment"]??e?.environment,resourceAttributes:s,beforeSpanSend:Ua(e?.beforeSpanSend,r),maxAttributesPerSpan:Q(e?.maxAttributesPerSpan,Oa),maxEventsPerSpan:Q(e?.maxEventsPerSpan,La),maxAttributesPerEvent:Na,maxAttributeValueLength:Q(e?.maxAttributeValueLength,Ma),flushIntervalMs:Q(e?.flushIntervalMs,Ta),maxExportBatchSize:i,maxQueueSize:Math.max(Q(e?.maxQueueSize,Ca),i),maxLiveSpans:Q(e?.maxLiveSpans,Da),maxSpanAgeMs:Q(e?.maxSpanAgeMs,$a)}}import{constants as wi}from"node:fs";import{open as Ba}from"node:fs/promises";import{isAbsolute as Ii}from"node:path";import{createInterface as ja}from"node:readline";var Mt=new ir(25),Ge=new ir(20),Or=7,Va=1000,za=1e4,Cr=10485760;async function Ti(e,t=Ba,r){let s={},i;try{i=process.cwd()}catch{}for(let l=e.length-1;l>=0;l--){let a=e[l],c=a?.filename;if(!a||typeof c!="string"||typeof a.lineno!="number"||Wa(c)||Xa(a))continue;if(!Ii(c)&&i===void 0)continue;if(!s[c])s[c]=[];s[c].push(a.lineno)}let n=Object.keys(s);if(n.length==0)return e;let o=[];for(let l of n){let a=Ri(l,i);if(a===void 0)continue;if(Ge.get(a))continue;let c=s[l];if(!c)continue;c.sort((h,p)=>h-p);let u=Ja(c);if(u.every((h)=>Qa(a,h)))continue;let f=Ya(Mt,a,{});o.push(Ga(l,u,f,a,t,r))}if(await Promise.all(o).catch(()=>{}),e&&e.length>0)Ka(e,Mt,i);return Mt.reduce(),e}async function qa(e,t,r){let s,i=!1;try{s=await t(e,wi.O_RDONLY|wi.O_NONBLOCK);let n=await s.stat();if(!n.isFile())return;if(n.size>Cr)return void r?.debug(`Skipping source context for oversized file ${e}: ${n.size} bytes exceeds ${Cr}`);return i=!0,s}catch{return}finally{if(s&&!i)await s.close().catch(()=>{})}}async function Ga(e,t,r,s,i,n){let o=await qa(e,i,n);if(o===void 0)return void Ge.set(s,1);let l=o;return new Promise((a)=>{let c=!1;function u(E){if(c)return;c=!0,E?.destroy(),l.close().then(a,a)}let f;try{f=l.createReadStream({autoClose:!1,start:0,end:Cr-1})}catch{Ge.set(s,1),u();return}let h;try{h=ja({input:f})}catch{Ge.set(s,1),u(f);return}let p=0,d=0,g=t[d];if(g===void 0)return void u(f);let m=g[0],b=g[1];function S(){Ge.set(s,1),h.close(),h.removeAllListeners(),u(f)}f.on("error",S),h.on("error",S),h.on("close",()=>u(f)),h.on("line",(E)=>{if(p++,p<m)return;if(r[p]=Za(E,0),p>=b){if(d===t.length-1){h.close(),h.removeAllListeners();return}d++;let A=t[d];if(A===void 0){h.close(),h.removeAllListeners();return}m=A[0],b=A[1]}})})}function Ka(e,t,r){for(let s of e)if(s.filename&&s.context_line===void 0&&typeof s.lineno=="number"){let i=Ri(s.filename,r),n=i===void 0?void 0:t.get(i);if(n===void 0)continue;Ha(s.lineno,s,n)}}function Ha(e,t,r){if(t.lineno===void 0||r===void 0)return;t.pre_context=[];for(let i=Ci(e);i<e;i++){let n=r[i];if(n===void 0)return void Pi(t);t.pre_context.push(n)}if(r[e]===void 0)return void Pi(t);t.context_line=r[e];let s=Oi(e);t.post_context=[];for(let i=e+1;i<=s;i++){let n=r[i];if(n===void 0)break;t.post_context.push(n)}}function Pi(e){delete e.pre_context,delete e.context_line,delete e.post_context}function Wa(e){return e.startsWith("node:")||e.endsWith(".min.js")||e.endsWith(".min.cjs")||e.endsWith(".min.mjs")||e.startsWith("data:")}function Xa(e){if(e.lineno!==void 0&&e.lineno>za)return!0;if(e.colno!==void 0&&e.colno>Va)return!0;return!1}function Ri(e,t){if(Ii(e))return JSON.stringify([null,e]);return t===void 0?void 0:JSON.stringify([t,e])}function Qa(e,t){let r=Mt.get(e);if(r===void 0)return!1;for(let s=t[0];s<=t[1];s++)if(r[s]===void 0)return!1;return!0}function Ja(e){if(!e.length)return[];let t=0,r=e[0];if(typeof r!="number")return[];let s=xi(r),i=[];while(!0){if(t===e.length-1){i.push(s);break}let n=e[t+1];if(typeof n!="number")break;if(n<=s[1])s[1]=n+Or;else i.push(s),s=xi(n);t++}return i}function xi(e){return[Ci(e),Oi(e)]}function Ci(e){return Math.max(1,e-Or)}function Oi(e){return e+Or}function Ya(e,t,r){let s=e.get(t);if(s===void 0)return e.set(t,r),r;return s}function Za(e,t){let r=e,s=r.length;if(s<=150)return r;if(t>s)t=s;let i=Math.max(t-60,0);if(i<5)i=0;let n=Math.min(i+140,s);if(n>s-5)n=s;if(n===s)i=Math.max(n-140,0);if(r=r.slice(i,n),i>0)r=`...${r}`;if(n<s)r+="...";return r}import{isAbsolute as el,relative as tl,sep as rl}from"path";function Li(e=process.cwd()){let t=rl==="\\",r=(i)=>t?i.replace(/\\/g,"/"):i,s=r(e);return async(i)=>{for(let n of i)if(!(!n.filename||n.filename.startsWith("node:")||n.filename.startsWith("data:"))){if(el(n.filename))n.filename=r(tl(s,r(n.filename)))}return i}}var Ni="5.57.2";var z={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",LOCAL_EVALUATION_INCONCLUSIVE:"local_evaluation_inconclusive",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};class J{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._unresolvedFlags=Object.freeze({...e.unresolvedFlags}),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 r=this._flags[e];return this._recordAccess(e),r?.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 r=this._flags[t];if(r)e[t]=r}return this._cloneWith(e)}only(e){let t={},r=[];for(let s of e){let i=this._flags[s];if(i)t[s]=i;else r.push(s)}if(r.length>0)this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${r.join(", ")}`);return this._cloneWith(t)}get keys(){return Object.keys(this._flags)}get unresolvedFlags(){return this._unresolvedFlags}_getEventProperties(){let e={},t=[];for(let[r,s]of Object.entries(this._flags)){let i=s.enabled===!1?!1:s.variant??!0;if(e[`$feature/${r}`]=i,s.enabled)t.push(r)}if(t.length>0)t.sort(),e.$active_feature_flags=t;return e}_cloneWith(e){return new J({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],r=t===void 0?void 0:t.enabled===!1?!1:t.variant??!0,s={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:r,$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 i=[];if(this._errorsWhileComputing)i.push(z.ERRORS_WHILE_COMPUTING);if(this._quotaLimited)i.push(z.QUOTA_LIMITED);if(t===void 0)i.push(Object.prototype.hasOwnProperty.call(this._unresolvedFlags,e)?z.LOCAL_EVALUATION_INCONCLUSIVE:z.FLAG_MISSING);if(i.length>0)s.$feature_flag_error=i.join(",");this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:r,groups:this._groups,disableGeoip:this._disableGeoip,properties:s})}}var sl=60000;function Mi(e){return e==="client"||e==="server"?e:"all"}function il(e,t){return e===t||e==="all"||t==="all"}class ne extends Error{constructor(e){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,ne.prototype)}}function nl(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class B extends Error{constructor(e){super(e),this.reason="unsupported_definition",nl(this,B)}}var Di=["experience_continuity","unsupported_definition","unresolved_dependency","missing_context"];function oe(e,t){if(e===void 0)return t;return Di.indexOf(t)<Di.indexOf(e)?t:e}function Ke(e,t){if(t instanceof y&&Symbol.for("posthog.requiresServerRegexEvaluation")in t)Object.defineProperty(e,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0});return e}class Lr{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:s,host:i,customHeaders:n,...o}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.warnedUnresolvableFlags=new Map,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=s,this.projectApiKey=r,this.host=i,this.poller=void 0,this.fetch=o.fetch||fetch,this.onError=o.onError,this.customHeaders=n,this.onLoad=o.onLoad,this.onMinimalFlagCalledEvents=o.onMinimalFlagCalledEvents,this.cacheProvider=o.cacheProvider,this.strictLocalEvaluation=o.strictLocalEvaluation??!1,this.evaluationContexts=o.evaluationContexts,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){if(this.debugMode)e()}currentDefinitions(){return{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}withEvaluationSnapshot(e){if(e.definitions)return e;return{...e,evaluationCache:{},definitions:this.currentDefinitions()}}createEvaluationContext(e,t={},r={},s={},i={}){return{distinctId:e,groups:t,personProperties:r,groupProperties:s,evaluationCache:i}}async getFeatureFlag(e,t,r={},s={},i={}){await this.loadFeatureFlags();let n,o;if(!this.loadedSuccessfullyOnce)return n;if(o=this.featureFlagsByKey[e],o!==void 0){let l=this.createEvaluationContext(t,r,s,i);try{n=(await this.computeFlagAndPayloadLocally(o,l)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${n}`))}catch(a){if(a instanceof B||a instanceof y)this.logMsgIfDebug(()=>console.debug(`${a.name} when computing flag locally: ${e}: ${a.message}`));else if(a instanceof Error)this.onError?.(Error(`Error computing flag locally: ${e}: ${a}`))}}return n}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let r={},s={},i={},n=this.featureFlags.length==0,o=t?t.map((a)=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,l=this.withEvaluationSnapshot({...e,definitions:void 0});return await Promise.all(o.map(async(a)=>{try{let{value:c,payload:u}=await this.computeFlagAndPayloadLocally(a,l,{skipLoadCheck:!0});if(r[a.key]=c,u)s[a.key]=u}catch(c){if(c instanceof B||c instanceof y)this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${a.key}: ${c.message}`)),i[a.key]=c.reason;else if(c instanceof Error)this.onError?.(Error(`Error computing flag locally: ${a.key}: ${c}`));n=!0}})),{response:r,payloads:s,unresolved:i,fallbackToFlags:n}}async computeFlagAndPayloadLocally(e,t,r={}){let{matchValue:s,skipLoadCheck:i=!1}=r;if(this.loadedSuccessfullyOnce)t=this.withEvaluationSnapshot(t);if(!i)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};t=this.withEvaluationSnapshot(t),e=t.definitions.featureFlagsByKey[e.key]??e;let n;n=s!==void 0?s:await this.computeFlagValueLocally(e,t);let o=_r(e.filters?.payloads,n);return{value:n,payload:o}}async computeFlagValueLocally(e,t){let{distinctId:r,groups:s,personProperties:i,groupProperties:n}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new y("Flag has experience continuity enabled","experience_continuity");let l=(e.filters||{}).aggregation_group_type_index;if(l!=null){let a=t.definitions.groupTypeMapping[String(l)];if(!a)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${l} for feature flag ${e.key}`)),new y("Flag has unknown group type index");if(!(a 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"&&(i?.$device_id===void 0||i?.$device_id===null||i?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let c=n[a];return await this.matchFeatureFlagProperties(e,s[a],c,t)}{let a=this.getBucketingValueForFlag(e,r,i);if(a===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 y(`Can't compute feature flag: ${e.key} without $device_id`,$i(e,t.definitions)??"missing_context");return await this.matchFeatureFlagProperties(e,a,i,t)}}getBucketingValueForFlag(e,t,r){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let s=r?.$device_id;if(s==null||s==="")return;return s}return t}async evaluateFlagDependency(e,t,r){let{evaluationCache:s}=r,i=e.key;if(!r.definitions.featureFlagsByKey)throw new y("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new y(`Flag dependency property for '${i}' is missing required 'dependency_chain' field`);let n=e.dependency_chain;if(!Array.isArray(n))throw new y(`Flag dependency property for '${i}' has an invalid 'dependency_chain' (expected array, got ${typeof n})`);if(n.length===0)throw new y(`Circular dependency detected for flag '${i}' (empty dependency chain)`);let o=n.find((a)=>!(a in s)&&!r.definitions.featureFlagsByKey[a]&&!r.definitions.filteredOutFlagKeys.has(a));if(o!==void 0)throw new y(`Missing flag dependency '${o}' for flag '${i}'`);for(let a of n){if(!(a in s)){let u=r.definitions.featureFlagsByKey[a];if(u)if(u.active)try{let f=await this.computeFlagValueLocally(u,r);s[a]=f}catch(f){throw Ke(new y(`Error evaluating flag dependency '${a}' for flag '${i}': ${f}`,"unresolved_dependency"),f)}else s[a]=!1;else s[a]=!1}if(s[a]==null)throw new y(`Dependency '${a}' could not be evaluated`,"unresolved_dependency")}let l=s[i];return this.flagEvaluatesToExpectedValue(e.value,l)}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,r,s){s=this.withEvaluationSnapshot(s);let i=e.filters||{},n=await gr(i.holdout,t);if(n!==void 0)return n;let o=i.groups||[],l=i.aggregation_group_type_index,a=i.early_exit??!1,{groups:c,groupProperties:u}=s,f,h,p=new Set,d;for(let g of o){let m=t;try{let b=g.aggregation_group_type_index!==void 0?g.aggregation_group_type_index:l,S=r;if(b!==l){if(b!=null){let A=s.definitions.groupTypeMapping[String(b)];if(!A||!(A in c)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${b} not available`));continue}if(!(A in u)){f=oe(f,"missing_context");continue}S=u[A],m=c[A]}}let E=await this.isConditionMatch(e,m,g,S,s);if(E==="match"){let A=g.variant,x=i.multivariate?.variants||[];d=A&&x.some((v)=>v.key===A)?A:await this.getMatchingVariant(e,m)||!0;break}if(a&&E==="out_of_rollout_bound"){if(f)break;return!1}}catch(b){if(b instanceof B)throw b;if(b instanceof y){if(f=oe(f,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b)if(h=b,a&&g.rollout_percentage!=null&&await ye(e.key,m)>g.rollout_percentage/100)p.add(!1);else{let S=i.multivariate?.variants||[],E=g.variant;p.add(E&&S.some((A)=>A.key===E)?E:await this.getMatchingVariant(e,m)||!0)}}else throw b}}if(d!==void 0&&!(h&&[...p].some((g)=>g!==d)))return d;if(f)throw Ke(new y("Can't determine if feature flag is enabled or not with given properties",f),h);return!1}async isConditionMatch(e,t,r,s,i){i=this.withEvaluationSnapshot(i);let n=i.definitions,o=r.rollout_percentage,l=(a)=>{this.logMsgIfDebug(()=>console.warn(a))};if((r.properties||[]).length>0){let a,c,u;for(let f of r.properties){let h=f.type,p=!1;try{if(h==="cohort"){let d=await ji(f,s,n.cohorts,this.debugMode,(g)=>this.evaluateFlagDependency(g,s,i),n.propertyMatchingVersion);p=f.operator==="not_in"?!d:d}else if(h==="flag")p=await this.evaluateFlagDependency(f,s,i);else if(Object.prototype.hasOwnProperty.call(s,f.key))p=Bi(f,s,l,n.propertyMatchingVersion);else{Me(f),a=oe(a,"missing_context");continue}}catch(d){if(d instanceof B){if(a===void 0)u??=d;a=oe(a,d.reason);continue}if(d instanceof y){if(Symbol.for("posthog.requiresServerRegexEvaluation")in d)c=d;a=oe(a,d.reason);continue}throw d}if(!p)return"no_match"}if(u)throw u;if(a)throw Ke(new y(`Can't determine if a condition of flag ${e.key} matches`,a),c);if(o==null)return"match"}if(o!=null&&await ye(e.key,t)>o/100)return"out_of_rollout_bound";return"match"}async getMatchingVariant(e,t){return mr(e.key,t,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return yt(e.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(e){if(!this.evaluationContexts||this.evaluationContexts.length===0)return e;let t=new Set(this.evaluationContexts);return e.filter((r)=>{let s=r.evaluation_contexts??r.evaluation_tags;if(!s||s.length===0)return!0;return s.some((i)=>t.has(i))})}getEvaluationRuntimeForFlag(e){let t=this.featureFlagsByKey[e];return t?Mi(t.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(e){return this.featureFlags.filter((t)=>il(Mi(t.evaluation_runtime),e)).map((t)=>t.key)}updateFlagState(e){let t=this.filterFlagsByEvaluationContexts(e.flags),r=t.reduce((n,o)=>(n[o.key]=o,n),{}),s=new Set(t.map((n)=>n.key)),i=new Set(e.flags.filter((n)=>!s.has(n.key)).map((n)=>n.key));this.featureFlags=t,this.featureFlagsByKey=r,this.filteredOutFlagKeys=i,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)}warnAboutUnresolvableFlags(e){let t=[],r=[],s=new Map,i=this.currentDefinitions();for(let n of e){let o=$i(n,i);if(!o)continue;let l=JSON.stringify(n);if(s.set(n.key,l),this.warnedUnresolvableFlags.get(n.key)!==l)if(o==="experience_continuity")t.push(n.key);else r.push(n.key)}if(this.warnedUnresolvableFlags=s,t.length>0){let n=this.strictLocalEvaluation?"With strictLocalEvaluation enabled these flags are left unresolved. To evaluate them locally, disable experience continuity on these flags in PostHog.":"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).";console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled and cannot be resolved locally (reason: experience_continuity): ${t.join(", ")}. `+n)}if(r.length>0){let n=this.strictLocalEvaluation?"With strictLocalEvaluation enabled these flags are left unresolved when evaluation reaches that part.":"Evaluating these flags falls back to a server request when evaluation reaches that part.";console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) use something local evaluation does not support, such as a static cohort, an unknown operator, or a missing or circular flag dependency (reason: unsupported_definition): ${r.join(", ")}. ${n} To evaluate them locally, change these flags in PostHog or upgrade posthog-node.`)}}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.warnAboutUnresolvableFlags(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(sl,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(r){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${r}`))}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 ne(`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 ne(`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 ne(`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 r=await t.json()??{};if(!("flags"in r))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let s=r.group_type_mapping||{},i=r.minimal_flag_called_events===!0,n={flags:r.flags??[],group_type_mapping:s,cohorts:r.cohorts||{},minimal_flag_called_events:i,property_matching_version:r.property_matching_version,propertyMatchingVersion:r.property_matching_version,groupTypeMapping:s,minimalFlagCalledEvents:i};if(this.updateFlagState(n),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(o){this.onError?.(Error(`Failed to store in cache: ${o}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags);break}default:return}}catch(e){if(e instanceof ne)this.onError?.(e)}finally{if(!this.pollerStopped&&this.pollingInterval!==null)this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval())}}getPersonalApiKeyRequestOptions(e="GET",t){let r={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};if(t)r["If-None-Match"]=t;return{method:e,headers:r}}async _requestFeatureFlagDefinitions(){if(!this.personalApiKey)throw new ne("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),r=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;r=T(()=>{i.abort()},this.timeout),t.signal=i.signal}let s=()=>clearTimeout(r);try{let i=this.fetch,n=await i(e,t);if(n.status!==200)return s(),n;return{status:n.status,headers:n.headers,body:n.body,text:async()=>{try{return await n.text()}finally{s()}},json:async()=>{try{return await n.json()}finally{s()}}}}catch(i){throw s(),i}}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 H(t,e,()=>{throw Error(`Cache shutdown timeout after ${e}ms`)})}catch(t){this.onError?.(Error(`Error during cache shutdown: ${t}`))}}}function $i(e,t){if(!e.active)return;if(e.ensure_experience_continuity)return"experience_continuity";let r=e.filters||{},s=r.aggregation_group_type_index;if(s!=null&&!t.groupTypeMapping[String(s)])return"unsupported_definition";return(r.groups||[]).some((n)=>(n.properties||[]).some((o)=>ki(o,t,new Set)))?"unsupported_definition":void 0}function ki(e,t,r){if(e.type==="flag"){let i=e.dependency_chain;if(!Array.isArray(i)||i.length===0)return!0;return i.some((n)=>!t.featureFlagsByKey[n]&&!t.filteredOutFlagKeys.has(n))}if(e.type!=="cohort")try{return Me(e),!1}catch(i){if(i instanceof y)return!0;throw i}let s=String(e.value);if(!(s in t.cohorts))return!0;if(r.has(s))return!1;return r.add(s),Ui(t.cohorts[s],t,r)}function Ui(e,t,r){return(e?.values??[]).some((s)=>("values"in s)?Ui(s,t,r):ki(s,t,r))}function Bi(e,t,r,s){return pr(e,t,{warnFunction:r,propertyMatchingVersion:s})}function ol(e,t){if(!(e in t))throw new B(`cohort ${e} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function ji(e,t,r,s=!1,i,n){let o=String(e.value);ol(o,r);let l=r[o];return Vi(l,t,r,s,i,n)}async function Vi(e,t,r,s=!1,i,n){if(!e)return!0;let{type:o,values:l}=e;if(!l||l.length===0)return!0;let a,c;if("values"in l[0]){for(let u of l)try{let f=await Vi(u,t,r,s,i,n);if(o==="AND"){if(!f)return!1}else if(f)return!0}catch(f){if(f instanceof B)throw f;if(f instanceof y){if(s)console.debug(`Failed to compute property ${u} locally: ${f}`);if(a=oe(a,f.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in f)c=f}else throw f}if(a)throw Ke(new y("Can't match cohort without a given cohort property value",a),c);return o==="AND"}for(let u of l)try{let f;if(u.type==="cohort")f=await ji(u,t,r,s,i,n);else if(u.type==="flag"){if(!i)throw new y(`Flag dependency '${u.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);f=await i(u)}else f=Bi(u,t,void 0,n);let h=u.negation||!1;if(o==="AND"){if(!f&&!h)return!1;if(f&&h)return!1}else{if(f&&!h)return!0;if(!f&&h)return!0}}catch(f){if(f instanceof B)throw f;if(f instanceof y){if(s)console.debug(`Failed to compute property ${u} locally: ${f}`);if(a=oe(a,f.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in f)c=f}else throw f}if(a)throw Ke(new y("can't match cohort without a given cohort property value",a),c);return o==="AND"}var al=["--unhandled-rejections","--unhandled_rejections"],ll=new Set(["throw","strict","warn","warn-with-error-code","none"]),cl=[...globalThis.process?.execArgv??[]],ul=globalThis.process?.env?.NODE_OPTIONS;function fl(e){let t=[],r="",s=!1;for(let i=0;i<e.length;i++){let n=e[i];if(n==="\\"&&s&&i+1<e.length)r+=e[++i];else if(n!==" "||s)if(n==='"')s=!s;else r+=n;else if(r)t.push(r),r=""}if(r)t.push(r);return t}function zi(e){let t;for(let r=0;r<e.length;r++){let s=e[r],i=al.find((o)=>s===o||s.startsWith(`${o}=`));if(!i)continue;let n=s===i?e[++r]:s.slice(i.length+1);if(ll.has(n))t=n}return t}function dl(e=cl,t=ul){return zi(e)??zi(fl(t??""))??"throw"}var qi=dl();function Gi(e,t,r){e(t,{mechanism:{type:r==="unhandledRejection"?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function hl(e,t){let r=!1;return Object.assign((s,i)=>{let n=global.process.listeners("uncaughtException").filter((o)=>o.name!=="domainUncaughtExceptionClear"&&o._posthogErrorHandler!==!0).length;if(Gi(e,s,i),!r&&n===0)r=!0,t(s)},{_posthogErrorHandler:!0})}function Ki(e,t,r=qi){let s=globalThis.process;if(!s)return;if(r==="strict")return void s.on("uncaughtExceptionMonitor",(i,n)=>Gi(e,i,n));s.on("uncaughtException",hl(e,t))}function Hi(e,t=qi){let r=globalThis.process;if(!r||t==="throw"||t==="strict"||t==="warn-with-error-code")return;r.on("unhandledRejection",(s)=>{e(s,{mechanism:{type:"onunhandledrejection",handled:!1}})})}var pl=2000;class Dt{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new Gt({...Qr(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return Qe(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,r,s,i){let n={...i},o=e.buildFromUnknown(t,r);o.$exception_list=await e.modifyFrames(o.$exception_list);let l=Ds();if(l)n.$release_id=l;return{event:"$exception",distinctId:s,properties:{...o,...n},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled())Ki(this.onException.bind(this),this.onFatalError.bind(this)),Hi(this.onException.bind(this))}onException(e,t){this.client.addPendingPromise((async()=>{if(!Dt.isPreviouslyCapturedError(e)){let r=await Dt.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),i=r.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(i))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:i});return this.client._capturePreparedEvent(r,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(pl),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}var ae=Dt;var gl=/^[0-9a-f]{32}$/i,ml=/^[0-9a-f]{16}$/i,_l=Symbol.for("opentelemetry.js.api.1"),yl=Symbol.for("OpenTelemetry Context Key SPAN");async function Wi(){try{let r=globalThis[_l]?.context?.active().getValue(yl)?.spanContext(),s=r?.traceId,i=r?.spanId;if(typeof s=="string"&&typeof i=="string"&&gl.test(s)&&ml.test(i)&&!/^0+$/.test(s)&&!/^0+$/.test(i))return{$trace_id:s.toLowerCase(),$span_id:i.toLowerCase()}}catch{}return{}}class Nr{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}}function bl(e){return e==="v0"||e==="v1"}function Xi(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return bl(e)?e:"v0"}var He="analytics",We="ai";function Qi(e){return typeof e.event=="string"&&e.event.startsWith("$ai_")}class Fe extends Error{constructor({requestId:e,drops:t,retryExhausted:r,cause:s}){super(Fe.buildMessage(e,t,r,s)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=r,this.cause=s}static buildMessage(e,t,r,s){let i=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${r.length} undelivered`;if(s instanceof Error)i+=` (${s.message})`;return i}}function Mr(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 El(e){return typeof e=="string"?e:void 0}var vl=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Mr},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Mr},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Mr},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:El}],Fl=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function Sl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Al(e){if(typeof e=="string"){let r=new Date(e);if(Number.isNaN(r.getTime()))return new Date().toISOString();let s=r.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?s.replace(/\.\d{3}Z$/,`.${i}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 Ji(e,t,r){if(r!==void 0&&!(t in e))e[t]=r}function wl(e){let r={...Sl(e.properties)?e.properties:{}},s={};for(let{property:n,optionKey:o,coerce:l}of vl)if(n in r){let a=l(r[n]);if(a!==void 0)s[o]=a;delete r[n]}let i={};for(let{property:n,field:o}of Fl)if(n in r){let l=r[n];if(typeof l=="string")i[o]=l;delete r[n]}return delete r.$lib,delete r.$lib_version,Ji(r,"$set",e.$set),Ji(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:Al(e.timestamp),...i,options:s,properties:r}}function Yi(e,{createdAt:t,historicalMigration:r}){let s={created_at:t,batch:e.map(wl)};if(r)s.historical_migration=!0;return s}var Pl="/i/v1/analytics/events",xl=30000,Il=new Set([408,500,502,503,504]);class Dr{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??xl,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??((r)=>new Promise((s)=>T(s,r))),this.generateRequestId=t.generateRequestId??I,this.compress=t.compress??Ce}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),r=new Date(this.now()).toISOString(),{batch:s}=Yi(e,{createdAt:r,historicalMigration:this.config.historicalMigration}),i=`${this.config.host}${Pl}`,n=[],o=s,l=Math.max(1,this.config.maxAttempts);for(let a=1;a<=l;a++){let c=a===l,u=Y({created_at:r,...this.config.historicalMigration?{historical_migration:!0}:{},batch:o}),f,h;try{f=await this.sendOnce(i,u,a,t);let{response:p,signal:d}=f,{status:g}=p;if(g<200||g>=300)if(!c&&Il.has(g)){let m=this.parseRetryAfter(p);await f.waitFor(f.cancelBody()).catch(()=>{}),h=this.backoffDelay(a,m)}else{let m=await this.buildHttpError(p,g,f.waitFor);return this.surfaceBatchFailure(t,n,o,m)}else{let m;try{m=await f.waitFor(this.parseResponse(p))}catch(E){if(d.aborted)throw E;return this.surfaceBatchFailure(t,n,o,Error(`Capture V1 returned an unparseable ${g} response body`))}let b=this.classify(o,m,n);if(b.length===0)return this.surfacePartialDrops(t,n);if(c)return void this.onError(new Fe({requestId:t,drops:n,retryExhausted:b.map((E)=>E.uuid)}));o=b;let S=this.parseRetryAfter(p);h=this.backoffDelay(a,S)}}catch(p){if(f&&!f.signal.aborted)throw p;if(c)return this.surfaceBatchFailure(t,n,o,p);h=this.backoffDelay(a)}finally{f?.cleanup()}if(h!==void 0)await this.sleep(h)}}async sendOnce(e,t,r,s){let i=this.buildHeaders(r,s),n=t;if(this.config.compressionEnabled){let u=await this.compress(t,this.config.isDebug);if(u!==null)n=u,i["Content-Encoding"]="gzip"}let o=new AbortController,l="waiting for response headers",a,c=new Promise((u,f)=>{a=T(()=>{let h=Error(`Capture V1 request timed out ${l} after ${this.config.requestTimeoutMs}ms`);h.name="AbortError",f(h),o.abort(h)},this.config.requestTimeoutMs)});try{let u=this.fetchFn(e,{method:"POST",headers:i,body:n,signal:o.signal}),f=!1;u.then((m)=>{if(o.signal.aborted&&!f)this.cancelBody(m)}).catch(()=>{});let h=await Promise.race([u,c]);f=!0,l="while reading the response body";let p=!1,d,g=()=>d??=this.cancelBody(h);return{response:h,signal:o.signal,waitFor:(m)=>Promise.race([m,c]),cancelBody:g,cleanup:()=>{if(p)return;if(p=!0,clearTimeout(a),o.signal.aborted)g()}}}catch(u){throw clearTimeout(a),u}}buildHeaders(e,t){let r=`${this.config.libraryId}/${this.config.libraryVersion}`,s={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":r,"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,r){let s=t.results??{},i=[];for(let n of e){let o=s[n.uuid];if(o){if(o.result==="drop")r.push({uuid:n.uuid,details:o.details??void 0});else if(o.result==="retry")i.push(n)}}return i}backoffDelay(e,t){let r=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);if(t===void 0)return r;return Math.max(r,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let r=t.trim();if(/^\d+$/.test(r)){let n=parseInt(r,10);return Number.isFinite(n)&&n>0?1000*n:void 0}let s=Date.parse(r);if(Number.isNaN(s))return;let i=s-this.now();return i>0?i:void 0}async parseResponse(e){let t=await e.text(),r=JSON.parse(t);if(typeof r!="object"||r===null||Array.isArray(r))throw Error("unexpected response shape");let s=r.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,r){let s="";try{s=(await r(e.text())).slice(0,512)}catch{}let i=s?`: ${s}`:"";return Error(`Capture V1 request failed with HTTP ${t}${i}`)}surfaceBatchFailure(e,t,r,s){this.onError(new Fe({requestId:e,drops:t,retryExhausted:r.map((i)=>i.uuid),cause:s}))}surfacePartialDrops(e,t){if(t.length>0)this.onError(new Fe({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}}var le="ai-capture",$t="/i/v0/ai/batch/",kt=8388608,Zi=5242880;var Tl=new TextEncoder;function $r(e){return Tl.encode(Y(e)).length}function en(e,t=kt,r=Zi){let s=[],i=[],n=[],o=0;for(let l of e){if(l===void 0)continue;let a=$r(l);if(a>t){i.push({event:typeof l.event=="string"?l.event:"unknown",bytes:a});continue}if(n.length>0&&o+a>r)s.push(n),n=[],o=0;n.push(l),o+=a}if(n.length>0)s.push(n);return{batches:s,dropped:i}}var Rl=100,tn=30000,Cl=50000,Ol=50,Ll=500,Nl="https://us.i.posthog.com",rn=new Set;function Ut(e,t){if(rn.has(e))return;rn.add(e),console.warn(`[PostHog] ${t}`)}function Ml(e){return typeof e=="string"?e.trim():""}function Dl(e){return(typeof e=="string"?e.trim():"")||void 0}function $l(e){return(typeof e=="string"?e.trim():"")||Nl}function kl(e){return(Array.isArray(e)?e:[e]).filter((r)=>typeof r=="string"&&r.trim().length>0)}function Ul(e){if(!e)return{};let t={};for(let[s,i]of Object.entries(e))t[`$feature/${s}`]=i;let r=Object.keys(e).filter((s)=>e[s]!==!1).sort();if(r.length>0)t.$active_feature_flags=r;return t}class kr extends mt{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(e){this._distinctIdHasSentFlagCalls=new Map(Object.entries(e??{}))}constructor(e,t={}){let r=Ml(e),s={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5000,host:$l(t.host),personalApiKey:Dl(t.secretKey??t.personalApiKey)};if(super(r,s),this._memoryStorage=new Nr,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=s,this.captureMode=Xi(),this.enableFullAiCapture=s.enableFullAiCapture===!0,this.privacyMode=s.privacyMode===!0,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof s.featureFlagsPollingInterval=="number"?Math.max(s.featureFlagsPollingInterval,Rl):s.featureFlagsPollingInterval===null?null:tn,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 Lr({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:s.personalApiKey,projectApiKey:r,timeout:s.requestTimeout??1e4,host:this.host,fetch:s.fetch,onError:(n)=>{this._events.emit("error",n)},onLoad:(n)=>{this._events.emit("localEvaluationFlagsLoaded",n)},onMinimalFlagCalledEvents:(n)=>{this._minimalFlagCalledEvents=n},customHeaders:this.getCustomHeaders(),cacheProvider:s.flagDefinitionCacheProvider,strictLocalEvaluation:s.strictLocalEvaluation,evaluationContexts:s.evaluationContexts??s.evaluationEnvironments})}this.errorTracking=new ae(this,s,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=s.maxCacheSize||Cl}enqueue(e,t,r,s){super.enqueue(e,t,r,s),this.scheduleDebouncedFlush()}_flushEventsAndSpans(e=!1){let t=this.flushWithPendingPromises();if(!this._traces||e&&this._traces.throttled)return t;return Pe([t,this._traces.flush().catch(()=>{})]).then(([r])=>{if(r.status==="rejected")throw r.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(e){let t=this._flushEventsAndSpans(e),r=this.options.waitUntil;if(r&&!this._waitUntilCycle)try{r(t.catch(()=>{}))}catch{}return t}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e)return;if(this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let n,o=new Promise((l)=>{n=l});try{e(o)}catch{return}this._waitUntilCycle={resolve:n,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,r=this.options.waitUntilMaxWaitMs??Ll,s=t>=r;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(s)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??Ol;this._waitUntilCycle.timer=T(()=>{this.resolveWaitUntilFlush()},i)}_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"&&Qi(e)?We:He}persistedQueueKeyForRoute(e){if(e===le)return R.AiCaptureQueue;return e===We?R.AiQueue:R.Queue}getActiveQueueRoutes(){let e=this.captureMode==="v1"?[He,We]:[He];if(this._aiCaptureRouteActive)e.push(le);return e}getBatchEndpointPath(e){return e===le?$t:super.getBatchEndpointPath(e)}async sendBatch(e,t,r=He){if(r===le)return this.sendAiCaptureBatch(e,t);if(this.captureMode!=="v1"||r===We)return super.sendBatch(e,t,r);let s=e.filter((i)=>i!==void 0);await this.getV1Sender().sendV1Batch(s)}async sendAiCaptureBatch(e,t){let{batches:r,dropped:s}=en(e);for(let{event:i,bytes:n}of s){let o=`Event ${i} (${n} bytes) exceeds the ${kt/1048576}MiB limit for ${$t}, dropping.`;this._logger.error(o),this._events.emit("error",Error(o))}for(let i of r)await this.sendAiSubBatch(i,t)}async sendAiSubBatch(e,t){try{await super.sendBatch(e,t,le)}catch(r){if(!me(r))throw r;if(e.length===1){let[i]=e,o=`Event ${typeof i.event=="string"?i.event:"unknown"} (${$r(i)} bytes) was rejected with 413 by ${$t} on its own, dropping.`;this._logger.error(o),this._events.emit("error",Error(o));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 Dr({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 Ni}get metrics(){if(!this._metrics)this._metrics=new At(this,St(this.options.metrics),this._logger);return this._metrics}initializeSpanContextManager(){return new Nt}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 Lt(this,Rr(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)??X(t,this._spanContextManager.active())}withSpan(e,t,r){let s=typeof t=="function"?void 0:t,i=typeof t=="function"?t:r,n=this._tracesPipeline;if(!n)return qe(this._spanContextManager,X(s,this._spanContextManager.active()),i);return s?n.withSpan(e,s,i):n.withSpan(e,i)}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,r){if(typeof e=="string")this._logger.warn(t);if(e.event==="$exception"&&!e._originatedFromCaptureException)this._logger.warn(r)}_sendPreparedEvent(e,t,r,s,i){return this.addPendingPromise(this._prepareEventMessage(t,s).then(({distinctId:n,event:o,properties:l,options:a})=>{let c={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},u={distinctId:n,event:o,properties:{...l,...this.getCommonEventProperties()}};return r?this.sendImmediate(e,u,c,i):this.enqueue(e,u,c,i)}).catch((n)=>{if(n)console.error(n)}))}_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=ee(e.uuid,I);return this._sendPreparedAiEvent({...e,uuid:t},!1),t}async captureAiImmediate(e){if(this.disabled)return;let t=ee(e.uuid,I);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,le)}identify({distinctId:e,properties:t={},disableGeoip:r}){let{$set:s,$set_once:i,$anon_distinct_id:n,...o}=t,c={$set:s||o,$set_once:i||{},$anon_distinct_id:n??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:c,disableGeoip:r},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:r}){let{$set:s,$set_once:i,$anon_distinct_id:n,...o}=t,c={$set:s||o,$set_once:i||{},$anon_distinct_id:n??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:c,disableGeoip:r},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:r={}}){if(Object.keys(t).length===0&&Object.keys(r).length===0)return;let s={};if(Object.keys(t).length>0)s.$set=t;if(Object.keys(r).length>0)s.$set_once=r;this.capture({distinctId:e,event:"$set",properties:s})}unsetPersonProperties({distinctId:e,properties:t}){let r=kl(t);if(r.length===0)return;this.capture({distinctId:e,event:"$set",properties:{$unset:r}})}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=tn){if(this.isLocalEvaluationReady())return!0;if(this.featureFlagsPoller===void 0)return!1;return new Promise((t)=>{let r=setTimeout(()=>{s(),t(!1)},e),s=this._events.on("localEvaluationFlagsLoaded",(i)=>{clearTimeout(r),s(),t(i>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,r={},s){if(this.disabled)return void this._logger.warn("The client is disabled");let i=r.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let v=this._flagOverrides[e];if(v===void 0)return;let _=this._payloadOverrides?.[e];return{key:e,enabled:v!==!1,variant:typeof v=="string"?v:void 0,payload:_}}let{groups:n,disableGeoip:o}=r,{onlyEvaluateLocally:l,personProperties:a,groupProperties:c}=r,u=this.addLocalPersonAndGroupProperties(t,n,a,c);a=u.allPersonProperties,c=u.allGroupProperties;let f=this.createFeatureFlagEvaluationContext(t,n,this.personPropertiesForLocalEvaluation(t,a),c);if(l==null)l=this.options.strictLocalEvaluation??!1;let h,p=!1,d,g,m,b,S,E,A;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let v=this.featureFlagsPoller?.featureFlagsByKey[e];if(v)try{let _=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(v,f,{matchValue:s});if(_){p=!0;let F=_.value;b=v.id,E="Evaluated locally",A=v.has_experiment,h={key:e,enabled:F!==!1,variant:typeof F=="string"?F:void 0,payload:_.payload??void 0,reason:E,reasonCode:v.active===!1?"flag_disabled":void 0}}}catch(_){if(_ instanceof B||_ instanceof y)this._logger?.info(`${_.name} when computing flag locally: ${e}: ${_.message}`);else throw _}}if(!p&&!l){let v=await super.getFeatureFlagDetailsStateless(f.distinctId,f.groups,a,c,o,[e]);if(v===void 0)m=z.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=v.minimalFlagCalledEvents===!0,d=v.requestId,g=v.evaluatedAt;let _=[];if(v.errorsWhileComputingFlags)_.push(z.ERRORS_WHILE_COMPUTING);if(v.quotaLimited?.includes("feature_flags"))_.push(z.QUOTA_LIMITED);let F=v.flags[e];if(F===void 0)_.push(z.FLAG_MISSING);else{b=F.metadata?.id,S=F.metadata?.version,E=F.reason?.description??F.reason?.code,A=F.metadata?.has_experiment;let w;if(F.metadata?.payload!==void 0)try{w=JSON.parse(F.metadata.payload)}catch{w=F.metadata.payload}h={key:e,enabled:F.enabled,variant:F.variant??void 0,payload:w,reason:E,reasonCode:F.reason?.code}}if(_.length>0)m=_.join(",")}}if(i){let v=h===void 0?void 0:h.enabled===!1?!1:h.variant??!0,_={$feature_flag:e,$feature_flag_response:v,$feature_flag_id:b,$feature_flag_version:S,$feature_flag_reason:E,locally_evaluated:p,[`$feature/${e}`]:v,$feature_flag_request_id:d,$feature_flag_evaluated_at:p?Date.now():g};if(A!==void 0)_.$feature_flag_has_experiment=A;if(p&&this.featureFlagsPoller){let F=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(F!==void 0)_.$feature_flag_definitions_loaded_at=F}if(m)_.$feature_flag_error=m;this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:v,groups:n,disableGeoip:o,properties:_})}if(h!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides)h={...h,payload:this._payloadOverrides[e]};return h}async getFeatureFlag(e,t,r){Ut("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let s=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(s===void 0)return;if(s.enabled===!1)return!1;return s.variant??!0}async getFeatureFlagPayload(e,t,r,s){if(Ut("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead — 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 i=await this._getFeatureFlagResult(e,t,{...s,sendFeatureFlagEvents:!1},r);if(i===void 0)return;return i.payload??null}async getFeatureFlagResult(e,t,r){let{distinctId:s,options:i}=this._resolveDistinctId(t,r);if(!s)return void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()");return this._getFeatureFlagResult(e,s,{...i,sendFeatureFlagEvents:i?.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 r=await t.json();if(typeof r=="string")try{return JSON.parse(r)}catch(s){}return r}async isFeatureEnabled(e,t,r){Ut("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let s=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.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:r,options:s}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{};return(await this.getAllFlagsAndPayloads(r,s)).featureFlags||{}}async getAllFlagsAndPayloads(e,t){let{distinctId:r,options:s}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads — pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:i,disableGeoip:n,flagKeys:o}=s||{},{onlyEvaluateLocally:l,personProperties:a,groupProperties:c}=s||{},u=this.addLocalPersonAndGroupProperties(r,i,a,c);a=u.allPersonProperties,c=u.allGroupProperties;let f=this.createFeatureFlagEvaluationContext(r,i,this.personPropertiesForLocalEvaluation(r,a),c);if(l==null)l=this.options.strictLocalEvaluation??!1;let h=await this.featureFlagsPoller?.getAllFlagsAndPayloads(f,o),p={},d={},g=!0;if(h)p=h.response,d=h.payloads,g=h.fallbackToFlags;if(g&&!l){let m=await super.getFeatureFlagsAndPayloadsStateless(f.distinctId,f.groups,a,c,n,o);p={...p,...m.flags||{}},d={...d,...m.payloads||{}}}if(this._flagOverrides!==void 0)p={...p,...this._flagOverrides};if(this._payloadOverrides!==void 0)d={...d,...this._payloadOverrides};return{featureFlags:p,featureFlagPayloads:d}}async evaluateFlags(e,t){let{distinctId:r,options:s}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new J({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new J({host:this._getFeatureFlagEvaluationsHost(),distinctId:r,flags:{}});let{groups:i,disableGeoip:n}=s||{},o=s?.flagKeys??void 0;if(o?.length===0)return new J({host:this._getFeatureFlagEvaluationsHost(),distinctId:r,groups:i,disableGeoip:n,flags:{}});let{onlyEvaluateLocally:l,personProperties:a,groupProperties:c}=s||{},u=this.addLocalPersonAndGroupProperties(r,i,a,c);a=u.allPersonProperties,c=u.allGroupProperties;let f=this.createFeatureFlagEvaluationContext(r,i,this.personPropertiesForLocalEvaluation(r,a),c);if(l==null)l=this.options.strictLocalEvaluation??!1;let h=o?new Set(o):void 0,p={},d,g,m=!1,b=!1,S=await this.featureFlagsPoller?.getAllFlagsAndPayloads(f,o),E=new Set;if(S)for(let[_,F]of Object.entries(S.response)){let w=this.featureFlagsPoller?.featureFlagsByKey[_];p[_]={key:_,enabled:F!==!1,variant:typeof F=="string"?F:void 0,payload:S.payloads[_],id:w?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:w?.has_experiment},E.add(_)}let A=h!==void 0&&Array.from(h).some((_)=>this.featureFlagsPoller?.featureFlagsByKey[_]===void 0);if((S?S.fallbackToFlags||A:!0)&&!l){let _=await super.getFeatureFlagDetailsStateless(f.distinctId,f.groups,a,c,n,o);if(_){this._minimalFlagCalledEvents=_.minimalFlagCalledEvents===!0,d=_.requestId,g=_.evaluatedAt,m=Boolean(_.errorsWhileComputingFlags),b=Array.isArray(_.quotaLimited)&&_.quotaLimited.includes("feature_flags");for(let[F,w]of Object.entries(_.flags)){if(E.has(F))continue;let Bt;if(w.metadata?.payload!==void 0)try{Bt=JSON.parse(w.metadata.payload)}catch{Bt=w.metadata.payload}p[F]={key:F,enabled:w.enabled,variant:w.variant,payload:Bt,id:w.metadata?.id,version:w.metadata?.version,reason:w.reason?.description??w.reason?.code,locallyEvaluated:!1,hasExperiment:w.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[_,F]of Object.entries(this._flagOverrides)){if(F===void 0){delete p[_];continue}let w=p[_];p[_]={key:_,enabled:F!==!1,variant:typeof F=="string"?F:void 0,payload:w?.payload,id:w?.id,version:w?.version,reason:w?.reason,locallyEvaluated:w?.locallyEvaluated??!1,hasExperiment:w?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[_,F]of Object.entries(this._payloadOverrides)){let w=p[_];if(w)p[_]={...w,payload:F}}if(h!==void 0){for(let _ of Object.keys(p))if(!h.has(_))delete p[_]}let v={};for(let[_,F]of Object.entries(S?.unresolved??{}))if(!Object.prototype.hasOwnProperty.call(p,_))v[_]=F;return new J({host:this._getFeatureFlagEvaluationsHost(),distinctId:r,groups:i,disableGeoip:n,flags:p,unresolvedFlags:v,requestId:d,evaluatedAt:g,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:m,quotaLimited:b})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:r,response:s,groups:i,disableGeoip:n,properties:o}=e,l=i&&Object.keys(i).length>0?`_${JSON.stringify(Object.entries(i).sort(([u],[f])=>u<f?-1:u>f?1:0))}`:"",a=`${r}_${s}${l}`,c=this._distinctIdHasSentFlagCalls.get(t)??new Set;if(this._distinctIdHasSentFlagCalls.delete(t),this._distinctIdHasSentFlagCalls.set(t,c),c.has(a))return;c.add(a);while(this._distinctIdHasSentFlagCalls.size>Math.max(this.maxCacheSize,1)){let u=this._distinctIdHasSentFlagCalls.keys().next().value;if(u===void 0)break;this._distinctIdHasSentFlagCalls.delete(u)}this.capture({distinctId:t,event:"$feature_flag_called",properties:o,groups:i,disableGeoip:n})}_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:r,distinctId:s,disableGeoip:i}){this._sendPreparedEvent("capture",{distinctId:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:i},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:r,distinctId:s,disableGeoip:i}){await this._sendPreparedEvent("capture",{distinctId:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:i},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=(r)=>Object.fromEntries(r.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 r=t.flags;if(r===!1||Array.isArray(r)||typeof r=="object"&&r!==null)return!0}if("payloads"in t){let r=t.payloads;if(r===!1||typeof r=="object"&&r!==null)return!0}return!1}withContext(e,t,r){if(!this.context)return t();return this.context.run(e,t,r)}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??30000),r=this._consumeWaitUntilCycle();if(await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics)await H(this._metrics.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._metrics.reset();if(this._traces)await H(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(),r?.()}}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)}`,r={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 i=new AbortController;s=T(()=>{i.abort()},this.options.requestTimeout),r.signal=i.signal}try{return await this.fetch(t,r)}catch(i){this._events.emit("error",i);return}finally{if(s)clearTimeout(s)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let r={},s={};for(let[i,n]of Object.entries(e))if(Hr(n)&&t&&i in t){let o={};for(let[l,a]of Object.entries(n))o[String(l)]=String(a);s[String(i)]=o}else r[String(i)]=String(n);return{personProperties:r,groupProperties:s}}async getFeatureFlagsForEvent(e,t,r,s){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let i=s?.personProperties||{},n=s?.groupProperties||{},o=s?.flagKeys;if(s?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let a={};for(let[c,u]of Object.entries(t||{}))a[c]=String(u);return await this.getAllFlags(e,{groups:a,personProperties:i,groupProperties:n,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:o})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let a={};for(let[c,u]of Object.entries(t||{}))a[c]=String(u);return await this.getAllFlags(e,{groups:a,personProperties:i,groupProperties:n,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:o})}return(await super.getFeatureFlagsStateless(e,t,i,n,r)).flags}addLocalPersonAndGroupProperties(e,t,r,s){let i={...r||{}},n={};if(t)for(let o of Object.keys(t))n[o]={$group_key:t[o],...s?.[o]||{}};return{allPersonProperties:i,allGroupProperties:n}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,r,s){return{distinctId:e,groups:t||{},personProperties:r||{},groupProperties:s||{},evaluationCache:{}}}captureException(e,t,r,s,i){if(!ae.isPreviouslyCapturedError(e)){let n=Error("PostHog syntheticException");this.addPendingPromise(ae.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:n},t,r).then((o)=>this._capturePreparedEvent({...o,uuid:s,flags:i},!1)))}}async captureExceptionImmediate(e,t,r,s){if(!ae.isPreviouslyCapturedError(e)){let i=Error("PostHog syntheticException");return this.addPendingPromise(ae.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:i},t,r).then((n)=>this.captureImmediate({...n,flags:s})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:r,event:s,properties:i,groups:n,flags:o,sendFeatureFlags:l,timestamp:a,disableGeoip:c,uuid:u}=e,f=this.context?.get(),h=t.includeContextProperties??!0,p=r||f?.distinctId,d=h?{...this.props,...f?.properties||{},...i||{}}:{...i||{}};if(s==="$exception"&&!(("$trace_id"in d)||("$span_id"in d)))Object.assign(d,await Wi());if(!p)p=I(),d.$process_person_profile=!1;if(h&&f?.sessionId&&!d.$session_id)d.$session_id=f.sessionId;let g=this._shouldSendMinimalFlagCalledEvent(s,d)?Te(d):d,m=this._runBeforeSend({distinctId:p,event:s,properties:g,groups:n,flags:o,sendFeatureFlags:l,timestamp:a,disableGeoip:c,uuid:u});if(!m)return Promise.reject(null);let b=await Promise.resolve().then(async()=>{if(o){if(l)console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.");return o._getEventProperties()}if(l){Ut("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let S=typeof l=="object"?l:void 0,E=await this.getFeatureFlagsForEvent(m.distinctId,n,c,S);return Ul(E)}return{}}).catch(()=>({})).then((S)=>{let E=m.groups||n;return{...S,...m.properties||{},...E!==void 0&&Object.keys(E).length>0?{$groups:E}:{}}});if(m.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof b.$raw_user_agent=="string"){if(Xr(b.$raw_user_agent,this.options.custom_blocked_useragents||[]))m.event="$bot_pageview",b.$browser_type="bot"}return{distinctId:m.distinctId,event:m.event,properties:b,options:{timestamp:m.timestamp,disableGeoip:m.disableGeoip,uuid:m.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let r=Array.isArray(t)?t:[t],s=e;for(let i of r)try{if(s=i(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 n=`Event '${s.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(n)}}catch(n){return this._logger.error(`Error in before_send function for event '${e.event}':`,n),null}return s}}import{AsyncLocalStorage as Bl}from"node:async_hooks";class Ur{constructor(){this.storage=new Bl}get(){return this.storage.getStore()}run(e,t,r){return this.storage.run(this.resolve(e,r),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let r=this.get()||{};return{distinctId:e.distinctId??r.distinctId,sessionId:e.sessionId??r.sessionId,properties:{...r.properties||{},...e.properties||{}}}}}import{AsyncLocalStorage as jl}from"node:async_hooks";class Br{active(){return this._storage.getStore()}with(e,t){return this._storage.run(e,t)}constructor(){this._storage=new jl}}import{gzip as Vl}from"node:zlib";import{promisify as zl}from"node:util";var ql=zl(Vl);async function sn(e,t=!0){try{let r=await ql(e);return new Uint8Array(r)}catch(r){if(t)console.error("Failed to gzip compress data",r);return null}}import{platform as Gl,release as Kl}from"node:os";function nn(){let e,t;try{e=Gl(),t=Kl()}catch{}return br(e,t)}var on="posthog-node";function Hl(e,{organization:t,projectId:r,prefix:s,severityAllowList:i=["error"],sendExceptionsToPostHog:n=!0}={}){return(o)=>{if(!(i==="*"||i.includes(o.level)))return o;if(!o.tags)o.tags={};let a=o.tags[an.POSTHOG_ID_TAG];if(a===void 0)return o;let c=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${a}`,c).toString();o.tags["PostHog Person URL"]=u;let f=o.exception?.values||[],h=f.map((g)=>({...g,stacktrace:g.stacktrace?{...g.stacktrace,type:"raw",frames:(g.stacktrace.frames||[]).map((m)=>({...m,platform:"node:javascript"}))}:void 0})),p={$exception_message:f[0]?.value||o.message,$exception_type:f[0]?.type,$exception_level:o.level,$exception_list:h,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:f[0]?.value||o.message,$sentry_exception_type:f[0]?.type,$sentry_tags:o.tags},d=Ds();if(d)p.$release_id=d;if(t&&r)p.$sentry_url=(s||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id;if(n)e.capture({event:"$exception",distinctId:a,properties:p});return o}}class an{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,t,r,s,i){this.name=on,this.name=on,this.setupOnce=function(n,o){let l=o()?.getClient()?.getDsn()?.projectId;n(Hl(e,{organization:t,projectId:l,prefix:r,severityAllowList:s,sendExceptionsToPostHog:i??!0}))}}}class jr extends kr{getLibraryId(){return"posthog-node"}compressPayload(e){return sn(e,this.isDebug)}initializeContext(){return new Ur}initializeSpanContextManager(){return new Br}hostResourceAttributes(){return nn()}createErrorPropertiesBuilder(){return new at([new Ns,new ct,new dt,new ut,new ht],Os("node:javascript",Ps),[zr(),(e)=>Ti(e,void 0,this._logger),Li()])}}function Ig(e,t){return new jr(e,{host:"https://data.cline.bot",...t})}class Wl{client;settings;logger;constructor(e){if(!e.client)throw Error("PostHog client is required for feature flags");this.logger=e.config.logger,this.settings={enabled:!0},this.client=e.client}async getAllFlagsAndPayloads(e){if(!this.enabled)return;let t=this.resolveDistinctId(e.context);if(!t)return this.logger?.log?.("PostHog feature flags requested without a distinct ID"),{};try{return await this.client.getAllFlagsAndPayloads(t,{flagKeys:e.flagKeys?[...e.flagKeys]:void 0})}catch(r){return this.logger?.error?.("Error getting PostHog feature flags",{error:r}),{}}}get enabled(){return this.settings.enabled}getSettings(){return{...this.settings}}async dispose(){try{await this.client.shutdown()}catch(e){this.logger?.error?.("Error shutting down PostHog feature flags client",{error:e})}}resolveDistinctId(e){return e?.distinctId?.trim()||e?.userId?.trim()||void 0}}export{Wl as PostHogFeatureFlagsProvider,Ig as buildClinePostHogClient};
@@ -0,0 +1 @@
1
+ import{Gi,Gn,Ve,ii}from"../../index-e2q4azd9.js";import"../../index-f2mvvryf.js";import{Jr,li,$i,os,rs,ss,cs}from"../../index-28c7m0fv.js";import{kn,Di}from"../../index-6k6ep10s.js";import{Jo}from"../../index-9qkpjy7x.js";import{po}from"../../index-91p1ghfk.js";import{Wt,fa,mn}from"../../index-54eea0ex.js";import"../../index-1f8vb421.js";import{R}from"../../index-rtzf3vvk.js";import{v,e,r,o,t,on,s,je}from"../../index-mcnngj50.js";import{existsSync as J,mkdirSync as Q,readFileSync as X,writeFileSync as Y}from"node:fs";import{resolve as Z}from"node:path";var ee=v(Jr(),1),E=v(li(),1);var F=v(li(),1),k=v(os(),1),z=v(rs(),1),B=v(po(),1),G=v(fa(),1),y=v(ss(),1),P=v(cs(),1),A=v(mn(),1),U=v(Jo(),1),S=v(Wt(),1);import{mkdirSync as He,readFileSync as ne,statSync as ae,writeFileSync as We}from"node:fs";var te="machine-id",N,M=!1;function re(){if(!M)N=V(),M=!0;return N??D()}function L(i){let n=i?.trim();if(n)return n;let a=V();if(a)return a;return D()}function ie(){let i=ee;return i.machineIdSync??i.default?.machineIdSync}function V(){try{let i=ie();if(!i)return;return i().trim()||void 0}catch{return}}function D(){let i=Ve(),n=Z(i,te);try{if(J(n)){let l=X(n,"utf8").trim();if(l.length>0)return l}}catch{}let a=`cl-${R()}`;try{Q(i,{recursive:!0}),Y(n,a,"utf8")}catch{}return a}class j{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor(i){this.name=i.name??"OpenTelemetryAdapter",this.metadata={...i.metadata},this.meterProvider=i.meterProvider,this.loggerProvider=i.loggerProvider,this.meter=i.meterProvider?.getMeter("cline")??null,this.logger=i.loggerProvider?.getLogger("cline")??null,this.enabled=i.enabled??!0,this.distinctId=i.distinctId,this.commonProperties=i.commonProperties?{...i.commonProperties}:{}}emit(i,n){if(!this.isEnabled())return;this.emitLog(i,n,!1)}emitRequired(i,n){this.emitLog(i,n,!0)}recordCounter(i,n,a,l,d=!1){if(!this.meter||!d&&!this.isEnabled())return;let c=this.counters.get(i);if(!c)c=this.meter.createCounter(i,l?{description:l}:void 0),this.counters.set(i,c);c.add(n,this.flattenProperties(this.buildAttributes(a)))}recordHistogram(i,n,a,l,d=!1){if(!this.meter||!d&&!this.isEnabled())return;let c=this.histograms.get(i);if(!c)c=this.meter.createHistogram(i,l?{description:l}:void 0),this.histograms.set(i,c);c.record(n,this.flattenProperties(this.buildAttributes(a)))}recordGauge(i,n,a,l,d=!1){if(!this.meter||!d&&!this.isEnabled())return;let c=this.buildAttributes(a),u=JSON.stringify(c),p=this.gaugeValues.get(i);if(n===null){if(p){if(p.delete(u),p.size===0)this.gaugeValues.delete(i),this.gauges.delete(i)}return}let m=p;if(!m)m=new Map,this.gaugeValues.set(i,m);if(!this.gauges.has(i)){let h=this.meter.createObservableGauge(i,l?{description:l}:void 0);h.addCallback((g)=>{for(let x of this.snapshotGaugeSeries(i))g.observe(x.value,this.flattenProperties(x.attributes))}),this.gauges.set(i,h)}m.set(u,{value:n,attributes:c})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId(i){this.distinctId=i}setCommonProperties(i){this.commonProperties={...i}}updateCommonProperties(i){this.commonProperties={...this.commonProperties,...i}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog(i,n,a){if(!this.logger)return;let l=this.flattenProperties(this.buildAttributes(n,a)),d=oe(l.severity);this.logger.emit({severityText:d.text,severityNumber:d.number,body:i,attributes:l})}buildAttributes(i,n=!1){return{...this.commonProperties,...this.metadata,...i,...this.distinctId?{distinct_id:this.distinctId}:{},...n?{_required:!0}:{}}}snapshotGaugeSeries(i){let n=this.gaugeValues.get(i);if(!n)return[];return Array.from(n.values(),(a)=>({value:a.value,attributes:a.attributes?{...a.attributes}:void 0}))}flattenProperties(i,n="",a=new WeakSet,l=0){if(!i)return{};let d={},c=100,u=10;for(let[p,m]of Object.entries(i)){if(p==="__proto__"||p==="constructor"||p==="prototype")continue;let h=n?`${n}.${p}`:p;if(m===null||m===void 0){d[h]=String(m);continue}if(Array.isArray(m)){let g=m.length>c?m.slice(0,c):m;try{d[h]=JSON.stringify(g)}catch{d[h]="[UnserializableArray]"}if(m.length>c)d[`${h}_truncated`]=!0,d[`${h}_original_length`]=m.length;continue}if(typeof m==="object"){if(m instanceof Date){d[h]=m.toISOString();continue}if(m instanceof Error){d[h]=m.message;continue}if(a.has(m)){d[h]="[Circular]";continue}if(l>=u){d[h]="[MaxDepthExceeded]";continue}a.add(m),Object.assign(d,this.flattenProperties(m,h,a,l+1));continue}if(se(m)){d[h]=m;continue}try{d[h]=JSON.stringify(m)}catch{d[h]=String(m)}}return d}}function oe(i){switch(typeof i==="string"?i.toLowerCase():i){case"trace":return{text:"TRACE",number:E.SeverityNumber.TRACE};case"debug":return{text:"DEBUG",number:E.SeverityNumber.DEBUG};case"warn":case"warning":return{text:"WARN",number:E.SeverityNumber.WARN};case"error":return{text:"ERROR",number:E.SeverityNumber.ERROR};case"fatal":return{text:"FATAL",number:E.SeverityNumber.FATAL};default:return{text:"INFO",number:E.SeverityNumber.INFO}}}function se(i){return typeof i==="string"||typeof i==="number"||typeof i==="boolean"}var I=je((i)=>Array.isArray(i)?i.filter((n)=>typeof n==="string").map((n)=>n.trim()).filter(Boolean):void 0,o(e()).optional()).transform((i)=>{if(!i)return;let n=[...new Set(i)].sort((a,l)=>a.localeCompare(l));return n.length>0?n:void 0}),le=s(["basic","agentic"]).catch("agentic"),de=on(s(Gi),t({enabled:r()}).strip()).optional(),ce=s(["plan","act"]),K=t({telemetryOptOut:r().default(!1).catch(!1),autoUpdateEnabled:r().default(!0).catch(!0),compactionStrategy:le.optional(),compactionEnabled:r().optional().catch(void 0),planActMode:ce.optional().catch(void 0),toolAutoApprove:r().optional().catch(void 0),tuiTheme:e().optional().catch(void 0),disabledTools:I.optional(),tools:de,disabledPlugins:I.optional(),disabledAgentPlugins:I.optional()}).strip().transform((i)=>{let n={autoUpdateEnabled:i.autoUpdateEnabled,telemetryOptOut:i.telemetryOptOut};if(i.compactionStrategy)n.compactionStrategy=i.compactionStrategy;if(i.compactionEnabled!==void 0)n.compactionEnabled=i.compactionEnabled;if(i.planActMode)n.planActMode=i.planActMode;if(i.toolAutoApprove!==void 0)n.toolAutoApprove=i.toolAutoApprove;if(i.tuiTheme?.trim())n.tuiTheme=i.tuiTheme.trim();if(i.disabledTools?.length)n.disabledTools=i.disabledTools;if(i.tools&&Object.keys(i.tools).length>0)n.tools=i.tools;if(i.disabledPlugins?.length)n.disabledPlugins=i.disabledPlugins;if(i.disabledAgentPlugins?.length)n.disabledAgentPlugins=i.disabledAgentPlugins;return n});function T(){return K.parse({})}var _;function ue(i){if(i.disabledTools)Object.freeze(i.disabledTools);if(i.tools){for(let n of Object.values(i.tools))Object.freeze(n);Object.freeze(i.tools)}if(i.disabledPlugins)Object.freeze(i.disabledPlugins);if(i.disabledAgentPlugins)Object.freeze(i.disabledAgentPlugins);return Object.freeze(i)}function me(i){let n;try{n=ne(i,"utf8")}catch{return{value:T(),loadFailed:!0}}try{let a=K.safeParse(JSON.parse(n));return a.success?{value:a.data,loadFailed:!1}:{value:T(),loadFailed:!0}}catch{return{value:T(),loadFailed:!0}}}function pe(){let i=ii(),n=ae(i,{throwIfNoEntry:!1}),a=n?.mtimeMs??0,l=n?.size??0,d=_;if(d&&d.path===i&&d.mtimeMs===a&&d.size===l)return d;let c=n?me(i):{value:T(),loadFailed:!1},u=ue(c.value);return _={path:i,mtimeMs:a,size:l,value:u,loadFailed:c.loadFailed},_}function he(){return pe().value}function fe(){return he().telemetryOptOut}class q{name;logger;enabled;constructor(i={}){this.name=i.name??"TelemetryLoggerSink",this.logger=i.logger,this.enabled=i.enabled??!0}emit(i,n){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:i,properties:n})}emitRequired(i,n){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:i,properties:n})}recordCounter(i,n,a,l,d){if(!d&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:i,value:n,attributes:a,description:l,required:d===!0})}recordHistogram(i,n,a,l,d){if(!d&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:i,value:n,attributes:a,description:l,required:d===!0})}recordGauge(i,n,a,l,d){if(!d&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:i,value:n,attributes:a,description:l,required:d===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class w{adapters;metadata;distinctId;deviceId;commonProperties;constructor(i={}){if(this.adapters=[...i.adapters??[]],i.logger)this.adapters.push(new q({logger:i.logger}));this.metadata={...i.metadata??{}},this.distinctId=i.distinctId,this.deviceId=i.deviceId??re(),this.commonProperties={...i.commonProperties??{}}}addAdapter(i){this.adapters.push(i)}setDistinctId(i){this.distinctId=i}setMetadata(i){this.metadata={...i}}updateMetadata(i){this.metadata={...this.metadata,...i}}setCommonProperties(i){this.commonProperties={...i}}updateCommonProperties(i){this.commonProperties={...this.commonProperties,...i}}isEnabled(){return this.adapters.some((i)=>i.isEnabled())}capture(i){let n=this.buildAttributes(i.properties);for(let a of this.adapters)a.emit(i.event,n)}captureRequired(i,n){let a=this.buildAttributes(n);for(let l of this.adapters)l.emitRequired(i,a)}recordCounter(i,n,a,l,d=!1){let c=this.buildAttributes(a);for(let u of this.adapters)u.recordCounter(i,n,c,l,d)}recordHistogram(i,n,a,l,d=!1){let c=this.buildAttributes(a);for(let u of this.adapters)u.recordHistogram(i,n,c,l,d)}recordGauge(i,n,a,l,d=!1){let c=this.buildAttributes(a);for(let u of this.adapters)u.recordGauge(i,n,c,l,d)}async flush(){await Promise.all(this.adapters.map((i)=>i.flush()))}async dispose(){await Promise.all(this.adapters.map((i)=>i.dispose()))}buildAttributes(i){let n=typeof i?.distinct_id==="string"&&i.distinct_id.trim()?i.distinct_id.trim():this.distinctId,a={...this.commonProperties,...this.metadata,...i,...n?{distinct_id:n}:{},device_id:this.deviceId};return Object.fromEntries(Object.entries(a).filter(([,l])=>l!==void 0))}}class H{distinctId;metadata;commonProperties;constructor(i={}){this.distinctId=i.distinctId,this.metadata={...i.metadata??{}},this.commonProperties={...i.commonProperties??{}}}setDistinctId(i){this.distinctId=i}setMetadata(i){this.metadata={...i}}updateMetadata(i){this.metadata={...this.metadata,...i}}setCommonProperties(i){this.commonProperties={...i}}updateCommonProperties(i){this.commonProperties={...this.commonProperties,...i}}isEnabled(){return!1}capture(i){this.resolveProperties(i.properties)}captureRequired(i,n){this.resolveProperties(n)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties(i){let n=typeof i?.distinct_id==="string"&&i.distinct_id.trim()?i.distinct_id.trim():this.distinctId,a={...this.commonProperties,...this.metadata,...i,...n?{distinct_id:n}:{}};return Object.fromEntries(Object.entries(a).filter(([,l])=>l!==void 0))}}class W{meterProvider;loggerProvider;tracerProvider;options;constructor(i={}){this.options=i;let n=G.resourceFromAttributes({...i.resourceAttributes,[S.ATTR_SERVICE_NAME]:i.serviceName??"cline",...i.serviceVersion?{[S.ATTR_SERVICE_VERSION]:i.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(n),this.loggerProvider=this.createLoggerProvider(n),this.tracerProvider=this.createTracerProvider(n),this.meterProvider)kn.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)F.logs.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(i="cline",n){return Di.getTracer(i,n??this.options.serviceVersion)}createAdapter(i){return new j({...i,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(i){let n=this.createAdapter({name:i.name,enabled:this.options.enabled,metadata:i.metadata});return new w({...i,adapters:[n],distinctId:L(i.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider(i){let n=O(this.options.metricsExporter);if(n.length===0)return null;let a=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),l=Math.min(30000,Math.floor(a*0.8)),d=n.map((c)=>Pe(c,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:a,timeout:l})).filter((c)=>c!==null);if(d.length===0)return null;return new P.MeterProvider({resource:i,readers:d})}createTracerProvider(i){let n=O(this.options.tracesExporter);if(n.length===0)return null;let a=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,l=this.options.otlpTracesHeaders??this.options.otlpHeaders,d=[],c=!1;for(let p of n){let m=Ee(p,{endpoint:a,headers:l,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(m){if(d.push(m),p!=="console")c=!0}}if(d.length===0)return null;let u=new U.NodeTracerProvider({resource:i,spanProcessors:c?[new $i,...d]:d});if(c)Gn(u);return u}createLoggerProvider(i){let n=O(this.options.logsExporter);if(n.length===0)return null;let a=n.map((l)=>{let d=be(l,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!d)return null;return new y.BatchLogRecordProcessor(d,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((l)=>l!==null);if(a.length===0)return null;return new y.LoggerProvider({resource:i,processors:a})}}function ge(i){let n=new W(i),a=n.createTelemetryService(i),l=()=>{a.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:i.enabled??!0,logsExporter:Array.isArray(i.logsExporter)?i.logsExporter.join(","):i.logsExporter,metricsExporter:Array.isArray(i.metricsExporter)?i.metricsExporter.join(","):i.metricsExporter,tracesExporter:Array.isArray(i.tracesExporter)?i.tracesExporter.join(","):i.tracesExporter,otlpProtocol:i.otlpProtocol,hasOtlpEndpoint:Boolean(i.otlpEndpoint),serviceName:i.serviceName,serviceVersion:i.serviceVersion})};if(!i.deferProviderCreatedEvent)l();return{provider:n,telemetry:a,emitProviderCreated:l}}function ve(i){if(fe())return{telemetry:new H(i)};if(i.enabled!==!0)return{telemetry:new w({...i,distinctId:L(i.distinctId)})};return ge(i)}function Ye(i){let{telemetry:n,provider:a,emitProviderCreated:l}=ve(i);return{telemetry:n,provider:a,flush:async()=>{let d=a;if(d&&typeof d.forceFlush==="function")try{await d.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([n.dispose(),a?.dispose()])},...i.deferProviderCreatedEvent&&l?{emitProviderCreated:l}:{}}}function O(i){if(!i)return[];return(Array.isArray(i)?i:i.split(",")).map((n)=>n.trim()).filter((n)=>n==="console"||n==="otlp")}function be(i,n){if(i==="console")return new y.ConsoleLogRecordExporter;if(!n.endpoint)return null;let a=C(n.endpoint,"/v1/logs");return new k.OTLPLogExporter({url:a,headers:n.headers})}function Ee(i,n){if(i==="console")return new A.SimpleSpanProcessor(new A.ConsoleSpanExporter);if(!n.endpoint)return null;let a=C(n.endpoint,"/v1/traces");return new A.BatchSpanProcessor(new B.OTLPTraceExporter({url:a,headers:n.headers}))}function Pe(i,n){if(i==="console")return new P.PeriodicExportingMetricReader({exporter:new P.ConsoleMetricExporter,exportIntervalMillis:n.interval,exportTimeoutMillis:n.timeout});if(!n.endpoint)return null;let a=C(n.endpoint,"/v1/metrics");return new P.PeriodicExportingMetricReader({exporter:new z.OTLPMetricExporter({url:a,headers:n.headers}),exportIntervalMillis:n.interval,exportTimeoutMillis:n.timeout})}function C(i,n){let a=new URL(i),l=a.pathname.endsWith("/")?a.pathname.slice(0,-1):a.pathname;return a.pathname=l.endsWith(n)?l:`${l}${n}`,a.toString()}var b={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};function ye(i){let n=[i?.name,i?.platform].filter((a)=>typeof a==="string").join(" ").toLowerCase();if(!n)return;if(n.includes("vscode")||n.includes("visual studio code"))return b.VSCODE;if(n.includes("jetbrains")||n.includes("webstorm")||n.includes("intellij")||n.includes("pycharm")||n.includes("goland")||n.includes("clion")||n.includes("rider")||n.includes("android studio"))return b.JETBRAINS;if(n.includes("neovim"))return b.NEOVIM;if(n.includes("kanban"))return b.KANBAN;if(n.includes("desktop"))return b.DESKTOP;if(n.includes("cline-platform"))return b.WEB;if(n.includes("cline-cli")||n.includes("cline-acp"))return b.CLI;if(n.includes("cline-sdk")||n.includes("cline-core"))return b.CORE;return}function f(i){let n=i?.trim();return n?n:void 0}function Ae(i){let n=i.client,a=ye(n)??f(i.source),l=f(n.version),d=f(n.platform)??f(n.name),c=f(n.platformVersion)??l,u={cline_type:a,extension_version:l,platform:d,platform_version:c};if(i.user?.accountId===void 0)return u;let p=typeof i.user.accountId==="string"?f(i.user.accountId):void 0;return{...u,distinct_id:p??f(i.user.distinctId),user_id:p,account_id:p,account_email:p?f(i.user.email):void 0,organization_id:p?f(i.user.organizationId):void 0}}function Te(i,n){let a={},l={},d,c=(u)=>({...n,...l,...a,...u,...d?{distinct_id:d}:{}});return{setDistinctId(u){d=f(u)},setMetadata(u){a={...u}},updateMetadata(u){a={...a,...u}},setCommonProperties(u){l={...u}},updateCommonProperties(u){l={...l,...u}},isEnabled:()=>i.isEnabled(),capture:(u)=>i.capture({event:u.event,properties:c(u.properties)}),captureRequired:(u,p)=>i.captureRequired(u,c(p)),recordCounter:(u,p,m,h,g)=>i.recordCounter(u,p,c(m),h,g),recordHistogram:(u,p,m,h,g)=>i.recordHistogram(u,p,c(m),h,g),recordGauge:(u,p,m,h,g)=>i.recordGauge(u,p,c(m),h,g),flush:()=>i.flush(),dispose:async()=>{}}}function et(i,n){return Te(i,Ae(n))}export{j as OpenTelemetryAdapter,W as OpenTelemetryProvider,et as createClientScopedTelemetryService,Ye as createConfiguredTelemetryHandle,ve as createConfiguredTelemetryService,ge as createOpenTelemetryTelemetryService,Te as createScopedTelemetryService,Ae as resolveClientTelemetryProperties,re as resolveCoreDeviceId,L as resolveCoreDistinctId};
@@ -0,0 +1 @@
1
+ import{mp,hp}from"./index-6k6ep10s.js";import{i}from"./index-mcnngj50.js";var v=i(function(y,s){var{defineProperty:c,getOwnPropertyDescriptor:_,getOwnPropertyNames:k}=Object,l=Object.prototype.hasOwnProperty,u=(t,e)=>{for(var o in e)c(t,o,{get:e[o],enumerable:!0})},d=(t,e,o,n)=>{if(e&&typeof e==="object"||typeof e==="function"){for(let r of k(e))if(!l.call(t,r)&&r!==o)c(t,r,{get:()=>e[r],enumerable:!(n=_(e,r))||n.enumerable})}return t},O=(t)=>d(c({},"__esModule",{value:!0}),t),f={};u(f,{refreshToken:()=>j});s.exports=O(f);var p=mp(),a=hp();async function j(t){let e=t?.project,o=t?.team;if(!e&&!o){let r=(0,a.findProjectInfo)();e=r.projectId,o=r.teamId}else if(!e||!o){let r=(0,a.findProjectInfo)();e=e??r.projectId,o=o??r.teamId}if(!e)throw new p.VercelOidcTokenError("Failed to refresh OIDC token: No project specified. Try re-linking your project with `vc link`");let n=(0,a.loadToken)(e);if(!n||(0,a.isExpired)((0,a.getTokenPayload)(n.token),t?.expirationBufferMs)){let r=await(0,a.getVercelToken)({expirationBufferMs:t?.expirationBufferMs});if(n=await(0,a.getVercelOidcToken)(r,e,o),!n)throw new p.VercelOidcTokenError("Failed to refresh OIDC token");(0,a.saveToken)(n,e)}process.env.VERCEL_OIDC_TOKEN=n.token;return}});export default v();
@@ -0,0 +1 @@
1
+ import{hp}from"./index-6k6ep10s.js";export default hp();
@@ -0,0 +1 @@
1
+ import{fl,yl}from"./index-n2srkkh0.js";import"./index-f2mvvryf.js";import{qv,uo,ct}from"./index-28c7m0fv.js";import"./index-rmhzyxr8.js";function g(e,o){return{...e?{projectId:e}:{},clientOptions:{transporterOptions:{fetchImplementation:o}}}}function a(e,o){let t=e?.[o];return typeof t==="string"&&t.trim().length>0?t:void 0}function p(e,o,t){let r=e?.[o];if(!r||typeof r!=="object"||Array.isArray(r))return;let n=r[t];return typeof n==="string"&&n.trim().length>0?n:void 0}async function v(e,o){let t=a(e.options,"project")??a(e.options,"projectId")??p(e.options,"gcp","projectId")??"",r=a(e.options,"location")??a(e.options,"region")??p(e.options,"gcp","region")??"us-central1",n=t||void 0,d=uo(e.fetch),u=g(n,d);if(qv(o.model.id)){let i=yl({project:t,location:r,googleAuthOptions:u,baseURL:e.baseUrl,headers:e.headers,fetch:d});return{operations:{language:(s)=>i(s)}}}let l=fl({project:t,location:r,apiKey:n?void 0:await ct(e),googleAuthOptions:n?u:void 0,baseURL:e.baseUrl,headers:e.headers,fetch:d});return{buildModelTools:(i)=>{let s={};for(let c of i)if(c.name==="web_search")s.web_search={tool:l.tools.googleSearch({})};return s},operations:{language:(i)=>l(i),imageGeneration:(i)=>l.image(i)}}}export{v as createVertexProviderModule};