failproofai 1.0.0-beta.16 → 1.0.0-beta.18

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 (119) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/build-manifest.json +5 -5
  3. package/.next/standalone/.next/prerender-manifest.json +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 +7 -7
  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 +7 -7
  13. package/.next/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +3 -3
  14. package/.next/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +3 -3
  15. package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  16. package/.next/standalone/.next/server/app/_not-found/page/build-manifest.json +2 -2
  17. package/.next/standalone/.next/server/app/_not-found/page/server-reference-manifest.json +1 -1
  18. package/.next/standalone/.next/server/app/_not-found/page.js.nft.json +1 -1
  19. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  20. package/.next/standalone/.next/server/app/_not-found.html +1 -1
  21. package/.next/standalone/.next/server/app/_not-found.rsc +14 -14
  22. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +14 -14
  23. package/.next/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +4 -4
  24. package/.next/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +9 -9
  25. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
  26. package/.next/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +3 -3
  27. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  28. package/.next/standalone/.next/server/app/audit/page/build-manifest.json +2 -2
  29. package/.next/standalone/.next/server/app/audit/page/server-reference-manifest.json +2 -2
  30. package/.next/standalone/.next/server/app/audit/page.js.nft.json +1 -1
  31. package/.next/standalone/.next/server/app/audit/page_client-reference-manifest.js +1 -1
  32. package/.next/standalone/.next/server/app/index.html +1 -1
  33. package/.next/standalone/.next/server/app/index.rsc +14 -14
  34. package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
  35. package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +14 -14
  36. package/.next/standalone/.next/server/app/index.segments/_head.segment.rsc +4 -4
  37. package/.next/standalone/.next/server/app/index.segments/_index.segment.rsc +9 -9
  38. package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  39. package/.next/standalone/.next/server/app/page/build-manifest.json +2 -2
  40. package/.next/standalone/.next/server/app/page/server-reference-manifest.json +1 -1
  41. package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
  42. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  43. package/.next/standalone/.next/server/app/policies/page/build-manifest.json +2 -2
  44. package/.next/standalone/.next/server/app/policies/page/server-reference-manifest.json +10 -10
  45. package/.next/standalone/.next/server/app/policies/page.js.nft.json +1 -1
  46. package/.next/standalone/.next/server/app/policies/page_client-reference-manifest.js +1 -1
  47. package/.next/standalone/.next/server/app/project/[name]/page/build-manifest.json +2 -2
  48. package/.next/standalone/.next/server/app/project/[name]/page/server-reference-manifest.json +1 -1
  49. package/.next/standalone/.next/server/app/project/[name]/page.js.nft.json +1 -1
  50. package/.next/standalone/.next/server/app/project/[name]/page_client-reference-manifest.js +1 -1
  51. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/build-manifest.json +2 -2
  52. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/react-loadable-manifest.json +2 -2
  53. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/server-reference-manifest.json +2 -2
  54. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page.js.nft.json +1 -1
  55. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page_client-reference-manifest.js +1 -1
  56. package/.next/standalone/.next/server/app/projects/page/build-manifest.json +2 -2
  57. package/.next/standalone/.next/server/app/projects/page/server-reference-manifest.json +1 -1
  58. package/.next/standalone/.next/server/app/projects/page.js.nft.json +1 -1
  59. package/.next/standalone/.next/server/app/projects/page_client-reference-manifest.js +1 -1
  60. package/.next/standalone/.next/server/app/settings/page/build-manifest.json +2 -2
  61. package/.next/standalone/.next/server/app/settings/page/server-reference-manifest.json +4 -4
  62. package/.next/standalone/.next/server/app/settings/page.js.nft.json +1 -1
  63. package/.next/standalone/.next/server/app/settings/page_client-reference-manifest.js +1 -1
  64. package/.next/standalone/.next/server/chunks/[root-of-the-server]__06hexd0._.js +1 -1
  65. package/.next/standalone/.next/server/chunks/_0lxbzdq._.js +1 -1
  66. package/.next/standalone/.next/server/chunks/_1zuiiy3._.js +1 -1
  67. package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_01r25oi._.js +1 -1
  68. package/.next/standalone/.next/server/chunks/package_json_[json]_cjs_1nxcc4v._.js +1 -1
  69. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0spkm68._.js +2 -2
  70. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__17itmx-._.js +1 -1
  71. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0no2gzh._.js → [root-of-the-server]__1a-my61._.js} +2 -2
  72. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1rv-sc9._.js +1 -1
  73. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1u-wx42._.js +2 -2
  74. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1vwv3db._.js +3 -0
  75. package/.next/standalone/.next/server/chunks/ssr/_0rjgfln._.js +1 -1
  76. package/.next/standalone/.next/server/chunks/ssr/_0vo2qyt._.js +1 -1
  77. package/.next/standalone/.next/server/chunks/ssr/_0xej-0e._.js +1 -1
  78. package/.next/standalone/.next/server/chunks/ssr/_10399ge._.js +1 -1
  79. package/.next/standalone/.next/server/chunks/ssr/_149k9oy._.js +1 -1
  80. package/.next/standalone/.next/server/chunks/ssr/_1_hwp06._.js +1 -1
  81. package/.next/standalone/.next/server/chunks/ssr/{_09tcu2b._.js → _1ifzifk._.js} +1 -1
  82. package/.next/standalone/.next/server/chunks/ssr/_1mnhi_r._.js +1 -1
  83. package/.next/standalone/.next/server/chunks/ssr/_1ror7k9._.js +1 -1
  84. package/.next/standalone/.next/server/chunks/ssr/app_audit__components_audit-dashboard_tsx_0p9ud47._.js +1 -1
  85. package/.next/standalone/.next/server/chunks/ssr/app_global-error_tsx_1kp6l3x._.js +1 -1
  86. package/.next/standalone/.next/server/chunks/ssr/app_policies_hooks-client_tsx_19dqvpc._.js +1 -1
  87. package/.next/standalone/.next/server/middleware-build-manifest.js +5 -5
  88. package/.next/standalone/.next/server/pages/404.html +1 -1
  89. package/.next/standalone/.next/server/pages/500.html +1 -1
  90. package/.next/standalone/.next/server/server-reference-manifest.js +1 -1
  91. package/.next/standalone/.next/server/server-reference-manifest.json +15 -15
  92. package/.next/standalone/.next/static/chunks/{1_as8528fwqxf.js → 0rsx_d5zvy-dc.js} +1 -1
  93. package/.next/standalone/.next/static/chunks/{0fx3tgb_n0vz5.js → 16_af09907p72.js} +1 -1
  94. package/.next/standalone/.next/static/chunks/{2okcei5v0-xrx.js → 27nyktroru6xd.js} +1 -1
  95. package/.next/standalone/.next/static/chunks/{16yzosmvpinbh.js → 2_g_ltvh3jcgh.js} +1 -1
  96. package/.next/standalone/.next/static/chunks/{3xp43uu8jj8t4.js → 2cgpelmb2zoh-.js} +1 -1
  97. package/.next/standalone/.next/static/chunks/{2f2h7g8sm0bhr.js → 2kjsoq1g8t4qc.js} +1 -1
  98. package/.next/standalone/.next/static/chunks/{1nsy22eg5q-pi.js → 2q5ygkgs9l1gk.js} +1 -1
  99. package/.next/standalone/.next/static/chunks/{2n6wkcj5q_0yd.js → 2toc5dmy7efqk.js} +1 -1
  100. package/.next/standalone/.next/static/chunks/{2rl5gq4xl8oa2.js → 31fmsp1soxi07.js} +1 -1
  101. package/.next/standalone/.next/static/chunks/{43kqvfa-2jq0g.js → 3wq4n27ea5hkm.js} +1 -1
  102. package/.next/standalone/.next/static/chunks/{3vsiw3ayz3c7_.js → 3yxozwzbd09eg.js} +1 -1
  103. package/.next/standalone/.next/static/chunks/{turbopack-0ud32mdjjcn6y.js → turbopack-3diub4ctvn1n0.js} +1 -1
  104. package/.next/standalone/package.json +9 -9
  105. package/.next/standalone/server.js +1 -1
  106. package/dist/cli.mjs +175 -142
  107. package/dist/worker.mjs +1 -1
  108. package/package.json +9 -9
  109. package/src/hooks/configure-wizard.ts +34 -1
  110. package/src/hooks/daemon-service.ts +89 -62
  111. package/src/hooks/fp-reset.ts +16 -0
  112. package/src/hooks/harness-cli.ts +88 -11
  113. package/src/hooks/hook-activity-store.ts +29 -1
  114. package/src/hooks/migrations.ts +40 -15
  115. package/src/hooks/tui.ts +28 -0
  116. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0hxmox-._.js +0 -3
  117. /package/.next/standalone/.next/static/{kSTfP_Tzl760gYDnYr-JC → d2alqN0WTpN7MpYISLm81}/_buildManifest.js +0 -0
  118. /package/.next/standalone/.next/static/{kSTfP_Tzl760gYDnYr-JC → d2alqN0WTpN7MpYISLm81}/_clientMiddlewareManifest.js +0 -0
  119. /package/.next/standalone/.next/static/{kSTfP_Tzl760gYDnYr-JC → d2alqN0WTpN7MpYISLm81}/_ssgManifest.js +0 -0
