failproofai 1.0.5 → 1.0.6-beta.1

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 (204) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/build-manifest.json +5 -5
  3. package/.next/standalone/.next/prerender-manifest.json +5 -5
  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 +7 -7
  11. package/.next/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +6 -6
  12. package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +7 -7
  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 +14 -14
  20. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +14 -14
  21. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +13 -13
  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 +4 -4
  25. package/.next/standalone/.next/server/app/api/audit/run/route.js.nft.json +1 -1
  26. package/.next/standalone/.next/server/app/api/audit/status/route.js.nft.json +1 -1
  27. package/.next/standalone/.next/server/app/api/auth/login-request/route.js.nft.json +1 -1
  28. package/.next/standalone/.next/server/app/api/auth/login-verify/route.js.nft.json +1 -1
  29. package/.next/standalone/.next/server/app/api/auth/logout/route.js.nft.json +1 -1
  30. package/.next/standalone/.next/server/app/api/auth/status/route.js.nft.json +1 -1
  31. package/.next/standalone/.next/server/app/api/download/[project]/[session]/route.js.nft.json +1 -1
  32. package/.next/standalone/.next/server/app/audit/page/build-manifest.json +2 -2
  33. package/.next/standalone/.next/server/app/audit/page/server-reference-manifest.json +2 -2
  34. package/.next/standalone/.next/server/app/audit/page.js.nft.json +1 -1
  35. package/.next/standalone/.next/server/app/audit/page_client-reference-manifest.js +1 -1
  36. package/.next/standalone/.next/server/app/index.html +1 -1
  37. package/.next/standalone/.next/server/app/index.rsc +14 -14
  38. package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +13 -13
  39. package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +14 -14
  40. package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  41. package/.next/standalone/.next/server/app/page/build-manifest.json +2 -2
  42. package/.next/standalone/.next/server/app/page/server-reference-manifest.json +1 -1
  43. package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
  44. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  45. package/.next/standalone/.next/server/app/policies/page/build-manifest.json +2 -2
  46. package/.next/standalone/.next/server/app/policies/page/server-reference-manifest.json +14 -14
  47. package/.next/standalone/.next/server/app/policies/page.js +6 -5
  48. package/.next/standalone/.next/server/app/policies/page.js.nft.json +1 -1
  49. package/.next/standalone/.next/server/app/policies/page_client-reference-manifest.js +1 -1
  50. package/.next/standalone/.next/server/app/project/[name]/page/build-manifest.json +2 -2
  51. package/.next/standalone/.next/server/app/project/[name]/page/server-reference-manifest.json +1 -1
  52. package/.next/standalone/.next/server/app/project/[name]/page.js +1 -1
  53. package/.next/standalone/.next/server/app/project/[name]/page.js.nft.json +1 -1
  54. package/.next/standalone/.next/server/app/project/[name]/page_client-reference-manifest.js +1 -1
  55. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/build-manifest.json +2 -2
  56. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/react-loadable-manifest.json +2 -2
  57. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/server-reference-manifest.json +2 -2
  58. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page.js +2 -2
  59. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page.js.nft.json +1 -1
  60. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page_client-reference-manifest.js +1 -1
  61. package/.next/standalone/.next/server/app/projects/page/build-manifest.json +2 -2
  62. package/.next/standalone/.next/server/app/projects/page/server-reference-manifest.json +1 -1
  63. package/.next/standalone/.next/server/app/projects/page.js.nft.json +1 -1
  64. package/.next/standalone/.next/server/app/projects/page_client-reference-manifest.js +1 -1
  65. package/.next/standalone/.next/server/app/settings/page/build-manifest.json +2 -2
  66. package/.next/standalone/.next/server/app/settings/page/server-reference-manifest.json +4 -4
  67. package/.next/standalone/.next/server/app/settings/page.js +3 -2
  68. package/.next/standalone/.next/server/app/settings/page.js.nft.json +1 -1
  69. package/.next/standalone/.next/server/app/settings/page_client-reference-manifest.js +1 -1
  70. package/.next/standalone/.next/server/chunks/[externals]__0sds_16._.js +3 -0
  71. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0o07qi9._.js +1 -1
  72. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0zlqo2t._.js +1 -1
  73. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__112b4go._.js → [root-of-the-server]__1_r2rbg._.js} +4 -4
  74. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1anxb5k._.js +1 -1
  75. package/.next/standalone/.next/server/chunks/_09dz7xv._.js +3 -3
  76. package/.next/standalone/.next/server/chunks/_0tovk6q._.js +1 -1
  77. package/.next/standalone/.next/server/chunks/_0trp3yc._.js +1 -1
  78. package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_01r25oi._.js +2 -2
  79. package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_09z9-p7._.js +2 -2
  80. package/.next/standalone/.next/server/chunks/package_json_[json]_cjs_1nxcc4v._.js +1 -1
  81. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0-_ki57._.js +4 -0
  82. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__013jr2b._.js +2 -2
  83. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__01wy8d-._.js +2 -2
  84. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__02npjtd._.js +2 -2
  85. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0576iuy._.js +3 -0
  86. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0bym1os._.js → [root-of-the-server]__0cg-bgc._.js} +2 -2
  87. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0da85px._.js +2 -2
  88. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0ftmoxc._.js +2 -2
  89. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0p-5p8u._.js +2 -2
  90. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__00y9ww2._.js → [root-of-the-server]__0u3w0ll._.js} +2 -2
  91. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0sz_5na._.js → [root-of-the-server]__1ouobn4._.js} +1 -1
  92. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1p2otjt._.js +2 -2
  93. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1py795m._.js +1 -1
  94. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1qapotl._.js +1 -1
  95. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__15k-dqb._.js → [root-of-the-server]__1x3j9mj._.js} +2 -2
  96. package/.next/standalone/.next/server/chunks/ssr/_0-yi74u._.js +1 -1
  97. package/.next/standalone/.next/server/chunks/ssr/_06imw3p._.js +5 -0
  98. package/.next/standalone/.next/server/chunks/ssr/_08x1r5t._.js +1 -1
  99. package/.next/standalone/.next/server/chunks/ssr/{_0guaevg._.js → _0qlygw6._.js} +2 -2
  100. package/.next/standalone/.next/server/chunks/ssr/_0wso5d3._.js +1 -1
  101. package/.next/standalone/.next/server/chunks/ssr/_1-3unkg._.js +1 -1
  102. package/.next/standalone/.next/server/chunks/ssr/{_1b78kcp._.js → _1_ddpm3._.js} +1 -1
  103. package/.next/standalone/.next/server/chunks/ssr/{_14c6q09._.js → _1_qswah._.js} +2 -2
  104. package/.next/standalone/.next/server/chunks/ssr/_1ddpc5g._.js +1 -1
  105. package/.next/standalone/.next/server/chunks/ssr/_1es2j7i._.js +3 -3
  106. package/.next/standalone/.next/server/chunks/ssr/_1u8-lu2._.js +1 -1
  107. package/.next/standalone/.next/server/chunks/ssr/_1zopuov._.js +1 -1
  108. package/.next/standalone/.next/server/chunks/ssr/_next-internal_server_app_policies_page_actions_1sp2-yo.js +12 -11
  109. package/.next/standalone/.next/server/chunks/ssr/app_audit__components_audit-dashboard_tsx_0p9ud47._.js +1 -1
  110. package/.next/standalone/.next/server/chunks/ssr/app_components_project-list_tsx_1ke6anr._.js +1 -1
  111. package/.next/standalone/.next/server/chunks/ssr/app_global-error_tsx_1kp6l3x._.js +1 -1
  112. package/.next/standalone/.next/server/chunks/ssr/app_policies_hooks-client_tsx_19dqvpc._.js +2 -2
  113. package/.next/standalone/.next/server/chunks/ssr/app_settings_settings-client_tsx_20lq-mq._.js +1 -1
  114. package/.next/standalone/.next/server/chunks/ssr/node_modules_1hl81y4._.js +3 -0
  115. package/.next/standalone/.next/server/chunks/ssr/node_modules_posthog-node_dist_entrypoints_index_node_mjs_11bnuzn._.js +2 -2
  116. package/.next/standalone/.next/server/middleware-build-manifest.js +5 -5
  117. package/.next/standalone/.next/server/pages/404.html +1 -1
  118. package/.next/standalone/.next/server/pages/500.html +1 -1
  119. package/.next/standalone/.next/server/server-reference-manifest.js +1 -1
  120. package/.next/standalone/.next/server/server-reference-manifest.json +19 -19
  121. package/.next/standalone/.next/static/chunks/{3w46euc60dx39.js → 02vwr5js1x28j.js} +1 -1
  122. package/.next/standalone/.next/static/chunks/06fjx8-0_qufs.js +1 -0
  123. package/.next/standalone/.next/static/chunks/{2zafgs90r_leq.js → 06jxjnw8bfczc.js} +1 -1
  124. package/.next/standalone/.next/static/chunks/0cbvytf8epn34.js +1 -0
  125. package/.next/standalone/.next/static/chunks/0y227_ohdqwvn.js +1 -0
  126. package/.next/standalone/.next/static/chunks/{252xreaecy80h.js → 1p4xauf-zu6zk.js} +1 -1
  127. package/.next/standalone/.next/static/chunks/{021ydrq6rhpsi.js → 1qf2uiipatr80.js} +1 -1
  128. package/.next/standalone/.next/static/chunks/1uc_s_dftgxiq.js +6 -0
  129. package/.next/standalone/.next/static/chunks/1xacnwjkbekn7.js +1 -0
  130. package/.next/standalone/.next/static/chunks/{11s_v03ub6nss.js → 27_bwbg8sv6vj.js} +1 -1
  131. package/.next/standalone/.next/static/chunks/2hg_bp8z_vm2g.js +1 -0
  132. package/.next/standalone/.next/static/chunks/{3bleyy40s99f2.js → 2x776s0x3n_tu.js} +1 -1
  133. package/.next/standalone/.next/static/chunks/{1vb33xa6j9y2q.js → 3ht0xsco46pul.js} +1 -1
  134. package/.next/standalone/.next/static/chunks/{turbopack-3p73obe0xmrxm.js → turbopack-38nzuvp95_2rv.js} +1 -1
  135. package/.next/standalone/fp-cloud-cli/uv.lock +3 -3
  136. package/.next/standalone/hermes-plugin/README.md +138 -0
  137. package/.next/standalone/hermes-plugin/__init__.py +248 -0
  138. package/.next/standalone/hermes-plugin/client.py +150 -0
  139. package/.next/standalone/hermes-plugin/ledger.py +187 -0
  140. package/.next/standalone/hermes-plugin/plugin.yaml +37 -0
  141. package/.next/standalone/lib/hermes-profiles.ts +67 -19
  142. package/.next/standalone/lib/hermes-sessions.ts +3 -2
  143. package/.next/standalone/node_modules/@next/env/package.json +1 -1
  144. package/.next/standalone/node_modules/next/dist/build/swc/index.js +1 -1
  145. package/.next/standalone/node_modules/next/dist/compiled/next-server/app-page-turbo-experimental.runtime.prod.js +1 -1
  146. package/.next/standalone/node_modules/next/dist/compiled/next-server/app-page-turbo.runtime.prod.js +1 -1
  147. package/.next/standalone/node_modules/next/dist/lib/patch-incorrect-lockfile.js +3 -3
  148. package/.next/standalone/node_modules/next/dist/server/app-render/create-component-styles-and-scripts.js +2 -1
  149. package/.next/standalone/node_modules/next/dist/server/config.js +1 -1
  150. package/.next/standalone/node_modules/next/dist/server/dev/hot-reloader-turbopack.js +2 -2
  151. package/.next/standalone/node_modules/next/dist/server/dev/hot-reloader-webpack.js +1 -1
  152. package/.next/standalone/node_modules/next/dist/server/image-optimizer.js +14 -0
  153. package/.next/standalone/node_modules/next/dist/server/lib/app-info-log.js +1 -1
  154. package/.next/standalone/node_modules/next/dist/server/lib/disk-lru-cache.external.js +7 -1
  155. package/.next/standalone/node_modules/next/dist/server/lib/start-server.js +1 -1
  156. package/.next/standalone/node_modules/next/dist/server/use-cache/use-cache-wrapper.js +6 -1
  157. package/.next/standalone/node_modules/next/dist/telemetry/anonymous-meta.js +1 -1
  158. package/.next/standalone/node_modules/next/dist/telemetry/events/swc-load-failure.js +1 -1
  159. package/.next/standalone/node_modules/next/dist/telemetry/events/version.js +2 -2
  160. package/.next/standalone/node_modules/next/package.json +10 -10
  161. package/.next/standalone/node_modules/react/cjs/react.development.js +92 -46
  162. package/.next/standalone/node_modules/react/cjs/react.production.js +112 -89
  163. package/.next/standalone/node_modules/react/package.json +1 -1
  164. package/.next/standalone/node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.js +1165 -790
  165. package/.next/standalone/node_modules/react-dom/cjs/react-dom-server-legacy.node.production.js +1171 -791
  166. package/.next/standalone/node_modules/react-dom/cjs/react-dom-server.browser.production.js +1294 -862
  167. package/.next/standalone/node_modules/react-dom/cjs/react-dom-server.edge.production.js +1305 -868
  168. package/.next/standalone/node_modules/react-dom/cjs/react-dom-server.node.production.js +1315 -896
  169. package/.next/standalone/node_modules/react-dom/cjs/react-dom.production.js +24 -5
  170. package/.next/standalone/node_modules/react-dom/package.json +4 -4
  171. package/.next/standalone/package.json +13 -12
  172. package/.next/standalone/sdk/python/uv.lock +18 -18
  173. package/.next/standalone/server.js +1 -1
  174. package/README.md +29 -13
  175. package/bin/failproofai.mjs +3 -1
  176. package/dist/cli.mjs +655 -360
  177. package/dist/worker.mjs +78 -34
  178. package/hermes-plugin/README.md +138 -0
  179. package/hermes-plugin/__init__.py +248 -0
  180. package/hermes-plugin/client.py +150 -0
  181. package/hermes-plugin/ledger.py +187 -0
  182. package/hermes-plugin/plugin.yaml +37 -0
  183. package/lib/hermes-profiles.ts +67 -19
  184. package/lib/hermes-sessions.ts +3 -2
  185. package/package.json +13 -12
  186. package/scripts/translate-docs/validate-translation.ts +48 -0
  187. package/src/hooks/handler.ts +29 -1
  188. package/src/hooks/integrations.ts +271 -73
  189. package/src/hooks/manager.ts +41 -7
  190. package/src/hooks/types.ts +8 -8
  191. package/src/hooks/worker-server.ts +1 -0
  192. package/.next/standalone/.next/server/chunks/[externals]__157pf8j._.js +0 -3
  193. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0oa1lav._.js +0 -3
  194. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0s740oi._.js +0 -6
  195. package/.next/standalone/.next/server/chunks/ssr/node_modules_13n822a._.js +0 -3
  196. package/.next/standalone/.next/static/chunks/0y8_1s45gbqmn.js +0 -6
  197. package/.next/standalone/.next/static/chunks/14b3ezufe5411.js +0 -1
  198. package/.next/standalone/.next/static/chunks/1oskk7pdo8aon.js +0 -1
  199. package/.next/standalone/.next/static/chunks/2xycd6mjg00fb.js +0 -1
  200. package/.next/standalone/.next/static/chunks/3l36d73kj18zw.js +0 -1
  201. package/.next/standalone/.next/static/chunks/40lpt2o2b283e.js +0 -1
  202. /package/.next/standalone/.next/static/{uFpAs_vIXSo6qBzmkXPWD → QCNYz2yCxxdeggg1k0iEq}/_buildManifest.js +0 -0
  203. /package/.next/standalone/.next/static/{uFpAs_vIXSo6qBzmkXPWD → QCNYz2yCxxdeggg1k0iEq}/_clientMiddlewareManifest.js +0 -0
  204. /package/.next/standalone/.next/static/{uFpAs_vIXSo6qBzmkXPWD → QCNYz2yCxxdeggg1k0iEq}/_ssgManifest.js +0 -0
