failproofai 1.0.14 → 1.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/build-manifest.json +13 -13
  3. package/.next/standalone/.next/prerender-manifest.json +3 -3
  4. package/.next/standalone/.next/required-server-files.json +1 -1
  5. package/.next/standalone/.next/server/app/_global-error/page/build-manifest.json +2 -2
  6. package/.next/standalone/.next/server/app/_global-error/page/server-reference-manifest.json +1 -1
  7. package/.next/standalone/.next/server/app/_global-error/page.js.nft.json +1 -1
  8. package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  9. package/.next/standalone/.next/server/app/_global-error.html +1 -1
  10. package/.next/standalone/.next/server/app/_global-error.rsc +2 -2
  11. package/.next/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +2 -2
  12. package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +2 -2
  13. package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  14. package/.next/standalone/.next/server/app/_not-found/page/build-manifest.json +2 -2
  15. package/.next/standalone/.next/server/app/_not-found/page/server-reference-manifest.json +1 -1
  16. package/.next/standalone/.next/server/app/_not-found/page.js.nft.json +1 -1
  17. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  18. package/.next/standalone/.next/server/app/_not-found.html +1 -1
  19. package/.next/standalone/.next/server/app/_not-found.rsc +3 -3
  20. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
  21. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
  22. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  23. package/.next/standalone/.next/server/app/api/audit/invite/route.js.nft.json +1 -1
  24. package/.next/standalone/.next/server/app/api/audit/run/route.js.nft.json +1 -1
  25. package/.next/standalone/.next/server/app/api/audit/status/route.js.nft.json +1 -1
  26. package/.next/standalone/.next/server/app/api/auth/login-request/route.js.nft.json +1 -1
  27. package/.next/standalone/.next/server/app/api/auth/login-verify/route.js.nft.json +1 -1
  28. package/.next/standalone/.next/server/app/api/auth/logout/route.js.nft.json +1 -1
  29. package/.next/standalone/.next/server/app/api/auth/status/route.js.nft.json +1 -1
  30. package/.next/standalone/.next/server/app/api/download/[project]/[session]/route.js.nft.json +1 -1
  31. package/.next/standalone/.next/server/app/audit/page/build-manifest.json +2 -2
  32. package/.next/standalone/.next/server/app/audit/page/server-reference-manifest.json +2 -2
  33. package/.next/standalone/.next/server/app/audit/page.js.nft.json +1 -1
  34. package/.next/standalone/.next/server/app/audit/page_client-reference-manifest.js +1 -1
  35. package/.next/standalone/.next/server/app/index.html +1 -1
  36. package/.next/standalone/.next/server/app/index.rsc +3 -3
  37. package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
  38. package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +3 -3
  39. package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  40. package/.next/standalone/.next/server/app/page/build-manifest.json +2 -2
  41. package/.next/standalone/.next/server/app/page/server-reference-manifest.json +1 -1
  42. package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
  43. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  44. package/.next/standalone/.next/server/app/policies/page/build-manifest.json +2 -2
  45. package/.next/standalone/.next/server/app/policies/page/server-reference-manifest.json +14 -14
  46. package/.next/standalone/.next/server/app/policies/page.js.nft.json +1 -1
  47. package/.next/standalone/.next/server/app/policies/page_client-reference-manifest.js +1 -1
  48. package/.next/standalone/.next/server/app/project/[name]/page/build-manifest.json +2 -2
  49. package/.next/standalone/.next/server/app/project/[name]/page/server-reference-manifest.json +1 -1
  50. package/.next/standalone/.next/server/app/project/[name]/page.js.nft.json +1 -1
  51. package/.next/standalone/.next/server/app/project/[name]/page_client-reference-manifest.js +1 -1
  52. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/build-manifest.json +2 -2
  53. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/react-loadable-manifest.json +2 -2
  54. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/server-reference-manifest.json +2 -2
  55. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page.js.nft.json +1 -1
  56. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page_client-reference-manifest.js +1 -1
  57. package/.next/standalone/.next/server/app/projects/page/build-manifest.json +2 -2
  58. package/.next/standalone/.next/server/app/projects/page/server-reference-manifest.json +1 -1
  59. package/.next/standalone/.next/server/app/projects/page.js.nft.json +1 -1
  60. package/.next/standalone/.next/server/app/projects/page_client-reference-manifest.js +1 -1
  61. package/.next/standalone/.next/server/app/settings/page/build-manifest.json +2 -2
  62. package/.next/standalone/.next/server/app/settings/page/server-reference-manifest.json +8 -8
  63. package/.next/standalone/.next/server/app/settings/page.js.nft.json +1 -1
  64. package/.next/standalone/.next/server/app/settings/page_client-reference-manifest.js +1 -1
  65. package/.next/standalone/.next/server/chunks/[root-of-the-server]__048f1wnr8pysf._.js +2 -2
  66. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1oclamblhzhrf._.js +1 -1
  67. package/.next/standalone/.next/server/chunks/_0tovk6q0miud6._.js +1 -1
  68. package/.next/standalone/.next/server/chunks/_0trp3ycqv17cl._.js +1 -1
  69. package/.next/standalone/.next/server/chunks/_1vslkoe35wok6._.js +1 -1
  70. package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_01r25oigsgz07._.js +1 -1
  71. package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_09z9-p77cu37y._.js +1 -1
  72. package/.next/standalone/.next/server/chunks/package_json_[json]_cjs_1nxcc4vkpxxu7._.js +1 -1
  73. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__1xwr4hi-on27i._.js → [root-of-the-server]__05-glpesefmmi._.js} +2 -2
  74. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__08ch3staq3ejw._.js +1 -1
  75. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0bigvy9xmv2ka._.js +1 -1
  76. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0ezoipo-r7_5k._.js +1 -1
  77. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0h86bl2qf0k_o._.js +1 -1
  78. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0pia5h3p8re4c._.js +1 -1
  79. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1-ey9fgesfbc0._.js +1 -1
  80. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__15usvs-ms-0hf._.js +1 -1
  81. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__16gb3_92zvk5x._.js +1 -1
  82. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1avi2kypusyb_._.js +1 -1
  83. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1r7drlqli-ado._.js +1 -1
  84. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1vxwetblyf8vp._.js +1 -1
  85. package/.next/standalone/.next/server/chunks/ssr/_0eoura3_9gjb-._.js +1 -1
  86. package/.next/standalone/.next/server/chunks/ssr/{_0p1cb69sml__f._.js → _0ge1hz9485xpp._.js} +2 -2
  87. package/.next/standalone/.next/server/chunks/ssr/_0pedwblqdoh58._.js +1 -1
  88. package/.next/standalone/.next/server/chunks/ssr/_1_ozgifqv1ssi._.js +1 -1
  89. package/.next/standalone/.next/server/chunks/ssr/_1djqs9i27e4kg._.js +1 -1
  90. package/.next/standalone/.next/server/chunks/ssr/_1v4_ul3sj2lq_._.js +1 -1
  91. package/.next/standalone/.next/server/chunks/ssr/_next-internal_server_app_policies_page_actions_1sp2-yo5_vm5f.js +2 -2
  92. package/.next/standalone/.next/server/chunks/ssr/app_actions_get-scheduled-audit_ts_0ei9snixb5fd-._.js +1 -1
  93. package/.next/standalone/.next/server/chunks/ssr/app_audit__components_audit-dashboard_tsx_0p9ud47q0xq5w._.js +1 -1
  94. package/.next/standalone/.next/server/chunks/ssr/app_global-error_tsx_1kp6l3x33jqb6._.js +1 -1
  95. package/.next/standalone/.next/server/chunks/ssr/app_policies_hooks-client_tsx_19dqvpcz0uxur._.js +1 -1
  96. package/.next/standalone/.next/server/chunks/ssr/app_settings_02tf1h47jmhhd._.js +1 -1
  97. package/.next/standalone/.next/server/chunks/ssr/{node_modules_html-to-image_es_index_0r9i9nq3-ei-l.js → node_modules_html-to-image_es_index_0e3yg5gbcfsai.js} +1 -1
  98. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_0bz67659f5z-3._.js +1 -1
  99. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_1khq67j4vo9y4._.js +1 -1
  100. package/.next/standalone/.next/server/chunks/ssr/node_modules_posthog-node_dist_entrypoints_index_node_mjs_11bnuznb72p7z._.js +1 -1
  101. package/.next/standalone/.next/server/chunks/ssr/package_json_[json]_cjs_013tntikdft59._.js +1 -1
  102. package/.next/standalone/.next/server/middleware-build-manifest.js +13 -13
  103. package/.next/standalone/.next/server/pages/404.html +1 -1
  104. package/.next/standalone/.next/server/pages/500.html +1 -1
  105. package/.next/standalone/.next/server/preview-props.json +3 -3
  106. package/.next/standalone/.next/server/server-reference-manifest.js +1 -1
  107. package/.next/standalone/.next/server/server-reference-manifest.json +23 -23
  108. package/.next/standalone/.next/static/chunks/{3hk5y4kny2ktd.js → 05g1pu2r8o5q3.js} +1 -1
  109. package/.next/standalone/.next/static/chunks/{2zlfhyqvlvf7o.js → 098vx6twrn-vk.js} +1 -1
  110. package/.next/standalone/.next/static/chunks/0oxlfb02aqo3e.js +1 -0
  111. package/.next/standalone/.next/static/chunks/{110hwwc6agsr8.js → 0p14j2e6dnj1x.js} +1 -1
  112. package/.next/standalone/.next/static/chunks/12ys9uaq6i1h2.js +6 -0
  113. package/.next/standalone/.next/static/chunks/{435eshlryosz1.js → 1osrmi14e2jub.js} +1 -1
  114. package/.next/standalone/.next/static/chunks/2o8j51ujh1ox4.js +1 -0
  115. package/.next/standalone/.next/static/chunks/2zwsbp8xyfv__.js +1 -0
  116. package/.next/standalone/.next/static/chunks/{2wye36b3mbzpa.js → 34rjkinfk6d4p.js} +1 -1
  117. package/.next/standalone/.next/static/chunks/{2wh64znsc_mo2.js → 38lnk75xvqiug.js} +1 -1
  118. package/.next/standalone/.next/static/chunks/3d6_vjbvr0c2n.js +1 -0
  119. package/.next/standalone/assets/logos/failproof-dark.png +0 -0
  120. package/.next/standalone/assets/logos/failproof-light.png +0 -0
  121. package/.next/standalone/fp-cloud-cli/CHANGELOG.md +24 -3
  122. package/.next/standalone/fp-cloud-cli/fp_cli/_version.py +1 -1
  123. package/.next/standalone/fp-cloud-cli/uv.lock +6 -6
  124. package/.next/standalone/hermes-plugin/plugin.yaml +1 -1
  125. package/.next/standalone/node_modules/@next/env/package.json +1 -1
  126. package/.next/standalone/node_modules/next/dist/build/swc/index.js +1 -1
  127. package/.next/standalone/node_modules/next/dist/compiled/next-server/app-page-turbo-experimental.runtime.prod.js +1 -1
  128. package/.next/standalone/node_modules/next/dist/compiled/next-server/app-page-turbo.runtime.prod.js +1 -1
  129. package/.next/standalone/node_modules/next/dist/compiled/next-server/app-route-turbo.runtime.prod.js +1 -1
  130. package/.next/standalone/node_modules/next/dist/lib/patch-incorrect-lockfile.js +3 -3
  131. package/.next/standalone/node_modules/next/dist/server/app-render/async-local-storage.js +1 -1
  132. package/.next/standalone/node_modules/next/dist/server/base-http/node.js +7 -2
  133. package/.next/standalone/node_modules/next/dist/server/config.js +1 -1
  134. package/.next/standalone/node_modules/next/dist/server/dev/hot-reloader-turbopack.js +2 -2
  135. package/.next/standalone/node_modules/next/dist/server/dev/hot-reloader-webpack.js +1 -1
  136. package/.next/standalone/node_modules/next/dist/server/lib/app-info-log.js +1 -1
  137. package/.next/standalone/node_modules/next/dist/server/lib/router-server.js +1 -1
  138. package/.next/standalone/node_modules/next/dist/server/lib/start-server.js +1 -1
  139. package/.next/standalone/node_modules/next/dist/server/lib/trace/tracer.js +1 -1
  140. package/.next/standalone/node_modules/next/dist/server/use-cache/use-cache-wrapper.js +1 -1
  141. package/.next/standalone/node_modules/next/dist/telemetry/anonymous-meta.js +1 -1
  142. package/.next/standalone/node_modules/next/dist/telemetry/events/swc-load-failure.js +1 -1
  143. package/.next/standalone/node_modules/next/dist/telemetry/events/version.js +2 -2
  144. package/.next/standalone/node_modules/next/package.json +10 -10
  145. package/.next/standalone/package.json +10 -10
  146. package/.next/standalone/sdk/python/uv.lock +18 -18
  147. package/.next/standalone/sdk/typescript/integration/fixtures/nextjs/package-lock.json +40 -40
  148. package/.next/standalone/sdk/typescript/integration/fixtures/nextjs/package.json +1 -1
  149. package/.next/standalone/server.js +1 -1
  150. package/README.md +174 -83
  151. package/dist/cli.mjs +11 -11
  152. package/dist/worker.mjs +1 -1
  153. package/hermes-plugin/plugin.yaml +1 -1
  154. package/openclaw-plugin/daemon-client.js +95 -26
  155. package/openclaw-plugin/hooks.js +4 -1
  156. package/package.json +10 -10
  157. package/.next/standalone/.next/static/chunks/107jrtkeylnrv.js +0 -6
  158. package/.next/standalone/.next/static/chunks/19e9khxgv8fb8.js +0 -1
  159. package/.next/standalone/.next/static/chunks/2codb6nb412m9.js +0 -1
  160. package/.next/standalone/.next/static/chunks/2maurwweshrsj.js +0 -1
  161. package/.next/standalone/.next/static/chunks/3v49ogp389dun.js +0 -1
  162. /package/.next/standalone/.next/static/{-iBiSmrLiylRKLAg77zlQ → -AugwIGiiIYcahO4J7mdM}/_buildManifest.js +0 -0
  163. /package/.next/standalone/.next/static/{-iBiSmrLiylRKLAg77zlQ → -AugwIGiiIYcahO4J7mdM}/_clientMiddlewareManifest.js +0 -0
  164. /package/.next/standalone/.next/static/{-iBiSmrLiylRKLAg77zlQ → -AugwIGiiIYcahO4J7mdM}/_ssgManifest.js +0 -0
@@ -1,3 +1,3 @@
1
- module.exports=[74493,a=>{"use strict";let b,c,d,e,f,g;var h,i=a.i(14747);function j(a){return a.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var k=((h={}).AnonymousId="anonymous_id",h.DistinctId="distinct_id",h.Props="props",h.EnablePersonProcessing="enable_person_processing",h.PersonMode="person_mode",h.FeatureFlagDetails="feature_flag_details",h.FeatureFlags="feature_flags",h.FeatureFlagPayloads="feature_flag_payloads",h.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",h.BootstrapFeatureFlags="bootstrap_feature_flags",h.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",h.OverrideFeatureFlags="override_feature_flags",h.Queue="queue",h.AiQueue="ai_queue",h.AiCaptureQueue="ai_capture_queue",h.LogsQueue="logs_queue",h.OptedOut="opted_out",h.SessionId="session_id",h.SessionStartTimestamp="session_start_timestamp",h.SessionLastTimestamp="session_timestamp",h.PersonProperties="person_properties",h.GroupProperties="group_properties",h.InstalledAppBuild="installed_app_build",h.InstalledAppVersion="installed_app_version",h.SessionReplay="session_replay",h.PushRegistered="push_registered",h.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",h.SurveyLastSeenDate="survey_last_seen_date",h.SurveysInProgress="surveys_in_progress",h.SurveysSeen="surveys_seen",h.Surveys="surveys",h.RemoteConfig="remote_config",h.FlagsEndpointWasHit="flags_endpoint_was_hit",h.DeviceId="device_id",h);let l={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",LOCAL_EVALUATION_INCONCLUSIVE:"local_evaluation_inconclusive",QUOTA_LIMITED:"quota_limited",TIMEOUT:"timeout",CONNECTION_ERROR:"connection_error",UNKNOWN_ERROR:"unknown_error",apiError:a=>`api_error_${a}`};function m(a,b){return -1!==a.indexOf(b)}function n(a){let b=[];return JSON.stringify(a,function(a,c){if("bigint"==typeof c)return c.toString();if("function"!=typeof c&&"symbol"!=typeof c){if(c instanceof Error)return{name:c.name,message:c.message,stack:c.stack};if(c&&"object"==typeof c){for(;b.length>0&&b[b.length-1]!==this;)b.pop();if(b.includes(c))return"[Circular]";b.push(c)}return c}})??"null"}let o=Array.isArray,p=Object.prototype;p.hasOwnProperty;let q=p.toString,r=o||function(a){return"[object Array]"===q.call(a)},s=a=>void 0===a,t=a=>"[object String]"==q.call(a),u=a=>t(a)&&0===a.trim().length,v=a=>null===a,w=a=>s(a)||v(a);function x(a){switch(Object.prototype.toString.call(a)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return z(a,Error)}}function y(a){return"u">typeof Event&&z(a,Event)}function z(a,b){try{return a instanceof b}catch{return!1}}let A=[!0,"true",1,"1","yes"],B=[!1,"false",0,"0","no"];function C(a,b,c){return a&&c?b.length===Object.keys(c).length&&b.every(b=>a[b]===c[b]):a===c}class D{constructor(a,b,c=[]){this.coercers=a,this.stackParser=b,this.modifiers=c}buildFromUnknown(a,b={}){let c=b&&b.mechanism||{handled:!0,type:"generic"},d=this.buildCoercingContext(c,b,0).apply(a),e=this.buildParsingContext(b),f=this.parseStacktrace(d,e);return{$exception_list:this.convertToExceptionList(f,c),$exception_level:"error"}}async modifyFrames(a){for(let b of a)b.stacktrace&&b.stacktrace.frames&&r(b.stacktrace.frames)&&(b.stacktrace.frames=await this.applyModifiers(b.stacktrace.frames));return a}coerceFallback(a){return{type:"Error",value:"Unknown error",stack:a.syntheticException?.stack,synthetic:!0}}parseStacktrace(a,b){let c,d;if(null!=a.cause&&(c=this.parseStacktrace(a.cause,b)),""!=a.stack&&null!=a.stack)try{d=this.applyChunkIds(this.stackParser(a.stack,a.synthetic?b.skipFirstLines:0),b.chunkIdMap)}catch{}return{...a,cause:c,stack:d,errors:a.errors?.map(a=>this.parseStacktrace(a,b))}}applyChunkIds(a,b){return a.map(a=>(a.filename&&b&&(a.chunk_id=b[a.filename]),a))}applyCoercers(a,b){for(let c of this.coercers)if(c.match(a))return c.coerce(a,b);return this.coerceFallback(b)}async applyModifiers(a){let b=a;for(let a of this.modifiers)b=await a(b);return b}convertToExceptionList(a,b){let c=[],d=(a,e,f)=>{let g=c.length,h=void 0===e?{type:"string"==typeof b.type&&b.type.length>0?b.type:"generic",..."boolean"==typeof b.handled?{handled:b.handled}:void 0===b.handled?{handled:!0}:{},synthetic:"boolean"==typeof b.synthetic?b.synthetic:a.synthetic,exception_id:g}:{type:"chained",source:f,synthetic:a.synthetic,exception_id:g,parent_id:e},i={type:a.type,value:a.value,mechanism:h};for(let b of(a.stack&&(i.stacktrace={type:"raw",frames:a.stack}),c.push(i),a.cause&&d(a.cause,g,"cause"),a.errors??[]))d(b,g,"member")};return d(a),c}buildParsingContext(a){return{chunkIdMap:function(a){let f=globalThis._posthogChunkIds,g=globalThis._debugIds;if(!f&&!g)return;let h=f?Object.keys(f):[],i=g?Object.keys(g):[];if(e&&C(f,h,c)&&C(g,i,d))return e;c=f?{...f}:void 0,d=g?{...g}:void 0,e={},b??={};let j=(c,d)=>{for(let f of c){let c=d[f];if(!c)continue;let g=b?.[f];if(g){e[g]=c;continue}let h=a(f);for(let a=h.length-1;a>=0;a--){let d=h[a]?.filename;if(d){e[d]=c,b[f]=d;break}}}};return g&&j(i,g),f&&j(h,f),e}(this.stackParser),skipFirstLines:a.skipFirstLines??1}}getAggregateErrors(a){try{if(x(a)){let b=Object.getPrototypeOf(a);for(let c=0;b&&c<100;c++){let c=Object.getOwnPropertyDescriptor(b,"constructor")?.value;if("function"==typeof c&&"AggregateError"===c.name){let b=a.errors;return r(b)?b:void 0}b=Object.getPrototypeOf(b)}}}catch{}}buildCoercingContext(a,b,c=0){let d=0,e=0,f=!1,g=new Set,h=[],i={},j=(a,b,c=0)=>{let j,l,m=k(b,c),n=m.apply;if(m.apply=b=>{h.push(a);try{return n(b)}finally{h.pop()}},c>4||c>0&&-1!==h.indexOf(a))return this.coerceFallback(m);let o="object"==typeof a&&null!==a||"function"==typeof a;if(0===c&&d>=50||o&&g.has(a))return;o&&g.add(a),0===c&&d++;let p=this.getAggregateErrors(a);f||=!!p;try{if(!(j=this.applyCoercers(a,m)))throw i}catch(a){if(a===i){0===c&&d--;return}if(!f)throw a;j=this.coerceFallback(m)}if(!p||d>=50)return j;try{l=p.length}catch{return j}if(!Number.isInteger(l)||l<0||l>0xffffffff)return j;let q=[];for(let a=0;d<50&&e<1e3&&a<l;a++){let c;e++;try{c=m.next(p[a])}catch{d++,c=this.coerceFallback(k(b+1))}c&&q.push(c)}return{...j,errors:q}},k=(c,d=0)=>({...b,syntheticException:0==c?b.syntheticException:void 0,mechanism:0==c?a:{},apply:a=>{let b=j(a,c,d+1);if(!b)throw i;return b},next:a=>j(a,c+1)}),l=k(c);return{...l,apply:a=>j(a,c)??this.coerceFallback(l)}}}a.s(["ErrorPropertiesBuilder",0,D],6762),a.i(6762);let E=/^([a-z][a-z0-9.+-]+):/i,F=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function G(a,b,c,d,e){let f={platform:a,filename:b,function:"<anonymous>"===c?"?":c,in_app:function(a){if(!a||"<anonymous>"===a)return!1;let b=E.exec(a);return!b||F.includes(b[1].toLowerCase())}(b)};return s(d)||(f.lineno=d),s(e)||(f.colno=e),f}let H=(a,b)=>{let c=-1!==a.indexOf("safari-extension"),d=-1!==a.indexOf("safari-web-extension");return c||d?[-1!==a.indexOf("@")?a.split("@")[0]:"?",c?`safari-extension:${b}`:`safari-web-extension:${b}`]:[a,b]},I=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,J=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,K=/\((\S*)(?::(\d+))(?::(\d+))\)/,L=(a,b)=>{let c=I.exec(a);if(c){let[,a,d,e]=c;return G(b,a,"?",+d,+e)}let d=J.exec(a);if(d){if(d[2]&&0===d[2].indexOf("eval")){let a=K.exec(d[2]);a&&(d[2]=a[1],d[3]=a[2],d[4]=a[3])}let[a,c]=H(d[1]||"?",d[2]);return G(b,c,a,d[3]?+d[3]:void 0,d[4]?+d[4]:void 0)}},M=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,N=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,O=(a,b)=>{let c=M.exec(a);if(c){if(c[3]&&c[3].indexOf(" > eval")>-1){let a=N.exec(c[3]);a&&(c[1]=c[1]||"eval",c[3]=a[1],c[4]=a[2],c[5]="")}let a=c[3],d=c[1]||"?";return[d,a]=H(d,a),G(b,a,d,c[4]?+c[4]:void 0,c[5]?+c[5]:void 0)}},P=/\(error: (.*)\)/;function Q(a,b){return a.filename===b.filename&&a.function===b.function&&a.module===b.module&&a.lineno===b.lineno&&a.colno===b.colno}function R(a,b){let c=b.start;for(;c>0&&Q(a[c-1],a[c-1+b.length]);)c--;return b.start-c}function S(a,b){let c=b.start+b.length,d=c;for(;d<a.length&&Q(a[d],a[d-b.length]);)d++;return d-c}function T(a,...b){return(c,d=0)=>{let e=[],f=c.split("\n"),g=Math.min(f.length,d+1e3),h=[];for(let c=d;c<g;c++){let d=f[c];if(d.length>1024)continue;let g=P.test(d)?d.replace(P,"$1"):d;if(!g.match(/\S*Error: /)){for(let c of b){let b=c(g,a);if(b){e.push(b);let a=function(a){for(let b=1;b<=10;b++){let c=a.length-2*b;if(c<0)break;let d=!0;for(let e=0;e<b;e++)if(!Q(a[c+e],a[c+b+e])){d=!1;break}if(d){for(let d=0;d<b;d++)a[c+d]=a[c+b+d];return a.length=c+b,{start:c,length:b}}}}(e);if(a){for(let b=h.length-1;b>=0;b--){let c=h[b];if(c.start+c.length<=a.start)break;h.pop()}h.push(a)}break}}if(function(a,b){let c=b[0],d=a.length-(c?R(a,c):0);for(let c of b)d-=S(a,c);return d}(e,h)>=50)break}}let i=[...h].sort((a,b)=>b.start-a.start),j=i[i.length-1];if(j){let a=R(e,j);for(let b of(e.splice(j.start-a,a),i))b.start-=a}for(let a of i)!function(a,b){let c=b.start+b.length,d=S(a,b);d&&a.splice(c+d===a.length?c:b.start,d)}(e,a);h.some(a=>0===a.start&&e.length===a.length)&&function(a){let b=a.map(a=>`${a.function}|${a.filename}|${a.lineno}|${a.colno}|${a.module}`),c=0;for(let a=1;a<b.length;a++)(function(a,b,c){for(let d=0;d<a.length;d++){let e=a[(b+d)%a.length],f=a[(c+d)%a.length];if(e!==f)return e<f}return!1})(b,a,c)&&(c=a);a.push(...a.splice(0,c))}(e);if(!e.length)return[];let k=Array.from(e);return k.reverse(),k.slice(0,50).map(a=>{var b;return{...a,filename:a.filename||((b=k)[b.length-1]||{}).filename,function:a.function||"?"}})}}let U=/^\s*[-]{4,}$/,V=/at (?:async (?!\((?!.*\)\s+\()))?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,W=/^Promise\.(?:all|any)$/,X=/^index \d+$/,Y=(a,b)=>{let c=a.match(V);if(c){let a,d,e,f,g;if(c[1]){let b=(e=c[1]).lastIndexOf(".");if("."===e[b-1]&&b--,b>0){a=e.slice(0,b),d=e.slice(b+1);let c=a.indexOf(".Module");c>0&&(e=e.slice(c+1),a=a.slice(0,c))}f=void 0}d&&(f=a,g=d),"<anonymous>"===d&&(g=void 0,e=void 0),void 0===e&&(g=g||"?",e=f?`${f}.${g}`:g);let h=c[2]?.startsWith("file://")?c[2].slice(7):c[2],i="native"===c[5];return h?.match(/\/[A-Z]:/)&&(h=h.slice(1)),h||!c[5]||i||(h=c[5]),W.test(e)&&X.test(h||"")&&(h="node:internal/promise"),{filename:h?decodeURI(h):void 0,module:void 0,function:e,lineno:Z(c[3]),colno:Z(c[4]),in_app:function(a,b=!1){return!(b||a&&!a.startsWith("/")&&!a.match(/^[A-Z]:/)&&!a.startsWith(".")&&!a.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==a&&!a.includes("node_modules/")}(h||"",i),platform:b}}if(a.match(U))return{filename:a,platform:b}};function Z(a){return parseInt(a||"",10)||void 0}a.s(["createStackParser",0,T,"nodeStackLineParser",0,Y],64583),a.i(64583),a.s([],51671),a.i(51671);class ${match(a){return x(a)}coerce(a,b){let c=this.getStack(a),d=void 0===c?b.syntheticException?.stack:void 0;return{type:this.getType(a),value:this.getMessage(a,b),stack:c??d,cause:a.cause?b.next(a.cause):void 0,synthetic:!!d}}getType(a){return a.name||a.constructor.name}getMessage(a,b){let c=a.message;return c.error&&"string"==typeof c.error.message?String(c.error.message):String(c)}getStack(a){try{let b=a.stacktrace;if("string"==typeof b&&b.length>0)return b;let c=a.stack;return"string"==typeof c&&c.length>0?c:void 0}catch{return}}}a.s(["ErrorCoercer",0,$],10692),a.i(10692),a.s([],75368),a.i(75368);let _=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class aa{match(a){return"string"==typeof a}coerce(a,b){let[c,d]=this.getInfos(a);return{type:c??"Error",value:d??a,stack:b.syntheticException?.stack,synthetic:!0}}getInfos(a){let b="Error",c=a,d=a.match(_);return d&&(b=d[1],c=d[2]),[b,c]}}a.s(["StringCoercer",0,aa],57802),a.i(57802);let ab=["fatal","error","warning","log","info","debug"];function ac(a,b=40){let c=Object.keys(a);if(c.sort(),!c.length)return"[object has no keys]";for(let a=c.length;a>0;a--){let d=c.slice(0,a).join(", ");if(!(d.length>b)){if(a===c.length)return d;return d.length<=b?d:`${d.slice(0,b)}...`}}return""}class ad{match(a){return"object"==typeof a&&null!==a}coerce(a,b){let c=this.getErrorPropertyFromObject(a);return c?b.apply(c):{type:this.getType(a),value:this.getValue(a),stack:this.getStack(a)??b.syntheticException?.stack,level:this.isSeverityLevel(a.level)?a.level:"error",synthetic:!0}}getType(a){if(y(a))return a.constructor.name;let b="name"in a?a.name:void 0;return t(b)&&!u(b)?b:"Error"}getValue(a){if("name"in a&&"string"==typeof a.name){let b=`'${a.name}' captured as exception`;return"message"in a&&"string"==typeof a.message&&(b+=` with message: '${a.message}'`),b}if("message"in a&&"string"==typeof a.message)return a.message;let b=this.getObjectClassName(a),c=ac(a);return`${b&&"Object"!==b?`'${b}'`:"Object"} captured as exception with keys: ${c}`}isSeverityLevel(a){return t(a)&&!u(a)&&ab.indexOf(a)>=0}getStack(a){try{if(t(a.stacktrace)&&a.stacktrace.length>0)return a.stacktrace;return t(a.stack)&&a.stack.length>0?a.stack:void 0}catch{return}}getErrorPropertyFromObject(a){for(let b in a)if(Object.prototype.hasOwnProperty.call(a,b)){let c=a[b];if(x(c))return c}}getObjectClassName(a){try{let b=Object.getPrototypeOf(a);return b?b.constructor.name:void 0}catch(a){return}}}a.s(["ObjectCoercer",0,ad],93874),a.i(93874);class ae{match(a){return y(a)}coerce(a,b){let c=a.constructor.name;return{type:c,value:`${c} captured as exception with keys: ${ac(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["EventCoercer",0,ae],46980),a.i(46980);class af{match(a){return null===a||"object"!=typeof a}coerce(a,b){return{type:"Error",value:`Primitive value captured as exception: ${String(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["PrimitiveCoercer",0,af],28150),a.i(28150),a.s([],98140),a.i(98140),a.s(["ErrorCoercer",0,$,"EventCoercer",0,ae,"ObjectCoercer",0,ad,"PrimitiveCoercer",0,af,"StringCoercer",0,aa],54253),a.i(54253);class ag{constructor(a){this._maxSize=a,this._cache=new Map}get(a){let b=this._cache.get(a);if(void 0!==b)return this._cache.delete(a),this._cache.set(a,b),b}set(a,b){this._cache.set(a,b)}reduce(){for(;this._cache.size>=this._maxSize;){let a=this._cache.keys().next().value;a&&this._cache.delete(a)}}}a.s(["ReduceableCache",0,ag],98966),a.i(98966);function ah(){if("u">typeof process){let a=process.env.POSTHOG_RELEASE_ID?.trim();if(a)return a}let a=globalThis._posthogReleaseId;return"string"==typeof a&&a.length>0?a:void 0}a.s([],97383),a.i(97383),a.s(["getInjectedReleaseId",0,ah],28861),a.i(28861),a.s(["ErrorCoercer",0,$,"ErrorPropertiesBuilder",0,D,"EventCoercer",0,ae,"ObjectCoercer",0,ad,"PrimitiveCoercer",0,af,"ReduceableCache",0,ag,"StringCoercer",0,aa,"createStackParser",0,T,"getInjectedReleaseId",0,ah,"nodeStackLineParser",0,Y],60485);var ai=a.i(60485),ai=ai,aj=a.i(2157),ak=a.i(12714),al=a.i(50227),am=a.i(1457);let an=new ai.ReduceableCache(25),ao=new ai.ReduceableCache(20);async function ap(a,b=ak.open,c){let d,e={};try{d=process.cwd()}catch{}for(let b=a.length-1;b>=0;b--){var f,g;let c=a[b],h=c?.filename;!(!c||"string"!=typeof h||"number"!=typeof c.lineno||(f=h).startsWith("node:")||f.endsWith(".min.js")||f.endsWith(".min.cjs")||f.endsWith(".min.mjs")||f.startsWith("data:")||void 0!==(g=c).lineno&&g.lineno>1e4||void 0!==g.colno&&g.colno>1e3)&&((0,al.isAbsolute)(h)||void 0!==d)&&(e[h]||(e[h]=[]),e[h].push(c.lineno))}let h=Object.keys(e);if(0==h.length)return a;let i=[];for(let a of h){let f=at(a,d);if(void 0===f||ao.get(f))continue;let g=e[a];if(!g)continue;g.sort((a,b)=>a-b);let h=function(a){if(!a.length)return[];let b=0,c=a[0];if("number"!=typeof c)return[];let d=au(c),e=[];for(;;){if(b===a.length-1){e.push(d);break}let c=a[b+1];if("number"!=typeof c)break;c<=d[1]?d[1]=c+7:(e.push(d),d=au(c)),b++}return e}(g);if(h.every(a=>(function(a,b){let c=an.get(a);if(void 0===c)return!1;for(let a=b[0];a<=b[1];a++)if(void 0===c[a])return!1;return!0})(f,a)))continue;let j=function(a,b,c){let d=a.get(b);return void 0===d?(a.set(b,c),c):d}(an,f,{});i.push(ar(a,h,j,f,b,c))}return await Promise.all(i).catch(()=>{}),a&&a.length>0&&function(a,b,c){for(let d of a)if(d.filename&&void 0===d.context_line&&"number"==typeof d.lineno){let a=at(d.filename,c),e=void 0===a?void 0:b.get(a);if(void 0===e)continue;!function(a,b,c){if(void 0===b.lineno||void 0===c)return;b.pre_context=[];for(let d=av(a);d<a;d++){let a=c[d];if(void 0===a)return void as(b);b.pre_context.push(a)}if(void 0===c[a])return as(b);b.context_line=c[a];let d=function(a){return a+7}(a);b.post_context=[];for(let e=a+1;e<=d;e++){let a=c[e];if(void 0===a)break;b.post_context.push(a)}}(d.lineno,d,e)}}(a,an,d),an.reduce(),a}async function aq(a,b,c){let d,e=!1;try{d=await b(a,aj.constants.O_RDONLY|aj.constants.O_NONBLOCK);let f=await d.stat();if(!f.isFile())return;if(f.size>0xa00000)return void c?.debug(`Skipping source context for oversized file ${a}: ${f.size} bytes exceeds 10485760`);return e=!0,d}catch{return}finally{d&&!e&&await d.close().catch(()=>{})}}async function ar(a,b,c,d,e,f){let g=await aq(a,e,f);return void 0===g?void ao.set(d,1):new Promise(a=>{let e,f,h=!1;function i(b){h||(h=!0,b?.destroy(),g.close().then(a,a))}try{e=g.createReadStream({autoClose:!1,start:0,end:0x9fffff})}catch{ao.set(d,1),i();return}try{f=(0,am.createInterface)({input:e})}catch{ao.set(d,1),i(e);return}let j=0,k=0,l=b[0];if(void 0===l)return void i(e);let m=l[0],n=l[1];function o(){ao.set(d,1),f.close(),f.removeAllListeners(),i(e)}e.on("error",o),f.on("error",o),f.on("close",()=>i(e)),f.on("line",a=>{if(!(++j<m)&&(c[j]=function(a,b){let c=a,d=c.length;if(d<=150)return c;b>d&&(b=d);let e=Math.max(b-60,0);e<5&&(e=0);let f=Math.min(e+140,d);return f>d-5&&(f=d),f===d&&(e=Math.max(f-140,0)),c=c.slice(e,f),e>0&&(c=`...${c}`),f<d&&(c+="..."),c}(a,0),j>=n)){if(k===b.length-1){f.close(),f.removeAllListeners();return}let a=b[++k];if(void 0===a){f.close(),f.removeAllListeners();return}m=a[0],n=a[1]}})})}function as(a){delete a.pre_context,delete a.context_line,delete a.post_context}function at(a,b){return(0,al.isAbsolute)(a)?JSON.stringify([null,a]):void 0===b?void 0:JSON.stringify([b,a])}function au(a){return[av(a),a+7]}function av(a){return Math.max(1,a-7)}class aw{constructor(){this.events={},this.events={}}on(a,b){return this.events[a]||(this.events[a]=[]),this.events[a].push(b),()=>{this.events[a]=this.events[a].filter(a=>a!==b)}}emit(a,b){for(let c of this.events[a]||[])c(b);for(let c of this.events["*"]||[])c(a,b)}}let ax=a=>void 0===a?void 0:a.variant??a.enabled,ay=a=>{if("string"!=typeof a)return a;try{return JSON.parse(a)}catch{return a}},az=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","bfcid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],aA=(a,b=[])=>{let c={},d=b=>{void 0!==a[b]&&(c[b]=a[b])};return az.forEach(d),b.forEach(d),c},aB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function aC(a,b){return"string"==typeof a&&aB.test(a)?a:b()}function aD(a,b){let c=Error(b);try{Object.defineProperty(c,"name",{value:a,writable:!0,enumerable:!0,configurable:!0})}catch{}return c}function aE(a){return a?.replace(/\/+$/,"")}function aF(a){return a?a.split("#")[0]:a}async function aG(a,b){let c=null;for(let d=0;d<b.retryCount+1;d++){d>0&&await new Promise(a=>setTimeout(a,b.retryDelay));try{return await a()}catch(a){if(c=a,!b.retryCheck(a))throw a}}throw c}function aH(){return new Date().toISOString()}function aI(a,b){let c=setTimeout(a,b);return c?.unref&&c?.unref(),c}async function aJ(a,b,c){let d;try{return await Promise.race([a,new Promise((a,e)=>{d=aI(()=>{try{c?.(),a()}catch(a){e(a)}},b)})])}finally{clearTimeout(d)}}function aK(a){return Promise.all(a.map(a=>(a??Promise.resolve()).then(a=>({status:"fulfilled",value:a}),a=>({status:"rejected",reason:a}))))}let aL=a=>{throw aD("NativeGzipValidationError",`Native gzip produced invalid output: ${a}`)},aM=async(a,b)=>{a.size<18&&aL("too-short");let c=new Uint8Array(await a.slice(0,10).arrayBuffer());c.length>=2&&31===c[0]&&139===c[1]&&8===c[2]||aL("invalid-header");let d=new DataView(await a.slice(a.size-8).arrayBuffer());d.getUint32(0,!0)!==(a=>{let b=(()=>{if(f)return f;f=[];for(let a=0;a<256;a++){let b=a;for(let a=0;a<8;a++)b=1&b?0xedb88320^b>>>1:b>>>1;f[a]=b>>>0}return f})(),c=0xffffffff;for(let d=0;d<a.length;d++)c=b[(c^a[d])&255]^c>>>8;return(0xffffffff^c)>>>0})(b)&&aL("invalid-crc");let e=b.length>>>0;d.getUint32(4,!0)!==e&&aL("invalid-size")};async function aN(a,b=!0,c){try{let b=new TextEncoder().encode(a),c=new globalThis.CompressionStream("gzip"),d=c.writable.getWriter(),e=d.write(b).then(()=>d.close()).catch(async a=>{try{await d.abort(a)}catch{}throw a}),f=new Response(c.readable).blob(),[g]=await Promise.all([f,e]);return await aM(g,b),g}catch(a){if(c?.rethrow)throw a;return b&&console.error("Failed to gzip compress data",a),null}}let aO="0123456789abcdef";class aP{constructor(a){this.bytes=a}static ofInner(a){if(16===a.length)return new aP(a);throw TypeError("not 128-bit length")}static fromFieldsV7(a,b,c,d){if(!Number.isInteger(a)||!Number.isInteger(b)||!Number.isInteger(c)||!Number.isInteger(d)||a<0||b<0||c<0||d<0||a>0xffffffffffff||b>4095||c>0x3fffffff||d>0xffffffff)throw RangeError("invalid field value");let e=new Uint8Array(16);return e[0]=a/0x10000000000,e[1]=a/0x100000000,e[2]=a/0x1000000,e[3]=a/65536,e[4]=a/256,e[5]=a,e[6]=112|b>>>8,e[7]=b,e[8]=128|c>>>24,e[9]=c>>>16,e[10]=c>>>8,e[11]=c,e[12]=d>>>24,e[13]=d>>>16,e[14]=d>>>8,e[15]=d,new aP(e)}static parse(a){let b;switch(a.length){case 32:b=/^[0-9a-f]{32}$/i.exec(a)?.[0];break;case 36:b=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(a)?.slice(1,6).join("");break;case 38:b=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(a)?.slice(1,6).join("");break;case 45:b=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(a)?.slice(1,6).join("")}if(b){let a=new Uint8Array(16);for(let c=0;c<16;c+=4){let d=parseInt(b.substring(2*c,2*c+8),16);a[c+0]=d>>>24,a[c+1]=d>>>16,a[c+2]=d>>>8,a[c+3]=d}return new aP(a)}throw SyntaxError("could not parse UUID string")}toString(){let a="";for(let b=0;b<this.bytes.length;b++)a+=aO.charAt(this.bytes[b]>>>4),a+=aO.charAt(15&this.bytes[b]),(3===b||5===b||7===b||9===b)&&(a+="-");return a}toHex(){let a="";for(let b=0;b<this.bytes.length;b++)a+=aO.charAt(this.bytes[b]>>>4),a+=aO.charAt(15&this.bytes[b]);return a}toJSON(){return this.toString()}getVariant(){let a=this.bytes[8]>>>4;if(a<0)throw Error("unreachable");if(a<=7)return this.bytes.every(a=>0===a)?"NIL":"VAR_0";if(a<=11)return"VAR_10";if(a<=13)return"VAR_110";if(a<=15)return this.bytes.every(a=>255===a)?"MAX":"VAR_RESERVED";throw Error("unreachable")}getVersion(){return"VAR_10"===this.getVariant()?this.bytes[6]>>>4:void 0}clone(){return new aP(this.bytes.slice(0))}equals(a){return 0===this.compareTo(a)}compareTo(a){for(let b=0;b<16;b++){let c=this.bytes[b]-a.bytes[b];if(0!==c)return Math.sign(c)}return 0}}class aQ{constructor(a){this.timestamp=0,this.counter=0,this.random=a??aR()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(a,b){let c=this.generateOrAbortCore(a,b);return void 0===c&&(this.timestamp=0,c=this.generateOrAbortCore(a,b)),c}generateOrAbortCore(a,b){if(!Number.isInteger(a)||a<1||a>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(b<0||b>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(a>this.timestamp)this.timestamp=a,this.resetCounter();else{if(!(a+b>=this.timestamp))return;this.counter++,this.counter>0x3ffffffffff&&(this.timestamp++,this.resetCounter())}return aP.fromFieldsV7(this.timestamp,Math.trunc(this.counter/0x40000000),0x3fffffff&this.counter,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let a=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return a[6]=64|a[6]>>>4,a[8]=128|a[8]>>>2,aP.ofInner(a)}}let aR=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),aS=()=>aT().toString(),aT=()=>(g||(g=new aQ)).generate();class aU{add(a){let b=aS(),c=++this.nextId;return this.promiseByIds[b]={id:c,promise:a},a.catch(()=>{}).finally(()=>{delete this.promiseByIds[b]}),a}async join(){let a=Object.values(this.promiseByIds).map(a=>a.promise),b=a.length;for(;b>0;)await Promise.all(a),b=(a=Object.values(this.promiseByIds).map(a=>a.promise)).length}getPromises(a=[],b=this.nextId){let c=new Set(a);return Object.values(this.promiseByIds).filter(a=>a.id<=b&&!c.has(a.promise)).map(a=>a.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}let aV=(a,b,c)=>{function d(e,...f){b(()=>{(0,c[e])(a,...f)})}return{debug:(...a)=>{d("debug",...a)},info:(...a)=>{d("log",...a)},warn:(...a)=>{d("warn",...a)},error:(...a)=>{d("error",...a)},critical:(...b)=>{c.error(a,...b)},createLogger:d=>aV(`${a} ${d}`,b,c)}};function aW(a,b=Date.now(),c=3e5){if("string"!=typeof a||!a)return;let d=a.trim(),e=/^\d+\s*,/.test(d)?d.slice(0,d.indexOf(",")).trim():d;if(/^\d+$/.test(e)){let a=1e3*Math.min(Number(e),c/1e3);return a>0?a:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(e))return;let f=Date.parse(/^\w{3} \w{3} /.test(e)?e+" GMT":e)-b;if(Number.isFinite(f)&&!(f<=0))return Math.min(f,c)}class aX{record(a){if("too-large"===a.kind)return;if("retry-later"!==a.kind)return void this.reset();if(!a.retryAfterMs)return;let b=this.isOpen(),c=Date.now(),d=Math.min(a.retryAfterMs,3e5);if(!b){this._installedAt=c,this._until=c+d;return}this._until=Math.max(this._until,Math.min(c+d,this._installedAt+3e5))}remainingMs(){let a=Date.now();if(a<this._installedAt-5e3)return this.reset(),0;let b=Math.min(3e5,Math.max(0,this._until-a));return 0===b&&this.reset(),b}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}}class aY extends Error{constructor(a,b,c,d){super("HTTP error while fetching PostHog: status="+a.status+", reqByteLength="+b),this.response=a,this.reqByteLength=b,this.responseBodyDeadline=c,this.abortController=d,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return aW(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 a=aD("AbortError","Response body read timed out");this.cancelResponseBody(a),this.responseBodyTextPromise=Promise.reject(a)}else{let a,b=new Promise((a,b)=>{this.responseBodyTimer=aI(()=>{this._bodyReadTimedOut=!0;let a=aD("AbortError","Response body read timed out");b(a),this.cancelResponseBody(a)},this.responseBodyDeadline-Date.now())});try{a=Promise.resolve(this.response.text())}catch(b){a=Promise.reject(b)}this.responseBodyTextPromise=Promise.race([a,b]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(a=>JSON.parse(a))}cancelResponseBody(a){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(a),(async()=>{try{await this.response.body?.cancel()}catch{}})()}}class aZ extends Error{constructor(a){super("Network error while fetching PostHog",a instanceof Error?{cause:a}:{}),this.error=a,this.name="PostHogFetchNetworkError"}}async function a$(a){if(a instanceof aY){let b="";try{b=await a.text}catch{a.bodyReadTimedOut&&(b="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${a.message}, response body=${b}`,a)}else console.error("Error while flushing PostHog",a);return Promise.resolve()}function a_(a){return a instanceof aZ}function a0(a){if(a instanceof aY)return 502===a.status||504===a.status;if(!(a instanceof aZ))return!1;let b=a.error;return"ECONNREFUSED"!==(b?.code??b?.cause?.code)}function a1(a){try{if("string"!=typeof a)return a instanceof Uint8Array?a.byteLength:a.size;if("u">typeof Buffer)return Buffer.byteLength(a,"utf8");return new TextEncoder().encode(a).length}catch{return 0}}function a2(a){return"object"==typeof a&&a instanceof aY&&413===a.status}function a3(a){return a instanceof aY?408===a.status||429===a.status||a.status>=500:a_(a)}function a4(a){return null!==a&&"object"==typeof a&&!Array.isArray(a)}let a5="default";class a6{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new D([new $,new ad,new aa,new af],T("web:javascript",L,O))}getEvaluationRuntime(){}get apiKey(){return this.projectToken}constructor(a,b={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new aU,this._events=new aw,this._isInitialized=!1;let c="string"==typeof a?a.trim():"",d="string"==typeof b.host?b.host.trim():"",e=!c;this._logger=function(a,b=a=>a()){return aV(a,b,function(a=console){return{log:a.log.bind(a),warn:a.warn.bind(a),error:a.error.bind(a),debug:a.debug.bind(a)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),e&&this._logger.error("You must pass your PostHog project token. The client will be disabled."),this.projectToken=c,this.host=aE(d||"https://us.i.posthog.com"),this.flushAt=b.flushAt?Math.max(b.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,b.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,b.maxQueueSize??1e3),this.flushInterval=b.flushInterval??1e4,this.preloadFeatureFlags=b.preloadFeatureFlags??!0,this.defaultOptIn=b.defaultOptIn??!0,this.disableSurveys=b.disableSurveys??!1,this._retryOptions={retryCount:b.fetchRetryCount??3,retryDelay:b.fetchRetryDelay??3e3,retryCheck:a3},this.requestTimeout=b.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=b.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=b.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=b.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=b.disableGeoip??!0,this.disabled=(b.disabled??!1)||e,this.historicalMigration=b?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=b?.evaluationContexts??b?.evaluationEnvironments,b?.evaluationEnvironments&&!b?.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)||(b?.disableCompression??!1)}logMsgIfDebug(a){this.isDebug&&a()}wrap(a){return this.disabled?void this._logger.warn("The client is disabled"):this._isInitialized?a():void this._initPromise.then(()=>a())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(k.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(k.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(k.OptedOut,!0)})}on(a,b){return this._events.on(a,b)}debug(a=!0){if(this.removeDebugCallback?.(),a){let a=this.on("*",(a,b)=>this._logger.info(a,b));this.removeDebugCallback=()=>{a(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(a){let b=a.properties||{},c=this.mergeCommonEventProperties(b);var d=c;for(let a of Object.keys(b))(a.startsWith("$feature/")||"$active_feature_flags"===a)&&(d[a]=b[a]);return"$feature_flag_called"===a.event&&!1===c.$feature_flag_has_experiment&&this.isMinimalFlagCalledEventsEnabled()&&(c=aA(c)),{distinct_id:a.distinct_id,event:a.event,properties:c}}mergeCommonEventProperties(a){return{...a,...this.getCommonEventProperties()}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(a){return this.promiseQueue.add(a)}identifyStateless(a,b,c){this.wrap(()=>{let d={...this.buildPayload({distinct_id:a,event:"$identify",properties:b})};this.enqueue("identify",d,c)})}async identifyStatelessImmediate(a,b,c){let d={...this.buildPayload({distinct_id:a,event:"$identify",properties:b})};await this.sendImmediate("identify",d,c)}captureStateless(a,b,c,d){this.wrap(()=>{let e=this.buildPayload({distinct_id:a,event:b,properties:c});this.enqueue("capture",e,d)})}async captureStatelessImmediate(a,b,c,d){let e=this.buildPayload({distinct_id:a,event:b,properties:c});await this.sendImmediate("capture",e,d)}aliasStateless(a,b,c,d){this.wrap(()=>{let e=this.buildPayload({event:"$create_alias",distinct_id:b,properties:{...c||{},distinct_id:b,alias:a}});this.enqueue("alias",e,d)})}async aliasStatelessImmediate(a,b,c,d){let e=this.buildPayload({event:"$create_alias",distinct_id:b,properties:{...c||{},distinct_id:b,alias:a}});await this.sendImmediate("alias",e,d)}groupIdentifyStateless(a,b,c,d,e,f){this.wrap(()=>{let g=this.buildPayload({distinct_id:e||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{},...f||{}}});this.enqueue("capture",g,d)})}async groupIdentifyStatelessImmediate(a,b,c,d,e,f){let g=this.buildPayload({distinct_id:e||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{},...f||{}}});await this.sendImmediate("capture",g,d)}async getRemoteConfig(){await this._initPromise;let a=this.host;"https://us.i.posthog.com"===a?a="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===a&&(a="https://eu-assets.i.posthog.com");let b=`${a}/array/${this.projectToken}/config`,c={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(b,c,{type:"required",consume:a=>a.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(a=>{this._logger.error("Remote config could not be loaded",a),this._events.emit("error",a)})}async getFlags(a,b={},c={},d={},e={},f=!1){await this._initPromise;let g=`${this.host}/flags/?v=2${f?"&config=true":""}`,h={token:this.projectToken,distinct_id:a,groups:b,person_properties:c,group_properties:d,...e};c.$device_id&&(h.$device_id=c.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(h.evaluation_contexts=this.evaluationContexts);let i=this.getEvaluationRuntime();i&&(h.evaluation_runtime=i);let j={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(h)};return this._logger.info("Flags URL",g),this.fetchWithRetry(g,j,{type:"required",consume:a=>a.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:a0},this.featureFlagsRequestTimeoutMs).then(a=>({success:!0,response:(a=>{if("flags"in a){let b,c=Object.fromEntries(Object.entries(a.flags??{}).map(([a,b])=>[a,ax(b)]).filter(([,a])=>void 0!==a)),d=Object.fromEntries(Object.keys(b=a.flags??{}).filter(a=>{let c=b[a];return c.enabled&&c.metadata&&void 0!==c.metadata.payload}).map(a=>{let c=b[a].metadata?.payload;return[a,c?ay(c):void 0]}));return{...a,featureFlags:c,featureFlagPayloads:d}}{let b=a.featureFlags??{},c=Object.fromEntries(Object.entries(a.featureFlagPayloads||{}).map(([a,b])=>[a,ay(b)])),d=Object.fromEntries(Object.entries(b).map(([a,b])=>{var d,e;return[a,{key:a,enabled:"string"==typeof(d=b)||d,variant:"string"==typeof d?d:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:(e=c[a])?JSON.stringify(e):void 0,description:void 0}}]}));return{...a,featureFlags:b,featureFlagPayloads:c,flags:d}}})(a)})).catch(a=>(this._events.emit("error",a),{success:!1,error:this.categorizeRequestError(a)}))}categorizeRequestError(a){if(a instanceof aY)return{type:"api_error",statusCode:a.status};if(a instanceof aZ){let b=a.error;return b instanceof Error&&("AbortError"===b.name||"TimeoutError"===b.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagDetailStateless(a,b,c,d,e,f);if(void 0===g)return{response:void 0,requestId:void 0};let h=ax(g.response);return void 0===h&&(h=!1),{response:h,requestId:g.requestId}}async getFeatureFlagDetailStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagDetailsStateless(b,c,d,e,f,[a]);if(void 0!==g)return{response:g.flags[a],requestId:g.requestId,evaluatedAt:g.evaluatedAt}}async getFeatureFlagPayloadStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagPayloadsStateless(b,c,d,e,f,[a]);if(!g)return;let h=g[a];return void 0===h?null:h}async getFeatureFlagPayloadsStateless(a,b={},c={},d={},e,f){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(a,b,c,d,e,f)).payloads}async getFeatureFlagsStateless(a,b={},c={},d={},e,f){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(a,b,c,d,e,f)}async getFeatureFlagsAndPayloadsStateless(a,b={},c={},d={},e,f){await this._initPromise;let g=await this.getFeatureFlagDetailsStateless(a,b,c,d,e,f);return g?{flags:g.featureFlags,payloads:g.featureFlagPayloads,requestId:g.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(a,b={},c={},d={},e,f){await this._initPromise;let g={geoip_disable:e??this.disableGeoip};f&&(g.flag_keys_to_evaluate=f);let h=await this.getFlags(a,b,c,d,g);if(!h.success)return;let i=h.response;return(i.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"),i.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:i?.requestId,quotaLimited:i.quotaLimited}):i}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let a=`${this.host}/api/surveys/?token=${this.projectToken}`,b={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},c=await this.fetchWithRetry(a,b,{type:"required",consume:a=>{if(200!==a.status||!a.json){let b=`Surveys API could not be loaded: ${a.status}`,c=Error(b);return this._logger.error(c),this._events.emit("error",Error(b)),Promise.resolve(void 0)}return a.json()}}).catch(a=>{this._logger.error("Surveys API could not be loaded",a),this._events.emit("error",a)}),d=c?.surveys;return d&&this._logger.info("Surveys fetched from API: ",JSON.stringify(d)),d??[]}get props(){return this._props||(this._props=this.getPersistedProperty(k.Props)),this._props||{}}set props(a){this._props=a}async register(a){this.wrap(()=>{this.props={...this.props,...a},this.setPersistedProperty(k.Props,this.props)})}async unregister(a){this.wrap(()=>{delete this.props[a],this.setPersistedProperty(k.Props,this.props)})}processBeforeEnqueue(a){return a}async flushStorage(){}getQueueRouteKey(a){return a5}persistedQueueKeyForRoute(a){return k.Queue}getActiveQueueRoutes(){return[a5]}getRouteQueue(a){return this.getPersistedProperty(this.persistedQueueKeyForRoute(a))||[]}enqueue(a,b,c,d){this.wrap(()=>{if(this.optedOut)return void this._events.emit(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let e=this.prepareMessage(b,c);if(null===(e=this.processBeforeEnqueue(e)))return;e=this.normalizeMessage(e);let f=this.persistedQueueKeyForRoute(d??this.getQueueRouteKey(e)),g=this.getPersistedProperty(f)||[];g.length>=this.maxQueueSize&&(g.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),g.push({message:e}),this.setPersistedProperty(f,g),this._events.emit(a,e),g.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=aI(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(a,b,c,d){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(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let e=this.prepareMessage(b,c);if(null!==(e=this.processBeforeEnqueue(e))){e=this.normalizeMessage(e);try{await this.sendBatch([e],void 0,d??this.getQueueRouteKey(e))}catch(a){this._events.emit("error",a)}}}normalizeMessage(a){let{type:b,library:c,library_version:d,...e}=a,f=a4(e.properties)?e.properties:void 0;return void 0!==c&&f?.$lib===void 0&&(f={...f||{},$lib:c}),void 0!==d&&f?.$lib_version===void 0&&(f={...f||{},$lib_version:d}),f&&(e.properties=f),e.uuid=aC(e.uuid,aS),e}normalizeTimestampForWire(a){let b=a instanceof Date?a:"string"==typeof a?new Date(a):null;if(!b||Number.isNaN(b.getTime()))return a;let c=b.toISOString(),d="string"==typeof a?a.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return d&&d.length>3?c.replace(/\.\d{3}Z$/,`.${d}Z`):c}prepareMessage(a,b){let c={...a,timestamp:b?.timestamp?b?.timestamp:aH(),uuid:aC(b?.uuid,aS)};return(b?.disableGeoip??this.disableGeoip)&&(a4(c.properties)||(c.properties={}),c.properties.$geoip_disable=!0),c.distinctId&&(c.distinct_id=c.distinctId,delete c.distinctId),c}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async a=>{await a$(a)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(a,b=[]){let c=b.filter(a=>!!a),d=0;for(;;){let b=this.promiseQueue.getPromises([...c,...this.flushPromises],a);if(0===b.length)return;d>0&&this._logger.debug(`flush() re-checking ${b.length} pending promise(s) before flushing`),await Promise.all(b.map(a=>a.catch(()=>{}))),d++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(a){if(this.disabled)return Promise.resolve();if(!a&&this.pendingFlushPromise)return this.pendingFlushPromise;let b=this.flushPromise,c=this.promiseQueue.maxId,d=Promise.resolve().then(()=>{if(a)return this.waitForPendingPromises(c,[b,d])}).then(()=>aK([b])).then(()=>(this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=d,this.flushPromise=d,this.flushPromises.add(d),this.addPendingPromise(d),aK([d]).then(()=>{this.flushPromises.delete(d),this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this.flushPromise===d&&(this.flushPromise=null)}),d}getCustomHeaders(){let a=this.getCustomUserAgent(),b={};return a&&""!==a&&(b["User-Agent"]=a),b}compressPayload(a){return aN(a,this.isDebug)}getBatchEndpointPath(a){return"/batch/"}async sendBatch(a,b,c=a5){let d={api_key:this.projectToken,batch:a.map(a=>{if(!a)return a;let b=this.normalizeTimestampForWire(a.timestamp);return b===a.timestamp?a:{...a,timestamp:b}}),sent_at:aH()};this.historicalMigration&&(d.historical_migration=!0);let e=n(d),f=`${this.host}${this.getBatchEndpointPath(c)}`,g=this.disableCompression?null:await this.compressPayload(e),h={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==g&&{"Content-Encoding":"gzip"}},body:g||e};await this.fetchWithRetry(f,h,{type:"successful-write"},b)}async _flush(){let a;this.clearFlushTimer(),await this._initPromise;let b=this.getActiveQueueRoutes();if(!b.some(a=>this.getRouteQueue(a).length>0))return;let c=[];for(let d of b)try{await this._flushRoute(d,c)}catch(b){void 0===a&&(a=b)}if(void 0!==a)throw a;this._events.emit("flush",c)}async _flushRoute(a,b){let c=this.persistedQueueKeyForRoute(a),d=this.getPersistedProperty(c)||[];if(!d.length)return;let e=d.length,f=0;for(;d.length>0&&f<e;){let e=d.slice(0,this.maxBatchSize),g=e.map(a=>void 0===a.message?a.message:this.normalizeMessage(a.message)),h=async()=>{let a=this.getPersistedProperty(c)||[],b=[...e],f=a.filter(a=>{let c=a.message?.uuid,d=b.findIndex(b=>b===a||"string"==typeof c&&c.length>0&&b.message?.uuid===c);return -1===d||(b.splice(d,1),!1)});this.setPersistedProperty(c,f),d=f,this._dequeuedMessagesCount+=e.length,await this.flushStorage()},i={retryCheck:a=>!a2(a)&&a3(a)};try{await this.sendBatch(g,i,a)}catch(a){if(a2(a)&&g.length>1){this.maxBatchSize=Math.max(1,Math.floor(g.length/2)),this._logger.warn(`Received 413 when sending batch of size ${g.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw a instanceof aZ||await h(),this._events.emit("error",a),a}await h(),b.push(...g),f+=g.length}}async _sendOtlpBatch({path:a,auth:b,payload:c}){let d;if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};try{d=JSON.stringify(c)}catch(b){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${a} batch; reporting it as too large`,b)),{kind:"too-large",measuredLocally:!0}}let e=a1(d);if(e>0xa00000)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${a} batch of ${e} bytes: the endpoint accepts at most 10485760`)),{kind:"too-large",measuredLocally:!0};let f="bearer"===b?`${this.host}/i/v1/${a}`:`${this.host}/i/v1/${a}?token=${encodeURIComponent(this.projectToken)}`,g=this.disableCompression?null:await this.compressPayload(d),h=g||d,i={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",..."bearer"===b&&{Authorization:`Bearer ${this.projectToken}`},...null!==g&&{"Content-Encoding":"gzip"}},body:h};try{return await this.fetchWithRetry(f,i,{type:"successful-write"},{retryCheck:a=>!a2(a)&&(!(a instanceof aY)||void 0===a.retryAfterMs)&&a3(a)}),{kind:"ok"}}catch(a){if(a2(a))return{kind:"too-large"};if(a3(a)){let b=a instanceof aY?a.retryAfterMs:void 0;return{kind:"retry-later",error:a,...void 0!==b&&{retryAfterMs:b}}}return{kind:"fatal",error:a}}}async _sendLogsBatch(a){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:a})}async _sendMetricsBatch(a){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:a})}async _sendTracesBatch(a){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:a})}async fetchWithRetry(a,b,c,d,e){let f=a1(b.body?b.body:""),g={...this._retryOptions,...d},h=0;return await aG(async()=>{let d,g,i;h++;let j=new AbortController,k=e??this.requestTimeout,l=Date.now()+k,m=new Promise((a,b)=>{d=aI(()=>{let a=aD("AbortError",`Request timed out after ${k}ms`);b(a),j.abort(a)},k)}),n=!1,o=()=>i??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let d;try{d=this.fetch(a,{signal:j.signal,...b})}catch(a){throw new aZ(a)}d.then(a=>{j.signal.aborted&&!n&&Promise.resolve(a.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([d,m]),n=!0}catch(a){throw new aZ(a)}let e="no-cors"===b.mode,h="successful-write"===c.type?300:400;if(!e&&(g.status<200||g.status>=h))throw new aY(g,f,l,j);if("successful-write"===c.type){try{await Promise.race([o(),m])}catch{}return}try{return await Promise.race([c.consume(g),m])}catch(a){if(j.signal.aborted)throw new aZ(a);throw a}}finally{clearTimeout(d),j.signal.aborted&&g&&o()}},{...g,retryCheck:a=>{let b=g.retryCheck(a);return b&&h<=g.retryCount&&a instanceof aY&&a.cancelResponseBody(),b}})}async _shutdown(a=3e4){await this._initPromise;let b=!1;if(this.clearFlushTimer(),!this.disabled)return aJ((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(a=>this.getRouteQueue(a).length>0);){let a=this._dequeuedMessagesCount;if(await this.flush(),b)break;if(this._dequeuedMessagesCount===a){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(a){if(!("object"==typeof a&&(a instanceof aY||a_(a))))throw a;await a$(a)}})(),a,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:a}),b=!0})}async shutdown(a=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(a).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}class a7{constructor(a){this._onFire=a,this._firesAt=0}get pending(){return!!this._timer}arm(a){this.clear(),this._firesAt=Date.now()+a,this._timer=aI(()=>{this._timer=void 0,this._onFire()},a)}armNoEarlierThan(a){this._timer&&Date.now()+a<=this._firesAt||this.arm(a)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}function a8(){return .75+.25*Math.random()*2}function a9(a,b,c,d){let e=Math.min(Math.max(0,b-1),6),f=a*2**e;return Math.round((void 0===d?f:Math.min(f,Math.max(d,a)))*c)}let ba="[Circular]",bb="[Truncated]",bc="[Unserializable]";function bd(a){let b="";for(let c=0;c<a.length;c++){let d=a.charCodeAt(c);if(d>=55296&&d<=56319){let d=a.charCodeAt(c+1);d>=56320&&d<=57343?(b+=a[c]+a[c+1],c++):b+="�"}else b+=d>=56320&&d<=57343?"�":a[c]}return b}function be(a,b){if(!b)return a;let c=[];try{c=Object.keys(b)}catch{c=[]}for(let d of c){let c;try{c=b[d]}catch{c=bc}Object.defineProperty(a,d,{value:c,enumerable:!0,writable:!0,configurable:!0})}return a}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let bf=Object.prototype.propertyIsEnumerable;function bg(a,b){try{return bh(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function bh(a,b,c,d){let e=[];for(let f in a)if(bf.call(a,f)){if(!f){b?.debug("Dropping an attribute with an empty key");continue}if(e.length>=1e3||c.remainingNodes<=0){b?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let g=a[f];if(v(g)||s(g))continue;e.push({key:bd(f),value:function a(b,c,d,e){if(d.remainingNodes<=0)return{stringValue:bb};if(d.remainingNodes--,"[object Boolean]"===q.call(b))return{boolValue:b};if("bigint"==typeof b){let a,d;return a=b.toString(),b>=(d=BigInt("9223372036854775808"))||b<-d?(c?.debug(`Attribute ${a} is outside the int64 range; encoding it as a string`),{stringValue:a}):{intValue:a}}if("number"==typeof b){if(!Number.isFinite(b))return{stringValue:String(b)};if(Number.isInteger(b)){if(Number.isSafeInteger(b))return{intValue:String(b)};if("u"<typeof BigInt)return{stringValue:String(b)};let a=BigInt(b).toString();return b>=0x8000000000000000||b<-0x8000000000000000?(c?.debug(`Attribute ${a} is outside the int64 range; encoding it as a string`),{stringValue:a}):{intValue:a}}return{doubleValue:b}}if("string"==typeof b)return{stringValue:bd(b)};if("function"==typeof b)return{stringValue:"[Function]"};if("symbol"==typeof b)return{stringValue:String(b)};if("object"==typeof b&&null!==b){if(d.ancestors.has(b))return{stringValue:ba};if(e>=20)return{stringValue:bb};if(b instanceof Date){let a=Number.isFinite(b.getTime())?b.toISOString():String(b);return{stringValue:"string"==typeof a?bd(a):String(a)}}d.ancestors.add(b);try{try{let f=b.toJSON;if("function"==typeof f)return a(f.call(b),c,d,e+1)}catch{}if(r(b))return{arrayValue:{values:function(b,c,d,e){let f=[],g=Math.min(b.length,1e3),h=0;for(;h<g&&d.remainingNodes>0;h++)try{let g=h in b?b[h]:void 0;if(w(g))continue;f.push(a(g,c,d,e))}catch{f.push({stringValue:bc})}return b.length>h&&f.push({stringValue:bb}),f}(b,c,d,e+1)}};return{kvlistValue:{values:bh(b,c,d,e+1)}}}finally{d.ancestors.delete(b)}}return{stringValue:bd(String(b))}}(g,b,c,d)})}catch{e.push({key:bd(f),value:{stringValue:bc}})}}return e}let bi="0000000000000000",bj=bi+bi,bk=/^[0-9a-f]+$/;function bl(a){let b=function(a){let b="";for(let c=0;c<a.length;c++)b+=a[c].toString(16).padStart(2,"0");return b}(function(a){let b=new Uint8Array(a),c=globalThis.crypto;if(c&&"function"==typeof c.getRandomValues)try{return c.getRandomValues(b),b}catch{}for(let c=0;c<a;c++)b[c]=Math.floor(256*Math.random());return b}(a));return/[^0]/.test(b)?b:b.slice(0,-1)+"1"}function bm(a,b,c){return"string"==typeof a&&a.length===b&&a!==c&&bk.test(a)}let bn=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function bo(a){let b=bp(a);return b&&{traceId:b.traceId,spanId:b.spanId,flags:1&parseInt(b.flags,16)?br:bs}}function bp(a){if("string"!=typeof a)return;let b=bn.exec(a.trim());if(!b)return;let[,c,d,e,f,g]=b;if("ff"!==c&&("00"!==c||!g)&&bm(d,32,bj)&&bm(e,16,bi))return{version:c,traceId:d,spanId:e,flags:f}}function bq(a){return Array.isArray(a)&&1===a.length?a[0]:a}let br="01",bs="00";function bt(a){if("string"!=typeof a)return;let b=a.trim();if(!b||/[^\x20-\x7e\t]/.test(b))return;let c=b.split(",");if(!(c.length>32)){for(let a of c)if(a.trim()&&!a.includes("="))return;return b.length<=512?b:function(a){let b=[...a],c=()=>b.reduce((a,b)=>a+b.length,0)+b.length-1;for(let a=b.length-1;a>=0&&c()>512;a--)b[a].length>128&&b.splice(a,1);for(;b.length&&c()>512;)b.pop();return b.length?b.join(","):void 0}(c)}}function bu(a,b,c){return{...be({},a.resourceAttributes),"service.name":a.serviceName||"unknown_service",...a.environment&&{"deployment.environment":a.environment},...a.serviceVersion&&{"service.version":a.serviceVersion},"telemetry.sdk.name":b,"telemetry.sdk.version":c}}let bv=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function bw(a,b){let c=be({},a),d={};for(let a of bv)Object.prototype.hasOwnProperty.call(c,a)&&(d[a]=c[a],delete c[a]);return[...bg(c,b),...bg(d,b)]}let bx={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"},by=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function bz(a){return String(a)+"000000"}function bA(a,b,c,d){let e="";return d&&(e=Object.keys(d).sort().map(a=>`${JSON.stringify(a)}:${JSON.stringify(d[a])}`).join(",")),`${a}\0${b}\0${c??""}\0${e}`}class bB{constructor(a,b,c){this._instance=a,this._config=b,this._logger=c,this._series=new Map,this._flushTimer=new a7(()=>this.flush().catch(a=>{this._logger.error("Metrics flush failed:",a)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._boundsByHistogram=new Map,this._boundsConflictWarned=new Set,this._boundsCapWarned=!1,this._retryAfter=new aX,this._consecutiveFlushFailures=0,this._flushJitter=1,this._generation=0}count(a,b=1,c){this._capture({name:a,type:"count",value:b,unit:c?.unit,attributes:c?.attributes})}gauge(a,b,c){this._capture({name:a,type:"gauge",value:b,unit:c?.unit,attributes:c?.attributes})}histogram(a,b,c){this._capture({name:a,type:"histogram",value:b,unit:c?.unit,attributes:c?.attributes,bounds:r(c?.bounds)?c.bounds.slice():c?.bounds})}flush(){let a=this._flushPromise,b=(async()=>{a&&await a.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===b&&(this._flushPromise=null)});return this._flushPromise=b,b}drainWindow(){if(0===this._series.size)return null;let a=this._series;return this._startWindow(),this._buildPayload(a)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=1,this._flushTimer.clear(),this._flushPromise=null,this._startWindow(),this._boundsByHistogram=new Map,this._boundsCapWarned=!1}_startWindow(){this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._boundsConflictWarned=new Set}_capture(a){var b;let c,d,e;if(this._instance.isDisabled||this._instance.optedOut)return;let f=this._runBeforeSend(a);if(null===f)return;if(!f.name||"string"!=typeof f.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof f.value||!Number.isFinite(f.value))return void this._logger.warn(`Dropping metric '${f.name}': value must be a finite number`);if("count"!==f.type&&"gauge"!==f.type&&"histogram"!==f.type)return void this._logger.warn(`Dropping metric '${f.name}': unknown type '${String(f.type)}'`);if("count"===f.type&&f.value<0)return void this._logger.warn(`Dropping count '${f.name}': counters are monotonic, value must be >= 0`);try{c=f.attributes?{...f.attributes}:void 0,d=bA(f.type,f.name,f.unit,c)}catch(a){this._logger.warn(`Dropping metric '${f.name}': attributes could not be serialized`,a);return}let g=this._series.get(d);if(!g&&!this._admitNewSeries()||"histogram"===f.type&&!(e=this._histogramBounds(f.name,f.unit,f.bounds)))return;g||(g={name:f.name,type:f.type,unit:f.unit,attributes:c,windowStartMs:Date.now(),hist:e&&{bounds:b=e,count:0,sum:0,min:1/0,max:-1/0,bucketCounts:Array(b.length+1).fill(0)}},this._series.set(d,g));let h=this._typeByName.get(f.name);void 0===h?this._typeByName.set(f.name,f.type):h===f.type||this._typeCollisionWarned.has(f.name)||(this._typeCollisionWarned.add(f.name),this._logger.warn(`Metric name '${f.name}' is already used as a ${h}; recording it as a ${f.type} too will blend both series in charts. Use a distinct name.`)),this._fold(g,f.value);let i=this._activeTraceContext();i&&(g.exemplar={...i,value:f.value,timeMs:Date.now()}),this._armFlushTimer()}_activeTraceContext(){try{let a=bo(this._instance.getActiveSpan?.()?.traceparent());if(a&&a.flags===br)return{traceId:a.traceId,spanId:a.spanId}}catch{}}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush||(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_histogramBounds(a,b,c){if(void 0!==c&&!function(a){if(!r(a)||0===a.length)return!1;for(let b=0;b<a.length;b++)if(!Number.isFinite(a[b])||b>0&&a[b]<=a[b-1])return!1;return!0}(c))return void this._logger.warn(`Dropping histogram '${a}': bounds must be a non-empty array of finite, strictly increasing numbers`);let d=bA("histogram",a,b,void 0),e=this._boundsByHistogram.get(d);if(e)return this._warnOnBoundsConflict(a,d,e,c),e;if(this._boundsByHistogram.size>=this._config.maxSeriesPerFlush){if(this._boundsCapWarned||(this._boundsCapWarned=!0,this._logger.warn(`Histogram bounds limit reached (${this._config.maxSeriesPerFlush} distinct histograms); new histograms that pass custom bounds are dropped. Reduce histogram name cardinality.`)),c&&!bC(c,by))return;return by}let f=c?c.slice():by;return this._boundsByHistogram.set(d,f),f}_warnOnBoundsConflict(a,b,c,d){bC(c,d??by)||this._boundsConflictWarned.has(b)||(this._boundsConflictWarned.add(b),this._logger.warn(`Histogram '${a}' already uses the bounds [${c.join(", ")}]; samples that pass different bounds are recorded in those buckets.`))}_fold(a,b){switch(a.type){case"count":a.total=(a.total??0)+b;break;case"gauge":a.last=b;break;case"histogram":{let c=a.hist;c.count+=1,c.sum+=b,c.min=Math.min(c.min,b),c.max=Math.max(c.max,b),c.bucketCounts[function(a,b){for(let c=0;c<b.length;c++)if(a<=b[c])return c;return b.length}(b,c.bounds)]+=1}}}_runBeforeSend(a){let b=this._config.beforeSend;if(!b)return a;let c=r(b)?b:[b],d=a;for(let a of c)try{let b=a(d);if(!b)return this._logger.info("Metric was rejected in beforeSend function"),null;d=b}catch(a){return this._logger.error("Error in beforeSend function for metric:",a),null}return d}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(a9(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),0===this._series.size)return;let a=this._series;this._startWindow();let b=this._generation,c=await this._instance._sendMetricsBatch(this._buildPayload(a));if(b===this._generation)switch(this._retryAfter.record(c),"retry-later"===c.kind?(this._consecutiveFlushFailures++,this._flushJitter=a8()):(this._consecutiveFlushFailures=0,this._flushJitter=1),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),c.kind){case"ok":return;case"retry-later":this._mergeWindowBack(a),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:",c.error);return}}_buildPayload(a){var b,c,d,e;return b=this._buildMetrics(a),c=bu(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),d=this._instance.getLibraryId(),e=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:bw(c)},scopeMetrics:[{scope:{name:d,version:e},metrics:b}]}]}}_buildMetrics(a){let b=bz(Date.now()),c=new Map;for(let e of a.values()){var d;let a=bA(e.type,e.name,e.unit,void 0),f=c.get(a);f||(f={name:e.name,...e.unit&&{unit:e.unit}},"count"===e.type?f.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===e.type?f.gauge={dataPoints:[]}:f.histogram={aggregationTemporality:1,dataPoints:[]},c.set(a,f));let g=bg(e.attributes??{},this._logger),h=bz(e.windowStartMs),i=(d=e.exemplar)?{exemplars:[{filteredAttributes:[],timeUnixNano:bz(d.timeMs),asDouble:d.value,traceId:d.traceId,spanId:d.spanId}]}:{};if("count"===e.type){let a={attributes:g,startTimeUnixNano:h,timeUnixNano:b,asDouble:e.total??0,...i};f.sum.dataPoints.push(a)}else if("gauge"===e.type){let a={attributes:g,timeUnixNano:b,asDouble:e.last??0,...i};f.gauge.dataPoints.push(a)}else{let a=e.hist,c={attributes:g,startTimeUnixNano:h,timeUnixNano:b,count:a.count,sum:a.sum,min:a.min,max:a.max,bucketCounts:a.bucketCounts,explicitBounds:a.bounds,...i};f.histogram.dataPoints.push(c)}}return Array.from(c.values())}_mergeWindowBack(a){for(let[b,c]of a){let a=this._series.get(b);if(!a){this._admitNewSeries()&&this._series.set(b,c);continue}switch(a.windowStartMs=Math.min(a.windowStartMs,c.windowStartMs),a.exemplar=a.exemplar??c.exemplar,a.type){case"count":a.total=(a.total??0)+(c.total??0);break;case"gauge":break;case"histogram":{let b=a.hist,d=c.hist;b.count+=d.count,b.sum+=d.sum,b.min=Math.min(b.min,d.min),b.max=Math.max(b.max,d.max);for(let a=0;a<b.bucketCounts.length;a++)b.bucketCounts[a]+=d.bucketCounts[a]}}}}}function bC(a,b){if(a===b)return!0;if(a.length!==b.length)return!1;for(let c=0;c<a.length;c++)if(a[c]!==b[c])return!1;return!0}let bD="unknown";function bE(a,b,c,d){return"string"==typeof a&&a.trim()?a.length>c?a.slice(0,c):a:(d?.debug(`${b} must be a non-empty string; using "${bD}"`),bD)}function bF(a){if(null==a)return;let b=a;if(a instanceof Date)try{b=a.getTime()}catch{return}if("number"==typeof b&&Number.isFinite(b)&&!(b<0)&&!(b>0x8637bd05af6))return b}function bG(a,b,c,d){let e=bF(a);return void 0===e?(void 0!==a&&d?.debug(`Span ${c} is out of range or not a valid time; using the derived time`),b):e}function bH(){let a=globalThis.performance;return"function"==typeof a?.now?a.now():void 0}class bI{constructor(a,b,c){for(let d of(this._onEnd=b,this._logger=c,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=a.traceId,this._spanId=a.spanId,this._parentSpanId=a.parentSpanId,this._traceState=a.traceState,this._traceFlags=a.traceFlags??br,this._parentIsRemote=a.parentIsRemote??!1,this._name=a.name,this._kind=a.kind,this._autoKeys=new Set(a.autoAttributeKeys),this._maxAttributes=a.maxAttributes,this._maxEvents=a.maxEvents,this._maxAttributesPerEvent=a.maxAttributesPerEvent,this._maxAttributeValueLength=a.maxAttributeValueLength,this._attributes=Object.create(null),Object.keys(a.attributes)))this._writeAttribute(d,a.attributes[d]);this._startMono=a.backdated?void 0:bH(),this._startTime=a.clockAnchor&&void 0!==this._startMono?a.clockAnchor.wall+(this._startMono-a.clockAnchor.mono):a.startTime,void 0!==this._startMono&&(this._clockAnchor=a.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(void 0!==this._startMono){let a=bH();if(void 0!==a)return this._startTime+Math.max(0,a-this._startMono)}return Date.now()}_mutable(a){return!this._ended||(this._logger?.debug(`Ignoring ${a} on a span that has already ended`),!1)}_writeAttribute(a,b){if(w(b)){a in this._attributes&&!this._autoKeys.has(a)&&this._userAttributeCount--,delete this._attributes[a];return}if(!this._autoKeys.has(a)&&!(a in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[a]=bR(b,this._maxAttributeValueLength)}setAttribute(a,b){return this._mutable("setAttribute")&&this._writeAttribute(a,b),this}setAttributes(a){if(this._mutable("setAttributes")){let b=be({},a);for(let a of Object.keys(b))this._writeAttribute(a,b[a])}return this}addEvent(a,b,c){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let d=b&&bS(b,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:bE(a,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:bG(c,this._now(),"event timestamp",this._logger),...d&&{attributes:d.attributes,...d.dropped&&{droppedAttributesCount:d.dropped}}})}return this}setStatus(a,b){if(this._mutable("setStatus")){if("ok"!==a&&"error"!==a)return this._logger?.debug(`Ignoring unknown span status "${String(a)}"; expected "ok" or "error"`),this;this._status={code:a,...b&&{message:bQ(b,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(a){if(!this._mutable("recordException"))return this;let{type:b,message:c,stack:d}=bU(a);return this.addEvent(bJ,{"exception.type":b,"exception.message":c,...d&&{"exception.stacktrace":d}}),this.setStatus("error",c)}updateName(a){return this._mutable("updateName")&&(this._name=bE(a,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return function(a,b,c=br){return`00-${a}-${b}-${c}`}(this._traceId,this._spanId,this._traceFlags)}get traceId(){return this._traceId}get spanId(){return this._spanId}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(a){var b;if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let c=bG(a,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:c<(b=this._startTime)?b:c,...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}}let bJ="exception";function bK(a){return"number"!=typeof a||!Number.isFinite(a)||a<=0?0:Math.min(Math.floor(a),0xffffffff)}class bL{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}get traceId(){return null}get spanId(){return null}tracestate(){return null}end(){}}let bM=new bL;class bN extends bL{constructor(a,b){super(),this._traceparent=a,this._tracestate=b}traceparent(){return this._traceparent}get traceId(){return this._traceparent.split("-")[1]??null}get spanId(){return this._traceparent.split("-")[2]??null}tracestate(){return this._tracestate??null}}function bO(a,b){var c;let d=bq(a?.parent)??b,e=bp(c="string"==typeof d||null==d?d:bP(d,"traceparent"))&&c.trim();return e?new bN(e,bt("string"==typeof d||null==d?a?.tracestate:bP(d,"tracestate"))):bM}function bP(a,b){try{let c=a[b];return"function"==typeof c?c.call(a):void 0}catch{return}}function bQ(a,b){return a.length>b?a.slice(0,b):a}function bR(a,b){return function a(b,c,d,e){if(null===b||"object"!=typeof b)return w(b)||d.remainingNodes<=0?b:(d.remainingNodes--,"string"==typeof b?bQ(b,c):b);if(d.ancestors.has(b))return ba;if(d.remainingNodes<=0||e>=20)return b;d.remainingNodes--,d.ancestors.add(b);try{if(b instanceof Date)return b;let f=function(a){try{let b=a.toJSON;if("function"==typeof b)return{selfDescribed:!0,value:b.call(a)}}catch{}return{selfDescribed:!1}}(b);if(f.selfDescribed)return w(f.value)?String(f.value):a(f.value,c,d,e+1);if(r(b)){let f=Math.min(b.length,1e3),g=[];for(let h=0;h<f;h++)try{g.push(a(b[h],c,d,e+1))}catch{g.push(bc)}return b.length>f&&(g.length=b.length),g}let g={},h=0;for(let f of Object.keys(b)){let i;if(h>=1e3)break;try{i=a(b[f],c,d,e+1)}catch{i=bc}f&&!w(i)&&h++,Object.defineProperty(g,f,{value:i,enumerable:!0,writable:!0,configurable:!0})}return g}catch{return b}finally{d.ancestors.delete(b)}}(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}function bS(a,b,c){let d;try{d=Object.keys(a)}catch{return{attributes:{},dropped:0}}let e={},f=0,g=0;for(let h of d){let d;if(f>=b){g++;continue}try{d=bR(a[h],c)}catch{d=bc}w(d)||(f++,Object.defineProperty(e,h,{value:d,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:e,dropped:g}}function bT(a,b,c){return b===bM?c(b):a.with(b,()=>c(b))}function bU(a){try{let b=function(a){try{let b=a.stack;return"string"==typeof b&&b?{stack:b}:{}}catch{return{}}}(a);if(x(a))return{type:a.name||"Error",message:a.message||"",...b};if("string"==typeof a)return{type:"string",message:a};if(a&&"object"==typeof a&&"string"==typeof a.message)return{type:"string"==typeof a.name?a.name:"Object",message:a.message,...b};return{type:typeof a,message:String(a)}}catch{return{type:typeof a,message:""}}}let bV={internal:1,server:2,client:3,producer:4,consumer:5},bW={ok:1,error:2};function bX(a){if("string"==typeof a)return bd(a);try{return bd(String(a))}catch{return bc}}function bY(a){let b=Math.floor(a),c=Math.round((a-b)*1e6);return c>=1e6&&(b+=1,c=0),String(b)+String(c).padStart(6,"0")}function bZ(){return bH()??Date.now()}function b$(a){try{return a instanceof bI}catch{return!1}}function b_(a,b){let c=bo(a);if(c)return{traceId:c.traceId,parentSpanId:c.spanId,traceState:bt(b),traceFlags:c.flags,isRemote:!0}}function b0(a,b,c){a[b]!==c&&(a[b]=c)}class b1{constructor(a,b,c,d,e,f){this._instance=a,this._config=b,this._logger=c,this._getContext=d,this._contextManager=e,this._onSpanQueued=f,this._queue=[],this._flushTimer=new a7(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter=new aX,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=b.maxExportBatchSize}startSpan(a,b){var c,d;let e;if(this._instance.isDisabled||this._instance.optedOut)return bO(b,this._contextManager.active());let f=bq(b?.parent);if(f&&"string"!=typeof f&&!b$(f)){if(function(a){try{return"function"==typeof a.traceparent}catch{return!1}}(f))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),bO(b,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let g=this._resolveParent(f,b);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached — spans are being started and never ended`),bO(b,this._contextManager.active());let h=Date.now(),i=(c=b?.startTime,d=this._logger,void 0===(e=bF(c))?(void 0!==c&&d?.debug("Span startTime is out of range or not a valid time; using the current time"),h):(h-e>864e5?d?.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"):e>h&&d?.debug("Span startTime is in the future; the span may export with a zero duration"),e)),j=bl(8);this._liveSpans.set(j,bZ());let k=this._autoContextAttributes();return new bI({traceId:g?.traceId??bl(16),spanId:j,parentSpanId:g?.parentSpanId,traceState:g?.traceState,traceFlags:g?.traceFlags,parentIsRemote:g?.isRemote,name:bE(a,"Span name",this._config.maxAttributeValueLength,this._logger),kind:b?.kind??"internal",attributes:be({...k},b?.attributes),autoAttributeKeys:Object.keys(k),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:i,backdated:i!==h,clockAnchor:void 0===bF(b?.startTime)?g?.clockAnchor:void 0},(a,b)=>this._onSpanEnd(a,b),this._logger)}withSpan(a,b,c){let d=this.startSpan(a,"function"==typeof b?void 0:b);try{let a=bT(this._contextManager,d,"function"==typeof b?b:c);if(a&&"function"==typeof a.then)return a.then(a=>(d.end(),a),a=>{throw this._recordCallbackError(d,a),d.end(),a});return d.end(),a}catch(a){throw this._recordCallbackError(d,a),d.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;){if(!this._queue.length)return;let a=this._flushPromise;if(!await (a??this._startFlush()))return}}_startFlush(){this._flushTimer.clear();let a=this._generation,b=Promise.resolve().then(()=>a===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===b&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=b,b}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(a,b){if("string"==typeof a){let c=b_(a,b?.tracestate);return c||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),c}if(b$(a))return a.childContext();let c=this._contextManager.active();return b$(c)?c.childContext():c instanceof bN?b_(c.traceparent(),c.tracestate()??void 0):void 0}_autoContextAttributes(){let a;try{a=this._getContext()}catch(a){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",a),{}}let b={};return a.distinctId&&(b.posthogDistinctId=a.distinctId),a.sessionId&&(b.sessionId=a.sessionId),a.currentUrl&&(b["url.full"]=a.currentUrl),a.screenName&&(b["screen.name"]=a.screenName),a.appState&&(b["app.state"]=a.appState),b}_recordCallbackError(a,b){if(!(a instanceof bI))return;let{type:c,message:d,stack:e}=bU(b);a.addEvent("exception",{"exception.type":c,"exception.message":d,...e&&{"exception.stacktrace":e}}),a.statusIsExplicitlyOk||a.setStatus("error",d)}_evictAgedSpans(){let a=bZ()-this._config.maxSpanAgeMs,b=0;for(let[c,d]of this._liveSpans){if(d>a)break;this._liveSpans.delete(c),b++}b&&this._recordDrop(b,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(a,b){if(!this._liveSpans.delete(a.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let c=this._runBeforeSpanSend(a,b);if(c){if(this._reportLimitDrops(c),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(c);try{this._onSpanQueued?.()}catch(a){this._logger.debug("Span queue notification failed",a)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(a){let b=a.droppedAttributesCount??0,c=a.droppedEventsCount??0,d=0;for(let b of a.events)d+=b.droppedAttributesCount??0;(b||c||d)&&this._logger.debug(`Span limits discarded data from "${a.name}": ${b} attributes, ${c} events, ${d} event attributes`)}_runBeforeSpanSend(a,b){if(!this._config.beforeSpanSend.length)return a;let c={traceId:a.traceId,spanId:a.spanId,parentSpanId:a.parentSpanId,traceState:a.traceState},d={startTime:a.startTime,endTime:a.endTime},e={attributes:a.droppedAttributesCount,events:a.droppedEventsCount},f=Object.keys(a.attributes),g={traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote},h=a.status&&{...a.status},i=a,j=a;try{var k,l,m;for(let a of this._config.beforeSpanSend){let b=a(i);if(!b)return this._recordDrop(1,"beforeSpanSend dropped it"),null;i=this._keepSpanIdentity(b,c)}if(!((k=j={traceId:c.traceId,spanId:c.spanId,parentSpanId:c.parentSpanId,traceState:c.traceState,name:i.name,kind:i.kind,status:i.status,attributes:i.attributes,events:i.events,startTime:i.startTime,endTime:i.endTime,traceFlags:g.traceFlags,parentIsRemote:g.parentIsRemote,droppedAttributesCount:e.attributes,droppedEventsCount:e.events}).attributes&&"object"==typeof k.attributes&&!Array.isArray(k.attributes)&&Array.isArray(k.events)&&void 0!==k.name&&void 0!==k.kind&&void 0!==k.startTime&&void 0!==k.endTime))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;j.name=bE(j.name,"Span name",this._config.maxAttributeValueLength,this._logger),j.status&&"ok"!==j.status.code&&"error"!==j.status.code&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),j.status=h),j.startTime=bF(j.startTime)??d.startTime,j.endTime=(l=bF(j.endTime)??d.endTime,m=j.startTime,l<m?m:l);let a=[];for(let b of j.events)try{a.push({...b,name:bE(b.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:bG(b.timestamp,j.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return j.events=a,!function(a,b,c,d,e,f,g=[]){let h=0,i=0,j={};for(let d of function(a,b){if(!b.length)return Object.keys(a);let c=b.filter(b=>Object.prototype.propertyIsEnumerable.call(a,b)),d=new Set(c);return[...c,...Object.keys(a).filter(a=>!d.has(a))]}(a.attributes,g)){let e=a.attributes[d];if(!w(e)){if(!b.has(d)){if(h>=c){i++;continue}h++}Object.defineProperty(j,d,{value:bR(e,f),enumerable:!0,writable:!0,configurable:!0})}}a.attributes=j,i&&(a.droppedAttributesCount=bK(a.droppedAttributesCount)+i);let k=0,l=0,m=[];for(let b of a.events){if(k>=d){l++;continue}if(k++,b.attributes){let a=bS(b.attributes,e,f);b.attributes=a.attributes,a.dropped&&(b.droppedAttributesCount=bK(b.droppedAttributesCount)+a.dropped)}m.push(b)}a.events=m,l&&(a.droppedEventsCount=bK(a.droppedEventsCount)+l),a.status?.message&&(a.status={...a.status,message:bQ(function(a){try{return"string"==typeof a?a:String(a)}catch{return bc}}(a.status.message),f)})}(j,b,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,f),j}catch(a){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",a),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(a,b){(a.traceId!==b.traceId||a.spanId!==b.spanId||a.parentSpanId!==b.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{b0(a,"traceId",b.traceId),b0(a,"spanId",b.spanId),b0(a,"parentSpanId",b.parentSpanId),b0(a,"traceState",b.traceState)}catch{try{let c=Object.getOwnPropertyDescriptors(a);for(let a of["traceId","spanId","parentSpanId","traceState"])c[a]={value:b[a],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(a),c)}catch{;}}return a}_recordDrop(a,b){this._droppedSinceWarning+=a,this._dropReasons.add(b),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(a){let b=[];for(let c of a)try{b.push(function(a,b){var c;let d,e={traceId:a.traceId,spanId:a.spanId,name:bX(a.name),kind:(c=a.kind)&&Object.prototype.hasOwnProperty.call(bV,c)?bV[c]:bV.internal,startTimeUnixNano:bY(a.startTime),endTimeUnixNano:bY(a.endTime),flags:(Number.isFinite(d=parseInt(a.traceFlags,16))?255&d:1)|256|512*!!a.parentIsRemote};a.parentSpanId&&(e.parentSpanId=a.parentSpanId),a.traceState&&(e.traceState=bX(a.traceState));let f=bg(a.attributes,b);f.length&&(e.attributes=f),a.events.length&&(e.events=a.events.map(a=>(function(a,b){let c={name:bX(a.name),timeUnixNano:bY(a.timestamp)};if(a.attributes){let d=bg(a.attributes,b);d.length&&(c.attributes=d)}let d=bK(a.droppedAttributesCount);return d&&(c.droppedAttributesCount=d),c})(a,b)));let g=bK(a.droppedAttributesCount);g&&(e.droppedAttributesCount=g);let h=bK(a.droppedEventsCount);return h&&(e.droppedEventsCount=h),a.status&&(e.status={code:bW[a.status.code],...a.status.message&&{message:bX(a.status.message)}}),e}(c,this._logger))}catch(a){this._logger.debug("Failed to encode a span; dropping it",a),this._recordDrop(1,"its attributes could not be encoded")}return b}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let a=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(a,"the user has opted out"),this._warnAboutDrops(),a}async _flushInner(){var a,b;if(!this._queue.length)return 0;let c=this._discardQueueIfConsentWithdrawn();if(c)return c;let d=function(a,b){for(let c of Object.keys(a))a[c]=bR(a[c],b);return a}((a=this._config,bu(a,this._instance.getLibraryId(),this._instance.getLibraryVersion())),this._config.maxAttributeValueLength),e=this._instance.getLibraryId(),f=this._instance.getLibraryVersion(),g=this._queue.length,h=0,i=1/0,j=this._generation;try{for(;g>0&&this._queue.length>0;){let a=this._discardQueueIfConsentWithdrawn();if(a)return h+a;let c=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,k=Math.max(1,Math.min(c,i,g,this._queue.length)),l=this._queue.slice(0,k),m=this._encodeBatch(l);if(!m.length){this._queue.splice(0,k),g-=k,h+=k,this._resetHeadBatchBudget();continue}let n=bZ()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),o=await this._instance._sendTracesBatch((b=this._logger,{resourceSpans:[{resource:{attributes:bw(d,b)},scopeSpans:[{scope:{name:e,version:f},spans:m}]}]}));if(j!==this._generation)break;if(this._retryAfter.record(o),"ok"===o.kind){this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._queue.splice(0,k),g-=k,h+=k,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if("too-large"===o.kind){if(1===k){this._queue.splice(0,1),g-=1,h+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget();continue}let a=Math.max(1,Math.floor(k/2));o.measuredLocally?i=a:this._maxExportBatchSize=a,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${a}`);continue}if("retry-later"===o.kind){if(this._consecutiveFlushFailures++,this._flushJitter=a8(),this._headBatchSize=k,n&&(this._headBatchFailures++,this._headBatchChargeableAt=bZ()+this._nextFlushDelay()),this._headBatchFailures<8)return this._logger.debug("Span export failed; retrying on the next flush",o.error),h;if(this._queue.splice(0,k),g-=k,h+=k,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(k,"the ingestion endpoint failed 8 times in a row"),this._retryAfter.isOpen())return h;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",o.error),this._queue.splice(0,k),g-=k,h+=k,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(k,"the ingestion endpoint rejected the batch")}return h}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(a=>{this._logger.debug("Background span flush failed",a)}).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(a9(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}}class b2{active(){return this._active}with(a,b){let c=this._active;this._active=a;try{return b()}finally{this._active=c}}}let b3=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","lightpanda","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],b4=new Map,b5=function(a,b=[]){if(!a)return!1;let c=function(a,b){let c="";for(let a=0;a<b.length;a++){let d=b[a];c+=d.length+":"+d}return a.length+":"+a+"|"+b.length+":"+c}(a,b),d=b4.get(c);if(void 0!==d)return d;let e=a.toLowerCase(),f=b3.concat(b).some(a=>-1!==e.indexOf(a.toLowerCase()));return b4.size>=256&&b4.clear(),b4.set(c,f),f};function b6(a,b){return"number"==typeof a&&Number.isInteger(a)&&a>=1?a:b}let b7=["service.name","service.version","deployment.environment"],b8={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",LOCAL_EVALUATION_INCONCLUSIVE:"local_evaluation_inconclusive",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};a.s(["FeatureFlagError",0,b8],46539);class b9{constructor(a){this._host=a.host,this._distinctId=a.distinctId,this._groups=a.groups,this._disableGeoip=a.disableGeoip,this._flags=a.flags,this._unresolvedFlags=Object.freeze({...a.unresolvedFlags}),this._requestId=a.requestId,this._evaluatedAt=a.evaluatedAt,this._flagDefinitionsLoadedAt=a.flagDefinitionsLoadedAt,this._errorsWhileComputing=a.errorsWhileComputing??!1,this._quotaLimited=a.quotaLimited??!1,this._accessed=a.accessed??new Set,this._isSlice=a.isSlice??!1}isEnabled(a,b={}){let c=this._flags[a];return this._recordAccess(a,b.sendFeatureFlagEvents),c?.enabled??b.defaultValue??!1}getFlag(a,b={}){let c=this._flags[a];if(this._recordAccess(a,b.sendFeatureFlagEvents),c)return!!c.enabled&&(c.variant??!0)}getFlagPayload(a){return this._flags[a]?.payload}onlyAccessed(){let a={};for(let b of this._accessed){let c=this._flags[b];c&&(a[b]=c)}return this._cloneWith(a)}only(a){let b={},c=[];for(let d of a){let a=this._flags[d];a?b[d]=a:c.push(d)}return c.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${c.join(", ")}`),this._cloneWith(b)}get keys(){return Object.keys(this._flags)}get unresolvedFlags(){return this._unresolvedFlags}_getEventProperties(){let a={},b=[];for(let[c,d]of Object.entries(this._flags)){let e=!1!==d.enabled&&(d.variant??!0);a[`$feature/${c}`]=e,d.enabled&&b.push(c)}return b.length>0&&(b.sort(),a.$active_feature_flags=b),a}_cloneWith(a){return new b9({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:a,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(a,b){if(this._accessed.add(a),!this._host.resolveSendFeatureFlagEvents(b)||""===this._distinctId||this._isSlice&&!(a in this._flags))return;let c=this._flags[a],d=void 0===c?void 0:!1!==c.enabled&&(c.variant??!0),e={$feature_flag:a,$feature_flag_response:d,$feature_flag_id:c?.id,$feature_flag_version:c?.version,$feature_flag_reason:c?.reason,locally_evaluated:c?.locallyEvaluated??!1,[`$feature/${a}`]:d,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:c?.locallyEvaluated?Date.now():this._evaluatedAt};c?.hasExperiment!==void 0&&(e.$feature_flag_has_experiment=c.hasExperiment),c?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(e.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let f=[];this._errorsWhileComputing&&f.push(b8.ERRORS_WHILE_COMPUTING),this._quotaLimited&&f.push(b8.QUOTA_LIMITED),void 0===c&&f.push(Object.prototype.hasOwnProperty.call(this._unresolvedFlags,a)?b8.LOCAL_EVALUATION_INCONCLUSIVE:b8.FLAG_MISSING),f.length>0&&(e.$feature_flag_error=f.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:a,response:d,groups:this._groups,disableGeoip:this._disableGeoip,properties:e})}}let ca=["exact","is_not","icontains","not_icontains","starts_with","not_starts_with","ends_with","not_ends_with","regex","not_regex"];class cb extends Error{constructor(a,b="unsupported_definition"){super(a),this.name=this.constructor.name,this.reason=b,Object.setPrototypeOf(this,cb.prototype)}}function cc(a){try{return a()}catch(a){if(a instanceof cb)throw new cb(a.message,"missing_context");throw a}}function cd(a){if("boolean"==typeof a)return!0;if("string"==typeof a){let b=a.toLowerCase();return"true"===b||"false"===b}if(!Array.isArray(a))return!1;for(let b=0;b<a.length;b++)if(!cd(b in a?a[b]:null))return!1;return!0}function ce(a){if("boolean"==typeof a)return a;if("string"==typeof a)return"true"===a.toLowerCase();if(!Array.isArray(a))return!1;for(let b=0;b<a.length;b++)if(!ce(b in a?a[b]:null))return!1;return!0}function cf(a){for(let b=0;b<a.length;b++){let c=a.charCodeAt(b);if(c>=55296&&c<=56319){let c=a.charCodeAt(b+1);if(b+1>=a.length||c<56320||c>57343)throw new cb("Cannot stringify an unpaired surrogate like the flags service");b++}else if(c>=56320&&c<=57343)throw new cb("Cannot stringify an unpaired surrogate like the flags service")}}function cg(a,b=new Set){if(null!==a&&"boolean"!=typeof a){if("string"==typeof a)return void cf(a);if("number"==typeof a){if(!Number.isFinite(a))throw new cb(`Cannot represent non-finite number ${a} like the flags service`);return}if(Array.isArray(a)){if(b.has(a))throw new cb("Cannot represent a circular array during local evaluation");b.add(a);try{for(let c=0;c<a.length;c++)c in a&&cg(a[c],b)}finally{b.delete(a)}return}if("object"==typeof a){let c=Object.getPrototypeOf(a);if(c!==Object.prototype&&null!==c)throw new cb("Cannot represent a non-JSON object like the flags service");if(b.has(a))throw new cb("Cannot represent a circular object during local evaluation");b.add(a);try{for(let c of Object.keys(a))cf(c),cg(a[c],b)}finally{b.delete(a)}return}throw new cb(`Cannot represent ${typeof a} like the flags service`)}}function ch(a,b){let c=0,d=0;for(;c<a.length&&d<b.length;){let e=a.charCodeAt(c),f=b.charCodeAt(d),g=e>=55296&&e<=56319,h=f>=55296&&f<=56319,i=g?a.charCodeAt(c+1):0,j=h?b.charCodeAt(d+1):0,k=g?(e-55296)*1024+i-56320+65536:e,l=h?(f-55296)*1024+j-56320+65536:f;if(k!==l)return k-l;c+=g?2:1,d+=h?2:1}return a.length-b.length}function ci(a){return"string"==typeof a?(cf(a),a):function a(b,c=new Set){if(null===b)return"null";if("string"==typeof b)return cf(b),JSON.stringify(b);if("boolean"==typeof b)return b?"true":"false";if("number"==typeof b){if(!Number.isFinite(b))throw new cb(`Cannot stringify non-finite number ${b} like the flags service`);if(Number.isInteger(b))throw new cb(`Cannot distinguish integer ${b} from an integral JSON float during local evaluation`);return String(b)}if(Array.isArray(b)){if(c.has(b))throw new cb("Cannot stringify a circular array during local evaluation");c.add(b);try{let d=[];for(let e=0;e<b.length;e++)d.push(e in b?a(b[e],c):"null");return`[${d.join(",")}]`}finally{c.delete(b)}}if("object"==typeof b){let d=Object.getPrototypeOf(b);if(d!==Object.prototype&&null!==d)throw new cb("Cannot stringify a non-JSON object like the flags service");if(c.has(b))throw new cb("Cannot stringify a circular object during local evaluation");c.add(b);try{let d=Object.keys(b);return d.forEach(cf),`{${d.sort(ch).map(d=>`${JSON.stringify(d)}:${a(b[d],c)}`).join(",")}}`}finally{c.delete(b)}}throw new cb(`Cannot stringify ${typeof b} like the flags service`)}(a)}let cj=/[\x20-\x2f:;=?@\x5b-\x60\x7b-\x7e]/;function ck(a){let b=new cb(a);return Object.defineProperty(b,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),b}function cl(a){return String(a).replace(/[A-Z]/g,a=>a.toLowerCase())}function cm(a,b,c){if(!/^\d+$/.test(a)||"strict"===c&&a.length>1&&"0"===a[0])throw new cb(`Invalid semver: ${b}`);return parseInt(a,10)}function cn(a,b="strict"){let c=String(a).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!c||c.startsWith("."))throw new cb(`Invalid semver: ${a}`);let d=c.split("."),e=c=>void 0===c||""===c?0:cm(c,a,b);return[e(d[0]),e(d[1]),e(d[2])]}function co(a,b){for(let c=0;c<3;c++){if(a[c]<b[c])return -1;if(a[c]>b[c])return 1}return 0}function cp(a,b){let c=cn(a,b);return{lower:[c[0],c[1],c[2]],upper:[c[0],c[1]+1,0]}}function cq(a,b){let[c,d,e]=cn(a,b);return{lower:[c,d,e],upper:c>0?[c+1,0,0]:d>0?[0,d+1,0]:[0,0,e+1]}}function cr(a,b){let c=String(a).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!c)throw new cb(`Invalid wildcard semver: ${a}`);let d=c.split("."),e=c=>{if("legacy-permissive"===b){let a=parseInt(c,10);if(!isNaN(a))return a}else try{return cm(c,a,b)}catch{}throw new cb(`Invalid wildcard semver: ${a}`)},f=e(d[0]);if(1===d.length)return{lower:[f,0,0],upper:[f+1,0,0]};let g=e(d[1]);return{lower:[f,g,0],upper:[f,g+1,0]}}function cs(a){if(a instanceof Date)return a;if("string"==typeof a||"number"==typeof a){let b=new Date(a);if(!isNaN(b.valueOf()))return b;throw new cb(`${a} is in an invalid date format`)}throw new cb(`The date provided ${a} must be a string, number, or date object`)}function ct(a){if("boolean"==typeof a)throw new cb("Date operations cannot be performed on boolean values");return function(a){let b=a.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),c=new Date(new Date().toISOString());if(!b||!b.groups)return null;let d=parseInt(b.groups.number);if(d>=1e4)return null;let e=b.groups.interval;if("h"===e)c.setUTCHours(c.getUTCHours()-d);else if("d"===e)c.setUTCDate(c.getUTCDate()-d);else if("w"===e)c.setUTCDate(c.getUTCDate()-7*d);else if("m"===e)c.setUTCMonth(c.getUTCMonth()-d);else{if("y"!==e)return null;c.setUTCFullYear(c.getUTCFullYear()-d)}return c}(String(a))??cs(a)}function cu(a,b={}){let c=a.value,d=b.semverParsingPolicy??"strict";switch(a.operator||"exact"){case"exact":case"is_not":for(let a of Array.isArray(c)?c:[c])ci(a);return;case"is_set":case"is_not_set":case"icontains":case"not_icontains":case"starts_with":case"not_starts_with":case"ends_with":case"not_ends_with":case"regex":case"not_regex":case"gt":case"gte":case"lt":case"lte":return;case"is_date_after":case"is_date_before":ct(c);return;case"semver_eq":case"semver_neq":case"semver_gt":case"semver_gte":case"semver_lt":case"semver_lte":cn(String(c),d);return;case"semver_tilde":cp(String(c),d);return;case"semver_caret":cq(String(c),d);return;case"semver_wildcard":cr(String(c),d);return;default:throw new cb(`Unknown operator: ${a.operator}`)}}async function cv(a){let b=globalThis.crypto?.subtle;if(!b)throw Error("SubtleCrypto API not available");return Array.from(new Uint8Array(await b.digest("SHA-1",new TextEncoder().encode(a)))).map(a=>a.toString(16).padStart(2,"0")).join("")}async function cw(a,b,c="",d="."){return parseInt((await cv(`${a}${d}${b}${c}`)).slice(0,15),16)/0x1000000000000000}async function cx(a,b){if(null==a||null==a.id||null==a.exclusion_percentage)return;let c=Number(a.exclusion_percentage);if(!Number.isFinite(c))return;let d=Math.min(Math.max(c,0),100);if(!(100!==d&&await cw("holdout",b,"","-")>d/100))return`holdout-${a.id}`}function cy(a){let b=[],c=0;for(let d of a){let a=c+d.rollout_percentage/100;b.push({valueMin:c,valueMax:a,key:d.key}),c=a}return b}async function cz(a,b,c){let d=await cw(a,b,"variant");return cy(c).find(a=>d>=a.valueMin&&d<a.valueMax)?.key}function cA(a){return"client"===a||"server"===a?a:"all"}function cB(a,b){return a===b||"all"===a||"all"===b}class cC extends Error{constructor(a){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=a,Object.setPrototypeOf(this,cC.prototype)}}class cD extends Error{constructor(a,b="unsupported_definition"){super(a),this.reason=b,this.name=cD.name,Error.captureStackTrace(this,cD),Object.setPrototypeOf(this,cD.prototype)}}let cE=["experience_continuity","unsupported_definition","unresolved_dependency","missing_context"];function cF(a,b){return void 0===a||cE.indexOf(b)<cE.indexOf(a)?b:a}function cG(a,b){return b instanceof cb&&Symbol.for("posthog.requiresServerRegexEvaluation")in b&&Object.defineProperty(a,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),a}class cH{constructor({pollingInterval:a,personalApiKey:b,projectApiKey:c,timeout:d,host:e,customHeaders:f,...g}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.warnedUnresolvableFlags=new Map,this.pollingInterval=a,this.personalApiKey=b,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=d,this.projectApiKey=c,this.host=e,this.poller=void 0,this.fetch=g.fetch||fetch,this.onError=g.onError,this.customHeaders=f,this.onLoad=g.onLoad,this.onMinimalFlagCalledEvents=g.onMinimalFlagCalledEvents,this.cacheProvider=g.cacheProvider,this.strictLocalEvaluation=g.strictLocalEvaluation??!1,this.evaluationContexts=g.evaluationContexts,this.loadFeatureFlags()}debug(a=!0){this.debugMode=a}logMsgIfDebug(a){this.debugMode&&a()}currentDefinitions(){return{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}withEvaluationSnapshot(a){return a.definitions?a:{...a,evaluationCache:{},definitions:this.currentDefinitions()}}createEvaluationContext(a,b={},c={},d={},e={}){return{distinctId:a,groups:b,personProperties:c,groupProperties:d,evaluationCache:e}}async getFeatureFlag(a,b,c={},d={},e={}){let f,g;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return f;if(void 0!==(g=this.featureFlagsByKey[a])){let h=this.createEvaluationContext(b,c,d,e);try{f=(await this.computeFlagAndPayloadLocally(g,h)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${a} -> ${f}`))}catch(b){b instanceof cD||b instanceof cb?this.logMsgIfDebug(()=>console.debug(`${b.name} when computing flag locally: ${a}: ${b.message}`)):b instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${a}: ${b}`))}}return f}async getAllFlagsAndPayloads(a,b){await this.loadFeatureFlags();let c={},d={},e={},f=0==this.featureFlags.length,g=b?b.map(a=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,h=this.withEvaluationSnapshot({...a,definitions:void 0});return await Promise.all(g.map(async a=>{try{let{value:b,payload:e}=await this.computeFlagAndPayloadLocally(a,h,{skipLoadCheck:!0});c[a.key]=b,e&&(d[a.key]=e)}catch(b){b instanceof cD||b instanceof cb?(this.logMsgIfDebug(()=>console.debug(`${b.name} when computing flag locally: ${a.key}: ${b.message}`)),e[a.key]=b.reason):b instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${a.key}: ${b}`)),cB(cA(a.evaluation_runtime),"server")&&(f=!0)}})),{response:c,payloads:d,unresolved:e,fallbackToFlags:f}}async computeFlagAndPayloadLocally(a,b,c={}){let d,{matchValue:e,skipLoadCheck:f=!1}=c;if(this.loadedSuccessfullyOnce&&(b=this.withEvaluationSnapshot(b)),f||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};a=(b=this.withEvaluationSnapshot(b)).definitions.featureFlagsByKey[a.key]??a,d=void 0!==e?e:await this.computeFlagValueLocally(a,b);let g=function(a,b){if(!1===b||null==b||!a)return null;let c=a["boolean"==typeof b?b.toString():b]||null;return null==c?null:ay(c)}(a.filters?.payloads,d);return{value:d,payload:g}}async computeFlagValueLocally(a,b){let{distinctId:c,groups:d,personProperties:e,groupProperties:f}=b;if(!a.active)return!1;if(a.ensure_experience_continuity)throw new cb("Flag has experience continuity enabled","experience_continuity");let g=(a.filters||{}).aggregation_group_type_index;if(void 0!=g){let c=b.definitions.groupTypeMapping[String(g)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${g} for feature flag ${a.key}`)),new cb("Flag has unknown group type index");if(!(c in d))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${a.key} without group names passed in`)),!1;"device_id"===a.bucketing_identifier&&(e?.$device_id===void 0||e?.$device_id===null||e?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${a.key}`));let h=f[c];return await this.matchFeatureFlagProperties(a,d[c],h,b)}{let d=this.getBucketingValueForFlag(a,c,e);if(void 0===d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${a.key} without $device_id, falling back to server evaluation`)),new cb(`Can't compute feature flag: ${a.key} without $device_id`,cI(a,b.definitions)??"missing_context");return await this.matchFeatureFlagProperties(a,d,e,b)}}getBucketingValueForFlag(a,b,c){if(a.filters?.aggregation_group_type_index!=void 0)return b;if("device_id"===a.bucketing_identifier){let a=c?.$device_id;if(null==a||""===a)return;return a}return b}async evaluateFlagDependency(a,b,c){let{evaluationCache:d}=c,e=a.key;if(!c.definitions.featureFlagsByKey)throw new cb("Feature flags not available for dependency evaluation");if(!("dependency_chain"in a))throw new cb(`Flag dependency property for '${e}' is missing required 'dependency_chain' field`);let f=a.dependency_chain;if(!Array.isArray(f))throw new cb(`Flag dependency property for '${e}' has an invalid 'dependency_chain' (expected array, got ${typeof f})`);if(0===f.length)throw new cb(`Circular dependency detected for flag '${e}' (empty dependency chain)`);let g=f.find(a=>!(a in d)&&!c.definitions.featureFlagsByKey[a]&&!c.definitions.filteredOutFlagKeys.has(a));if(void 0!==g)throw new cb(`Missing flag dependency '${g}' for flag '${e}'`);for(let a of f){if(!(a in d)){let b=c.definitions.featureFlagsByKey[a];if(b)if(b.active)try{let e=await this.computeFlagValueLocally(b,c);d[a]=e}catch(b){if(b instanceof cD)throw new cD(`Flag dependency '${a}' for flag '${e}' requires server evaluation: ${b.message}`,"unresolved_dependency");throw cG(new cb(`Error evaluating flag dependency '${a}' for flag '${e}': ${b}`,"unresolved_dependency"),b)}else d[a]=!1;else d[a]=!1}if(null==d[a])throw new cb(`Dependency '${a}' could not be evaluated`,"unresolved_dependency")}let h=d[e];return this.flagEvaluatesToExpectedValue(a.value,h)}flagEvaluatesToExpectedValue(a,b){return"boolean"==typeof a?a===b||"string"==typeof b&&""!==b&&!0===a:"string"==typeof a&&b===a}async matchFeatureFlagProperties(a,b,c,d){let e,f,g;d=this.withEvaluationSnapshot(d);let h=a.filters||{},i=await cx(h.holdout,b);if(void 0!==i)return i;let j=h.groups||[],k=h.aggregation_group_type_index,l=h.early_exit??!1,{groups:m,groupProperties:n}=d,o=new Set;for(let i of j){let j=b;try{let b=void 0!==i.aggregation_group_type_index?i.aggregation_group_type_index:k,f=c;if(b!==k&&null!=b){let c=d.definitions.groupTypeMapping[String(b)];if(!c||!(c in m)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${a.key}': group type index ${b} not available`));continue}if(!(c in n)){e=cF(e,"missing_context");continue}f=n[c],j=m[c]}let o=await this.isConditionMatch(a,j,i,f,d);if("match"===o){let b=i.variant,c=h.multivariate?.variants||[];g=b&&c.some(a=>a.key===b)?b:await this.getMatchingVariant(a,j)||!0;break}if(l&&"out_of_rollout_bound"===o){if(e)break;return!1}}catch(b){if(b instanceof cD){let c;try{c=cI(a,d.definitions)}catch{}let f=cF(cF(e,b.reason),c??b.reason);throw f===b.reason?b:new cD(b.message,f)}if(b instanceof cb){if(e=cF(e,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b)if(f=b,l&&void 0!=i.rollout_percentage&&await cw(a.key,j)>i.rollout_percentage/100)o.add(!1);else{let b=h.multivariate?.variants||[],c=i.variant;o.add(c&&b.some(a=>a.key===c)?c:await this.getMatchingVariant(a,j)||!0)}}else throw b}}if(void 0!==g&&!(f&&[...o].some(a=>a!==g)))return g;if(e)throw cG(new cb("Can't determine if feature flag is enabled or not with given properties",e),f);return!1}async isConditionMatch(a,b,c,d,e){let f=(e=this.withEvaluationSnapshot(e)).definitions,g=c.rollout_percentage,h=a=>{this.logMsgIfDebug(()=>console.warn(a))};if((c.properties||[]).length>0){let b,i,j;for(let a of c.properties){let c=a.type,g=!1;try{if("cohort"===c){let b=await cK(a,d,f.cohorts,this.debugMode,a=>this.evaluateFlagDependency(a,d,e),f.propertyMatchingVersion);g="not_in"===a.operator?!b:b}else if("flag"===c)g=await this.evaluateFlagDependency(a,d,e);else if(Object.prototype.hasOwnProperty.call(d,a.key))g=cJ(a,d,h,f.propertyMatchingVersion);else{cu(a),b=cF(b,"missing_context");continue}}catch(a){if(a instanceof cD){void 0===b&&(j??=a),b=cF(b,a.reason);continue}if(a instanceof cb){Symbol.for("posthog.requiresServerRegexEvaluation")in a&&(i=a),b=cF(b,a.reason);continue}if(void 0!==b)break;throw a}if(!g)return"no_match"}if(j)throw j;if(b)throw cG(new cb(`Can't determine if a condition of flag ${a.key} matches`,b),i);if(void 0==g)return"match"}return void 0!=g&&await cw(a.key,b)>g/100?"out_of_rollout_bound":"match"}async getMatchingVariant(a,b){return cz(a.key,b,a.filters?.multivariate?.variants||[])}variantLookupTable(a){return cy(a.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(a){if(!this.evaluationContexts||0===this.evaluationContexts.length)return a;let b=new Set(this.evaluationContexts);return a.filter(a=>{let c=a.evaluation_contexts??a.evaluation_tags;return!c||0===c.length||c.some(a=>b.has(a))})}getEvaluationRuntimeForFlag(a){let b=this.featureFlagsByKey[a];return b?cA(b.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(a){return this.featureFlags.filter(b=>cB(cA(b.evaluation_runtime),a)).map(a=>a.key)}updateFlagState(a){let b=this.filterFlagsByEvaluationContexts(a.flags),c=b.reduce((a,b)=>(a[b.key]=b,a),{}),d=new Set(b.map(a=>a.key)),e=new Set(a.flags.filter(a=>!d.has(a.key)).map(a=>a.key));this.featureFlags=b,this.featureFlagsByKey=c,this.filteredOutFlagKeys=e,this.groupTypeMapping=a.group_type_mapping??a.groupTypeMapping??{},this.cohorts=a.cohorts,this.propertyMatchingVersion=a.property_matching_version??a.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((a.minimal_flag_called_events??a.minimalFlagCalledEvents)===!0)}warnAboutUnresolvableFlags(a){let b=[],c=[],d=new Map,e=this.currentDefinitions();for(let f of a){if(!cB(cA(f.evaluation_runtime),"server"))continue;let a=cI(f,e);if(!a)continue;let g=JSON.stringify(f);d.set(f.key,g),this.warnedUnresolvableFlags.get(f.key)!==g&&("experience_continuity"===a?b.push(f.key):c.push(f.key))}if(this.warnedUnresolvableFlags=d,b.length>0){let a=this.strictLocalEvaluation?"With strictLocalEvaluation enabled these flags are left unresolved. To evaluate them locally, disable experience continuity on these flags in PostHog.":"Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).";console.warn(`[PostHog] You are using local evaluation but ${b.length} flag(s) have experience continuity enabled and cannot be resolved locally (reason: experience_continuity): ${b.join(", ")}. `+a)}if(c.length>0){let a=this.strictLocalEvaluation?"With strictLocalEvaluation enabled these flags are left unresolved when evaluation reaches that part.":"Evaluating these flags falls back to a server request when evaluation reaches that part.";console.warn(`[PostHog] You are using local evaluation but ${c.length} flag(s) use something local evaluation does not support, such as a static cohort, an unknown operator, or a missing or circular flag dependency (reason: unsupported_definition): ${c.join(", ")}. ${a} To evaluate them locally, change these flags in PostHog or upgrade posthog-node.`)}}async loadFromCache(a){if(!this.cacheProvider)return!1;try{let b=await this.cacheProvider.getFlagDefinitions();if(b)return this.updateFlagState(b),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${a} (${b.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags),!0;return!1}catch(a){return this.onError?.(Error(`Failed to load from cache: ${a}`)),!1}}async loadFeatureFlags(a=!1){if(!this.loadedSuccessfullyOnce||a)return!a&&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(a=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${a}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let a=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(6e4,a*2**this.backOffCount):a}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{if(this.cacheProvider&&!this.personalApiKey)return void await this.loadFromCache("Loaded flags from cache (cache-only reader)");let a=!0;if(this.cacheProvider)try{a=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(a){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${a}`))}if(!a&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let b=await this._requestFeatureFlagDefinitions();if(!b)return;switch(b.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=b.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new cC(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new cC(`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 cC(`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 c=await b.json()??{};if(!("flags"in c))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(c)}`));this.flagsEtag=b.headers?.get("ETag")??void 0;let d=c.group_type_mapping||{},e=!0===c.minimal_flag_called_events,f={flags:c.flags??[],group_type_mapping:d,cohorts:c.cohorts||{},minimal_flag_called_events:e,property_matching_version:c.property_matching_version,propertyMatchingVersion:c.property_matching_version,groupTypeMapping:d,minimalFlagCalledEvents:e};if(this.updateFlagState(f),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&a)try{await this.cacheProvider.onFlagDefinitionsReceived(f)}catch(a){this.onError?.(Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags);break}default:return}}catch(a){a instanceof cC&&this.onError?.(a)}finally{this.pollerStopped||null===this.pollingInterval||(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(a="GET",b){let c={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return b&&(c["If-None-Match"]=b),{method:a,headers:c}}async _requestFeatureFlagDefinitions(){if(!this.personalApiKey)throw new cC("A secretKey or personalApiKey is required to fetch feature flag definitions from PostHog.");let a=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,b=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),c=null;if(this.timeout&&"number"==typeof this.timeout){let a=new AbortController;c=aI(()=>{a.abort()},this.timeout),b.signal=a.signal}try{let d=this.fetch,e=await d(a,b);if(200!==e.status)return clearTimeout(c),e;return{status:e.status,headers:e.headers,body:e.body,text:async()=>{try{return await e.text()}finally{clearTimeout(c)}},json:async()=>{try{return await e.json()}finally{clearTimeout(c)}}}}catch(a){throw clearTimeout(c),a}}async stopPoller(a=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let b=this.cacheProvider.shutdown();b instanceof Promise&&await aJ(b,a,()=>{throw Error(`Cache shutdown timeout after ${a}ms`)})}catch(a){this.onError?.(Error(`Error during cache shutdown: ${a}`))}}}function cI(a,b){if(!a.active)return;if(a.ensure_experience_continuity)return"experience_continuity";let c=a.filters||{},d=c.aggregation_group_type_index;return void 0==d||b.groupTypeMapping[String(d)]?(c.groups||[]).some(a=>(a.properties||[]).some(a=>(function a(b,c,d){if("flag"===b.type){let a=b.dependency_chain;return!Array.isArray(a)||0===a.length||a.some(a=>!c.featureFlagsByKey[a]&&!c.filteredOutFlagKeys.has(a))}if("cohort"!==b.type)try{return cu(b),!1}catch(a){if(a instanceof cb)return!0;throw a}let e=String(b.value);return!(e in c.cohorts)||!d.has(e)&&(d.add(e),function b(c,d,e){return(c?.values??[]).some(c=>"values"in c?b(c,d,e):a(c,d,e))}(c.cohorts[e],c,d))})(a,b,new Set)))?"unsupported_definition":void 0:"unsupported_definition"}function cJ(a,b,c,d){return function(a,b,c={}){try{return function(a,b,c){let d=a.key,e=a.value,f=a.operator||"exact",g=c.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(b,d)){if("is_not_set"===f)return!1;else if("is_set"===f)return!0}else throw new cb(`Property ${d} not found in propertyValues`,"missing_context");let h=b[d];if(void 0===h)throw c.warnFunction?.(`Property ${d} cannot have a value of undefined with the ${f} operator`),new cb(`Property ${d} is undefined in propertyValues`);if(null===h&&!ca.includes(f))return c.warnFunction?.(`Property ${d} cannot have a value of null with the ${f} operator`),!1;let i=(a,b)=>{if(2!==c.propertyMatchingVersion&&cd(a)||Array.isArray(a)&&0===a.length)return cc(()=>cg(b)),ce(a)===ce(b);if(2===c.propertyMatchingVersion&&"number"==typeof b&&cd(a))return cc(()=>cg(b)),!1;if(Array.isArray(a)){let c=cc(()=>ci(b)).toLowerCase();return a.some(a=>ci(a).toLowerCase()===c)}return ci(a).toLowerCase()===cc(()=>ci(b)).toLowerCase()},j=(a,b,c)=>{if("gt"===c)return a>b;if("gte"===c)return a>=b;if("lt"===c)return a<b;if("lte"===c)return a<=b;throw Error(`Invalid operator: ${c}`)},k=()=>cc(()=>cn(String(h),g)),l=()=>{let a=cn(String(e),g);return co(k(),a)},m=({lower:a,upper:b})=>{let c=k();return co(c,a)>=0&&0>co(c,b)};switch(f){case"exact":return i(e,h);case"is_not":return!i(e,h);case"is_set":return!0;case"icontains":return cl(h).includes(cl(e));case"not_icontains":return!cl(h).includes(cl(e));case"starts_with":return cl(h).startsWith(cl(e));case"not_starts_with":return!cl(h).startsWith(cl(e));case"ends_with":return cl(h).endsWith(cl(e));case"not_ends_with":return!cl(h).endsWith(cl(e));case"regex":case"not_regex":{let a=function(a,b){let c;if(""===a)return!0;let d=function(a){let b=[],c=-1,d="";for(let e=0;e<a.length;e++){let f=a[e];if(f.charCodeAt(0)>127)return null;if("\\"===f){let b=a[++e];if(void 0===b)break;if("x"===b){if(!/^[\da-f]{2}$/i.test(a.slice(e+1,e+3)))return null;e+=2}else if(!"dDsSwWbBfnrtv".includes(b)&&!cj.test(b))return null;if(-1===c&&"bB".includes(b))return null;d="literal";continue}if("["===f){if(-1!==c)return null;c=e}else if("]"===f&&-1!==c){if(e===c+("^"===a[c+1]?2:1))return null;b.push(a.slice(c,e+1)),c=-1,d="literal";continue}else if(-1!==c){if(["&&","--","~~"].includes(a.slice(e,e+2)))return null;continue}else if("("===f&&"?"===a[e+1]){if(":"!==a[e+2])return null;e+=2}else if("{"===f){let b=/^\{(\d+)(?:,(\d*))?\}/.exec(a.slice(e));if(!b||["","|","("].includes(d)||b.slice(1).some(a=>Number(a)>0xffffffff))return null}else if("*+?}".includes(f)&&("+"===a[e+1]||"{"===a[e+1]))return null;if("*+?{".includes(f)&&["^","$","empty group"].includes(d))return null;d=")"===f&&["(","empty group"].includes(d)?"empty group":f}return b}(a);if(null===d)throw ck("Regex syntax requires server evaluation");try{c=new RegExp(a)}catch(a){if(a instanceof SyntaxError)return null;throw ck("Regex compilation requires server evaluation")}for(let a of d)try{RegExp(a,"u")}catch{throw ck("Regex character class syntax requires server evaluation")}for(let a=0;a<b.length;a++){let c=b[a];if(c.charCodeAt(0)>127||"\r"===c)throw ck("Regex matching for Unicode or carriage returns requires server evaluation")}try{return c.test(b)}catch{throw ck("Regex execution requires server evaluation")}}(String(e),String(h));if(null===a)return!1;return"regex"===f?a:!a}case"gt":case"gte":case"lt":case"lte":{let a="number"==typeof e?e:parseFloat(String(e)),b="number"==typeof h?h:null!=h?parseFloat(String(h)):0/0;if(Number.isFinite(a)&&Number.isFinite(b))return j(b,a,f);return j(String(h),String(e),f)}case"is_date_after":case"is_date_before":{let a=ct(e),b=cc(()=>cs(h));return"is_date_before"===f?b<a:b>a}case"semver_eq":return 0===l();case"semver_neq":return 0!==l();case"semver_gt":return l()>0;case"semver_gte":return l()>=0;case"semver_lt":return 0>l();case"semver_lte":return 0>=l();case"semver_tilde":return m(cp(String(e),g));case"semver_caret":return m(cq(String(e),g));case"semver_wildcard":return m(cr(String(e),g));default:throw new cb(`Unknown operator: ${f}`)}}(a,b,c)}catch(b){throw b instanceof cb&&"missing_context"===b.reason&&cu(a,c),b}}(a,b,{warnFunction:c,propertyMatchingVersion:d})}async function cK(a,b,c,d=!1,e,f){let g=String(a.value);if(!(g in c))throw new cD(`cohort ${g} not found in local cohorts - likely a static cohort that requires server evaluation`);return cL(c[g],b,c,d,e,f)}async function cL(a,b,c,d=!1,e,f){let g,h;if(!a)return!0;let i=a.type,j=a.values;if(!j||0===j.length)return!0;if("values"in j[0]){for(let a of j)try{let g=await cL(a,b,c,d,e,f);if("AND"===i){if(!g)return!1}else if(g)return!0}catch(b){if(b instanceof cD)throw b;if(b instanceof cb)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),g=cF(g,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b&&(h=b);else throw b}if(g)throw cG(new cb("Can't match cohort without a given cohort property value",g),h);return"AND"===i}for(let a of j)try{let g;if("cohort"===a.type)g=await cK(a,b,c,d,e,f);else if("flag"===a.type){if(!e)throw new cb(`Flag dependency '${a.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);g=await e(a)}else g=cJ(a,b,void 0,f);let h=a.negation||!1;if("AND"===i){if(!g&&!h||g&&h)return!1}else if(g&&!h||!g&&h)return!0}catch(b){if(b instanceof cD)throw b;if(b instanceof cb)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),g=cF(g,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b&&(h=b);else throw b}if(g)throw cG(new cb("can't match cohort without a given cohort property value",g),h);return"AND"===i}let cM=["--unhandled-rejections","--unhandled_rejections"],cN=new Set(["throw","strict","warn","warn-with-error-code","none"]),cO=[...globalThis.process?.execArgv??[]],cP=globalThis.process?.env?.NODE_OPTIONS;function cQ(a){let b;for(let c=0;c<a.length;c++){let d=a[c],e=cM.find(a=>d===a||d.startsWith(`${a}=`));if(!e)continue;let f=d===e?a[++c]:d.slice(e.length+1);cN.has(f)&&(b=f)}return b}let cR=function(a=cO,b=cP){return cQ(a)??cQ(function(a){let b=[],c="",d=!1;for(let e=0;e<a.length;e++){let f=a[e];"\\"===f&&d&&e+1<a.length?c+=a[++e]:" "!==f||d?'"'===f?d=!d:c+=f:c&&(b.push(c),c="")}return c&&b.push(c),b}(b??""))??"throw"}(),cS={mechanism:{type:"onunhandledrejection",handled:!1}},cT={mechanism:{type:"onuncaughtexception",handled:!1}},cU=new Set(["HANGING_PROMISE_REJECTION","NEXT_PRERENDER_INTERRUPTED","DYNAMIC_SERVER_USAGE","BAILOUT_TO_CLIENT_SIDE_RENDERING"]),cV=Symbol.for("react.postpone"),cW=Symbol.for("next.unhandledRejectionFilter"),cX=Symbol.for("posthog-node.exception-autocapture.v1"),cY=globalThis;function cZ(a){return"function"==typeof a&&!0===a._posthogErrorHandler}function c$(a){return"object"==typeof a&&null!==a||"function"==typeof a}function c_(a){return Object.assign(a,{_posthogErrorHandler:!0})}function c0(a){return a.listeners("unhandledRejection").some(a=>!cZ(a))}function c1(a,b){return function a(b,c=0){try{if(!c$(b))return!1;if(b.$$typeof===cV||"string"==typeof b.digest&&cU.has(b.digest))return!0;return c<5&&a(b.cause,c+1)}catch{return!1}}(a)||"unhandledRejection"===b&&function(a){try{return c$(a)&&"AbortError"===a.name}catch{return!1}}(a)}function c2(a){let b=new Map;for(let c of a.clients){let a=b.get(c.key);a&&(void 0!==a.getContext()||void 0===c.getContext())||b.set(c.key,c)}for(let[c,d]of a.retired)b.has(c)||b.set(c,d);return[...b.values()]}function c3(a){"function"==typeof globalThis.setImmediate?setImmediate(a):setTimeout(a,0)}function c4(a,b,c,d){let e=a.capturedThisTurn.get(b)??new Map;e.has(c)||e.set(c,d),a.capturedThisTurn.set(b,e),a.turnResetScheduled||(a.turnResetScheduled=!0,c3(()=>{c3(()=>{a.capturedThisTurn.clear(),a.turnResetScheduled=!1})}))}function c5(a,b,c,d){let e=a.capturedThisTurn.get(b),f=[];for(let g of c2(a))e?.has(g.key)||d?.has(g.key)||(c4(a,b,g.key,"autocapture"),g.capture(b,c),f.push(g));return f}function c6(a,b){return a.deferred.get(b.exception)!==b?[]:(a.deferred.delete(b.exception),b.runInContext(()=>c5(a,b.exception,b.hint,b.skipKeys)))}function c7(a,b,c){let d;if(void 0!==(d=a.capturedThisTurn.get(b))&&c2(a).every(a=>d.has(a.key))||a.deferred.has(b))return;let e={exception:b,hint:c,skipKeys:new Set(a.capturedThisTurn.get(b)?.keys()),runInContext:function(){try{let a=globalThis.process,b=a?.getBuiltinModule?.("node:async_hooks"),c=b?.AsyncLocalStorage?.snapshot?.();if(c)return c}catch{}return a=>a()}()};a.deferred.set(b,e),c3(()=>c6(a,e))}async function c8(a,b){try{console.error(b)}catch{}dd();let c=new Set([...a.clients,...a.retired.values()]);await Promise.all([...c].map(a=>a.shutdown().catch(()=>void 0))),globalThis.process.exit(1)}function c9(a,b,c,d){let e="unhandledRejection"===c?cS:cT;if(!d){c1(b,c)||c7(a,b,e);return}let f=a.deferred.get(b);f?c6(a,f):c5(a,b,e)}function da(a){try{return String(a)}catch{return typeof a}}function db(a){let b=globalThis.process;cY[cW]&&"function"==typeof b.rawListeners&&b.rawListeners("unhandledRejection").includes(a)&&(Object.getPrototypeOf(b).removeListener.call(b,"unhandledRejection",a),b.listeners("unhandledRejection").includes(a)||b.prependListener("unhandledRejection",a))}function dc(a){let b=globalThis.process,c=[],d=(a,d)=>{b.on(a,d),c.push(()=>b.removeListener(a,d))},e=()=>c.forEach(a=>a());if("strict"===a.mode){let c=(b,c)=>c9(a,b,c,!0);return d("uncaughtExceptionMonitor",c),{remove:e,areInstalled:()=>b.listeners("uncaughtExceptionMonitor").includes(c)}}let f=c_((b,c)=>{let d=0===globalThis.process.listeners("uncaughtException").filter(a=>"domainUncaughtExceptionClear"!==a.name&&!cZ(a)).length;c9(a,b,c,d),d&&!a.calledFatalError&&(a.calledFatalError=!0,c8(a,b))});d("uncaughtException",f);let g="throw"===a.mode||"warn-with-error-code"===a.mode,h=g&&!b.versions?.bun,i=()=>b.listeners("unhandledRejection").includes(j),j=c_(b=>{g&&!c0(globalThis.process)&&i()?function(a,b){let c=globalThis.process;if("warn-with-error-code"===a.mode){c.emitWarning(`Unhandled promise rejection: ${da(b)}`,"UnhandledPromiseRejectionWarning"),c.exitCode=1,c1(b,"unhandledRejection")||c5(a,b,cS);return}if(c.versions?.bun){c.exitCode=1,c5(a,b,cS),a.calledFatalError||(a.calledFatalError=!0,c8(a,b));return}let d=b instanceof Error?b:Object.assign(Error(`This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "${da(b)}".`),{name:"UnhandledPromiseRejection",code:"ERR_UNHANDLED_REJECTION"}),e=c.emit;e.call(c,"uncaughtExceptionMonitor",d,"unhandledRejection"),e.call(c,"uncaughtException",d,"unhandledRejection")}(a,b):c1(b,"unhandledRejection")||c7(a,b,cS)});return d("newListener",c_((a,c)=>{cZ(c)||("unhandledRejection"===a?(i()||b.prependListener("unhandledRejection",j),queueMicrotask(()=>{let a;(a="function"==typeof b.rawListeners?b.rawListeners("unhandledRejection"):[]).includes(j)&&a[0]!==j&&(b.removeListener("unhandledRejection",j),b.prependListener("unhandledRejection",j)),db(j)})):"Next.UnhandledRejectionFilter.MacguffinEvent"===a&&queueMicrotask(()=>{i()||b.prependListener("unhandledRejection",j)}))})),h?(d("removeListener",c_(a=>{"unhandledRejection"===a&&i()&&!c0(b)&&b.removeListener("unhandledRejection",j)})),c0(b)&&b.prependListener("unhandledRejection",j)):b.prependListener("unhandledRejection",j),db(j),c.push(()=>{b.removeListener("unhandledRejection",j),"function"==typeof b.rawListeners&&b.rawListeners("unhandledRejection").includes(j)&&Object.getPrototypeOf(b).removeListener.call(b,"unhandledRejection",j)}),{remove:e,areInstalled:()=>b.listeners("uncaughtException").includes(f)&&(h||i())}}function dd(){let a=new Set,b=cY[cX];if(b)for(let c of[...b.deferred.values()])c6(b,c).forEach(b=>a.add(b));return a}let de=Symbol("capturedContext");function df(a,b,c,d,e){if(b>c&&(d.warn("min cannot be greater than max."),b=c),"[object Number]"==q.call(a)&&a==a)if(a>c)return d.warn(" cannot be greater than max: "+c+". Using max value instead."),c;else return a<b?(d.warn(" cannot be less than min: "+b+". Using min value instead."),b):a;return d.warn(" must be a number. using max or fallback. max: "+c+", fallback: "+e),df(e??c,b,c,d)}class dg{constructor(a){this._buckets={},this._onBucketRateLimited=a._onBucketRateLimited,this._bucketSize=df(a.bucketSize,0,100,a._logger),this._refillRate=df(a.refillRate,0,this._bucketSize,a._logger),this._refillInterval=df(a.refillInterval,0,864e5,a._logger)}_applyRefill(a,b){let c=Math.floor((b-a.lastAccess)/this._refillInterval);if(c>0){let b=c*this._refillRate;a.tokens=Math.min(a.tokens+b,this._bucketSize),a.lastAccess=a.lastAccess+c*this._refillInterval}}consumeRateLimit(a){let b=Date.now(),c=String(a),d=this._buckets[c];return d?this._applyRefill(d,b):(d={tokens:this._bucketSize,lastAccess:b},this._buckets[c]=d),0===d.tokens||(d.tokens--,0===d.tokens&&this._onBucketRateLimited?.(a),0===d.tokens)}stop(){this._buckets={}}}var dh=ai;let di=class a{constructor(a,b,c){this.client=a,this._exceptionAutocaptureEnabled=b.enableExceptionAutocapture||!1,this._logger=c,this._rateLimiter=new dg({...function(a={}){return{refillRate:a.exceptionRateLimiterRefillRate??a.__exceptionRateLimiterRefillRate??1,bucketSize:a.exceptionRateLimiterBucketSize??a.__exceptionRateLimiterBucketSize??10}}(b),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(a){return a===Object(a)&&!r(a)&&"__posthog_previously_captured_error"in a&&!0===a.__posthog_previously_captured_error}static async buildEventMessage(a,b,c,d,e,f){let g,h=(g=f?{...f,properties:{...f.properties}}:null,a=>Object.assign(a,{[de]:g})),i={...e},j=a.buildFromUnknown(b,c);j.$exception_list=await a.modifyFrames(j.$exception_list);let k=dh.getInjectedReleaseId();return k&&(i.$release_id=k),h({event:"$exception",distinctId:d,properties:{...j,...i},_originatedFromCaptureException:!0})}get destinationKey(){return`${this.client.apiKey}@${this.client.host}`}startAutocaptureIfEnabled(){this.isEnabled()&&(this._autocaptureClient={key:this.destinationKey,capture:(a,b)=>this.onException(a,b),getContext:()=>this.client.getContext(),flush:()=>this.client.flush(),shutdown:()=>this.client.shutdown(2e3)},this._stopAutocapture=function(a,b=cR){if(!globalThis.process?.on)return()=>void 0;let c=cY[cX];if(c)c.listeners.areInstalled()||(c.listeners.remove(),c.listeners=dc(c));else{let a={mode:b,clients:new Set,retired:new Map,capturedThisTurn:new Map,deferred:new Map,turnResetScheduled:!1,calledFatalError:!1,listeners:{remove:()=>void 0,areInstalled:()=>!0}};a.listeners=dc(a),cY[cX]=a,c=a}c.clients.add(a),c.retired.delete(a.key);let d=c;return()=>{d.clients.delete(a)&&([...d.clients].some(b=>b.key===a.key)||d.retired.set(a.key,a))}}(this._autocaptureClient))}claimExplicitCapture(a){var b;let c;return b=this.destinationKey,!(c=cY[cX])||c.capturedThisTurn.get(a)?.get(b)!=="autocapture"&&(c4(c,a,b,"app"),c.deferred.get(a)?.skipKeys.add(b),!0)}capturePendingExceptions(){for(let a of dd())a!==this._autocaptureClient&&this.client.addPendingPromise(a.flush().catch(()=>void 0))}onException(b,c){this.client.addPendingPromise((async()=>{if(!a.isPreviouslyCapturedError(b)){let d=await a.buildEventMessage(this.client.getErrorPropertiesBuilder(),b,c,void 0,void 0,this.client.getContext()),e=d.properties,f=e?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(f)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:f}):this.client._capturePreparedEvent(d,!1)}})().catch(a=>{this._logger.error("Failed to capture an exception:",a)}))}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop(),this.capturePendingExceptions(),this._stopAutocapture?.(),this._stopAutocapture=void 0}},dj=/^[0-9a-f]{32}$/i,dk=/^[0-9a-f]{16}$/i,dl=Symbol.for("opentelemetry.js.api.1"),dm=Symbol.for("OpenTelemetry Context Key SPAN");async function dn(){try{let a=globalThis[dl],b=a?.context?.active().getValue(dm),c=b?.spanContext(),d=c?.traceId,e=c?.spanId;if("string"==typeof d&&"string"==typeof e&&dj.test(d)&&dk.test(e)&&!/^0+$/.test(d)&&!/^0+$/.test(e))return{$trace_id:d.toLowerCase(),$span_id:e.toLowerCase()}}catch{}return{}}class dp{getProperty(a){return this._memoryStorage[a]}setProperty(a,b){this._memoryStorage[a]=null!==b?b:void 0}constructor(){this._memoryStorage={}}}let dq=Symbol.for("posthog-node.context-listeners"),dr=globalThis,ds=dr[dq]??=new WeakMap;function dt(a,b=!1){for(let c of ds.get(a)??[])try{c(b)}catch{}}function du(a){dt(a,!0)}let dv="analytics";class dw extends Error{constructor({requestId:a,drops:b,retryExhausted:c,cause:d}){super(dw.buildMessage(a,b,c,d)),this.name="CaptureV1Error",this.requestId=a,this.drops=b,this.retryExhausted=c,this.cause=d}static buildMessage(a,b,c,d){let e=`Capture V1 batch ${a} did not fully deliver: ${b.length} dropped, ${c.length} undelivered`;return d instanceof Error&&(e+=` (${d.message})`),e}}function dx(a){if("boolean"==typeof a)return a;if("number"==typeof a)return 0!==a;if("string"==typeof a){let b=a.trim().toLowerCase();if("true"===b||"1"===b)return!0;if("false"===b||"0"===b)return!1}}let dy=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:dx},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:dx},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:dx},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(a){return"string"==typeof a?a:void 0}}],dz=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function dA(a,b,c){void 0===c||b in a||(a[b]=c)}function dB(a){var b;let c={..."object"==typeof(b=a.properties)&&null!==b&&!Array.isArray(b)?a.properties:{}},d={};for(let{property:a,optionKey:b,coerce:e}of dy)if(a in c){let f=e(c[a]);void 0!==f&&(d[b]=f),delete c[a]}let e={};for(let{property:a,field:b}of dz)if(a in c){let d=c[a];"string"==typeof d&&(e[b]=d),delete c[a]}return delete c.$lib,delete c.$lib_version,dA(c,"$set",a.$set),dA(c,"$set_once",a.$set_once),{event:String(a.event??""),uuid:String(a.uuid??""),distinct_id:String(a.distinct_id??""),timestamp:function(a){if("string"==typeof a){let b=new Date(a);if(Number.isNaN(b.getTime()))return new Date().toISOString();let c=b.toISOString(),d=a.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return d&&d.length>3?c.replace(/\.\d{3}Z$/,`.${d}Z`):c}if(a instanceof Date)return Number.isNaN(a.getTime())?new Date().toISOString():a.toISOString();let b=null==a?new Date:new Date(a);return Number.isNaN(b.getTime())?new Date().toISOString():b.toISOString()}(a.timestamp),...e,options:d,properties:c}}let dC=new Set([408,500,502,503,504]);class dD{constructor(a,b){this.config=a,this.maxBackoffMs=a.maxBackoffMs??3e4,this.fetchFn=b.fetch,this.onError=b.onError,this.now=b.now??Date.now,this.sleep=b.sleep??(a=>new Promise(b=>aI(b,a))),this.generateRequestId=b.generateRequestId??aS,this.compress=b.compress??aN}async sendV1Batch(a){if(0===a.length)return;let b=this.generateRequestId(),c=new Date(this.now()).toISOString(),{batch:d}=function(a,{createdAt:b,historicalMigration:c}){let d={created_at:b,batch:a.map(dB)};return c&&(d.historical_migration=!0),d}(a,{createdAt:c,historicalMigration:this.config.historicalMigration}),e=`${this.config.host}/i/v1/analytics/events`,f=[],g=d,h=Math.max(1,this.config.maxAttempts);for(let a=1;a<=h;a++){let d,i,j=a===h,k=n({created_at:c,...this.config.historicalMigration?{historical_migration:!0}:{},batch:g});try{let{response:c,signal:h}=d=await this.sendOnce(e,k,a,b),{status:l}=c;if(l<200||l>=300)if(!j&&dC.has(l)){let b=this.parseRetryAfter(c);await d.waitFor(d.cancelBody()).catch(()=>{}),i=this.backoffDelay(a,b)}else{let a=await this.buildHttpError(c,l,d.waitFor);return this.surfaceBatchFailure(b,f,g,a)}else{let e;try{e=await d.waitFor(this.parseResponse(c))}catch(a){if(h.aborted)throw a;return this.surfaceBatchFailure(b,f,g,Error(`Capture V1 returned an unparseable ${l} response body`))}let k=this.classify(g,e,f);if(0===k.length)return this.surfacePartialDrops(b,f);if(j)return void this.onError(new dw({requestId:b,drops:f,retryExhausted:k.map(a=>a.uuid)}));g=k;let m=this.parseRetryAfter(c);i=this.backoffDelay(a,m)}}catch(c){if(d&&!d.signal.aborted)throw c;if(j)return this.surfaceBatchFailure(b,f,g,c);i=this.backoffDelay(a)}finally{d?.cleanup()}void 0!==i&&await this.sleep(i)}}async sendOnce(a,b,c,d){let e,f=this.buildHeaders(c,d),g=b;if(this.config.compressionEnabled){let a=await this.compress(b,this.config.isDebug);null!==a&&(g=a,f["Content-Encoding"]="gzip")}let h=new AbortController,i="waiting for response headers",j=new Promise((a,b)=>{e=aI(()=>{let a=Error(`Capture V1 request timed out ${i} after ${this.config.requestTimeoutMs}ms`);a.name="AbortError",b(a),h.abort(a)},this.config.requestTimeoutMs)});try{let b,c=this.fetchFn(a,{method:"POST",headers:f,body:g,signal:h.signal}),d=!1;c.then(a=>{h.signal.aborted&&!d&&this.cancelBody(a)}).catch(()=>{});let k=await Promise.race([c,j]);d=!0,i="while reading the response body";let l=!1,m=()=>b??=this.cancelBody(k);return{response:k,signal:h.signal,waitFor:a=>Promise.race([a,j]),cancelBody:m,cleanup:()=>{!l&&(l=!0,clearTimeout(e),h.signal.aborted&&m())}}}catch(a){throw clearTimeout(e),a}}buildHeaders(a,b){let c=`${this.config.libraryId}/${this.config.libraryVersion}`,d={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":c,"PostHog-Attempt":String(a),"PostHog-Request-Id":b,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(d["User-Agent"]=this.config.userAgent),d}classify(a,b,c){let d=b.results??{},e=[];for(let b of a){let a=d[b.uuid];a&&("drop"===a.result?c.push({uuid:b.uuid,details:a.details??void 0}):"retry"===a.result&&e.push(b))}return e}backoffDelay(a,b){let c=Math.min(this.config.initialRetryDelayMs*2**(a-1),this.maxBackoffMs);return void 0===b?c:Math.max(c,Math.min(b,this.maxBackoffMs))}parseRetryAfter(a){let b=a.headers?.get("Retry-After");if(!b)return;let c=b.trim();if(/^\d+$/.test(c)){let a=parseInt(c,10);return Number.isFinite(a)&&a>0?1e3*a:void 0}let d=Date.parse(c);if(Number.isNaN(d))return;let e=d-this.now();return e>0?e:void 0}async parseResponse(a){let b=JSON.parse(await a.text());if("object"!=typeof b||null===b||Array.isArray(b))throw Error("unexpected response shape");let c=b.results;if(void 0!==c&&("object"!=typeof c||null===c||Array.isArray(c)))throw Error("unexpected results shape");return{results:c??{}}}async buildHttpError(a,b,c){let d="";try{d=(await c(a.text())).slice(0,512)}catch{}let e=d?`: ${d}`:"";return Error(`Capture V1 request failed with HTTP ${b}${e}`)}surfaceBatchFailure(a,b,c,d){this.onError(new dw({requestId:a,drops:b,retryExhausted:c.map(a=>a.uuid),cause:d}))}surfacePartialDrops(a,b){b.length>0&&this.onError(new dw({requestId:a,drops:b,retryExhausted:[]}))}async cancelBody(a){try{await a.body?.cancel()}catch{}}}let dE="ai-capture",dF="/i/v0/ai/batch/",dG=new TextEncoder;function dH(a){return dG.encode(n(a)).length}class dI extends Error{constructor(a){super(a.message,void 0===a.cause?void 0:{cause:a.cause}),this.name=function(a,b){if("missing_secret_key"===b||401===a)return"missing_api_key";if(void 0===a)return"network_error"===b?"service_unavailable":b.startsWith("invalid_")?"validation_error":"application_error";switch(a){case 400:return"validation_error";case 403:return"invalid_permission";case 404:return"not_found";case 409:return"template_outdated"===b?"validation_error":"concurrent_idempotent_requests";case 422:return"idempotency_key_reused"===b?"invalid_idempotent_request":"validation_error";case 429:return"quota_limited"===b?"monthly_quota_exceeded":"rate_limit_exceeded";case 503:return"service_unavailable";default:return"application_error"}}(a.statusCode,a.code),this.code=a.code,this.statusCode=a.statusCode,this.why=a.why,this.fix=a.fix,this.docsUrl=a.docsUrl,this.field=a.field,this.retryAfterMs=a.retryAfterMs}}let dJ="https://us.posthog.com",dK="https://eu.posthog.com",dL={"https://us.i.posthog.com":dJ,"https://us.posthog.com":dJ,"https://app.posthog.com":dJ,"https://eu.i.posthog.com":dK,"https://eu.posthog.com":dK},dM=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,dN=/^[\x21-\x7e]{1,255}$/,dO=/^[a-zA-Z0-9_-]{1,400}$/,dP={to:!0,distinctId:!0,idempotencyKey:!0,maxRetries:!0},dQ={name:"templateId",fields:dV(dP,{templateId:!0,templateData:!0}),why:"A template made in PostHog sets its own sender, subject and content, and follows the project's engagement setting.",howToSend:"send a template made in PostHog with templateId"},dR={name:"templateKey",fields:dV(dP,{templateKey:!0,subject:!0,from:!0,replyTo:!0,captureEngagement:!0,html:!0,text:!0}),why:"A send with templateKey takes its content from your code.",howToSend:"send content from your code with templateKey"};class dS{constructor(a,b){this.inFlight=new Set,this.config=a,this.hooks=b}send(a,...b){return this.track(this.sendUntracked(a,b))}get(a){return this.track(this.getUntracked(a))}track(a){return this.inFlight.add(a),a.finally(()=>this.inFlight.delete(a)),a}async drain(){for(;this.inFlight.size>0;)await Promise.all(this.inFlight)}async sendUntracked(a,b){try{var c=b;if(c.some(a=>void 0!==a))throw new dI({code:"invalid_form",message:"send takes one options object, so no email was sent. Put idempotencyKey and every other option in it."});let d=function(a,b){let c=a??{},{to:d,distinctId:e,idempotencyKey:f,maxRetries:g}=c;if("string"!=typeof d||!d.trim())throw dW("invalid_recipient","to must be one email address as a nonempty string.","to");if(void 0!==e&&("string"!=typeof e||!e))throw dW("invalid_distinct_id","distinctId must be a nonempty string.","distinctId");let h=function(a,b){if(void 0===a.templateId==(void 0===a.templateKey))throw new dI({code:"invalid_form",message:"Send either templateId, or templateKey with subject and html or text."});return void 0===a.templateKey?function(a,b){let{templateId:c,templateData:d}=a;if("string"!=typeof c||!dM.test(c))throw dW("invalid_template_id","templateId must be the template's UUID.","templateId");if(void 0!==d&&("object"!=typeof d||null===d||Array.isArray(d)))throw dW("invalid_template_data","templateData must be an object.","templateData");return dU(a,dQ,dR),{template_id:c.toLowerCase(),message_data:d??{},...void 0!==b&&{distinct_id:b}}}(a,b):function(a,b){let{templateKey:c,subject:d,html:e,text:f,from:g,replyTo:h,captureEngagement:i}=a;if("string"!=typeof c||!dO.test(c))throw dW("invalid_template_key","templateKey can only have letters, digits, hyphens (-) and underscores (_), at most 400.","templateKey");if(dU(a,dR,dQ),"string"!=typeof d)throw dW("invalid_form","A send with templateKey needs a subject.","subject");if(void 0!==e&&"string"!=typeof e)throw dW("invalid_form","html must be a string.","html");if(void 0!==f&&"string"!=typeof f)throw dW("invalid_form","text must be a string.","text");if(void 0===e&&void 0===f)throw dW("invalid_form","A send with templateKey needs html, text or both.","html");let j=void 0!==h&&!(Array.isArray(h)&&0===h.length);return{template_key:c,subject:d,...void 0!==e&&{html:e},...void 0!==f&&{text:f},...void 0!==g&&{from:g},...j&&{reply_to:"string"==typeof h?[h]:h},capture_engagement:i??!0,...void 0!==b&&{distinct_id:b}}}(a,b)}(c,e);if(void 0!==f&&("string"!=typeof f||!dN.test(f)))throw dW("invalid_idempotency_key","idempotencyKey must be 1 to 255 visible ASCII characters without spaces.","idempotencyKey");if(void 0!==g&&!dT(g))throw dW("invalid_max_retries","maxRetries must be a nonnegative integer.","maxRetries");return{path:"/api/projects/@current/messaging/send/email/",body:n({...h,to:d}),idempotencyKey:f??globalThis.crypto.randomUUID(),maxRetries:dT(g)?g:b}}(a,this.config.maxRetries),{appHost:e,secretKey:f}=this.connect("no email was sent","Sending email needs secretKey, a project secret API key with the transactional_email:write scope."),g=this.headers(f,{"Content-Type":"application/json","Idempotency-Key":d.idempotencyKey}),h=await this.withRetries(d.maxRetries,async()=>(function({status:a,payload:b,retryAfterMs:c}){let d=dZ(b);if(a>=200&&a<300){let b=dY(d.message_id);if(!b)throw new dI({code:"api_error",message:"PostHog answered without a message ID.",statusCode:a});let c=[];if(Array.isArray(d.warnings))for(let a of d.warnings)null!==a&&"object"==typeof a&&c.push({code:dY(a.code)??"warning",message:dY(a.detail)??dY(a.message)??"",fix:dY(a.fix)});return{id:b,replayed:!0===d.replayed,warnings:c}}throw d$(d,a,c)})(await this.request(e+d.path,"POST",g,d.body)));for(let a of h.warnings)this.hooks.logger.warn(`PostHog email warning ${a.code}: ${a.message}`);return{data:h,error:null}}catch(a){return{data:null,error:d_(a,"Sending the email failed unexpectedly.")}}}async getUntracked(a){try{if("string"!=typeof a||!dM.test(a))throw dW("invalid_message_id","id must be the message ID that send() returned.","id");let{appHost:b,secretKey:c}=this.connect("no email status was read","Reading an email status needs secretKey, a project secret API key with the transactional_email:read or transactional_email:write scope."),d=b+"/api/projects/@current/messaging/emails/{messageId}/".replace("{messageId}",a.toLowerCase()),e=this.headers(c,{});return{data:await this.withRetries(this.config.maxRetries,async()=>(function({status:a,payload:b,retryAfterMs:c}){let d=dZ(b);if(a<200||a>=300)throw d$(d,a,c);let e=dY(d.id),f=dY(d.status),g=dY(d.created_at),h=dY(d.status_at);if(!e||!f||!g||!h)throw new dI({code:"api_error",message:"PostHog answered without an email status.",statusCode:a});return{id:e,status:f,createdAt:g,statusAt:h,reason:dY(d.reason)??null}})(await this.request(d,"GET",e))),error:null}}catch(a){return{data:null,error:d_(a,"Reading the email status failed unexpectedly.")}}}connect(a,b){var c,d;let e;if(this.hooks.isDisabled())throw new dI({code:"client_disabled",message:`The PostHog client is disabled, so ${a}.`});if(this.hooks.isClosed())throw new dI({code:"client_closed",message:`The PostHog client is shut down, so ${a}.`});let f=(c=this.config.host,(e="string"==typeof(d=this.config.appHost)?aE(d.trim()):"")?dL[e]??e:dL[aE(c)]);if(!f)throw new dI({code:"missing_app_host",message:"The client's host is not PostHog Cloud, so the client can't tell where to send email. Set appHost to your PostHog app host on the client."});let g=this.config.secretKey?.trim();if(!g)throw new dI({code:"missing_secret_key",message:b});return{appHost:f,secretKey:g}}headers(a,b){let c={Authorization:`Bearer ${a}`,Accept:"application/json",...b};return this.hooks.userAgent&&(c["User-Agent"]=this.hooks.userAgent),this.config.migratedFrom&&(c["X-PostHog-Migrated-From"]=this.config.migratedFrom),c}async withRetries(a,b){for(let c=0;;c++){let d;try{return await b()}catch(a){d=a instanceof dI?a:new dI({code:"network_error",message:"The request to PostHog failed.",cause:a})}let e=function(a,b,c){if(!(b>=c)&&(void 0===a.statusCode?"network_error"===a.code:409===a.statusCode?"idempotency_key_in_flight"===a.code:429===a.statusCode?"quota_limited"!==a.code:503===a.statusCode)&&(void 0===a.retryAfterMs||!(a.retryAfterMs>3e4)))return Math.max(Math.min(3e4,1e3*2**b*(.8+.4*Math.random())),a.retryAfterMs??0)}(d,c,a);if(void 0===e)throw d;await new Promise(a=>setTimeout(a,e))}}async request(a,b,c,d){let e,f,g=new AbortController,h=this.config.requestTimeoutMs,i=new Promise((a,b)=>{e=setTimeout(()=>{let a=Error(`Email request timed out after ${h}ms`);a.name="AbortError",b(a),g.abort(a)},h)}),j=Promise.resolve().then(()=>this.hooks.fetch(a,{method:b,headers:c,...void 0===d?{}:{body:d},signal:g.signal}));j.then(a=>{g.signal.aborted&&Promise.resolve(a.body?.cancel()).catch(()=>{})}).catch(()=>{});try{let a;f=await Promise.race([j,i]);try{a=await Promise.race([f.text(),i])}catch(a){if(f.status>=200&&f.status<300)throw a;return{status:f.status,payload:null,retryAfterMs:dX(f)}}return{status:f.status,payload:function(a){try{return JSON.parse(a)}catch{return null}}(a),retryAfterMs:dX(f)}}finally{clearTimeout(e),g.signal.aborted&&f&&Promise.resolve(f.body?.cancel()).catch(()=>{})}}}function dT(a){return"number"==typeof a&&Number.isInteger(a)&&a>=0}function dU(a,b,c){let d=Object.entries(a).find(([a,c])=>void 0!==c&&!b.fields.has(a))?.[0];if(void 0===d)return;let e=`A send with ${b.name} doesn't take ${d}, so no email was sent.`;if(!c.fields.has(d))throw new dI({code:"invalid_form",message:e,field:d,fix:`Remove ${d} and send again.`});throw new dI({code:"invalid_form",message:e,field:d,why:b.why,fix:`Remove ${d}, or ${c.howToSend}.`})}function dV(...a){return new Set(a.flatMap(a=>Object.keys(a)))}function dW(a,b,c){return new dI({code:a,message:b,field:c})}function dX(a){try{return aW(a.headers?.get("retry-after"),Date.now(),Number.MAX_SAFE_INTEGER)}catch{return}}function dY(a){return"string"==typeof a&&a?a:void 0}function dZ(a){return null===a||"object"!=typeof a||Array.isArray(a)?{}:a}function d$(a,b,c){return new dI({code:dY(a.code)??"api_error",message:dY(a.detail)??`PostHog answered HTTP ${b}.`,statusCode:b,why:dY(a.why),fix:dY(a.fix),docsUrl:dY(a.docs_url),field:dY(a.attr),retryAfterMs:c})}function d_(a,b){return a instanceof dI?a:new dI({code:"unexpected_error",message:b,cause:a})}let d0=new Set;function d1(a,b){d0.has(a)||(d0.add(a),console.warn(`[PostHog] ${b}`))}class d2 extends a6{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(a){this._distinctIdHasSentFlagCalls=new Map(Object.entries(a??{}))}constructor(a,b={}){var c,d;let e,f="string"==typeof a?a.trim():"",g={...b,maxQueueSize:b.maxQueueSize??1e4,flushInterval:b.flushInterval??5e3,host:("string"==typeof(c=b.host)?c.trim():"")||"https://us.i.posthog.com",personalApiKey:("string"==typeof(d=b.secretKey??b.personalApiKey)?d.trim():"")||void 0};if(super(f,g),this._memoryStorage=new dp,this._isShutdown=!1,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=g,this.captureMode="v0"===(e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0)||"v1"===e?e:"v0",this.enableFullAiCapture=!0===g.enableFullAiCapture,this.privacyMode=!0===g.privacyMode,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof g.featureFlagsPollingInterval?Math.max(g.featureFlagsPollingInterval,100):null===g.featureFlagsPollingInterval?null:3e4,"number"==typeof g.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(g.waitUntilDebounceMs,0)),"number"==typeof g.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(g.waitUntilMaxWaitMs,0)),!this.disabled&&(g.personalApiKey||g.flagDefinitionCacheProvider)){if(g.personalApiKey?.includes("phc_"))throw Error('A project API key ("phc_...") was provided as secretKey or personalApiKey. Pass the project API key as the first constructor argument. For local evaluation, set secretKey (or the deprecated personalApiKey alias) to a server-only Project Secret API Key ("phs_...") or Personal API Key ("phx_...") with feature flag read access.');!1!==g.enableLocalEvaluation&&(this.featureFlagsPoller=new cH({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:g.personalApiKey,projectApiKey:f,timeout:g.requestTimeout??1e4,host:this.host,fetch:g.fetch,onError:a=>{this._events.emit("error",a)},onLoad:a=>{this._events.emit("localEvaluationFlagsLoaded",a)},onMinimalFlagCalledEvents:a=>{this._minimalFlagCalledEvents=a},customHeaders:this.getCustomHeaders(),cacheProvider:g.flagDefinitionCacheProvider,strictLocalEvaluation:g.strictLocalEvaluation,evaluationContexts:g.evaluationContexts??g.evaluationEnvironments}))}this.errorTracking=new di(this,g,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=g.maxCacheSize||5e4}enqueue(a,b,c,d){super.enqueue(a,b,c,d),this.scheduleDebouncedFlush()}_flushEventsAndSpans(a=!1){let b=this.flushWithPendingPromises();return!this._traces||a&&this._traces.throttled?b:aK([b,this._traces.flush().catch(()=>{})]).then(([a])=>{if("rejected"===a.status)throw a.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this.errorTracking.capturePendingExceptions(),this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(a){let b=this._flushEventsAndSpans(a),c=this.options.waitUntil;if(c&&!this._waitUntilCycle)try{c(b.catch(()=>{}))}catch{}return b}scheduleDebouncedFlush(){let a=this.options.waitUntil;if(!a||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let b,c=new Promise(a=>{b=a});try{a(c)}catch{return}this._waitUntilCycle={resolve:b,startedAt:Date.now(),timer:void 0}}let b=Date.now()-this._waitUntilCycle.startedAt,c=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),b>=c)return void this.resolveWaitUntilFlush();let d=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=aI(()=>{this.resolveWaitUntilFlush()},d)}_consumeWaitUntilCycle(){let a=this._waitUntilCycle;return a&&(clearTimeout(a.timer),this._waitUntilCycle=void 0),a?.resolve}async resolveWaitUntilFlush(){let a=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{a?.()}}getPersistedProperty(a){return this._memoryStorage.getProperty(a)}setPersistedProperty(a,b){return this._memoryStorage.setProperty(a,b)}fetch(a,b){return this.options.fetch?this.options.fetch(a,b):fetch(a,b)}getQueueRouteKey(a){var b;return"v1"===this.captureMode&&"string"==typeof(b=a).event&&b.event.startsWith("$ai_")?"ai":dv}persistedQueueKeyForRoute(a){return a===dE?k.AiCaptureQueue:"ai"===a?k.AiQueue:k.Queue}getActiveQueueRoutes(){let a="v1"===this.captureMode?[dv,"ai"]:[dv];return this._aiCaptureRouteActive&&a.push(dE),a}getBatchEndpointPath(a){return a===dE?dF:super.getBatchEndpointPath(a)}async sendBatch(a,b,c=dv){if(c===dE)return this.sendAiCaptureBatch(a,b);if("v1"!==this.captureMode||"ai"===c)return super.sendBatch(a,b,c);let d=a.filter(a=>void 0!==a);await this.getV1Sender().sendV1Batch(d)}async sendAiCaptureBatch(a,b){let{batches:c,dropped:d}=function(a,b=8388608,c=5242880){let d=[],e=[],f=[],g=0;for(let h of a){if(void 0===h)continue;let a=dH(h);if(a>b){e.push({event:"string"==typeof h.event?h.event:"unknown",bytes:a});continue}f.length>0&&g+a>c&&(d.push(f),f=[],g=0),f.push(h),g+=a}return f.length>0&&d.push(f),{batches:d,dropped:e}}(a);for(let{event:a,bytes:b}of d){let c=`Event ${a} (${b} bytes) exceeds the 8MiB limit for ${dF}, dropping.`;this._logger.error(c),this._events.emit("error",Error(c))}for(let a of c)await this.sendAiSubBatch(a,b)}async sendAiSubBatch(a,b){try{await super.sendBatch(a,b,dE)}catch(d){if(!a2(d))throw d;if(1===a.length){let[b]=a,c="string"==typeof b.event?b.event:"unknown",d=`Event ${c} (${dH(b)} bytes) was rejected with 413 by ${dF} on its own, dropping.`;this._logger.error(d),this._events.emit("error",Error(d));return}let c=Math.ceil(a.length/2);await this.sendAiSubBatch(a.slice(0,c),b),await this.sendAiSubBatch(a.slice(c),b)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new dD({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:(a,b)=>this.fetch(a,b),onError:a=>this._events.emit("error",a),compress:a=>this.compressPayload(a)})),this._v1Sender}getLibraryVersion(){return"5.63.1"}get metrics(){var a;let b;return this._metrics||(this._metrics=new bB(this,(a=this.options.metrics,b=a?.resourceAttributes,{serviceName:b?.["service.name"]??a?.serviceName,serviceVersion:b?.["service.version"]??a?.serviceVersion,environment:b?.["deployment.environment"]??a?.environment,resourceAttributes:b,beforeSend:a?.beforeSend,flushIntervalMs:a?.flushIntervalMs??1e4,maxSeriesPerFlush:a?.maxSeriesPerFlush??1e3}),this._logger)),this._metrics}get emails(){var a,b;return this._emails||(this._emails=new dS({secretKey:this.options.personalApiKey,host:this.host,appHost:this.options.appHost,requestTimeoutMs:"number"==typeof(a=this.options.emailRequestTimeoutMs)&&Number.isFinite(a)&&a>0?a:15e3,maxRetries:"number"==typeof(b=this.options.emailRequestMaxRetries)&&Number.isFinite(b)&&b>=0?Math.floor(b):2,migratedFrom:this.options.migratedFrom},{fetch:(a,b)=>this.fetch(a,b),isDisabled:()=>this.disabled,isClosed:()=>this._isShutdown,logger:this._logger,userAgent:this.getCustomUserAgent()||void 0})),this._emails}initializeSpanContextManager(){return new b2}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces){var a,b,c;let d,e;return this._traces||(this._traces=new b1(this,(a=this.options.traces,b=this.hostResourceAttributes(),c=this._logger,d=be({...b},function(a){if(!(!a||"object"!=typeof a||Array.isArray(a)))try{if(b7.every(b=>!(b in a)||"string"==typeof a[b]))return a;let b={...a};for(let a of b7)a in b&&"string"!=typeof b[a]&&delete b[a];return b}catch{return}}(a?.resourceAttributes)),e=b6(a?.maxExportBatchSize,512),{serviceName:d?.["service.name"]??a?.serviceName,serviceVersion:d?.["service.version"]??a?.serviceVersion,environment:d?.["deployment.environment"]??a?.environment,resourceAttributes:d,beforeSpanSend:function(a,b){if(!a)return[];let c=[a].flat().filter(a=>!!a),d=c.filter(a=>"function"==typeof a);return d.length!==c.length&&b?.critical(`beforeSpanSend: ignoring ${c.length-d.length} of ${c.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),d}(a?.beforeSpanSend,c),maxAttributesPerSpan:b6(a?.maxAttributesPerSpan,128),maxEventsPerSpan:b6(a?.maxEventsPerSpan,128),maxAttributesPerEvent:128,maxAttributeValueLength:b6(a?.maxAttributeValueLength,8192),flushIntervalMs:b6(a?.flushIntervalMs,5e3),maxExportBatchSize:e,maxQueueSize:Math.max(b6(a?.maxQueueSize,2048),e),maxLiveSpans:b6(a?.maxLiveSpans,1e4),maxSpanAgeMs:b6(a?.maxSpanAgeMs,36e5)}),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}}_tracingContext(){let a=this.context?.get();return{distinctId:a?.distinctId,sessionId:a?.sessionId}}startSpan(a,b){return this._tracesPipeline?.startSpan(a,b)??bO(b,this._spanContextManager.active())}withSpan(a,b,c){let d="function"==typeof b?void 0:b,e="function"==typeof b?b:c,f=this._tracesPipeline;return f?d?f.withSpan(a,d,e):f.withSpan(a,e):bT(this._spanContextManager,bO(d,this._spanContextManager.active()),e)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let a=super.getCommonEventProperties();return(this.options.isServer??!0)&&(a.$is_server=!0),a}enable(){return super.optIn()}disable(){return super.optOut()}debug(a=!0){super.debug(a),this.featureFlagsPoller?.debug(a)}_warnIfInvalidCapture(a,b,c){"string"==typeof a&&this._logger.warn(b),"$exception"!==a.event||a._originatedFromCaptureException||this._logger.warn(c)}_sendPreparedEvent(a,b,c,d,e){return this.addPendingPromise(this._prepareEventMessage(b,d).then(({distinctId:b,event:d,properties:f,options:g})=>{let h={timestamp:g.timestamp,disableGeoip:g.disableGeoip,uuid:g.uuid},i={distinctId:b,event:d,properties:{...f,...this.getCommonEventProperties()}};return c?this.sendImmediate(a,i,h,e):this.enqueue(a,i,h,e)}).catch(a=>{a&&console.error(a)}))}_capturePreparedEvent(a,b){return this._sendPreparedEvent("capture",a,b)}capture(a){this._warnIfInvalidCapture(a,"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(a,!1)}async captureImmediate(a){return this._warnIfInvalidCapture(a,"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(a,!0)}captureAi(a){if(this.disabled)return;let b=aC(a.uuid,aS);return this._sendPreparedAiEvent({...a,uuid:b},!1),b}async captureAiImmediate(a){if(this.disabled)return;let b=aC(a.uuid,aS);return await this._sendPreparedAiEvent({...a,uuid:b},!0),b}_sendPreparedAiEvent(a,b){return"string"!=typeof a?.event||a.event.startsWith("$ai_")||this._logger.debug(`captureAi called with non-AI event ${a.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",a,b,void 0,dE)}identify({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;this._sendPreparedEvent("identify",{distinctId:a,event:"$identify",properties:{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},disableGeoip:c},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;await this._sendPreparedEvent("identify",{distinctId:a,event:"$identify",properties:{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},disableGeoip:c},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:a,properties:b={},propertiesOnce:c={}}){if(0===Object.keys(b).length&&0===Object.keys(c).length)return;let d={};Object.keys(b).length>0&&(d.$set=b),Object.keys(c).length>0&&(d.$set_once=c),this.capture({distinctId:a,event:"$set",properties:d})}unsetPersonProperties({distinctId:a,properties:b}){let c=(Array.isArray(b)?b:[b]).filter(a=>"string"==typeof a&&a.trim().length>0);0!==c.length&&this.capture({distinctId:a,event:"$set",properties:{$unset:c}})}alias(a){this._sendPreparedEvent("alias",{distinctId:a.distinctId,event:"$create_alias",properties:{distinct_id:a.distinctId,alias:a.alias},disableGeoip:a.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(a){await this._sendPreparedEvent("alias",{distinctId:a.distinctId,event:"$create_alias",properties:{distinct_id:a.distinctId,alias:a.alias},disableGeoip:a.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(a){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(a)}getFeatureFlagKeysByEvaluationRuntime(a){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(a)??[]}async waitForLocalEvaluationReady(a=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(b=>{let c=setTimeout(()=>{d(),b(!1)},a),d=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(c),d(),b(a>0)})})}_resolveDistinctId(a,b){return"string"==typeof a?{distinctId:a,options:b}:{distinctId:this.context?.get()?.distinctId,options:a}}async _getFeatureFlagResult(a,b,c={},d){let e,f,g,h,i,j,k,l;if(this.disabled)return void this._logger.warn("The client is disabled");let m=c.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&a in this._flagOverrides){let b=this._flagOverrides[a];if(void 0===b)return;let c=this._payloadOverrides?.[a];return{key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:c}}let{groups:n,disableGeoip:o}=c,{onlyEvaluateLocally:p,personProperties:q,groupProperties:r}=c,s=this.addLocalPersonAndGroupProperties(b,n,q,r);q=s.allPersonProperties,r=s.allGroupProperties;let t=this.createFeatureFlagEvaluationContext(b,n,this.personPropertiesForLocalEvaluation(b,q),r);void 0==p&&(p=this.options.strictLocalEvaluation??!1);let u=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let b=this.featureFlagsPoller?.featureFlagsByKey[a];if(b)try{let c=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(b,t,{matchValue:d});if(c){u=!0;let d=c.value;i=b.id,k="Evaluated locally",l=b.has_experiment,e={key:a,enabled:!1!==d,variant:"string"==typeof d?d:void 0,payload:c.payload??void 0,reason:k,reasonCode:!1===b.active?"flag_disabled":void 0}}}catch(b){if(b instanceof cD||b instanceof cb)this._logger?.info(`${b.name} when computing flag locally: ${a}: ${b.message}`);else throw b}}if(!u&&!p){let b=await super.getFeatureFlagDetailsStateless(t.distinctId,t.groups,q,r,o,[a]);if(void 0===b)h=b8.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===b.minimalFlagCalledEvents,f=b.requestId,g=b.evaluatedAt;let c=[];b.errorsWhileComputingFlags&&c.push(b8.ERRORS_WHILE_COMPUTING),b.quotaLimited?.includes("feature_flags")&&c.push(b8.QUOTA_LIMITED);let d=b.flags[a];if(void 0===d)c.push(b8.FLAG_MISSING);else{let b;if(i=d.metadata?.id,j=d.metadata?.version,k=d.reason?.description??d.reason?.code,l=d.metadata?.has_experiment,d.metadata?.payload!==void 0)try{b=JSON.parse(d.metadata.payload)}catch{b=d.metadata.payload}e={key:a,enabled:d.enabled,variant:d.variant??void 0,payload:b,reason:k,reasonCode:d.reason?.code}}c.length>0&&(h=c.join(","))}}if(m){let c=void 0===e?void 0:!1!==e.enabled&&(e.variant??!0),d={$feature_flag:a,$feature_flag_response:c,$feature_flag_id:i,$feature_flag_version:j,$feature_flag_reason:k,locally_evaluated:u,[`$feature/${a}`]:c,$feature_flag_request_id:f,$feature_flag_evaluated_at:u?Date.now():g};if(void 0!==l&&(d.$feature_flag_has_experiment=l),u&&this.featureFlagsPoller){let a=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==a&&(d.$feature_flag_definitions_loaded_at=a)}h&&(d.$feature_flag_error=h),this._captureFlagCalledEventIfNeeded({distinctId:b,key:a,response:c,groups:n,disableGeoip:o,properties:d})}return void 0!==e&&void 0!==this._payloadOverrides&&a in this._payloadOverrides&&(e={...e,payload:this._payloadOverrides[a]}),e}async getFeatureFlag(a,b,c){d1("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 d=await this._getFeatureFlagResult(a,b,{...c,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(c?.sendFeatureFlagEvents)});if(void 0!==d)return!1!==d.enabled&&(d.variant??!0)}async getFeatureFlagPayload(a,b,c,d){if(d1("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&&a in this._payloadOverrides)return this._payloadOverrides[a];let e=await this._getFeatureFlagResult(a,b,{...d,sendFeatureFlagEvents:!1},c);if(void 0!==e)return e.payload??null}async getFeatureFlagResult(a,b,c){let{distinctId:d,options:e}=this._resolveDistinctId(b,c);return d?this._getFeatureFlagResult(a,d,{...e,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(e?.sendFeatureFlagEvents)}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}async getRemoteConfigPayload(a){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 b=await this._requestRemoteConfigPayload(a);if(!b)return;let c=await b.json();if("string"==typeof c)try{return JSON.parse(c)}catch(a){}return c}async isFeatureEnabled(a,b,c){d1("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 d=await this._getFeatureFlagResult(a,b,{...c,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(c?.sendFeatureFlagEvents)});return void 0===d?void 0:!1!==d.enabled&&!!(d.variant??!0)}async getAllFlags(a,b){let{distinctId:c,options:d}=this._resolveDistinctId(a,b);return c?(await this.getAllFlagsAndPayloads(c,d)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(a,b){let{distinctId:c,options:d}=this._resolveDistinctId(a,b);if(!c)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:e,disableGeoip:f,flagKeys:g}=d||{},{onlyEvaluateLocally:h,personProperties:i,groupProperties:j}=d||{},k=this.addLocalPersonAndGroupProperties(c,e,i,j);i=k.allPersonProperties,j=k.allGroupProperties;let l=this.createFeatureFlagEvaluationContext(c,e,this.personPropertiesForLocalEvaluation(c,i),j);void 0==h&&(h=this.options.strictLocalEvaluation??!1);let m=await this.featureFlagsPoller?.getAllFlagsAndPayloads(l,g),n={},o={},p=!0;if(m&&(n=m.response,o=m.payloads,p=m.fallbackToFlags),p&&!h){let a=await super.getFeatureFlagsAndPayloadsStateless(l.distinctId,l.groups,i,j,f,g);n={...n,...a.flags||{}},o={...o,...a.payloads||{}}}return void 0!==this._flagOverrides&&(n={...n,...this._flagOverrides}),void 0!==this._payloadOverrides&&(o={...o,...this._payloadOverrides}),{featureFlags:n,featureFlagPayloads:o}}async evaluateFlags(a,b){let c,d,{distinctId:e,options:f}=this._resolveDistinctId(a,b);if(!e)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new b9({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new b9({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,flags:{}});let{groups:g,disableGeoip:h}=f||{},i=f?.flagKeys??void 0;if(i?.length===0)return new b9({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:{}});let{onlyEvaluateLocally:j,personProperties:k,groupProperties:l}=f||{},m=this.addLocalPersonAndGroupProperties(e,g,k,l);k=m.allPersonProperties,l=m.allGroupProperties;let n=this.createFeatureFlagEvaluationContext(e,g,this.personPropertiesForLocalEvaluation(e,k),l);void 0==j&&(j=this.options.strictLocalEvaluation??!1);let o=i?new Set(i):void 0,p={},q=!1,r=!1,s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(n,i),t=new Set;if(s)for(let[a,b]of Object.entries(s.response)){let c=this.featureFlagsPoller?.featureFlagsByKey[a];p[a]={key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:s.payloads[a],id:c?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:c?.has_experiment},t.add(a)}let u=void 0!==o&&Array.from(o).some(a=>this.featureFlagsPoller?.featureFlagsByKey[a]===void 0);if((!s||s.fallbackToFlags||u)&&!j){let a=await super.getFeatureFlagDetailsStateless(n.distinctId,n.groups,k,l,h,i);if(a)for(let[b,e]of(this._minimalFlagCalledEvents=!0===a.minimalFlagCalledEvents,c=a.requestId,d=a.evaluatedAt,q=!!a.errorsWhileComputingFlags,r=Array.isArray(a.quotaLimited)&&a.quotaLimited.includes("feature_flags"),Object.entries(a.flags))){let a;if(!t.has(b)){if(e.metadata?.payload!==void 0)try{a=JSON.parse(e.metadata.payload)}catch{a=e.metadata.payload}p[b]={key:b,enabled:e.enabled,variant:e.variant,payload:a,id:e.metadata?.id,version:e.metadata?.version,reason:e.reason?.description??e.reason?.code,locallyEvaluated:!1,hasExperiment:e.metadata?.has_experiment}}}}if(void 0!==this._flagOverrides)for(let[a,b]of Object.entries(this._flagOverrides)){if(void 0===b){delete p[a];continue}let c=p[a];p[a]={key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:c?.payload,id:c?.id,version:c?.version,reason:c?.reason,locallyEvaluated:c?.locallyEvaluated??!1,hasExperiment:c?.hasExperiment}}if(void 0!==this._payloadOverrides)for(let[a,b]of Object.entries(this._payloadOverrides)){let c=p[a];c&&(p[a]={...c,payload:b})}if(void 0!==o)for(let a of Object.keys(p))o.has(a)||delete p[a];let v={};for(let[a,b]of Object.entries(s?.unresolved??{}))Object.prototype.hasOwnProperty.call(p,a)||(v[a]=b);return new b9({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:p,unresolvedFlags:v,requestId:c,evaluatedAt:d,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:q,quotaLimited:r})}_shouldSendMinimalFlagCalledEvent(a,b){return"$feature_flag_called"===a&&this._minimalFlagCalledEvents&&!1===b.$feature_flag_has_experiment}_captureFlagCalledEventIfNeeded(a){let{distinctId:b,key:c,response:d,groups:e,disableGeoip:f,properties:g}=a,h=e&&Object.keys(e).length>0?`_${JSON.stringify(Object.entries(e).sort(([a],[b])=>a<b?-1:+(a>b)))}`:"",i=`${c}_${d}${h}`,j=this._distinctIdHasSentFlagCalls.get(b)??new Set;if(this._distinctIdHasSentFlagCalls.delete(b),this._distinctIdHasSentFlagCalls.set(b,j),!j.has(i)){for(j.add(i);this._distinctIdHasSentFlagCalls.size>Math.max(this.maxCacheSize,1);){let a=this._distinctIdHasSentFlagCalls.keys().next().value;if(void 0===a)break;this._distinctIdHasSentFlagCalls.delete(a)}this.capture({distinctId:b,event:"$feature_flag_called",properties:g,groups:e,disableGeoip:f})}}_resolveSendFeatureFlagEvents(a){return a??this.options.sendFeatureFlagEvent??!0}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:a=>this._captureFlagCalledEventIfNeeded(a),resolveSendFeatureFlagEvents:a=>this._resolveSendFeatureFlagEvents(a),logWarning:a=>{!1!==this.options.featureFlagsLogWarnings&&console.warn(`[PostHog] ${a}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:a,groupKey:b,properties:c,distinctId:d,disableGeoip:e}){this._sendPreparedEvent("capture",{distinctId:d||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{}},disableGeoip:e},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:a,groupKey:b,properties:c,distinctId:d,disableGeoip:e}){await this._sendPreparedEvent("capture",{distinctId:d||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{}},disableGeoip:e},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(a){let b=a=>Object.fromEntries(a.map(a=>[a,!0]));if(!1===a){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(a)){this._flagOverrides=b(a);return}if(this._isFeatureFlagOverrideOptions(a)){"flags"in a&&(!1===a.flags?this._flagOverrides=void 0:Array.isArray(a.flags)?this._flagOverrides=b(a.flags):void 0!==a.flags&&(this._flagOverrides={...a.flags})),"payloads"in a&&(!1===a.payloads?this._payloadOverrides=void 0:void 0!==a.payloads&&(this._payloadOverrides={...a.payloads}));return}this._flagOverrides={...a}}_isFeatureFlagOverrideOptions(a){if("object"!=typeof a||null===a||Array.isArray(a))return!1;if("flags"in a){let b=a.flags;if(!1===b||Array.isArray(b)||"object"==typeof b&&null!==b)return!0}if("payloads"in a){let b=a.payloads;if(!1===b||"object"==typeof b&&null!==b)return!0}return!1}withContext(a,b,c){return this.context?this.context.run(a,()=>(dt(this),b()),c):b()}getContext(){return this.context?.get()}enterContext(a,b){this.context?.enter(a,b),dt(this)}async _shutdown(a){let b=Date.now()+(a??3e4);this._isShutdown=!0;let c=this._emails?.drain(),d=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(a),this.errorTracking.shutdown(),this._metrics&&(await aJ(this._metrics.flush().catch(()=>{}),Math.max(0,b-Date.now())),this._metrics.reset()),this._traces&&(await aJ(this._traces.flush().catch(()=>{}),Math.max(0,b-Date.now())),this._traces.reset());let e=Math.max(0,b-Date.now()),f=c?aJ(c,e):void 0;try{return await super._shutdown(e)}finally{await f,this._distinctIdHasSentFlagCalls.clear(),d?.()}}async _requestRemoteConfigPayload(a){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let b=`${this.host}/api/projects/@current/feature_flags/${a}/remote_config?token=${encodeURIComponent(this.apiKey)}`,c={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},d=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let a=new AbortController;d=aI(()=>{a.abort()},this.options.requestTimeout),c.signal=a.signal}try{return await this.fetch(b,c)}catch(a){this._events.emit("error",a);return}finally{d&&clearTimeout(d)}}extractPropertiesFromEvent(a,b){if(!a)return{personProperties:{},groupProperties:{}};let c={},d={};for(let[e,f]of Object.entries(a))if(function(a){return"[object Object]"===Object.prototype.toString.call(a)}(f)&&b&&e in b){let a={};for(let[b,c]of Object.entries(f))a[String(b)]=String(c);d[String(e)]=a}else c[String(e)]=String(f);return{personProperties:c,groupProperties:d}}async getFeatureFlagsForEvent(a,b,c,d){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let e=d?.personProperties||{},f=d?.groupProperties||{},g=d?.flagKeys;if(d?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let d={};for(let[a,c]of Object.entries(b||{}))d[a]=String(c);return await this.getAllFlags(a,{groups:d,personProperties:e,groupProperties:f,disableGeoip:c,onlyEvaluateLocally:!0,flagKeys:g})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let d={};for(let[a,c]of Object.entries(b||{}))d[a]=String(c);return await this.getAllFlags(a,{groups:d,personProperties:e,groupProperties:f,disableGeoip:c,onlyEvaluateLocally:!0,flagKeys:g})}return(await super.getFeatureFlagsStateless(a,b,e,f,c)).flags}addLocalPersonAndGroupProperties(a,b,c,d){let e={...c||{}},f={};if(b)for(let a of Object.keys(b))f[a]={$group_key:b[a],...d?.[a]||{}};return{allPersonProperties:e,allGroupProperties:f}}personPropertiesForLocalEvaluation(a,b){return{distinct_id:a,...b||{}}}createFeatureFlagEvaluationContext(a,b,c,d){return{distinctId:a,groups:b||{},personProperties:c||{},groupProperties:d||{},evaluationCache:{}}}captureException(a,b,c,d,e){if(!di.isPreviouslyCapturedError(a)&&this.errorTracking.claimExplicitCapture(a)){let f=Error("PostHog syntheticException");this.addPendingPromise(di.buildEventMessage(this.getErrorPropertiesBuilder(),a,{syntheticException:f},b,c,this.getContext()).then(a=>this._capturePreparedEvent({...a,uuid:d,flags:e},!1)))}}async captureExceptionImmediate(a,b,c,d){if(!di.isPreviouslyCapturedError(a)&&this.errorTracking.claimExplicitCapture(a)){let e=Error("PostHog syntheticException");return this.addPendingPromise(di.buildEventMessage(this.getErrorPropertiesBuilder(),a,{syntheticException:e},b,c,this.getContext()).then(a=>this.captureImmediate({...a,flags:d})))}}async prepareEventMessage(a){return this._prepareEventMessage(a)}async _prepareEventMessage(a,b={}){var c;let{distinctId:d,event:e,properties:f,groups:g,flags:h,sendFeatureFlags:i,timestamp:j,disableGeoip:k,uuid:l}=a,m=(c=this.context?.get(),de in a?a[de]??void 0:c),n=b.includeContextProperties??!0,o=d||m?.distinctId,p=n?{...this.props,...m?.properties||{},...f||{}}:{...f||{}};"$exception"!==e||"$trace_id"in p||"$span_id"in p||Object.assign(p,await dn()),o||(o=aS(),p.$process_person_profile=!1),n&&m?.sessionId&&!p.$session_id&&(p.$session_id=m.sessionId);let q=this._shouldSendMinimalFlagCalledEvent(e,p)?aA(p):p,r=this._runBeforeSend({distinctId:o,event:e,properties:q,groups:g,flags:h,sendFeatureFlags:i,timestamp:j,disableGeoip:k,uuid:l});if(!r)return Promise.reject(null);let s=await Promise.resolve().then(async()=>{if(h)return i&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),h._getEventProperties();if(i){d1("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 a=await this.getFeatureFlagsForEvent(r.distinctId,g,k,"object"==typeof i?i:void 0);if(!a)return{};let b={};for(let[c,d]of Object.entries(a))b[`$feature/${c}`]=d;let c=Object.keys(a).filter(b=>!1!==a[b]).sort();return c.length>0&&(b.$active_feature_flags=c),b}return{}}).catch(()=>({})).then(a=>{let b=r.groups||g;return{...a,...r.properties||{},...void 0!==b&&Object.keys(b).length>0?{$groups:b}:{}}});return"$pageview"===r.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof s.$raw_user_agent&&b5(s.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(r.event="$bot_pageview",s.$browser_type="bot"),{distinctId:r.distinctId,event:r.event,properties:s,options:{timestamp:r.timestamp,disableGeoip:r.disableGeoip,uuid:r.uuid}}}_runBeforeSend(a){let b=this.options.before_send;if(!b)return a;let c=Array.isArray(b)?b:[b],d=a;for(let b of c)try{if(!(d=b(d)))return this._logger.info(`Event '${a.event}' was rejected in beforeSend function`),null;if(!d.properties||0===Object.keys(d.properties).length){let a=`Event '${d.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(a)}}catch(b){return this._logger.error(`Error in before_send function for event '${a.event}':`,b),null}return d}}var d3=ai,d4=ai,d5=ai,d6=ai,d7=ai,d8=ai,d9=ai,ea=ai,eb=a.i(78500);let ec=new WeakMap;function ed(a,b,c){let d=a&&ec.get(a);return c?ec.set(b,{signal:c,parent:d}):d&&ec.set(b,d),b}class ee{constructor(){this.storage=new eb.AsyncLocalStorage}get(){let a=this.storage.getStore();return a&&function(a){let b=ec.get(a);for(;b;){if(b.signal.aborted)return!1;b=b.parent}return!0}(a)?a:void 0}run(a,b,c){return this.storage.run(this.resolve(a,c),b)}enter(a,b){this.storage.enterWith(this.resolve(a,b))}resolve(a,b){let c=this.get();return b?.fresh===!0?ed(void 0,{...a},b.signal):ed(c,{distinctId:a.distinctId??c?.distinctId,sessionId:a.sessionId??c?.sessionId,properties:{...c?.properties||{},...a.properties||{}}},b?.signal)}}class ef{active(){return this._storage.getStore()}with(a,b){return this._storage.run(a,b)}constructor(){this._storage=new eb.AsyncLocalStorage}}var eg=a.i(27028);let eh=(0,a.i(12057).promisify)(eg.gzip);async function ei(a,b=!0){try{let b=await eh(a);return new Uint8Array(b)}catch(a){return b&&console.error("Failed to gzip compress data",a),null}}var ej=a.i(60526),dh=ai;let ek="posthog-node";function el(a,{organization:b,projectId:c,prefix:d,severityAllowList:e=["error"],sendExceptionsToPostHog:f=!0}={}){return g=>{if(!("*"===e||e.includes(g.level)))return g;g.tags||(g.tags={});let h=g.tags[en.POSTHOG_ID_TAG];if(void 0===h)return g;let i=a.options.host??"https://us.i.posthog.com",j=new URL(`/project/${a.apiKey}/person/${h}`,i).toString();g.tags["PostHog Person URL"]=j;let k=g.exception?.values||[],l=k.map(a=>({...a,stacktrace:a.stacktrace?{...a.stacktrace,type:"raw",frames:(a.stacktrace.frames||[]).map(a=>({...a,platform:"node:javascript"}))}:void 0})),m={$exception_message:k[0]?.value||g.message,$exception_type:k[0]?.type,$exception_level:g.level,$exception_list:l,$sentry_event_id:g.event_id,$sentry_exception:g.exception,$sentry_exception_message:k[0]?.value||g.message,$sentry_exception_type:k[0]?.type,$sentry_tags:g.tags},n=dh.getInjectedReleaseId();return n&&(m.$release_id=n),b&&c&&(m.$sentry_url=(d||"https://sentry.io/organizations/")+b+"/issues/?project="+c+"&query="+g.event_id),f&&a.capture({event:"$exception",distinctId:h,properties:m}),g}}function em(a,b){let c=el(a,b);return{name:ek,processEvent:a=>c(a)}}class en{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(a,b,c,d,e){this.name=ek,this.name=ek,this.setupOnce=function(f,g){f(el(a,{organization:b,projectId:g()?.getClient()?.getDsn()?.projectId,prefix:c,severityAllowList:d,sendExceptionsToPostHog:e??!0}))}}}function eo(a){let b={};if(a)for(let c of a.split(";")){let[a,...d]=c.trim().split("=");if(a){let c=d.join("=").trim();try{b[a.trim()]=decodeURIComponent(c)}catch{b[a.trim()]=c}}}return{get:a=>a in b?{value:b[a]}:void 0}}function ep(a){let b=a.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${b}_posthog`}function eq(a){let b=Date.now();return JSON.stringify({distinct_id:a,$device_id:a,$user_state:"anonymous",$sesid:[b,aS(),b]})}function er(a,b){let c=ep(b),d=a.get(c);return d?et(d.value):null}function es(a){if(!a)return;let b={};return a.sessionId&&(b.$session_id=a.sessionId),a.deviceId&&(b.$device_id=a.deviceId),Object.keys(b).length>0?b:void 0}function et(a){if(!a)return null;try{let b=JSON.parse(a);if(!b||"object"!=typeof b||!b.distinct_id)return null;let c=r(b.$sesid)?b.$sesid:[],d=c[1];return{distinctId:String(b.distinct_id),isIdentified:"identified"===b.$user_state,sessionId:"string"==typeof d?d:void 0,sessionLastActivityTimestamp:eu(c[0]),sessionStartTimestamp:eu(c[2]),deviceId:"string"==typeof b.$device_id?b.$device_id:void 0}}catch{return null}}function eu(a){return"number"==typeof a&&Number.isFinite(a)?a:void 0}a.s(["PostHogSentryIntegration",0,en,"createEventProcessor",0,el,"sentryIntegration",0,em],9318);let ev=/[\x00-\x1f\x7f-\x9f]/g;function ew(a,b,c){null!=c&&""!==c&&(a[b]=c)}function ex(a){return Array.isArray(a)?a[0]:a}function ey(a){if(Array.isArray(a)){for(let b of a){let a=ey(b);if(void 0!==a)return a}return}if("string"!=typeof a)return;let b=a.replace(ev,"").trim();if(b)return b.length>1e3?b.slice(0,1e3):b}function ez(a,b,c){return"number"==typeof a&&Number.isFinite(a)&&Math.abs(b-a)<=c}function eA(a,b){var c,d;let e,f,g=function(a,b){let c;if(!a)return{};let d=ey(a["x-posthog-session-id"]),e=ey(a["x-posthog-distinct-id"]),{sessionId:f,distinctId:g}=void 0===d&&void 0===e&&b?function(a,b,c=Date.now(),d=18e5,e=!1){try{let f;if("string"!=typeof a)return{};let g=eo(a.split(";").reverse().join(";")),h=g.get(ep(b))?.value,i=g.get("__ph_opt_in_out_"+b)?.value??"";if(!h||m(B,i)||e&&!m(A,i))return{};let j=JSON.parse(h);if(!j||"object"!=typeof j)return{};let k="identified"===j.$user_state?ey(j.distinct_id):void 0,l=j.$sesid;if(Array.isArray(l)&&(2===l.length||3===l.length)){let[a,b,e=a]=l;ez(a,c,d)&&ez(e,c,864e5)&&(f=ey(b))}return{...void 0!==f?{sessionId:f}:{},...void 0!==k?{distinctId:k}:{}}}catch{return{}}}(a.cookie,b.apiKey,Date.now(),"number"==typeof(c=b.sessionIdleTimeoutSeconds)&&Number.isFinite(c)&&0!==c?1e3*Math.min(Math.max(c,60),36e3):18e5,!0===b.optOutCapturingByDefault):{sessionId:d,distinctId:e};return{...void 0!==f?{sessionId:f}:{},...void 0!==g?{distinctId:g}:{}}}(b.headers,!0===(e=a.options.readPostHogCookie)?{apiKey:a.apiKey}:e&&"object"==typeof e?{apiKey:a.apiKey,sessionIdleTimeoutSeconds:e.sessionIdleTimeoutSeconds,optOutCapturingByDefault:e.optOutCapturingByDefault}:null),h=a.getContext(),i=h?.sessionId??g.sessionId,j=h?.distinctId??g.distinctId,k={},l=!0===a.options.disable_capture_url_hashes;return ew(k,"$current_url",(c=b.originalUrl||b.url,l?aF(c):c)),ew(k,"$request_method",b.method),ew(k,"$request_path",(d=b.path,f=function(a){if(!a)return a;let b=a.indexOf("?"),c=a.indexOf("#");return -1===b||-1!==c&&c<b?a:`${a.slice(0,b)}${-1===c?"":a.slice(c)}`}(d),l?aF(f):f)),ew(k,"$user_agent",ex(b.headers["user-agent"])),ew(k,"$ip",function(a){let b=ex(a.headers["x-forwarded-for"]);if(b){let a=b.split(",")[0].trim();if(a)return a}return a.socket?.remoteAddress}(b)),{...void 0!==i?{sessionId:i}:{},...void 0!==j?{distinctId:j}:{},properties:k}}function eB(a,b){var c;b.use((c=a,(a,b,d)=>{c.withContext(eA(c,a),()=>{dt(c,!0),d()})}))}function eC(a,b){var c;b.use((c=a,(a,b,d,e)=>{if(di.isPreviouslyCapturedError(a))return void e(a);let f=eA(c,b),g=Error("Synthetic exception"),h={...void 0!==f.sessionId?{$session_id:f.sessionId}:{},...f.properties||{}};c.addPendingPromise(Promise.all([di.buildEventMessage(c.getErrorPropertiesBuilder(),a,{mechanism:{type:"middleware",handled:!1},syntheticException:g},f.distinctId,h,c.getContext()),d.headersSent||d.destroyed?Promise.resolve(d.headersSent?d.statusCode:void 0):new Promise(a=>{let b=b=>{clearTimeout(e),d.removeListener("finish",c),d.removeListener("close",c),a(b)},c=()=>b(d.headersSent?d.statusCode:void 0),e=setTimeout(()=>b(void 0),1e3);e.unref(),d.once("finish",c),d.once("close",c)})]).then(([a,b])=>(void 0!==b&&(a.properties={...a.properties,$response_status_code:b}),c._capturePreparedEvent(a,!1)))),e(a)}))}a.s(["setupExpressErrorHandler",0,eC,"setupExpressRequestContext",0,eB],40602),a.i(9318),a.i(40602),a.i(46539),a.s(["EmailError",0,dI,"FeatureFlagError",0,l,"FeatureFlagEvaluations",0,b9,"PostHogSentryIntegration",0,en,"cookieStateToProperties",0,es,"cookieStoreFromHeader",0,eo,"createEventProcessor",0,el,"enrichCurrentSpan",0,du,"getPostHogCookieName",0,ep,"parsePostHogCookie",0,et,"readPostHogCookie",0,er,"sentryIntegration",0,em,"serializePostHogCookie",0,eq,"setupExpressErrorHandler",0,eC,"setupExpressRequestContext",0,eB,"uuidv7",0,aS],80456),a.i(80456),a.s(["EmailError",0,dI,"FeatureFlagError",0,l,"FeatureFlagEvaluations",0,b9,"PostHog",0,class extends d2{getLibraryId(){return"posthog-node"}compressPayload(a){return ei(a,this.isDebug)}initializeContext(){return new ee}initializeSpanContextManager(){return new ef}hostResourceAttributes(){return function(){var a,b;let c,d,e;try{c=(0,ej.platform)(),d=(0,ej.release)()}catch{}return a=c,b=d,{...(e=function(a){if(a)return Object.prototype.hasOwnProperty.call(bx,a)?bx[a]:a}(a))?{"os.name":e}:{},...b?{"os.version":b}:{}}}()}createErrorPropertiesBuilder(){let a;return new d3.ErrorPropertiesBuilder([new d4.EventCoercer,new d5.ErrorCoercer,new d6.ObjectCoercer,new d7.StringCoercer,new d8.PrimitiveCoercer],d9.createStackParser("node:javascript",ea.nodeStackLineParser),[(a=function(a=process.argv[1]?(0,i.dirname)(process.argv[1]):process.cwd(),b="\\"===i.sep){let c=b?j(a):a;return a=>{if(!a)return;let d=b?j(a):a,{dir:e,base:f,ext:g}=i.posix.parse(d);(".js"===g||".mjs"===g||".cjs"===g)&&(f=f.slice(0,-1*g.length));let h=decodeURIComponent(f);e||(e=".");let k=e.lastIndexOf("/node_modules");if(k>-1)return`${e.slice(k+14).replace(/\//g,".")}:${h}`;if(e.startsWith(c)){let a=e.slice(c.length+1).replace(/\//g,".");return a?`${a}:${h}`:h}return h}}(),async b=>{for(let c of b)c.module=a(c.filename);return b}),a=>ap(a,void 0,this._logger),function(a=process.cwd()){i.sep;let b=a=>a,c=b(a);return async a=>{for(let d of a)!(!d.filename||d.filename.startsWith("node:")||d.filename.startsWith("data:"))&&(0,i.isAbsolute)(d.filename)&&(d.filename=b((0,i.relative)(c,b(d.filename))));return a}}()])}},"PostHogSentryIntegration",0,en,"cookieStateToProperties",0,es,"cookieStoreFromHeader",0,eo,"createEventProcessor",0,el,"enrichCurrentSpan",0,du,"getPostHogCookieName",0,ep,"parsePostHogCookie",0,et,"readPostHogCookie",0,er,"sentryIntegration",0,em,"serializePostHogCookie",0,eq,"setupExpressErrorHandler",0,eC,"setupExpressRequestContext",0,eB,"uuidv7",0,aS],74493)}];
1
+ module.exports=[74493,a=>{"use strict";let b,c,d,e,f,g;var h,i=a.i(14747);function j(a){return a.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var k=((h={}).AnonymousId="anonymous_id",h.DistinctId="distinct_id",h.Props="props",h.EnablePersonProcessing="enable_person_processing",h.PersonMode="person_mode",h.FeatureFlagDetails="feature_flag_details",h.FeatureFlags="feature_flags",h.FeatureFlagPayloads="feature_flag_payloads",h.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",h.BootstrapFeatureFlags="bootstrap_feature_flags",h.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",h.OverrideFeatureFlags="override_feature_flags",h.Queue="queue",h.AiQueue="ai_queue",h.AiCaptureQueue="ai_capture_queue",h.LogsQueue="logs_queue",h.OptedOut="opted_out",h.SessionId="session_id",h.SessionStartTimestamp="session_start_timestamp",h.SessionLastTimestamp="session_timestamp",h.PersonProperties="person_properties",h.GroupProperties="group_properties",h.InstalledAppBuild="installed_app_build",h.InstalledAppVersion="installed_app_version",h.SessionReplay="session_replay",h.PushRegistered="push_registered",h.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",h.SurveyLastSeenDate="survey_last_seen_date",h.SurveysInProgress="surveys_in_progress",h.SurveysSeen="surveys_seen",h.Surveys="surveys",h.RemoteConfig="remote_config",h.FlagsEndpointWasHit="flags_endpoint_was_hit",h.DeviceId="device_id",h);let l={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",EVALUATION_FAILED:"evaluation_failed",LOCAL_EVALUATION_INCONCLUSIVE:"local_evaluation_inconclusive",QUOTA_LIMITED:"quota_limited",TIMEOUT:"timeout",CONNECTION_ERROR:"connection_error",UNKNOWN_ERROR:"unknown_error",apiError:a=>`api_error_${a}`};function m(a,b){return -1!==a.indexOf(b)}function n(a){let b=[];return JSON.stringify(a,function(a,c){if("bigint"==typeof c)return c.toString();if("function"!=typeof c&&"symbol"!=typeof c){if(c instanceof Error)return{name:c.name,message:c.message,stack:c.stack};if(c&&"object"==typeof c){for(;b.length>0&&b[b.length-1]!==this;)b.pop();if(b.includes(c))return"[Circular]";b.push(c)}return c}})??"null"}let o=Array.isArray,p=Object.prototype,q=p.hasOwnProperty,r=p.toString,s=o||function(a){return"[object Array]"===r.call(a)},t=a=>void 0===a,u=a=>"[object String]"==r.call(a),v=a=>u(a)&&0===a.trim().length,w=a=>null===a,x=a=>t(a)||w(a),y=a=>"[object Number]"==r.call(a)&&a==a,z=a=>"[object Boolean]"===r.call(a);function A(a){switch(Object.prototype.toString.call(a)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return D(a,Error)}}function B(a){return"u">typeof Event&&D(a,Event)}function C(a){return"[object Object]"===Object.prototype.toString.call(a)}function D(a,b){try{return a instanceof b}catch{return!1}}let E=[!0,"true",1,"1","yes"],F=[!1,"false",0,"0","no"];function G(a,b,c){return a&&c?b.length===Object.keys(c).length&&b.every(b=>a[b]===c[b]):a===c}class H{constructor(a,b,c=[]){this.coercers=a,this.stackParser=b,this.modifiers=c}buildFromUnknown(a,b={}){let c=b&&b.mechanism||{handled:!0,type:"generic"},d=this.buildCoercingContext(c,b,0).apply(a),e=this.buildParsingContext(b),f=this.parseStacktrace(d,e);return{$exception_list:this.convertToExceptionList(f,c),$exception_level:"error"}}async modifyFrames(a){for(let b of a)b.stacktrace&&b.stacktrace.frames&&s(b.stacktrace.frames)&&(b.stacktrace.frames=await this.applyModifiers(b.stacktrace.frames));return a}coerceFallback(a){return{type:"Error",value:"Unknown error",stack:a.syntheticException?.stack,synthetic:!0}}parseStacktrace(a,b){let c,d;if(null!=a.cause&&(c=this.parseStacktrace(a.cause,b)),""!=a.stack&&null!=a.stack)try{d=this.applyChunkIds(this.stackParser(a.stack,a.synthetic?b.skipFirstLines:0),b.chunkIdMap)}catch{}return{...a,cause:c,stack:d,errors:a.errors?.map(a=>this.parseStacktrace(a,b))}}applyChunkIds(a,b){return a.map(a=>(a.filename&&b&&(a.chunk_id=b[a.filename]),a))}applyCoercers(a,b){for(let c of this.coercers)if(c.match(a))return c.coerce(a,b);return this.coerceFallback(b)}async applyModifiers(a){let b=a;for(let a of this.modifiers)b=await a(b);return b}convertToExceptionList(a,b){let c=[],d=(a,e,f)=>{let g=c.length,h=void 0===e?{type:"string"==typeof b.type&&b.type.length>0?b.type:"generic",..."boolean"==typeof b.handled?{handled:b.handled}:void 0===b.handled?{handled:!0}:{},synthetic:"boolean"==typeof b.synthetic?b.synthetic:a.synthetic,exception_id:g}:{type:"chained",source:f,synthetic:a.synthetic,exception_id:g,parent_id:e},i={type:a.type,value:a.value,mechanism:h};for(let b of(a.stack&&(i.stacktrace={type:"raw",frames:a.stack}),c.push(i),a.cause&&d(a.cause,g,"cause"),a.errors??[]))d(b,g,"member")};return d(a),c}buildParsingContext(a){return{chunkIdMap:function(a){let f=globalThis._posthogChunkIds,g=globalThis._debugIds;if(!f&&!g)return;let h=f?Object.keys(f):[],i=g?Object.keys(g):[];if(e&&G(f,h,c)&&G(g,i,d))return e;c=f?{...f}:void 0,d=g?{...g}:void 0,e={},b??={};let j=(c,d)=>{for(let f of c){let c=d[f];if(!c)continue;let g=b?.[f];if(g){e[g]=c;continue}let h=a(f);for(let a=h.length-1;a>=0;a--){let d=h[a]?.filename;if(d){e[d]=c,b[f]=d;break}}}};return g&&j(i,g),f&&j(h,f),e}(this.stackParser),skipFirstLines:a.skipFirstLines??1}}getAggregateErrors(a){try{if(A(a)){let b=Object.getPrototypeOf(a);for(let c=0;b&&c<100;c++){let c=Object.getOwnPropertyDescriptor(b,"constructor")?.value;if("function"==typeof c&&"AggregateError"===c.name){let b=a.errors;return s(b)?b:void 0}b=Object.getPrototypeOf(b)}}}catch{}}buildCoercingContext(a,b,c=0){let d=0,e=0,f=!1,g=new Set,h=[],i={},j=(a,b,c=0)=>{let j,l,m=k(b,c),n=m.apply;if(m.apply=b=>{h.push(a);try{return n(b)}finally{h.pop()}},c>4||c>0&&-1!==h.indexOf(a))return this.coerceFallback(m);let o="object"==typeof a&&null!==a||"function"==typeof a;if(0===c&&d>=50||o&&g.has(a))return;o&&g.add(a),0===c&&d++;let p=this.getAggregateErrors(a);f||=!!p;try{if(!(j=this.applyCoercers(a,m)))throw i}catch(a){if(a===i){0===c&&d--;return}if(!f)throw a;j=this.coerceFallback(m)}if(!p||d>=50)return j;try{l=p.length}catch{return j}if(!Number.isInteger(l)||l<0||l>0xffffffff)return j;let q=[];for(let a=0;d<50&&e<1e3&&a<l;a++){let c;e++;try{c=m.next(p[a])}catch{d++,c=this.coerceFallback(k(b+1))}c&&q.push(c)}return{...j,errors:q}},k=(c,d=0)=>({...b,syntheticException:0==c?b.syntheticException:void 0,mechanism:0==c?a:{},apply:a=>{let b=j(a,c,d+1);if(!b)throw i;return b},next:a=>j(a,c+1)}),l=k(c);return{...l,apply:a=>j(a,c)??this.coerceFallback(l)}}}a.s(["ErrorPropertiesBuilder",0,H],6762),a.i(6762);let I=/^([a-z][a-z0-9.+-]+):/i,J=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function K(a,b,c,d,e){let f={platform:a,filename:b,function:"<anonymous>"===c?"?":c,in_app:function(a){if(!a||"<anonymous>"===a)return!1;let b=I.exec(a);return!b||J.includes(b[1].toLowerCase())}(b)};return t(d)||(f.lineno=d),t(e)||(f.colno=e),f}let L=(a,b)=>{let c=-1!==a.indexOf("safari-extension"),d=-1!==a.indexOf("safari-web-extension");return c||d?[-1!==a.indexOf("@")?a.split("@")[0]:"?",c?`safari-extension:${b}`:`safari-web-extension:${b}`]:[a,b]},M=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,N=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,O=/\((\S*)(?::(\d+))(?::(\d+))\)/,P=(a,b)=>{let c=M.exec(a);if(c){let[,a,d,e]=c;return K(b,a,"?",+d,+e)}let d=N.exec(a);if(d){if(d[2]&&0===d[2].indexOf("eval")){let a=O.exec(d[2]);a&&(d[2]=a[1],d[3]=a[2],d[4]=a[3])}let[a,c]=L(d[1]||"?",d[2]);return K(b,c,a,d[3]?+d[3]:void 0,d[4]?+d[4]:void 0)}},Q=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,R=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,S=(a,b)=>{let c=Q.exec(a);if(c){if(c[3]&&c[3].indexOf(" > eval")>-1){let a=R.exec(c[3]);a&&(c[1]=c[1]||"eval",c[3]=a[1],c[4]=a[2],c[5]="")}let a=c[3],d=c[1]||"?";return[d,a]=L(d,a),K(b,a,d,c[4]?+c[4]:void 0,c[5]?+c[5]:void 0)}},T=/\(error: (.*)\)/;function U(a,b){return a.filename===b.filename&&a.function===b.function&&a.module===b.module&&a.lineno===b.lineno&&a.colno===b.colno}function V(a,b){let c=b.start;for(;c>0&&U(a[c-1],a[c-1+b.length]);)c--;return b.start-c}function W(a,b){let c=b.start+b.length,d=c;for(;d<a.length&&U(a[d],a[d-b.length]);)d++;return d-c}function X(a,...b){return(c,d=0)=>{let e=[],f=c.split("\n"),g=Math.min(f.length,d+1e3),h=[];for(let c=d;c<g;c++){let d=f[c];if(d.length>1024)continue;let g=T.test(d)?d.replace(T,"$1"):d;if(!g.match(/\S*Error: /)){for(let c of b){let b=c(g,a);if(b){e.push(b);let a=function(a){for(let b=1;b<=10;b++){let c=a.length-2*b;if(c<0)break;let d=!0;for(let e=0;e<b;e++)if(!U(a[c+e],a[c+b+e])){d=!1;break}if(d){for(let d=0;d<b;d++)a[c+d]=a[c+b+d];return a.length=c+b,{start:c,length:b}}}}(e);if(a){for(let b=h.length-1;b>=0;b--){let c=h[b];if(c.start+c.length<=a.start)break;h.pop()}h.push(a)}break}}if(function(a,b){let c=b[0],d=a.length-(c?V(a,c):0);for(let c of b)d-=W(a,c);return d}(e,h)>=50)break}}let i=[...h].sort((a,b)=>b.start-a.start),j=i[i.length-1];if(j){let a=V(e,j);for(let b of(e.splice(j.start-a,a),i))b.start-=a}for(let a of i)!function(a,b){let c=b.start+b.length,d=W(a,b);d&&a.splice(c+d===a.length?c:b.start,d)}(e,a);h.some(a=>0===a.start&&e.length===a.length)&&function(a){let b=a.map(a=>`${a.function}|${a.filename}|${a.lineno}|${a.colno}|${a.module}`),c=0;for(let a=1;a<b.length;a++)(function(a,b,c){for(let d=0;d<a.length;d++){let e=a[(b+d)%a.length],f=a[(c+d)%a.length];if(e!==f)return e<f}return!1})(b,a,c)&&(c=a);a.push(...a.splice(0,c))}(e);if(!e.length)return[];let k=Array.from(e);return k.reverse(),k.slice(0,50).map(a=>{var b;return{...a,filename:a.filename||((b=k)[b.length-1]||{}).filename,function:a.function||"?"}})}}let Y=/^\s*[-]{4,}$/,Z=/at (?:async (?!\((?!.*\)\s+\()))?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,$=/^Promise\.(?:all|any)$/,_=/^index \d+$/,aa=(a,b)=>{let c=a.match(Z);if(c){let a,d,e,f,g;if(c[1]){let b=(e=c[1]).lastIndexOf(".");if("."===e[b-1]&&b--,b>0){a=e.slice(0,b),d=e.slice(b+1);let c=a.indexOf(".Module");c>0&&(e=e.slice(c+1),a=a.slice(0,c))}f=void 0}d&&(f=a,g=d),"<anonymous>"===d&&(g=void 0,e=void 0),void 0===e&&(g=g||"?",e=f?`${f}.${g}`:g);let h=c[2]?.startsWith("file://")?c[2].slice(7):c[2],i="native"===c[5];return h?.match(/\/[A-Z]:/)&&(h=h.slice(1)),h||!c[5]||i||(h=c[5]),$.test(e)&&_.test(h||"")&&(h="node:internal/promise"),{filename:h?decodeURI(h):void 0,module:void 0,function:e,lineno:ab(c[3]),colno:ab(c[4]),in_app:function(a,b=!1){return!(b||a&&!a.startsWith("/")&&!a.match(/^[A-Z]:/)&&!a.startsWith(".")&&!a.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==a&&!a.includes("node_modules/")}(h||"",i),platform:b}}if(a.match(Y))return{filename:a,platform:b}};function ab(a){return parseInt(a||"",10)||void 0}a.s(["createStackParser",0,X,"nodeStackLineParser",0,aa],64583),a.i(64583),a.s([],51671),a.i(51671);class ac{match(a){return A(a)}coerce(a,b){let c=this.getStack(a),d=void 0===c?b.syntheticException?.stack:void 0;return{type:this.getType(a),value:this.getMessage(a,b),stack:c??d,cause:a.cause?b.next(a.cause):void 0,synthetic:!!d}}getType(a){return a.name||a.constructor.name}getMessage(a,b){let c=a.message;return c.error&&"string"==typeof c.error.message?String(c.error.message):String(c)}getStack(a){try{let b=a.stacktrace;if("string"==typeof b&&b.length>0)return b;let c=a.stack;return"string"==typeof c&&c.length>0?c:void 0}catch{return}}}a.s(["ErrorCoercer",0,ac],10692),a.i(10692),a.s([],75368),a.i(75368);let ad=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class ae{match(a){return"string"==typeof a}coerce(a,b){let[c,d]=this.getInfos(a);return{type:c??"Error",value:d??a,stack:b.syntheticException?.stack,synthetic:!0}}getInfos(a){let b="Error",c=a,d=a.match(ad);return d&&(b=d[1],c=d[2]),[b,c]}}a.s(["StringCoercer",0,ae],57802),a.i(57802);let af=["fatal","error","warning","log","info","debug"];function ag(a,b=40){let c=Object.keys(a);if(c.sort(),!c.length)return"[object has no keys]";let d="";for(let a of c){let c=d?`${d}, ${a}`:a;if(c.length>b)break;d=c}return d}class ah{match(a){return"object"==typeof a&&null!==a}coerce(a,b){let c=this.getErrorPropertyFromObject(a);return c?b.apply(c):{type:this.getType(a),value:this.getValue(a),stack:this.getStack(a)??b.syntheticException?.stack,level:this.isSeverityLevel(a.level)?a.level:"error",synthetic:!0}}getType(a){if(B(a))return a.constructor.name;let b="name"in a?a.name:void 0;return u(b)&&!v(b)?b:"Error"}getValue(a){if("name"in a&&"string"==typeof a.name){let b=`'${a.name}' captured as exception`;return"message"in a&&"string"==typeof a.message&&(b+=` with message: '${a.message}'`),b}if("message"in a&&"string"==typeof a.message)return a.message;let b=this.getObjectClassName(a),c=ag(a);return`${b&&"Object"!==b?`'${b}'`:"Object"} captured as exception with keys: ${c}`}isSeverityLevel(a){return u(a)&&!v(a)&&af.indexOf(a)>=0}getStack(a){try{if(u(a.stacktrace)&&a.stacktrace.length>0)return a.stacktrace;return u(a.stack)&&a.stack.length>0?a.stack:void 0}catch{return}}getErrorPropertyFromObject(a){for(let b in a)if(Object.prototype.hasOwnProperty.call(a,b)){let c=a[b];if(A(c))return c}}getObjectClassName(a){try{let b=Object.getPrototypeOf(a);return b?b.constructor.name:void 0}catch(a){return}}}a.s(["ObjectCoercer",0,ah],93874),a.i(93874);class ai{match(a){return B(a)}coerce(a,b){let c=a.constructor.name;return{type:c,value:`${c} captured as exception with keys: ${ag(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["EventCoercer",0,ai],46980),a.i(46980);class aj{match(a){return null===a||"object"!=typeof a}coerce(a,b){return{type:"Error",value:`Primitive value captured as exception: ${String(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["PrimitiveCoercer",0,aj],28150),a.i(28150),a.s([],98140),a.i(98140),a.s(["ErrorCoercer",0,ac,"EventCoercer",0,ai,"ObjectCoercer",0,ah,"PrimitiveCoercer",0,aj,"StringCoercer",0,ae],54253),a.i(54253);class ak{constructor(a){this._maxSize=a,this._cache=new Map}get(a){let b=this._cache.get(a);if(void 0!==b)return this._cache.delete(a),this._cache.set(a,b),b}set(a,b){this._cache.set(a,b)}reduce(){for(;this._cache.size>=this._maxSize;){let a=this._cache.keys().next().value;a&&this._cache.delete(a)}}}a.s(["ReduceableCache",0,ak],98966),a.i(98966);function al(){if("u">typeof process){let a=process.env.POSTHOG_RELEASE_ID?.trim();if(a)return a}let a=globalThis._posthogReleaseId;return"string"==typeof a&&a.length>0?a:void 0}a.s([],97383),a.i(97383),a.s(["getInjectedReleaseId",0,al],28861),a.i(28861),a.s(["ErrorCoercer",0,ac,"ErrorPropertiesBuilder",0,H,"EventCoercer",0,ai,"ObjectCoercer",0,ah,"PrimitiveCoercer",0,aj,"ReduceableCache",0,ak,"StringCoercer",0,ae,"createStackParser",0,X,"getInjectedReleaseId",0,al,"nodeStackLineParser",0,aa],60485);var am=a.i(60485),am=am,an=a.i(2157),ao=a.i(12714),ap=a.i(50227),aq=a.i(1457);let ar=new am.ReduceableCache(25),as=new am.ReduceableCache(20);async function at(a,b=ao.open,c){let d,e={};try{d=process.cwd()}catch{}for(let b=a.length-1;b>=0;b--){var f,g;let c=a[b],h=c?.filename;!(!c||"string"!=typeof h||"number"!=typeof c.lineno||(f=h).startsWith("node:")||f.endsWith(".min.js")||f.endsWith(".min.cjs")||f.endsWith(".min.mjs")||f.startsWith("data:")||void 0!==(g=c).lineno&&g.lineno>1e4||void 0!==g.colno&&g.colno>1e3)&&((0,ap.isAbsolute)(h)||void 0!==d)&&(e[h]||(e[h]=[]),e[h].push(c.lineno))}let h=Object.keys(e);if(0==h.length)return a;let i=[];for(let a of h){let f=ax(a,d);if(void 0===f||as.get(f))continue;let g=e[a];if(!g)continue;g.sort((a,b)=>a-b);let h=function(a){if(!a.length)return[];let b=0,c=a[0];if("number"!=typeof c)return[];let d=ay(c),e=[];for(;;){if(b===a.length-1){e.push(d);break}let c=a[b+1];if("number"!=typeof c)break;c<=d[1]?d[1]=c+7:(e.push(d),d=ay(c)),b++}return e}(g);if(h.every(a=>(function(a,b){let c=ar.get(a);if(void 0===c)return!1;for(let a=b[0];a<=b[1];a++)if(void 0===c[a])return!1;return!0})(f,a)))continue;let j=function(a,b,c){let d=a.get(b);return void 0===d?(a.set(b,c),c):d}(ar,f,{});i.push(av(a,h,j,f,b,c))}return await Promise.all(i).catch(()=>{}),a&&a.length>0&&function(a,b,c){for(let d of a)if(d.filename&&void 0===d.context_line&&"number"==typeof d.lineno){let a=ax(d.filename,c),e=void 0===a?void 0:b.get(a);if(void 0===e)continue;!function(a,b,c){if(void 0===b.lineno||void 0===c)return;b.pre_context=[];for(let d=az(a);d<a;d++){let a=c[d];if(void 0===a)return void aw(b);b.pre_context.push(a)}if(void 0===c[a])return aw(b);b.context_line=c[a];let d=function(a){return a+7}(a);b.post_context=[];for(let e=a+1;e<=d;e++){let a=c[e];if(void 0===a)break;b.post_context.push(a)}}(d.lineno,d,e)}}(a,ar,d),ar.reduce(),a}async function au(a,b,c){let d,e=!1;try{d=await b(a,an.constants.O_RDONLY|an.constants.O_NONBLOCK);let f=await d.stat();if(!f.isFile())return;if(f.size>0xa00000)return void c?.debug(`Skipping source context for oversized file ${a}: ${f.size} bytes exceeds 10485760`);return e=!0,d}catch{return}finally{d&&!e&&await d.close().catch(()=>{})}}async function av(a,b,c,d,e,f){let g=await au(a,e,f);return void 0===g?void as.set(d,1):new Promise(a=>{let e,f,h=!1;function i(b){h||(h=!0,b?.destroy(),g.close().then(a,a))}try{e=g.createReadStream({autoClose:!1,start:0,end:0x9fffff})}catch{as.set(d,1),i();return}try{f=(0,aq.createInterface)({input:e})}catch{as.set(d,1),i(e);return}let j=0,k=0,l=b[0];if(void 0===l)return void i(e);let m=l[0],n=l[1];function o(){as.set(d,1),f.close(),f.removeAllListeners(),i(e)}e.on("error",o),f.on("error",o),f.on("close",()=>i(e)),f.on("line",a=>{if(!(++j<m)&&(c[j]=function(a,b){let c=a,d=c.length;if(d<=150)return c;b>d&&(b=d);let e=Math.max(b-60,0);e<5&&(e=0);let f=Math.min(e+140,d);return f>d-5&&(f=d),f===d&&(e=Math.max(f-140,0)),c=c.slice(e,f),e>0&&(c=`...${c}`),f<d&&(c+="..."),c}(a,0),j>=n)){if(k===b.length-1){f.close(),f.removeAllListeners();return}let a=b[++k];if(void 0===a){f.close(),f.removeAllListeners();return}m=a[0],n=a[1]}})})}function aw(a){delete a.pre_context,delete a.context_line,delete a.post_context}function ax(a,b){return(0,ap.isAbsolute)(a)?JSON.stringify([null,a]):void 0===b?void 0:JSON.stringify([b,a])}function ay(a){return[az(a),a+7]}function az(a){return Math.max(1,a-7)}class aA{constructor(){this.events={},this.events={}}on(a,b){return this.events[a]||(this.events[a]=[]),this.events[a].push(b),()=>{this.events[a]=this.events[a].filter(a=>a!==b)}}emit(a,b){for(let c of this.events[a]||[])c(b);for(let c of this.events["*"]||[])c(a,b)}}let aB=a=>void 0===a||!0===a.failed?void 0:a.variant??a.enabled,aC=a=>{if("string"!=typeof a)return a;try{return JSON.parse(a)}catch{return a}},aD=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","bfcid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],aE=(a,b=[])=>{let c={},d=b=>{void 0!==a[b]&&(c[b]=a[b])};return aD.forEach(d),b.forEach(d),c},aF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function aG(a,b){return"string"==typeof a&&aF.test(a)?a:b()}function aH(a,b){let c=Error(b);try{Object.defineProperty(c,"name",{value:a,writable:!0,enumerable:!0,configurable:!0})}catch{}return c}function aI(a){return a?.replace(/\/+$/,"")}function aJ(a){return a?a.split("#")[0]:a}async function aK(a,b){let c=null;for(let d=0;d<b.retryCount+1;d++){d>0&&await new Promise(a=>setTimeout(a,b.retryDelay));try{return await a()}catch(a){if(c=a,!b.retryCheck(a))throw a}}throw c}function aL(){return new Date().toISOString()}function aM(a,b){let c=setTimeout(a,b);return c?.unref&&c?.unref(),c}async function aN(a,b,c){let d;try{return await Promise.race([a,new Promise((a,e)=>{d=aM(()=>{try{c?.(),a()}catch(a){e(a)}},b)})])}finally{clearTimeout(d)}}function aO(a){return Promise.all(a.map(a=>(a??Promise.resolve()).then(a=>({status:"fulfilled",value:a}),a=>({status:"rejected",reason:a}))))}let aP=a=>{throw aH("NativeGzipValidationError",`Native gzip produced invalid output: ${a}`)},aQ=async(a,b)=>{a.size<18&&aP("too-short");let c=new Uint8Array(await a.slice(0,10).arrayBuffer());c.length>=2&&31===c[0]&&139===c[1]&&8===c[2]||aP("invalid-header");let d=new DataView(await a.slice(a.size-8).arrayBuffer());d.getUint32(0,!0)!==(a=>{let b=(()=>{if(f)return f;f=[];for(let a=0;a<256;a++){let b=a;for(let a=0;a<8;a++)b=1&b?0xedb88320^b>>>1:b>>>1;f[a]=b>>>0}return f})(),c=0xffffffff;for(let d=0;d<a.length;d++)c=b[(c^a[d])&255]^c>>>8;return(0xffffffff^c)>>>0})(b)&&aP("invalid-crc");let e=b.length>>>0;d.getUint32(4,!0)!==e&&aP("invalid-size")};async function aR(a,b=!0,c){try{let b=new TextEncoder().encode(a),c=new globalThis.CompressionStream("gzip"),d=c.writable.getWriter(),e=d.write(b).then(()=>d.close()).catch(async a=>{try{await d.abort(a)}catch{}throw a}),f=new Response(c.readable).blob(),[g]=await Promise.all([f,e]);return await aQ(g,b),g}catch(a){if(c?.rethrow)throw a;return b&&console.error("Failed to gzip compress data",a),null}}let aS="0123456789abcdef";class aT{constructor(a){this.bytes=a}static ofInner(a){if(16===a.length)return new aT(a);throw TypeError("not 128-bit length")}static fromFieldsV7(a,b,c,d){if(!Number.isInteger(a)||!Number.isInteger(b)||!Number.isInteger(c)||!Number.isInteger(d)||a<0||b<0||c<0||d<0||a>0xffffffffffff||b>4095||c>0x3fffffff||d>0xffffffff)throw RangeError("invalid field value");let e=new Uint8Array(16);return e[0]=a/0x10000000000,e[1]=a/0x100000000,e[2]=a/0x1000000,e[3]=a/65536,e[4]=a/256,e[5]=a,e[6]=112|b>>>8,e[7]=b,e[8]=128|c>>>24,e[9]=c>>>16,e[10]=c>>>8,e[11]=c,e[12]=d>>>24,e[13]=d>>>16,e[14]=d>>>8,e[15]=d,new aT(e)}static parse(a){let b;switch(a.length){case 32:b=/^[0-9a-f]{32}$/i.exec(a)?.[0];break;case 36:b=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(a)?.slice(1,6).join("");break;case 38:b=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(a)?.slice(1,6).join("");break;case 45:b=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(a)?.slice(1,6).join("")}if(b){let a=new Uint8Array(16);for(let c=0;c<16;c+=4){let d=parseInt(b.substring(2*c,2*c+8),16);a[c+0]=d>>>24,a[c+1]=d>>>16,a[c+2]=d>>>8,a[c+3]=d}return new aT(a)}throw SyntaxError("could not parse UUID string")}toString(){let a="";for(let b=0;b<this.bytes.length;b++)a+=aS.charAt(this.bytes[b]>>>4),a+=aS.charAt(15&this.bytes[b]),(3===b||5===b||7===b||9===b)&&(a+="-");return a}toHex(){let a="";for(let b=0;b<this.bytes.length;b++)a+=aS.charAt(this.bytes[b]>>>4),a+=aS.charAt(15&this.bytes[b]);return a}toJSON(){return this.toString()}getVariant(){let a=this.bytes[8]>>>4;if(a<0)throw Error("unreachable");if(a<=7)return this.bytes.every(a=>0===a)?"NIL":"VAR_0";if(a<=11)return"VAR_10";if(a<=13)return"VAR_110";if(a<=15)return this.bytes.every(a=>255===a)?"MAX":"VAR_RESERVED";throw Error("unreachable")}getVersion(){return"VAR_10"===this.getVariant()?this.bytes[6]>>>4:void 0}clone(){return new aT(this.bytes.slice(0))}equals(a){return 0===this.compareTo(a)}compareTo(a){for(let b=0;b<16;b++){let c=this.bytes[b]-a.bytes[b];if(0!==c)return Math.sign(c)}return 0}}class aU{constructor(a){this.timestamp=0,this.counter=0,this.random=a??aV()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(a,b){let c=this.generateOrAbortCore(a,b);return void 0===c&&(this.timestamp=0,c=this.generateOrAbortCore(a,b)),c}generateOrAbortCore(a,b){if(!Number.isInteger(a)||a<1||a>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(b<0||b>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(a>this.timestamp)this.timestamp=a,this.resetCounter();else{if(!(a+b>=this.timestamp))return;this.counter++,this.counter>0x3ffffffffff&&(this.timestamp++,this.resetCounter())}return aT.fromFieldsV7(this.timestamp,Math.trunc(this.counter/0x40000000),0x3fffffff&this.counter,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let a=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return a[6]=64|a[6]>>>4,a[8]=128|a[8]>>>2,aT.ofInner(a)}}let aV=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),aW=()=>aX().toString(),aX=()=>(g||(g=new aU)).generate();class aY{add(a){let b=aW(),c=++this.nextId;return this.promiseByIds[b]={id:c,promise:a},a.catch(()=>{}).finally(()=>{delete this.promiseByIds[b]}),a}async join(){let a=Object.values(this.promiseByIds).map(a=>a.promise),b=a.length;for(;b>0;)await Promise.all(a),b=(a=Object.values(this.promiseByIds).map(a=>a.promise)).length}getPromises(a=[],b=this.nextId){let c=new Set(a);return Object.values(this.promiseByIds).filter(a=>a.id<=b&&!c.has(a.promise)).map(a=>a.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}let aZ=(a,b,c)=>{function d(e,...f){b(()=>{(0,c[e])(a,...f)})}return{debug:(...a)=>{d("debug",...a)},info:(...a)=>{d("log",...a)},warn:(...a)=>{d("warn",...a)},error:(...a)=>{d("error",...a)},critical:(...b)=>{c.error(a,...b)},createLogger:d=>aZ(`${a} ${d}`,b,c)}};function a$(a,b=Date.now(),c=3e5){if("string"!=typeof a||!a)return;let d=a.trim(),e=/^\d+\s*,/.test(d)?d.slice(0,d.indexOf(",")).trim():d;if(/^\d+$/.test(e)){let a=1e3*Math.min(Number(e),c/1e3);return a>0?a:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(e))return;let f=Date.parse(/^\w{3} \w{3} /.test(e)?e+" GMT":e)-b;if(Number.isFinite(f)&&!(f<=0))return Math.min(f,c)}class a_{record(a){if("too-large"===a.kind)return;if("retry-later"!==a.kind)return void this.reset();if(!a.retryAfterMs)return;let b=this.isOpen(),c=Date.now(),d=Math.min(a.retryAfterMs,3e5);if(!b){this._installedAt=c,this._until=c+d;return}this._until=Math.max(this._until,Math.min(c+d,this._installedAt+3e5))}remainingMs(){let a=Date.now();if(a<this._installedAt-5e3)return this.reset(),0;let b=Math.min(3e5,Math.max(0,this._until-a));return 0===b&&this.reset(),b}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}}class a0 extends Error{constructor(a,b,c,d){super("HTTP error while fetching PostHog: status="+a.status+", reqByteLength="+b),this.response=a,this.reqByteLength=b,this.responseBodyDeadline=c,this.abortController=d,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return a$(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 a=aH("AbortError","Response body read timed out");this.cancelResponseBody(a),this.responseBodyTextPromise=Promise.reject(a)}else{let a,b=new Promise((a,b)=>{this.responseBodyTimer=aM(()=>{this._bodyReadTimedOut=!0;let a=aH("AbortError","Response body read timed out");b(a),this.cancelResponseBody(a)},this.responseBodyDeadline-Date.now())});try{a=Promise.resolve(this.response.text())}catch(b){a=Promise.reject(b)}this.responseBodyTextPromise=Promise.race([a,b]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(a=>JSON.parse(a))}cancelResponseBody(a){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(a),(async()=>{try{await this.response.body?.cancel()}catch{}})()}}class a1 extends Error{constructor(a){super("Network error while fetching PostHog",a instanceof Error?{cause:a}:{}),this.error=a,this.name="PostHogFetchNetworkError"}}async function a2(a){if(a instanceof a0){let b="";try{b=await a.text}catch{a.bodyReadTimedOut&&(b="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${a.message}, response body=${b}`,a)}else console.error("Error while flushing PostHog",a);return Promise.resolve()}function a3(a){return a instanceof a1}function a4(a){if(a instanceof a0)return 502===a.status||504===a.status;if(!(a instanceof a1))return!1;let b=a.error;return"ECONNREFUSED"!==(b?.code??b?.cause?.code)}function a5(a){try{if("string"!=typeof a)return a instanceof Uint8Array?a.byteLength:a.size;if("u">typeof Buffer)return Buffer.byteLength(a,"utf8");return new TextEncoder().encode(a).length}catch{return 0}}function a6(a){return"object"==typeof a&&a instanceof a0&&413===a.status}function a7(a){return a instanceof a0?408===a.status||429===a.status||a.status>=500:a3(a)}function a8(a){return null!==a&&"object"==typeof a&&!Array.isArray(a)}let a9="default";class ba{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new H([new ac,new ah,new ae,new aj],X("web:javascript",P,S))}getEvaluationRuntime(){}getFlagsResponseFormat(){return{version:2,read:a=>(a=>{if("flags"in a){let b,c=Object.fromEntries(Object.entries(a.flags??{}).map(([a,b])=>[a,aB(b)]).filter(([,a])=>void 0!==a)),d=Object.fromEntries(Object.keys(b=a.flags??{}).filter(a=>{let c=b[a];return!c.failed&&c.enabled&&c.metadata&&void 0!==c.metadata.payload}).map(a=>{let c=b[a].metadata?.payload;return[a,c?aC(c):void 0]}));return{...a,featureFlags:c,featureFlagPayloads:d}}{let b=a.featureFlags??{},c=Object.fromEntries(Object.entries(a.featureFlagPayloads||{}).map(([a,b])=>[a,aC(b)])),d=Object.fromEntries(Object.entries(b).map(([a,b])=>{var d,e;return[a,{key:a,enabled:"string"==typeof(d=b)||d,variant:"string"==typeof d?d:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:(e=c[a])?JSON.stringify(e):void 0,description:void 0}}]}));return{...a,featureFlags:b,featureFlagPayloads:c,flags:d}}})(a)}}get apiKey(){return this.projectToken}constructor(a,b={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new aY,this._events=new aA,this._isInitialized=!1;let c="string"==typeof a?a.trim():"",d="string"==typeof b.host?b.host.trim():"",e=!c;this._logger=function(a,b=a=>a()){return aZ(a,b,function(a=console){return{log:a.log.bind(a),warn:a.warn.bind(a),error:a.error.bind(a),debug:a.debug.bind(a)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),e&&this._logger.error("You must pass your PostHog project token. The client will be disabled."),this.projectToken=c,this.host=aI(d||"https://us.i.posthog.com"),this.flushAt=b.flushAt?Math.max(b.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,b.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,b.maxQueueSize??1e3),this.flushInterval=b.flushInterval??1e4,this.preloadFeatureFlags=b.preloadFeatureFlags??!0,this.defaultOptIn=b.defaultOptIn??!0,this.disableSurveys=b.disableSurveys??!1,this._retryOptions={retryCount:b.fetchRetryCount??3,retryDelay:b.fetchRetryDelay??3e3,retryCheck:a7},this.requestTimeout=b.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=b.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=b.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=b.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=b.disableGeoip??!0,this.disabled=(b.disabled??!1)||e,this.historicalMigration=b?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=b?.evaluationContexts??b?.evaluationEnvironments,b?.evaluationEnvironments&&!b?.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)||(b?.disableCompression??!1)}logMsgIfDebug(a){this.isDebug&&a()}wrap(a){return this.disabled?void this._logger.warn("The client is disabled"):this._isInitialized?a():void this._initPromise.then(()=>a())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(k.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(k.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(k.OptedOut,!0)})}on(a,b){return this._events.on(a,b)}debug(a=!0){if(this.removeDebugCallback?.(),a){let a=this.on("*",(a,b)=>this._logger.info(a,b));this.removeDebugCallback=()=>{a(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(a){let b=a.properties||{},c=this.mergeCommonEventProperties(b);var d=c;for(let a of Object.keys(b))(a.startsWith("$feature/")||"$active_feature_flags"===a)&&(d[a]=b[a]);return"$feature_flag_called"===a.event&&!1===c.$feature_flag_has_experiment&&this.isMinimalFlagCalledEventsEnabled()&&(c=aE(c)),{distinct_id:a.distinct_id,event:a.event,properties:c}}mergeCommonEventProperties(a){return{...a,...this.getCommonEventProperties()}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(a){return this.promiseQueue.add(a)}identifyStateless(a,b,c){this.wrap(()=>{let d={...this.buildPayload({distinct_id:a,event:"$identify",properties:b})};this.enqueue("identify",d,c)})}async identifyStatelessImmediate(a,b,c){let d={...this.buildPayload({distinct_id:a,event:"$identify",properties:b})};await this.sendImmediate("identify",d,c)}captureStateless(a,b,c,d){this.wrap(()=>{let e=this.buildPayload({distinct_id:a,event:b,properties:c});this.enqueue("capture",e,d)})}async captureStatelessImmediate(a,b,c,d){let e=this.buildPayload({distinct_id:a,event:b,properties:c});await this.sendImmediate("capture",e,d)}aliasStateless(a,b,c,d){this.wrap(()=>{let e=this.buildPayload({event:"$create_alias",distinct_id:b,properties:{...c||{},distinct_id:b,alias:a}});this.enqueue("alias",e,d)})}async aliasStatelessImmediate(a,b,c,d){let e=this.buildPayload({event:"$create_alias",distinct_id:b,properties:{...c||{},distinct_id:b,alias:a}});await this.sendImmediate("alias",e,d)}groupIdentifyStateless(a,b,c,d,e,f){this.wrap(()=>{let g=this.buildPayload({distinct_id:e||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{},...f||{}}});this.enqueue("capture",g,d)})}async groupIdentifyStatelessImmediate(a,b,c,d,e,f){let g=this.buildPayload({distinct_id:e||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{},...f||{}}});await this.sendImmediate("capture",g,d)}async getRemoteConfig(){await this._initPromise;let a=this.host;"https://us.i.posthog.com"===a?a="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===a&&(a="https://eu-assets.i.posthog.com");let b=`${a}/array/${this.projectToken}/config`,c={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(b,c,{type:"required",consume:a=>a.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(a=>{this._logger.error("Remote config could not be loaded",a),this._events.emit("error",a)})}async getFlags(a,b={},c={},d={},e={},f=!1){await this._initPromise;let g=this.getFlagsResponseFormat(),h=`${this.host}/flags/?v=${g.version}${f?"&config=true":""}`,i={token:this.projectToken,distinct_id:a,groups:b,person_properties:c,group_properties:d,...e};c.$device_id&&(i.$device_id=c.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(i.evaluation_contexts=this.evaluationContexts);let j=this.getEvaluationRuntime();j&&(i.evaluation_runtime=j);let k={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(i)};return this._logger.info("Flags URL",h),this.fetchWithRetry(h,k,{type:"required",consume:a=>a.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:a4},this.featureFlagsRequestTimeoutMs).then(a=>({success:!0,response:g.read(a)})).catch(a=>(this._events.emit("error",a),{success:!1,error:this.categorizeRequestError(a)}))}categorizeRequestError(a){if(a instanceof a0)return{type:"api_error",statusCode:a.status};if(a instanceof a1){let b=a.error;return b instanceof Error&&("AbortError"===b.name||"TimeoutError"===b.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagDetailStateless(a,b,c,d,e,f);if(void 0===g)return{response:void 0,requestId:void 0};let h=aB(g.response);return void 0===h&&(h=!1),{response:h,requestId:g.requestId}}async getFeatureFlagDetailStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagDetailsStateless(b,c,d,e,f,[a]);if(void 0!==g)return{response:g.flags[a],requestId:g.requestId,evaluatedAt:g.evaluatedAt}}async getFeatureFlagPayloadStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagPayloadsStateless(b,c,d,e,f,[a]);if(!g)return;let h=g[a];return void 0===h?null:h}async getFeatureFlagPayloadsStateless(a,b={},c={},d={},e,f){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(a,b,c,d,e,f)).payloads}async getFeatureFlagsStateless(a,b={},c={},d={},e,f){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(a,b,c,d,e,f)}async getFeatureFlagsAndPayloadsStateless(a,b={},c={},d={},e,f){await this._initPromise;let g=await this.getFeatureFlagDetailsStateless(a,b,c,d,e,f);return g?{flags:g.featureFlags,payloads:g.featureFlagPayloads,requestId:g.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(a,b={},c={},d={},e,f){await this._initPromise;let g={geoip_disable:e??this.disableGeoip};f&&(g.flag_keys_to_evaluate=f);let h=await this.getFlags(a,b,c,d,g);if(!h.success)return;let i=h.response;return(i.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"),i.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:i?.requestId,quotaLimited:i.quotaLimited}):i}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let a=`${this.host}/api/surveys/?token=${this.projectToken}`,b={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},c=await this.fetchWithRetry(a,b,{type:"required",consume:a=>{if(200!==a.status||!a.json){let b=`Surveys API could not be loaded: ${a.status}`,c=Error(b);return this._logger.error(c),this._events.emit("error",Error(b)),Promise.resolve(void 0)}return a.json()}}).catch(a=>{this._logger.error("Surveys API could not be loaded",a),this._events.emit("error",a)}),d=c?.surveys;return d&&this._logger.info("Surveys fetched from API: ",JSON.stringify(d)),d??[]}get props(){return this._props||(this._props=this.getPersistedProperty(k.Props)),this._props||{}}set props(a){this._props=a}async register(a){this.wrap(()=>{this.props={...this.props,...a},this.setPersistedProperty(k.Props,this.props)})}async unregister(a){this.wrap(()=>{delete this.props[a],this.setPersistedProperty(k.Props,this.props)})}processBeforeEnqueue(a){return a}async flushStorage(){}getQueueRouteKey(a){return a9}persistedQueueKeyForRoute(a){return k.Queue}getActiveQueueRoutes(){return[a9]}getRouteQueue(a){return this.getPersistedProperty(this.persistedQueueKeyForRoute(a))||[]}enqueue(a,b,c,d){this.wrap(()=>{if(this.optedOut)return void this._events.emit(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let e=this.prepareMessage(b,c);if(null===(e=this.processBeforeEnqueue(e)))return;e=this.normalizeMessage(e);let f=this.persistedQueueKeyForRoute(d??this.getQueueRouteKey(e)),g=this.getPersistedProperty(f)||[];g.length>=this.maxQueueSize&&(g.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),g.push({message:e}),this.setPersistedProperty(f,g),this._events.emit(a,e),g.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=aM(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(a,b,c,d){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(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let e=this.prepareMessage(b,c);if(null!==(e=this.processBeforeEnqueue(e))){e=this.normalizeMessage(e);try{await this.sendBatch([e],void 0,d??this.getQueueRouteKey(e))}catch(a){this._events.emit("error",a)}}}normalizeMessage(a){let{type:b,library:c,library_version:d,...e}=a,f=a8(e.properties)?e.properties:void 0;return void 0!==c&&f?.$lib===void 0&&(f={...f||{},$lib:c}),void 0!==d&&f?.$lib_version===void 0&&(f={...f||{},$lib_version:d}),f&&(e.properties=f),e.uuid=aG(e.uuid,aW),e}normalizeTimestampForWire(a){let b=a instanceof Date?a:"string"==typeof a?new Date(a):null;if(!b||Number.isNaN(b.getTime()))return a;let c=b.toISOString(),d="string"==typeof a?a.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return d&&d.length>3?c.replace(/\.\d{3}Z$/,`.${d}Z`):c}prepareMessage(a,b){let c={...a,timestamp:b?.timestamp?b?.timestamp:aL(),uuid:aG(b?.uuid,aW)};return(b?.disableGeoip??this.disableGeoip)&&(a8(c.properties)||(c.properties={}),c.properties.$geoip_disable=!0),c.distinctId&&(c.distinct_id=c.distinctId,delete c.distinctId),c}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async a=>{await a2(a)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(a,b=[]){let c=b.filter(a=>!!a),d=0;for(;;){let b=this.promiseQueue.getPromises([...c,...this.flushPromises],a);if(0===b.length)return;d>0&&this._logger.debug(`flush() re-checking ${b.length} pending promise(s) before flushing`),await Promise.all(b.map(a=>a.catch(()=>{}))),d++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(a){if(this.disabled)return Promise.resolve();if(!a&&this.pendingFlushPromise)return this.pendingFlushPromise;let b=this.flushPromise,c=this.promiseQueue.maxId,d=Promise.resolve().then(()=>{if(a)return this.waitForPendingPromises(c,[b,d])}).then(()=>aO([b])).then(()=>(this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=d,this.flushPromise=d,this.flushPromises.add(d),this.addPendingPromise(d),aO([d]).then(()=>{this.flushPromises.delete(d),this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this.flushPromise===d&&(this.flushPromise=null)}),d}getCustomHeaders(){let a=this.getCustomUserAgent(),b={};return a&&""!==a&&(b["User-Agent"]=a),b}compressPayload(a){return aR(a,this.isDebug)}getBatchEndpointPath(a){return"/batch/"}async sendBatch(a,b,c=a9){let d={api_key:this.projectToken,batch:a.map(a=>{if(!a)return a;let b=this.normalizeTimestampForWire(a.timestamp);return b===a.timestamp?a:{...a,timestamp:b}}),sent_at:aL()};this.historicalMigration&&(d.historical_migration=!0);let e=n(d),f=`${this.host}${this.getBatchEndpointPath(c)}`,g=this.disableCompression?null:await this.compressPayload(e),h={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==g&&{"Content-Encoding":"gzip"}},body:g||e};await this.fetchWithRetry(f,h,{type:"successful-write"},b)}async _flush(){let a;this.clearFlushTimer(),await this._initPromise;let b=this.getActiveQueueRoutes();if(!b.some(a=>this.getRouteQueue(a).length>0))return;let c=[];for(let d of b)try{await this._flushRoute(d,c)}catch(b){void 0===a&&(a=b)}if(void 0!==a)throw a;this._events.emit("flush",c)}async _flushRoute(a,b){let c=this.persistedQueueKeyForRoute(a),d=this.getPersistedProperty(c)||[];if(!d.length)return;let e=d.length,f=0;for(;d.length>0&&f<e;){let e=d.slice(0,this.maxBatchSize),g=e.map(a=>void 0===a.message?a.message:this.normalizeMessage(a.message)),h=async()=>{let a=this.getPersistedProperty(c)||[],b=[...e],f=a.filter(a=>{let c=a.message?.uuid,d=b.findIndex(b=>b===a||"string"==typeof c&&c.length>0&&b.message?.uuid===c);return -1===d||(b.splice(d,1),!1)});this.setPersistedProperty(c,f),d=f,this._dequeuedMessagesCount+=e.length,await this.flushStorage()},i={retryCheck:a=>!a6(a)&&a7(a)};try{await this.sendBatch(g,i,a)}catch(a){if(a6(a)&&g.length>1){this.maxBatchSize=Math.max(1,Math.floor(g.length/2)),this._logger.warn(`Received 413 when sending batch of size ${g.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw a instanceof a1||await h(),this._events.emit("error",a),a}await h(),b.push(...g),f+=g.length}}async _sendOtlpBatch({path:a,auth:b,payload:c}){let d;if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};try{d=JSON.stringify(c)}catch(b){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${a} batch; reporting it as too large`,b)),{kind:"too-large",measuredLocally:!0}}let e=a5(d);if(e>0xa00000)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${a} batch of ${e} bytes: the endpoint accepts at most 10485760`)),{kind:"too-large",measuredLocally:!0};let f="bearer"===b?`${this.host}/i/v1/${a}`:`${this.host}/i/v1/${a}?token=${encodeURIComponent(this.projectToken)}`,g=this.disableCompression?null:await this.compressPayload(d),h=g||d,i={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",..."bearer"===b&&{Authorization:`Bearer ${this.projectToken}`},...null!==g&&{"Content-Encoding":"gzip"}},body:h};try{return await this.fetchWithRetry(f,i,{type:"successful-write"},{retryCheck:a=>!a6(a)&&(!(a instanceof a0)||void 0===a.retryAfterMs)&&a7(a)}),{kind:"ok"}}catch(a){if(a6(a))return{kind:"too-large"};if(a7(a)){let b=a instanceof a0?a.retryAfterMs:void 0;return{kind:"retry-later",error:a,...void 0!==b&&{retryAfterMs:b}}}return{kind:"fatal",error:a}}}async _sendLogsBatch(a){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:a})}async _sendMetricsBatch(a){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:a})}async _sendTracesBatch(a){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:a})}async fetchWithRetry(a,b,c,d,e){let f=a5(b.body?b.body:""),g={...this._retryOptions,...d},h=0;return await aK(async()=>{let d,g,i;h++;let j=new AbortController,k=e??this.requestTimeout,l=Date.now()+k,m=new Promise((a,b)=>{d=aM(()=>{let a=aH("AbortError",`Request timed out after ${k}ms`);b(a),j.abort(a)},k)}),n=!1,o=()=>i??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let d;try{d=this.fetch(a,{signal:j.signal,...b})}catch(a){throw new a1(a)}d.then(a=>{j.signal.aborted&&!n&&Promise.resolve(a.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([d,m]),n=!0}catch(a){throw new a1(a)}let e="no-cors"===b.mode,h="successful-write"===c.type?300:400;if(!e&&(g.status<200||g.status>=h))throw new a0(g,f,l,j);if("successful-write"===c.type){try{await Promise.race([o(),m])}catch{}return}try{return await Promise.race([c.consume(g),m])}catch(a){if(j.signal.aborted)throw new a1(a);throw a}}finally{clearTimeout(d),j.signal.aborted&&g&&o()}},{...g,retryCheck:a=>{let b=g.retryCheck(a);return b&&h<=g.retryCount&&a instanceof a0&&a.cancelResponseBody(),b}})}async _shutdown(a=3e4){await this._initPromise;let b=!1;if(this.clearFlushTimer(),!this.disabled)return aN((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(a=>this.getRouteQueue(a).length>0);){let a=this._dequeuedMessagesCount;if(await this.flush(),b)break;if(this._dequeuedMessagesCount===a){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(a){if(!("object"==typeof a&&(a instanceof a0||a3(a))))throw a;await a2(a)}})(),a,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:a}),b=!0})}async shutdown(a=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(a).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}let bb="[Circular]",bc="[Truncated]",bd="[Unserializable]";function be(a){let b="";for(let c=0;c<a.length;c++){let d=a.charCodeAt(c);if(d>=55296&&d<=56319){let d=a.charCodeAt(c+1);d>=56320&&d<=57343?(b+=a[c]+a[c+1],c++):b+="�"}else b+=d>=56320&&d<=57343?"�":a[c]}return b}function bf(a,b){if(!b)return a;let c=[];try{c=Object.keys(b)}catch{c=[]}for(let d of c){let c;try{c=b[d]}catch{c=bd}Object.defineProperty(a,d,{value:c,enumerable:!0,writable:!0,configurable:!0})}return a}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let bg=Object.prototype.propertyIsEnumerable;function bh(a,b){try{return bi(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function bi(a,b,c,d){let e=[];for(let f in a)if(bg.call(a,f)){if(!f){b?.debug("Dropping an attribute with an empty key");continue}if(e.length>=1e3||c.remainingNodes<=0){b?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let g=a[f];if(w(g)||t(g))continue;e.push({key:be(f),value:function a(b,c,d,e){if(d.remainingNodes<=0)return{stringValue:bc};if(d.remainingNodes--,z(b))return{boolValue:b};if("bigint"==typeof b){let a,d;return a=b.toString(),b>=(d=BigInt("9223372036854775808"))||b<-d?(c?.debug(`Attribute ${a} is outside the int64 range; encoding it as a string`),{stringValue:a}):{intValue:a}}if("number"==typeof b){if(!Number.isFinite(b))return{stringValue:String(b)};if(Number.isInteger(b)){if(Number.isSafeInteger(b))return{intValue:String(b)};if("u"<typeof BigInt)return{stringValue:String(b)};let a=BigInt(b).toString();return b>=0x8000000000000000||b<-0x8000000000000000?(c?.debug(`Attribute ${a} is outside the int64 range; encoding it as a string`),{stringValue:a}):{intValue:a}}return{doubleValue:b}}if("string"==typeof b)return{stringValue:be(b)};if("function"==typeof b)return{stringValue:"[Function]"};if("symbol"==typeof b)return{stringValue:String(b)};if("object"==typeof b&&null!==b){if(d.ancestors.has(b))return{stringValue:bb};if(e>=20)return{stringValue:bc};if(b instanceof Date){let a=Number.isFinite(b.getTime())?b.toISOString():String(b);return{stringValue:"string"==typeof a?be(a):String(a)}}d.ancestors.add(b);try{try{let f=b.toJSON;if("function"==typeof f)return a(f.call(b),c,d,e+1)}catch{}if(s(b))return{arrayValue:{values:function(b,c,d,e){let f=[],g=Math.min(b.length,1e3),h=0;for(;h<g&&d.remainingNodes>0;h++)try{let g=h in b?b[h]:void 0;if(x(g))continue;f.push(a(g,c,d,e))}catch{f.push({stringValue:bd})}return b.length>h&&f.push({stringValue:bc}),f}(b,c,d,e+1)}};return{kvlistValue:{values:bi(b,c,d,e+1)}}}finally{d.ancestors.delete(b)}}return{stringValue:be(String(b))}}(g,b,c,d)})}catch{e.push({key:be(f),value:{stringValue:bd}})}}return e}function bj(a,b,c){return{...bf({},a.resourceAttributes),"service.name":a.serviceName||"unknown_service",...a.environment&&{"deployment.environment":a.environment},...a.serviceVersion&&{"service.version":a.serviceVersion},"telemetry.sdk.name":b,"telemetry.sdk.version":c}}let bk=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function bl(a,b){let c=bf({},a),d={};for(let a of bk)Object.prototype.hasOwnProperty.call(c,a)&&(d[a]=c[a],delete c[a]);return[...bh(c,b),...bh(d,b)]}let bm={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"},bn={text:"INFO",number:9},bo={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:bn,warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}};class bp{constructor(a){this._onFire=a,this._firesAt=0}get pending(){return!!this._timer}arm(a){this.clear(),this._firesAt=Date.now()+a,this._timer=aM(()=>{this._timer=void 0,this._onFire()},a)}armNoEarlierThan(a){this._timer&&Date.now()+a<=this._firesAt||this.arm(a)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}function bq(){return .75+.25*Math.random()*2}function br(a,b,c,d){let e=Math.min(Math.max(0,b-1),6),f=a*2**e;return Math.round((void 0===d?f:Math.min(f,Math.max(d,a)))*c)}class bs{constructor(a,b,c,d,e,f=()=>Promise.resolve(),g,h=()=>!1){this._instance=a,this._config=b,this._logger=c,this._getContext=d,this._onReady=e,this._waitForStoragePersist=f,this._scopeName=g,this._isConsentWithdrawn=h,this._flushTimer=new bp(()=>this._flushInBackground()),this._flushPromise=null,this._evictedSinceAdvance=0,this._queueGeneration=0,this._backgroundFlushPromise=null,this._retryAfter=new a_,this._consecutiveFlushFailures=0,this._flushJitter=1,this._intervalWindowStart=0,this._intervalLogCount=0,this._droppedWarned=!1,this._maxBufferSize=b.maxBufferSize,this._maxQueueSize=Math.max(b.maxQueueSize??b.maxBufferSize,b.maxBufferSize),this._flushIntervalMs=b.flushIntervalMs,this._maxBatchRecordsPerPost=b.maxBatchRecordsPerPost,this._rateCapWindowMs=b.rateCapWindowMs,this._maxLogsPerInterval=b.maxLogsPerInterval}clearQueue(){this._queueGeneration++,this._instance.setPersistedProperty(k.LogsQueue,[])}get throttled(){return this._retryAfter.isOpen()}reset(){this._flushTimer.clear(),this._intervalWindowStart=0,this._intervalLogCount=0,this._droppedWarned=!1,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter.reset(),this._maxBatchRecordsPerPost=this._config.maxBatchRecordsPerPost}onReconnect(){if(this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter.isOpen()){this._hasQueuedRecords()&&this._armFlushTimer();return}this._flushInBackground()}captureLog(a,b){if(this._instance.isDisabled||this._instance.optedOut||!a?.body)return;let c=this._runBeforeSend(a);if(null===c)return;if(!c.body)return void this._logger.info("Log was rejected in beforeSend function");if(!this._checkRateLimit())return;let d={record:function(a,b,c,d){let{text:e,number:f}=bo[a.level||"info"]||bn,g=function(a=Date.now()){return String(a)+"000000"}(y(d)?d:void 0),h={};b.distinctId&&(h.posthogDistinctId=b.distinctId),b.sessionId&&(h.sessionId=b.sessionId),b.windowId&&(h["window.id"]=b.windowId),x(b.sessionStartTimestamp)||(h.sessionStartTimestamp=String(b.sessionStartTimestamp)),x(b.lastActivityTimestamp)||(h.lastActivityTimestamp=String(b.lastActivityTimestamp)),b.currentUrl&&(h["url.full"]=b.currentUrl),b.screenName&&(h["screen.name"]=b.screenName),b.appState&&(h["app.state"]=b.appState),b.activeFeatureFlags&&b.activeFeatureFlags.length>0&&(h.feature_flags=b.activeFeatureFlags);let i={...h},j=a.attributes;if(j){let a=[];try{a=Object.keys(j)}catch{a=[]}for(let b of a){let a;try{a=j[b]}catch{a=bd}Object.defineProperty(i,b,{value:a,enumerable:!0,writable:!0,configurable:!0})}}let k={timeUnixNano:g,observedTimeUnixNano:g,severityNumber:f,severityText:e,body:{stringValue:function(a){try{return be(String(a))}catch{return bd}}(a.body)},attributes:bh(i,c)};return a.trace_id&&(k.traceId=a.trace_id),a.span_id&&(k.spanId=a.span_id),t(a.trace_flags)||(k.flags=a.trace_flags),k}(c,b?.context??this._getContext(),this._logger,b?.occurredAtMs)};this._onReady(()=>this._enqueue(d))}_runBeforeSend(a){let b=this._config.beforeSend;if(!b)return a;let c=s(b)?b:[b],d=a;for(let a of c)try{let b=a(d);if(!b)return this._logger.info("Log was rejected in beforeSend function"),null;d=b}catch(a){return this._logger.error("Error in beforeSend function for log:",a),null}return d}_checkRateLimit(){if(void 0===this._maxLogsPerInterval)return!0;let a=Date.now(),b=a-this._intervalWindowStart;return((b>=this._rateCapWindowMs||b<0)&&(this._intervalWindowStart=a,this._intervalLogCount=0,this._droppedWarned=!1),this._intervalLogCount>=this._maxLogsPerInterval)?(this._droppedWarned||(this._logger.warn(`captureLog dropping logs: exceeded ${this._maxLogsPerInterval} logs per ${this._rateCapWindowMs}ms`),this._droppedWarned=!0),!1):(this._intervalLogCount++,!0)}async flush(){if(!this._instance.isDisabled)return this._flushPromise||(this._flushPromise=this._flushInner().finally(()=>{this._flushPromise=null})),this._flushPromise}async _flushInner(){if(this._flushTimer.clear(),this._discardQueueIfConsentWithdrawn())return;let a=this._instance.getPersistedProperty(k.LogsQueue)??[];if(0===a.length)return;let b=a.length,c=0;for(;a.length>0&&c<b;){var d,e,f,g;if(this._discardQueueIfConsentWithdrawn())return;let b=this._queueGeneration;this._evictedSinceAdvance=0;let h=Math.min(a.length,this._maxBatchRecordsPerPost),i=a.slice(0,h),j=(d=i.map(a=>a.record),e=this._buildResourceAttributes(),f=this._scopeName??this._instance.getLibraryId(),g=this._instance.getLibraryVersion(),{resourceLogs:[{resource:{attributes:bl(e)},scopeLogs:[{scope:{name:f,version:g},logRecords:d}]}]}),l=await this._instance._sendLogsBatch(j);if(this._queueGeneration!==b)return;if("too-large"===l.kind&&i.length>1){this._maxBatchRecordsPerPost=Math.max(1,Math.floor(i.length/2)),this._logger.warn(`Logs batch of size ${i.length} was too large for the ingestion endpoint, reducing batch size to ${this._maxBatchRecordsPerPost}`);continue}if(this._retryAfter.record(l),this._flushTimer.pending&&this._flushTimer.arm(Math.max(this._flushIntervalMs,this._retryAfter.remainingMs())),"retry-later"===l.kind||("too-large"===l.kind?this._logger.warn("Dropping a single log record with batch size 1 — the record is larger than the server cap and cannot be split further."):"ok"===l.kind&&this._maxBatchRecordsPerPost<this._config.maxBatchRecordsPerPost&&(this._maxBatchRecordsPerPost=Math.min(this._config.maxBatchRecordsPerPost,this._maxBatchRecordsPerPost+1)),await this._persistQueueAdvance(i.length),a=this._instance.getPersistedProperty(k.LogsQueue)??[],c+=i.length,"fatal"===l.kind))throw l.error}}_discardQueueIfConsentWithdrawn(){return!!this._isConsentWithdrawn()&&(this._hasQueuedRecords()&&this.clearQueue(),!0)}async _persistQueueAdvance(a){let b=Math.max(0,a-this._evictedSinceAdvance),c=this._instance.getPersistedProperty(k.LogsQueue)??[];this._instance.setPersistedProperty(k.LogsQueue,c.slice(b)),await this._waitForStoragePersist()}_buildResourceAttributes(){var a;return a=this._config,bj(a,this._instance.getLibraryId(),this._instance.getLibraryVersion())}_enqueue(a){if(this._instance.optedOut)return;let b=this._instance.getPersistedProperty(k.LogsQueue)??[];(b.length>=this._maxQueueSize&&(b.shift(),this._evictedSinceAdvance++,this._logger.info("Logs queue is full, dropping oldest record.")),b.push(a),this._instance.setPersistedProperty(k.LogsQueue,b),b.length>=this._maxBufferSize&&!this._retryAfter.isOpen())?this._flushInBackground():this._armFlushTimer()}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(Math.max(this._flushIntervalMs,this._retryAfter.remainingMs()))}_nextFlushDelay(){return Math.max(br(this._flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}_hasQueuedRecords(){let a=this._instance.getPersistedProperty(k.LogsQueue);return!!a&&a.length>0}async shutdown(a){this._flushTimer.clear();let b=this.flush().catch(()=>{});void 0===a?await b:await aN(b,a)}async flushWithTimeout(a){let b=this.flush();await aN(b,a,()=>{b.catch(()=>{})})}flushInBackground(){if(this._backgroundFlushPromise)return this._backgroundFlushPromise;let a=this.flush().then(()=>{this._consecutiveFlushFailures=0,this._flushJitter=1},a=>{this._consecutiveFlushFailures++,this._flushJitter=bq(),this._logger.error("PostHog logs flush failed:",a)}).finally(()=>{this._backgroundFlushPromise===a&&(this._backgroundFlushPromise=null),!this._instance.isDisabled&&this._hasQueuedRecords()&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())});return this._backgroundFlushPromise=a,a}_flushInBackground(){this.flushInBackground()}}let bt="0000000000000000",bu=bt+bt,bv=/^[0-9a-f]+$/;function bw(a){let b=function(a){let b="";for(let c=0;c<a.length;c++)b+=a[c].toString(16).padStart(2,"0");return b}(function(a){let b=new Uint8Array(a),c=globalThis.crypto;if(c&&"function"==typeof c.getRandomValues)try{return c.getRandomValues(b),b}catch{}for(let c=0;c<a;c++)b[c]=Math.floor(256*Math.random());return b}(a));return/[^0]/.test(b)?b:b.slice(0,-1)+"1"}function bx(a,b,c){return"string"==typeof a&&a.length===b&&a!==c&&bv.test(a)}let by=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function bz(a){let b=bA(a);return b&&{traceId:b.traceId,spanId:b.spanId,flags:1&parseInt(b.flags,16)?bC:bD}}function bA(a){if("string"!=typeof a)return;let b=by.exec(a.trim());if(!b)return;let[,c,d,e,f,g]=b;if("ff"!==c&&("00"!==c||!g)&&bx(d,32,bu)&&bx(e,16,bt))return{version:c,traceId:d,spanId:e,flags:f}}function bB(a){return Array.isArray(a)&&1===a.length?a[0]:a}let bC="01",bD="00";function bE(a){if("string"!=typeof a)return;let b=a.trim();if(!b||/[^\x20-\x7e\t]/.test(b))return;let c=b.split(",");if(!(c.length>32)){for(let a of c)if(a.trim()&&!a.includes("="))return;return b.length<=512?b:function(a){let b=[...a],c=()=>b.reduce((a,b)=>a+b.length,0)+b.length-1;for(let a=b.length-1;a>=0&&c()>512;a--)b[a].length>128&&b.splice(a,1);for(;b.length&&c()>512;)b.pop();return b.length?b.join(","):void 0}(c)}}let bF=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function bG(a){return String(a)+"000000"}function bH(a,b,c,d){let e="";return d&&(e=Object.keys(d).sort().map(a=>`${JSON.stringify(a)}:${JSON.stringify(d[a])}`).join(",")),`${a}\0${b}\0${c??""}\0${e}`}class bI{constructor(a,b,c){this._instance=a,this._config=b,this._logger=c,this._series=new Map,this._flushTimer=new bp(()=>this.flush().catch(a=>{this._logger.error("Metrics flush failed:",a)})),this._flushPromise=null,this._queuedFlush=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._boundsByHistogram=new Map,this._boundsConflictWarned=new Set,this._boundsCapWarned=!1,this._retryAfter=new a_,this._consecutiveFlushFailures=0,this._flushJitter=1,this._generation=0}count(a,b=1,c){this._capture({name:a,type:"count",value:b,unit:c?.unit,attributes:c?.attributes})}gauge(a,b,c){this._capture({name:a,type:"gauge",value:b,unit:c?.unit,attributes:c?.attributes})}histogram(a,b,c){this._capture({name:a,type:"histogram",value:b,unit:c?.unit,attributes:c?.attributes,bounds:s(c?.bounds)?c.bounds.slice():c?.bounds})}flush(){let a=this._flushPromise,b=(async()=>{a&&await a.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===b&&(this._flushPromise=null)});return this._flushPromise=b,b}flushCoalesced(){return this._isBackingOff()?this._flushPromise??Promise.resolve():(this._queuedFlush||(this._queuedFlush=(this._flushPromise??Promise.resolve()).catch(()=>{}).then(()=>(this._queuedFlush=null,this._isBackingOff()?void 0:this.flush()))),this._queuedFlush)}_isBackingOff(){return this._consecutiveFlushFailures>0||this._retryAfter.remainingMs()>0}drainWindow(){if(0===this._series.size)return null;let a=this._series;return this._startWindow(),this._buildPayload(a)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=1,this._flushTimer.clear(),this._flushPromise=null,this._queuedFlush=null,this._startWindow(),this._boundsByHistogram=new Map,this._boundsCapWarned=!1}_startWindow(){this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._boundsConflictWarned=new Set}_capture(a){var b;let c,d,e;if(this._instance.isDisabled||this._instance.optedOut)return;let f=this._runBeforeSend(a);if(null===f)return;if(!f.name||"string"!=typeof f.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof f.value||!Number.isFinite(f.value))return void this._logger.warn(`Dropping metric '${f.name}': value must be a finite number`);if("count"!==f.type&&"gauge"!==f.type&&"histogram"!==f.type)return void this._logger.warn(`Dropping metric '${f.name}': unknown type '${String(f.type)}'`);if("count"===f.type&&f.value<0)return void this._logger.warn(`Dropping count '${f.name}': counters are monotonic, value must be >= 0`);try{c=f.attributes?{...f.attributes}:void 0,d=bH(f.type,f.name,f.unit,c)}catch(a){this._logger.warn(`Dropping metric '${f.name}': attributes could not be serialized`,a);return}let g=this._series.get(d);if(!g&&!this._admitNewSeries()||"histogram"===f.type&&!(e=this._histogramBounds(f.name,f.unit,f.bounds)))return;g||(g={name:f.name,type:f.type,unit:f.unit,attributes:c,windowStartMs:Date.now(),hist:e&&{bounds:b=e,count:0,sum:0,min:1/0,max:-1/0,bucketCounts:Array(b.length+1).fill(0)}},this._series.set(d,g));let h=this._typeByName.get(f.name);void 0===h?this._typeByName.set(f.name,f.type):h===f.type||this._typeCollisionWarned.has(f.name)||(this._typeCollisionWarned.add(f.name),this._logger.warn(`Metric name '${f.name}' is already used as a ${h}; recording it as a ${f.type} too will blend both series in charts. Use a distinct name.`)),this._fold(g,f.value);let i=this._activeTraceContext();i&&(g.exemplar={...i,value:f.value,timeMs:Date.now()}),this._armFlushTimer()}_activeTraceContext(){try{let a=bz(this._instance.getActiveSpan?.()?.traceparent());if(a&&a.flags===bC)return{traceId:a.traceId,spanId:a.spanId}}catch{}}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush||(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_histogramBounds(a,b,c){if(void 0!==c&&!function(a){if(!s(a)||0===a.length)return!1;for(let b=0;b<a.length;b++)if(!Number.isFinite(a[b])||b>0&&a[b]<=a[b-1])return!1;return!0}(c))return void this._logger.warn(`Dropping histogram '${a}': bounds must be a non-empty array of finite, strictly increasing numbers`);let d=bH("histogram",a,b,void 0),e=this._boundsByHistogram.get(d);if(e)return this._warnOnBoundsConflict(a,d,e,c),e;if(this._boundsByHistogram.size>=this._config.maxSeriesPerFlush){if(this._boundsCapWarned||(this._boundsCapWarned=!0,this._logger.warn(`Histogram bounds limit reached (${this._config.maxSeriesPerFlush} distinct histograms); new histograms that pass custom bounds are dropped. Reduce histogram name cardinality.`)),c&&!bJ(c,bF))return;return bF}let f=c?c.slice():bF;return this._boundsByHistogram.set(d,f),f}_warnOnBoundsConflict(a,b,c,d){bJ(c,d??bF)||this._boundsConflictWarned.has(b)||(this._boundsConflictWarned.add(b),this._logger.warn(`Histogram '${a}' already uses the bounds [${c.join(", ")}]; samples that pass different bounds are recorded in those buckets.`))}_fold(a,b){switch(a.type){case"count":a.total=(a.total??0)+b;break;case"gauge":a.last=b;break;case"histogram":{let c=a.hist;c.count+=1,c.sum+=b,c.min=Math.min(c.min,b),c.max=Math.max(c.max,b),c.bucketCounts[function(a,b){for(let c=0;c<b.length;c++)if(a<=b[c])return c;return b.length}(b,c.bounds)]+=1}}}_runBeforeSend(a){let b=this._config.beforeSend;if(!b)return a;let c=s(b)?b:[b],d=a;for(let a of c)try{let b=a(d);if(!b)return this._logger.info("Metric was rejected in beforeSend function"),null;d=b}catch(a){return this._logger.error("Error in beforeSend function for metric:",a),null}return d}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(br(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),0===this._series.size)return;let a=this._series;this._startWindow();let b=this._generation,c=await this._instance._sendMetricsBatch(this._buildPayload(a));if(b===this._generation)switch(this._retryAfter.record(c),"retry-later"===c.kind?(this._consecutiveFlushFailures++,this._flushJitter=bq()):(this._consecutiveFlushFailures=0,this._flushJitter=1),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),c.kind){case"ok":return;case"retry-later":this._mergeWindowBack(a),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:",c.error);return}}_buildPayload(a){var b,c,d,e;return b=this._buildMetrics(a),c=bj(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),d=this._instance.getLibraryId(),e=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:bl(c)},scopeMetrics:[{scope:{name:d,version:e},metrics:b}]}]}}_buildMetrics(a){let b=bG(Date.now()),c=new Map;for(let e of a.values()){var d;let a=bH(e.type,e.name,e.unit,void 0),f=c.get(a);f||(f={name:e.name,...e.unit&&{unit:e.unit}},"count"===e.type?f.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===e.type?f.gauge={dataPoints:[]}:f.histogram={aggregationTemporality:1,dataPoints:[]},c.set(a,f));let g=bh(e.attributes??{},this._logger),h=bG(e.windowStartMs),i=(d=e.exemplar)?{exemplars:[{filteredAttributes:[],timeUnixNano:bG(d.timeMs),asDouble:d.value,traceId:d.traceId,spanId:d.spanId}]}:{};if("count"===e.type){let a={attributes:g,startTimeUnixNano:h,timeUnixNano:b,asDouble:e.total??0,...i};f.sum.dataPoints.push(a)}else if("gauge"===e.type){let a={attributes:g,timeUnixNano:b,asDouble:e.last??0,...i};f.gauge.dataPoints.push(a)}else{let a=e.hist,c={attributes:g,startTimeUnixNano:h,timeUnixNano:b,count:a.count,sum:a.sum,min:a.min,max:a.max,bucketCounts:a.bucketCounts,explicitBounds:a.bounds,...i};f.histogram.dataPoints.push(c)}}return Array.from(c.values())}_mergeWindowBack(a){for(let[b,c]of a){let a=this._series.get(b);if(!a){this._admitNewSeries()&&this._series.set(b,c);continue}switch(a.windowStartMs=Math.min(a.windowStartMs,c.windowStartMs),a.exemplar=a.exemplar??c.exemplar,a.type){case"count":a.total=(a.total??0)+(c.total??0);break;case"gauge":break;case"histogram":{let b=a.hist,d=c.hist;b.count+=d.count,b.sum+=d.sum,b.min=Math.min(b.min,d.min),b.max=Math.max(b.max,d.max);for(let a=0;a<b.bucketCounts.length;a++)b.bucketCounts[a]+=d.bucketCounts[a]}}}}}function bJ(a,b){if(a===b)return!0;if(a.length!==b.length)return!1;for(let c=0;c<a.length;c++)if(a[c]!==b[c])return!1;return!0}let bK="unknown";function bL(a,b,c,d){return"string"==typeof a&&a.trim()?a.length>c?a.slice(0,c):a:(d?.debug(`${b} must be a non-empty string; using "${bK}"`),bK)}function bM(a){if(null==a)return;let b=a;if(a instanceof Date)try{b=a.getTime()}catch{return}if("number"==typeof b&&Number.isFinite(b)&&!(b<0)&&!(b>0x8637bd05af6))return b}function bN(a,b,c,d){let e=bM(a);return void 0===e?(void 0!==a&&d?.debug(`Span ${c} is out of range or not a valid time; using the derived time`),b):e}function bO(){let a=globalThis.performance;return"function"==typeof a?.now?a.now():void 0}class bP{constructor(a,b,c){for(let d of(this._onEnd=b,this._logger=c,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=a.traceId,this._spanId=a.spanId,this._parentSpanId=a.parentSpanId,this._traceState=a.traceState,this._traceFlags=a.traceFlags??bC,this._parentIsRemote=a.parentIsRemote??!1,this._name=a.name,this._kind=a.kind,this._autoKeys=new Set(a.autoAttributeKeys),this._maxAttributes=a.maxAttributes,this._maxEvents=a.maxEvents,this._maxAttributesPerEvent=a.maxAttributesPerEvent,this._maxAttributeValueLength=a.maxAttributeValueLength,this._attributes=Object.create(null),Object.keys(a.attributes)))this._writeAttribute(d,a.attributes[d]);this._startMono=a.backdated?void 0:bO(),this._startTime=a.clockAnchor&&void 0!==this._startMono?a.clockAnchor.wall+(this._startMono-a.clockAnchor.mono):a.startTime,void 0!==this._startMono&&(this._clockAnchor=a.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(void 0!==this._startMono){let a=bO();if(void 0!==a)return this._startTime+Math.max(0,a-this._startMono)}return Date.now()}_mutable(a){return!this._ended||(this._logger?.debug(`Ignoring ${a} on a span that has already ended`),!1)}_writeAttribute(a,b){if(x(b)){a in this._attributes&&!this._autoKeys.has(a)&&this._userAttributeCount--,delete this._attributes[a];return}if(!this._autoKeys.has(a)&&!(a in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[a]=bY(b,this._maxAttributeValueLength)}setAttribute(a,b){return this._mutable("setAttribute")&&this._writeAttribute(a,b),this}setAttributes(a){if(this._mutable("setAttributes")){let b=bf({},a);for(let a of Object.keys(b))this._writeAttribute(a,b[a])}return this}addEvent(a,b,c){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let d=b&&bZ(b,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:bL(a,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:bN(c,this._now(),"event timestamp",this._logger),...d&&{attributes:d.attributes,...d.dropped&&{droppedAttributesCount:d.dropped}}})}return this}setStatus(a,b){if(this._mutable("setStatus")){if("ok"!==a&&"error"!==a)return this._logger?.debug(`Ignoring unknown span status "${String(a)}"; expected "ok" or "error"`),this;this._status={code:a,...b&&{message:bX(b,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(a){if(!this._mutable("recordException"))return this;let{type:b,message:c,stack:d}=b_(a);return this.addEvent(bQ,{"exception.type":b,"exception.message":c,...d&&{"exception.stacktrace":d}}),this.setStatus("error",c)}updateName(a){return this._mutable("updateName")&&(this._name=bL(a,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return function(a,b,c=bC){return`00-${a}-${b}-${c}`}(this._traceId,this._spanId,this._traceFlags)}get traceId(){return this._traceId}get spanId(){return this._spanId}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(a){var b;if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let c=bN(a,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:c<(b=this._startTime)?b:c,...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}}let bQ="exception";function bR(a){return"number"!=typeof a||!Number.isFinite(a)||a<=0?0:Math.min(Math.floor(a),0xffffffff)}class bS{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}get traceId(){return null}get spanId(){return null}tracestate(){return null}end(){}}let bT=new bS;class bU extends bS{constructor(a,b){super(),this._traceparent=a,this._tracestate=b}traceparent(){return this._traceparent}get traceId(){return this._traceparent.split("-")[1]??null}get spanId(){return this._traceparent.split("-")[2]??null}tracestate(){return this._tracestate??null}}function bV(a,b){var c;let d=bB(a?.parent)??b,e=bA(c="string"==typeof d||null==d?d:bW(d,"traceparent"))&&c.trim();return e?new bU(e,bE("string"==typeof d||null==d?a?.tracestate:bW(d,"tracestate"))):bT}function bW(a,b){try{let c=a[b];return"function"==typeof c?c.call(a):void 0}catch{return}}function bX(a,b){return a.length>b?a.slice(0,b):a}function bY(a,b){return function a(b,c,d,e){if(null===b||"object"!=typeof b)return x(b)||d.remainingNodes<=0?b:(d.remainingNodes--,"string"==typeof b?bX(b,c):b);if(d.ancestors.has(b))return bb;if(d.remainingNodes<=0||e>=20)return b;d.remainingNodes--,d.ancestors.add(b);try{if(b instanceof Date)return b;let f=function(a){try{let b=a.toJSON;if("function"==typeof b)return{selfDescribed:!0,value:b.call(a)}}catch{}return{selfDescribed:!1}}(b);if(f.selfDescribed)return x(f.value)?String(f.value):a(f.value,c,d,e+1);if(s(b)){let f=Math.min(b.length,1e3),g=[];for(let h=0;h<f;h++)try{g.push(a(b[h],c,d,e+1))}catch{g.push(bd)}return b.length>f&&(g.length=b.length),g}let g={},h=0;for(let f of Object.keys(b)){let i;if(h>=1e3)break;try{i=a(b[f],c,d,e+1)}catch{i=bd}f&&!x(i)&&h++,Object.defineProperty(g,f,{value:i,enumerable:!0,writable:!0,configurable:!0})}return g}catch{return b}finally{d.ancestors.delete(b)}}(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}function bZ(a,b,c){let d;try{d=Object.keys(a)}catch{return{attributes:{},dropped:0}}let e={},f=0,g=0;for(let h of d){let d;if(f>=b){g++;continue}try{d=bY(a[h],c)}catch{d=bd}x(d)||(f++,Object.defineProperty(e,h,{value:d,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:e,dropped:g}}function b$(a,b,c){return b===bT?c(b):a.with(b,()=>c(b))}function b_(a){try{let b=function(a){try{let b=a.stack;return"string"==typeof b&&b?{stack:b}:{}}catch{return{}}}(a);if(A(a))return{type:a.name||"Error",message:a.message||"",...b};if("string"==typeof a)return{type:"string",message:a};if(a&&"object"==typeof a&&"string"==typeof a.message)return{type:"string"==typeof a.name?a.name:"Object",message:a.message,...b};return{type:typeof a,message:String(a)}}catch{return{type:typeof a,message:""}}}let b0={internal:1,server:2,client:3,producer:4,consumer:5},b1={ok:1,error:2};function b2(a){if("string"==typeof a)return be(a);try{return be(String(a))}catch{return bd}}function b3(a){let b=Math.floor(a),c=Math.round((a-b)*1e6);return c>=1e6&&(b+=1,c=0),String(b)+String(c).padStart(6,"0")}function b4(){return bO()??Date.now()}function b5(a){try{return a instanceof bP}catch{return!1}}function b6(a,b){let c=bz(a);if(c)return{traceId:c.traceId,parentSpanId:c.spanId,traceState:bE(b),traceFlags:c.flags,isRemote:!0}}function b7(a,b,c){a[b]!==c&&(a[b]=c)}class b8{constructor(a,b,c,d,e,f){this._instance=a,this._config=b,this._logger=c,this._getContext=d,this._contextManager=e,this._onSpanQueued=f,this._queue=[],this._flushTimer=new bp(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter=new a_,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=b.maxExportBatchSize}startSpan(a,b){var c,d;let e;if(this._instance.isDisabled||this._instance.optedOut)return bV(b,this._contextManager.active());let f=bB(b?.parent);if(f&&"string"!=typeof f&&!b5(f)){if(function(a){try{return"function"==typeof a.traceparent}catch{return!1}}(f))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),bV(b,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let g=this._resolveParent(f,b);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached — spans are being started and never ended`),bV(b,this._contextManager.active());let h=Date.now(),i=(c=b?.startTime,d=this._logger,void 0===(e=bM(c))?(void 0!==c&&d?.debug("Span startTime is out of range or not a valid time; using the current time"),h):(h-e>864e5?d?.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"):e>h&&d?.debug("Span startTime is in the future; the span may export with a zero duration"),e)),j=bw(8);this._liveSpans.set(j,b4());let k=this._autoContextAttributes();return new bP({traceId:g?.traceId??bw(16),spanId:j,parentSpanId:g?.parentSpanId,traceState:g?.traceState,traceFlags:g?.traceFlags,parentIsRemote:g?.isRemote,name:bL(a,"Span name",this._config.maxAttributeValueLength,this._logger),kind:b?.kind??"internal",attributes:bf({...k},b?.attributes),autoAttributeKeys:Object.keys(k),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:i,backdated:i!==h,clockAnchor:void 0===bM(b?.startTime)?g?.clockAnchor:void 0},(a,b)=>this._onSpanEnd(a,b),this._logger)}withSpan(a,b,c){let d=this.startSpan(a,"function"==typeof b?void 0:b);try{let a=b$(this._contextManager,d,"function"==typeof b?b:c);if(a&&"function"==typeof a.then)return a.then(a=>(d.end(),a),a=>{throw this._recordCallbackError(d,a),d.end(),a});return d.end(),a}catch(a){throw this._recordCallbackError(d,a),d.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;){if(!this._queue.length)return;let a=this._flushPromise;if(!await (a??this._startFlush()))return}}_startFlush(){this._flushTimer.clear();let a=this._generation,b=Promise.resolve().then(()=>a===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===b&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=b,b}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(a,b){if("string"==typeof a){let c=b6(a,b?.tracestate);return c||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),c}if(b5(a))return a.childContext();let c=this._contextManager.active();return b5(c)?c.childContext():c instanceof bU?b6(c.traceparent(),c.tracestate()??void 0):void 0}_autoContextAttributes(){let a;try{a=this._getContext()}catch(a){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",a),{}}let b={};return a.distinctId&&(b.posthogDistinctId=a.distinctId),a.sessionId&&(b.sessionId=a.sessionId),a.currentUrl&&(b["url.full"]=a.currentUrl),a.screenName&&(b["screen.name"]=a.screenName),a.appState&&(b["app.state"]=a.appState),b}_recordCallbackError(a,b){if(!(a instanceof bP))return;let{type:c,message:d,stack:e}=b_(b);a.addEvent("exception",{"exception.type":c,"exception.message":d,...e&&{"exception.stacktrace":e}}),a.statusIsExplicitlyOk||a.setStatus("error",d)}_evictAgedSpans(){let a=b4()-this._config.maxSpanAgeMs,b=0;for(let[c,d]of this._liveSpans){if(d>a)break;this._liveSpans.delete(c),b++}b&&this._recordDrop(b,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(a,b){if(!this._liveSpans.delete(a.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let c=this._runBeforeSpanSend(a,b);if(c){if(this._reportLimitDrops(c),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(c);try{this._onSpanQueued?.()}catch(a){this._logger.debug("Span queue notification failed",a)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(a){let b=a.droppedAttributesCount??0,c=a.droppedEventsCount??0,d=0;for(let b of a.events)d+=b.droppedAttributesCount??0;(b||c||d)&&this._logger.debug(`Span limits discarded data from "${a.name}": ${b} attributes, ${c} events, ${d} event attributes`)}_runBeforeSpanSend(a,b){if(!this._config.beforeSpanSend.length)return a;let c={traceId:a.traceId,spanId:a.spanId,parentSpanId:a.parentSpanId,traceState:a.traceState},d={startTime:a.startTime,endTime:a.endTime},e={attributes:a.droppedAttributesCount,events:a.droppedEventsCount},f=Object.keys(a.attributes),g={traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote},h=a.status&&{...a.status},i=a,j=a;try{var k,l,m;for(let a of this._config.beforeSpanSend){let b=a(i);if(!b)return this._recordDrop(1,"beforeSpanSend dropped it"),null;i=this._keepSpanIdentity(b,c)}if(!((k=j={traceId:c.traceId,spanId:c.spanId,parentSpanId:c.parentSpanId,traceState:c.traceState,name:i.name,kind:i.kind,status:i.status,attributes:i.attributes,events:i.events,startTime:i.startTime,endTime:i.endTime,traceFlags:g.traceFlags,parentIsRemote:g.parentIsRemote,droppedAttributesCount:e.attributes,droppedEventsCount:e.events}).attributes&&"object"==typeof k.attributes&&!Array.isArray(k.attributes)&&Array.isArray(k.events)&&void 0!==k.name&&void 0!==k.kind&&void 0!==k.startTime&&void 0!==k.endTime))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;j.name=bL(j.name,"Span name",this._config.maxAttributeValueLength,this._logger),j.status&&"ok"!==j.status.code&&"error"!==j.status.code&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),j.status=h),j.startTime=bM(j.startTime)??d.startTime,j.endTime=(l=bM(j.endTime)??d.endTime,m=j.startTime,l<m?m:l);let a=[];for(let b of j.events)try{a.push({...b,name:bL(b.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:bN(b.timestamp,j.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return j.events=a,!function(a,b,c,d,e,f,g=[]){let h=0,i=0,j={};for(let d of function(a,b){if(!b.length)return Object.keys(a);let c=b.filter(b=>Object.prototype.propertyIsEnumerable.call(a,b)),d=new Set(c);return[...c,...Object.keys(a).filter(a=>!d.has(a))]}(a.attributes,g)){let e=a.attributes[d];if(!x(e)){if(!b.has(d)){if(h>=c){i++;continue}h++}Object.defineProperty(j,d,{value:bY(e,f),enumerable:!0,writable:!0,configurable:!0})}}a.attributes=j,i&&(a.droppedAttributesCount=bR(a.droppedAttributesCount)+i);let k=0,l=0,m=[];for(let b of a.events){if(k>=d){l++;continue}if(k++,b.attributes){let a=bZ(b.attributes,e,f);b.attributes=a.attributes,a.dropped&&(b.droppedAttributesCount=bR(b.droppedAttributesCount)+a.dropped)}m.push(b)}a.events=m,l&&(a.droppedEventsCount=bR(a.droppedEventsCount)+l),a.status?.message&&(a.status={...a.status,message:bX(function(a){try{return"string"==typeof a?a:String(a)}catch{return bd}}(a.status.message),f)})}(j,b,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,f),j}catch(a){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",a),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(a,b){(a.traceId!==b.traceId||a.spanId!==b.spanId||a.parentSpanId!==b.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{b7(a,"traceId",b.traceId),b7(a,"spanId",b.spanId),b7(a,"parentSpanId",b.parentSpanId),b7(a,"traceState",b.traceState)}catch{try{let c=Object.getOwnPropertyDescriptors(a);for(let a of["traceId","spanId","parentSpanId","traceState"])c[a]={value:b[a],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(a),c)}catch{;}}return a}_recordDrop(a,b){this._droppedSinceWarning+=a,this._dropReasons.add(b),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(a){let b=[];for(let c of a)try{b.push(function(a,b){var c;let d,e={traceId:a.traceId,spanId:a.spanId,name:b2(a.name),kind:(c=a.kind)&&Object.prototype.hasOwnProperty.call(b0,c)?b0[c]:b0.internal,startTimeUnixNano:b3(a.startTime),endTimeUnixNano:b3(a.endTime),flags:(Number.isFinite(d=parseInt(a.traceFlags,16))?255&d:1)|256|512*!!a.parentIsRemote};a.parentSpanId&&(e.parentSpanId=a.parentSpanId),a.traceState&&(e.traceState=b2(a.traceState));let f=bh(a.attributes,b);f.length&&(e.attributes=f),a.events.length&&(e.events=a.events.map(a=>(function(a,b){let c={name:b2(a.name),timeUnixNano:b3(a.timestamp)};if(a.attributes){let d=bh(a.attributes,b);d.length&&(c.attributes=d)}let d=bR(a.droppedAttributesCount);return d&&(c.droppedAttributesCount=d),c})(a,b)));let g=bR(a.droppedAttributesCount);g&&(e.droppedAttributesCount=g);let h=bR(a.droppedEventsCount);return h&&(e.droppedEventsCount=h),a.status&&(e.status={code:b1[a.status.code],...a.status.message&&{message:b2(a.status.message)}}),e}(c,this._logger))}catch(a){this._logger.debug("Failed to encode a span; dropping it",a),this._recordDrop(1,"its attributes could not be encoded")}return b}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let a=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(a,"the user has opted out"),this._warnAboutDrops(),a}async _flushInner(){var a,b;if(!this._queue.length)return 0;let c=this._discardQueueIfConsentWithdrawn();if(c)return c;let d=function(a,b){for(let c of Object.keys(a))a[c]=bY(a[c],b);return a}((a=this._config,bj(a,this._instance.getLibraryId(),this._instance.getLibraryVersion())),this._config.maxAttributeValueLength),e=this._instance.getLibraryId(),f=this._instance.getLibraryVersion(),g=this._queue.length,h=0,i=1/0,j=this._generation;try{for(;g>0&&this._queue.length>0;){let a=this._discardQueueIfConsentWithdrawn();if(a)return h+a;let c=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,k=Math.max(1,Math.min(c,i,g,this._queue.length)),l=this._queue.slice(0,k),m=this._encodeBatch(l);if(!m.length){this._queue.splice(0,k),g-=k,h+=k,this._resetHeadBatchBudget();continue}let n=b4()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),o=await this._instance._sendTracesBatch((b=this._logger,{resourceSpans:[{resource:{attributes:bl(d,b)},scopeSpans:[{scope:{name:e,version:f},spans:m}]}]}));if(j!==this._generation)break;if(this._retryAfter.record(o),"ok"===o.kind){this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._queue.splice(0,k),g-=k,h+=k,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if("too-large"===o.kind){if(1===k){this._queue.splice(0,1),g-=1,h+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget();continue}let a=Math.max(1,Math.floor(k/2));o.measuredLocally?i=a:this._maxExportBatchSize=a,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${a}`);continue}if("retry-later"===o.kind){if(this._consecutiveFlushFailures++,this._flushJitter=bq(),this._headBatchSize=k,n&&(this._headBatchFailures++,this._headBatchChargeableAt=b4()+this._nextFlushDelay()),this._headBatchFailures<8)return this._logger.debug("Span export failed; retrying on the next flush",o.error),h;if(this._queue.splice(0,k),g-=k,h+=k,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(k,"the ingestion endpoint failed 8 times in a row"),this._retryAfter.isOpen())return h;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",o.error),this._queue.splice(0,k),g-=k,h+=k,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(k,"the ingestion endpoint rejected the batch")}return h}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(a=>{this._logger.debug("Background span flush failed",a)}).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(br(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}}class b9{active(){return this._active}with(a,b){let c=this._active;this._active=a;try{return b()}finally{this._active=c}}}let ca=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","lightpanda","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],cb=new Map,cc=function(a,b=[]){if(!a)return!1;let c=function(a,b){let c="";for(let a=0;a<b.length;a++){let d=b[a];c+=d.length+":"+d}return a.length+":"+a+"|"+b.length+":"+c}(a,b),d=cb.get(c);if(void 0!==d)return d;let e=a.toLowerCase(),f=ca.concat(b).some(a=>-1!==e.indexOf(a.toLowerCase()));return cb.size>=256&&cb.clear(),cb.set(c,f),f};function cd(a){let b=a?.resourceAttributes;return{serviceName:b?.["service.name"]??a?.serviceName,serviceVersion:b?.["service.version"]??a?.serviceVersion,environment:b?.["deployment.environment"]??a?.environment,resourceAttributes:b,beforeSend:a?.beforeSend,flushIntervalMs:a?.flushIntervalMs??1e4,maxSeriesPerFlush:a?.maxSeriesPerFlush??1e3}}function ce(a,b){return"number"==typeof a&&Number.isInteger(a)&&a>=1?a:b}let cf=["service.name","service.version","deployment.environment"];function cg(a,b,c){let d=bf({...b},function(a){if(!(!a||"object"!=typeof a||Array.isArray(a)))try{if(cf.every(b=>!(b in a)||"string"==typeof a[b]))return a;let b={...a};for(let a of cf)a in b&&"string"!=typeof b[a]&&delete b[a];return b}catch{return}}(a?.resourceAttributes)),e=ce(a?.maxExportBatchSize,512);return{serviceName:d?.["service.name"]??a?.serviceName,serviceVersion:d?.["service.version"]??a?.serviceVersion,environment:d?.["deployment.environment"]??a?.environment,resourceAttributes:d,beforeSpanSend:function(a,b){if(!a)return[];let c=[a].flat().filter(a=>!!a),d=c.filter(a=>"function"==typeof a);return d.length!==c.length&&b?.critical(`beforeSpanSend: ignoring ${c.length-d.length} of ${c.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),d}(a?.beforeSpanSend,c),maxAttributesPerSpan:ce(a?.maxAttributesPerSpan,128),maxEventsPerSpan:ce(a?.maxEventsPerSpan,128),maxAttributesPerEvent:128,maxAttributeValueLength:ce(a?.maxAttributeValueLength,8192),flushIntervalMs:ce(a?.flushIntervalMs,5e3),maxExportBatchSize:e,maxQueueSize:Math.max(ce(a?.maxQueueSize,2048),e),maxLiveSpans:ce(a?.maxLiveSpans,1e4),maxSpanAgeMs:ce(a?.maxSpanAgeMs,36e5)}}let ch={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",LOCAL_EVALUATION_INCONCLUSIVE:"local_evaluation_inconclusive",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};a.s(["FeatureFlagError",0,ch],46539);class ci{constructor(a){this._host=a.host,this._distinctId=a.distinctId,this._groups=a.groups,this._disableGeoip=a.disableGeoip,this._flags=a.flags,this._unresolvedFlags=Object.freeze({...a.unresolvedFlags}),this._requestId=a.requestId,this._evaluatedAt=a.evaluatedAt,this._flagDefinitionsLoadedAt=a.flagDefinitionsLoadedAt,this._errorsWhileComputing=a.errorsWhileComputing??!1,this._quotaLimited=a.quotaLimited??!1,this._accessed=a.accessed??new Set,this._isSlice=a.isSlice??!1}isEnabled(a,b={}){let c=this._flags[a];return this._recordAccess(a,b.sendFeatureFlagEvents),c?.enabled??b.defaultValue??!1}getFlag(a,b={}){let c=this._flags[a];if(this._recordAccess(a,b.sendFeatureFlagEvents),c)return!!c.enabled&&(c.variant??!0)}getFlagPayload(a){return this._flags[a]?.payload}onlyAccessed(){let a={};for(let b of this._accessed){let c=this._flags[b];c&&(a[b]=c)}return this._cloneWith(a)}only(a){let b={},c=[];for(let d of a){let a=this._flags[d];a?b[d]=a:c.push(d)}return c.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${c.join(", ")}`),this._cloneWith(b)}get keys(){return Object.keys(this._flags)}get unresolvedFlags(){return this._unresolvedFlags}_getEventProperties(){let a={},b=[];for(let[c,d]of Object.entries(this._flags)){let e=!1!==d.enabled&&(d.variant??!0);a[`$feature/${c}`]=e,d.enabled&&b.push(c)}return b.length>0&&(b.sort(),a.$active_feature_flags=b),a}_cloneWith(a){return new ci({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:a,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(a,b){if(this._accessed.add(a),!this._host.resolveSendFeatureFlagEvents(b)||""===this._distinctId||this._isSlice&&!(a in this._flags))return;let c=this._flags[a],d=void 0===c?void 0:!1!==c.enabled&&(c.variant??!0),e={$feature_flag:a,$feature_flag_response:d,$feature_flag_id:c?.id,$feature_flag_version:c?.version,$feature_flag_reason:c?.reason,locally_evaluated:c?.locallyEvaluated??!1,[`$feature/${a}`]:d,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:c?.locallyEvaluated?Date.now():this._evaluatedAt};c?.hasExperiment!==void 0&&(e.$feature_flag_has_experiment=c.hasExperiment),c?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(e.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let f=[];this._errorsWhileComputing&&f.push(ch.ERRORS_WHILE_COMPUTING),this._quotaLimited&&f.push(ch.QUOTA_LIMITED),void 0===c&&f.push(Object.prototype.hasOwnProperty.call(this._unresolvedFlags,a)?ch.LOCAL_EVALUATION_INCONCLUSIVE:ch.FLAG_MISSING),f.length>0&&(e.$feature_flag_error=f.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:a,response:d,groups:this._groups,disableGeoip:this._disableGeoip,properties:e,record:c?.parsed})}}let cj=new WeakMap;class ck extends Error{constructor(a){super(a),this.field=a}}function cl(a){let b=cj.get(a);return b||{value:a.variant??a.enabled??null,failed:!0===a.failed,reason:a.reason&&{code:a.reason.code,conditionIndex:a.reason.condition_index,description:a.reason.description},metadata:{id:a.metadata?.id,version:a.metadata?.version,configVersion:1,description:a.metadata?.description,hasExperiment:a.metadata?.has_experiment}}}function cm(a,b){return{detail:{key:a,enabled:!1,variant:void 0,reason:void 0,metadata:void 0,failed:!0},record:{value:null,failed:!0,unreadableField:b,metadata:{}}}}function cn(a){cq(a.key,"key",u)}function co(a){let b=cq(a,"reason",C);if(void 0!==b)return{code:cq(b.code,"reason.code",u),conditionIndex:cr(b.condition_index,"reason.condition_index"),description:cq(b.description,"reason.description",u)}}function cp(a){return{id:cr(a?.id,"metadata.id"),version:cr(a?.version,"metadata.version"),description:cq(a?.description,"metadata.description",u),hasExperiment:cq(a?.has_experiment,"metadata.has_experiment",z)}}function cq(a,b,c){if(!x(a)){if(c(a))return a;throw new ck(b)}}function cr(a,b){return cq(a,b,a=>y(a)&&Number.isInteger(a))}let cs="experiment_split",ct="experiment",cu=new Map([["targeting_match",new Set(["targeted_release","percentage_rollout"])],[cs,new Set([ct])],["rollout_miss",new Set(["percentage_rollout",ct])],["experiment_paused",new Set([ct])],["holdout",new Set([ct])]]),cv=["$feature_flag_config_version","$feature_flag_reason_code","$feature_flag_rule_id","$feature_flag_rule_type","$feature_flag_variant_key"],cw=new Set([...cv,"$feature_flag_reason","$feature_flag_forced_variant","$feature_flag_experiment_id"]),cx=new Set(["$feature_flag_config_version","$feature_flag_reason_code","$feature_flag_rule_type","$experiment_exposure_source","$feature_flag_experiment_id","$feature_flag_forced_variant"]),cy=["$feature_flag_id","$feature_flag_version","$feature_flag_request_id","$feature_flag_evaluated_at"],cz=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,cA=["exact","is_not","icontains","not_icontains","starts_with","not_starts_with","ends_with","not_ends_with","regex","not_regex"];class cB extends Error{constructor(a,b="unsupported_definition"){super(a),this.name=this.constructor.name,this.reason=b,Object.setPrototypeOf(this,cB.prototype)}}function cC(a){try{return a()}catch(a){if(a instanceof cB)throw new cB(a.message,"missing_context");throw a}}function cD(a){if("boolean"==typeof a)return!0;if("string"==typeof a){let b=a.toLowerCase();return"true"===b||"false"===b}if(!Array.isArray(a))return!1;for(let b=0;b<a.length;b++)if(!cD(b in a?a[b]:null))return!1;return!0}function cE(a){if("boolean"==typeof a)return a;if("string"==typeof a)return"true"===a.toLowerCase();if(!Array.isArray(a))return!1;for(let b=0;b<a.length;b++)if(!cE(b in a?a[b]:null))return!1;return!0}function cF(a){for(let b=0;b<a.length;b++){let c=a.charCodeAt(b);if(c>=55296&&c<=56319){let c=a.charCodeAt(b+1);if(b+1>=a.length||c<56320||c>57343)throw new cB("Cannot stringify an unpaired surrogate like the flags service");b++}else if(c>=56320&&c<=57343)throw new cB("Cannot stringify an unpaired surrogate like the flags service")}}function cG(a,b=new Set){if(null!==a&&"boolean"!=typeof a){if("string"==typeof a)return void cF(a);if("number"==typeof a){if(!Number.isFinite(a))throw new cB(`Cannot represent non-finite number ${a} like the flags service`);return}if(Array.isArray(a)){if(b.has(a))throw new cB("Cannot represent a circular array during local evaluation");b.add(a);try{for(let c=0;c<a.length;c++)c in a&&cG(a[c],b)}finally{b.delete(a)}return}if("object"==typeof a){let c=Object.getPrototypeOf(a);if(c!==Object.prototype&&null!==c)throw new cB("Cannot represent a non-JSON object like the flags service");if(b.has(a))throw new cB("Cannot represent a circular object during local evaluation");b.add(a);try{for(let c of Object.keys(a))cF(c),cG(a[c],b)}finally{b.delete(a)}return}throw new cB(`Cannot represent ${typeof a} like the flags service`)}}function cH(a,b){let c=0,d=0;for(;c<a.length&&d<b.length;){let e=a.charCodeAt(c),f=b.charCodeAt(d),g=e>=55296&&e<=56319,h=f>=55296&&f<=56319,i=g?a.charCodeAt(c+1):0,j=h?b.charCodeAt(d+1):0,k=g?(e-55296)*1024+i-56320+65536:e,l=h?(f-55296)*1024+j-56320+65536:f;if(k!==l)return k-l;c+=g?2:1,d+=h?2:1}return a.length-b.length}function cI(a){return"string"==typeof a?(cF(a),a):function a(b,c=new Set){if(null===b)return"null";if("string"==typeof b)return cF(b),JSON.stringify(b);if("boolean"==typeof b)return b?"true":"false";if("number"==typeof b){if(!Number.isFinite(b))throw new cB(`Cannot stringify non-finite number ${b} like the flags service`);if(Number.isInteger(b))throw new cB(`Cannot distinguish integer ${b} from an integral JSON float during local evaluation`);return String(b)}if(Array.isArray(b)){if(c.has(b))throw new cB("Cannot stringify a circular array during local evaluation");c.add(b);try{let d=[];for(let e=0;e<b.length;e++)d.push(e in b?a(b[e],c):"null");return`[${d.join(",")}]`}finally{c.delete(b)}}if("object"==typeof b){let d=Object.getPrototypeOf(b);if(d!==Object.prototype&&null!==d)throw new cB("Cannot stringify a non-JSON object like the flags service");if(c.has(b))throw new cB("Cannot stringify a circular object during local evaluation");c.add(b);try{let d=Object.keys(b);return d.forEach(cF),`{${d.sort(cH).map(d=>`${JSON.stringify(d)}:${a(b[d],c)}`).join(",")}}`}finally{c.delete(b)}}throw new cB(`Cannot stringify ${typeof b} like the flags service`)}(a)}let cJ=/[\x20-\x2f:;=?@\x5b-\x60\x7b-\x7e]/;function cK(a){let b=new cB(a);return Object.defineProperty(b,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),b}function cL(a){return String(a).replace(/[A-Z]/g,a=>a.toLowerCase())}function cM(a,b,c){if(!/^\d+$/.test(a)||"strict"===c&&a.length>1&&"0"===a[0])throw new cB(`Invalid semver: ${b}`);return parseInt(a,10)}function cN(a,b="strict"){let c=String(a).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!c||c.startsWith("."))throw new cB(`Invalid semver: ${a}`);let d=c.split("."),e=c=>void 0===c||""===c?0:cM(c,a,b);return[e(d[0]),e(d[1]),e(d[2])]}function cO(a,b){for(let c=0;c<3;c++){if(a[c]<b[c])return -1;if(a[c]>b[c])return 1}return 0}function cP(a,b){let c=cN(a,b);return{lower:[c[0],c[1],c[2]],upper:[c[0],c[1]+1,0]}}function cQ(a,b){let[c,d,e]=cN(a,b);return{lower:[c,d,e],upper:c>0?[c+1,0,0]:d>0?[0,d+1,0]:[0,0,e+1]}}function cR(a,b){let c=String(a).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!c)throw new cB(`Invalid wildcard semver: ${a}`);let d=c.split("."),e=c=>{if("legacy-permissive"===b){let a=parseInt(c,10);if(!isNaN(a))return a}else try{return cM(c,a,b)}catch{}throw new cB(`Invalid wildcard semver: ${a}`)},f=e(d[0]);if(1===d.length)return{lower:[f,0,0],upper:[f+1,0,0]};let g=e(d[1]);return{lower:[f,g,0],upper:[f,g+1,0]}}function cS(a){if(a instanceof Date)return a;if("string"==typeof a||"number"==typeof a){let b=new Date(a);if(!isNaN(b.valueOf()))return b;throw new cB(`${a} is in an invalid date format`)}throw new cB(`The date provided ${a} must be a string, number, or date object`)}function cT(a){if("boolean"==typeof a)throw new cB("Date operations cannot be performed on boolean values");return function(a){let b=a.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),c=new Date(new Date().toISOString());if(!b||!b.groups)return null;let d=parseInt(b.groups.number);if(d>=1e4)return null;let e=b.groups.interval;if("h"===e)c.setUTCHours(c.getUTCHours()-d);else if("d"===e)c.setUTCDate(c.getUTCDate()-d);else if("w"===e)c.setUTCDate(c.getUTCDate()-7*d);else if("m"===e){var f,g,h=c,i=d;let a=h.getUTCFullYear(),b=h.getUTCMonth(),e=h.getUTCDate();for(let c=1;c<=i&&e>28;c++)e=Math.min(e,new Date(Date.UTC(a,b-c+1,0)).getUTCDate());h.setUTCFullYear(a,b-i,e)}else{let a,b;if("y"!==e)return null;f=c,g=d,a=f.getUTCMonth(),b=g>0&&1===a&&29===f.getUTCDate()?28:f.getUTCDate(),f.setUTCFullYear(f.getUTCFullYear()-g,a,b)}return c}(String(a))??cS(a)}function cU(a,b={}){let c=a.value,d=b.semverParsingPolicy??"strict";switch(a.operator||"exact"){case"exact":case"is_not":for(let a of Array.isArray(c)?c:[c])cI(a);return;case"is_set":case"is_not_set":case"icontains":case"not_icontains":case"starts_with":case"not_starts_with":case"ends_with":case"not_ends_with":case"regex":case"not_regex":case"gt":case"gte":case"lt":case"lte":return;case"is_date_after":case"is_date_before":cT(c);return;case"semver_eq":case"semver_neq":case"semver_gt":case"semver_gte":case"semver_lt":case"semver_lte":cN(String(c),d);return;case"semver_tilde":cP(String(c),d);return;case"semver_caret":cQ(String(c),d);return;case"semver_wildcard":cR(String(c),d);return;default:throw new cB(`Unknown operator: ${a.operator}`)}}async function cV(a){let b=globalThis.crypto?.subtle;if(!b)throw Error("SubtleCrypto API not available");return Array.from(new Uint8Array(await b.digest("SHA-1",new TextEncoder().encode(a)))).map(a=>a.toString(16).padStart(2,"0")).join("")}async function cW(a,b,c="",d="."){return parseInt((await cV(`${a}${d}${b}${c}`)).slice(0,15),16)/0x1000000000000000}async function cX(a,b){if(null==a||null==a.id||null==a.exclusion_percentage)return;let c=Number(a.exclusion_percentage);if(!Number.isFinite(c))return;let d=Math.min(Math.max(c,0),100);if(!(100!==d&&await cW("holdout",b,"","-")>d/100))return`holdout-${a.id}`}function cY(a){let b=[],c=0;for(let d of a){let a=c+d.rollout_percentage/100;b.push({valueMin:c,valueMax:a,key:d.key}),c=a}return b}async function cZ(a,b,c){let d=await cW(a,b,"variant");return cY(c).find(a=>d>=a.valueMin&&d<a.valueMax)?.key}function c$(a){return"client"===a||"server"===a?a:"all"}function c_(a,b){return a===b||"all"===a||"all"===b}class c0 extends Error{constructor(a){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=a,Object.setPrototypeOf(this,c0.prototype)}}class c1 extends Error{constructor(a,b="unsupported_definition"){super(a),this.reason=b,this.name=c1.name,Error.captureStackTrace(this,c1),Object.setPrototypeOf(this,c1.prototype)}}let c2=["experience_continuity","unsupported_definition","unresolved_dependency","missing_context"];function c3(a,b){return void 0===a||c2.indexOf(b)<c2.indexOf(a)?b:a}function c4(a,b){return b instanceof cB&&Symbol.for("posthog.requiresServerRegexEvaluation")in b&&Object.defineProperty(a,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),a}class c5{constructor({pollingInterval:a,personalApiKey:b,projectApiKey:c,timeout:d,host:e,customHeaders:f,...g}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.warnedUnresolvableFlags=new Map,this.pollingInterval=a,this.personalApiKey=b,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=d,this.projectApiKey=c,this.host=e,this.poller=void 0,this.fetch=g.fetch||fetch,this.onError=g.onError,this.customHeaders=f,this.onLoad=g.onLoad,this.onMinimalFlagCalledEvents=g.onMinimalFlagCalledEvents,this.cacheProvider=g.cacheProvider,this.strictLocalEvaluation=g.strictLocalEvaluation??!1,this.evaluationContexts=g.evaluationContexts,this.loadFeatureFlags()}debug(a=!0){this.debugMode=a}logMsgIfDebug(a){this.debugMode&&a()}currentDefinitions(){return{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}withEvaluationSnapshot(a){return a.definitions?a:{...a,evaluationCache:{},definitions:this.currentDefinitions()}}createEvaluationContext(a,b={},c={},d={},e={}){return{distinctId:a,groups:b,personProperties:c,groupProperties:d,evaluationCache:e}}async getFeatureFlag(a,b,c={},d={},e={}){let f,g;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return f;if(void 0!==(g=this.featureFlagsByKey[a])){let h=this.createEvaluationContext(b,c,d,e);try{f=(await this.computeFlagAndPayloadLocally(g,h)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${a} -> ${f}`))}catch(b){b instanceof c1||b instanceof cB?this.logMsgIfDebug(()=>console.debug(`${b.name} when computing flag locally: ${a}: ${b.message}`)):b instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${a}: ${b}`))}}return f}async getAllFlagsAndPayloads(a,b){await this.loadFeatureFlags();let c={},d={},e={},f=0==this.featureFlags.length,g=b?b.map(a=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,h=this.withEvaluationSnapshot({...a,definitions:void 0});return await Promise.all(g.map(async a=>{try{let{value:b,payload:e}=await this.computeFlagAndPayloadLocally(a,h,{skipLoadCheck:!0});c[a.key]=b,e&&(d[a.key]=e)}catch(b){b instanceof c1||b instanceof cB?(this.logMsgIfDebug(()=>console.debug(`${b.name} when computing flag locally: ${a.key}: ${b.message}`)),e[a.key]=b.reason):b instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${a.key}: ${b}`)),c_(c$(a.evaluation_runtime),"server")&&(f=!0)}})),{response:c,payloads:d,unresolved:e,fallbackToFlags:f}}async computeFlagAndPayloadLocally(a,b,c={}){let d,{matchValue:e,skipLoadCheck:f=!1}=c;if(this.loadedSuccessfullyOnce&&(b=this.withEvaluationSnapshot(b)),f||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};a=(b=this.withEvaluationSnapshot(b)).definitions.featureFlagsByKey[a.key]??a,d=void 0!==e?e:await this.computeFlagValueLocally(a,b);let g=function(a,b){if(!1===b||null==b||!a)return null;let c=a["boolean"==typeof b?b.toString():b]||null;return null==c?null:aC(c)}(a.filters?.payloads,d);return{value:d,payload:g}}async computeFlagValueLocally(a,b){let{distinctId:c,groups:d,personProperties:e,groupProperties:f}=b;if(!a.active)return!1;if(a.ensure_experience_continuity)throw new cB("Flag has experience continuity enabled","experience_continuity");let g=(a.filters||{}).aggregation_group_type_index;if(void 0!=g){let c=b.definitions.groupTypeMapping[String(g)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${g} for feature flag ${a.key}`)),new cB("Flag has unknown group type index");if(!(c in d))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${a.key} without group names passed in`)),!1;"device_id"===a.bucketing_identifier&&(e?.$device_id===void 0||e?.$device_id===null||e?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${a.key}`));let h=f[c];return await this.matchFeatureFlagProperties(a,d[c],h,b)}{let d=this.getBucketingValueForFlag(a,c,e);if(void 0===d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${a.key} without $device_id, falling back to server evaluation`)),new cB(`Can't compute feature flag: ${a.key} without $device_id`,c6(a,b.definitions)??"missing_context");return await this.matchFeatureFlagProperties(a,d,e,b)}}getBucketingValueForFlag(a,b,c){if(a.filters?.aggregation_group_type_index!=void 0)return b;if("device_id"===a.bucketing_identifier){let a=c?.$device_id;if(null==a||""===a)return;return a}return b}async evaluateFlagDependency(a,b,c){let{evaluationCache:d}=c,e=a.key;if(!c.definitions.featureFlagsByKey)throw new cB("Feature flags not available for dependency evaluation");if(!("dependency_chain"in a))throw new cB(`Flag dependency property for '${e}' is missing required 'dependency_chain' field`);let f=a.dependency_chain;if(!Array.isArray(f))throw new cB(`Flag dependency property for '${e}' has an invalid 'dependency_chain' (expected array, got ${typeof f})`);if(0===f.length)throw new cB(`Circular dependency detected for flag '${e}' (empty dependency chain)`);let g=f.find(a=>!(a in d)&&!c.definitions.featureFlagsByKey[a]&&!c.definitions.filteredOutFlagKeys.has(a));if(void 0!==g)throw new cB(`Missing flag dependency '${g}' for flag '${e}'`);for(let a of f){if(!(a in d)){let b=c.definitions.featureFlagsByKey[a];if(b)if(b.active)try{let e=await this.computeFlagValueLocally(b,c);d[a]=e}catch(b){if(b instanceof c1)throw new c1(`Flag dependency '${a}' for flag '${e}' requires server evaluation: ${b.message}`,"unresolved_dependency");throw c4(new cB(`Error evaluating flag dependency '${a}' for flag '${e}': ${b}`,"unresolved_dependency"),b)}else d[a]=!1;else d[a]=!1}if(null==d[a])throw new cB(`Dependency '${a}' could not be evaluated`,"unresolved_dependency")}let h=d[e];return this.flagEvaluatesToExpectedValue(a.value,h)}flagEvaluatesToExpectedValue(a,b){return"boolean"==typeof a?a===b||"string"==typeof b&&""!==b&&!0===a:"string"==typeof a&&b===a}async matchFeatureFlagProperties(a,b,c,d){let e,f,g;d=this.withEvaluationSnapshot(d);let h=a.filters||{},i=await cX(h.holdout,b);if(void 0!==i)return i;let j=h.groups||[],k=h.aggregation_group_type_index,l=h.early_exit??!1,{groups:m,groupProperties:n}=d,o=new Set;for(let i of j){let j=b;try{let b=void 0!==i.aggregation_group_type_index?i.aggregation_group_type_index:k,f=c;if(b!==k&&null!=b){let c=d.definitions.groupTypeMapping[String(b)];if(!c||!(c in m)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${a.key}': group type index ${b} not available`));continue}if(!(c in n)){e=c3(e,"missing_context");continue}f=n[c],j=m[c]}let o=await this.isConditionMatch(a,j,i,f,d);if("match"===o){let b=i.variant,c=h.multivariate?.variants||[];g=b&&c.some(a=>a.key===b)?b:await this.getMatchingVariant(a,j)||!0;break}if(l&&"out_of_rollout_bound"===o){if(e)break;return!1}}catch(b){if(b instanceof c1){let c;try{c=c6(a,d.definitions)}catch{}let f=c3(c3(e,b.reason),c??b.reason);throw f===b.reason?b:new c1(b.message,f)}if(b instanceof cB){if(e=c3(e,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b)if(f=b,l&&void 0!=i.rollout_percentage&&await cW(a.key,j)>i.rollout_percentage/100)o.add(!1);else{let b=h.multivariate?.variants||[],c=i.variant;o.add(c&&b.some(a=>a.key===c)?c:await this.getMatchingVariant(a,j)||!0)}}else throw b}}if(void 0!==g&&!(f&&[...o].some(a=>a!==g)))return g;if(e)throw c4(new cB("Can't determine if feature flag is enabled or not with given properties",e),f);return!1}async isConditionMatch(a,b,c,d,e){let f=(e=this.withEvaluationSnapshot(e)).definitions,g=c.rollout_percentage,h=a=>{this.logMsgIfDebug(()=>console.warn(a))};if((c.properties||[]).length>0){let b,i,j;for(let a of c.properties){let c=a.type,g=!1;try{if("cohort"===c)g=await c8(a,d,f.cohorts,this.debugMode,a=>this.evaluateFlagDependency(a,d,e),f.propertyMatchingVersion);else if("flag"===c)g=await this.evaluateFlagDependency(a,d,e);else if(Object.prototype.hasOwnProperty.call(d,a.key))g=c7(a,d,h,f.propertyMatchingVersion);else{cU(a),b=c3(b,"missing_context");continue}}catch(a){if(a instanceof c1){void 0===b&&(j??=a),b=c3(b,a.reason);continue}if(a instanceof cB){Symbol.for("posthog.requiresServerRegexEvaluation")in a&&(i=a),b=c3(b,a.reason);continue}if(void 0!==b)break;throw a}if(!g)return"no_match"}if(j)throw j;if(b)throw c4(new cB(`Can't determine if a condition of flag ${a.key} matches`,b),i);if(void 0==g)return"match"}return void 0!=g&&await cW(a.key,b)>g/100?"out_of_rollout_bound":"match"}async getMatchingVariant(a,b){return cZ(a.key,b,a.filters?.multivariate?.variants||[])}variantLookupTable(a){return cY(a.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(a){if(!this.evaluationContexts||0===this.evaluationContexts.length)return a;let b=new Set(this.evaluationContexts);return a.filter(a=>{let c=a.evaluation_contexts??a.evaluation_tags;return!c||0===c.length||c.some(a=>b.has(a))})}getEvaluationRuntimeForFlag(a){let b=this.featureFlagsByKey[a];return b?c$(b.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(a){return this.featureFlags.filter(b=>c_(c$(b.evaluation_runtime),a)).map(a=>a.key)}updateFlagState(a){let b=this.filterFlagsByEvaluationContexts(a.flags),c=b.reduce((a,b)=>(a[b.key]=b,a),{}),d=new Set(b.map(a=>a.key)),e=new Set(a.flags.filter(a=>!d.has(a.key)).map(a=>a.key));this.featureFlags=b,this.featureFlagsByKey=c,this.filteredOutFlagKeys=e,this.groupTypeMapping=a.group_type_mapping??a.groupTypeMapping??{},this.cohorts=a.cohorts,this.propertyMatchingVersion=a.property_matching_version??a.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((a.minimal_flag_called_events??a.minimalFlagCalledEvents)===!0)}warnAboutUnresolvableFlags(a){let b=[],c=[],d=new Map,e=this.currentDefinitions();for(let f of a){if(!c_(c$(f.evaluation_runtime),"server"))continue;let a=c6(f,e);if(!a)continue;let g=JSON.stringify(f);d.set(f.key,g),this.warnedUnresolvableFlags.get(f.key)!==g&&("experience_continuity"===a?b.push(f.key):c.push(f.key))}if(this.warnedUnresolvableFlags=d,b.length>0){let a=this.strictLocalEvaluation?"With strictLocalEvaluation enabled these flags are left unresolved. To evaluate them locally, disable experience continuity on these flags in PostHog.":"Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).";console.warn(`[PostHog] You are using local evaluation but ${b.length} flag(s) have experience continuity enabled and cannot be resolved locally (reason: experience_continuity): ${b.join(", ")}. `+a)}if(c.length>0){let a=this.strictLocalEvaluation?"With strictLocalEvaluation enabled these flags are left unresolved when evaluation reaches that part.":"Evaluating these flags falls back to a server request when evaluation reaches that part.";console.warn(`[PostHog] You are using local evaluation but ${c.length} flag(s) use something local evaluation does not support, such as a static cohort, an unknown operator, or a missing or circular flag dependency (reason: unsupported_definition): ${c.join(", ")}. ${a} To evaluate them locally, change these flags in PostHog or upgrade posthog-node.`)}}async loadFromCache(a){if(!this.cacheProvider)return!1;try{let b=await this.cacheProvider.getFlagDefinitions();if(b)return this.updateFlagState(b),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${a} (${b.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags),!0;return!1}catch(a){return this.onError?.(Error(`Failed to load from cache: ${a}`)),!1}}async loadFeatureFlags(a=!1){if(!this.loadedSuccessfullyOnce||a)return!a&&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(a=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${a}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let a=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(6e4,a*2**this.backOffCount):a}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{if(this.cacheProvider&&!this.personalApiKey)return void await this.loadFromCache("Loaded flags from cache (cache-only reader)");let a=!0;if(this.cacheProvider)try{a=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(a){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${a}`))}if(!a&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let b=await this._requestFeatureFlagDefinitions();if(!b)return;switch(b.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=b.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new c0(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new c0(`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 c0(`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 c=await b.json()??{};if(!("flags"in c))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(c)}`));this.flagsEtag=b.headers?.get("ETag")??void 0;let d=c.group_type_mapping||{},e=!0===c.minimal_flag_called_events,f={flags:c.flags??[],group_type_mapping:d,cohorts:c.cohorts||{},minimal_flag_called_events:e,property_matching_version:c.property_matching_version,propertyMatchingVersion:c.property_matching_version,groupTypeMapping:d,minimalFlagCalledEvents:e};if(this.updateFlagState(f),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&a)try{await this.cacheProvider.onFlagDefinitionsReceived(f)}catch(a){this.onError?.(Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags);break}default:return}}catch(a){a instanceof c0&&this.onError?.(a)}finally{this.pollerStopped||null===this.pollingInterval||(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(a="GET",b){let c={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return b&&(c["If-None-Match"]=b),{method:a,headers:c}}async _requestFeatureFlagDefinitions(){if(!this.personalApiKey)throw new c0("A secretKey or personalApiKey is required to fetch feature flag definitions from PostHog.");let a=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,b=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),c=null;if(this.timeout&&"number"==typeof this.timeout){let a=new AbortController;c=aM(()=>{a.abort()},this.timeout),b.signal=a.signal}try{let d=this.fetch,e=await d(a,b);if(200!==e.status)return clearTimeout(c),e;return{status:e.status,headers:e.headers,body:e.body,text:async()=>{try{return await e.text()}finally{clearTimeout(c)}},json:async()=>{try{return await e.json()}finally{clearTimeout(c)}}}}catch(a){throw clearTimeout(c),a}}async stopPoller(a=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let b=this.cacheProvider.shutdown();b instanceof Promise&&await aN(b,a,()=>{throw Error(`Cache shutdown timeout after ${a}ms`)})}catch(a){this.onError?.(Error(`Error during cache shutdown: ${a}`))}}}function c6(a,b){if(!a.active)return;if(a.ensure_experience_continuity)return"experience_continuity";let c=a.filters||{},d=c.aggregation_group_type_index;return void 0==d||b.groupTypeMapping[String(d)]?(c.groups||[]).some(a=>(a.properties||[]).some(a=>(function a(b,c,d){if("flag"===b.type){let a=b.dependency_chain;return!Array.isArray(a)||0===a.length||a.some(a=>!c.featureFlagsByKey[a]&&!c.filteredOutFlagKeys.has(a))}if("cohort"!==b.type)try{return cU(b),!1}catch(a){if(a instanceof cB)return!0;throw a}let e=String(b.value);return!(e in c.cohorts)||!d.has(e)&&(d.add(e),function b(c,d,e){return(c?.values??[]).some(c=>"values"in c?b(c,d,e):a(c,d,e))}(c.cohorts[e],c,d))})(a,b,new Set)))?"unsupported_definition":void 0:"unsupported_definition"}function c7(a,b,c,d){return function(a,b,c={}){try{return function(a,b,c){let d=a.key,e=a.value,f=a.operator||"exact",g=c.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(b,d)){if("is_not_set"===f)return!1;else if("is_set"===f)return!0}else throw new cB(`Property ${d} not found in propertyValues`,"missing_context");let h=b[d];if(void 0===h)throw c.warnFunction?.(`Property ${d} cannot have a value of undefined with the ${f} operator`),new cB(`Property ${d} is undefined in propertyValues`);if(null===h&&!cA.includes(f))return c.warnFunction?.(`Property ${d} cannot have a value of null with the ${f} operator`),!1;let i=(a,b)=>{if(2!==c.propertyMatchingVersion&&cD(a)||Array.isArray(a)&&0===a.length)return cC(()=>cG(b)),cE(a)===cE(b);if(2===c.propertyMatchingVersion&&"number"==typeof b&&cD(a))return cC(()=>cG(b)),!1;if(Array.isArray(a)){let c=cC(()=>cI(b)).toLowerCase();return a.some(a=>cI(a).toLowerCase()===c)}return cI(a).toLowerCase()===cC(()=>cI(b)).toLowerCase()},j=(a,b,c)=>{if("gt"===c)return a>b;if("gte"===c)return a>=b;if("lt"===c)return a<b;if("lte"===c)return a<=b;throw Error(`Invalid operator: ${c}`)},k=()=>cC(()=>cN(String(h),g)),l=()=>{let a=cN(String(e),g);return cO(k(),a)},m=({lower:a,upper:b})=>{let c=k();return cO(c,a)>=0&&0>cO(c,b)};switch(f){case"exact":return i(e,h);case"is_not":return!i(e,h);case"is_set":return!0;case"icontains":return cL(h).includes(cL(e));case"not_icontains":return!cL(h).includes(cL(e));case"starts_with":return cL(h).startsWith(cL(e));case"not_starts_with":return!cL(h).startsWith(cL(e));case"ends_with":return cL(h).endsWith(cL(e));case"not_ends_with":return!cL(h).endsWith(cL(e));case"regex":case"not_regex":{let a=function(a,b){let c;if(""===a)return!0;let d=function(a){let b=[],c=-1,d="";for(let e=0;e<a.length;e++){let f=a[e];if(f.charCodeAt(0)>127)return null;if("\\"===f){let b=a[++e];if(void 0===b)break;if("x"===b){if(!/^[\da-f]{2}$/i.test(a.slice(e+1,e+3)))return null;e+=2}else if(!"dDsSwWbBfnrtv".includes(b)&&!cJ.test(b))return null;if(-1===c&&"bB".includes(b))return null;d="literal";continue}if("["===f){if(-1!==c)return null;c=e}else if("]"===f&&-1!==c){if(e===c+("^"===a[c+1]?2:1))return null;b.push(a.slice(c,e+1)),c=-1,d="literal";continue}else if(-1!==c){if(["&&","--","~~"].includes(a.slice(e,e+2)))return null;continue}else if("("===f&&"?"===a[e+1]){if(":"!==a[e+2])return null;e+=2}else if("{"===f){let b=/^\{(\d+)(?:,(\d*))?\}/.exec(a.slice(e));if(!b||["","|","("].includes(d)||b.slice(1).some(a=>Number(a)>0xffffffff))return null}else if("*+?}".includes(f)&&("+"===a[e+1]||"{"===a[e+1]))return null;if("*+?{".includes(f)&&["^","$","empty group"].includes(d))return null;d=")"===f&&["(","empty group"].includes(d)?"empty group":f}return b}(a);if(null===d)throw cK("Regex syntax requires server evaluation");try{c=new RegExp(a)}catch(a){if(a instanceof SyntaxError)return null;throw cK("Regex compilation requires server evaluation")}for(let a of d)try{RegExp(a,"u")}catch{throw cK("Regex character class syntax requires server evaluation")}for(let a=0;a<b.length;a++){let c=b[a];if(c.charCodeAt(0)>127||"\r"===c)throw cK("Regex matching for Unicode or carriage returns requires server evaluation")}try{return c.test(b)}catch{throw cK("Regex execution requires server evaluation")}}(String(e),String(h));if(null===a)return!1;return"regex"===f?a:!a}case"gt":case"gte":case"lt":case"lte":{let a="number"==typeof e?e:parseFloat(String(e)),b="number"==typeof h?h:null!=h?parseFloat(String(h)):0/0;if(Number.isFinite(a)&&Number.isFinite(b))return j(b,a,f);return j(String(h),String(e),f)}case"is_date_after":case"is_date_before":{let a=cT(e),b=cC(()=>cS(h));return"is_date_before"===f?b<a:b>a}case"semver_eq":return 0===l();case"semver_neq":return 0!==l();case"semver_gt":return l()>0;case"semver_gte":return l()>=0;case"semver_lt":return 0>l();case"semver_lte":return 0>=l();case"semver_tilde":return m(cP(String(e),g));case"semver_caret":return m(cQ(String(e),g));case"semver_wildcard":return m(cR(String(e),g));default:throw new cB(`Unknown operator: ${f}`)}}(a,b,c)}catch(b){throw b instanceof cB&&"missing_context"===b.reason&&cU(a,c),b}}(a,b,{warnFunction:c,propertyMatchingVersion:d})}async function c8(a,b,c,d=!1,e,f){let g=String(a.value);if(!(g in c))throw new c1(`cohort ${g} not found in local cohorts - likely a static cohort that requires server evaluation`);let h=c[g],i=await c9(h,b,c,d,e,f);return"not_in"===a.operator?!i:i}async function c9(a,b,c,d=!1,e,f){let g,h;if(!a||0===Object.keys(a).length)return!0;let i="property"===a.type?"AND":a.type;if("AND"!==i&&"OR"!==i)throw new c1(`Unsupported cohort property group type: ${a.type}`);let j=a.values;if(!j||0===j.length)return"AND"===i;if("values"in j[0]){for(let a of j)try{let g=await c9(a,b,c,d,e,f);if("AND"===i){if(!g)return!1}else if(g)return!0}catch(b){if(b instanceof c1)throw b;if(b instanceof cB)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),g=c3(g,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b&&(h=b);else throw b}if(g)throw c4(new cB("Can't match cohort without a given cohort property value",g),h);return"AND"===i}for(let a of j)try{let g;if("cohort"===a.type)g=await c8(a,b,c,d,e,f);else if("flag"===a.type){if(!e)throw new cB(`Flag dependency '${a.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);g=await e(a)}else g=c7(a,b,void 0,f);let h=a.negation||!1;if("AND"===i){if(!g&&!h||g&&h)return!1}else if(g&&!h||!g&&h)return!0}catch(b){if(b instanceof c1)throw b;if(b instanceof cB)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),g=c3(g,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b&&(h=b);else throw b}if(g)throw c4(new cB("can't match cohort without a given cohort property value",g),h);return"AND"===i}let da=["--unhandled-rejections","--unhandled_rejections"],db=new Set(["throw","strict","warn","warn-with-error-code","none"]),dc=[...globalThis.process?.execArgv??[]],dd=globalThis.process?.env?.NODE_OPTIONS;function de(a){let b;for(let c=0;c<a.length;c++){let d=a[c],e=da.find(a=>d===a||d.startsWith(`${a}=`));if(!e)continue;let f=d===e?a[++c]:d.slice(e.length+1);db.has(f)&&(b=f)}return b}let df=function(a=dc,b=dd){return de(a)??de(function(a){let b=[],c="",d=!1;for(let e=0;e<a.length;e++){let f=a[e];"\\"===f&&d&&e+1<a.length?c+=a[++e]:" "!==f||d?'"'===f?d=!d:c+=f:c&&(b.push(c),c="")}return c&&b.push(c),b}(b??""))??"throw"}(),dg={mechanism:{type:"onunhandledrejection",handled:!1}},dh={mechanism:{type:"onuncaughtexception",handled:!1}},di=new Set(["HANGING_PROMISE_REJECTION","NEXT_PRERENDER_INTERRUPTED","DYNAMIC_SERVER_USAGE","BAILOUT_TO_CLIENT_SIDE_RENDERING"]),dj=Symbol.for("react.postpone"),dk=Symbol.for("next.unhandledRejectionFilter"),dl=Symbol.for("posthog-node.exception-autocapture.v1"),dm=globalThis;function dn(a){return"function"==typeof a&&!0===a._posthogErrorHandler}function dp(a){return"object"==typeof a&&null!==a||"function"==typeof a}function dq(a){return Object.assign(a,{_posthogErrorHandler:!0})}function dr(a){return a.listeners("unhandledRejection").some(a=>!dn(a))}function ds(a,b){return function a(b,c=0){try{if(!dp(b))return!1;if(b.$$typeof===dj||"string"==typeof b.digest&&di.has(b.digest))return!0;return c<5&&a(b.cause,c+1)}catch{return!1}}(a)||"unhandledRejection"===b&&function(a){try{return dp(a)&&"AbortError"===a.name}catch{return!1}}(a)}function dt(a){let b=new Map;for(let c of a.clients){let a=b.get(c.key);a&&(void 0!==a.getContext()||void 0===c.getContext())||b.set(c.key,c)}for(let[c,d]of a.retired)b.has(c)||b.set(c,d);return[...b.values()]}function du(a){"function"==typeof globalThis.setImmediate?setImmediate(a):setTimeout(a,0)}function dv(a,b,c,d){let e=a.capturedThisTurn.get(b)??new Map;e.has(c)||e.set(c,d),a.capturedThisTurn.set(b,e),a.turnResetScheduled||(a.turnResetScheduled=!0,du(()=>{du(()=>{a.capturedThisTurn.clear(),a.turnResetScheduled=!1})}))}function dw(a,b,c,d){let e=a.capturedThisTurn.get(b),f=[];for(let g of dt(a))e?.has(g.key)||d?.has(g.key)||(dv(a,b,g.key,"autocapture"),g.capture(b,c),f.push(g));return f}function dx(a,b){return a.deferred.get(b.exception)!==b?[]:(a.deferred.delete(b.exception),b.runInContext(()=>dw(a,b.exception,b.hint,b.skipKeys)))}function dy(a,b,c){let d;if(void 0!==(d=a.capturedThisTurn.get(b))&&dt(a).every(a=>d.has(a.key))||a.deferred.has(b))return;let e={exception:b,hint:c,skipKeys:new Set(a.capturedThisTurn.get(b)?.keys()),runInContext:function(){try{let a=globalThis.process,b=a?.getBuiltinModule?.("node:async_hooks"),c=b?.AsyncLocalStorage?.snapshot?.();if(c)return c}catch{}return a=>a()}()};a.deferred.set(b,e),du(()=>dx(a,e))}async function dz(a,b){try{console.error(b)}catch{}dE();let c=new Set([...a.clients,...a.retired.values()]);await Promise.all([...c].map(a=>a.shutdown().catch(()=>void 0))),globalThis.process.exit(1)}function dA(a,b,c,d){let e="unhandledRejection"===c?dg:dh;if(!d){ds(b,c)||dy(a,b,e);return}let f=a.deferred.get(b);f?dx(a,f):dw(a,b,e)}function dB(a){try{return String(a)}catch{return typeof a}}function dC(a){let b=globalThis.process;dm[dk]&&"function"==typeof b.rawListeners&&b.rawListeners("unhandledRejection").includes(a)&&(Object.getPrototypeOf(b).removeListener.call(b,"unhandledRejection",a),b.listeners("unhandledRejection").includes(a)||b.prependListener("unhandledRejection",a))}function dD(a){let b=globalThis.process,c=[],d=(a,d)=>{b.on(a,d),c.push(()=>b.removeListener(a,d))},e=()=>c.forEach(a=>a());if("strict"===a.mode){let c=(b,c)=>dA(a,b,c,!0);return d("uncaughtExceptionMonitor",c),{remove:e,areInstalled:()=>b.listeners("uncaughtExceptionMonitor").includes(c)}}let f=dq((b,c)=>{let d=0===globalThis.process.listeners("uncaughtException").filter(a=>"domainUncaughtExceptionClear"!==a.name&&!dn(a)).length;dA(a,b,c,d),d&&!a.calledFatalError&&(a.calledFatalError=!0,dz(a,b))});d("uncaughtException",f);let g="throw"===a.mode||"warn-with-error-code"===a.mode,h=g&&!b.versions?.bun,i=()=>b.listeners("unhandledRejection").includes(j),j=dq(b=>{g&&!dr(globalThis.process)&&i()?function(a,b){let c=globalThis.process;if("warn-with-error-code"===a.mode){c.emitWarning(`Unhandled promise rejection: ${dB(b)}`,"UnhandledPromiseRejectionWarning"),c.exitCode=1,ds(b,"unhandledRejection")||dw(a,b,dg);return}if(c.versions?.bun){c.exitCode=1,dw(a,b,dg),a.calledFatalError||(a.calledFatalError=!0,dz(a,b));return}let d=b instanceof Error?b:Object.assign(Error(`This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "${dB(b)}".`),{name:"UnhandledPromiseRejection",code:"ERR_UNHANDLED_REJECTION"}),e=c.emit;e.call(c,"uncaughtExceptionMonitor",d,"unhandledRejection"),e.call(c,"uncaughtException",d,"unhandledRejection")}(a,b):ds(b,"unhandledRejection")||dy(a,b,dg)});return d("newListener",dq((a,c)=>{dn(c)||("unhandledRejection"===a?(i()||b.prependListener("unhandledRejection",j),queueMicrotask(()=>{let a;(a="function"==typeof b.rawListeners?b.rawListeners("unhandledRejection"):[]).includes(j)&&a[0]!==j&&(b.removeListener("unhandledRejection",j),b.prependListener("unhandledRejection",j)),dC(j)})):"Next.UnhandledRejectionFilter.MacguffinEvent"===a&&queueMicrotask(()=>{i()||b.prependListener("unhandledRejection",j)}))})),h?(d("removeListener",dq(a=>{"unhandledRejection"===a&&i()&&!dr(b)&&b.removeListener("unhandledRejection",j)})),dr(b)&&b.prependListener("unhandledRejection",j)):b.prependListener("unhandledRejection",j),dC(j),c.push(()=>{b.removeListener("unhandledRejection",j),"function"==typeof b.rawListeners&&b.rawListeners("unhandledRejection").includes(j)&&Object.getPrototypeOf(b).removeListener.call(b,"unhandledRejection",j)}),{remove:e,areInstalled:()=>b.listeners("uncaughtException").includes(f)&&(h||i())}}function dE(){let a=new Set,b=dm[dl];if(b)for(let c of[...b.deferred.values()])dx(b,c).forEach(b=>a.add(b));return a}let dF=Symbol("capturedContext");function dG(a,b,c,d,e){if(b>c&&(d.warn("min cannot be greater than max."),b=c),y(a))if(a>c)return d.warn(" cannot be greater than max: "+c+". Using max value instead."),c;else return a<b?(d.warn(" cannot be less than min: "+b+". Using min value instead."),b):a;return d.warn(" must be a number. using max or fallback. max: "+c+", fallback: "+e),dG(e??c,b,c,d)}class dH{constructor(a){this._buckets={},this._onBucketRateLimited=a._onBucketRateLimited,this._bucketSize=dG(a.bucketSize,0,100,a._logger),this._refillRate=dG(a.refillRate,0,this._bucketSize,a._logger),this._refillInterval=dG(a.refillInterval,0,864e5,a._logger)}_applyRefill(a,b){let c=Math.floor((b-a.lastAccess)/this._refillInterval);if(c>0){let b=c*this._refillRate;a.tokens=Math.min(a.tokens+b,this._bucketSize),a.lastAccess=a.lastAccess+c*this._refillInterval}}consumeRateLimit(a){let b=Date.now(),c=String(a),d=this._buckets[c];return d?this._applyRefill(d,b):(d={tokens:this._bucketSize,lastAccess:b},this._buckets[c]=d),0===d.tokens||(d.tokens--,0===d.tokens&&this._onBucketRateLimited?.(a),0===d.tokens)}stop(){this._buckets={}}}var dI=am;let dJ=class a{constructor(a,b,c){this.client=a,this._exceptionAutocaptureEnabled=b.enableExceptionAutocapture||!1,this._logger=c,this._rateLimiter=new dH({...function(a={}){return{refillRate:a.exceptionRateLimiterRefillRate??a.__exceptionRateLimiterRefillRate??1,bucketSize:a.exceptionRateLimiterBucketSize??a.__exceptionRateLimiterBucketSize??10}}(b),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(a){return a===Object(a)&&!s(a)&&"__posthog_previously_captured_error"in a&&!0===a.__posthog_previously_captured_error}static async buildEventMessage(a,b,c,d,e,f){let g,h=(g=f?{...f,properties:{...f.properties}}:null,a=>Object.assign(a,{[dF]:g})),i={...e},j=a.buildFromUnknown(b,c);j.$exception_list=await a.modifyFrames(j.$exception_list);let k=dI.getInjectedReleaseId();return k&&(i.$release_id=k),h({event:"$exception",distinctId:d,properties:{...j,...i},_originatedFromCaptureException:!0})}get destinationKey(){return`${this.client.apiKey}@${this.client.host}`}startAutocaptureIfEnabled(){this.isEnabled()&&(this._autocaptureClient={key:this.destinationKey,capture:(a,b)=>this.onException(a,b),getContext:()=>this.client.getContext(),flush:()=>this.client.flush(),shutdown:()=>this.client.shutdown(2e3)},this._stopAutocapture=function(a,b=df){if(!globalThis.process?.on)return()=>void 0;let c=dm[dl];if(c)c.listeners.areInstalled()||(c.listeners.remove(),c.listeners=dD(c));else{let a={mode:b,clients:new Set,retired:new Map,capturedThisTurn:new Map,deferred:new Map,turnResetScheduled:!1,calledFatalError:!1,listeners:{remove:()=>void 0,areInstalled:()=>!0}};a.listeners=dD(a),dm[dl]=a,c=a}c.clients.add(a),c.retired.delete(a.key);let d=c;return()=>{d.clients.delete(a)&&([...d.clients].some(b=>b.key===a.key)||d.retired.set(a.key,a))}}(this._autocaptureClient))}claimExplicitCapture(a){var b;let c;return b=this.destinationKey,!(c=dm[dl])||c.capturedThisTurn.get(a)?.get(b)!=="autocapture"&&(dv(c,a,b,"app"),c.deferred.get(a)?.skipKeys.add(b),!0)}capturePendingExceptions(){for(let a of dE())a!==this._autocaptureClient&&this.client.addPendingPromise(a.flush().catch(()=>void 0))}onException(b,c){this.client.addPendingPromise((async()=>{if(!a.isPreviouslyCapturedError(b)){let d=await a.buildEventMessage(this.client.getErrorPropertiesBuilder(),b,c,void 0,void 0,this.client.getContext()),e=d.properties,f=e?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(f)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:f}):this.client._capturePreparedEvent(d,!1)}})().catch(a=>{this._logger.error("Failed to capture an exception:",a)}))}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop(),this.capturePendingExceptions(),this._stopAutocapture?.(),this._stopAutocapture=void 0}},dK=/^[0-9a-f]{32}$/i,dL=/^[0-9a-f]{16}$/i,dM=Symbol.for("opentelemetry.js.api.1"),dN=Symbol.for("OpenTelemetry Context Key SPAN");async function dO(){try{let a=globalThis[dM],b=a?.context?.active().getValue(dN),c=b?.spanContext(),d=c?.traceId,e=c?.spanId;if("string"==typeof d&&"string"==typeof e&&dK.test(d)&&dL.test(e)&&!/^0+$/.test(d)&&!/^0+$/.test(e))return{$trace_id:d.toLowerCase(),$span_id:e.toLowerCase()}}catch{}return{}}class dP{getProperty(a){return this._memoryStorage[a]}setProperty(a,b){this._memoryStorage[a]=null!==b?b:void 0}constructor(){this._memoryStorage={}}}let dQ=Symbol.for("posthog-node.context-listeners"),dR=globalThis,dS=dR[dQ]??=new WeakMap;function dT(a,b=!1){for(let c of dS.get(a)??[])try{c(b)}catch{}}function dU(a){dT(a,!0)}let dV="analytics";class dW extends Error{constructor({requestId:a,drops:b,retryExhausted:c,cause:d}){super(dW.buildMessage(a,b,c,d)),this.name="CaptureV1Error",this.requestId=a,this.drops=b,this.retryExhausted=c,this.cause=d}static buildMessage(a,b,c,d){let e=`Capture V1 batch ${a} did not fully deliver: ${b.length} dropped, ${c.length} undelivered`;return d instanceof Error&&(e+=` (${d.message})`),e}}function dX(a){if("boolean"==typeof a)return a;if("number"==typeof a)return 0!==a;if("string"==typeof a){let b=a.trim().toLowerCase();if("true"===b||"1"===b)return!0;if("false"===b||"0"===b)return!1}}let dY=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:dX},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:dX},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:dX},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(a){return"string"==typeof a?a:void 0}}],dZ=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function d$(a,b,c){void 0===c||b in a||(a[b]=c)}function d_(a){var b;let c={..."object"==typeof(b=a.properties)&&null!==b&&!Array.isArray(b)?a.properties:{}},d={};for(let{property:a,optionKey:b,coerce:e}of dY)if(a in c){let f=e(c[a]);void 0!==f&&(d[b]=f),delete c[a]}let e={};for(let{property:a,field:b}of dZ)if(a in c){let d=c[a];"string"==typeof d&&(e[b]=d),delete c[a]}return delete c.$lib,delete c.$lib_version,d$(c,"$set",a.$set),d$(c,"$set_once",a.$set_once),{event:String(a.event??""),uuid:String(a.uuid??""),distinct_id:String(a.distinct_id??""),timestamp:function(a){if("string"==typeof a){let b=new Date(a);if(Number.isNaN(b.getTime()))return new Date().toISOString();let c=b.toISOString(),d=a.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return d&&d.length>3?c.replace(/\.\d{3}Z$/,`.${d}Z`):c}if(a instanceof Date)return Number.isNaN(a.getTime())?new Date().toISOString():a.toISOString();let b=null==a?new Date:new Date(a);return Number.isNaN(b.getTime())?new Date().toISOString():b.toISOString()}(a.timestamp),...e,options:d,properties:c}}let d0=new Set([404,408,429,500,502,503,504]);class d1{constructor(a,b){this.config=a,this.maxBackoffMs=a.maxBackoffMs??3e4,this.fetchFn=b.fetch,this.onError=b.onError,this.now=b.now??Date.now,this.sleep=b.sleep??(a=>new Promise(b=>aM(b,a))),this.generateRequestId=b.generateRequestId??aW,this.compress=b.compress??aR}async sendV1Batch(a){if(0===a.length)return;let b=this.generateRequestId(),c=new Date(this.now()).toISOString(),{batch:d}=function(a,{createdAt:b,historicalMigration:c}){let d={created_at:b,batch:a.map(d_)};return c&&(d.historical_migration=!0),d}(a,{createdAt:c,historicalMigration:this.config.historicalMigration}),e=`${this.config.host}/i/v1/analytics/events`,f=[],g=d,h=Math.max(1,this.config.maxAttempts);for(let a=1;a<=h;a++){let d,i,j=a===h,k=n({created_at:c,...this.config.historicalMigration?{historical_migration:!0}:{},batch:g});try{let{response:c,signal:h}=d=await this.sendOnce(e,k,a,b),{status:l}=c;if(l<200||l>=300)if(!j&&d0.has(l)){let b=this.parseRetryAfter(c);await d.waitFor(d.cancelBody()).catch(()=>{}),i=this.backoffDelay(a,b)}else{let a=await this.buildHttpError(c,l,d.waitFor);return this.surfaceBatchFailure(b,f,g,a)}else{let e;try{e=await d.waitFor(this.parseResponse(c))}catch(a){if(h.aborted)throw a;return this.surfaceBatchFailure(b,f,g,Error(`Capture V1 returned an unparseable ${l} response body`))}let k=this.classify(g,e,f);if(0===k.length)return this.surfacePartialDrops(b,f);if(j)return void this.onError(new dW({requestId:b,drops:f,retryExhausted:k.map(a=>a.uuid)}));g=k;let m=this.parseRetryAfter(c);i=this.backoffDelay(a,m)}}catch(c){if(d&&!d.signal.aborted)throw c;if(j)return this.surfaceBatchFailure(b,f,g,c);i=this.backoffDelay(a)}finally{d?.cleanup()}void 0!==i&&await this.sleep(i)}}async sendOnce(a,b,c,d){let e,f=this.buildHeaders(c,d),g=b;if(this.config.compressionEnabled){let a=await this.compress(b,this.config.isDebug);null!==a&&(g=a,f["Content-Encoding"]="gzip")}let h=new AbortController,i="waiting for response headers",j=new Promise((a,b)=>{e=aM(()=>{let a=Error(`Capture V1 request timed out ${i} after ${this.config.requestTimeoutMs}ms`);a.name="AbortError",b(a),h.abort(a)},this.config.requestTimeoutMs)});try{let b,c=this.fetchFn(a,{method:"POST",headers:f,body:g,signal:h.signal}),d=!1;c.then(a=>{h.signal.aborted&&!d&&this.cancelBody(a)}).catch(()=>{});let k=await Promise.race([c,j]);d=!0,i="while reading the response body";let l=!1,m=()=>b??=this.cancelBody(k);return{response:k,signal:h.signal,waitFor:a=>Promise.race([a,j]),cancelBody:m,cleanup:()=>{!l&&(l=!0,clearTimeout(e),h.signal.aborted&&m())}}}catch(a){throw clearTimeout(e),a}}buildHeaders(a,b){let c=`${this.config.libraryId}/${this.config.libraryVersion}`,d={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":c,"PostHog-Attempt":String(a),"PostHog-Request-Id":b,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(d["User-Agent"]=this.config.userAgent),d}classify(a,b,c){let d=b.results??{},e=[];for(let b of a){let a=d[b.uuid];a&&("drop"===a.result?c.push({uuid:b.uuid,details:a.details??void 0}):"retry"===a.result&&e.push(b))}return e}backoffDelay(a,b){let c=Math.min(this.config.initialRetryDelayMs*2**(a-1),this.maxBackoffMs);return void 0===b?c:Math.max(c,Math.min(b,this.maxBackoffMs))}parseRetryAfter(a){let b=a.headers?.get("Retry-After");if(!b)return;let c=b.trim();if(/^\d+$/.test(c)){let a=parseInt(c,10);return Number.isFinite(a)&&a>0?1e3*a:void 0}let d=Date.parse(c);if(Number.isNaN(d))return;let e=d-this.now();return e>0?e:void 0}async parseResponse(a){let b=JSON.parse(await a.text());if("object"!=typeof b||null===b||Array.isArray(b))throw Error("unexpected response shape");let c=b.results;if(void 0!==c&&("object"!=typeof c||null===c||Array.isArray(c)))throw Error("unexpected results shape");return{results:c??{}}}async buildHttpError(a,b,c){let d="";try{d=(await c(a.text())).slice(0,512)}catch{}let e=d?`: ${d}`:"";return Error(`Capture V1 request failed with HTTP ${b}${e}`)}surfaceBatchFailure(a,b,c,d){this.onError(new dW({requestId:a,drops:b,retryExhausted:c.map(a=>a.uuid),cause:d}))}surfacePartialDrops(a,b){b.length>0&&this.onError(new dW({requestId:a,drops:b,retryExhausted:[]}))}async cancelBody(a){try{await a.body?.cancel()}catch{}}}let d2="ai-capture",d3="/i/v0/ai/batch/",d4=new TextEncoder;function d5(a){return d4.encode(n(a)).length}class d6 extends Error{constructor(a){super(a.message,void 0===a.cause?void 0:{cause:a.cause}),this.name=function(a,b){if("missing_secret_key"===b||401===a)return"missing_api_key";if(void 0===a)return"network_error"===b?"service_unavailable":b.startsWith("invalid_")||d7.has(b)?"validation_error":"application_error";if("attachment_upload_failed"===b)return a>=500?"service_unavailable":"application_error";switch(a){case 400:return"validation_error";case 403:return"invalid_permission";case 404:return"not_found";case 409:return"template_outdated"===b?"validation_error":"concurrent_idempotent_requests";case 422:return"idempotency_key_reused"===b?"invalid_idempotent_request":"validation_error";case 429:return"quota_limited"===b?"monthly_quota_exceeded":"rate_limit_exceeded";case 503:return"service_unavailable";default:return"application_error"}}(a.statusCode,a.code),this.code=a.code,this.statusCode=a.statusCode,this.why=a.why,this.fix=a.fix,this.docsUrl=a.docsUrl,this.field=a.field,this.retryAfterMs=a.retryAfterMs}}let d7=new Set(["too_many_attachments","message_too_large"]),d8=/^[A-Za-z0-9+/]*={0,2}$/;async function d9(a){return Promise.all(a.map(async(a,b)=>({...a,sha256:await ed(a.bytes),field:`attachments__${b}`})))}function ea({sha256:a,filename:b,contentType:c,contentId:d}){return{sha256:a,filename:b,...void 0!==c&&{content_type:c},...void 0!==d&&{content_id:d}}}function eb(a,b){var c,d;let e;if("object"!=typeof a||null===a||Array.isArray(a)||ArrayBuffer.isView(a))throw ee("An attachment is an object with filename and content. Pass the file's bytes as its content.",`attachments__${b}`);let{filename:f,content:g,contentType:h,contentId:i,path:j,...k}=a;if(void 0!==j)throw ee("PostHog can't fetch an attachment from a path or URL. Read the file and pass its content instead.",`attachments__${b}__path`);let l=Object.entries(k).find(([,a])=>void 0!==a)?.[0];if(void 0!==l)throw ee(`An attachment takes filename, content, contentType and contentId, not ${l}.`,`attachments__${b}__${l}`);if("string"!=typeof f||""===f)throw ee("An attachment needs a filename, such as 'invoice.pdf'.",`attachments__${b}__filename`);if("string"!=typeof g&&!(g instanceof Uint8Array))throw ee("An attachment needs content: a Buffer, a Uint8Array or a Base64 string.",`attachments__${b}__content`);if("string"==typeof g&&!((c=g).length%4==0&&d8.test(c)))throw ee("An attachment's content string must be Base64. Pass text as a Buffer or a Uint8Array.",`attachments__${b}__content`);if(void 0!==h&&"string"!=typeof h)throw ee("An attachment's contentType must be a string, such as 'application/pdf'.",`attachments__${b}__contentType`);if(void 0!==i&&"string"!=typeof i)throw ee("An attachment's contentId must be a string.",`attachments__${b}__contentId`);let m="string"==typeof g?(e=(d=g).endsWith("==")?2:+!!d.endsWith("="),d.length/4*3-e):g.byteLength;if(0===m)throw ee("An attachment needs at least one byte.",`attachments__${b}__content`);return{filename:f,content:g,size:m,...void 0!==h&&{contentType:h},...void 0!==i&&{contentId:i}}}function ec(a,b,c){if(0===a.length)return;let d=new TextEncoder;if([...a,...b.map(a=>d.encode(a).byteLength)].reduce((a,b)=>a+Math.ceil(4*Math.ceil(b/3)*78/76),65536+75*Math.ceil(d.encode(c).byteLength/42))>4e7)throw new d6({code:"message_too_large",message:"These files make the email larger than 40 MB after Base64 encoding, about 29 MB of files, so no email was sent.",field:"attachments",why:"PostHog's email provider takes emails up to 40 MB, and Base64 encoding makes each file about a third larger.",fix:"Send fewer or smaller files, or link to large files from the email body."})}async function ed(a){return Array.from(new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",a)),a=>a.toString(16).padStart(2,"0")).join("")}function ee(a,b){return new d6({code:"invalid_attachment",message:a,field:b})}let ef="https://us.posthog.com",eg="https://eu.posthog.com",eh={"https://us.i.posthog.com":ef,"https://us.posthog.com":ef,"https://app.posthog.com":ef,"https://eu.i.posthog.com":eg,"https://eu.posthog.com":eg},ei=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ej=/^[\x21-\x7e]{1,255}$/,ek=/^[a-zA-Z0-9_-]{1,400}$/,el={to:!0,distinctId:!0,idempotencyKey:!0,maxRetries:!0},em={name:"templateId",fields:ey(el,{templateId:!0,templateData:!0}),why:"A template made in PostHog sets its own sender, subject and content, and follows the project's engagement setting.",howToSend:"send a template made in PostHog with templateId"},en={name:"templateKey",fields:ey(el,{templateKey:!0,subject:!0,from:!0,replyTo:!0,captureEngagement:!0,cc:!0,bcc:!0,attachments:!0,sensitive:!0,tracking:!0,html:!0,text:!0,react:!0}),why:"A send with templateKey takes its content from your code.",howToSend:"send content from your code with templateKey"};class eo{constructor(a,b){this.inFlight=new Set,this.config=a,this.hooks=b}send(a,...b){return this.track(this.sendUntracked(a,b))}get(a){return this.track(this.getUntracked(a))}setPreferences(a){return this.track(this.setPreferencesUntracked(a))}track(a){return this.inFlight.add(a),a.finally(()=>this.inFlight.delete(a)),a}async drain(){for(;this.inFlight.size>0;)await Promise.all(this.inFlight)}async sendUntracked(a,b){try{let e,f;var c,d=b;if(d.some(a=>void 0!==a))throw new d6({code:"invalid_form",message:"send takes one options object, so no email was sent. Put idempotencyKey and every other option in it."});let g=function(a,b){let c=a??{},{to:d,distinctId:e,idempotencyKey:f,maxRetries:g}=c;if("string"!=typeof d||!d.trim())throw ez("invalid_recipient","to must be one email address as a nonempty string.","to");if(void 0!==e&&("string"!=typeof e||!e))throw ez("invalid_distinct_id","distinctId must be a nonempty string.","distinctId");let{content:h,files:i}=function(a,b){if(void 0===a.templateId==(void 0===a.templateKey))throw new d6({code:"invalid_form",message:"Send either templateId, or templateKey with subject and html, text or react."});return void 0===a.templateKey?{content:function(a,b){let{templateId:c,templateData:d}=a;if("string"!=typeof c||!ei.test(c))throw ez("invalid_template_id","templateId must be the template's UUID.","templateId");if(void 0!==d&&("object"!=typeof d||null===d||Array.isArray(d)))throw ez("invalid_template_data","templateData must be an object.","templateData");return ex(a,em,en),{template_id:c.toLowerCase(),message_data:d??{},...void 0!==b&&{distinct_id:b}}}(a,b),files:[]}:function(a,b){let{templateKey:c,subject:d,html:e,text:f,react:g}=a;if("string"!=typeof c||!ek.test(c))throw ez("invalid_template_key","templateKey can only have letters, digits, hyphens (-) and underscores (_), at most 400.","templateKey");if(ex(a,en,em),"string"!=typeof d)throw ez("invalid_form","A send with templateKey needs a subject.","subject");if(void 0!==e&&"string"!=typeof e)throw ez("invalid_form","html must be a string.","html");if(void 0!==f&&"string"!=typeof f)throw ez("invalid_form","text must be a string.","text");if(void 0!==g){var h=g,i=e;if(!et(h))throw ez("invalid_form","react must be a React element, such as <WelcomeEmail />.","react");if(void 0!==i)throw new d6({code:"invalid_form",message:"A send with react renders its own html, so it takes no html. No email was sent.",field:"html",fix:"Remove html to send the rendered react element, or remove react to send your html."})}else if(void 0===e&&void 0===f)throw ez("invalid_form","A send with templateKey needs html, text or react.","html");let j=void 0===a.attachments?[]:function(a,{html:b,text:c,subject:d}){if(!Array.isArray(a))throw ee("attachments must be a list of files.","attachments");if(a.length>10)throw new d6({code:"too_many_attachments",message:"An email carries at most 10 files, so no email was sent.",field:"attachments",fix:"Attach at most 10 files, and link to any others from the email body."});let e=Array.from(a,eb);return ec(e.map(({size:a})=>a),[b??"",c||b||""],d),e.map(({content:a,size:b,...c})=>({...c,bytes:"string"==typeof a?function(a){if("u">typeof Buffer)return Buffer.from(a,"base64");let b=atob(a),c=new Uint8Array(b.length);for(let a=0;a<b.length;a++)c[a]=b.charCodeAt(a);return c}(a):new Uint8Array(a)}))}(a.attachments,{html:e,text:f,subject:d});return{content:{template_key:c,subject:d,...void 0!==e&&{html:e},...void 0!==f&&{text:f},...function(a){let{from:b,replyTo:c,cc:d,bcc:e,captureEngagement:f,sensitive:g,tracking:h}=a;return{...void 0!==b&&{from:b},...void 0!==c&&eq("reply_to",er(c)),...void 0!==d&&eq("cc",er(d)),...void 0!==e&&eq("bcc",er(e)),...void 0!==f&&{capture_engagement:f},...void 0!==g&&{sensitive:g},...void 0!==h&&{tracking:h}}}(a),...void 0!==b&&{distinct_id:b}},files:j}}(a,b)}(c,e);if(void 0!==f&&("string"!=typeof f||!ej.test(f)))throw ez("invalid_idempotency_key","idempotencyKey must be 1 to 255 visible ASCII characters without spaces.","idempotencyKey");if(void 0!==g&&!ep(g))throw ez("invalid_max_retries","maxRetries must be a nonnegative integer.","maxRetries");return{content:JSON.parse(n({...h,to:d})),files:i,react:et(c.react)?c.react:void 0,idempotencyKey:f??globalThis.crypto.randomUUID(),maxRetries:ep(g)?g:b}}(a,this.config.maxRetries),{appHost:h,secretKey:i}=this.connect("no email was sent","Sending email needs secretKey, a project secret API key with the transactional_email:write scope."),j=void 0===g.react?g.content:await eu(g.content,g.react,this.config.requestTimeoutMs);void 0!==g.react&&(c=g.files,e="string"==typeof j.html?j.html:"",f="string"==typeof j.text?j.text:"",ec(c.map(({bytes:a})=>a.byteLength),[e,f||e],"string"==typeof j.subject?j.subject:""));let k=await this.uploadAttachments(g,h,i),l=n({...j,...eq("attachments",k)}),m=this.headers(i,{"Content-Type":"application/json","Idempotency-Key":g.idempotencyKey}),o=await this.withRetries(g.maxRetries,async()=>(function({status:a,text:b,retryAfterMs:c}){let d=eD(eA(b));if(a>=200&&a<300){let b=eC(d.message_id);if(!b)throw new d6({code:"api_error",message:"PostHog answered without a message ID.",statusCode:a});let c=[];if(Array.isArray(d.warnings))for(let a of d.warnings)null!==a&&"object"==typeof a&&c.push({code:eC(a.code)??"warning",message:eC(a.detail)??eC(a.message)??"",fix:eC(a.fix)});return{id:b,replayed:!0===d.replayed,warnings:c}}throw eE(d,a,c)})(await this.request(h+"/api/projects/@current/messaging/send/email/","POST",m,l)));for(let a of o.warnings)this.hooks.logger.warn(`PostHog email warning ${a.code}: ${a.message}`);return{data:o,error:null}}catch(a){return{data:null,error:eF(a,"Sending the email failed unexpectedly.")}}}async getUntracked(a){try{if("string"!=typeof a||!ei.test(a))throw ez("invalid_message_id","id must be the message ID that send() returned.","id");let{appHost:b,secretKey:c}=this.connect("no email status was read","Reading an email status needs secretKey, a project secret API key with the transactional_email:read or transactional_email:write scope."),d=b+"/api/projects/@current/messaging/emails/{messageId}/".replace("{messageId}",a.toLowerCase()),e=this.headers(c,{});return{data:await this.withRetries(this.config.maxRetries,async()=>(function({status:a,text:b,retryAfterMs:c}){let d=eD(eA(b));if(a<200||a>=300)throw eE(d,a,c);let e=eC(d.id),f=eC(d.status),g=eC(d.created_at),h=eC(d.status_at);if(!e||!f||!g||!h)throw new d6({code:"api_error",message:"PostHog answered without an email status.",statusCode:a});return{id:e,status:f,createdAt:g,statusAt:h,reason:eC(d.reason)??null}})(await this.request(d,"GET",e))),error:null}}catch(a){return{data:null,error:eF(a,"Reading the email status failed unexpectedly.")}}}async uploadAttachments({files:a,maxRetries:b},c,d){if(0===a.length)return[];let e=await d9(a),f=new Map;for(let a of e)f.has(a.sha256)||f.set(a.sha256,a);let g=[...f.values()],h=n({files:g.map(({sha256:a,bytes:b})=>({sha256:a,size:b.byteLength}))}),i=this.headers(d,{"Content-Type":"application/json"}),j=await this.withRetries(b,async()=>(function({status:a,text:b,retryAfterMs:c},d){var e,f,g;let h=eD(eA(b));if(404===a)throw eE({code:"not_found",...h,attr:eC(h.attr)??"attachments"},a,c);if(a<200||a>=300){let b;throw eE({...h,attr:(e=eC(h.attr),f=d,(b=void 0===e?null:/^files(?:__(\d+))?(?:__|$)/.exec(e))?void 0===b[1]?"attachments":f[Number(b[1])]?.field??"attachments":e)},a,c)}let i=Array.isArray(h.files)?h.files.map(eD):[],j=[];for(let{sha256:b,bytes:c,field:e}of d){let d=i.find(a=>a.sha256===b);if(d?.status==="present")continue;let f=eC(d?.url);if(d?.status!=="upload"||!f||!(null!==(g=d.headers)&&"object"==typeof g&&!Array.isArray(g)&&Object.values(g).every(a=>"string"==typeof a)))throw new d6({code:"api_error",message:"PostHog answered without telling where to upload every file.",statusCode:a});j.push({url:f,headers:d.headers,bytes:c,field:e})}return j})(await this.request(c+"/api/projects/@current/messaging/attachments/uploads/","POST",i,h),g)),k=c.toLowerCase().startsWith("http://")?void 0:j.find(({url:a})=>!a.toLowerCase().startsWith("https://"));if(k)throw new d6({code:"api_error",message:`PostHog named an upload URL for ${k.field} that isn't https, so the file would travel unencrypted. No email was sent.`,field:k.field,fix:"Make your PostHog's file storage URL use https. For local development over plain HTTP, set appHost to your http app host."});for(let a of j)await this.withRetries(b,()=>this.uploadFile(a));return e.map(ea)}async uploadFile({url:a,headers:b,bytes:c,field:d}){let e;try{e=await this.request(a,"PUT",b,c,"manual")}catch(a){if(a instanceof Error&&"AbortError"===a.name)throw new d6({code:"network_error",message:`The upload of ${d} timed out after ${this.config.requestTimeoutMs}ms, so no email was sent.`,fix:"Raise emailRequestTimeoutMs on the client, or send smaller files.",field:d,cause:a});throw new d6({code:"network_error",message:`The upload of ${d} didn't reach PostHog's file storage, so no email was sent.`,field:d,cause:a})}if(e.status>=300&&e.status<400)throw new d6({code:"attachment_upload_failed",message:`PostHog's file storage redirected the upload of ${d} elsewhere. The SDK uploads only to the URL PostHog signed, so no email was sent.`,statusCode:e.status,fix:"Make your PostHog's file storage URL point straight at the storage, over https.",field:d});if(e.status<200||e.status>=300)throw new d6({code:"attachment_upload_failed",message:`PostHog's file storage refused the upload of ${d}, so no email was sent. ${function({status:a,text:b}){let c=/<Code>([^<]{1,100})<\/Code>/.exec(b)?.[1],d=/<Message>([^<]{1,300})<\/Message>/.exec(b)?.[1],e=`It answered HTTP ${a}${c?` ${c}`:""}${d?`: ${d}`:""}`;return e.endsWith(".")?e:`${e}.`}(e)}`,statusCode:e.status,fix:"Send the email again. Each send asks for new upload URLs.",field:d,retryAfterMs:e.retryAfterMs})}async setPreferencesUntracked(a){try{let b=function(a){let{to:b,allMarketing:c,topics:d}=a??{};if("string"!=typeof b||!b.trim())throw ez("invalid_recipient","to must be one email address as a nonempty string.","to");if(void 0!==c&&"boolean"!=typeof c)throw ez("invalid_preferences","allMarketing must be true or false.","allMarketing");if(void 0!==d&&("object"!=typeof d||null===d||Array.isArray(d)||!Object.values(d).every(a=>"boolean"==typeof a)))throw ez("invalid_preferences","topics must map each topic key to true or false.","topics");let e=void 0!==d&&Object.keys(d).length>0;if(void 0===c&&!e)throw ez("invalid_preferences","Set allMarketing, topics, or both.","topics");return n({identifier:b,...void 0===c?{}:{all_marketing:c},...e?{topics:d}:{}})}(a),{appHost:c,secretKey:d}=this.connect("no preferences changed","Setting email preferences needs secretKey, a project secret API key with the messaging_preference:write scope."),e=this.headers(d,{"Content-Type":"application/json"});return{data:await this.withRetries(this.config.maxRetries,async()=>(function({status:a,text:b,retryAfterMs:c}){let d=eD(eA(b));if(a<200||a>=300)throw eE(d,a,c);let e=eC(d.identifier),f=d.all_marketing,g=d.topics;if(!e||null!==f&&"boolean"!=typeof f||null===g||"object"!=typeof g||Array.isArray(g)||!Object.values(g).every(a=>"boolean"==typeof a))throw new d6({code:"api_error",message:"PostHog answered without the preferences.",statusCode:a});return{to:e,allMarketing:f,topics:g}})(await this.request(c+"/api/projects/@current/messaging/preferences/","POST",e,b))),error:null}}catch(a){return{data:null,error:eF(a,"Setting the email preferences failed unexpectedly.")}}}connect(a,b){var c,d;let e;if(this.hooks.isDisabled())throw new d6({code:"client_disabled",message:`The PostHog client is disabled, so ${a}.`});if(this.hooks.isClosed())throw new d6({code:"client_closed",message:`The PostHog client is shut down, so ${a}.`});let f=(c=this.config.host,(e="string"==typeof(d=this.config.appHost)?aI(d.trim()):"")?eh[e]??e:eh[aI(c)]);if(!f)throw new d6({code:"missing_app_host",message:"The client's host is not PostHog Cloud, so the client can't tell where to send email. Set appHost to your PostHog app host on the client."});let g=this.config.secretKey?.trim();if(!g)throw new d6({code:"missing_secret_key",message:b});return{appHost:f,secretKey:g}}headers(a,b){let c={Authorization:`Bearer ${a}`,Accept:"application/json",...b};return this.hooks.userAgent&&(c["User-Agent"]=this.hooks.userAgent),this.config.migratedFrom&&(c["X-PostHog-Migrated-From"]=this.config.migratedFrom),c}async withRetries(a,b){for(let c=0;;c++){let d;try{return await b()}catch(a){d=a instanceof d6?a:new d6({code:"network_error",message:"The request to PostHog failed.",cause:a})}let e=function(a,b,c){if(!(b>=c)&&(void 0===a.statusCode?"network_error"===a.code:"attachment_upload_failed"===a.code?429===a.statusCode||a.statusCode>=500:409===a.statusCode?"idempotency_key_in_flight"===a.code:429===a.statusCode?"quota_limited"!==a.code&&"upload_quota_exceeded"!==a.code:503===a.statusCode)&&(void 0===a.retryAfterMs||!(a.retryAfterMs>3e4)))return Math.max(Math.min(3e4,1e3*2**b*(.8+.4*Math.random())),a.retryAfterMs??0)}(d,c,a);if(void 0===e)throw d;await new Promise(a=>setTimeout(a,e))}}async request(a,b,c,d,e){let f,g,h=new AbortController,i=this.config.requestTimeoutMs,j=new Promise((a,b)=>{f=setTimeout(()=>{let a=Error(`Email request timed out after ${i}ms`);a.name="AbortError",b(a),h.abort(a)},i)}),k=Promise.resolve().then(()=>this.hooks.fetch(a,{method:b,headers:c,...void 0===d?{}:{body:d},...e?{redirect:e}:{},signal:h.signal}));k.then(a=>{h.signal.aborted&&Promise.resolve(a.body?.cancel()).catch(()=>{})}).catch(()=>{});try{let a;g=await Promise.race([k,j]);try{a=await Promise.race([g.text(),j])}catch(a){if(g.status>=200&&g.status<300)throw a;return{status:g.status,text:"",retryAfterMs:eB(g)}}return{status:g.status,text:a,retryAfterMs:eB(g)}}finally{clearTimeout(f),h.signal.aborted&&g&&Promise.resolve(g.body?.cancel()).catch(()=>{})}}}function ep(a){return"number"==typeof a&&Number.isInteger(a)&&a>=0}function eq(a,b){return Array.isArray(b)&&0===b.length?{}:{[a]:b}}function er(a){return"string"==typeof a?[a]:a}let es=[Symbol.for("react.element"),Symbol.for("react.transitional.element")];function et(a){return"object"==typeof a&&null!==a&&"$$typeof"in a&&es.includes(a.$$typeof)&&"type"in a&&"props"in a}async function eu(a,b,c){let{render:d,toPlainText:e}=await ew();try{let f=await ev(d(b),c,"Rendering the react element");return{...a,html:f,...void 0===a.text&&{text:e(f)}}}catch(a){throw new d6({code:"react_render_failed",message:"Rendering the react element failed, so no email was sent.",cause:a})}}async function ev(a,b,c){let d,e=new Promise((a,e)=>{d=setTimeout(()=>e(Error(`${c} took longer than ${b}ms.`)),b)});try{return await Promise.race([a,e])}finally{clearTimeout(d)}}async function ew(){try{return await Promise.resolve().then(()=>{let a=Error("Cannot find module '@react-email/render'");throw a.code="MODULE_NOT_FOUND",a})}catch(a){throw new d6({code:"missing_react_renderer",message:"react needs the @react-email/render package, which isn't installed or failed to load, so no email was sent.",fix:"Install @react-email/render with react and react-dom next to posthog-node, or render the email yourself and send html.",cause:a})}}function ex(a,b,c){let d=Object.entries(a).find(([a,c])=>void 0!==c&&!b.fields.has(a))?.[0];if(void 0===d)return;let e=`A send with ${b.name} doesn't take ${d}, so no email was sent.`;if(!c.fields.has(d))throw new d6({code:"invalid_form",message:e,field:d,fix:`Remove ${d} and send again.`});throw new d6({code:"invalid_form",message:e,field:d,why:b.why,fix:`Remove ${d}, or ${c.howToSend}.`})}function ey(...a){return new Set(a.flatMap(a=>Object.keys(a)))}function ez(a,b,c){return new d6({code:a,message:b,field:c})}function eA(a){try{return JSON.parse(a)}catch{return null}}function eB(a){try{return a$(a.headers?.get("retry-after"),Date.now(),Number.MAX_SAFE_INTEGER)}catch{return}}function eC(a){return"string"==typeof a&&a?a:void 0}function eD(a){return null===a||"object"!=typeof a||Array.isArray(a)?{}:a}function eE(a,b,c){return new d6({code:eC(a.code)??"api_error",message:eC(a.detail)??`PostHog answered HTTP ${b}.`,statusCode:b,why:eC(a.why),fix:eC(a.fix),docsUrl:eC(a.docs_url),field:eC(a.attr),retryAfterMs:c})}function eF(a,b){return a instanceof d6?a:new d6({code:"unexpected_error",message:b,cause:a})}let eG=new Set;function eH(a,b){eG.has(a)||(eG.add(a),console.warn(`[PostHog] ${b}`))}class eI extends ba{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(a){this._distinctIdHasSentFlagCalls=new Map(Object.entries(a??{}))}constructor(a,b={}){var c,d;let e,f="string"==typeof a?a.trim():"",g={...b,maxQueueSize:b.maxQueueSize??1e4,flushInterval:b.flushInterval??5e3,host:("string"==typeof(c=b.host)?c.trim():"")||"https://us.i.posthog.com",personalApiKey:("string"==typeof(d=b.secretKey??b.personalApiKey)?d.trim():"")||void 0};if(super(f,g),this._memoryStorage=new dP,this._isShutdown=!1,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this._loggedFlagsResponseWithoutTypedValues=!1,this._experimentExposuresReported=new Map,this.options=g,this.captureMode="v0"===(e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0)||"v1"===e?e:"v0",this.enableFullAiCapture=!0===g.enableFullAiCapture,this.privacyMode=!0===g.privacyMode,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof g.featureFlagsPollingInterval?Math.max(g.featureFlagsPollingInterval,100):null===g.featureFlagsPollingInterval?null:3e4,"number"==typeof g.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(g.waitUntilDebounceMs,0)),"number"==typeof g.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(g.waitUntilMaxWaitMs,0)),!this.disabled&&(g.personalApiKey||g.flagDefinitionCacheProvider)){if(g.personalApiKey?.includes("phc_"))throw Error('A project API key ("phc_...") was provided as secretKey or personalApiKey. Pass the project API key as the first constructor argument. For local evaluation, set secretKey (or the deprecated personalApiKey alias) to a server-only Project Secret API Key ("phs_...") or Personal API Key ("phx_...") with feature flag read access.');!1!==g.enableLocalEvaluation&&(this.featureFlagsPoller=new c5({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:g.personalApiKey,projectApiKey:f,timeout:g.requestTimeout??1e4,host:this.host,fetch:g.fetch,onError:a=>{this._events.emit("error",a)},onLoad:a=>{this._events.emit("localEvaluationFlagsLoaded",a)},onMinimalFlagCalledEvents:a=>{this._minimalFlagCalledEvents=a},customHeaders:this.getCustomHeaders(),cacheProvider:g.flagDefinitionCacheProvider,strictLocalEvaluation:g.strictLocalEvaluation,evaluationContexts:g.evaluationContexts??g.evaluationEnvironments}))}this.errorTracking=new dJ(this,g,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=g.maxCacheSize||5e4}enqueue(a,b,c,d){super.enqueue(a,b,c,d),this.scheduleDebouncedFlush()}_flushEventsAndSpans(a=!1){let b=this.flushWithPendingPromises(),c=[];return(this._traces&&!(a&&this._traces.throttled)&&c.push(this._traces.flush().catch(()=>{})),this._logs&&!(a&&this._logs.throttled)&&c.push(this._logs.flushInBackground()),0===c.length)?b:aO([b,...c]).then(([a])=>{if("rejected"===a.status)throw a.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this.errorTracking.capturePendingExceptions(),this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(a){let b=this._flushEventsAndSpans(a),c=this.options.waitUntil;if(c&&!this._waitUntilCycle)try{c(b.catch(()=>{}))}catch{}return b}_flushMetricsWithinInvocation(){let a=this.options.waitUntil;if(a&&this._metrics)try{a(this._metrics.flushCoalesced().catch(()=>{}))}catch{}}scheduleDebouncedFlush(){let a=this.options.waitUntil;if(!a||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let b,c=new Promise(a=>{b=a});try{a(c)}catch{return}this._waitUntilCycle={resolve:b,startedAt:Date.now(),timer:void 0}}let b=Date.now()-this._waitUntilCycle.startedAt,c=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),b>=c)return void this.resolveWaitUntilFlush();let d=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=aM(()=>{this.resolveWaitUntilFlush()},d)}_consumeWaitUntilCycle(){let a=this._waitUntilCycle;return a&&(clearTimeout(a.timer),this._waitUntilCycle=void 0),a?.resolve}async resolveWaitUntilFlush(){let a=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{a?.()}}getPersistedProperty(a){return this._memoryStorage.getProperty(a)}setPersistedProperty(a,b){return this._memoryStorage.setProperty(a,b)}fetch(a,b){return this.options.fetch?this.options.fetch(a,b):fetch(a,b)}getQueueRouteKey(a){var b;return"v1"===this.captureMode&&"string"==typeof(b=a).event&&b.event.startsWith("$ai_")?"ai":dV}persistedQueueKeyForRoute(a){return a===d2?k.AiCaptureQueue:"ai"===a?k.AiQueue:k.Queue}getActiveQueueRoutes(){let a="v1"===this.captureMode?[dV,"ai"]:[dV];return this._aiCaptureRouteActive&&a.push(d2),a}getBatchEndpointPath(a){return a===d2?d3:super.getBatchEndpointPath(a)}async sendBatch(a,b,c=dV){if(c===d2)return this.sendAiCaptureBatch(a,b);if("v1"!==this.captureMode||"ai"===c)return super.sendBatch(a,b,c);let d=a.filter(a=>void 0!==a);await this.getV1Sender().sendV1Batch(d)}async sendAiCaptureBatch(a,b){let{batches:c,dropped:d}=function(a,b=8388608,c=5242880){let d=[],e=[],f=[],g=0;for(let h of a){if(void 0===h)continue;let a=d5(h);if(a>b){e.push({event:"string"==typeof h.event?h.event:"unknown",bytes:a});continue}f.length>0&&g+a>c&&(d.push(f),f=[],g=0),f.push(h),g+=a}return f.length>0&&d.push(f),{batches:d,dropped:e}}(a);for(let{event:a,bytes:b}of d){let c=`Event ${a} (${b} bytes) exceeds the 8MiB limit for ${d3}, dropping.`;this._logger.error(c),this._events.emit("error",Error(c))}for(let a of c)await this.sendAiSubBatch(a,b)}async sendAiSubBatch(a,b){try{await super.sendBatch(a,b,d2)}catch(d){if(!a6(d))throw d;if(1===a.length){let[b]=a,c="string"==typeof b.event?b.event:"unknown",d=`Event ${c} (${d5(b)} bytes) was rejected with 413 by ${d3} on its own, dropping.`;this._logger.error(d),this._events.emit("error",Error(d));return}let c=Math.ceil(a.length/2);await this.sendAiSubBatch(a.slice(0,c),b),await this.sendAiSubBatch(a.slice(c),b)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new d1({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:(a,b)=>this.fetch(a,b),onError:a=>this._events.emit("error",a),compress:a=>this.compressPayload(a)})),this._v1Sender}getLibraryVersion(){return"5.73.0"}get metrics(){return this._metrics||(this._metrics=new bI(this,cd(this.options.metrics),this._logger)),this._metrics}get _logsPipeline(){if(!this._logs){let a=function(a,b={}){let{rateCap:c,...d}=a??{},e=a?.rateCap?.windowMs??1e4,f=a?.rateCap&&"maxLogs"in a.rateCap?a.rateCap.maxLogs:1e4,g=void 0!==f&&f>0&&e>0?f:void 0,h=a?.maxBatchRecordsPerPost;return{...d,serviceName:a?.serviceName??b.serviceName,maxBufferSize:a?.maxBufferSize??100,flushIntervalMs:a?.flushIntervalMs??3e3,maxBatchRecordsPerPost:Number.isInteger(h)&&h>0?h:100,rateCapWindowMs:e,maxLogsPerInterval:g,maxQueueSize:g??1e4,backgroundFlushBudgetMs:25e3,terminationFlushBudgetMs:2e3,resourceAttributes:{...b.hostResourceAttributes,...a?.resourceAttributes}}}(this.options.logs,{serviceName:this._resolveServiceName()??void 0,hostResourceAttributes:this.hostResourceAttributes()});this._logs=new bs(this,a,this._logger,()=>this._logContext(),a=>a(),void 0,void 0,()=>this.disabled||this.optedOut)}return this._logs}_logContext(){let a=this.context?.get();return{distinctId:a?.distinctId,sessionId:a?.sessionId}}captureLog(a){let b=a;if(!a.trace_id&&!a.span_id){let c=this.getActiveSpan(),d=c?.traceId,e=c?.spanId;if(d&&e){let f=parseInt(c?.traceparent()?.split("-")[3]??"",16);b={...a,trace_id:d,span_id:e,...void 0===a.trace_flags&&!Number.isNaN(f)&&{trace_flags:f}}}}this._logsPipeline.captureLog(b),this.scheduleDebouncedFlush()}get logger(){if(!this._captureLogger){let a=a=>(b,c)=>this.captureLog({body:b,level:a,attributes:c});this._captureLogger={trace:a("trace"),debug:a("debug"),info:a("info"),warn:a("warn"),error:a("error"),fatal:a("fatal")}}return this._captureLogger}get emails(){var a,b;return this._emails||(this._emails=new eo({secretKey:this.options.personalApiKey,host:this.host,appHost:this.options.appHost,requestTimeoutMs:"number"==typeof(a=this.options.emailRequestTimeoutMs)&&Number.isFinite(a)&&a>0?a:15e3,maxRetries:"number"==typeof(b=this.options.emailRequestMaxRetries)&&Number.isFinite(b)&&b>=0?Math.floor(b):2,migratedFrom:this.options.migratedFrom},{fetch:(a,b)=>this.fetch(a,b),isDisabled:()=>this.disabled,isClosed:()=>this._isShutdown,logger:this._logger,userAgent:this.getCustomUserAgent()||void 0})),this._emails}initializeSpanContextManager(){return new b9}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces)return this._traces||(this._traces=new b8(this,cg(this.options.traces,this.hostResourceAttributes(),this._logger),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}_tracingContext(){let a=this.context?.get();return{distinctId:a?.distinctId,sessionId:a?.sessionId}}startSpan(a,b){return this._tracesPipeline?.startSpan(a,b)??bV(b,this._spanContextManager.active())}withSpan(a,b,c){let d="function"==typeof b?void 0:b,e="function"==typeof b?b:c,f=this._tracesPipeline;return f?d?f.withSpan(a,d,e):f.withSpan(a,e):b$(this._spanContextManager,bV(d,this._spanContextManager.active()),e)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getFlagsResponseFormat(){let a=super.getFlagsResponseFormat();return{version:4,read:b=>{let{body:c,withoutTypedValues:d}=function(a){if(!C(a))return{body:a,withoutTypedValues:!1};let b=a.flags;if(!C(b)){let b=a.featureFlags;return{body:a,withoutTypedValues:C(b)&&Object.keys(b).length>0}}let c=!1,d=Object.fromEntries(Object.entries(b).map(([a,b])=>{C(b)&&!q.call(b,"value")&&(c=!0);let{detail:d,record:e}=function(a,b){try{if(C(b)&&!q.call(b,"value")){var c;let a,d,e,f,g;return c=b,cn(c),a=cq(c.enabled,"enabled",z),d=cq(c.variant,"variant",u),e=!0===cq(c.failed,"failed",z),f=co(c.reason),g=cp(cq(c.metadata,"metadata",C)),{detail:c,record:{value:d??a??null,failed:e,reason:f,metadata:{...g,configVersion:1}}}}return function(a,b){var c;if(!C(b))throw new ck("record");cn(b);let d=function(a){if(w(a)||z(a)||u(a)||C(a)||y(a)&&Number.isFinite(a))return a;throw new ck("value")}(b.value),e=!0===cq(b.failed,"failed",z),f=co(b.reason),g=cq(b.metadata,"metadata",C),h={...cp(g),configVersion:cr(g?.config_version,"metadata.config_version"),ruleType:cq(g?.rule_type,"metadata.rule_type",u),ruleId:cq(g?.rule_id,"metadata.rule_id",u),variantKey:cq(g?.variant_key,"metadata.variant_key",u),forcedVariant:cq(g?.forced_variant,"metadata.forced_variant",z)};cr(g?.experiment_id,"metadata.experiment_id");let i=e?null:d,{enabled:j,variant:k,payload:l}=w(c=i)||z(c)?{enabled:!0===c,variant:void 0,payload:void 0}:u(c)?{enabled:!0,variant:c,payload:void 0}:{enabled:!0,variant:void 0,payload:JSON.stringify(c)},m={key:a,enabled:j,variant:k,reason:f&&{code:f.code,condition_index:f.conditionIndex,description:f.description},metadata:g||void 0!==l?{id:h.id,version:h.version,description:h.description,payload:e?null:l??g?.payload,has_experiment:h.hasExperiment}:void 0};return e&&(m.failed=!0),{detail:m,record:{value:i,failed:e,reason:f,metadata:h}}}(a,b)}catch(b){if(b instanceof ck)return cm(a,b.field);if(b instanceof RangeError)return cm(a,"value");throw b}}(a,b);return cj.set(d,e),[a,d]}));return{body:{...a,flags:d},withoutTypedValues:c}}(b);return d&&!this._loggedFlagsResponseWithoutTypedValues&&(this._loggedFlagsResponseWithoutTypedValues=!0,this._logger.info("[FEATURE FLAGS] The /flags response has no typed flag values, so the server may not support /flags?v=4. Its flags are read as config version 1.")),a.read(c)}}}getCommonEventProperties(){let a=super.getCommonEventProperties();return(this.options.isServer??!0)&&(a.$is_server=!0),a}enable(){return super.optIn()}disable(){return super.optOut()}debug(a=!0){super.debug(a),this.featureFlagsPoller?.debug(a)}_warnIfInvalidCapture(a,b,c){"string"==typeof a&&this._logger.warn(b),"$exception"!==a.event||a._originatedFromCaptureException||this._logger.warn(c)}_sendPreparedEvent(a,b,c,d,e){return this.addPendingPromise(this._prepareEventMessage(b,d).then(({distinctId:b,event:f,properties:g,options:h})=>{(this.disabled||this.optedOut)&&d?.onCaptureFailed?.();let i={timestamp:h.timestamp,disableGeoip:h.disableGeoip,uuid:h.uuid},j={distinctId:b,event:f,properties:{...g,...this.getCommonEventProperties()}};return c?this.sendImmediate(a,j,i,e):this.enqueue(a,j,i,e)}).catch(a=>{a&&(console.error(a),d?.onCaptureFailed?.())}))}_capturePreparedEvent(a,b){return this._sendPreparedEvent("capture",a,b)}capture(a){this._warnIfInvalidCapture(a,"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(a,!1)}async captureImmediate(a){return this._warnIfInvalidCapture(a,"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(a,!0)}captureAi(a){if(this.disabled)return;let b=aG(a.uuid,aW);return this._sendPreparedAiEvent({...a,uuid:b},!1),b}async captureAiImmediate(a){if(this.disabled)return;let b=aG(a.uuid,aW);return await this._sendPreparedAiEvent({...a,uuid:b},!0),b}_sendPreparedAiEvent(a,b){return"string"!=typeof a?.event||a.event.startsWith("$ai_")||this._logger.debug(`captureAi called with non-AI event ${a.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",a,b,void 0,d2)}identify({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;this._sendPreparedEvent("identify",{distinctId:a,event:"$identify",properties:{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},disableGeoip:c},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;await this._sendPreparedEvent("identify",{distinctId:a,event:"$identify",properties:{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},disableGeoip:c},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:a,properties:b={},propertiesOnce:c={}}){if(0===Object.keys(b).length&&0===Object.keys(c).length)return;let d={};Object.keys(b).length>0&&(d.$set=b),Object.keys(c).length>0&&(d.$set_once=c),this.capture({distinctId:a,event:"$set",properties:d})}unsetPersonProperties({distinctId:a,properties:b}){let c=(Array.isArray(b)?b:[b]).filter(a=>"string"==typeof a&&a.trim().length>0);0!==c.length&&this.capture({distinctId:a,event:"$set",properties:{$unset:c}})}alias(a){this._sendPreparedEvent("alias",{distinctId:a.distinctId,event:"$create_alias",properties:{distinct_id:a.distinctId,alias:a.alias},disableGeoip:a.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(a){await this._sendPreparedEvent("alias",{distinctId:a.distinctId,event:"$create_alias",properties:{distinct_id:a.distinctId,alias:a.alias},disableGeoip:a.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(a){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(a)}getFeatureFlagKeysByEvaluationRuntime(a){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(a)??[]}async waitForLocalEvaluationReady(a=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(b=>{let c=setTimeout(()=>{d(),b(!1)},a),d=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(c),d(),b(a>0)})})}_resolveDistinctId(a,b){return"string"==typeof a?{distinctId:a,options:b}:{distinctId:this.context?.get()?.distinctId,options:a}}async getFeatureFlagDetailsStateless(a,b={},c={},d={},e,f){let g=await super.getFeatureFlagDetailsStateless(a,b,c,d,e,f);if(void 0!==g&&!C(g.flags)){let a="/flags response has a non-object `flags` field, treating it as a failed request";this._logger.warn(`[FEATURE FLAGS] ${a}`),this._events.emit("error",Error(a));return}return g}async _getFeatureFlagResult(a,b,c={},d){let e,f,g,h,i,j,k,l,m;if(this.disabled)return void this._logger.warn("The client is disabled");let n=c.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&a in this._flagOverrides){let b=this._flagOverrides[a];if(void 0===b)return;let c=this._payloadOverrides?.[a];return{key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:c}}let{groups:o,disableGeoip:p}=c,{onlyEvaluateLocally:q,personProperties:r,groupProperties:s}=c,t=this.addLocalPersonAndGroupProperties(b,o,r,s);r=t.allPersonProperties,s=t.allGroupProperties;let u=this.createFeatureFlagEvaluationContext(b,o,this.personPropertiesForLocalEvaluation(b,r),s);void 0==q&&(q=this.options.strictLocalEvaluation??!1);let v=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let b=this.featureFlagsPoller?.featureFlagsByKey[a];if(b)try{let c=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(b,u,{matchValue:d});if(c){v=!0;let d=c.value;i=b.id,k="Evaluated locally",l=b.has_experiment,e={key:a,enabled:!1!==d,variant:"string"==typeof d?d:void 0,payload:c.payload??void 0,reason:k,reasonCode:!1===b.active?"flag_disabled":void 0}}}catch(b){if(b instanceof c1||b instanceof cB)this._logger?.info(`${b.name} when computing flag locally: ${a}: ${b.message}`);else throw b}}if(!v&&!q){let b=await this.getFeatureFlagDetailsStateless(u.distinctId,u.groups,r,s,p,[a]);if(void 0===b)h=ch.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===b.minimalFlagCalledEvents,f=b.requestId,g=b.evaluatedAt;let c=[];b.errorsWhileComputingFlags&&c.push(ch.ERRORS_WHILE_COMPUTING),b.quotaLimited?.includes("feature_flags")&&c.push(ch.QUOTA_LIMITED);let d=b.flags[a];if(void 0===d)c.push(ch.FLAG_MISSING);else{let b;if(i=d.metadata?.id,j=d.metadata?.version,k=d.reason?.description??d.reason?.code,l=d.metadata?.has_experiment,d.metadata?.payload!==void 0)try{b=JSON.parse(d.metadata.payload)}catch{b=d.metadata.payload}e={key:a,enabled:d.enabled,variant:d.variant??void 0,payload:b,reason:k,reasonCode:d.reason?.code},m=cl(d)}void 0!==d&&cj.get(d)?.unreadableField!==void 0?(h=ch.UNKNOWN_ERROR,f=void 0,g=void 0):c.length>0&&(h=c.join(","))}}if(n){let c=void 0===e?void 0:!1!==e.enabled&&(e.variant??!0),d={$feature_flag:a,$feature_flag_response:c,$feature_flag_id:i,$feature_flag_version:j,$feature_flag_reason:k,locally_evaluated:v,[`$feature/${a}`]:c,$feature_flag_request_id:f,$feature_flag_evaluated_at:v?Date.now():g};if(void 0!==l&&(d.$feature_flag_has_experiment=l),v&&this.featureFlagsPoller){let a=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==a&&(d.$feature_flag_definitions_loaded_at=a)}h&&(d.$feature_flag_error=h),this._captureFlagCalledEventIfNeeded({distinctId:b,key:a,response:c,groups:o,disableGeoip:p,properties:d,record:m})}return void 0!==e&&void 0!==this._payloadOverrides&&a in this._payloadOverrides&&(e={...e,payload:this._payloadOverrides[a]}),e}async getFeatureFlag(a,b,c){eH("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 d=await this._getFeatureFlagResult(a,b,{...c,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(c?.sendFeatureFlagEvents)});if(void 0!==d)return!1!==d.enabled&&(d.variant??!0)}async getFeatureFlagPayload(a,b,c,d){if(eH("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&&a in this._payloadOverrides)return this._payloadOverrides[a];let e=await this._getFeatureFlagResult(a,b,{...d,sendFeatureFlagEvents:!1},c);if(void 0!==e)return e.payload??null}async getFeatureFlagResult(a,b,c){let{distinctId:d,options:e}=this._resolveDistinctId(b,c);return d?this._getFeatureFlagResult(a,d,{...e,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(e?.sendFeatureFlagEvents)}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}async getRemoteConfigPayload(a){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 b=await this._requestRemoteConfigPayload(a);if(!b)return;let c=await b.json();if("string"==typeof c)try{return JSON.parse(c)}catch(a){}return c}async isFeatureEnabled(a,b,c){eH("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 d=await this._getFeatureFlagResult(a,b,{...c,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(c?.sendFeatureFlagEvents)});return void 0===d?void 0:!1!==d.enabled&&!!(d.variant??!0)}async getAllFlags(a,b){let{distinctId:c,options:d}=this._resolveDistinctId(a,b);return c?(await this.getAllFlagsAndPayloads(c,d)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(a,b){let{distinctId:c,options:d}=this._resolveDistinctId(a,b);if(!c)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:e,disableGeoip:f,flagKeys:g}=d||{},{onlyEvaluateLocally:h,personProperties:i,groupProperties:j}=d||{},k=this.addLocalPersonAndGroupProperties(c,e,i,j);i=k.allPersonProperties,j=k.allGroupProperties;let l=this.createFeatureFlagEvaluationContext(c,e,this.personPropertiesForLocalEvaluation(c,i),j);void 0==h&&(h=this.options.strictLocalEvaluation??!1);let m=await this.featureFlagsPoller?.getAllFlagsAndPayloads(l,g),n={},o={},p=!0;if(m&&(n=m.response,o=m.payloads,p=m.fallbackToFlags),p&&!h){let a=await super.getFeatureFlagsAndPayloadsStateless(l.distinctId,l.groups,i,j,f,g);n={...n,...a.flags||{}},o={...o,...a.payloads||{}}}return void 0!==this._flagOverrides&&(n={...n,...this._flagOverrides}),void 0!==this._payloadOverrides&&(o={...o,...this._payloadOverrides}),{featureFlags:n,featureFlagPayloads:o}}async evaluateFlags(a,b){let c,d,{distinctId:e,options:f}=this._resolveDistinctId(a,b);if(!e)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new ci({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new ci({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,flags:{}});let{groups:g,disableGeoip:h}=f||{},i=f?.flagKeys??void 0;if(i?.length===0)return new ci({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:{}});let{onlyEvaluateLocally:j,personProperties:k,groupProperties:l}=f||{},m=this.addLocalPersonAndGroupProperties(e,g,k,l);k=m.allPersonProperties,l=m.allGroupProperties;let n=this.createFeatureFlagEvaluationContext(e,g,this.personPropertiesForLocalEvaluation(e,k),l);void 0==j&&(j=this.options.strictLocalEvaluation??!1);let o=i?new Set(i):void 0,p={},q=!1,r=!1,s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(n,i),t=new Set;if(s)for(let[a,b]of Object.entries(s.response)){let c=this.featureFlagsPoller?.featureFlagsByKey[a];p[a]={key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:s.payloads[a],id:c?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:c?.has_experiment},t.add(a)}let u=void 0!==o&&Array.from(o).some(a=>this.featureFlagsPoller?.featureFlagsByKey[a]===void 0);if((!s||s.fallbackToFlags||u)&&!j){let a=await this.getFeatureFlagDetailsStateless(n.distinctId,n.groups,k,l,h,i);if(a)for(let[b,e]of(this._minimalFlagCalledEvents=!0===a.minimalFlagCalledEvents,c=a.requestId,d=a.evaluatedAt,q=!!a.errorsWhileComputingFlags,r=Array.isArray(a.quotaLimited)&&a.quotaLimited.includes("feature_flags"),Object.entries(a.flags))){let a;if(!t.has(b)){if(e.metadata?.payload!==void 0)try{a=JSON.parse(e.metadata.payload)}catch{a=e.metadata.payload}p[b]={key:b,enabled:e.enabled,variant:e.variant,payload:a,id:e.metadata?.id,version:e.metadata?.version,reason:e.reason?.description??e.reason?.code,locallyEvaluated:!1,hasExperiment:e.metadata?.has_experiment,parsed:cl(e)}}}}if(void 0!==this._flagOverrides)for(let[a,b]of Object.entries(this._flagOverrides)){if(void 0===b){delete p[a];continue}let c=p[a];p[a]={key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:c?.payload,id:c?.id,version:c?.version,reason:c?.reason,locallyEvaluated:c?.locallyEvaluated??!1,hasExperiment:c?.hasExperiment}}if(void 0!==this._payloadOverrides)for(let[a,b]of Object.entries(this._payloadOverrides)){let c=p[a];c&&(p[a]={...c,payload:b})}if(void 0!==o)for(let a of Object.keys(p))o.has(a)||delete p[a];let v={};for(let[a,b]of Object.entries(s?.unresolved??{}))Object.prototype.hasOwnProperty.call(p,a)||(v[a]=b);return new ci({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:p,unresolvedFlags:v,requestId:c,evaluatedAt:d,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:q,quotaLimited:r})}_shouldSendMinimalFlagCalledEvent(a,b){return"$feature_flag_called"===a&&this._minimalFlagCalledEvents&&!1===b.$feature_flag_has_experiment}_captureFlagCalledEventIfNeeded(a){let{distinctId:b,key:c,response:d,groups:e,disableGeoip:f,properties:g,record:h}=a,i=function(a){let{key:b,response:c,groups:d,record:e}=a,f=function(a){if(void 0===a||void 0!==a.unreadableField||2!==a.metadata.configVersion)return;let b=a.reason?.code||void 0,c={reasonCode:b,ruleId:void 0,ruleType:void 0,variantKey:void 0},d=void 0===b?void 0:cu.get(b);if(a.failed||void 0===d)return c;let{ruleId:e,ruleType:f,variantKey:g}=a.metadata;return void 0!==e&&cz.test(e)&&void 0!==f&&d.has(f)?b!==cs?{...c,ruleId:e,ruleType:f}:void 0===g?c:{reasonCode:b,ruleId:e,ruleType:f,variantKey:g}:c}(e);if(void 0===f)return;let{reasonCode:g,ruleId:h,ruleType:i,variantKey:j}=f,k=Object.entries(d??{}).sort(([a],[b])=>a<b?-1:+(a>b)),l={$feature_flag_config_version:2};void 0!==g&&(l.$feature_flag_reason_code=g),void 0!==h&&(l.$feature_flag_rule_id=h,l.$feature_flag_rule_type=i),void 0!==j&&(l.$feature_flag_variant_key=j);let{$feature_flag_reason:m,...n}=a.properties;Object.assign(n,l);let o={event:"$feature_flag_called",dedupeKey:JSON.stringify([b,c??null,k,2,g??null,h??null,i??null,j??null]),properties:n,capture:{removed:cw,pinned:l}};if(void 0===j)return{flagCalled:o,exposure:void 0};let p={$feature_flag:b,$feature_flag_response:c,$feature_flag_variant_key:j,$feature_flag_rule_id:h,locally_evaluated:!0===n.locally_evaluated},q={};for(let a of cy)void 0!==n[a]&&(q[a]=n[a]);return Object.assign(q,p),{flagCalled:o,exposure:{event:"$experiment_exposure",dedupeKey:JSON.stringify([b,k,2,h,j]),properties:q,capture:{removed:cx,pinned:p}}}}({key:c,response:d,groups:e,properties:g,record:h});if(void 0!==i){this._captureFlagEventOnce(this._distinctIdHasSentFlagCalls,b,i.flagCalled,a),void 0!==i.exposure&&this._captureFlagEventOnce(this._experimentExposuresReported,String(b),i.exposure,a);return}let j=e&&Object.keys(e).length>0?`_${JSON.stringify(Object.entries(e).sort(([a],[b])=>a<b?-1:+(a>b)))}`:"",k=`${c}_${d}${j}`;void 0!==this._reserveFlagEventKey(this._distinctIdHasSentFlagCalls,b,k)&&this.capture({distinctId:b,event:"$feature_flag_called",properties:g,groups:e,disableGeoip:f})}_reserveFlagEventKey(a,b,c){let d=a.get(b)??new Set;if(a.delete(b),a.set(b,d),!d.has(c)){for(d.add(c);a.size>Math.max(this.maxCacheSize,1);){let b=a.keys().next().value;if(void 0===b)break;a.delete(b)}return d}}_captureFlagEventOnce(a,b,c,d){let e=this._reserveFlagEventKey(a,b,c.dedupeKey);if(void 0===e)return;let f=!1,g=()=>{f||(f=!0,e.delete(c.dedupeKey))};try{if(this.disabled||this.optedOut)return void g();this._sendPreparedEvent("capture",{distinctId:d.distinctId,event:c.event,properties:c.properties,groups:d.groups,disableGeoip:d.disableGeoip},!1,{flagEvent:c.capture,onCaptureFailed:g})}catch(a){this._logger.error(`[FEATURE FLAGS] Failed to capture ${c.event}:`,a),g()}}_resolveSendFeatureFlagEvents(a){return a??this.options.sendFeatureFlagEvent??!0}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:a=>this._captureFlagCalledEventIfNeeded(a),resolveSendFeatureFlagEvents:a=>this._resolveSendFeatureFlagEvents(a),logWarning:a=>{!1!==this.options.featureFlagsLogWarnings&&console.warn(`[PostHog] ${a}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:a,groupKey:b,properties:c,distinctId:d,disableGeoip:e}){this._sendPreparedEvent("capture",{distinctId:d||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{}},disableGeoip:e},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:a,groupKey:b,properties:c,distinctId:d,disableGeoip:e}){await this._sendPreparedEvent("capture",{distinctId:d||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{}},disableGeoip:e},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(a){let b=a=>Object.fromEntries(a.map(a=>[a,!0]));if(!1===a){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(a)){this._flagOverrides=b(a);return}if(this._isFeatureFlagOverrideOptions(a)){"flags"in a&&(!1===a.flags?this._flagOverrides=void 0:Array.isArray(a.flags)?this._flagOverrides=b(a.flags):void 0!==a.flags&&(this._flagOverrides={...a.flags})),"payloads"in a&&(!1===a.payloads?this._payloadOverrides=void 0:void 0!==a.payloads&&(this._payloadOverrides={...a.payloads}));return}this._flagOverrides={...a}}_isFeatureFlagOverrideOptions(a){if("object"!=typeof a||null===a||Array.isArray(a))return!1;if("flags"in a){let b=a.flags;if(!1===b||Array.isArray(b)||"object"==typeof b&&null!==b)return!0}if("payloads"in a){let b=a.payloads;if(!1===b||"object"==typeof b&&null!==b)return!0}return!1}withContext(a,b,c){return this.context?this.context.run(a,()=>(dT(this),b()),c):b()}getContext(){return this.context?.get()}enterContext(a,b){this.context?.enter(a,b),dT(this)}async _shutdown(a){let b=Date.now()+(a??3e4);this._isShutdown=!0;let c=this._emails?.drain(),d=this._logs,e=d?aN(d.flush().catch(()=>{}),Math.max(0,b-Date.now())).then(()=>{d.reset(),d.clearQueue()}):void 0,f=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(a),this.errorTracking.shutdown(),this._metrics&&(await aN(this._metrics.flush().catch(()=>{}),Math.max(0,b-Date.now())),this._metrics.reset()),this._traces&&(await aN(this._traces.flush().catch(()=>{}),Math.max(0,b-Date.now())),this._traces.reset());let g=Math.max(0,b-Date.now()),h=c?aN(c,g):void 0;try{return await super._shutdown(g)}finally{await h,await e,this._distinctIdHasSentFlagCalls.clear(),this._experimentExposuresReported.clear(),f?.()}}async _requestRemoteConfigPayload(a){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let b=`${this.host}/api/projects/@current/feature_flags/${a}/remote_config?token=${encodeURIComponent(this.apiKey)}`,c={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},d=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let a=new AbortController;d=aM(()=>{a.abort()},this.options.requestTimeout),c.signal=a.signal}try{return await this.fetch(b,c)}catch(a){this._events.emit("error",a);return}finally{d&&clearTimeout(d)}}extractPropertiesFromEvent(a,b){if(!a)return{personProperties:{},groupProperties:{}};let c={},d={};for(let[e,f]of Object.entries(a))if(C(f)&&b&&e in b){let a={};for(let[b,c]of Object.entries(f))a[String(b)]=String(c);d[String(e)]=a}else c[String(e)]=String(f);return{personProperties:c,groupProperties:d}}async getFeatureFlagsForEvent(a,b,c,d){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let e=d?.personProperties||{},f=d?.groupProperties||{},g=d?.flagKeys;if(d?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let d={};for(let[a,c]of Object.entries(b||{}))d[a]=String(c);return await this.getAllFlags(a,{groups:d,personProperties:e,groupProperties:f,disableGeoip:c,onlyEvaluateLocally:!0,flagKeys:g})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let d={};for(let[a,c]of Object.entries(b||{}))d[a]=String(c);return await this.getAllFlags(a,{groups:d,personProperties:e,groupProperties:f,disableGeoip:c,onlyEvaluateLocally:!0,flagKeys:g})}return(await super.getFeatureFlagsStateless(a,b,e,f,c)).flags}addLocalPersonAndGroupProperties(a,b,c,d){let e={...c||{}},f={};if(b)for(let a of Object.keys(b))f[a]={$group_key:b[a],...d?.[a]||{}};return{allPersonProperties:e,allGroupProperties:f}}personPropertiesForLocalEvaluation(a,b){return{distinct_id:a,...b||{}}}createFeatureFlagEvaluationContext(a,b,c,d){return{distinctId:a,groups:b||{},personProperties:c||{},groupProperties:d||{},evaluationCache:{}}}captureException(a,b,c,d,e){if(!dJ.isPreviouslyCapturedError(a)&&this.errorTracking.claimExplicitCapture(a)){let f=Error("PostHog syntheticException");this.addPendingPromise(dJ.buildEventMessage(this.getErrorPropertiesBuilder(),a,{syntheticException:f},b,c,this.getContext()).then(a=>this._capturePreparedEvent({...a,uuid:d,flags:e},!1)))}}async captureExceptionImmediate(a,b,c,d){if(!dJ.isPreviouslyCapturedError(a)&&this.errorTracking.claimExplicitCapture(a)){let e=Error("PostHog syntheticException");return this.addPendingPromise(dJ.buildEventMessage(this.getErrorPropertiesBuilder(),a,{syntheticException:e},b,c,this.getContext()).then(a=>this.captureImmediate({...a,flags:d})))}}async prepareEventMessage(a){return this._prepareEventMessage(a)}_serviceNameProperties(){let a=this._resolveServiceName();return a?{service_name:a}:{}}_resolveServiceName(){return void 0===this._serviceName&&(this._serviceName=(this.options.traces?cg(this.options.traces,this.hostResourceAttributes()).serviceName:void 0)||cd(this.options.metrics).serviceName||null),this._serviceName}async _prepareEventMessage(a,b={}){var c;let{distinctId:d,event:e,properties:f,groups:g,flags:h,sendFeatureFlags:i,timestamp:j,disableGeoip:k,uuid:l}=a,m=(c=this.context?.get(),dF in a?a[dF]??void 0:c),n=b.includeContextProperties??!0,o=d||m?.distinctId,p=n?{...this._serviceNameProperties(),...this.props,...m?.properties||{},...f||{}}:{...this._serviceNameProperties(),...f||{}};"$exception"!==e||"$trace_id"in p||"$span_id"in p||Object.assign(p,await dO()),o||(o=aW(),p.$process_person_profile=!1),n&&m?.sessionId&&!p.$session_id&&(p.$session_id=m.sessionId);let q=b.flagEvent,r=q?{...Object.fromEntries(Object.entries(p).filter(([a])=>!q.removed.has(a))),...q.pinned}:p,s=this._shouldSendMinimalFlagCalledEvent(e,r)?q?function(a){let b=aE(a);for(let c of cv)void 0!==a[c]&&(b[c]=a[c]);return b}(r):aE(r):r,t=this._runBeforeSend({distinctId:o,event:e,properties:s,groups:g,flags:h,sendFeatureFlags:i,timestamp:j,disableGeoip:k,uuid:l},b.onCaptureFailed);if(!t)return Promise.reject(null);let u=await Promise.resolve().then(async()=>{if(h)return i&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),h._getEventProperties();if(i){eH("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 a=await this.getFeatureFlagsForEvent(t.distinctId,g,k,"object"==typeof i?i:void 0);if(!a)return{};let b={};for(let[c,d]of Object.entries(a))b[`$feature/${c}`]=d;let c=Object.keys(a).filter(b=>!1!==a[b]).sort();return c.length>0&&(b.$active_feature_flags=c),b}return{}}).catch(()=>({})).then(a=>{let b=t.groups||g;return{...a,...t.properties||{},...void 0!==b&&Object.keys(b).length>0?{$groups:b}:{}}});return"$pageview"===t.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof u.$raw_user_agent&&cc(u.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(t.event="$bot_pageview",u.$browser_type="bot"),{distinctId:t.distinctId,event:t.event,properties:u,options:{timestamp:t.timestamp,disableGeoip:t.disableGeoip,uuid:t.uuid}}}_runBeforeSend(a,b){let c=this.options.before_send;if(!c)return a;let d=Array.isArray(c)?c:[c],e=a;for(let c of d)try{if(!(e=c(e)))return this._logger.info(`Event '${a.event}' was rejected in beforeSend function`),null;if(!e.properties||0===Object.keys(e.properties).length){let a=`Event '${e.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(a)}}catch(c){return this._logger.error(`Error in before_send function for event '${a.event}':`,c),b?.(),null}return e}}var eJ=am,eK=am,eL=am,eM=am,eN=am,eO=am,eP=am,eQ=am,eR=a.i(78500);let eS=Symbol.for("posthog-node.context-lifetimes"),eT=globalThis,eU=eT[eS]??=new WeakMap;function eV(a,b,c){let d=a&&eU.get(a);return c?eU.set(b,{signal:c,parent:d}):d&&eU.set(b,d),b}class eW{constructor(){this.storage=new eR.AsyncLocalStorage}get(){let a=this.storage.getStore();return a&&function(a){let b=eU.get(a);for(;b;){if(b.signal.aborted)return!1;b=b.parent}return!0}(a)?a:void 0}run(a,b,c){return this.storage.run(this.resolve(a,c),b)}enter(a,b){this.storage.enterWith(this.resolve(a,b))}resolve(a,b){let c=this.get();return b?.fresh===!0?eV(void 0,{...a},b.signal):eV(c,{distinctId:a.distinctId??c?.distinctId,sessionId:a.sessionId??c?.sessionId,properties:{...c?.properties||{},...a.properties||{}}},b?.signal)}}class eX{active(){return this._storage.getStore()}with(a,b){return this._storage.run(a,b)}constructor(){this._storage=new eR.AsyncLocalStorage}}var eY=a.i(27028);let eZ=(0,a.i(12057).promisify)(eY.gzip);async function e$(a,b=!0){try{let b=await eZ(a);return new Uint8Array(b)}catch(a){return b&&console.error("Failed to gzip compress data",a),null}}var e_=a.i(60526),dI=am;let e0="posthog-node";function e1(a,{organization:b,projectId:c,prefix:d,severityAllowList:e=["error"],sendExceptionsToPostHog:f=!0}={}){return g=>{if(!("*"===e||e.includes(g.level)))return g;g.tags||(g.tags={});let h=g.tags[e3.POSTHOG_ID_TAG];if(void 0===h)return g;let i=a.options.host??"https://us.i.posthog.com",j=new URL(`/project/${a.apiKey}/person/${h}`,i).toString();g.tags["PostHog Person URL"]=j;let k=g.exception?.values||[],l=k.map(a=>({...a,stacktrace:a.stacktrace?{...a.stacktrace,type:"raw",frames:(a.stacktrace.frames||[]).map(a=>({...a,platform:"node:javascript"}))}:void 0})),m={$exception_message:k[0]?.value||g.message,$exception_type:k[0]?.type,$exception_level:g.level,$exception_list:l,$sentry_event_id:g.event_id,$sentry_exception:g.exception,$sentry_exception_message:k[0]?.value||g.message,$sentry_exception_type:k[0]?.type,$sentry_tags:g.tags},n=dI.getInjectedReleaseId();return n&&(m.$release_id=n),b&&c&&(m.$sentry_url=(d||"https://sentry.io/organizations/")+b+"/issues/?project="+c+"&query="+g.event_id),f&&a.capture({event:"$exception",distinctId:h,properties:m}),g}}function e2(a,b){let c=e1(a,b);return{name:e0,processEvent:a=>c(a)}}class e3{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(a,b,c,d,e){this.name=e0,this.name=e0,this.setupOnce=function(f,g){f(e1(a,{organization:b,projectId:g()?.getClient()?.getDsn()?.projectId,prefix:c,severityAllowList:d,sendExceptionsToPostHog:e??!0}))}}}function e4(a){let b={};if(a)for(let c of a.split(";")){let[a,...d]=c.trim().split("=");if(a){let c=d.join("=").trim();try{b[a.trim()]=decodeURIComponent(c)}catch{b[a.trim()]=c}}}return{get:a=>a in b?{value:b[a]}:void 0}}function e5(a){let b=a.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${b}_posthog`}function e6(a){let b=Date.now();return JSON.stringify({distinct_id:a,$device_id:a,$user_state:"anonymous",$sesid:[b,aW(),b]})}function e7(a,b){let c=e5(b),d=a.get(c);return d?e9(d.value):null}function e8(a){if(!a)return;let b={};return a.sessionId&&(b.$session_id=a.sessionId),a.deviceId&&(b.$device_id=a.deviceId),Object.keys(b).length>0?b:void 0}function e9(a){if(!a)return null;try{let b=JSON.parse(a);if(!b||"object"!=typeof b||!b.distinct_id)return null;let c=s(b.$sesid)?b.$sesid:[],d=c[1];return{distinctId:String(b.distinct_id),isIdentified:"identified"===b.$user_state,sessionId:"string"==typeof d?d:void 0,sessionLastActivityTimestamp:fa(c[0]),sessionStartTimestamp:fa(c[2]),deviceId:"string"==typeof b.$device_id?b.$device_id:void 0}}catch{return null}}function fa(a){return"number"==typeof a&&Number.isFinite(a)?a:void 0}a.s(["PostHogSentryIntegration",0,e3,"createEventProcessor",0,e1,"sentryIntegration",0,e2],9318);let fb=/[\x00-\x1f\x7f-\x9f]/g;function fc(a){let b=a.options.readPostHogCookie;return!0===b?{apiKey:a.apiKey}:b&&"object"==typeof b?{apiKey:a.apiKey,sessionIdleTimeoutSeconds:b.sessionIdleTimeoutSeconds,optOutCapturingByDefault:b.optOutCapturingByDefault}:null}function fd(a,b,c){null!=c&&""!==c&&(a[b]=c)}function fe(a){return Array.isArray(a)?a[0]:a}function ff(a){if(Array.isArray(a)){for(let b of a){let a=ff(b);if(void 0!==a)return a}return}if("string"!=typeof a)return;let b=a.replace(fb,"").trim();if(b)return b.length>1e3?b.slice(0,1e3):b}function fg(a,b,c){return"number"==typeof a&&Number.isFinite(a)&&Math.abs(b-a)<=c}function fh(a,b){let c;if(!a)return{};let d=ff(a["x-posthog-session-id"]),e=ff(a["x-posthog-distinct-id"]),{sessionId:f,distinctId:g}=void 0===d&&void 0===e&&b?function(a,b,c=Date.now(),d=18e5,e=!1){try{let f;if("string"!=typeof a)return{};let g=e4(a.split(";").reverse().join(";")),h=g.get(e5(b))?.value,i=g.get("__ph_opt_in_out_"+b)?.value??"";if(!h||m(F,i)||e&&!m(E,i))return{};let j=JSON.parse(h);if(!j||"object"!=typeof j)return{};let k="identified"===j.$user_state?ff(j.distinct_id):void 0,l=j.$sesid;if(Array.isArray(l)&&(2===l.length||3===l.length)){let[a,b,e=a]=l;fg(a,c,d)&&fg(e,c,864e5)&&(f=ff(b))}return{...void 0!==f?{sessionId:f}:{},...void 0!==k?{distinctId:k}:{}}}catch{return{}}}(a.cookie,b.apiKey,Date.now(),"number"==typeof(c=b.sessionIdleTimeoutSeconds)&&Number.isFinite(c)&&0!==c?1e3*Math.min(Math.max(c,60),36e3):18e5,!0===b.optOutCapturingByDefault):{sessionId:d,distinctId:e};return{...void 0!==f?{sessionId:f}:{},...void 0!==g?{distinctId:g}:{}}}function fi(a,b){let c=function(a){if(!a)return a;let b=a.indexOf("?"),c=a.indexOf("#");return -1===b||-1!==c&&c<b?a:`${a.slice(0,b)}${-1===c?"":a.slice(c)}`}(a);return b?aJ(c):c}function fj(a,b){var c;let d=fh(b.headers,fc(a)),e=a.getContext(),f=e?.sessionId??d.sessionId,g=e?.distinctId??d.distinctId,h={},i=!0===a.options.disable_capture_url_hashes;return fd(h,"$current_url",(c=b.originalUrl||b.url,i?aJ(c):c)),fd(h,"$request_method",b.method),fd(h,"$request_path",fi(b.path,i)),fd(h,"$user_agent",fe(b.headers["user-agent"])),fd(h,"$ip",function(a){let b=fe(a.headers["x-forwarded-for"]);if(b){let a=b.split(",")[0].trim();if(a)return a}return a.socket?.remoteAddress}(b)),{...void 0!==f?{sessionId:f}:{},...void 0!==g?{distinctId:g}:{},properties:h}}function fk(a,b){var c;b.use((c=a,(a,b,d)=>{c.withContext(fj(c,a),()=>{dT(c,!0),d()})}))}function fl(a,b){var c;b.use((c=a,(a,b,d,e)=>{if(dJ.isPreviouslyCapturedError(a))return void e(a);let f=fj(c,b),g=Error("Synthetic exception"),h={...void 0!==f.sessionId?{$session_id:f.sessionId}:{},...f.properties||{}};c.addPendingPromise(Promise.all([dJ.buildEventMessage(c.getErrorPropertiesBuilder(),a,{mechanism:{type:"middleware",handled:!1},syntheticException:g},f.distinctId,h,c.getContext()),d.headersSent||d.destroyed?Promise.resolve(d.headersSent?d.statusCode:void 0):new Promise(a=>{let b=b=>{clearTimeout(e),d.removeListener("finish",c),d.removeListener("close",c),a(b)},c=()=>b(d.headersSent?d.statusCode:void 0),e=setTimeout(()=>b(void 0),1e3);e.unref(),d.once("finish",c),d.once("close",c)})]).then(([a,b])=>(void 0!==b&&(a.properties={...a.properties,$response_status_code:b}),c._capturePreparedEvent(a,!1)))),e(a)}))}a.s(["setupExpressErrorHandler",0,fl,"setupExpressRequestContext",0,fk],40602);let fm="http.server.request.duration",fn="http.server.request.count",fo=[.005,.01,.025,.05,.075,.1,.25,.5,.75,1,2.5,5,7.5,10],fp=new Set(["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","QUERY","TRACE"]);function fq(a,b,c,d={}){return fr(a,b,c,d)}async function fr(a,b,c,d,e){var f;let g;if(d.ignore?.(b))return c();let h=fh((f=b.headers,g={},f.forEach((a,b)=>{g[b.toLowerCase()]=a}),g),fc(a)),i=a.getContext(),j=!0===a.options.disable_capture_url_hashes,k=function(a){try{return new URL(a.url).pathname}catch{return}}(b),l={};fd(l,"$request_method",b.method),fd(l,"$request_path",k?fi(k,j):void 0),fd(l,"$user_agent",b.headers.get("user-agent")??void 0);let m=i?.sessionId??h.sessionId,n=i?.distinctId??h.distinctId,o={...void 0!==m?{sessionId:m}:{},...void 0!==n?{distinctId:n}:{},properties:l},p=b.method.toUpperCase(),q=fp.has(p)?p:"_OTHER",r="_OTHER"===q?"HTTP":q,s=performance.now(),t=new AbortController,u=!1;try{return await a.withContext(o,()=>(dT(a,!0),a.withSpan(r,{kind:"server",parent:b.headers.get("traceparent")??void 0,tracestate:b.headers.get("tracestate")??void 0,attributes:{"http.request.method":q,..."_OTHER"===q?{"http.request.method_original":b.method}:{},...k?{"url.path":k}:{}}},async f=>{var g,h,i;let j,k,l,m,n=!1;try{k=await c()}catch(a){n=!0,l=a}try{m=d.getRoute?.(b,k)}catch{}let p=n?500:k?.status??500;if(m&&(f.updateName(`${r} ${m}`),f.setAttribute("http.route",m)),f.setAttribute("http.response.status_code",p),!n&&p>=500){let a;try{a=e?.()}catch{}null!=a?f.recordException(a):f.setStatus("error")}let v={"http.request.method":q,"http.response.status_code":p,...m?{"http.route":m}:{}};if(a.metrics.histogram(fm,(performance.now()-s)/1e3,{unit:"s",attributes:v,bounds:fo}),a.metrics.count(fn,1,{attributes:v}),a._flushMetricsWithinInvocation(),n)throw l;return k?.body&&"HEAD"!==q?(u=!0,g=k,h=b=>a.withContext(o,b,{signal:t.signal}),i=()=>t.abort(),j=g.body.getReader(),new Response(new ReadableStream({async pull(a){try{let{done:b,value:c}=await h(()=>j.read());b?(a.close(),i()):a.enqueue(c)}catch(b){i(),a.error(b)}},async cancel(a){try{await h(()=>j.cancel(a))}finally{i()}}}),g)):k})),{signal:t.signal})}finally{u||t.abort()}}function fs(a,b={}){return async(c,d)=>{c.res=await fr(a,c.req.raw,async()=>(await d(),c.res),{...b,getRoute:()=>c.req.routePath&&"/*"!==c.req.routePath?c.req.routePath:void 0},()=>c.error)}}a.s(["HTTP_SERVER_REQUEST_COUNT_METRIC",0,fn,"HTTP_SERVER_REQUEST_DURATION_METRIC",0,fm,"instrumentRequest",0,fq,"posthogHonoMiddleware",0,fs],3157),a.i(9318),a.i(40602),a.i(3157),a.i(46539),a.s(["EmailError",0,d6,"FeatureFlagError",0,l,"FeatureFlagEvaluations",0,ci,"HTTP_SERVER_REQUEST_COUNT_METRIC",0,fn,"HTTP_SERVER_REQUEST_DURATION_METRIC",0,fm,"PostHogSentryIntegration",0,e3,"cookieStateToProperties",0,e8,"cookieStoreFromHeader",0,e4,"createEventProcessor",0,e1,"enrichCurrentSpan",0,dU,"getPostHogCookieName",0,e5,"instrumentRequest",0,fq,"parsePostHogCookie",0,e9,"posthogHonoMiddleware",0,fs,"readPostHogCookie",0,e7,"sentryIntegration",0,e2,"serializePostHogCookie",0,e6,"setupExpressErrorHandler",0,fl,"setupExpressRequestContext",0,fk,"uuidv7",0,aW],80456),a.i(80456),a.s(["EmailError",0,d6,"FeatureFlagError",0,l,"FeatureFlagEvaluations",0,ci,"HTTP_SERVER_REQUEST_COUNT_METRIC",0,fn,"HTTP_SERVER_REQUEST_DURATION_METRIC",0,fm,"PostHog",0,class extends eI{getLibraryId(){return"posthog-node"}compressPayload(a){return e$(a,this.isDebug)}initializeContext(){return new eW}initializeSpanContextManager(){return new eX}hostResourceAttributes(){return function(){var a,b;let c,d,e;try{c=(0,e_.platform)(),d=(0,e_.release)()}catch{}return a=c,b=d,{...(e=function(a){if(a)return Object.prototype.hasOwnProperty.call(bm,a)?bm[a]:a}(a))?{"os.name":e}:{},...b?{"os.version":b}:{}}}()}createErrorPropertiesBuilder(){let a;return new eJ.ErrorPropertiesBuilder([new eK.EventCoercer,new eL.ErrorCoercer,new eM.ObjectCoercer,new eN.StringCoercer,new eO.PrimitiveCoercer],eP.createStackParser("node:javascript",eQ.nodeStackLineParser),[(a=function(a=process.argv[1]?(0,i.dirname)(process.argv[1]):process.cwd(),b="\\"===i.sep){let c=b?j(a):a;return a=>{if(!a)return;let d=b?j(a):a,{dir:e,base:f,ext:g}=i.posix.parse(d);(".js"===g||".mjs"===g||".cjs"===g)&&(f=f.slice(0,-1*g.length));let h=decodeURIComponent(f);e||(e=".");let k=e.lastIndexOf("/node_modules");if(k>-1)return`${e.slice(k+14).replace(/\//g,".")}:${h}`;if(e.startsWith(c)){let a=e.slice(c.length+1).replace(/\//g,".");return a?`${a}:${h}`:h}return h}}(),async b=>{for(let c of b)c.module=a(c.filename);return b}),a=>at(a,void 0,this._logger),function(a=process.cwd()){i.sep;let b=a=>a,c=b(a);return async a=>{for(let d of a)!(!d.filename||d.filename.startsWith("node:")||d.filename.startsWith("data:"))&&(0,i.isAbsolute)(d.filename)&&(d.filename=b((0,i.relative)(c,b(d.filename))));return a}}()])}},"PostHogSentryIntegration",0,e3,"cookieStateToProperties",0,e8,"cookieStoreFromHeader",0,e4,"createEventProcessor",0,e1,"enrichCurrentSpan",0,dU,"getPostHogCookieName",0,e5,"instrumentRequest",0,fq,"parsePostHogCookie",0,e9,"posthogHonoMiddleware",0,fs,"readPostHogCookie",0,e7,"sentryIntegration",0,e2,"serializePostHogCookie",0,e6,"setupExpressErrorHandler",0,fl,"setupExpressRequestContext",0,fk,"uuidv7",0,aW],74493)}];
2
2
 
3
3
  //# sourceMappingURL=node_modules_posthog-node_dist_entrypoints_index_node_mjs_11bnuznb72p7z._.js.map