failproofai 1.0.14 → 1.0.15

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 (164) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/build-manifest.json +13 -13
  3. package/.next/standalone/.next/prerender-manifest.json +3 -3
  4. package/.next/standalone/.next/required-server-files.json +1 -1
  5. package/.next/standalone/.next/server/app/_global-error/page/build-manifest.json +2 -2
  6. package/.next/standalone/.next/server/app/_global-error/page/server-reference-manifest.json +1 -1
  7. package/.next/standalone/.next/server/app/_global-error/page.js.nft.json +1 -1
  8. package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  9. package/.next/standalone/.next/server/app/_global-error.html +1 -1
  10. package/.next/standalone/.next/server/app/_global-error.rsc +2 -2
  11. package/.next/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +2 -2
  12. package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +2 -2
  13. package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  14. package/.next/standalone/.next/server/app/_not-found/page/build-manifest.json +2 -2
  15. package/.next/standalone/.next/server/app/_not-found/page/server-reference-manifest.json +1 -1
  16. package/.next/standalone/.next/server/app/_not-found/page.js.nft.json +1 -1
  17. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  18. package/.next/standalone/.next/server/app/_not-found.html +1 -1
  19. package/.next/standalone/.next/server/app/_not-found.rsc +3 -3
  20. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
  21. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
  22. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  23. package/.next/standalone/.next/server/app/api/audit/invite/route.js.nft.json +1 -1
  24. package/.next/standalone/.next/server/app/api/audit/run/route.js.nft.json +1 -1
  25. package/.next/standalone/.next/server/app/api/audit/status/route.js.nft.json +1 -1
  26. package/.next/standalone/.next/server/app/api/auth/login-request/route.js.nft.json +1 -1
  27. package/.next/standalone/.next/server/app/api/auth/login-verify/route.js.nft.json +1 -1
  28. package/.next/standalone/.next/server/app/api/auth/logout/route.js.nft.json +1 -1
  29. package/.next/standalone/.next/server/app/api/auth/status/route.js.nft.json +1 -1
  30. package/.next/standalone/.next/server/app/api/download/[project]/[session]/route.js.nft.json +1 -1
  31. package/.next/standalone/.next/server/app/audit/page/build-manifest.json +2 -2
  32. package/.next/standalone/.next/server/app/audit/page/server-reference-manifest.json +2 -2
  33. package/.next/standalone/.next/server/app/audit/page.js.nft.json +1 -1
  34. package/.next/standalone/.next/server/app/audit/page_client-reference-manifest.js +1 -1
  35. package/.next/standalone/.next/server/app/index.html +1 -1
  36. package/.next/standalone/.next/server/app/index.rsc +3 -3
  37. package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
  38. package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +3 -3
  39. package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  40. package/.next/standalone/.next/server/app/page/build-manifest.json +2 -2
  41. package/.next/standalone/.next/server/app/page/server-reference-manifest.json +1 -1
  42. package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
  43. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  44. package/.next/standalone/.next/server/app/policies/page/build-manifest.json +2 -2
  45. package/.next/standalone/.next/server/app/policies/page/server-reference-manifest.json +14 -14
  46. package/.next/standalone/.next/server/app/policies/page.js.nft.json +1 -1
  47. package/.next/standalone/.next/server/app/policies/page_client-reference-manifest.js +1 -1
  48. package/.next/standalone/.next/server/app/project/[name]/page/build-manifest.json +2 -2
  49. package/.next/standalone/.next/server/app/project/[name]/page/server-reference-manifest.json +1 -1
  50. package/.next/standalone/.next/server/app/project/[name]/page.js.nft.json +1 -1
  51. package/.next/standalone/.next/server/app/project/[name]/page_client-reference-manifest.js +1 -1
  52. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/build-manifest.json +2 -2
  53. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/react-loadable-manifest.json +2 -2
  54. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/server-reference-manifest.json +2 -2
  55. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page.js.nft.json +1 -1
  56. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page_client-reference-manifest.js +1 -1
  57. package/.next/standalone/.next/server/app/projects/page/build-manifest.json +2 -2
  58. package/.next/standalone/.next/server/app/projects/page/server-reference-manifest.json +1 -1
  59. package/.next/standalone/.next/server/app/projects/page.js.nft.json +1 -1
  60. package/.next/standalone/.next/server/app/projects/page_client-reference-manifest.js +1 -1
  61. package/.next/standalone/.next/server/app/settings/page/build-manifest.json +2 -2
  62. package/.next/standalone/.next/server/app/settings/page/server-reference-manifest.json +8 -8
  63. package/.next/standalone/.next/server/app/settings/page.js.nft.json +1 -1
  64. package/.next/standalone/.next/server/app/settings/page_client-reference-manifest.js +1 -1
  65. package/.next/standalone/.next/server/chunks/[root-of-the-server]__048f1wnr8pysf._.js +2 -2
  66. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1oclamblhzhrf._.js +1 -1
  67. package/.next/standalone/.next/server/chunks/_0tovk6q0miud6._.js +1 -1
  68. package/.next/standalone/.next/server/chunks/_0trp3ycqv17cl._.js +1 -1
  69. package/.next/standalone/.next/server/chunks/_1vslkoe35wok6._.js +1 -1
  70. package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_01r25oigsgz07._.js +1 -1
  71. package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_09z9-p77cu37y._.js +1 -1
  72. package/.next/standalone/.next/server/chunks/package_json_[json]_cjs_1nxcc4vkpxxu7._.js +1 -1
  73. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__1xwr4hi-on27i._.js → [root-of-the-server]__05-glpesefmmi._.js} +2 -2
  74. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__08ch3staq3ejw._.js +1 -1
  75. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0bigvy9xmv2ka._.js +1 -1
  76. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0ezoipo-r7_5k._.js +1 -1
  77. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0h86bl2qf0k_o._.js +1 -1
  78. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0pia5h3p8re4c._.js +1 -1
  79. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1-ey9fgesfbc0._.js +1 -1
  80. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__15usvs-ms-0hf._.js +1 -1
  81. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__16gb3_92zvk5x._.js +1 -1
  82. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1avi2kypusyb_._.js +1 -1
  83. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1r7drlqli-ado._.js +1 -1
  84. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1vxwetblyf8vp._.js +1 -1
  85. package/.next/standalone/.next/server/chunks/ssr/_0eoura3_9gjb-._.js +1 -1
  86. package/.next/standalone/.next/server/chunks/ssr/{_0p1cb69sml__f._.js → _0ge1hz9485xpp._.js} +2 -2
  87. package/.next/standalone/.next/server/chunks/ssr/_0pedwblqdoh58._.js +1 -1
  88. package/.next/standalone/.next/server/chunks/ssr/_1_ozgifqv1ssi._.js +1 -1
  89. package/.next/standalone/.next/server/chunks/ssr/_1djqs9i27e4kg._.js +1 -1
  90. package/.next/standalone/.next/server/chunks/ssr/_1v4_ul3sj2lq_._.js +1 -1
  91. package/.next/standalone/.next/server/chunks/ssr/_next-internal_server_app_policies_page_actions_1sp2-yo5_vm5f.js +2 -2
  92. package/.next/standalone/.next/server/chunks/ssr/app_actions_get-scheduled-audit_ts_0ei9snixb5fd-._.js +1 -1
  93. package/.next/standalone/.next/server/chunks/ssr/app_audit__components_audit-dashboard_tsx_0p9ud47q0xq5w._.js +1 -1
  94. package/.next/standalone/.next/server/chunks/ssr/app_global-error_tsx_1kp6l3x33jqb6._.js +1 -1
  95. package/.next/standalone/.next/server/chunks/ssr/app_policies_hooks-client_tsx_19dqvpcz0uxur._.js +1 -1
  96. package/.next/standalone/.next/server/chunks/ssr/app_settings_02tf1h47jmhhd._.js +1 -1
  97. package/.next/standalone/.next/server/chunks/ssr/{node_modules_html-to-image_es_index_0r9i9nq3-ei-l.js → node_modules_html-to-image_es_index_0e3yg5gbcfsai.js} +1 -1
  98. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_0bz67659f5z-3._.js +1 -1
  99. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_1khq67j4vo9y4._.js +1 -1
  100. package/.next/standalone/.next/server/chunks/ssr/node_modules_posthog-node_dist_entrypoints_index_node_mjs_11bnuznb72p7z._.js +1 -1
  101. package/.next/standalone/.next/server/chunks/ssr/package_json_[json]_cjs_013tntikdft59._.js +1 -1
  102. package/.next/standalone/.next/server/middleware-build-manifest.js +13 -13
  103. package/.next/standalone/.next/server/pages/404.html +1 -1
  104. package/.next/standalone/.next/server/pages/500.html +1 -1
  105. package/.next/standalone/.next/server/preview-props.json +3 -3
  106. package/.next/standalone/.next/server/server-reference-manifest.js +1 -1
  107. package/.next/standalone/.next/server/server-reference-manifest.json +23 -23
  108. package/.next/standalone/.next/static/chunks/{3hk5y4kny2ktd.js → 05g1pu2r8o5q3.js} +1 -1
  109. package/.next/standalone/.next/static/chunks/{2zlfhyqvlvf7o.js → 098vx6twrn-vk.js} +1 -1
  110. package/.next/standalone/.next/static/chunks/0oxlfb02aqo3e.js +1 -0
  111. package/.next/standalone/.next/static/chunks/{110hwwc6agsr8.js → 0p14j2e6dnj1x.js} +1 -1
  112. package/.next/standalone/.next/static/chunks/12ys9uaq6i1h2.js +6 -0
  113. package/.next/standalone/.next/static/chunks/{435eshlryosz1.js → 1osrmi14e2jub.js} +1 -1
  114. package/.next/standalone/.next/static/chunks/2o8j51ujh1ox4.js +1 -0
  115. package/.next/standalone/.next/static/chunks/2zwsbp8xyfv__.js +1 -0
  116. package/.next/standalone/.next/static/chunks/{2wye36b3mbzpa.js → 34rjkinfk6d4p.js} +1 -1
  117. package/.next/standalone/.next/static/chunks/{2wh64znsc_mo2.js → 38lnk75xvqiug.js} +1 -1
  118. package/.next/standalone/.next/static/chunks/3d6_vjbvr0c2n.js +1 -0
  119. package/.next/standalone/assets/logos/failproof-dark.png +0 -0
  120. package/.next/standalone/assets/logos/failproof-light.png +0 -0
  121. package/.next/standalone/fp-cloud-cli/CHANGELOG.md +24 -3
  122. package/.next/standalone/fp-cloud-cli/fp_cli/_version.py +1 -1
  123. package/.next/standalone/fp-cloud-cli/uv.lock +6 -6
  124. package/.next/standalone/hermes-plugin/plugin.yaml +1 -1
  125. package/.next/standalone/node_modules/@next/env/package.json +1 -1
  126. package/.next/standalone/node_modules/next/dist/build/swc/index.js +1 -1
  127. package/.next/standalone/node_modules/next/dist/compiled/next-server/app-page-turbo-experimental.runtime.prod.js +1 -1
  128. package/.next/standalone/node_modules/next/dist/compiled/next-server/app-page-turbo.runtime.prod.js +1 -1
  129. package/.next/standalone/node_modules/next/dist/compiled/next-server/app-route-turbo.runtime.prod.js +1 -1
  130. package/.next/standalone/node_modules/next/dist/lib/patch-incorrect-lockfile.js +3 -3
  131. package/.next/standalone/node_modules/next/dist/server/app-render/async-local-storage.js +1 -1
  132. package/.next/standalone/node_modules/next/dist/server/base-http/node.js +7 -2
  133. package/.next/standalone/node_modules/next/dist/server/config.js +1 -1
  134. package/.next/standalone/node_modules/next/dist/server/dev/hot-reloader-turbopack.js +2 -2
  135. package/.next/standalone/node_modules/next/dist/server/dev/hot-reloader-webpack.js +1 -1
  136. package/.next/standalone/node_modules/next/dist/server/lib/app-info-log.js +1 -1
  137. package/.next/standalone/node_modules/next/dist/server/lib/router-server.js +1 -1
  138. package/.next/standalone/node_modules/next/dist/server/lib/start-server.js +1 -1
  139. package/.next/standalone/node_modules/next/dist/server/lib/trace/tracer.js +1 -1
  140. package/.next/standalone/node_modules/next/dist/server/use-cache/use-cache-wrapper.js +1 -1
  141. package/.next/standalone/node_modules/next/dist/telemetry/anonymous-meta.js +1 -1
  142. package/.next/standalone/node_modules/next/dist/telemetry/events/swc-load-failure.js +1 -1
  143. package/.next/standalone/node_modules/next/dist/telemetry/events/version.js +2 -2
  144. package/.next/standalone/node_modules/next/package.json +10 -10
  145. package/.next/standalone/package.json +10 -10
  146. package/.next/standalone/sdk/python/uv.lock +18 -18
  147. package/.next/standalone/sdk/typescript/integration/fixtures/nextjs/package-lock.json +40 -40
  148. package/.next/standalone/sdk/typescript/integration/fixtures/nextjs/package.json +1 -1
  149. package/.next/standalone/server.js +1 -1
  150. package/README.md +174 -83
  151. package/dist/cli.mjs +11 -11
  152. package/dist/worker.mjs +1 -1
  153. package/hermes-plugin/plugin.yaml +1 -1
  154. package/openclaw-plugin/daemon-client.js +95 -26
  155. package/openclaw-plugin/hooks.js +4 -1
  156. package/package.json +10 -10
  157. package/.next/standalone/.next/static/chunks/107jrtkeylnrv.js +0 -6
  158. package/.next/standalone/.next/static/chunks/19e9khxgv8fb8.js +0 -1
  159. package/.next/standalone/.next/static/chunks/2codb6nb412m9.js +0 -1
  160. package/.next/standalone/.next/static/chunks/2maurwweshrsj.js +0 -1
  161. package/.next/standalone/.next/static/chunks/3v49ogp389dun.js +0 -1
  162. /package/.next/standalone/.next/static/{-iBiSmrLiylRKLAg77zlQ → -AugwIGiiIYcahO4J7mdM}/_buildManifest.js +0 -0
  163. /package/.next/standalone/.next/static/{-iBiSmrLiylRKLAg77zlQ → -AugwIGiiIYcahO4J7mdM}/_clientMiddlewareManifest.js +0 -0
  164. /package/.next/standalone/.next/static/{-iBiSmrLiylRKLAg77zlQ → -AugwIGiiIYcahO4J7mdM}/_ssgManifest.js +0 -0
@@ -1,3 +1,3 @@
1
- module.exports=[28864,e=>{"use strict";let t,r,i,s,n,a;var o,l=e.i(14747);function u(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var c=((o={}).AnonymousId="anonymous_id",o.DistinctId="distinct_id",o.Props="props",o.EnablePersonProcessing="enable_person_processing",o.PersonMode="person_mode",o.FeatureFlagDetails="feature_flag_details",o.FeatureFlags="feature_flags",o.FeatureFlagPayloads="feature_flag_payloads",o.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",o.BootstrapFeatureFlags="bootstrap_feature_flags",o.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",o.OverrideFeatureFlags="override_feature_flags",o.Queue="queue",o.AiQueue="ai_queue",o.AiCaptureQueue="ai_capture_queue",o.LogsQueue="logs_queue",o.OptedOut="opted_out",o.SessionId="session_id",o.SessionStartTimestamp="session_start_timestamp",o.SessionLastTimestamp="session_timestamp",o.PersonProperties="person_properties",o.GroupProperties="group_properties",o.InstalledAppBuild="installed_app_build",o.InstalledAppVersion="installed_app_version",o.SessionReplay="session_replay",o.PushRegistered="push_registered",o.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",o.SurveyLastSeenDate="survey_last_seen_date",o.SurveysInProgress="surveys_in_progress",o.SurveysSeen="surveys_seen",o.Surveys="surveys",o.RemoteConfig="remote_config",o.FlagsEndpointWasHit="flags_endpoint_was_hit",o.DeviceId="device_id",o);let h={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",LOCAL_EVALUATION_INCONCLUSIVE:"local_evaluation_inconclusive",QUOTA_LIMITED:"quota_limited",TIMEOUT:"timeout",CONNECTION_ERROR:"connection_error",UNKNOWN_ERROR:"unknown_error",apiError:e=>`api_error_${e}`};function d(e,t){return -1!==e.indexOf(t)}function f(e){let t=[];return JSON.stringify(e,function(e,r){if("bigint"==typeof r)return r.toString();if("function"!=typeof r&&"symbol"!=typeof r){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&"object"==typeof r){for(;t.length>0&&t[t.length-1]!==this;)t.pop();if(t.includes(r))return"[Circular]";t.push(r)}return r}})??"null"}let p=Array.isArray,g=Object.prototype;g.hasOwnProperty;let m=g.toString,y=p||function(e){return"[object Array]"===m.call(e)},_=e=>void 0===e,v=e=>"[object String]"==m.call(e),b=e=>v(e)&&0===e.trim().length,w=e=>null===e,x=e=>_(e)||w(e);function S(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 E(e,Error)}}function F(e){return"u">typeof Event&&E(e,Event)}function E(e,t){try{return e instanceof t}catch{return!1}}let P=[!0,"true",1,"1","yes"],I=[!1,"false",0,"0","no"];function A(e,t,r){return e&&r?t.length===Object.keys(r).length&&t.every(t=>e[t]===r[t]):e===r}class k{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){let r=t&&t.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(r,t,0).apply(e),s=this.buildParsingContext(t),n=this.parseStacktrace(i,s);return{$exception_list:this.convertToExceptionList(n,r),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&y(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,i;if(null!=e.cause&&(r=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack)try{i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)}catch{}return{...e,cause:r,stack:i,errors:e.errors?.map(e=>this.parseStacktrace(e,t))}}applyChunkIds(e,t){return e.map(e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e))}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 e of this.modifiers)t=await e(t);return t}convertToExceptionList(e,t){let r=[],i=(e,s,n)=>{let a=r.length,o=void 0===s?{type:"string"==typeof t.type&&t.type.length>0?t.type:"generic",..."boolean"==typeof t.handled?{handled:t.handled}:void 0===t.handled?{handled:!0}:{},synthetic:"boolean"==typeof t.synthetic?t.synthetic:e.synthetic,exception_id:a}:{type:"chained",source:n,synthetic:e.synthetic,exception_id:a,parent_id:s},l={type:e.type,value:e.value,mechanism:o};for(let t of(e.stack&&(l.stacktrace={type:"raw",frames:e.stack}),r.push(l),e.cause&&i(e.cause,a,"cause"),e.errors??[]))i(t,a,"member")};return i(e),r}buildParsingContext(e){return{chunkIdMap:function(e){let n=globalThis._posthogChunkIds,a=globalThis._debugIds;if(!n&&!a)return;let o=n?Object.keys(n):[],l=a?Object.keys(a):[];if(s&&A(n,o,r)&&A(a,l,i))return s;r=n?{...n}:void 0,i=a?{...a}:void 0,s={},t??={};let u=(r,i)=>{for(let n of r){let r=i[n];if(!r)continue;let a=t?.[n];if(a){s[a]=r;continue}let o=e(n);for(let e=o.length-1;e>=0;e--){let i=o[e]?.filename;if(i){s[i]=r,t[n]=i;break}}}};return a&&u(l,a),n&&u(o,n),s}(this.stackParser),skipFirstLines:e.skipFirstLines??1}}getAggregateErrors(e){try{if(S(e)){let t=Object.getPrototypeOf(e);for(let r=0;t&&r<100;r++){let r=Object.getOwnPropertyDescriptor(t,"constructor")?.value;if("function"==typeof r&&"AggregateError"===r.name){let t=e.errors;return y(t)?t:void 0}t=Object.getPrototypeOf(t)}}}catch{}}buildCoercingContext(e,t,r=0){let i=0,s=0,n=!1,a=new Set,o=[],l={},u=(e,t,r=0)=>{let u,h,d=c(t,r),f=d.apply;if(d.apply=t=>{o.push(e);try{return f(t)}finally{o.pop()}},r>4||r>0&&-1!==o.indexOf(e))return this.coerceFallback(d);let p="object"==typeof e&&null!==e||"function"==typeof e;if(0===r&&i>=50||p&&a.has(e))return;p&&a.add(e),0===r&&i++;let g=this.getAggregateErrors(e);n||=!!g;try{if(!(u=this.applyCoercers(e,d)))throw l}catch(e){if(e===l){0===r&&i--;return}if(!n)throw e;u=this.coerceFallback(d)}if(!g||i>=50)return u;try{h=g.length}catch{return u}if(!Number.isInteger(h)||h<0||h>0xffffffff)return u;let m=[];for(let e=0;i<50&&s<1e3&&e<h;e++){let r;s++;try{r=d.next(g[e])}catch{i++,r=this.coerceFallback(c(t+1))}r&&m.push(r)}return{...u,errors:m}},c=(r,i=0)=>({...t,syntheticException:0==r?t.syntheticException:void 0,mechanism:0==r?e:{},apply:e=>{let t=u(e,r,i+1);if(!t)throw l;return t},next:e=>u(e,r+1)}),h=c(r);return{...h,apply:e=>u(e,r)??this.coerceFallback(h)}}}e.s(["ErrorPropertiesBuilder",0,k],80446),e.i(80446);let C=/^([a-z][a-z0-9.+-]+):/i,$=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function O(e,t,r,i,s){let n={platform:e,filename:t,function:"<anonymous>"===r?"?":r,in_app:function(e){if(!e||"<anonymous>"===e)return!1;let t=C.exec(e);return!t||$.includes(t[1].toLowerCase())}(t)};return _(i)||(n.lineno=i),_(s)||(n.colno=s),n}let T=(e,t)=>{let r=-1!==e.indexOf("safari-extension"),i=-1!==e.indexOf("safari-web-extension");return r||i?[-1!==e.indexOf("@")?e.split("@")[0]:"?",r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},M=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,R=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,j=/\((\S*)(?::(\d+))(?::(\d+))\)/,D=(e,t)=>{let r=M.exec(e);if(r){let[,e,i,s]=r;return O(t,e,"?",+i,+s)}let i=R.exec(e);if(i){if(i[2]&&0===i[2].indexOf("eval")){let e=j.exec(i[2]);e&&(i[2]=e[1],i[3]=e[2],i[4]=e[3])}let[e,r]=T(i[1]||"?",i[2]);return O(t,r,e,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},L=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,B=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,N=(e,t)=>{let r=L.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let e=B.exec(r[3]);e&&(r[1]=r[1]||"eval",r[3]=e[1],r[4]=e[2],r[5]="")}let e=r[3],i=r[1]||"?";return[i,e]=T(i,e),O(t,e,i,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}},q=/\(error: (.*)\)/;function U(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function H(e,t){let r=t.start;for(;r>0&&U(e[r-1],e[r-1+t.length]);)r--;return t.start-r}function K(e,t){let r=t.start+t.length,i=r;for(;i<e.length&&U(e[i],e[i-t.length]);)i++;return i-r}function V(e,...t){return(r,i=0)=>{let s=[],n=r.split("\n"),a=Math.min(n.length,i+1e3),o=[];for(let r=i;r<a;r++){let i=n[r];if(i.length>1024)continue;let a=q.test(i)?i.replace(q,"$1"):i;if(!a.match(/\S*Error: /)){for(let r of t){let t=r(a,e);if(t){s.push(t);let e=function(e){for(let t=1;t<=10;t++){let r=e.length-2*t;if(r<0)break;let i=!0;for(let s=0;s<t;s++)if(!U(e[r+s],e[r+t+s])){i=!1;break}if(i){for(let i=0;i<t;i++)e[r+i]=e[r+t+i];return e.length=r+t,{start:r,length:t}}}}(s);if(e){for(let t=o.length-1;t>=0;t--){let r=o[t];if(r.start+r.length<=e.start)break;o.pop()}o.push(e)}break}}if(function(e,t){let r=t[0],i=e.length-(r?H(e,r):0);for(let r of t)i-=K(e,r);return i}(s,o)>=50)break}}let l=[...o].sort((e,t)=>t.start-e.start),u=l[l.length-1];if(u){let e=H(s,u);for(let t of(s.splice(u.start-e,e),l))t.start-=e}for(let e of l)!function(e,t){let r=t.start+t.length,i=K(e,t);i&&e.splice(r+i===e.length?r:t.start,i)}(s,e);o.some(e=>0===e.start&&s.length===e.length)&&function(e){let t=e.map(e=>`${e.function}|${e.filename}|${e.lineno}|${e.colno}|${e.module}`),r=0;for(let e=1;e<t.length;e++)(function(e,t,r){for(let i=0;i<e.length;i++){let s=e[(t+i)%e.length],n=e[(r+i)%e.length];if(s!==n)return s<n}return!1})(t,e,r)&&(r=e);e.push(...e.splice(0,r))}(s);if(!s.length)return[];let c=Array.from(s);return c.reverse(),c.slice(0,50).map(e=>{var t;return{...e,filename:e.filename||((t=c)[t.length-1]||{}).filename,function:e.function||"?"}})}}let W=/^\s*[-]{4,}$/,z=/at (?:async (?!\((?!.*\)\s+\()))?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,G=/^Promise\.(?:all|any)$/,Q=/^index \d+$/,J=(e,t)=>{let r=e.match(z);if(r){let e,i,s,n,a;if(r[1]){let t=(s=r[1]).lastIndexOf(".");if("."===s[t-1]&&t--,t>0){e=s.slice(0,t),i=s.slice(t+1);let r=e.indexOf(".Module");r>0&&(s=s.slice(r+1),e=e.slice(0,r))}n=void 0}i&&(n=e,a=i),"<anonymous>"===i&&(a=void 0,s=void 0),void 0===s&&(a=a||"?",s=n?`${n}.${a}`:a);let o=r[2]?.startsWith("file://")?r[2].slice(7):r[2],l="native"===r[5];return o?.match(/\/[A-Z]:/)&&(o=o.slice(1)),o||!r[5]||l||(o=r[5]),G.test(s)&&Q.test(o||"")&&(o="node:internal/promise"),{filename:o?decodeURI(o):void 0,module:void 0,function:s,lineno:Z(r[3]),colno:Z(r[4]),in_app:function(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==e&&!e.includes("node_modules/")}(o||"",l),platform:t}}if(e.match(W))return{filename:e,platform:t}};function Z(e){return parseInt(e||"",10)||void 0}e.s(["createStackParser",0,V,"nodeStackLineParser",0,J],70736),e.i(70736),e.s([],29569),e.i(29569);class Y{match(e){return S(e)}coerce(e,t){let r=this.getStack(e),i=void 0===r?t.syntheticException?.stack:void 0;return{type:this.getType(e),value:this.getMessage(e,t),stack:r??i,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;return r.error&&"string"==typeof r.error.message?String(r.error.message):String(r)}getStack(e){try{let t=e.stacktrace;if("string"==typeof t&&t.length>0)return t;let r=e.stack;return"string"==typeof r&&r.length>0?r:void 0}catch{return}}}e.s(["ErrorCoercer",0,Y],11475),e.i(11475),e.s([],43179),e.i(43179);let X=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class ee{match(e){return"string"==typeof e}coerce(e,t){let[r,i]=this.getInfos(e);return{type:r??"Error",value:i??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",r=e,i=e.match(X);return i&&(t=i[1],r=i[2]),[t,r]}}e.s(["StringCoercer",0,ee],45098),e.i(45098);let et=["fatal","error","warning","log","info","debug"];function er(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let e=r.length;e>0;e--){let i=r.slice(0,e).join(", ");if(!(i.length>t)){if(e===r.length)return i;return i.length<=t?i:`${i.slice(0,t)}...`}}return""}class ei{match(e){return"object"==typeof e&&null!==e}coerce(e,t){let r=this.getErrorPropertyFromObject(e);return r?t.apply(r):{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(F(e))return e.constructor.name;let t="name"in e?e.name:void 0;return v(t)&&!b(t)?t:"Error"}getValue(e){if("name"in e&&"string"==typeof e.name){let t=`'${e.name}' captured as exception`;return"message"in e&&"string"==typeof e.message&&(t+=` with message: '${e.message}'`),t}if("message"in e&&"string"==typeof e.message)return e.message;let t=this.getObjectClassName(e),r=er(e);return`${t&&"Object"!==t?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return v(e)&&!b(e)&&et.indexOf(e)>=0}getStack(e){try{if(v(e.stacktrace)&&e.stacktrace.length>0)return e.stacktrace;return v(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(S(r))return r}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){return}}}e.s(["ObjectCoercer",0,ei],6881),e.i(6881);class es{match(e){return F(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${er(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["EventCoercer",0,es],80322),e.i(80322);class en{match(e){return null===e||"object"!=typeof e}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["PrimitiveCoercer",0,en],80049),e.i(80049),e.s([],98689),e.i(98689),e.s(["ErrorCoercer",0,Y,"EventCoercer",0,es,"ObjectCoercer",0,ei,"PrimitiveCoercer",0,en,"StringCoercer",0,ee],21854),e.i(21854);class ea{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(void 0!==t)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}}e.s(["ReduceableCache",0,ea],46986),e.i(46986);function eo(){if("u">typeof process){let e=process.env.POSTHOG_RELEASE_ID?.trim();if(e)return e}let e=globalThis._posthogReleaseId;return"string"==typeof e&&e.length>0?e:void 0}e.s([],52001),e.i(52001),e.s(["getInjectedReleaseId",0,eo],41508),e.i(41508),e.s(["ErrorCoercer",0,Y,"ErrorPropertiesBuilder",0,k,"EventCoercer",0,es,"ObjectCoercer",0,ei,"PrimitiveCoercer",0,en,"ReduceableCache",0,ea,"StringCoercer",0,ee,"createStackParser",0,V,"getInjectedReleaseId",0,eo,"nodeStackLineParser",0,J],96117);var el=e.i(96117),el=el,eu=e.i(2157),ec=e.i(12714),eh=e.i(50227),ed=e.i(1457);let ef=new el.ReduceableCache(25),ep=new el.ReduceableCache(20);async function eg(e,t=ec.open,r){let i,s={};try{i=process.cwd()}catch{}for(let t=e.length-1;t>=0;t--){var n,a;let r=e[t],o=r?.filename;!(!r||"string"!=typeof o||"number"!=typeof r.lineno||(n=o).startsWith("node:")||n.endsWith(".min.js")||n.endsWith(".min.cjs")||n.endsWith(".min.mjs")||n.startsWith("data:")||void 0!==(a=r).lineno&&a.lineno>1e4||void 0!==a.colno&&a.colno>1e3)&&((0,eh.isAbsolute)(o)||void 0!==i)&&(s[o]||(s[o]=[]),s[o].push(r.lineno))}let o=Object.keys(s);if(0==o.length)return e;let l=[];for(let e of o){let n=ev(e,i);if(void 0===n||ep.get(n))continue;let a=s[e];if(!a)continue;a.sort((e,t)=>e-t);let o=function(e){if(!e.length)return[];let t=0,r=e[0];if("number"!=typeof r)return[];let i=eb(r),s=[];for(;;){if(t===e.length-1){s.push(i);break}let r=e[t+1];if("number"!=typeof r)break;r<=i[1]?i[1]=r+7:(s.push(i),i=eb(r)),t++}return s}(a);if(o.every(e=>(function(e,t){let r=ef.get(e);if(void 0===r)return!1;for(let e=t[0];e<=t[1];e++)if(void 0===r[e])return!1;return!0})(n,e)))continue;let u=function(e,t,r){let i=e.get(t);return void 0===i?(e.set(t,r),r):i}(ef,n,{});l.push(ey(e,o,u,n,t,r))}return await Promise.all(l).catch(()=>{}),e&&e.length>0&&function(e,t,r){for(let i of e)if(i.filename&&void 0===i.context_line&&"number"==typeof i.lineno){let e=ev(i.filename,r),s=void 0===e?void 0:t.get(e);if(void 0===s)continue;!function(e,t,r){if(void 0===t.lineno||void 0===r)return;t.pre_context=[];for(let i=ew(e);i<e;i++){let e=r[i];if(void 0===e)return void e_(t);t.pre_context.push(e)}if(void 0===r[e])return e_(t);t.context_line=r[e];let i=function(e){return e+7}(e);t.post_context=[];for(let s=e+1;s<=i;s++){let e=r[s];if(void 0===e)break;t.post_context.push(e)}}(i.lineno,i,s)}}(e,ef,i),ef.reduce(),e}async function em(e,t,r){let i,s=!1;try{i=await t(e,eu.constants.O_RDONLY|eu.constants.O_NONBLOCK);let n=await i.stat();if(!n.isFile())return;if(n.size>0xa00000)return void r?.debug(`Skipping source context for oversized file ${e}: ${n.size} bytes exceeds 10485760`);return s=!0,i}catch{return}finally{i&&!s&&await i.close().catch(()=>{})}}async function ey(e,t,r,i,s,n){let a=await em(e,s,n);return void 0===a?void ep.set(i,1):new Promise(e=>{let s,n,o=!1;function l(t){o||(o=!0,t?.destroy(),a.close().then(e,e))}try{s=a.createReadStream({autoClose:!1,start:0,end:0x9fffff})}catch{ep.set(i,1),l();return}try{n=(0,ed.createInterface)({input:s})}catch{ep.set(i,1),l(s);return}let u=0,c=0,h=t[0];if(void 0===h)return void l(s);let d=h[0],f=h[1];function p(){ep.set(i,1),n.close(),n.removeAllListeners(),l(s)}s.on("error",p),n.on("error",p),n.on("close",()=>l(s)),n.on("line",e=>{if(!(++u<d)&&(r[u]=function(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let s=Math.max(t-60,0);s<5&&(s=0);let n=Math.min(s+140,i);return n>i-5&&(n=i),n===i&&(s=Math.max(n-140,0)),r=r.slice(s,n),s>0&&(r=`...${r}`),n<i&&(r+="..."),r}(e,0),u>=f)){if(c===t.length-1){n.close(),n.removeAllListeners();return}let e=t[++c];if(void 0===e){n.close(),n.removeAllListeners();return}d=e[0],f=e[1]}})})}function e_(e){delete e.pre_context,delete e.context_line,delete e.post_context}function ev(e,t){return(0,eh.isAbsolute)(e)?JSON.stringify([null,e]):void 0===t?void 0:JSON.stringify([t,e])}function eb(e){return[ew(e),e+7]}function ew(e){return Math.max(1,e-7)}class ex{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,t){for(let r of this.events[e]||[])r(t);for(let r of this.events["*"]||[])r(e,t)}}let eS=e=>void 0===e?void 0:e.variant??e.enabled,eF=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}},eE=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","bfcid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],eP=(e,t=[])=>{let r={},i=t=>{void 0!==e[t]&&(r[t]=e[t])};return eE.forEach(i),t.forEach(i),r},eI=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function eA(e,t){return"string"==typeof e&&eI.test(e)?e:t()}function ek(e,t){let r=Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function eC(e){return e?.replace(/\/+$/,"")}function e$(e){return e?e.split("#")[0]:e}async function eO(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(e=>setTimeout(e,t.retryDelay));try{return await e()}catch(e){if(r=e,!t.retryCheck(e))throw e}}throw r}function eT(){return new Date().toISOString()}function eM(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}async function eR(e,t,r){let i;try{return await Promise.race([e,new Promise((e,s)=>{i=eM(()=>{try{r?.(),e()}catch(e){s(e)}},t)})])}finally{clearTimeout(i)}}function ej(e){return Promise.all(e.map(e=>(e??Promise.resolve()).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}let eD=e=>{throw ek("NativeGzipValidationError",`Native gzip produced invalid output: ${e}`)},eL=async(e,t)=>{e.size<18&&eD("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());r.length>=2&&31===r[0]&&139===r[1]&&8===r[2]||eD("invalid-header");let i=new DataView(await e.slice(e.size-8).arrayBuffer());i.getUint32(0,!0)!==(e=>{let t=(()=>{if(n)return n;n=[];for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t=1&t?0xedb88320^t>>>1:t>>>1;n[e]=t>>>0}return n})(),r=0xffffffff;for(let i=0;i<e.length;i++)r=t[(r^e[i])&255]^r>>>8;return(0xffffffff^r)>>>0})(t)&&eD("invalid-crc");let s=t.length>>>0;i.getUint32(4,!0)!==s&&eD("invalid-size")};async function eB(e,t=!0,r){try{let t=new TextEncoder().encode(e),r=new globalThis.CompressionStream("gzip"),i=r.writable.getWriter(),s=i.write(t).then(()=>i.close()).catch(async e=>{try{await i.abort(e)}catch{}throw e}),n=new Response(r.readable).blob(),[a]=await Promise.all([n,s]);return await eL(a,t),a}catch(e){if(r?.rethrow)throw e;return t&&console.error("Failed to gzip compress data",e),null}}let eN="0123456789abcdef";class eq{constructor(e){this.bytes=e}static ofInner(e){if(16===e.length)return new eq(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,r,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||e<0||t<0||r<0||i<0||e>0xffffffffffff||t>4095||r>0x3fffffff||i>0xffffffff)throw RangeError("invalid field value");let s=new Uint8Array(16);return s[0]=e/0x10000000000,s[1]=e/0x100000000,s[2]=e/0x1000000,s[3]=e/65536,s[4]=e/256,s[5]=e,s[6]=112|t>>>8,s[7]=t,s[8]=128|r>>>24,s[9]=r>>>16,s[10]=r>>>8,s[11]=r,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new eq(s)}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("")}if(t){let e=new Uint8Array(16);for(let r=0;r<16;r+=4){let i=parseInt(t.substring(2*r,2*r+8),16);e[r+0]=i>>>24,e[r+1]=i>>>16,e[r+2]=i>>>8,e[r+3]=i}return new eq(e)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=eN.charAt(this.bytes[t]>>>4),e+=eN.charAt(15&this.bytes[t]),(3===t||5===t||7===t||9===t)&&(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=eN.charAt(this.bytes[t]>>>4),e+=eN.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(e=>0===e)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(e=>255===e)?"MAX":"VAR_RESERVED";throw Error("unreachable")}getVersion(){return"VAR_10"===this.getVariant()?this.bytes[6]>>>4:void 0}clone(){return new eq(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(let t=0;t<16;t++){let r=this.bytes[t]-e.bytes[t];if(0!==r)return Math.sign(r)}return 0}}class eU{constructor(e){this.timestamp=0,this.counter=0,this.random=e??eH()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);return void 0===r&&(this.timestamp=0,r=this.generateOrAbortCore(e,t)),r}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>0x3ffffffffff&&(this.timestamp++,this.resetCounter())}return eq.fromFieldsV7(this.timestamp,Math.trunc(this.counter/0x40000000),0x3fffffff&this.counter,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,eq.ofInner(e)}}let eH=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),eK=()=>eV().toString(),eV=()=>(a||(a=new eU)).generate();class eW{add(e){let t=eK(),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(e=>e.promise),t=e.length;for(;t>0;)await Promise.all(e),t=(e=Object.values(this.promiseByIds).map(e=>e.promise)).length}getPromises(e=[],t=this.nextId){let r=new Set(e);return Object.values(this.promiseByIds).filter(e=>e.id<=t&&!r.has(e.promise)).map(e=>e.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}let ez=(e,t,r)=>{function i(s,...n){t(()=>{(0,r[s])(e,...n)})}return{debug:(...e)=>{i("debug",...e)},info:(...e)=>{i("log",...e)},warn:(...e)=>{i("warn",...e)},error:(...e)=>{i("error",...e)},critical:(...t)=>{r.error(e,...t)},createLogger:i=>ez(`${e} ${i}`,t,r)}};function eG(e,t=Date.now(),r=3e5){if("string"!=typeof e||!e)return;let i=e.trim(),s=/^\d+\s*,/.test(i)?i.slice(0,i.indexOf(",")).trim():i;if(/^\d+$/.test(s)){let e=1e3*Math.min(Number(s),r/1e3);return e>0?e:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(s))return;let n=Date.parse(/^\w{3} \w{3} /.test(s)?s+" GMT":s)-t;if(Number.isFinite(n)&&!(n<=0))return Math.min(n,r)}class eQ{record(e){if("too-large"===e.kind)return;if("retry-later"!==e.kind)return void this.reset();if(!e.retryAfterMs)return;let t=this.isOpen(),r=Date.now(),i=Math.min(e.retryAfterMs,3e5);if(!t){this._installedAt=r,this._until=r+i;return}this._until=Math.max(this._until,Math.min(r+i,this._installedAt+3e5))}remainingMs(){let e=Date.now();if(e<this._installedAt-5e3)return this.reset(),0;let t=Math.min(3e5,Math.max(0,this._until-e));return 0===t&&this.reset(),t}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}}class eJ extends Error{constructor(e,t,r,i){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.responseBodyDeadline=r,this.abortController=i,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return eG(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=ek("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e,t=new Promise((e,t)=>{this.responseBodyTimer=eM(()=>{this._bodyReadTimedOut=!0;let e=ek("AbortError","Response body read timed out");t(e),this.cancelResponseBody(e)},this.responseBodyDeadline-Date.now())});try{e=Promise.resolve(this.response.text())}catch(t){e=Promise.reject(t)}this.responseBodyTextPromise=Promise.race([e,t]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(e=>JSON.parse(e))}cancelResponseBody(e){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(e),(async()=>{try{await this.response.body?.cancel()}catch{}})()}}class eZ extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}async function eY(e){if(e instanceof eJ){let t="";try{t=await e.text}catch{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 eX(e){return e instanceof eZ}function e0(e){if(e instanceof eJ)return 502===e.status||504===e.status;if(!(e instanceof eZ))return!1;let t=e.error;return"ECONNREFUSED"!==(t?.code??t?.cause?.code)}function e1(e){try{if("string"!=typeof e)return e instanceof Uint8Array?e.byteLength:e.size;if("u">typeof Buffer)return Buffer.byteLength(e,"utf8");return new TextEncoder().encode(e).length}catch{return 0}}function e2(e){return"object"==typeof e&&e instanceof eJ&&413===e.status}function e3(e){return e instanceof eJ?408===e.status||429===e.status||e.status>=500:eX(e)}function e5(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}let e4="default";class e6{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new k([new Y,new ei,new ee,new en],V("web:javascript",D,N))}getEvaluationRuntime(){}get apiKey(){return this.projectToken}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new eW,this._events=new ex,this._isInitialized=!1;let r="string"==typeof e?e.trim():"",i="string"==typeof t.host?t.host.trim():"",s=!r;this._logger=function(e,t=e=>e()){return ez(e,t,function(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),s&&this._logger.error("You must pass your PostHog project token. The client will be disabled."),this.projectToken=r,this.host=eC(i||"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??1e3),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??3e3,retryCheck:e3},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||s,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=!("CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&"function"==typeof Response.prototype.blob)||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){return this.disabled?void this._logger.warn("The client is disabled"):this._isInitialized?e():void this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(c.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(c.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(c.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let e=this.on("*",(e,t)=>this._logger.info(e,t));this.removeDebugCallback=()=>{e(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},r=this.mergeCommonEventProperties(t);var i=r;for(let e of Object.keys(t))(e.startsWith("$feature/")||"$active_feature_flags"===e)&&(i[e]=t[e]);return"$feature_flag_called"===e.event&&!1===r.$feature_flag_has_experiment&&this.isMinimalFlagCalledEventsEnabled()&&(r=eP(r)),{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 i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",i,r)})}async identifyStatelessImmediate(e,t,r){let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",i,r)}captureStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",s,i)})}async captureStatelessImmediate(e,t,r,i){let s=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",s,i)}aliasStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",s,i)})}async aliasStatelessImmediate(e,t,r,i){let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",s,i)}groupIdentifyStateless(e,t,r,i,s,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...n||{}}});this.enqueue("capture",a,i)})}async groupIdentifyStatelessImmediate(e,t,r,i,s,n){let a=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...n||{}}});await this.sendImmediate("capture",a,i)}async getRemoteConfig(){await this._initPromise;let e=this.host;"https://us.i.posthog.com"===e?e="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===e&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.projectToken}/config`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,r,{type:"required",consume:e=>e.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(e=>{this._logger.error("Remote config could not be loaded",e),this._events.emit("error",e)})}async getFlags(e,t={},r={},i={},s={},n=!1){await this._initPromise;let a=`${this.host}/flags/?v=2${n?"&config=true":""}`,o={token:this.projectToken,distinct_id:e,groups:t,person_properties:r,group_properties:i,...s};r.$device_id&&(o.$device_id=r.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(o.evaluation_contexts=this.evaluationContexts);let l=this.getEvaluationRuntime();l&&(o.evaluation_runtime=l);let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(o)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,u,{type:"required",consume:e=>e.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:e0},this.featureFlagsRequestTimeoutMs).then(e=>({success:!0,response:(e=>{if("flags"in e){let t,r=Object.fromEntries(Object.entries(e.flags??{}).map(([e,t])=>[e,eS(t)]).filter(([,e])=>void 0!==e)),i=Object.fromEntries(Object.keys(t=e.flags??{}).filter(e=>{let r=t[e];return r.enabled&&r.metadata&&void 0!==r.metadata.payload}).map(e=>{let r=t[e].metadata?.payload;return[e,r?eF(r):void 0]}));return{...e,featureFlags:r,featureFlagPayloads:i}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([e,t])=>[e,eF(t)])),i=Object.fromEntries(Object.entries(t).map(([e,t])=>{var i,s;return[e,{key:e,enabled:"string"==typeof(i=t)||i,variant:"string"==typeof i?i:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:(s=r[e])?JSON.stringify(s):void 0,description:void 0}}]}));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}})(e)})).catch(e=>(this._events.emit("error",e),{success:!1,error:this.categorizeRequestError(e)}))}categorizeRequestError(e){if(e instanceof eJ)return{type:"api_error",statusCode:e.status};if(e instanceof eZ){let t=e.error;return t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,r={},i={},s={},n){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(e,t,r,i,s,n);if(void 0===a)return{response:void 0,requestId:void 0};let o=eS(a.response);return void 0===o&&(o=!1),{response:o,requestId:a.requestId}}async getFeatureFlagDetailStateless(e,t,r={},i={},s={},n){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,r,i,s,n,[e]);if(void 0!==a)return{response:a.flags[e],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,r={},i={},s={},n){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(t,r,i,s,n,[e]);if(!a)return;let o=a[e];return void 0===o?null:o}async getFeatureFlagPayloadsStateless(e,t={},r={},i={},s,n){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,n)).payloads}async getFeatureFlagsStateless(e,t={},r={},i={},s,n){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,n)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},i={},s,n){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(e,t,r,i,s,n);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},r={},i={},s,n){await this._initPromise;let a={geoip_disable:s??this.disableGeoip};n&&(a.flag_keys_to_evaluate=n);let o=await this.getFlags(e,t,r,i,a);if(!o.success)return;let l=o.response;return(l.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"),l.quotaLimited?.includes("feature_flags"))?(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:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.projectToken}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},r=await this.fetchWithRetry(e,t,{type:"required",consume:e=>{if(200!==e.status||!e.json){let t=`Surveys API could not be loaded: ${e.status}`,r=Error(t);return this._logger.error(r),this._events.emit("error",Error(t)),Promise.resolve(void 0)}return e.json()}}).catch(e=>{this._logger.error("Surveys API could not be loaded",e),this._events.emit("error",e)}),i=r?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(c.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(c.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(c.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return e4}persistedQueueKeyForRoute(e){return c.Queue}getActiveQueueRoutes(){return[e4]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,r,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let s=this.prepareMessage(t,r);if(null===(s=this.processBeforeEnqueue(s)))return;s=this.normalizeMessage(s);let n=this.persistedQueueKeyForRoute(i??this.getQueueRouteKey(s)),a=this.getPersistedProperty(n)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:s}),this.setPersistedProperty(n,a),this._events.emit(e,s),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=eM(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,r,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let s=this.prepareMessage(t,r);if(null!==(s=this.processBeforeEnqueue(s))){s=this.normalizeMessage(s);try{await this.sendBatch([s],void 0,i??this.getQueueRouteKey(s))}catch(e){this._events.emit("error",e)}}}normalizeMessage(e){let{type:t,library:r,library_version:i,...s}=e,n=e5(s.properties)?s.properties:void 0;return void 0!==r&&n?.$lib===void 0&&(n={...n||{},$lib:r}),void 0!==i&&n?.$lib_version===void 0&&(n={...n||{},$lib_version:i}),n&&(s.properties=n),s.uuid=eA(s.uuid,eK),s}normalizeTimestampForWire(e){let t=e instanceof Date?e:"string"==typeof e?new Date(e):null;if(!t||Number.isNaN(t.getTime()))return e;let r=t.toISOString(),i="string"==typeof e?e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return i&&i.length>3?r.replace(/\.\d{3}Z$/,`.${i}Z`):r}prepareMessage(e,t){let r={...e,timestamp:t?.timestamp?t?.timestamp:eT(),uuid:eA(t?.uuid,eK)};return(t?.disableGeoip??this.disableGeoip)&&(e5(r.properties)||(r.properties={}),r.properties.$geoip_disable=!0),r.distinctId&&(r.distinct_id=r.distinctId,delete r.distinctId),r}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async e=>{await eY(e)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(e,t=[]){let r=t.filter(e=>!!e),i=0;for(;;){let t=this.promiseQueue.getPromises([...r,...this.flushPromises],e);if(0===t.length)return;i>0&&this._logger.debug(`flush() re-checking ${t.length} pending promise(s) before flushing`),await Promise.all(t.map(e=>e.catch(()=>{}))),i++}}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,i=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(r,[t,i])}).then(()=>ej([t])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),ej([i]).then(()=>{this.flushPromises.delete(i),this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this.flushPromise===i&&(this.flushPromise=null)}),i}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&""!==e&&(t["User-Agent"]=e),t}compressPayload(e){return eB(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,t,r=e4){let i={api_key:this.projectToken,batch:e.map(e=>{if(!e)return e;let t=this.normalizeTimestampForWire(e.timestamp);return t===e.timestamp?e:{...e,timestamp:t}}),sent_at:eT()};this.historicalMigration&&(i.historical_migration=!0);let s=f(i),n=`${this.host}${this.getBatchEndpointPath(r)}`,a=this.disableCompression?null:await this.compressPayload(s),o={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==a&&{"Content-Encoding":"gzip"}},body:a||s};await this.fetchWithRetry(n,o,{type:"successful-write"},t)}async _flush(){let e;this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(e=>this.getRouteQueue(e).length>0))return;let r=[];for(let i of t)try{await this._flushRoute(i,r)}catch(t){void 0===e&&(e=t)}if(void 0!==e)throw e;this._events.emit("flush",r)}async _flushRoute(e,t){let r=this.persistedQueueKeyForRoute(e),i=this.getPersistedProperty(r)||[];if(!i.length)return;let s=i.length,n=0;for(;i.length>0&&n<s;){let s=i.slice(0,this.maxBatchSize),a=s.map(e=>void 0===e.message?e.message:this.normalizeMessage(e.message)),o=async()=>{let e=this.getPersistedProperty(r)||[],t=[...s],n=e.filter(e=>{let r=e.message?.uuid,i=t.findIndex(t=>t===e||"string"==typeof r&&r.length>0&&t.message?.uuid===r);return -1===i||(t.splice(i,1),!1)});this.setPersistedProperty(r,n),i=n,this._dequeuedMessagesCount+=s.length,await this.flushStorage()},l={retryCheck:e=>!e2(e)&&e3(e)};try{await this.sendBatch(a,l,e)}catch(e){if(e2(e)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this._logger.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw e instanceof eZ||await o(),this._events.emit("error",e),e}await o(),t.push(...a),n+=a.length}}async _sendOtlpBatch({path:e,auth:t,payload:r}){let i;if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};try{i=JSON.stringify(r)}catch(t){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${e} batch; reporting it as too large`,t)),{kind:"too-large",measuredLocally:!0}}let s=e1(i);if(s>0xa00000)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${s} bytes: the endpoint accepts at most 10485760`)),{kind:"too-large",measuredLocally:!0};let n="bearer"===t?`${this.host}/i/v1/${e}`:`${this.host}/i/v1/${e}?token=${encodeURIComponent(this.projectToken)}`,a=this.disableCompression?null:await this.compressPayload(i),o=a||i,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",..."bearer"===t&&{Authorization:`Bearer ${this.projectToken}`},...null!==a&&{"Content-Encoding":"gzip"}},body:o};try{return await this.fetchWithRetry(n,l,{type:"successful-write"},{retryCheck:e=>!e2(e)&&(!(e instanceof eJ)||void 0===e.retryAfterMs)&&e3(e)}),{kind:"ok"}}catch(e){if(e2(e))return{kind:"too-large"};if(e3(e)){let t=e instanceof eJ?e.retryAfterMs:void 0;return{kind:"retry-later",error:e,...void 0!==t&&{retryAfterMs:t}}}return{kind:"fatal",error:e}}}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,i,s){let n=e1(t.body?t.body:""),a={...this._retryOptions,...i},o=0;return await eO(async()=>{let i,a,l;o++;let u=new AbortController,c=s??this.requestTimeout,h=Date.now()+c,d=new Promise((e,t)=>{i=eM(()=>{let e=ek("AbortError",`Request timed out after ${c}ms`);t(e),u.abort(e)},c)}),f=!1,p=()=>l??=(async()=>{try{await a?.body?.cancel()}catch{}})();try{let i;try{i=this.fetch(e,{signal:u.signal,...t})}catch(e){throw new eZ(e)}i.then(e=>{u.signal.aborted&&!f&&Promise.resolve(e.body?.cancel()).catch(()=>{})}).catch(()=>{});try{a=await Promise.race([i,d]),f=!0}catch(e){throw new eZ(e)}let s="no-cors"===t.mode,o="successful-write"===r.type?300:400;if(!s&&(a.status<200||a.status>=o))throw new eJ(a,n,h,u);if("successful-write"===r.type){try{await Promise.race([p(),d])}catch{}return}try{return await Promise.race([r.consume(a),d])}catch(e){if(u.signal.aborted)throw new eZ(e);throw e}}finally{clearTimeout(i),u.signal.aborted&&a&&p()}},{...a,retryCheck:e=>{let t=a.retryCheck(e);return t&&o<=a.retryCount&&e instanceof eJ&&e.cancelResponseBody(),t}})}async _shutdown(e=3e4){await this._initPromise;let t=!1;if(this.clearFlushTimer(),!this.disabled)return eR((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(e=>this.getRouteQueue(e).length>0);){let e=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===e){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(e){if(!("object"==typeof e&&(e instanceof eJ||eX(e))))throw e;await eY(e)}})(),e,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:e}),t=!0})}async shutdown(e=3e4){return 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"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}class e8{constructor(e){this._onFire=e,this._firesAt=0}get pending(){return!!this._timer}arm(e){this.clear(),this._firesAt=Date.now()+e,this._timer=eM(()=>{this._timer=void 0,this._onFire()},e)}armNoEarlierThan(e){this._timer&&Date.now()+e<=this._firesAt||this.arm(e)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}function e9(){return .75+.25*Math.random()*2}function e7(e,t,r,i){let s=Math.min(Math.max(0,t-1),6),n=e*2**s;return Math.round((void 0===i?n:Math.min(n,Math.max(i,e)))*r)}let te="[Circular]",tt="[Truncated]",tr="[Unserializable]";function ti(e){let t="";for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i>=55296&&i<=56319){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(t+=e[r]+e[r+1],r++):t+="�"}else t+=i>=56320&&i<=57343?"�":e[r]}return t}function ts(e,t){if(!t)return e;let r=[];try{r=Object.keys(t)}catch{r=[]}for(let i of r){let r;try{r=t[i]}catch{r=tr}Object.defineProperty(e,i,{value:r,enumerable:!0,writable:!0,configurable:!0})}return e}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let tn=Object.prototype.propertyIsEnumerable;function ta(e,t){try{return to(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function to(e,t,r,i){let s=[];for(let n in e)if(tn.call(e,n)){if(!n){t?.debug("Dropping an attribute with an empty key");continue}if(s.length>=1e3||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let a=e[n];if(w(a)||_(a))continue;s.push({key:ti(n),value:function e(t,r,i,s){if(i.remainingNodes<=0)return{stringValue:tt};if(i.remainingNodes--,"[object Boolean]"===m.call(t))return{boolValue:t};if("bigint"==typeof t){let e,i;return e=t.toString(),t>=(i=BigInt("9223372036854775808"))||t<-i?(r?.debug(`Attribute ${e} is outside the int64 range; encoding it as a string`),{stringValue:e}):{intValue:e}}if("number"==typeof t){if(!Number.isFinite(t))return{stringValue:String(t)};if(Number.isInteger(t)){if(Number.isSafeInteger(t))return{intValue:String(t)};if("u"<typeof BigInt)return{stringValue:String(t)};let e=BigInt(t).toString();return t>=0x8000000000000000||t<-0x8000000000000000?(r?.debug(`Attribute ${e} is outside the int64 range; encoding it as a string`),{stringValue:e}):{intValue:e}}return{doubleValue:t}}if("string"==typeof t)return{stringValue:ti(t)};if("function"==typeof t)return{stringValue:"[Function]"};if("symbol"==typeof t)return{stringValue:String(t)};if("object"==typeof t&&null!==t){if(i.ancestors.has(t))return{stringValue:te};if(s>=20)return{stringValue:tt};if(t instanceof Date){let e=Number.isFinite(t.getTime())?t.toISOString():String(t);return{stringValue:"string"==typeof e?ti(e):String(e)}}i.ancestors.add(t);try{try{let n=t.toJSON;if("function"==typeof n)return e(n.call(t),r,i,s+1)}catch{}if(y(t))return{arrayValue:{values:function(t,r,i,s){let n=[],a=Math.min(t.length,1e3),o=0;for(;o<a&&i.remainingNodes>0;o++)try{let a=o in t?t[o]:void 0;if(x(a))continue;n.push(e(a,r,i,s))}catch{n.push({stringValue:tr})}return t.length>o&&n.push({stringValue:tt}),n}(t,r,i,s+1)}};return{kvlistValue:{values:to(t,r,i,s+1)}}}finally{i.ancestors.delete(t)}}return{stringValue:ti(String(t))}}(a,t,r,i)})}catch{s.push({key:ti(n),value:{stringValue:tr}})}}return s}let tl="0000000000000000",tu=tl+tl,tc=/^[0-9a-f]+$/;function th(e){let t=function(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}(function(e){let t=new Uint8Array(e),r=globalThis.crypto;if(r&&"function"==typeof r.getRandomValues)try{return r.getRandomValues(t),t}catch{}for(let r=0;r<e;r++)t[r]=Math.floor(256*Math.random());return t}(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function td(e,t,r){return"string"==typeof e&&e.length===t&&e!==r&&tc.test(e)}let tf=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function tp(e){let t=tg(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:1&parseInt(t.flags,16)?ty:t_}}function tg(e){if("string"!=typeof e)return;let t=tf.exec(e.trim());if(!t)return;let[,r,i,s,n,a]=t;if("ff"!==r&&("00"!==r||!a)&&td(i,32,tu)&&td(s,16,tl))return{version:r,traceId:i,spanId:s,flags:n}}function tm(e){return Array.isArray(e)&&1===e.length?e[0]:e}let ty="01",t_="00";function tv(e){if("string"!=typeof e)return;let t=e.trim();if(!t||/[^\x20-\x7e\t]/.test(t))return;let r=t.split(",");if(!(r.length>32)){for(let e of r)if(e.trim()&&!e.includes("="))return;return t.length<=512?t:function(e){let t=[...e],r=()=>t.reduce((e,t)=>e+t.length,0)+t.length-1;for(let e=t.length-1;e>=0&&r()>512;e--)t[e].length>128&&t.splice(e,1);for(;t.length&&r()>512;)t.pop();return t.length?t.join(","):void 0}(r)}}function tb(e,t,r){return{...ts({},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}}let tw=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function tx(e,t){let r=ts({},e),i={};for(let e of tw)Object.prototype.hasOwnProperty.call(r,e)&&(i[e]=r[e],delete r[e]);return[...ta(r,t),...ta(i,t)]}let tS={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"},tF=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function tE(e){return String(e)+"000000"}function tP(e,t,r,i){let s="";return i&&(s=Object.keys(i).sort().map(e=>`${JSON.stringify(e)}:${JSON.stringify(i[e])}`).join(",")),`${e}\0${t}\0${r??""}\0${s}`}class tI{constructor(e,t,r){this._instance=e,this._config=t,this._logger=r,this._series=new Map,this._flushTimer=new e8(()=>this.flush().catch(e=>{this._logger.error("Metrics flush failed:",e)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._boundsByHistogram=new Map,this._boundsConflictWarned=new Set,this._boundsCapWarned=!1,this._retryAfter=new eQ,this._consecutiveFlushFailures=0,this._flushJitter=1,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,bounds:y(r?.bounds)?r.bounds.slice():r?.bounds})}flush(){let e=this._flushPromise,t=(async()=>{e&&await e.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===t&&(this._flushPromise=null)});return this._flushPromise=t,t}drainWindow(){if(0===this._series.size)return null;let e=this._series;return this._startWindow(),this._buildPayload(e)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=1,this._flushTimer.clear(),this._flushPromise=null,this._startWindow(),this._boundsByHistogram=new Map,this._boundsCapWarned=!1}_startWindow(){this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._boundsConflictWarned=new Set}_capture(e){var t;let r,i,s;if(this._instance.isDisabled||this._instance.optedOut)return;let n=this._runBeforeSend(e);if(null===n)return;if(!n.name||"string"!=typeof n.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof n.value||!Number.isFinite(n.value))return void this._logger.warn(`Dropping metric '${n.name}': value must be a finite number`);if("count"!==n.type&&"gauge"!==n.type&&"histogram"!==n.type)return void this._logger.warn(`Dropping metric '${n.name}': unknown type '${String(n.type)}'`);if("count"===n.type&&n.value<0)return void this._logger.warn(`Dropping count '${n.name}': counters are monotonic, value must be >= 0`);try{r=n.attributes?{...n.attributes}:void 0,i=tP(n.type,n.name,n.unit,r)}catch(e){this._logger.warn(`Dropping metric '${n.name}': attributes could not be serialized`,e);return}let a=this._series.get(i);if(!a&&!this._admitNewSeries()||"histogram"===n.type&&!(s=this._histogramBounds(n.name,n.unit,n.bounds)))return;a||(a={name:n.name,type:n.type,unit:n.unit,attributes:r,windowStartMs:Date.now(),hist:s&&{bounds:t=s,count:0,sum:0,min:1/0,max:-1/0,bucketCounts:Array(t.length+1).fill(0)}},this._series.set(i,a));let o=this._typeByName.get(n.name);void 0===o?this._typeByName.set(n.name,n.type):o===n.type||this._typeCollisionWarned.has(n.name)||(this._typeCollisionWarned.add(n.name),this._logger.warn(`Metric name '${n.name}' is already used as a ${o}; recording it as a ${n.type} too will blend both series in charts. Use a distinct name.`)),this._fold(a,n.value);let l=this._activeTraceContext();l&&(a.exemplar={...l,value:n.value,timeMs:Date.now()}),this._armFlushTimer()}_activeTraceContext(){try{let e=tp(this._instance.getActiveSpan?.()?.traceparent());if(e&&e.flags===ty)return{traceId:e.traceId,spanId:e.spanId}}catch{}}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush||(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.`)),!1)}_histogramBounds(e,t,r){if(void 0!==r&&!function(e){if(!y(e)||0===e.length)return!1;for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t])||t>0&&e[t]<=e[t-1])return!1;return!0}(r))return void this._logger.warn(`Dropping histogram '${e}': bounds must be a non-empty array of finite, strictly increasing numbers`);let i=tP("histogram",e,t,void 0),s=this._boundsByHistogram.get(i);if(s)return this._warnOnBoundsConflict(e,i,s,r),s;if(this._boundsByHistogram.size>=this._config.maxSeriesPerFlush){if(this._boundsCapWarned||(this._boundsCapWarned=!0,this._logger.warn(`Histogram bounds limit reached (${this._config.maxSeriesPerFlush} distinct histograms); new histograms that pass custom bounds are dropped. Reduce histogram name cardinality.`)),r&&!tA(r,tF))return;return tF}let n=r?r.slice():tF;return this._boundsByHistogram.set(i,n),n}_warnOnBoundsConflict(e,t,r,i){tA(r,i??tF)||this._boundsConflictWarned.has(t)||(this._boundsConflictWarned.add(t),this._logger.warn(`Histogram '${e}' already uses the bounds [${r.join(", ")}]; samples that pass different bounds are recorded in those buckets.`))}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{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[function(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}(t,r.bounds)]+=1}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=y(t)?t:[t],i=e;for(let e of r)try{let t=e(i);if(!t)return this._logger.info("Metric was rejected in beforeSend function"),null;i=t}catch(e){return this._logger.error("Error in beforeSend function for metric:",e),null}return i}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(e7(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),0===this._series.size)return;let e=this._series;this._startWindow();let t=this._generation,r=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t===this._generation)switch(this._retryAfter.record(r),"retry-later"===r.kind?(this._consecutiveFlushFailures++,this._flushJitter=e9()):(this._consecutiveFlushFailures=0,this._flushJitter=1),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),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){var t,r,i,s;return t=this._buildMetrics(e),r=tb(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),s=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:tx(r)},scopeMetrics:[{scope:{name:i,version:s},metrics:t}]}]}}_buildMetrics(e){let t=tE(Date.now()),r=new Map;for(let s of e.values()){var i;let e=tP(s.type,s.name,s.unit,void 0),n=r.get(e);n||(n={name:s.name,...s.unit&&{unit:s.unit}},"count"===s.type?n.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===s.type?n.gauge={dataPoints:[]}:n.histogram={aggregationTemporality:1,dataPoints:[]},r.set(e,n));let a=ta(s.attributes??{},this._logger),o=tE(s.windowStartMs),l=(i=s.exemplar)?{exemplars:[{filteredAttributes:[],timeUnixNano:tE(i.timeMs),asDouble:i.value,traceId:i.traceId,spanId:i.spanId}]}:{};if("count"===s.type){let e={attributes:a,startTimeUnixNano:o,timeUnixNano:t,asDouble:s.total??0,...l};n.sum.dataPoints.push(e)}else if("gauge"===s.type){let e={attributes:a,timeUnixNano:t,asDouble:s.last??0,...l};n.gauge.dataPoints.push(e)}else{let e=s.hist,r={attributes:a,startTimeUnixNano:o,timeUnixNano:t,count:e.count,sum:e.sum,min:e.min,max:e.max,bucketCounts:e.bucketCounts,explicitBounds:e.bounds,...l};n.histogram.dataPoints.push(r)}}return Array.from(r.values())}_mergeWindowBack(e){for(let[t,r]of e){let e=this._series.get(t);if(!e){this._admitNewSeries()&&this._series.set(t,r);continue}switch(e.windowStartMs=Math.min(e.windowStartMs,r.windowStartMs),e.exemplar=e.exemplar??r.exemplar,e.type){case"count":e.total=(e.total??0)+(r.total??0);break;case"gauge":break;case"histogram":{let t=e.hist,i=r.hist;t.count+=i.count,t.sum+=i.sum,t.min=Math.min(t.min,i.min),t.max=Math.max(t.max,i.max);for(let e=0;e<t.bucketCounts.length;e++)t.bucketCounts[e]+=i.bucketCounts[e]}}}}}function tA(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}let tk="unknown";function tC(e,t,r,i){return"string"==typeof e&&e.trim()?e.length>r?e.slice(0,r):e:(i?.debug(`${t} must be a non-empty string; using "${tk}"`),tk)}function t$(e){if(null==e)return;let t=e;if(e instanceof Date)try{t=e.getTime()}catch{return}if("number"==typeof t&&Number.isFinite(t)&&!(t<0)&&!(t>0x8637bd05af6))return t}function tO(e,t,r,i){let s=t$(e);return void 0===s?(void 0!==e&&i?.debug(`Span ${r} is out of range or not a valid time; using the derived time`),t):s}function tT(){let e=globalThis.performance;return"function"==typeof e?.now?e.now():void 0}class tM{constructor(e,t,r){for(let i of(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??ty,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),Object.keys(e.attributes)))this._writeAttribute(i,e.attributes[i]);this._startMono=e.backdated?void 0:tT(),this._startTime=e.clockAnchor&&void 0!==this._startMono?e.clockAnchor.wall+(this._startMono-e.clockAnchor.mono):e.startTime,void 0!==this._startMono&&(this._clockAnchor=e.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(void 0!==this._startMono){let e=tT();if(void 0!==e)return this._startTime+Math.max(0,e-this._startMono)}return Date.now()}_mutable(e){return!this._ended||(this._logger?.debug(`Ignoring ${e} on a span that has already ended`),!1)}_writeAttribute(e,t){if(x(t)){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]=tH(t,this._maxAttributeValueLength)}setAttribute(e,t){return this._mutable("setAttribute")&&this._writeAttribute(e,t),this}setAttributes(e){if(this._mutable("setAttributes")){let t=ts({},e);for(let e of Object.keys(t))this._writeAttribute(e,t[e])}return this}addEvent(e,t,r){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let i=t&&tK(t,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:tC(e,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:tO(r,this._now(),"event timestamp",this._logger),...i&&{attributes:i.attributes,...i.dropped&&{droppedAttributesCount:i.dropped}}})}return this}setStatus(e,t){if(this._mutable("setStatus")){if("ok"!==e&&"error"!==e)return this._logger?.debug(`Ignoring unknown span status "${String(e)}"; expected "ok" or "error"`),this;this._status={code:e,...t&&{message:tU(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:i}=tW(e);return this.addEvent(tR,{"exception.type":t,"exception.message":r,...i&&{"exception.stacktrace":i}}),this.setStatus("error",r)}updateName(e){return this._mutable("updateName")&&(this._name=tC(e,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return function(e,t,r=ty){return`00-${e}-${t}-${r}`}(this._traceId,this._spanId,this._traceFlags)}get traceId(){return this._traceId}get spanId(){return this._spanId}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(e){var t;if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let r=tO(e,this._now(),"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:r<(t=this._startTime)?t:r,...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}}let tR="exception";function tj(e){return"number"!=typeof e||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),0xffffffff)}class tD{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}get traceId(){return null}get spanId(){return null}tracestate(){return null}end(){}}let tL=new tD;class tB extends tD{constructor(e,t){super(),this._traceparent=e,this._tracestate=t}traceparent(){return this._traceparent}get traceId(){return this._traceparent.split("-")[1]??null}get spanId(){return this._traceparent.split("-")[2]??null}tracestate(){return this._tracestate??null}}function tN(e,t){var r;let i=tm(e?.parent)??t,s=tg(r="string"==typeof i||null==i?i:tq(i,"traceparent"))&&r.trim();return s?new tB(s,tv("string"==typeof i||null==i?e?.tracestate:tq(i,"tracestate"))):tL}function tq(e,t){try{let r=e[t];return"function"==typeof r?r.call(e):void 0}catch{return}}function tU(e,t){return e.length>t?e.slice(0,t):e}function tH(e,t){return function e(t,r,i,s){if(null===t||"object"!=typeof t)return x(t)||i.remainingNodes<=0?t:(i.remainingNodes--,"string"==typeof t?tU(t,r):t);if(i.ancestors.has(t))return te;if(i.remainingNodes<=0||s>=20)return t;i.remainingNodes--,i.ancestors.add(t);try{if(t instanceof Date)return t;let n=function(e){try{let t=e.toJSON;if("function"==typeof t)return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}(t);if(n.selfDescribed)return x(n.value)?String(n.value):e(n.value,r,i,s+1);if(y(t)){let n=Math.min(t.length,1e3),a=[];for(let o=0;o<n;o++)try{a.push(e(t[o],r,i,s+1))}catch{a.push(tr)}return t.length>n&&(a.length=t.length),a}let a={},o=0;for(let n of Object.keys(t)){let l;if(o>=1e3)break;try{l=e(t[n],r,i,s+1)}catch{l=tr}n&&!x(l)&&o++,Object.defineProperty(a,n,{value:l,enumerable:!0,writable:!0,configurable:!0})}return a}catch{return t}finally{i.ancestors.delete(t)}}(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function tK(e,t,r){let i;try{i=Object.keys(e)}catch{return{attributes:{},dropped:0}}let s={},n=0,a=0;for(let o of i){let i;if(n>=t){a++;continue}try{i=tH(e[o],r)}catch{i=tr}x(i)||(n++,Object.defineProperty(s,o,{value:i,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:s,dropped:a}}function tV(e,t,r){return t===tL?r(t):e.with(t,()=>r(t))}function tW(e){try{let t=function(e){try{let t=e.stack;return"string"==typeof t&&t?{stack:t}:{}}catch{return{}}}(e);if(S(e))return{type:e.name||"Error",message:e.message||"",...t};if("string"==typeof e)return{type:"string",message:e};if(e&&"object"==typeof e&&"string"==typeof e.message)return{type:"string"==typeof e.name?e.name:"Object",message:e.message,...t};return{type:typeof e,message:String(e)}}catch{return{type:typeof e,message:""}}}let tz={internal:1,server:2,client:3,producer:4,consumer:5},tG={ok:1,error:2};function tQ(e){if("string"==typeof e)return ti(e);try{return ti(String(e))}catch{return tr}}function tJ(e){let t=Math.floor(e),r=Math.round((e-t)*1e6);return r>=1e6&&(t+=1,r=0),String(t)+String(r).padStart(6,"0")}function tZ(){return tT()??Date.now()}function tY(e){try{return e instanceof tM}catch{return!1}}function tX(e,t){let r=tp(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:tv(t),traceFlags:r.flags,isRemote:!0}}function t0(e,t,r){e[t]!==r&&(e[t]=r)}class t1{constructor(e,t,r,i,s,n){this._instance=e,this._config=t,this._logger=r,this._getContext=i,this._contextManager=s,this._onSpanQueued=n,this._queue=[],this._flushTimer=new e8(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter=new eQ,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=t.maxExportBatchSize}startSpan(e,t){var r,i;let s;if(this._instance.isDisabled||this._instance.optedOut)return tN(t,this._contextManager.active());let n=tm(t?.parent);if(n&&"string"!=typeof n&&!tY(n)){if(function(e){try{return"function"==typeof e.traceparent}catch{return!1}}(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),tN(t,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let a=this._resolveParent(n,t);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),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`),tN(t,this._contextManager.active());let o=Date.now(),l=(r=t?.startTime,i=this._logger,void 0===(s=t$(r))?(void 0!==r&&i?.debug("Span startTime is out of range or not a valid time; using the current time"),o):(o-s>864e5?i?.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"):s>o&&i?.debug("Span startTime is in the future; the span may export with a zero duration"),s)),u=th(8);this._liveSpans.set(u,tZ());let c=this._autoContextAttributes();return new tM({traceId:a?.traceId??th(16),spanId:u,parentSpanId:a?.parentSpanId,traceState:a?.traceState,traceFlags:a?.traceFlags,parentIsRemote:a?.isRemote,name:tC(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:t?.kind??"internal",attributes:ts({...c},t?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:l,backdated:l!==o,clockAnchor:void 0===t$(t?.startTime)?a?.clockAnchor:void 0},(e,t)=>this._onSpanEnd(e,t),this._logger)}withSpan(e,t,r){let i=this.startSpan(e,"function"==typeof t?void 0:t);try{let e=tV(this._contextManager,i,"function"==typeof t?t:r);if(e&&"function"==typeof e.then)return e.then(e=>(i.end(),e),e=>{throw this._recordCallbackError(i,e),i.end(),e});return i.end(),e}catch(e){throw this._recordCallbackError(i,e),i.end(),e}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;){if(!this._queue.length)return;let e=this._flushPromise;if(!await (e??this._startFlush()))return}}_startFlush(){this._flushTimer.clear();let e=this._generation,t=Promise.resolve().then(()=>e===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===t&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=t,t}reset(){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=1,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(e,t){if("string"==typeof e){let r=tX(e,t?.tracestate);return r||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),r}if(tY(e))return e.childContext();let r=this._contextManager.active();return tY(r)?r.childContext():r instanceof tB?tX(r.traceparent(),r.tracestate()??void 0):void 0}_autoContextAttributes(){let e;try{e=this._getContext()}catch(e){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",e),{}}let t={};return e.distinctId&&(t.posthogDistinctId=e.distinctId),e.sessionId&&(t.sessionId=e.sessionId),e.currentUrl&&(t["url.full"]=e.currentUrl),e.screenName&&(t["screen.name"]=e.screenName),e.appState&&(t["app.state"]=e.appState),t}_recordCallbackError(e,t){if(!(e instanceof tM))return;let{type:r,message:i,stack:s}=tW(t);e.addEvent("exception",{"exception.type":r,"exception.message":i,...s&&{"exception.stacktrace":s}}),e.statusIsExplicitlyOk||e.setStatus("error",i)}_evictAgedSpans(){let e=tZ()-this._config.maxSpanAgeMs,t=0;for(let[r,i]of this._liveSpans){if(i>e)break;this._liveSpans.delete(r),t++}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){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(e){this._logger.debug("Span queue notification failed",e)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(e){let t=e.droppedAttributesCount??0,r=e.droppedEventsCount??0,i=0;for(let t of e.events)i+=t.droppedAttributesCount??0;(t||r||i)&&this._logger.debug(`Span limits discarded data from "${e.name}": ${t} attributes, ${r} events, ${i} 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},i={startTime:e.startTime,endTime:e.endTime},s={attributes:e.droppedAttributesCount,events:e.droppedEventsCount},n=Object.keys(e.attributes),a={traceFlags:e.traceFlags,parentIsRemote:e.parentIsRemote},o=e.status&&{...e.status},l=e,u=e;try{var c,h,d;for(let e of this._config.beforeSpanSend){let t=e(l);if(!t)return this._recordDrop(1,"beforeSpanSend dropped it"),null;l=this._keepSpanIdentity(t,r)}if(!((c=u={traceId:r.traceId,spanId:r.spanId,parentSpanId:r.parentSpanId,traceState:r.traceState,name:l.name,kind:l.kind,status:l.status,attributes:l.attributes,events:l.events,startTime:l.startTime,endTime:l.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:s.attributes,droppedEventsCount:s.events}).attributes&&"object"==typeof c.attributes&&!Array.isArray(c.attributes)&&Array.isArray(c.events)&&void 0!==c.name&&void 0!==c.kind&&void 0!==c.startTime&&void 0!==c.endTime))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;u.name=tC(u.name,"Span name",this._config.maxAttributeValueLength,this._logger),u.status&&"ok"!==u.status.code&&"error"!==u.status.code&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),u.status=o),u.startTime=t$(u.startTime)??i.startTime,u.endTime=(h=t$(u.endTime)??i.endTime,d=u.startTime,h<d?d:h);let e=[];for(let t of u.events)try{e.push({...t,name:tC(t.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:tO(t.timestamp,u.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return u.events=e,!function(e,t,r,i,s,n,a=[]){let o=0,l=0,u={};for(let i of function(e,t){if(!t.length)return Object.keys(e);let r=t.filter(t=>Object.prototype.propertyIsEnumerable.call(e,t)),i=new Set(r);return[...r,...Object.keys(e).filter(e=>!i.has(e))]}(e.attributes,a)){let s=e.attributes[i];if(!x(s)){if(!t.has(i)){if(o>=r){l++;continue}o++}Object.defineProperty(u,i,{value:tH(s,n),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=u,l&&(e.droppedAttributesCount=tj(e.droppedAttributesCount)+l);let c=0,h=0,d=[];for(let t of e.events){if(c>=i){h++;continue}if(c++,t.attributes){let e=tK(t.attributes,s,n);t.attributes=e.attributes,e.dropped&&(t.droppedAttributesCount=tj(t.droppedAttributesCount)+e.dropped)}d.push(t)}e.events=d,h&&(e.droppedEventsCount=tj(e.droppedEventsCount)+h),e.status?.message&&(e.status={...e.status,message:tU(function(e){try{return"string"==typeof e?e:String(e)}catch{return tr}}(e.status.message),n)})}(u,t,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,n),u}catch(e){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",e),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(e,t){(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{t0(e,"traceId",t.traceId),t0(e,"spanId",t.spanId),t0(e,"parentSpanId",t.parentSpanId),t0(e,"traceState",t.traceState)}catch{try{let r=Object.getOwnPropertyDescriptors(e);for(let e of["traceId","spanId","parentSpanId","traceState"])r[e]={value:t[e],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(e),r)}catch{;}}return e}_recordDrop(e,t){this._droppedSinceWarning+=e,this._dropReasons.add(t),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(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(function(e,t){var r;let i,s={traceId:e.traceId,spanId:e.spanId,name:tQ(e.name),kind:(r=e.kind)&&Object.prototype.hasOwnProperty.call(tz,r)?tz[r]:tz.internal,startTimeUnixNano:tJ(e.startTime),endTimeUnixNano:tJ(e.endTime),flags:(Number.isFinite(i=parseInt(e.traceFlags,16))?255&i:1)|256|512*!!e.parentIsRemote};e.parentSpanId&&(s.parentSpanId=e.parentSpanId),e.traceState&&(s.traceState=tQ(e.traceState));let n=ta(e.attributes,t);n.length&&(s.attributes=n),e.events.length&&(s.events=e.events.map(e=>(function(e,t){let r={name:tQ(e.name),timeUnixNano:tJ(e.timestamp)};if(e.attributes){let i=ta(e.attributes,t);i.length&&(r.attributes=i)}let i=tj(e.droppedAttributesCount);return i&&(r.droppedAttributesCount=i),r})(e,t)));let a=tj(e.droppedAttributesCount);a&&(s.droppedAttributesCount=a);let o=tj(e.droppedEventsCount);return o&&(s.droppedEventsCount=o),e.status&&(s.status={code:tG[e.status.code],...e.status.message&&{message:tQ(e.status.message)}}),s}(r,this._logger))}catch(e){this._logger.debug("Failed to encode a span; dropping it",e),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(){var e,t;if(!this._queue.length)return 0;let r=this._discardQueueIfConsentWithdrawn();if(r)return r;let i=function(e,t){for(let r of Object.keys(e))e[r]=tH(e[r],t);return e}((e=this._config,tb(e,this._instance.getLibraryId(),this._instance.getLibraryVersion())),this._config.maxAttributeValueLength),s=this._instance.getLibraryId(),n=this._instance.getLibraryVersion(),a=this._queue.length,o=0,l=1/0,u=this._generation;try{for(;a>0&&this._queue.length>0;){let e=this._discardQueueIfConsentWithdrawn();if(e)return o+e;let r=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,c=Math.max(1,Math.min(r,l,a,this._queue.length)),h=this._queue.slice(0,c),d=this._encodeBatch(h);if(!d.length){this._queue.splice(0,c),a-=c,o+=c,this._resetHeadBatchBudget();continue}let f=tZ()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),p=await this._instance._sendTracesBatch((t=this._logger,{resourceSpans:[{resource:{attributes:tx(i,t)},scopeSpans:[{scope:{name:s,version:n},spans:d}]}]}));if(u!==this._generation)break;if(this._retryAfter.record(p),"ok"===p.kind){this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._queue.splice(0,c),a-=c,o+=c,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if("too-large"===p.kind){if(1===c){this._queue.splice(0,1),a-=1,o+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget();continue}let e=Math.max(1,Math.floor(c/2));p.measuredLocally?l=e:this._maxExportBatchSize=e,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${e}`);continue}if("retry-later"===p.kind){if(this._consecutiveFlushFailures++,this._flushJitter=e9(),this._headBatchSize=c,f&&(this._headBatchFailures++,this._headBatchChargeableAt=tZ()+this._nextFlushDelay()),this._headBatchFailures<8)return this._logger.debug("Span export failed; retrying on the next flush",p.error),o;if(this._queue.splice(0,c),a-=c,o+=c,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(c,"the ingestion endpoint failed 8 times in a row"),this._retryAfter.isOpen())return o;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",p.error),this._queue.splice(0,c),a-=c,o+=c,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(c,"the ingestion endpoint rejected the batch")}return o}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(e=>{this._logger.debug("Background span flush failed",e)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){!this._flushTimer.pending&&this._queue.length&&this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(e7(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}}class t2{active(){return this._active}with(e,t){let r=this._active;this._active=e;try{return t()}finally{this._active=r}}}let t3=["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","lightpanda","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"],t5=new Map,t4=function(e,t=[]){if(!e)return!1;let r=function(e,t){let r="";for(let e=0;e<t.length;e++){let i=t[e];r+=i.length+":"+i}return e.length+":"+e+"|"+t.length+":"+r}(e,t),i=t5.get(r);if(void 0!==i)return i;let s=e.toLowerCase(),n=t3.concat(t).some(e=>-1!==s.indexOf(e.toLowerCase()));return t5.size>=256&&t5.clear(),t5.set(r,n),n};function t6(e,t){return"number"==typeof e&&Number.isInteger(e)&&e>=1?e:t}let t8=["service.name","service.version","deployment.environment"],t9={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"};e.s(["FeatureFlagError",0,t9],58325);class t7{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,t.sendFeatureFlagEvents),r?.enabled??t.defaultValue??!1}getFlag(e,t={}){let r=this._flags[e];if(this._recordAccess(e,t.sendFeatureFlagEvents),r)return!!r.enabled&&(r.variant??!0)}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let r=this._flags[t];r&&(e[t]=r)}return this._cloneWith(e)}only(e){let t={},r=[];for(let i of e){let e=this._flags[i];e?t[i]=e:r.push(i)}return 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(", ")}`),this._cloneWith(t)}get keys(){return Object.keys(this._flags)}get unresolvedFlags(){return this._unresolvedFlags}_getEventProperties(){let e={},t=[];for(let[r,i]of Object.entries(this._flags)){let s=!1!==i.enabled&&(i.variant??!0);e[`$feature/${r}`]=s,i.enabled&&t.push(r)}return t.length>0&&(t.sort(),e.$active_feature_flags=t),e}_cloneWith(e){return new t7({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,t){if(this._accessed.add(e),!this._host.resolveSendFeatureFlagEvents(t)||""===this._distinctId||this._isSlice&&!(e in this._flags))return;let r=this._flags[e],i=void 0===r?void 0:!1!==r.enabled&&(r.variant??!0),s={$feature_flag:e,$feature_flag_response:i,$feature_flag_id:r?.id,$feature_flag_version:r?.version,$feature_flag_reason:r?.reason,locally_evaluated:r?.locallyEvaluated??!1,[`$feature/${e}`]:i,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:r?.locallyEvaluated?Date.now():this._evaluatedAt};r?.hasExperiment!==void 0&&(s.$feature_flag_has_experiment=r.hasExperiment),r?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(s.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let n=[];this._errorsWhileComputing&&n.push(t9.ERRORS_WHILE_COMPUTING),this._quotaLimited&&n.push(t9.QUOTA_LIMITED),void 0===r&&n.push(Object.prototype.hasOwnProperty.call(this._unresolvedFlags,e)?t9.LOCAL_EVALUATION_INCONCLUSIVE:t9.FLAG_MISSING),n.length>0&&(s.$feature_flag_error=n.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:i,groups:this._groups,disableGeoip:this._disableGeoip,properties:s})}}let re=["exact","is_not","icontains","not_icontains","starts_with","not_starts_with","ends_with","not_ends_with","regex","not_regex"];class rt extends Error{constructor(e,t="unsupported_definition"){super(e),this.name=this.constructor.name,this.reason=t,Object.setPrototypeOf(this,rt.prototype)}}function rr(e){try{return e()}catch(e){if(e instanceof rt)throw new rt(e.message,"missing_context");throw e}}function ri(e){if("boolean"==typeof e)return!0;if("string"==typeof e){let t=e.toLowerCase();return"true"===t||"false"===t}if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!ri(t in e?e[t]:null))return!1;return!0}function rs(e){if("boolean"==typeof e)return e;if("string"==typeof e)return"true"===e.toLowerCase();if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!rs(t in e?e[t]:null))return!1;return!0}function rn(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let r=e.charCodeAt(t+1);if(t+1>=e.length||r<56320||r>57343)throw new rt("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new rt("Cannot stringify an unpaired surrogate like the flags service")}}function ra(e,t=new Set){if(null!==e&&"boolean"!=typeof e){if("string"==typeof e)return void rn(e);if("number"==typeof e){if(!Number.isFinite(e))throw new rt(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new rt("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&ra(e[r],t)}finally{t.delete(e)}return}if("object"==typeof e){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&null!==r)throw new rt("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new rt("Cannot represent a circular object during local evaluation");t.add(e);try{for(let r of Object.keys(e))rn(r),ra(e[r],t)}finally{t.delete(e)}return}throw new rt(`Cannot represent ${typeof e} like the flags service`)}}function ro(e,t){let r=0,i=0;for(;r<e.length&&i<t.length;){let s=e.charCodeAt(r),n=t.charCodeAt(i),a=s>=55296&&s<=56319,o=n>=55296&&n<=56319,l=a?e.charCodeAt(r+1):0,u=o?t.charCodeAt(i+1):0,c=a?(s-55296)*1024+l-56320+65536:s,h=o?(n-55296)*1024+u-56320+65536:n;if(c!==h)return c-h;r+=a?2:1,i+=o?2:1}return e.length-t.length}function rl(e){return"string"==typeof e?(rn(e),e):function e(t,r=new Set){if(null===t)return"null";if("string"==typeof t)return rn(t),JSON.stringify(t);if("boolean"==typeof t)return t?"true":"false";if("number"==typeof t){if(!Number.isFinite(t))throw new rt(`Cannot stringify non-finite number ${t} like the flags service`);if(Number.isInteger(t))throw new rt(`Cannot distinguish integer ${t} from an integral JSON float during local evaluation`);return String(t)}if(Array.isArray(t)){if(r.has(t))throw new rt("Cannot stringify a circular array during local evaluation");r.add(t);try{let i=[];for(let s=0;s<t.length;s++)i.push(s in t?e(t[s],r):"null");return`[${i.join(",")}]`}finally{r.delete(t)}}if("object"==typeof t){let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&null!==i)throw new rt("Cannot stringify a non-JSON object like the flags service");if(r.has(t))throw new rt("Cannot stringify a circular object during local evaluation");r.add(t);try{let i=Object.keys(t);return i.forEach(rn),`{${i.sort(ro).map(i=>`${JSON.stringify(i)}:${e(t[i],r)}`).join(",")}}`}finally{r.delete(t)}}throw new rt(`Cannot stringify ${typeof t} like the flags service`)}(e)}let ru=/[\x20-\x2f:;=?@\x5b-\x60\x7b-\x7e]/;function rc(e){let t=new rt(e);return Object.defineProperty(t,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),t}function rh(e){return String(e).replace(/[A-Z]/g,e=>e.toLowerCase())}function rd(e,t,r){if(!/^\d+$/.test(e)||"strict"===r&&e.length>1&&"0"===e[0])throw new rt(`Invalid semver: ${t}`);return parseInt(e,10)}function rf(e,t="strict"){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new rt(`Invalid semver: ${e}`);let i=r.split("."),s=r=>void 0===r||""===r?0:rd(r,e,t);return[s(i[0]),s(i[1]),s(i[2])]}function rp(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 rg(e,t){let r=rf(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function rm(e,t){let[r,i,s]=rf(e,t);return{lower:[r,i,s],upper:r>0?[r+1,0,0]:i>0?[0,i+1,0]:[0,0,s+1]}}function ry(e,t){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new rt(`Invalid wildcard semver: ${e}`);let i=r.split("."),s=r=>{if("legacy-permissive"===t){let e=parseInt(r,10);if(!isNaN(e))return e}else try{return rd(r,e,t)}catch{}throw new rt(`Invalid wildcard semver: ${e}`)},n=s(i[0]);if(1===i.length)return{lower:[n,0,0],upper:[n+1,0,0]};let a=s(i[1]);return{lower:[n,a,0],upper:[n,a+1,0]}}function r_(e){if(e instanceof Date)return e;if("string"==typeof e||"number"==typeof e){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new rt(`${e} is in an invalid date format`)}throw new rt(`The date provided ${e} must be a string, number, or date object`)}function rv(e){if("boolean"==typeof e)throw new rt("Date operations cannot be performed on boolean values");return function(e){let t=e.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),r=new Date(new Date().toISOString());if(!t||!t.groups)return null;let i=parseInt(t.groups.number);if(i>=1e4)return null;let s=t.groups.interval;if("h"===s)r.setUTCHours(r.getUTCHours()-i);else if("d"===s)r.setUTCDate(r.getUTCDate()-i);else if("w"===s)r.setUTCDate(r.getUTCDate()-7*i);else if("m"===s)r.setUTCMonth(r.getUTCMonth()-i);else{if("y"!==s)return null;r.setUTCFullYear(r.getUTCFullYear()-i)}return r}(String(e))??r_(e)}function rb(e,t={}){let r=e.value,i=t.semverParsingPolicy??"strict";switch(e.operator||"exact"){case"exact":case"is_not":for(let e of Array.isArray(r)?r:[r])rl(e);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":rv(r);return;case"semver_eq":case"semver_neq":case"semver_gt":case"semver_gte":case"semver_lt":case"semver_lte":rf(String(r),i);return;case"semver_tilde":rg(String(r),i);return;case"semver_caret":rm(String(r),i);return;case"semver_wildcard":ry(String(r),i);return;default:throw new rt(`Unknown operator: ${e.operator}`)}}async function rw(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");return Array.from(new Uint8Array(await t.digest("SHA-1",new TextEncoder().encode(e)))).map(e=>e.toString(16).padStart(2,"0")).join("")}async function rx(e,t,r="",i="."){return parseInt((await rw(`${e}${i}${t}${r}`)).slice(0,15),16)/0x1000000000000000}async function rS(e,t){if(null==e||null==e.id||null==e.exclusion_percentage)return;let r=Number(e.exclusion_percentage);if(!Number.isFinite(r))return;let i=Math.min(Math.max(r,0),100);if(!(100!==i&&await rx("holdout",t,"","-")>i/100))return`holdout-${e.id}`}function rF(e){let t=[],r=0;for(let i of e){let e=r+i.rollout_percentage/100;t.push({valueMin:r,valueMax:e,key:i.key}),r=e}return t}async function rE(e,t,r){let i=await rx(e,t,"variant");return rF(r).find(e=>i>=e.valueMin&&i<e.valueMax)?.key}function rP(e){return"client"===e||"server"===e?e:"all"}function rI(e,t){return e===t||"all"===e||"all"===t}class rA extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,rA.prototype)}}class rk extends Error{constructor(e,t="unsupported_definition"){super(e),this.reason=t,this.name=rk.name,Error.captureStackTrace(this,rk),Object.setPrototypeOf(this,rk.prototype)}}let rC=["experience_continuity","unsupported_definition","unresolved_dependency","missing_context"];function r$(e,t){return void 0===e||rC.indexOf(t)<rC.indexOf(e)?t:e}function rO(e,t){return t instanceof rt&&Symbol.for("posthog.requiresServerRegexEvaluation")in t&&Object.defineProperty(e,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),e}class rT{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:i,host:s,customHeaders:n,...a}){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=i,this.projectApiKey=r,this.host=s,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=n,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}currentDefinitions(){return{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}withEvaluationSnapshot(e){return e.definitions?e:{...e,evaluationCache:{},definitions:this.currentDefinitions()}}createEvaluationContext(e,t={},r={},i={},s={}){return{distinctId:e,groups:t,personProperties:r,groupProperties:i,evaluationCache:s}}async getFeatureFlag(e,t,r={},i={},s={}){let n,a;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return n;if(void 0!==(a=this.featureFlagsByKey[e])){let o=this.createEvaluationContext(t,r,i,s);try{n=(await this.computeFlagAndPayloadLocally(a,o)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${n}`))}catch(t){t instanceof rk||t instanceof rt?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e}: ${t}`))}}return n}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let r={},i={},s={},n=0==this.featureFlags.length,a=t?t.map(e=>this.featureFlagsByKey[e]).filter(Boolean):this.featureFlags,o=this.withEvaluationSnapshot({...e,definitions:void 0});return await Promise.all(a.map(async e=>{try{let{value:t,payload:s}=await this.computeFlagAndPayloadLocally(e,o,{skipLoadCheck:!0});r[e.key]=t,s&&(i[e.key]=s)}catch(t){t instanceof rk||t instanceof rt?(this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e.key}: ${t.message}`)),s[e.key]=t.reason):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e.key}: ${t}`)),rI(rP(e.evaluation_runtime),"server")&&(n=!0)}})),{response:r,payloads:i,unresolved:s,fallbackToFlags:n}}async computeFlagAndPayloadLocally(e,t,r={}){let i,{matchValue:s,skipLoadCheck:n=!1}=r;if(this.loadedSuccessfullyOnce&&(t=this.withEvaluationSnapshot(t)),n||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};e=(t=this.withEvaluationSnapshot(t)).definitions.featureFlagsByKey[e.key]??e,i=void 0!==s?s:await this.computeFlagValueLocally(e,t);let a=function(e,t){if(!1===t||null==t||!e)return null;let r=e["boolean"==typeof t?t.toString():t]||null;return null==r?null:eF(r)}(e.filters?.payloads,i);return{value:i,payload:a}}async computeFlagValueLocally(e,t){let{distinctId:r,groups:i,personProperties:s,groupProperties:n}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new rt("Flag has experience continuity enabled","experience_continuity");let a=(e.filters||{}).aggregation_group_type_index;if(void 0!=a){let r=t.definitions.groupTypeMapping[String(a)];if(!r)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${a} for feature flag ${e.key}`)),new rt("Flag has unknown group type index");if(!(r in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;"device_id"===e.bucketing_identifier&&(s?.$device_id===void 0||s?.$device_id===null||s?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let o=n[r];return await this.matchFeatureFlagProperties(e,i[r],o,t)}{let i=this.getBucketingValueForFlag(e,r,s);if(void 0===i)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new rt(`Can't compute feature flag: ${e.key} without $device_id`,rM(e,t.definitions)??"missing_context");return await this.matchFeatureFlagProperties(e,i,s,t)}}getBucketingValueForFlag(e,t,r){if(e.filters?.aggregation_group_type_index!=void 0)return t;if("device_id"===e.bucketing_identifier){let e=r?.$device_id;if(null==e||""===e)return;return e}return t}async evaluateFlagDependency(e,t,r){let{evaluationCache:i}=r,s=e.key;if(!r.definitions.featureFlagsByKey)throw new rt("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new rt(`Flag dependency property for '${s}' is missing required 'dependency_chain' field`);let n=e.dependency_chain;if(!Array.isArray(n))throw new rt(`Flag dependency property for '${s}' has an invalid 'dependency_chain' (expected array, got ${typeof n})`);if(0===n.length)throw new rt(`Circular dependency detected for flag '${s}' (empty dependency chain)`);let a=n.find(e=>!(e in i)&&!r.definitions.featureFlagsByKey[e]&&!r.definitions.filteredOutFlagKeys.has(e));if(void 0!==a)throw new rt(`Missing flag dependency '${a}' for flag '${s}'`);for(let e of n){if(!(e in i)){let t=r.definitions.featureFlagsByKey[e];if(t)if(t.active)try{let s=await this.computeFlagValueLocally(t,r);i[e]=s}catch(t){if(t instanceof rk)throw new rk(`Flag dependency '${e}' for flag '${s}' requires server evaluation: ${t.message}`,"unresolved_dependency");throw rO(new rt(`Error evaluating flag dependency '${e}' for flag '${s}': ${t}`,"unresolved_dependency"),t)}else i[e]=!1;else i[e]=!1}if(null==i[e])throw new rt(`Dependency '${e}' could not be evaluated`,"unresolved_dependency")}let o=i[s];return this.flagEvaluatesToExpectedValue(e.value,o)}flagEvaluatesToExpectedValue(e,t){return"boolean"==typeof e?e===t||"string"==typeof t&&""!==t&&!0===e:"string"==typeof e&&t===e}async matchFeatureFlagProperties(e,t,r,i){let s,n,a;i=this.withEvaluationSnapshot(i);let o=e.filters||{},l=await rS(o.holdout,t);if(void 0!==l)return l;let u=o.groups||[],c=o.aggregation_group_type_index,h=o.early_exit??!1,{groups:d,groupProperties:f}=i,p=new Set;for(let l of u){let u=t;try{let t=void 0!==l.aggregation_group_type_index?l.aggregation_group_type_index:c,n=r;if(t!==c&&null!=t){let r=i.definitions.groupTypeMapping[String(t)];if(!r||!(r in d)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${t} not available`));continue}if(!(r in f)){s=r$(s,"missing_context");continue}n=f[r],u=d[r]}let p=await this.isConditionMatch(e,u,l,n,i);if("match"===p){let t=l.variant,r=o.multivariate?.variants||[];a=t&&r.some(e=>e.key===t)?t:await this.getMatchingVariant(e,u)||!0;break}if(h&&"out_of_rollout_bound"===p){if(s)break;return!1}}catch(t){if(t instanceof rk){let r;try{r=rM(e,i.definitions)}catch{}let n=r$(r$(s,t.reason),r??t.reason);throw n===t.reason?t:new rk(t.message,n)}if(t instanceof rt){if(s=r$(s,t.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in t)if(n=t,h&&void 0!=l.rollout_percentage&&await rx(e.key,u)>l.rollout_percentage/100)p.add(!1);else{let t=o.multivariate?.variants||[],r=l.variant;p.add(r&&t.some(e=>e.key===r)?r:await this.getMatchingVariant(e,u)||!0)}}else throw t}}if(void 0!==a&&!(n&&[...p].some(e=>e!==a)))return a;if(s)throw rO(new rt("Can't determine if feature flag is enabled or not with given properties",s),n);return!1}async isConditionMatch(e,t,r,i,s){let n=(s=this.withEvaluationSnapshot(s)).definitions,a=r.rollout_percentage,o=e=>{this.logMsgIfDebug(()=>console.warn(e))};if((r.properties||[]).length>0){let t,l,u;for(let e of r.properties){let r=e.type,a=!1;try{if("cohort"===r){let t=await rj(e,i,n.cohorts,this.debugMode,e=>this.evaluateFlagDependency(e,i,s),n.propertyMatchingVersion);a="not_in"===e.operator?!t:t}else if("flag"===r)a=await this.evaluateFlagDependency(e,i,s);else if(Object.prototype.hasOwnProperty.call(i,e.key))a=rR(e,i,o,n.propertyMatchingVersion);else{rb(e),t=r$(t,"missing_context");continue}}catch(e){if(e instanceof rk){void 0===t&&(u??=e),t=r$(t,e.reason);continue}if(e instanceof rt){Symbol.for("posthog.requiresServerRegexEvaluation")in e&&(l=e),t=r$(t,e.reason);continue}if(void 0!==t)break;throw e}if(!a)return"no_match"}if(u)throw u;if(t)throw rO(new rt(`Can't determine if a condition of flag ${e.key} matches`,t),l);if(void 0==a)return"match"}return void 0!=a&&await rx(e.key,t)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){return rE(e.key,t,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return rF(e.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(e){if(!this.evaluationContexts||0===this.evaluationContexts.length)return e;let t=new Set(this.evaluationContexts);return e.filter(e=>{let r=e.evaluation_contexts??e.evaluation_tags;return!r||0===r.length||r.some(e=>t.has(e))})}getEvaluationRuntimeForFlag(e){let t=this.featureFlagsByKey[e];return t?rP(t.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(e){return this.featureFlags.filter(t=>rI(rP(t.evaluation_runtime),e)).map(e=>e.key)}updateFlagState(e){let t=this.filterFlagsByEvaluationContexts(e.flags),r=t.reduce((e,t)=>(e[t.key]=t,e),{}),i=new Set(t.map(e=>e.key)),s=new Set(e.flags.filter(e=>!i.has(e.key)).map(e=>e.key));this.featureFlags=t,this.featureFlagsByKey=r,this.filteredOutFlagKeys=s,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=[],i=new Map,s=this.currentDefinitions();for(let n of e){if(!rI(rP(n.evaluation_runtime),"server"))continue;let e=rM(n,s);if(!e)continue;let a=JSON.stringify(n);i.set(n.key,a),this.warnedUnresolvableFlags.get(n.key)!==a&&("experience_continuity"===e?t.push(n.key):r.push(n.key))}if(this.warnedUnresolvableFlags=i,t.length>0){let e=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(", ")}. `+e)}if(r.length>0){let e=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(", ")}. ${e} 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(e){return this.onError?.(Error(`Failed to load from cache: ${e}`)),!1}}async loadFeatureFlags(e=!1){if(!this.loadedSuccessfullyOnce||e)return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(e=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${e}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let e=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(6e4,e*2**this.backOffCount):e}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(){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(e){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${e}`))}if(!e&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||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 rA(`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 rA(`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 rA(`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 i=r.group_type_mapping||{},s=!0===r.minimal_flag_called_events,n={flags:r.flags??[],group_type_mapping:i,cohorts:r.cohorts||{},minimal_flag_called_events:s,property_matching_version:r.property_matching_version,propertyMatchingVersion:r.property_matching_version,groupTypeMapping:i,minimalFlagCalledEvents:s};if(this.updateFlagState(n),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(e){this.onError?.(Error(`Failed to store in cache: ${e}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags);break}default:return}}catch(e){e instanceof rA&&this.onError?.(e)}finally{this.pollerStopped||null===this.pollingInterval||(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(e="GET",t){let r={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(r["If-None-Match"]=t),{method:e,headers:r}}async _requestFeatureFlagDefinitions(){if(!this.personalApiKey)throw new rA("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&&"number"==typeof this.timeout){let e=new AbortController;r=eM(()=>{e.abort()},this.timeout),t.signal=e.signal}try{let i=this.fetch,s=await i(e,t);if(200!==s.status)return clearTimeout(r),s;return{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{clearTimeout(r)}},json:async()=>{try{return await s.json()}finally{clearTimeout(r)}}}}catch(e){throw clearTimeout(r),e}}async stopPoller(e=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await eR(t,e,()=>{throw Error(`Cache shutdown timeout after ${e}ms`)})}catch(e){this.onError?.(Error(`Error during cache shutdown: ${e}`))}}}function rM(e,t){if(!e.active)return;if(e.ensure_experience_continuity)return"experience_continuity";let r=e.filters||{},i=r.aggregation_group_type_index;return void 0==i||t.groupTypeMapping[String(i)]?(r.groups||[]).some(e=>(e.properties||[]).some(e=>(function e(t,r,i){if("flag"===t.type){let e=t.dependency_chain;return!Array.isArray(e)||0===e.length||e.some(e=>!r.featureFlagsByKey[e]&&!r.filteredOutFlagKeys.has(e))}if("cohort"!==t.type)try{return rb(t),!1}catch(e){if(e instanceof rt)return!0;throw e}let s=String(t.value);return!(s in r.cohorts)||!i.has(s)&&(i.add(s),function t(r,i,s){return(r?.values??[]).some(r=>"values"in r?t(r,i,s):e(r,i,s))}(r.cohorts[s],r,i))})(e,t,new Set)))?"unsupported_definition":void 0:"unsupported_definition"}function rR(e,t,r,i){return function(e,t,r={}){try{return function(e,t,r){let i=e.key,s=e.value,n=e.operator||"exact",a=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,i)){if("is_not_set"===n)return!1;else if("is_set"===n)return!0}else throw new rt(`Property ${i} not found in propertyValues`,"missing_context");let o=t[i];if(void 0===o)throw r.warnFunction?.(`Property ${i} cannot have a value of undefined with the ${n} operator`),new rt(`Property ${i} is undefined in propertyValues`);if(null===o&&!re.includes(n))return r.warnFunction?.(`Property ${i} cannot have a value of null with the ${n} operator`),!1;let l=(e,t)=>{if(2!==r.propertyMatchingVersion&&ri(e)||Array.isArray(e)&&0===e.length)return rr(()=>ra(t)),rs(e)===rs(t);if(2===r.propertyMatchingVersion&&"number"==typeof t&&ri(e))return rr(()=>ra(t)),!1;if(Array.isArray(e)){let r=rr(()=>rl(t)).toLowerCase();return e.some(e=>rl(e).toLowerCase()===r)}return rl(e).toLowerCase()===rr(()=>rl(t)).toLowerCase()},u=(e,t,r)=>{if("gt"===r)return e>t;if("gte"===r)return e>=t;if("lt"===r)return e<t;if("lte"===r)return e<=t;throw Error(`Invalid operator: ${r}`)},c=()=>rr(()=>rf(String(o),a)),h=()=>{let e=rf(String(s),a);return rp(c(),e)},d=({lower:e,upper:t})=>{let r=c();return rp(r,e)>=0&&0>rp(r,t)};switch(n){case"exact":return l(s,o);case"is_not":return!l(s,o);case"is_set":return!0;case"icontains":return rh(o).includes(rh(s));case"not_icontains":return!rh(o).includes(rh(s));case"starts_with":return rh(o).startsWith(rh(s));case"not_starts_with":return!rh(o).startsWith(rh(s));case"ends_with":return rh(o).endsWith(rh(s));case"not_ends_with":return!rh(o).endsWith(rh(s));case"regex":case"not_regex":{let e=function(e,t){let r;if(""===e)return!0;let i=function(e){let t=[],r=-1,i="";for(let s=0;s<e.length;s++){let n=e[s];if(n.charCodeAt(0)>127)return null;if("\\"===n){let t=e[++s];if(void 0===t)break;if("x"===t){if(!/^[\da-f]{2}$/i.test(e.slice(s+1,s+3)))return null;s+=2}else if(!"dDsSwWbBfnrtv".includes(t)&&!ru.test(t))return null;if(-1===r&&"bB".includes(t))return null;i="literal";continue}if("["===n){if(-1!==r)return null;r=s}else if("]"===n&&-1!==r){if(s===r+("^"===e[r+1]?2:1))return null;t.push(e.slice(r,s+1)),r=-1,i="literal";continue}else if(-1!==r){if(["&&","--","~~"].includes(e.slice(s,s+2)))return null;continue}else if("("===n&&"?"===e[s+1]){if(":"!==e[s+2])return null;s+=2}else if("{"===n){let t=/^\{(\d+)(?:,(\d*))?\}/.exec(e.slice(s));if(!t||["","|","("].includes(i)||t.slice(1).some(e=>Number(e)>0xffffffff))return null}else if("*+?}".includes(n)&&("+"===e[s+1]||"{"===e[s+1]))return null;if("*+?{".includes(n)&&["^","$","empty group"].includes(i))return null;i=")"===n&&["(","empty group"].includes(i)?"empty group":n}return t}(e);if(null===i)throw rc("Regex syntax requires server evaluation");try{r=new RegExp(e)}catch(e){if(e instanceof SyntaxError)return null;throw rc("Regex compilation requires server evaluation")}for(let e of i)try{RegExp(e,"u")}catch{throw rc("Regex character class syntax requires server evaluation")}for(let e=0;e<t.length;e++){let r=t[e];if(r.charCodeAt(0)>127||"\r"===r)throw rc("Regex matching for Unicode or carriage returns requires server evaluation")}try{return r.test(t)}catch{throw rc("Regex execution requires server evaluation")}}(String(s),String(o));if(null===e)return!1;return"regex"===n?e:!e}case"gt":case"gte":case"lt":case"lte":{let e="number"==typeof s?s:parseFloat(String(s)),t="number"==typeof o?o:null!=o?parseFloat(String(o)):0/0;if(Number.isFinite(e)&&Number.isFinite(t))return u(t,e,n);return u(String(o),String(s),n)}case"is_date_after":case"is_date_before":{let e=rv(s),t=rr(()=>r_(o));return"is_date_before"===n?t<e:t>e}case"semver_eq":return 0===h();case"semver_neq":return 0!==h();case"semver_gt":return h()>0;case"semver_gte":return h()>=0;case"semver_lt":return 0>h();case"semver_lte":return 0>=h();case"semver_tilde":return d(rg(String(s),a));case"semver_caret":return d(rm(String(s),a));case"semver_wildcard":return d(ry(String(s),a));default:throw new rt(`Unknown operator: ${n}`)}}(e,t,r)}catch(t){throw t instanceof rt&&"missing_context"===t.reason&&rb(e,r),t}}(e,t,{warnFunction:r,propertyMatchingVersion:i})}async function rj(e,t,r,i=!1,s,n){let a=String(e.value);if(!(a in r))throw new rk(`cohort ${a} not found in local cohorts - likely a static cohort that requires server evaluation`);return rD(r[a],t,r,i,s,n)}async function rD(e,t,r,i=!1,s,n){let a,o;if(!e)return!0;let l=e.type,u=e.values;if(!u||0===u.length)return!0;if("values"in u[0]){for(let e of u)try{let a=await rD(e,t,r,i,s,n);if("AND"===l){if(!a)return!1}else if(a)return!0}catch(t){if(t instanceof rk)throw t;if(t instanceof rt)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),a=r$(a,t.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in t&&(o=t);else throw t}if(a)throw rO(new rt("Can't match cohort without a given cohort property value",a),o);return"AND"===l}for(let e of u)try{let a;if("cohort"===e.type)a=await rj(e,t,r,i,s,n);else if("flag"===e.type){if(!s)throw new rt(`Flag dependency '${e.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);a=await s(e)}else a=rR(e,t,void 0,n);let o=e.negation||!1;if("AND"===l){if(!a&&!o||a&&o)return!1}else if(a&&!o||!a&&o)return!0}catch(t){if(t instanceof rk)throw t;if(t instanceof rt)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),a=r$(a,t.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in t&&(o=t);else throw t}if(a)throw rO(new rt("can't match cohort without a given cohort property value",a),o);return"AND"===l}let rL=["--unhandled-rejections","--unhandled_rejections"],rB=new Set(["throw","strict","warn","warn-with-error-code","none"]),rN=[...globalThis.process?.execArgv??[]],rq=globalThis.process?.env?.NODE_OPTIONS;function rU(e){let t;for(let r=0;r<e.length;r++){let i=e[r],s=rL.find(e=>i===e||i.startsWith(`${e}=`));if(!s)continue;let n=i===s?e[++r]:i.slice(s.length+1);rB.has(n)&&(t=n)}return t}let rH=function(e=rN,t=rq){return rU(e)??rU(function(e){let t=[],r="",i=!1;for(let s=0;s<e.length;s++){let n=e[s];"\\"===n&&i&&s+1<e.length?r+=e[++s]:" "!==n||i?'"'===n?i=!i:r+=n:r&&(t.push(r),r="")}return r&&t.push(r),t}(t??""))??"throw"}(),rK={mechanism:{type:"onunhandledrejection",handled:!1}},rV={mechanism:{type:"onuncaughtexception",handled:!1}},rW=new Set(["HANGING_PROMISE_REJECTION","NEXT_PRERENDER_INTERRUPTED","DYNAMIC_SERVER_USAGE","BAILOUT_TO_CLIENT_SIDE_RENDERING"]),rz=Symbol.for("react.postpone"),rG=Symbol.for("next.unhandledRejectionFilter"),rQ=Symbol.for("posthog-node.exception-autocapture.v1"),rJ=globalThis;function rZ(e){return"function"==typeof e&&!0===e._posthogErrorHandler}function rY(e){return"object"==typeof e&&null!==e||"function"==typeof e}function rX(e){return Object.assign(e,{_posthogErrorHandler:!0})}function r0(e){return e.listeners("unhandledRejection").some(e=>!rZ(e))}function r1(e,t){return function e(t,r=0){try{if(!rY(t))return!1;if(t.$$typeof===rz||"string"==typeof t.digest&&rW.has(t.digest))return!0;return r<5&&e(t.cause,r+1)}catch{return!1}}(e)||"unhandledRejection"===t&&function(e){try{return rY(e)&&"AbortError"===e.name}catch{return!1}}(e)}function r2(e){let t=new Map;for(let r of e.clients){let e=t.get(r.key);e&&(void 0!==e.getContext()||void 0===r.getContext())||t.set(r.key,r)}for(let[r,i]of e.retired)t.has(r)||t.set(r,i);return[...t.values()]}function r3(e){"function"==typeof globalThis.setImmediate?setImmediate(e):setTimeout(e,0)}function r5(e,t,r,i){let s=e.capturedThisTurn.get(t)??new Map;s.has(r)||s.set(r,i),e.capturedThisTurn.set(t,s),e.turnResetScheduled||(e.turnResetScheduled=!0,r3(()=>{r3(()=>{e.capturedThisTurn.clear(),e.turnResetScheduled=!1})}))}function r4(e,t,r,i){let s=e.capturedThisTurn.get(t),n=[];for(let a of r2(e))s?.has(a.key)||i?.has(a.key)||(r5(e,t,a.key,"autocapture"),a.capture(t,r),n.push(a));return n}function r6(e,t){return e.deferred.get(t.exception)!==t?[]:(e.deferred.delete(t.exception),t.runInContext(()=>r4(e,t.exception,t.hint,t.skipKeys)))}function r8(e,t,r){let i;if(void 0!==(i=e.capturedThisTurn.get(t))&&r2(e).every(e=>i.has(e.key))||e.deferred.has(t))return;let s={exception:t,hint:r,skipKeys:new Set(e.capturedThisTurn.get(t)?.keys()),runInContext:function(){try{let e=globalThis.process,t=e?.getBuiltinModule?.("node:async_hooks"),r=t?.AsyncLocalStorage?.snapshot?.();if(r)return r}catch{}return e=>e()}()};e.deferred.set(t,s),r3(()=>r6(e,s))}async function r9(e,t){try{console.error(t)}catch{}ii();let r=new Set([...e.clients,...e.retired.values()]);await Promise.all([...r].map(e=>e.shutdown().catch(()=>void 0))),globalThis.process.exit(1)}function r7(e,t,r,i){let s="unhandledRejection"===r?rK:rV;if(!i){r1(t,r)||r8(e,t,s);return}let n=e.deferred.get(t);n?r6(e,n):r4(e,t,s)}function ie(e){try{return String(e)}catch{return typeof e}}function it(e){let t=globalThis.process;rJ[rG]&&"function"==typeof t.rawListeners&&t.rawListeners("unhandledRejection").includes(e)&&(Object.getPrototypeOf(t).removeListener.call(t,"unhandledRejection",e),t.listeners("unhandledRejection").includes(e)||t.prependListener("unhandledRejection",e))}function ir(e){let t=globalThis.process,r=[],i=(e,i)=>{t.on(e,i),r.push(()=>t.removeListener(e,i))},s=()=>r.forEach(e=>e());if("strict"===e.mode){let r=(t,r)=>r7(e,t,r,!0);return i("uncaughtExceptionMonitor",r),{remove:s,areInstalled:()=>t.listeners("uncaughtExceptionMonitor").includes(r)}}let n=rX((t,r)=>{let i=0===globalThis.process.listeners("uncaughtException").filter(e=>"domainUncaughtExceptionClear"!==e.name&&!rZ(e)).length;r7(e,t,r,i),i&&!e.calledFatalError&&(e.calledFatalError=!0,r9(e,t))});i("uncaughtException",n);let a="throw"===e.mode||"warn-with-error-code"===e.mode,o=a&&!t.versions?.bun,l=()=>t.listeners("unhandledRejection").includes(u),u=rX(t=>{a&&!r0(globalThis.process)&&l()?function(e,t){let r=globalThis.process;if("warn-with-error-code"===e.mode){r.emitWarning(`Unhandled promise rejection: ${ie(t)}`,"UnhandledPromiseRejectionWarning"),r.exitCode=1,r1(t,"unhandledRejection")||r4(e,t,rK);return}if(r.versions?.bun){r.exitCode=1,r4(e,t,rK),e.calledFatalError||(e.calledFatalError=!0,r9(e,t));return}let i=t instanceof Error?t:Object.assign(Error(`This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "${ie(t)}".`),{name:"UnhandledPromiseRejection",code:"ERR_UNHANDLED_REJECTION"}),s=r.emit;s.call(r,"uncaughtExceptionMonitor",i,"unhandledRejection"),s.call(r,"uncaughtException",i,"unhandledRejection")}(e,t):r1(t,"unhandledRejection")||r8(e,t,rK)});return i("newListener",rX((e,r)=>{rZ(r)||("unhandledRejection"===e?(l()||t.prependListener("unhandledRejection",u),queueMicrotask(()=>{let e;(e="function"==typeof t.rawListeners?t.rawListeners("unhandledRejection"):[]).includes(u)&&e[0]!==u&&(t.removeListener("unhandledRejection",u),t.prependListener("unhandledRejection",u)),it(u)})):"Next.UnhandledRejectionFilter.MacguffinEvent"===e&&queueMicrotask(()=>{l()||t.prependListener("unhandledRejection",u)}))})),o?(i("removeListener",rX(e=>{"unhandledRejection"===e&&l()&&!r0(t)&&t.removeListener("unhandledRejection",u)})),r0(t)&&t.prependListener("unhandledRejection",u)):t.prependListener("unhandledRejection",u),it(u),r.push(()=>{t.removeListener("unhandledRejection",u),"function"==typeof t.rawListeners&&t.rawListeners("unhandledRejection").includes(u)&&Object.getPrototypeOf(t).removeListener.call(t,"unhandledRejection",u)}),{remove:s,areInstalled:()=>t.listeners("uncaughtException").includes(n)&&(o||l())}}function ii(){let e=new Set,t=rJ[rQ];if(t)for(let r of[...t.deferred.values()])r6(t,r).forEach(t=>e.add(t));return e}let is=Symbol("capturedContext");function ia(e,t,r,i,s){if(t>r&&(i.warn("min cannot be greater than max."),t=r),"[object Number]"==m.call(e)&&e==e)if(e>r)return i.warn(" cannot be greater than max: "+r+". Using max value instead."),r;else return e<t?(i.warn(" cannot be less than min: "+t+". Using min value instead."),t):e;return i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+s),ia(s??r,t,r,i)}class io{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=ia(e.bucketSize,0,100,e._logger),this._refillRate=ia(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=ia(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){let r=Math.floor((t-e.lastAccess)/this._refillInterval);if(r>0){let t=r*this._refillRate;e.tokens=Math.min(e.tokens+t,this._bucketSize),e.lastAccess=e.lastAccess+r*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),r=String(e),i=this._buckets[r];return i?this._applyRefill(i,t):(i={tokens:this._bucketSize,lastAccess:t},this._buckets[r]=i),0===i.tokens||(i.tokens--,0===i.tokens&&this._onBucketRateLimited?.(e),0===i.tokens)}stop(){this._buckets={}}}var il=el;let iu=class e{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new io({...function(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??1,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??10}}(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return e===Object(e)&&!y(e)&&"__posthog_previously_captured_error"in e&&!0===e.__posthog_previously_captured_error}static async buildEventMessage(e,t,r,i,s,n){let a,o=(a=n?{...n,properties:{...n.properties}}:null,e=>Object.assign(e,{[is]:a})),l={...s},u=e.buildFromUnknown(t,r);u.$exception_list=await e.modifyFrames(u.$exception_list);let c=il.getInjectedReleaseId();return c&&(l.$release_id=c),o({event:"$exception",distinctId:i,properties:{...u,...l},_originatedFromCaptureException:!0})}get destinationKey(){return`${this.client.apiKey}@${this.client.host}`}startAutocaptureIfEnabled(){this.isEnabled()&&(this._autocaptureClient={key:this.destinationKey,capture:(e,t)=>this.onException(e,t),getContext:()=>this.client.getContext(),flush:()=>this.client.flush(),shutdown:()=>this.client.shutdown(2e3)},this._stopAutocapture=function(e,t=rH){if(!globalThis.process?.on)return()=>void 0;let r=rJ[rQ];if(r)r.listeners.areInstalled()||(r.listeners.remove(),r.listeners=ir(r));else{let e={mode:t,clients:new Set,retired:new Map,capturedThisTurn:new Map,deferred:new Map,turnResetScheduled:!1,calledFatalError:!1,listeners:{remove:()=>void 0,areInstalled:()=>!0}};e.listeners=ir(e),rJ[rQ]=e,r=e}r.clients.add(e),r.retired.delete(e.key);let i=r;return()=>{i.clients.delete(e)&&([...i.clients].some(t=>t.key===e.key)||i.retired.set(e.key,e))}}(this._autocaptureClient))}claimExplicitCapture(e){var t;let r;return t=this.destinationKey,!(r=rJ[rQ])||r.capturedThisTurn.get(e)?.get(t)!=="autocapture"&&(r5(r,e,t,"app"),r.deferred.get(e)?.skipKeys.add(t),!0)}capturePendingExceptions(){for(let e of ii())e!==this._autocaptureClient&&this.client.addPendingPromise(e.flush().catch(()=>void 0))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let i=await e.buildEventMessage(this.client.getErrorPropertiesBuilder(),t,r,void 0,void 0,this.client.getContext()),s=i.properties,n=s?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(n)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:n}):this.client._capturePreparedEvent(i,!1)}})().catch(e=>{this._logger.error("Failed to capture an exception:",e)}))}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop(),this.capturePendingExceptions(),this._stopAutocapture?.(),this._stopAutocapture=void 0}},ic=/^[0-9a-f]{32}$/i,ih=/^[0-9a-f]{16}$/i,id=Symbol.for("opentelemetry.js.api.1"),ip=Symbol.for("OpenTelemetry Context Key SPAN");async function ig(){try{let e=globalThis[id],t=e?.context?.active().getValue(ip),r=t?.spanContext(),i=r?.traceId,s=r?.spanId;if("string"==typeof i&&"string"==typeof s&&ic.test(i)&&ih.test(s)&&!/^0+$/.test(i)&&!/^0+$/.test(s))return{$trace_id:i.toLowerCase(),$span_id:s.toLowerCase()}}catch{}return{}}class im{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=null!==t?t:void 0}constructor(){this._memoryStorage={}}}let iy=Symbol.for("posthog-node.context-listeners"),i_=globalThis,iv=i_[iy]??=new WeakMap;function ib(e,t=!1){for(let r of iv.get(e)??[])try{r(t)}catch{}}function iw(e){ib(e,!0)}let ix="analytics";class iS extends Error{constructor({requestId:e,drops:t,retryExhausted:r,cause:i}){super(iS.buildMessage(e,t,r,i)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=r,this.cause=i}static buildMessage(e,t,r,i){let s=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${r.length} undelivered`;return i instanceof Error&&(s+=` (${i.message})`),s}}function iF(e){if("boolean"==typeof e)return e;if("number"==typeof e)return 0!==e;if("string"==typeof e){let t=e.trim().toLowerCase();if("true"===t||"1"===t)return!0;if("false"===t||"0"===t)return!1}}let iE=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:iF},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:iF},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:iF},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(e){return"string"==typeof e?e:void 0}}],iP=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function iI(e,t,r){void 0===r||t in e||(e[t]=r)}function iA(e){var t;let r={..."object"==typeof(t=e.properties)&&null!==t&&!Array.isArray(t)?e.properties:{}},i={};for(let{property:e,optionKey:t,coerce:s}of iE)if(e in r){let n=s(r[e]);void 0!==n&&(i[t]=n),delete r[e]}let s={};for(let{property:e,field:t}of iP)if(e in r){let i=r[e];"string"==typeof i&&(s[t]=i),delete r[e]}return delete r.$lib,delete r.$lib_version,iI(r,"$set",e.$set),iI(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:function(e){if("string"==typeof e){let t=new Date(e);if(Number.isNaN(t.getTime()))return new Date().toISOString();let r=t.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?r.replace(/\.\d{3}Z$/,`.${i}Z`):r}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=null==e?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}(e.timestamp),...s,options:i,properties:r}}let ik=new Set([408,500,502,503,504]);class iC{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??3e4,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??(e=>new Promise(t=>eM(t,e))),this.generateRequestId=t.generateRequestId??eK,this.compress=t.compress??eB}async sendV1Batch(e){if(0===e.length)return;let t=this.generateRequestId(),r=new Date(this.now()).toISOString(),{batch:i}=function(e,{createdAt:t,historicalMigration:r}){let i={created_at:t,batch:e.map(iA)};return r&&(i.historical_migration=!0),i}(e,{createdAt:r,historicalMigration:this.config.historicalMigration}),s=`${this.config.host}/i/v1/analytics/events`,n=[],a=i,o=Math.max(1,this.config.maxAttempts);for(let e=1;e<=o;e++){let i,l,u=e===o,c=f({created_at:r,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a});try{let{response:r,signal:o}=i=await this.sendOnce(s,c,e,t),{status:h}=r;if(h<200||h>=300)if(!u&&ik.has(h)){let t=this.parseRetryAfter(r);await i.waitFor(i.cancelBody()).catch(()=>{}),l=this.backoffDelay(e,t)}else{let e=await this.buildHttpError(r,h,i.waitFor);return this.surfaceBatchFailure(t,n,a,e)}else{let s;try{s=await i.waitFor(this.parseResponse(r))}catch(e){if(o.aborted)throw e;return this.surfaceBatchFailure(t,n,a,Error(`Capture V1 returned an unparseable ${h} response body`))}let c=this.classify(a,s,n);if(0===c.length)return this.surfacePartialDrops(t,n);if(u)return void this.onError(new iS({requestId:t,drops:n,retryExhausted:c.map(e=>e.uuid)}));a=c;let d=this.parseRetryAfter(r);l=this.backoffDelay(e,d)}}catch(r){if(i&&!i.signal.aborted)throw r;if(u)return this.surfaceBatchFailure(t,n,a,r);l=this.backoffDelay(e)}finally{i?.cleanup()}void 0!==l&&await this.sleep(l)}}async sendOnce(e,t,r,i){let s,n=this.buildHeaders(r,i),a=t;if(this.config.compressionEnabled){let e=await this.compress(t,this.config.isDebug);null!==e&&(a=e,n["Content-Encoding"]="gzip")}let o=new AbortController,l="waiting for response headers",u=new Promise((e,t)=>{s=eM(()=>{let e=Error(`Capture V1 request timed out ${l} after ${this.config.requestTimeoutMs}ms`);e.name="AbortError",t(e),o.abort(e)},this.config.requestTimeoutMs)});try{let t,r=this.fetchFn(e,{method:"POST",headers:n,body:a,signal:o.signal}),i=!1;r.then(e=>{o.signal.aborted&&!i&&this.cancelBody(e)}).catch(()=>{});let c=await Promise.race([r,u]);i=!0,l="while reading the response body";let h=!1,d=()=>t??=this.cancelBody(c);return{response:c,signal:o.signal,waitFor:e=>Promise.race([e,u]),cancelBody:d,cleanup:()=>{!h&&(h=!0,clearTimeout(s),o.signal.aborted&&d())}}}catch(e){throw clearTimeout(s),e}}buildHeaders(e,t){let r=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"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()};return this.config.userAgent&&(i["User-Agent"]=this.config.userAgent),i}classify(e,t,r){let i=t.results??{},s=[];for(let t of e){let e=i[t.uuid];e&&("drop"===e.result?r.push({uuid:t.uuid,details:e.details??void 0}):"retry"===e.result&&s.push(t))}return s}backoffDelay(e,t){let r=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return void 0===t?r: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 e=parseInt(r,10);return Number.isFinite(e)&&e>0?1e3*e:void 0}let i=Date.parse(r);if(Number.isNaN(i))return;let s=i-this.now();return s>0?s:void 0}async parseResponse(e){let t=JSON.parse(await e.text());if("object"!=typeof t||null===t||Array.isArray(t))throw Error("unexpected response shape");let r=t.results;if(void 0!==r&&("object"!=typeof r||null===r||Array.isArray(r)))throw Error("unexpected results shape");return{results:r??{}}}async buildHttpError(e,t,r){let i="";try{i=(await r(e.text())).slice(0,512)}catch{}let s=i?`: ${i}`:"";return Error(`Capture V1 request failed with HTTP ${t}${s}`)}surfaceBatchFailure(e,t,r,i){this.onError(new iS({requestId:e,drops:t,retryExhausted:r.map(e=>e.uuid),cause:i}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new iS({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}}let i$="ai-capture",iO="/i/v0/ai/batch/",iT=new TextEncoder;function iM(e){return iT.encode(f(e)).length}class iR extends Error{constructor(e){super(e.message,void 0===e.cause?void 0:{cause:e.cause}),this.name=function(e,t){if("missing_secret_key"===t||401===e)return"missing_api_key";if(void 0===e)return"network_error"===t?"service_unavailable":t.startsWith("invalid_")?"validation_error":"application_error";switch(e){case 400:return"validation_error";case 403:return"invalid_permission";case 404:return"not_found";case 409:return"template_outdated"===t?"validation_error":"concurrent_idempotent_requests";case 422:return"idempotency_key_reused"===t?"invalid_idempotent_request":"validation_error";case 429:return"quota_limited"===t?"monthly_quota_exceeded":"rate_limit_exceeded";case 503:return"service_unavailable";default:return"application_error"}}(e.statusCode,e.code),this.code=e.code,this.statusCode=e.statusCode,this.why=e.why,this.fix=e.fix,this.docsUrl=e.docsUrl,this.field=e.field,this.retryAfterMs=e.retryAfterMs}}let ij="https://us.posthog.com",iD="https://eu.posthog.com",iL={"https://us.i.posthog.com":ij,"https://us.posthog.com":ij,"https://app.posthog.com":ij,"https://eu.i.posthog.com":iD,"https://eu.posthog.com":iD},iB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,iN=/^[\x21-\x7e]{1,255}$/,iq=/^[a-zA-Z0-9_-]{1,400}$/,iU={to:!0,distinctId:!0,idempotencyKey:!0,maxRetries:!0},iH={name:"templateId",fields:iG(iU,{templateId:!0,templateData:!0}),why:"A template made in PostHog sets its own sender, subject and content, and follows the project's engagement setting.",howToSend:"send a template made in PostHog with templateId"},iK={name:"templateKey",fields:iG(iU,{templateKey:!0,subject:!0,from:!0,replyTo:!0,captureEngagement:!0,html:!0,text:!0}),why:"A send with templateKey takes its content from your code.",howToSend:"send content from your code with templateKey"};class iV{constructor(e,t){this.inFlight=new Set,this.config=e,this.hooks=t}send(e,...t){return this.track(this.sendUntracked(e,t))}get(e){return this.track(this.getUntracked(e))}track(e){return this.inFlight.add(e),e.finally(()=>this.inFlight.delete(e)),e}async drain(){for(;this.inFlight.size>0;)await Promise.all(this.inFlight)}async sendUntracked(e,t){try{var r=t;if(r.some(e=>void 0!==e))throw new iR({code:"invalid_form",message:"send takes one options object, so no email was sent. Put idempotencyKey and every other option in it."});let i=function(e,t){let r=e??{},{to:i,distinctId:s,idempotencyKey:n,maxRetries:a}=r;if("string"!=typeof i||!i.trim())throw iQ("invalid_recipient","to must be one email address as a nonempty string.","to");if(void 0!==s&&("string"!=typeof s||!s))throw iQ("invalid_distinct_id","distinctId must be a nonempty string.","distinctId");let o=function(e,t){if(void 0===e.templateId==(void 0===e.templateKey))throw new iR({code:"invalid_form",message:"Send either templateId, or templateKey with subject and html or text."});return void 0===e.templateKey?function(e,t){let{templateId:r,templateData:i}=e;if("string"!=typeof r||!iB.test(r))throw iQ("invalid_template_id","templateId must be the template's UUID.","templateId");if(void 0!==i&&("object"!=typeof i||null===i||Array.isArray(i)))throw iQ("invalid_template_data","templateData must be an object.","templateData");return iz(e,iH,iK),{template_id:r.toLowerCase(),message_data:i??{},...void 0!==t&&{distinct_id:t}}}(e,t):function(e,t){let{templateKey:r,subject:i,html:s,text:n,from:a,replyTo:o,captureEngagement:l}=e;if("string"!=typeof r||!iq.test(r))throw iQ("invalid_template_key","templateKey can only have letters, digits, hyphens (-) and underscores (_), at most 400.","templateKey");if(iz(e,iK,iH),"string"!=typeof i)throw iQ("invalid_form","A send with templateKey needs a subject.","subject");if(void 0!==s&&"string"!=typeof s)throw iQ("invalid_form","html must be a string.","html");if(void 0!==n&&"string"!=typeof n)throw iQ("invalid_form","text must be a string.","text");if(void 0===s&&void 0===n)throw iQ("invalid_form","A send with templateKey needs html, text or both.","html");let u=void 0!==o&&!(Array.isArray(o)&&0===o.length);return{template_key:r,subject:i,...void 0!==s&&{html:s},...void 0!==n&&{text:n},...void 0!==a&&{from:a},...u&&{reply_to:"string"==typeof o?[o]:o},capture_engagement:l??!0,...void 0!==t&&{distinct_id:t}}}(e,t)}(r,s);if(void 0!==n&&("string"!=typeof n||!iN.test(n)))throw iQ("invalid_idempotency_key","idempotencyKey must be 1 to 255 visible ASCII characters without spaces.","idempotencyKey");if(void 0!==a&&!iW(a))throw iQ("invalid_max_retries","maxRetries must be a nonnegative integer.","maxRetries");return{path:"/api/projects/@current/messaging/send/email/",body:f({...o,to:i}),idempotencyKey:n??globalThis.crypto.randomUUID(),maxRetries:iW(a)?a:t}}(e,this.config.maxRetries),{appHost:s,secretKey:n}=this.connect("no email was sent","Sending email needs secretKey, a project secret API key with the transactional_email:write scope."),a=this.headers(n,{"Content-Type":"application/json","Idempotency-Key":i.idempotencyKey}),o=await this.withRetries(i.maxRetries,async()=>(function({status:e,payload:t,retryAfterMs:r}){let i=iY(t);if(e>=200&&e<300){let t=iZ(i.message_id);if(!t)throw new iR({code:"api_error",message:"PostHog answered without a message ID.",statusCode:e});let r=[];if(Array.isArray(i.warnings))for(let e of i.warnings)null!==e&&"object"==typeof e&&r.push({code:iZ(e.code)??"warning",message:iZ(e.detail)??iZ(e.message)??"",fix:iZ(e.fix)});return{id:t,replayed:!0===i.replayed,warnings:r}}throw iX(i,e,r)})(await this.request(s+i.path,"POST",a,i.body)));for(let e of o.warnings)this.hooks.logger.warn(`PostHog email warning ${e.code}: ${e.message}`);return{data:o,error:null}}catch(e){return{data:null,error:i0(e,"Sending the email failed unexpectedly.")}}}async getUntracked(e){try{if("string"!=typeof e||!iB.test(e))throw iQ("invalid_message_id","id must be the message ID that send() returned.","id");let{appHost:t,secretKey:r}=this.connect("no email status was read","Reading an email status needs secretKey, a project secret API key with the transactional_email:read or transactional_email:write scope."),i=t+"/api/projects/@current/messaging/emails/{messageId}/".replace("{messageId}",e.toLowerCase()),s=this.headers(r,{});return{data:await this.withRetries(this.config.maxRetries,async()=>(function({status:e,payload:t,retryAfterMs:r}){let i=iY(t);if(e<200||e>=300)throw iX(i,e,r);let s=iZ(i.id),n=iZ(i.status),a=iZ(i.created_at),o=iZ(i.status_at);if(!s||!n||!a||!o)throw new iR({code:"api_error",message:"PostHog answered without an email status.",statusCode:e});return{id:s,status:n,createdAt:a,statusAt:o,reason:iZ(i.reason)??null}})(await this.request(i,"GET",s))),error:null}}catch(e){return{data:null,error:i0(e,"Reading the email status failed unexpectedly.")}}}connect(e,t){var r,i;let s;if(this.hooks.isDisabled())throw new iR({code:"client_disabled",message:`The PostHog client is disabled, so ${e}.`});if(this.hooks.isClosed())throw new iR({code:"client_closed",message:`The PostHog client is shut down, so ${e}.`});let n=(r=this.config.host,(s="string"==typeof(i=this.config.appHost)?eC(i.trim()):"")?iL[s]??s:iL[eC(r)]);if(!n)throw new iR({code:"missing_app_host",message:"The client's host is not PostHog Cloud, so the client can't tell where to send email. Set appHost to your PostHog app host on the client."});let a=this.config.secretKey?.trim();if(!a)throw new iR({code:"missing_secret_key",message:t});return{appHost:n,secretKey:a}}headers(e,t){let r={Authorization:`Bearer ${e}`,Accept:"application/json",...t};return this.hooks.userAgent&&(r["User-Agent"]=this.hooks.userAgent),this.config.migratedFrom&&(r["X-PostHog-Migrated-From"]=this.config.migratedFrom),r}async withRetries(e,t){for(let r=0;;r++){let i;try{return await t()}catch(e){i=e instanceof iR?e:new iR({code:"network_error",message:"The request to PostHog failed.",cause:e})}let s=function(e,t,r){if(!(t>=r)&&(void 0===e.statusCode?"network_error"===e.code:409===e.statusCode?"idempotency_key_in_flight"===e.code:429===e.statusCode?"quota_limited"!==e.code:503===e.statusCode)&&(void 0===e.retryAfterMs||!(e.retryAfterMs>3e4)))return Math.max(Math.min(3e4,1e3*2**t*(.8+.4*Math.random())),e.retryAfterMs??0)}(i,r,e);if(void 0===s)throw i;await new Promise(e=>setTimeout(e,s))}}async request(e,t,r,i){let s,n,a=new AbortController,o=this.config.requestTimeoutMs,l=new Promise((e,t)=>{s=setTimeout(()=>{let e=Error(`Email request timed out after ${o}ms`);e.name="AbortError",t(e),a.abort(e)},o)}),u=Promise.resolve().then(()=>this.hooks.fetch(e,{method:t,headers:r,...void 0===i?{}:{body:i},signal:a.signal}));u.then(e=>{a.signal.aborted&&Promise.resolve(e.body?.cancel()).catch(()=>{})}).catch(()=>{});try{let e;n=await Promise.race([u,l]);try{e=await Promise.race([n.text(),l])}catch(e){if(n.status>=200&&n.status<300)throw e;return{status:n.status,payload:null,retryAfterMs:iJ(n)}}return{status:n.status,payload:function(e){try{return JSON.parse(e)}catch{return null}}(e),retryAfterMs:iJ(n)}}finally{clearTimeout(s),a.signal.aborted&&n&&Promise.resolve(n.body?.cancel()).catch(()=>{})}}}function iW(e){return"number"==typeof e&&Number.isInteger(e)&&e>=0}function iz(e,t,r){let i=Object.entries(e).find(([e,r])=>void 0!==r&&!t.fields.has(e))?.[0];if(void 0===i)return;let s=`A send with ${t.name} doesn't take ${i}, so no email was sent.`;if(!r.fields.has(i))throw new iR({code:"invalid_form",message:s,field:i,fix:`Remove ${i} and send again.`});throw new iR({code:"invalid_form",message:s,field:i,why:t.why,fix:`Remove ${i}, or ${r.howToSend}.`})}function iG(...e){return new Set(e.flatMap(e=>Object.keys(e)))}function iQ(e,t,r){return new iR({code:e,message:t,field:r})}function iJ(e){try{return eG(e.headers?.get("retry-after"),Date.now(),Number.MAX_SAFE_INTEGER)}catch{return}}function iZ(e){return"string"==typeof e&&e?e:void 0}function iY(e){return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}function iX(e,t,r){return new iR({code:iZ(e.code)??"api_error",message:iZ(e.detail)??`PostHog answered HTTP ${t}.`,statusCode:t,why:iZ(e.why),fix:iZ(e.fix),docsUrl:iZ(e.docs_url),field:iZ(e.attr),retryAfterMs:r})}function i0(e,t){return e instanceof iR?e:new iR({code:"unexpected_error",message:t,cause:e})}let i1=new Set;function i2(e,t){i1.has(e)||(i1.add(e),console.warn(`[PostHog] ${t}`))}class i3 extends e6{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(e){this._distinctIdHasSentFlagCalls=new Map(Object.entries(e??{}))}constructor(e,t={}){var r,i;let s,n="string"==typeof e?e.trim():"",a={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:("string"==typeof(r=t.host)?r.trim():"")||"https://us.i.posthog.com",personalApiKey:("string"==typeof(i=t.secretKey??t.personalApiKey)?i.trim():"")||void 0};if(super(n,a),this._memoryStorage=new im,this._isShutdown=!1,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=a,this.captureMode="v0"===(s="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0)||"v1"===s?s:"v0",this.enableFullAiCapture=!0===a.enableFullAiCapture,this.privacyMode=!0===a.privacyMode,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof a.featureFlagsPollingInterval?Math.max(a.featureFlagsPollingInterval,100):null===a.featureFlagsPollingInterval?null:3e4,"number"==typeof a.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(a.waitUntilDebounceMs,0)),"number"==typeof a.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(a.waitUntilMaxWaitMs,0)),!this.disabled&&(a.personalApiKey||a.flagDefinitionCacheProvider)){if(a.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.');!1!==a.enableLocalEvaluation&&(this.featureFlagsPoller=new rT({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:a.personalApiKey,projectApiKey:n,timeout:a.requestTimeout??1e4,host:this.host,fetch:a.fetch,onError:e=>{this._events.emit("error",e)},onLoad:e=>{this._events.emit("localEvaluationFlagsLoaded",e)},onMinimalFlagCalledEvents:e=>{this._minimalFlagCalledEvents=e},customHeaders:this.getCustomHeaders(),cacheProvider:a.flagDefinitionCacheProvider,strictLocalEvaluation:a.strictLocalEvaluation,evaluationContexts:a.evaluationContexts??a.evaluationEnvironments}))}this.errorTracking=new iu(this,a,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=a.maxCacheSize||5e4}enqueue(e,t,r,i){super.enqueue(e,t,r,i),this.scheduleDebouncedFlush()}_flushEventsAndSpans(e=!1){let t=this.flushWithPendingPromises();return!this._traces||e&&this._traces.throttled?t:ej([t,this._traces.flush().catch(()=>{})]).then(([e])=>{if("rejected"===e.status)throw e.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this.errorTracking.capturePendingExceptions(),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||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let t,r=new Promise(e=>{t=e});try{e(r)}catch{return}this._waitUntilCycle={resolve:t,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,r=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),t>=r)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=eM(()=>{this.resolveWaitUntilFlush()},i)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),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){var t;return"v1"===this.captureMode&&"string"==typeof(t=e).event&&t.event.startsWith("$ai_")?"ai":ix}persistedQueueKeyForRoute(e){return e===i$?c.AiCaptureQueue:"ai"===e?c.AiQueue:c.Queue}getActiveQueueRoutes(){let e="v1"===this.captureMode?[ix,"ai"]:[ix];return this._aiCaptureRouteActive&&e.push(i$),e}getBatchEndpointPath(e){return e===i$?iO:super.getBatchEndpointPath(e)}async sendBatch(e,t,r=ix){if(r===i$)return this.sendAiCaptureBatch(e,t);if("v1"!==this.captureMode||"ai"===r)return super.sendBatch(e,t,r);let i=e.filter(e=>void 0!==e);await this.getV1Sender().sendV1Batch(i)}async sendAiCaptureBatch(e,t){let{batches:r,dropped:i}=function(e,t=8388608,r=5242880){let i=[],s=[],n=[],a=0;for(let o of e){if(void 0===o)continue;let e=iM(o);if(e>t){s.push({event:"string"==typeof o.event?o.event:"unknown",bytes:e});continue}n.length>0&&a+e>r&&(i.push(n),n=[],a=0),n.push(o),a+=e}return n.length>0&&i.push(n),{batches:i,dropped:s}}(e);for(let{event:e,bytes:t}of i){let r=`Event ${e} (${t} bytes) exceeds the 8MiB limit for ${iO}, dropping.`;this._logger.error(r),this._events.emit("error",Error(r))}for(let e of r)await this.sendAiSubBatch(e,t)}async sendAiSubBatch(e,t){try{await super.sendBatch(e,t,i$)}catch(i){if(!e2(i))throw i;if(1===e.length){let[t]=e,r="string"==typeof t.event?t.event:"unknown",i=`Event ${r} (${iM(t)} bytes) was rejected with 413 by ${iO} on its own, dropping.`;this._logger.error(i),this._events.emit("error",Error(i));return}let r=Math.ceil(e.length/2);await this.sendAiSubBatch(e.slice(0,r),t),await this.sendAiSubBatch(e.slice(r),t)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new iC({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??3e3,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:e=>this._events.emit("error",e),compress:e=>this.compressPayload(e)})),this._v1Sender}getLibraryVersion(){return"5.63.1"}get metrics(){var e;let t;return this._metrics||(this._metrics=new tI(this,(e=this.options.metrics,t=e?.resourceAttributes,{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??1e3}),this._logger)),this._metrics}get emails(){var e,t;return this._emails||(this._emails=new iV({secretKey:this.options.personalApiKey,host:this.host,appHost:this.options.appHost,requestTimeoutMs:"number"==typeof(e=this.options.emailRequestTimeoutMs)&&Number.isFinite(e)&&e>0?e:15e3,maxRetries:"number"==typeof(t=this.options.emailRequestMaxRetries)&&Number.isFinite(t)&&t>=0?Math.floor(t):2,migratedFrom:this.options.migratedFrom},{fetch:(e,t)=>this.fetch(e,t),isDisabled:()=>this.disabled,isClosed:()=>this._isShutdown,logger:this._logger,userAgent:this.getCustomUserAgent()||void 0})),this._emails}initializeSpanContextManager(){return new t2}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces){var e,t,r;let i,s;return this._traces||(this._traces=new t1(this,(e=this.options.traces,t=this.hostResourceAttributes(),r=this._logger,i=ts({...t},function(e){if(!(!e||"object"!=typeof e||Array.isArray(e)))try{if(t8.every(t=>!(t in e)||"string"==typeof e[t]))return e;let t={...e};for(let e of t8)e in t&&"string"!=typeof t[e]&&delete t[e];return t}catch{return}}(e?.resourceAttributes)),s=t6(e?.maxExportBatchSize,512),{serviceName:i?.["service.name"]??e?.serviceName,serviceVersion:i?.["service.version"]??e?.serviceVersion,environment:i?.["deployment.environment"]??e?.environment,resourceAttributes:i,beforeSpanSend:function(e,t){if(!e)return[];let r=[e].flat().filter(e=>!!e),i=r.filter(e=>"function"==typeof e);return i.length!==r.length&&t?.critical(`beforeSpanSend: ignoring ${r.length-i.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),i}(e?.beforeSpanSend,r),maxAttributesPerSpan:t6(e?.maxAttributesPerSpan,128),maxEventsPerSpan:t6(e?.maxEventsPerSpan,128),maxAttributesPerEvent:128,maxAttributeValueLength:t6(e?.maxAttributeValueLength,8192),flushIntervalMs:t6(e?.flushIntervalMs,5e3),maxExportBatchSize:s,maxQueueSize:Math.max(t6(e?.maxQueueSize,2048),s),maxLiveSpans:t6(e?.maxLiveSpans,1e4),maxSpanAgeMs:t6(e?.maxSpanAgeMs,36e5)}),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}}_tracingContext(){let e=this.context?.get();return{distinctId:e?.distinctId,sessionId:e?.sessionId}}startSpan(e,t){return this._tracesPipeline?.startSpan(e,t)??tN(t,this._spanContextManager.active())}withSpan(e,t,r){let i="function"==typeof t?void 0:t,s="function"==typeof t?t:r,n=this._tracesPipeline;return n?i?n.withSpan(e,i,s):n.withSpan(e,s):tV(this._spanContextManager,tN(i,this._spanContextManager.active()),s)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,r){"string"==typeof e&&this._logger.warn(t),"$exception"!==e.event||e._originatedFromCaptureException||this._logger.warn(r)}_sendPreparedEvent(e,t,r,i,s){return this.addPendingPromise(this._prepareEventMessage(t,i).then(({distinctId:t,event:i,properties:n,options:a})=>{let o={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},l={distinctId:t,event:i,properties:{...n,...this.getCommonEventProperties()}};return r?this.sendImmediate(e,l,o,s):this.enqueue(e,l,o,s)}).catch(e=>{e&&console.error(e)}))}_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=eA(e.uuid,eK);return this._sendPreparedAiEvent({...e,uuid:t},!1),t}async captureAiImmediate(e){if(this.disabled)return;let t=eA(e.uuid,eK);return await this._sendPreparedAiEvent({...e,uuid:t},!0),t}_sendPreparedAiEvent(e,t){return"string"!=typeof e?.event||e.event.startsWith("$ai_")||this._logger.debug(`captureAi called with non-AI event ${e.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",e,t,void 0,i$)}identify({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:n,...a}=t;this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:i||a,$set_once:s||{},$anon_distinct_id:n??void 0},disableGeoip:r},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:n,...a}=t;await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:i||a,$set_once:s||{},$anon_distinct_id:n??void 0},disableGeoip:r},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:r={}}){if(0===Object.keys(t).length&&0===Object.keys(r).length)return;let i={};Object.keys(t).length>0&&(i.$set=t),Object.keys(r).length>0&&(i.$set_once=r),this.capture({distinctId:e,event:"$set",properties:i})}unsetPersonProperties({distinctId:e,properties:t}){let r=(Array.isArray(t)?t:[t]).filter(e=>"string"==typeof e&&e.trim().length>0);0!==r.length&&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=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(t=>{let r=setTimeout(()=>{i(),t(!1)},e),i=this._events.on("localEvaluationFlagsLoaded",e=>{clearTimeout(r),i(),t(e>0)})})}_resolveDistinctId(e,t){return"string"==typeof e?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,r={},i){let s,n,a,o,l,u,c,h;if(this.disabled)return void this._logger.warn("The client is disabled");let d=r.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&e in this._flagOverrides){let t=this._flagOverrides[e];if(void 0===t)return;let r=this._payloadOverrides?.[e];return{key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:r}}let{groups:f,disableGeoip:p}=r,{onlyEvaluateLocally:g,personProperties:m,groupProperties:y}=r,_=this.addLocalPersonAndGroupProperties(t,f,m,y);m=_.allPersonProperties,y=_.allGroupProperties;let v=this.createFeatureFlagEvaluationContext(t,f,this.personPropertiesForLocalEvaluation(t,m),y);void 0==g&&(g=this.options.strictLocalEvaluation??!1);let b=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let t=this.featureFlagsPoller?.featureFlagsByKey[e];if(t)try{let r=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(t,v,{matchValue:i});if(r){b=!0;let i=r.value;l=t.id,c="Evaluated locally",h=t.has_experiment,s={key:e,enabled:!1!==i,variant:"string"==typeof i?i:void 0,payload:r.payload??void 0,reason:c,reasonCode:!1===t.active?"flag_disabled":void 0}}}catch(t){if(t instanceof rk||t instanceof rt)this._logger?.info(`${t.name} when computing flag locally: ${e}: ${t.message}`);else throw t}}if(!b&&!g){let t=await super.getFeatureFlagDetailsStateless(v.distinctId,v.groups,m,y,p,[e]);if(void 0===t)o=t9.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===t.minimalFlagCalledEvents,n=t.requestId,a=t.evaluatedAt;let r=[];t.errorsWhileComputingFlags&&r.push(t9.ERRORS_WHILE_COMPUTING),t.quotaLimited?.includes("feature_flags")&&r.push(t9.QUOTA_LIMITED);let i=t.flags[e];if(void 0===i)r.push(t9.FLAG_MISSING);else{let t;if(l=i.metadata?.id,u=i.metadata?.version,c=i.reason?.description??i.reason?.code,h=i.metadata?.has_experiment,i.metadata?.payload!==void 0)try{t=JSON.parse(i.metadata.payload)}catch{t=i.metadata.payload}s={key:e,enabled:i.enabled,variant:i.variant??void 0,payload:t,reason:c,reasonCode:i.reason?.code}}r.length>0&&(o=r.join(","))}}if(d){let r=void 0===s?void 0:!1!==s.enabled&&(s.variant??!0),i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:l,$feature_flag_version:u,$feature_flag_reason:c,locally_evaluated:b,[`$feature/${e}`]:r,$feature_flag_request_id:n,$feature_flag_evaluated_at:b?Date.now():a};if(void 0!==h&&(i.$feature_flag_has_experiment=h),b&&this.featureFlagsPoller){let e=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==e&&(i.$feature_flag_definitions_loaded_at=e)}o&&(i.$feature_flag_error=o),this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:r,groups:f,disableGeoip:p,properties:i})}return void 0!==s&&void 0!==this._payloadOverrides&&e in this._payloadOverrides&&(s={...s,payload:this._payloadOverrides[e]}),s}async getFeatureFlag(e,t,r){i2("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 i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(r?.sendFeatureFlagEvents)});if(void 0!==i)return!1!==i.enabled&&(i.variant??!0)}async getFeatureFlagPayload(e,t,r,i){if(i2("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."),void 0!==this._payloadOverrides&&e in this._payloadOverrides)return this._payloadOverrides[e];let s=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:!1},r);if(void 0!==s)return s.payload??null}async getFeatureFlagResult(e,t,r){let{distinctId:i,options:s}=this._resolveDistinctId(t,r);return i?this._getFeatureFlagResult(e,i,{...s,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(s?.sendFeatureFlagEvents)}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}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("string"==typeof r)try{return JSON.parse(r)}catch(e){}return r}async isFeatureEnabled(e,t,r){i2("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 i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(r?.sendFeatureFlagEvents)});return void 0===i?void 0:!1!==i.enabled&&!!(i.variant??!0)}async getAllFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);return r?(await this.getAllFlagsAndPayloads(r,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:r,options:i}=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:s,disableGeoip:n,flagKeys:a}=i||{},{onlyEvaluateLocally:o,personProperties:l,groupProperties:u}=i||{},c=this.addLocalPersonAndGroupProperties(r,s,l,u);l=c.allPersonProperties,u=c.allGroupProperties;let h=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,l),u);void 0==o&&(o=this.options.strictLocalEvaluation??!1);let d=await this.featureFlagsPoller?.getAllFlagsAndPayloads(h,a),f={},p={},g=!0;if(d&&(f=d.response,p=d.payloads,g=d.fallbackToFlags),g&&!o){let e=await super.getFeatureFlagsAndPayloadsStateless(h.distinctId,h.groups,l,u,n,a);f={...f,...e.flags||{}},p={...p,...e.payloads||{}}}return void 0!==this._flagOverrides&&(f={...f,...this._flagOverrides}),void 0!==this._payloadOverrides&&(p={...p,...this._payloadOverrides}),{featureFlags:f,featureFlagPayloads:p}}async evaluateFlags(e,t){let r,i,{distinctId:s,options:n}=this._resolveDistinctId(e,t);if(!s)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new t7({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new t7({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,flags:{}});let{groups:a,disableGeoip:o}=n||{},l=n?.flagKeys??void 0;if(l?.length===0)return new t7({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:a,disableGeoip:o,flags:{}});let{onlyEvaluateLocally:u,personProperties:c,groupProperties:h}=n||{},d=this.addLocalPersonAndGroupProperties(s,a,c,h);c=d.allPersonProperties,h=d.allGroupProperties;let f=this.createFeatureFlagEvaluationContext(s,a,this.personPropertiesForLocalEvaluation(s,c),h);void 0==u&&(u=this.options.strictLocalEvaluation??!1);let p=l?new Set(l):void 0,g={},m=!1,y=!1,_=await this.featureFlagsPoller?.getAllFlagsAndPayloads(f,l),v=new Set;if(_)for(let[e,t]of Object.entries(_.response)){let r=this.featureFlagsPoller?.featureFlagsByKey[e];g[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:_.payloads[e],id:r?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:r?.has_experiment},v.add(e)}let b=void 0!==p&&Array.from(p).some(e=>this.featureFlagsPoller?.featureFlagsByKey[e]===void 0);if((!_||_.fallbackToFlags||b)&&!u){let e=await super.getFeatureFlagDetailsStateless(f.distinctId,f.groups,c,h,o,l);if(e)for(let[t,s]of(this._minimalFlagCalledEvents=!0===e.minimalFlagCalledEvents,r=e.requestId,i=e.evaluatedAt,m=!!e.errorsWhileComputingFlags,y=Array.isArray(e.quotaLimited)&&e.quotaLimited.includes("feature_flags"),Object.entries(e.flags))){let e;if(!v.has(t)){if(s.metadata?.payload!==void 0)try{e=JSON.parse(s.metadata.payload)}catch{e=s.metadata.payload}g[t]={key:t,enabled:s.enabled,variant:s.variant,payload:e,id:s.metadata?.id,version:s.metadata?.version,reason:s.reason?.description??s.reason?.code,locallyEvaluated:!1,hasExperiment:s.metadata?.has_experiment}}}}if(void 0!==this._flagOverrides)for(let[e,t]of Object.entries(this._flagOverrides)){if(void 0===t){delete g[e];continue}let r=g[e];g[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:r?.payload,id:r?.id,version:r?.version,reason:r?.reason,locallyEvaluated:r?.locallyEvaluated??!1,hasExperiment:r?.hasExperiment}}if(void 0!==this._payloadOverrides)for(let[e,t]of Object.entries(this._payloadOverrides)){let r=g[e];r&&(g[e]={...r,payload:t})}if(void 0!==p)for(let e of Object.keys(g))p.has(e)||delete g[e];let w={};for(let[e,t]of Object.entries(_?.unresolved??{}))Object.prototype.hasOwnProperty.call(g,e)||(w[e]=t);return new t7({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:a,disableGeoip:o,flags:g,unresolvedFlags:w,requestId:r,evaluatedAt:i,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:m,quotaLimited:y})}_shouldSendMinimalFlagCalledEvent(e,t){return"$feature_flag_called"===e&&this._minimalFlagCalledEvents&&!1===t.$feature_flag_has_experiment}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:r,response:i,groups:s,disableGeoip:n,properties:a}=e,o=s&&Object.keys(s).length>0?`_${JSON.stringify(Object.entries(s).sort(([e],[t])=>e<t?-1:+(e>t)))}`:"",l=`${r}_${i}${o}`,u=this._distinctIdHasSentFlagCalls.get(t)??new Set;if(this._distinctIdHasSentFlagCalls.delete(t),this._distinctIdHasSentFlagCalls.set(t,u),!u.has(l)){for(u.add(l);this._distinctIdHasSentFlagCalls.size>Math.max(this.maxCacheSize,1);){let e=this._distinctIdHasSentFlagCalls.keys().next().value;if(void 0===e)break;this._distinctIdHasSentFlagCalls.delete(e)}this.capture({distinctId:t,event:"$feature_flag_called",properties:a,groups:s,disableGeoip:n})}}_resolveSendFeatureFlagEvents(e){return e??this.options.sendFeatureFlagEvent??!0}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),resolveSendFeatureFlagEvents:e=>this._resolveSendFeatureFlagEvents(e),logWarning:e=>{!1!==this.options.featureFlagsLogWarnings&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:s}){this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:s},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:s}){await this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:s},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=e=>Object.fromEntries(e.map(e=>[e,!0]));if(!1===e){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(!1===e.flags?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):void 0!==e.flags&&(this._flagOverrides={...e.flags})),"payloads"in e&&(!1===e.payloads?this._payloadOverrides=void 0:void 0!==e.payloads&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if("flags"in e){let t=e.flags;if(!1===t||Array.isArray(t)||"object"==typeof t&&null!==t)return!0}if("payloads"in e){let t=e.payloads;if(!1===t||"object"==typeof t&&null!==t)return!0}return!1}withContext(e,t,r){return this.context?this.context.run(e,()=>(ib(this),t()),r):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t),ib(this)}async _shutdown(e){let t=Date.now()+(e??3e4);this._isShutdown=!0;let r=this._emails?.drain(),i=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await eR(this._metrics.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._metrics.reset()),this._traces&&(await eR(this._traces.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._traces.reset());let s=Math.max(0,t-Date.now()),n=r?eR(r,s):void 0;try{return await super._shutdown(s)}finally{await n,this._distinctIdHasSentFlagCalls.clear(),i?.()}}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}`}},i=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let e=new AbortController;i=eM(()=>{e.abort()},this.options.requestTimeout),r.signal=e.signal}try{return await this.fetch(t,r)}catch(e){this._events.emit("error",e);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let r={},i={};for(let[s,n]of Object.entries(e))if(function(e){return"[object Object]"===Object.prototype.toString.call(e)}(n)&&t&&s in t){let e={};for(let[t,r]of Object.entries(n))e[String(t)]=String(r);i[String(s)]=e}else r[String(s)]=String(n);return{personProperties:r,groupProperties:i}}async getFeatureFlagsForEvent(e,t,r,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let s=i?.personProperties||{},n=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:n,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:a})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:n,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(e,t,s,n,r)).flags}addLocalPersonAndGroupProperties(e,t,r,i){let s={...r||{}},n={};if(t)for(let e of Object.keys(t))n[e]={$group_key:t[e],...i?.[e]||{}};return{allPersonProperties:s,allGroupProperties:n}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,r,i){return{distinctId:e,groups:t||{},personProperties:r||{},groupProperties:i||{},evaluationCache:{}}}captureException(e,t,r,i,s){if(!iu.isPreviouslyCapturedError(e)&&this.errorTracking.claimExplicitCapture(e)){let n=Error("PostHog syntheticException");this.addPendingPromise(iu.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:n},t,r,this.getContext()).then(e=>this._capturePreparedEvent({...e,uuid:i,flags:s},!1)))}}async captureExceptionImmediate(e,t,r,i){if(!iu.isPreviouslyCapturedError(e)&&this.errorTracking.claimExplicitCapture(e)){let s=Error("PostHog syntheticException");return this.addPendingPromise(iu.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,r,this.getContext()).then(e=>this.captureImmediate({...e,flags:i})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){var r;let{distinctId:i,event:s,properties:n,groups:a,flags:o,sendFeatureFlags:l,timestamp:u,disableGeoip:c,uuid:h}=e,d=(r=this.context?.get(),is in e?e[is]??void 0:r),f=t.includeContextProperties??!0,p=i||d?.distinctId,g=f?{...this.props,...d?.properties||{},...n||{}}:{...n||{}};"$exception"!==s||"$trace_id"in g||"$span_id"in g||Object.assign(g,await ig()),p||(p=eK(),g.$process_person_profile=!1),f&&d?.sessionId&&!g.$session_id&&(g.$session_id=d.sessionId);let m=this._shouldSendMinimalFlagCalledEvent(s,g)?eP(g):g,y=this._runBeforeSend({distinctId:p,event:s,properties:m,groups:a,flags:o,sendFeatureFlags:l,timestamp:u,disableGeoip:c,uuid:h});if(!y)return Promise.reject(null);let _=await Promise.resolve().then(async()=>{if(o)return l&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),o._getEventProperties();if(l){i2("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.");var e=await this.getFeatureFlagsForEvent(y.distinctId,a,c,"object"==typeof l?l:void 0);if(!e)return{};let t={};for(let[r,i]of Object.entries(e))t[`$feature/${r}`]=i;let r=Object.keys(e).filter(t=>!1!==e[t]).sort();return r.length>0&&(t.$active_feature_flags=r),t}return{}}).catch(()=>({})).then(e=>{let t=y.groups||a;return{...e,...y.properties||{},...void 0!==t&&Object.keys(t).length>0?{$groups:t}:{}}});return"$pageview"===y.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof _.$raw_user_agent&&t4(_.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(y.event="$bot_pageview",_.$browser_type="bot"),{distinctId:y.distinctId,event:y.event,properties:_,options:{timestamp:y.timestamp,disableGeoip:y.disableGeoip,uuid:y.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let r=Array.isArray(t)?t:[t],i=e;for(let t of r)try{if(!(i=t(i)))return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!i.properties||0===Object.keys(i.properties).length){let e=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(e)}}catch(t){return this._logger.error(`Error in before_send function for event '${e.event}':`,t),null}return i}}var i5=el,i4=el,i6=el,i8=el,i9=el,i7=el,se=el,st=el,sr=e.i(78500);let si=new WeakMap;function ss(e,t,r){let i=e&&si.get(e);return r?si.set(t,{signal:r,parent:i}):i&&si.set(t,i),t}class sn{constructor(){this.storage=new sr.AsyncLocalStorage}get(){let e=this.storage.getStore();return e&&function(e){let t=si.get(e);for(;t;){if(t.signal.aborted)return!1;t=t.parent}return!0}(e)?e:void 0}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){let r=this.get();return t?.fresh===!0?ss(void 0,{...e},t.signal):ss(r,{distinctId:e.distinctId??r?.distinctId,sessionId:e.sessionId??r?.sessionId,properties:{...r?.properties||{},...e.properties||{}}},t?.signal)}}class sa{active(){return this._storage.getStore()}with(e,t){return this._storage.run(e,t)}constructor(){this._storage=new sr.AsyncLocalStorage}}var so=e.i(27028);let sl=(0,e.i(12057).promisify)(so.gzip);async function su(e,t=!0){try{let t=await sl(e);return new Uint8Array(t)}catch(e){return t&&console.error("Failed to gzip compress data",e),null}}var sc=e.i(60526),il=el;let sh="posthog-node";function sd(e,{organization:t,projectId:r,prefix:i,severityAllowList:s=["error"],sendExceptionsToPostHog:n=!0}={}){return a=>{if(!("*"===s||s.includes(a.level)))return a;a.tags||(a.tags={});let o=a.tags[sp.POSTHOG_ID_TAG];if(void 0===o)return a;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${o}`,l).toString();a.tags["PostHog Person URL"]=u;let c=a.exception?.values||[],h=c.map(e=>({...e,stacktrace:e.stacktrace?{...e.stacktrace,type:"raw",frames:(e.stacktrace.frames||[]).map(e=>({...e,platform:"node:javascript"}))}:void 0})),d={$exception_message:c[0]?.value||a.message,$exception_type:c[0]?.type,$exception_level:a.level,$exception_list:h,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:c[0]?.value||a.message,$sentry_exception_type:c[0]?.type,$sentry_tags:a.tags},f=il.getInjectedReleaseId();return f&&(d.$release_id=f),t&&r&&(d.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+a.event_id),n&&e.capture({event:"$exception",distinctId:o,properties:d}),a}}function sf(e,t){let r=sd(e,t);return{name:sh,processEvent:e=>r(e)}}class sp{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,t,r,i,s){this.name=sh,this.name=sh,this.setupOnce=function(n,a){n(sd(e,{organization:t,projectId:a()?.getClient()?.getDsn()?.projectId,prefix:r,severityAllowList:i,sendExceptionsToPostHog:s??!0}))}}}function sg(e){let t={};if(e)for(let r of e.split(";")){let[e,...i]=r.trim().split("=");if(e){let r=i.join("=").trim();try{t[e.trim()]=decodeURIComponent(r)}catch{t[e.trim()]=r}}}return{get:e=>e in t?{value:t[e]}:void 0}}function sm(e){let t=e.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${t}_posthog`}function sy(e){let t=Date.now();return JSON.stringify({distinct_id:e,$device_id:e,$user_state:"anonymous",$sesid:[t,eK(),t]})}function s_(e,t){let r=sm(t),i=e.get(r);return i?sb(i.value):null}function sv(e){if(!e)return;let t={};return e.sessionId&&(t.$session_id=e.sessionId),e.deviceId&&(t.$device_id=e.deviceId),Object.keys(t).length>0?t:void 0}function sb(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||"object"!=typeof t||!t.distinct_id)return null;let r=y(t.$sesid)?t.$sesid:[],i=r[1];return{distinctId:String(t.distinct_id),isIdentified:"identified"===t.$user_state,sessionId:"string"==typeof i?i:void 0,sessionLastActivityTimestamp:sw(r[0]),sessionStartTimestamp:sw(r[2]),deviceId:"string"==typeof t.$device_id?t.$device_id:void 0}}catch{return null}}function sw(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}e.s(["PostHogSentryIntegration",0,sp,"createEventProcessor",0,sd,"sentryIntegration",0,sf],91573);let sx=/[\x00-\x1f\x7f-\x9f]/g;function sS(e,t,r){null!=r&&""!==r&&(e[t]=r)}function sF(e){return Array.isArray(e)?e[0]:e}function sE(e){if(Array.isArray(e)){for(let t of e){let e=sE(t);if(void 0!==e)return e}return}if("string"!=typeof e)return;let t=e.replace(sx,"").trim();if(t)return t.length>1e3?t.slice(0,1e3):t}function sP(e,t,r){return"number"==typeof e&&Number.isFinite(e)&&Math.abs(t-e)<=r}function sI(e,t){var r,i;let s,n,a=function(e,t){let r;if(!e)return{};let i=sE(e["x-posthog-session-id"]),s=sE(e["x-posthog-distinct-id"]),{sessionId:n,distinctId:a}=void 0===i&&void 0===s&&t?function(e,t,r=Date.now(),i=18e5,s=!1){try{let n;if("string"!=typeof e)return{};let a=sg(e.split(";").reverse().join(";")),o=a.get(sm(t))?.value,l=a.get("__ph_opt_in_out_"+t)?.value??"";if(!o||d(I,l)||s&&!d(P,l))return{};let u=JSON.parse(o);if(!u||"object"!=typeof u)return{};let c="identified"===u.$user_state?sE(u.distinct_id):void 0,h=u.$sesid;if(Array.isArray(h)&&(2===h.length||3===h.length)){let[e,t,s=e]=h;sP(e,r,i)&&sP(s,r,864e5)&&(n=sE(t))}return{...void 0!==n?{sessionId:n}:{},...void 0!==c?{distinctId:c}:{}}}catch{return{}}}(e.cookie,t.apiKey,Date.now(),"number"==typeof(r=t.sessionIdleTimeoutSeconds)&&Number.isFinite(r)&&0!==r?1e3*Math.min(Math.max(r,60),36e3):18e5,!0===t.optOutCapturingByDefault):{sessionId:i,distinctId:s};return{...void 0!==n?{sessionId:n}:{},...void 0!==a?{distinctId:a}:{}}}(t.headers,!0===(s=e.options.readPostHogCookie)?{apiKey:e.apiKey}:s&&"object"==typeof s?{apiKey:e.apiKey,sessionIdleTimeoutSeconds:s.sessionIdleTimeoutSeconds,optOutCapturingByDefault:s.optOutCapturingByDefault}:null),o=e.getContext(),l=o?.sessionId??a.sessionId,u=o?.distinctId??a.distinctId,c={},h=!0===e.options.disable_capture_url_hashes;return sS(c,"$current_url",(r=t.originalUrl||t.url,h?e$(r):r)),sS(c,"$request_method",t.method),sS(c,"$request_path",(i=t.path,n=function(e){if(!e)return e;let t=e.indexOf("?"),r=e.indexOf("#");return -1===t||-1!==r&&r<t?e:`${e.slice(0,t)}${-1===r?"":e.slice(r)}`}(i),h?e$(n):n)),sS(c,"$user_agent",sF(t.headers["user-agent"])),sS(c,"$ip",function(e){let t=sF(e.headers["x-forwarded-for"]);if(t){let e=t.split(",")[0].trim();if(e)return e}return e.socket?.remoteAddress}(t)),{...void 0!==l?{sessionId:l}:{},...void 0!==u?{distinctId:u}:{},properties:c}}function sA(e,t){var r;t.use((r=e,(e,t,i)=>{r.withContext(sI(r,e),()=>{ib(r,!0),i()})}))}function sk(e,t){var r;t.use((r=e,(e,t,i,s)=>{if(iu.isPreviouslyCapturedError(e))return void s(e);let n=sI(r,t),a=Error("Synthetic exception"),o={...void 0!==n.sessionId?{$session_id:n.sessionId}:{},...n.properties||{}};r.addPendingPromise(Promise.all([iu.buildEventMessage(r.getErrorPropertiesBuilder(),e,{mechanism:{type:"middleware",handled:!1},syntheticException:a},n.distinctId,o,r.getContext()),i.headersSent||i.destroyed?Promise.resolve(i.headersSent?i.statusCode:void 0):new Promise(e=>{let t=t=>{clearTimeout(s),i.removeListener("finish",r),i.removeListener("close",r),e(t)},r=()=>t(i.headersSent?i.statusCode:void 0),s=setTimeout(()=>t(void 0),1e3);s.unref(),i.once("finish",r),i.once("close",r)})]).then(([e,t])=>(void 0!==t&&(e.properties={...e.properties,$response_status_code:t}),r._capturePreparedEvent(e,!1)))),s(e)}))}e.s(["setupExpressErrorHandler",0,sk,"setupExpressRequestContext",0,sA],93546),e.i(91573),e.i(93546),e.i(58325),e.s(["EmailError",0,iR,"FeatureFlagError",0,h,"FeatureFlagEvaluations",0,t7,"PostHogSentryIntegration",0,sp,"cookieStateToProperties",0,sv,"cookieStoreFromHeader",0,sg,"createEventProcessor",0,sd,"enrichCurrentSpan",0,iw,"getPostHogCookieName",0,sm,"parsePostHogCookie",0,sb,"readPostHogCookie",0,s_,"sentryIntegration",0,sf,"serializePostHogCookie",0,sy,"setupExpressErrorHandler",0,sk,"setupExpressRequestContext",0,sA,"uuidv7",0,eK],57564),e.i(57564),e.s(["EmailError",0,iR,"FeatureFlagError",0,h,"FeatureFlagEvaluations",0,t7,"PostHog",0,class extends i3{getLibraryId(){return"posthog-node"}compressPayload(e){return su(e,this.isDebug)}initializeContext(){return new sn}initializeSpanContextManager(){return new sa}hostResourceAttributes(){return function(){var e,t;let r,i,s;try{r=(0,sc.platform)(),i=(0,sc.release)()}catch{}return e=r,t=i,{...(s=function(e){if(e)return Object.prototype.hasOwnProperty.call(tS,e)?tS[e]:e}(e))?{"os.name":s}:{},...t?{"os.version":t}:{}}}()}createErrorPropertiesBuilder(){let e;return new i5.ErrorPropertiesBuilder([new i4.EventCoercer,new i6.ErrorCoercer,new i8.ObjectCoercer,new i9.StringCoercer,new i7.PrimitiveCoercer],se.createStackParser("node:javascript",st.nodeStackLineParser),[(e=function(e=process.argv[1]?(0,l.dirname)(process.argv[1]):process.cwd(),t="\\"===l.sep){let r=t?u(e):e;return e=>{if(!e)return;let i=t?u(e):e,{dir:s,base:n,ext:a}=l.posix.parse(i);(".js"===a||".mjs"===a||".cjs"===a)&&(n=n.slice(0,-1*a.length));let o=decodeURIComponent(n);s||(s=".");let c=s.lastIndexOf("/node_modules");if(c>-1)return`${s.slice(c+14).replace(/\//g,".")}:${o}`;if(s.startsWith(r)){let e=s.slice(r.length+1).replace(/\//g,".");return e?`${e}:${o}`:o}return o}}(),async t=>{for(let r of t)r.module=e(r.filename);return t}),e=>eg(e,void 0,this._logger),function(e=process.cwd()){l.sep;let t=e=>e,r=t(e);return async e=>{for(let i of e)!(!i.filename||i.filename.startsWith("node:")||i.filename.startsWith("data:"))&&(0,l.isAbsolute)(i.filename)&&(i.filename=t((0,l.relative)(r,t(i.filename))));return e}}()])}},"PostHogSentryIntegration",0,sp,"cookieStateToProperties",0,sv,"cookieStoreFromHeader",0,sg,"createEventProcessor",0,sd,"enrichCurrentSpan",0,iw,"getPostHogCookieName",0,sm,"parsePostHogCookie",0,sb,"readPostHogCookie",0,s_,"sentryIntegration",0,sf,"serializePostHogCookie",0,sy,"setupExpressErrorHandler",0,sk,"setupExpressRequestContext",0,sA,"uuidv7",0,eK],28864)}];
1
+ module.exports=[28864,e=>{"use strict";let t,r,i,s,n,a;var o,l=e.i(14747);function u(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var c=((o={}).AnonymousId="anonymous_id",o.DistinctId="distinct_id",o.Props="props",o.EnablePersonProcessing="enable_person_processing",o.PersonMode="person_mode",o.FeatureFlagDetails="feature_flag_details",o.FeatureFlags="feature_flags",o.FeatureFlagPayloads="feature_flag_payloads",o.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",o.BootstrapFeatureFlags="bootstrap_feature_flags",o.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",o.OverrideFeatureFlags="override_feature_flags",o.Queue="queue",o.AiQueue="ai_queue",o.AiCaptureQueue="ai_capture_queue",o.LogsQueue="logs_queue",o.OptedOut="opted_out",o.SessionId="session_id",o.SessionStartTimestamp="session_start_timestamp",o.SessionLastTimestamp="session_timestamp",o.PersonProperties="person_properties",o.GroupProperties="group_properties",o.InstalledAppBuild="installed_app_build",o.InstalledAppVersion="installed_app_version",o.SessionReplay="session_replay",o.PushRegistered="push_registered",o.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",o.SurveyLastSeenDate="survey_last_seen_date",o.SurveysInProgress="surveys_in_progress",o.SurveysSeen="surveys_seen",o.Surveys="surveys",o.RemoteConfig="remote_config",o.FlagsEndpointWasHit="flags_endpoint_was_hit",o.DeviceId="device_id",o);let h={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",EVALUATION_FAILED:"evaluation_failed",LOCAL_EVALUATION_INCONCLUSIVE:"local_evaluation_inconclusive",QUOTA_LIMITED:"quota_limited",TIMEOUT:"timeout",CONNECTION_ERROR:"connection_error",UNKNOWN_ERROR:"unknown_error",apiError:e=>`api_error_${e}`};function d(e,t){return -1!==e.indexOf(t)}function f(e){let t=[];return JSON.stringify(e,function(e,r){if("bigint"==typeof r)return r.toString();if("function"!=typeof r&&"symbol"!=typeof r){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&"object"==typeof r){for(;t.length>0&&t[t.length-1]!==this;)t.pop();if(t.includes(r))return"[Circular]";t.push(r)}return r}})??"null"}let p=Array.isArray,g=Object.prototype,m=g.hasOwnProperty,_=g.toString,y=p||function(e){return"[object Array]"===_.call(e)},v=e=>void 0===e,b=e=>"[object String]"==_.call(e),w=e=>b(e)&&0===e.trim().length,x=e=>null===e,S=e=>v(e)||x(e),F=e=>"[object Number]"==_.call(e)&&e==e,E=e=>"[object Boolean]"===_.call(e);function P(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 C(e,Error)}}function A(e){return"u">typeof Event&&C(e,Event)}function I(e){return"[object Object]"===Object.prototype.toString.call(e)}function C(e,t){try{return e instanceof t}catch{return!1}}let k=[!0,"true",1,"1","yes"],$=[!1,"false",0,"0","no"];function T(e,t,r){return e&&r?t.length===Object.keys(r).length&&t.every(t=>e[t]===r[t]):e===r}class O{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){let r=t&&t.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(r,t,0).apply(e),s=this.buildParsingContext(t),n=this.parseStacktrace(i,s);return{$exception_list:this.convertToExceptionList(n,r),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&y(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,i;if(null!=e.cause&&(r=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack)try{i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)}catch{}return{...e,cause:r,stack:i,errors:e.errors?.map(e=>this.parseStacktrace(e,t))}}applyChunkIds(e,t){return e.map(e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e))}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 e of this.modifiers)t=await e(t);return t}convertToExceptionList(e,t){let r=[],i=(e,s,n)=>{let a=r.length,o=void 0===s?{type:"string"==typeof t.type&&t.type.length>0?t.type:"generic",..."boolean"==typeof t.handled?{handled:t.handled}:void 0===t.handled?{handled:!0}:{},synthetic:"boolean"==typeof t.synthetic?t.synthetic:e.synthetic,exception_id:a}:{type:"chained",source:n,synthetic:e.synthetic,exception_id:a,parent_id:s},l={type:e.type,value:e.value,mechanism:o};for(let t of(e.stack&&(l.stacktrace={type:"raw",frames:e.stack}),r.push(l),e.cause&&i(e.cause,a,"cause"),e.errors??[]))i(t,a,"member")};return i(e),r}buildParsingContext(e){return{chunkIdMap:function(e){let n=globalThis._posthogChunkIds,a=globalThis._debugIds;if(!n&&!a)return;let o=n?Object.keys(n):[],l=a?Object.keys(a):[];if(s&&T(n,o,r)&&T(a,l,i))return s;r=n?{...n}:void 0,i=a?{...a}:void 0,s={},t??={};let u=(r,i)=>{for(let n of r){let r=i[n];if(!r)continue;let a=t?.[n];if(a){s[a]=r;continue}let o=e(n);for(let e=o.length-1;e>=0;e--){let i=o[e]?.filename;if(i){s[i]=r,t[n]=i;break}}}};return a&&u(l,a),n&&u(o,n),s}(this.stackParser),skipFirstLines:e.skipFirstLines??1}}getAggregateErrors(e){try{if(P(e)){let t=Object.getPrototypeOf(e);for(let r=0;t&&r<100;r++){let r=Object.getOwnPropertyDescriptor(t,"constructor")?.value;if("function"==typeof r&&"AggregateError"===r.name){let t=e.errors;return y(t)?t:void 0}t=Object.getPrototypeOf(t)}}}catch{}}buildCoercingContext(e,t,r=0){let i=0,s=0,n=!1,a=new Set,o=[],l={},u=(e,t,r=0)=>{let u,h,d=c(t,r),f=d.apply;if(d.apply=t=>{o.push(e);try{return f(t)}finally{o.pop()}},r>4||r>0&&-1!==o.indexOf(e))return this.coerceFallback(d);let p="object"==typeof e&&null!==e||"function"==typeof e;if(0===r&&i>=50||p&&a.has(e))return;p&&a.add(e),0===r&&i++;let g=this.getAggregateErrors(e);n||=!!g;try{if(!(u=this.applyCoercers(e,d)))throw l}catch(e){if(e===l){0===r&&i--;return}if(!n)throw e;u=this.coerceFallback(d)}if(!g||i>=50)return u;try{h=g.length}catch{return u}if(!Number.isInteger(h)||h<0||h>0xffffffff)return u;let m=[];for(let e=0;i<50&&s<1e3&&e<h;e++){let r;s++;try{r=d.next(g[e])}catch{i++,r=this.coerceFallback(c(t+1))}r&&m.push(r)}return{...u,errors:m}},c=(r,i=0)=>({...t,syntheticException:0==r?t.syntheticException:void 0,mechanism:0==r?e:{},apply:e=>{let t=u(e,r,i+1);if(!t)throw l;return t},next:e=>u(e,r+1)}),h=c(r);return{...h,apply:e=>u(e,r)??this.coerceFallback(h)}}}e.s(["ErrorPropertiesBuilder",0,O],80446),e.i(80446);let R=/^([a-z][a-z0-9.+-]+):/i,M=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function j(e,t,r,i,s){let n={platform:e,filename:t,function:"<anonymous>"===r?"?":r,in_app:function(e){if(!e||"<anonymous>"===e)return!1;let t=R.exec(e);return!t||M.includes(t[1].toLowerCase())}(t)};return v(i)||(n.lineno=i),v(s)||(n.colno=s),n}let L=(e,t)=>{let r=-1!==e.indexOf("safari-extension"),i=-1!==e.indexOf("safari-web-extension");return r||i?[-1!==e.indexOf("@")?e.split("@")[0]:"?",r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},D=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,B=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,N=/\((\S*)(?::(\d+))(?::(\d+))\)/,q=(e,t)=>{let r=D.exec(e);if(r){let[,e,i,s]=r;return j(t,e,"?",+i,+s)}let i=B.exec(e);if(i){if(i[2]&&0===i[2].indexOf("eval")){let e=N.exec(i[2]);e&&(i[2]=e[1],i[3]=e[2],i[4]=e[3])}let[e,r]=L(i[1]||"?",i[2]);return j(t,r,e,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},U=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,H=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,W=(e,t)=>{let r=U.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let e=H.exec(r[3]);e&&(r[1]=r[1]||"eval",r[3]=e[1],r[4]=e[2],r[5]="")}let e=r[3],i=r[1]||"?";return[i,e]=L(i,e),j(t,e,i,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}},K=/\(error: (.*)\)/;function V(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function z(e,t){let r=t.start;for(;r>0&&V(e[r-1],e[r-1+t.length]);)r--;return t.start-r}function Q(e,t){let r=t.start+t.length,i=r;for(;i<e.length&&V(e[i],e[i-t.length]);)i++;return i-r}function G(e,...t){return(r,i=0)=>{let s=[],n=r.split("\n"),a=Math.min(n.length,i+1e3),o=[];for(let r=i;r<a;r++){let i=n[r];if(i.length>1024)continue;let a=K.test(i)?i.replace(K,"$1"):i;if(!a.match(/\S*Error: /)){for(let r of t){let t=r(a,e);if(t){s.push(t);let e=function(e){for(let t=1;t<=10;t++){let r=e.length-2*t;if(r<0)break;let i=!0;for(let s=0;s<t;s++)if(!V(e[r+s],e[r+t+s])){i=!1;break}if(i){for(let i=0;i<t;i++)e[r+i]=e[r+t+i];return e.length=r+t,{start:r,length:t}}}}(s);if(e){for(let t=o.length-1;t>=0;t--){let r=o[t];if(r.start+r.length<=e.start)break;o.pop()}o.push(e)}break}}if(function(e,t){let r=t[0],i=e.length-(r?z(e,r):0);for(let r of t)i-=Q(e,r);return i}(s,o)>=50)break}}let l=[...o].sort((e,t)=>t.start-e.start),u=l[l.length-1];if(u){let e=z(s,u);for(let t of(s.splice(u.start-e,e),l))t.start-=e}for(let e of l)!function(e,t){let r=t.start+t.length,i=Q(e,t);i&&e.splice(r+i===e.length?r:t.start,i)}(s,e);o.some(e=>0===e.start&&s.length===e.length)&&function(e){let t=e.map(e=>`${e.function}|${e.filename}|${e.lineno}|${e.colno}|${e.module}`),r=0;for(let e=1;e<t.length;e++)(function(e,t,r){for(let i=0;i<e.length;i++){let s=e[(t+i)%e.length],n=e[(r+i)%e.length];if(s!==n)return s<n}return!1})(t,e,r)&&(r=e);e.push(...e.splice(0,r))}(s);if(!s.length)return[];let c=Array.from(s);return c.reverse(),c.slice(0,50).map(e=>{var t;return{...e,filename:e.filename||((t=c)[t.length-1]||{}).filename,function:e.function||"?"}})}}let J=/^\s*[-]{4,}$/,Z=/at (?:async (?!\((?!.*\)\s+\()))?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,Y=/^Promise\.(?:all|any)$/,X=/^index \d+$/,ee=(e,t)=>{let r=e.match(Z);if(r){let e,i,s,n,a;if(r[1]){let t=(s=r[1]).lastIndexOf(".");if("."===s[t-1]&&t--,t>0){e=s.slice(0,t),i=s.slice(t+1);let r=e.indexOf(".Module");r>0&&(s=s.slice(r+1),e=e.slice(0,r))}n=void 0}i&&(n=e,a=i),"<anonymous>"===i&&(a=void 0,s=void 0),void 0===s&&(a=a||"?",s=n?`${n}.${a}`:a);let o=r[2]?.startsWith("file://")?r[2].slice(7):r[2],l="native"===r[5];return o?.match(/\/[A-Z]:/)&&(o=o.slice(1)),o||!r[5]||l||(o=r[5]),Y.test(s)&&X.test(o||"")&&(o="node:internal/promise"),{filename:o?decodeURI(o):void 0,module:void 0,function:s,lineno:et(r[3]),colno:et(r[4]),in_app:function(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==e&&!e.includes("node_modules/")}(o||"",l),platform:t}}if(e.match(J))return{filename:e,platform:t}};function et(e){return parseInt(e||"",10)||void 0}e.s(["createStackParser",0,G,"nodeStackLineParser",0,ee],70736),e.i(70736),e.s([],29569),e.i(29569);class er{match(e){return P(e)}coerce(e,t){let r=this.getStack(e),i=void 0===r?t.syntheticException?.stack:void 0;return{type:this.getType(e),value:this.getMessage(e,t),stack:r??i,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;return r.error&&"string"==typeof r.error.message?String(r.error.message):String(r)}getStack(e){try{let t=e.stacktrace;if("string"==typeof t&&t.length>0)return t;let r=e.stack;return"string"==typeof r&&r.length>0?r:void 0}catch{return}}}e.s(["ErrorCoercer",0,er],11475),e.i(11475),e.s([],43179),e.i(43179);let ei=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class es{match(e){return"string"==typeof e}coerce(e,t){let[r,i]=this.getInfos(e);return{type:r??"Error",value:i??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",r=e,i=e.match(ei);return i&&(t=i[1],r=i[2]),[t,r]}}e.s(["StringCoercer",0,es],45098),e.i(45098);let en=["fatal","error","warning","log","info","debug"];function ea(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";let i="";for(let e of r){let r=i?`${i}, ${e}`:e;if(r.length>t)break;i=r}return i}class eo{match(e){return"object"==typeof e&&null!==e}coerce(e,t){let r=this.getErrorPropertyFromObject(e);return r?t.apply(r):{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(A(e))return e.constructor.name;let t="name"in e?e.name:void 0;return b(t)&&!w(t)?t:"Error"}getValue(e){if("name"in e&&"string"==typeof e.name){let t=`'${e.name}' captured as exception`;return"message"in e&&"string"==typeof e.message&&(t+=` with message: '${e.message}'`),t}if("message"in e&&"string"==typeof e.message)return e.message;let t=this.getObjectClassName(e),r=ea(e);return`${t&&"Object"!==t?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return b(e)&&!w(e)&&en.indexOf(e)>=0}getStack(e){try{if(b(e.stacktrace)&&e.stacktrace.length>0)return e.stacktrace;return b(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(P(r))return r}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){return}}}e.s(["ObjectCoercer",0,eo],6881),e.i(6881);class el{match(e){return A(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${ea(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["EventCoercer",0,el],80322),e.i(80322);class eu{match(e){return null===e||"object"!=typeof e}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["PrimitiveCoercer",0,eu],80049),e.i(80049),e.s([],98689),e.i(98689),e.s(["ErrorCoercer",0,er,"EventCoercer",0,el,"ObjectCoercer",0,eo,"PrimitiveCoercer",0,eu,"StringCoercer",0,es],21854),e.i(21854);class ec{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(void 0!==t)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}}e.s(["ReduceableCache",0,ec],46986),e.i(46986);function eh(){if("u">typeof process){let e=process.env.POSTHOG_RELEASE_ID?.trim();if(e)return e}let e=globalThis._posthogReleaseId;return"string"==typeof e&&e.length>0?e:void 0}e.s([],52001),e.i(52001),e.s(["getInjectedReleaseId",0,eh],41508),e.i(41508),e.s(["ErrorCoercer",0,er,"ErrorPropertiesBuilder",0,O,"EventCoercer",0,el,"ObjectCoercer",0,eo,"PrimitiveCoercer",0,eu,"ReduceableCache",0,ec,"StringCoercer",0,es,"createStackParser",0,G,"getInjectedReleaseId",0,eh,"nodeStackLineParser",0,ee],96117);var ed=e.i(96117),ed=ed,ef=e.i(2157),ep=e.i(12714),eg=e.i(50227),em=e.i(1457);let e_=new ed.ReduceableCache(25),ey=new ed.ReduceableCache(20);async function ev(e,t=ep.open,r){let i,s={};try{i=process.cwd()}catch{}for(let t=e.length-1;t>=0;t--){var n,a;let r=e[t],o=r?.filename;!(!r||"string"!=typeof o||"number"!=typeof r.lineno||(n=o).startsWith("node:")||n.endsWith(".min.js")||n.endsWith(".min.cjs")||n.endsWith(".min.mjs")||n.startsWith("data:")||void 0!==(a=r).lineno&&a.lineno>1e4||void 0!==a.colno&&a.colno>1e3)&&((0,eg.isAbsolute)(o)||void 0!==i)&&(s[o]||(s[o]=[]),s[o].push(r.lineno))}let o=Object.keys(s);if(0==o.length)return e;let l=[];for(let e of o){let n=eS(e,i);if(void 0===n||ey.get(n))continue;let a=s[e];if(!a)continue;a.sort((e,t)=>e-t);let o=function(e){if(!e.length)return[];let t=0,r=e[0];if("number"!=typeof r)return[];let i=eF(r),s=[];for(;;){if(t===e.length-1){s.push(i);break}let r=e[t+1];if("number"!=typeof r)break;r<=i[1]?i[1]=r+7:(s.push(i),i=eF(r)),t++}return s}(a);if(o.every(e=>(function(e,t){let r=e_.get(e);if(void 0===r)return!1;for(let e=t[0];e<=t[1];e++)if(void 0===r[e])return!1;return!0})(n,e)))continue;let u=function(e,t,r){let i=e.get(t);return void 0===i?(e.set(t,r),r):i}(e_,n,{});l.push(ew(e,o,u,n,t,r))}return await Promise.all(l).catch(()=>{}),e&&e.length>0&&function(e,t,r){for(let i of e)if(i.filename&&void 0===i.context_line&&"number"==typeof i.lineno){let e=eS(i.filename,r),s=void 0===e?void 0:t.get(e);if(void 0===s)continue;!function(e,t,r){if(void 0===t.lineno||void 0===r)return;t.pre_context=[];for(let i=eE(e);i<e;i++){let e=r[i];if(void 0===e)return void ex(t);t.pre_context.push(e)}if(void 0===r[e])return ex(t);t.context_line=r[e];let i=function(e){return e+7}(e);t.post_context=[];for(let s=e+1;s<=i;s++){let e=r[s];if(void 0===e)break;t.post_context.push(e)}}(i.lineno,i,s)}}(e,e_,i),e_.reduce(),e}async function eb(e,t,r){let i,s=!1;try{i=await t(e,ef.constants.O_RDONLY|ef.constants.O_NONBLOCK);let n=await i.stat();if(!n.isFile())return;if(n.size>0xa00000)return void r?.debug(`Skipping source context for oversized file ${e}: ${n.size} bytes exceeds 10485760`);return s=!0,i}catch{return}finally{i&&!s&&await i.close().catch(()=>{})}}async function ew(e,t,r,i,s,n){let a=await eb(e,s,n);return void 0===a?void ey.set(i,1):new Promise(e=>{let s,n,o=!1;function l(t){o||(o=!0,t?.destroy(),a.close().then(e,e))}try{s=a.createReadStream({autoClose:!1,start:0,end:0x9fffff})}catch{ey.set(i,1),l();return}try{n=(0,em.createInterface)({input:s})}catch{ey.set(i,1),l(s);return}let u=0,c=0,h=t[0];if(void 0===h)return void l(s);let d=h[0],f=h[1];function p(){ey.set(i,1),n.close(),n.removeAllListeners(),l(s)}s.on("error",p),n.on("error",p),n.on("close",()=>l(s)),n.on("line",e=>{if(!(++u<d)&&(r[u]=function(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let s=Math.max(t-60,0);s<5&&(s=0);let n=Math.min(s+140,i);return n>i-5&&(n=i),n===i&&(s=Math.max(n-140,0)),r=r.slice(s,n),s>0&&(r=`...${r}`),n<i&&(r+="..."),r}(e,0),u>=f)){if(c===t.length-1){n.close(),n.removeAllListeners();return}let e=t[++c];if(void 0===e){n.close(),n.removeAllListeners();return}d=e[0],f=e[1]}})})}function ex(e){delete e.pre_context,delete e.context_line,delete e.post_context}function eS(e,t){return(0,eg.isAbsolute)(e)?JSON.stringify([null,e]):void 0===t?void 0:JSON.stringify([t,e])}function eF(e){return[eE(e),e+7]}function eE(e){return Math.max(1,e-7)}class eP{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,t){for(let r of this.events[e]||[])r(t);for(let r of this.events["*"]||[])r(e,t)}}let eA=e=>void 0===e||!0===e.failed?void 0:e.variant??e.enabled,eI=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}},eC=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","bfcid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],ek=(e,t=[])=>{let r={},i=t=>{void 0!==e[t]&&(r[t]=e[t])};return eC.forEach(i),t.forEach(i),r},e$=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function eT(e,t){return"string"==typeof e&&e$.test(e)?e:t()}function eO(e,t){let r=Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function eR(e){return e?.replace(/\/+$/,"")}function eM(e){return e?e.split("#")[0]:e}async function ej(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(e=>setTimeout(e,t.retryDelay));try{return await e()}catch(e){if(r=e,!t.retryCheck(e))throw e}}throw r}function eL(){return new Date().toISOString()}function eD(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}async function eB(e,t,r){let i;try{return await Promise.race([e,new Promise((e,s)=>{i=eD(()=>{try{r?.(),e()}catch(e){s(e)}},t)})])}finally{clearTimeout(i)}}function eN(e){return Promise.all(e.map(e=>(e??Promise.resolve()).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}let eq=e=>{throw eO("NativeGzipValidationError",`Native gzip produced invalid output: ${e}`)},eU=async(e,t)=>{e.size<18&&eq("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());r.length>=2&&31===r[0]&&139===r[1]&&8===r[2]||eq("invalid-header");let i=new DataView(await e.slice(e.size-8).arrayBuffer());i.getUint32(0,!0)!==(e=>{let t=(()=>{if(n)return n;n=[];for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t=1&t?0xedb88320^t>>>1:t>>>1;n[e]=t>>>0}return n})(),r=0xffffffff;for(let i=0;i<e.length;i++)r=t[(r^e[i])&255]^r>>>8;return(0xffffffff^r)>>>0})(t)&&eq("invalid-crc");let s=t.length>>>0;i.getUint32(4,!0)!==s&&eq("invalid-size")};async function eH(e,t=!0,r){try{let t=new TextEncoder().encode(e),r=new globalThis.CompressionStream("gzip"),i=r.writable.getWriter(),s=i.write(t).then(()=>i.close()).catch(async e=>{try{await i.abort(e)}catch{}throw e}),n=new Response(r.readable).blob(),[a]=await Promise.all([n,s]);return await eU(a,t),a}catch(e){if(r?.rethrow)throw e;return t&&console.error("Failed to gzip compress data",e),null}}let eW="0123456789abcdef";class eK{constructor(e){this.bytes=e}static ofInner(e){if(16===e.length)return new eK(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,r,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||e<0||t<0||r<0||i<0||e>0xffffffffffff||t>4095||r>0x3fffffff||i>0xffffffff)throw RangeError("invalid field value");let s=new Uint8Array(16);return s[0]=e/0x10000000000,s[1]=e/0x100000000,s[2]=e/0x1000000,s[3]=e/65536,s[4]=e/256,s[5]=e,s[6]=112|t>>>8,s[7]=t,s[8]=128|r>>>24,s[9]=r>>>16,s[10]=r>>>8,s[11]=r,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new eK(s)}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("")}if(t){let e=new Uint8Array(16);for(let r=0;r<16;r+=4){let i=parseInt(t.substring(2*r,2*r+8),16);e[r+0]=i>>>24,e[r+1]=i>>>16,e[r+2]=i>>>8,e[r+3]=i}return new eK(e)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=eW.charAt(this.bytes[t]>>>4),e+=eW.charAt(15&this.bytes[t]),(3===t||5===t||7===t||9===t)&&(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=eW.charAt(this.bytes[t]>>>4),e+=eW.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(e=>0===e)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(e=>255===e)?"MAX":"VAR_RESERVED";throw Error("unreachable")}getVersion(){return"VAR_10"===this.getVariant()?this.bytes[6]>>>4:void 0}clone(){return new eK(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(let t=0;t<16;t++){let r=this.bytes[t]-e.bytes[t];if(0!==r)return Math.sign(r)}return 0}}class eV{constructor(e){this.timestamp=0,this.counter=0,this.random=e??ez()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);return void 0===r&&(this.timestamp=0,r=this.generateOrAbortCore(e,t)),r}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>0x3ffffffffff&&(this.timestamp++,this.resetCounter())}return eK.fromFieldsV7(this.timestamp,Math.trunc(this.counter/0x40000000),0x3fffffff&this.counter,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,eK.ofInner(e)}}let ez=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),eQ=()=>eG().toString(),eG=()=>(a||(a=new eV)).generate();class eJ{add(e){let t=eQ(),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(e=>e.promise),t=e.length;for(;t>0;)await Promise.all(e),t=(e=Object.values(this.promiseByIds).map(e=>e.promise)).length}getPromises(e=[],t=this.nextId){let r=new Set(e);return Object.values(this.promiseByIds).filter(e=>e.id<=t&&!r.has(e.promise)).map(e=>e.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}let eZ=(e,t,r)=>{function i(s,...n){t(()=>{(0,r[s])(e,...n)})}return{debug:(...e)=>{i("debug",...e)},info:(...e)=>{i("log",...e)},warn:(...e)=>{i("warn",...e)},error:(...e)=>{i("error",...e)},critical:(...t)=>{r.error(e,...t)},createLogger:i=>eZ(`${e} ${i}`,t,r)}};function eY(e,t=Date.now(),r=3e5){if("string"!=typeof e||!e)return;let i=e.trim(),s=/^\d+\s*,/.test(i)?i.slice(0,i.indexOf(",")).trim():i;if(/^\d+$/.test(s)){let e=1e3*Math.min(Number(s),r/1e3);return e>0?e:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(s))return;let n=Date.parse(/^\w{3} \w{3} /.test(s)?s+" GMT":s)-t;if(Number.isFinite(n)&&!(n<=0))return Math.min(n,r)}class eX{record(e){if("too-large"===e.kind)return;if("retry-later"!==e.kind)return void this.reset();if(!e.retryAfterMs)return;let t=this.isOpen(),r=Date.now(),i=Math.min(e.retryAfterMs,3e5);if(!t){this._installedAt=r,this._until=r+i;return}this._until=Math.max(this._until,Math.min(r+i,this._installedAt+3e5))}remainingMs(){let e=Date.now();if(e<this._installedAt-5e3)return this.reset(),0;let t=Math.min(3e5,Math.max(0,this._until-e));return 0===t&&this.reset(),t}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}}class e0 extends Error{constructor(e,t,r,i){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.responseBodyDeadline=r,this.abortController=i,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return eY(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=eO("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e,t=new Promise((e,t)=>{this.responseBodyTimer=eD(()=>{this._bodyReadTimedOut=!0;let e=eO("AbortError","Response body read timed out");t(e),this.cancelResponseBody(e)},this.responseBodyDeadline-Date.now())});try{e=Promise.resolve(this.response.text())}catch(t){e=Promise.reject(t)}this.responseBodyTextPromise=Promise.race([e,t]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(e=>JSON.parse(e))}cancelResponseBody(e){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(e),(async()=>{try{await this.response.body?.cancel()}catch{}})()}}class e1 extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}async function e2(e){if(e instanceof e0){let t="";try{t=await e.text}catch{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 e5(e){return e instanceof e1}function e3(e){if(e instanceof e0)return 502===e.status||504===e.status;if(!(e instanceof e1))return!1;let t=e.error;return"ECONNREFUSED"!==(t?.code??t?.cause?.code)}function e4(e){try{if("string"!=typeof e)return e instanceof Uint8Array?e.byteLength:e.size;if("u">typeof Buffer)return Buffer.byteLength(e,"utf8");return new TextEncoder().encode(e).length}catch{return 0}}function e6(e){return"object"==typeof e&&e instanceof e0&&413===e.status}function e8(e){return e instanceof e0?408===e.status||429===e.status||e.status>=500:e5(e)}function e9(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}let e7="default";class te{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new O([new er,new eo,new es,new eu],G("web:javascript",q,W))}getEvaluationRuntime(){}getFlagsResponseFormat(){return{version:2,read:e=>(e=>{if("flags"in e){let t,r=Object.fromEntries(Object.entries(e.flags??{}).map(([e,t])=>[e,eA(t)]).filter(([,e])=>void 0!==e)),i=Object.fromEntries(Object.keys(t=e.flags??{}).filter(e=>{let r=t[e];return!r.failed&&r.enabled&&r.metadata&&void 0!==r.metadata.payload}).map(e=>{let r=t[e].metadata?.payload;return[e,r?eI(r):void 0]}));return{...e,featureFlags:r,featureFlagPayloads:i}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([e,t])=>[e,eI(t)])),i=Object.fromEntries(Object.entries(t).map(([e,t])=>{var i,s;return[e,{key:e,enabled:"string"==typeof(i=t)||i,variant:"string"==typeof i?i:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:(s=r[e])?JSON.stringify(s):void 0,description:void 0}}]}));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}})(e)}}get apiKey(){return this.projectToken}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new eJ,this._events=new eP,this._isInitialized=!1;let r="string"==typeof e?e.trim():"",i="string"==typeof t.host?t.host.trim():"",s=!r;this._logger=function(e,t=e=>e()){return eZ(e,t,function(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),s&&this._logger.error("You must pass your PostHog project token. The client will be disabled."),this.projectToken=r,this.host=eR(i||"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??1e3),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??3e3,retryCheck:e8},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||s,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=!("CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&"function"==typeof Response.prototype.blob)||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){return this.disabled?void this._logger.warn("The client is disabled"):this._isInitialized?e():void this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(c.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(c.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(c.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let e=this.on("*",(e,t)=>this._logger.info(e,t));this.removeDebugCallback=()=>{e(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},r=this.mergeCommonEventProperties(t);var i=r;for(let e of Object.keys(t))(e.startsWith("$feature/")||"$active_feature_flags"===e)&&(i[e]=t[e]);return"$feature_flag_called"===e.event&&!1===r.$feature_flag_has_experiment&&this.isMinimalFlagCalledEventsEnabled()&&(r=ek(r)),{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 i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",i,r)})}async identifyStatelessImmediate(e,t,r){let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",i,r)}captureStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",s,i)})}async captureStatelessImmediate(e,t,r,i){let s=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",s,i)}aliasStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",s,i)})}async aliasStatelessImmediate(e,t,r,i){let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",s,i)}groupIdentifyStateless(e,t,r,i,s,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...n||{}}});this.enqueue("capture",a,i)})}async groupIdentifyStatelessImmediate(e,t,r,i,s,n){let a=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...n||{}}});await this.sendImmediate("capture",a,i)}async getRemoteConfig(){await this._initPromise;let e=this.host;"https://us.i.posthog.com"===e?e="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===e&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.projectToken}/config`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,r,{type:"required",consume:e=>e.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(e=>{this._logger.error("Remote config could not be loaded",e),this._events.emit("error",e)})}async getFlags(e,t={},r={},i={},s={},n=!1){await this._initPromise;let a=this.getFlagsResponseFormat(),o=`${this.host}/flags/?v=${a.version}${n?"&config=true":""}`,l={token:this.projectToken,distinct_id:e,groups:t,person_properties:r,group_properties:i,...s};r.$device_id&&(l.$device_id=r.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(l.evaluation_contexts=this.evaluationContexts);let u=this.getEvaluationRuntime();u&&(l.evaluation_runtime=u);let c={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(l)};return this._logger.info("Flags URL",o),this.fetchWithRetry(o,c,{type:"required",consume:e=>e.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:e3},this.featureFlagsRequestTimeoutMs).then(e=>({success:!0,response:a.read(e)})).catch(e=>(this._events.emit("error",e),{success:!1,error:this.categorizeRequestError(e)}))}categorizeRequestError(e){if(e instanceof e0)return{type:"api_error",statusCode:e.status};if(e instanceof e1){let t=e.error;return t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,r={},i={},s={},n){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(e,t,r,i,s,n);if(void 0===a)return{response:void 0,requestId:void 0};let o=eA(a.response);return void 0===o&&(o=!1),{response:o,requestId:a.requestId}}async getFeatureFlagDetailStateless(e,t,r={},i={},s={},n){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,r,i,s,n,[e]);if(void 0!==a)return{response:a.flags[e],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,r={},i={},s={},n){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(t,r,i,s,n,[e]);if(!a)return;let o=a[e];return void 0===o?null:o}async getFeatureFlagPayloadsStateless(e,t={},r={},i={},s,n){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,n)).payloads}async getFeatureFlagsStateless(e,t={},r={},i={},s,n){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,n)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},i={},s,n){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(e,t,r,i,s,n);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},r={},i={},s,n){await this._initPromise;let a={geoip_disable:s??this.disableGeoip};n&&(a.flag_keys_to_evaluate=n);let o=await this.getFlags(e,t,r,i,a);if(!o.success)return;let l=o.response;return(l.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"),l.quotaLimited?.includes("feature_flags"))?(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:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.projectToken}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},r=await this.fetchWithRetry(e,t,{type:"required",consume:e=>{if(200!==e.status||!e.json){let t=`Surveys API could not be loaded: ${e.status}`,r=Error(t);return this._logger.error(r),this._events.emit("error",Error(t)),Promise.resolve(void 0)}return e.json()}}).catch(e=>{this._logger.error("Surveys API could not be loaded",e),this._events.emit("error",e)}),i=r?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(c.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(c.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(c.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return e7}persistedQueueKeyForRoute(e){return c.Queue}getActiveQueueRoutes(){return[e7]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,r,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let s=this.prepareMessage(t,r);if(null===(s=this.processBeforeEnqueue(s)))return;s=this.normalizeMessage(s);let n=this.persistedQueueKeyForRoute(i??this.getQueueRouteKey(s)),a=this.getPersistedProperty(n)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:s}),this.setPersistedProperty(n,a),this._events.emit(e,s),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=eD(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,r,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let s=this.prepareMessage(t,r);if(null!==(s=this.processBeforeEnqueue(s))){s=this.normalizeMessage(s);try{await this.sendBatch([s],void 0,i??this.getQueueRouteKey(s))}catch(e){this._events.emit("error",e)}}}normalizeMessage(e){let{type:t,library:r,library_version:i,...s}=e,n=e9(s.properties)?s.properties:void 0;return void 0!==r&&n?.$lib===void 0&&(n={...n||{},$lib:r}),void 0!==i&&n?.$lib_version===void 0&&(n={...n||{},$lib_version:i}),n&&(s.properties=n),s.uuid=eT(s.uuid,eQ),s}normalizeTimestampForWire(e){let t=e instanceof Date?e:"string"==typeof e?new Date(e):null;if(!t||Number.isNaN(t.getTime()))return e;let r=t.toISOString(),i="string"==typeof e?e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return i&&i.length>3?r.replace(/\.\d{3}Z$/,`.${i}Z`):r}prepareMessage(e,t){let r={...e,timestamp:t?.timestamp?t?.timestamp:eL(),uuid:eT(t?.uuid,eQ)};return(t?.disableGeoip??this.disableGeoip)&&(e9(r.properties)||(r.properties={}),r.properties.$geoip_disable=!0),r.distinctId&&(r.distinct_id=r.distinctId,delete r.distinctId),r}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async e=>{await e2(e)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(e,t=[]){let r=t.filter(e=>!!e),i=0;for(;;){let t=this.promiseQueue.getPromises([...r,...this.flushPromises],e);if(0===t.length)return;i>0&&this._logger.debug(`flush() re-checking ${t.length} pending promise(s) before flushing`),await Promise.all(t.map(e=>e.catch(()=>{}))),i++}}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,i=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(r,[t,i])}).then(()=>eN([t])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),eN([i]).then(()=>{this.flushPromises.delete(i),this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this.flushPromise===i&&(this.flushPromise=null)}),i}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&""!==e&&(t["User-Agent"]=e),t}compressPayload(e){return eH(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,t,r=e7){let i={api_key:this.projectToken,batch:e.map(e=>{if(!e)return e;let t=this.normalizeTimestampForWire(e.timestamp);return t===e.timestamp?e:{...e,timestamp:t}}),sent_at:eL()};this.historicalMigration&&(i.historical_migration=!0);let s=f(i),n=`${this.host}${this.getBatchEndpointPath(r)}`,a=this.disableCompression?null:await this.compressPayload(s),o={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==a&&{"Content-Encoding":"gzip"}},body:a||s};await this.fetchWithRetry(n,o,{type:"successful-write"},t)}async _flush(){let e;this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(e=>this.getRouteQueue(e).length>0))return;let r=[];for(let i of t)try{await this._flushRoute(i,r)}catch(t){void 0===e&&(e=t)}if(void 0!==e)throw e;this._events.emit("flush",r)}async _flushRoute(e,t){let r=this.persistedQueueKeyForRoute(e),i=this.getPersistedProperty(r)||[];if(!i.length)return;let s=i.length,n=0;for(;i.length>0&&n<s;){let s=i.slice(0,this.maxBatchSize),a=s.map(e=>void 0===e.message?e.message:this.normalizeMessage(e.message)),o=async()=>{let e=this.getPersistedProperty(r)||[],t=[...s],n=e.filter(e=>{let r=e.message?.uuid,i=t.findIndex(t=>t===e||"string"==typeof r&&r.length>0&&t.message?.uuid===r);return -1===i||(t.splice(i,1),!1)});this.setPersistedProperty(r,n),i=n,this._dequeuedMessagesCount+=s.length,await this.flushStorage()},l={retryCheck:e=>!e6(e)&&e8(e)};try{await this.sendBatch(a,l,e)}catch(e){if(e6(e)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this._logger.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw e instanceof e1||await o(),this._events.emit("error",e),e}await o(),t.push(...a),n+=a.length}}async _sendOtlpBatch({path:e,auth:t,payload:r}){let i;if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};try{i=JSON.stringify(r)}catch(t){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${e} batch; reporting it as too large`,t)),{kind:"too-large",measuredLocally:!0}}let s=e4(i);if(s>0xa00000)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${s} bytes: the endpoint accepts at most 10485760`)),{kind:"too-large",measuredLocally:!0};let n="bearer"===t?`${this.host}/i/v1/${e}`:`${this.host}/i/v1/${e}?token=${encodeURIComponent(this.projectToken)}`,a=this.disableCompression?null:await this.compressPayload(i),o=a||i,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",..."bearer"===t&&{Authorization:`Bearer ${this.projectToken}`},...null!==a&&{"Content-Encoding":"gzip"}},body:o};try{return await this.fetchWithRetry(n,l,{type:"successful-write"},{retryCheck:e=>!e6(e)&&(!(e instanceof e0)||void 0===e.retryAfterMs)&&e8(e)}),{kind:"ok"}}catch(e){if(e6(e))return{kind:"too-large"};if(e8(e)){let t=e instanceof e0?e.retryAfterMs:void 0;return{kind:"retry-later",error:e,...void 0!==t&&{retryAfterMs:t}}}return{kind:"fatal",error:e}}}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,i,s){let n=e4(t.body?t.body:""),a={...this._retryOptions,...i},o=0;return await ej(async()=>{let i,a,l;o++;let u=new AbortController,c=s??this.requestTimeout,h=Date.now()+c,d=new Promise((e,t)=>{i=eD(()=>{let e=eO("AbortError",`Request timed out after ${c}ms`);t(e),u.abort(e)},c)}),f=!1,p=()=>l??=(async()=>{try{await a?.body?.cancel()}catch{}})();try{let i;try{i=this.fetch(e,{signal:u.signal,...t})}catch(e){throw new e1(e)}i.then(e=>{u.signal.aborted&&!f&&Promise.resolve(e.body?.cancel()).catch(()=>{})}).catch(()=>{});try{a=await Promise.race([i,d]),f=!0}catch(e){throw new e1(e)}let s="no-cors"===t.mode,o="successful-write"===r.type?300:400;if(!s&&(a.status<200||a.status>=o))throw new e0(a,n,h,u);if("successful-write"===r.type){try{await Promise.race([p(),d])}catch{}return}try{return await Promise.race([r.consume(a),d])}catch(e){if(u.signal.aborted)throw new e1(e);throw e}}finally{clearTimeout(i),u.signal.aborted&&a&&p()}},{...a,retryCheck:e=>{let t=a.retryCheck(e);return t&&o<=a.retryCount&&e instanceof e0&&e.cancelResponseBody(),t}})}async _shutdown(e=3e4){await this._initPromise;let t=!1;if(this.clearFlushTimer(),!this.disabled)return eB((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(e=>this.getRouteQueue(e).length>0);){let e=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===e){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(e){if(!("object"==typeof e&&(e instanceof e0||e5(e))))throw e;await e2(e)}})(),e,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:e}),t=!0})}async shutdown(e=3e4){return 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"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}let tt="[Circular]",tr="[Truncated]",ti="[Unserializable]";function ts(e){let t="";for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i>=55296&&i<=56319){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(t+=e[r]+e[r+1],r++):t+="�"}else t+=i>=56320&&i<=57343?"�":e[r]}return t}function tn(e,t){if(!t)return e;let r=[];try{r=Object.keys(t)}catch{r=[]}for(let i of r){let r;try{r=t[i]}catch{r=ti}Object.defineProperty(e,i,{value:r,enumerable:!0,writable:!0,configurable:!0})}return e}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let ta=Object.prototype.propertyIsEnumerable;function to(e,t){try{return tl(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function tl(e,t,r,i){let s=[];for(let n in e)if(ta.call(e,n)){if(!n){t?.debug("Dropping an attribute with an empty key");continue}if(s.length>=1e3||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let a=e[n];if(x(a)||v(a))continue;s.push({key:ts(n),value:function e(t,r,i,s){if(i.remainingNodes<=0)return{stringValue:tr};if(i.remainingNodes--,E(t))return{boolValue:t};if("bigint"==typeof t){let e,i;return e=t.toString(),t>=(i=BigInt("9223372036854775808"))||t<-i?(r?.debug(`Attribute ${e} is outside the int64 range; encoding it as a string`),{stringValue:e}):{intValue:e}}if("number"==typeof t){if(!Number.isFinite(t))return{stringValue:String(t)};if(Number.isInteger(t)){if(Number.isSafeInteger(t))return{intValue:String(t)};if("u"<typeof BigInt)return{stringValue:String(t)};let e=BigInt(t).toString();return t>=0x8000000000000000||t<-0x8000000000000000?(r?.debug(`Attribute ${e} is outside the int64 range; encoding it as a string`),{stringValue:e}):{intValue:e}}return{doubleValue:t}}if("string"==typeof t)return{stringValue:ts(t)};if("function"==typeof t)return{stringValue:"[Function]"};if("symbol"==typeof t)return{stringValue:String(t)};if("object"==typeof t&&null!==t){if(i.ancestors.has(t))return{stringValue:tt};if(s>=20)return{stringValue:tr};if(t instanceof Date){let e=Number.isFinite(t.getTime())?t.toISOString():String(t);return{stringValue:"string"==typeof e?ts(e):String(e)}}i.ancestors.add(t);try{try{let n=t.toJSON;if("function"==typeof n)return e(n.call(t),r,i,s+1)}catch{}if(y(t))return{arrayValue:{values:function(t,r,i,s){let n=[],a=Math.min(t.length,1e3),o=0;for(;o<a&&i.remainingNodes>0;o++)try{let a=o in t?t[o]:void 0;if(S(a))continue;n.push(e(a,r,i,s))}catch{n.push({stringValue:ti})}return t.length>o&&n.push({stringValue:tr}),n}(t,r,i,s+1)}};return{kvlistValue:{values:tl(t,r,i,s+1)}}}finally{i.ancestors.delete(t)}}return{stringValue:ts(String(t))}}(a,t,r,i)})}catch{s.push({key:ts(n),value:{stringValue:ti}})}}return s}function tu(e,t,r){return{...tn({},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}}let tc=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function th(e,t){let r=tn({},e),i={};for(let e of tc)Object.prototype.hasOwnProperty.call(r,e)&&(i[e]=r[e],delete r[e]);return[...to(r,t),...to(i,t)]}let td={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"},tf={text:"INFO",number:9},tp={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:tf,warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}};class tg{constructor(e){this._onFire=e,this._firesAt=0}get pending(){return!!this._timer}arm(e){this.clear(),this._firesAt=Date.now()+e,this._timer=eD(()=>{this._timer=void 0,this._onFire()},e)}armNoEarlierThan(e){this._timer&&Date.now()+e<=this._firesAt||this.arm(e)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}function tm(){return .75+.25*Math.random()*2}function t_(e,t,r,i){let s=Math.min(Math.max(0,t-1),6),n=e*2**s;return Math.round((void 0===i?n:Math.min(n,Math.max(i,e)))*r)}class ty{constructor(e,t,r,i,s,n=()=>Promise.resolve(),a,o=()=>!1){this._instance=e,this._config=t,this._logger=r,this._getContext=i,this._onReady=s,this._waitForStoragePersist=n,this._scopeName=a,this._isConsentWithdrawn=o,this._flushTimer=new tg(()=>this._flushInBackground()),this._flushPromise=null,this._evictedSinceAdvance=0,this._queueGeneration=0,this._backgroundFlushPromise=null,this._retryAfter=new eX,this._consecutiveFlushFailures=0,this._flushJitter=1,this._intervalWindowStart=0,this._intervalLogCount=0,this._droppedWarned=!1,this._maxBufferSize=t.maxBufferSize,this._maxQueueSize=Math.max(t.maxQueueSize??t.maxBufferSize,t.maxBufferSize),this._flushIntervalMs=t.flushIntervalMs,this._maxBatchRecordsPerPost=t.maxBatchRecordsPerPost,this._rateCapWindowMs=t.rateCapWindowMs,this._maxLogsPerInterval=t.maxLogsPerInterval}clearQueue(){this._queueGeneration++,this._instance.setPersistedProperty(c.LogsQueue,[])}get throttled(){return this._retryAfter.isOpen()}reset(){this._flushTimer.clear(),this._intervalWindowStart=0,this._intervalLogCount=0,this._droppedWarned=!1,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter.reset(),this._maxBatchRecordsPerPost=this._config.maxBatchRecordsPerPost}onReconnect(){if(this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter.isOpen()){this._hasQueuedRecords()&&this._armFlushTimer();return}this._flushInBackground()}captureLog(e,t){if(this._instance.isDisabled||this._instance.optedOut||!e?.body)return;let r=this._runBeforeSend(e);if(null===r)return;if(!r.body)return void this._logger.info("Log was rejected in beforeSend function");if(!this._checkRateLimit())return;let i={record:function(e,t,r,i){let{text:s,number:n}=tp[e.level||"info"]||tf,a=function(e=Date.now()){return String(e)+"000000"}(F(i)?i:void 0),o={};t.distinctId&&(o.posthogDistinctId=t.distinctId),t.sessionId&&(o.sessionId=t.sessionId),t.windowId&&(o["window.id"]=t.windowId),S(t.sessionStartTimestamp)||(o.sessionStartTimestamp=String(t.sessionStartTimestamp)),S(t.lastActivityTimestamp)||(o.lastActivityTimestamp=String(t.lastActivityTimestamp)),t.currentUrl&&(o["url.full"]=t.currentUrl),t.screenName&&(o["screen.name"]=t.screenName),t.appState&&(o["app.state"]=t.appState),t.activeFeatureFlags&&t.activeFeatureFlags.length>0&&(o.feature_flags=t.activeFeatureFlags);let l={...o},u=e.attributes;if(u){let e=[];try{e=Object.keys(u)}catch{e=[]}for(let t of e){let e;try{e=u[t]}catch{e=ti}Object.defineProperty(l,t,{value:e,enumerable:!0,writable:!0,configurable:!0})}}let c={timeUnixNano:a,observedTimeUnixNano:a,severityNumber:n,severityText:s,body:{stringValue:function(e){try{return ts(String(e))}catch{return ti}}(e.body)},attributes:to(l,r)};return e.trace_id&&(c.traceId=e.trace_id),e.span_id&&(c.spanId=e.span_id),v(e.trace_flags)||(c.flags=e.trace_flags),c}(r,t?.context??this._getContext(),this._logger,t?.occurredAtMs)};this._onReady(()=>this._enqueue(i))}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=y(t)?t:[t],i=e;for(let e of r)try{let t=e(i);if(!t)return this._logger.info("Log was rejected in beforeSend function"),null;i=t}catch(e){return this._logger.error("Error in beforeSend function for log:",e),null}return i}_checkRateLimit(){if(void 0===this._maxLogsPerInterval)return!0;let e=Date.now(),t=e-this._intervalWindowStart;return((t>=this._rateCapWindowMs||t<0)&&(this._intervalWindowStart=e,this._intervalLogCount=0,this._droppedWarned=!1),this._intervalLogCount>=this._maxLogsPerInterval)?(this._droppedWarned||(this._logger.warn(`captureLog dropping logs: exceeded ${this._maxLogsPerInterval} logs per ${this._rateCapWindowMs}ms`),this._droppedWarned=!0),!1):(this._intervalLogCount++,!0)}async flush(){if(!this._instance.isDisabled)return this._flushPromise||(this._flushPromise=this._flushInner().finally(()=>{this._flushPromise=null})),this._flushPromise}async _flushInner(){if(this._flushTimer.clear(),this._discardQueueIfConsentWithdrawn())return;let e=this._instance.getPersistedProperty(c.LogsQueue)??[];if(0===e.length)return;let t=e.length,r=0;for(;e.length>0&&r<t;){var i,s,n,a;if(this._discardQueueIfConsentWithdrawn())return;let t=this._queueGeneration;this._evictedSinceAdvance=0;let o=Math.min(e.length,this._maxBatchRecordsPerPost),l=e.slice(0,o),u=(i=l.map(e=>e.record),s=this._buildResourceAttributes(),n=this._scopeName??this._instance.getLibraryId(),a=this._instance.getLibraryVersion(),{resourceLogs:[{resource:{attributes:th(s)},scopeLogs:[{scope:{name:n,version:a},logRecords:i}]}]}),h=await this._instance._sendLogsBatch(u);if(this._queueGeneration!==t)return;if("too-large"===h.kind&&l.length>1){this._maxBatchRecordsPerPost=Math.max(1,Math.floor(l.length/2)),this._logger.warn(`Logs batch of size ${l.length} was too large for the ingestion endpoint, reducing batch size to ${this._maxBatchRecordsPerPost}`);continue}if(this._retryAfter.record(h),this._flushTimer.pending&&this._flushTimer.arm(Math.max(this._flushIntervalMs,this._retryAfter.remainingMs())),"retry-later"===h.kind||("too-large"===h.kind?this._logger.warn("Dropping a single log record with batch size 1 — the record is larger than the server cap and cannot be split further."):"ok"===h.kind&&this._maxBatchRecordsPerPost<this._config.maxBatchRecordsPerPost&&(this._maxBatchRecordsPerPost=Math.min(this._config.maxBatchRecordsPerPost,this._maxBatchRecordsPerPost+1)),await this._persistQueueAdvance(l.length),e=this._instance.getPersistedProperty(c.LogsQueue)??[],r+=l.length,"fatal"===h.kind))throw h.error}}_discardQueueIfConsentWithdrawn(){return!!this._isConsentWithdrawn()&&(this._hasQueuedRecords()&&this.clearQueue(),!0)}async _persistQueueAdvance(e){let t=Math.max(0,e-this._evictedSinceAdvance),r=this._instance.getPersistedProperty(c.LogsQueue)??[];this._instance.setPersistedProperty(c.LogsQueue,r.slice(t)),await this._waitForStoragePersist()}_buildResourceAttributes(){var e;return e=this._config,tu(e,this._instance.getLibraryId(),this._instance.getLibraryVersion())}_enqueue(e){if(this._instance.optedOut)return;let t=this._instance.getPersistedProperty(c.LogsQueue)??[];(t.length>=this._maxQueueSize&&(t.shift(),this._evictedSinceAdvance++,this._logger.info("Logs queue is full, dropping oldest record.")),t.push(e),this._instance.setPersistedProperty(c.LogsQueue,t),t.length>=this._maxBufferSize&&!this._retryAfter.isOpen())?this._flushInBackground():this._armFlushTimer()}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(Math.max(this._flushIntervalMs,this._retryAfter.remainingMs()))}_nextFlushDelay(){return Math.max(t_(this._flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}_hasQueuedRecords(){let e=this._instance.getPersistedProperty(c.LogsQueue);return!!e&&e.length>0}async shutdown(e){this._flushTimer.clear();let t=this.flush().catch(()=>{});void 0===e?await t:await eB(t,e)}async flushWithTimeout(e){let t=this.flush();await eB(t,e,()=>{t.catch(()=>{})})}flushInBackground(){if(this._backgroundFlushPromise)return this._backgroundFlushPromise;let e=this.flush().then(()=>{this._consecutiveFlushFailures=0,this._flushJitter=1},e=>{this._consecutiveFlushFailures++,this._flushJitter=tm(),this._logger.error("PostHog logs flush failed:",e)}).finally(()=>{this._backgroundFlushPromise===e&&(this._backgroundFlushPromise=null),!this._instance.isDisabled&&this._hasQueuedRecords()&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())});return this._backgroundFlushPromise=e,e}_flushInBackground(){this.flushInBackground()}}let tv="0000000000000000",tb=tv+tv,tw=/^[0-9a-f]+$/;function tx(e){let t=function(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}(function(e){let t=new Uint8Array(e),r=globalThis.crypto;if(r&&"function"==typeof r.getRandomValues)try{return r.getRandomValues(t),t}catch{}for(let r=0;r<e;r++)t[r]=Math.floor(256*Math.random());return t}(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function tS(e,t,r){return"string"==typeof e&&e.length===t&&e!==r&&tw.test(e)}let tF=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function tE(e){let t=tP(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:1&parseInt(t.flags,16)?tI:tC}}function tP(e){if("string"!=typeof e)return;let t=tF.exec(e.trim());if(!t)return;let[,r,i,s,n,a]=t;if("ff"!==r&&("00"!==r||!a)&&tS(i,32,tb)&&tS(s,16,tv))return{version:r,traceId:i,spanId:s,flags:n}}function tA(e){return Array.isArray(e)&&1===e.length?e[0]:e}let tI="01",tC="00";function tk(e){if("string"!=typeof e)return;let t=e.trim();if(!t||/[^\x20-\x7e\t]/.test(t))return;let r=t.split(",");if(!(r.length>32)){for(let e of r)if(e.trim()&&!e.includes("="))return;return t.length<=512?t:function(e){let t=[...e],r=()=>t.reduce((e,t)=>e+t.length,0)+t.length-1;for(let e=t.length-1;e>=0&&r()>512;e--)t[e].length>128&&t.splice(e,1);for(;t.length&&r()>512;)t.pop();return t.length?t.join(","):void 0}(r)}}let t$=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function tT(e){return String(e)+"000000"}function tO(e,t,r,i){let s="";return i&&(s=Object.keys(i).sort().map(e=>`${JSON.stringify(e)}:${JSON.stringify(i[e])}`).join(",")),`${e}\0${t}\0${r??""}\0${s}`}class tR{constructor(e,t,r){this._instance=e,this._config=t,this._logger=r,this._series=new Map,this._flushTimer=new tg(()=>this.flush().catch(e=>{this._logger.error("Metrics flush failed:",e)})),this._flushPromise=null,this._queuedFlush=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._boundsByHistogram=new Map,this._boundsConflictWarned=new Set,this._boundsCapWarned=!1,this._retryAfter=new eX,this._consecutiveFlushFailures=0,this._flushJitter=1,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,bounds:y(r?.bounds)?r.bounds.slice():r?.bounds})}flush(){let e=this._flushPromise,t=(async()=>{e&&await e.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===t&&(this._flushPromise=null)});return this._flushPromise=t,t}flushCoalesced(){return this._isBackingOff()?this._flushPromise??Promise.resolve():(this._queuedFlush||(this._queuedFlush=(this._flushPromise??Promise.resolve()).catch(()=>{}).then(()=>(this._queuedFlush=null,this._isBackingOff()?void 0:this.flush()))),this._queuedFlush)}_isBackingOff(){return this._consecutiveFlushFailures>0||this._retryAfter.remainingMs()>0}drainWindow(){if(0===this._series.size)return null;let e=this._series;return this._startWindow(),this._buildPayload(e)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=1,this._flushTimer.clear(),this._flushPromise=null,this._queuedFlush=null,this._startWindow(),this._boundsByHistogram=new Map,this._boundsCapWarned=!1}_startWindow(){this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._boundsConflictWarned=new Set}_capture(e){var t;let r,i,s;if(this._instance.isDisabled||this._instance.optedOut)return;let n=this._runBeforeSend(e);if(null===n)return;if(!n.name||"string"!=typeof n.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof n.value||!Number.isFinite(n.value))return void this._logger.warn(`Dropping metric '${n.name}': value must be a finite number`);if("count"!==n.type&&"gauge"!==n.type&&"histogram"!==n.type)return void this._logger.warn(`Dropping metric '${n.name}': unknown type '${String(n.type)}'`);if("count"===n.type&&n.value<0)return void this._logger.warn(`Dropping count '${n.name}': counters are monotonic, value must be >= 0`);try{r=n.attributes?{...n.attributes}:void 0,i=tO(n.type,n.name,n.unit,r)}catch(e){this._logger.warn(`Dropping metric '${n.name}': attributes could not be serialized`,e);return}let a=this._series.get(i);if(!a&&!this._admitNewSeries()||"histogram"===n.type&&!(s=this._histogramBounds(n.name,n.unit,n.bounds)))return;a||(a={name:n.name,type:n.type,unit:n.unit,attributes:r,windowStartMs:Date.now(),hist:s&&{bounds:t=s,count:0,sum:0,min:1/0,max:-1/0,bucketCounts:Array(t.length+1).fill(0)}},this._series.set(i,a));let o=this._typeByName.get(n.name);void 0===o?this._typeByName.set(n.name,n.type):o===n.type||this._typeCollisionWarned.has(n.name)||(this._typeCollisionWarned.add(n.name),this._logger.warn(`Metric name '${n.name}' is already used as a ${o}; recording it as a ${n.type} too will blend both series in charts. Use a distinct name.`)),this._fold(a,n.value);let l=this._activeTraceContext();l&&(a.exemplar={...l,value:n.value,timeMs:Date.now()}),this._armFlushTimer()}_activeTraceContext(){try{let e=tE(this._instance.getActiveSpan?.()?.traceparent());if(e&&e.flags===tI)return{traceId:e.traceId,spanId:e.spanId}}catch{}}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush||(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.`)),!1)}_histogramBounds(e,t,r){if(void 0!==r&&!function(e){if(!y(e)||0===e.length)return!1;for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t])||t>0&&e[t]<=e[t-1])return!1;return!0}(r))return void this._logger.warn(`Dropping histogram '${e}': bounds must be a non-empty array of finite, strictly increasing numbers`);let i=tO("histogram",e,t,void 0),s=this._boundsByHistogram.get(i);if(s)return this._warnOnBoundsConflict(e,i,s,r),s;if(this._boundsByHistogram.size>=this._config.maxSeriesPerFlush){if(this._boundsCapWarned||(this._boundsCapWarned=!0,this._logger.warn(`Histogram bounds limit reached (${this._config.maxSeriesPerFlush} distinct histograms); new histograms that pass custom bounds are dropped. Reduce histogram name cardinality.`)),r&&!tM(r,t$))return;return t$}let n=r?r.slice():t$;return this._boundsByHistogram.set(i,n),n}_warnOnBoundsConflict(e,t,r,i){tM(r,i??t$)||this._boundsConflictWarned.has(t)||(this._boundsConflictWarned.add(t),this._logger.warn(`Histogram '${e}' already uses the bounds [${r.join(", ")}]; samples that pass different bounds are recorded in those buckets.`))}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{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[function(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}(t,r.bounds)]+=1}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=y(t)?t:[t],i=e;for(let e of r)try{let t=e(i);if(!t)return this._logger.info("Metric was rejected in beforeSend function"),null;i=t}catch(e){return this._logger.error("Error in beforeSend function for metric:",e),null}return i}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(t_(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),0===this._series.size)return;let e=this._series;this._startWindow();let t=this._generation,r=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t===this._generation)switch(this._retryAfter.record(r),"retry-later"===r.kind?(this._consecutiveFlushFailures++,this._flushJitter=tm()):(this._consecutiveFlushFailures=0,this._flushJitter=1),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),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){var t,r,i,s;return t=this._buildMetrics(e),r=tu(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),s=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:th(r)},scopeMetrics:[{scope:{name:i,version:s},metrics:t}]}]}}_buildMetrics(e){let t=tT(Date.now()),r=new Map;for(let s of e.values()){var i;let e=tO(s.type,s.name,s.unit,void 0),n=r.get(e);n||(n={name:s.name,...s.unit&&{unit:s.unit}},"count"===s.type?n.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===s.type?n.gauge={dataPoints:[]}:n.histogram={aggregationTemporality:1,dataPoints:[]},r.set(e,n));let a=to(s.attributes??{},this._logger),o=tT(s.windowStartMs),l=(i=s.exemplar)?{exemplars:[{filteredAttributes:[],timeUnixNano:tT(i.timeMs),asDouble:i.value,traceId:i.traceId,spanId:i.spanId}]}:{};if("count"===s.type){let e={attributes:a,startTimeUnixNano:o,timeUnixNano:t,asDouble:s.total??0,...l};n.sum.dataPoints.push(e)}else if("gauge"===s.type){let e={attributes:a,timeUnixNano:t,asDouble:s.last??0,...l};n.gauge.dataPoints.push(e)}else{let e=s.hist,r={attributes:a,startTimeUnixNano:o,timeUnixNano:t,count:e.count,sum:e.sum,min:e.min,max:e.max,bucketCounts:e.bucketCounts,explicitBounds:e.bounds,...l};n.histogram.dataPoints.push(r)}}return Array.from(r.values())}_mergeWindowBack(e){for(let[t,r]of e){let e=this._series.get(t);if(!e){this._admitNewSeries()&&this._series.set(t,r);continue}switch(e.windowStartMs=Math.min(e.windowStartMs,r.windowStartMs),e.exemplar=e.exemplar??r.exemplar,e.type){case"count":e.total=(e.total??0)+(r.total??0);break;case"gauge":break;case"histogram":{let t=e.hist,i=r.hist;t.count+=i.count,t.sum+=i.sum,t.min=Math.min(t.min,i.min),t.max=Math.max(t.max,i.max);for(let e=0;e<t.bucketCounts.length;e++)t.bucketCounts[e]+=i.bucketCounts[e]}}}}}function tM(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}let tj="unknown";function tL(e,t,r,i){return"string"==typeof e&&e.trim()?e.length>r?e.slice(0,r):e:(i?.debug(`${t} must be a non-empty string; using "${tj}"`),tj)}function tD(e){if(null==e)return;let t=e;if(e instanceof Date)try{t=e.getTime()}catch{return}if("number"==typeof t&&Number.isFinite(t)&&!(t<0)&&!(t>0x8637bd05af6))return t}function tB(e,t,r,i){let s=tD(e);return void 0===s?(void 0!==e&&i?.debug(`Span ${r} is out of range or not a valid time; using the derived time`),t):s}function tN(){let e=globalThis.performance;return"function"==typeof e?.now?e.now():void 0}class tq{constructor(e,t,r){for(let i of(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??tI,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),Object.keys(e.attributes)))this._writeAttribute(i,e.attributes[i]);this._startMono=e.backdated?void 0:tN(),this._startTime=e.clockAnchor&&void 0!==this._startMono?e.clockAnchor.wall+(this._startMono-e.clockAnchor.mono):e.startTime,void 0!==this._startMono&&(this._clockAnchor=e.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(void 0!==this._startMono){let e=tN();if(void 0!==e)return this._startTime+Math.max(0,e-this._startMono)}return Date.now()}_mutable(e){return!this._ended||(this._logger?.debug(`Ignoring ${e} on a span that has already ended`),!1)}_writeAttribute(e,t){if(S(t)){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]=tJ(t,this._maxAttributeValueLength)}setAttribute(e,t){return this._mutable("setAttribute")&&this._writeAttribute(e,t),this}setAttributes(e){if(this._mutable("setAttributes")){let t=tn({},e);for(let e of Object.keys(t))this._writeAttribute(e,t[e])}return this}addEvent(e,t,r){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let i=t&&tZ(t,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:tL(e,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:tB(r,this._now(),"event timestamp",this._logger),...i&&{attributes:i.attributes,...i.dropped&&{droppedAttributesCount:i.dropped}}})}return this}setStatus(e,t){if(this._mutable("setStatus")){if("ok"!==e&&"error"!==e)return this._logger?.debug(`Ignoring unknown span status "${String(e)}"; expected "ok" or "error"`),this;this._status={code:e,...t&&{message:tG(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:i}=tX(e);return this.addEvent(tU,{"exception.type":t,"exception.message":r,...i&&{"exception.stacktrace":i}}),this.setStatus("error",r)}updateName(e){return this._mutable("updateName")&&(this._name=tL(e,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return function(e,t,r=tI){return`00-${e}-${t}-${r}`}(this._traceId,this._spanId,this._traceFlags)}get traceId(){return this._traceId}get spanId(){return this._spanId}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(e){var t;if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let r=tB(e,this._now(),"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:r<(t=this._startTime)?t:r,...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}}let tU="exception";function tH(e){return"number"!=typeof e||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),0xffffffff)}class tW{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}get traceId(){return null}get spanId(){return null}tracestate(){return null}end(){}}let tK=new tW;class tV extends tW{constructor(e,t){super(),this._traceparent=e,this._tracestate=t}traceparent(){return this._traceparent}get traceId(){return this._traceparent.split("-")[1]??null}get spanId(){return this._traceparent.split("-")[2]??null}tracestate(){return this._tracestate??null}}function tz(e,t){var r;let i=tA(e?.parent)??t,s=tP(r="string"==typeof i||null==i?i:tQ(i,"traceparent"))&&r.trim();return s?new tV(s,tk("string"==typeof i||null==i?e?.tracestate:tQ(i,"tracestate"))):tK}function tQ(e,t){try{let r=e[t];return"function"==typeof r?r.call(e):void 0}catch{return}}function tG(e,t){return e.length>t?e.slice(0,t):e}function tJ(e,t){return function e(t,r,i,s){if(null===t||"object"!=typeof t)return S(t)||i.remainingNodes<=0?t:(i.remainingNodes--,"string"==typeof t?tG(t,r):t);if(i.ancestors.has(t))return tt;if(i.remainingNodes<=0||s>=20)return t;i.remainingNodes--,i.ancestors.add(t);try{if(t instanceof Date)return t;let n=function(e){try{let t=e.toJSON;if("function"==typeof t)return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}(t);if(n.selfDescribed)return S(n.value)?String(n.value):e(n.value,r,i,s+1);if(y(t)){let n=Math.min(t.length,1e3),a=[];for(let o=0;o<n;o++)try{a.push(e(t[o],r,i,s+1))}catch{a.push(ti)}return t.length>n&&(a.length=t.length),a}let a={},o=0;for(let n of Object.keys(t)){let l;if(o>=1e3)break;try{l=e(t[n],r,i,s+1)}catch{l=ti}n&&!S(l)&&o++,Object.defineProperty(a,n,{value:l,enumerable:!0,writable:!0,configurable:!0})}return a}catch{return t}finally{i.ancestors.delete(t)}}(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function tZ(e,t,r){let i;try{i=Object.keys(e)}catch{return{attributes:{},dropped:0}}let s={},n=0,a=0;for(let o of i){let i;if(n>=t){a++;continue}try{i=tJ(e[o],r)}catch{i=ti}S(i)||(n++,Object.defineProperty(s,o,{value:i,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:s,dropped:a}}function tY(e,t,r){return t===tK?r(t):e.with(t,()=>r(t))}function tX(e){try{let t=function(e){try{let t=e.stack;return"string"==typeof t&&t?{stack:t}:{}}catch{return{}}}(e);if(P(e))return{type:e.name||"Error",message:e.message||"",...t};if("string"==typeof e)return{type:"string",message:e};if(e&&"object"==typeof e&&"string"==typeof e.message)return{type:"string"==typeof e.name?e.name:"Object",message:e.message,...t};return{type:typeof e,message:String(e)}}catch{return{type:typeof e,message:""}}}let t0={internal:1,server:2,client:3,producer:4,consumer:5},t1={ok:1,error:2};function t2(e){if("string"==typeof e)return ts(e);try{return ts(String(e))}catch{return ti}}function t5(e){let t=Math.floor(e),r=Math.round((e-t)*1e6);return r>=1e6&&(t+=1,r=0),String(t)+String(r).padStart(6,"0")}function t3(){return tN()??Date.now()}function t4(e){try{return e instanceof tq}catch{return!1}}function t6(e,t){let r=tE(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:tk(t),traceFlags:r.flags,isRemote:!0}}function t8(e,t,r){e[t]!==r&&(e[t]=r)}class t9{constructor(e,t,r,i,s,n){this._instance=e,this._config=t,this._logger=r,this._getContext=i,this._contextManager=s,this._onSpanQueued=n,this._queue=[],this._flushTimer=new tg(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter=new eX,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=t.maxExportBatchSize}startSpan(e,t){var r,i;let s;if(this._instance.isDisabled||this._instance.optedOut)return tz(t,this._contextManager.active());let n=tA(t?.parent);if(n&&"string"!=typeof n&&!t4(n)){if(function(e){try{return"function"==typeof e.traceparent}catch{return!1}}(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),tz(t,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let a=this._resolveParent(n,t);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),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`),tz(t,this._contextManager.active());let o=Date.now(),l=(r=t?.startTime,i=this._logger,void 0===(s=tD(r))?(void 0!==r&&i?.debug("Span startTime is out of range or not a valid time; using the current time"),o):(o-s>864e5?i?.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"):s>o&&i?.debug("Span startTime is in the future; the span may export with a zero duration"),s)),u=tx(8);this._liveSpans.set(u,t3());let c=this._autoContextAttributes();return new tq({traceId:a?.traceId??tx(16),spanId:u,parentSpanId:a?.parentSpanId,traceState:a?.traceState,traceFlags:a?.traceFlags,parentIsRemote:a?.isRemote,name:tL(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:t?.kind??"internal",attributes:tn({...c},t?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:l,backdated:l!==o,clockAnchor:void 0===tD(t?.startTime)?a?.clockAnchor:void 0},(e,t)=>this._onSpanEnd(e,t),this._logger)}withSpan(e,t,r){let i=this.startSpan(e,"function"==typeof t?void 0:t);try{let e=tY(this._contextManager,i,"function"==typeof t?t:r);if(e&&"function"==typeof e.then)return e.then(e=>(i.end(),e),e=>{throw this._recordCallbackError(i,e),i.end(),e});return i.end(),e}catch(e){throw this._recordCallbackError(i,e),i.end(),e}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;){if(!this._queue.length)return;let e=this._flushPromise;if(!await (e??this._startFlush()))return}}_startFlush(){this._flushTimer.clear();let e=this._generation,t=Promise.resolve().then(()=>e===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===t&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=t,t}reset(){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=1,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(e,t){if("string"==typeof e){let r=t6(e,t?.tracestate);return r||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),r}if(t4(e))return e.childContext();let r=this._contextManager.active();return t4(r)?r.childContext():r instanceof tV?t6(r.traceparent(),r.tracestate()??void 0):void 0}_autoContextAttributes(){let e;try{e=this._getContext()}catch(e){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",e),{}}let t={};return e.distinctId&&(t.posthogDistinctId=e.distinctId),e.sessionId&&(t.sessionId=e.sessionId),e.currentUrl&&(t["url.full"]=e.currentUrl),e.screenName&&(t["screen.name"]=e.screenName),e.appState&&(t["app.state"]=e.appState),t}_recordCallbackError(e,t){if(!(e instanceof tq))return;let{type:r,message:i,stack:s}=tX(t);e.addEvent("exception",{"exception.type":r,"exception.message":i,...s&&{"exception.stacktrace":s}}),e.statusIsExplicitlyOk||e.setStatus("error",i)}_evictAgedSpans(){let e=t3()-this._config.maxSpanAgeMs,t=0;for(let[r,i]of this._liveSpans){if(i>e)break;this._liveSpans.delete(r),t++}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){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(e){this._logger.debug("Span queue notification failed",e)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(e){let t=e.droppedAttributesCount??0,r=e.droppedEventsCount??0,i=0;for(let t of e.events)i+=t.droppedAttributesCount??0;(t||r||i)&&this._logger.debug(`Span limits discarded data from "${e.name}": ${t} attributes, ${r} events, ${i} 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},i={startTime:e.startTime,endTime:e.endTime},s={attributes:e.droppedAttributesCount,events:e.droppedEventsCount},n=Object.keys(e.attributes),a={traceFlags:e.traceFlags,parentIsRemote:e.parentIsRemote},o=e.status&&{...e.status},l=e,u=e;try{var c,h,d;for(let e of this._config.beforeSpanSend){let t=e(l);if(!t)return this._recordDrop(1,"beforeSpanSend dropped it"),null;l=this._keepSpanIdentity(t,r)}if(!((c=u={traceId:r.traceId,spanId:r.spanId,parentSpanId:r.parentSpanId,traceState:r.traceState,name:l.name,kind:l.kind,status:l.status,attributes:l.attributes,events:l.events,startTime:l.startTime,endTime:l.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:s.attributes,droppedEventsCount:s.events}).attributes&&"object"==typeof c.attributes&&!Array.isArray(c.attributes)&&Array.isArray(c.events)&&void 0!==c.name&&void 0!==c.kind&&void 0!==c.startTime&&void 0!==c.endTime))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;u.name=tL(u.name,"Span name",this._config.maxAttributeValueLength,this._logger),u.status&&"ok"!==u.status.code&&"error"!==u.status.code&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),u.status=o),u.startTime=tD(u.startTime)??i.startTime,u.endTime=(h=tD(u.endTime)??i.endTime,d=u.startTime,h<d?d:h);let e=[];for(let t of u.events)try{e.push({...t,name:tL(t.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:tB(t.timestamp,u.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return u.events=e,!function(e,t,r,i,s,n,a=[]){let o=0,l=0,u={};for(let i of function(e,t){if(!t.length)return Object.keys(e);let r=t.filter(t=>Object.prototype.propertyIsEnumerable.call(e,t)),i=new Set(r);return[...r,...Object.keys(e).filter(e=>!i.has(e))]}(e.attributes,a)){let s=e.attributes[i];if(!S(s)){if(!t.has(i)){if(o>=r){l++;continue}o++}Object.defineProperty(u,i,{value:tJ(s,n),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=u,l&&(e.droppedAttributesCount=tH(e.droppedAttributesCount)+l);let c=0,h=0,d=[];for(let t of e.events){if(c>=i){h++;continue}if(c++,t.attributes){let e=tZ(t.attributes,s,n);t.attributes=e.attributes,e.dropped&&(t.droppedAttributesCount=tH(t.droppedAttributesCount)+e.dropped)}d.push(t)}e.events=d,h&&(e.droppedEventsCount=tH(e.droppedEventsCount)+h),e.status?.message&&(e.status={...e.status,message:tG(function(e){try{return"string"==typeof e?e:String(e)}catch{return ti}}(e.status.message),n)})}(u,t,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,n),u}catch(e){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",e),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(e,t){(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{t8(e,"traceId",t.traceId),t8(e,"spanId",t.spanId),t8(e,"parentSpanId",t.parentSpanId),t8(e,"traceState",t.traceState)}catch{try{let r=Object.getOwnPropertyDescriptors(e);for(let e of["traceId","spanId","parentSpanId","traceState"])r[e]={value:t[e],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(e),r)}catch{;}}return e}_recordDrop(e,t){this._droppedSinceWarning+=e,this._dropReasons.add(t),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(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(function(e,t){var r;let i,s={traceId:e.traceId,spanId:e.spanId,name:t2(e.name),kind:(r=e.kind)&&Object.prototype.hasOwnProperty.call(t0,r)?t0[r]:t0.internal,startTimeUnixNano:t5(e.startTime),endTimeUnixNano:t5(e.endTime),flags:(Number.isFinite(i=parseInt(e.traceFlags,16))?255&i:1)|256|512*!!e.parentIsRemote};e.parentSpanId&&(s.parentSpanId=e.parentSpanId),e.traceState&&(s.traceState=t2(e.traceState));let n=to(e.attributes,t);n.length&&(s.attributes=n),e.events.length&&(s.events=e.events.map(e=>(function(e,t){let r={name:t2(e.name),timeUnixNano:t5(e.timestamp)};if(e.attributes){let i=to(e.attributes,t);i.length&&(r.attributes=i)}let i=tH(e.droppedAttributesCount);return i&&(r.droppedAttributesCount=i),r})(e,t)));let a=tH(e.droppedAttributesCount);a&&(s.droppedAttributesCount=a);let o=tH(e.droppedEventsCount);return o&&(s.droppedEventsCount=o),e.status&&(s.status={code:t1[e.status.code],...e.status.message&&{message:t2(e.status.message)}}),s}(r,this._logger))}catch(e){this._logger.debug("Failed to encode a span; dropping it",e),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(){var e,t;if(!this._queue.length)return 0;let r=this._discardQueueIfConsentWithdrawn();if(r)return r;let i=function(e,t){for(let r of Object.keys(e))e[r]=tJ(e[r],t);return e}((e=this._config,tu(e,this._instance.getLibraryId(),this._instance.getLibraryVersion())),this._config.maxAttributeValueLength),s=this._instance.getLibraryId(),n=this._instance.getLibraryVersion(),a=this._queue.length,o=0,l=1/0,u=this._generation;try{for(;a>0&&this._queue.length>0;){let e=this._discardQueueIfConsentWithdrawn();if(e)return o+e;let r=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,c=Math.max(1,Math.min(r,l,a,this._queue.length)),h=this._queue.slice(0,c),d=this._encodeBatch(h);if(!d.length){this._queue.splice(0,c),a-=c,o+=c,this._resetHeadBatchBudget();continue}let f=t3()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),p=await this._instance._sendTracesBatch((t=this._logger,{resourceSpans:[{resource:{attributes:th(i,t)},scopeSpans:[{scope:{name:s,version:n},spans:d}]}]}));if(u!==this._generation)break;if(this._retryAfter.record(p),"ok"===p.kind){this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._queue.splice(0,c),a-=c,o+=c,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if("too-large"===p.kind){if(1===c){this._queue.splice(0,1),a-=1,o+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget();continue}let e=Math.max(1,Math.floor(c/2));p.measuredLocally?l=e:this._maxExportBatchSize=e,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${e}`);continue}if("retry-later"===p.kind){if(this._consecutiveFlushFailures++,this._flushJitter=tm(),this._headBatchSize=c,f&&(this._headBatchFailures++,this._headBatchChargeableAt=t3()+this._nextFlushDelay()),this._headBatchFailures<8)return this._logger.debug("Span export failed; retrying on the next flush",p.error),o;if(this._queue.splice(0,c),a-=c,o+=c,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(c,"the ingestion endpoint failed 8 times in a row"),this._retryAfter.isOpen())return o;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",p.error),this._queue.splice(0,c),a-=c,o+=c,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(c,"the ingestion endpoint rejected the batch")}return o}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(e=>{this._logger.debug("Background span flush failed",e)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){!this._flushTimer.pending&&this._queue.length&&this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(t_(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}}class t7{active(){return this._active}with(e,t){let r=this._active;this._active=e;try{return t()}finally{this._active=r}}}let re=["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","lightpanda","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"],rt=new Map,rr=function(e,t=[]){if(!e)return!1;let r=function(e,t){let r="";for(let e=0;e<t.length;e++){let i=t[e];r+=i.length+":"+i}return e.length+":"+e+"|"+t.length+":"+r}(e,t),i=rt.get(r);if(void 0!==i)return i;let s=e.toLowerCase(),n=re.concat(t).some(e=>-1!==s.indexOf(e.toLowerCase()));return rt.size>=256&&rt.clear(),rt.set(r,n),n};function ri(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??1e3}}function rs(e,t){return"number"==typeof e&&Number.isInteger(e)&&e>=1?e:t}let rn=["service.name","service.version","deployment.environment"];function ra(e,t,r){let i=tn({...t},function(e){if(!(!e||"object"!=typeof e||Array.isArray(e)))try{if(rn.every(t=>!(t in e)||"string"==typeof e[t]))return e;let t={...e};for(let e of rn)e in t&&"string"!=typeof t[e]&&delete t[e];return t}catch{return}}(e?.resourceAttributes)),s=rs(e?.maxExportBatchSize,512);return{serviceName:i?.["service.name"]??e?.serviceName,serviceVersion:i?.["service.version"]??e?.serviceVersion,environment:i?.["deployment.environment"]??e?.environment,resourceAttributes:i,beforeSpanSend:function(e,t){if(!e)return[];let r=[e].flat().filter(e=>!!e),i=r.filter(e=>"function"==typeof e);return i.length!==r.length&&t?.critical(`beforeSpanSend: ignoring ${r.length-i.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),i}(e?.beforeSpanSend,r),maxAttributesPerSpan:rs(e?.maxAttributesPerSpan,128),maxEventsPerSpan:rs(e?.maxEventsPerSpan,128),maxAttributesPerEvent:128,maxAttributeValueLength:rs(e?.maxAttributeValueLength,8192),flushIntervalMs:rs(e?.flushIntervalMs,5e3),maxExportBatchSize:s,maxQueueSize:Math.max(rs(e?.maxQueueSize,2048),s),maxLiveSpans:rs(e?.maxLiveSpans,1e4),maxSpanAgeMs:rs(e?.maxSpanAgeMs,36e5)}}let ro={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"};e.s(["FeatureFlagError",0,ro],58325);class rl{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,t.sendFeatureFlagEvents),r?.enabled??t.defaultValue??!1}getFlag(e,t={}){let r=this._flags[e];if(this._recordAccess(e,t.sendFeatureFlagEvents),r)return!!r.enabled&&(r.variant??!0)}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let r=this._flags[t];r&&(e[t]=r)}return this._cloneWith(e)}only(e){let t={},r=[];for(let i of e){let e=this._flags[i];e?t[i]=e:r.push(i)}return 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(", ")}`),this._cloneWith(t)}get keys(){return Object.keys(this._flags)}get unresolvedFlags(){return this._unresolvedFlags}_getEventProperties(){let e={},t=[];for(let[r,i]of Object.entries(this._flags)){let s=!1!==i.enabled&&(i.variant??!0);e[`$feature/${r}`]=s,i.enabled&&t.push(r)}return t.length>0&&(t.sort(),e.$active_feature_flags=t),e}_cloneWith(e){return new rl({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,t){if(this._accessed.add(e),!this._host.resolveSendFeatureFlagEvents(t)||""===this._distinctId||this._isSlice&&!(e in this._flags))return;let r=this._flags[e],i=void 0===r?void 0:!1!==r.enabled&&(r.variant??!0),s={$feature_flag:e,$feature_flag_response:i,$feature_flag_id:r?.id,$feature_flag_version:r?.version,$feature_flag_reason:r?.reason,locally_evaluated:r?.locallyEvaluated??!1,[`$feature/${e}`]:i,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:r?.locallyEvaluated?Date.now():this._evaluatedAt};r?.hasExperiment!==void 0&&(s.$feature_flag_has_experiment=r.hasExperiment),r?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(s.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let n=[];this._errorsWhileComputing&&n.push(ro.ERRORS_WHILE_COMPUTING),this._quotaLimited&&n.push(ro.QUOTA_LIMITED),void 0===r&&n.push(Object.prototype.hasOwnProperty.call(this._unresolvedFlags,e)?ro.LOCAL_EVALUATION_INCONCLUSIVE:ro.FLAG_MISSING),n.length>0&&(s.$feature_flag_error=n.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:i,groups:this._groups,disableGeoip:this._disableGeoip,properties:s,record:r?.parsed})}}let ru=new WeakMap;class rc extends Error{constructor(e){super(e),this.field=e}}function rh(e){let t=ru.get(e);return t||{value:e.variant??e.enabled??null,failed:!0===e.failed,reason:e.reason&&{code:e.reason.code,conditionIndex:e.reason.condition_index,description:e.reason.description},metadata:{id:e.metadata?.id,version:e.metadata?.version,configVersion:1,description:e.metadata?.description,hasExperiment:e.metadata?.has_experiment}}}function rd(e,t){return{detail:{key:e,enabled:!1,variant:void 0,reason:void 0,metadata:void 0,failed:!0},record:{value:null,failed:!0,unreadableField:t,metadata:{}}}}function rf(e){rm(e.key,"key",b)}function rp(e){let t=rm(e,"reason",I);if(void 0!==t)return{code:rm(t.code,"reason.code",b),conditionIndex:r_(t.condition_index,"reason.condition_index"),description:rm(t.description,"reason.description",b)}}function rg(e){return{id:r_(e?.id,"metadata.id"),version:r_(e?.version,"metadata.version"),description:rm(e?.description,"metadata.description",b),hasExperiment:rm(e?.has_experiment,"metadata.has_experiment",E)}}function rm(e,t,r){if(!S(e)){if(r(e))return e;throw new rc(t)}}function r_(e,t){return rm(e,t,e=>F(e)&&Number.isInteger(e))}let ry="experiment_split",rv="experiment",rb=new Map([["targeting_match",new Set(["targeted_release","percentage_rollout"])],[ry,new Set([rv])],["rollout_miss",new Set(["percentage_rollout",rv])],["experiment_paused",new Set([rv])],["holdout",new Set([rv])]]),rw=["$feature_flag_config_version","$feature_flag_reason_code","$feature_flag_rule_id","$feature_flag_rule_type","$feature_flag_variant_key"],rx=new Set([...rw,"$feature_flag_reason","$feature_flag_forced_variant","$feature_flag_experiment_id"]),rS=new Set(["$feature_flag_config_version","$feature_flag_reason_code","$feature_flag_rule_type","$experiment_exposure_source","$feature_flag_experiment_id","$feature_flag_forced_variant"]),rF=["$feature_flag_id","$feature_flag_version","$feature_flag_request_id","$feature_flag_evaluated_at"],rE=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,rP=["exact","is_not","icontains","not_icontains","starts_with","not_starts_with","ends_with","not_ends_with","regex","not_regex"];class rA extends Error{constructor(e,t="unsupported_definition"){super(e),this.name=this.constructor.name,this.reason=t,Object.setPrototypeOf(this,rA.prototype)}}function rI(e){try{return e()}catch(e){if(e instanceof rA)throw new rA(e.message,"missing_context");throw e}}function rC(e){if("boolean"==typeof e)return!0;if("string"==typeof e){let t=e.toLowerCase();return"true"===t||"false"===t}if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!rC(t in e?e[t]:null))return!1;return!0}function rk(e){if("boolean"==typeof e)return e;if("string"==typeof e)return"true"===e.toLowerCase();if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!rk(t in e?e[t]:null))return!1;return!0}function r$(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let r=e.charCodeAt(t+1);if(t+1>=e.length||r<56320||r>57343)throw new rA("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new rA("Cannot stringify an unpaired surrogate like the flags service")}}function rT(e,t=new Set){if(null!==e&&"boolean"!=typeof e){if("string"==typeof e)return void r$(e);if("number"==typeof e){if(!Number.isFinite(e))throw new rA(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new rA("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&rT(e[r],t)}finally{t.delete(e)}return}if("object"==typeof e){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&null!==r)throw new rA("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new rA("Cannot represent a circular object during local evaluation");t.add(e);try{for(let r of Object.keys(e))r$(r),rT(e[r],t)}finally{t.delete(e)}return}throw new rA(`Cannot represent ${typeof e} like the flags service`)}}function rO(e,t){let r=0,i=0;for(;r<e.length&&i<t.length;){let s=e.charCodeAt(r),n=t.charCodeAt(i),a=s>=55296&&s<=56319,o=n>=55296&&n<=56319,l=a?e.charCodeAt(r+1):0,u=o?t.charCodeAt(i+1):0,c=a?(s-55296)*1024+l-56320+65536:s,h=o?(n-55296)*1024+u-56320+65536:n;if(c!==h)return c-h;r+=a?2:1,i+=o?2:1}return e.length-t.length}function rR(e){return"string"==typeof e?(r$(e),e):function e(t,r=new Set){if(null===t)return"null";if("string"==typeof t)return r$(t),JSON.stringify(t);if("boolean"==typeof t)return t?"true":"false";if("number"==typeof t){if(!Number.isFinite(t))throw new rA(`Cannot stringify non-finite number ${t} like the flags service`);if(Number.isInteger(t))throw new rA(`Cannot distinguish integer ${t} from an integral JSON float during local evaluation`);return String(t)}if(Array.isArray(t)){if(r.has(t))throw new rA("Cannot stringify a circular array during local evaluation");r.add(t);try{let i=[];for(let s=0;s<t.length;s++)i.push(s in t?e(t[s],r):"null");return`[${i.join(",")}]`}finally{r.delete(t)}}if("object"==typeof t){let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&null!==i)throw new rA("Cannot stringify a non-JSON object like the flags service");if(r.has(t))throw new rA("Cannot stringify a circular object during local evaluation");r.add(t);try{let i=Object.keys(t);return i.forEach(r$),`{${i.sort(rO).map(i=>`${JSON.stringify(i)}:${e(t[i],r)}`).join(",")}}`}finally{r.delete(t)}}throw new rA(`Cannot stringify ${typeof t} like the flags service`)}(e)}let rM=/[\x20-\x2f:;=?@\x5b-\x60\x7b-\x7e]/;function rj(e){let t=new rA(e);return Object.defineProperty(t,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),t}function rL(e){return String(e).replace(/[A-Z]/g,e=>e.toLowerCase())}function rD(e,t,r){if(!/^\d+$/.test(e)||"strict"===r&&e.length>1&&"0"===e[0])throw new rA(`Invalid semver: ${t}`);return parseInt(e,10)}function rB(e,t="strict"){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new rA(`Invalid semver: ${e}`);let i=r.split("."),s=r=>void 0===r||""===r?0:rD(r,e,t);return[s(i[0]),s(i[1]),s(i[2])]}function rN(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 rq(e,t){let r=rB(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function rU(e,t){let[r,i,s]=rB(e,t);return{lower:[r,i,s],upper:r>0?[r+1,0,0]:i>0?[0,i+1,0]:[0,0,s+1]}}function rH(e,t){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new rA(`Invalid wildcard semver: ${e}`);let i=r.split("."),s=r=>{if("legacy-permissive"===t){let e=parseInt(r,10);if(!isNaN(e))return e}else try{return rD(r,e,t)}catch{}throw new rA(`Invalid wildcard semver: ${e}`)},n=s(i[0]);if(1===i.length)return{lower:[n,0,0],upper:[n+1,0,0]};let a=s(i[1]);return{lower:[n,a,0],upper:[n,a+1,0]}}function rW(e){if(e instanceof Date)return e;if("string"==typeof e||"number"==typeof e){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new rA(`${e} is in an invalid date format`)}throw new rA(`The date provided ${e} must be a string, number, or date object`)}function rK(e){if("boolean"==typeof e)throw new rA("Date operations cannot be performed on boolean values");return function(e){let t=e.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),r=new Date(new Date().toISOString());if(!t||!t.groups)return null;let i=parseInt(t.groups.number);if(i>=1e4)return null;let s=t.groups.interval;if("h"===s)r.setUTCHours(r.getUTCHours()-i);else if("d"===s)r.setUTCDate(r.getUTCDate()-i);else if("w"===s)r.setUTCDate(r.getUTCDate()-7*i);else if("m"===s){var n,a,o=r,l=i;let e=o.getUTCFullYear(),t=o.getUTCMonth(),s=o.getUTCDate();for(let r=1;r<=l&&s>28;r++)s=Math.min(s,new Date(Date.UTC(e,t-r+1,0)).getUTCDate());o.setUTCFullYear(e,t-l,s)}else{let e,t;if("y"!==s)return null;n=r,a=i,e=n.getUTCMonth(),t=a>0&&1===e&&29===n.getUTCDate()?28:n.getUTCDate(),n.setUTCFullYear(n.getUTCFullYear()-a,e,t)}return r}(String(e))??rW(e)}function rV(e,t={}){let r=e.value,i=t.semverParsingPolicy??"strict";switch(e.operator||"exact"){case"exact":case"is_not":for(let e of Array.isArray(r)?r:[r])rR(e);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":rK(r);return;case"semver_eq":case"semver_neq":case"semver_gt":case"semver_gte":case"semver_lt":case"semver_lte":rB(String(r),i);return;case"semver_tilde":rq(String(r),i);return;case"semver_caret":rU(String(r),i);return;case"semver_wildcard":rH(String(r),i);return;default:throw new rA(`Unknown operator: ${e.operator}`)}}async function rz(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");return Array.from(new Uint8Array(await t.digest("SHA-1",new TextEncoder().encode(e)))).map(e=>e.toString(16).padStart(2,"0")).join("")}async function rQ(e,t,r="",i="."){return parseInt((await rz(`${e}${i}${t}${r}`)).slice(0,15),16)/0x1000000000000000}async function rG(e,t){if(null==e||null==e.id||null==e.exclusion_percentage)return;let r=Number(e.exclusion_percentage);if(!Number.isFinite(r))return;let i=Math.min(Math.max(r,0),100);if(!(100!==i&&await rQ("holdout",t,"","-")>i/100))return`holdout-${e.id}`}function rJ(e){let t=[],r=0;for(let i of e){let e=r+i.rollout_percentage/100;t.push({valueMin:r,valueMax:e,key:i.key}),r=e}return t}async function rZ(e,t,r){let i=await rQ(e,t,"variant");return rJ(r).find(e=>i>=e.valueMin&&i<e.valueMax)?.key}function rY(e){return"client"===e||"server"===e?e:"all"}function rX(e,t){return e===t||"all"===e||"all"===t}class r0 extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,r0.prototype)}}class r1 extends Error{constructor(e,t="unsupported_definition"){super(e),this.reason=t,this.name=r1.name,Error.captureStackTrace(this,r1),Object.setPrototypeOf(this,r1.prototype)}}let r2=["experience_continuity","unsupported_definition","unresolved_dependency","missing_context"];function r5(e,t){return void 0===e||r2.indexOf(t)<r2.indexOf(e)?t:e}function r3(e,t){return t instanceof rA&&Symbol.for("posthog.requiresServerRegexEvaluation")in t&&Object.defineProperty(e,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),e}class r4{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:i,host:s,customHeaders:n,...a}){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=i,this.projectApiKey=r,this.host=s,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=n,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}currentDefinitions(){return{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}withEvaluationSnapshot(e){return e.definitions?e:{...e,evaluationCache:{},definitions:this.currentDefinitions()}}createEvaluationContext(e,t={},r={},i={},s={}){return{distinctId:e,groups:t,personProperties:r,groupProperties:i,evaluationCache:s}}async getFeatureFlag(e,t,r={},i={},s={}){let n,a;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return n;if(void 0!==(a=this.featureFlagsByKey[e])){let o=this.createEvaluationContext(t,r,i,s);try{n=(await this.computeFlagAndPayloadLocally(a,o)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${n}`))}catch(t){t instanceof r1||t instanceof rA?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e}: ${t}`))}}return n}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let r={},i={},s={},n=0==this.featureFlags.length,a=t?t.map(e=>this.featureFlagsByKey[e]).filter(Boolean):this.featureFlags,o=this.withEvaluationSnapshot({...e,definitions:void 0});return await Promise.all(a.map(async e=>{try{let{value:t,payload:s}=await this.computeFlagAndPayloadLocally(e,o,{skipLoadCheck:!0});r[e.key]=t,s&&(i[e.key]=s)}catch(t){t instanceof r1||t instanceof rA?(this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e.key}: ${t.message}`)),s[e.key]=t.reason):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e.key}: ${t}`)),rX(rY(e.evaluation_runtime),"server")&&(n=!0)}})),{response:r,payloads:i,unresolved:s,fallbackToFlags:n}}async computeFlagAndPayloadLocally(e,t,r={}){let i,{matchValue:s,skipLoadCheck:n=!1}=r;if(this.loadedSuccessfullyOnce&&(t=this.withEvaluationSnapshot(t)),n||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};e=(t=this.withEvaluationSnapshot(t)).definitions.featureFlagsByKey[e.key]??e,i=void 0!==s?s:await this.computeFlagValueLocally(e,t);let a=function(e,t){if(!1===t||null==t||!e)return null;let r=e["boolean"==typeof t?t.toString():t]||null;return null==r?null:eI(r)}(e.filters?.payloads,i);return{value:i,payload:a}}async computeFlagValueLocally(e,t){let{distinctId:r,groups:i,personProperties:s,groupProperties:n}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new rA("Flag has experience continuity enabled","experience_continuity");let a=(e.filters||{}).aggregation_group_type_index;if(void 0!=a){let r=t.definitions.groupTypeMapping[String(a)];if(!r)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${a} for feature flag ${e.key}`)),new rA("Flag has unknown group type index");if(!(r in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;"device_id"===e.bucketing_identifier&&(s?.$device_id===void 0||s?.$device_id===null||s?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let o=n[r];return await this.matchFeatureFlagProperties(e,i[r],o,t)}{let i=this.getBucketingValueForFlag(e,r,s);if(void 0===i)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new rA(`Can't compute feature flag: ${e.key} without $device_id`,r6(e,t.definitions)??"missing_context");return await this.matchFeatureFlagProperties(e,i,s,t)}}getBucketingValueForFlag(e,t,r){if(e.filters?.aggregation_group_type_index!=void 0)return t;if("device_id"===e.bucketing_identifier){let e=r?.$device_id;if(null==e||""===e)return;return e}return t}async evaluateFlagDependency(e,t,r){let{evaluationCache:i}=r,s=e.key;if(!r.definitions.featureFlagsByKey)throw new rA("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new rA(`Flag dependency property for '${s}' is missing required 'dependency_chain' field`);let n=e.dependency_chain;if(!Array.isArray(n))throw new rA(`Flag dependency property for '${s}' has an invalid 'dependency_chain' (expected array, got ${typeof n})`);if(0===n.length)throw new rA(`Circular dependency detected for flag '${s}' (empty dependency chain)`);let a=n.find(e=>!(e in i)&&!r.definitions.featureFlagsByKey[e]&&!r.definitions.filteredOutFlagKeys.has(e));if(void 0!==a)throw new rA(`Missing flag dependency '${a}' for flag '${s}'`);for(let e of n){if(!(e in i)){let t=r.definitions.featureFlagsByKey[e];if(t)if(t.active)try{let s=await this.computeFlagValueLocally(t,r);i[e]=s}catch(t){if(t instanceof r1)throw new r1(`Flag dependency '${e}' for flag '${s}' requires server evaluation: ${t.message}`,"unresolved_dependency");throw r3(new rA(`Error evaluating flag dependency '${e}' for flag '${s}': ${t}`,"unresolved_dependency"),t)}else i[e]=!1;else i[e]=!1}if(null==i[e])throw new rA(`Dependency '${e}' could not be evaluated`,"unresolved_dependency")}let o=i[s];return this.flagEvaluatesToExpectedValue(e.value,o)}flagEvaluatesToExpectedValue(e,t){return"boolean"==typeof e?e===t||"string"==typeof t&&""!==t&&!0===e:"string"==typeof e&&t===e}async matchFeatureFlagProperties(e,t,r,i){let s,n,a;i=this.withEvaluationSnapshot(i);let o=e.filters||{},l=await rG(o.holdout,t);if(void 0!==l)return l;let u=o.groups||[],c=o.aggregation_group_type_index,h=o.early_exit??!1,{groups:d,groupProperties:f}=i,p=new Set;for(let l of u){let u=t;try{let t=void 0!==l.aggregation_group_type_index?l.aggregation_group_type_index:c,n=r;if(t!==c&&null!=t){let r=i.definitions.groupTypeMapping[String(t)];if(!r||!(r in d)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${t} not available`));continue}if(!(r in f)){s=r5(s,"missing_context");continue}n=f[r],u=d[r]}let p=await this.isConditionMatch(e,u,l,n,i);if("match"===p){let t=l.variant,r=o.multivariate?.variants||[];a=t&&r.some(e=>e.key===t)?t:await this.getMatchingVariant(e,u)||!0;break}if(h&&"out_of_rollout_bound"===p){if(s)break;return!1}}catch(t){if(t instanceof r1){let r;try{r=r6(e,i.definitions)}catch{}let n=r5(r5(s,t.reason),r??t.reason);throw n===t.reason?t:new r1(t.message,n)}if(t instanceof rA){if(s=r5(s,t.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in t)if(n=t,h&&void 0!=l.rollout_percentage&&await rQ(e.key,u)>l.rollout_percentage/100)p.add(!1);else{let t=o.multivariate?.variants||[],r=l.variant;p.add(r&&t.some(e=>e.key===r)?r:await this.getMatchingVariant(e,u)||!0)}}else throw t}}if(void 0!==a&&!(n&&[...p].some(e=>e!==a)))return a;if(s)throw r3(new rA("Can't determine if feature flag is enabled or not with given properties",s),n);return!1}async isConditionMatch(e,t,r,i,s){let n=(s=this.withEvaluationSnapshot(s)).definitions,a=r.rollout_percentage,o=e=>{this.logMsgIfDebug(()=>console.warn(e))};if((r.properties||[]).length>0){let t,l,u;for(let e of r.properties){let r=e.type,a=!1;try{if("cohort"===r)a=await r9(e,i,n.cohorts,this.debugMode,e=>this.evaluateFlagDependency(e,i,s),n.propertyMatchingVersion);else if("flag"===r)a=await this.evaluateFlagDependency(e,i,s);else if(Object.prototype.hasOwnProperty.call(i,e.key))a=r8(e,i,o,n.propertyMatchingVersion);else{rV(e),t=r5(t,"missing_context");continue}}catch(e){if(e instanceof r1){void 0===t&&(u??=e),t=r5(t,e.reason);continue}if(e instanceof rA){Symbol.for("posthog.requiresServerRegexEvaluation")in e&&(l=e),t=r5(t,e.reason);continue}if(void 0!==t)break;throw e}if(!a)return"no_match"}if(u)throw u;if(t)throw r3(new rA(`Can't determine if a condition of flag ${e.key} matches`,t),l);if(void 0==a)return"match"}return void 0!=a&&await rQ(e.key,t)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){return rZ(e.key,t,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return rJ(e.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(e){if(!this.evaluationContexts||0===this.evaluationContexts.length)return e;let t=new Set(this.evaluationContexts);return e.filter(e=>{let r=e.evaluation_contexts??e.evaluation_tags;return!r||0===r.length||r.some(e=>t.has(e))})}getEvaluationRuntimeForFlag(e){let t=this.featureFlagsByKey[e];return t?rY(t.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(e){return this.featureFlags.filter(t=>rX(rY(t.evaluation_runtime),e)).map(e=>e.key)}updateFlagState(e){let t=this.filterFlagsByEvaluationContexts(e.flags),r=t.reduce((e,t)=>(e[t.key]=t,e),{}),i=new Set(t.map(e=>e.key)),s=new Set(e.flags.filter(e=>!i.has(e.key)).map(e=>e.key));this.featureFlags=t,this.featureFlagsByKey=r,this.filteredOutFlagKeys=s,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=[],i=new Map,s=this.currentDefinitions();for(let n of e){if(!rX(rY(n.evaluation_runtime),"server"))continue;let e=r6(n,s);if(!e)continue;let a=JSON.stringify(n);i.set(n.key,a),this.warnedUnresolvableFlags.get(n.key)!==a&&("experience_continuity"===e?t.push(n.key):r.push(n.key))}if(this.warnedUnresolvableFlags=i,t.length>0){let e=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(", ")}. `+e)}if(r.length>0){let e=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(", ")}. ${e} 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(e){return this.onError?.(Error(`Failed to load from cache: ${e}`)),!1}}async loadFeatureFlags(e=!1){if(!this.loadedSuccessfullyOnce||e)return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(e=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${e}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let e=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(6e4,e*2**this.backOffCount):e}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(){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(e){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${e}`))}if(!e&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||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 r0(`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 r0(`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 r0(`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 i=r.group_type_mapping||{},s=!0===r.minimal_flag_called_events,n={flags:r.flags??[],group_type_mapping:i,cohorts:r.cohorts||{},minimal_flag_called_events:s,property_matching_version:r.property_matching_version,propertyMatchingVersion:r.property_matching_version,groupTypeMapping:i,minimalFlagCalledEvents:s};if(this.updateFlagState(n),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(e){this.onError?.(Error(`Failed to store in cache: ${e}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags);break}default:return}}catch(e){e instanceof r0&&this.onError?.(e)}finally{this.pollerStopped||null===this.pollingInterval||(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(e="GET",t){let r={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(r["If-None-Match"]=t),{method:e,headers:r}}async _requestFeatureFlagDefinitions(){if(!this.personalApiKey)throw new r0("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&&"number"==typeof this.timeout){let e=new AbortController;r=eD(()=>{e.abort()},this.timeout),t.signal=e.signal}try{let i=this.fetch,s=await i(e,t);if(200!==s.status)return clearTimeout(r),s;return{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{clearTimeout(r)}},json:async()=>{try{return await s.json()}finally{clearTimeout(r)}}}}catch(e){throw clearTimeout(r),e}}async stopPoller(e=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await eB(t,e,()=>{throw Error(`Cache shutdown timeout after ${e}ms`)})}catch(e){this.onError?.(Error(`Error during cache shutdown: ${e}`))}}}function r6(e,t){if(!e.active)return;if(e.ensure_experience_continuity)return"experience_continuity";let r=e.filters||{},i=r.aggregation_group_type_index;return void 0==i||t.groupTypeMapping[String(i)]?(r.groups||[]).some(e=>(e.properties||[]).some(e=>(function e(t,r,i){if("flag"===t.type){let e=t.dependency_chain;return!Array.isArray(e)||0===e.length||e.some(e=>!r.featureFlagsByKey[e]&&!r.filteredOutFlagKeys.has(e))}if("cohort"!==t.type)try{return rV(t),!1}catch(e){if(e instanceof rA)return!0;throw e}let s=String(t.value);return!(s in r.cohorts)||!i.has(s)&&(i.add(s),function t(r,i,s){return(r?.values??[]).some(r=>"values"in r?t(r,i,s):e(r,i,s))}(r.cohorts[s],r,i))})(e,t,new Set)))?"unsupported_definition":void 0:"unsupported_definition"}function r8(e,t,r,i){return function(e,t,r={}){try{return function(e,t,r){let i=e.key,s=e.value,n=e.operator||"exact",a=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,i)){if("is_not_set"===n)return!1;else if("is_set"===n)return!0}else throw new rA(`Property ${i} not found in propertyValues`,"missing_context");let o=t[i];if(void 0===o)throw r.warnFunction?.(`Property ${i} cannot have a value of undefined with the ${n} operator`),new rA(`Property ${i} is undefined in propertyValues`);if(null===o&&!rP.includes(n))return r.warnFunction?.(`Property ${i} cannot have a value of null with the ${n} operator`),!1;let l=(e,t)=>{if(2!==r.propertyMatchingVersion&&rC(e)||Array.isArray(e)&&0===e.length)return rI(()=>rT(t)),rk(e)===rk(t);if(2===r.propertyMatchingVersion&&"number"==typeof t&&rC(e))return rI(()=>rT(t)),!1;if(Array.isArray(e)){let r=rI(()=>rR(t)).toLowerCase();return e.some(e=>rR(e).toLowerCase()===r)}return rR(e).toLowerCase()===rI(()=>rR(t)).toLowerCase()},u=(e,t,r)=>{if("gt"===r)return e>t;if("gte"===r)return e>=t;if("lt"===r)return e<t;if("lte"===r)return e<=t;throw Error(`Invalid operator: ${r}`)},c=()=>rI(()=>rB(String(o),a)),h=()=>{let e=rB(String(s),a);return rN(c(),e)},d=({lower:e,upper:t})=>{let r=c();return rN(r,e)>=0&&0>rN(r,t)};switch(n){case"exact":return l(s,o);case"is_not":return!l(s,o);case"is_set":return!0;case"icontains":return rL(o).includes(rL(s));case"not_icontains":return!rL(o).includes(rL(s));case"starts_with":return rL(o).startsWith(rL(s));case"not_starts_with":return!rL(o).startsWith(rL(s));case"ends_with":return rL(o).endsWith(rL(s));case"not_ends_with":return!rL(o).endsWith(rL(s));case"regex":case"not_regex":{let e=function(e,t){let r;if(""===e)return!0;let i=function(e){let t=[],r=-1,i="";for(let s=0;s<e.length;s++){let n=e[s];if(n.charCodeAt(0)>127)return null;if("\\"===n){let t=e[++s];if(void 0===t)break;if("x"===t){if(!/^[\da-f]{2}$/i.test(e.slice(s+1,s+3)))return null;s+=2}else if(!"dDsSwWbBfnrtv".includes(t)&&!rM.test(t))return null;if(-1===r&&"bB".includes(t))return null;i="literal";continue}if("["===n){if(-1!==r)return null;r=s}else if("]"===n&&-1!==r){if(s===r+("^"===e[r+1]?2:1))return null;t.push(e.slice(r,s+1)),r=-1,i="literal";continue}else if(-1!==r){if(["&&","--","~~"].includes(e.slice(s,s+2)))return null;continue}else if("("===n&&"?"===e[s+1]){if(":"!==e[s+2])return null;s+=2}else if("{"===n){let t=/^\{(\d+)(?:,(\d*))?\}/.exec(e.slice(s));if(!t||["","|","("].includes(i)||t.slice(1).some(e=>Number(e)>0xffffffff))return null}else if("*+?}".includes(n)&&("+"===e[s+1]||"{"===e[s+1]))return null;if("*+?{".includes(n)&&["^","$","empty group"].includes(i))return null;i=")"===n&&["(","empty group"].includes(i)?"empty group":n}return t}(e);if(null===i)throw rj("Regex syntax requires server evaluation");try{r=new RegExp(e)}catch(e){if(e instanceof SyntaxError)return null;throw rj("Regex compilation requires server evaluation")}for(let e of i)try{RegExp(e,"u")}catch{throw rj("Regex character class syntax requires server evaluation")}for(let e=0;e<t.length;e++){let r=t[e];if(r.charCodeAt(0)>127||"\r"===r)throw rj("Regex matching for Unicode or carriage returns requires server evaluation")}try{return r.test(t)}catch{throw rj("Regex execution requires server evaluation")}}(String(s),String(o));if(null===e)return!1;return"regex"===n?e:!e}case"gt":case"gte":case"lt":case"lte":{let e="number"==typeof s?s:parseFloat(String(s)),t="number"==typeof o?o:null!=o?parseFloat(String(o)):0/0;if(Number.isFinite(e)&&Number.isFinite(t))return u(t,e,n);return u(String(o),String(s),n)}case"is_date_after":case"is_date_before":{let e=rK(s),t=rI(()=>rW(o));return"is_date_before"===n?t<e:t>e}case"semver_eq":return 0===h();case"semver_neq":return 0!==h();case"semver_gt":return h()>0;case"semver_gte":return h()>=0;case"semver_lt":return 0>h();case"semver_lte":return 0>=h();case"semver_tilde":return d(rq(String(s),a));case"semver_caret":return d(rU(String(s),a));case"semver_wildcard":return d(rH(String(s),a));default:throw new rA(`Unknown operator: ${n}`)}}(e,t,r)}catch(t){throw t instanceof rA&&"missing_context"===t.reason&&rV(e,r),t}}(e,t,{warnFunction:r,propertyMatchingVersion:i})}async function r9(e,t,r,i=!1,s,n){let a=String(e.value);if(!(a in r))throw new r1(`cohort ${a} not found in local cohorts - likely a static cohort that requires server evaluation`);let o=r[a],l=await r7(o,t,r,i,s,n);return"not_in"===e.operator?!l:l}async function r7(e,t,r,i=!1,s,n){let a,o;if(!e||0===Object.keys(e).length)return!0;let l="property"===e.type?"AND":e.type;if("AND"!==l&&"OR"!==l)throw new r1(`Unsupported cohort property group type: ${e.type}`);let u=e.values;if(!u||0===u.length)return"AND"===l;if("values"in u[0]){for(let e of u)try{let a=await r7(e,t,r,i,s,n);if("AND"===l){if(!a)return!1}else if(a)return!0}catch(t){if(t instanceof r1)throw t;if(t instanceof rA)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),a=r5(a,t.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in t&&(o=t);else throw t}if(a)throw r3(new rA("Can't match cohort without a given cohort property value",a),o);return"AND"===l}for(let e of u)try{let a;if("cohort"===e.type)a=await r9(e,t,r,i,s,n);else if("flag"===e.type){if(!s)throw new rA(`Flag dependency '${e.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);a=await s(e)}else a=r8(e,t,void 0,n);let o=e.negation||!1;if("AND"===l){if(!a&&!o||a&&o)return!1}else if(a&&!o||!a&&o)return!0}catch(t){if(t instanceof r1)throw t;if(t instanceof rA)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),a=r5(a,t.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in t&&(o=t);else throw t}if(a)throw r3(new rA("can't match cohort without a given cohort property value",a),o);return"AND"===l}let ie=["--unhandled-rejections","--unhandled_rejections"],it=new Set(["throw","strict","warn","warn-with-error-code","none"]),ir=[...globalThis.process?.execArgv??[]],ii=globalThis.process?.env?.NODE_OPTIONS;function is(e){let t;for(let r=0;r<e.length;r++){let i=e[r],s=ie.find(e=>i===e||i.startsWith(`${e}=`));if(!s)continue;let n=i===s?e[++r]:i.slice(s.length+1);it.has(n)&&(t=n)}return t}let ia=function(e=ir,t=ii){return is(e)??is(function(e){let t=[],r="",i=!1;for(let s=0;s<e.length;s++){let n=e[s];"\\"===n&&i&&s+1<e.length?r+=e[++s]:" "!==n||i?'"'===n?i=!i:r+=n:r&&(t.push(r),r="")}return r&&t.push(r),t}(t??""))??"throw"}(),io={mechanism:{type:"onunhandledrejection",handled:!1}},il={mechanism:{type:"onuncaughtexception",handled:!1}},iu=new Set(["HANGING_PROMISE_REJECTION","NEXT_PRERENDER_INTERRUPTED","DYNAMIC_SERVER_USAGE","BAILOUT_TO_CLIENT_SIDE_RENDERING"]),ic=Symbol.for("react.postpone"),ih=Symbol.for("next.unhandledRejectionFilter"),id=Symbol.for("posthog-node.exception-autocapture.v1"),ip=globalThis;function ig(e){return"function"==typeof e&&!0===e._posthogErrorHandler}function im(e){return"object"==typeof e&&null!==e||"function"==typeof e}function i_(e){return Object.assign(e,{_posthogErrorHandler:!0})}function iy(e){return e.listeners("unhandledRejection").some(e=>!ig(e))}function iv(e,t){return function e(t,r=0){try{if(!im(t))return!1;if(t.$$typeof===ic||"string"==typeof t.digest&&iu.has(t.digest))return!0;return r<5&&e(t.cause,r+1)}catch{return!1}}(e)||"unhandledRejection"===t&&function(e){try{return im(e)&&"AbortError"===e.name}catch{return!1}}(e)}function ib(e){let t=new Map;for(let r of e.clients){let e=t.get(r.key);e&&(void 0!==e.getContext()||void 0===r.getContext())||t.set(r.key,r)}for(let[r,i]of e.retired)t.has(r)||t.set(r,i);return[...t.values()]}function iw(e){"function"==typeof globalThis.setImmediate?setImmediate(e):setTimeout(e,0)}function ix(e,t,r,i){let s=e.capturedThisTurn.get(t)??new Map;s.has(r)||s.set(r,i),e.capturedThisTurn.set(t,s),e.turnResetScheduled||(e.turnResetScheduled=!0,iw(()=>{iw(()=>{e.capturedThisTurn.clear(),e.turnResetScheduled=!1})}))}function iS(e,t,r,i){let s=e.capturedThisTurn.get(t),n=[];for(let a of ib(e))s?.has(a.key)||i?.has(a.key)||(ix(e,t,a.key,"autocapture"),a.capture(t,r),n.push(a));return n}function iF(e,t){return e.deferred.get(t.exception)!==t?[]:(e.deferred.delete(t.exception),t.runInContext(()=>iS(e,t.exception,t.hint,t.skipKeys)))}function iE(e,t,r){let i;if(void 0!==(i=e.capturedThisTurn.get(t))&&ib(e).every(e=>i.has(e.key))||e.deferred.has(t))return;let s={exception:t,hint:r,skipKeys:new Set(e.capturedThisTurn.get(t)?.keys()),runInContext:function(){try{let e=globalThis.process,t=e?.getBuiltinModule?.("node:async_hooks"),r=t?.AsyncLocalStorage?.snapshot?.();if(r)return r}catch{}return e=>e()}()};e.deferred.set(t,s),iw(()=>iF(e,s))}async function iP(e,t){try{console.error(t)}catch{}i$();let r=new Set([...e.clients,...e.retired.values()]);await Promise.all([...r].map(e=>e.shutdown().catch(()=>void 0))),globalThis.process.exit(1)}function iA(e,t,r,i){let s="unhandledRejection"===r?io:il;if(!i){iv(t,r)||iE(e,t,s);return}let n=e.deferred.get(t);n?iF(e,n):iS(e,t,s)}function iI(e){try{return String(e)}catch{return typeof e}}function iC(e){let t=globalThis.process;ip[ih]&&"function"==typeof t.rawListeners&&t.rawListeners("unhandledRejection").includes(e)&&(Object.getPrototypeOf(t).removeListener.call(t,"unhandledRejection",e),t.listeners("unhandledRejection").includes(e)||t.prependListener("unhandledRejection",e))}function ik(e){let t=globalThis.process,r=[],i=(e,i)=>{t.on(e,i),r.push(()=>t.removeListener(e,i))},s=()=>r.forEach(e=>e());if("strict"===e.mode){let r=(t,r)=>iA(e,t,r,!0);return i("uncaughtExceptionMonitor",r),{remove:s,areInstalled:()=>t.listeners("uncaughtExceptionMonitor").includes(r)}}let n=i_((t,r)=>{let i=0===globalThis.process.listeners("uncaughtException").filter(e=>"domainUncaughtExceptionClear"!==e.name&&!ig(e)).length;iA(e,t,r,i),i&&!e.calledFatalError&&(e.calledFatalError=!0,iP(e,t))});i("uncaughtException",n);let a="throw"===e.mode||"warn-with-error-code"===e.mode,o=a&&!t.versions?.bun,l=()=>t.listeners("unhandledRejection").includes(u),u=i_(t=>{a&&!iy(globalThis.process)&&l()?function(e,t){let r=globalThis.process;if("warn-with-error-code"===e.mode){r.emitWarning(`Unhandled promise rejection: ${iI(t)}`,"UnhandledPromiseRejectionWarning"),r.exitCode=1,iv(t,"unhandledRejection")||iS(e,t,io);return}if(r.versions?.bun){r.exitCode=1,iS(e,t,io),e.calledFatalError||(e.calledFatalError=!0,iP(e,t));return}let i=t instanceof Error?t:Object.assign(Error(`This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "${iI(t)}".`),{name:"UnhandledPromiseRejection",code:"ERR_UNHANDLED_REJECTION"}),s=r.emit;s.call(r,"uncaughtExceptionMonitor",i,"unhandledRejection"),s.call(r,"uncaughtException",i,"unhandledRejection")}(e,t):iv(t,"unhandledRejection")||iE(e,t,io)});return i("newListener",i_((e,r)=>{ig(r)||("unhandledRejection"===e?(l()||t.prependListener("unhandledRejection",u),queueMicrotask(()=>{let e;(e="function"==typeof t.rawListeners?t.rawListeners("unhandledRejection"):[]).includes(u)&&e[0]!==u&&(t.removeListener("unhandledRejection",u),t.prependListener("unhandledRejection",u)),iC(u)})):"Next.UnhandledRejectionFilter.MacguffinEvent"===e&&queueMicrotask(()=>{l()||t.prependListener("unhandledRejection",u)}))})),o?(i("removeListener",i_(e=>{"unhandledRejection"===e&&l()&&!iy(t)&&t.removeListener("unhandledRejection",u)})),iy(t)&&t.prependListener("unhandledRejection",u)):t.prependListener("unhandledRejection",u),iC(u),r.push(()=>{t.removeListener("unhandledRejection",u),"function"==typeof t.rawListeners&&t.rawListeners("unhandledRejection").includes(u)&&Object.getPrototypeOf(t).removeListener.call(t,"unhandledRejection",u)}),{remove:s,areInstalled:()=>t.listeners("uncaughtException").includes(n)&&(o||l())}}function i$(){let e=new Set,t=ip[id];if(t)for(let r of[...t.deferred.values()])iF(t,r).forEach(t=>e.add(t));return e}let iT=Symbol("capturedContext");function iO(e,t,r,i,s){if(t>r&&(i.warn("min cannot be greater than max."),t=r),F(e))if(e>r)return i.warn(" cannot be greater than max: "+r+". Using max value instead."),r;else return e<t?(i.warn(" cannot be less than min: "+t+". Using min value instead."),t):e;return i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+s),iO(s??r,t,r,i)}class iR{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=iO(e.bucketSize,0,100,e._logger),this._refillRate=iO(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=iO(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){let r=Math.floor((t-e.lastAccess)/this._refillInterval);if(r>0){let t=r*this._refillRate;e.tokens=Math.min(e.tokens+t,this._bucketSize),e.lastAccess=e.lastAccess+r*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),r=String(e),i=this._buckets[r];return i?this._applyRefill(i,t):(i={tokens:this._bucketSize,lastAccess:t},this._buckets[r]=i),0===i.tokens||(i.tokens--,0===i.tokens&&this._onBucketRateLimited?.(e),0===i.tokens)}stop(){this._buckets={}}}var iM=ed;let ij=class e{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new iR({...function(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??1,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??10}}(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return e===Object(e)&&!y(e)&&"__posthog_previously_captured_error"in e&&!0===e.__posthog_previously_captured_error}static async buildEventMessage(e,t,r,i,s,n){let a,o=(a=n?{...n,properties:{...n.properties}}:null,e=>Object.assign(e,{[iT]:a})),l={...s},u=e.buildFromUnknown(t,r);u.$exception_list=await e.modifyFrames(u.$exception_list);let c=iM.getInjectedReleaseId();return c&&(l.$release_id=c),o({event:"$exception",distinctId:i,properties:{...u,...l},_originatedFromCaptureException:!0})}get destinationKey(){return`${this.client.apiKey}@${this.client.host}`}startAutocaptureIfEnabled(){this.isEnabled()&&(this._autocaptureClient={key:this.destinationKey,capture:(e,t)=>this.onException(e,t),getContext:()=>this.client.getContext(),flush:()=>this.client.flush(),shutdown:()=>this.client.shutdown(2e3)},this._stopAutocapture=function(e,t=ia){if(!globalThis.process?.on)return()=>void 0;let r=ip[id];if(r)r.listeners.areInstalled()||(r.listeners.remove(),r.listeners=ik(r));else{let e={mode:t,clients:new Set,retired:new Map,capturedThisTurn:new Map,deferred:new Map,turnResetScheduled:!1,calledFatalError:!1,listeners:{remove:()=>void 0,areInstalled:()=>!0}};e.listeners=ik(e),ip[id]=e,r=e}r.clients.add(e),r.retired.delete(e.key);let i=r;return()=>{i.clients.delete(e)&&([...i.clients].some(t=>t.key===e.key)||i.retired.set(e.key,e))}}(this._autocaptureClient))}claimExplicitCapture(e){var t;let r;return t=this.destinationKey,!(r=ip[id])||r.capturedThisTurn.get(e)?.get(t)!=="autocapture"&&(ix(r,e,t,"app"),r.deferred.get(e)?.skipKeys.add(t),!0)}capturePendingExceptions(){for(let e of i$())e!==this._autocaptureClient&&this.client.addPendingPromise(e.flush().catch(()=>void 0))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let i=await e.buildEventMessage(this.client.getErrorPropertiesBuilder(),t,r,void 0,void 0,this.client.getContext()),s=i.properties,n=s?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(n)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:n}):this.client._capturePreparedEvent(i,!1)}})().catch(e=>{this._logger.error("Failed to capture an exception:",e)}))}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop(),this.capturePendingExceptions(),this._stopAutocapture?.(),this._stopAutocapture=void 0}},iL=/^[0-9a-f]{32}$/i,iD=/^[0-9a-f]{16}$/i,iB=Symbol.for("opentelemetry.js.api.1"),iN=Symbol.for("OpenTelemetry Context Key SPAN");async function iq(){try{let e=globalThis[iB],t=e?.context?.active().getValue(iN),r=t?.spanContext(),i=r?.traceId,s=r?.spanId;if("string"==typeof i&&"string"==typeof s&&iL.test(i)&&iD.test(s)&&!/^0+$/.test(i)&&!/^0+$/.test(s))return{$trace_id:i.toLowerCase(),$span_id:s.toLowerCase()}}catch{}return{}}class iU{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=null!==t?t:void 0}constructor(){this._memoryStorage={}}}let iH=Symbol.for("posthog-node.context-listeners"),iW=globalThis,iK=iW[iH]??=new WeakMap;function iV(e,t=!1){for(let r of iK.get(e)??[])try{r(t)}catch{}}function iz(e){iV(e,!0)}let iQ="analytics";class iG extends Error{constructor({requestId:e,drops:t,retryExhausted:r,cause:i}){super(iG.buildMessage(e,t,r,i)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=r,this.cause=i}static buildMessage(e,t,r,i){let s=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${r.length} undelivered`;return i instanceof Error&&(s+=` (${i.message})`),s}}function iJ(e){if("boolean"==typeof e)return e;if("number"==typeof e)return 0!==e;if("string"==typeof e){let t=e.trim().toLowerCase();if("true"===t||"1"===t)return!0;if("false"===t||"0"===t)return!1}}let iZ=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:iJ},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:iJ},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:iJ},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(e){return"string"==typeof e?e:void 0}}],iY=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function iX(e,t,r){void 0===r||t in e||(e[t]=r)}function i0(e){var t;let r={..."object"==typeof(t=e.properties)&&null!==t&&!Array.isArray(t)?e.properties:{}},i={};for(let{property:e,optionKey:t,coerce:s}of iZ)if(e in r){let n=s(r[e]);void 0!==n&&(i[t]=n),delete r[e]}let s={};for(let{property:e,field:t}of iY)if(e in r){let i=r[e];"string"==typeof i&&(s[t]=i),delete r[e]}return delete r.$lib,delete r.$lib_version,iX(r,"$set",e.$set),iX(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:function(e){if("string"==typeof e){let t=new Date(e);if(Number.isNaN(t.getTime()))return new Date().toISOString();let r=t.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?r.replace(/\.\d{3}Z$/,`.${i}Z`):r}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=null==e?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}(e.timestamp),...s,options:i,properties:r}}let i1=new Set([404,408,429,500,502,503,504]);class i2{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??3e4,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??(e=>new Promise(t=>eD(t,e))),this.generateRequestId=t.generateRequestId??eQ,this.compress=t.compress??eH}async sendV1Batch(e){if(0===e.length)return;let t=this.generateRequestId(),r=new Date(this.now()).toISOString(),{batch:i}=function(e,{createdAt:t,historicalMigration:r}){let i={created_at:t,batch:e.map(i0)};return r&&(i.historical_migration=!0),i}(e,{createdAt:r,historicalMigration:this.config.historicalMigration}),s=`${this.config.host}/i/v1/analytics/events`,n=[],a=i,o=Math.max(1,this.config.maxAttempts);for(let e=1;e<=o;e++){let i,l,u=e===o,c=f({created_at:r,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a});try{let{response:r,signal:o}=i=await this.sendOnce(s,c,e,t),{status:h}=r;if(h<200||h>=300)if(!u&&i1.has(h)){let t=this.parseRetryAfter(r);await i.waitFor(i.cancelBody()).catch(()=>{}),l=this.backoffDelay(e,t)}else{let e=await this.buildHttpError(r,h,i.waitFor);return this.surfaceBatchFailure(t,n,a,e)}else{let s;try{s=await i.waitFor(this.parseResponse(r))}catch(e){if(o.aborted)throw e;return this.surfaceBatchFailure(t,n,a,Error(`Capture V1 returned an unparseable ${h} response body`))}let c=this.classify(a,s,n);if(0===c.length)return this.surfacePartialDrops(t,n);if(u)return void this.onError(new iG({requestId:t,drops:n,retryExhausted:c.map(e=>e.uuid)}));a=c;let d=this.parseRetryAfter(r);l=this.backoffDelay(e,d)}}catch(r){if(i&&!i.signal.aborted)throw r;if(u)return this.surfaceBatchFailure(t,n,a,r);l=this.backoffDelay(e)}finally{i?.cleanup()}void 0!==l&&await this.sleep(l)}}async sendOnce(e,t,r,i){let s,n=this.buildHeaders(r,i),a=t;if(this.config.compressionEnabled){let e=await this.compress(t,this.config.isDebug);null!==e&&(a=e,n["Content-Encoding"]="gzip")}let o=new AbortController,l="waiting for response headers",u=new Promise((e,t)=>{s=eD(()=>{let e=Error(`Capture V1 request timed out ${l} after ${this.config.requestTimeoutMs}ms`);e.name="AbortError",t(e),o.abort(e)},this.config.requestTimeoutMs)});try{let t,r=this.fetchFn(e,{method:"POST",headers:n,body:a,signal:o.signal}),i=!1;r.then(e=>{o.signal.aborted&&!i&&this.cancelBody(e)}).catch(()=>{});let c=await Promise.race([r,u]);i=!0,l="while reading the response body";let h=!1,d=()=>t??=this.cancelBody(c);return{response:c,signal:o.signal,waitFor:e=>Promise.race([e,u]),cancelBody:d,cleanup:()=>{!h&&(h=!0,clearTimeout(s),o.signal.aborted&&d())}}}catch(e){throw clearTimeout(s),e}}buildHeaders(e,t){let r=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"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()};return this.config.userAgent&&(i["User-Agent"]=this.config.userAgent),i}classify(e,t,r){let i=t.results??{},s=[];for(let t of e){let e=i[t.uuid];e&&("drop"===e.result?r.push({uuid:t.uuid,details:e.details??void 0}):"retry"===e.result&&s.push(t))}return s}backoffDelay(e,t){let r=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return void 0===t?r: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 e=parseInt(r,10);return Number.isFinite(e)&&e>0?1e3*e:void 0}let i=Date.parse(r);if(Number.isNaN(i))return;let s=i-this.now();return s>0?s:void 0}async parseResponse(e){let t=JSON.parse(await e.text());if("object"!=typeof t||null===t||Array.isArray(t))throw Error("unexpected response shape");let r=t.results;if(void 0!==r&&("object"!=typeof r||null===r||Array.isArray(r)))throw Error("unexpected results shape");return{results:r??{}}}async buildHttpError(e,t,r){let i="";try{i=(await r(e.text())).slice(0,512)}catch{}let s=i?`: ${i}`:"";return Error(`Capture V1 request failed with HTTP ${t}${s}`)}surfaceBatchFailure(e,t,r,i){this.onError(new iG({requestId:e,drops:t,retryExhausted:r.map(e=>e.uuid),cause:i}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new iG({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}}let i5="ai-capture",i3="/i/v0/ai/batch/",i4=new TextEncoder;function i6(e){return i4.encode(f(e)).length}class i8 extends Error{constructor(e){super(e.message,void 0===e.cause?void 0:{cause:e.cause}),this.name=function(e,t){if("missing_secret_key"===t||401===e)return"missing_api_key";if(void 0===e)return"network_error"===t?"service_unavailable":t.startsWith("invalid_")||i9.has(t)?"validation_error":"application_error";if("attachment_upload_failed"===t)return e>=500?"service_unavailable":"application_error";switch(e){case 400:return"validation_error";case 403:return"invalid_permission";case 404:return"not_found";case 409:return"template_outdated"===t?"validation_error":"concurrent_idempotent_requests";case 422:return"idempotency_key_reused"===t?"invalid_idempotent_request":"validation_error";case 429:return"quota_limited"===t?"monthly_quota_exceeded":"rate_limit_exceeded";case 503:return"service_unavailable";default:return"application_error"}}(e.statusCode,e.code),this.code=e.code,this.statusCode=e.statusCode,this.why=e.why,this.fix=e.fix,this.docsUrl=e.docsUrl,this.field=e.field,this.retryAfterMs=e.retryAfterMs}}let i9=new Set(["too_many_attachments","message_too_large"]),i7=/^[A-Za-z0-9+/]*={0,2}$/;async function se(e){return Promise.all(e.map(async(e,t)=>({...e,sha256:await ss(e.bytes),field:`attachments__${t}`})))}function st({sha256:e,filename:t,contentType:r,contentId:i}){return{sha256:e,filename:t,...void 0!==r&&{content_type:r},...void 0!==i&&{content_id:i}}}function sr(e,t){var r,i;let s;if("object"!=typeof e||null===e||Array.isArray(e)||ArrayBuffer.isView(e))throw sn("An attachment is an object with filename and content. Pass the file's bytes as its content.",`attachments__${t}`);let{filename:n,content:a,contentType:o,contentId:l,path:u,...c}=e;if(void 0!==u)throw sn("PostHog can't fetch an attachment from a path or URL. Read the file and pass its content instead.",`attachments__${t}__path`);let h=Object.entries(c).find(([,e])=>void 0!==e)?.[0];if(void 0!==h)throw sn(`An attachment takes filename, content, contentType and contentId, not ${h}.`,`attachments__${t}__${h}`);if("string"!=typeof n||""===n)throw sn("An attachment needs a filename, such as 'invoice.pdf'.",`attachments__${t}__filename`);if("string"!=typeof a&&!(a instanceof Uint8Array))throw sn("An attachment needs content: a Buffer, a Uint8Array or a Base64 string.",`attachments__${t}__content`);if("string"==typeof a&&!((r=a).length%4==0&&i7.test(r)))throw sn("An attachment's content string must be Base64. Pass text as a Buffer or a Uint8Array.",`attachments__${t}__content`);if(void 0!==o&&"string"!=typeof o)throw sn("An attachment's contentType must be a string, such as 'application/pdf'.",`attachments__${t}__contentType`);if(void 0!==l&&"string"!=typeof l)throw sn("An attachment's contentId must be a string.",`attachments__${t}__contentId`);let d="string"==typeof a?(s=(i=a).endsWith("==")?2:+!!i.endsWith("="),i.length/4*3-s):a.byteLength;if(0===d)throw sn("An attachment needs at least one byte.",`attachments__${t}__content`);return{filename:n,content:a,size:d,...void 0!==o&&{contentType:o},...void 0!==l&&{contentId:l}}}function si(e,t,r){if(0===e.length)return;let i=new TextEncoder;if([...e,...t.map(e=>i.encode(e).byteLength)].reduce((e,t)=>e+Math.ceil(4*Math.ceil(t/3)*78/76),65536+75*Math.ceil(i.encode(r).byteLength/42))>4e7)throw new i8({code:"message_too_large",message:"These files make the email larger than 40 MB after Base64 encoding, about 29 MB of files, so no email was sent.",field:"attachments",why:"PostHog's email provider takes emails up to 40 MB, and Base64 encoding makes each file about a third larger.",fix:"Send fewer or smaller files, or link to large files from the email body."})}async function ss(e){return Array.from(new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",e)),e=>e.toString(16).padStart(2,"0")).join("")}function sn(e,t){return new i8({code:"invalid_attachment",message:e,field:t})}let sa="https://us.posthog.com",so="https://eu.posthog.com",sl={"https://us.i.posthog.com":sa,"https://us.posthog.com":sa,"https://app.posthog.com":sa,"https://eu.i.posthog.com":so,"https://eu.posthog.com":so},su=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,sc=/^[\x21-\x7e]{1,255}$/,sh=/^[a-zA-Z0-9_-]{1,400}$/,sd={to:!0,distinctId:!0,idempotencyKey:!0,maxRetries:!0},sf={name:"templateId",fields:sE(sd,{templateId:!0,templateData:!0}),why:"A template made in PostHog sets its own sender, subject and content, and follows the project's engagement setting.",howToSend:"send a template made in PostHog with templateId"},sp={name:"templateKey",fields:sE(sd,{templateKey:!0,subject:!0,from:!0,replyTo:!0,captureEngagement:!0,cc:!0,bcc:!0,attachments:!0,sensitive:!0,tracking:!0,html:!0,text:!0,react:!0}),why:"A send with templateKey takes its content from your code.",howToSend:"send content from your code with templateKey"};class sg{constructor(e,t){this.inFlight=new Set,this.config=e,this.hooks=t}send(e,...t){return this.track(this.sendUntracked(e,t))}get(e){return this.track(this.getUntracked(e))}setPreferences(e){return this.track(this.setPreferencesUntracked(e))}track(e){return this.inFlight.add(e),e.finally(()=>this.inFlight.delete(e)),e}async drain(){for(;this.inFlight.size>0;)await Promise.all(this.inFlight)}async sendUntracked(e,t){try{let s,n;var r,i=t;if(i.some(e=>void 0!==e))throw new i8({code:"invalid_form",message:"send takes one options object, so no email was sent. Put idempotencyKey and every other option in it."});let a=function(e,t){let r=e??{},{to:i,distinctId:s,idempotencyKey:n,maxRetries:a}=r;if("string"!=typeof i||!i.trim())throw sP("invalid_recipient","to must be one email address as a nonempty string.","to");if(void 0!==s&&("string"!=typeof s||!s))throw sP("invalid_distinct_id","distinctId must be a nonempty string.","distinctId");let{content:o,files:l}=function(e,t){if(void 0===e.templateId==(void 0===e.templateKey))throw new i8({code:"invalid_form",message:"Send either templateId, or templateKey with subject and html, text or react."});return void 0===e.templateKey?{content:function(e,t){let{templateId:r,templateData:i}=e;if("string"!=typeof r||!su.test(r))throw sP("invalid_template_id","templateId must be the template's UUID.","templateId");if(void 0!==i&&("object"!=typeof i||null===i||Array.isArray(i)))throw sP("invalid_template_data","templateData must be an object.","templateData");return sF(e,sf,sp),{template_id:r.toLowerCase(),message_data:i??{},...void 0!==t&&{distinct_id:t}}}(e,t),files:[]}:function(e,t){let{templateKey:r,subject:i,html:s,text:n,react:a}=e;if("string"!=typeof r||!sh.test(r))throw sP("invalid_template_key","templateKey can only have letters, digits, hyphens (-) and underscores (_), at most 400.","templateKey");if(sF(e,sp,sf),"string"!=typeof i)throw sP("invalid_form","A send with templateKey needs a subject.","subject");if(void 0!==s&&"string"!=typeof s)throw sP("invalid_form","html must be a string.","html");if(void 0!==n&&"string"!=typeof n)throw sP("invalid_form","text must be a string.","text");if(void 0!==a){var o=a,l=s;if(!sb(o))throw sP("invalid_form","react must be a React element, such as <WelcomeEmail />.","react");if(void 0!==l)throw new i8({code:"invalid_form",message:"A send with react renders its own html, so it takes no html. No email was sent.",field:"html",fix:"Remove html to send the rendered react element, or remove react to send your html."})}else if(void 0===s&&void 0===n)throw sP("invalid_form","A send with templateKey needs html, text or react.","html");let u=void 0===e.attachments?[]:function(e,{html:t,text:r,subject:i}){if(!Array.isArray(e))throw sn("attachments must be a list of files.","attachments");if(e.length>10)throw new i8({code:"too_many_attachments",message:"An email carries at most 10 files, so no email was sent.",field:"attachments",fix:"Attach at most 10 files, and link to any others from the email body."});let s=Array.from(e,sr);return si(s.map(({size:e})=>e),[t??"",r||t||""],i),s.map(({content:e,size:t,...r})=>({...r,bytes:"string"==typeof e?function(e){if("u">typeof Buffer)return Buffer.from(e,"base64");let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}(e):new Uint8Array(e)}))}(e.attachments,{html:s,text:n,subject:i});return{content:{template_key:r,subject:i,...void 0!==s&&{html:s},...void 0!==n&&{text:n},...function(e){let{from:t,replyTo:r,cc:i,bcc:s,captureEngagement:n,sensitive:a,tracking:o}=e;return{...void 0!==t&&{from:t},...void 0!==r&&s_("reply_to",sy(r)),...void 0!==i&&s_("cc",sy(i)),...void 0!==s&&s_("bcc",sy(s)),...void 0!==n&&{capture_engagement:n},...void 0!==a&&{sensitive:a},...void 0!==o&&{tracking:o}}}(e),...void 0!==t&&{distinct_id:t}},files:u}}(e,t)}(r,s);if(void 0!==n&&("string"!=typeof n||!sc.test(n)))throw sP("invalid_idempotency_key","idempotencyKey must be 1 to 255 visible ASCII characters without spaces.","idempotencyKey");if(void 0!==a&&!sm(a))throw sP("invalid_max_retries","maxRetries must be a nonnegative integer.","maxRetries");return{content:JSON.parse(f({...o,to:i})),files:l,react:sb(r.react)?r.react:void 0,idempotencyKey:n??globalThis.crypto.randomUUID(),maxRetries:sm(a)?a:t}}(e,this.config.maxRetries),{appHost:o,secretKey:l}=this.connect("no email was sent","Sending email needs secretKey, a project secret API key with the transactional_email:write scope."),u=void 0===a.react?a.content:await sw(a.content,a.react,this.config.requestTimeoutMs);void 0!==a.react&&(r=a.files,s="string"==typeof u.html?u.html:"",n="string"==typeof u.text?u.text:"",si(r.map(({bytes:e})=>e.byteLength),[s,n||s],"string"==typeof u.subject?u.subject:""));let c=await this.uploadAttachments(a,o,l),h=f({...u,...s_("attachments",c)}),d=this.headers(l,{"Content-Type":"application/json","Idempotency-Key":a.idempotencyKey}),p=await this.withRetries(a.maxRetries,async()=>(function({status:e,text:t,retryAfterMs:r}){let i=sk(sA(t));if(e>=200&&e<300){let t=sC(i.message_id);if(!t)throw new i8({code:"api_error",message:"PostHog answered without a message ID.",statusCode:e});let r=[];if(Array.isArray(i.warnings))for(let e of i.warnings)null!==e&&"object"==typeof e&&r.push({code:sC(e.code)??"warning",message:sC(e.detail)??sC(e.message)??"",fix:sC(e.fix)});return{id:t,replayed:!0===i.replayed,warnings:r}}throw s$(i,e,r)})(await this.request(o+"/api/projects/@current/messaging/send/email/","POST",d,h)));for(let e of p.warnings)this.hooks.logger.warn(`PostHog email warning ${e.code}: ${e.message}`);return{data:p,error:null}}catch(e){return{data:null,error:sT(e,"Sending the email failed unexpectedly.")}}}async getUntracked(e){try{if("string"!=typeof e||!su.test(e))throw sP("invalid_message_id","id must be the message ID that send() returned.","id");let{appHost:t,secretKey:r}=this.connect("no email status was read","Reading an email status needs secretKey, a project secret API key with the transactional_email:read or transactional_email:write scope."),i=t+"/api/projects/@current/messaging/emails/{messageId}/".replace("{messageId}",e.toLowerCase()),s=this.headers(r,{});return{data:await this.withRetries(this.config.maxRetries,async()=>(function({status:e,text:t,retryAfterMs:r}){let i=sk(sA(t));if(e<200||e>=300)throw s$(i,e,r);let s=sC(i.id),n=sC(i.status),a=sC(i.created_at),o=sC(i.status_at);if(!s||!n||!a||!o)throw new i8({code:"api_error",message:"PostHog answered without an email status.",statusCode:e});return{id:s,status:n,createdAt:a,statusAt:o,reason:sC(i.reason)??null}})(await this.request(i,"GET",s))),error:null}}catch(e){return{data:null,error:sT(e,"Reading the email status failed unexpectedly.")}}}async uploadAttachments({files:e,maxRetries:t},r,i){if(0===e.length)return[];let s=await se(e),n=new Map;for(let e of s)n.has(e.sha256)||n.set(e.sha256,e);let a=[...n.values()],o=f({files:a.map(({sha256:e,bytes:t})=>({sha256:e,size:t.byteLength}))}),l=this.headers(i,{"Content-Type":"application/json"}),u=await this.withRetries(t,async()=>(function({status:e,text:t,retryAfterMs:r},i){var s,n,a;let o=sk(sA(t));if(404===e)throw s$({code:"not_found",...o,attr:sC(o.attr)??"attachments"},e,r);if(e<200||e>=300){let t;throw s$({...o,attr:(s=sC(o.attr),n=i,(t=void 0===s?null:/^files(?:__(\d+))?(?:__|$)/.exec(s))?void 0===t[1]?"attachments":n[Number(t[1])]?.field??"attachments":s)},e,r)}let l=Array.isArray(o.files)?o.files.map(sk):[],u=[];for(let{sha256:t,bytes:r,field:s}of i){let i=l.find(e=>e.sha256===t);if(i?.status==="present")continue;let n=sC(i?.url);if(i?.status!=="upload"||!n||!(null!==(a=i.headers)&&"object"==typeof a&&!Array.isArray(a)&&Object.values(a).every(e=>"string"==typeof e)))throw new i8({code:"api_error",message:"PostHog answered without telling where to upload every file.",statusCode:e});u.push({url:n,headers:i.headers,bytes:r,field:s})}return u})(await this.request(r+"/api/projects/@current/messaging/attachments/uploads/","POST",l,o),a)),c=r.toLowerCase().startsWith("http://")?void 0:u.find(({url:e})=>!e.toLowerCase().startsWith("https://"));if(c)throw new i8({code:"api_error",message:`PostHog named an upload URL for ${c.field} that isn't https, so the file would travel unencrypted. No email was sent.`,field:c.field,fix:"Make your PostHog's file storage URL use https. For local development over plain HTTP, set appHost to your http app host."});for(let e of u)await this.withRetries(t,()=>this.uploadFile(e));return s.map(st)}async uploadFile({url:e,headers:t,bytes:r,field:i}){let s;try{s=await this.request(e,"PUT",t,r,"manual")}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw new i8({code:"network_error",message:`The upload of ${i} timed out after ${this.config.requestTimeoutMs}ms, so no email was sent.`,fix:"Raise emailRequestTimeoutMs on the client, or send smaller files.",field:i,cause:e});throw new i8({code:"network_error",message:`The upload of ${i} didn't reach PostHog's file storage, so no email was sent.`,field:i,cause:e})}if(s.status>=300&&s.status<400)throw new i8({code:"attachment_upload_failed",message:`PostHog's file storage redirected the upload of ${i} elsewhere. The SDK uploads only to the URL PostHog signed, so no email was sent.`,statusCode:s.status,fix:"Make your PostHog's file storage URL point straight at the storage, over https.",field:i});if(s.status<200||s.status>=300)throw new i8({code:"attachment_upload_failed",message:`PostHog's file storage refused the upload of ${i}, so no email was sent. ${function({status:e,text:t}){let r=/<Code>([^<]{1,100})<\/Code>/.exec(t)?.[1],i=/<Message>([^<]{1,300})<\/Message>/.exec(t)?.[1],s=`It answered HTTP ${e}${r?` ${r}`:""}${i?`: ${i}`:""}`;return s.endsWith(".")?s:`${s}.`}(s)}`,statusCode:s.status,fix:"Send the email again. Each send asks for new upload URLs.",field:i,retryAfterMs:s.retryAfterMs})}async setPreferencesUntracked(e){try{let t=function(e){let{to:t,allMarketing:r,topics:i}=e??{};if("string"!=typeof t||!t.trim())throw sP("invalid_recipient","to must be one email address as a nonempty string.","to");if(void 0!==r&&"boolean"!=typeof r)throw sP("invalid_preferences","allMarketing must be true or false.","allMarketing");if(void 0!==i&&("object"!=typeof i||null===i||Array.isArray(i)||!Object.values(i).every(e=>"boolean"==typeof e)))throw sP("invalid_preferences","topics must map each topic key to true or false.","topics");let s=void 0!==i&&Object.keys(i).length>0;if(void 0===r&&!s)throw sP("invalid_preferences","Set allMarketing, topics, or both.","topics");return f({identifier:t,...void 0===r?{}:{all_marketing:r},...s?{topics:i}:{}})}(e),{appHost:r,secretKey:i}=this.connect("no preferences changed","Setting email preferences needs secretKey, a project secret API key with the messaging_preference:write scope."),s=this.headers(i,{"Content-Type":"application/json"});return{data:await this.withRetries(this.config.maxRetries,async()=>(function({status:e,text:t,retryAfterMs:r}){let i=sk(sA(t));if(e<200||e>=300)throw s$(i,e,r);let s=sC(i.identifier),n=i.all_marketing,a=i.topics;if(!s||null!==n&&"boolean"!=typeof n||null===a||"object"!=typeof a||Array.isArray(a)||!Object.values(a).every(e=>"boolean"==typeof e))throw new i8({code:"api_error",message:"PostHog answered without the preferences.",statusCode:e});return{to:s,allMarketing:n,topics:a}})(await this.request(r+"/api/projects/@current/messaging/preferences/","POST",s,t))),error:null}}catch(e){return{data:null,error:sT(e,"Setting the email preferences failed unexpectedly.")}}}connect(e,t){var r,i;let s;if(this.hooks.isDisabled())throw new i8({code:"client_disabled",message:`The PostHog client is disabled, so ${e}.`});if(this.hooks.isClosed())throw new i8({code:"client_closed",message:`The PostHog client is shut down, so ${e}.`});let n=(r=this.config.host,(s="string"==typeof(i=this.config.appHost)?eR(i.trim()):"")?sl[s]??s:sl[eR(r)]);if(!n)throw new i8({code:"missing_app_host",message:"The client's host is not PostHog Cloud, so the client can't tell where to send email. Set appHost to your PostHog app host on the client."});let a=this.config.secretKey?.trim();if(!a)throw new i8({code:"missing_secret_key",message:t});return{appHost:n,secretKey:a}}headers(e,t){let r={Authorization:`Bearer ${e}`,Accept:"application/json",...t};return this.hooks.userAgent&&(r["User-Agent"]=this.hooks.userAgent),this.config.migratedFrom&&(r["X-PostHog-Migrated-From"]=this.config.migratedFrom),r}async withRetries(e,t){for(let r=0;;r++){let i;try{return await t()}catch(e){i=e instanceof i8?e:new i8({code:"network_error",message:"The request to PostHog failed.",cause:e})}let s=function(e,t,r){if(!(t>=r)&&(void 0===e.statusCode?"network_error"===e.code:"attachment_upload_failed"===e.code?429===e.statusCode||e.statusCode>=500:409===e.statusCode?"idempotency_key_in_flight"===e.code:429===e.statusCode?"quota_limited"!==e.code&&"upload_quota_exceeded"!==e.code:503===e.statusCode)&&(void 0===e.retryAfterMs||!(e.retryAfterMs>3e4)))return Math.max(Math.min(3e4,1e3*2**t*(.8+.4*Math.random())),e.retryAfterMs??0)}(i,r,e);if(void 0===s)throw i;await new Promise(e=>setTimeout(e,s))}}async request(e,t,r,i,s){let n,a,o=new AbortController,l=this.config.requestTimeoutMs,u=new Promise((e,t)=>{n=setTimeout(()=>{let e=Error(`Email request timed out after ${l}ms`);e.name="AbortError",t(e),o.abort(e)},l)}),c=Promise.resolve().then(()=>this.hooks.fetch(e,{method:t,headers:r,...void 0===i?{}:{body:i},...s?{redirect:s}:{},signal:o.signal}));c.then(e=>{o.signal.aborted&&Promise.resolve(e.body?.cancel()).catch(()=>{})}).catch(()=>{});try{let e;a=await Promise.race([c,u]);try{e=await Promise.race([a.text(),u])}catch(e){if(a.status>=200&&a.status<300)throw e;return{status:a.status,text:"",retryAfterMs:sI(a)}}return{status:a.status,text:e,retryAfterMs:sI(a)}}finally{clearTimeout(n),o.signal.aborted&&a&&Promise.resolve(a.body?.cancel()).catch(()=>{})}}}function sm(e){return"number"==typeof e&&Number.isInteger(e)&&e>=0}function s_(e,t){return Array.isArray(t)&&0===t.length?{}:{[e]:t}}function sy(e){return"string"==typeof e?[e]:e}let sv=[Symbol.for("react.element"),Symbol.for("react.transitional.element")];function sb(e){return"object"==typeof e&&null!==e&&"$$typeof"in e&&sv.includes(e.$$typeof)&&"type"in e&&"props"in e}async function sw(e,t,r){let{render:i,toPlainText:s}=await sS();try{let n=await sx(i(t),r,"Rendering the react element");return{...e,html:n,...void 0===e.text&&{text:s(n)}}}catch(e){throw new i8({code:"react_render_failed",message:"Rendering the react element failed, so no email was sent.",cause:e})}}async function sx(e,t,r){let i,s=new Promise((e,s)=>{i=setTimeout(()=>s(Error(`${r} took longer than ${t}ms.`)),t)});try{return await Promise.race([e,s])}finally{clearTimeout(i)}}async function sS(){try{return await Promise.resolve().then(()=>{let e=Error("Cannot find module '@react-email/render'");throw e.code="MODULE_NOT_FOUND",e})}catch(e){throw new i8({code:"missing_react_renderer",message:"react needs the @react-email/render package, which isn't installed or failed to load, so no email was sent.",fix:"Install @react-email/render with react and react-dom next to posthog-node, or render the email yourself and send html.",cause:e})}}function sF(e,t,r){let i=Object.entries(e).find(([e,r])=>void 0!==r&&!t.fields.has(e))?.[0];if(void 0===i)return;let s=`A send with ${t.name} doesn't take ${i}, so no email was sent.`;if(!r.fields.has(i))throw new i8({code:"invalid_form",message:s,field:i,fix:`Remove ${i} and send again.`});throw new i8({code:"invalid_form",message:s,field:i,why:t.why,fix:`Remove ${i}, or ${r.howToSend}.`})}function sE(...e){return new Set(e.flatMap(e=>Object.keys(e)))}function sP(e,t,r){return new i8({code:e,message:t,field:r})}function sA(e){try{return JSON.parse(e)}catch{return null}}function sI(e){try{return eY(e.headers?.get("retry-after"),Date.now(),Number.MAX_SAFE_INTEGER)}catch{return}}function sC(e){return"string"==typeof e&&e?e:void 0}function sk(e){return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}function s$(e,t,r){return new i8({code:sC(e.code)??"api_error",message:sC(e.detail)??`PostHog answered HTTP ${t}.`,statusCode:t,why:sC(e.why),fix:sC(e.fix),docsUrl:sC(e.docs_url),field:sC(e.attr),retryAfterMs:r})}function sT(e,t){return e instanceof i8?e:new i8({code:"unexpected_error",message:t,cause:e})}let sO=new Set;function sR(e,t){sO.has(e)||(sO.add(e),console.warn(`[PostHog] ${t}`))}class sM extends te{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(e){this._distinctIdHasSentFlagCalls=new Map(Object.entries(e??{}))}constructor(e,t={}){var r,i;let s,n="string"==typeof e?e.trim():"",a={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:("string"==typeof(r=t.host)?r.trim():"")||"https://us.i.posthog.com",personalApiKey:("string"==typeof(i=t.secretKey??t.personalApiKey)?i.trim():"")||void 0};if(super(n,a),this._memoryStorage=new iU,this._isShutdown=!1,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this._loggedFlagsResponseWithoutTypedValues=!1,this._experimentExposuresReported=new Map,this.options=a,this.captureMode="v0"===(s="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0)||"v1"===s?s:"v0",this.enableFullAiCapture=!0===a.enableFullAiCapture,this.privacyMode=!0===a.privacyMode,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof a.featureFlagsPollingInterval?Math.max(a.featureFlagsPollingInterval,100):null===a.featureFlagsPollingInterval?null:3e4,"number"==typeof a.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(a.waitUntilDebounceMs,0)),"number"==typeof a.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(a.waitUntilMaxWaitMs,0)),!this.disabled&&(a.personalApiKey||a.flagDefinitionCacheProvider)){if(a.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.');!1!==a.enableLocalEvaluation&&(this.featureFlagsPoller=new r4({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:a.personalApiKey,projectApiKey:n,timeout:a.requestTimeout??1e4,host:this.host,fetch:a.fetch,onError:e=>{this._events.emit("error",e)},onLoad:e=>{this._events.emit("localEvaluationFlagsLoaded",e)},onMinimalFlagCalledEvents:e=>{this._minimalFlagCalledEvents=e},customHeaders:this.getCustomHeaders(),cacheProvider:a.flagDefinitionCacheProvider,strictLocalEvaluation:a.strictLocalEvaluation,evaluationContexts:a.evaluationContexts??a.evaluationEnvironments}))}this.errorTracking=new ij(this,a,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=a.maxCacheSize||5e4}enqueue(e,t,r,i){super.enqueue(e,t,r,i),this.scheduleDebouncedFlush()}_flushEventsAndSpans(e=!1){let t=this.flushWithPendingPromises(),r=[];return(this._traces&&!(e&&this._traces.throttled)&&r.push(this._traces.flush().catch(()=>{})),this._logs&&!(e&&this._logs.throttled)&&r.push(this._logs.flushInBackground()),0===r.length)?t:eN([t,...r]).then(([e])=>{if("rejected"===e.status)throw e.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this.errorTracking.capturePendingExceptions(),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}_flushMetricsWithinInvocation(){let e=this.options.waitUntil;if(e&&this._metrics)try{e(this._metrics.flushCoalesced().catch(()=>{}))}catch{}}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let t,r=new Promise(e=>{t=e});try{e(r)}catch{return}this._waitUntilCycle={resolve:t,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,r=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),t>=r)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=eD(()=>{this.resolveWaitUntilFlush()},i)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),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){var t;return"v1"===this.captureMode&&"string"==typeof(t=e).event&&t.event.startsWith("$ai_")?"ai":iQ}persistedQueueKeyForRoute(e){return e===i5?c.AiCaptureQueue:"ai"===e?c.AiQueue:c.Queue}getActiveQueueRoutes(){let e="v1"===this.captureMode?[iQ,"ai"]:[iQ];return this._aiCaptureRouteActive&&e.push(i5),e}getBatchEndpointPath(e){return e===i5?i3:super.getBatchEndpointPath(e)}async sendBatch(e,t,r=iQ){if(r===i5)return this.sendAiCaptureBatch(e,t);if("v1"!==this.captureMode||"ai"===r)return super.sendBatch(e,t,r);let i=e.filter(e=>void 0!==e);await this.getV1Sender().sendV1Batch(i)}async sendAiCaptureBatch(e,t){let{batches:r,dropped:i}=function(e,t=8388608,r=5242880){let i=[],s=[],n=[],a=0;for(let o of e){if(void 0===o)continue;let e=i6(o);if(e>t){s.push({event:"string"==typeof o.event?o.event:"unknown",bytes:e});continue}n.length>0&&a+e>r&&(i.push(n),n=[],a=0),n.push(o),a+=e}return n.length>0&&i.push(n),{batches:i,dropped:s}}(e);for(let{event:e,bytes:t}of i){let r=`Event ${e} (${t} bytes) exceeds the 8MiB limit for ${i3}, dropping.`;this._logger.error(r),this._events.emit("error",Error(r))}for(let e of r)await this.sendAiSubBatch(e,t)}async sendAiSubBatch(e,t){try{await super.sendBatch(e,t,i5)}catch(i){if(!e6(i))throw i;if(1===e.length){let[t]=e,r="string"==typeof t.event?t.event:"unknown",i=`Event ${r} (${i6(t)} bytes) was rejected with 413 by ${i3} on its own, dropping.`;this._logger.error(i),this._events.emit("error",Error(i));return}let r=Math.ceil(e.length/2);await this.sendAiSubBatch(e.slice(0,r),t),await this.sendAiSubBatch(e.slice(r),t)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new i2({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??3e3,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:e=>this._events.emit("error",e),compress:e=>this.compressPayload(e)})),this._v1Sender}getLibraryVersion(){return"5.73.0"}get metrics(){return this._metrics||(this._metrics=new tR(this,ri(this.options.metrics),this._logger)),this._metrics}get _logsPipeline(){if(!this._logs){let e=function(e,t={}){let{rateCap:r,...i}=e??{},s=e?.rateCap?.windowMs??1e4,n=e?.rateCap&&"maxLogs"in e.rateCap?e.rateCap.maxLogs:1e4,a=void 0!==n&&n>0&&s>0?n:void 0,o=e?.maxBatchRecordsPerPost;return{...i,serviceName:e?.serviceName??t.serviceName,maxBufferSize:e?.maxBufferSize??100,flushIntervalMs:e?.flushIntervalMs??3e3,maxBatchRecordsPerPost:Number.isInteger(o)&&o>0?o:100,rateCapWindowMs:s,maxLogsPerInterval:a,maxQueueSize:a??1e4,backgroundFlushBudgetMs:25e3,terminationFlushBudgetMs:2e3,resourceAttributes:{...t.hostResourceAttributes,...e?.resourceAttributes}}}(this.options.logs,{serviceName:this._resolveServiceName()??void 0,hostResourceAttributes:this.hostResourceAttributes()});this._logs=new ty(this,e,this._logger,()=>this._logContext(),e=>e(),void 0,void 0,()=>this.disabled||this.optedOut)}return this._logs}_logContext(){let e=this.context?.get();return{distinctId:e?.distinctId,sessionId:e?.sessionId}}captureLog(e){let t=e;if(!e.trace_id&&!e.span_id){let r=this.getActiveSpan(),i=r?.traceId,s=r?.spanId;if(i&&s){let n=parseInt(r?.traceparent()?.split("-")[3]??"",16);t={...e,trace_id:i,span_id:s,...void 0===e.trace_flags&&!Number.isNaN(n)&&{trace_flags:n}}}}this._logsPipeline.captureLog(t),this.scheduleDebouncedFlush()}get logger(){if(!this._captureLogger){let e=e=>(t,r)=>this.captureLog({body:t,level:e,attributes:r});this._captureLogger={trace:e("trace"),debug:e("debug"),info:e("info"),warn:e("warn"),error:e("error"),fatal:e("fatal")}}return this._captureLogger}get emails(){var e,t;return this._emails||(this._emails=new sg({secretKey:this.options.personalApiKey,host:this.host,appHost:this.options.appHost,requestTimeoutMs:"number"==typeof(e=this.options.emailRequestTimeoutMs)&&Number.isFinite(e)&&e>0?e:15e3,maxRetries:"number"==typeof(t=this.options.emailRequestMaxRetries)&&Number.isFinite(t)&&t>=0?Math.floor(t):2,migratedFrom:this.options.migratedFrom},{fetch:(e,t)=>this.fetch(e,t),isDisabled:()=>this.disabled,isClosed:()=>this._isShutdown,logger:this._logger,userAgent:this.getCustomUserAgent()||void 0})),this._emails}initializeSpanContextManager(){return new t7}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces)return this._traces||(this._traces=new t9(this,ra(this.options.traces,this.hostResourceAttributes(),this._logger),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}_tracingContext(){let e=this.context?.get();return{distinctId:e?.distinctId,sessionId:e?.sessionId}}startSpan(e,t){return this._tracesPipeline?.startSpan(e,t)??tz(t,this._spanContextManager.active())}withSpan(e,t,r){let i="function"==typeof t?void 0:t,s="function"==typeof t?t:r,n=this._tracesPipeline;return n?i?n.withSpan(e,i,s):n.withSpan(e,s):tY(this._spanContextManager,tz(i,this._spanContextManager.active()),s)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getFlagsResponseFormat(){let e=super.getFlagsResponseFormat();return{version:4,read:t=>{let{body:r,withoutTypedValues:i}=function(e){if(!I(e))return{body:e,withoutTypedValues:!1};let t=e.flags;if(!I(t)){let t=e.featureFlags;return{body:e,withoutTypedValues:I(t)&&Object.keys(t).length>0}}let r=!1,i=Object.fromEntries(Object.entries(t).map(([e,t])=>{I(t)&&!m.call(t,"value")&&(r=!0);let{detail:i,record:s}=function(e,t){try{if(I(t)&&!m.call(t,"value")){var r;let e,i,s,n,a;return r=t,rf(r),e=rm(r.enabled,"enabled",E),i=rm(r.variant,"variant",b),s=!0===rm(r.failed,"failed",E),n=rp(r.reason),a=rg(rm(r.metadata,"metadata",I)),{detail:r,record:{value:i??e??null,failed:s,reason:n,metadata:{...a,configVersion:1}}}}return function(e,t){var r;if(!I(t))throw new rc("record");rf(t);let i=function(e){if(x(e)||E(e)||b(e)||I(e)||F(e)&&Number.isFinite(e))return e;throw new rc("value")}(t.value),s=!0===rm(t.failed,"failed",E),n=rp(t.reason),a=rm(t.metadata,"metadata",I),o={...rg(a),configVersion:r_(a?.config_version,"metadata.config_version"),ruleType:rm(a?.rule_type,"metadata.rule_type",b),ruleId:rm(a?.rule_id,"metadata.rule_id",b),variantKey:rm(a?.variant_key,"metadata.variant_key",b),forcedVariant:rm(a?.forced_variant,"metadata.forced_variant",E)};r_(a?.experiment_id,"metadata.experiment_id");let l=s?null:i,{enabled:u,variant:c,payload:h}=x(r=l)||E(r)?{enabled:!0===r,variant:void 0,payload:void 0}:b(r)?{enabled:!0,variant:r,payload:void 0}:{enabled:!0,variant:void 0,payload:JSON.stringify(r)},d={key:e,enabled:u,variant:c,reason:n&&{code:n.code,condition_index:n.conditionIndex,description:n.description},metadata:a||void 0!==h?{id:o.id,version:o.version,description:o.description,payload:s?null:h??a?.payload,has_experiment:o.hasExperiment}:void 0};return s&&(d.failed=!0),{detail:d,record:{value:l,failed:s,reason:n,metadata:o}}}(e,t)}catch(t){if(t instanceof rc)return rd(e,t.field);if(t instanceof RangeError)return rd(e,"value");throw t}}(e,t);return ru.set(i,s),[e,i]}));return{body:{...e,flags:i},withoutTypedValues:r}}(t);return i&&!this._loggedFlagsResponseWithoutTypedValues&&(this._loggedFlagsResponseWithoutTypedValues=!0,this._logger.info("[FEATURE FLAGS] The /flags response has no typed flag values, so the server may not support /flags?v=4. Its flags are read as config version 1.")),e.read(r)}}}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,r){"string"==typeof e&&this._logger.warn(t),"$exception"!==e.event||e._originatedFromCaptureException||this._logger.warn(r)}_sendPreparedEvent(e,t,r,i,s){return this.addPendingPromise(this._prepareEventMessage(t,i).then(({distinctId:t,event:n,properties:a,options:o})=>{(this.disabled||this.optedOut)&&i?.onCaptureFailed?.();let l={timestamp:o.timestamp,disableGeoip:o.disableGeoip,uuid:o.uuid},u={distinctId:t,event:n,properties:{...a,...this.getCommonEventProperties()}};return r?this.sendImmediate(e,u,l,s):this.enqueue(e,u,l,s)}).catch(e=>{e&&(console.error(e),i?.onCaptureFailed?.())}))}_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=eT(e.uuid,eQ);return this._sendPreparedAiEvent({...e,uuid:t},!1),t}async captureAiImmediate(e){if(this.disabled)return;let t=eT(e.uuid,eQ);return await this._sendPreparedAiEvent({...e,uuid:t},!0),t}_sendPreparedAiEvent(e,t){return"string"!=typeof e?.event||e.event.startsWith("$ai_")||this._logger.debug(`captureAi called with non-AI event ${e.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",e,t,void 0,i5)}identify({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:n,...a}=t;this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:i||a,$set_once:s||{},$anon_distinct_id:n??void 0},disableGeoip:r},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:n,...a}=t;await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:i||a,$set_once:s||{},$anon_distinct_id:n??void 0},disableGeoip:r},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:r={}}){if(0===Object.keys(t).length&&0===Object.keys(r).length)return;let i={};Object.keys(t).length>0&&(i.$set=t),Object.keys(r).length>0&&(i.$set_once=r),this.capture({distinctId:e,event:"$set",properties:i})}unsetPersonProperties({distinctId:e,properties:t}){let r=(Array.isArray(t)?t:[t]).filter(e=>"string"==typeof e&&e.trim().length>0);0!==r.length&&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=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(t=>{let r=setTimeout(()=>{i(),t(!1)},e),i=this._events.on("localEvaluationFlagsLoaded",e=>{clearTimeout(r),i(),t(e>0)})})}_resolveDistinctId(e,t){return"string"==typeof e?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async getFeatureFlagDetailsStateless(e,t={},r={},i={},s,n){let a=await super.getFeatureFlagDetailsStateless(e,t,r,i,s,n);if(void 0!==a&&!I(a.flags)){let e="/flags response has a non-object `flags` field, treating it as a failed request";this._logger.warn(`[FEATURE FLAGS] ${e}`),this._events.emit("error",Error(e));return}return a}async _getFeatureFlagResult(e,t,r={},i){let s,n,a,o,l,u,c,h,d;if(this.disabled)return void this._logger.warn("The client is disabled");let f=r.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&e in this._flagOverrides){let t=this._flagOverrides[e];if(void 0===t)return;let r=this._payloadOverrides?.[e];return{key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:r}}let{groups:p,disableGeoip:g}=r,{onlyEvaluateLocally:m,personProperties:_,groupProperties:y}=r,v=this.addLocalPersonAndGroupProperties(t,p,_,y);_=v.allPersonProperties,y=v.allGroupProperties;let b=this.createFeatureFlagEvaluationContext(t,p,this.personPropertiesForLocalEvaluation(t,_),y);void 0==m&&(m=this.options.strictLocalEvaluation??!1);let w=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let t=this.featureFlagsPoller?.featureFlagsByKey[e];if(t)try{let r=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(t,b,{matchValue:i});if(r){w=!0;let i=r.value;l=t.id,c="Evaluated locally",h=t.has_experiment,s={key:e,enabled:!1!==i,variant:"string"==typeof i?i:void 0,payload:r.payload??void 0,reason:c,reasonCode:!1===t.active?"flag_disabled":void 0}}}catch(t){if(t instanceof r1||t instanceof rA)this._logger?.info(`${t.name} when computing flag locally: ${e}: ${t.message}`);else throw t}}if(!w&&!m){let t=await this.getFeatureFlagDetailsStateless(b.distinctId,b.groups,_,y,g,[e]);if(void 0===t)o=ro.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===t.minimalFlagCalledEvents,n=t.requestId,a=t.evaluatedAt;let r=[];t.errorsWhileComputingFlags&&r.push(ro.ERRORS_WHILE_COMPUTING),t.quotaLimited?.includes("feature_flags")&&r.push(ro.QUOTA_LIMITED);let i=t.flags[e];if(void 0===i)r.push(ro.FLAG_MISSING);else{let t;if(l=i.metadata?.id,u=i.metadata?.version,c=i.reason?.description??i.reason?.code,h=i.metadata?.has_experiment,i.metadata?.payload!==void 0)try{t=JSON.parse(i.metadata.payload)}catch{t=i.metadata.payload}s={key:e,enabled:i.enabled,variant:i.variant??void 0,payload:t,reason:c,reasonCode:i.reason?.code},d=rh(i)}void 0!==i&&ru.get(i)?.unreadableField!==void 0?(o=ro.UNKNOWN_ERROR,n=void 0,a=void 0):r.length>0&&(o=r.join(","))}}if(f){let r=void 0===s?void 0:!1!==s.enabled&&(s.variant??!0),i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:l,$feature_flag_version:u,$feature_flag_reason:c,locally_evaluated:w,[`$feature/${e}`]:r,$feature_flag_request_id:n,$feature_flag_evaluated_at:w?Date.now():a};if(void 0!==h&&(i.$feature_flag_has_experiment=h),w&&this.featureFlagsPoller){let e=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==e&&(i.$feature_flag_definitions_loaded_at=e)}o&&(i.$feature_flag_error=o),this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:r,groups:p,disableGeoip:g,properties:i,record:d})}return void 0!==s&&void 0!==this._payloadOverrides&&e in this._payloadOverrides&&(s={...s,payload:this._payloadOverrides[e]}),s}async getFeatureFlag(e,t,r){sR("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 i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(r?.sendFeatureFlagEvents)});if(void 0!==i)return!1!==i.enabled&&(i.variant??!0)}async getFeatureFlagPayload(e,t,r,i){if(sR("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."),void 0!==this._payloadOverrides&&e in this._payloadOverrides)return this._payloadOverrides[e];let s=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:!1},r);if(void 0!==s)return s.payload??null}async getFeatureFlagResult(e,t,r){let{distinctId:i,options:s}=this._resolveDistinctId(t,r);return i?this._getFeatureFlagResult(e,i,{...s,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(s?.sendFeatureFlagEvents)}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}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("string"==typeof r)try{return JSON.parse(r)}catch(e){}return r}async isFeatureEnabled(e,t,r){sR("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 i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(r?.sendFeatureFlagEvents)});return void 0===i?void 0:!1!==i.enabled&&!!(i.variant??!0)}async getAllFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);return r?(await this.getAllFlagsAndPayloads(r,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:r,options:i}=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:s,disableGeoip:n,flagKeys:a}=i||{},{onlyEvaluateLocally:o,personProperties:l,groupProperties:u}=i||{},c=this.addLocalPersonAndGroupProperties(r,s,l,u);l=c.allPersonProperties,u=c.allGroupProperties;let h=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,l),u);void 0==o&&(o=this.options.strictLocalEvaluation??!1);let d=await this.featureFlagsPoller?.getAllFlagsAndPayloads(h,a),f={},p={},g=!0;if(d&&(f=d.response,p=d.payloads,g=d.fallbackToFlags),g&&!o){let e=await super.getFeatureFlagsAndPayloadsStateless(h.distinctId,h.groups,l,u,n,a);f={...f,...e.flags||{}},p={...p,...e.payloads||{}}}return void 0!==this._flagOverrides&&(f={...f,...this._flagOverrides}),void 0!==this._payloadOverrides&&(p={...p,...this._payloadOverrides}),{featureFlags:f,featureFlagPayloads:p}}async evaluateFlags(e,t){let r,i,{distinctId:s,options:n}=this._resolveDistinctId(e,t);if(!s)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new rl({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new rl({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,flags:{}});let{groups:a,disableGeoip:o}=n||{},l=n?.flagKeys??void 0;if(l?.length===0)return new rl({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:a,disableGeoip:o,flags:{}});let{onlyEvaluateLocally:u,personProperties:c,groupProperties:h}=n||{},d=this.addLocalPersonAndGroupProperties(s,a,c,h);c=d.allPersonProperties,h=d.allGroupProperties;let f=this.createFeatureFlagEvaluationContext(s,a,this.personPropertiesForLocalEvaluation(s,c),h);void 0==u&&(u=this.options.strictLocalEvaluation??!1);let p=l?new Set(l):void 0,g={},m=!1,_=!1,y=await this.featureFlagsPoller?.getAllFlagsAndPayloads(f,l),v=new Set;if(y)for(let[e,t]of Object.entries(y.response)){let r=this.featureFlagsPoller?.featureFlagsByKey[e];g[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:y.payloads[e],id:r?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:r?.has_experiment},v.add(e)}let b=void 0!==p&&Array.from(p).some(e=>this.featureFlagsPoller?.featureFlagsByKey[e]===void 0);if((!y||y.fallbackToFlags||b)&&!u){let e=await this.getFeatureFlagDetailsStateless(f.distinctId,f.groups,c,h,o,l);if(e)for(let[t,s]of(this._minimalFlagCalledEvents=!0===e.minimalFlagCalledEvents,r=e.requestId,i=e.evaluatedAt,m=!!e.errorsWhileComputingFlags,_=Array.isArray(e.quotaLimited)&&e.quotaLimited.includes("feature_flags"),Object.entries(e.flags))){let e;if(!v.has(t)){if(s.metadata?.payload!==void 0)try{e=JSON.parse(s.metadata.payload)}catch{e=s.metadata.payload}g[t]={key:t,enabled:s.enabled,variant:s.variant,payload:e,id:s.metadata?.id,version:s.metadata?.version,reason:s.reason?.description??s.reason?.code,locallyEvaluated:!1,hasExperiment:s.metadata?.has_experiment,parsed:rh(s)}}}}if(void 0!==this._flagOverrides)for(let[e,t]of Object.entries(this._flagOverrides)){if(void 0===t){delete g[e];continue}let r=g[e];g[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:r?.payload,id:r?.id,version:r?.version,reason:r?.reason,locallyEvaluated:r?.locallyEvaluated??!1,hasExperiment:r?.hasExperiment}}if(void 0!==this._payloadOverrides)for(let[e,t]of Object.entries(this._payloadOverrides)){let r=g[e];r&&(g[e]={...r,payload:t})}if(void 0!==p)for(let e of Object.keys(g))p.has(e)||delete g[e];let w={};for(let[e,t]of Object.entries(y?.unresolved??{}))Object.prototype.hasOwnProperty.call(g,e)||(w[e]=t);return new rl({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:a,disableGeoip:o,flags:g,unresolvedFlags:w,requestId:r,evaluatedAt:i,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:m,quotaLimited:_})}_shouldSendMinimalFlagCalledEvent(e,t){return"$feature_flag_called"===e&&this._minimalFlagCalledEvents&&!1===t.$feature_flag_has_experiment}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:r,response:i,groups:s,disableGeoip:n,properties:a,record:o}=e,l=function(e){let{key:t,response:r,groups:i,record:s}=e,n=function(e){if(void 0===e||void 0!==e.unreadableField||2!==e.metadata.configVersion)return;let t=e.reason?.code||void 0,r={reasonCode:t,ruleId:void 0,ruleType:void 0,variantKey:void 0},i=void 0===t?void 0:rb.get(t);if(e.failed||void 0===i)return r;let{ruleId:s,ruleType:n,variantKey:a}=e.metadata;return void 0!==s&&rE.test(s)&&void 0!==n&&i.has(n)?t!==ry?{...r,ruleId:s,ruleType:n}:void 0===a?r:{reasonCode:t,ruleId:s,ruleType:n,variantKey:a}:r}(s);if(void 0===n)return;let{reasonCode:a,ruleId:o,ruleType:l,variantKey:u}=n,c=Object.entries(i??{}).sort(([e],[t])=>e<t?-1:+(e>t)),h={$feature_flag_config_version:2};void 0!==a&&(h.$feature_flag_reason_code=a),void 0!==o&&(h.$feature_flag_rule_id=o,h.$feature_flag_rule_type=l),void 0!==u&&(h.$feature_flag_variant_key=u);let{$feature_flag_reason:d,...f}=e.properties;Object.assign(f,h);let p={event:"$feature_flag_called",dedupeKey:JSON.stringify([t,r??null,c,2,a??null,o??null,l??null,u??null]),properties:f,capture:{removed:rx,pinned:h}};if(void 0===u)return{flagCalled:p,exposure:void 0};let g={$feature_flag:t,$feature_flag_response:r,$feature_flag_variant_key:u,$feature_flag_rule_id:o,locally_evaluated:!0===f.locally_evaluated},m={};for(let e of rF)void 0!==f[e]&&(m[e]=f[e]);return Object.assign(m,g),{flagCalled:p,exposure:{event:"$experiment_exposure",dedupeKey:JSON.stringify([t,c,2,o,u]),properties:m,capture:{removed:rS,pinned:g}}}}({key:r,response:i,groups:s,properties:a,record:o});if(void 0!==l){this._captureFlagEventOnce(this._distinctIdHasSentFlagCalls,t,l.flagCalled,e),void 0!==l.exposure&&this._captureFlagEventOnce(this._experimentExposuresReported,String(t),l.exposure,e);return}let u=s&&Object.keys(s).length>0?`_${JSON.stringify(Object.entries(s).sort(([e],[t])=>e<t?-1:+(e>t)))}`:"",c=`${r}_${i}${u}`;void 0!==this._reserveFlagEventKey(this._distinctIdHasSentFlagCalls,t,c)&&this.capture({distinctId:t,event:"$feature_flag_called",properties:a,groups:s,disableGeoip:n})}_reserveFlagEventKey(e,t,r){let i=e.get(t)??new Set;if(e.delete(t),e.set(t,i),!i.has(r)){for(i.add(r);e.size>Math.max(this.maxCacheSize,1);){let t=e.keys().next().value;if(void 0===t)break;e.delete(t)}return i}}_captureFlagEventOnce(e,t,r,i){let s=this._reserveFlagEventKey(e,t,r.dedupeKey);if(void 0===s)return;let n=!1,a=()=>{n||(n=!0,s.delete(r.dedupeKey))};try{if(this.disabled||this.optedOut)return void a();this._sendPreparedEvent("capture",{distinctId:i.distinctId,event:r.event,properties:r.properties,groups:i.groups,disableGeoip:i.disableGeoip},!1,{flagEvent:r.capture,onCaptureFailed:a})}catch(e){this._logger.error(`[FEATURE FLAGS] Failed to capture ${r.event}:`,e),a()}}_resolveSendFeatureFlagEvents(e){return e??this.options.sendFeatureFlagEvent??!0}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),resolveSendFeatureFlagEvents:e=>this._resolveSendFeatureFlagEvents(e),logWarning:e=>{!1!==this.options.featureFlagsLogWarnings&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:s}){this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:s},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:s}){await this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:s},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=e=>Object.fromEntries(e.map(e=>[e,!0]));if(!1===e){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(!1===e.flags?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):void 0!==e.flags&&(this._flagOverrides={...e.flags})),"payloads"in e&&(!1===e.payloads?this._payloadOverrides=void 0:void 0!==e.payloads&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if("flags"in e){let t=e.flags;if(!1===t||Array.isArray(t)||"object"==typeof t&&null!==t)return!0}if("payloads"in e){let t=e.payloads;if(!1===t||"object"==typeof t&&null!==t)return!0}return!1}withContext(e,t,r){return this.context?this.context.run(e,()=>(iV(this),t()),r):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t),iV(this)}async _shutdown(e){let t=Date.now()+(e??3e4);this._isShutdown=!0;let r=this._emails?.drain(),i=this._logs,s=i?eB(i.flush().catch(()=>{}),Math.max(0,t-Date.now())).then(()=>{i.reset(),i.clearQueue()}):void 0,n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await eB(this._metrics.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._metrics.reset()),this._traces&&(await eB(this._traces.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._traces.reset());let a=Math.max(0,t-Date.now()),o=r?eB(r,a):void 0;try{return await super._shutdown(a)}finally{await o,await s,this._distinctIdHasSentFlagCalls.clear(),this._experimentExposuresReported.clear(),n?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let e=new AbortController;i=eD(()=>{e.abort()},this.options.requestTimeout),r.signal=e.signal}try{return await this.fetch(t,r)}catch(e){this._events.emit("error",e);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let r={},i={};for(let[s,n]of Object.entries(e))if(I(n)&&t&&s in t){let e={};for(let[t,r]of Object.entries(n))e[String(t)]=String(r);i[String(s)]=e}else r[String(s)]=String(n);return{personProperties:r,groupProperties:i}}async getFeatureFlagsForEvent(e,t,r,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let s=i?.personProperties||{},n=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:n,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:a})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:n,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(e,t,s,n,r)).flags}addLocalPersonAndGroupProperties(e,t,r,i){let s={...r||{}},n={};if(t)for(let e of Object.keys(t))n[e]={$group_key:t[e],...i?.[e]||{}};return{allPersonProperties:s,allGroupProperties:n}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,r,i){return{distinctId:e,groups:t||{},personProperties:r||{},groupProperties:i||{},evaluationCache:{}}}captureException(e,t,r,i,s){if(!ij.isPreviouslyCapturedError(e)&&this.errorTracking.claimExplicitCapture(e)){let n=Error("PostHog syntheticException");this.addPendingPromise(ij.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:n},t,r,this.getContext()).then(e=>this._capturePreparedEvent({...e,uuid:i,flags:s},!1)))}}async captureExceptionImmediate(e,t,r,i){if(!ij.isPreviouslyCapturedError(e)&&this.errorTracking.claimExplicitCapture(e)){let s=Error("PostHog syntheticException");return this.addPendingPromise(ij.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,r,this.getContext()).then(e=>this.captureImmediate({...e,flags:i})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}_serviceNameProperties(){let e=this._resolveServiceName();return e?{service_name:e}:{}}_resolveServiceName(){return void 0===this._serviceName&&(this._serviceName=(this.options.traces?ra(this.options.traces,this.hostResourceAttributes()).serviceName:void 0)||ri(this.options.metrics).serviceName||null),this._serviceName}async _prepareEventMessage(e,t={}){var r;let{distinctId:i,event:s,properties:n,groups:a,flags:o,sendFeatureFlags:l,timestamp:u,disableGeoip:c,uuid:h}=e,d=(r=this.context?.get(),iT in e?e[iT]??void 0:r),f=t.includeContextProperties??!0,p=i||d?.distinctId,g=f?{...this._serviceNameProperties(),...this.props,...d?.properties||{},...n||{}}:{...this._serviceNameProperties(),...n||{}};"$exception"!==s||"$trace_id"in g||"$span_id"in g||Object.assign(g,await iq()),p||(p=eQ(),g.$process_person_profile=!1),f&&d?.sessionId&&!g.$session_id&&(g.$session_id=d.sessionId);let m=t.flagEvent,_=m?{...Object.fromEntries(Object.entries(g).filter(([e])=>!m.removed.has(e))),...m.pinned}:g,y=this._shouldSendMinimalFlagCalledEvent(s,_)?m?function(e){let t=ek(e);for(let r of rw)void 0!==e[r]&&(t[r]=e[r]);return t}(_):ek(_):_,v=this._runBeforeSend({distinctId:p,event:s,properties:y,groups:a,flags:o,sendFeatureFlags:l,timestamp:u,disableGeoip:c,uuid:h},t.onCaptureFailed);if(!v)return Promise.reject(null);let b=await Promise.resolve().then(async()=>{if(o)return l&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),o._getEventProperties();if(l){sR("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.");var e=await this.getFeatureFlagsForEvent(v.distinctId,a,c,"object"==typeof l?l:void 0);if(!e)return{};let t={};for(let[r,i]of Object.entries(e))t[`$feature/${r}`]=i;let r=Object.keys(e).filter(t=>!1!==e[t]).sort();return r.length>0&&(t.$active_feature_flags=r),t}return{}}).catch(()=>({})).then(e=>{let t=v.groups||a;return{...e,...v.properties||{},...void 0!==t&&Object.keys(t).length>0?{$groups:t}:{}}});return"$pageview"===v.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof b.$raw_user_agent&&rr(b.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(v.event="$bot_pageview",b.$browser_type="bot"),{distinctId:v.distinctId,event:v.event,properties:b,options:{timestamp:v.timestamp,disableGeoip:v.disableGeoip,uuid:v.uuid}}}_runBeforeSend(e,t){let r=this.options.before_send;if(!r)return e;let i=Array.isArray(r)?r:[r],s=e;for(let r of i)try{if(!(s=r(s)))return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!s.properties||0===Object.keys(s.properties).length){let e=`Event '${s.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(e)}}catch(r){return this._logger.error(`Error in before_send function for event '${e.event}':`,r),t?.(),null}return s}}var sj=ed,sL=ed,sD=ed,sB=ed,sN=ed,sq=ed,sU=ed,sH=ed,sW=e.i(78500);let sK=Symbol.for("posthog-node.context-lifetimes"),sV=globalThis,sz=sV[sK]??=new WeakMap;function sQ(e,t,r){let i=e&&sz.get(e);return r?sz.set(t,{signal:r,parent:i}):i&&sz.set(t,i),t}class sG{constructor(){this.storage=new sW.AsyncLocalStorage}get(){let e=this.storage.getStore();return e&&function(e){let t=sz.get(e);for(;t;){if(t.signal.aborted)return!1;t=t.parent}return!0}(e)?e:void 0}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){let r=this.get();return t?.fresh===!0?sQ(void 0,{...e},t.signal):sQ(r,{distinctId:e.distinctId??r?.distinctId,sessionId:e.sessionId??r?.sessionId,properties:{...r?.properties||{},...e.properties||{}}},t?.signal)}}class sJ{active(){return this._storage.getStore()}with(e,t){return this._storage.run(e,t)}constructor(){this._storage=new sW.AsyncLocalStorage}}var sZ=e.i(27028);let sY=(0,e.i(12057).promisify)(sZ.gzip);async function sX(e,t=!0){try{let t=await sY(e);return new Uint8Array(t)}catch(e){return t&&console.error("Failed to gzip compress data",e),null}}var s0=e.i(60526),iM=ed;let s1="posthog-node";function s2(e,{organization:t,projectId:r,prefix:i,severityAllowList:s=["error"],sendExceptionsToPostHog:n=!0}={}){return a=>{if(!("*"===s||s.includes(a.level)))return a;a.tags||(a.tags={});let o=a.tags[s3.POSTHOG_ID_TAG];if(void 0===o)return a;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${o}`,l).toString();a.tags["PostHog Person URL"]=u;let c=a.exception?.values||[],h=c.map(e=>({...e,stacktrace:e.stacktrace?{...e.stacktrace,type:"raw",frames:(e.stacktrace.frames||[]).map(e=>({...e,platform:"node:javascript"}))}:void 0})),d={$exception_message:c[0]?.value||a.message,$exception_type:c[0]?.type,$exception_level:a.level,$exception_list:h,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:c[0]?.value||a.message,$sentry_exception_type:c[0]?.type,$sentry_tags:a.tags},f=iM.getInjectedReleaseId();return f&&(d.$release_id=f),t&&r&&(d.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+a.event_id),n&&e.capture({event:"$exception",distinctId:o,properties:d}),a}}function s5(e,t){let r=s2(e,t);return{name:s1,processEvent:e=>r(e)}}class s3{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,t,r,i,s){this.name=s1,this.name=s1,this.setupOnce=function(n,a){n(s2(e,{organization:t,projectId:a()?.getClient()?.getDsn()?.projectId,prefix:r,severityAllowList:i,sendExceptionsToPostHog:s??!0}))}}}function s4(e){let t={};if(e)for(let r of e.split(";")){let[e,...i]=r.trim().split("=");if(e){let r=i.join("=").trim();try{t[e.trim()]=decodeURIComponent(r)}catch{t[e.trim()]=r}}}return{get:e=>e in t?{value:t[e]}:void 0}}function s6(e){let t=e.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${t}_posthog`}function s8(e){let t=Date.now();return JSON.stringify({distinct_id:e,$device_id:e,$user_state:"anonymous",$sesid:[t,eQ(),t]})}function s9(e,t){let r=s6(t),i=e.get(r);return i?ne(i.value):null}function s7(e){if(!e)return;let t={};return e.sessionId&&(t.$session_id=e.sessionId),e.deviceId&&(t.$device_id=e.deviceId),Object.keys(t).length>0?t:void 0}function ne(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||"object"!=typeof t||!t.distinct_id)return null;let r=y(t.$sesid)?t.$sesid:[],i=r[1];return{distinctId:String(t.distinct_id),isIdentified:"identified"===t.$user_state,sessionId:"string"==typeof i?i:void 0,sessionLastActivityTimestamp:nt(r[0]),sessionStartTimestamp:nt(r[2]),deviceId:"string"==typeof t.$device_id?t.$device_id:void 0}}catch{return null}}function nt(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}e.s(["PostHogSentryIntegration",0,s3,"createEventProcessor",0,s2,"sentryIntegration",0,s5],91573);let nr=/[\x00-\x1f\x7f-\x9f]/g;function ni(e){let t=e.options.readPostHogCookie;return!0===t?{apiKey:e.apiKey}:t&&"object"==typeof t?{apiKey:e.apiKey,sessionIdleTimeoutSeconds:t.sessionIdleTimeoutSeconds,optOutCapturingByDefault:t.optOutCapturingByDefault}:null}function ns(e,t,r){null!=r&&""!==r&&(e[t]=r)}function nn(e){return Array.isArray(e)?e[0]:e}function na(e){if(Array.isArray(e)){for(let t of e){let e=na(t);if(void 0!==e)return e}return}if("string"!=typeof e)return;let t=e.replace(nr,"").trim();if(t)return t.length>1e3?t.slice(0,1e3):t}function no(e,t,r){return"number"==typeof e&&Number.isFinite(e)&&Math.abs(t-e)<=r}function nl(e,t){let r;if(!e)return{};let i=na(e["x-posthog-session-id"]),s=na(e["x-posthog-distinct-id"]),{sessionId:n,distinctId:a}=void 0===i&&void 0===s&&t?function(e,t,r=Date.now(),i=18e5,s=!1){try{let n;if("string"!=typeof e)return{};let a=s4(e.split(";").reverse().join(";")),o=a.get(s6(t))?.value,l=a.get("__ph_opt_in_out_"+t)?.value??"";if(!o||d($,l)||s&&!d(k,l))return{};let u=JSON.parse(o);if(!u||"object"!=typeof u)return{};let c="identified"===u.$user_state?na(u.distinct_id):void 0,h=u.$sesid;if(Array.isArray(h)&&(2===h.length||3===h.length)){let[e,t,s=e]=h;no(e,r,i)&&no(s,r,864e5)&&(n=na(t))}return{...void 0!==n?{sessionId:n}:{},...void 0!==c?{distinctId:c}:{}}}catch{return{}}}(e.cookie,t.apiKey,Date.now(),"number"==typeof(r=t.sessionIdleTimeoutSeconds)&&Number.isFinite(r)&&0!==r?1e3*Math.min(Math.max(r,60),36e3):18e5,!0===t.optOutCapturingByDefault):{sessionId:i,distinctId:s};return{...void 0!==n?{sessionId:n}:{},...void 0!==a?{distinctId:a}:{}}}function nu(e,t){let r=function(e){if(!e)return e;let t=e.indexOf("?"),r=e.indexOf("#");return -1===t||-1!==r&&r<t?e:`${e.slice(0,t)}${-1===r?"":e.slice(r)}`}(e);return t?eM(r):r}function nc(e,t){var r;let i=nl(t.headers,ni(e)),s=e.getContext(),n=s?.sessionId??i.sessionId,a=s?.distinctId??i.distinctId,o={},l=!0===e.options.disable_capture_url_hashes;return ns(o,"$current_url",(r=t.originalUrl||t.url,l?eM(r):r)),ns(o,"$request_method",t.method),ns(o,"$request_path",nu(t.path,l)),ns(o,"$user_agent",nn(t.headers["user-agent"])),ns(o,"$ip",function(e){let t=nn(e.headers["x-forwarded-for"]);if(t){let e=t.split(",")[0].trim();if(e)return e}return e.socket?.remoteAddress}(t)),{...void 0!==n?{sessionId:n}:{},...void 0!==a?{distinctId:a}:{},properties:o}}function nh(e,t){var r;t.use((r=e,(e,t,i)=>{r.withContext(nc(r,e),()=>{iV(r,!0),i()})}))}function nd(e,t){var r;t.use((r=e,(e,t,i,s)=>{if(ij.isPreviouslyCapturedError(e))return void s(e);let n=nc(r,t),a=Error("Synthetic exception"),o={...void 0!==n.sessionId?{$session_id:n.sessionId}:{},...n.properties||{}};r.addPendingPromise(Promise.all([ij.buildEventMessage(r.getErrorPropertiesBuilder(),e,{mechanism:{type:"middleware",handled:!1},syntheticException:a},n.distinctId,o,r.getContext()),i.headersSent||i.destroyed?Promise.resolve(i.headersSent?i.statusCode:void 0):new Promise(e=>{let t=t=>{clearTimeout(s),i.removeListener("finish",r),i.removeListener("close",r),e(t)},r=()=>t(i.headersSent?i.statusCode:void 0),s=setTimeout(()=>t(void 0),1e3);s.unref(),i.once("finish",r),i.once("close",r)})]).then(([e,t])=>(void 0!==t&&(e.properties={...e.properties,$response_status_code:t}),r._capturePreparedEvent(e,!1)))),s(e)}))}e.s(["setupExpressErrorHandler",0,nd,"setupExpressRequestContext",0,nh],93546);let nf="http.server.request.duration",np="http.server.request.count",ng=[.005,.01,.025,.05,.075,.1,.25,.5,.75,1,2.5,5,7.5,10],nm=new Set(["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","QUERY","TRACE"]);function n_(e,t,r,i={}){return ny(e,t,r,i)}async function ny(e,t,r,i,s){var n;let a;if(i.ignore?.(t))return r();let o=nl((n=t.headers,a={},n.forEach((e,t)=>{a[t.toLowerCase()]=e}),a),ni(e)),l=e.getContext(),u=!0===e.options.disable_capture_url_hashes,c=function(e){try{return new URL(e.url).pathname}catch{return}}(t),h={};ns(h,"$request_method",t.method),ns(h,"$request_path",c?nu(c,u):void 0),ns(h,"$user_agent",t.headers.get("user-agent")??void 0);let d=l?.sessionId??o.sessionId,f=l?.distinctId??o.distinctId,p={...void 0!==d?{sessionId:d}:{},...void 0!==f?{distinctId:f}:{},properties:h},g=t.method.toUpperCase(),m=nm.has(g)?g:"_OTHER",_="_OTHER"===m?"HTTP":m,y=performance.now(),v=new AbortController,b=!1;try{return await e.withContext(p,()=>(iV(e,!0),e.withSpan(_,{kind:"server",parent:t.headers.get("traceparent")??void 0,tracestate:t.headers.get("tracestate")??void 0,attributes:{"http.request.method":m,..."_OTHER"===m?{"http.request.method_original":t.method}:{},...c?{"url.path":c}:{}}},async n=>{var a,o,l;let u,c,h,d,f=!1;try{c=await r()}catch(e){f=!0,h=e}try{d=i.getRoute?.(t,c)}catch{}let g=f?500:c?.status??500;if(d&&(n.updateName(`${_} ${d}`),n.setAttribute("http.route",d)),n.setAttribute("http.response.status_code",g),!f&&g>=500){let e;try{e=s?.()}catch{}null!=e?n.recordException(e):n.setStatus("error")}let w={"http.request.method":m,"http.response.status_code":g,...d?{"http.route":d}:{}};if(e.metrics.histogram(nf,(performance.now()-y)/1e3,{unit:"s",attributes:w,bounds:ng}),e.metrics.count(np,1,{attributes:w}),e._flushMetricsWithinInvocation(),f)throw h;return c?.body&&"HEAD"!==m?(b=!0,a=c,o=t=>e.withContext(p,t,{signal:v.signal}),l=()=>v.abort(),u=a.body.getReader(),new Response(new ReadableStream({async pull(e){try{let{done:t,value:r}=await o(()=>u.read());t?(e.close(),l()):e.enqueue(r)}catch(t){l(),e.error(t)}},async cancel(e){try{await o(()=>u.cancel(e))}finally{l()}}}),a)):c})),{signal:v.signal})}finally{b||v.abort()}}function nv(e,t={}){return async(r,i)=>{r.res=await ny(e,r.req.raw,async()=>(await i(),r.res),{...t,getRoute:()=>r.req.routePath&&"/*"!==r.req.routePath?r.req.routePath:void 0},()=>r.error)}}e.s(["HTTP_SERVER_REQUEST_COUNT_METRIC",0,np,"HTTP_SERVER_REQUEST_DURATION_METRIC",0,nf,"instrumentRequest",0,n_,"posthogHonoMiddleware",0,nv],67532),e.i(91573),e.i(93546),e.i(67532),e.i(58325),e.s(["EmailError",0,i8,"FeatureFlagError",0,h,"FeatureFlagEvaluations",0,rl,"HTTP_SERVER_REQUEST_COUNT_METRIC",0,np,"HTTP_SERVER_REQUEST_DURATION_METRIC",0,nf,"PostHogSentryIntegration",0,s3,"cookieStateToProperties",0,s7,"cookieStoreFromHeader",0,s4,"createEventProcessor",0,s2,"enrichCurrentSpan",0,iz,"getPostHogCookieName",0,s6,"instrumentRequest",0,n_,"parsePostHogCookie",0,ne,"posthogHonoMiddleware",0,nv,"readPostHogCookie",0,s9,"sentryIntegration",0,s5,"serializePostHogCookie",0,s8,"setupExpressErrorHandler",0,nd,"setupExpressRequestContext",0,nh,"uuidv7",0,eQ],57564),e.i(57564),e.s(["EmailError",0,i8,"FeatureFlagError",0,h,"FeatureFlagEvaluations",0,rl,"HTTP_SERVER_REQUEST_COUNT_METRIC",0,np,"HTTP_SERVER_REQUEST_DURATION_METRIC",0,nf,"PostHog",0,class extends sM{getLibraryId(){return"posthog-node"}compressPayload(e){return sX(e,this.isDebug)}initializeContext(){return new sG}initializeSpanContextManager(){return new sJ}hostResourceAttributes(){return function(){var e,t;let r,i,s;try{r=(0,s0.platform)(),i=(0,s0.release)()}catch{}return e=r,t=i,{...(s=function(e){if(e)return Object.prototype.hasOwnProperty.call(td,e)?td[e]:e}(e))?{"os.name":s}:{},...t?{"os.version":t}:{}}}()}createErrorPropertiesBuilder(){let e;return new sj.ErrorPropertiesBuilder([new sL.EventCoercer,new sD.ErrorCoercer,new sB.ObjectCoercer,new sN.StringCoercer,new sq.PrimitiveCoercer],sU.createStackParser("node:javascript",sH.nodeStackLineParser),[(e=function(e=process.argv[1]?(0,l.dirname)(process.argv[1]):process.cwd(),t="\\"===l.sep){let r=t?u(e):e;return e=>{if(!e)return;let i=t?u(e):e,{dir:s,base:n,ext:a}=l.posix.parse(i);(".js"===a||".mjs"===a||".cjs"===a)&&(n=n.slice(0,-1*a.length));let o=decodeURIComponent(n);s||(s=".");let c=s.lastIndexOf("/node_modules");if(c>-1)return`${s.slice(c+14).replace(/\//g,".")}:${o}`;if(s.startsWith(r)){let e=s.slice(r.length+1).replace(/\//g,".");return e?`${e}:${o}`:o}return o}}(),async t=>{for(let r of t)r.module=e(r.filename);return t}),e=>ev(e,void 0,this._logger),function(e=process.cwd()){l.sep;let t=e=>e,r=t(e);return async e=>{for(let i of e)!(!i.filename||i.filename.startsWith("node:")||i.filename.startsWith("data:"))&&(0,l.isAbsolute)(i.filename)&&(i.filename=t((0,l.relative)(r,t(i.filename))));return e}}()])}},"PostHogSentryIntegration",0,s3,"cookieStateToProperties",0,s7,"cookieStoreFromHeader",0,s4,"createEventProcessor",0,s2,"enrichCurrentSpan",0,iz,"getPostHogCookieName",0,s6,"instrumentRequest",0,n_,"parsePostHogCookie",0,ne,"posthogHonoMiddleware",0,nv,"readPostHogCookie",0,s9,"sentryIntegration",0,s5,"serializePostHogCookie",0,s8,"setupExpressErrorHandler",0,nd,"setupExpressRequestContext",0,nh,"uuidv7",0,eQ],28864)}];
2
2
 
3
3
  //# sourceMappingURL=node_modules_posthog-node_dist_entrypoints_index_node_mjs_09z9-p77cu37y._.js.map