@@ -1,4 +1,4 @@
1
- module.exports=[39702,e=>{"use strict";let t,r,i,s,a;var n,o=e.i(14747);function l(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function u(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"}var c=((n={}).AnonymousId="anonymous_id",n.DistinctId="distinct_id",n.Props="props",n.EnablePersonProcessing="enable_person_processing",n.PersonMode="person_mode",n.FeatureFlagDetails="feature_flag_details",n.FeatureFlags="feature_flags",n.FeatureFlagPayloads="feature_flag_payloads",n.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",n.BootstrapFeatureFlags="bootstrap_feature_flags",n.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",n.OverrideFeatureFlags="override_feature_flags",n.Queue="queue",n.AiQueue="ai_queue",n.AiCaptureQueue="ai_capture_queue",n.LogsQueue="logs_queue",n.OptedOut="opted_out",n.SessionId="session_id",n.SessionStartTimestamp="session_start_timestamp",n.SessionLastTimestamp="session_timestamp",n.PersonProperties="person_properties",n.GroupProperties="group_properties",n.InstalledAppBuild="installed_app_build",n.InstalledAppVersion="installed_app_version",n.SessionReplay="session_replay",n.PushRegistered="push_registered",n.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",n.SurveyLastSeenDate="survey_last_seen_date",n.SurveysSeen="surveys_seen",n.Surveys="surveys",n.RemoteConfig="remote_config",n.FlagsEndpointWasHit="flags_endpoint_was_hit",n.DeviceId="device_id",n);let h={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",TIMEOUT:"timeout",CONNECTION_ERROR:"connection_error",UNKNOWN_ERROR:"unknown_error",apiError:e=>`api_error_${e}`},d=Array.isArray,g=Object.prototype;g.hasOwnProperty;let f=g.toString,p=d||function(e){return"[object Array]"===f.call(e)},y=e=>e===Object(e)&&!p(e),m=e=>void 0===e,v=e=>"[object String]"==f.call(e),_=e=>v(e)&&0===e.trim().length,b=e=>null===e,w=e=>m(e)||b(e),E=e=>"[object Number]"==f.call(e)&&e==e;function F(e){return null===e||"object"!=typeof e}function P(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function x(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,Error)}}function S(e){return"u">typeof Event&&$(e,Event)}function $(e,t){try{return e instanceof t}catch{return!1}}let C="Android",I="BlackBerry",k="Nintendo",A="PlayStation",O="Xbox",R="Windows",T="(\\d+(\\.\\d+)?)";RegExp("Version/"+T),RegExp("(Claude|Codex|ChatGPT)\\/"+T),RegExp(O,"i"),RegExp(A+" \\w+","i"),RegExp(k+" \\w+","i"),RegExp(I+"|PlayBook|BB10","i");RegExp("rv:"+T),RegExp("Edge?\\/"+T),RegExp("(Chrome|CrMo)\\/"+T),RegExp("CriOS\\/"+T),RegExp("(UCBrowser|UCWEB)\\/"+T),RegExp("(Opera|OPR)\\/"+T),RegExp("Firefox\\/"+T),RegExp("FxiOS\\/"+T),RegExp("Konqueror[:/]?"+T,"i"),RegExp(I+" "+T),RegExp("android\\s"+T,"i"),RegExp("SamsungBrowser\\/"+T),RegExp("OculusBrowser\\/"+T),RegExp("Vivaldi\\/"+T),RegExp("YaBrowser\\/"+T),RegExp("Whale\\/"+T),RegExp("Brave\\/"+T),RegExp("(DuckDuckGo|Ddg)\\/"+T),RegExp("PaleMoon\\/"+T),RegExp("Waterfox\\/"+T),RegExp("GSA\\/"+T),RegExp("(rv:|MSIE )"+T),RegExp("rv:"+T),RegExp(O+"; "+O+" (.*?)[);]","i"),RegExp(k,"i"),RegExp(A,"i"),RegExp(R,"i"),RegExp("("+C+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+C+")","i");let M=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function j(e,t){return"string"==typeof e&&M.test(e)?e:t()}function D(e,t){let r=Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function L(e){return e?e.split("#")[0]:e}async function B(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 N(){return new Date().toISOString()}function U(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}async function q(e,t,r){let i;try{return await Promise.race([e,new Promise((e,s)=>{i=U(()=>{try{r?.(),e()}catch(e){s(e)}},t)})])}finally{clearTimeout(i)}}function H(e){return Promise.all(e.map(e=>(e??Promise.resolve()).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}class W{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),a=this.parseStacktrace(i,s);return{$exception_list:this.convertToExceptionList(a,r),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&p(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;return null!=e.cause&&(r=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack&&(i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),{...e,cause:r,stack:i}}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={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};e.stack&&(r.stacktrace={type:"raw",frames:e.stack});let i=[r];return null!=e.cause&&i.push(...this.convertToExceptionList(e.cause,{...t,handled:!0})),i}buildParsingContext(e){return{chunkIdMap:function(e){let s=globalThis._posthogChunkIds;if(!s)return;let a=Object.keys(s);return i&&a.length===r?i:(r=a.length,i=a.reduce((r,i)=>{t||(t={});let a=t[i];if(a)r[a[0]]=a[1];else{let a=e(i);for(let e=a.length-1;e>=0;e--){let n=a[e],o=n?.filename,l=s[i];if(o&&l){r[o]=l,t[i]=[o,l];break}}}return r},{}))}(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,r=0){let i=(r,i)=>{if(i<=4){let s=this.buildCoercingContext(e,t,i);return this.applyCoercers(r,s)}};return{...t,syntheticException:0==r?t.syntheticException:void 0,mechanism:e,apply:e=>i(e,r),next:e=>i(e,r+1)}}}function z(e,t,r,i,s){let a={platform:e,filename:t,function:"<anonymous>"===r?"?":r,in_app:!!t&&!t.startsWith("webkit-masked-url://")&&"<anonymous>"!==t};return m(i)||(a.lineno=i),m(s)||(a.colno=s),a}e.s(["ErrorPropertiesBuilder",0,W],69309);let V=(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]},G=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,K=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Q=/\((\S*)(?::(\d+))(?::(\d+))\)/,J=(e,t)=>{let r=G.exec(e);if(r){let[,e,i,s]=r;return z(t,e,"?",+i,+s)}let i=K.exec(e);if(i){if(i[2]&&0===i[2].indexOf("eval")){let e=Q.exec(i[2]);e&&(i[2]=e[1],i[3]=e[2],i[4]=e[3])}let[e,r]=V(i[1]||"?",i[2]);return z(t,r,e,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},Z=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Y=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,X=(e,t)=>{let r=Z.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let e=Y.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]=V(i,e),z(t,e,i,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}},ee=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,et=(e,t)=>{let r=ee.exec(e);return r?z(t,r[2],r[1]||"?",+r[3],r[4]?+r[4]:void 0):void 0},er=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,ei=(e,t)=>{let r=er.exec(e);return r?z(t,r[2],r[3]||"?",+r[1]):void 0},es=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,ea=(e,t)=>{let r=es.exec(e);return r?z(t,r[5],r[3]||r[4]||"?",+r[1],+r[2]):void 0},en=/^\s*[-]{4,}$/,eo=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,el=/^Promise\.(?:all|any)$/,eu=/^index \d+$/,ec=(e,t)=>{let r=e.match(eo);if(r){let e,i,s,a,n;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))}a=void 0}i&&(a=e,n=i),"<anonymous>"===i&&(n=void 0,s=void 0),void 0===s&&(n=n||"?",s=a?`${a}.${n}`:n);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]),el.test(s)&&eu.test(o||"")&&(o="node:internal/promise"),{filename:o?decodeURI(o):void 0,module:void 0,function:s,lineno:eh(r[3]),colno:eh(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(en))return{filename:e,platform:t}};function eh(e){return parseInt(e||"",10)||void 0}let ed=/\(error: (.*)\)/;function eg(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,50).map(e=>{var r;return{...e,filename:e.filename||((r=t)[r.length-1]||{}).filename,function:e.function||"?"}})}function ef(){return ep("web:javascript",J,X)}function ep(e,...t){return(r,i=0)=>{let s=[],a=r.split("\n");for(let r=i;r<a.length;r++){let i=a[r];if(i.length>1024)continue;let n=ed.test(i)?i.replace(ed,"$1"):i;if(!n.match(/\S*Error: /)){for(let r of t){let t=r(n,e);if(t){s.push(t);break}}if(s.length>=50)break}}return eg(s)}}e.s(["createDefaultStackParser",0,ef,"createStackParser",0,ep,"reverseAndStripFrames",0,eg],10728);class ey{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let r=v(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return P(e,"DOMException")}isDOMError(e){return P(e,"DOMError")}}e.s(["DOMExceptionCoercer",0,ey],33603);class em{match(e){return!!P(e,"ErrorEvent")&&(void 0!=e.error||this._hasUsableMessage(e))}coerce(e,t){if(void 0!=e.error)return t.apply(e.error);let r=t.apply(e.message);return{...r,stack:this._buildLocationStack(e)??r.stack,synthetic:!0}}_hasUsableMessage(e){return v(e.message)&&e.message.length>0}_buildLocationStack(e){let t=e.lineno??0,r=e.colno??0;if(v(e.filename)&&0!==e.filename.length&&0!==t)return`Error
2
- at ${e.filename}:${t}:${r}`}}e.s(["ErrorEventCoercer",0,em],60887);let ev=["fatal","error","warning","log","info","debug"];function e_(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 eb{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(S(e))return e.constructor.name;let t="name"in e?e.name:void 0;return v(t)&&!_(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=e_(e);return`${t&&"Object"!==t?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return v(e)&&!_(e)&&ev.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(x(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,eb],12154);class ew{match(e){return S(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${e_(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["EventCoercer",0,ew],41324);class eE{match(e){return F(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,eE],79478);class eF{match(e){return P(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!S(e))return!1;try{let t=e.detail;return null!=t&&"object"==typeof t&&"reason"in t}catch{return!1}}coerce(e,t){let r=this.getUnhandledRejectionReason(e);return F(r)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(r)}`,stack:t.syntheticException?.stack,synthetic:!0}:t.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&null!=e.detail&&"object"==typeof e.detail&&"reason"in e.detail)return e.detail.reason}catch{}return e}}e.s(["PromiseRejectionEventCoercer",0,eF],1802),e.s([],59567);let eP={MESSAGE:"$message",TIMESTAMP:"$timestamp"},ex=new Set([eP.MESSAGE,eP.TIMESTAMP]),eS={enabled:!0,max_bytes:32768};function e$(e){return e?{enabled:e.enabled??eS.enabled,max_bytes:function(e,t){if(!E(e)||1/0===e||-1/0===e)return t;let r=Math.floor(e);return r<0?t:r}(e.max_bytes,eS.max_bytes)}:{...eS}}function eC(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((r,i)=>(ex.has(i)?t.push(i):r[i]=e[i],r),{}),droppedKeys:t}}class eI{constructor(e){this._entries=[],this._totalBytes=0,this._config=e$(e)}setConfig(e){this._config=e$(e),this._trimToMaxBytes()}add(e){let t=function(e){let t;try{t=u(e)}catch{return}try{let e=JSON.parse(t);if(!y(e))return;let r=e[eP.MESSAGE],i=e[eP.TIMESTAMP];if(!v(r)||0===r.trim().length||!v(i)&&!E(i))return;return{step:e,json:t}}catch{return}}(e);if(!t)return;let r=ek(t.json);r>this._config.max_bytes||(this._entries.push({step:t.step,bytes:r}),this._totalBytes+=r,this._trimToMaxBytes())}getAttachable(){return this._entries.map(e=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}}function ek(e){if("u">typeof TextEncoder)return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let e=0;e<t.length;e++)"%"===t[e]?(r+=1,e+=2):r+=1;return r}e.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,eS,"EXCEPTION_STEP_INTERNAL_FIELDS",0,eP,"ExceptionStepsBuffer",0,eI,"getUtf8ByteLength",0,ek,"resolveExceptionStepsConfig",0,e$,"stripReservedExceptionStepFields",0,eC],45162),e.s([],21754),e.i(21754),e.i(69309),e.i(10728),e.s(["chromeStackLineParser",0,J,"createDefaultStackParser",0,ef,"createStackParser",0,ep,"geckoStackLineParser",0,X,"nodeStackLineParser",0,ec,"opera10StackLineParser",0,ei,"opera11StackLineParser",0,ea,"reverseAndStripFrames",0,eg,"winjsStackLineParser",0,et],22546),e.i(22546),e.i(59567),e.i(33603);class eA{match(e){return x(e)}coerce(e,t){let r=this.getStack(e);return{type:this.getType(e),value:this.getMessage(e,t),stack:r??t.syntheticException?.stack,cause:e.cause?t.next(e.cause):void 0,synthetic:void 0===r}}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){return e.stacktrace||e.stack||void 0}}e.s(["ErrorCoercer",0,eA],13446),e.i(13446),e.i(60887);let eO=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class eR{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(eO);return i&&(t=i[1],r=i[2]),[t,r]}}e.s(["StringCoercer",0,eR],22175),e.i(22175),e.i(12154),e.i(41324),e.i(79478),e.i(1802),e.s(["DOMExceptionCoercer",0,ey,"ErrorCoercer",0,eA,"ErrorEventCoercer",0,em,"EventCoercer",0,ew,"ObjectCoercer",0,eb,"PrimitiveCoercer",0,eE,"PromiseRejectionEventCoercer",0,eF,"StringCoercer",0,eR],90166),e.i(90166);class eT{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)}}}function eM(){let e=globalThis._posthogReleaseId;return"string"==typeof e&&e.length>0?e:void 0}e.s(["ReduceableCache",0,eT],45294),e.i(45294),e.i(45162),e.s(["getInjectedReleaseId",0,eM],56168),e.i(56168),e.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,eS,"DOMExceptionCoercer",0,ey,"EXCEPTION_STEP_INTERNAL_FIELDS",0,eP,"ErrorCoercer",0,eA,"ErrorEventCoercer",0,em,"ErrorPropertiesBuilder",0,W,"EventCoercer",0,ew,"ExceptionStepsBuffer",0,eI,"ObjectCoercer",0,eb,"PrimitiveCoercer",0,eE,"PromiseRejectionEventCoercer",0,eF,"ReduceableCache",0,eT,"StringCoercer",0,eR,"chromeStackLineParser",0,J,"createDefaultStackParser",0,ef,"createStackParser",0,ep,"geckoStackLineParser",0,X,"getInjectedReleaseId",0,eM,"getUtf8ByteLength",0,ek,"nodeStackLineParser",0,ec,"opera10StackLineParser",0,ei,"opera11StackLineParser",0,ea,"resolveExceptionStepsConfig",0,e$,"reverseAndStripFrames",0,eg,"stripReservedExceptionStepFields",0,eC,"winjsStackLineParser",0,et],11168);var ej=e.i(11168);let eD="0123456789abcdef";class eL{constructor(e){this.bytes=e}static ofInner(e){if(16===e.length)return new eL(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 eL(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 eL(e)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=eD.charAt(this.bytes[t]>>>4),e+=eD.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+=eD.charAt(this.bytes[t]>>>4),e+=eD.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 eL(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 eB{constructor(e){this.timestamp=0,this.counter=0,this.random=e??eN()}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 eL.fromFieldsV7(this.timestamp,Math.trunc(this.counter/0x40000000),this.counter&0x40000000-1,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,eL.ofInner(e)}}let eN=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),eU=()=>eq().toString(),eq=()=>(s||(s=new eB)).generate();function eH(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 eW(e){let t=e.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${t}_posthog`}function ez(e){let t=Date.now();return JSON.stringify({distinct_id:e,$device_id:e,$user_state:"anonymous",$sesid:[t,eU(),t]})}function eV(e,t){let r=eW(t),i=e.get(r);return i?eK(i.value):null}function eG(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 eK(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||"object"!=typeof t||!t.distinct_id)return null;let r=p(t.$sesid)?t.$sesid[1]:void 0;return{distinctId:String(t.distinct_id),isIdentified:"identified"===t.$user_state,sessionId:"string"==typeof r?r:void 0,deviceId:"string"==typeof t.$device_id?t.$device_id:void 0}}catch{return null}}let eQ=e=>void 0===e?void 0:e.variant??e.enabled,eJ=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}},eZ=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],eY=(e,t=[])=>{let r={},i=t=>{void 0!==e[t]&&(r[t]=e[t])};return eZ.forEach(i),t.forEach(i),r};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 e0=e=>{throw D("NativeGzipValidationError",`Native gzip produced invalid output: ${e}`)},e1=async(e,t)=>{e.size<18&&e0("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());r.length>=2&&31===r[0]&&139===r[1]&&8===r[2]||e0("invalid-header");let i=new DataView(await e.slice(e.size-8).arrayBuffer());i.getUint32(0,!0)!==(e=>{let t=(()=>{if(a)return a;a=[];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;a[e]=t>>>0}return a})(),r=0xffffffff;for(let i=0;i<e.length;i++)r=t[(r^e[i])&255]^r>>>8;return(0xffffffff^r)>>>0})(t)&&e0("invalid-crc");let s=t.length>>>0;i.getUint32(4,!0)!==s&&e0("invalid-size")};async function e2(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}),a=new Response(r.readable).blob(),[n]=await Promise.all([a,s]);return await e1(n,t),n}catch(e){if(r?.rethrow)throw e;return t&&console.error("Failed to gzip compress data",e),null}}class e3{add(e){let t=eU(),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 e4=(e,t,r)=>{function i(s,...a){t(()=>{(0,r[s])(e,...a)})}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=>e4(`${e} ${i}`,t,r)}};class e5 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 bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let e=D("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e,t=new Promise((e,t)=>{this.responseBodyTimer=U(()=>{this._bodyReadTimedOut=!0;let e=D("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 e6 extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}async function e8(e){if(e instanceof e5){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 e9(e){return e instanceof e6}function e7(e){if(e instanceof e5)return 502===e.status||504===e.status;if(!(e instanceof e6))return!1;let t=e.error;return"ECONNREFUSED"!==(t?.code??t?.cause?.code)}function te(e){return"object"==typeof e&&e instanceof e5&&413===e.status}function tt(e){return e instanceof e5?408===e.status||429===e.status||e.status>=500:e9(e)}function tr(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}let ti="default";class ts{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new W([new eA,new eb,new eR,new eE],ef())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new e3,this._events=new eX,this._isInitialized=!1;const r="string"==typeof e?e.trim():"",i="string"==typeof t.host?t.host.trim():"",s=!r;this._logger=function(e,t=e=>e()){return e4(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's api key. The client will be disabled."),this.apiKey=r,this.host=function(e){return e?.replace(/\/+$/,"")}(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:tt},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={...t,...this.getCommonEventProperties()};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=eY(r)),{distinct_id:e.distinct_id,event:e.event,properties:r}}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,a){this.wrap(()=>{let n=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...a||{}}});this.enqueue("capture",n,i)})}async groupIdentifyStatelessImmediate(e,t,r,i,s,a){let n=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...a||{}}});await this.sendImmediate("capture",n,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.apiKey}/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={},a=!1){await this._initPromise;let n=`${this.host}/flags/?v=2${a?"&config=true":""}`,o={token:this.apiKey,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={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(o)};return this._logger.info("Flags URL",n),this.fetchWithRetry(n,l,{type:"required",consume:e=>e.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:e7},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,eQ(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?eJ(r):void 0]}));return{...e,featureFlags:r,featureFlagPayloads:i}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([e,t])=>[e,eJ(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 e5)return{type:"api_error",statusCode:e.status};if(e instanceof e6){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={},a){await this._initPromise;let n=await this.getFeatureFlagDetailStateless(e,t,r,i,s,a);if(void 0===n)return{response:void 0,requestId:void 0};let o=eQ(n.response);return void 0===o&&(o=!1),{response:o,requestId:n.requestId}}async getFeatureFlagDetailStateless(e,t,r={},i={},s={},a){await this._initPromise;let n=await this.getFeatureFlagDetailsStateless(t,r,i,s,a,[e]);if(void 0!==n)return{response:n.flags[e],requestId:n.requestId,evaluatedAt:n.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,r={},i={},s={},a){await this._initPromise;let n=await this.getFeatureFlagPayloadsStateless(t,r,i,s,a,[e]);if(!n)return;let o=n[e];return void 0===o?null:o}async getFeatureFlagPayloadsStateless(e,t={},r={},i={},s,a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,a)).payloads}async getFeatureFlagsStateless(e,t={},r={},i={},s,a){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,a)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},i={},s,a){await this._initPromise;let n=await this.getFeatureFlagDetailsStateless(e,t,r,i,s,a);return n?{flags:n.featureFlags,payloads:n.featureFlagPayloads,requestId:n.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},r={},i={},s,a){await this._initPromise;let n={geoip_disable:s??this.disableGeoip};a&&(n.flag_keys_to_evaluate=a);let o=await this.getFlags(e,t,r,i,n);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.apiKey}`,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 ti}persistedQueueKeyForRoute(e){return c.Queue}getActiveQueueRoutes(){return[ti]}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 a=this.persistedQueueKeyForRoute(i??this.getQueueRouteKey(s)),n=this.getPersistedProperty(a)||[];n.length>=this.maxQueueSize&&(n.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),n.push({message:s}),this.setPersistedProperty(a,n),this._events.emit(e,s),n.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=U(()=>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,a=tr(s.properties)?s.properties:void 0;return void 0!==r&&a?.$lib===void 0&&(a={...a||{},$lib:r}),void 0!==i&&a?.$lib_version===void 0&&(a={...a||{},$lib_version:i}),a&&(s.properties=a),s.uuid=j(s.uuid,eU),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:N(),uuid:j(t?.uuid,eU)};return(t?.disableGeoip??this.disableGeoip)&&(tr(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.flush().catch(async e=>{await e8(e)})}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(()=>H([t])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),H([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 e2(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,t,r=ti){let i={api_key:this.apiKey,batch:e.map(e=>{if(!e)return e;let t=this.normalizeTimestampForWire(e.timestamp);return t===e.timestamp?e:{...e,timestamp:t}}),sent_at:N()};this.historicalMigration&&(i.historical_migration=!0);let s=u(i),a=`${this.host}${this.getBatchEndpointPath(r)}`,n=this.disableCompression?null:await this.compressPayload(s),o={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==n&&{"Content-Encoding":"gzip"}},body:n||s};await this.fetchWithRetry(a,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,a=0;for(;i.length>0&&a<s;){let s=i.slice(0,this.maxBatchSize),n=s.map(e=>void 0===e.message?e.message:this.normalizeMessage(e.message)),o=async()=>{let e=this.getPersistedProperty(r)||[],t=[...s],a=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,a),i=a,this._dequeuedMessagesCount+=s.length,await this.flushStorage()},l={retryCheck:e=>!te(e)&&tt(e)};try{await this.sendBatch(n,l,e)}catch(e){if(te(e)&&n.length>1){this.maxBatchSize=Math.max(1,Math.floor(n.length/2)),this._logger.warn(`Received 413 when sending batch of size ${n.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw e instanceof e6||await o(),this._events.emit("error",e),e}await o(),t.push(...n),a+=n.length}}async _sendOtlpBatch({path:e,payload:t}){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let r=JSON.stringify(t),i=`${this.host}/i/v1/${e}?token=${encodeURIComponent(this.apiKey)}`,s=this.disableCompression?null:await this.compressPayload(r),a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==s&&{"Content-Encoding":"gzip"}},body:s||r};try{return await this.fetchWithRetry(i,a,{type:"successful-write"},{retryCheck:e=>!te(e)&&tt(e)}),{kind:"ok"}}catch(e){if(te(e))return{kind:"too-large"};if(tt(e))return{kind:"retry-later",error:e};return{kind:"fatal",error:e}}}async _sendLogsBatch(e){return this._sendOtlpBatch({path:"logs",payload:e})}async _sendMetricsBatch(e){return this._sendOtlpBatch({path:"metrics",payload:e})}async fetchWithRetry(e,t,r,i,s){let a=t.body?t.body:"",n=-1;try{n=a instanceof Blob?a.size:a instanceof Uint8Array?a.byteLength:Buffer.byteLength(a,"utf8")}catch{n=a instanceof Blob?a.size:a instanceof Uint8Array?a.byteLength:new TextEncoder().encode(a).length}let o={...this._retryOptions,...i},l=0;return await B(async()=>{let i,a,o;l++;let u=new AbortController,c=s??this.requestTimeout,h=Date.now()+c,d=new Promise((e,t)=>{i=U(()=>{let e=D("AbortError",`Request timed out after ${c}ms`);t(e),u.abort(e)},c)}),g=!1,f=()=>o??=(async()=>{try{await a?.body?.cancel()}catch{}})();try{let i;try{i=this.fetch(e,{signal:u.signal,...t})}catch(e){throw new e6(e)}i.then(e=>{u.signal.aborted&&!g&&Promise.resolve(e.body?.cancel()).catch(()=>{})}).catch(()=>{});try{a=await Promise.race([i,d]),g=!0}catch(e){throw new e6(e)}if("no-cors"!==t.mode&&(a.status<200||a.status>=400))throw new e5(a,n,h,u);if("successful-write"===r.type){try{await Promise.race([f(),d])}catch{}return}try{return await Promise.race([r.consume(a),d])}catch(e){if(u.signal.aborted)throw new e6(e);throw e}}finally{clearTimeout(i),u.signal.aborted&&a&&f()}},{...o,retryCheck:e=>{let t=o.retryCheck(e);return t&&l<=o.retryCount&&e instanceof e5&&e.cancelResponseBody(),t}})}async _shutdown(e=3e4){await this._initPromise;let t=!1;if(this.clearFlushTimer(),!this.disabled)return q((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 e5||e9(e))))throw e;await e8(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 ta="[Truncated]",tn="[Unserializable]";function to(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}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let tl=Object.prototype.propertyIsEnumerable;function tu(e,t){try{return tc(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function tc(e,t,r,i){let s=[];for(let a in e)if(tl.call(e,a)){if(!a){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 n=e[a];if(b(n)||m(n))continue;s.push({key:to(a),value:function e(t,r,i,s){if(i.remainingNodes<=0)return{stringValue:ta};if(i.remainingNodes--,"[object Boolean]"===f.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:to(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:"[Circular]"};if(s>=20)return{stringValue:ta};if(t instanceof Date){let e=Number.isFinite(t.getTime())?t.toISOString():String(t);return{stringValue:"string"==typeof e?to(e):String(e)}}i.ancestors.add(t);try{try{let a=t.toJSON;if("function"==typeof a)return e(a.call(t),r,i,s+1)}catch{}if(p(t))return{arrayValue:{values:function(t,r,i,s){let a=[],n=Math.min(t.length,1e3),o=0;for(;o<n&&i.remainingNodes>0;o++)try{let n=o in t?t[o]:void 0;if(w(n))continue;a.push(e(n,r,i,s))}catch{a.push({stringValue:tn})}return t.length>o&&a.push({stringValue:ta}),a}(t,r,i,s+1)}};return{kvlistValue:{values:tc(t,r,i,s+1)}}}finally{i.ancestors.delete(t)}}return{stringValue:to(String(t))}}(n,t,r,i)})}catch{s.push({key:to(a),value:{stringValue:tn}})}}return s}let th=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function td(e){return String(e)+"000000"}function tg(e,t,r,i){let s="";return i&&(s=Object.keys(i).sort().map(e=>`${JSON.stringify(e)}:${JSON.stringify(i[e])}`).join(",")),`${e}\u0000${t}\u0000${r??""}\u0000${s}`}class tf{constructor(e,t,r){this._instance=e,this._config=t,this._logger=r,this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._generation=0}count(e,t=1,r){this._capture({name:e,type:"count",value:t,unit:r?.unit,attributes:r?.attributes})}gauge(e,t,r){this._capture({name:e,type:"gauge",value:t,unit:r?.unit,attributes:r?.attributes})}histogram(e,t,r){this._capture({name:e,type:"histogram",value:t,unit:r?.unit,attributes:r?.attributes})}flush(){let e=this._flushPromise,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._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._clearFlushTimer(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){let t,r;if(this._instance.isDisabled||this._instance.optedOut)return;let i=this._runBeforeSend(e);if(null===i)return;if(!i.name||"string"!=typeof i.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof i.value||!Number.isFinite(i.value))return void this._logger.warn(`Dropping metric '${i.name}': value must be a finite number`);if("count"===i.type&&i.value<0)return void this._logger.warn(`Dropping count '${i.name}': counters are monotonic, value must be >= 0`);try{t=i.attributes?{...i.attributes}:void 0,r=tg(i.type,i.name,i.unit,t)}catch(e){this._logger.warn(`Dropping metric '${i.name}': attributes could not be serialized`,e);return}let s=this._series.get(r);if(!s){if(!this._admitNewSeries())return;s={name:i.name,type:i.type,unit:i.unit,attributes:t,windowStartMs:Date.now()},this._series.set(r,s)}let a=this._typeByName.get(i.name);void 0===a?this._typeByName.set(i.name,i.type):a===i.type||this._typeCollisionWarned.has(i.name)||(this._typeCollisionWarned.add(i.name),this._logger.warn(`Metric name '${i.name}' is already used as a ${a}; recording it as a ${i.type} too will blend both series in charts. Use a distinct name.`)),this._fold(s,i.value),this._armFlushTimer()}_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)}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:Array(th.length+1).fill(0)});let r=e.hist;r.count+=1,r.sum+=t,r.min=Math.min(r.min,t),r.max=Math.max(r.max,t),r.bucketCounts[function(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}(t,th)]+=1}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=p(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||(this._flushTimer=U(()=>{this._flushTimer=void 0,this.flush().catch(e=>{this._logger.error("Metrics flush failed:",e)})},this._config.flushIntervalMs))}_clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}async _doFlush(){if(0===this._series.size)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,r=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t===this._generation)switch(r.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._armFlushTimer();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,a,n,o;return s=this._buildMetrics(e),t=this._config,r=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),a={...t.resourceAttributes,"service.name":t.serviceName||"unknown_service",...t.environment&&{"deployment.environment":t.environment},...t.serviceVersion&&{"service.version":t.serviceVersion},"telemetry.sdk.name":r,"telemetry.sdk.version":i},n=this._instance.getLibraryId(),o=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:tu(a)},scopeMetrics:[{scope:{name:n,version:o},metrics:s}]}]}}_buildMetrics(e){let t=td(Date.now()),r=new Map;for(let i of e.values()){let e=tg(i.type,i.name,i.unit,void 0),s=r.get(e);s||(s={name:i.name,...i.unit&&{unit:i.unit}},"count"===i.type?s.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===i.type?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:1,dataPoints:[]},r.set(e,s));let a=tu(i.attributes??{},this._logger),n=td(i.windowStartMs);if("count"===i.type){let e={attributes:a,startTimeUnixNano:n,timeUnixNano:t,asDouble:i.total??0};s.sum.dataPoints.push(e)}else if("gauge"===i.type){let e={attributes:a,timeUnixNano:t,asDouble:i.last??0};s.gauge.dataPoints.push(e)}else if(i.hist){let e={attributes:a,startTimeUnixNano:n,timeUnixNano:t,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:th};s.histogram.dataPoints.push(e)}}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.type){case"count":e.total=(e.total??0)+(r.total??0);break;case"gauge":break;case"histogram":if(r.hist)if(e.hist){e.hist.count+=r.hist.count,e.hist.sum+=r.hist.sum,e.hist.min=Math.min(e.hist.min,r.hist.min),e.hist.max=Math.max(e.hist.max,r.hist.max);for(let t=0;t<e.hist.bucketCounts.length;t++)e.hist.bucketCounts[t]+=r.hist.bucketCounts[t]}else e.hist=r.hist}}}}var tp=ej,ty=e.i(2157),tm=e.i(12714),tv=e.i(50227),t_=e.i(1457);let tb=new tp.ReduceableCache(25),tw=new tp.ReduceableCache(20);async function tE(e,t=tm.open,r){let i,s={};try{i=process.cwd()}catch{}for(let t=e.length-1;t>=0;t--){var a,n;let r=e[t],o=r?.filename;!(!r||"string"!=typeof o||"number"!=typeof r.lineno||(a=o).startsWith("node:")||a.endsWith(".min.js")||a.endsWith(".min.cjs")||a.endsWith(".min.mjs")||a.startsWith("data:")||void 0!==(n=r).lineno&&n.lineno>1e4||void 0!==n.colno&&n.colno>1e3)&&((0,tv.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 a=tS(e,i);if(void 0===a||tw.get(a))continue;let n=s[e];if(!n)continue;n.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=t$(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=t$(r)),t++}return s}(n);if(o.every(e=>(function(e,t){let r=tb.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})(a,e)))continue;let u=function(e,t,r){let i=e.get(t);return void 0===i?(e.set(t,r),r):i}(tb,a,{});l.push(tP(e,o,u,a,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=tS(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=tC(e);i<e;i++){let e=r[i];if(void 0===e)return void tx(t);t.pre_context.push(e)}if(void 0===r[e])return tx(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,tb,i),tb.reduce(),e}async function tF(e,t,r){let i,s=!1;try{i=await t(e,ty.constants.O_RDONLY|ty.constants.O_NONBLOCK);let a=await i.stat();if(!a.isFile())return;if(a.size>0xa00000)return void r?.debug(`Skipping source context for oversized file ${e}: ${a.size} bytes exceeds 10485760`);return s=!0,i}catch{return}finally{i&&!s&&await i.close().catch(()=>{})}}async function tP(e,t,r,i,s,a){let n=await tF(e,s,a);return void 0===n?void tw.set(i,1):new Promise(e=>{let s,a,o=!1;function l(t){o||(o=!0,t?.destroy(),n.close().then(e,e))}try{s=n.createReadStream({autoClose:!1,start:0,end:0x9fffff})}catch{tw.set(i,1),l();return}try{a=(0,t_.createInterface)({input:s})}catch{tw.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],g=h[1];function f(){tw.set(i,1),a.close(),a.removeAllListeners(),l(s)}s.on("error",f),a.on("error",f),a.on("close",()=>l(s)),a.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 a=Math.min(s+140,i);return a>i-5&&(a=i),a===i&&(s=Math.max(a-140,0)),r=r.slice(s,a),s>0&&(r=`...${r}`),a<i&&(r+="..."),r}(e,0),u>=g)){if(c===t.length-1){a.close(),a.removeAllListeners();return}let e=t[++c];if(void 0===e){a.close(),a.removeAllListeners();return}d=e[0],g=e[1]}})})}function tx(e){delete e.pre_context,delete e.context_line,delete e.post_context}function tS(e,t){return(0,tv.isAbsolute)(e)?JSON.stringify([null,e]):void 0===t?void 0:JSON.stringify([t,e])}function t$(e){return[tC(e),e+7]}function tC(e){return Math.max(1,e-7)}let tI=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],tk=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return tI.concat(t).some(e=>{let t=e.toLowerCase();return -1!==r.indexOf(t)})},tA={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};e.s(["FeatureFlagError",0,tA],88096);class tO{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e,t={}){let r=this._flags[e];return this._recordAccess(e),r?.enabled??t.defaultValue??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),t)return!!t.enabled&&(t.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)}_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 tO({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),""===this._distinctId||this._isSlice&&!(e in this._flags))return;let t=this._flags[e],r=void 0===t?void 0:!1!==t.enabled&&(t.variant??!0),i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:r,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};t?.hasExperiment!==void 0&&(i.$feature_flag_has_experiment=t.hasExperiment),t?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let s=[];this._errorsWhileComputing&&s.push(tA.ERRORS_WHILE_COMPUTING),this._quotaLimited&&s.push(tA.QUOTA_LIMITED),void 0===t&&s.push(tA.FLAG_MISSING),s.length>0&&(i.$feature_flag_error=s.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:r,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}}let tR=["is_not","is_set"];class tT extends Error{constructor(e){super(e),this.name=this.constructor.name,Object.setPrototypeOf(this,tT.prototype)}}function tM(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(!tM(t in e?e[t]:null))return!1;return!0}function tj(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 tT("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new tT("Cannot stringify an unpaired surrogate like the flags service")}}function tD(e,t){let r=0,i=0;for(;r<e.length&&i<t.length;){let s=e.charCodeAt(r),a=t.charCodeAt(i),n=s>=55296&&s<=56319,o=a>=55296&&a<=56319,l=n?e.charCodeAt(r+1):0,u=o?t.charCodeAt(i+1):0,c=n?(s-55296)*1024+l-56320+65536:s,h=o?(a-55296)*1024+u-56320+65536:a;if(c!==h)return c-h;r+=n?2:1,i+=o?2:1}return e.length-t.length}function tL(e){return"string"==typeof e?(tj(e),e):function e(t,r=new Set){if(null===t)return"null";if("string"==typeof t)return tj(t),JSON.stringify(t);if("boolean"==typeof t)return t?"true":"false";if("number"==typeof t){if(!Number.isFinite(t))throw new tT(`Cannot stringify non-finite number ${t} like the flags service`);if(Number.isInteger(t))throw new tT(`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 tT("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 tT("Cannot stringify a non-JSON object like the flags service");if(r.has(t))throw new tT("Cannot stringify a circular object during local evaluation");r.add(t);try{let i=Object.keys(t);return i.forEach(tj),`{${i.sort(tD).map(i=>`${JSON.stringify(i)}:${e(t[i],r)}`).join(",")}}`}finally{r.delete(t)}}throw new tT(`Cannot stringify ${typeof t} like the flags service`)}(e)}function tB(e){try{return new RegExp(e),!0}catch{return!1}}function tN(e){return String(e).replace(/[A-Z]/g,e=>e.toLowerCase())}function tU(e,t,r){if(!/^\d+$/.test(e)||"strict"===r&&e.length>1&&"0"===e[0])throw new tT(`Invalid semver: ${t}`);return parseInt(e,10)}function tq(e,t="strict"){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new tT(`Invalid semver: ${e}`);let i=r.split("."),s=r=>void 0===r||""===r?0:tU(r,e,t);return[s(i[0]),s(i[1]),s(i[2])]}function tH(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 tW(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 tT(`${e} is in an invalid date format`)}throw new tT(`The date provided ${e} must be a string, number, or date object`)}async function tz(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 tV(e,t,r=""){return parseInt((await tz(`${e}.${t}${r}`)).slice(0,15),16)/0x1000000000000000}function tG(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 tK(e,t,r){let i=await tV(e,t,"variant");return tG(r).find(e=>i>=e.valueMin&&i<e.valueMax)?.key}class tQ extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,tQ.prototype)}}class tJ extends Error{constructor(e){super(e),function(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}(this,tJ)}}class tZ{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:i,host:s,customHeaders:a,...n}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=r,this.host=s,this.poller=void 0,this.fetch=n.fetch||fetch,this.onError=n.onError,this.customHeaders=a,this.onLoad=n.onLoad,this.onMinimalFlagCalledEvents=n.onMinimalFlagCalledEvents,this.cacheProvider=n.cacheProvider,this.strictLocalEvaluation=n.strictLocalEvaluation??!1,this.evaluationContexts=n.evaluationContexts,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}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 a,n;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return a;if(void 0!==(n=this.featureFlagsByKey[e])){let o=this.createEvaluationContext(t,r,i,s);try{a=(await this.computeFlagAndPayloadLocally(n,o)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${a}`))}catch(t){t instanceof tJ||t instanceof tT?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 a}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let r={},i={},s=0==this.featureFlags.length,a=t?t.map(e=>this.featureFlagsByKey[e]).filter(Boolean):this.featureFlags,n={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(a.map(async e=>{try{let{value:t,payload:s}=await this.computeFlagAndPayloadLocally(e,n);r[e.key]=t,s&&(i[e.key]=s)}catch(t){t instanceof tJ||t instanceof tT?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e.key}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e.key}: ${t}`)),s=!0}})),{response:r,payloads:i,fallbackToFlags:s}}async computeFlagAndPayloadLocally(e,t,r={}){let i,{matchValue:s,skipLoadCheck:a=!1}=r;if(a||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};i=void 0!==s?s:await this.computeFlagValueLocally(e,t);let n=this.getFeatureFlagPayload(e.key,i);return{value:i,payload:n}}async computeFlagValueLocally(e,t){let{distinctId:r,groups:i,personProperties:s,groupProperties:a}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new tT("Flag has experience continuity enabled");let n=(e.filters||{}).aggregation_group_type_index;if(void 0!=n){let r=this.groupTypeMapping[String(n)];if(!r)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${n} for feature flag ${e.key}`)),new tT("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=a[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 tT(`Can't compute feature flag: ${e.key} without $device_id`);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}getFeatureFlagPayload(e,t){var r=this.featureFlagsByKey?.[e]?.filters?.payloads;if(!1===t||null==t||!r)return null;let i=r["boolean"==typeof t?t.toString():t]||null;return null==i?null:eJ(i)}async evaluateFlagDependency(e,t,r){let{evaluationCache:i}=r,s=e.key;if(!this.featureFlagsByKey)throw new tT("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new tT(`Flag dependency property for '${s}' is missing required 'dependency_chain' field`);let a=e.dependency_chain;if(!Array.isArray(a))throw new tT(`Flag dependency property for '${s}' has an invalid 'dependency_chain' (expected array, got ${typeof a})`);if(0===a.length)throw new tT(`Circular dependency detected for flag '${s}' (empty dependency chain)`);for(let e of a){if(!(e in i)){let t=this.featureFlagsByKey[e];if(t)if(t.active)try{let s=await this.computeFlagValueLocally(t,r);i[e]=s}catch(t){throw new tT(`Error evaluating flag dependency '${e}' for flag '${s}': ${t}`)}else i[e]=!1;else if(this.filteredOutFlagKeys.has(e))i[e]=!1;else throw new tT(`Missing flag dependency '${e}' for flag '${s}'`)}if(null==i[e])throw new tT(`Dependency '${e}' could not be evaluated`)}let n=i[s];return this.flagEvaluatesToExpectedValue(e.value,n)}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,a=e.filters||{},n=a.groups||[],o=a.aggregation_group_type_index,l=a.early_exit??!1,{groups:u,groupProperties:c}=i,h=!1;for(let d of n)try{let n=void 0!==d.aggregation_group_type_index?d.aggregation_group_type_index:o,g=r,f=t;if(n!==o&&null!=n){let t=this.groupTypeMapping[String(n)];if(!t||!(t in u)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${n} not available`));continue}if(!(t in c)){h=!0;continue}g=c[t],f=u[t]}let p=await this.isConditionMatch(e,f,d,g,i);if("match"===p){let t=d.variant,r=a.multivariate?.variants||[];s=t&&r.some(e=>e.key===t)?t:await this.getMatchingVariant(e,f)||!0;break}if(l&&"out_of_rollout_bound"===p){if(h)break;return!1}}catch(e){if(e instanceof tJ)throw e;if(e instanceof tT)h=!0;else throw e}if(void 0!==s)return s;if(h)throw new tT("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,r,i,s){let a=r.rollout_percentage,n=e=>{this.logMsgIfDebug(()=>console.warn(e))};if((r.properties||[]).length>0){for(let e of r.properties){let t=e.type,r=!1;if("cohort"===t){let t=await tX(e,i,this.cohorts,this.debugMode,e=>this.evaluateFlagDependency(e,i,s));r="not_in"===e.operator?!t:t}else r="flag"===t?await this.evaluateFlagDependency(e,i,s):tY(e,i,n);if(!r)return"no_match"}if(void 0==a)return"match"}return void 0!=a&&await tV(e.key,t)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){return tK(e.key,t,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return tG(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))})}updateFlagState(e){let t=this.filterFlagsByEvaluationContexts(e.flags);this.featureFlags=t,this.featureFlagsByKey=t.reduce((e,t)=>(e[t.key]=t,e),{});let r=new Set(t.map(e=>e.key));this.filteredOutFlagKeys=new Set(e.flags.filter(e=>!r.has(e.key)).map(e=>e.key)),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(!0===e.minimalFlagCalledEvents)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter(e=>e.ensure_experience_continuity);t.length>0&&console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map(e=>e.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();if(t)return this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags),!0;return!1}catch(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(){return this.shouldBeginExponentialBackoff?Math.min(6e4,this.pollingInterval*2**this.backOffCount):this.pollingInterval}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{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 tQ(`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.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new tQ(`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 tQ(`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={flags:r.flags??[],groupTypeMapping:r.group_type_mapping||{},cohorts:r.cohorts||{},minimalFlagCalledEvents:!0===r.minimal_flag_called_events};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(e){this.onError?.(Error(`Failed to store in cache: ${e}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(e){e instanceof tQ&&this.onError?.(e)}finally{this.pollerStopped||(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(){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=U(()=>{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 q(t,e,()=>{throw Error(`Cache shutdown timeout after ${e}ms`)})}catch(e){this.onError?.(Error(`Error during cache shutdown: ${e}`))}}}function tY(e,t,r){return function(e,t,r={}){let i=e.key,s=e.value,a=e.operator||"exact",n=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,i)){if("is_not_set"===a)return!1;else if("is_set"===a)return!0}else throw new tT(`Property ${i} not found in propertyValues`);let o=t[i];if(void 0===o)return r.warnFunction?.(`Property ${i} cannot have a value of undefined with the ${a} operator`),"is_not"===a;if(null===o&&!tR.includes(a)&&"exact"!==a&&"is_not"!==a)return r.warnFunction?.(`Property ${i} cannot have a value of null with the ${a} operator`),!1;let l=(e,t)=>{if(function e(t){if("boolean"==typeof t)return!0;if("string"==typeof t){let e=t.toLowerCase();return"true"===e||"false"===e}if(!Array.isArray(t))return!1;for(let r=0;r<t.length;r++)if(!e(r in t?t[r]:null))return!1;return!0}(e))return!function e(t,r=new Set){if(null!==t&&"boolean"!=typeof t){if("string"==typeof t)return void tj(t);if("number"==typeof t){if(!Number.isFinite(t))throw new tT(`Cannot represent non-finite number ${t} like the flags service`);return}if(Array.isArray(t)){if(r.has(t))throw new tT("Cannot represent a circular array during local evaluation");r.add(t);try{for(let i=0;i<t.length;i++)i in t&&e(t[i],r)}finally{r.delete(t)}return}if("object"==typeof t){let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&null!==i)throw new tT("Cannot represent a non-JSON object like the flags service");if(r.has(t))throw new tT("Cannot represent a circular object during local evaluation");r.add(t);try{for(let i of Object.keys(t))tj(i),e(t[i],r)}finally{r.delete(t)}return}throw new tT(`Cannot represent ${typeof t} like the flags service`)}}(t),tM(e)===tM(t);if(Array.isArray(e)){let r=tL(t).toLowerCase();return e.some(e=>tL(e).toLowerCase()===r)}return tL(e).toLowerCase()===tL(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}`)};switch(a){case"exact":return l(s,o);case"is_not":return!l(s,o);case"is_set":return!0;case"icontains":return tN(o).includes(tN(s));case"not_icontains":return!tN(o).includes(tN(s));case"starts_with":return tN(o).startsWith(tN(s));case"not_starts_with":return!tN(o).startsWith(tN(s));case"ends_with":return tN(o).endsWith(tN(s));case"not_ends_with":return!tN(o).endsWith(tN(s));case"regex":return tB(String(s))&&null!==String(o).match(String(s));case"not_regex":return tB(String(s))&&null===String(o).match(String(s));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,a);return u(String(o),String(s),a)}case"is_date_after":case"is_date_before":{if("boolean"==typeof s)throw new tT("Date operations cannot be performed on boolean values");let e=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(s));null==e&&(e=tW(s));let t=tW(o);return"is_date_before"===a?t<e:t>e}case"semver_eq":return 0===tH(tq(String(o),n),tq(String(s),n));case"semver_neq":return 0!==tH(tq(String(o),n),tq(String(s),n));case"semver_gt":return tH(tq(String(o),n),tq(String(s),n))>0;case"semver_gte":return tH(tq(String(o),n),tq(String(s),n))>=0;case"semver_lt":return 0>tH(tq(String(o),n),tq(String(s),n));case"semver_lte":return 0>=tH(tq(String(o),n),tq(String(s),n));case"semver_tilde":{let e,t=tq(String(o),n),{lower:r,upper:i}={lower:[(e=tq(String(s),n))[0],e[1],e[2]],upper:[e[0],e[1]+1,0]};return tH(t,r)>=0&&0>tH(t,i)}case"semver_caret":{let e=tq(String(o),n),{lower:t,upper:r}=function(e,t){let[r,i,s]=tq(e,t);return{lower:[r,i,s],upper:r>0?[r+1,0,0]:i>0?[0,i+1,0]:[0,0,s+1]}}(String(s),n);return tH(e,t)>=0&&0>tH(e,r)}case"semver_wildcard":{let e=tq(String(o),n),{lower:t,upper:r}=function(e,t){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new tT(`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 tU(r,e,t)}catch{}throw new tT(`Invalid wildcard semver: ${e}`)},a=s(i[0]);if(1===i.length)return{lower:[a,0,0],upper:[a+1,0,0]};let n=s(i[1]);return{lower:[a,n,0],upper:[a,n+1,0]}}(String(s),n);return tH(e,t)>=0&&0>tH(e,r)}default:throw new tT(`Unknown operator: ${a}`)}}(e,t,{warnFunction:r})}async function tX(e,t,r,i=!1,s){let a=String(e.value);if(!(a in r))throw new tJ(`cohort ${a} not found in local cohorts - likely a static cohort that requires server evaluation`);return t0(r[a],t,r,i,s)}async function t0(e,t,r,i=!1,s){if(!e)return!0;let a=e.type,n=e.values;if(!n||0===n.length)return!0;let o=!1;if("values"in n[0]){for(let e of n)try{let n=await t0(e,t,r,i,s);if("AND"===a){if(!n)return!1}else if(n)return!0}catch(t){if(t instanceof tJ)throw t;if(t instanceof tT)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0;else throw t}if(o)throw new tT("Can't match cohort without a given cohort property value");return"AND"===a}for(let e of n)try{let n;if("cohort"===e.type)n=await tX(e,t,r,i,s);else if("flag"===e.type){if(!s)throw new tT(`Flag dependency '${e.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);n=await s(e)}else n=tY(e,t);let o=e.negation||!1;if("AND"===a){if(!n&&!o||n&&o)return!1}else if(n&&!o||!n&&o)return!0}catch(t){if(t instanceof tJ)throw t;if(t instanceof tT)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0;else throw t}if(o)throw new tT("can't match cohort without a given cohort property value");return"AND"===a}let t1=["--unhandled-rejections","--unhandled_rejections"],t2=new Set(["throw","strict","warn","warn-with-error-code","none"]),t3=[...globalThis.process?.execArgv??[]],t4=globalThis.process?.env?.NODE_OPTIONS;function t5(e){let t;for(let r=0;r<e.length;r++){let i=e[r],s=t1.find(e=>i===e||i.startsWith(`${e}=`));if(!s)continue;let a=i===s?e[++r]:i.slice(s.length+1);t2.has(a)&&(t=a)}return t}let t6=function(e=t3,t=t4){return t5(e)??t5(function(e){let t=[],r="",i=!1;for(let s=0;s<e.length;s++){let a=e[s];"\\"===a&&i&&s+1<e.length?r+=e[++s]:" "!==a||i?'"'===a?i=!i:r+=a:r&&(t.push(r),r="")}return r&&t.push(r),t}(t??""))??"throw"}();function t8(e,t,r){e(t,{mechanism:{type:"unhandledRejection"===r?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function t9(e,t,r,i,s){if(t>r&&(i.warn("min cannot be greater than max."),t=r),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),t9(s??r,t,r,i)}class t7{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=t9(e.bucketSize,0,100,e._logger),this._refillRate=t9(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=t9(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 tp=ej;class re{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new t7({...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 y(e)&&"__posthog_previously_captured_error"in e&&!0===e.__posthog_previously_captured_error}static async buildEventMessage(e,t,r,i,s){let a={...s},n=e.buildFromUnknown(t,r);n.$exception_list=await e.modifyFrames(n.$exception_list);let o=tp.getInjectedReleaseId();return o&&(a.$release_id=o),{event:"$exception",distinctId:i,properties:{...n,...a},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(!function(t,r,i=t6){let s=globalThis.process;if(s){let a;if("strict"===i)return s.on("uncaughtExceptionMonitor",(e,r)=>t8(t,e,r));s.on("uncaughtException",(a=!1,Object.assign((i,s)=>{let n=e.g.process.listeners("uncaughtException").filter(e=>"domainUncaughtExceptionClear"!==e.name&&!0!==e._posthogErrorHandler).length;t8(t,i,s),a||0!==n||(a=!0,r(i))},{_posthogErrorHandler:!0})))}}(this.onException.bind(this),this.onFatalError.bind(this)),function(e,t=t6){let r=globalThis.process;r&&"throw"!==t&&"strict"!==t&&"warn-with-error-code"!==t&&r.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}(this.onException.bind(this)))}onException(e,t){this.client.addPendingPromise((async()=>{if(!re.isPreviouslyCapturedError(e)){let r=await re.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),i=r.properties,s=i?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(s)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:s}):this.client._capturePreparedEvent(r,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(2e3),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class rt{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=null!==t?t:void 0}constructor(){this._memoryStorage={}}}let rr="analytics";class ri extends Error{constructor({requestId:e,drops:t,retryExhausted:r,cause:i}){super(ri.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 rs(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 ra=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:rs},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:rs},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:rs},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(e){return"string"==typeof e?e:void 0}}],rn=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function ro(e,t,r){void 0===r||t in e||(e[t]=r)}function rl(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 ra)if(e in r){let a=s(r[e]);void 0!==a&&(i[t]=a),delete r[e]}let s={};for(let{property:e,field:t}of rn)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,ro(r,"$set",e.$set),ro(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 ru=new Set([408,500,502,503,504]);class rc{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=>U(t,e))),this.generateRequestId=t.generateRequestId??eU,this.compress=t.compress??e2}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(rl)};return r&&(i.historical_migration=!0),i}(e,{createdAt:r,historicalMigration:this.config.historicalMigration}),s=`${this.config.host}/i/v1/analytics/events`,a=[],n=i,o=Math.max(1,this.config.maxAttempts);for(let e=1;e<=o;e++){let i,l,c=e===o,h=u({created_at:r,...this.config.historicalMigration?{historical_migration:!0}:{},batch:n});try{let{response:r,signal:o}=i=await this.sendOnce(s,h,e,t),{status:u}=r;if(u<200||u>=300)if(!c&&ru.has(u)){let t=this.parseRetryAfter(r);await i.waitFor(i.cancelBody()).catch(()=>{}),l=this.backoffDelay(e,t)}else{let e=await this.buildHttpError(r,u,i.waitFor);return this.surfaceBatchFailure(t,a,n,e)}else{let s;try{s=await i.waitFor(this.parseResponse(r))}catch(e){if(o.aborted)throw e;return this.surfaceBatchFailure(t,a,n,Error(`Capture V1 returned an unparseable ${u} response body`))}let h=this.classify(n,s,a);if(0===h.length)return this.surfacePartialDrops(t,a);if(c)return void this.onError(new ri({requestId:t,drops:a,retryExhausted:h.map(e=>e.uuid)}));n=h;let d=this.parseRetryAfter(r);l=this.backoffDelay(e,d)}}catch(r){if(i&&!i.signal.aborted)throw r;if(c)return this.surfaceBatchFailure(t,a,n,r);l=this.backoffDelay(e)}finally{i?.cleanup()}void 0!==l&&await this.sleep(l)}}async sendOnce(e,t,r,i){let s,a=this.buildHeaders(r,i),n=t;if(this.config.compressionEnabled){let e=await this.compress(t,this.config.isDebug);null!==e&&(n=e,a["Content-Encoding"]="gzip")}let o=new AbortController,l="waiting for response headers",u=new Promise((e,t)=>{s=U(()=>{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:a,body:n,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 ri({requestId:e,drops:t,retryExhausted:r.map(e=>e.uuid),cause:i}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new ri({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}}let rh="ai-capture",rd="/i/v0/ai/batch/",rg=new TextEncoder;function rf(e){return rg.encode(u(e)).length}let rp=new Set;function ry(e,t){rp.has(e)||(rp.add(e),console.warn(`[PostHog] ${t}`))}class rm extends ts{constructor(e,t={}){const r=function(e){return"string"==typeof e?e.trim():""}(e),i={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:function(e){return("string"==typeof e?e.trim():"")||"https://us.i.posthog.com"}(t.host),personalApiKey:function(e){return("string"==typeof e?e.trim():"")||void 0}(t.secretKey??t.personalApiKey)};if(super(r,i),this._memoryStorage=new rt,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=function(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return"v0"===e||"v1"===e?e:"v0"}(),this.enableFullAiCapture=!0===i.enableFullAiCapture,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof i.featureFlagsPollingInterval?Math.max(i.featureFlagsPollingInterval,100):3e4,"number"==typeof i.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),"number"==typeof i.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),!this.disabled&&i.personalApiKey){if(i.personalApiKey.includes("phc_"))throw Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');!1!==i.enableLocalEvaluation&&(this.featureFlagsPoller=new tZ({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:r,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:e=>{this._events.emit("error",e)},onLoad:e=>{this._events.emit("localEvaluationFlagsLoaded",e)},onMinimalFlagCalledEvents:e=>{this._minimalFlagCalledEvents=e},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation,evaluationContexts:i.evaluationContexts??i.evaluationEnvironments}))}this.errorTracking=new re(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||5e4}enqueue(e,t,r,i){super.enqueue(e,t,r,i),this.scheduleDebouncedFlush()}async flush(){let e=this.flushWithPendingPromises(),t=this.options.waitUntil;if(t&&!this._waitUntilCycle)try{t(e.catch(()=>{}))}catch{}return e}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=U(()=>{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.flushWithPendingPromises()}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":rr}persistedQueueKeyForRoute(e){return e===rh?c.AiCaptureQueue:"ai"===e?c.AiQueue:c.Queue}getActiveQueueRoutes(){let e="v1"===this.captureMode?[rr,"ai"]:[rr];return this._aiCaptureRouteActive&&e.push(rh),e}getBatchEndpointPath(e){return e===rh?rd:super.getBatchEndpointPath(e)}async sendBatch(e,t,r=rr){if(r===rh)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=[],a=[],n=0;for(let o of e){if(void 0===o)continue;let e=rf(o);if(e>t){s.push({event:"string"==typeof o.event?o.event:"unknown",bytes:e});continue}a.length>0&&n+e>r&&(i.push(a),a=[],n=0),a.push(o),n+=e}return a.length>0&&i.push(a),{batches:i,dropped:s}}(e);for(let{event:e,bytes:t}of i){let r=`Event ${e} (${t} bytes) exceeds the 8MiB limit for ${rd}, 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,rh)}catch(i){if(!te(i))throw i;if(1===e.length){let[t]=e,r="string"==typeof t.event?t.event:"unknown",i=`Event ${r} (${rf(t)} bytes) was rejected with 413 by ${rd} 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 rc({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.51.6"}get metrics(){var e;let t;return this._metrics||(this._metrics=new tf(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}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}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:a,options:n})=>{let o={timestamp:n.timestamp,disableGeoip:n.disableGeoip,uuid:n.uuid},l={distinctId:t,event:i,properties:{...a,...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=j(e.uuid,eU);return this._sendPreparedAiEvent({...e,uuid:t},!1),t}async captureAiImmediate(e){if(this.disabled)return;let t=j(e.uuid,eU);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,rh)}identify({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:a,...n}=t;this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:i||n,$set_once:s||{},$anon_distinct_id:a??void 0},disableGeoip:r},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:a,...n}=t;await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:i||n,$set_once:s||{},$anon_distinct_id:a??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}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,a,n,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:g,disableGeoip:f}=r,{onlyEvaluateLocally:p,personProperties:y,groupProperties:m}=r,v=this.addLocalPersonAndGroupProperties(t,g,y,m);y=v.allPersonProperties,m=v.allGroupProperties;let _=this.createFeatureFlagEvaluationContext(t,g,this.personPropertiesForLocalEvaluation(t,y),m);void 0==p&&(p=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,_,{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}}}catch(t){if(t instanceof tJ||t instanceof tT)this._logger?.info(`${t.name} when computing flag locally: ${e}: ${t.message}`);else throw t}}if(!b&&!p){let t=await super.getFeatureFlagDetailsStateless(_.distinctId,_.groups,y,m,f,[e]);if(void 0===t)o=tA.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===t.minimalFlagCalledEvents,a=t.requestId,n=t.evaluatedAt;let r=[];t.errorsWhileComputingFlags&&r.push(tA.ERRORS_WHILE_COMPUTING),t.quotaLimited?.includes("feature_flags")&&r.push(tA.QUOTA_LIMITED);let i=t.flags[e];if(void 0===i)r.push(tA.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}}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:a,$feature_flag_evaluated_at:b?Date.now():n};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:g,disableGeoip:f,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){ry("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:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(void 0!==i)return!1!==i.enabled&&(i.variant??!0)}async getFeatureFlagPayload(e,t,r,i){if(ry("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:s?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):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){ry("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:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});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:a,flagKeys:n}=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,n),g={},f={},p=!0;if(d&&(g=d.response,f=d.payloads,p=d.fallbackToFlags),p&&!o){let e=await super.getFeatureFlagsAndPayloadsStateless(h.distinctId,h.groups,l,u,a,n);g={...g,...e.flags||{}},f={...f,...e.payloads||{}}}return void 0!==this._flagOverrides&&(g={...g,...this._flagOverrides}),void 0!==this._payloadOverrides&&(f={...f,...this._payloadOverrides}),{featureFlags:g,featureFlagPayloads:f}}async evaluateFlags(e,t){let r,i,{distinctId:s,options:a}=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 tO({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new tO({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,flags:{}});let{groups:n,disableGeoip:o}=a||{},l=a?.flagKeys??void 0;if(l?.length===0)return new tO({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:n,disableGeoip:o,flags:{}});let{onlyEvaluateLocally:u,personProperties:c,groupProperties:h}=a||{},d=this.addLocalPersonAndGroupProperties(s,n,c,h);c=d.allPersonProperties,h=d.allGroupProperties;let g=this.createFeatureFlagEvaluationContext(s,n,this.personPropertiesForLocalEvaluation(s,c),h);void 0==u&&(u=this.options.strictLocalEvaluation??!1);let f=l?new Set(l):void 0,p={},y=!1,m=!1,v=await this.featureFlagsPoller?.getAllFlagsAndPayloads(g,l),_=new Set;if(v)for(let[e,t]of Object.entries(v.response)){let r=this.featureFlagsPoller?.featureFlagsByKey[e];p[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:v.payloads[e],id:r?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:r?.has_experiment},_.add(e)}let b=void 0!==f&&Array.from(f).some(e=>this.featureFlagsPoller?.featureFlagsByKey[e]===void 0);if((!v||v.fallbackToFlags||b)&&!u){let e=await super.getFeatureFlagDetailsStateless(g.distinctId,g.groups,c,h,o,l);if(e)for(let[t,s]of(this._minimalFlagCalledEvents=!0===e.minimalFlagCalledEvents,r=e.requestId,i=e.evaluatedAt,y=!!e.errorsWhileComputingFlags,m=Array.isArray(e.quotaLimited)&&e.quotaLimited.includes("feature_flags"),Object.entries(e.flags))){let e;if(!_.has(t)){if(s.metadata?.payload!==void 0)try{e=JSON.parse(s.metadata.payload)}catch{e=s.metadata.payload}p[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 p[e];continue}let r=p[e];p[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=p[e];r&&(p[e]={...r,payload:t})}if(void 0!==f)for(let e of Object.keys(p))f.has(e)||delete p[e];return new tO({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:n,disableGeoip:o,flags:p,requestId:r,evaluatedAt:i,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:y,quotaLimited:m})}_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:a,properties:n}=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}`;t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(l)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[t]instanceof Set?this.distinctIdHasSentFlagCalls[t].add(l):this.distinctIdHasSentFlagCalls[t]=new Set([l]),this.capture({distinctId:t,event:"$feature_flag_called",properties:n,groups:s,disableGeoip:a}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(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,t,r):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??3e4),r=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await q(this._metrics.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._metrics.reset());try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},r?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let e=new AbortController;i=U(()=>{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,a]of Object.entries(e))if(P(a,"Object")&&t&&s in t){let e={};for(let[t,r]of Object.entries(a))e[String(t)]=String(r);i[String(s)]=e}else r[String(s)]=String(a);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||{},a=i?.groupProperties||{},n=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:a,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:n})}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:a,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:n})}return(await super.getFeatureFlagsStateless(e,t,s,a,r)).flags}addLocalPersonAndGroupProperties(e,t,r,i){let s={...r||{}},a={};if(t)for(let e of Object.keys(t))a[e]={$group_key:t[e],...i?.[e]||{}};return{allPersonProperties:s,allGroupProperties:a}}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(!re.isPreviouslyCapturedError(e)){let a=Error("PostHog syntheticException");this.addPendingPromise(re.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:a},t,r).then(e=>this._capturePreparedEvent({...e,uuid:i,flags:s},!1)))}}async captureExceptionImmediate(e,t,r,i){if(!re.isPreviouslyCapturedError(e)){let s=Error("PostHog syntheticException");return this.addPendingPromise(re.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,r).then(e=>this.captureImmediate({...e,flags:i})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:r,event:i,properties:s,groups:a,flags:n,sendFeatureFlags:o,timestamp:l,disableGeoip:u,uuid:c}=e,h=this.context?.get(),d=t.includeContextProperties??!0,g=r||h?.distinctId,f=d?{...this.props,...h?.properties||{},...s||{}}:{...s||{}};g||(g=eU(),f.$process_person_profile=!1),d&&h?.sessionId&&!f.$session_id&&(f.$session_id=h.sessionId);let p=this._shouldSendMinimalFlagCalledEvent(i,f)?eY(f):f,y=this._runBeforeSend({distinctId:g,event:i,properties:p,groups:a,flags:n,sendFeatureFlags:o,timestamp:l,disableGeoip:u,uuid:c});if(!y)return Promise.reject(null);let m=await Promise.resolve().then(async()=>{if(n)return o&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),n._getEventProperties();if(o){ry("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,u,"object"==typeof o?o: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 m.$raw_user_agent&&tk(m.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(y.event="$bot_pageview",m.$browser_type="bot"),{distinctId:y.distinctId,event:y.event,properties:m,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 tp=ej,rv=e.i(78500);class r_{constructor(){this.storage=new rv.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,r){return this.storage.run(this.resolve(e,r),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let r=this.get()||{};return{distinctId:e.distinctId??r.distinctId,sessionId:e.sessionId??r.sessionId,properties:{...r.properties||{},...e.properties||{}}}}}var rb=e.i(27028);let rw=(0,e.i(12057).promisify)(rb.gzip);async function rE(e,t=!0){try{let t=await rw(e);return new Uint8Array(t)}catch(e){return t&&console.error("Failed to gzip compress data",e),null}}var tp=ej;let rF="posthog-node";function rP(e,{organization:t,projectId:r,prefix:i,severityAllowList:s=["error"],sendExceptionsToPostHog:a=!0}={}){return n=>{if(!("*"===s||s.includes(n.level)))return n;n.tags||(n.tags={});let o=n.tags[rS.POSTHOG_ID_TAG];if(void 0===o)return n;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${o}`,l).toString();n.tags["PostHog Person URL"]=u;let c=n.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||n.message,$exception_type:c[0]?.type,$exception_level:n.level,$exception_list:h,$sentry_event_id:n.event_id,$sentry_exception:n.exception,$sentry_exception_message:c[0]?.value||n.message,$sentry_exception_type:c[0]?.type,$sentry_tags:n.tags},g=tp.getInjectedReleaseId();return g&&(d.$release_id=g),t&&r&&(d.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+n.event_id),a&&e.capture({event:"$exception",distinctId:o,properties:d}),n}}function rx(e,t){let r=rP(e,t);return{name:rF,processEvent:e=>r(e)}}class rS{static #e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,r,i,s){this.name=rF,this.name=rF,this.setupOnce=function(a,n){a(rP(e,{organization:t,projectId:n()?.getClient()?.getDsn()?.projectId,prefix:r,severityAllowList:i,sendExceptionsToPostHog:s??!0}))}}}e.s(["PostHogSentryIntegration",0,rS,"createEventProcessor",0,rP,"sentryIntegration",0,rx],92164);let r$=/[\x00-\x1f\x7f-\x9f]/g;function rC(e,t,r){null!=r&&""!==r&&(e[t]=r)}function rI(e){return Array.isArray(e)?e[0]:e}function rk(e){if(Array.isArray(e)){for(let t of e){let e=rk(t);if(void 0!==e)return e}return}if("string"!=typeof e)return;let t=e.replace(r$,"").trim();if(t)return t.length>1e3?t.slice(0,1e3):t}function rA(e,t){var r,i;let s,{sessionId:a,distinctId:n}=function(e){if(!e)return{};let t=rk(e["x-posthog-session-id"]),r=rk(e["x-posthog-distinct-id"]);return{...void 0!==t?{sessionId:t}:{},...void 0!==r?{distinctId:r}:{}}}(t.headers),o={},l=!0===e.options.disable_capture_url_hashes;return rC(o,"$current_url",(r=t.originalUrl||t.url,l?L(r):r)),rC(o,"$request_method",t.method),rC(o,"$request_path",(i=t.path,s=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),l?L(s):s)),rC(o,"$user_agent",rI(t.headers["user-agent"])),rC(o,"$ip",function(e){let t=rI(e.headers["x-forwarded-for"]);if(t){let e=t.split(",")[0].trim();if(e)return e}return e.socket?.remoteAddress}(t)),{...void 0!==a?{sessionId:a}:{},...void 0!==n?{distinctId:n}:{},properties:o}}function rO(e,t){var r;t.use((r=e,(e,t,i)=>{r.withContext(rA(r,e),()=>i())}))}function rR(e,t){var r;t.use((r=e,(e,t,i,s)=>{if(re.isPreviouslyCapturedError(e))return void s(e);let a=rA(r,t),n=Error("Synthetic exception"),o={...void 0!==a.sessionId?{$session_id:a.sessionId}:{},...a.properties||{},$response_status_code:i.statusCode};r.addPendingPromise(re.buildEventMessage(r.getErrorPropertiesBuilder(),e,{mechanism:{type:"middleware",handled:!1},syntheticException:n},a.distinctId,o).then(e=>r._capturePreparedEvent(e,!1))),s(e)}))}e.s(["setupExpressErrorHandler",0,rR,"setupExpressRequestContext",0,rO],88512),e.s([],52538);class rT extends rm{getLibraryId(){return"posthog-node"}compressPayload(e){return rE(e,this.isDebug)}initializeContext(){return new r_}createErrorPropertiesBuilder(){let e;return new tp.ErrorPropertiesBuilder([new tp.EventCoercer,new tp.ErrorCoercer,new tp.ObjectCoercer,new tp.StringCoercer,new tp.PrimitiveCoercer],tp.createStackParser("node:javascript",tp.nodeStackLineParser),[(e=function(e=process.argv[1]?(0,o.dirname)(process.argv[1]):process.cwd(),t="\\"===o.sep){let r=t?l(e):e;return e=>{if(!e)return;let i=t?l(e):e,{dir:s,base:a,ext:n}=o.posix.parse(i);(".js"===n||".mjs"===n||".cjs"===n)&&(a=a.slice(0,-1*n.length));let u=decodeURIComponent(a);s||(s=".");let c=s.lastIndexOf("/node_modules");if(c>-1)return`${s.slice(c+14).replace(/\//g,".")}:${u}`;if(s.startsWith(r)){let e=s.slice(r.length+1).replace(/\//g,".");return e?`${e}:${u}`:u}return u}}(),async t=>{for(let r of t)r.module=e(r.filename);return t}),e=>tE(e,void 0,this._logger),function(e=process.cwd()){o.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,o.isAbsolute)(i.filename)&&(i.filename=t((0,o.relative)(r,t(i.filename))));return e}}()])}}e.s(["PostHog",0,rT],89767),e.i(89767),e.i(52538),e.i(92164),e.i(88512),e.i(88096),e.s(["FeatureFlagError",0,h,"FeatureFlagEvaluations",0,tO,"PostHogSentryIntegration",0,rS,"cookieStateToProperties",0,eG,"cookieStoreFromHeader",0,eH,"createEventProcessor",0,rP,"getPostHogCookieName",0,eW,"parsePostHogCookie",0,eK,"readPostHogCookie",0,eV,"sentryIntegration",0,rx,"serializePostHogCookie",0,ez,"setupExpressErrorHandler",0,rR,"setupExpressRequestContext",0,rO,"uuidv7",0,eU],92349),e.i(92349),e.s(["FeatureFlagError",0,h,"FeatureFlagEvaluations",0,tO,"PostHog",0,rT,"PostHogSentryIntegration",0,rS,"cookieStateToProperties",0,eG,"cookieStoreFromHeader",0,eH,"createEventProcessor",0,rP,"getPostHogCookieName",0,eW,"parsePostHogCookie",0,eK,"readPostHogCookie",0,eV,"sentryIntegration",0,rx,"serializePostHogCookie",0,ez,"setupExpressErrorHandler",0,rR,"setupExpressRequestContext",0,rO,"uuidv7",0,eU],39702)}];
1
+ module.exports=[39702,e=>{"use strict";let t,r,i,s,n;var a,o=e.i(14747);function l(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var u=((a={}).AnonymousId="anonymous_id",a.DistinctId="distinct_id",a.Props="props",a.EnablePersonProcessing="enable_person_processing",a.PersonMode="person_mode",a.FeatureFlagDetails="feature_flag_details",a.FeatureFlags="feature_flags",a.FeatureFlagPayloads="feature_flag_payloads",a.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",a.BootstrapFeatureFlags="bootstrap_feature_flags",a.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",a.OverrideFeatureFlags="override_feature_flags",a.Queue="queue",a.AiQueue="ai_queue",a.AiCaptureQueue="ai_capture_queue",a.LogsQueue="logs_queue",a.OptedOut="opted_out",a.SessionId="session_id",a.SessionStartTimestamp="session_start_timestamp",a.SessionLastTimestamp="session_timestamp",a.PersonProperties="person_properties",a.GroupProperties="group_properties",a.InstalledAppBuild="installed_app_build",a.InstalledAppVersion="installed_app_version",a.SessionReplay="session_replay",a.PushRegistered="push_registered",a.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",a.SurveyLastSeenDate="survey_last_seen_date",a.SurveysSeen="surveys_seen",a.Surveys="surveys",a.RemoteConfig="remote_config",a.FlagsEndpointWasHit="flags_endpoint_was_hit",a.DeviceId="device_id",a);let c={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",TIMEOUT:"timeout",CONNECTION_ERROR:"connection_error",UNKNOWN_ERROR:"unknown_error",apiError:e=>`api_error_${e}`};function h(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 d=Array.isArray,g=Object.prototype;g.hasOwnProperty;let p=g.toString,f=d||function(e){return"[object Array]"===p.call(e)},m=e=>e===Object(e)&&!f(e),y=e=>void 0===e,_=e=>"[object String]"==p.call(e),v=e=>_(e)&&0===e.trim().length,b=e=>null===e,w=e=>y(e)||b(e),S=e=>"[object Number]"==p.call(e)&&e==e;function x(e){return null===e||"object"!=typeof e}function E(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function F(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 I(e,Error)}}function P(e){return"u">typeof Event&&I(e,Event)}function I(e,t){try{return e instanceof t}catch{return!1}}let A="Android",C="BlackBerry",$="Nintendo",k="PlayStation",O="Xbox",M="Windows",T="(\\d+(\\.\\d+)?)";RegExp("Version/"+T),RegExp("(Claude|Codex|ChatGPT)\\/"+T),RegExp(O,"i"),RegExp(k+" \\w+","i"),RegExp($+" \\w+","i"),RegExp(C+"|PlayBook|BB10","i");RegExp("rv:"+T),RegExp("Edge?\\/"+T),RegExp("(Chrome|CrMo)\\/"+T),RegExp("CriOS\\/"+T),RegExp("(UCBrowser|UCWEB)\\/"+T),RegExp("(Opera|OPR)\\/"+T),RegExp("Firefox\\/"+T),RegExp("FxiOS\\/"+T),RegExp("Konqueror[:/]?"+T,"i"),RegExp(C+" "+T),RegExp("android\\s"+T,"i"),RegExp("SamsungBrowser\\/"+T),RegExp("OculusBrowser\\/"+T),RegExp("Vivaldi\\/"+T),RegExp("YaBrowser\\/"+T),RegExp("Whale\\/"+T),RegExp("Brave\\/"+T),RegExp("(DuckDuckGo|Ddg)\\/"+T),RegExp("PaleMoon\\/"+T),RegExp("Waterfox\\/"+T),RegExp("GSA\\/"+T),RegExp("(rv:|MSIE )"+T),RegExp("rv:"+T),RegExp(O+"; "+O+" (.*?)[);]","i"),RegExp($,"i"),RegExp(k,"i"),RegExp(M,"i"),RegExp("("+A+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+A+")","i");let R=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function D(e,t){return"string"==typeof e&&R.test(e)?e:t()}function j(e,t){let r=Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function B(e){return e?e.split("#")[0]:e}async function L(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 N(){return new Date().toISOString()}function q(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}async function U(e,t,r){let i;try{return await Promise.race([e,new Promise((e,s)=>{i=q(()=>{try{r?.(),e()}catch(e){s(e)}},t)})])}finally{clearTimeout(i)}}function z(e){return Promise.all(e.map(e=>(e??Promise.resolve()).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}class H{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&&f(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;return null!=e.cause&&(r=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack&&(i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),{...e,cause:r,stack:i}}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={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};e.stack&&(r.stacktrace={type:"raw",frames:e.stack});let i=[r];return null!=e.cause&&i.push(...this.convertToExceptionList(e.cause,{...t,handled:!0})),i}buildParsingContext(e){return{chunkIdMap:function(e){let s=globalThis._posthogChunkIds;if(!s)return;let n=Object.keys(s);return i&&n.length===r?i:(r=n.length,i=n.reduce((r,i)=>{t||(t={});let n=t[i];if(n)r[n[0]]=n[1];else{let n=e(i);for(let e=n.length-1;e>=0;e--){let a=n[e],o=a?.filename,l=s[i];if(o&&l){r[o]=l,t[i]=[o,l];break}}}return r},{}))}(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,r=0){let i=(r,i)=>{if(i<=4){let s=this.buildCoercingContext(e,t,i);return this.applyCoercers(r,s)}};return{...t,syntheticException:0==r?t.syntheticException:void 0,mechanism:e,apply:e=>i(e,r),next:e=>i(e,r+1)}}}e.s(["ErrorPropertiesBuilder",0,H],69309);let W=/^([a-z][a-z0-9.+-]+):/i,V=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function K(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=W.exec(e);return!t||V.includes(t[1].toLowerCase())}(t)};return y(i)||(n.lineno=i),y(s)||(n.colno=s),n}let G=(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]},Q=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,J=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Z=/\((\S*)(?::(\d+))(?::(\d+))\)/,Y=(e,t)=>{let r=Q.exec(e);if(r){let[,e,i,s]=r;return K(t,e,"?",+i,+s)}let i=J.exec(e);if(i){if(i[2]&&0===i[2].indexOf("eval")){let e=Z.exec(i[2]);e&&(i[2]=e[1],i[3]=e[2],i[4]=e[3])}let[e,r]=G(i[1]||"?",i[2]);return K(t,r,e,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},X=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ee=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,et=(e,t)=>{let r=X.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let e=ee.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]=G(i,e),K(t,e,i,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}},er=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ei=(e,t)=>{let r=er.exec(e);return r?K(t,r[2],r[1]||"?",+r[3],r[4]?+r[4]:void 0):void 0},es=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,en=(e,t)=>{let r=es.exec(e);return r?K(t,r[2],r[3]||"?",+r[1]):void 0},ea=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,eo=(e,t)=>{let r=ea.exec(e);return r?K(t,r[5],r[3]||r[4]||"?",+r[1],+r[2]):void 0},el=/^\s*[-]{4,}$/,eu=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,ec=/^Promise\.(?:all|any)$/,eh=/^index \d+$/,ed=(e,t)=>{let r=e.match(eu);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]),ec.test(s)&&eh.test(o||"")&&(o="node:internal/promise"),{filename:o?decodeURI(o):void 0,module:void 0,function:s,lineno:eg(r[3]),colno:eg(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(el))return{filename:e,platform:t}};function eg(e){return parseInt(e||"",10)||void 0}let ep=/\(error: (.*)\)/;function ef(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function em(e,t){let r=t.start;for(;r>0&&ef(e[r-1],e[r-1+t.length]);)r--;return t.start-r}function ey(e,t){let r=t.start+t.length,i=r;for(;i<e.length&&ef(e[i],e[i-t.length]);)i++;return i-r}function e_(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,50).map(e=>{var r;return{...e,filename:e.filename||((r=t)[r.length-1]||{}).filename,function:e.function||"?"}})}function ev(){return eb("web:javascript",Y,et)}function eb(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=ep.test(i)?i.replace(ep,"$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(!ef(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?em(e,r):0);for(let r of t)i-=ey(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=em(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=ey(e,t);i&&e.splice(r+i===e.length?r:t.start,i)}(s,e);return 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),e_(s)}}e.s(["createDefaultStackParser",0,ev,"createStackParser",0,eb,"reverseAndStripFrames",0,e_],10728);class ew{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let r=_(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return E(e,"DOMException")}isDOMError(e){return E(e,"DOMError")}}e.s(["DOMExceptionCoercer",0,ew],33603);class eS{match(e){return!!E(e,"ErrorEvent")&&(void 0!=e.error||this._hasUsableMessage(e))}coerce(e,t){if(void 0!=e.error)return t.apply(e.error);let r=t.apply(e.message);return{...r,stack:this._buildLocationStack(e)??r.stack,synthetic:!0}}_hasUsableMessage(e){return _(e.message)&&e.message.length>0}_buildLocationStack(e){let t=e.lineno??0,r=e.colno??0;if(_(e.filename)&&0!==e.filename.length&&0!==t)return`Error
2
+ at ${e.filename}:${t}:${r}`}}e.s(["ErrorEventCoercer",0,eS],60887);let ex=["fatal","error","warning","log","info","debug"];function eE(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 eF{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(P(e))return e.constructor.name;let t="name"in e?e.name:void 0;return _(t)&&!v(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=eE(e);return`${t&&"Object"!==t?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return _(e)&&!v(e)&&ex.indexOf(e)>=0}getStack(e){try{if(_(e.stacktrace)&&e.stacktrace.length>0)return e.stacktrace;return _(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(F(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,eF],12154);class eP{match(e){return P(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${eE(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["EventCoercer",0,eP],41324);class eI{match(e){return x(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,eI],79478);class eA{match(e){return E(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!P(e))return!1;try{let t=e.detail;return null!=t&&"object"==typeof t&&"reason"in t}catch{return!1}}coerce(e,t){let r=this.getUnhandledRejectionReason(e);return x(r)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(r)}`,stack:t.syntheticException?.stack,synthetic:!0}:t.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&null!=e.detail&&"object"==typeof e.detail&&"reason"in e.detail)return e.detail.reason}catch{}return e}}e.s(["PromiseRejectionEventCoercer",0,eA],1802),e.s([],59567);let eC={MESSAGE:"$message",TIMESTAMP:"$timestamp"},e$=new Set([eC.MESSAGE,eC.TIMESTAMP]),ek={enabled:!0,max_bytes:32768};function eO(e){return e?{enabled:e.enabled??ek.enabled,max_bytes:function(e,t){if(!S(e)||1/0===e||-1/0===e)return t;let r=Math.floor(e);return r<0?t:r}(e.max_bytes,ek.max_bytes)}:{...ek}}function eM(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((r,i)=>(e$.has(i)?t.push(i):r[i]=e[i],r),{}),droppedKeys:t}}class eT{constructor(e){this._entries=[],this._totalBytes=0,this._config=eO(e)}setConfig(e){this._config=eO(e),this._trimToMaxBytes()}add(e){let t=function(e){let t;try{t=h(e)}catch{return}try{let e=JSON.parse(t);if(!m(e))return;let r=e[eC.MESSAGE],i=e[eC.TIMESTAMP];if(!_(r)||0===r.trim().length||!_(i)&&!S(i))return;return{step:e,json:t}}catch{return}}(e);if(!t)return;let r=eR(t.json);r>this._config.max_bytes||(this._entries.push({step:t.step,bytes:r}),this._totalBytes+=r,this._trimToMaxBytes())}getAttachable(){return this._entries.map(e=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}}function eR(e){if("u">typeof TextEncoder)return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let e=0;e<t.length;e++)"%"===t[e]?(r+=1,e+=2):r+=1;return r}e.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,ek,"EXCEPTION_STEP_INTERNAL_FIELDS",0,eC,"ExceptionStepsBuffer",0,eT,"getUtf8ByteLength",0,eR,"resolveExceptionStepsConfig",0,eO,"stripReservedExceptionStepFields",0,eM],45162),e.s([],21754),e.i(21754),e.i(69309),e.i(10728),e.s(["chromeStackLineParser",0,Y,"createDefaultStackParser",0,ev,"createStackParser",0,eb,"geckoStackLineParser",0,et,"nodeStackLineParser",0,ed,"opera10StackLineParser",0,en,"opera11StackLineParser",0,eo,"reverseAndStripFrames",0,e_,"winjsStackLineParser",0,ei],22546),e.i(22546),e.i(59567),e.i(33603);class eD{match(e){return F(e)}coerce(e,t){let r=this.getStack(e);return{type:this.getType(e),value:this.getMessage(e,t),stack:r??t.syntheticException?.stack,cause:e.cause?t.next(e.cause):void 0,synthetic:void 0===r}}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){return e.stacktrace||e.stack||void 0}}e.s(["ErrorCoercer",0,eD],13446),e.i(13446),e.i(60887);let ej=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class eB{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(ej);return i&&(t=i[1],r=i[2]),[t,r]}}e.s(["StringCoercer",0,eB],22175),e.i(22175),e.i(12154),e.i(41324),e.i(79478),e.i(1802),e.s(["DOMExceptionCoercer",0,ew,"ErrorCoercer",0,eD,"ErrorEventCoercer",0,eS,"EventCoercer",0,eP,"ObjectCoercer",0,eF,"PrimitiveCoercer",0,eI,"PromiseRejectionEventCoercer",0,eA,"StringCoercer",0,eB],90166),e.i(90166);class eL{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)}}}function eN(){let e=globalThis._posthogReleaseId;return"string"==typeof e&&e.length>0?e:void 0}e.s(["ReduceableCache",0,eL],45294),e.i(45294),e.i(45162),e.s(["getInjectedReleaseId",0,eN],56168),e.i(56168),e.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,ek,"DOMExceptionCoercer",0,ew,"EXCEPTION_STEP_INTERNAL_FIELDS",0,eC,"ErrorCoercer",0,eD,"ErrorEventCoercer",0,eS,"ErrorPropertiesBuilder",0,H,"EventCoercer",0,eP,"ExceptionStepsBuffer",0,eT,"ObjectCoercer",0,eF,"PrimitiveCoercer",0,eI,"PromiseRejectionEventCoercer",0,eA,"ReduceableCache",0,eL,"StringCoercer",0,eB,"chromeStackLineParser",0,Y,"createDefaultStackParser",0,ev,"createStackParser",0,eb,"geckoStackLineParser",0,et,"getInjectedReleaseId",0,eN,"getUtf8ByteLength",0,eR,"nodeStackLineParser",0,ed,"opera10StackLineParser",0,en,"opera11StackLineParser",0,eo,"resolveExceptionStepsConfig",0,eO,"reverseAndStripFrames",0,e_,"stripReservedExceptionStepFields",0,eM,"winjsStackLineParser",0,ei],11168);var eq=e.i(11168);let eU="0123456789abcdef";class ez{constructor(e){this.bytes=e}static ofInner(e){if(16===e.length)return new ez(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 ez(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 ez(e)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=eU.charAt(this.bytes[t]>>>4),e+=eU.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+=eU.charAt(this.bytes[t]>>>4),e+=eU.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 ez(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 eH{constructor(e){this.timestamp=0,this.counter=0,this.random=e??eW()}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 ez.fromFieldsV7(this.timestamp,Math.trunc(this.counter/0x40000000),this.counter&0x40000000-1,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,ez.ofInner(e)}}let eW=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),eV=()=>eK().toString(),eK=()=>(s||(s=new eH)).generate();function eG(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 eQ(e){let t=e.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${t}_posthog`}function eJ(e){let t=Date.now();return JSON.stringify({distinct_id:e,$device_id:e,$user_state:"anonymous",$sesid:[t,eV(),t]})}function eZ(e,t){let r=eQ(t),i=e.get(r);return i?eX(i.value):null}function eY(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 eX(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||"object"!=typeof t||!t.distinct_id)return null;let r=f(t.$sesid)?t.$sesid[1]:void 0;return{distinctId:String(t.distinct_id),isIdentified:"identified"===t.$user_state,sessionId:"string"==typeof r?r:void 0,deviceId:"string"==typeof t.$device_id?t.$device_id:void 0}}catch{return null}}let e0=e=>void 0===e?void 0:e.variant??e.enabled,e1=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}},e2=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],e3=(e,t=[])=>{let r={},i=t=>{void 0!==e[t]&&(r[t]=e[t])};return e2.forEach(i),t.forEach(i),r};class e5{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 e4=e=>{throw j("NativeGzipValidationError",`Native gzip produced invalid output: ${e}`)},e6=async(e,t)=>{e.size<18&&e4("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());r.length>=2&&31===r[0]&&139===r[1]&&8===r[2]||e4("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)&&e4("invalid-crc");let s=t.length>>>0;i.getUint32(4,!0)!==s&&e4("invalid-size")};async function e8(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 e6(a,t),a}catch(e){if(r?.rethrow)throw e;return t&&console.error("Failed to gzip compress data",e),null}}class e9{add(e){let t=eV(),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 e7=(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=>e7(`${e} ${i}`,t,r)}};class te{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 tt 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 function(e,t=Date.now()){if("string"!=typeof e||!e)return;let r=e.trim(),i=/^\d+\s*,/.test(r)?r.slice(0,r.indexOf(",")).trim():r;if(/^\d+$/.test(i)){let e=1e3*Math.min(Number(i),300);return e>0?e:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(i))return;let s=Date.parse(/^\w{3} \w{3} /.test(i)?i+" GMT":i)-t;if(Number.isFinite(s)&&!(s<=0))return Math.min(s,3e5)}(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=j("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e,t=new Promise((e,t)=>{this.responseBodyTimer=q(()=>{this._bodyReadTimedOut=!0;let e=j("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 tr extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}async function ti(e){if(e instanceof tt){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 ts(e){return e instanceof tr}function tn(e){if(e instanceof tt)return 502===e.status||504===e.status;if(!(e instanceof tr))return!1;let t=e.error;return"ECONNREFUSED"!==(t?.code??t?.cause?.code)}function ta(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 to(e){return"object"==typeof e&&e instanceof tt&&413===e.status}function tl(e){return e instanceof tt?408===e.status||429===e.status||e.status>=500:ts(e)}function tu(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}let tc="default";class th{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new H([new eD,new eF,new eB,new eI],ev())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new e9,this._events=new e5,this._isInitialized=!1;const r="string"==typeof e?e.trim():"",i="string"==typeof t.host?t.host.trim():"",s=!r;this._logger=function(e,t=e=>e()){return e7(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's api key. The client will be disabled."),this.apiKey=r,this.host=function(e){return e?.replace(/\/+$/,"")}(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:tl},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(u.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(u.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(u.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={...t,...this.getCommonEventProperties()};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=e3(r)),{distinct_id:e.distinct_id,event:e.event,properties:r}}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.apiKey}/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.apiKey,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={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(o)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,l,{type:"required",consume:e=>e.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:tn},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,e0(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?e1(r):void 0]}));return{...e,featureFlags:r,featureFlagPayloads:i}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([e,t])=>[e,e1(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 tt)return{type:"api_error",statusCode:e.status};if(e instanceof tr){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=e0(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.apiKey}`,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(u.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(u.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(u.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return tc}persistedQueueKeyForRoute(e){return u.Queue}getActiveQueueRoutes(){return[tc]}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=q(()=>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=tu(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=D(s.uuid,eV),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:N(),uuid:D(t?.uuid,eV)};return(t?.disableGeoip??this.disableGeoip)&&(tu(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 ti(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(()=>z([t])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),z([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 e8(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,t,r=tc){let i={api_key:this.apiKey,batch:e.map(e=>{if(!e)return e;let t=this.normalizeTimestampForWire(e.timestamp);return t===e.timestamp?e:{...e,timestamp:t}}),sent_at:N()};this.historicalMigration&&(i.historical_migration=!0);let s=h(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=>!to(e)&&tl(e)};try{await this.sendBatch(a,l,e)}catch(e){if(to(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 tr||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=ta(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.apiKey)}`,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.apiKey}`},...null!==a&&{"Content-Encoding":"gzip"}},body:o};try{return await this.fetchWithRetry(n,l,{type:"successful-write"},{retryCheck:e=>!to(e)&&(!(e instanceof tt)||void 0===e.retryAfterMs)&&tl(e)}),{kind:"ok"}}catch(e){if(to(e))return{kind:"too-large"};if(tl(e)){let t=e instanceof tt?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=ta(t.body?t.body:""),a={...this._retryOptions,...i},o=0;return await L(async()=>{let i,a,l;o++;let u=new AbortController,c=s??this.requestTimeout,h=Date.now()+c,d=new Promise((e,t)=>{i=q(()=>{let e=j("AbortError",`Request timed out after ${c}ms`);t(e),u.abort(e)},c)}),g=!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 tr(e)}i.then(e=>{u.signal.aborted&&!g&&Promise.resolve(e.body?.cancel()).catch(()=>{})}).catch(()=>{});try{a=await Promise.race([i,d]),g=!0}catch(e){throw new tr(e)}let s="no-cors"===t.mode,o="successful-write"===r.type?300:400;if(!s&&(a.status<200||a.status>=o))throw new tt(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 tr(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 tt&&e.cancelResponseBody(),t}})}async _shutdown(e=3e4){await this._initPromise;let t=!1;if(this.clearFlushTimer(),!this.disabled)return U((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 tt||ts(e))))throw e;await ti(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 td="[Circular]",tg="[Truncated]",tp="[Unserializable]";function tf(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 tm(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=tp}Object.defineProperty(e,i,{value:r,enumerable:!0,writable:!0,configurable:!0})}return e}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let ty=Object.prototype.propertyIsEnumerable;function t_(e,t){try{return tv(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function tv(e,t,r,i){let s=[];for(let n in e)if(ty.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(b(a)||y(a))continue;s.push({key:tf(n),value:function e(t,r,i,s){if(i.remainingNodes<=0)return{stringValue:tg};if(i.remainingNodes--,"[object Boolean]"===p.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:tf(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:td};if(s>=20)return{stringValue:tg};if(t instanceof Date){let e=Number.isFinite(t.getTime())?t.toISOString():String(t);return{stringValue:"string"==typeof e?tf(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(f(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(w(a))continue;n.push(e(a,r,i,s))}catch{n.push({stringValue:tp})}return t.length>o&&n.push({stringValue:tg}),n}(t,r,i,s+1)}};return{kvlistValue:{values:tv(t,r,i,s+1)}}}finally{i.ancestors.delete(t)}}return{stringValue:tf(String(t))}}(a,t,r,i)})}catch{s.push({key:tf(n),value:{stringValue:tp}})}}return s}function tb(e,t,r){return{...tm({},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 tS(e,t){let r=tm({},e),i={};for(let e of tw)Object.prototype.hasOwnProperty.call(r,e)&&(i[e]=r[e],delete r[e]);return[...t_(r,t),...t_(i,t)]}let tx={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"};class tE{constructor(e){this._onFire=e,this._firesAt=0}get pending(){return!!this._timer}arm(e){this.clear(),this._firesAt=Date.now()+e,this._timer=q(()=>{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 tF(){return .75+.25*Math.random()*2}function tP(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 tI=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function tA(e){return String(e)+"000000"}function tC(e,t,r,i){let s="";return i&&(s=Object.keys(i).sort().map(e=>`${JSON.stringify(e)}:${JSON.stringify(i[e])}`).join(",")),`${e}\u0000${t}\u0000${r??""}\u0000${s}`}class t${constructor(e,t,r){this._instance=e,this._config=t,this._logger=r,this._series=new Map,this._flushTimer=new tE(()=>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._retryAfter=new te,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})}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._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=1,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){let t,r;if(this._instance.isDisabled||this._instance.optedOut)return;let i=this._runBeforeSend(e);if(null===i)return;if(!i.name||"string"!=typeof i.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof i.value||!Number.isFinite(i.value))return void this._logger.warn(`Dropping metric '${i.name}': value must be a finite number`);if("count"===i.type&&i.value<0)return void this._logger.warn(`Dropping count '${i.name}': counters are monotonic, value must be >= 0`);try{t=i.attributes?{...i.attributes}:void 0,r=tC(i.type,i.name,i.unit,t)}catch(e){this._logger.warn(`Dropping metric '${i.name}': attributes could not be serialized`,e);return}let s=this._series.get(r);if(!s){if(!this._admitNewSeries())return;s={name:i.name,type:i.type,unit:i.unit,attributes:t,windowStartMs:Date.now()},this._series.set(r,s)}let n=this._typeByName.get(i.name);void 0===n?this._typeByName.set(i.name,i.type):n===i.type||this._typeCollisionWarned.has(i.name)||(this._typeCollisionWarned.add(i.name),this._logger.warn(`Metric name '${i.name}' is already used as a ${n}; recording it as a ${i.type} too will blend both series in charts. Use a distinct name.`)),this._fold(s,i.value),this._armFlushTimer()}_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)}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:Array(tI.length+1).fill(0)});let r=e.hist;r.count+=1,r.sum+=t,r.min=Math.min(r.min,t),r.max=Math.max(r.max,t),r.bucketCounts[function(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}(t,tI)]+=1}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=f(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(tP(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._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,r=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t===this._generation)switch(this._retryAfter.record(r),"retry-later"===r.kind?(this._consecutiveFlushFailures++,this._flushJitter=tF()):(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:tS(r)},scopeMetrics:[{scope:{name:i,version:s},metrics:t}]}]}}_buildMetrics(e){let t=tA(Date.now()),r=new Map;for(let i of e.values()){let e=tC(i.type,i.name,i.unit,void 0),s=r.get(e);s||(s={name:i.name,...i.unit&&{unit:i.unit}},"count"===i.type?s.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===i.type?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:1,dataPoints:[]},r.set(e,s));let n=t_(i.attributes??{},this._logger),a=tA(i.windowStartMs);if("count"===i.type){let e={attributes:n,startTimeUnixNano:a,timeUnixNano:t,asDouble:i.total??0};s.sum.dataPoints.push(e)}else if("gauge"===i.type){let e={attributes:n,timeUnixNano:t,asDouble:i.last??0};s.gauge.dataPoints.push(e)}else if(i.hist){let e={attributes:n,startTimeUnixNano:a,timeUnixNano:t,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:tI};s.histogram.dataPoints.push(e)}}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.type){case"count":e.total=(e.total??0)+(r.total??0);break;case"gauge":break;case"histogram":if(r.hist)if(e.hist){e.hist.count+=r.hist.count,e.hist.sum+=r.hist.sum,e.hist.min=Math.min(e.hist.min,r.hist.min),e.hist.max=Math.max(e.hist.max,r.hist.max);for(let t=0;t<e.hist.bucketCounts.length;t++)e.hist.bucketCounts[t]+=r.hist.bucketCounts[t]}else e.hist=r.hist}}}}let tk="0".repeat(32),tO="0".repeat(16),tM=/^[0-9a-f]+$/;function tT(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 tR(e,t,r){return"string"==typeof e&&e.length===t&&e!==r&&tM.test(e)}let tD=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function tj(e){if("string"!=typeof e)return;let t=tD.exec(e.trim());if(!t)return;let[,r,i,s,n,a]=t;if("ff"!==r&&("00"!==r||!a)&&tR(i,32,tk)&&tR(s,16,tO))return{version:r,traceId:i,spanId:s,flags:n}}function tB(e){return Array.isArray(e)&&1===e.length?e[0]:e}function tL(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 tN="unknown";function tq(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 "${tN}"`),tN)}function tU(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 tz(e,t,r,i){let s=tU(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 tH(){let e=globalThis.performance;return"function"==typeof e?.now?e.now():void 0}class tW{constructor(e,t,r){for(const 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??"01",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:tH(),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=tH();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(w(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]=t0(t,this._maxAttributeValueLength)}setAttribute(e,t){return this._mutable("setAttribute")&&this._writeAttribute(e,t),this}setAttributes(e){if(this._mutable("setAttributes")){let t=tm({},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&&t1(t,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:tq(e,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:tz(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:tX(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}=t3(e);return this.addEvent(tV,{"exception.type":t,"exception.message":r,...i&&{"exception.stacktrace":i}}),this.setStatus("error",r)}updateName(e){return this._mutable("updateName")&&(this._name=tq(e,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return function(e,t,r="01"){return`00-${e}-${t}-${r}`}(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(e){var t;if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let r=tz(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 tV="exception";function tK(e){return"number"!=typeof e||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),0xffffffff)}class tG{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}}let tQ=new tG;class tJ extends tG{constructor(e,t){super(),this._traceparent=e,this._tracestate=t}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}}function tZ(e,t){var r;let i=tB(e?.parent)??t,s=tj(r="string"==typeof i||null==i?i:tY(i,"traceparent"))&&r.trim();return s?new tJ(s,tL("string"==typeof i||null==i?e?.tracestate:tY(i,"tracestate"))):tQ}function tY(e,t){try{let r=e[t];return"function"==typeof r?r.call(e):void 0}catch{return}}function tX(e,t){return e.length>t?e.slice(0,t):e}function t0(e,t){return function e(t,r,i,s){if(null===t||"object"!=typeof t)return w(t)||i.remainingNodes<=0?t:(i.remainingNodes--,"string"==typeof t?tX(t,r):t);if(i.ancestors.has(t))return td;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 w(n.value)?String(n.value):e(n.value,r,i,s+1);if(f(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(tp)}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=tp}n&&!w(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 t1(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=t0(e[o],r)}catch{i=tp}w(i)||(n++,Object.defineProperty(s,o,{value:i,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:s,dropped:a}}function t2(e,t,r){return t===tQ?r(t):e.with(t,()=>r(t))}function t3(e){try{let t=function(e){try{let t=e.stack;return"string"==typeof t&&t?{stack:t}:{}}catch{return{}}}(e);if(F(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 t5={internal:1,server:2,client:3,producer:4,consumer:5},t4={ok:1,error:2};function t6(e){if("string"==typeof e)return tf(e);try{return tf(String(e))}catch{return tp}}function t8(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 t9(){return tH()??Date.now()}function t7(e){try{return e instanceof tW}catch{return!1}}function re(e,t){let r,i=(r=tj(e))&&{traceId:r.traceId,spanId:r.spanId,flags:1&parseInt(r.flags,16)?"01":"00"};if(i)return{traceId:i.traceId,parentSpanId:i.spanId,traceState:tL(t),traceFlags:i.flags,isRemote:!0}}function rt(e,t,r){e[t]!==r&&(e[t]=r)}class rr{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 tE(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter=new te,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=tB(t?.parent);if(n&&"string"!=typeof n&&!t7(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._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=tU(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=tT(8);this._liveSpans.set(u,t9());let c=this._autoContextAttributes();return new tW({traceId:a?.traceId??tT(16),spanId:u,parentSpanId:a?.parentSpanId,traceState:a?.traceState,traceFlags:a?.traceFlags,parentIsRemote:a?.isRemote,name:tq(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:t?.kind??"internal",attributes:tm({...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===tU(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=t2(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=re(e,t?.tracestate);return r||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),r}if(t7(e))return e.childContext();let r=this._contextManager.active();return t7(r)?r.childContext():r instanceof tJ?re(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 tW))return;let{type:r,message:i,stack:s}=t3(t);e.addEvent("exception",{"exception.type":r,"exception.message":i,...s&&{"exception.stacktrace":s}}),e.statusIsExplicitlyOk||e.setStatus("error",i)}_evictAgedSpans(){let e=t9()-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=tq(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=tU(u.startTime)??i.startTime,u.endTime=(h=tU(u.endTime)??i.endTime,d=u.startTime,h<d?d:h);let e=[];for(let t of u.events)try{e.push({...t,name:tq(t.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:tz(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(!w(s)){if(!t.has(i)){if(o>=r){l++;continue}o++}Object.defineProperty(u,i,{value:t0(s,n),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=u,l&&(e.droppedAttributesCount=tK(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=t1(t.attributes,s,n);t.attributes=e.attributes,e.dropped&&(t.droppedAttributesCount=tK(t.droppedAttributesCount)+e.dropped)}d.push(t)}e.events=d,h&&(e.droppedEventsCount=tK(e.droppedEventsCount)+h),e.status?.message&&(e.status={...e.status,message:tX(function(e){try{return"string"==typeof e?e:String(e)}catch{return tp}}(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{rt(e,"traceId",t.traceId),rt(e,"spanId",t.spanId),rt(e,"parentSpanId",t.parentSpanId),rt(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:t6(e.name),kind:(r=e.kind)&&Object.prototype.hasOwnProperty.call(t5,r)?t5[r]:t5.internal,startTimeUnixNano:t8(e.startTime),endTimeUnixNano:t8(e.endTime),flags:(i=parseInt(e.traceFlags,16),(Number.isFinite(i)?255&i:1)|256|512*!!e.parentIsRemote)};e.parentSpanId&&(s.parentSpanId=e.parentSpanId),e.traceState&&(s.traceState=t6(e.traceState));let n=t_(e.attributes,t);n.length&&(s.attributes=n),e.events.length&&(s.events=e.events.map(e=>(function(e,t){let r={name:t6(e.name),timeUnixNano:t8(e.timestamp)};if(e.attributes){let i=t_(e.attributes,t);i.length&&(r.attributes=i)}let i=tK(e.droppedAttributesCount);return i&&(r.droppedAttributesCount=i),r})(e,t)));let a=tK(e.droppedAttributesCount);a&&(s.droppedAttributesCount=a);let o=tK(e.droppedEventsCount);return o&&(s.droppedEventsCount=o),e.status&&(s.status={code:t4[e.status.code],...e.status.message&&{message:t6(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]=t0(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 g=t9()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),p=await this._instance._sendTracesBatch((t=this._logger,{resourceSpans:[{resource:{attributes:tS(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=tF(),this._headBatchSize=c,g&&(this._headBatchFailures++,this._headBatchChargeableAt=t9()+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(tP(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}}var ri=eq,rs=e.i(2157),rn=e.i(12714),ra=e.i(50227),ro=e.i(1457);let rl=new ri.ReduceableCache(25),ru=new ri.ReduceableCache(20);async function rc(e,t=rn.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,ra.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=rp(e,i);if(void 0===n||ru.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=rf(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=rf(r)),t++}return s}(a);if(o.every(e=>(function(e,t){let r=rl.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}(rl,n,{});l.push(rd(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=rp(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=rm(e);i<e;i++){let e=r[i];if(void 0===e)return void rg(t);t.pre_context.push(e)}if(void 0===r[e])return rg(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,rl,i),rl.reduce(),e}async function rh(e,t,r){let i,s=!1;try{i=await t(e,rs.constants.O_RDONLY|rs.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 rd(e,t,r,i,s,n){let a=await rh(e,s,n);return void 0===a?void ru.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{ru.set(i,1),l();return}try{n=(0,ro.createInterface)({input:s})}catch{ru.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],g=h[1];function p(){ru.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>=g)){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],g=e[1]}})})}function rg(e){delete e.pre_context,delete e.context_line,delete e.post_context}function rp(e,t){return(0,ra.isAbsolute)(e)?JSON.stringify([null,e]):void 0===t?void 0:JSON.stringify([t,e])}function rf(e){return[rm(e),e+7]}function rm(e){return Math.max(1,e-7)}class ry{active(){return this._active}with(e,t){let r=this._active;this._active=e;try{return t()}finally{this._active=r}}}let r_=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],rv=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return r_.concat(t).some(e=>{let t=e.toLowerCase();return -1!==r.indexOf(t)})};function rb(e,t){return"number"==typeof e&&Number.isInteger(e)&&e>=1?e:t}let rw=["service.name","service.version","deployment.environment"],rS={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};e.s(["FeatureFlagError",0,rS],88096);class rx{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e,t={}){let r=this._flags[e];return this._recordAccess(e),r?.enabled??t.defaultValue??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),t)return!!t.enabled&&(t.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)}_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 rx({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),""===this._distinctId||this._isSlice&&!(e in this._flags))return;let t=this._flags[e],r=void 0===t?void 0:!1!==t.enabled&&(t.variant??!0),i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:r,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};t?.hasExperiment!==void 0&&(i.$feature_flag_has_experiment=t.hasExperiment),t?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let s=[];this._errorsWhileComputing&&s.push(rS.ERRORS_WHILE_COMPUTING),this._quotaLimited&&s.push(rS.QUOTA_LIMITED),void 0===t&&s.push(rS.FLAG_MISSING),s.length>0&&(i.$feature_flag_error=s.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:r,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}}let rE=["is_not","is_set"];class rF extends Error{constructor(e){super(e),this.name=this.constructor.name,Object.setPrototypeOf(this,rF.prototype)}}function rP(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(!rP(t in e?e[t]:null))return!1;return!0}function rI(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 rF("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new rF("Cannot stringify an unpaired surrogate like the flags service")}}function rA(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 rC(e){return"string"==typeof e?(rI(e),e):function e(t,r=new Set){if(null===t)return"null";if("string"==typeof t)return rI(t),JSON.stringify(t);if("boolean"==typeof t)return t?"true":"false";if("number"==typeof t){if(!Number.isFinite(t))throw new rF(`Cannot stringify non-finite number ${t} like the flags service`);if(Number.isInteger(t))throw new rF(`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 rF("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 rF("Cannot stringify a non-JSON object like the flags service");if(r.has(t))throw new rF("Cannot stringify a circular object during local evaluation");r.add(t);try{let i=Object.keys(t);return i.forEach(rI),`{${i.sort(rA).map(i=>`${JSON.stringify(i)}:${e(t[i],r)}`).join(",")}}`}finally{r.delete(t)}}throw new rF(`Cannot stringify ${typeof t} like the flags service`)}(e)}function r$(e){try{return new RegExp(e),!0}catch{return!1}}function rk(e){return String(e).replace(/[A-Z]/g,e=>e.toLowerCase())}function rO(e,t,r){if(!/^\d+$/.test(e)||"strict"===r&&e.length>1&&"0"===e[0])throw new rF(`Invalid semver: ${t}`);return parseInt(e,10)}function rM(e,t="strict"){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new rF(`Invalid semver: ${e}`);let i=r.split("."),s=r=>void 0===r||""===r?0:rO(r,e,t);return[s(i[0]),s(i[1]),s(i[2])]}function rT(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 rR(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 rF(`${e} is in an invalid date format`)}throw new rF(`The date provided ${e} must be a string, number, or date object`)}async function rD(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 rj(e,t,r=""){return parseInt((await rD(`${e}.${t}${r}`)).slice(0,15),16)/0x1000000000000000}function rB(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 rL(e,t,r){let i=await rj(e,t,"variant");return rB(r).find(e=>i>=e.valueMin&&i<e.valueMax)?.key}class rN extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,rN.prototype)}}class rq extends Error{constructor(e){super(e),function(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}(this,rq)}}class rU{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.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()}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 rq||t instanceof rF?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=0==this.featureFlags.length,n=t?t.map(e=>this.featureFlagsByKey[e]).filter(Boolean):this.featureFlags,a={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(n.map(async e=>{try{let{value:t,payload:s}=await this.computeFlagAndPayloadLocally(e,a);r[e.key]=t,s&&(i[e.key]=s)}catch(t){t instanceof rq||t instanceof rF?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e.key}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e.key}: ${t}`)),s=!0}})),{response:r,payloads:i,fallbackToFlags:s}}async computeFlagAndPayloadLocally(e,t,r={}){let i,{matchValue:s,skipLoadCheck:n=!1}=r;if(n||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};i=void 0!==s?s:await this.computeFlagValueLocally(e,t);let a=this.getFeatureFlagPayload(e.key,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 rF("Flag has experience continuity enabled");let a=(e.filters||{}).aggregation_group_type_index;if(void 0!=a){let r=this.groupTypeMapping[String(a)];if(!r)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${a} for feature flag ${e.key}`)),new rF("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 rF(`Can't compute feature flag: ${e.key} without $device_id`);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}getFeatureFlagPayload(e,t){var r=this.featureFlagsByKey?.[e]?.filters?.payloads;if(!1===t||null==t||!r)return null;let i=r["boolean"==typeof t?t.toString():t]||null;return null==i?null:e1(i)}async evaluateFlagDependency(e,t,r){let{evaluationCache:i}=r,s=e.key;if(!this.featureFlagsByKey)throw new rF("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new rF(`Flag dependency property for '${s}' is missing required 'dependency_chain' field`);let n=e.dependency_chain;if(!Array.isArray(n))throw new rF(`Flag dependency property for '${s}' has an invalid 'dependency_chain' (expected array, got ${typeof n})`);if(0===n.length)throw new rF(`Circular dependency detected for flag '${s}' (empty dependency chain)`);for(let e of n){if(!(e in i)){let t=this.featureFlagsByKey[e];if(t)if(t.active)try{let s=await this.computeFlagValueLocally(t,r);i[e]=s}catch(t){throw new rF(`Error evaluating flag dependency '${e}' for flag '${s}': ${t}`)}else i[e]=!1;else if(this.filteredOutFlagKeys.has(e))i[e]=!1;else throw new rF(`Missing flag dependency '${e}' for flag '${s}'`)}if(null==i[e])throw new rF(`Dependency '${e}' could not be evaluated`)}let a=i[s];return this.flagEvaluatesToExpectedValue(e.value,a)}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=e.filters||{},a=n.groups||[],o=n.aggregation_group_type_index,l=n.early_exit??!1,{groups:u,groupProperties:c}=i,h=!1;for(let d of a)try{let a=void 0!==d.aggregation_group_type_index?d.aggregation_group_type_index:o,g=r,p=t;if(a!==o&&null!=a){let t=this.groupTypeMapping[String(a)];if(!t||!(t in u)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${a} not available`));continue}if(!(t in c)){h=!0;continue}g=c[t],p=u[t]}let f=await this.isConditionMatch(e,p,d,g,i);if("match"===f){let t=d.variant,r=n.multivariate?.variants||[];s=t&&r.some(e=>e.key===t)?t:await this.getMatchingVariant(e,p)||!0;break}if(l&&"out_of_rollout_bound"===f){if(h)break;return!1}}catch(e){if(e instanceof rq)throw e;if(e instanceof rF)h=!0;else throw e}if(void 0!==s)return s;if(h)throw new rF("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,r,i,s){let n=r.rollout_percentage,a=e=>{this.logMsgIfDebug(()=>console.warn(e))};if((r.properties||[]).length>0){for(let e of r.properties){let t=e.type,r=!1;if("cohort"===t){let t=await rH(e,i,this.cohorts,this.debugMode,e=>this.evaluateFlagDependency(e,i,s));r="not_in"===e.operator?!t:t}else r="flag"===t?await this.evaluateFlagDependency(e,i,s):rz(e,i,a);if(!r)return"no_match"}if(void 0==n)return"match"}return void 0!=n&&await rj(e.key,t)>n/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){return rL(e.key,t,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return rB(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))})}updateFlagState(e){let t=this.filterFlagsByEvaluationContexts(e.flags);this.featureFlags=t,this.featureFlagsByKey=t.reduce((e,t)=>(e[t.key]=t,e),{});let r=new Set(t.map(e=>e.key));this.filteredOutFlagKeys=new Set(e.flags.filter(e=>!r.has(e.key)).map(e=>e.key)),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(!0===e.minimalFlagCalledEvents)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter(e=>e.ensure_experience_continuity);t.length>0&&console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map(e=>e.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();if(t)return this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags),!0;return!1}catch(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(){return this.shouldBeginExponentialBackoff?Math.min(6e4,this.pollingInterval*2**this.backOffCount):this.pollingInterval}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{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 rN(`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.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new rN(`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 rN(`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={flags:r.flags??[],groupTypeMapping:r.group_type_mapping||{},cohorts:r.cohorts||{},minimalFlagCalledEvents:!0===r.minimal_flag_called_events};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(e){this.onError?.(Error(`Failed to store in cache: ${e}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(e){e instanceof rN&&this.onError?.(e)}finally{this.pollerStopped||(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(){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=q(()=>{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 U(t,e,()=>{throw Error(`Cache shutdown timeout after ${e}ms`)})}catch(e){this.onError?.(Error(`Error during cache shutdown: ${e}`))}}}function rz(e,t,r){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 rF(`Property ${i} not found in propertyValues`);let o=t[i];if(void 0===o)return r.warnFunction?.(`Property ${i} cannot have a value of undefined with the ${n} operator`),"is_not"===n;if(null===o&&!rE.includes(n)&&"exact"!==n&&"is_not"!==n)return r.warnFunction?.(`Property ${i} cannot have a value of null with the ${n} operator`),!1;let l=(e,t)=>{if(function e(t){if("boolean"==typeof t)return!0;if("string"==typeof t){let e=t.toLowerCase();return"true"===e||"false"===e}if(!Array.isArray(t))return!1;for(let r=0;r<t.length;r++)if(!e(r in t?t[r]:null))return!1;return!0}(e))return!function e(t,r=new Set){if(null!==t&&"boolean"!=typeof t){if("string"==typeof t)return void rI(t);if("number"==typeof t){if(!Number.isFinite(t))throw new rF(`Cannot represent non-finite number ${t} like the flags service`);return}if(Array.isArray(t)){if(r.has(t))throw new rF("Cannot represent a circular array during local evaluation");r.add(t);try{for(let i=0;i<t.length;i++)i in t&&e(t[i],r)}finally{r.delete(t)}return}if("object"==typeof t){let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&null!==i)throw new rF("Cannot represent a non-JSON object like the flags service");if(r.has(t))throw new rF("Cannot represent a circular object during local evaluation");r.add(t);try{for(let i of Object.keys(t))rI(i),e(t[i],r)}finally{r.delete(t)}return}throw new rF(`Cannot represent ${typeof t} like the flags service`)}}(t),rP(e)===rP(t);if(Array.isArray(e)){let r=rC(t).toLowerCase();return e.some(e=>rC(e).toLowerCase()===r)}return rC(e).toLowerCase()===rC(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}`)};switch(n){case"exact":return l(s,o);case"is_not":return!l(s,o);case"is_set":return!0;case"icontains":return rk(o).includes(rk(s));case"not_icontains":return!rk(o).includes(rk(s));case"starts_with":return rk(o).startsWith(rk(s));case"not_starts_with":return!rk(o).startsWith(rk(s));case"ends_with":return rk(o).endsWith(rk(s));case"not_ends_with":return!rk(o).endsWith(rk(s));case"regex":return r$(String(s))&&null!==String(o).match(String(s));case"not_regex":return r$(String(s))&&null===String(o).match(String(s));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":{if("boolean"==typeof s)throw new rF("Date operations cannot be performed on boolean values");let e=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(s));null==e&&(e=rR(s));let t=rR(o);return"is_date_before"===n?t<e:t>e}case"semver_eq":return 0===rT(rM(String(o),a),rM(String(s),a));case"semver_neq":return 0!==rT(rM(String(o),a),rM(String(s),a));case"semver_gt":return rT(rM(String(o),a),rM(String(s),a))>0;case"semver_gte":return rT(rM(String(o),a),rM(String(s),a))>=0;case"semver_lt":return 0>rT(rM(String(o),a),rM(String(s),a));case"semver_lte":return 0>=rT(rM(String(o),a),rM(String(s),a));case"semver_tilde":{let e,t=rM(String(o),a),{lower:r,upper:i}={lower:[(e=rM(String(s),a))[0],e[1],e[2]],upper:[e[0],e[1]+1,0]};return rT(t,r)>=0&&0>rT(t,i)}case"semver_caret":{let e=rM(String(o),a),{lower:t,upper:r}=function(e,t){let[r,i,s]=rM(e,t);return{lower:[r,i,s],upper:r>0?[r+1,0,0]:i>0?[0,i+1,0]:[0,0,s+1]}}(String(s),a);return rT(e,t)>=0&&0>rT(e,r)}case"semver_wildcard":{let e=rM(String(o),a),{lower:t,upper:r}=function(e,t){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new rF(`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 rO(r,e,t)}catch{}throw new rF(`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]}}(String(s),a);return rT(e,t)>=0&&0>rT(e,r)}default:throw new rF(`Unknown operator: ${n}`)}}(e,t,{warnFunction:r})}async function rH(e,t,r,i=!1,s){let n=String(e.value);if(!(n in r))throw new rq(`cohort ${n} not found in local cohorts - likely a static cohort that requires server evaluation`);return rW(r[n],t,r,i,s)}async function rW(e,t,r,i=!1,s){if(!e)return!0;let n=e.type,a=e.values;if(!a||0===a.length)return!0;let o=!1;if("values"in a[0]){for(let e of a)try{let a=await rW(e,t,r,i,s);if("AND"===n){if(!a)return!1}else if(a)return!0}catch(t){if(t instanceof rq)throw t;if(t instanceof rF)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0;else throw t}if(o)throw new rF("Can't match cohort without a given cohort property value");return"AND"===n}for(let e of a)try{let a;if("cohort"===e.type)a=await rH(e,t,r,i,s);else if("flag"===e.type){if(!s)throw new rF(`Flag dependency '${e.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);a=await s(e)}else a=rz(e,t);let o=e.negation||!1;if("AND"===n){if(!a&&!o||a&&o)return!1}else if(a&&!o||!a&&o)return!0}catch(t){if(t instanceof rq)throw t;if(t instanceof rF)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0;else throw t}if(o)throw new rF("can't match cohort without a given cohort property value");return"AND"===n}let rV=["--unhandled-rejections","--unhandled_rejections"],rK=new Set(["throw","strict","warn","warn-with-error-code","none"]),rG=[...globalThis.process?.execArgv??[]],rQ=globalThis.process?.env?.NODE_OPTIONS;function rJ(e){let t;for(let r=0;r<e.length;r++){let i=e[r],s=rV.find(e=>i===e||i.startsWith(`${e}=`));if(!s)continue;let n=i===s?e[++r]:i.slice(s.length+1);rK.has(n)&&(t=n)}return t}let rZ=function(e=rG,t=rQ){return rJ(e)??rJ(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"}();function rY(e,t,r){e(t,{mechanism:{type:"unhandledRejection"===r?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function rX(e,t,r,i,s){if(t>r&&(i.warn("min cannot be greater than max."),t=r),S(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),rX(s??r,t,r,i)}class r0{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=rX(e.bucketSize,0,100,e._logger),this._refillRate=rX(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=rX(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 ri=eq;let r1=class t{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new r0({...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 m(e)&&"__posthog_previously_captured_error"in e&&!0===e.__posthog_previously_captured_error}static async buildEventMessage(e,t,r,i,s){let n={...s},a=e.buildFromUnknown(t,r);a.$exception_list=await e.modifyFrames(a.$exception_list);let o=ri.getInjectedReleaseId();return o&&(n.$release_id=o),{event:"$exception",distinctId:i,properties:{...a,...n},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(!function(t,r,i=rZ){let s=globalThis.process;if(s){let n;if("strict"===i)return s.on("uncaughtExceptionMonitor",(e,r)=>rY(t,e,r));s.on("uncaughtException",(n=!1,Object.assign((i,s)=>{let a=e.g.process.listeners("uncaughtException").filter(e=>"domainUncaughtExceptionClear"!==e.name&&!0!==e._posthogErrorHandler).length;rY(t,i,s),n||0!==a||(n=!0,r(i))},{_posthogErrorHandler:!0})))}}(this.onException.bind(this),this.onFatalError.bind(this)),function(e,t=rZ){let r=globalThis.process;r&&"throw"!==t&&"strict"!==t&&"warn-with-error-code"!==t&&r.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}(this.onException.bind(this)))}onException(e,r){this.client.addPendingPromise((async()=>{if(!t.isPreviouslyCapturedError(e)){let i=await t.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,r),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)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(2e3),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};class r2{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=null!==t?t:void 0}constructor(){this._memoryStorage={}}}let r3="analytics";class r5 extends Error{constructor({requestId:e,drops:t,retryExhausted:r,cause:i}){super(r5.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 r4(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 r6=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:r4},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:r4},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:r4},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(e){return"string"==typeof e?e:void 0}}],r8=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function r9(e,t,r){void 0===r||t in e||(e[t]=r)}function r7(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 r6)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 r8)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,r9(r,"$set",e.$set),r9(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 ie=new Set([408,500,502,503,504]);class it{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=>q(t,e))),this.generateRequestId=t.generateRequestId??eV,this.compress=t.compress??e8}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(r7)};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=h({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&&ie.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 r5({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=q(()=>{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 r5({requestId:e,drops:t,retryExhausted:r.map(e=>e.uuid),cause:i}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new r5({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}}let ir="ai-capture",ii="/i/v0/ai/batch/",is=new TextEncoder;function ia(e){return is.encode(h(e)).length}let io=new Set;function il(e,t){io.has(e)||(io.add(e),console.warn(`[PostHog] ${t}`))}class iu extends th{constructor(e,t={}){const r=function(e){return"string"==typeof e?e.trim():""}(e),i={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:function(e){return("string"==typeof e?e.trim():"")||"https://us.i.posthog.com"}(t.host),personalApiKey:function(e){return("string"==typeof e?e.trim():"")||void 0}(t.secretKey??t.personalApiKey)};if(super(r,i),this._memoryStorage=new r2,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=function(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return"v0"===e||"v1"===e?e:"v0"}(),this.enableFullAiCapture=!0===i.enableFullAiCapture,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof i.featureFlagsPollingInterval?Math.max(i.featureFlagsPollingInterval,100):3e4,"number"==typeof i.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),"number"==typeof i.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),!this.disabled&&i.personalApiKey){if(i.personalApiKey.includes("phc_"))throw Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');!1!==i.enableLocalEvaluation&&(this.featureFlagsPoller=new rU({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:r,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:e=>{this._events.emit("error",e)},onLoad:e=>{this._events.emit("localEvaluationFlagsLoaded",e)},onMinimalFlagCalledEvents:e=>{this._minimalFlagCalledEvents=e},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation,evaluationContexts:i.evaluationContexts??i.evaluationEnvironments}))}this.errorTracking=new r1(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.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:z([t,this._traces.flush().catch(()=>{})]).then(([e])=>{if("rejected"===e.status)throw e.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(e){let t=this._flushEventsAndSpans(e),r=this.options.waitUntil;if(r&&!this._waitUntilCycle)try{r(t.catch(()=>{}))}catch{}return t}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||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=q(()=>{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":r3}persistedQueueKeyForRoute(e){return e===ir?u.AiCaptureQueue:"ai"===e?u.AiQueue:u.Queue}getActiveQueueRoutes(){let e="v1"===this.captureMode?[r3,"ai"]:[r3];return this._aiCaptureRouteActive&&e.push(ir),e}getBatchEndpointPath(e){return e===ir?ii:super.getBatchEndpointPath(e)}async sendBatch(e,t,r=r3){if(r===ir)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=ia(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 ${ii}, 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,ir)}catch(i){if(!to(i))throw i;if(1===e.length){let[t]=e,r="string"==typeof t.event?t.event:"unknown",i=`Event ${r} (${ia(t)} bytes) was rejected with 413 by ${ii} 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 it({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.52.1"}get metrics(){var e;let t;return this._metrics||(this._metrics=new t$(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}initializeSpanContextManager(){return new ry}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 rr(this,(e=this.options.traces,t=this.hostResourceAttributes(),r=this._logger,i=tm({...t},function(e){if(!(!e||"object"!=typeof e||Array.isArray(e)))try{if(rw.every(t=>!(t in e)||"string"==typeof e[t]))return e;let t={...e};for(let e of rw)e in t&&"string"!=typeof t[e]&&delete t[e];return t}catch{return}}(e?.resourceAttributes)),s=rb(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:rb(e?.maxAttributesPerSpan,128),maxEventsPerSpan:rb(e?.maxEventsPerSpan,128),maxAttributesPerEvent:128,maxAttributeValueLength:rb(e?.maxAttributeValueLength,8192),flushIntervalMs:rb(e?.flushIntervalMs,5e3),maxExportBatchSize:s,maxQueueSize:Math.max(rb(e?.maxQueueSize,2048),s),maxLiveSpans:rb(e?.maxLiveSpans,1e4),maxSpanAgeMs:rb(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)??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):t2(this._spanContextManager,tZ(i,this._spanContextManager.active()),s)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}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=D(e.uuid,eV);return this._sendPreparedAiEvent({...e,uuid:t},!1),t}async captureAiImmediate(e){if(this.disabled)return;let t=D(e.uuid,eV);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,ir)}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}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:g,disableGeoip:p}=r,{onlyEvaluateLocally:f,personProperties:m,groupProperties:y}=r,_=this.addLocalPersonAndGroupProperties(t,g,m,y);m=_.allPersonProperties,y=_.allGroupProperties;let v=this.createFeatureFlagEvaluationContext(t,g,this.personPropertiesForLocalEvaluation(t,m),y);void 0==f&&(f=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}}}catch(t){if(t instanceof rq||t instanceof rF)this._logger?.info(`${t.name} when computing flag locally: ${e}: ${t.message}`);else throw t}}if(!b&&!f){let t=await super.getFeatureFlagDetailsStateless(v.distinctId,v.groups,m,y,p,[e]);if(void 0===t)o=rS.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===t.minimalFlagCalledEvents,n=t.requestId,a=t.evaluatedAt;let r=[];t.errorsWhileComputingFlags&&r.push(rS.ERRORS_WHILE_COMPUTING),t.quotaLimited?.includes("feature_flags")&&r.push(rS.QUOTA_LIMITED);let i=t.flags[e];if(void 0===i)r.push(rS.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}}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:g,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){il("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:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(void 0!==i)return!1!==i.enabled&&(i.variant??!0)}async getFeatureFlagPayload(e,t,r,i){if(il("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:s?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):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){il("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:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});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),g={},p={},f=!0;if(d&&(g=d.response,p=d.payloads,f=d.fallbackToFlags),f&&!o){let e=await super.getFeatureFlagsAndPayloadsStateless(h.distinctId,h.groups,l,u,n,a);g={...g,...e.flags||{}},p={...p,...e.payloads||{}}}return void 0!==this._flagOverrides&&(g={...g,...this._flagOverrides}),void 0!==this._payloadOverrides&&(p={...p,...this._payloadOverrides}),{featureFlags:g,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 rx({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new rx({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,flags:{}});let{groups:a,disableGeoip:o}=n||{},l=n?.flagKeys??void 0;if(l?.length===0)return new rx({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 g=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,f={},m=!1,y=!1,_=await this.featureFlagsPoller?.getAllFlagsAndPayloads(g,l),v=new Set;if(_)for(let[e,t]of Object.entries(_.response)){let r=this.featureFlagsPoller?.featureFlagsByKey[e];f[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(g.distinctId,g.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}f[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 f[e];continue}let r=f[e];f[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=f[e];r&&(f[e]={...r,payload:t})}if(void 0!==p)for(let e of Object.keys(f))p.has(e)||delete f[e];return new rx({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:a,disableGeoip:o,flags:f,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}`;t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(l)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[t]instanceof Set?this.distinctIdHasSentFlagCalls[t].add(l):this.distinctIdHasSentFlagCalls[t]=new Set([l]),this.capture({distinctId:t,event:"$feature_flag_called",properties:a,groups:s,disableGeoip:n}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(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,t,r):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??3e4),r=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await U(this._metrics.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._metrics.reset()),this._traces&&(await U(this._traces.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},r?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let e=new AbortController;i=q(()=>{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(E(n,"Object")&&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(!r1.isPreviouslyCapturedError(e)){let n=Error("PostHog syntheticException");this.addPendingPromise(r1.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:n},t,r).then(e=>this._capturePreparedEvent({...e,uuid:i,flags:s},!1)))}}async captureExceptionImmediate(e,t,r,i){if(!r1.isPreviouslyCapturedError(e)){let s=Error("PostHog syntheticException");return this.addPendingPromise(r1.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,r).then(e=>this.captureImmediate({...e,flags:i})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:r,event:i,properties:s,groups:n,flags:a,sendFeatureFlags:o,timestamp:l,disableGeoip:u,uuid:c}=e,h=this.context?.get(),d=t.includeContextProperties??!0,g=r||h?.distinctId,p=d?{...this.props,...h?.properties||{},...s||{}}:{...s||{}};g||(g=eV(),p.$process_person_profile=!1),d&&h?.sessionId&&!p.$session_id&&(p.$session_id=h.sessionId);let f=this._shouldSendMinimalFlagCalledEvent(i,p)?e3(p):p,m=this._runBeforeSend({distinctId:g,event:i,properties:f,groups:n,flags:a,sendFeatureFlags:o,timestamp:l,disableGeoip:u,uuid:c});if(!m)return Promise.reject(null);let y=await Promise.resolve().then(async()=>{if(a)return o&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(o){il("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(m.distinctId,n,u,"object"==typeof o?o: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=m.groups||n;return{...e,...m.properties||{},...void 0!==t&&Object.keys(t).length>0?{$groups:t}:{}}});return"$pageview"===m.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof y.$raw_user_agent&&rv(y.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(m.event="$bot_pageview",y.$browser_type="bot"),{distinctId:m.distinctId,event:m.event,properties:y,options:{timestamp:m.timestamp,disableGeoip:m.disableGeoip,uuid:m.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let r=Array.isArray(t)?t:[t],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 ri=eq,ic=e.i(78500);class ih{constructor(){this.storage=new ic.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,r){return this.storage.run(this.resolve(e,r),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let r=this.get()||{};return{distinctId:e.distinctId??r.distinctId,sessionId:e.sessionId??r.sessionId,properties:{...r.properties||{},...e.properties||{}}}}}class id{active(){return this._storage.getStore()}with(e,t){return this._storage.run(e,t)}constructor(){this._storage=new ic.AsyncLocalStorage}}var ig=e.i(27028);let ip=(0,e.i(12057).promisify)(ig.gzip);async function im(e,t=!0){try{let t=await ip(e);return new Uint8Array(t)}catch(e){return t&&console.error("Failed to gzip compress data",e),null}}var iy=e.i(60526),ri=eq;let i_="posthog-node";function iv(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[iw.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},g=ri.getInjectedReleaseId();return g&&(d.$release_id=g),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 ib(e,t){let r=iv(e,t);return{name:i_,processEvent:e=>r(e)}}class iw{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,t,r,i,s){this.name=i_,this.name=i_,this.setupOnce=function(n,a){n(iv(e,{organization:t,projectId:a()?.getClient()?.getDsn()?.projectId,prefix:r,severityAllowList:i,sendExceptionsToPostHog:s??!0}))}}}e.s(["PostHogSentryIntegration",0,iw,"createEventProcessor",0,iv,"sentryIntegration",0,ib],92164);let iS=/[\x00-\x1f\x7f-\x9f]/g;function ix(e,t,r){null!=r&&""!==r&&(e[t]=r)}function iE(e){return Array.isArray(e)?e[0]:e}function iF(e){if(Array.isArray(e)){for(let t of e){let e=iF(t);if(void 0!==e)return e}return}if("string"!=typeof e)return;let t=e.replace(iS,"").trim();if(t)return t.length>1e3?t.slice(0,1e3):t}function iP(e,t){var r,i;let s,{sessionId:n,distinctId:a}=function(e){if(!e)return{};let t=iF(e["x-posthog-session-id"]),r=iF(e["x-posthog-distinct-id"]);return{...void 0!==t?{sessionId:t}:{},...void 0!==r?{distinctId:r}:{}}}(t.headers),o={},l=!0===e.options.disable_capture_url_hashes;return ix(o,"$current_url",(r=t.originalUrl||t.url,l?B(r):r)),ix(o,"$request_method",t.method),ix(o,"$request_path",(i=t.path,s=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),l?B(s):s)),ix(o,"$user_agent",iE(t.headers["user-agent"])),ix(o,"$ip",function(e){let t=iE(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 iI(e,t){var r;t.use((r=e,(e,t,i)=>{r.withContext(iP(r,e),()=>i())}))}function iA(e,t){var r;t.use((r=e,(e,t,i,s)=>{if(r1.isPreviouslyCapturedError(e))return void s(e);let n=iP(r,t),a=Error("Synthetic exception"),o={...void 0!==n.sessionId?{$session_id:n.sessionId}:{},...n.properties||{},$response_status_code:i.statusCode};r.addPendingPromise(r1.buildEventMessage(r.getErrorPropertiesBuilder(),e,{mechanism:{type:"middleware",handled:!1},syntheticException:a},n.distinctId,o).then(e=>r._capturePreparedEvent(e,!1))),s(e)}))}e.s(["setupExpressErrorHandler",0,iA,"setupExpressRequestContext",0,iI],88512),e.s([],52538);class iC extends iu{getLibraryId(){return"posthog-node"}compressPayload(e){return im(e,this.isDebug)}initializeContext(){return new ih}initializeSpanContextManager(){return new id}hostResourceAttributes(){return function(){var e,t;let r,i,s;try{r=(0,iy.platform)(),i=(0,iy.release)()}catch{}return e=r,t=i,{...(s=function(e){if(e)return Object.prototype.hasOwnProperty.call(tx,e)?tx[e]:e}(e))?{"os.name":s}:{},...t?{"os.version":t}:{}}}()}createErrorPropertiesBuilder(){let e;return new ri.ErrorPropertiesBuilder([new ri.EventCoercer,new ri.ErrorCoercer,new ri.ObjectCoercer,new ri.StringCoercer,new ri.PrimitiveCoercer],ri.createStackParser("node:javascript",ri.nodeStackLineParser),[(e=function(e=process.argv[1]?(0,o.dirname)(process.argv[1]):process.cwd(),t="\\"===o.sep){let r=t?l(e):e;return e=>{if(!e)return;let i=t?l(e):e,{dir:s,base:n,ext:a}=o.posix.parse(i);(".js"===a||".mjs"===a||".cjs"===a)&&(n=n.slice(0,-1*a.length));let u=decodeURIComponent(n);s||(s=".");let c=s.lastIndexOf("/node_modules");if(c>-1)return`${s.slice(c+14).replace(/\//g,".")}:${u}`;if(s.startsWith(r)){let e=s.slice(r.length+1).replace(/\//g,".");return e?`${e}:${u}`:u}return u}}(),async t=>{for(let r of t)r.module=e(r.filename);return t}),e=>rc(e,void 0,this._logger),function(e=process.cwd()){o.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,o.isAbsolute)(i.filename)&&(i.filename=t((0,o.relative)(r,t(i.filename))));return e}}()])}}e.s(["PostHog",0,iC],89767),e.i(89767),e.i(52538),e.i(92164),e.i(88512),e.i(88096),e.s(["FeatureFlagError",0,c,"FeatureFlagEvaluations",0,rx,"PostHogSentryIntegration",0,iw,"cookieStateToProperties",0,eY,"cookieStoreFromHeader",0,eG,"createEventProcessor",0,iv,"getPostHogCookieName",0,eQ,"parsePostHogCookie",0,eX,"readPostHogCookie",0,eZ,"sentryIntegration",0,ib,"serializePostHogCookie",0,eJ,"setupExpressErrorHandler",0,iA,"setupExpressRequestContext",0,iI,"uuidv7",0,eV],92349),e.i(92349),e.s(["FeatureFlagError",0,c,"FeatureFlagEvaluations",0,rx,"PostHog",0,iC,"PostHogSentryIntegration",0,iw,"cookieStateToProperties",0,eY,"cookieStoreFromHeader",0,eG,"createEventProcessor",0,iv,"getPostHogCookieName",0,eQ,"parsePostHogCookie",0,eX,"readPostHogCookie",0,eZ,"sentryIntegration",0,ib,"serializePostHogCookie",0,eJ,"setupExpressErrorHandler",0,iA,"setupExpressRequestContext",0,iI,"uuidv7",0,eV],39702)}];
3
3
 
4
4
  //# sourceMappingURL=node_modules_posthog-node_dist_entrypoints_index_node_mjs_01r25oi._.js.map