@@ -1,4 +1,4 @@
1
1
  module.exports=[39702,e=>{"use strict";let t,i,r,s,a;var n,o=e.i(14747);function l(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}let u=e=>void 0===e?void 0:e.variant??e.enabled,c=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}},h=["$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","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],d=(e,t=[])=>{let i={},r=t=>{void 0!==e[t]&&(i[t]=e[t])};return h.forEach(r),t.forEach(r),i};var g=((n={}).AnonymousId="anonymous_id",n.DistinctId="distinct_id",n.Props="props",n.EnablePersonProcessing="enable_person_processing",n.PersonMode="person_mode",n.FeatureFlagDetails="feature_flag_details",n.FeatureFlags="feature_flags",n.FeatureFlagPayloads="feature_flag_payloads",n.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",n.BootstrapFeatureFlags="bootstrap_feature_flags",n.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",n.OverrideFeatureFlags="override_feature_flags",n.Queue="queue",n.AiQueue="ai_queue",n.LogsQueue="logs_queue",n.OptedOut="opted_out",n.SessionId="session_id",n.SessionStartTimestamp="session_start_timestamp",n.SessionLastTimestamp="session_timestamp",n.PersonProperties="person_properties",n.GroupProperties="group_properties",n.InstalledAppBuild="installed_app_build",n.InstalledAppVersion="installed_app_version",n.SessionReplay="session_replay",n.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",n.SurveyLastSeenDate="survey_last_seen_date",n.SurveysSeen="surveys_seen",n.Surveys="surveys",n.RemoteConfig="remote_config",n.FlagsEndpointWasHit="flags_endpoint_was_hit",n.DeviceId="device_id",n);let f={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",TIMEOUT:"timeout",CONNECTION_ERROR:"connection_error",UNKNOWN_ERROR:"unknown_error",apiError:e=>`api_error_${e}`},p=e=>{let t=Error(`Native gzip produced invalid output: ${e}`);throw t.name="NativeGzipValidationError",t},y=async(e,i)=>{e.size<18&&p("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());r.length>=2&&31===r[0]&&139===r[1]&&8===r[2]||p("invalid-header");let s=new DataView(await e.slice(e.size-8).arrayBuffer());s.getUint32(0,!0)!==(e=>{let i=(()=>{if(t)return t;t=[];for(let e=0;e<256;e++){let i=e;for(let e=0;e<8;e++)i=1&i?0xedb88320^i>>>1:i>>>1;t[e]=i>>>0}return t})(),r=0xffffffff;for(let t=0;t<e.length;t++)r=i[(r^e[t])&255]^r>>>8;return(0xffffffff^r)>>>0})(i)&&p("invalid-crc");let a=i.length>>>0;s.getUint32(4,!0)!==a&&p("invalid-size")};async function m(e,t=!0,i){try{let t=new TextEncoder().encode(e),i=new globalThis.CompressionStream("gzip"),r=i.writable.getWriter(),s=r.write(t).then(()=>r.close()).catch(async e=>{try{await r.abort(e)}catch{}throw e}),a=new Response(i.readable).blob(),[n]=await Promise.all([a,s]);return await y(n,t),n}catch(e){if(i?.rethrow)throw e;return t&&console.error("Failed to gzip compress data",e),null}}function v(e){let t=[];return JSON.stringify(e,function(e,i){if("bigint"==typeof i)return i.toString();if("function"!=typeof i&&"symbol"!=typeof i){if(i instanceof Error)return{name:i.name,message:i.message,stack:i.stack};if(i&&"object"==typeof i){for(;t.length>0&&t[t.length-1]!==this;)t.pop();if(t.includes(i))return"[Circular]";t.push(i)}return i}})??"null"}let _=Array.isArray,b=Object.prototype;b.hasOwnProperty;let w=b.toString,E=_||function(e){return"[object Array]"===w.call(e)},F=e=>e===Object(e)&&!E(e),P=e=>void 0===e,x=e=>"[object String]"==w.call(e),S=e=>null===e,$=e=>"[object Number]"==w.call(e)&&e==e;function I(e){return null===e||"object"!=typeof e}function C(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function k(e){return"u">typeof Event&&A(e,Event)}function A(e,t){try{return e instanceof t}catch{return!1}}let O="Android",M="BlackBerry",R="Nintendo",T="PlayStation",L="Xbox",j="Windows",D="(\\d+(\\.\\d+)?)";RegExp("Version/"+D),RegExp(L,"i"),RegExp(T+" \\w+","i"),RegExp(R+" \\w+","i"),RegExp(M+"|PlayBook|BB10","i");RegExp("rv:"+D),RegExp("Edge?\\/"+D),RegExp("(Chrome|CrMo)\\/"+D),RegExp("CriOS\\/"+D),RegExp("(UCBrowser|UCWEB)\\/"+D),RegExp("(Opera|OPR)\\/"+D),RegExp("Firefox\\/"+D),RegExp("FxiOS\\/"+D),RegExp("Konqueror[:/]?"+D,"i"),RegExp(M+" "+D),RegExp("android\\s"+D,"i"),RegExp("SamsungBrowser\\/"+D),RegExp("OculusBrowser\\/"+D),RegExp("Vivaldi\\/"+D),RegExp("YaBrowser\\/"+D),RegExp("Whale\\/"+D),RegExp("Brave\\/"+D),RegExp("(DuckDuckGo|Ddg)\\/"+D),RegExp("PaleMoon\\/"+D),RegExp("Waterfox\\/"+D),RegExp("GSA\\/"+D),RegExp("(rv:|MSIE )"+D),RegExp("rv:"+D),RegExp(L+"; "+L+" (.*?)[);]","i"),RegExp(R,"i"),RegExp(T,"i"),RegExp(j,"i"),RegExp("("+O+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+O+")","i");let B=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function U(e,t){return"string"==typeof e&&B.test(e)?e:t()}function N(e){return e?e.split("#")[0]:e}async function q(e,t){let i=null;for(let r=0;r<t.retryCount+1;r++){r>0&&await new Promise(e=>setTimeout(e,t.retryDelay));try{return await e()}catch(e){if(i=e,!t.retryCheck(e))throw e}}throw i}function H(){return new Date().toISOString()}function W(e,t){let i=setTimeout(e,t);return i?.unref&&i?.unref(),i}async function z(e,t,i){let r;try{return await Promise.race([e,new Promise((e,s)=>{r=W(()=>{try{i?.(),e()}catch(e){s(e)}},t)})])}finally{clearTimeout(r)}}let G=e=>e instanceof Error;function K(e){return Promise.all(e.map(e=>(e??Promise.resolve()).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}function V(e){let t=[];for(let i in e){let r=e[i];S(r)||P(r)||t.push({key:i,value:function e(t){if("[object Boolean]"===w.call(t))return{boolValue:t};if("number"==typeof t)return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if("string"==typeof t)return{stringValue:t};if(E(t))return{arrayValue:{values:t.map(t=>e(t))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}(r)})}return t}let Q=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function J(e){return String(e)+"000000"}function Y(e,t,i,r){let s="";return r&&(s=Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${JSON.stringify(r[e])}`).join(",")),`${e}\u0000${t}\u0000${i??""}\u0000${s}`}class X{constructor(e,t,i){this._instance=e,this._config=t,this._logger=i,this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._generation=0}count(e,t=1,i){this._capture({name:e,type:"count",value:t,unit:i?.unit,attributes:i?.attributes})}gauge(e,t,i){this._capture({name:e,type:"gauge",value:t,unit:i?.unit,attributes:i?.attributes})}histogram(e,t,i){this._capture({name:e,type:"histogram",value:t,unit:i?.unit,attributes:i?.attributes})}flush(){let e=this._flushPromise,t=(async()=>{e&&await e.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===t&&(this._flushPromise=null)});return this._flushPromise=t,t}drainWindow(){if(0===this._series.size)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._clearFlushTimer(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){let t,i;if(this._instance.isDisabled||this._instance.optedOut)return;let r=this._runBeforeSend(e);if(null===r)return;if(!r.name||"string"!=typeof r.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof r.value||!Number.isFinite(r.value))return void this._logger.warn(`Dropping metric '${r.name}': value must be a finite number`);if("count"===r.type&&r.value<0)return void this._logger.warn(`Dropping count '${r.name}': counters are monotonic, value must be >= 0`);try{t=r.attributes?{...r.attributes}:void 0,i=Y(r.type,r.name,r.unit,t)}catch(e){this._logger.warn(`Dropping metric '${r.name}': attributes could not be serialized`,e);return}let s=this._series.get(i);if(!s){if(!this._admitNewSeries())return;s={name:r.name,type:r.type,unit:r.unit,attributes:t,windowStartMs:Date.now()},this._series.set(i,s)}let a=this._typeByName.get(r.name);void 0===a?this._typeByName.set(r.name,r.type):a===r.type||this._typeCollisionWarned.has(r.name)||(this._typeCollisionWarned.add(r.name),this._logger.warn(`Metric name '${r.name}' is already used as a ${a}; recording it as a ${r.type} too will blend both series in charts. Use a distinct name.`)),this._fold(s,r.value),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush||(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:Array(Q.length+1).fill(0)});let i=e.hist;i.count+=1,i.sum+=t,i.min=Math.min(i.min,t),i.max=Math.max(i.max,t),i.bucketCounts[function(e,t){for(let i=0;i<t.length;i++)if(e<=t[i])return i;return t.length}(t,Q)]+=1}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let i=E(t)?t:[t],r=e;for(let e of i)try{let t=e(r);if(!t)return this._logger.info("Metric was rejected in beforeSend function"),null;r=t}catch(e){return this._logger.error("Error in beforeSend function for metric:",e),null}return r}_armFlushTimer(){this._flushTimer||(this._flushTimer=W(()=>{this._flushTimer=void 0,this.flush().catch(e=>{this._logger.error("Metrics flush failed:",e)})},this._config.flushIntervalMs))}_clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}async _doFlush(){if(0===this._series.size)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,i=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t===this._generation)switch(i.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._armFlushTimer();return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",i.error);return}}_buildPayload(e){var t,i,r,s,a,n,o;return s=this._buildMetrics(e),t=this._config,i=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),a={...t.resourceAttributes,"service.name":t.serviceName||"unknown_service",...t.environment&&{"deployment.environment":t.environment},...t.serviceVersion&&{"service.version":t.serviceVersion},"telemetry.sdk.name":i,"telemetry.sdk.version":r},n=this._instance.getLibraryId(),o=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:V(a)},scopeMetrics:[{scope:{name:n,version:o},metrics:s}]}]}}_buildMetrics(e){let t=J(Date.now()),i=new Map;for(let r of e.values()){let e=Y(r.type,r.name,r.unit,void 0),s=i.get(e);s||(s={name:r.name,...r.unit&&{unit:r.unit}},"count"===r.type?s.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===r.type?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:1,dataPoints:[]},i.set(e,s));let a=V(r.attributes??{}),n=J(r.windowStartMs);if("count"===r.type){let e={attributes:a,startTimeUnixNano:n,timeUnixNano:t,asDouble:r.total??0};s.sum.dataPoints.push(e)}else if("gauge"===r.type){let e={attributes:a,timeUnixNano:t,asDouble:r.last??0};s.gauge.dataPoints.push(e)}else if(r.hist){let e={attributes:a,startTimeUnixNano:n,timeUnixNano:t,count:r.hist.count,sum:r.hist.sum,min:r.hist.min,max:r.hist.max,bucketCounts:r.hist.bucketCounts,explicitBounds:Q};s.histogram.dataPoints.push(e)}}return Array.from(i.values())}_mergeWindowBack(e){for(let[t,i]of e){let e=this._series.get(t);if(!e){this._admitNewSeries()&&this._series.set(t,i);continue}switch(e.windowStartMs=Math.min(e.windowStartMs,i.windowStartMs),e.type){case"count":e.total=(e.total??0)+(i.total??0);break;case"gauge":break;case"histogram":if(i.hist)if(e.hist){e.hist.count+=i.hist.count,e.hist.sum+=i.hist.sum,e.hist.min=Math.min(e.hist.min,i.hist.min),e.hist.max=Math.max(e.hist.max,i.hist.max);for(let t=0;t<e.hist.bucketCounts.length;t++)e.hist.bucketCounts[t]+=i.hist.bucketCounts[t]}else e.hist=i.hist}}}}let Z="0123456789abcdef";class ee{constructor(e){this.bytes=e}static ofInner(e){if(16===e.length)return new ee(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,i,r){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(i)||!Number.isInteger(r)||e<0||t<0||i<0||r<0||e>0xffffffffffff||t>4095||i>0x3fffffff||r>0xffffffff)throw RangeError("invalid field value");let s=new Uint8Array(16);return s[0]=e/0x10000000000,s[1]=e/0x100000000,s[2]=e/0x1000000,s[3]=e/65536,s[4]=e/256,s[5]=e,s[6]=112|t>>>8,s[7]=t,s[8]=128|i>>>24,s[9]=i>>>16,s[10]=i>>>8,s[11]=i,s[12]=r>>>24,s[13]=r>>>16,s[14]=r>>>8,s[15]=r,new ee(s)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("")}if(t){let e=new Uint8Array(16);for(let i=0;i<16;i+=4){let r=parseInt(t.substring(2*i,2*i+8),16);e[i+0]=r>>>24,e[i+1]=r>>>16,e[i+2]=r>>>8,e[i+3]=r}return new ee(e)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=Z.charAt(this.bytes[t]>>>4),e+=Z.charAt(15&this.bytes[t]),(3===t||5===t||7===t||9===t)&&(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=Z.charAt(this.bytes[t]>>>4),e+=Z.charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw Error("unreachable");if(e<=7)return this.bytes.every(e=>0===e)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(e=>255===e)?"MAX":"VAR_RESERVED";throw Error("unreachable")}getVersion(){return"VAR_10"===this.getVariant()?this.bytes[6]>>>4:void 0}clone(){return new ee(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(let t=0;t<16;t++){let i=this.bytes[t]-e.bytes[t];if(0!==i)return Math.sign(i)}return 0}}class et{constructor(e){this.timestamp=0,this.counter=0,this.random=e??ei()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let i=this.generateOrAbortCore(e,t);return void 0===i&&(this.timestamp=0,i=this.generateOrAbortCore(e,t)),i}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>0x3ffffffffff&&(this.timestamp++,this.resetCounter())}return ee.fromFieldsV7(this.timestamp,Math.trunc(this.counter/0x40000000),this.counter&0x40000000-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,ee.ofInner(e)}}let ei=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),er=()=>es().toString(),es=()=>(i||(i=new et)).generate();function ea(e){let t={};if(e)for(let i of e.split(";")){let[e,...r]=i.trim().split("=");if(e){let i=r.join("=").trim();try{t[e.trim()]=decodeURIComponent(i)}catch{t[e.trim()]=i}}}return{get:e=>e in t?{value:t[e]}:void 0}}function en(e){let t=e.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${t}_posthog`}function eo(e){let t=Date.now();return JSON.stringify({distinct_id:e,$device_id:e,$user_state:"anonymous",$sesid:[t,er(),t]})}function el(e,t){let i=en(t),r=e.get(i);return r?ec(r.value):null}function eu(e){if(!e)return;let t={};return e.sessionId&&(t.$session_id=e.sessionId),e.deviceId&&(t.$device_id=e.deviceId),Object.keys(t).length>0?t:void 0}function ec(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||"object"!=typeof t||!t.distinct_id)return null;let i=E(t.$sesid)?t.$sesid[1]:void 0;return{distinctId:String(t.distinct_id),isIdentified:"identified"===t.$user_state,sessionId:"string"==typeof i?i:void 0,deviceId:"string"==typeof t.$device_id?t.$device_id:void 0}}catch{return null}}class eh{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,t){for(let i of this.events[e]||[])i(t);for(let i of this.events["*"]||[])i(e,t)}}class ed{add(e){let t=er(),i=++this.nextId;return this.promiseByIds[t]={id:i,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map(e=>e.promise),t=e.length;for(;t>0;)await Promise.all(e),t=(e=Object.values(this.promiseByIds).map(e=>e.promise)).length}getPromises(e=[],t=this.nextId){let i=new Set(e);return Object.values(this.promiseByIds).filter(e=>e.id<=t&&!i.has(e.promise)).map(e=>e.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}let eg=(e,t,i)=>{function r(s,...a){t(()=>{(0,i[s])(e,...a)})}return{debug:(...e)=>{r("debug",...e)},info:(...e)=>{r("log",...e)},warn:(...e)=>{r("warn",...e)},error:(...e)=>{r("error",...e)},critical:(...t)=>{i.error(e,...t)},createLogger:r=>eg(`${e} ${r}`,t,i)}};class ef{constructor(e,t,i=[]){this.coercers=e,this.stackParser=t,this.modifiers=i}buildFromUnknown(e,t={}){let i=t&&t.mechanism||{handled:!0,type:"generic"},r=this.buildCoercingContext(i,t,0).apply(e),s=this.buildParsingContext(t),a=this.parseStacktrace(r,s);return{$exception_list:this.convertToExceptionList(a,i),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&E(t.stacktrace.frames)&&(t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames));return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let i,r;return null!=e.cause&&(i=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),{...e,cause:i,stack:r}}applyChunkIds(e,t){return e.map(e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e))}applyCoercers(e,t){for(let i of this.coercers)if(i.match(e))return i.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let e of this.modifiers)t=await e(t);return t}convertToExceptionList(e,t){let i={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};e.stack&&(i.stacktrace={type:"raw",frames:e.stack});let r=[i];return null!=e.cause&&r.push(...this.convertToExceptionList(e.cause,{...t,handled:!0})),r}buildParsingContext(e){return{chunkIdMap:function(e){let t=globalThis._posthogChunkIds;if(!t)return;let i=Object.keys(t);return a&&i.length===s?a:(s=i.length,a=i.reduce((i,s)=>{r||(r={});let a=r[s];if(a)i[a[0]]=a[1];else{let a=e(s);for(let e=a.length-1;e>=0;e--){let n=a[e],o=n?.filename,l=t[s];if(o&&l){i[o]=l,r[s]=[o,l];break}}}return i},{}))}(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,i=0){let r=(i,r)=>{if(r<=4){let s=this.buildCoercingContext(e,t,r);return this.applyCoercers(i,s)}};return{...t,syntheticException:0==i?t.syntheticException:void 0,mechanism:e,apply:e=>r(e,i),next:e=>r(e,i+1)}}}function ep(e,t,i,r,s){let a={platform:e,filename:t,function:"<anonymous>"===i?"?":i,in_app:!0};return P(r)||(a.lineno=r),P(s)||(a.colno=s),a}e.s(["ErrorPropertiesBuilder",0,ef],69309);let ey=(e,t)=>{let i=-1!==e.indexOf("safari-extension"),r=-1!==e.indexOf("safari-web-extension");return i||r?[-1!==e.indexOf("@")?e.split("@")[0]:"?",i?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},em=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ev=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,e_=/\((\S*)(?::(\d+))(?::(\d+))\)/,eb=(e,t)=>{let i=em.exec(e);if(i){let[,e,r,s]=i;return ep(t,e,"?",+r,+s)}let r=ev.exec(e);if(r){if(r[2]&&0===r[2].indexOf("eval")){let e=e_.exec(r[2]);e&&(r[2]=e[1],r[3]=e[2],r[4]=e[3])}let[e,i]=ey(r[1]||"?",r[2]);return ep(t,i,e,r[3]?+r[3]:void 0,r[4]?+r[4]:void 0)}},ew=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,eE=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,eF=(e,t)=>{let i=ew.exec(e);if(i){if(i[3]&&i[3].indexOf(" > eval")>-1){let e=eE.exec(i[3]);e&&(i[1]=i[1]||"eval",i[3]=e[1],i[4]=e[2],i[5]="")}let e=i[3],r=i[1]||"?";return[r,e]=ey(r,e),ep(t,e,r,i[4]?+i[4]:void 0,i[5]?+i[5]:void 0)}},eP=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ex=(e,t)=>{let i=eP.exec(e);return i?ep(t,i[2],i[1]||"?",+i[3],i[4]?+i[4]:void 0):void 0},eS=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,e$=(e,t)=>{let i=eS.exec(e);return i?ep(t,i[2],i[3]||"?",+i[1]):void 0},eI=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,eC=(e,t)=>{let i=eI.exec(e);return i?ep(t,i[5],i[3]||i[4]||"?",+i[1],+i[2]):void 0},ek=/^\s*[-]{4,}$/,eA=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,eO=/^Promise\.(?:all|any)$/,eM=/^index \d+$/,eR=(e,t)=>{let i=e.match(eA);if(i){let e,r,s,a,n;if(i[1]){let t=(s=i[1]).lastIndexOf(".");if("."===s[t-1]&&t--,t>0){e=s.slice(0,t),r=s.slice(t+1);let i=e.indexOf(".Module");i>0&&(s=s.slice(i+1),e=e.slice(0,i))}a=void 0}r&&(a=e,n=r),"<anonymous>"===r&&(n=void 0,s=void 0),void 0===s&&(n=n||"?",s=a?`${a}.${n}`:n);let o=i[2]?.startsWith("file://")?i[2].slice(7):i[2],l="native"===i[5];return o?.match(/\/[A-Z]:/)&&(o=o.slice(1)),o||!i[5]||l||(o=i[5]),eO.test(s)&&eM.test(o||"")&&(o="node:internal/promise"),{filename:o?decodeURI(o):void 0,module:void 0,function:s,lineno:eT(i[3]),colno:eT(i[4]),in_app:function(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==e&&!e.includes("node_modules/")}(o||"",l),platform:t}}if(e.match(ek))return{filename:e,platform:t}};function eT(e){return parseInt(e||"",10)||void 0}let eL=/\(error: (.*)\)/;function ej(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,50).map(e=>{var i;return{...e,filename:e.filename||((i=t)[i.length-1]||{}).filename,function:e.function||"?"}})}function eD(){return eB("web:javascript",eb,eF)}function eB(e,...t){return(i,r=0)=>{let s=[],a=i.split("\n");for(let i=r;i<a.length;i++){let r=a[i];if(r.length>1024)continue;let n=eL.test(r)?r.replace(eL,"$1"):r;if(!n.match(/\S*Error: /)){for(let i of t){let t=i(n,e);if(t){s.push(t);break}}if(s.length>=50)break}}return ej(s)}}e.s(["createDefaultStackParser",0,eD,"createStackParser",0,eB,"reverseAndStripFrames",0,ej],10728);class eU{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let i=x(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return C(e,"DOMException")}isDOMError(e){return C(e,"DOMError")}}e.s(["DOMExceptionCoercer",0,eU],33603);class eN{match(e){return!!C(e,"ErrorEvent")&&(void 0!=e.error||this._hasUsableMessage(e))}coerce(e,t){if(void 0!=e.error)return t.apply(e.error);let i=t.apply(e.message);return{...i,stack:this._buildLocationStack(e)??i.stack,synthetic:!0}}_hasUsableMessage(e){return x(e.message)&&e.message.length>0}_buildLocationStack(e){if(x(e.filename)&&e.filename.length>0){let t=e.lineno??0,i=e.colno??0;return`Error
2
- at ${e.filename}:${t}:${i}`}}}e.s(["ErrorEventCoercer",0,eN],60887);let eq=["fatal","error","warning","log","info","debug"];function eH(e,t=40){let i=Object.keys(e);if(i.sort(),!i.length)return"[object has no keys]";for(let e=i.length;e>0;e--){let r=i.slice(0,e).join(", ");if(!(r.length>t)){if(e===i.length)return r;return r.length<=t?r:`${r.slice(0,t)}...`}}return""}class eW{match(e){return"object"==typeof e&&null!==e}coerce(e,t){let i=this.getErrorPropertyFromObject(e);return i?t.apply(i):{type:this.getType(e),value:this.getValue(e),stack:this.getStack(e)??t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return k(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&"string"==typeof e.name){let t=`'${e.name}' captured as exception`;return"message"in e&&"string"==typeof e.message&&(t+=` with message: '${e.message}'`),t}if("message"in e&&"string"==typeof e.message)return e.message;let t=this.getObjectClassName(e),i=eH(e);return`${t&&"Object"!==t?`'${t}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(e){return x(e)&&!(x(e)&&0===e.trim().length)&&eq.indexOf(e)>=0}getStack(e){try{if(x(e.stacktrace)&&e.stacktrace.length>0)return e.stacktrace;return x(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let i=e[t];if(G(i))return i}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){return}}}e.s(["ObjectCoercer",0,eW],12154);class ez{match(e){return k(e)}coerce(e,t){let i=e.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${eH(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["EventCoercer",0,ez],41324);class eG{match(e){return I(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["PrimitiveCoercer",0,eG],79478);class eK{match(e){return C(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!k(e))return!1;try{let t=e.detail;return null!=t&&"object"==typeof t&&"reason"in t}catch{return!1}}coerce(e,t){let i=this.getUnhandledRejectionReason(e);return I(i)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:t.syntheticException?.stack,synthetic:!0}:t.apply(i)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&null!=e.detail&&"object"==typeof e.detail&&"reason"in e.detail)return e.detail.reason}catch{}return e}}e.s(["PromiseRejectionEventCoercer",0,eK],1802),e.s([],59567);let eV={MESSAGE:"$message",TIMESTAMP:"$timestamp"},eQ=new Set([eV.MESSAGE,eV.TIMESTAMP]),eJ={enabled:!0,max_bytes:32768};function eY(e){return e?{enabled:e.enabled??eJ.enabled,max_bytes:function(e,t){if(!$(e)||e===1/0||e===-1/0)return t;let i=Math.floor(e);return i<0?t:i}(e.max_bytes,eJ.max_bytes)}:{...eJ}}function eX(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((i,r)=>(eQ.has(r)?t.push(r):i[r]=e[r],i),{}),droppedKeys:t}}class eZ{constructor(e){this._entries=[],this._totalBytes=0,this._config=eY(e)}setConfig(e){this._config=eY(e),this._trimToMaxBytes()}add(e){let t=function(e){let t;try{t=v(e)}catch{return}try{let e=JSON.parse(t);if(!F(e))return;let i=e[eV.MESSAGE],r=e[eV.TIMESTAMP];if(!x(i)||0===i.trim().length||!x(r)&&!$(r))return;return{step:e,json:t}}catch{return}}(e);if(!t)return;let i=e0(t.json);i>this._config.max_bytes||(this._entries.push({step:t.step,bytes:i}),this._totalBytes+=i,this._trimToMaxBytes())}getAttachable(){return this._entries.map(e=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}}function e0(e){if("u">typeof TextEncoder)return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),i=0;for(let e=0;e<t.length;e++)"%"===t[e]?(i+=1,e+=2):i+=1;return i}e.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,eJ,"EXCEPTION_STEP_INTERNAL_FIELDS",0,eV,"ExceptionStepsBuffer",0,eZ,"getUtf8ByteLength",0,e0,"resolveExceptionStepsConfig",0,eY,"stripReservedExceptionStepFields",0,eX],45162),e.s([],21754);class e1{match(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return A(e,Error)}}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let i=e.message;return i.error&&"string"==typeof i.error.message?String(i.error.message):String(i)}getStack(e){return e.stacktrace||e.stack||void 0}}e.s(["ErrorCoercer",0,e1],13446);let e2=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class e4{match(e){return"string"==typeof e}coerce(e,t){let[i,r]=this.getInfos(e);return{type:i??"Error",value:r??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",i=e,r=e.match(e2);return r&&(t=r[1],i=r[2]),[t,i]}}e.s(["StringCoercer",0,e4],22175);class e3 extends Error{constructor(e,t){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}}class e5 extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}async function e6(e){if(e instanceof e3){let t="";try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function e8(e){return e instanceof e5}function e9(e){if(e instanceof e3)return 502===e.status||504===e.status;if(!(e instanceof e5))return!1;let t=e.error;return"ECONNREFUSED"!==(t?.code??t?.cause?.code)}function e7(e){return"object"==typeof e&&e instanceof e3&&413===e.status}function te(e){return e instanceof e3?408===e.status||429===e.status||e.status>=500:e8(e)}function tt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}let ti="default";class tr{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new ef([new e1,new eW,new e4,new eG],eD())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new ed,this._events=new eh,this._isInitialized=!1;const i="string"==typeof e?e.trim():"",r="string"==typeof t.host?t.host.trim():"",s=!i;this._logger=function(e,t=e=>e()){return eg(e,t,function(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),s&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=i,this.host=function(e){return e?.replace(/\/+$/,"")}(r||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1e3),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3e3,retryCheck:te},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||s,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!("CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&"function"==typeof Response.prototype.blob)||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){return this.disabled?void this._logger.warn("The client is disabled"):this._isInitialized?e():void this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(g.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(g.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(g.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let e=this.on("*",(e,t)=>this._logger.info(e,t));this.removeDebugCallback=()=>{e(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},i={...t,...this.getCommonEventProperties()};var r=i;for(let e of Object.keys(t))(e.startsWith("$feature/")||"$active_feature_flags"===e)&&(r[e]=t[e]);return"$feature_flag_called"===e.event&&!1===i.$feature_flag_has_experiment&&this.isMinimalFlagCalledEventsEnabled()&&(i=d(i)),{distinct_id:e.distinct_id,event:e.event,properties:i}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,i){this.wrap(()=>{let r={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",r,i)})}async identifyStatelessImmediate(e,t,i){let r={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",r,i)}captureStateless(e,t,i,r){this.wrap(()=>{let s=this.buildPayload({distinct_id:e,event:t,properties:i});this.enqueue("capture",s,r)})}async captureStatelessImmediate(e,t,i,r){let s=this.buildPayload({distinct_id:e,event:t,properties:i});await this.sendImmediate("capture",s,r)}aliasStateless(e,t,i,r){this.wrap(()=>{let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...i||{},distinct_id:t,alias:e}});this.enqueue("alias",s,r)})}async aliasStatelessImmediate(e,t,i,r){let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...i||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",s,r)}groupIdentifyStateless(e,t,i,r,s,a){this.wrap(()=>{let n=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{},...a||{}}});this.enqueue("capture",n,r)})}async groupIdentifyStatelessImmediate(e,t,i,r,s,a){let n=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{},...a||{}}});await this.sendImmediate("capture",n,r)}async getRemoteConfig(){await this._initPromise;let e=this.host;"https://us.i.posthog.com"===e?e="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===e&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.apiKey}/config`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,i,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(e=>e.json()).catch(e=>{this._logger.error("Remote config could not be loaded",e),this._events.emit("error",e)})}async getFlags(e,t={},i={},r={},s={},a=!1){await this._initPromise;let n=`${this.host}/flags/?v=2${a?"&config=true":""}`,o={token:this.apiKey,distinct_id:e,groups:t,person_properties:i,group_properties:r,...s};i.$device_id&&(o.$device_id=i.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(o.evaluation_contexts=this.evaluationContexts);let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(o)};return this._logger.info("Flags URL",n),this.fetchWithRetry(n,l,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:e9},this.featureFlagsRequestTimeoutMs).then(e=>e.json()).then(e=>({success:!0,response:(e=>{if("flags"in e){let t,i=Object.fromEntries(Object.entries(e.flags??{}).map(([e,t])=>[e,u(t)]).filter(([,e])=>void 0!==e)),r=Object.fromEntries(Object.keys(t=e.flags??{}).filter(e=>{let i=t[e];return i.enabled&&i.metadata&&void 0!==i.metadata.payload}).map(e=>{let i=t[e].metadata?.payload;return[e,i?c(i):void 0]}));return{...e,featureFlags:i,featureFlagPayloads:r}}{let t=e.featureFlags??{},i=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([e,t])=>[e,c(t)])),r=Object.fromEntries(Object.entries(t).map(([e,t])=>{var r,s;return[e,{key:e,enabled:"string"==typeof(r=t)||r,variant:"string"==typeof r?r:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:(s=i[e])?JSON.stringify(s):void 0,description:void 0}}]}));return{...e,featureFlags:t,featureFlagPayloads:i,flags:r}}})(e)})).catch(e=>(this._events.emit("error",e),{success:!1,error:this.categorizeRequestError(e)}))}categorizeRequestError(e){if(e instanceof e3)return{type:"api_error",statusCode:e.status};if(e instanceof e5){let t=e.error;return t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,i={},r={},s={},a){await this._initPromise;let n=await this.getFeatureFlagDetailStateless(e,t,i,r,s,a);if(void 0===n)return{response:void 0,requestId:void 0};let o=u(n.response);return void 0===o&&(o=!1),{response:o,requestId:n.requestId}}async getFeatureFlagDetailStateless(e,t,i={},r={},s={},a){await this._initPromise;let n=await this.getFeatureFlagDetailsStateless(t,i,r,s,a,[e]);if(void 0!==n)return{response:n.flags[e],requestId:n.requestId,evaluatedAt:n.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,i={},r={},s={},a){await this._initPromise;let n=await this.getFeatureFlagPayloadsStateless(t,i,r,s,a,[e]);if(!n)return;let o=n[e];return void 0===o?null:o}async getFeatureFlagPayloadsStateless(e,t={},i={},r={},s,a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,i,r,s,a)).payloads}async getFeatureFlagsStateless(e,t={},i={},r={},s,a){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,i,r,s,a)}async getFeatureFlagsAndPayloadsStateless(e,t={},i={},r={},s,a){await this._initPromise;let n=await this.getFeatureFlagDetailsStateless(e,t,i,r,s,a);return n?{flags:n.featureFlags,payloads:n.featureFlagPayloads,requestId:n.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},i={},r={},s,a){await this._initPromise;let n={geoip_disable:s??this.disableGeoip};a&&(n.flag_keys_to_evaluate=a);let o=await this.getFlags(e,t,i,r,n);if(!o.success)return;let l=o.response;return(l.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),l.quotaLimited?.includes("feature_flags"))?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},i=await this.fetchWithRetry(e,t).then(e=>{if(200!==e.status||!e.json){let t=`Surveys API could not be loaded: ${e.status}`,i=Error(t);this._logger.error(i),this._events.emit("error",Error(t));return}return e.json()}).catch(e=>{this._logger.error("Surveys API could not be loaded",e),this._events.emit("error",e)}),r=i?.surveys;return r&&this._logger.info("Surveys fetched from API: ",JSON.stringify(r)),r??[]}get props(){return this._props||(this._props=this.getPersistedProperty(g.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(g.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(g.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return ti}persistedQueueKeyForRoute(e){return g.Queue}getActiveQueueRoutes(){return[ti]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let r=this.prepareMessage(t,i);if(null===(r=this.processBeforeEnqueue(r)))return;r=this.normalizeMessage(r);let s=this.persistedQueueKeyForRoute(this.getQueueRouteKey(r)),a=this.getPersistedProperty(s)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:r}),this.setPersistedProperty(s,a),this._events.emit(e,r),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=W(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let r=this.prepareMessage(t,i);if(null!==(r=this.processBeforeEnqueue(r))){r=this.normalizeMessage(r);try{await this.sendBatch([r],void 0,this.getQueueRouteKey(r))}catch(e){this._events.emit("error",e)}}}normalizeMessage(e){let{type:t,library:i,library_version:r,...s}=e,a=tt(s.properties)?s.properties:void 0;return void 0!==i&&a?.$lib===void 0&&(a={...a||{},$lib:i}),void 0!==r&&a?.$lib_version===void 0&&(a={...a||{},$lib_version:r}),a&&(s.properties=a),s.uuid=U(s.uuid,er),s}prepareMessage(e,t){let i={...e,timestamp:t?.timestamp?t?.timestamp:H(),uuid:U(t?.uuid,er)};return(t?.disableGeoip??this.disableGeoip)&&(tt(i.properties)||(i.properties={}),i.properties.$geoip_disable=!0),i.distinctId&&(i.distinct_id=i.distinctId,delete i.distinctId),i}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flush().catch(async e=>{await e6(e)})}async waitForPendingPromises(e,t=[]){let i=t.filter(e=>!!e),r=0;for(;;){let t=this.promiseQueue.getPromises([...i,...this.flushPromises],e);if(0===t.length)return;r>0&&this._logger.debug(`flush() re-checking ${t.length} pending promise(s) before flushing`),await Promise.all(t.map(e=>e.catch(()=>{}))),r++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,i=this.promiseQueue.maxId,r=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(i,[t,r])}).then(()=>K([t])).then(()=>(this.pendingFlushPromise===r&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=r,this.flushPromise=r,this.flushPromises.add(r),this.addPendingPromise(r),K([r]).then(()=>{this.flushPromises.delete(r),this.pendingFlushPromise===r&&(this.pendingFlushPromise=null),this.flushPromise===r&&(this.flushPromise=null)}),r}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&""!==e&&(t["User-Agent"]=e),t}async sendBatch(e,t,i=ti){let r={api_key:this.apiKey,batch:e,sent_at:H()};this.historicalMigration&&(r.historical_migration=!0);let s=v(r),a=`${this.host}/batch/`,n=this.disableCompression?null:await m(s,this.isDebug),o={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==n&&{"Content-Encoding":"gzip"}},body:n||s},l=await this.fetchWithRetry(a,o,t);await l.body?.cancel()?.catch(()=>{})}async _flush(){let e;this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(e=>this.getRouteQueue(e).length>0))return;let i=[];for(let r of t)try{await this._flushRoute(r,i)}catch(t){void 0===e&&(e=t)}if(void 0!==e)throw e;this._events.emit("flush",i)}async _flushRoute(e,t){let i=this.persistedQueueKeyForRoute(e),r=this.getPersistedProperty(i)||[];if(!r.length)return;let s=r.length,a=0;for(;r.length>0&&a<s;){let s=r.slice(0,this.maxBatchSize),n=s.map(e=>void 0===e.message?e.message:this.normalizeMessage(e.message)),o=async()=>{let e=this.getPersistedProperty(i)||[],t=[...s],a=e.filter(e=>{let i=e.message?.uuid,r=t.findIndex(t=>t===e||"string"==typeof i&&i.length>0&&t.message?.uuid===i);return -1===r||(t.splice(r,1),!1)});this.setPersistedProperty(i,a),r=a,this._dequeuedMessagesCount+=s.length,await this.flushStorage()},l={retryCheck:e=>!e7(e)&&te(e)};try{await this.sendBatch(n,l,e)}catch(e){if(e7(e)&&n.length>1){this.maxBatchSize=Math.max(1,Math.floor(n.length/2)),this._logger.warn(`Received 413 when sending batch of size ${n.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw e instanceof e5||await o(),this._events.emit("error",e),e}await o(),t.push(...n),a+=n.length}}async _sendLogsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),i=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,r=this.disableCompression?null:await m(t,this.isDebug),s={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==r&&{"Content-Encoding":"gzip"}},body:r||t};try{return await this.fetchWithRetry(i,s,{retryCheck:e=>!e7(e)&&te(e)}),{kind:"ok"}}catch(e){if(e7(e))return{kind:"too-large"};if(e instanceof e5)return{kind:"retry-later",error:e};return{kind:"fatal",error:e}}}async _sendMetricsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),i=`${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`,r=this.disableCompression?null:await m(t,this.isDebug),s={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==r&&{"Content-Encoding":"gzip"}},body:r||t};try{return await this.fetchWithRetry(i,s,{retryCheck:e=>!e7(e)&&te(e)}),{kind:"ok"}}catch(e){if(e7(e))return{kind:"too-large"};if(te(e))return{kind:"retry-later",error:e};return{kind:"fatal",error:e}}}async fetchWithRetry(e,t,i,r){let s=t.body?t.body:"",a=-1;try{a=s instanceof Blob?s.size:Buffer.byteLength(s,"utf8")}catch{a=s instanceof Blob?s.size:new TextEncoder().encode(s).length}return await q(async()=>{let i=new AbortController,s=W(()=>i.abort(),r??this.requestTimeout),n=null;try{n=await this.fetch(e,{signal:i.signal,...t})}catch(e){throw new e5(e)}finally{clearTimeout(s)}if("no-cors"!==t.mode&&(n.status<200||n.status>=400))throw new e3(n,a);return n},{...this._retryOptions,...i})}async _shutdown(e=3e4){await this._initPromise;let t=!1;if(this.clearFlushTimer(),!this.disabled)return z((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(e=>this.getRouteQueue(e).length>0);){let e=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===e){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(e){if(!("object"==typeof e&&(e instanceof e3||e8(e))))throw e;await e6(e)}})(),e,()=>{throw this._logger.error("Timed out while shutting down PostHog"),t=!0,"Timeout while shutting down PostHog. Some events may not have been sent."})}async shutdown(e=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}e.i(21754),e.i(69309),e.i(10728),e.s(["chromeStackLineParser",0,eb,"createDefaultStackParser",0,eD,"createStackParser",0,eB,"geckoStackLineParser",0,eF,"nodeStackLineParser",0,eR,"opera10StackLineParser",0,e$,"opera11StackLineParser",0,eC,"reverseAndStripFrames",0,ej,"winjsStackLineParser",0,ex],22546),e.i(22546),e.i(59567),e.i(33603),e.i(13446),e.i(60887),e.i(22175),e.i(12154),e.i(41324),e.i(79478),e.i(1802),e.s(["DOMExceptionCoercer",0,eU,"ErrorCoercer",0,e1,"ErrorEventCoercer",0,eN,"EventCoercer",0,ez,"ObjectCoercer",0,eW,"PrimitiveCoercer",0,eG,"PromiseRejectionEventCoercer",0,eK,"StringCoercer",0,e4],90166),e.i(90166);class ts{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(void 0!==t)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}}function ta(){let e=globalThis._posthogReleaseId;return"string"==typeof e&&e.length>0?e:void 0}e.s(["ReduceableCache",0,ts],45294),e.i(45294),e.i(45162),e.s(["getInjectedReleaseId",0,ta],56168),e.i(56168),e.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,eJ,"DOMExceptionCoercer",0,eU,"EXCEPTION_STEP_INTERNAL_FIELDS",0,eV,"ErrorCoercer",0,e1,"ErrorEventCoercer",0,eN,"ErrorPropertiesBuilder",0,ef,"EventCoercer",0,ez,"ExceptionStepsBuffer",0,eZ,"ObjectCoercer",0,eW,"PrimitiveCoercer",0,eG,"PromiseRejectionEventCoercer",0,eK,"ReduceableCache",0,ts,"StringCoercer",0,e4,"chromeStackLineParser",0,eb,"createDefaultStackParser",0,eD,"createStackParser",0,eB,"geckoStackLineParser",0,eF,"getInjectedReleaseId",0,ta,"getUtf8ByteLength",0,e0,"nodeStackLineParser",0,eR,"opera10StackLineParser",0,e$,"opera11StackLineParser",0,eC,"resolveExceptionStepsConfig",0,eY,"reverseAndStripFrames",0,ej,"stripReservedExceptionStepFields",0,eX,"winjsStackLineParser",0,ex],11168);var tn=e.i(11168),to=tn,tl=e.i(2157),tu=e.i(12714),tc=e.i(50227),th=e.i(1457);let td=new to.ReduceableCache(25),tg=new to.ReduceableCache(20);async function tf(e,t=tu.open,i){let r,s={};try{r=process.cwd()}catch{}for(let t=e.length-1;t>=0;t--){var a,n;let i=e[t],o=i?.filename;!(!i||"string"!=typeof o||"number"!=typeof i.lineno||(a=o).startsWith("node:")||a.endsWith(".min.js")||a.endsWith(".min.cjs")||a.endsWith(".min.mjs")||a.startsWith("data:")||void 0!==(n=i).lineno&&n.lineno>1e4||void 0!==n.colno&&n.colno>1e3)&&((0,tc.isAbsolute)(o)||void 0!==r)&&(s[o]||(s[o]=[]),s[o].push(i.lineno))}let o=Object.keys(s);if(0==o.length)return e;let l=[];for(let e of o){let a=tv(e,r);if(void 0===a||tg.get(a))continue;let n=s[e];if(!n)continue;n.sort((e,t)=>e-t);let o=function(e){if(!e.length)return[];let t=0,i=e[0];if("number"!=typeof i)return[];let r=t_(i),s=[];for(;;){if(t===e.length-1){s.push(r);break}let i=e[t+1];if("number"!=typeof i)break;i<=r[1]?r[1]=i+7:(s.push(r),r=t_(i)),t++}return s}(n);if(o.every(e=>(function(e,t){let i=td.get(e);if(void 0===i)return!1;for(let e=t[0];e<=t[1];e++)if(void 0===i[e])return!1;return!0})(a,e)))continue;let u=function(e,t,i){let r=e.get(t);return void 0===r?(e.set(t,i),i):r}(td,a,{});l.push(ty(e,o,u,a,t,i))}return await Promise.all(l).catch(()=>{}),e&&e.length>0&&function(e,t,i){for(let r of e)if(r.filename&&void 0===r.context_line&&"number"==typeof r.lineno){let e=tv(r.filename,i),s=void 0===e?void 0:t.get(e);if(void 0===s)continue;!function(e,t,i){if(void 0===t.lineno||void 0===i)return;t.pre_context=[];for(let r=tb(e);r<e;r++){let e=i[r];if(void 0===e)return void tm(t);t.pre_context.push(e)}if(void 0===i[e])return tm(t);t.context_line=i[e];let r=function(e){return e+7}(e);t.post_context=[];for(let s=e+1;s<=r;s++){let e=i[s];if(void 0===e)break;t.post_context.push(e)}}(r.lineno,r,s)}}(e,td,r),td.reduce(),e}async function tp(e,t,i){let r,s=!1;try{r=await t(e,tl.constants.O_RDONLY|tl.constants.O_NONBLOCK);let a=await r.stat();if(!a.isFile())return;if(a.size>0xa00000)return void i?.debug(`Skipping source context for oversized file ${e}: ${a.size} bytes exceeds 10485760`);return s=!0,r}catch{return}finally{r&&!s&&await r.close().catch(()=>{})}}async function ty(e,t,i,r,s,a){let n=await tp(e,s,a);return void 0===n?void tg.set(r,1):new Promise(e=>{let s,a,o=!1;function l(t){o||(o=!0,t?.destroy(),n.close().then(e,e))}try{s=n.createReadStream({autoClose:!1,start:0,end:0x9fffff})}catch{tg.set(r,1),l();return}try{a=(0,th.createInterface)({input:s})}catch{tg.set(r,1),l(s);return}let u=0,c=0,h=t[0];if(void 0===h)return void l(s);let d=h[0],g=h[1];function f(){tg.set(r,1),a.close(),a.removeAllListeners(),l(s)}s.on("error",f),a.on("error",f),a.on("close",()=>l(s)),a.on("line",e=>{if(!(++u<d)&&(i[u]=function(e,t){let i=e,r=i.length;if(r<=150)return i;t>r&&(t=r);let s=Math.max(t-60,0);s<5&&(s=0);let a=Math.min(s+140,r);return a>r-5&&(a=r),a===r&&(s=Math.max(a-140,0)),i=i.slice(s,a),s>0&&(i=`...${i}`),a<r&&(i+="..."),i}(e,0),u>=g)){if(c===t.length-1){a.close(),a.removeAllListeners();return}let e=t[++c];if(void 0===e){a.close(),a.removeAllListeners();return}d=e[0],g=e[1]}})})}function tm(e){delete e.pre_context,delete e.context_line,delete e.post_context}function tv(e,t){return(0,tc.isAbsolute)(e)?JSON.stringify([null,e]):void 0===t?void 0:JSON.stringify([t,e])}function t_(e){return[tb(e),e+7]}function tb(e){return Math.max(1,e-7)}let tw=["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","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],tE=function(e,t=[]){if(!e)return!1;let i=e.toLowerCase();return tw.concat(t).some(e=>{let t=e.toLowerCase();return -1!==i.indexOf(t)})},tF={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};e.s(["FeatureFlagError",0,tF],88096);class tP{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e){let t=this._flags[e];return this._recordAccess(e),t?.enabled??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),t)return!!t.enabled&&(t.variant??!0)}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let i=this._flags[t];i&&(e[t]=i)}return this._cloneWith(e)}only(e){let t={},i=[];for(let r of e){let e=this._flags[r];e?t[r]=e:i.push(r)}return i.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${i.join(", ")}`),this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[i,r]of Object.entries(this._flags)){let s=!1!==r.enabled&&(r.variant??!0);e[`$feature/${i}`]=s,r.enabled&&t.push(i)}return t.length>0&&(t.sort(),e.$active_feature_flags=t),e}_cloneWith(e){return new tP({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),""===this._distinctId||this._isSlice&&!(e in this._flags))return;let t=this._flags[e],i=void 0===t?void 0:!1!==t.enabled&&(t.variant??!0),r={$feature_flag:e,$feature_flag_response:i,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:i,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};t?.hasExperiment!==void 0&&(r.$feature_flag_has_experiment=t.hasExperiment),t?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(r.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let s=[];this._errorsWhileComputing&&s.push(tF.ERRORS_WHILE_COMPUTING),this._quotaLimited&&s.push(tF.QUOTA_LIMITED),void 0===t&&s.push(tF.FLAG_MISSING),s.length>0&&(r.$feature_flag_error=s.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:i,groups:this._groups,disableGeoip:this._disableGeoip,properties:r})}}async function tx(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");return Array.from(new Uint8Array(await t.digest("SHA-1",new TextEncoder().encode(e)))).map(e=>e.toString(16).padStart(2,"0")).join("")}let tS=["is_not","is_set"];class t$ extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,t$.prototype)}}function tI(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class tC extends Error{constructor(e){super(e),tI(this,tC)}}class tk extends Error{constructor(e){super(e),tI(this,tk)}}class tA{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:i,timeout:r,host:s,customHeaders:a,...n}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=r,this.projectApiKey=i,this.host=s,this.poller=void 0,this.fetch=n.fetch||fetch,this.onError=n.onError,this.customHeaders=a,this.onLoad=n.onLoad,this.onMinimalFlagCalledEvents=n.onMinimalFlagCalledEvents,this.cacheProvider=n.cacheProvider,this.strictLocalEvaluation=n.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}createEvaluationContext(e,t={},i={},r={},s={}){return{distinctId:e,groups:t,personProperties:i,groupProperties:r,evaluationCache:s}}async getFeatureFlag(e,t,i={},r={},s={}){let a,n;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return a;if(void 0!==(n=this.featureFlagsByKey[e])){let o=this.createEvaluationContext(t,i,r,s);try{a=(await this.computeFlagAndPayloadLocally(n,o)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${a}`))}catch(t){t instanceof tk||t instanceof tC?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e}: ${t}`))}}return a}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let i={},r={},s=0==this.featureFlags.length,a=t?t.map(e=>this.featureFlagsByKey[e]).filter(Boolean):this.featureFlags,n={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(a.map(async e=>{try{let{value:t,payload:s}=await this.computeFlagAndPayloadLocally(e,n);i[e.key]=t,s&&(r[e.key]=s)}catch(t){t instanceof tk||t instanceof tC?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e.key}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e.key}: ${t}`)),s=!0}})),{response:i,payloads:r,fallbackToFlags:s}}async computeFlagAndPayloadLocally(e,t,i={}){let r,{matchValue:s,skipLoadCheck:a=!1}=i;if(a||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};r=void 0!==s?s:await this.computeFlagValueLocally(e,t);let n=this.getFeatureFlagPayload(e.key,r);return{value:r,payload:n}}async computeFlagValueLocally(e,t){let{distinctId:i,groups:r,personProperties:s,groupProperties:a}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new tC("Flag has experience continuity enabled");let n=(e.filters||{}).aggregation_group_type_index;if(void 0!=n){let i=this.groupTypeMapping[String(n)];if(!i)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${n} for feature flag ${e.key}`)),new tC("Flag has unknown group type index");if(!(i in r))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;"device_id"===e.bucketing_identifier&&(s?.$device_id===void 0||s?.$device_id===null||s?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let o=a[i];return await this.matchFeatureFlagProperties(e,r[i],o,t)}{let r=this.getBucketingValueForFlag(e,i,s);if(void 0===r)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new tC(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,r,s,t)}}getBucketingValueForFlag(e,t,i){if(e.filters?.aggregation_group_type_index!=void 0)return t;if("device_id"===e.bucketing_identifier){let e=i?.$device_id;if(null==e||""===e)return;return e}return t}getFeatureFlagPayload(e,t){let i=null;if(!1!==t&&null!=t&&("boolean"==typeof t?i=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null:"string"==typeof t&&(i=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null),null!=i)){if("object"==typeof i)return i;if("string"==typeof i)try{return JSON.parse(i)}catch{}return i}return null}async evaluateFlagDependency(e,t,i){let{evaluationCache:r}=i,s=e.key;if(!this.featureFlagsByKey)throw new tC("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new tC(`Flag dependency property for '${s}' is missing required 'dependency_chain' field`);let a=e.dependency_chain;if(!Array.isArray(a))throw new tC(`Flag dependency property for '${s}' has an invalid 'dependency_chain' (expected array, got ${typeof a})`);if(0===a.length)throw new tC(`Circular dependency detected for flag '${s}' (empty dependency chain)`);for(let e of a){if(!(e in r)){let t=this.featureFlagsByKey[e];if(t)if(t.active)try{let s=await this.computeFlagValueLocally(t,i);r[e]=s}catch(t){throw new tC(`Error evaluating flag dependency '${e}' for flag '${s}': ${t}`)}else r[e]=!1;else throw new tC(`Missing flag dependency '${e}' for flag '${s}'`)}if(null==r[e])throw new tC(`Dependency '${e}' could not be evaluated`)}let n=r[s];return this.flagEvaluatesToExpectedValue(e.value,n)}flagEvaluatesToExpectedValue(e,t){return"boolean"==typeof e?e===t||"string"==typeof t&&""!==t&&!0===e:"string"==typeof e&&t===e}async matchFeatureFlagProperties(e,t,i,r){let s,a=e.filters||{},n=a.groups||[],o=a.aggregation_group_type_index,l=a.early_exit??!1,{groups:u,groupProperties:c}=r,h=!1;for(let d of n)try{let n=void 0!==d.aggregation_group_type_index?d.aggregation_group_type_index:o,g=i,f=t;if(n!==o&&null!=n){let t=this.groupTypeMapping[String(n)];if(!t||!(t in u)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${n} not available`));continue}if(!(t in c)){h=!0;continue}g=c[t],f=u[t]}let p=await this.isConditionMatch(e,f,d,g,r);if("match"===p){let t=d.variant,i=a.multivariate?.variants||[];s=t&&i.some(e=>e.key===t)?t:await this.getMatchingVariant(e,f)||!0;break}if(l&&"out_of_rollout_bound"===p)return!1}catch(e){if(e instanceof tk)throw e;if(e instanceof tC)h=!0;else throw e}if(void 0!==s)return s;if(h)throw new tC("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,i,r,s){let a=i.rollout_percentage,n=e=>{this.logMsgIfDebug(()=>console.warn(e))};if((i.properties||[]).length>0){for(let e of i.properties){let t=e.type,i=!1;if("cohort"===t){let t=await tR(e,r,this.cohorts,this.debugMode,e=>this.evaluateFlagDependency(e,r,s));i="not_in"===e.operator?!t:t}else i="flag"===t?await this.evaluateFlagDependency(e,r,s):tM(e,r,n);if(!i)return"no_match"}if(void 0==a)return"match"}return void 0!=a&&await tO(e.key,t)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){let i=await tO(e.key,t,"variant"),r=this.variantLookupTable(e).find(e=>i>=e.valueMin&&i<e.valueMax);if(r)return r.key}variantLookupTable(e){let t=[],i=0,r=0,s=e.filters||{};return(s.multivariate?.variants||[]).forEach(e=>{r=i+e.rollout_percentage/100,t.push({valueMin:i,valueMax:r,key:e.key}),i=r}),t}updateFlagState(e){this.featureFlags=e.flags,this.featureFlagsByKey=e.flags.reduce((e,t)=>(e[t.key]=t,e),{}),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(!0===e.minimalFlagCalledEvents)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter(e=>e.ensure_experience_continuity);t.length>0&&console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map(e=>e.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();if(t)return this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(t.flags),!0;return!1}catch(e){return this.onError?.(Error(`Failed to load from cache: ${e}`)),!1}}async loadFeatureFlags(e=!1){if(!this.loadedSuccessfullyOnce||e)return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(e=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${e}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(6e4,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(e){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${e}`))}if(!e&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new t$(`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.groupTypeMapping={},this.cohorts={},this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new t$(`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 t$(`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 i=await t.json()??{};if(!("flags"in i))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let r={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{},minimalFlagCalledEvents:!0===i.minimal_flag_called_events};if(this.updateFlagState(r),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(r)}catch(e){this.onError?.(Error(`Failed to store in cache: ${e}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(r.flags);break}default:return}}catch(e){e instanceof t$&&this.onError?.(e)}}getPersonalApiKeyRequestOptions(e="GET",t){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(i["If-None-Match"]=t),{method:e,headers:i}}async _requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&"number"==typeof this.timeout){let e=new AbortController;i=W(()=>{e.abort()},this.timeout),t.signal=e.signal}try{let r=this.fetch,s=await r(e,t);if(200!==s.status)return clearTimeout(i),s;return{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{clearTimeout(i)}},json:async()=>{try{return await s.json()}finally{clearTimeout(i)}}}}catch(e){throw clearTimeout(i),e}}async stopPoller(e=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await z(t,e,()=>{throw Error(`Cache shutdown timeout after ${e}ms`)})}catch(e){this.onError?.(Error(`Error during cache shutdown: ${e}`))}}}async function tO(e,t,i=""){return parseInt((await tx(`${e}.${t}${i}`)).slice(0,15),16)/0x1000000000000000}function tM(e,t,i){let r=e.key,s=e.value,a=e.operator||"exact";if(r in t){if("is_not_set"===a)return!1}else{if("is_not_set"===a)return!0;throw new tC(`Property ${r} not found in propertyValues`)}let n=t[r];if(null==n&&!tS.includes(a))return i&&i(`Property ${r} cannot have a value of null/undefined with the ${a} operator`),!1;function o(e,t){return Array.isArray(e)?e.map(e=>String(e).toLowerCase()).includes(String(t).toLowerCase()):String(e).toLowerCase()===String(t).toLowerCase()}function l(e,t,i){if("gt"===i)return e>t;if("gte"===i)return e>=t;if("lt"===i)return e<t;if("lte"===i)return e<=t;throw Error(`Invalid operator: ${i}`)}switch(a){case"exact":return o(s,n);case"is_not":return!o(s,n);case"is_set":return r in t;case"icontains":return String(n).toLowerCase().includes(String(s).toLowerCase());case"not_icontains":return!String(n).toLowerCase().includes(String(s).toLowerCase());case"regex":return tL(String(s))&&null!==String(n).match(String(s));case"not_regex":return tL(String(s))&&null===String(n).match(String(s));case"gt":case"gte":case"lt":case"lte":{let e,t="number"==typeof s?s:parseFloat(String(s));if(e="number"==typeof n?n:null!=n?parseFloat(String(n)):NaN,Number.isFinite(t)&&Number.isFinite(e))return l(e,t,a);return l(String(n),String(s),a)}case"is_date_after":case"is_date_before":{if("boolean"==typeof s)throw new tC("Date operations cannot be performed on boolean values");let e=function(e){let t=e.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),i=new Date(new Date().toISOString());if(!t)return null;{if(!t.groups)return null;let e=parseInt(t.groups.number);if(e>=1e4)return null;let r=t.groups.interval;if("h"==r)i.setUTCHours(i.getUTCHours()-e);else if("d"==r)i.setUTCDate(i.getUTCDate()-e);else if("w"==r)i.setUTCDate(i.getUTCDate()-7*e);else if("m"==r)i.setUTCMonth(i.getUTCMonth()-e);else{if("y"!=r)return null;i.setUTCFullYear(i.getUTCFullYear()-e)}return i}}(String(s));if(null==e&&(e=tU(s)),null==e)throw new tC(`Invalid date: ${s}`);let t=tU(n);if(["is_date_before"].includes(a))return t<e;return t>e}case"semver_eq":return 0===tB(tD(String(n)),tD(String(s)));case"semver_neq":return 0!==tB(tD(String(n)),tD(String(s)));case"semver_gt":return tB(tD(String(n)),tD(String(s)))>0;case"semver_gte":return tB(tD(String(n)),tD(String(s)))>=0;case"semver_lt":return 0>tB(tD(String(n)),tD(String(s)));case"semver_lte":return 0>=tB(tD(String(n)),tD(String(s)));case"semver_tilde":{let e,t=tD(String(n)),{lower:i,upper:r}={lower:[(e=tD(String(s)))[0],e[1],e[2]],upper:[e[0],e[1]+1,0]};return tB(t,i)>=0&&0>tB(t,r)}case"semver_caret":{let e=tD(String(n)),{lower:t,upper:i}=function(e){let[t,i,r]=tD(e);return{lower:[t,i,r],upper:t>0?[t+1,0,0]:i>0?[0,i+1,0]:[0,0,r+1]}}(String(s));return tB(e,t)>=0&&0>tB(e,i)}case"semver_wildcard":{let e=tD(String(n)),{lower:t,upper:i}=function(e){let t,i,r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new tC(`Invalid wildcard semver: ${e}`);let s=r.split("."),a=t=>{try{return tj(t,e)}catch{throw new tC(`Invalid wildcard semver: ${e}`)}},n=a(s[0]);if(1===s.length)t=[n,0,0],i=[n+1,0,0];else{let e=a(s[1]);t=[n,e,0],i=[n,e+1,0]}return{lower:t,upper:i}}(String(s));return tB(e,t)>=0&&0>tB(e,i)}default:throw new tC(`Unknown operator: ${a}`)}}async function tR(e,t,i,r=!1,s){let a=String(e.value);if(!(a in i))throw new tk(`cohort ${a} not found in local cohorts - likely a static cohort that requires server evaluation`);return tT(i[a],t,i,r,s)}async function tT(e,t,i,r=!1,s){if(!e)return!0;let a=e.type,n=e.values;if(!n||0===n.length)return!0;let o=!1;if("values"in n[0]){for(let e of n)try{let n=await tT(e,t,i,r,s);if("AND"===a){if(!n)return!1}else if(n)return!0}catch(t){if(t instanceof tk)throw t;if(t instanceof tC)r&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0;else throw t}if(o)throw new tC("Can't match cohort without a given cohort property value");return"AND"===a}for(let e of n)try{let n;if("cohort"===e.type)n=await tR(e,t,i,r,s);else if("flag"===e.type){if(!s)throw new tC(`Flag dependency '${e.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);n=await s(e)}else n=tM(e,t);let o=e.negation||!1;if("AND"===a){if(!n&&!o||n&&o)return!1}else if(n&&!o||!n&&o)return!0}catch(t){if(t instanceof tk)throw t;if(t instanceof tC)r&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0;else throw t}if(o)throw new tC("can't match cohort without a given cohort property value");return"AND"===a}function tL(e){try{return new RegExp(e),!0}catch(e){return!1}}function tj(e,t){if(!/^\d+$/.test(e)||e.length>1&&"0"===e[0])throw new tC(`Invalid semver: ${t}`);return parseInt(e,10)}function tD(e){let t=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!t||t.startsWith("."))throw new tC(`Invalid semver: ${e}`);let i=t.split("."),r=t=>void 0===t||""===t?0:tj(t,e);return[r(i[0]),r(i[1]),r(i[2])]}function tB(e,t){for(let i=0;i<3;i++){if(e[i]<t[i])return -1;if(e[i]>t[i])return 1}return 0}function tU(e){if(e instanceof Date)return e;if("string"==typeof e||"number"==typeof e){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new tC(`${e} is in an invalid date format`)}throw new tC(`The date provided ${e} must be a string, number, or date object`)}function tN(e,t,i,r,s){if(t>i&&(r.warn("min cannot be greater than max."),t=i),$(e))if(e>i)return r.warn(" cannot be greater than max: "+i+". Using max value instead."),i;else return e<t?(r.warn(" cannot be less than min: "+t+". Using min value instead."),t):e;return r.warn(" must be a number. using max or fallback. max: "+i+", fallback: "+s),tN(s||i,t,i,r)}class tq{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=tN(e.bucketSize,0,100,e._logger),this._refillRate=tN(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=tN(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){let i=Math.floor((t-e.lastAccess)/this._refillInterval);if(i>0){let t=i*this._refillRate;e.tokens=Math.min(e.tokens+t,this._bucketSize),e.lastAccess=e.lastAccess+i*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),i=String(e),r=this._buckets[i];return r?this._applyRefill(r,t):(r={tokens:this._bucketSize,lastAccess:t},this._buckets[i]=r),0===r.tokens||(r.tokens--,0===r.tokens&&this._onBucketRateLimited?.(e),0===r.tokens)}stop(){this._buckets={}}}var to=tn;class tH{constructor(e,t,i){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new tq({...function(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??1,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??10}}(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return F(e)&&"__posthog_previously_captured_error"in e&&!0===e.__posthog_previously_captured_error}static async buildEventMessage(e,t,i,r,s){let a={...s},n=e.buildFromUnknown(t,i);n.$exception_list=await e.modifyFrames(n.$exception_list);let o=to.getInjectedReleaseId();return o&&(a.$release_id=o),{event:"$exception",distinctId:r,properties:{...n,...a},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled()){var t,i,r;let s;t=this.onException.bind(this),i=this.onFatalError.bind(this),globalThis.process?.on("uncaughtException",(s=!1,Object.assign(r=>{let a=e.g.process.listeners("uncaughtException").filter(e=>"domainUncaughtExceptionClear"!==e.name&&!0!==e._posthogErrorHandler).length;t(r,{mechanism:{type:"onuncaughtexception",handled:!1}}),s||0!==a||(s=!0,i(r))},{_posthogErrorHandler:!0}))),r=this.onException.bind(this),globalThis.process?.on("unhandledRejection",e=>r(e,{mechanism:{type:"onunhandledrejection",handled:!1}}))}}onException(e,t){this.client.addPendingPromise((async()=>{if(!tH.isPreviouslyCapturedError(e)){let i=await tH.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),r=i.properties,s=r?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(s)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:s}):this.client._capturePreparedEvent(i,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(2e3),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class tW{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=null!==t?t:void 0}constructor(){this._memoryStorage={}}}let tz="analytics";class tG extends Error{constructor({requestId:e,drops:t,retryExhausted:i,cause:r}){super(tG.buildMessage(e,t,i,r)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=i,this.cause=r}static buildMessage(e,t,i,r){let s=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${i.length} undelivered`;return r instanceof Error&&(s+=` (${r.message})`),s}}function tK(e){if("boolean"==typeof e)return e;if("number"==typeof e)return 0!==e;if("string"==typeof e){let t=e.trim().toLowerCase();if("true"===t||"1"===t)return!0;if("false"===t||"0"===t)return!1}}let tV=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:tK},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:tK},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:tK},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(e){return"string"==typeof e?e:void 0}}],tQ=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function tJ(e,t,i){void 0===i||t in e||(e[t]=i)}function tY(e){var t;let i={..."object"==typeof(t=e.properties)&&null!==t&&!Array.isArray(t)?e.properties:{}},r={};for(let{property:e,optionKey:t,coerce:s}of tV)if(e in i){let a=s(i[e]);void 0!==a&&(r[t]=a),delete i[e]}let s={};for(let{property:e,field:t}of tQ)if(e in i){let r=i[e];"string"==typeof r&&(s[t]=r),delete i[e]}return delete i.$lib,delete i.$lib_version,tJ(i,"$set",e.$set),tJ(i,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:function(e){if("string"==typeof e)return Number.isNaN(new Date(e).getTime())?new Date().toISOString():e;if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=null==e?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}(e.timestamp),...s,options:r,properties:i}}let tX=new Set([408,500,502,503,504]);class tZ{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??3e4,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??(e=>new Promise(t=>W(t,e))),this.generateRequestId=t.generateRequestId??er,this.compress=t.compress??m}async sendV1Batch(e){if(0===e.length)return;let t=this.generateRequestId(),i=new Date(this.now()).toISOString(),{batch:r}=function(e,{createdAt:t,historicalMigration:i}){let r={created_at:t,batch:e.map(tY)};return i&&(r.historical_migration=!0),r}(e,{createdAt:i,historicalMigration:this.config.historicalMigration}),s=`${this.config.host}/i/v1/analytics/events`,a=[],n=r,o=Math.max(1,this.config.maxAttempts);for(let e=1;e<=o;e++){let r,l,u=e===o,c=v({created_at:i,...this.config.historicalMigration?{historical_migration:!0}:{},batch:n});try{r=await this.sendOnce(s,c,e,t)}catch(i){if(u)return this.surfaceBatchFailure(t,a,n,i);await this.sleep(this.backoffDelay(e));continue}let{status:h}=r;if(h<200||h>=300){if(!u&&tX.has(h)){let t=this.parseRetryAfter(r);await this.cancelBody(r),await this.sleep(this.backoffDelay(e,t));continue}let i=await this.buildHttpError(r,h);return this.surfaceBatchFailure(t,a,n,i)}try{l=await this.parseResponse(r)}catch{return this.surfaceBatchFailure(t,a,n,Error(`Capture V1 returned an unparseable ${h} response body`))}let d=this.classify(n,l,a);if(0===d.length)return this.surfacePartialDrops(t,a);if(u)return void this.onError(new tG({requestId:t,drops:a,retryExhausted:d.map(e=>e.uuid)}));n=d;let g=this.parseRetryAfter(r);await this.sleep(this.backoffDelay(e,g))}}async sendOnce(e,t,i,r){let s=this.buildHeaders(i,r),a=t;if(this.config.compressionEnabled){let e=await this.compress(t,this.config.isDebug);null!==e&&(a=e,s["Content-Encoding"]="gzip")}let n=new AbortController,o=W(()=>n.abort(),this.config.requestTimeoutMs);try{return await this.fetchFn(e,{method:"POST",headers:s,body:a,signal:n.signal})}finally{clearTimeout(o)}}buildHeaders(e,t){let i=`${this.config.libraryId}/${this.config.libraryVersion}`,r={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":i,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(r["User-Agent"]=this.config.userAgent),r}classify(e,t,i){let r=t.results??{},s=[];for(let t of e){let e=r[t.uuid];e&&("drop"===e.result?i.push({uuid:t.uuid,details:e.details??void 0}):"retry"===e.result&&s.push(t))}return s}backoffDelay(e,t){let i=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return void 0===t?i:Math.max(i,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let i=t.trim();if(/^\d+$/.test(i)){let e=parseInt(i,10);return Number.isFinite(e)&&e>0?1e3*e:void 0}let r=Date.parse(i);if(Number.isNaN(r))return;let s=r-this.now();return s>0?s:void 0}async parseResponse(e){let t=JSON.parse(await e.text());if("object"!=typeof t||null===t||Array.isArray(t))throw Error("unexpected response shape");let i=t.results;if(void 0!==i&&("object"!=typeof i||null===i||Array.isArray(i)))throw Error("unexpected results shape");return{results:i??{}}}async buildHttpError(e,t){let i="";try{i=(await e.text()).slice(0,512)}catch{}let r=i?`: ${i}`:"";return Error(`Capture V1 request failed with HTTP ${t}${r}`)}surfaceBatchFailure(e,t,i,r){this.onError(new tG({requestId:e,drops:t,retryExhausted:i.map(e=>e.uuid),cause:r}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new tG({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}}let t0=new Set;function t1(e,t){t0.has(e)||(t0.add(e),console.warn(`[PostHog] ${t}`))}class t2 extends tr{constructor(e,t={}){const i=function(e){return"string"==typeof e?e.trim():""}(e),r={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:function(e){return("string"==typeof e?e.trim():"")||"https://us.i.posthog.com"}(t.host),personalApiKey:function(e){return("string"==typeof e?e.trim():"")||void 0}(t.secretKey??t.personalApiKey)};if(super(i,r),this._memoryStorage=new tW,this._minimalFlagCalledEvents=!1,this.options=r,this.captureMode=function(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return"v0"===e||"v1"===e?e:"v0"}(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof r.featureFlagsPollingInterval?Math.max(r.featureFlagsPollingInterval,100):3e4,"number"==typeof r.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(r.waitUntilDebounceMs,0)),"number"==typeof r.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(r.waitUntilMaxWaitMs,0)),!this.disabled&&r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');!1!==r.enableLocalEvaluation&&(this.featureFlagsPoller=new tA({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:i,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:e=>{this._events.emit("error",e)},onLoad:e=>{this._events.emit("localEvaluationFlagsLoaded",e)},onMinimalFlagCalledEvents:e=>{this._minimalFlagCalledEvents=e},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new tH(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||5e4}enqueue(e,t,i){super.enqueue(e,t,i),this.scheduleDebouncedFlush()}async flush(){let e=this.flushWithPendingPromises(),t=this.options.waitUntil;if(t&&!this._waitUntilCycle)try{t(e.catch(()=>{}))}catch{}return e}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let t,i=new Promise(e=>{t=e});try{e(i)}catch{return}this._waitUntilCycle={resolve:t,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,i=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),t>=i)return void this.resolveWaitUntilFlush();let r=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=W(()=>{this.resolveWaitUntilFlush()},r)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this.flushWithPendingPromises()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){var t;return"v1"===this.captureMode&&"string"==typeof(t=e).event&&t.event.startsWith("$ai_")?"ai":tz}persistedQueueKeyForRoute(e){return"ai"===e?g.AiQueue:g.Queue}getActiveQueueRoutes(){return"v1"===this.captureMode?[tz,"ai"]:[tz]}async sendBatch(e,t,i=tz){if("v1"!==this.captureMode||"ai"===i)return super.sendBatch(e,t,i);let r=e.filter(e=>void 0!==e);await this.getV1Sender().sendV1Batch(r)}getV1Sender(){return this._v1Sender||(this._v1Sender=new tZ({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:e=>this._events.emit("error",e)})),this._v1Sender}getLibraryVersion(){return"5.47.7"}get metrics(){var e;let t;return this._metrics||(this._metrics=new X(this,(e=this.options.metrics,t=e?.resourceAttributes,{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1e3}),this._logger)),this._metrics}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,i){"string"==typeof e&&this._logger.warn(t),"$exception"!==e.event||e._originatedFromCaptureException||this._logger.warn(i)}_sendPreparedEvent(e,t,i,r){return this.addPendingPromise(this._prepareEventMessage(t,r).then(({distinctId:t,event:r,properties:s,options:a})=>{let n={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},o={distinctId:t,event:r,properties:{...s,...this.getCommonEventProperties()}};return i?this.sendImmediate(e,o,n):this.enqueue(e,o,n)}).catch(e=>{e&&console.error(e)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}identify({distinctId:e,properties:t={},disableGeoip:i}){let{$set:r,$set_once:s,$anon_distinct_id:a,...n}=t;this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:r||n,$set_once:s||{},$anon_distinct_id:a??void 0},disableGeoip:i},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:i}){let{$set:r,$set_once:s,$anon_distinct_id:a,...n}=t;await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:r||n,$set_once:s||{},$anon_distinct_id:a??void 0},disableGeoip:i},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:i={}}){if(0===Object.keys(t).length&&0===Object.keys(i).length)return;let r={};Object.keys(t).length>0&&(r.$set=t),Object.keys(i).length>0&&(r.$set_once=i),this.capture({distinctId:e,event:"$set",properties:r})}unsetPersonProperties({distinctId:e,properties:t}){let i=(Array.isArray(t)?t:[t]).filter(e=>"string"==typeof e&&e.trim().length>0);0!==i.length&&this.capture({distinctId:e,event:"$set",properties:{$unset:i}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(t=>{let i=setTimeout(()=>{r(),t(!1)},e),r=this._events.on("localEvaluationFlagsLoaded",e=>{clearTimeout(i),r(),t(e>0)})})}_resolveDistinctId(e,t){return"string"==typeof e?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,i={},r){let s,a,n,o,l,u,c,h;if(this.disabled)return void this._logger.warn("The client is disabled");let d=i.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&e in this._flagOverrides){let t=this._flagOverrides[e];if(void 0===t)return;let i=this._payloadOverrides?.[e];return{key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:i}}let{groups:g,disableGeoip:f}=i,{onlyEvaluateLocally:p,personProperties:y,groupProperties:m}=i,v=this.addLocalPersonAndGroupProperties(t,g,y,m);y=v.allPersonProperties,m=v.allGroupProperties;let _=this.createFeatureFlagEvaluationContext(t,g,this.personPropertiesForLocalEvaluation(t,y),m);void 0==p&&(p=this.options.strictLocalEvaluation??!1);let b=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let t=this.featureFlagsPoller?.featureFlagsByKey[e];if(t)try{let i=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(t,_,{matchValue:r});if(i){b=!0;let r=i.value;l=t.id,c="Evaluated locally",h=t.has_experiment,s={key:e,enabled:!1!==r,variant:"string"==typeof r?r:void 0,payload:i.payload??void 0}}}catch(t){if(t instanceof tk||t instanceof tC)this._logger?.info(`${t.name} when computing flag locally: ${e}: ${t.message}`);else throw t}}if(!b&&!p){let t=await super.getFeatureFlagDetailsStateless(_.distinctId,_.groups,y,m,f,[e]);if(void 0===t)o=tF.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===t.minimalFlagCalledEvents,a=t.requestId,n=t.evaluatedAt;let i=[];t.errorsWhileComputingFlags&&i.push(tF.ERRORS_WHILE_COMPUTING),t.quotaLimited?.includes("feature_flags")&&i.push(tF.QUOTA_LIMITED);let r=t.flags[e];if(void 0===r)i.push(tF.FLAG_MISSING);else{let t;if(l=r.metadata?.id,u=r.metadata?.version,c=r.reason?.description??r.reason?.code,h=r.metadata?.has_experiment,r.metadata?.payload!==void 0)try{t=JSON.parse(r.metadata.payload)}catch{t=r.metadata.payload}s={key:e,enabled:r.enabled,variant:r.variant,payload:t}}i.length>0&&(o=i.join(","))}}if(d){let i=void 0===s?void 0:!1!==s.enabled&&(s.variant??!0),r={$feature_flag:e,$feature_flag_response:i,$feature_flag_id:l,$feature_flag_version:u,$feature_flag_reason:c,locally_evaluated:b,[`$feature/${e}`]:i,$feature_flag_request_id:a,$feature_flag_evaluated_at:b?Date.now():n};if(void 0!==h&&(r.$feature_flag_has_experiment=h),b&&this.featureFlagsPoller){let e=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==e&&(r.$feature_flag_definitions_loaded_at=e)}o&&(r.$feature_flag_error=o),this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:i,groups:g,disableGeoip:f,properties:r})}return void 0!==s&&void 0!==this._payloadOverrides&&e in this._payloadOverrides&&(s={...s,payload:this._payloadOverrides[e]}),s}async getFeatureFlag(e,t,i){t1("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 r=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(void 0!==r)return!1!==r.enabled&&(r.variant??!0)}async getFeatureFlagPayload(e,t,i,r){if(t1("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request."),void 0!==this._payloadOverrides&&e in this._payloadOverrides)return this._payloadOverrides[e];let s=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:!1},i);if(void 0!==s)return s.payload??null}async getFeatureFlagResult(e,t,i){let{distinctId:r,options:s}=this._resolveDistinctId(t,i);return r?this._getFeatureFlagResult(e,r,{...s,sendFeatureFlagEvents:s?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let i=await t.json();if("string"==typeof i)try{return JSON.parse(i)}catch(e){}return i}async isFeatureEnabled(e,t,i){t1("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 r=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return void 0===r?void 0:!1!==r.enabled&&!!(r.variant??!0)}async getAllFlags(e,t){let{distinctId:i,options:r}=this._resolveDistinctId(e,t);return i?(await this.getAllFlagsAndPayloads(i,r)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:i,options:r}=this._resolveDistinctId(e,t);if(!i)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads — pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:s,disableGeoip:a,flagKeys:n}=r||{},{onlyEvaluateLocally:o,personProperties:l,groupProperties:u}=r||{},c=this.addLocalPersonAndGroupProperties(i,s,l,u);l=c.allPersonProperties,u=c.allGroupProperties;let h=this.createFeatureFlagEvaluationContext(i,s,this.personPropertiesForLocalEvaluation(i,l),u);void 0==o&&(o=this.options.strictLocalEvaluation??!1);let d=await this.featureFlagsPoller?.getAllFlagsAndPayloads(h,n),g={},f={},p=!0;if(d&&(g=d.response,f=d.payloads,p=d.fallbackToFlags),p&&!o){let e=await super.getFeatureFlagsAndPayloadsStateless(h.distinctId,h.groups,l,u,a,n);g={...g,...e.flags||{}},f={...f,...e.payloads||{}}}return void 0!==this._flagOverrides&&(g={...g,...this._flagOverrides}),void 0!==this._payloadOverrides&&(f={...f,...this._payloadOverrides}),{featureFlags:g,featureFlagPayloads:f}}async evaluateFlags(e,t){let i,r,{distinctId:s,options:a}=this._resolveDistinctId(e,t);if(!s)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new tP({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new tP({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,flags:{}});let{groups:n,disableGeoip:o,flagKeys:l}=a||{},{onlyEvaluateLocally:u,personProperties:c,groupProperties:h}=a||{},d=this.addLocalPersonAndGroupProperties(s,n,c,h);c=d.allPersonProperties,h=d.allGroupProperties;let g=this.createFeatureFlagEvaluationContext(s,n,this.personPropertiesForLocalEvaluation(s,c),h);void 0==u&&(u=this.options.strictLocalEvaluation??!1);let f={},p=!1,y=!1,m=await this.featureFlagsPoller?.getAllFlagsAndPayloads(g,l),v=new Set;if(m)for(let[e,t]of Object.entries(m.response)){let i=this.featureFlagsPoller?.featureFlagsByKey[e];f[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:m.payloads[e],id:i?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:i?.has_experiment},v.add(e)}if((!m||m.fallbackToFlags)&&!u){let e=await super.getFeatureFlagDetailsStateless(g.distinctId,g.groups,c,h,o,l);if(e)for(let[t,s]of(this._minimalFlagCalledEvents=!0===e.minimalFlagCalledEvents,i=e.requestId,r=e.evaluatedAt,p=!!e.errorsWhileComputingFlags,y=Array.isArray(e.quotaLimited)&&e.quotaLimited.includes("feature_flags"),Object.entries(e.flags))){let e;if(!v.has(t)){if(s.metadata?.payload!==void 0)try{e=JSON.parse(s.metadata.payload)}catch{e=s.metadata.payload}f[t]={key:t,enabled:s.enabled,variant:s.variant,payload:e,id:s.metadata?.id,version:s.metadata?.version,reason:s.reason?.description??s.reason?.code,locallyEvaluated:!1,hasExperiment:s.metadata?.has_experiment}}}}if(void 0!==this._flagOverrides)for(let[e,t]of Object.entries(this._flagOverrides)){if(void 0===t){delete f[e];continue}let i=f[e];f[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:i?.payload,id:i?.id,version:i?.version,reason:i?.reason,locallyEvaluated:i?.locallyEvaluated??!1,hasExperiment:i?.hasExperiment}}if(void 0!==this._payloadOverrides)for(let[e,t]of Object.entries(this._payloadOverrides)){let i=f[e];i&&(f[e]={...i,payload:t})}return new tP({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:n,disableGeoip:o,flags:f,requestId:i,evaluatedAt:r,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:p,quotaLimited:y})}_shouldSendMinimalFlagCalledEvent(e,t){return"$feature_flag_called"===e&&this._minimalFlagCalledEvents&&!1===t.$feature_flag_has_experiment}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:i,response:r,groups:s,disableGeoip:a,properties:n}=e,o=s&&Object.keys(s).length>0?`_${JSON.stringify(Object.entries(s).sort(([e],[t])=>e<t?-1:+(e>t)))}`:"",l=`${i}_${r}${o}`;t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(l)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[t]instanceof Set?this.distinctIdHasSentFlagCalls[t].add(l):this.distinctIdHasSentFlagCalls[t]=new Set([l]),this.capture({distinctId:t,event:"$feature_flag_called",properties:n,groups:s,disableGeoip:a}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),logWarning:e=>{!1!==this.options.featureFlagsLogWarnings&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:i,distinctId:r,disableGeoip:s}){this._sendPreparedEvent("capture",{distinctId:r||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{}},disableGeoip:s},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:i,distinctId:r,disableGeoip:s}){await this._sendPreparedEvent("capture",{distinctId:r||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{}},disableGeoip:s},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=e=>Object.fromEntries(e.map(e=>[e,!0]));if(!1===e){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(!1===e.flags?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):void 0!==e.flags&&(this._flagOverrides={...e.flags})),"payloads"in e&&(!1===e.payloads?this._payloadOverrides=void 0:void 0!==e.payloads&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if("flags"in e){let t=e.flags;if(!1===t||Array.isArray(t)||"object"==typeof t&&null!==t)return!0}if("payloads"in e){let t=e.payloads;if(!1===t||"object"==typeof t&&null!==t)return!0}return!1}withContext(e,t,i){return this.context?this.context.run(e,t,i):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??3e4),i=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await z(this._metrics.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._metrics.reset());try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},i?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},r=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let e=new AbortController;r=W(()=>{e.abort()},this.options.requestTimeout),i.signal=e.signal}try{return await this.fetch(t,i)}catch(e){this._events.emit("error",e);return}finally{r&&clearTimeout(r)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let i={},r={};for(let[s,a]of Object.entries(e))if(C(a,"Object")&&t&&s in t){let e={};for(let[t,i]of Object.entries(a))e[String(t)]=String(i);r[String(s)]=e}else i[String(s)]=String(a);return{personProperties:i,groupProperties:r}}async getFeatureFlagsForEvent(e,t,i,r){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let s=r?.personProperties||{},a=r?.groupProperties||{},n=r?.flagKeys;if(r?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let r={};for(let[e,i]of Object.entries(t||{}))r[e]=String(i);return await this.getAllFlags(e,{groups:r,personProperties:s,groupProperties:a,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:n})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let r={};for(let[e,i]of Object.entries(t||{}))r[e]=String(i);return await this.getAllFlags(e,{groups:r,personProperties:s,groupProperties:a,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:n})}return(await super.getFeatureFlagsStateless(e,t,s,a,i)).flags}addLocalPersonAndGroupProperties(e,t,i,r){let s={...i||{}},a={};if(t)for(let e of Object.keys(t))a[e]={$group_key:t[e],...r?.[e]||{}};return{allPersonProperties:s,allGroupProperties:a}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,i,r){return{distinctId:e,groups:t||{},personProperties:i||{},groupProperties:r||{},evaluationCache:{}}}captureException(e,t,i,r,s){if(!tH.isPreviouslyCapturedError(e)){let a=Error("PostHog syntheticException");this.addPendingPromise(tH.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:a},t,i).then(e=>this._capturePreparedEvent({...e,uuid:r,flags:s},!1)))}}async captureExceptionImmediate(e,t,i,r){if(!tH.isPreviouslyCapturedError(e)){let s=Error("PostHog syntheticException");return this.addPendingPromise(tH.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,i).then(e=>this.captureImmediate({...e,flags:r})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:i,event:r,properties:s,groups:a,flags:n,sendFeatureFlags:o,timestamp:l,disableGeoip:u,uuid:c}=e,h=this.context?.get(),g=t.includeContextProperties??!0,f=i||h?.distinctId,p=g?{...this.props,...h?.properties||{},...s||{}}:{...s||{}};f||(f=er(),p.$process_person_profile=!1),g&&h?.sessionId&&!p.$session_id&&(p.$session_id=h.sessionId);let y=this._shouldSendMinimalFlagCalledEvent(r,p)?d(p):p,m=this._runBeforeSend({distinctId:f,event:r,properties:y,groups:a,flags:n,sendFeatureFlags:o,timestamp:l,disableGeoip:u,uuid:c});if(!m)return Promise.reject(null);let v=await Promise.resolve().then(async()=>{if(n)return o&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),n._getEventProperties();if(o){t1("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");var e=await this.getFeatureFlagsForEvent(m.distinctId,a,u,"object"==typeof o?o:void 0);if(!e)return{};let t={};for(let[i,r]of Object.entries(e))t[`$feature/${i}`]=r;let i=Object.keys(e).filter(t=>!1!==e[t]).sort();return i.length>0&&(t.$active_feature_flags=i),t}return{}}).catch(()=>({})).then(e=>{let t=m.groups||a;return{...e,...m.properties||{},...void 0!==t&&Object.keys(t).length>0?{$groups:t}:{}}});return"$pageview"===m.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof v.$raw_user_agent&&tE(v.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(m.event="$bot_pageview",v.$browser_type="bot"),{distinctId:m.distinctId,event:m.event,properties:v,options:{timestamp:m.timestamp,disableGeoip:m.disableGeoip,uuid:m.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let i=Array.isArray(t)?t:[t],r=e;for(let t of i){if(!(r=t(r)))return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!r.properties||0===Object.keys(r.properties).length){let e=`Event '${r.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(e)}}return r}}var to=tn,t4=e.i(78500);class t3{constructor(){this.storage=new t4.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,i){return this.storage.run(this.resolve(e,i),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let i=this.get()||{};return{distinctId:e.distinctId??i.distinctId,sessionId:e.sessionId??i.sessionId,properties:{...i.properties||{},...e.properties||{}}}}}var to=tn;let t5="posthog-node";function t6(e,{organization:t,projectId:i,prefix:r,severityAllowList:s=["error"],sendExceptionsToPostHog:a=!0}={}){return n=>{if(!("*"===s||s.includes(n.level)))return n;n.tags||(n.tags={});let o=n.tags[t9.POSTHOG_ID_TAG];if(void 0===o)return n;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${o}`,l).toString();n.tags["PostHog Person URL"]=u;let c=n.exception?.values||[],h=c.map(e=>({...e,stacktrace:e.stacktrace?{...e.stacktrace,type:"raw",frames:(e.stacktrace.frames||[]).map(e=>({...e,platform:"node:javascript"}))}:void 0})),d={$exception_message:c[0]?.value||n.message,$exception_type:c[0]?.type,$exception_level:n.level,$exception_list:h,$sentry_event_id:n.event_id,$sentry_exception:n.exception,$sentry_exception_message:c[0]?.value||n.message,$sentry_exception_type:c[0]?.type,$sentry_tags:n.tags},g=to.getInjectedReleaseId();return g&&(d.$release_id=g),t&&i&&(d.$sentry_url=(r||"https://sentry.io/organizations/")+t+"/issues/?project="+i+"&query="+n.event_id),a&&e.capture({event:"$exception",distinctId:o,properties:d}),n}}function t8(e,t){let i=t6(e,t);return{name:t5,processEvent:e=>i(e)}}class t9{static #e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,i,r,s){this.name=t5,this.name=t5,this.setupOnce=function(a,n){a(t6(e,{organization:t,projectId:n()?.getClient()?.getDsn()?.projectId,prefix:i,severityAllowList:r,sendExceptionsToPostHog:s??!0}))}}}e.s(["PostHogSentryIntegration",0,t9,"createEventProcessor",0,t6,"sentryIntegration",0,t8],92164);let t7=/[\x00-\x1f\x7f-\x9f]/g;function ie(e,t,i){null!=i&&""!==i&&(e[t]=i)}function it(e){return Array.isArray(e)?e[0]:e}function ii(e){if(Array.isArray(e)){for(let t of e){let e=ii(t);if(void 0!==e)return e}return}if("string"!=typeof e)return;let t=e.replace(t7,"").trim();if(t)return t.length>1e3?t.slice(0,1e3):t}function ir(e,t){var i,r;let s,{sessionId:a,distinctId:n}=function(e){if(!e)return{};let t=ii(e["x-posthog-session-id"]),i=ii(e["x-posthog-distinct-id"]);return{...void 0!==t?{sessionId:t}:{},...void 0!==i?{distinctId:i}:{}}}(t.headers),o={},l=!0===e.options.disable_capture_url_hashes;return ie(o,"$current_url",(i=t.originalUrl||t.url,l?N(i):i)),ie(o,"$request_method",t.method),ie(o,"$request_path",(r=t.path,s=function(e){if(!e)return e;let t=e.indexOf("?"),i=e.indexOf("#");return -1===t||-1!==i&&i<t?e:`${e.slice(0,t)}${-1===i?"":e.slice(i)}`}(r),l?N(s):s)),ie(o,"$user_agent",it(t.headers["user-agent"])),ie(o,"$ip",function(e){let t=it(e.headers["x-forwarded-for"]);if(t){let e=t.split(",")[0].trim();if(e)return e}return e.socket?.remoteAddress}(t)),{...void 0!==a?{sessionId:a}:{},...void 0!==n?{distinctId:n}:{},properties:o}}function is(e,t){var i;t.use((i=e,(e,t,r)=>{i.withContext(ir(i,e),()=>r())}))}function ia(e,t){var i;t.use((i=e,(e,t,r,s)=>{if(tH.isPreviouslyCapturedError(e))return void s(e);let a=ir(i,t),n=Error("Synthetic exception"),o={...void 0!==a.sessionId?{$session_id:a.sessionId}:{},...a.properties||{},$response_status_code:r.statusCode};i.addPendingPromise(tH.buildEventMessage(i.getErrorPropertiesBuilder(),e,{mechanism:{type:"middleware",handled:!1},syntheticException:n},a.distinctId,o).then(e=>i._capturePreparedEvent(e,!1))),s(e)}))}e.s(["setupExpressErrorHandler",0,ia,"setupExpressRequestContext",0,is],88512),e.s([],52538);class io extends t2{getLibraryId(){return"posthog-node"}initializeContext(){return new t3}createErrorPropertiesBuilder(){let e;return new to.ErrorPropertiesBuilder([new to.EventCoercer,new to.ErrorCoercer,new to.ObjectCoercer,new to.StringCoercer,new to.PrimitiveCoercer],to.createStackParser("node:javascript",to.nodeStackLineParser),[(e=function(e=process.argv[1]?(0,o.dirname)(process.argv[1]):process.cwd(),t="\\"===o.sep){let i=t?l(e):e;return e=>{if(!e)return;let r=t?l(e):e,{dir:s,base:a,ext:n}=o.posix.parse(r);(".js"===n||".mjs"===n||".cjs"===n)&&(a=a.slice(0,-1*n.length));let u=decodeURIComponent(a);s||(s=".");let c=s.lastIndexOf("/node_modules");if(c>-1)return`${s.slice(c+14).replace(/\//g,".")}:${u}`;if(s.startsWith(i)){let e=s.slice(i.length+1).replace(/\//g,".");return e?`${e}:${u}`:u}return u}}(),async t=>{for(let i of t)i.module=e(i.filename);return t}),e=>tf(e,void 0,this._logger),function(e=process.cwd()){let t="\\"===o.sep,i=e=>t?e.replace(/\\/g,"/"):e,r=i(e);return async e=>{for(let t of e)!(!t.filename||t.filename.startsWith("node:")||t.filename.startsWith("data:"))&&(0,o.isAbsolute)(t.filename)&&(t.filename=i((0,o.relative)(r,i(t.filename))));return e}}()])}}e.s(["PostHog",0,io],89767),e.i(89767),e.i(52538),e.i(92164),e.i(88512),e.i(88096),e.s(["FeatureFlagError",0,f,"FeatureFlagEvaluations",0,tP,"PostHogSentryIntegration",0,t9,"cookieStateToProperties",0,eu,"cookieStoreFromHeader",0,ea,"createEventProcessor",0,t6,"getPostHogCookieName",0,en,"parsePostHogCookie",0,ec,"readPostHogCookie",0,el,"sentryIntegration",0,t8,"serializePostHogCookie",0,eo,"setupExpressErrorHandler",0,ia,"setupExpressRequestContext",0,is,"uuidv7",0,er],92349),e.i(92349),e.s(["FeatureFlagError",0,f,"FeatureFlagEvaluations",0,tP,"PostHog",0,io,"PostHogSentryIntegration",0,t9,"cookieStateToProperties",0,eu,"cookieStoreFromHeader",0,ea,"createEventProcessor",0,t6,"getPostHogCookieName",0,en,"parsePostHogCookie",0,ec,"readPostHogCookie",0,el,"sentryIntegration",0,t8,"serializePostHogCookie",0,eo,"setupExpressErrorHandler",0,ia,"setupExpressRequestContext",0,is,"uuidv7",0,er],39702)}];
2
+ at ${e.filename}:${t}:${i}`}}}e.s(["ErrorEventCoercer",0,eN],60887);let eq=["fatal","error","warning","log","info","debug"];function eH(e,t=40){let i=Object.keys(e);if(i.sort(),!i.length)return"[object has no keys]";for(let e=i.length;e>0;e--){let r=i.slice(0,e).join(", ");if(!(r.length>t)){if(e===i.length)return r;return r.length<=t?r:`${r.slice(0,t)}...`}}return""}class eW{match(e){return"object"==typeof e&&null!==e}coerce(e,t){let i=this.getErrorPropertyFromObject(e);return i?t.apply(i):{type:this.getType(e),value:this.getValue(e),stack:this.getStack(e)??t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return k(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&"string"==typeof e.name){let t=`'${e.name}' captured as exception`;return"message"in e&&"string"==typeof e.message&&(t+=` with message: '${e.message}'`),t}if("message"in e&&"string"==typeof e.message)return e.message;let t=this.getObjectClassName(e),i=eH(e);return`${t&&"Object"!==t?`'${t}'`:"Object"} captured as exception with keys: ${i}`}isSeverityLevel(e){return x(e)&&!(x(e)&&0===e.trim().length)&&eq.indexOf(e)>=0}getStack(e){try{if(x(e.stacktrace)&&e.stacktrace.length>0)return e.stacktrace;return x(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let i=e[t];if(G(i))return i}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){return}}}e.s(["ObjectCoercer",0,eW],12154);class ez{match(e){return k(e)}coerce(e,t){let i=e.constructor.name;return{type:i,value:`${i} captured as exception with keys: ${eH(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["EventCoercer",0,ez],41324);class eG{match(e){return I(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["PrimitiveCoercer",0,eG],79478);class eK{match(e){return C(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!k(e))return!1;try{let t=e.detail;return null!=t&&"object"==typeof t&&"reason"in t}catch{return!1}}coerce(e,t){let i=this.getUnhandledRejectionReason(e);return I(i)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(i)}`,stack:t.syntheticException?.stack,synthetic:!0}:t.apply(i)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&null!=e.detail&&"object"==typeof e.detail&&"reason"in e.detail)return e.detail.reason}catch{}return e}}e.s(["PromiseRejectionEventCoercer",0,eK],1802),e.s([],59567);let eV={MESSAGE:"$message",TIMESTAMP:"$timestamp"},eQ=new Set([eV.MESSAGE,eV.TIMESTAMP]),eJ={enabled:!0,max_bytes:32768};function eY(e){return e?{enabled:e.enabled??eJ.enabled,max_bytes:function(e,t){if(!$(e)||e===1/0||e===-1/0)return t;let i=Math.floor(e);return i<0?t:i}(e.max_bytes,eJ.max_bytes)}:{...eJ}}function eX(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((i,r)=>(eQ.has(r)?t.push(r):i[r]=e[r],i),{}),droppedKeys:t}}class eZ{constructor(e){this._entries=[],this._totalBytes=0,this._config=eY(e)}setConfig(e){this._config=eY(e),this._trimToMaxBytes()}add(e){let t=function(e){let t;try{t=v(e)}catch{return}try{let e=JSON.parse(t);if(!F(e))return;let i=e[eV.MESSAGE],r=e[eV.TIMESTAMP];if(!x(i)||0===i.trim().length||!x(r)&&!$(r))return;return{step:e,json:t}}catch{return}}(e);if(!t)return;let i=e0(t.json);i>this._config.max_bytes||(this._entries.push({step:t.step,bytes:i}),this._totalBytes+=i,this._trimToMaxBytes())}getAttachable(){return this._entries.map(e=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}}function e0(e){if("u">typeof TextEncoder)return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),i=0;for(let e=0;e<t.length;e++)"%"===t[e]?(i+=1,e+=2):i+=1;return i}e.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,eJ,"EXCEPTION_STEP_INTERNAL_FIELDS",0,eV,"ExceptionStepsBuffer",0,eZ,"getUtf8ByteLength",0,e0,"resolveExceptionStepsConfig",0,eY,"stripReservedExceptionStepFields",0,eX],25779),e.s([],21754);class e1{match(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return A(e,Error)}}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let i=e.message;return i.error&&"string"==typeof i.error.message?String(i.error.message):String(i)}getStack(e){return e.stacktrace||e.stack||void 0}}e.s(["ErrorCoercer",0,e1],13446);let e2=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class e4{match(e){return"string"==typeof e}coerce(e,t){let[i,r]=this.getInfos(e);return{type:i??"Error",value:r??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",i=e,r=e.match(e2);return r&&(t=r[1],i=r[2]),[t,i]}}e.s(["StringCoercer",0,e4],22175);class e3 extends Error{constructor(e,t){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}}class e5 extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}async function e8(e){if(e instanceof e3){let t="";try{t=await e.text}catch{}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function e6(e){return e instanceof e5}function e9(e){if(e instanceof e3)return 502===e.status||504===e.status;if(!(e instanceof e5))return!1;let t=e.error;return"ECONNREFUSED"!==(t?.code??t?.cause?.code)}function e7(e){return"object"==typeof e&&e instanceof e3&&413===e.status}function te(e){return e instanceof e3?408===e.status||429===e.status||e.status>=500:e6(e)}function tt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}let ti="default";class tr{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new ef([new e1,new eW,new e4,new eG],eD())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new ed,this._events=new eh,this._isInitialized=!1;const i="string"==typeof e?e.trim():"",r="string"==typeof t.host?t.host.trim():"",s=!i;this._logger=function(e,t=e=>e()){return eg(e,t,function(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),s&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=i,this.host=function(e){return e?.replace(/\/+$/,"")}(r||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1e3),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3e3,retryCheck:te},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||s,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!("CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&"function"==typeof Response.prototype.blob)||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){return this.disabled?void this._logger.warn("The client is disabled"):this._isInitialized?e():void this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(g.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(g.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(g.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let e=this.on("*",(e,t)=>this._logger.info(e,t));this.removeDebugCallback=()=>{e(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},i={...t,...this.getCommonEventProperties()};var r=i;for(let e of Object.keys(t))(e.startsWith("$feature/")||"$active_feature_flags"===e)&&(r[e]=t[e]);return"$feature_flag_called"===e.event&&!1===i.$feature_flag_has_experiment&&this.isMinimalFlagCalledEventsEnabled()&&(i=d(i)),{distinct_id:e.distinct_id,event:e.event,properties:i}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,i){this.wrap(()=>{let r={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",r,i)})}async identifyStatelessImmediate(e,t,i){let r={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",r,i)}captureStateless(e,t,i,r){this.wrap(()=>{let s=this.buildPayload({distinct_id:e,event:t,properties:i});this.enqueue("capture",s,r)})}async captureStatelessImmediate(e,t,i,r){let s=this.buildPayload({distinct_id:e,event:t,properties:i});await this.sendImmediate("capture",s,r)}aliasStateless(e,t,i,r){this.wrap(()=>{let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...i||{},distinct_id:t,alias:e}});this.enqueue("alias",s,r)})}async aliasStatelessImmediate(e,t,i,r){let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...i||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",s,r)}groupIdentifyStateless(e,t,i,r,s,a){this.wrap(()=>{let n=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{},...a||{}}});this.enqueue("capture",n,r)})}async groupIdentifyStatelessImmediate(e,t,i,r,s,a){let n=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{},...a||{}}});await this.sendImmediate("capture",n,r)}async getRemoteConfig(){await this._initPromise;let e=this.host;"https://us.i.posthog.com"===e?e="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===e&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.apiKey}/config`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,i,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(e=>e.json()).catch(e=>{this._logger.error("Remote config could not be loaded",e),this._events.emit("error",e)})}async getFlags(e,t={},i={},r={},s={},a=!1){await this._initPromise;let n=`${this.host}/flags/?v=2${a?"&config=true":""}`,o={token:this.apiKey,distinct_id:e,groups:t,person_properties:i,group_properties:r,...s};i.$device_id&&(o.$device_id=i.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(o.evaluation_contexts=this.evaluationContexts);let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(o)};return this._logger.info("Flags URL",n),this.fetchWithRetry(n,l,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:e9},this.featureFlagsRequestTimeoutMs).then(e=>e.json()).then(e=>({success:!0,response:(e=>{if("flags"in e){let t,i=Object.fromEntries(Object.entries(e.flags??{}).map(([e,t])=>[e,u(t)]).filter(([,e])=>void 0!==e)),r=Object.fromEntries(Object.keys(t=e.flags??{}).filter(e=>{let i=t[e];return i.enabled&&i.metadata&&void 0!==i.metadata.payload}).map(e=>{let i=t[e].metadata?.payload;return[e,i?c(i):void 0]}));return{...e,featureFlags:i,featureFlagPayloads:r}}{let t=e.featureFlags??{},i=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([e,t])=>[e,c(t)])),r=Object.fromEntries(Object.entries(t).map(([e,t])=>{var r,s;return[e,{key:e,enabled:"string"==typeof(r=t)||r,variant:"string"==typeof r?r:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:(s=i[e])?JSON.stringify(s):void 0,description:void 0}}]}));return{...e,featureFlags:t,featureFlagPayloads:i,flags:r}}})(e)})).catch(e=>(this._events.emit("error",e),{success:!1,error:this.categorizeRequestError(e)}))}categorizeRequestError(e){if(e instanceof e3)return{type:"api_error",statusCode:e.status};if(e instanceof e5){let t=e.error;return t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,i={},r={},s={},a){await this._initPromise;let n=await this.getFeatureFlagDetailStateless(e,t,i,r,s,a);if(void 0===n)return{response:void 0,requestId:void 0};let o=u(n.response);return void 0===o&&(o=!1),{response:o,requestId:n.requestId}}async getFeatureFlagDetailStateless(e,t,i={},r={},s={},a){await this._initPromise;let n=await this.getFeatureFlagDetailsStateless(t,i,r,s,a,[e]);if(void 0!==n)return{response:n.flags[e],requestId:n.requestId,evaluatedAt:n.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,i={},r={},s={},a){await this._initPromise;let n=await this.getFeatureFlagPayloadsStateless(t,i,r,s,a,[e]);if(!n)return;let o=n[e];return void 0===o?null:o}async getFeatureFlagPayloadsStateless(e,t={},i={},r={},s,a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,i,r,s,a)).payloads}async getFeatureFlagsStateless(e,t={},i={},r={},s,a){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,i,r,s,a)}async getFeatureFlagsAndPayloadsStateless(e,t={},i={},r={},s,a){await this._initPromise;let n=await this.getFeatureFlagDetailsStateless(e,t,i,r,s,a);return n?{flags:n.featureFlags,payloads:n.featureFlagPayloads,requestId:n.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},i={},r={},s,a){await this._initPromise;let n={geoip_disable:s??this.disableGeoip};a&&(n.flag_keys_to_evaluate=a);let o=await this.getFlags(e,t,i,r,n);if(!o.success)return;let l=o.response;return(l.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),l.quotaLimited?.includes("feature_flags"))?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},i=await this.fetchWithRetry(e,t).then(e=>{if(200!==e.status||!e.json){let t=`Surveys API could not be loaded: ${e.status}`,i=Error(t);this._logger.error(i),this._events.emit("error",Error(t));return}return e.json()}).catch(e=>{this._logger.error("Surveys API could not be loaded",e),this._events.emit("error",e)}),r=i?.surveys;return r&&this._logger.info("Surveys fetched from API: ",JSON.stringify(r)),r??[]}get props(){return this._props||(this._props=this.getPersistedProperty(g.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(g.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(g.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return ti}persistedQueueKeyForRoute(e){return g.Queue}getActiveQueueRoutes(){return[ti]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let r=this.prepareMessage(t,i);if(null===(r=this.processBeforeEnqueue(r)))return;r=this.normalizeMessage(r);let s=this.persistedQueueKeyForRoute(this.getQueueRouteKey(r)),a=this.getPersistedProperty(s)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:r}),this.setPersistedProperty(s,a),this._events.emit(e,r),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=W(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let r=this.prepareMessage(t,i);if(null!==(r=this.processBeforeEnqueue(r))){r=this.normalizeMessage(r);try{await this.sendBatch([r],void 0,this.getQueueRouteKey(r))}catch(e){this._events.emit("error",e)}}}normalizeMessage(e){let{type:t,library:i,library_version:r,...s}=e,a=tt(s.properties)?s.properties:void 0;return void 0!==i&&a?.$lib===void 0&&(a={...a||{},$lib:i}),void 0!==r&&a?.$lib_version===void 0&&(a={...a||{},$lib_version:r}),a&&(s.properties=a),s.uuid=U(s.uuid,er),s}prepareMessage(e,t){let i={...e,timestamp:t?.timestamp?t?.timestamp:H(),uuid:U(t?.uuid,er)};return(t?.disableGeoip??this.disableGeoip)&&(tt(i.properties)||(i.properties={}),i.properties.$geoip_disable=!0),i.distinctId&&(i.distinct_id=i.distinctId,delete i.distinctId),i}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flush().catch(async e=>{await e8(e)})}async waitForPendingPromises(e,t=[]){let i=t.filter(e=>!!e),r=0;for(;;){let t=this.promiseQueue.getPromises([...i,...this.flushPromises],e);if(0===t.length)return;r>0&&this._logger.debug(`flush() re-checking ${t.length} pending promise(s) before flushing`),await Promise.all(t.map(e=>e.catch(()=>{}))),r++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,i=this.promiseQueue.maxId,r=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(i,[t,r])}).then(()=>K([t])).then(()=>(this.pendingFlushPromise===r&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=r,this.flushPromise=r,this.flushPromises.add(r),this.addPendingPromise(r),K([r]).then(()=>{this.flushPromises.delete(r),this.pendingFlushPromise===r&&(this.pendingFlushPromise=null),this.flushPromise===r&&(this.flushPromise=null)}),r}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&""!==e&&(t["User-Agent"]=e),t}async sendBatch(e,t,i=ti){let r={api_key:this.apiKey,batch:e,sent_at:H()};this.historicalMigration&&(r.historical_migration=!0);let s=v(r),a=`${this.host}/batch/`,n=this.disableCompression?null:await m(s,this.isDebug),o={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==n&&{"Content-Encoding":"gzip"}},body:n||s},l=await this.fetchWithRetry(a,o,t);await l.body?.cancel()?.catch(()=>{})}async _flush(){let e;this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(e=>this.getRouteQueue(e).length>0))return;let i=[];for(let r of t)try{await this._flushRoute(r,i)}catch(t){void 0===e&&(e=t)}if(void 0!==e)throw e;this._events.emit("flush",i)}async _flushRoute(e,t){let i=this.persistedQueueKeyForRoute(e),r=this.getPersistedProperty(i)||[];if(!r.length)return;let s=r.length,a=0;for(;r.length>0&&a<s;){let s=r.slice(0,this.maxBatchSize),n=s.map(e=>void 0===e.message?e.message:this.normalizeMessage(e.message)),o=async()=>{let e=this.getPersistedProperty(i)||[],t=[...s],a=e.filter(e=>{let i=e.message?.uuid,r=t.findIndex(t=>t===e||"string"==typeof i&&i.length>0&&t.message?.uuid===i);return -1===r||(t.splice(r,1),!1)});this.setPersistedProperty(i,a),r=a,this._dequeuedMessagesCount+=s.length,await this.flushStorage()},l={retryCheck:e=>!e7(e)&&te(e)};try{await this.sendBatch(n,l,e)}catch(e){if(e7(e)&&n.length>1){this.maxBatchSize=Math.max(1,Math.floor(n.length/2)),this._logger.warn(`Received 413 when sending batch of size ${n.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw e instanceof e5||await o(),this._events.emit("error",e),e}await o(),t.push(...n),a+=n.length}}async _sendLogsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),i=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,r=this.disableCompression?null:await m(t,this.isDebug),s={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==r&&{"Content-Encoding":"gzip"}},body:r||t};try{return await this.fetchWithRetry(i,s,{retryCheck:e=>!e7(e)&&te(e)}),{kind:"ok"}}catch(e){if(e7(e))return{kind:"too-large"};if(e instanceof e5)return{kind:"retry-later",error:e};return{kind:"fatal",error:e}}}async _sendMetricsBatch(e){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let t=JSON.stringify(e),i=`${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`,r=this.disableCompression?null:await m(t,this.isDebug),s={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==r&&{"Content-Encoding":"gzip"}},body:r||t};try{return await this.fetchWithRetry(i,s,{retryCheck:e=>!e7(e)&&te(e)}),{kind:"ok"}}catch(e){if(e7(e))return{kind:"too-large"};if(te(e))return{kind:"retry-later",error:e};return{kind:"fatal",error:e}}}async fetchWithRetry(e,t,i,r){let s=t.body?t.body:"",a=-1;try{a=s instanceof Blob?s.size:Buffer.byteLength(s,"utf8")}catch{a=s instanceof Blob?s.size:new TextEncoder().encode(s).length}return await q(async()=>{let i=new AbortController,s=W(()=>i.abort(),r??this.requestTimeout),n=null;try{n=await this.fetch(e,{signal:i.signal,...t})}catch(e){throw new e5(e)}finally{clearTimeout(s)}if("no-cors"!==t.mode&&(n.status<200||n.status>=400))throw new e3(n,a);return n},{...this._retryOptions,...i})}async _shutdown(e=3e4){await this._initPromise;let t=!1;if(this.clearFlushTimer(),!this.disabled)return z((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(e=>this.getRouteQueue(e).length>0);){let e=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===e){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(e){if(!("object"==typeof e&&(e instanceof e3||e6(e))))throw e;await e8(e)}})(),e,()=>{throw this._logger.error("Timed out while shutting down PostHog"),t=!0,"Timeout while shutting down PostHog. Some events may not have been sent."})}async shutdown(e=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}e.i(21754),e.i(69309),e.i(10728),e.s(["chromeStackLineParser",0,eb,"createDefaultStackParser",0,eD,"createStackParser",0,eB,"geckoStackLineParser",0,eF,"nodeStackLineParser",0,eR,"opera10StackLineParser",0,e$,"opera11StackLineParser",0,eC,"reverseAndStripFrames",0,ej,"winjsStackLineParser",0,ex],22546),e.i(22546),e.i(59567),e.i(33603),e.i(13446),e.i(60887),e.i(22175),e.i(12154),e.i(41324),e.i(79478),e.i(1802),e.s(["DOMExceptionCoercer",0,eU,"ErrorCoercer",0,e1,"ErrorEventCoercer",0,eN,"EventCoercer",0,ez,"ObjectCoercer",0,eW,"PrimitiveCoercer",0,eG,"PromiseRejectionEventCoercer",0,eK,"StringCoercer",0,e4],90166),e.i(90166);class ts{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(void 0!==t)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}}function ta(){let e=globalThis._posthogReleaseId;return"string"==typeof e&&e.length>0?e:void 0}e.s(["ReduceableCache",0,ts],45294),e.i(45294),e.i(25779),e.s(["getInjectedReleaseId",0,ta],56168),e.i(56168),e.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,eJ,"DOMExceptionCoercer",0,eU,"EXCEPTION_STEP_INTERNAL_FIELDS",0,eV,"ErrorCoercer",0,e1,"ErrorEventCoercer",0,eN,"ErrorPropertiesBuilder",0,ef,"EventCoercer",0,ez,"ExceptionStepsBuffer",0,eZ,"ObjectCoercer",0,eW,"PrimitiveCoercer",0,eG,"PromiseRejectionEventCoercer",0,eK,"ReduceableCache",0,ts,"StringCoercer",0,e4,"chromeStackLineParser",0,eb,"createDefaultStackParser",0,eD,"createStackParser",0,eB,"geckoStackLineParser",0,eF,"getInjectedReleaseId",0,ta,"getUtf8ByteLength",0,e0,"nodeStackLineParser",0,eR,"opera10StackLineParser",0,e$,"opera11StackLineParser",0,eC,"resolveExceptionStepsConfig",0,eY,"reverseAndStripFrames",0,ej,"stripReservedExceptionStepFields",0,eX,"winjsStackLineParser",0,ex],11168);var tn=e.i(11168),to=tn,tl=e.i(2157),tu=e.i(12714),tc=e.i(50227),th=e.i(1457);let td=new to.ReduceableCache(25),tg=new to.ReduceableCache(20);async function tf(e,t=tu.open,i){let r,s={};try{r=process.cwd()}catch{}for(let t=e.length-1;t>=0;t--){var a,n;let i=e[t],o=i?.filename;!(!i||"string"!=typeof o||"number"!=typeof i.lineno||(a=o).startsWith("node:")||a.endsWith(".min.js")||a.endsWith(".min.cjs")||a.endsWith(".min.mjs")||a.startsWith("data:")||void 0!==(n=i).lineno&&n.lineno>1e4||void 0!==n.colno&&n.colno>1e3)&&((0,tc.isAbsolute)(o)||void 0!==r)&&(s[o]||(s[o]=[]),s[o].push(i.lineno))}let o=Object.keys(s);if(0==o.length)return e;let l=[];for(let e of o){let a=tv(e,r);if(void 0===a||tg.get(a))continue;let n=s[e];if(!n)continue;n.sort((e,t)=>e-t);let o=function(e){if(!e.length)return[];let t=0,i=e[0];if("number"!=typeof i)return[];let r=t_(i),s=[];for(;;){if(t===e.length-1){s.push(r);break}let i=e[t+1];if("number"!=typeof i)break;i<=r[1]?r[1]=i+7:(s.push(r),r=t_(i)),t++}return s}(n);if(o.every(e=>(function(e,t){let i=td.get(e);if(void 0===i)return!1;for(let e=t[0];e<=t[1];e++)if(void 0===i[e])return!1;return!0})(a,e)))continue;let u=function(e,t,i){let r=e.get(t);return void 0===r?(e.set(t,i),i):r}(td,a,{});l.push(ty(e,o,u,a,t,i))}return await Promise.all(l).catch(()=>{}),e&&e.length>0&&function(e,t,i){for(let r of e)if(r.filename&&void 0===r.context_line&&"number"==typeof r.lineno){let e=tv(r.filename,i),s=void 0===e?void 0:t.get(e);if(void 0===s)continue;!function(e,t,i){if(void 0===t.lineno||void 0===i)return;t.pre_context=[];for(let r=tb(e);r<e;r++){let e=i[r];if(void 0===e)return void tm(t);t.pre_context.push(e)}if(void 0===i[e])return tm(t);t.context_line=i[e];let r=function(e){return e+7}(e);t.post_context=[];for(let s=e+1;s<=r;s++){let e=i[s];if(void 0===e)break;t.post_context.push(e)}}(r.lineno,r,s)}}(e,td,r),td.reduce(),e}async function tp(e,t,i){let r,s=!1;try{r=await t(e,tl.constants.O_RDONLY|tl.constants.O_NONBLOCK);let a=await r.stat();if(!a.isFile())return;if(a.size>0xa00000)return void i?.debug(`Skipping source context for oversized file ${e}: ${a.size} bytes exceeds 10485760`);return s=!0,r}catch{return}finally{r&&!s&&await r.close().catch(()=>{})}}async function ty(e,t,i,r,s,a){let n=await tp(e,s,a);return void 0===n?void tg.set(r,1):new Promise(e=>{let s,a,o=!1;function l(t){o||(o=!0,t?.destroy(),n.close().then(e,e))}try{s=n.createReadStream({autoClose:!1,start:0,end:0x9fffff})}catch{tg.set(r,1),l();return}try{a=(0,th.createInterface)({input:s})}catch{tg.set(r,1),l(s);return}let u=0,c=0,h=t[0];if(void 0===h)return void l(s);let d=h[0],g=h[1];function f(){tg.set(r,1),a.close(),a.removeAllListeners(),l(s)}s.on("error",f),a.on("error",f),a.on("close",()=>l(s)),a.on("line",e=>{if(!(++u<d)&&(i[u]=function(e,t){let i=e,r=i.length;if(r<=150)return i;t>r&&(t=r);let s=Math.max(t-60,0);s<5&&(s=0);let a=Math.min(s+140,r);return a>r-5&&(a=r),a===r&&(s=Math.max(a-140,0)),i=i.slice(s,a),s>0&&(i=`...${i}`),a<r&&(i+="..."),i}(e,0),u>=g)){if(c===t.length-1){a.close(),a.removeAllListeners();return}let e=t[++c];if(void 0===e){a.close(),a.removeAllListeners();return}d=e[0],g=e[1]}})})}function tm(e){delete e.pre_context,delete e.context_line,delete e.post_context}function tv(e,t){return(0,tc.isAbsolute)(e)?JSON.stringify([null,e]):void 0===t?void 0:JSON.stringify([t,e])}function t_(e){return[tb(e),e+7]}function tb(e){return Math.max(1,e-7)}let tw=["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","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],tE=function(e,t=[]){if(!e)return!1;let i=e.toLowerCase();return tw.concat(t).some(e=>{let t=e.toLowerCase();return -1!==i.indexOf(t)})},tF={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};e.s(["FeatureFlagError",0,tF],88096);class tP{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e){let t=this._flags[e];return this._recordAccess(e),t?.enabled??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),t)return!!t.enabled&&(t.variant??!0)}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let i=this._flags[t];i&&(e[t]=i)}return this._cloneWith(e)}only(e){let t={},i=[];for(let r of e){let e=this._flags[r];e?t[r]=e:i.push(r)}return i.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${i.join(", ")}`),this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[i,r]of Object.entries(this._flags)){let s=!1!==r.enabled&&(r.variant??!0);e[`$feature/${i}`]=s,r.enabled&&t.push(i)}return t.length>0&&(t.sort(),e.$active_feature_flags=t),e}_cloneWith(e){return new tP({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),""===this._distinctId||this._isSlice&&!(e in this._flags))return;let t=this._flags[e],i=void 0===t?void 0:!1!==t.enabled&&(t.variant??!0),r={$feature_flag:e,$feature_flag_response:i,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:i,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};t?.hasExperiment!==void 0&&(r.$feature_flag_has_experiment=t.hasExperiment),t?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(r.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let s=[];this._errorsWhileComputing&&s.push(tF.ERRORS_WHILE_COMPUTING),this._quotaLimited&&s.push(tF.QUOTA_LIMITED),void 0===t&&s.push(tF.FLAG_MISSING),s.length>0&&(r.$feature_flag_error=s.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:i,groups:this._groups,disableGeoip:this._disableGeoip,properties:r})}}async function tx(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");return Array.from(new Uint8Array(await t.digest("SHA-1",new TextEncoder().encode(e)))).map(e=>e.toString(16).padStart(2,"0")).join("")}let tS=["is_not","is_set"];class t$ extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,t$.prototype)}}function tI(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class tC extends Error{constructor(e){super(e),tI(this,tC)}}class tk extends Error{constructor(e){super(e),tI(this,tk)}}class tA{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:i,timeout:r,host:s,customHeaders:a,...n}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=r,this.projectApiKey=i,this.host=s,this.poller=void 0,this.fetch=n.fetch||fetch,this.onError=n.onError,this.customHeaders=a,this.onLoad=n.onLoad,this.onMinimalFlagCalledEvents=n.onMinimalFlagCalledEvents,this.cacheProvider=n.cacheProvider,this.strictLocalEvaluation=n.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}createEvaluationContext(e,t={},i={},r={},s={}){return{distinctId:e,groups:t,personProperties:i,groupProperties:r,evaluationCache:s}}async getFeatureFlag(e,t,i={},r={},s={}){let a,n;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return a;if(void 0!==(n=this.featureFlagsByKey[e])){let o=this.createEvaluationContext(t,i,r,s);try{a=(await this.computeFlagAndPayloadLocally(n,o)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${a}`))}catch(t){t instanceof tk||t instanceof tC?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e}: ${t}`))}}return a}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let i={},r={},s=0==this.featureFlags.length,a=t?t.map(e=>this.featureFlagsByKey[e]).filter(Boolean):this.featureFlags,n={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(a.map(async e=>{try{let{value:t,payload:s}=await this.computeFlagAndPayloadLocally(e,n);i[e.key]=t,s&&(r[e.key]=s)}catch(t){t instanceof tk||t instanceof tC?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e.key}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e.key}: ${t}`)),s=!0}})),{response:i,payloads:r,fallbackToFlags:s}}async computeFlagAndPayloadLocally(e,t,i={}){let r,{matchValue:s,skipLoadCheck:a=!1}=i;if(a||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};r=void 0!==s?s:await this.computeFlagValueLocally(e,t);let n=this.getFeatureFlagPayload(e.key,r);return{value:r,payload:n}}async computeFlagValueLocally(e,t){let{distinctId:i,groups:r,personProperties:s,groupProperties:a}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new tC("Flag has experience continuity enabled");let n=(e.filters||{}).aggregation_group_type_index;if(void 0!=n){let i=this.groupTypeMapping[String(n)];if(!i)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${n} for feature flag ${e.key}`)),new tC("Flag has unknown group type index");if(!(i in r))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;"device_id"===e.bucketing_identifier&&(s?.$device_id===void 0||s?.$device_id===null||s?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let o=a[i];return await this.matchFeatureFlagProperties(e,r[i],o,t)}{let r=this.getBucketingValueForFlag(e,i,s);if(void 0===r)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new tC(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,r,s,t)}}getBucketingValueForFlag(e,t,i){if(e.filters?.aggregation_group_type_index!=void 0)return t;if("device_id"===e.bucketing_identifier){let e=i?.$device_id;if(null==e||""===e)return;return e}return t}getFeatureFlagPayload(e,t){let i=null;if(!1!==t&&null!=t&&("boolean"==typeof t?i=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null:"string"==typeof t&&(i=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null),null!=i)){if("object"==typeof i)return i;if("string"==typeof i)try{return JSON.parse(i)}catch{}return i}return null}async evaluateFlagDependency(e,t,i){let{evaluationCache:r}=i,s=e.key;if(!this.featureFlagsByKey)throw new tC("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new tC(`Flag dependency property for '${s}' is missing required 'dependency_chain' field`);let a=e.dependency_chain;if(!Array.isArray(a))throw new tC(`Flag dependency property for '${s}' has an invalid 'dependency_chain' (expected array, got ${typeof a})`);if(0===a.length)throw new tC(`Circular dependency detected for flag '${s}' (empty dependency chain)`);for(let e of a){if(!(e in r)){let t=this.featureFlagsByKey[e];if(t)if(t.active)try{let s=await this.computeFlagValueLocally(t,i);r[e]=s}catch(t){throw new tC(`Error evaluating flag dependency '${e}' for flag '${s}': ${t}`)}else r[e]=!1;else throw new tC(`Missing flag dependency '${e}' for flag '${s}'`)}if(null==r[e])throw new tC(`Dependency '${e}' could not be evaluated`)}let n=r[s];return this.flagEvaluatesToExpectedValue(e.value,n)}flagEvaluatesToExpectedValue(e,t){return"boolean"==typeof e?e===t||"string"==typeof t&&""!==t&&!0===e:"string"==typeof e&&t===e}async matchFeatureFlagProperties(e,t,i,r){let s,a=e.filters||{},n=a.groups||[],o=a.aggregation_group_type_index,l=a.early_exit??!1,{groups:u,groupProperties:c}=r,h=!1;for(let d of n)try{let n=void 0!==d.aggregation_group_type_index?d.aggregation_group_type_index:o,g=i,f=t;if(n!==o&&null!=n){let t=this.groupTypeMapping[String(n)];if(!t||!(t in u)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${n} not available`));continue}if(!(t in c)){h=!0;continue}g=c[t],f=u[t]}let p=await this.isConditionMatch(e,f,d,g,r);if("match"===p){let t=d.variant,i=a.multivariate?.variants||[];s=t&&i.some(e=>e.key===t)?t:await this.getMatchingVariant(e,f)||!0;break}if(l&&"out_of_rollout_bound"===p)return!1}catch(e){if(e instanceof tk)throw e;if(e instanceof tC)h=!0;else throw e}if(void 0!==s)return s;if(h)throw new tC("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,i,r,s){let a=i.rollout_percentage,n=e=>{this.logMsgIfDebug(()=>console.warn(e))};if((i.properties||[]).length>0){for(let e of i.properties){let t=e.type,i=!1;if("cohort"===t){let t=await tR(e,r,this.cohorts,this.debugMode,e=>this.evaluateFlagDependency(e,r,s));i="not_in"===e.operator?!t:t}else i="flag"===t?await this.evaluateFlagDependency(e,r,s):tM(e,r,n);if(!i)return"no_match"}if(void 0==a)return"match"}return void 0!=a&&await tO(e.key,t)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){let i=await tO(e.key,t,"variant"),r=this.variantLookupTable(e).find(e=>i>=e.valueMin&&i<e.valueMax);if(r)return r.key}variantLookupTable(e){let t=[],i=0,r=0,s=e.filters||{};return(s.multivariate?.variants||[]).forEach(e=>{r=i+e.rollout_percentage/100,t.push({valueMin:i,valueMax:r,key:e.key}),i=r}),t}updateFlagState(e){this.featureFlags=e.flags,this.featureFlagsByKey=e.flags.reduce((e,t)=>(e[t.key]=t,e),{}),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(!0===e.minimalFlagCalledEvents)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter(e=>e.ensure_experience_continuity);t.length>0&&console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map(e=>e.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();if(t)return this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(t.flags),!0;return!1}catch(e){return this.onError?.(Error(`Failed to load from cache: ${e}`)),!1}}async loadFeatureFlags(e=!1){if(!this.loadedSuccessfullyOnce||e)return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(e=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${e}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(6e4,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(e){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${e}`))}if(!e&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new t$(`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.groupTypeMapping={},this.cohorts={},this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new t$(`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 t$(`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 i=await t.json()??{};if(!("flags"in i))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(i)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let r={flags:i.flags??[],groupTypeMapping:i.group_type_mapping||{},cohorts:i.cohorts||{},minimalFlagCalledEvents:!0===i.minimal_flag_called_events};if(this.updateFlagState(r),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(r)}catch(e){this.onError?.(Error(`Failed to store in cache: ${e}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(r.flags);break}default:return}}catch(e){e instanceof t$&&this.onError?.(e)}}getPersonalApiKeyRequestOptions(e="GET",t){let i={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(i["If-None-Match"]=t),{method:e,headers:i}}async _requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),i=null;if(this.timeout&&"number"==typeof this.timeout){let e=new AbortController;i=W(()=>{e.abort()},this.timeout),t.signal=e.signal}try{let r=this.fetch,s=await r(e,t);if(200!==s.status)return clearTimeout(i),s;return{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{clearTimeout(i)}},json:async()=>{try{return await s.json()}finally{clearTimeout(i)}}}}catch(e){throw clearTimeout(i),e}}async stopPoller(e=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await z(t,e,()=>{throw Error(`Cache shutdown timeout after ${e}ms`)})}catch(e){this.onError?.(Error(`Error during cache shutdown: ${e}`))}}}async function tO(e,t,i=""){return parseInt((await tx(`${e}.${t}${i}`)).slice(0,15),16)/0x1000000000000000}function tM(e,t,i){let r=e.key,s=e.value,a=e.operator||"exact";if(r in t){if("is_not_set"===a)return!1}else{if("is_not_set"===a)return!0;throw new tC(`Property ${r} not found in propertyValues`)}let n=t[r];if(null==n&&!tS.includes(a))return i&&i(`Property ${r} cannot have a value of null/undefined with the ${a} operator`),!1;function o(e,t){return Array.isArray(e)?e.map(e=>String(e).toLowerCase()).includes(String(t).toLowerCase()):String(e).toLowerCase()===String(t).toLowerCase()}function l(e,t,i){if("gt"===i)return e>t;if("gte"===i)return e>=t;if("lt"===i)return e<t;if("lte"===i)return e<=t;throw Error(`Invalid operator: ${i}`)}switch(a){case"exact":return o(s,n);case"is_not":return!o(s,n);case"is_set":return r in t;case"icontains":return String(n).toLowerCase().includes(String(s).toLowerCase());case"not_icontains":return!String(n).toLowerCase().includes(String(s).toLowerCase());case"regex":return tL(String(s))&&null!==String(n).match(String(s));case"not_regex":return tL(String(s))&&null===String(n).match(String(s));case"gt":case"gte":case"lt":case"lte":{let e,t="number"==typeof s?s:parseFloat(String(s));if(e="number"==typeof n?n:null!=n?parseFloat(String(n)):NaN,Number.isFinite(t)&&Number.isFinite(e))return l(e,t,a);return l(String(n),String(s),a)}case"is_date_after":case"is_date_before":{if("boolean"==typeof s)throw new tC("Date operations cannot be performed on boolean values");let e=function(e){let t=e.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),i=new Date(new Date().toISOString());if(!t)return null;{if(!t.groups)return null;let e=parseInt(t.groups.number);if(e>=1e4)return null;let r=t.groups.interval;if("h"==r)i.setUTCHours(i.getUTCHours()-e);else if("d"==r)i.setUTCDate(i.getUTCDate()-e);else if("w"==r)i.setUTCDate(i.getUTCDate()-7*e);else if("m"==r)i.setUTCMonth(i.getUTCMonth()-e);else{if("y"!=r)return null;i.setUTCFullYear(i.getUTCFullYear()-e)}return i}}(String(s));if(null==e&&(e=tU(s)),null==e)throw new tC(`Invalid date: ${s}`);let t=tU(n);if(["is_date_before"].includes(a))return t<e;return t>e}case"semver_eq":return 0===tB(tD(String(n)),tD(String(s)));case"semver_neq":return 0!==tB(tD(String(n)),tD(String(s)));case"semver_gt":return tB(tD(String(n)),tD(String(s)))>0;case"semver_gte":return tB(tD(String(n)),tD(String(s)))>=0;case"semver_lt":return 0>tB(tD(String(n)),tD(String(s)));case"semver_lte":return 0>=tB(tD(String(n)),tD(String(s)));case"semver_tilde":{let e,t=tD(String(n)),{lower:i,upper:r}={lower:[(e=tD(String(s)))[0],e[1],e[2]],upper:[e[0],e[1]+1,0]};return tB(t,i)>=0&&0>tB(t,r)}case"semver_caret":{let e=tD(String(n)),{lower:t,upper:i}=function(e){let[t,i,r]=tD(e);return{lower:[t,i,r],upper:t>0?[t+1,0,0]:i>0?[0,i+1,0]:[0,0,r+1]}}(String(s));return tB(e,t)>=0&&0>tB(e,i)}case"semver_wildcard":{let e=tD(String(n)),{lower:t,upper:i}=function(e){let t,i,r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new tC(`Invalid wildcard semver: ${e}`);let s=r.split("."),a=t=>{try{return tj(t,e)}catch{throw new tC(`Invalid wildcard semver: ${e}`)}},n=a(s[0]);if(1===s.length)t=[n,0,0],i=[n+1,0,0];else{let e=a(s[1]);t=[n,e,0],i=[n,e+1,0]}return{lower:t,upper:i}}(String(s));return tB(e,t)>=0&&0>tB(e,i)}default:throw new tC(`Unknown operator: ${a}`)}}async function tR(e,t,i,r=!1,s){let a=String(e.value);if(!(a in i))throw new tk(`cohort ${a} not found in local cohorts - likely a static cohort that requires server evaluation`);return tT(i[a],t,i,r,s)}async function tT(e,t,i,r=!1,s){if(!e)return!0;let a=e.type,n=e.values;if(!n||0===n.length)return!0;let o=!1;if("values"in n[0]){for(let e of n)try{let n=await tT(e,t,i,r,s);if("AND"===a){if(!n)return!1}else if(n)return!0}catch(t){if(t instanceof tk)throw t;if(t instanceof tC)r&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0;else throw t}if(o)throw new tC("Can't match cohort without a given cohort property value");return"AND"===a}for(let e of n)try{let n;if("cohort"===e.type)n=await tR(e,t,i,r,s);else if("flag"===e.type){if(!s)throw new tC(`Flag dependency '${e.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);n=await s(e)}else n=tM(e,t);let o=e.negation||!1;if("AND"===a){if(!n&&!o||n&&o)return!1}else if(n&&!o||!n&&o)return!0}catch(t){if(t instanceof tk)throw t;if(t instanceof tC)r&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0;else throw t}if(o)throw new tC("can't match cohort without a given cohort property value");return"AND"===a}function tL(e){try{return new RegExp(e),!0}catch(e){return!1}}function tj(e,t){if(!/^\d+$/.test(e)||e.length>1&&"0"===e[0])throw new tC(`Invalid semver: ${t}`);return parseInt(e,10)}function tD(e){let t=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!t||t.startsWith("."))throw new tC(`Invalid semver: ${e}`);let i=t.split("."),r=t=>void 0===t||""===t?0:tj(t,e);return[r(i[0]),r(i[1]),r(i[2])]}function tB(e,t){for(let i=0;i<3;i++){if(e[i]<t[i])return -1;if(e[i]>t[i])return 1}return 0}function tU(e){if(e instanceof Date)return e;if("string"==typeof e||"number"==typeof e){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new tC(`${e} is in an invalid date format`)}throw new tC(`The date provided ${e} must be a string, number, or date object`)}function tN(e,t,i,r,s){if(t>i&&(r.warn("min cannot be greater than max."),t=i),$(e))if(e>i)return r.warn(" cannot be greater than max: "+i+". Using max value instead."),i;else return e<t?(r.warn(" cannot be less than min: "+t+". Using min value instead."),t):e;return r.warn(" must be a number. using max or fallback. max: "+i+", fallback: "+s),tN(s||i,t,i,r)}class tq{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=tN(e.bucketSize,0,100,e._logger),this._refillRate=tN(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=tN(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){let i=Math.floor((t-e.lastAccess)/this._refillInterval);if(i>0){let t=i*this._refillRate;e.tokens=Math.min(e.tokens+t,this._bucketSize),e.lastAccess=e.lastAccess+i*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),i=String(e),r=this._buckets[i];return r?this._applyRefill(r,t):(r={tokens:this._bucketSize,lastAccess:t},this._buckets[i]=r),0===r.tokens||(r.tokens--,0===r.tokens&&this._onBucketRateLimited?.(e),0===r.tokens)}stop(){this._buckets={}}}var to=tn;class tH{constructor(e,t,i){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=i,this._rateLimiter=new tq({...function(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??1,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??10}}(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return F(e)&&"__posthog_previously_captured_error"in e&&!0===e.__posthog_previously_captured_error}static async buildEventMessage(e,t,i,r,s){let a={...s},n=e.buildFromUnknown(t,i);n.$exception_list=await e.modifyFrames(n.$exception_list);let o=to.getInjectedReleaseId();return o&&(a.$release_id=o),{event:"$exception",distinctId:r,properties:{...n,...a},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled()){var t,i,r;let s;t=this.onException.bind(this),i=this.onFatalError.bind(this),globalThis.process?.on("uncaughtException",(s=!1,Object.assign(r=>{let a=e.g.process.listeners("uncaughtException").filter(e=>"domainUncaughtExceptionClear"!==e.name&&!0!==e._posthogErrorHandler).length;t(r,{mechanism:{type:"onuncaughtexception",handled:!1}}),s||0!==a||(s=!0,i(r))},{_posthogErrorHandler:!0}))),r=this.onException.bind(this),globalThis.process?.on("unhandledRejection",e=>r(e,{mechanism:{type:"onunhandledrejection",handled:!1}}))}}onException(e,t){this.client.addPendingPromise((async()=>{if(!tH.isPreviouslyCapturedError(e)){let i=await tH.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),r=i.properties,s=r?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(s)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:s}):this.client._capturePreparedEvent(i,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(2e3),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class tW{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=null!==t?t:void 0}constructor(){this._memoryStorage={}}}let tz="analytics";class tG extends Error{constructor({requestId:e,drops:t,retryExhausted:i,cause:r}){super(tG.buildMessage(e,t,i,r)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=i,this.cause=r}static buildMessage(e,t,i,r){let s=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${i.length} undelivered`;return r instanceof Error&&(s+=` (${r.message})`),s}}function tK(e){if("boolean"==typeof e)return e;if("number"==typeof e)return 0!==e;if("string"==typeof e){let t=e.trim().toLowerCase();if("true"===t||"1"===t)return!0;if("false"===t||"0"===t)return!1}}let tV=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:tK},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:tK},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:tK},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(e){return"string"==typeof e?e:void 0}}],tQ=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function tJ(e,t,i){void 0===i||t in e||(e[t]=i)}function tY(e){var t;let i={..."object"==typeof(t=e.properties)&&null!==t&&!Array.isArray(t)?e.properties:{}},r={};for(let{property:e,optionKey:t,coerce:s}of tV)if(e in i){let a=s(i[e]);void 0!==a&&(r[t]=a),delete i[e]}let s={};for(let{property:e,field:t}of tQ)if(e in i){let r=i[e];"string"==typeof r&&(s[t]=r),delete i[e]}return delete i.$lib,delete i.$lib_version,tJ(i,"$set",e.$set),tJ(i,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:function(e){if("string"==typeof e)return Number.isNaN(new Date(e).getTime())?new Date().toISOString():e;if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=null==e?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}(e.timestamp),...s,options:r,properties:i}}let tX=new Set([408,500,502,503,504]);class tZ{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??3e4,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??(e=>new Promise(t=>W(t,e))),this.generateRequestId=t.generateRequestId??er,this.compress=t.compress??m}async sendV1Batch(e){if(0===e.length)return;let t=this.generateRequestId(),i=new Date(this.now()).toISOString(),{batch:r}=function(e,{createdAt:t,historicalMigration:i}){let r={created_at:t,batch:e.map(tY)};return i&&(r.historical_migration=!0),r}(e,{createdAt:i,historicalMigration:this.config.historicalMigration}),s=`${this.config.host}/i/v1/analytics/events`,a=[],n=r,o=Math.max(1,this.config.maxAttempts);for(let e=1;e<=o;e++){let r,l,u=e===o,c=v({created_at:i,...this.config.historicalMigration?{historical_migration:!0}:{},batch:n});try{r=await this.sendOnce(s,c,e,t)}catch(i){if(u)return this.surfaceBatchFailure(t,a,n,i);await this.sleep(this.backoffDelay(e));continue}let{status:h}=r;if(h<200||h>=300){if(!u&&tX.has(h)){let t=this.parseRetryAfter(r);await this.cancelBody(r),await this.sleep(this.backoffDelay(e,t));continue}let i=await this.buildHttpError(r,h);return this.surfaceBatchFailure(t,a,n,i)}try{l=await this.parseResponse(r)}catch{return this.surfaceBatchFailure(t,a,n,Error(`Capture V1 returned an unparseable ${h} response body`))}let d=this.classify(n,l,a);if(0===d.length)return this.surfacePartialDrops(t,a);if(u)return void this.onError(new tG({requestId:t,drops:a,retryExhausted:d.map(e=>e.uuid)}));n=d;let g=this.parseRetryAfter(r);await this.sleep(this.backoffDelay(e,g))}}async sendOnce(e,t,i,r){let s=this.buildHeaders(i,r),a=t;if(this.config.compressionEnabled){let e=await this.compress(t,this.config.isDebug);null!==e&&(a=e,s["Content-Encoding"]="gzip")}let n=new AbortController,o=W(()=>n.abort(),this.config.requestTimeoutMs);try{return await this.fetchFn(e,{method:"POST",headers:s,body:a,signal:n.signal})}finally{clearTimeout(o)}}buildHeaders(e,t){let i=`${this.config.libraryId}/${this.config.libraryVersion}`,r={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":i,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(r["User-Agent"]=this.config.userAgent),r}classify(e,t,i){let r=t.results??{},s=[];for(let t of e){let e=r[t.uuid];e&&("drop"===e.result?i.push({uuid:t.uuid,details:e.details??void 0}):"retry"===e.result&&s.push(t))}return s}backoffDelay(e,t){let i=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return void 0===t?i:Math.max(i,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let i=t.trim();if(/^\d+$/.test(i)){let e=parseInt(i,10);return Number.isFinite(e)&&e>0?1e3*e:void 0}let r=Date.parse(i);if(Number.isNaN(r))return;let s=r-this.now();return s>0?s:void 0}async parseResponse(e){let t=JSON.parse(await e.text());if("object"!=typeof t||null===t||Array.isArray(t))throw Error("unexpected response shape");let i=t.results;if(void 0!==i&&("object"!=typeof i||null===i||Array.isArray(i)))throw Error("unexpected results shape");return{results:i??{}}}async buildHttpError(e,t){let i="";try{i=(await e.text()).slice(0,512)}catch{}let r=i?`: ${i}`:"";return Error(`Capture V1 request failed with HTTP ${t}${r}`)}surfaceBatchFailure(e,t,i,r){this.onError(new tG({requestId:e,drops:t,retryExhausted:i.map(e=>e.uuid),cause:r}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new tG({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}}let t0=new Set;function t1(e,t){t0.has(e)||(t0.add(e),console.warn(`[PostHog] ${t}`))}class t2 extends tr{constructor(e,t={}){const i=function(e){return"string"==typeof e?e.trim():""}(e),r={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:function(e){return("string"==typeof e?e.trim():"")||"https://us.i.posthog.com"}(t.host),personalApiKey:function(e){return("string"==typeof e?e.trim():"")||void 0}(t.secretKey??t.personalApiKey)};if(super(i,r),this._memoryStorage=new tW,this._minimalFlagCalledEvents=!1,this.options=r,this.captureMode=function(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return"v0"===e||"v1"===e?e:"v0"}(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof r.featureFlagsPollingInterval?Math.max(r.featureFlagsPollingInterval,100):3e4,"number"==typeof r.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(r.waitUntilDebounceMs,0)),"number"==typeof r.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(r.waitUntilMaxWaitMs,0)),!this.disabled&&r.personalApiKey){if(r.personalApiKey.includes("phc_"))throw Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');!1!==r.enableLocalEvaluation&&(this.featureFlagsPoller=new tA({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:r.personalApiKey,projectApiKey:i,timeout:r.requestTimeout??1e4,host:this.host,fetch:r.fetch,onError:e=>{this._events.emit("error",e)},onLoad:e=>{this._events.emit("localEvaluationFlagsLoaded",e)},onMinimalFlagCalledEvents:e=>{this._minimalFlagCalledEvents=e},customHeaders:this.getCustomHeaders(),cacheProvider:r.flagDefinitionCacheProvider,strictLocalEvaluation:r.strictLocalEvaluation}))}this.errorTracking=new tH(this,r,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=r.maxCacheSize||5e4}enqueue(e,t,i){super.enqueue(e,t,i),this.scheduleDebouncedFlush()}async flush(){let e=this.flushWithPendingPromises(),t=this.options.waitUntil;if(t&&!this._waitUntilCycle)try{t(e.catch(()=>{}))}catch{}return e}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let t,i=new Promise(e=>{t=e});try{e(i)}catch{return}this._waitUntilCycle={resolve:t,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,i=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),t>=i)return void this.resolveWaitUntilFlush();let r=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=W(()=>{this.resolveWaitUntilFlush()},r)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this.flushWithPendingPromises()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){var t;return"v1"===this.captureMode&&"string"==typeof(t=e).event&&t.event.startsWith("$ai_")?"ai":tz}persistedQueueKeyForRoute(e){return"ai"===e?g.AiQueue:g.Queue}getActiveQueueRoutes(){return"v1"===this.captureMode?[tz,"ai"]:[tz]}async sendBatch(e,t,i=tz){if("v1"!==this.captureMode||"ai"===i)return super.sendBatch(e,t,i);let r=e.filter(e=>void 0!==e);await this.getV1Sender().sendV1Batch(r)}getV1Sender(){return this._v1Sender||(this._v1Sender=new tZ({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:e=>this._events.emit("error",e)})),this._v1Sender}getLibraryVersion(){return"5.47.7"}get metrics(){var e;let t;return this._metrics||(this._metrics=new X(this,(e=this.options.metrics,t=e?.resourceAttributes,{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1e3}),this._logger)),this._metrics}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,i){"string"==typeof e&&this._logger.warn(t),"$exception"!==e.event||e._originatedFromCaptureException||this._logger.warn(i)}_sendPreparedEvent(e,t,i,r){return this.addPendingPromise(this._prepareEventMessage(t,r).then(({distinctId:t,event:r,properties:s,options:a})=>{let n={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},o={distinctId:t,event:r,properties:{...s,...this.getCommonEventProperties()}};return i?this.sendImmediate(e,o,n):this.enqueue(e,o,n)}).catch(e=>{e&&console.error(e)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}identify({distinctId:e,properties:t={},disableGeoip:i}){let{$set:r,$set_once:s,$anon_distinct_id:a,...n}=t;this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:r||n,$set_once:s||{},$anon_distinct_id:a??void 0},disableGeoip:i},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:i}){let{$set:r,$set_once:s,$anon_distinct_id:a,...n}=t;await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:r||n,$set_once:s||{},$anon_distinct_id:a??void 0},disableGeoip:i},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:i={}}){if(0===Object.keys(t).length&&0===Object.keys(i).length)return;let r={};Object.keys(t).length>0&&(r.$set=t),Object.keys(i).length>0&&(r.$set_once=i),this.capture({distinctId:e,event:"$set",properties:r})}unsetPersonProperties({distinctId:e,properties:t}){let i=(Array.isArray(t)?t:[t]).filter(e=>"string"==typeof e&&e.trim().length>0);0!==i.length&&this.capture({distinctId:e,event:"$set",properties:{$unset:i}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(t=>{let i=setTimeout(()=>{r(),t(!1)},e),r=this._events.on("localEvaluationFlagsLoaded",e=>{clearTimeout(i),r(),t(e>0)})})}_resolveDistinctId(e,t){return"string"==typeof e?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,i={},r){let s,a,n,o,l,u,c,h;if(this.disabled)return void this._logger.warn("The client is disabled");let d=i.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&e in this._flagOverrides){let t=this._flagOverrides[e];if(void 0===t)return;let i=this._payloadOverrides?.[e];return{key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:i}}let{groups:g,disableGeoip:f}=i,{onlyEvaluateLocally:p,personProperties:y,groupProperties:m}=i,v=this.addLocalPersonAndGroupProperties(t,g,y,m);y=v.allPersonProperties,m=v.allGroupProperties;let _=this.createFeatureFlagEvaluationContext(t,g,this.personPropertiesForLocalEvaluation(t,y),m);void 0==p&&(p=this.options.strictLocalEvaluation??!1);let b=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let t=this.featureFlagsPoller?.featureFlagsByKey[e];if(t)try{let i=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(t,_,{matchValue:r});if(i){b=!0;let r=i.value;l=t.id,c="Evaluated locally",h=t.has_experiment,s={key:e,enabled:!1!==r,variant:"string"==typeof r?r:void 0,payload:i.payload??void 0}}}catch(t){if(t instanceof tk||t instanceof tC)this._logger?.info(`${t.name} when computing flag locally: ${e}: ${t.message}`);else throw t}}if(!b&&!p){let t=await super.getFeatureFlagDetailsStateless(_.distinctId,_.groups,y,m,f,[e]);if(void 0===t)o=tF.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===t.minimalFlagCalledEvents,a=t.requestId,n=t.evaluatedAt;let i=[];t.errorsWhileComputingFlags&&i.push(tF.ERRORS_WHILE_COMPUTING),t.quotaLimited?.includes("feature_flags")&&i.push(tF.QUOTA_LIMITED);let r=t.flags[e];if(void 0===r)i.push(tF.FLAG_MISSING);else{let t;if(l=r.metadata?.id,u=r.metadata?.version,c=r.reason?.description??r.reason?.code,h=r.metadata?.has_experiment,r.metadata?.payload!==void 0)try{t=JSON.parse(r.metadata.payload)}catch{t=r.metadata.payload}s={key:e,enabled:r.enabled,variant:r.variant,payload:t}}i.length>0&&(o=i.join(","))}}if(d){let i=void 0===s?void 0:!1!==s.enabled&&(s.variant??!0),r={$feature_flag:e,$feature_flag_response:i,$feature_flag_id:l,$feature_flag_version:u,$feature_flag_reason:c,locally_evaluated:b,[`$feature/${e}`]:i,$feature_flag_request_id:a,$feature_flag_evaluated_at:b?Date.now():n};if(void 0!==h&&(r.$feature_flag_has_experiment=h),b&&this.featureFlagsPoller){let e=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==e&&(r.$feature_flag_definitions_loaded_at=e)}o&&(r.$feature_flag_error=o),this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:i,groups:g,disableGeoip:f,properties:r})}return void 0!==s&&void 0!==this._payloadOverrides&&e in this._payloadOverrides&&(s={...s,payload:this._payloadOverrides[e]}),s}async getFeatureFlag(e,t,i){t1("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 r=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(void 0!==r)return!1!==r.enabled&&(r.variant??!0)}async getFeatureFlagPayload(e,t,i,r){if(t1("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request."),void 0!==this._payloadOverrides&&e in this._payloadOverrides)return this._payloadOverrides[e];let s=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:!1},i);if(void 0!==s)return s.payload??null}async getFeatureFlagResult(e,t,i){let{distinctId:r,options:s}=this._resolveDistinctId(t,i);return r?this._getFeatureFlagResult(e,r,{...s,sendFeatureFlagEvents:s?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let i=await t.json();if("string"==typeof i)try{return JSON.parse(i)}catch(e){}return i}async isFeatureEnabled(e,t,i){t1("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 r=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return void 0===r?void 0:!1!==r.enabled&&!!(r.variant??!0)}async getAllFlags(e,t){let{distinctId:i,options:r}=this._resolveDistinctId(e,t);return i?(await this.getAllFlagsAndPayloads(i,r)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:i,options:r}=this._resolveDistinctId(e,t);if(!i)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads — pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:s,disableGeoip:a,flagKeys:n}=r||{},{onlyEvaluateLocally:o,personProperties:l,groupProperties:u}=r||{},c=this.addLocalPersonAndGroupProperties(i,s,l,u);l=c.allPersonProperties,u=c.allGroupProperties;let h=this.createFeatureFlagEvaluationContext(i,s,this.personPropertiesForLocalEvaluation(i,l),u);void 0==o&&(o=this.options.strictLocalEvaluation??!1);let d=await this.featureFlagsPoller?.getAllFlagsAndPayloads(h,n),g={},f={},p=!0;if(d&&(g=d.response,f=d.payloads,p=d.fallbackToFlags),p&&!o){let e=await super.getFeatureFlagsAndPayloadsStateless(h.distinctId,h.groups,l,u,a,n);g={...g,...e.flags||{}},f={...f,...e.payloads||{}}}return void 0!==this._flagOverrides&&(g={...g,...this._flagOverrides}),void 0!==this._payloadOverrides&&(f={...f,...this._payloadOverrides}),{featureFlags:g,featureFlagPayloads:f}}async evaluateFlags(e,t){let i,r,{distinctId:s,options:a}=this._resolveDistinctId(e,t);if(!s)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new tP({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new tP({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,flags:{}});let{groups:n,disableGeoip:o,flagKeys:l}=a||{},{onlyEvaluateLocally:u,personProperties:c,groupProperties:h}=a||{},d=this.addLocalPersonAndGroupProperties(s,n,c,h);c=d.allPersonProperties,h=d.allGroupProperties;let g=this.createFeatureFlagEvaluationContext(s,n,this.personPropertiesForLocalEvaluation(s,c),h);void 0==u&&(u=this.options.strictLocalEvaluation??!1);let f={},p=!1,y=!1,m=await this.featureFlagsPoller?.getAllFlagsAndPayloads(g,l),v=new Set;if(m)for(let[e,t]of Object.entries(m.response)){let i=this.featureFlagsPoller?.featureFlagsByKey[e];f[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:m.payloads[e],id:i?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:i?.has_experiment},v.add(e)}if((!m||m.fallbackToFlags)&&!u){let e=await super.getFeatureFlagDetailsStateless(g.distinctId,g.groups,c,h,o,l);if(e)for(let[t,s]of(this._minimalFlagCalledEvents=!0===e.minimalFlagCalledEvents,i=e.requestId,r=e.evaluatedAt,p=!!e.errorsWhileComputingFlags,y=Array.isArray(e.quotaLimited)&&e.quotaLimited.includes("feature_flags"),Object.entries(e.flags))){let e;if(!v.has(t)){if(s.metadata?.payload!==void 0)try{e=JSON.parse(s.metadata.payload)}catch{e=s.metadata.payload}f[t]={key:t,enabled:s.enabled,variant:s.variant,payload:e,id:s.metadata?.id,version:s.metadata?.version,reason:s.reason?.description??s.reason?.code,locallyEvaluated:!1,hasExperiment:s.metadata?.has_experiment}}}}if(void 0!==this._flagOverrides)for(let[e,t]of Object.entries(this._flagOverrides)){if(void 0===t){delete f[e];continue}let i=f[e];f[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:i?.payload,id:i?.id,version:i?.version,reason:i?.reason,locallyEvaluated:i?.locallyEvaluated??!1,hasExperiment:i?.hasExperiment}}if(void 0!==this._payloadOverrides)for(let[e,t]of Object.entries(this._payloadOverrides)){let i=f[e];i&&(f[e]={...i,payload:t})}return new tP({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:n,disableGeoip:o,flags:f,requestId:i,evaluatedAt:r,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:p,quotaLimited:y})}_shouldSendMinimalFlagCalledEvent(e,t){return"$feature_flag_called"===e&&this._minimalFlagCalledEvents&&!1===t.$feature_flag_has_experiment}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:i,response:r,groups:s,disableGeoip:a,properties:n}=e,o=s&&Object.keys(s).length>0?`_${JSON.stringify(Object.entries(s).sort(([e],[t])=>e<t?-1:+(e>t)))}`:"",l=`${i}_${r}${o}`;t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(l)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[t]instanceof Set?this.distinctIdHasSentFlagCalls[t].add(l):this.distinctIdHasSentFlagCalls[t]=new Set([l]),this.capture({distinctId:t,event:"$feature_flag_called",properties:n,groups:s,disableGeoip:a}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),logWarning:e=>{!1!==this.options.featureFlagsLogWarnings&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:i,distinctId:r,disableGeoip:s}){this._sendPreparedEvent("capture",{distinctId:r||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{}},disableGeoip:s},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:i,distinctId:r,disableGeoip:s}){await this._sendPreparedEvent("capture",{distinctId:r||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:i||{}},disableGeoip:s},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=e=>Object.fromEntries(e.map(e=>[e,!0]));if(!1===e){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(!1===e.flags?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):void 0!==e.flags&&(this._flagOverrides={...e.flags})),"payloads"in e&&(!1===e.payloads?this._payloadOverrides=void 0:void 0!==e.payloads&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if("flags"in e){let t=e.flags;if(!1===t||Array.isArray(t)||"object"==typeof t&&null!==t)return!0}if("payloads"in e){let t=e.payloads;if(!1===t||"object"==typeof t&&null!==t)return!0}return!1}withContext(e,t,i){return this.context?this.context.run(e,t,i):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??3e4),i=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await z(this._metrics.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._metrics.reset());try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},i?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,i={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},r=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let e=new AbortController;r=W(()=>{e.abort()},this.options.requestTimeout),i.signal=e.signal}try{return await this.fetch(t,i)}catch(e){this._events.emit("error",e);return}finally{r&&clearTimeout(r)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let i={},r={};for(let[s,a]of Object.entries(e))if(C(a,"Object")&&t&&s in t){let e={};for(let[t,i]of Object.entries(a))e[String(t)]=String(i);r[String(s)]=e}else i[String(s)]=String(a);return{personProperties:i,groupProperties:r}}async getFeatureFlagsForEvent(e,t,i,r){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let s=r?.personProperties||{},a=r?.groupProperties||{},n=r?.flagKeys;if(r?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let r={};for(let[e,i]of Object.entries(t||{}))r[e]=String(i);return await this.getAllFlags(e,{groups:r,personProperties:s,groupProperties:a,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:n})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let r={};for(let[e,i]of Object.entries(t||{}))r[e]=String(i);return await this.getAllFlags(e,{groups:r,personProperties:s,groupProperties:a,disableGeoip:i,onlyEvaluateLocally:!0,flagKeys:n})}return(await super.getFeatureFlagsStateless(e,t,s,a,i)).flags}addLocalPersonAndGroupProperties(e,t,i,r){let s={...i||{}},a={};if(t)for(let e of Object.keys(t))a[e]={$group_key:t[e],...r?.[e]||{}};return{allPersonProperties:s,allGroupProperties:a}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,i,r){return{distinctId:e,groups:t||{},personProperties:i||{},groupProperties:r||{},evaluationCache:{}}}captureException(e,t,i,r,s){if(!tH.isPreviouslyCapturedError(e)){let a=Error("PostHog syntheticException");this.addPendingPromise(tH.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:a},t,i).then(e=>this._capturePreparedEvent({...e,uuid:r,flags:s},!1)))}}async captureExceptionImmediate(e,t,i,r){if(!tH.isPreviouslyCapturedError(e)){let s=Error("PostHog syntheticException");return this.addPendingPromise(tH.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,i).then(e=>this.captureImmediate({...e,flags:r})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:i,event:r,properties:s,groups:a,flags:n,sendFeatureFlags:o,timestamp:l,disableGeoip:u,uuid:c}=e,h=this.context?.get(),g=t.includeContextProperties??!0,f=i||h?.distinctId,p=g?{...this.props,...h?.properties||{},...s||{}}:{...s||{}};f||(f=er(),p.$process_person_profile=!1),g&&h?.sessionId&&!p.$session_id&&(p.$session_id=h.sessionId);let y=this._shouldSendMinimalFlagCalledEvent(r,p)?d(p):p,m=this._runBeforeSend({distinctId:f,event:r,properties:y,groups:a,flags:n,sendFeatureFlags:o,timestamp:l,disableGeoip:u,uuid:c});if(!m)return Promise.reject(null);let v=await Promise.resolve().then(async()=>{if(n)return o&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),n._getEventProperties();if(o){t1("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");var e=await this.getFeatureFlagsForEvent(m.distinctId,a,u,"object"==typeof o?o:void 0);if(!e)return{};let t={};for(let[i,r]of Object.entries(e))t[`$feature/${i}`]=r;let i=Object.keys(e).filter(t=>!1!==e[t]).sort();return i.length>0&&(t.$active_feature_flags=i),t}return{}}).catch(()=>({})).then(e=>{let t=m.groups||a;return{...e,...m.properties||{},...void 0!==t&&Object.keys(t).length>0?{$groups:t}:{}}});return"$pageview"===m.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof v.$raw_user_agent&&tE(v.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(m.event="$bot_pageview",v.$browser_type="bot"),{distinctId:m.distinctId,event:m.event,properties:v,options:{timestamp:m.timestamp,disableGeoip:m.disableGeoip,uuid:m.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let i=Array.isArray(t)?t:[t],r=e;for(let t of i){if(!(r=t(r)))return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!r.properties||0===Object.keys(r.properties).length){let e=`Event '${r.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(e)}}return r}}var to=tn,t4=e.i(78500);class t3{constructor(){this.storage=new t4.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,i){return this.storage.run(this.resolve(e,i),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let i=this.get()||{};return{distinctId:e.distinctId??i.distinctId,sessionId:e.sessionId??i.sessionId,properties:{...i.properties||{},...e.properties||{}}}}}var to=tn;let t5="posthog-node";function t8(e,{organization:t,projectId:i,prefix:r,severityAllowList:s=["error"],sendExceptionsToPostHog:a=!0}={}){return n=>{if(!("*"===s||s.includes(n.level)))return n;n.tags||(n.tags={});let o=n.tags[t9.POSTHOG_ID_TAG];if(void 0===o)return n;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${o}`,l).toString();n.tags["PostHog Person URL"]=u;let c=n.exception?.values||[],h=c.map(e=>({...e,stacktrace:e.stacktrace?{...e.stacktrace,type:"raw",frames:(e.stacktrace.frames||[]).map(e=>({...e,platform:"node:javascript"}))}:void 0})),d={$exception_message:c[0]?.value||n.message,$exception_type:c[0]?.type,$exception_level:n.level,$exception_list:h,$sentry_event_id:n.event_id,$sentry_exception:n.exception,$sentry_exception_message:c[0]?.value||n.message,$sentry_exception_type:c[0]?.type,$sentry_tags:n.tags},g=to.getInjectedReleaseId();return g&&(d.$release_id=g),t&&i&&(d.$sentry_url=(r||"https://sentry.io/organizations/")+t+"/issues/?project="+i+"&query="+n.event_id),a&&e.capture({event:"$exception",distinctId:o,properties:d}),n}}function t6(e,t){let i=t8(e,t);return{name:t5,processEvent:e=>i(e)}}class t9{static #e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,i,r,s){this.name=t5,this.name=t5,this.setupOnce=function(a,n){a(t8(e,{organization:t,projectId:n()?.getClient()?.getDsn()?.projectId,prefix:i,severityAllowList:r,sendExceptionsToPostHog:s??!0}))}}}e.s(["PostHogSentryIntegration",0,t9,"createEventProcessor",0,t8,"sentryIntegration",0,t6],92164);let t7=/[\x00-\x1f\x7f-\x9f]/g;function ie(e,t,i){null!=i&&""!==i&&(e[t]=i)}function it(e){return Array.isArray(e)?e[0]:e}function ii(e){if(Array.isArray(e)){for(let t of e){let e=ii(t);if(void 0!==e)return e}return}if("string"!=typeof e)return;let t=e.replace(t7,"").trim();if(t)return t.length>1e3?t.slice(0,1e3):t}function ir(e,t){var i,r;let s,{sessionId:a,distinctId:n}=function(e){if(!e)return{};let t=ii(e["x-posthog-session-id"]),i=ii(e["x-posthog-distinct-id"]);return{...void 0!==t?{sessionId:t}:{},...void 0!==i?{distinctId:i}:{}}}(t.headers),o={},l=!0===e.options.disable_capture_url_hashes;return ie(o,"$current_url",(i=t.originalUrl||t.url,l?N(i):i)),ie(o,"$request_method",t.method),ie(o,"$request_path",(r=t.path,s=function(e){if(!e)return e;let t=e.indexOf("?"),i=e.indexOf("#");return -1===t||-1!==i&&i<t?e:`${e.slice(0,t)}${-1===i?"":e.slice(i)}`}(r),l?N(s):s)),ie(o,"$user_agent",it(t.headers["user-agent"])),ie(o,"$ip",function(e){let t=it(e.headers["x-forwarded-for"]);if(t){let e=t.split(",")[0].trim();if(e)return e}return e.socket?.remoteAddress}(t)),{...void 0!==a?{sessionId:a}:{},...void 0!==n?{distinctId:n}:{},properties:o}}function is(e,t){var i;t.use((i=e,(e,t,r)=>{i.withContext(ir(i,e),()=>r())}))}function ia(e,t){var i;t.use((i=e,(e,t,r,s)=>{if(tH.isPreviouslyCapturedError(e))return void s(e);let a=ir(i,t),n=Error("Synthetic exception"),o={...void 0!==a.sessionId?{$session_id:a.sessionId}:{},...a.properties||{},$response_status_code:r.statusCode};i.addPendingPromise(tH.buildEventMessage(i.getErrorPropertiesBuilder(),e,{mechanism:{type:"middleware",handled:!1},syntheticException:n},a.distinctId,o).then(e=>i._capturePreparedEvent(e,!1))),s(e)}))}e.s(["setupExpressErrorHandler",0,ia,"setupExpressRequestContext",0,is],88512),e.s([],52538);class io extends t2{getLibraryId(){return"posthog-node"}initializeContext(){return new t3}createErrorPropertiesBuilder(){let e;return new to.ErrorPropertiesBuilder([new to.EventCoercer,new to.ErrorCoercer,new to.ObjectCoercer,new to.StringCoercer,new to.PrimitiveCoercer],to.createStackParser("node:javascript",to.nodeStackLineParser),[(e=function(e=process.argv[1]?(0,o.dirname)(process.argv[1]):process.cwd(),t="\\"===o.sep){let i=t?l(e):e;return e=>{if(!e)return;let r=t?l(e):e,{dir:s,base:a,ext:n}=o.posix.parse(r);(".js"===n||".mjs"===n||".cjs"===n)&&(a=a.slice(0,-1*n.length));let u=decodeURIComponent(a);s||(s=".");let c=s.lastIndexOf("/node_modules");if(c>-1)return`${s.slice(c+14).replace(/\//g,".")}:${u}`;if(s.startsWith(i)){let e=s.slice(i.length+1).replace(/\//g,".");return e?`${e}:${u}`:u}return u}}(),async t=>{for(let i of t)i.module=e(i.filename);return t}),e=>tf(e,void 0,this._logger),function(e=process.cwd()){let t="\\"===o.sep,i=e=>t?e.replace(/\\/g,"/"):e,r=i(e);return async e=>{for(let t of e)!(!t.filename||t.filename.startsWith("node:")||t.filename.startsWith("data:"))&&(0,o.isAbsolute)(t.filename)&&(t.filename=i((0,o.relative)(r,i(t.filename))));return e}}()])}}e.s(["PostHog",0,io],89767),e.i(89767),e.i(52538),e.i(92164),e.i(88512),e.i(88096),e.s(["FeatureFlagError",0,f,"FeatureFlagEvaluations",0,tP,"PostHogSentryIntegration",0,t9,"cookieStateToProperties",0,eu,"cookieStoreFromHeader",0,ea,"createEventProcessor",0,t8,"getPostHogCookieName",0,en,"parsePostHogCookie",0,ec,"readPostHogCookie",0,el,"sentryIntegration",0,t6,"serializePostHogCookie",0,eo,"setupExpressErrorHandler",0,ia,"setupExpressRequestContext",0,is,"uuidv7",0,er],92349),e.i(92349),e.s(["FeatureFlagError",0,f,"FeatureFlagEvaluations",0,tP,"PostHog",0,io,"PostHogSentryIntegration",0,t9,"cookieStateToProperties",0,eu,"cookieStoreFromHeader",0,ea,"createEventProcessor",0,t8,"getPostHogCookieName",0,en,"parsePostHogCookie",0,ec,"readPostHogCookie",0,el,"sentryIntegration",0,t6,"serializePostHogCookie",0,eo,"setupExpressErrorHandler",0,ia,"setupExpressRequestContext",0,is,"uuidv7",0,er],39702)}];
3
3
 
4
4
  //# sourceMappingURL=node_modules_posthog-node_dist_entrypoints_index_node_mjs_01r25oi._.js.map
@@ -1,3 +1,3 @@
1
- module.exports=[93133,(e,t,i)=>{t.exports={name:"failproofai",version:"1.0.0-beta.16",description:"The easiest way to manage policies that keep your AI agents reliable, on-task, and running autonomously — for Claude Code & the Agents SDK",bin:{failproofai:"./dist/cli.mjs",failproofaid:"./bin/failproofaid-shim.mjs"},files:["bin/","src/","scripts/","lib/","pi-extension/","openclaw-plugin/",".next/standalone/","dist/","README.md"],engines:{node:">=20.9.0",bun:">=1.3.0"},scripts:{predev:"bun run build:cli && bun link",dev:"FAILPROOFAI_TELEMETRY_DISABLED=1 bun scripts/dev.ts --port 8020","build:cli":"bun build --target=node --format=esm --outfile=dist/cli.mjs bin/failproofai.mjs --external posthog-node --external sql.js && node -e \"const fs=require('fs');const c=fs.readFileSync('dist/cli.mjs','utf8');fs.writeFileSync('dist/cli.mjs',c.replace('#!/usr/bin/env bun','#!/usr/bin/env node').replace('// @bun\\n',''))\"","build:worker":"bun build --target=node --format=esm --outfile=dist/worker.mjs bin/failproofai-worker.mjs --external posthog-node --external sql.js",build:"bun build --target=node --format=cjs --outfile=dist/index.js src/index.ts && bun run build:cli && bun run build:worker && bun --bun next build && node -e \"const {cpSync}=require('fs');cpSync('.next/static','.next/standalone/.next/static',{recursive:true});\" && node scripts/prune-standalone.mjs",prestart:"bun run build:cli && bun link",start:"FAILPROOFAI_TELEMETRY_DISABLED=1 bun scripts/start.ts",test:"vitest","test:run":"vitest run",lint:"eslint . --config eslint.config.mjs",prepare:"bun run build","test:e2e":"vitest run --config vitest.config.e2e.mts","test:e2e:watch":"vitest --config vitest.config.e2e.mts",translate:"bun scripts/translate-docs/cli.ts","translate:readme":"bun scripts/translate-docs/cli.ts --readme-only","translate:docs":"bun scripts/translate-docs/cli.ts --docs-only","translate:dry-run":"bun scripts/translate-docs/cli.ts --dry-run","translate:validate":"bun scripts/translate-docs/cli.ts --validate","validate:mdx":"bun scripts/validate-mdx.ts"},keywords:["claude","claude-code","claude-agents-sdk","anthropic","ai-agent","agent-reliability","agent-monitoring","autonomous-agent","failure-prevention","developer-tools","devtools","cli","local-first","hooks","policies"],author:"ExosphereHost Inc. <failproofai@exosphere.host>",license:"SEE LICENSE IN LICENSE",homepage:"https://github.com/FailproofAI/failproofai",repository:{type:"git",url:"https://github.com/FailproofAI/failproofai.git"},bugs:{url:"https://github.com/FailproofAI/failproofai/issues"},publishConfig:{access:"public"},devDependencies:{"@anthropic-ai/sdk":"^0.115.0","@mdx-js/mdx":"^3.1.1","@tailwindcss/postcss":"^4.3.1","@tanstack/react-virtual":"^3.14.9","@testing-library/jest-dom":"^7.0.0","@testing-library/react":"^16.3.2","@testing-library/user-event":"^14.6.1","@types/node":"26.1.2","@types/react":"19.2.18","@types/react-dom":"^19.2.3","@vitejs/plugin-react":"^6.0.5",clsx:"^2.1.1",eslint:"^10.5.0","eslint-config-next":"^16.2.9",jsdom:"^30.0.1","lucide-react":"^1.28.0",next:"^16.2.11",react:"^19.2.4","react-dom":"^19.2.4","tailwind-merge":"^3.4.0",tailwindcss:"^4.3.1",typescript:"6.0.3",vitest:"^4.1.9"},dependencies:{"html-to-image":"^1.11.13","posthog-node":"^5.47.7","sql.js":"^1.14.1",yaml:"^2.9.0"},overrides:{postcss:"8.5.26","eslint-plugin-react-hooks":"7.0.1",vite:"8.0.16",undici:"7.29.0","brace-expansion":"5.0.9",sharp:"0.35.0"},optionalDependencies:{"@failproofai/failproofaid-linux-x64":"1.0.0-beta.16","@failproofai/failproofaid-linux-arm64":"1.0.0-beta.16","@failproofai/failproofaid-darwin-x64":"1.0.0-beta.16","@failproofai/failproofaid-darwin-arm64":"1.0.0-beta.16"},failproofaidBinaries:{"linux-x64":"b82471309d2e52724781d8074bae55444892030eb1b48305ef74053bb7938931","linux-arm64":"5a0bdc9f726844e7ed109c896bb894e84a51c7592fe4aed26eceea78c97fde04","darwin-x64":"08881822befb31fe13974d2861fc50b6b2c1c72741986656e8f9087586202d88","darwin-arm64":"cc85096de72f3e5813145b7c906ea6a2d4788f39f4dae6a86532d88107802cab"}}}];
1
+ module.exports=[93133,(e,t,i)=>{t.exports={name:"failproofai",version:"1.0.0-beta.18",description:"The easiest way to manage policies that keep your AI agents reliable, on-task, and running autonomously — for Claude Code & the Agents SDK",bin:{failproofai:"./dist/cli.mjs",failproofaid:"./bin/failproofaid-shim.mjs"},files:["bin/","src/","scripts/","lib/","pi-extension/","openclaw-plugin/",".next/standalone/","dist/","README.md"],engines:{node:">=20.9.0",bun:">=1.3.0"},scripts:{predev:"bun run build:cli && bun link",dev:"FAILPROOFAI_TELEMETRY_DISABLED=1 bun scripts/dev.ts --port 8020","build:cli":"bun build --target=node --format=esm --outfile=dist/cli.mjs bin/failproofai.mjs --external posthog-node --external sql.js && node -e \"const fs=require('fs');const c=fs.readFileSync('dist/cli.mjs','utf8');fs.writeFileSync('dist/cli.mjs',c.replace('#!/usr/bin/env bun','#!/usr/bin/env node').replace('// @bun\\n',''))\"","build:worker":"bun build --target=node --format=esm --outfile=dist/worker.mjs bin/failproofai-worker.mjs --external posthog-node --external sql.js",build:"bun build --target=node --format=cjs --outfile=dist/index.js src/index.ts && bun run build:cli && bun run build:worker && bun --bun next build && node -e \"const {cpSync}=require('fs');cpSync('.next/static','.next/standalone/.next/static',{recursive:true});\" && node scripts/prune-standalone.mjs",prestart:"bun run build:cli && bun link",start:"FAILPROOFAI_TELEMETRY_DISABLED=1 bun scripts/start.ts",test:"vitest","test:run":"vitest run",lint:"eslint . --config eslint.config.mjs",prepare:"bun run build","test:e2e":"vitest run --config vitest.config.e2e.mts","test:e2e:watch":"vitest --config vitest.config.e2e.mts",translate:"bun scripts/translate-docs/cli.ts","translate:readme":"bun scripts/translate-docs/cli.ts --readme-only","translate:docs":"bun scripts/translate-docs/cli.ts --docs-only","translate:dry-run":"bun scripts/translate-docs/cli.ts --dry-run","translate:validate":"bun scripts/translate-docs/cli.ts --validate","validate:mdx":"bun scripts/validate-mdx.ts"},keywords:["claude","claude-code","claude-agents-sdk","anthropic","ai-agent","agent-reliability","agent-monitoring","autonomous-agent","failure-prevention","developer-tools","devtools","cli","local-first","hooks","policies"],author:"ExosphereHost Inc. <failproofai@exosphere.host>",license:"SEE LICENSE IN LICENSE",homepage:"https://github.com/FailproofAI/failproofai",repository:{type:"git",url:"https://github.com/FailproofAI/failproofai.git"},bugs:{url:"https://github.com/FailproofAI/failproofai/issues"},publishConfig:{access:"public"},devDependencies:{"@anthropic-ai/sdk":"^0.115.0","@mdx-js/mdx":"^3.1.1","@tailwindcss/postcss":"^4.3.1","@tanstack/react-virtual":"^3.14.9","@testing-library/jest-dom":"^7.0.0","@testing-library/react":"^16.3.2","@testing-library/user-event":"^14.6.1","@types/node":"26.1.2","@types/react":"19.2.18","@types/react-dom":"^19.2.3","@vitejs/plugin-react":"^6.0.5",clsx:"^2.1.1",eslint:"^10.5.0","eslint-config-next":"^16.2.9",jsdom:"^30.0.1","lucide-react":"^1.28.0",next:"^16.2.11",react:"^19.2.4","react-dom":"^19.2.4","tailwind-merge":"^3.4.0",tailwindcss:"^4.3.1",typescript:"6.0.3",vitest:"^4.1.9"},dependencies:{"html-to-image":"^1.11.13","posthog-node":"^5.47.7","sql.js":"^1.14.1",yaml:"^2.9.0"},overrides:{postcss:"8.5.26","eslint-plugin-react-hooks":"7.0.1",vite:"8.0.16",undici:"7.29.0","brace-expansion":"5.0.9",sharp:"0.35.0"},optionalDependencies:{"@failproofai/failproofaid-linux-x64":"1.0.0-beta.18","@failproofai/failproofaid-linux-arm64":"1.0.0-beta.18","@failproofai/failproofaid-darwin-x64":"1.0.0-beta.18","@failproofai/failproofaid-darwin-arm64":"1.0.0-beta.18"},failproofaidBinaries:{"linux-x64":"54bf7cc41ee8b5a2ea9430459c1fe9b8b03ece25c18d8bee49441feee93c7057","linux-arm64":"1f5e7c4be2d9c591cf4fd39e5fc122e71f507115cdb2ad1a27c5f30f22a30028","darwin-x64":"ae510969144aaec5e8891cfa5cdf7374c5efbd7554547046efa5913aab5c3ab2","darwin-arm64":"bc8d96e295aa9a68590be6e12d4bf3711749a31371206e63ccc36dd42b275e18"}}}];
2
2
 
3
3
  //# sourceMappingURL=package_json_%5Bjson%5D_cjs_1nxcc4v._.js.map