failproofai 0.0.8 → 0.0.9-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/.next/standalone/.codex/hooks.json +77 -0
  2. package/.next/standalone/.next/BUILD_ID +1 -1
  3. package/.next/standalone/.next/build-manifest.json +6 -6
  4. package/.next/standalone/.next/prerender-manifest.json +3 -3
  5. package/.next/standalone/.next/required-server-files.json +1 -1
  6. package/.next/standalone/.next/server/app/_global-error/page/build-manifest.json +3 -3
  7. package/.next/standalone/.next/server/app/_global-error/page/server-reference-manifest.json +1 -1
  8. package/.next/standalone/.next/server/app/_global-error/page.js.nft.json +1 -1
  9. package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  10. package/.next/standalone/.next/server/app/_global-error.html +1 -1
  11. package/.next/standalone/.next/server/app/_global-error.rsc +7 -7
  12. package/.next/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +2 -2
  13. package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +7 -7
  14. package/.next/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +3 -3
  15. package/.next/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +3 -3
  16. package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  17. package/.next/standalone/.next/server/app/_not-found/page/build-manifest.json +3 -3
  18. package/.next/standalone/.next/server/app/_not-found/page/server-reference-manifest.json +1 -1
  19. package/.next/standalone/.next/server/app/_not-found/page.js.nft.json +1 -1
  20. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  21. package/.next/standalone/.next/server/app/_not-found.html +2 -2
  22. package/.next/standalone/.next/server/app/_not-found.rsc +17 -17
  23. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +17 -17
  24. package/.next/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +4 -4
  25. package/.next/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +11 -11
  26. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
  27. package/.next/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +3 -3
  28. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  29. package/.next/standalone/.next/server/app/index.html +1 -1
  30. package/.next/standalone/.next/server/app/index.rsc +16 -16
  31. package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
  32. package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +16 -16
  33. package/.next/standalone/.next/server/app/index.segments/_head.segment.rsc +4 -4
  34. package/.next/standalone/.next/server/app/index.segments/_index.segment.rsc +11 -11
  35. package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  36. package/.next/standalone/.next/server/app/page/build-manifest.json +3 -3
  37. package/.next/standalone/.next/server/app/page/server-reference-manifest.json +1 -1
  38. package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
  39. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  40. package/.next/standalone/.next/server/app/policies/page/build-manifest.json +3 -3
  41. package/.next/standalone/.next/server/app/policies/page/server-reference-manifest.json +8 -8
  42. package/.next/standalone/.next/server/app/policies/page.js +1 -1
  43. package/.next/standalone/.next/server/app/policies/page.js.nft.json +1 -1
  44. package/.next/standalone/.next/server/app/policies/page_client-reference-manifest.js +1 -1
  45. package/.next/standalone/.next/server/app/project/[name]/page/build-manifest.json +3 -3
  46. package/.next/standalone/.next/server/app/project/[name]/page/server-reference-manifest.json +1 -1
  47. package/.next/standalone/.next/server/app/project/[name]/page.js +1 -1
  48. package/.next/standalone/.next/server/app/project/[name]/page.js.nft.json +1 -1
  49. package/.next/standalone/.next/server/app/project/[name]/page_client-reference-manifest.js +1 -1
  50. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/build-manifest.json +3 -3
  51. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/react-loadable-manifest.json +2 -2
  52. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/server-reference-manifest.json +2 -2
  53. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page.js +1 -1
  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 +3 -3
  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/chunks/[root-of-the-server]__0g72weg._.js +1 -1
  61. package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_05pz9._._.js +1 -1
  62. package/.next/standalone/.next/server/chunks/package_json_[json]_cjs_0z7w.hh._.js +1 -1
  63. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0h3orxc._.js → [root-of-the-server]__0.f_cyx._.js} +2 -2
  64. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0m72uj7._.js → [root-of-the-server]__03rd.z8._.js} +2 -2
  65. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__092s1ta._.js +2 -2
  66. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__09icjsf._.js +2 -2
  67. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0dub28-._.js +3 -0
  68. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0e74wa-._.js +3 -0
  69. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0g.lg8b._.js +2 -2
  70. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0h..k-e._.js +2 -2
  71. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0okos0k._.js → [root-of-the-server]__0vu.o-3._.js} +3 -3
  72. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0w6l33k._.js +7 -7
  73. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0of~riu._.js → [root-of-the-server]__0zqcovi._.js} +2 -2
  74. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__11pa2ra._.js +2 -2
  75. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__12t-wym._.js +2 -2
  76. package/.next/standalone/.next/server/chunks/ssr/_07a1g.3._.js +3 -0
  77. package/.next/standalone/.next/server/chunks/ssr/_0uy6m~m._.js +3 -0
  78. package/.next/standalone/.next/server/chunks/ssr/_0zaq1hm._.js +3 -0
  79. package/.next/standalone/.next/server/chunks/ssr/_10lm7or._.js +2 -2
  80. package/.next/standalone/.next/server/chunks/ssr/_11rg2a_._.js +3 -0
  81. package/.next/standalone/.next/server/chunks/ssr/app_global-error_tsx_0xerkr6._.js +1 -1
  82. package/.next/standalone/.next/server/chunks/ssr/app_policies_hooks-client_tsx_0q-m0y-._.js +2 -2
  83. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_0h9llsw._.js +1 -1
  84. package/.next/standalone/.next/server/chunks/ssr/node_modules_posthog-node_dist_entrypoints_index_node_mjs_0mebn66._.js +1 -1
  85. package/.next/standalone/.next/server/middleware-build-manifest.js +6 -6
  86. package/.next/standalone/.next/server/pages/404.html +2 -2
  87. package/.next/standalone/.next/server/pages/500.html +1 -1
  88. package/.next/standalone/.next/server/server-reference-manifest.js +1 -1
  89. package/.next/standalone/.next/server/server-reference-manifest.json +9 -9
  90. package/.next/standalone/.next/static/chunks/0.rk1iwdt1d7c.css +1 -0
  91. package/.next/standalone/.next/static/chunks/00b5h4r1el.6f.js +1 -0
  92. package/.next/standalone/.next/static/chunks/{01q52wg_amm60.js → 0_c_yox08g_44.js} +2 -2
  93. package/.next/standalone/.next/static/chunks/0bghqwo4iloy0.js +1 -0
  94. package/.next/standalone/.next/static/chunks/0fw2h.g66c0h3.js +1 -0
  95. package/.next/standalone/.next/static/chunks/0gu87mlr5ssnt.js +6 -0
  96. package/.next/standalone/.next/static/chunks/{0mbc8hyeqe2c4.js → 0igf3xbisp1lx.js} +1 -1
  97. package/.next/standalone/.next/static/chunks/{175-vim0.ztb2.js → 0jryicwtm9z2g.js} +2 -2
  98. package/.next/standalone/.next/static/chunks/{12simlrcfk3g2.js → 0kzk5-mh1_x53.js} +1 -1
  99. package/.next/standalone/.next/static/chunks/0p5zh2diw90a1.js +1 -0
  100. package/.next/standalone/.next/static/chunks/{0eowehbf5egcz.js → 0ufq8smh~i7wc.js} +1 -1
  101. package/.next/standalone/.next/static/chunks/{0vlk_pv4somht.js → 0vwqucikost_q.js} +1 -1
  102. package/.next/standalone/.next/static/chunks/{0t3euwspxi_zg.js → 0w1f.k~gi-y6..js} +1 -1
  103. package/.next/standalone/.next/static/chunks/{151bdxm9n-pry.js → 0z-jh701rc~j8.js} +1 -1
  104. package/.next/standalone/.next/static/chunks/{turbopack-0o7k.hakttp4k.js → turbopack-0s36is87fc9r2.js} +1 -1
  105. package/.next/standalone/app/actions/install-hooks-web.ts +21 -5
  106. package/.next/standalone/app/policies/hooks-client.tsx +23 -0
  107. package/.next/standalone/assets/logos/claude.svg +1 -0
  108. package/.next/standalone/assets/logos/openai-dark.svg +1 -0
  109. package/.next/standalone/assets/logos/openai-light.svg +1 -0
  110. package/.next/standalone/package.json +2 -2
  111. package/.next/standalone/server.js +1 -1
  112. package/README.md +22 -3
  113. package/bin/failproofai.mjs +89 -9
  114. package/dist/cli.mjs +1123 -281
  115. package/package.json +2 -2
  116. package/src/hooks/builtin-policies.ts +29 -6
  117. package/src/hooks/handler.ts +39 -10
  118. package/src/hooks/hook-activity-store.ts +2 -0
  119. package/src/hooks/install-prompt.ts +165 -0
  120. package/src/hooks/integrations.ts +373 -0
  121. package/src/hooks/manager.ts +96 -171
  122. package/src/hooks/policy-evaluator.ts +28 -1
  123. package/src/hooks/policy-types.ts +3 -1
  124. package/src/hooks/resolve-permission-mode.ts +147 -0
  125. package/src/hooks/types.ts +30 -1
  126. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0_rr1ty._.js +0 -3
  127. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0dj-tbi._.js +0 -3
  128. package/.next/standalone/.next/server/chunks/ssr/_0h21oar._.js +0 -3
  129. package/.next/standalone/.next/server/chunks/ssr/_0i~.gk_._.js +0 -3
  130. package/.next/standalone/.next/server/chunks/ssr/_0q3h.2s._.js +0 -3
  131. package/.next/standalone/.next/server/chunks/ssr/_0x..fj-._.js +0 -3
  132. package/.next/standalone/.next/static/chunks/096~b1zwv69ph.js +0 -1
  133. package/.next/standalone/.next/static/chunks/0bkir2pd22ski.js +0 -1
  134. package/.next/standalone/.next/static/chunks/0ksdlt_1hucdm.js +0 -1
  135. package/.next/standalone/.next/static/chunks/0lua3p__elu_..js +0 -6
  136. package/.next/standalone/.next/static/chunks/0mir9jdxn35~s.css +0 -1
  137. package/.next/standalone/.next/static/chunks/0s_18.dox44e9.js +0 -1
  138. /package/.next/standalone/.next/static/{RYld7TSCDXm2_WhJq20rD → CiVeb_yiVt-O2JYrzGzB7}/_buildManifest.js +0 -0
  139. /package/.next/standalone/.next/static/{RYld7TSCDXm2_WhJq20rD → CiVeb_yiVt-O2JYrzGzB7}/_clientMiddlewareManifest.js +0 -0
  140. /package/.next/standalone/.next/static/{RYld7TSCDXm2_WhJq20rD → CiVeb_yiVt-O2JYrzGzB7}/_ssgManifest.js +0 -0
@@ -1,3 +1,3 @@
1
- module.exports=[28864,e=>{"use strict";let t,r,i,s,a;var n,o=e.i(14747);function l(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}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}};async function h(e,t=!0){try{let t=new Blob([e],{type:"text/plain"}).stream().pipeThrough(new CompressionStream("gzip"));return await new Response(t).blob()}catch(e){return t&&console.error("Failed to gzip compress data",e),null}}let d="0123456789abcdef";class g{constructor(e){this.bytes=e}static ofInner(e){if(16===e.length)return new g(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,r,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||e<0||t<0||r<0||i<0||e>0xffffffffffff||t>4095||r>0x3fffffff||i>0xffffffff)throw RangeError("invalid field value");let s=new Uint8Array(16);return s[0]=e/0x10000000000,s[1]=e/0x100000000,s[2]=e/0x1000000,s[3]=e/65536,s[4]=e/256,s[5]=e,s[6]=112|t>>>8,s[7]=t,s[8]=128|r>>>24,s[9]=r>>>16,s[10]=r>>>8,s[11]=r,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new g(s)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("")}if(t){let e=new Uint8Array(16);for(let r=0;r<16;r+=4){let i=parseInt(t.substring(2*r,2*r+8),16);e[r+0]=i>>>24,e[r+1]=i>>>16,e[r+2]=i>>>8,e[r+3]=i}return new g(e)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=d.charAt(this.bytes[t]>>>4),e+=d.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+=d.charAt(this.bytes[t]>>>4),e+=d.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 g(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(let t=0;t<16;t++){let r=this.bytes[t]-e.bytes[t];if(0!==r)return Math.sign(r)}return 0}}class p{constructor(e){this.timestamp=0,this.counter=0,this.random=e??f()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);return void 0===r&&(this.timestamp=0,r=this.generateOrAbortCore(e,t)),r}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>0x3ffffffffff&&(this.timestamp++,this.resetCounter())}return g.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,g.ofInner(e)}}let f=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),y=()=>(t||(t=new p)).generate();var m=((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.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.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 v={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}`},_=Array.isArray,b=Object.prototype;b.hasOwnProperty;let w=b.toString,E=_||function(e){return"[object Array]"===w.call(e)},F=e=>"[object String]"==w.call(e);function P(e){return null===e||"object"!=typeof e}function x(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function S(e){return"u">typeof Event&&function(e,t){try{return e instanceof t}catch{return!1}}(e,Event)}let k="Android",C="BlackBerry",I="Nintendo",$="PlayStation",O="Xbox",A="Windows",R="(\\d+(\\.\\d+)?)";RegExp("Version/"+R),RegExp(O,"i"),RegExp($+" \\w+","i"),RegExp(I+" \\w+","i"),RegExp(C+"|PlayBook|BB10","i");async function T(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(e=>setTimeout(e,t.retryDelay));try{return await e()}catch(e){if(r=e,!t.retryCheck(e))throw e}}throw r}function L(){return new Date().toISOString()}function M(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}RegExp("rv:"+R),RegExp("Edge?\\/"+R),RegExp("(Chrome|CrMo)\\/"+R),RegExp("CriOS\\/"+R),RegExp("(UCBrowser|UCWEB)\\/"+R),RegExp("(Opera|OPR)\\/"+R),RegExp("Firefox\\/"+R),RegExp("FxiOS\\/"+R),RegExp("Konqueror[:/]?"+R,"i"),RegExp(C+" "+R),RegExp("android\\s"+R,"i"),RegExp("SamsungBrowser\\/"+R),RegExp("(rv:|MSIE )"+R),RegExp("rv:"+R),RegExp(O+"; "+O+" (.*?)[);]","i"),RegExp(I,"i"),RegExp($,"i"),RegExp(A,"i"),RegExp("("+k+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+k+")","i");let j=e=>e instanceof Error;function D(e){return Promise.all(e.map(e=>(e??Promise.resolve()).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}class U{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,t){for(let r of this.events[e]||[])r(t);for(let r of this.events["*"]||[])r(e,t)}}class B{add(e){let t=y().toString();return this.promiseByIds[t]=e,e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds),t=e.length;for(;t>0;)await Promise.all(e),t=(e=Object.values(this.promiseByIds)).length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}}let q=(e,t,r)=>{function i(s,...a){t(()=>{(0,r[s])(e,...a)})}return{info:(...e)=>{i("log",...e)},warn:(...e)=>{i("warn",...e)},error:(...e)=>{i("error",...e)},critical:(...t)=>{r.error(e,...t)},createLogger:i=>q(`${e} ${i}`,t,r)}};class H 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 N extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}async function G(e){if(e instanceof H){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 z(e){return"object"==typeof e&&(e instanceof H||e instanceof N)}function W(e){return"object"==typeof e&&e instanceof H&&413===e.status}class K{constructor(e,t={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new B,this._events=new U,this._isInitialized=!1,function(e,t){if(!e||"string"!=typeof e||0===e.trim().length)throw Error(t)}(e,"You must pass your PostHog project's api key."),this.apiKey=e,this.host=function(e){return e?.replace(/\/+$/,"")}(t.host||"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:z},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=t.disabled??!1,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this._logger=function(e,t=e=>e()){return q(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)),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)||(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(m.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(m.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(m.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){return{distinct_id:e.distinct_id,event:e.event,properties:{...e.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,r){this.wrap(()=>{let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",i,r)})}async identifyStatelessImmediate(e,t,r){let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",i,r)}captureStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",s,i)})}async captureStatelessImmediate(e,t,r,i){let s=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",s,i)}aliasStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",s,i)})}async aliasStatelessImmediate(e,t,r,i){let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",s,i)}groupIdentifyStateless(e,t,r,i,s,a){this.wrap(()=>{let n=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...a||{}}});this.enqueue("capture",n,i)})}async getRemoteConfig(){await this._initPromise;let e=this.host;"https://us.i.posthog.com"===e?e="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===e&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.apiKey}/config`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,r,{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={},r={},i={},s={},a=!1){await this._initPromise;let n=`${this.host}/flags/?v=2${a?"&config=true":""}`,o={token:this.apiKey,distinct_id:e,groups:t,person_properties:r,group_properties:i,...s};r.$device_id&&(o.$device_id=r.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(o.evaluation_contexts=this.evaluationContexts);let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(o)};return this._logger.info("Flags URL",n),this.fetchWithRetry(n,l,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(e=>e.json()).then(e=>({success:!0,response:(e=>{if("flags"in e){let t,r=Object.fromEntries(Object.entries(e.flags??{}).map(([e,t])=>[e,u(t)]).filter(([,e])=>void 0!==e)),i=Object.fromEntries(Object.keys(t=e.flags??{}).filter(e=>{let r=t[e];return r.enabled&&r.metadata&&void 0!==r.metadata.payload}).map(e=>{let r=t[e].metadata?.payload;return[e,r?c(r):void 0]}));return{...e,featureFlags:r,featureFlagPayloads:i}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([e,t])=>[e,c(t)])),i=Object.fromEntries(Object.entries(t).map(([e,t])=>{var i,s;return[e,{key:e,enabled:"string"==typeof(i=t)||i,variant:"string"==typeof i?i:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:(s=r[e])?JSON.stringify(s):void 0,description:void 0}}]}));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}})(e)})).catch(e=>(this._events.emit("error",e),{success:!1,error:this.categorizeRequestError(e)}))}categorizeRequestError(e){if(e instanceof H)return{type:"api_error",statusCode:e.status};if(e instanceof N){let t=e.error;return t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,r={},i={},s={},a){await this._initPromise;let n=await this.getFeatureFlagDetailStateless(e,t,r,i,s,a);if(void 0===n)return{response:void 0,requestId:void 0};let o=u(n.response);return void 0===o&&(o=!1),{response:o,requestId:n.requestId}}async getFeatureFlagDetailStateless(e,t,r={},i={},s={},a){await this._initPromise;let n=await this.getFeatureFlagDetailsStateless(t,r,i,s,a,[e]);if(void 0!==n)return{response:n.flags[e],requestId:n.requestId,evaluatedAt:n.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,r={},i={},s={},a){await this._initPromise;let n=await this.getFeatureFlagPayloadsStateless(t,r,i,s,a,[e]);if(!n)return;let o=n[e];return void 0===o?null:o}async getFeatureFlagPayloadsStateless(e,t={},r={},i={},s,a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,a)).payloads}async getFeatureFlagsStateless(e,t={},r={},i={},s,a){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,a)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},i={},s,a){await this._initPromise;let n=await this.getFeatureFlagDetailsStateless(e,t,r,i,s,a);return n?{flags:n.featureFlags,payloads:n.featureFlagPayloads,requestId:n.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},r={},i={},s,a){await this._initPromise;let n={};(s??this.disableGeoip)&&(n.geoip_disable=!0),a&&(n.flag_keys_to_evaluate=a);let o=await this.getFlags(e,t,r,i,n);if(!o.success)return;let l=o.response;return(l.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),l.quotaLimited?.includes("feature_flags"))?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},r=await this.fetchWithRetry(e,t).then(e=>{if(200!==e.status||!e.json){let t=`Surveys API could not be loaded: ${e.status}`,r=Error(t);this._logger.error(r),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)}),i=r?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(m.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(m.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(m.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}enqueue(e,t,r){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(e,t,r);if(null===(i=this.processBeforeEnqueue(i)))return;let s=this.getPersistedProperty(m.Queue)||[];s.length>=this.maxQueueSize&&(s.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),s.push({message:i}),this.setPersistedProperty(m.Queue,s),this._events.emit(e,i),s.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=M(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,r){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 i=this.prepareMessage(e,t,r);if(null===(i=this.processBeforeEnqueue(i)))return;let s={api_key:this.apiKey,batch:[i],sent_at:L()};this.historicalMigration&&(s.historical_migration=!0);let a=JSON.stringify(s),n=`${this.host}/batch/`,o=this.disableCompression?null:await h(a,this.isDebug),l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==o&&{"Content-Encoding":"gzip"}},body:o||a};try{await this.fetchWithRetry(n,l)}catch(e){this._events.emit("error",e)}}prepareMessage(e,t,r){let i={...t,type:e,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:r?.timestamp?r?.timestamp:L(),uuid:r?.uuid?r.uuid:y().toString()};return(r?.disableGeoip??this.disableGeoip)&&(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.flush().catch(async e=>{await G(e)})}async flush(){let e=D([this.flushPromise]).then(()=>this._flush());return this.flushPromise=e,this.addPendingPromise(e),D([e]).then(()=>{this.flushPromise===e&&(this.flushPromise=null)}),e}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&""!==e&&(t["User-Agent"]=e),t}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getPersistedProperty(m.Queue)||[];if(!e.length)return;let t=[],r=e.length;for(;e.length>0&&t.length<r;){let r=e.slice(0,this.maxBatchSize),i=r.map(e=>e.message),s=async()=>{let t=(this.getPersistedProperty(m.Queue)||[]).slice(r.length);this.setPersistedProperty(m.Queue,t),e=t,await this.flushStorage()},a={api_key:this.apiKey,batch:i,sent_at:L()};this.historicalMigration&&(a.historical_migration=!0);let n=JSON.stringify(a),o=`${this.host}/batch/`,l=this.disableCompression?null:await h(n,this.isDebug),u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==l&&{"Content-Encoding":"gzip"}},body:l||n},c={retryCheck:e=>!W(e)&&z(e)};try{await this.fetchWithRetry(o,u,c)}catch(e){if(W(e)&&i.length>1){this.maxBatchSize=Math.max(1,Math.floor(i.length/2)),this._logger.warn(`Received 413 when sending batch of size ${i.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw e instanceof N||await s(),this._events.emit("error",e),e}await s(),t.push(...i)}this._events.emit("flush",t)}async fetchWithRetry(e,t,r,i){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 T(async()=>{let r=new AbortController,s=M(()=>r.abort(),i??this.requestTimeout),n=null;try{n=await this.fetch(e,{signal:r.signal,...t})}catch(e){throw new N(e)}finally{clearTimeout(s)}if("no-cors"!==t.mode&&(n.status<200||n.status>=400))throw new H(n,a);return n},{...this._retryOptions,...r})}async _shutdown(e=3e4){let t;await this._initPromise;let r=!1;this.clearFlushTimer();let i=async()=>{try{for(await this.promiseQueue.join();;){let e=this.getPersistedProperty(m.Queue)||[];if(0===e.length||(await this.flush(),r))break}}catch(e){if(!z(e))throw e;await G(e)}};try{return await Promise.race([new Promise((i,s)=>{t=M(()=>{this._logger.error("Timed out while shutting down PostHog"),r=!0,s("Timeout while shutting down PostHog. Some events may not have been sent.")},e)}),i()])}finally{clearTimeout(t)}}async shutdown(e=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}class V{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){let r=t&&t.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(r,t,0).apply(e),s=this.buildParsingContext(t),a=this.parseStacktrace(i,s);return{$exception_list:this.convertToExceptionList(a,r),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&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 r,i;return null!=e.cause&&(r=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack&&(i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),{...e,cause:r,stack:i}}applyChunkIds(e,t){return e.map(e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e))}applyCoercers(e,t){for(let r of this.coercers)if(r.match(e))return r.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let e of this.modifiers)t=await e(t);return t}convertToExceptionList(e,t){let r={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};e.stack&&(r.stacktrace={type:"raw",frames:e.stack});let i=[r];return null!=e.cause&&i.push(...this.convertToExceptionList(e.cause,{...t,handled:!0})),i}buildParsingContext(e){return{chunkIdMap:function(e){let t=globalThis._posthogChunkIds;if(!t)return;let a=Object.keys(t);return s&&a.length===i?s:(i=a.length,s=a.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,r=0){let i=(r,i)=>{if(i<=4){let s=this.buildCoercingContext(e,t,i);return this.applyCoercers(r,s)}};return{...t,syntheticException:0==r?t.syntheticException:void 0,mechanism:e,apply:e=>i(e,r),next:e=>i(e,r+1)}}}function Q(e,t,r,i,s){let a={platform:e,filename:t,function:"<anonymous>"===r?"?":r,in_app:!0};return void 0!==i&&(a.lineno=i),void 0!==s&&(a.colno=s),a}e.s(["ErrorPropertiesBuilder",0,V],80446);let J=(e,t)=>{let r=-1!==e.indexOf("safari-extension"),i=-1!==e.indexOf("safari-web-extension");return r||i?[-1!==e.indexOf("@")?e.split("@")[0]:"?",r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},Y=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Z=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,X=/\((\S*)(?::(\d+))(?::(\d+))\)/,ee=(e,t)=>{let r=Y.exec(e);if(r){let[,e,i,s]=r;return Q(t,e,"?",+i,+s)}let i=Z.exec(e);if(i){if(i[2]&&0===i[2].indexOf("eval")){let e=X.exec(i[2]);e&&(i[2]=e[1],i[3]=e[2],i[4]=e[3])}let[e,r]=J(i[1]||"?",i[2]);return Q(t,r,e,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},et=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,er=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ei=(e,t)=>{let r=et.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let e=er.exec(r[3]);e&&(r[1]=r[1]||"eval",r[3]=e[1],r[4]=e[2],r[5]="")}let e=r[3],i=r[1]||"?";return[i,e]=J(i,e),Q(t,e,i,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}},es=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ea=(e,t)=>{let r=es.exec(e);return r?Q(t,r[2],r[1]||"?",+r[3],r[4]?+r[4]:void 0):void 0},en=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,eo=(e,t)=>{let r=en.exec(e);return r?Q(t,r[2],r[3]||"?",+r[1]):void 0},el=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,eu=(e,t)=>{let r=el.exec(e);return r?Q(t,r[5],r[3]||r[4]||"?",+r[1],+r[2]):void 0},ec=/^\s*[-]{4,}$/,eh=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,ed=(e,t)=>{let r=e.match(eh);if(r){let e,i,s,a,n;if(r[1]){let t=(s=r[1]).lastIndexOf(".");if("."===s[t-1]&&t--,t>0){e=s.slice(0,t),i=s.slice(t+1);let r=e.indexOf(".Module");r>0&&(s=s.slice(r+1),e=e.slice(0,r))}a=void 0}i&&(a=e,n=i),"<anonymous>"===i&&(n=void 0,s=void 0),void 0===s&&(n=n||"?",s=a?`${a}.${n}`:n);let o=r[2]?.startsWith("file://")?r[2].slice(7):r[2],l="native"===r[5];return o?.match(/\/[A-Z]:/)&&(o=o.slice(1)),o||!r[5]||l||(o=r[5]),{filename:o?decodeURI(o):void 0,module:void 0,function:s,lineno:eg(r[3]),colno:eg(r[4]),in_app:function(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==e&&!e.includes("node_modules/")}(o||"",l),platform:t}}if(e.match(ec))return{filename:e,platform:t}};function eg(e){return parseInt(e||"",10)||void 0}let ep=/\(error: (.*)\)/;function ef(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,50).map(e=>{var r;return{...e,filename:e.filename||((r=t)[r.length-1]||{}).filename,function:e.function||"?"}})}function ey(){return em("web:javascript",ee,ei)}function em(e,...t){return(r,i=0)=>{let s=[],a=r.split("\n");for(let r=i;r<a.length;r++){let i=a[r];if(i.length>1024)continue;let n=ep.test(i)?i.replace(ep,"$1"):i;if(!n.match(/\S*Error: /)){for(let r of t){let t=r(n,e);if(t){s.push(t);break}}if(s.length>=50)break}}return ef(s)}}e.s(["createDefaultStackParser",0,ey,"createStackParser",0,em,"reverseAndStripFrames",0,ef],34246);class ev{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let r=F(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return x(e,"DOMException")}isDOMError(e){return x(e,"DOMError")}}e.s(["DOMExceptionCoercer",0,ev],29569);class e_{match(e){return e instanceof 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 r=e.message;return r.error&&"string"==typeof r.error.message?String(r.error.message):String(r)}getStack(e){return e.stacktrace||e.stack||void 0}}e.s(["ErrorCoercer",0,e_],11475);class eb{match(e){return x(e,"ErrorEvent")&&void 0!=e.error}coerce(e,t){let r=t.apply(e.error);return r||{type:"ErrorEvent",value:e.message,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["ErrorEventCoercer",0,eb],43179);let ew=["fatal","error","warning","log","info","debug"];function eE(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let e=r.length;e>0;e--){let i=r.slice(0,e).join(", ");if(!(i.length>t)){if(e===r.length)return i;return i.length<=t?i:`${i.slice(0,t)}...`}}return""}class eF{match(e){return"object"==typeof e&&null!==e}coerce(e,t){let r=this.getErrorPropertyFromObject(e);return r?t.apply(r):{type:this.getType(e),value:this.getValue(e),stack:t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return S(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),r=eE(e);return`${t&&"Object"!==t?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return F(e)&&!(F(e)&&0===e.trim().length)&&ew.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(j(r))return r}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){return}}}e.s(["ObjectCoercer",0,eF],6881);class eP{match(e){return S(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${eE(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["EventCoercer",0,eP],80322);class ex{match(e){return P(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,ex],80049);class eS{match(e){return x(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!S(e))return!1;try{let t=e.detail;return null!=t&&"object"==typeof t&&"reason"in t}catch{return!1}}coerce(e,t){let r=this.getUnhandledRejectionReason(e);return P(r)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(r)}`,stack:t.syntheticException?.stack,synthetic:!0}:t.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&null!=e.detail&&"object"==typeof e.detail&&"reason"in e.detail)return e.detail.reason}catch{}return e}}e.s(["PromiseRejectionEventCoercer",0,eS],98689),e.s([],99573),e.s([],47114),e.i(47114),e.i(80446),e.i(34246),e.s(["chromeStackLineParser",0,ee,"createDefaultStackParser",0,ey,"createStackParser",0,em,"geckoStackLineParser",0,ei,"nodeStackLineParser",0,ed,"opera10StackLineParser",0,eo,"opera11StackLineParser",0,eu,"reverseAndStripFrames",0,ef,"winjsStackLineParser",0,ea],70736),e.i(70736),e.i(99573),e.i(29569),e.i(11475),e.i(43179);let ek=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class eC{match(e){return"string"==typeof e}coerce(e,t){let[r,i]=this.getInfos(e);return{type:r??"Error",value:i??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",r=e,i=e.match(ek);return i&&(t=i[1],r=i[2]),[t,r]}}e.s(["StringCoercer",0,eC],45098),e.i(45098),e.i(6881),e.i(80322),e.i(80049),e.i(98689),e.s(["DOMExceptionCoercer",0,ev,"ErrorCoercer",0,e_,"ErrorEventCoercer",0,eb,"EventCoercer",0,eP,"ObjectCoercer",0,eF,"PrimitiveCoercer",0,ex,"PromiseRejectionEventCoercer",0,eS,"StringCoercer",0,eC],21854),e.i(21854);class eI{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(void 0!==t)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}}e.s(["ReduceableCache",0,eI],46986),e.i(46986),e.s(["DOMExceptionCoercer",0,ev,"ErrorCoercer",0,e_,"ErrorEventCoercer",0,eb,"ErrorPropertiesBuilder",0,V,"EventCoercer",0,eP,"ObjectCoercer",0,eF,"PrimitiveCoercer",0,ex,"PromiseRejectionEventCoercer",0,eS,"ReduceableCache",0,eI,"StringCoercer",0,eC,"chromeStackLineParser",0,ee,"createDefaultStackParser",0,ey,"createStackParser",0,em,"geckoStackLineParser",0,ei,"nodeStackLineParser",0,ed,"opera10StackLineParser",0,eo,"opera11StackLineParser",0,eu,"reverseAndStripFrames",0,ef,"winjsStackLineParser",0,ea],96117);var e$=e.i(96117),eO=e$,eA=e.i(2157),eR=e.i(1457);let eT=new eO.ReduceableCache(25),eL=new eO.ReduceableCache(20);async function eM(e){let t={};for(let s=e.length-1;s>=0;s--){var r,i;let a=e[s],n=a?.filename;!(!a||"string"!=typeof n||"number"!=typeof a.lineno||(r=n).startsWith("node:")||r.endsWith(".min.js")||r.endsWith(".min.cjs")||r.endsWith(".min.mjs")||r.startsWith("data:")||void 0!==(i=a).lineno&&i.lineno>1e4||void 0!==i.colno&&i.colno>1e3)&&(t[n]||(t[n]=[]),t[n].push(a.lineno))}let s=Object.keys(t);if(0==s.length)return e;let a=[];for(let e of s){if(eL.get(e))continue;let r=t[e];if(!r)continue;r.sort((e,t)=>e-t);let i=function(e){if(!e.length)return[];let t=0,r=e[0];if("number"!=typeof r)return[];let i=eD(r),s=[];for(;;){if(t===e.length-1){s.push(i);break}let r=e[t+1];if("number"!=typeof r)break;r<=i[1]?i[1]=r+7:(s.push(i),i=eD(r)),t++}return s}(r);if(i.every(t=>(function(e,t){let r=eT.get(e);if(void 0===r)return!1;for(let e=t[0];e<=t[1];e++)if(void 0===r[e])return!1;return!0})(e,t)))continue;let s=function(e,t,r){let i=e.get(t);return void 0===i?(e.set(t,r),r):i}(eT,e,{});a.push(function(e,t,r){return new Promise(i=>{let s=(0,eA.createReadStream)(e),a=(0,eR.createInterface)({input:s});function n(){s.destroy(),i()}let o=0,l=0,u=t[0];if(void 0===u)return void n();let c=u[0],h=u[1];function d(){eL.set(e,1),a.close(),a.removeAllListeners(),n()}s.on("error",d),a.on("error",d),a.on("close",n),a.on("line",e=>{if(!(++o<c)&&(r[o]=function(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let s=Math.max(t-60,0);s<5&&(s=0);let a=Math.min(s+140,i);return a>i-5&&(a=i),a===i&&(s=Math.max(a-140,0)),r=r.slice(s,a),s>0&&(r=`...${r}`),a<i&&(r+="..."),r}(e,0),o>=h)){if(l===t.length-1){a.close(),a.removeAllListeners();return}let e=t[++l];if(void 0===e){a.close(),a.removeAllListeners();return}c=e[0],h=e[1]}})})}(e,i,s))}return await Promise.all(a).catch(()=>{}),e&&e.length>0&&function(e,t){for(let r of e)if(r.filename&&void 0===r.context_line&&"number"==typeof r.lineno){let e=t.get(r.filename);if(void 0===e)continue;!function(e,t,r){if(void 0===t.lineno||void 0===r)return;t.pre_context=[];for(let i=eU(e);i<e;i++){let e=r[i];if(void 0===e)return void ej(t);t.pre_context.push(e)}if(void 0===r[e])return ej(t);t.context_line=r[e];let i=function(e){return e+7}(e);t.post_context=[];for(let s=e+1;s<=i;s++){let e=r[s];if(void 0===e)break;t.post_context.push(e)}}(r.lineno,r,e)}}(e,eT),eT.reduce(),e}function ej(e){delete e.pre_context,delete e.context_line,delete e.post_context}function eD(e){return[eU(e),e+7]}function eU(e){return Math.max(1,e-7)}function eB(e,t,r,i,s){if(t>r&&(i.warn("min cannot be greater than max."),t=r),"[object Number]"==w.call(e)&&e==e)if(e>r)return i.warn(" cannot be greater than max: "+r+". Using max value instead."),r;else return e<t?(i.warn(" cannot be less than min: "+t+". Using min value instead."),t):e;return i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+s),eB(s||r,t,r,i)}class eq{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=eB(e.bucketSize,0,100,e._logger),this._refillRate=eB(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=eB(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){let r=Math.floor((t-e.lastAccess)/this._refillInterval);if(r>0){let t=r*this._refillRate;e.tokens=Math.min(e.tokens+t,this._bucketSize),e.lastAccess=e.lastAccess+r*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),r=String(e),i=this._buckets[r];return i?this._applyRefill(i,t):(i={tokens:this._bucketSize,lastAccess:t},this._buckets[r]=i),0===i.tokens||(i.tokens--,0===i.tokens&&this._onBucketRateLimited?.(e),0===i.tokens)}stop(){this._buckets={}}}class eH{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new eq({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return e===Object(e)&&!E(e)&&"__posthog_previously_captured_error"in e&&!0===e.__posthog_previously_captured_error}static async buildEventMessage(e,t,r,i){let s={...i},a=this.errorPropertiesBuilder.buildFromUnknown(e,t);return a.$exception_list=await this.errorPropertiesBuilder.modifyFrames(a.$exception_list),{event:"$exception",distinctId:r,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled()){var t,r,i;let s;t=this.onException.bind(this),r=this.onFatalError.bind(this),globalThis.process?.on("uncaughtException",(s=!1,Object.assign(i=>{let a=e.g.process.listeners("uncaughtException").filter(e=>"domainUncaughtExceptionClear"!==e.name&&!0!==e._posthogErrorHandler).length;t(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),s||0!==a||(s=!0,r(i))},{_posthogErrorHandler:!0}))),i=this.onException.bind(this),globalThis.process?.on("unhandledRejection",e=>i(e,{mechanism:{type:"onunhandledrejection",handled:!1}}))}}onException(e,t){this.client.addPendingPromise((async()=>{if(!eH.isPreviouslyCapturedError(e)){let r=await eH.buildEventMessage(e,t),i=r.properties,s=i?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(s)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:s}):this.client.capture(r)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(2e3),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}let eN=["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"],eG=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return eN.concat(t).some(e=>{let t=e.toLowerCase();return -1!==r.indexOf(t)})},ez={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function eW(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("")}e.s(["FeatureFlagError",0,ez],58325);let eK=["is_not"];class eV extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,eV.prototype)}}class eQ extends Error{constructor(e){super(e),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,eQ.prototype)}}class eJ extends Error{constructor(e){super(e),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,eJ.prototype)}}class eY{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:i,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=i,this.projectApiKey=r,this.host=s,this.poller=void 0,this.fetch=n.fetch||fetch,this.onError=n.onError,this.customHeaders=a,this.onLoad=n.onLoad,this.cacheProvider=n.cacheProvider,this.strictLocalEvaluation=n.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}createEvaluationContext(e,t={},r={},i={},s={}){return{distinctId:e,groups:t,personProperties:r,groupProperties:i,evaluationCache:s}}async getFeatureFlag(e,t,r={},i={},s={}){let a,n;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return a;if(void 0!==(n=this.featureFlagsByKey[e])){let o=this.createEvaluationContext(t,r,i,s);try{a=(await this.computeFlagAndPayloadLocally(n,o)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${a}`))}catch(t){t instanceof eJ||t instanceof eQ?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e}: ${t}`))}}return a}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let r={},i={},s=0==this.featureFlags.length,a=t?t.map(e=>this.featureFlagsByKey[e]).filter(Boolean):this.featureFlags,n={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(a.map(async e=>{try{let{value:t,payload:s}=await this.computeFlagAndPayloadLocally(e,n);r[e.key]=t,s&&(i[e.key]=s)}catch(t){t instanceof eJ||t instanceof eQ?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e.key}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e.key}: ${t}`)),s=!0}})),{response:r,payloads:i,fallbackToFlags:s}}async computeFlagAndPayloadLocally(e,t,r={}){let i,{matchValue:s,skipLoadCheck:a=!1}=r;if(a||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};i=void 0!==s?s:await this.computeFlagValueLocally(e,t);let n=this.getFeatureFlagPayload(e.key,i);return{value:i,payload:n}}async computeFlagValueLocally(e,t){let{distinctId:r,groups:i,personProperties:s,groupProperties:a}=t;if(e.ensure_experience_continuity)throw new eQ("Flag has experience continuity enabled");if(!e.active)return!1;let n=(e.filters||{}).aggregation_group_type_index;if(void 0!=n){let r=this.groupTypeMapping[String(n)];if(!r)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${n} for feature flag ${e.key}`)),new eQ("Flag has unknown group type index");if(!(r in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;"device_id"===e.bucketing_identifier&&(s?.$device_id===void 0||s?.$device_id===null||s?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let o=a[r];return await this.matchFeatureFlagProperties(e,i[r],o,t)}{let i=this.getBucketingValueForFlag(e,r,s);if(void 0===i)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new eQ(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,i,s,t)}}getBucketingValueForFlag(e,t,r){if(e.filters?.aggregation_group_type_index!=void 0)return t;if("device_id"===e.bucketing_identifier){let e=r?.$device_id;if(null==e||""===e)return;return e}return t}getFeatureFlagPayload(e,t){let r=null;if(!1!==t&&null!=t&&("boolean"==typeof t?r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null:"string"==typeof t&&(r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null),null!=r)){if("object"==typeof r)return r;if("string"==typeof r)try{return JSON.parse(r)}catch{}return r}return null}async evaluateFlagDependency(e,t,r){let{evaluationCache:i}=r,s=e.key;if(!this.featureFlagsByKey)throw new eQ("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new eQ(`Flag dependency property for '${s}' is missing required 'dependency_chain' field`);let a=e.dependency_chain;if(!Array.isArray(a))throw new eQ(`Flag dependency property for '${s}' has an invalid 'dependency_chain' (expected array, got ${typeof a})`);if(0===a.length)throw new eQ(`Circular dependency detected for flag '${s}' (empty dependency chain)`);for(let e of a){if(!(e in i)){let t=this.featureFlagsByKey[e];if(t)if(t.active)try{let s=await this.computeFlagValueLocally(t,r);i[e]=s}catch(t){throw new eQ(`Error evaluating flag dependency '${e}' for flag '${s}': ${t}`)}else i[e]=!1;else throw new eQ(`Missing flag dependency '${e}' for flag '${s}'`)}if(null==i[e])throw new eQ(`Dependency '${e}' could not be evaluated`)}let n=i[s];return this.flagEvaluatesToExpectedValue(e.value,n)}flagEvaluatesToExpectedValue(e,t){return"boolean"==typeof e?e===t||"string"==typeof t&&""!==t&&!0===e:"string"==typeof e&&t===e}async matchFeatureFlagProperties(e,t,r,i){let s,a=e.filters||{},n=a.groups||[],o=!1;for(let l of n)try{if(await this.isConditionMatch(e,t,l,r,i)){let r=l.variant,i=a.multivariate?.variants||[];s=r&&i.some(e=>e.key===r)?r:await this.getMatchingVariant(e,t)||!0;break}}catch(e){if(e instanceof eJ)throw e;if(e instanceof eQ)o=!0;else throw e}if(void 0!==s)return s;if(o)throw new eQ("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,r,i,s){let a=r.rollout_percentage,n=e=>{this.logMsgIfDebug(()=>console.warn(e))};if((r.properties||[]).length>0){for(let e of r.properties){let t=e.type;if(!("cohort"===t?function e(t,r,i,s=!1){let a=String(t.value);if(!(a in i))throw new eJ(`cohort ${a} not found in local cohorts - likely a static cohort that requires server evaluation`);return function t(r,i,s,a=!1){if(!r)return!0;let n=r.type,o=r.values;if(!o||0===o.length)return!0;let l=!1;if("values"in o[0]){for(let e of o)try{let r=t(e,i,s,a);if("AND"===n){if(!r)return!1}else if(r)return!0}catch(t){if(t instanceof eJ)throw t;if(t instanceof eQ)a&&console.debug(`Failed to compute property ${e} locally: ${t}`),l=!0;else throw t}if(l)throw new eQ("Can't match cohort without a given cohort property value");return"AND"===n}for(let t of o)try{let r;if("cohort"===t.type)r=e(t,i,s,a);else if("flag"===t.type){a&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${t.key||"unknown"}'`);continue}else r=eX(t,i);let o=t.negation||!1;if("AND"===n){if(!r&&!o||r&&o)return!1}else if(r&&!o||!r&&o)return!0}catch(e){if(e instanceof eJ)throw e;if(e instanceof eQ)a&&console.debug(`Failed to compute property ${t} locally: ${e}`),l=!0;else throw e}if(l)throw new eQ("can't match cohort without a given cohort property value");return"AND"===n}(i[a],r,i,s)}(e,i,this.cohorts,this.debugMode):"flag"===t?await this.evaluateFlagDependency(e,i,s):eX(e,i,n)))return!1}if(void 0==a)return!0}return!(void 0!=a&&await eZ(e.key,t)>a/100)}async getMatchingVariant(e,t){let r=await eZ(e.key,t,"variant"),i=this.variantLookupTable(e).find(e=>r>=e.valueMin&&r<e.valueMax);if(i)return i.key}variantLookupTable(e){let t=[],r=0,i=0,s=e.filters||{};return(s.multivariate?.variants||[]).forEach(e=>{i=r+e.rollout_percentage/100,t.push({valueMin:r,valueMax:i,key:e.key}),r=i}),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}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 eV(`Your project key or personal API 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={};return;case 403:throw this.beginBackoff(),new eV(`Your personal API 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 personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new eV(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let r=await t.json()??{};if(!("flags"in r))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let i={flags:r.flags??[],groupTypeMapping:r.group_type_mapping||{},cohorts:r.cohorts||{}};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(e){this.onError?.(Error(`Failed to store in cache: ${e}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(e){e instanceof eV&&this.onError?.(e)}}getPersonalApiKeyRequestOptions(e="GET",t){let r={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(r["If-None-Match"]=t),{method:e,headers:r}}_requestFeatureFlagDefinitions(){let e=`${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),r=null;if(this.timeout&&"number"==typeof this.timeout){let e=new AbortController;r=M(()=>{e.abort()},this.timeout),t.signal=e.signal}try{return(0,this.fetch)(e,t)}finally{clearTimeout(r)}}async stopPoller(e=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await Promise.race([t,new Promise((t,r)=>setTimeout(()=>r(Error(`Cache shutdown timeout after ${e}ms`)),e))])}catch(e){this.onError?.(Error(`Error during cache shutdown: ${e}`))}}}async function eZ(e,t,r=""){return parseInt((await eW(`${e}.${t}${r}`)).slice(0,15),16)/0x1000000000000000}function eX(e,t,r){let i=e.key,s=e.value,a=e.operator||"exact";if(i in t){if("is_not_set"===a)throw new eQ("Operator is_not_set is not supported")}else throw new eQ(`Property ${i} not found in propertyValues`);let n=t[i];if(null==n&&!eK.includes(a))return r&&r(`Property ${i} 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,r){if("gt"===r)return e>t;if("gte"===r)return e>=t;if("lt"===r)return e<t;if("lte"===r)return e<=t;throw Error(`Invalid operator: ${r}`)}switch(a){case"exact":return o(s,n);case"is_not":return!o(s,n);case"is_set":return i 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 e0(String(s))&&null!==String(n).match(String(s));case"not_regex":return e0(String(s))&&null===String(n).match(String(s));case"gt":case"gte":case"lt":case"lte":{let e="number"==typeof s?s:null;if("string"==typeof s)try{e=parseFloat(s)}catch(e){}if(null==e||null==n)return l(String(n),String(s),a);if("string"==typeof n)return l(n,String(s),a);return l(n,e,a)}case"is_date_after":case"is_date_before":{if("boolean"==typeof s)throw new eQ("Date operations cannot be performed on boolean values");let e=function(e){let t=e.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),r=new Date(new Date().toISOString());if(!t)return null;{if(!t.groups)return null;let e=parseInt(t.groups.number);if(e>=1e4)return null;let i=t.groups.interval;if("h"==i)r.setUTCHours(r.getUTCHours()-e);else if("d"==i)r.setUTCDate(r.getUTCDate()-e);else if("w"==i)r.setUTCDate(r.getUTCDate()-7*e);else if("m"==i)r.setUTCMonth(r.getUTCMonth()-e);else{if("y"!=i)return null;r.setUTCFullYear(r.getUTCFullYear()-e)}return r}}(String(s));if(null==e&&(e=e2(s)),null==e)throw new eQ(`Invalid date: ${s}`);let t=e2(n);if(["is_date_before"].includes(a))return t<e;return t>e}case"semver_eq":return 0===e4(e1(String(n)),e1(String(s)));case"semver_neq":return 0!==e4(e1(String(n)),e1(String(s)));case"semver_gt":return e4(e1(String(n)),e1(String(s)))>0;case"semver_gte":return e4(e1(String(n)),e1(String(s)))>=0;case"semver_lt":return 0>e4(e1(String(n)),e1(String(s)));case"semver_lte":return 0>=e4(e1(String(n)),e1(String(s)));case"semver_tilde":{let e,t=e1(String(n)),{lower:r,upper:i}={lower:[(e=e1(String(s)))[0],e[1],e[2]],upper:[e[0],e[1]+1,0]};return e4(t,r)>=0&&0>e4(t,i)}case"semver_caret":{let e=e1(String(n)),{lower:t,upper:r}=function(e){let[t,r,i]=e1(e);return{lower:[t,r,i],upper:t>0?[t+1,0,0]:r>0?[0,r+1,0]:[0,0,i+1]}}(String(s));return e4(e,t)>=0&&0>e4(e,r)}case"semver_wildcard":{let e=e1(String(n)),{lower:t,upper:r}=function(e){let t,r,i=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!i)throw new eQ(`Invalid wildcard semver: ${e}`);let s=i.split("."),a=parseInt(s[0],10);if(isNaN(a))throw new eQ(`Invalid wildcard semver: ${e}`);if(1===s.length)t=[a,0,0],r=[a+1,0,0];else{let i=parseInt(s[1],10);if(isNaN(i))throw new eQ(`Invalid wildcard semver: ${e}`);t=[a,i,0],r=[a,i+1,0]}return{lower:t,upper:r}}(String(s));return e4(e,t)>=0&&0>e4(e,r)}default:throw new eQ(`Unknown operator: ${a}`)}}function e0(e){try{return new RegExp(e),!0}catch(e){return!1}}function e1(e){let t=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!t||t.startsWith("."))throw new eQ(`Invalid semver: ${e}`);let r=t.split("."),i=t=>{if(void 0===t||""===t)return 0;if(!/^\d+$/.test(t))throw new eQ(`Invalid semver: ${e}`);return parseInt(t,10)};return[i(r[0]),i(r[1]),i(r[2])]}function e4(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return -1;if(e[r]>t[r])return 1}return 0}function e2(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 eQ(`${e} is in an invalid date format`)}throw new eQ(`The date provided ${e} must be a string, number, or date object`)}class e3{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=null!==t?t:void 0}constructor(){this._memoryStorage={}}}class e5 extends K{constructor(e,t={}){if(super(e,t),this._memoryStorage=new e3,this.options=t,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof t.featureFlagsPollingInterval?Math.max(t.featureFlagsPollingInterval,100):3e4,"number"==typeof t.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(t.waitUntilDebounceMs,0)),"number"==typeof t.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(t.waitUntilMaxWaitMs,0)),t.personalApiKey){if(t.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!==t.enableLocalEvaluation&&(this.featureFlagsPoller=new eY({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:t.personalApiKey,projectApiKey:e,timeout:t.requestTimeout??1e4,host:this.host,fetch:t.fetch,onError:e=>{this._events.emit("error",e)},onLoad:e=>{this._events.emit("localEvaluationFlagsLoaded",e)},customHeaders:this.getCustomHeaders(),cacheProvider:t.flagDefinitionCacheProvider,strictLocalEvaluation:t.strictLocalEvaluation}))}this.errorTracking=new eH(this,t,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=t.maxCacheSize||5e4}enqueue(e,t,r){super.enqueue(e,t,r),this.scheduleDebouncedFlush()}async flush(){let e=super.flush(),t=this.options.waitUntil;if(t&&!this._waitUntilCycle)try{t(e.catch(()=>{}))}catch{}return e}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let t,r=new Promise(e=>{t=e});try{e(r)}catch{return}this._waitUntilCycle={resolve:t,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,r=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),t>=r)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=M(()=>{this.resolveWaitUntilFlush()},i)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await super.flush()}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)}getLibraryVersion(){return"5.29.2"}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}capture(e){"string"==typeof e&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),"$exception"!==e.event||e._originatedFromCaptureException||this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.addPendingPromise(this.prepareEventMessage(e).then(({distinctId:e,event:t,properties:r,options:i})=>super.captureStateless(e,t,r,{timestamp:i.timestamp,disableGeoip:i.disableGeoip,uuid:i.uuid})).catch(e=>{e&&console.error(e)}))}async captureImmediate(e){return"string"==typeof e&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),"$exception"!==e.event||e._originatedFromCaptureException||this._logger.warn("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.addPendingPromise(this.prepareEventMessage(e).then(({distinctId:e,event:t,properties:r,options:i})=>super.captureStatelessImmediate(e,t,r,{timestamp:i.timestamp,disableGeoip:i.disableGeoip,uuid:i.uuid})).catch(e=>{e&&console.error(e)}))}identify({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:a,...n}=t;super.identifyStateless(e,{$set:i||n,$set_once:s||{},$anon_distinct_id:a??void 0},{disableGeoip:r})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:a,...n}=t;super.identifyStatelessImmediate(e,{$set:i||n,$set_once:s||{},$anon_distinct_id:a??void 0},{disableGeoip:r})}alias(e){super.aliasStateless(e.alias,e.distinctId,void 0,{disableGeoip:e.disableGeoip})}async aliasImmediate(e){await super.aliasStatelessImmediate(e.alias,e.distinctId,void 0,{disableGeoip:e.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(t=>{let r=setTimeout(()=>{i(),t(!1)},e),i=this._events.on("localEvaluationFlagsLoaded",e=>{clearTimeout(r),i(),t(e>0)})})}_resolveDistinctId(e,t){return"string"==typeof e?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,r={},i){let s,a,n,o,l,u,c,h=r.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&e in this._flagOverrides){let t=this._flagOverrides[e];if(void 0===t)return;let r=this._payloadOverrides?.[e];return{key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:r}}let{groups:d,disableGeoip:g}=r,{onlyEvaluateLocally:p,personProperties:f,groupProperties:y}=r,m=this.addLocalPersonAndGroupProperties(t,d,f,y);f=m.allPersonProperties,y=m.allGroupProperties;let v=this.createFeatureFlagEvaluationContext(t,d,f,y);void 0==p&&(p=this.options.strictLocalEvaluation??!1);let _=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let t=this.featureFlagsPoller?.featureFlagsByKey[e];if(t)try{let r=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(t,v,{matchValue:i});if(r){_=!0;let i=r.value;l=t.id,c="Evaluated locally",s={key:e,enabled:!1!==i,variant:"string"==typeof i?i:void 0,payload:r.payload??void 0}}}catch(t){if(t instanceof eJ||t instanceof eQ)this._logger?.info(`${t.name} when computing flag locally: ${e}: ${t.message}`);else throw t}}if(!_&&!p){let t=await super.getFeatureFlagDetailsStateless(v.distinctId,v.groups,v.personProperties,v.groupProperties,g,[e]);if(void 0===t)o=ez.UNKNOWN_ERROR;else{a=t.requestId,n=t.evaluatedAt;let r=[];t.errorsWhileComputingFlags&&r.push(ez.ERRORS_WHILE_COMPUTING),t.quotaLimited?.includes("feature_flags")&&r.push(ez.QUOTA_LIMITED);let i=t.flags[e];if(void 0===i)r.push(ez.FLAG_MISSING);else{let t;if(l=i.metadata?.id,u=i.metadata?.version,c=i.reason?.description??i.reason?.code,i.metadata?.payload!==void 0)try{t=JSON.parse(i.metadata.payload)}catch{t=i.metadata.payload}s={key:e,enabled:i.enabled,variant:i.variant,payload:t}}r.length>0&&(o=r.join(","))}}if(h){let r=void 0===s?void 0:!1!==s.enabled&&(s.variant??!0),i=`${e}_${r}`;if(!(t in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[t].includes(i)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[t])?this.distinctIdHasSentFlagCalls[t].push(i):this.distinctIdHasSentFlagCalls[t]=[i];let s={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:l,$feature_flag_version:u,$feature_flag_reason:c,locally_evaluated:_,[`$feature/${e}`]:r,$feature_flag_request_id:a,$feature_flag_evaluated_at:_?Date.now():n};if(_&&this.featureFlagsPoller){let e=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==e&&(s.$feature_flag_definitions_loaded_at=e)}o&&(s.$feature_flag_error=o),this.capture({distinctId:t,event:"$feature_flag_called",properties:s,groups:d,disableGeoip:g})}}return void 0!==s&&void 0!==this._payloadOverrides&&e in this._payloadOverrides&&(s={...s,payload:this._payloadOverrides[e]}),s}async getFeatureFlag(e,t,r){let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(void 0!==i)return!1!==i.enabled&&(i.variant??!0)}async getFeatureFlagPayload(e,t,r,i){if(void 0!==this._payloadOverrides&&e in this._payloadOverrides)return this._payloadOverrides[e];let s=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:!1},r);if(void 0!==s)return s.payload??null}async getFeatureFlagResult(e,t,r){let{distinctId:i,options:s}=this._resolveDistinctId(t,r);return i?this._getFeatureFlagResult(e,i,{...s,sendFeatureFlagEvents:s?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let r=await t.json();if("string"==typeof r)try{return JSON.parse(r)}catch(e){}return r}async isFeatureEnabled(e,t,r){let i=await this.getFeatureFlag(e,t,r);if(void 0!==i)return!!i}async getAllFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);return r?(await this.getAllFlagsAndPayloads(r,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads — pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};let{groups:s,disableGeoip:a,flagKeys:n}=i||{},{onlyEvaluateLocally:o,personProperties:l,groupProperties:u}=i||{},c=this.addLocalPersonAndGroupProperties(r,s,l,u);l=c.allPersonProperties,u=c.allGroupProperties;let h=this.createFeatureFlagEvaluationContext(r,s,l,u);void 0==o&&(o=this.options.strictLocalEvaluation??!1);let d=await this.featureFlagsPoller?.getAllFlagsAndPayloads(h,n),g={},p={},f=!0;if(d&&(g=d.response,p=d.payloads,f=d.fallbackToFlags),f&&!o){let e=await super.getFeatureFlagsAndPayloadsStateless(h.distinctId,h.groups,h.personProperties,h.groupProperties,a,n);g={...g,...e.flags||{}},p={...p,...e.payloads||{}}}return void 0!==this._flagOverrides&&(g={...g,...this._flagOverrides}),void 0!==this._payloadOverrides&&(p={...p,...this._payloadOverrides}),{featureFlags:g,featureFlagPayloads:p}}groupIdentify({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:s}){super.groupIdentifyStateless(e,t,r,{disableGeoip:s},i)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=e=>Object.fromEntries(e.map(e=>[e,!0]));if(!1===e){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(!1===e.flags?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):void 0!==e.flags&&(this._flagOverrides={...e.flags})),"payloads"in e&&(!1===e.payloads?this._payloadOverrides=void 0:void 0!==e.payloads&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if("flags"in e){let t=e.flags;if(!1===t||Array.isArray(t)||"object"==typeof t&&null!==t)return!0}if("payloads"in e){let t=e.payloads;if(!1===t||"object"==typeof t&&null!==t)return!0}return!1}withContext(e,t,r){return this.context?this.context.run(e,t,r):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown();try{return await super._shutdown(e)}finally{t?.()}}async _requestRemoteConfigPayload(e){if(!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let e=new AbortController;i=M(()=>{e.abort()},this.options.requestTimeout),r.signal=e.signal}try{return await this.fetch(t,r)}catch(e){this._events.emit("error",e);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let r={},i={};for(let[s,a]of Object.entries(e))if(x(a,"Object")&&t&&s in t){let e={};for(let[t,r]of Object.entries(a))e[String(t)]=String(r);i[String(s)]=e}else r[String(s)]=String(a);return{personProperties:r,groupProperties:i}}async getFeatureFlagsForEvent(e,t,r,i){let s=i?.personProperties||{},a=i?.groupProperties||{},n=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:a,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:n})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:a,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:n})}return(await super.getFeatureFlagsStateless(e,t,s,a,r)).flags}addLocalPersonAndGroupProperties(e,t,r,i){let s={distinct_id:e,...r||{}},a={};if(t)for(let e of Object.keys(t))a[e]={$group_key:t[e],...i?.[e]||{}};return{allPersonProperties:s,allGroupProperties:a}}createFeatureFlagEvaluationContext(e,t,r,i){return{distinctId:e,groups:t||{},personProperties:r||{},groupProperties:i||{},evaluationCache:{}}}captureException(e,t,r,i){if(!eH.isPreviouslyCapturedError(e)){let s=Error("PostHog syntheticException");this.addPendingPromise(eH.buildEventMessage(e,{syntheticException:s},t,r).then(e=>this.capture({...e,uuid:i})))}}async captureExceptionImmediate(e,t,r){if(!eH.isPreviouslyCapturedError(e)){let i=Error("PostHog syntheticException");return this.addPendingPromise(eH.buildEventMessage(e,{syntheticException:i},t,r).then(e=>this.captureImmediate(e)))}}async prepareEventMessage(e){let{distinctId:t,event:r,properties:i,groups:s,sendFeatureFlags:a,timestamp:n,disableGeoip:o,uuid:l}=e,u=this.context?.get(),c=t||u?.distinctId,h={...this.props,...u?.properties||{},...i||{}};c||(c=y().toString(),h.$process_person_profile=!1),u?.sessionId&&!h.$session_id&&(h.$session_id=u.sessionId);let d=this._runBeforeSend({distinctId:c,event:r,properties:h,groups:s,sendFeatureFlags:a,timestamp:n,disableGeoip:o,uuid:l});if(!d)return Promise.reject(null);let g=await Promise.resolve().then(async()=>a?await this.getFeatureFlagsForEvent(d.distinctId,s,o,"object"==typeof a?a:void 0):(d.event,{})).then(e=>{let t={};if(e)for(let[r,i]of Object.entries(e))t[`$feature/${r}`]=i;let r=Object.keys(e||{}).filter(t=>e?.[t]!==!1).sort();return r.length>0&&(t.$active_feature_flags=r),t}).catch(()=>({})).then(e=>({...e,...d.properties||{},$groups:d.groups||s}));return"$pageview"===d.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof g.$raw_user_agent&&eG(g.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(d.event="$bot_pageview",g.$browser_type="bot"),{distinctId:d.distinctId,event:d.event,properties:g,options:{timestamp:d.timestamp,disableGeoip:d.disableGeoip,uuid:d.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let r=Array.isArray(t)?t:[t],i=e;for(let t of r){if(!(i=t(i)))return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!i.properties||0===Object.keys(i.properties).length){let e=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(e)}}return i}}var eO=e$,e9=e.i(78500);class e6{constructor(){this.storage=new e9.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,r){return this.storage.run(this.resolve(e,r),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let r=this.get()||{};return{distinctId:e.distinctId??r.distinctId,sessionId:e.sessionId??r.sessionId,properties:{...r.properties||{},...e.properties||{}}}}}function e8(e,t){var r;t.use((r=e,(e,t,i,s)=>{if(eH.isPreviouslyCapturedError(e))return void s(e);let a=t.headers["x-posthog-session-id"],n=t.headers["x-posthog-distinct-id"],o=Error("Synthetic exception");r.addPendingPromise(eH.buildEventMessage(e,{mechanism:{type:"middleware",handled:!1},syntheticException:o},n,{$session_id:a,$current_url:t.url,$request_method:t.method,$request_path:t.path,$user_agent:t.headers["user-agent"],$response_status_code:i.statusCode,$ip:t.headers["x-forwarded-for"]||t?.socket?.remoteAddress}).then(e=>{r.capture(e)})),s(e)}))}e.s(["setupExpressErrorHandler",0,e8],93546),e.s([],92998),eH.errorPropertiesBuilder=new eO.ErrorPropertiesBuilder([new eO.EventCoercer,new eO.ErrorCoercer,new eO.ObjectCoercer,new eO.StringCoercer,new eO.PrimitiveCoercer],eO.createStackParser("node:javascript",eO.nodeStackLineParser),[(a=function(e=process.argv[1]?(0,o.dirname)(process.argv[1]):process.cwd(),t="\\"===o.sep){let r=t?l(e):e;return e=>{if(!e)return;let i=t?l(e):e,{dir:s,base:a,ext:n}=o.posix.parse(i);(".js"===n||".mjs"===n||".cjs"===n)&&(a=a.slice(0,-1*n.length));let u=decodeURIComponent(a);s||(s=".");let c=s.lastIndexOf("/node_modules");if(c>-1)return`${s.slice(c+14).replace(/\//g,".")}:${u}`;if(s.startsWith(r)){let e=s.slice(r.length+1).replace(/\//g,".");return e?`${e}:${u}`:u}return u}}(),async e=>{for(let t of e)t.module=a(t.filename);return e}),eM]);class e7 extends e5{getLibraryId(){return"posthog-node"}initializeContext(){return new e6}}e.s(["PostHog",0,e7],47839),e.i(47839),e.i(92998);let te="posthog-node";function tt(e,{organization:t,projectId:r,prefix:i,severityAllowList:s=["error"],sendExceptionsToPostHog:a=!0}={}){return n=>{if(!("*"===s||s.includes(n.level)))return n;n.tags||(n.tags={});let o=n.tags[ti.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};return t&&r&&(d.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+n.event_id),a&&e.capture({event:"$exception",distinctId:o,properties:d}),n}}function tr(e,t){let r=tt(e,t);return{name:te,processEvent:e=>r(e)}}class ti{static #e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,r,i,s){this.name=te,this.name=te,this.setupOnce=function(a,n){a(tt(e,{organization:t,projectId:n()?.getClient()?.getDsn()?.projectId,prefix:r,severityAllowList:i,sendExceptionsToPostHog:s??!0}))}}}e.s(["PostHogSentryIntegration",0,ti,"createEventProcessor",0,tt,"sentryIntegration",0,tr],91573),e.i(91573),e.i(93546),e.i(58325),e.s(["FeatureFlagError",0,v,"PostHogSentryIntegration",0,ti,"createEventProcessor",0,tt,"sentryIntegration",0,tr,"setupExpressErrorHandler",0,e8],57564),e.i(57564),e.s(["FeatureFlagError",0,v,"PostHog",0,e7,"PostHogSentryIntegration",0,ti,"createEventProcessor",0,tt,"sentryIntegration",0,tr,"setupExpressErrorHandler",0,e8],28864)}];
1
+ module.exports=[28864,e=>{"use strict";let t,r,i,s,a;var n,o=e.i(14747);function l(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}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}};async function h(e,t=!0,r){try{let t=new CompressionStream("gzip"),r=t.writable.getWriter(),i=r.write(new TextEncoder().encode(e)).then(()=>r.close()).catch(async e=>{try{await r.abort(e)}catch{}throw e}),s=new Response(t.readable).blob(),[a]=await Promise.all([s,i]);return a}catch(e){if(r?.rethrow)throw e;return t&&console.error("Failed to gzip compress data",e),null}}var d=((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.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.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 g={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=Array.isArray,f=Object.prototype;f.hasOwnProperty;let y=f.toString,m=p||function(e){return"[object Array]"===y.call(e)},v=e=>e===Object(e)&&!m(e),_=e=>"[object String]"==y.call(e),b=e=>"[object Number]"==y.call(e)&&e==e;function w(e){return null===e||"object"!=typeof e}function E(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function F(e){return"u">typeof Event&&function(e,t){try{return e instanceof t}catch{return!1}}(e,Event)}let P="Android",x="BlackBerry",S="Nintendo",I="PlayStation",k="Xbox",C="Windows",$="(\\d+(\\.\\d+)?)";RegExp("Version/"+$),RegExp(k,"i"),RegExp(I+" \\w+","i"),RegExp(S+" \\w+","i"),RegExp(x+"|PlayBook|BB10","i");async function A(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(e=>setTimeout(e,t.retryDelay));try{return await e()}catch(e){if(r=e,!t.retryCheck(e))throw e}}throw r}function O(){return new Date().toISOString()}function T(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}RegExp("rv:"+$),RegExp("Edge?\\/"+$),RegExp("(Chrome|CrMo)\\/"+$),RegExp("CriOS\\/"+$),RegExp("(UCBrowser|UCWEB)\\/"+$),RegExp("(Opera|OPR)\\/"+$),RegExp("Firefox\\/"+$),RegExp("FxiOS\\/"+$),RegExp("Konqueror[:/]?"+$,"i"),RegExp(x+" "+$),RegExp("android\\s"+$,"i"),RegExp("SamsungBrowser\\/"+$),RegExp("(rv:|MSIE )"+$),RegExp("rv:"+$),RegExp(k+"; "+k+" (.*?)[);]","i"),RegExp(S,"i"),RegExp(I,"i"),RegExp(C,"i"),RegExp("("+P+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+P+")","i");let R=e=>e instanceof Error;function L(e){return Promise.all(e.map(e=>(e??Promise.resolve()).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}let M="0123456789abcdef";class j{constructor(e){this.bytes=e}static ofInner(e){if(16===e.length)return new j(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,r,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||e<0||t<0||r<0||i<0||e>0xffffffffffff||t>4095||r>0x3fffffff||i>0xffffffff)throw RangeError("invalid field value");let s=new Uint8Array(16);return s[0]=e/0x10000000000,s[1]=e/0x100000000,s[2]=e/0x1000000,s[3]=e/65536,s[4]=e/256,s[5]=e,s[6]=112|t>>>8,s[7]=t,s[8]=128|r>>>24,s[9]=r>>>16,s[10]=r>>>8,s[11]=r,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new j(s)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("")}if(t){let e=new Uint8Array(16);for(let r=0;r<16;r+=4){let i=parseInt(t.substring(2*r,2*r+8),16);e[r+0]=i>>>24,e[r+1]=i>>>16,e[r+2]=i>>>8,e[r+3]=i}return new j(e)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=M.charAt(this.bytes[t]>>>4),e+=M.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+=M.charAt(this.bytes[t]>>>4),e+=M.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 j(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(let t=0;t<16;t++){let r=this.bytes[t]-e.bytes[t];if(0!==r)return Math.sign(r)}return 0}}class D{constructor(e){this.timestamp=0,this.counter=0,this.random=e??U()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);return void 0===r&&(this.timestamp=0,r=this.generateOrAbortCore(e,t)),r}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>0x3ffffffffff&&(this.timestamp++,this.resetCounter())}return j.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,j.ofInner(e)}}let U=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),B=()=>(t||(t=new D)).generate();class q{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,t){for(let r of this.events[e]||[])r(t);for(let r of this.events["*"]||[])r(e,t)}}class N{add(e){let t=B().toString();return this.promiseByIds[t]=e,e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds),t=e.length;for(;t>0;)await Promise.all(e),t=(e=Object.values(this.promiseByIds)).length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}}let H=(e,t,r)=>{function i(s,...a){t(()=>{(0,r[s])(e,...a)})}return{info:(...e)=>{i("log",...e)},warn:(...e)=>{i("warn",...e)},error:(...e)=>{i("error",...e)},critical:(...t)=>{r.error(e,...t)},createLogger:i=>H(`${e} ${i}`,t,r)}};class G 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 z extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}async function W(e){if(e instanceof G){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 K(e){return"object"==typeof e&&(e instanceof G||e instanceof z)}function V(e){return"object"==typeof e&&e instanceof G&&413===e.status}class Q{constructor(e,t={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new N,this._events=new q,this._isInitialized=!1;const r="string"==typeof e?e.trim():"",i="string"==typeof t.host?t.host.trim():"",s=!r;this._logger=function(e,t=e=>e()){return H(e,t,function(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),s&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=r,this.host=function(e){return e?.replace(/\/+$/,"")}(i||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1e3),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3e3,retryCheck:K},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,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(d.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(d.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(d.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){return{distinct_id:e.distinct_id,event:e.event,properties:{...e.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,r){this.wrap(()=>{let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",i,r)})}async identifyStatelessImmediate(e,t,r){let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",i,r)}captureStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",s,i)})}async captureStatelessImmediate(e,t,r,i){let s=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",s,i)}aliasStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",s,i)})}async aliasStatelessImmediate(e,t,r,i){let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",s,i)}groupIdentifyStateless(e,t,r,i,s,a){this.wrap(()=>{let n=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...a||{}}});this.enqueue("capture",n,i)})}async getRemoteConfig(){await this._initPromise;let e=this.host;"https://us.i.posthog.com"===e?e="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===e&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.apiKey}/config`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,r,{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={},r={},i={},s={},a=!1){await this._initPromise;let n=`${this.host}/flags/?v=2${a?"&config=true":""}`,o={token:this.apiKey,distinct_id:e,groups:t,person_properties:r,group_properties:i,...s};r.$device_id&&(o.$device_id=r.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(o.evaluation_contexts=this.evaluationContexts);let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(o)};return this._logger.info("Flags URL",n),this.fetchWithRetry(n,l,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(e=>e.json()).then(e=>({success:!0,response:(e=>{if("flags"in e){let t,r=Object.fromEntries(Object.entries(e.flags??{}).map(([e,t])=>[e,u(t)]).filter(([,e])=>void 0!==e)),i=Object.fromEntries(Object.keys(t=e.flags??{}).filter(e=>{let r=t[e];return r.enabled&&r.metadata&&void 0!==r.metadata.payload}).map(e=>{let r=t[e].metadata?.payload;return[e,r?c(r):void 0]}));return{...e,featureFlags:r,featureFlagPayloads:i}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([e,t])=>[e,c(t)])),i=Object.fromEntries(Object.entries(t).map(([e,t])=>{var i,s;return[e,{key:e,enabled:"string"==typeof(i=t)||i,variant:"string"==typeof i?i:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:(s=r[e])?JSON.stringify(s):void 0,description:void 0}}]}));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}})(e)})).catch(e=>(this._events.emit("error",e),{success:!1,error:this.categorizeRequestError(e)}))}categorizeRequestError(e){if(e instanceof G)return{type:"api_error",statusCode:e.status};if(e instanceof z){let t=e.error;return t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,r={},i={},s={},a){await this._initPromise;let n=await this.getFeatureFlagDetailStateless(e,t,r,i,s,a);if(void 0===n)return{response:void 0,requestId:void 0};let o=u(n.response);return void 0===o&&(o=!1),{response:o,requestId:n.requestId}}async getFeatureFlagDetailStateless(e,t,r={},i={},s={},a){await this._initPromise;let n=await this.getFeatureFlagDetailsStateless(t,r,i,s,a,[e]);if(void 0!==n)return{response:n.flags[e],requestId:n.requestId,evaluatedAt:n.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,r={},i={},s={},a){await this._initPromise;let n=await this.getFeatureFlagPayloadsStateless(t,r,i,s,a,[e]);if(!n)return;let o=n[e];return void 0===o?null:o}async getFeatureFlagPayloadsStateless(e,t={},r={},i={},s,a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,a)).payloads}async getFeatureFlagsStateless(e,t={},r={},i={},s,a){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,a)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},i={},s,a){await this._initPromise;let n=await this.getFeatureFlagDetailsStateless(e,t,r,i,s,a);return n?{flags:n.featureFlags,payloads:n.featureFlagPayloads,requestId:n.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},r={},i={},s,a){await this._initPromise;let n={};(s??this.disableGeoip)&&(n.geoip_disable=!0),a&&(n.flag_keys_to_evaluate=a);let o=await this.getFlags(e,t,r,i,n);if(!o.success)return;let l=o.response;return(l.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),l.quotaLimited?.includes("feature_flags"))?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},r=await this.fetchWithRetry(e,t).then(e=>{if(200!==e.status||!e.json){let t=`Surveys API could not be loaded: ${e.status}`,r=Error(t);this._logger.error(r),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)}),i=r?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(d.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(d.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(d.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}enqueue(e,t,r){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(e,t,r);if(null===(i=this.processBeforeEnqueue(i)))return;let s=this.getPersistedProperty(d.Queue)||[];s.length>=this.maxQueueSize&&(s.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),s.push({message:i}),this.setPersistedProperty(d.Queue,s),this._events.emit(e,i),s.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=T(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,r){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 i=this.prepareMessage(e,t,r);if(null===(i=this.processBeforeEnqueue(i)))return;let s={api_key:this.apiKey,batch:[i],sent_at:O()};this.historicalMigration&&(s.historical_migration=!0);let a=JSON.stringify(s),n=`${this.host}/batch/`,o=this.disableCompression?null:await h(a,this.isDebug),l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==o&&{"Content-Encoding":"gzip"}},body:o||a};try{await this.fetchWithRetry(n,l)}catch(e){this._events.emit("error",e)}}prepareMessage(e,t,r){let i={...t,type:e,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:r?.timestamp?r?.timestamp:O(),uuid:r?.uuid?r.uuid:B().toString()};return(r?.disableGeoip??this.disableGeoip)&&(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.flush().catch(async e=>{await W(e)})}async flush(){let e=L([this.flushPromise]).then(()=>this._flush());return this.flushPromise=e,this.addPendingPromise(e),L([e]).then(()=>{this.flushPromise===e&&(this.flushPromise=null)}),e}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&""!==e&&(t["User-Agent"]=e),t}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getPersistedProperty(d.Queue)||[];if(!e.length)return;let t=[],r=e.length;for(;e.length>0&&t.length<r;){let r=e.slice(0,this.maxBatchSize),i=r.map(e=>e.message),s=async()=>{let t=(this.getPersistedProperty(d.Queue)||[]).slice(r.length);this.setPersistedProperty(d.Queue,t),e=t,await this.flushStorage()},a={api_key:this.apiKey,batch:i,sent_at:O()};this.historicalMigration&&(a.historical_migration=!0);let n=JSON.stringify(a),o=`${this.host}/batch/`,l=this.disableCompression?null:await h(n,this.isDebug),u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==l&&{"Content-Encoding":"gzip"}},body:l||n},c={retryCheck:e=>!V(e)&&K(e)};try{await this.fetchWithRetry(o,u,c)}catch(e){if(V(e)&&i.length>1){this.maxBatchSize=Math.max(1,Math.floor(i.length/2)),this._logger.warn(`Received 413 when sending batch of size ${i.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw e instanceof z||await s(),this._events.emit("error",e),e}await s(),t.push(...i)}this._events.emit("flush",t)}async fetchWithRetry(e,t,r,i){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 A(async()=>{let r=new AbortController,s=T(()=>r.abort(),i??this.requestTimeout),n=null;try{n=await this.fetch(e,{signal:r.signal,...t})}catch(e){throw new z(e)}finally{clearTimeout(s)}if("no-cors"!==t.mode&&(n.status<200||n.status>=400))throw new G(n,a);return n},{...this._retryOptions,...r})}async _shutdown(e=3e4){let t;await this._initPromise;let r=!1;this.clearFlushTimer();let i=async()=>{try{for(await this.promiseQueue.join();;){let e=this.getPersistedProperty(d.Queue)||[];if(0===e.length||(await this.flush(),r))break}}catch(e){if(!K(e))throw e;await W(e)}};try{return await Promise.race([new Promise((i,s)=>{t=T(()=>{this._logger.error("Timed out while shutting down PostHog"),r=!0,s("Timeout while shutting down PostHog. Some events may not have been sent.")},e)}),i()])}finally{clearTimeout(t)}}async shutdown(e=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}class J{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){let r=t&&t.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(r,t,0).apply(e),s=this.buildParsingContext(t),a=this.parseStacktrace(i,s);return{$exception_list:this.convertToExceptionList(a,r),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&m(t.stacktrace.frames)&&(t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames));return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let r,i;return null!=e.cause&&(r=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack&&(i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),{...e,cause:r,stack:i}}applyChunkIds(e,t){return e.map(e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e))}applyCoercers(e,t){for(let r of this.coercers)if(r.match(e))return r.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let e of this.modifiers)t=await e(t);return t}convertToExceptionList(e,t){let r={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};e.stack&&(r.stacktrace={type:"raw",frames:e.stack});let i=[r];return null!=e.cause&&i.push(...this.convertToExceptionList(e.cause,{...t,handled:!0})),i}buildParsingContext(e){return{chunkIdMap:function(e){let t=globalThis._posthogChunkIds;if(!t)return;let a=Object.keys(t);return s&&a.length===i?s:(i=a.length,s=a.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,r=0){let i=(r,i)=>{if(i<=4){let s=this.buildCoercingContext(e,t,i);return this.applyCoercers(r,s)}};return{...t,syntheticException:0==r?t.syntheticException:void 0,mechanism:e,apply:e=>i(e,r),next:e=>i(e,r+1)}}}function Y(e,t,r,i,s){let a={platform:e,filename:t,function:"<anonymous>"===r?"?":r,in_app:!0};return void 0!==i&&(a.lineno=i),void 0!==s&&(a.colno=s),a}e.s(["ErrorPropertiesBuilder",0,J],80446);let X=(e,t)=>{let r=-1!==e.indexOf("safari-extension"),i=-1!==e.indexOf("safari-web-extension");return r||i?[-1!==e.indexOf("@")?e.split("@")[0]:"?",r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},Z=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ee=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,et=/\((\S*)(?::(\d+))(?::(\d+))\)/,er=(e,t)=>{let r=Z.exec(e);if(r){let[,e,i,s]=r;return Y(t,e,"?",+i,+s)}let i=ee.exec(e);if(i){if(i[2]&&0===i[2].indexOf("eval")){let e=et.exec(i[2]);e&&(i[2]=e[1],i[3]=e[2],i[4]=e[3])}let[e,r]=X(i[1]||"?",i[2]);return Y(t,r,e,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},ei=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,es=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ea=(e,t)=>{let r=ei.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let e=es.exec(r[3]);e&&(r[1]=r[1]||"eval",r[3]=e[1],r[4]=e[2],r[5]="")}let e=r[3],i=r[1]||"?";return[i,e]=X(i,e),Y(t,e,i,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}},en=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,eo=(e,t)=>{let r=en.exec(e);return r?Y(t,r[2],r[1]||"?",+r[3],r[4]?+r[4]:void 0):void 0},el=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,eu=(e,t)=>{let r=el.exec(e);return r?Y(t,r[2],r[3]||"?",+r[1]):void 0},ec=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,eh=(e,t)=>{let r=ec.exec(e);return r?Y(t,r[5],r[3]||r[4]||"?",+r[1],+r[2]):void 0},ed=/^\s*[-]{4,}$/,eg=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,ep=(e,t)=>{let r=e.match(eg);if(r){let e,i,s,a,n;if(r[1]){let t=(s=r[1]).lastIndexOf(".");if("."===s[t-1]&&t--,t>0){e=s.slice(0,t),i=s.slice(t+1);let r=e.indexOf(".Module");r>0&&(s=s.slice(r+1),e=e.slice(0,r))}a=void 0}i&&(a=e,n=i),"<anonymous>"===i&&(n=void 0,s=void 0),void 0===s&&(n=n||"?",s=a?`${a}.${n}`:n);let o=r[2]?.startsWith("file://")?r[2].slice(7):r[2],l="native"===r[5];return o?.match(/\/[A-Z]:/)&&(o=o.slice(1)),o||!r[5]||l||(o=r[5]),{filename:o?decodeURI(o):void 0,module:void 0,function:s,lineno:ef(r[3]),colno:ef(r[4]),in_app:function(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==e&&!e.includes("node_modules/")}(o||"",l),platform:t}}if(e.match(ed))return{filename:e,platform:t}};function ef(e){return parseInt(e||"",10)||void 0}let ey=/\(error: (.*)\)/;function em(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,50).map(e=>{var r;return{...e,filename:e.filename||((r=t)[r.length-1]||{}).filename,function:e.function||"?"}})}function ev(){return e_("web:javascript",er,ea)}function e_(e,...t){return(r,i=0)=>{let s=[],a=r.split("\n");for(let r=i;r<a.length;r++){let i=a[r];if(i.length>1024)continue;let n=ey.test(i)?i.replace(ey,"$1"):i;if(!n.match(/\S*Error: /)){for(let r of t){let t=r(n,e);if(t){s.push(t);break}}if(s.length>=50)break}}return em(s)}}e.s(["createDefaultStackParser",0,ev,"createStackParser",0,e_,"reverseAndStripFrames",0,em],34246);class eb{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let r=_(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return E(e,"DOMException")}isDOMError(e){return E(e,"DOMError")}}e.s(["DOMExceptionCoercer",0,eb],29569);class ew{match(e){return e instanceof 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 r=e.message;return r.error&&"string"==typeof r.error.message?String(r.error.message):String(r)}getStack(e){return e.stacktrace||e.stack||void 0}}e.s(["ErrorCoercer",0,ew],11475);class eE{match(e){return E(e,"ErrorEvent")&&void 0!=e.error}coerce(e,t){let r=t.apply(e.error);return r||{type:"ErrorEvent",value:e.message,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["ErrorEventCoercer",0,eE],43179);let eF=["fatal","error","warning","log","info","debug"];function eP(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let e=r.length;e>0;e--){let i=r.slice(0,e).join(", ");if(!(i.length>t)){if(e===r.length)return i;return i.length<=t?i:`${i.slice(0,t)}...`}}return""}class ex{match(e){return"object"==typeof e&&null!==e}coerce(e,t){let r=this.getErrorPropertyFromObject(e);return r?t.apply(r):{type:this.getType(e),value:this.getValue(e),stack:t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return F(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),r=eP(e);return`${t&&"Object"!==t?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return _(e)&&!(_(e)&&0===e.trim().length)&&eF.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(R(r))return r}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){return}}}e.s(["ObjectCoercer",0,ex],6881);class eS{match(e){return F(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${eP(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["EventCoercer",0,eS],80322);class eI{match(e){return w(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["PrimitiveCoercer",0,eI],80049);class ek{match(e){return E(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!F(e))return!1;try{let t=e.detail;return null!=t&&"object"==typeof t&&"reason"in t}catch{return!1}}coerce(e,t){let r=this.getUnhandledRejectionReason(e);return w(r)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(r)}`,stack:t.syntheticException?.stack,synthetic:!0}:t.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&null!=e.detail&&"object"==typeof e.detail&&"reason"in e.detail)return e.detail.reason}catch{}return e}}e.s(["PromiseRejectionEventCoercer",0,ek],98689),e.s([],99573);let eC={MESSAGE:"$message",TIMESTAMP:"$timestamp"},e$=new Set([eC.MESSAGE,eC.TIMESTAMP]),eA={enabled:!0,max_bytes:32768};function eO(e){return e?{enabled:e.enabled??eA.enabled,max_bytes:function(e,t){if(!b(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}(e.max_bytes,eA.max_bytes)}:{...eA}}function eT(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((r,i)=>(e$.has(i)?t.push(i):r[i]=e[i],r),{}),droppedKeys:t}}class eR{constructor(e){this._entries=[],this._totalBytes=0,this._config=eO(e)}setConfig(e){this._config=eO(e),this._trimToMaxBytes()}add(e){let t=function(e){let t=function(e){let t=new WeakSet;try{return JSON.stringify(e,(e,r)=>{if("bigint"==typeof r)return r.toString();if("function"!=typeof r&&"symbol"!=typeof r){if(r instanceof Date)return r.toISOString();if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&"object"==typeof r){if(t.has(r))return"[Circular]";t.add(r)}return r}})}catch{return}}(e);if(t)try{let e=JSON.parse(t);if(!v(e))return;let r=e[eC.MESSAGE],i=e[eC.TIMESTAMP];if(!_(r)||0===r.trim().length||!_(i)&&!b(i))return;return{step:e,json:t}}catch{return}}(e);if(!t)return;let r=eL(t.json);r>this._config.max_bytes||(this._entries.push({step:t.step,bytes:r}),this._totalBytes+=r,this._trimToMaxBytes())}getAttachable(){return this._entries.map(e=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}}function eL(e){if("u">typeof TextEncoder)return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let e=0;e<t.length;e++)"%"===t[e]?(r+=1,e+=2):r+=1;return r}e.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,eA,"EXCEPTION_STEP_INTERNAL_FIELDS",0,eC,"ExceptionStepsBuffer",0,eR,"getUtf8ByteLength",0,eL,"resolveExceptionStepsConfig",0,eO,"stripReservedExceptionStepFields",0,eT],52001),e.s([],47114),e.i(47114),e.i(80446),e.i(34246),e.s(["chromeStackLineParser",0,er,"createDefaultStackParser",0,ev,"createStackParser",0,e_,"geckoStackLineParser",0,ea,"nodeStackLineParser",0,ep,"opera10StackLineParser",0,eu,"opera11StackLineParser",0,eh,"reverseAndStripFrames",0,em,"winjsStackLineParser",0,eo],70736),e.i(70736),e.i(99573),e.i(29569),e.i(11475),e.i(43179);let eM=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class ej{match(e){return"string"==typeof e}coerce(e,t){let[r,i]=this.getInfos(e);return{type:r??"Error",value:i??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",r=e,i=e.match(eM);return i&&(t=i[1],r=i[2]),[t,r]}}e.s(["StringCoercer",0,ej],45098),e.i(45098),e.i(6881),e.i(80322),e.i(80049),e.i(98689),e.s(["DOMExceptionCoercer",0,eb,"ErrorCoercer",0,ew,"ErrorEventCoercer",0,eE,"EventCoercer",0,eS,"ObjectCoercer",0,ex,"PrimitiveCoercer",0,eI,"PromiseRejectionEventCoercer",0,ek,"StringCoercer",0,ej],21854),e.i(21854);class eD{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(void 0!==t)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}}e.s(["ReduceableCache",0,eD],46986),e.i(46986),e.i(52001),e.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,eA,"DOMExceptionCoercer",0,eb,"EXCEPTION_STEP_INTERNAL_FIELDS",0,eC,"ErrorCoercer",0,ew,"ErrorEventCoercer",0,eE,"ErrorPropertiesBuilder",0,J,"EventCoercer",0,eS,"ExceptionStepsBuffer",0,eR,"ObjectCoercer",0,ex,"PrimitiveCoercer",0,eI,"PromiseRejectionEventCoercer",0,ek,"ReduceableCache",0,eD,"StringCoercer",0,ej,"chromeStackLineParser",0,er,"createDefaultStackParser",0,ev,"createStackParser",0,e_,"geckoStackLineParser",0,ea,"getUtf8ByteLength",0,eL,"nodeStackLineParser",0,ep,"opera10StackLineParser",0,eu,"opera11StackLineParser",0,eh,"resolveExceptionStepsConfig",0,eO,"reverseAndStripFrames",0,em,"stripReservedExceptionStepFields",0,eT,"winjsStackLineParser",0,eo],96117);var eU=e.i(96117),eB=eU,eq=e.i(2157),eN=e.i(1457);let eH=new eB.ReduceableCache(25),eG=new eB.ReduceableCache(20);async function ez(e){let t={};for(let s=e.length-1;s>=0;s--){var r,i;let a=e[s],n=a?.filename;!(!a||"string"!=typeof n||"number"!=typeof a.lineno||(r=n).startsWith("node:")||r.endsWith(".min.js")||r.endsWith(".min.cjs")||r.endsWith(".min.mjs")||r.startsWith("data:")||void 0!==(i=a).lineno&&i.lineno>1e4||void 0!==i.colno&&i.colno>1e3)&&(t[n]||(t[n]=[]),t[n].push(a.lineno))}let s=Object.keys(t);if(0==s.length)return e;let a=[];for(let e of s){if(eG.get(e))continue;let r=t[e];if(!r)continue;r.sort((e,t)=>e-t);let i=function(e){if(!e.length)return[];let t=0,r=e[0];if("number"!=typeof r)return[];let i=eK(r),s=[];for(;;){if(t===e.length-1){s.push(i);break}let r=e[t+1];if("number"!=typeof r)break;r<=i[1]?i[1]=r+7:(s.push(i),i=eK(r)),t++}return s}(r);if(i.every(t=>(function(e,t){let r=eH.get(e);if(void 0===r)return!1;for(let e=t[0];e<=t[1];e++)if(void 0===r[e])return!1;return!0})(e,t)))continue;let s=function(e,t,r){let i=e.get(t);return void 0===i?(e.set(t,r),r):i}(eH,e,{});a.push(function(e,t,r){return new Promise(i=>{let s=(0,eq.createReadStream)(e),a=(0,eN.createInterface)({input:s});function n(){s.destroy(),i()}let o=0,l=0,u=t[0];if(void 0===u)return void n();let c=u[0],h=u[1];function d(){eG.set(e,1),a.close(),a.removeAllListeners(),n()}s.on("error",d),a.on("error",d),a.on("close",n),a.on("line",e=>{if(!(++o<c)&&(r[o]=function(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let s=Math.max(t-60,0);s<5&&(s=0);let a=Math.min(s+140,i);return a>i-5&&(a=i),a===i&&(s=Math.max(a-140,0)),r=r.slice(s,a),s>0&&(r=`...${r}`),a<i&&(r+="..."),r}(e,0),o>=h)){if(l===t.length-1){a.close(),a.removeAllListeners();return}let e=t[++l];if(void 0===e){a.close(),a.removeAllListeners();return}c=e[0],h=e[1]}})})}(e,i,s))}return await Promise.all(a).catch(()=>{}),e&&e.length>0&&function(e,t){for(let r of e)if(r.filename&&void 0===r.context_line&&"number"==typeof r.lineno){let e=t.get(r.filename);if(void 0===e)continue;!function(e,t,r){if(void 0===t.lineno||void 0===r)return;t.pre_context=[];for(let i=eV(e);i<e;i++){let e=r[i];if(void 0===e)return void eW(t);t.pre_context.push(e)}if(void 0===r[e])return eW(t);t.context_line=r[e];let i=function(e){return e+7}(e);t.post_context=[];for(let s=e+1;s<=i;s++){let e=r[s];if(void 0===e)break;t.post_context.push(e)}}(r.lineno,r,e)}}(e,eH),eH.reduce(),e}function eW(e){delete e.pre_context,delete e.context_line,delete e.post_context}function eK(e){return[eV(e),e+7]}function eV(e){return Math.max(1,e-7)}function eQ(e,t,r,i,s){if(t>r&&(i.warn("min cannot be greater than max."),t=r),b(e))if(e>r)return i.warn(" cannot be greater than max: "+r+". Using max value instead."),r;else return e<t?(i.warn(" cannot be less than min: "+t+". Using min value instead."),t):e;return i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+s),eQ(s||r,t,r,i)}class eJ{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=eQ(e.bucketSize,0,100,e._logger),this._refillRate=eQ(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=eQ(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){let r=Math.floor((t-e.lastAccess)/this._refillInterval);if(r>0){let t=r*this._refillRate;e.tokens=Math.min(e.tokens+t,this._bucketSize),e.lastAccess=e.lastAccess+r*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),r=String(e),i=this._buckets[r];return i?this._applyRefill(i,t):(i={tokens:this._bucketSize,lastAccess:t},this._buckets[r]=i),0===i.tokens||(i.tokens--,0===i.tokens&&this._onBucketRateLimited?.(e),0===i.tokens)}stop(){this._buckets={}}}class eY{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new eJ({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return v(e)&&"__posthog_previously_captured_error"in e&&!0===e.__posthog_previously_captured_error}static async buildEventMessage(e,t,r,i){let s={...i},a=this.errorPropertiesBuilder.buildFromUnknown(e,t);return a.$exception_list=await this.errorPropertiesBuilder.modifyFrames(a.$exception_list),{event:"$exception",distinctId:r,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled()){var t,r,i;let s;t=this.onException.bind(this),r=this.onFatalError.bind(this),globalThis.process?.on("uncaughtException",(s=!1,Object.assign(i=>{let a=e.g.process.listeners("uncaughtException").filter(e=>"domainUncaughtExceptionClear"!==e.name&&!0!==e._posthogErrorHandler).length;t(i,{mechanism:{type:"onuncaughtexception",handled:!1}}),s||0!==a||(s=!0,r(i))},{_posthogErrorHandler:!0}))),i=this.onException.bind(this),globalThis.process?.on("unhandledRejection",e=>i(e,{mechanism:{type:"onunhandledrejection",handled:!1}}))}}onException(e,t){this.client.addPendingPromise((async()=>{if(!eY.isPreviouslyCapturedError(e)){let r=await eY.buildEventMessage(e,t),i=r.properties,s=i?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(s)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:s}):this.client.capture(r)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(2e3),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}let eX=["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"],eZ=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return eX.concat(t).some(e=>{let t=e.toLowerCase();return -1!==r.indexOf(t)})},e0={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function e1(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("")}e.s(["FeatureFlagError",0,e0],58325);let e4=["is_not"];class e2 extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,e2.prototype)}}class e3 extends Error{constructor(e){super(e),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e3.prototype)}}class e5 extends Error{constructor(e){super(e),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,e5.prototype)}}class e6{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:i,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=i,this.projectApiKey=r,this.host=s,this.poller=void 0,this.fetch=n.fetch||fetch,this.onError=n.onError,this.customHeaders=a,this.onLoad=n.onLoad,this.cacheProvider=n.cacheProvider,this.strictLocalEvaluation=n.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}createEvaluationContext(e,t={},r={},i={},s={}){return{distinctId:e,groups:t,personProperties:r,groupProperties:i,evaluationCache:s}}async getFeatureFlag(e,t,r={},i={},s={}){let a,n;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return a;if(void 0!==(n=this.featureFlagsByKey[e])){let o=this.createEvaluationContext(t,r,i,s);try{a=(await this.computeFlagAndPayloadLocally(n,o)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${a}`))}catch(t){t instanceof e5||t instanceof e3?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e}: ${t}`))}}return a}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let r={},i={},s=0==this.featureFlags.length,a=t?t.map(e=>this.featureFlagsByKey[e]).filter(Boolean):this.featureFlags,n={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(a.map(async e=>{try{let{value:t,payload:s}=await this.computeFlagAndPayloadLocally(e,n);r[e.key]=t,s&&(i[e.key]=s)}catch(t){t instanceof e5||t instanceof e3?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e.key}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e.key}: ${t}`)),s=!0}})),{response:r,payloads:i,fallbackToFlags:s}}async computeFlagAndPayloadLocally(e,t,r={}){let i,{matchValue:s,skipLoadCheck:a=!1}=r;if(a||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};i=void 0!==s?s:await this.computeFlagValueLocally(e,t);let n=this.getFeatureFlagPayload(e.key,i);return{value:i,payload:n}}async computeFlagValueLocally(e,t){let{distinctId:r,groups:i,personProperties:s,groupProperties:a}=t;if(e.ensure_experience_continuity)throw new e3("Flag has experience continuity enabled");if(!e.active)return!1;let n=(e.filters||{}).aggregation_group_type_index;if(void 0!=n){let r=this.groupTypeMapping[String(n)];if(!r)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${n} for feature flag ${e.key}`)),new e3("Flag has unknown group type index");if(!(r in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;"device_id"===e.bucketing_identifier&&(s?.$device_id===void 0||s?.$device_id===null||s?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let o=a[r];return await this.matchFeatureFlagProperties(e,i[r],o,t)}{let i=this.getBucketingValueForFlag(e,r,s);if(void 0===i)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new e3(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,i,s,t)}}getBucketingValueForFlag(e,t,r){if(e.filters?.aggregation_group_type_index!=void 0)return t;if("device_id"===e.bucketing_identifier){let e=r?.$device_id;if(null==e||""===e)return;return e}return t}getFeatureFlagPayload(e,t){let r=null;if(!1!==t&&null!=t&&("boolean"==typeof t?r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null:"string"==typeof t&&(r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null),null!=r)){if("object"==typeof r)return r;if("string"==typeof r)try{return JSON.parse(r)}catch{}return r}return null}async evaluateFlagDependency(e,t,r){let{evaluationCache:i}=r,s=e.key;if(!this.featureFlagsByKey)throw new e3("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new e3(`Flag dependency property for '${s}' is missing required 'dependency_chain' field`);let a=e.dependency_chain;if(!Array.isArray(a))throw new e3(`Flag dependency property for '${s}' has an invalid 'dependency_chain' (expected array, got ${typeof a})`);if(0===a.length)throw new e3(`Circular dependency detected for flag '${s}' (empty dependency chain)`);for(let e of a){if(!(e in i)){let t=this.featureFlagsByKey[e];if(t)if(t.active)try{let s=await this.computeFlagValueLocally(t,r);i[e]=s}catch(t){throw new e3(`Error evaluating flag dependency '${e}' for flag '${s}': ${t}`)}else i[e]=!1;else throw new e3(`Missing flag dependency '${e}' for flag '${s}'`)}if(null==i[e])throw new e3(`Dependency '${e}' could not be evaluated`)}let n=i[s];return this.flagEvaluatesToExpectedValue(e.value,n)}flagEvaluatesToExpectedValue(e,t){return"boolean"==typeof e?e===t||"string"==typeof t&&""!==t&&!0===e:"string"==typeof e&&t===e}async matchFeatureFlagProperties(e,t,r,i){let s,a=e.filters||{},n=a.groups||[],o=!1;for(let l of n)try{if(await this.isConditionMatch(e,t,l,r,i)){let r=l.variant,i=a.multivariate?.variants||[];s=r&&i.some(e=>e.key===r)?r:await this.getMatchingVariant(e,t)||!0;break}}catch(e){if(e instanceof e5)throw e;if(e instanceof e3)o=!0;else throw e}if(void 0!==s)return s;if(o)throw new e3("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,r,i,s){let a=r.rollout_percentage,n=e=>{this.logMsgIfDebug(()=>console.warn(e))};if((r.properties||[]).length>0){for(let e of r.properties){let t=e.type;if(!("cohort"===t?function e(t,r,i,s=!1){let a=String(t.value);if(!(a in i))throw new e5(`cohort ${a} not found in local cohorts - likely a static cohort that requires server evaluation`);return function t(r,i,s,a=!1){if(!r)return!0;let n=r.type,o=r.values;if(!o||0===o.length)return!0;let l=!1;if("values"in o[0]){for(let e of o)try{let r=t(e,i,s,a);if("AND"===n){if(!r)return!1}else if(r)return!0}catch(t){if(t instanceof e5)throw t;if(t instanceof e3)a&&console.debug(`Failed to compute property ${e} locally: ${t}`),l=!0;else throw t}if(l)throw new e3("Can't match cohort without a given cohort property value");return"AND"===n}for(let t of o)try{let r;if("cohort"===t.type)r=e(t,i,s,a);else if("flag"===t.type){a&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${t.key||"unknown"}'`);continue}else r=e9(t,i);let o=t.negation||!1;if("AND"===n){if(!r&&!o||r&&o)return!1}else if(r&&!o||!r&&o)return!0}catch(e){if(e instanceof e5)throw e;if(e instanceof e3)a&&console.debug(`Failed to compute property ${t} locally: ${e}`),l=!0;else throw e}if(l)throw new e3("can't match cohort without a given cohort property value");return"AND"===n}(i[a],r,i,s)}(e,i,this.cohorts,this.debugMode):"flag"===t?await this.evaluateFlagDependency(e,i,s):e9(e,i,n)))return!1}if(void 0==a)return!0}return!(void 0!=a&&await e8(e.key,t)>a/100)}async getMatchingVariant(e,t){let r=await e8(e.key,t,"variant"),i=this.variantLookupTable(e).find(e=>r>=e.valueMin&&r<e.valueMax);if(i)return i.key}variantLookupTable(e){let t=[],r=0,i=0,s=e.filters||{};return(s.multivariate?.variants||[]).forEach(e=>{i=r+e.rollout_percentage/100,t.push({valueMin:r,valueMax:i,key:e.key}),r=i}),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}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 e2(`Your project key or personal API 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={};return;case 403:throw this.beginBackoff(),new e2(`Your personal API 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 personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new e2(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let r=await t.json()??{};if(!("flags"in r))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let i={flags:r.flags??[],groupTypeMapping:r.group_type_mapping||{},cohorts:r.cohorts||{}};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(e){this.onError?.(Error(`Failed to store in cache: ${e}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(e){e instanceof e2&&this.onError?.(e)}}getPersonalApiKeyRequestOptions(e="GET",t){let r={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(r["If-None-Match"]=t),{method:e,headers:r}}_requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),r=null;if(this.timeout&&"number"==typeof this.timeout){let e=new AbortController;r=T(()=>{e.abort()},this.timeout),t.signal=e.signal}try{return(0,this.fetch)(e,t)}finally{clearTimeout(r)}}async stopPoller(e=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await Promise.race([t,new Promise((t,r)=>setTimeout(()=>r(Error(`Cache shutdown timeout after ${e}ms`)),e))])}catch(e){this.onError?.(Error(`Error during cache shutdown: ${e}`))}}}async function e8(e,t,r=""){return parseInt((await e1(`${e}.${t}${r}`)).slice(0,15),16)/0x1000000000000000}function e9(e,t,r){let i=e.key,s=e.value,a=e.operator||"exact";if(i in t){if("is_not_set"===a)throw new e3("Operator is_not_set is not supported")}else throw new e3(`Property ${i} not found in propertyValues`);let n=t[i];if(null==n&&!e4.includes(a))return r&&r(`Property ${i} 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,r){if("gt"===r)return e>t;if("gte"===r)return e>=t;if("lt"===r)return e<t;if("lte"===r)return e<=t;throw Error(`Invalid operator: ${r}`)}switch(a){case"exact":return o(s,n);case"is_not":return!o(s,n);case"is_set":return i 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 e7(String(s))&&null!==String(n).match(String(s));case"not_regex":return e7(String(s))&&null===String(n).match(String(s));case"gt":case"gte":case"lt":case"lte":{let e="number"==typeof s?s:null;if("string"==typeof s)try{e=parseFloat(s)}catch(e){}if(null==e||null==n)return l(String(n),String(s),a);if("string"==typeof n)return l(n,String(s),a);return l(n,e,a)}case"is_date_after":case"is_date_before":{if("boolean"==typeof s)throw new e3("Date operations cannot be performed on boolean values");let e=function(e){let t=e.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),r=new Date(new Date().toISOString());if(!t)return null;{if(!t.groups)return null;let e=parseInt(t.groups.number);if(e>=1e4)return null;let i=t.groups.interval;if("h"==i)r.setUTCHours(r.getUTCHours()-e);else if("d"==i)r.setUTCDate(r.getUTCDate()-e);else if("w"==i)r.setUTCDate(r.getUTCDate()-7*e);else if("m"==i)r.setUTCMonth(r.getUTCMonth()-e);else{if("y"!=i)return null;r.setUTCFullYear(r.getUTCFullYear()-e)}return r}}(String(s));if(null==e&&(e=tr(s)),null==e)throw new e3(`Invalid date: ${s}`);let t=tr(n);if(["is_date_before"].includes(a))return t<e;return t>e}case"semver_eq":return 0===tt(te(String(n)),te(String(s)));case"semver_neq":return 0!==tt(te(String(n)),te(String(s)));case"semver_gt":return tt(te(String(n)),te(String(s)))>0;case"semver_gte":return tt(te(String(n)),te(String(s)))>=0;case"semver_lt":return 0>tt(te(String(n)),te(String(s)));case"semver_lte":return 0>=tt(te(String(n)),te(String(s)));case"semver_tilde":{let e,t=te(String(n)),{lower:r,upper:i}={lower:[(e=te(String(s)))[0],e[1],e[2]],upper:[e[0],e[1]+1,0]};return tt(t,r)>=0&&0>tt(t,i)}case"semver_caret":{let e=te(String(n)),{lower:t,upper:r}=function(e){let[t,r,i]=te(e);return{lower:[t,r,i],upper:t>0?[t+1,0,0]:r>0?[0,r+1,0]:[0,0,i+1]}}(String(s));return tt(e,t)>=0&&0>tt(e,r)}case"semver_wildcard":{let e=te(String(n)),{lower:t,upper:r}=function(e){let t,r,i=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!i)throw new e3(`Invalid wildcard semver: ${e}`);let s=i.split("."),a=parseInt(s[0],10);if(isNaN(a))throw new e3(`Invalid wildcard semver: ${e}`);if(1===s.length)t=[a,0,0],r=[a+1,0,0];else{let i=parseInt(s[1],10);if(isNaN(i))throw new e3(`Invalid wildcard semver: ${e}`);t=[a,i,0],r=[a,i+1,0]}return{lower:t,upper:r}}(String(s));return tt(e,t)>=0&&0>tt(e,r)}default:throw new e3(`Unknown operator: ${a}`)}}function e7(e){try{return new RegExp(e),!0}catch(e){return!1}}function te(e){let t=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!t||t.startsWith("."))throw new e3(`Invalid semver: ${e}`);let r=t.split("."),i=t=>{if(void 0===t||""===t)return 0;if(!/^\d+$/.test(t))throw new e3(`Invalid semver: ${e}`);return parseInt(t,10)};return[i(r[0]),i(r[1]),i(r[2])]}function tt(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return -1;if(e[r]>t[r])return 1}return 0}function tr(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 e3(`${e} is in an invalid date format`)}throw new e3(`The date provided ${e} must be a string, number, or date object`)}class ti{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=null!==t?t:void 0}constructor(){this._memoryStorage={}}}class ts extends Q{constructor(e,t={}){const r=function(e){return"string"==typeof e?e.trim():""}(e),i={...t,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.personalApiKey)};if(super(r,i),this._memoryStorage=new ti,this.options=i,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof i.featureFlagsPollingInterval?Math.max(i.featureFlagsPollingInterval,100):3e4,"number"==typeof i.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),"number"==typeof i.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),i.personalApiKey){if(i.personalApiKey.includes("phc_"))throw Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');!1!==i.enableLocalEvaluation&&(this.featureFlagsPoller=new e6({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:r,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:e=>{this._events.emit("error",e)},onLoad:e=>{this._events.emit("localEvaluationFlagsLoaded",e)},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation}))}this.errorTracking=new eY(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||5e4}enqueue(e,t,r){super.enqueue(e,t,r),this.scheduleDebouncedFlush()}async flush(){let e=super.flush(),t=this.options.waitUntil;if(t&&!this._waitUntilCycle)try{t(e.catch(()=>{}))}catch{}return e}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let t,r=new Promise(e=>{t=e});try{e(r)}catch{return}this._waitUntilCycle={resolve:t,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,r=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),t>=r)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=T(()=>{this.resolveWaitUntilFlush()},i)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await super.flush()}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)}getLibraryVersion(){return"5.30.6"}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}capture(e){"string"==typeof e&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),"$exception"!==e.event||e._originatedFromCaptureException||this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.addPendingPromise(this.prepareEventMessage(e).then(({distinctId:e,event:t,properties:r,options:i})=>super.captureStateless(e,t,r,{timestamp:i.timestamp,disableGeoip:i.disableGeoip,uuid:i.uuid})).catch(e=>{e&&console.error(e)}))}async captureImmediate(e){return"string"==typeof e&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),"$exception"!==e.event||e._originatedFromCaptureException||this._logger.warn("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.addPendingPromise(this.prepareEventMessage(e).then(({distinctId:e,event:t,properties:r,options:i})=>super.captureStatelessImmediate(e,t,r,{timestamp:i.timestamp,disableGeoip:i.disableGeoip,uuid:i.uuid})).catch(e=>{e&&console.error(e)}))}identify({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:a,...n}=t;super.identifyStateless(e,{$set:i||n,$set_once:s||{},$anon_distinct_id:a??void 0},{disableGeoip:r})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:a,...n}=t;super.identifyStatelessImmediate(e,{$set:i||n,$set_once:s||{},$anon_distinct_id:a??void 0},{disableGeoip:r})}alias(e){super.aliasStateless(e.alias,e.distinctId,void 0,{disableGeoip:e.disableGeoip})}async aliasImmediate(e){await super.aliasStatelessImmediate(e.alias,e.distinctId,void 0,{disableGeoip:e.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(t=>{let r=setTimeout(()=>{i(),t(!1)},e),i=this._events.on("localEvaluationFlagsLoaded",e=>{clearTimeout(r),i(),t(e>0)})})}_resolveDistinctId(e,t){return"string"==typeof e?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,r={},i){let s,a,n,o,l,u,c,h=r.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&e in this._flagOverrides){let t=this._flagOverrides[e];if(void 0===t)return;let r=this._payloadOverrides?.[e];return{key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:r}}let{groups:d,disableGeoip:g}=r,{onlyEvaluateLocally:p,personProperties:f,groupProperties:y}=r,m=this.addLocalPersonAndGroupProperties(t,d,f,y);f=m.allPersonProperties,y=m.allGroupProperties;let v=this.createFeatureFlagEvaluationContext(t,d,f,y);void 0==p&&(p=this.options.strictLocalEvaluation??!1);let _=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let t=this.featureFlagsPoller?.featureFlagsByKey[e];if(t)try{let r=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(t,v,{matchValue:i});if(r){_=!0;let i=r.value;l=t.id,c="Evaluated locally",s={key:e,enabled:!1!==i,variant:"string"==typeof i?i:void 0,payload:r.payload??void 0}}}catch(t){if(t instanceof e5||t instanceof e3)this._logger?.info(`${t.name} when computing flag locally: ${e}: ${t.message}`);else throw t}}if(!_&&!p){let t=await super.getFeatureFlagDetailsStateless(v.distinctId,v.groups,v.personProperties,v.groupProperties,g,[e]);if(void 0===t)o=e0.UNKNOWN_ERROR;else{a=t.requestId,n=t.evaluatedAt;let r=[];t.errorsWhileComputingFlags&&r.push(e0.ERRORS_WHILE_COMPUTING),t.quotaLimited?.includes("feature_flags")&&r.push(e0.QUOTA_LIMITED);let i=t.flags[e];if(void 0===i)r.push(e0.FLAG_MISSING);else{let t;if(l=i.metadata?.id,u=i.metadata?.version,c=i.reason?.description??i.reason?.code,i.metadata?.payload!==void 0)try{t=JSON.parse(i.metadata.payload)}catch{t=i.metadata.payload}s={key:e,enabled:i.enabled,variant:i.variant,payload:t}}r.length>0&&(o=r.join(","))}}if(h){let r=void 0===s?void 0:!1!==s.enabled&&(s.variant??!0),i=`${e}_${r}`;if(!(t in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[t].includes(i)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[t])?this.distinctIdHasSentFlagCalls[t].push(i):this.distinctIdHasSentFlagCalls[t]=[i];let s={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:l,$feature_flag_version:u,$feature_flag_reason:c,locally_evaluated:_,[`$feature/${e}`]:r,$feature_flag_request_id:a,$feature_flag_evaluated_at:_?Date.now():n};if(_&&this.featureFlagsPoller){let e=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==e&&(s.$feature_flag_definitions_loaded_at=e)}o&&(s.$feature_flag_error=o),this.capture({distinctId:t,event:"$feature_flag_called",properties:s,groups:d,disableGeoip:g})}}return void 0!==s&&void 0!==this._payloadOverrides&&e in this._payloadOverrides&&(s={...s,payload:this._payloadOverrides[e]}),s}async getFeatureFlag(e,t,r){let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(void 0!==i)return!1!==i.enabled&&(i.variant??!0)}async getFeatureFlagPayload(e,t,r,i){if(void 0!==this._payloadOverrides&&e in this._payloadOverrides)return this._payloadOverrides[e];let s=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:!1},r);if(void 0!==s)return s.payload??null}async getFeatureFlagResult(e,t,r){let{distinctId:i,options:s}=this._resolveDistinctId(t,r);return i?this._getFeatureFlagResult(e,i,{...s,sendFeatureFlagEvents:s?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let r=await t.json();if("string"==typeof r)try{return JSON.parse(r)}catch(e){}return r}async isFeatureEnabled(e,t,r){let i=await this.getFeatureFlag(e,t,r);if(void 0!==i)return!!i}async getAllFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);return r?(await this.getAllFlagsAndPayloads(r,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads — pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};let{groups:s,disableGeoip:a,flagKeys:n}=i||{},{onlyEvaluateLocally:o,personProperties:l,groupProperties:u}=i||{},c=this.addLocalPersonAndGroupProperties(r,s,l,u);l=c.allPersonProperties,u=c.allGroupProperties;let h=this.createFeatureFlagEvaluationContext(r,s,l,u);void 0==o&&(o=this.options.strictLocalEvaluation??!1);let d=await this.featureFlagsPoller?.getAllFlagsAndPayloads(h,n),g={},p={},f=!0;if(d&&(g=d.response,p=d.payloads,f=d.fallbackToFlags),f&&!o){let e=await super.getFeatureFlagsAndPayloadsStateless(h.distinctId,h.groups,h.personProperties,h.groupProperties,a,n);g={...g,...e.flags||{}},p={...p,...e.payloads||{}}}return void 0!==this._flagOverrides&&(g={...g,...this._flagOverrides}),void 0!==this._payloadOverrides&&(p={...p,...this._payloadOverrides}),{featureFlags:g,featureFlagPayloads:p}}groupIdentify({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:s}){super.groupIdentifyStateless(e,t,r,{disableGeoip:s},i)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=e=>Object.fromEntries(e.map(e=>[e,!0]));if(!1===e){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(!1===e.flags?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):void 0!==e.flags&&(this._flagOverrides={...e.flags})),"payloads"in e&&(!1===e.payloads?this._payloadOverrides=void 0:void 0!==e.payloads&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if("flags"in e){let t=e.flags;if(!1===t||Array.isArray(t)||"object"==typeof t&&null!==t)return!0}if("payloads"in e){let t=e.payloads;if(!1===t||"object"==typeof t&&null!==t)return!0}return!1}withContext(e,t,r){return this.context?this.context.run(e,t,r):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown();try{return await super._shutdown(e)}finally{t?.()}}async _requestRemoteConfigPayload(e){if(!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let e=new AbortController;i=T(()=>{e.abort()},this.options.requestTimeout),r.signal=e.signal}try{return await this.fetch(t,r)}catch(e){this._events.emit("error",e);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let r={},i={};for(let[s,a]of Object.entries(e))if(E(a,"Object")&&t&&s in t){let e={};for(let[t,r]of Object.entries(a))e[String(t)]=String(r);i[String(s)]=e}else r[String(s)]=String(a);return{personProperties:r,groupProperties:i}}async getFeatureFlagsForEvent(e,t,r,i){let s=i?.personProperties||{},a=i?.groupProperties||{},n=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:a,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:n})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:a,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:n})}return(await super.getFeatureFlagsStateless(e,t,s,a,r)).flags}addLocalPersonAndGroupProperties(e,t,r,i){let s={distinct_id:e,...r||{}},a={};if(t)for(let e of Object.keys(t))a[e]={$group_key:t[e],...i?.[e]||{}};return{allPersonProperties:s,allGroupProperties:a}}createFeatureFlagEvaluationContext(e,t,r,i){return{distinctId:e,groups:t||{},personProperties:r||{},groupProperties:i||{},evaluationCache:{}}}captureException(e,t,r,i){if(!eY.isPreviouslyCapturedError(e)){let s=Error("PostHog syntheticException");this.addPendingPromise(eY.buildEventMessage(e,{syntheticException:s},t,r).then(e=>this.capture({...e,uuid:i})))}}async captureExceptionImmediate(e,t,r){if(!eY.isPreviouslyCapturedError(e)){let i=Error("PostHog syntheticException");return this.addPendingPromise(eY.buildEventMessage(e,{syntheticException:i},t,r).then(e=>this.captureImmediate(e)))}}async prepareEventMessage(e){let{distinctId:t,event:r,properties:i,groups:s,sendFeatureFlags:a,timestamp:n,disableGeoip:o,uuid:l}=e,u=this.context?.get(),c=t||u?.distinctId,h={...this.props,...u?.properties||{},...i||{}};c||(c=B().toString(),h.$process_person_profile=!1),u?.sessionId&&!h.$session_id&&(h.$session_id=u.sessionId);let d=this._runBeforeSend({distinctId:c,event:r,properties:h,groups:s,sendFeatureFlags:a,timestamp:n,disableGeoip:o,uuid:l});if(!d)return Promise.reject(null);let g=await Promise.resolve().then(async()=>a?await this.getFeatureFlagsForEvent(d.distinctId,s,o,"object"==typeof a?a:void 0):(d.event,{})).then(e=>{let t={};if(e)for(let[r,i]of Object.entries(e))t[`$feature/${r}`]=i;let r=Object.keys(e||{}).filter(t=>e?.[t]!==!1).sort();return r.length>0&&(t.$active_feature_flags=r),t}).catch(()=>({})).then(e=>({...e,...d.properties||{},$groups:d.groups||s}));return"$pageview"===d.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof g.$raw_user_agent&&eZ(g.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(d.event="$bot_pageview",g.$browser_type="bot"),{distinctId:d.distinctId,event:d.event,properties:g,options:{timestamp:d.timestamp,disableGeoip:d.disableGeoip,uuid:d.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let r=Array.isArray(t)?t:[t],i=e;for(let t of r){if(!(i=t(i)))return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!i.properties||0===Object.keys(i.properties).length){let e=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(e)}}return i}}var eB=eU,ta=e.i(78500);class tn{constructor(){this.storage=new ta.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,r){return this.storage.run(this.resolve(e,r),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let r=this.get()||{};return{distinctId:e.distinctId??r.distinctId,sessionId:e.sessionId??r.sessionId,properties:{...r.properties||{},...e.properties||{}}}}}function to(e,t){var r;t.use((r=e,(e,t,i,s)=>{if(eY.isPreviouslyCapturedError(e))return void s(e);let a=t.headers["x-posthog-session-id"],n=t.headers["x-posthog-distinct-id"],o=Error("Synthetic exception");r.addPendingPromise(eY.buildEventMessage(e,{mechanism:{type:"middleware",handled:!1},syntheticException:o},n,{$session_id:a,$current_url:t.url,$request_method:t.method,$request_path:t.path,$user_agent:t.headers["user-agent"],$response_status_code:i.statusCode,$ip:t.headers["x-forwarded-for"]||t?.socket?.remoteAddress}).then(e=>{r.capture(e)})),s(e)}))}e.s(["setupExpressErrorHandler",0,to],93546),e.s([],92998),eY.errorPropertiesBuilder=new eB.ErrorPropertiesBuilder([new eB.EventCoercer,new eB.ErrorCoercer,new eB.ObjectCoercer,new eB.StringCoercer,new eB.PrimitiveCoercer],eB.createStackParser("node:javascript",eB.nodeStackLineParser),[(a=function(e=process.argv[1]?(0,o.dirname)(process.argv[1]):process.cwd(),t="\\"===o.sep){let r=t?l(e):e;return e=>{if(!e)return;let i=t?l(e):e,{dir:s,base:a,ext:n}=o.posix.parse(i);(".js"===n||".mjs"===n||".cjs"===n)&&(a=a.slice(0,-1*n.length));let u=decodeURIComponent(a);s||(s=".");let c=s.lastIndexOf("/node_modules");if(c>-1)return`${s.slice(c+14).replace(/\//g,".")}:${u}`;if(s.startsWith(r)){let e=s.slice(r.length+1).replace(/\//g,".");return e?`${e}:${u}`:u}return u}}(),async e=>{for(let t of e)t.module=a(t.filename);return e}),ez,function(e=process.cwd()){let t="\\"===o.sep,r=e=>t?e.replace(/\\/g,"/"):e,i=r(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=r((0,o.relative)(i,r(t.filename))));return e}}()]);class tl extends ts{getLibraryId(){return"posthog-node"}initializeContext(){return new tn}}e.s(["PostHog",0,tl],47839),e.i(47839),e.i(92998);let tu="posthog-node";function tc(e,{organization:t,projectId:r,prefix:i,severityAllowList:s=["error"],sendExceptionsToPostHog:a=!0}={}){return n=>{if(!("*"===s||s.includes(n.level)))return n;n.tags||(n.tags={});let o=n.tags[td.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};return t&&r&&(d.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+n.event_id),a&&e.capture({event:"$exception",distinctId:o,properties:d}),n}}function th(e,t){let r=tc(e,t);return{name:tu,processEvent:e=>r(e)}}class td{static #e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,r,i,s){this.name=tu,this.name=tu,this.setupOnce=function(a,n){a(tc(e,{organization:t,projectId:n()?.getClient()?.getDsn()?.projectId,prefix:r,severityAllowList:i,sendExceptionsToPostHog:s??!0}))}}}e.s(["PostHogSentryIntegration",0,td,"createEventProcessor",0,tc,"sentryIntegration",0,th],91573),e.i(91573),e.i(93546),e.i(58325),e.s(["FeatureFlagError",0,g,"PostHogSentryIntegration",0,td,"createEventProcessor",0,tc,"sentryIntegration",0,th,"setupExpressErrorHandler",0,to],57564),e.i(57564),e.s(["FeatureFlagError",0,g,"PostHog",0,tl,"PostHogSentryIntegration",0,td,"createEventProcessor",0,tc,"sentryIntegration",0,th,"setupExpressErrorHandler",0,to],28864)}];
2
2
 
3
3
  //# sourceMappingURL=node_modules_posthog-node_dist_entrypoints_index_node_mjs_05pz9._._.js.map
@@ -1,3 +1,3 @@
1
- module.exports=[93133,(t,e,s)=>{e.exports={name:"failproofai",version:"0.0.8",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"},files:["bin/","src/","scripts/","lib/",".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 && 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:"bun build --target=node --format=cjs --outfile=dist/index.js src/index.ts && bun run build:cli && 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",postinstall:"node scripts/postinstall.mjs",preuninstall:"node scripts/preuninstall.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"},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/exospherehost/failproofai",repository:{type:"git",url:"https://github.com/exospherehost/failproofai.git"},bugs:{url:"https://github.com/exospherehost/failproofai/issues"},publishConfig:{access:"public"},devDependencies:{"@tailwindcss/postcss":"^4.1.18","@tanstack/react-virtual":"^3.13.18","@testing-library/jest-dom":"^6.9.1","@testing-library/react":"^16.3.2","@testing-library/user-event":"^14.6.1","@types/node":"^25.5.2","@types/react":"^19.2.13","@types/react-dom":"^19.2.3","@vitejs/plugin-react":"^6.0.1",clsx:"^2.1.1",eslint:"^10.2.0","eslint-config-next":"^16.2.2","happy-dom":"^20.7.0","lucide-react":"^1.0.1",next:"^16.2.2",react:"^19.2.4","react-dom":"^19.2.4","tailwind-merge":"^3.4.0",tailwindcss:"^4.1.18",typescript:"^6.0.2","@anthropic-ai/sdk":"^0.90.0",vitest:"^4.0.18"},dependencies:{"posthog-node":"^5.28.11"}}}];
1
+ module.exports=[93133,(t,e,s)=>{e.exports={name:"failproofai",version:"0.0.9-beta.1",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"},files:["bin/","src/","scripts/","lib/",".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 && 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:"bun build --target=node --format=cjs --outfile=dist/index.js src/index.ts && bun run build:cli && 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",postinstall:"node scripts/postinstall.mjs",preuninstall:"node scripts/preuninstall.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"},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/exospherehost/failproofai",repository:{type:"git",url:"https://github.com/exospherehost/failproofai.git"},bugs:{url:"https://github.com/exospherehost/failproofai/issues"},publishConfig:{access:"public"},devDependencies:{"@tailwindcss/postcss":"^4.1.18","@tanstack/react-virtual":"^3.13.18","@testing-library/jest-dom":"^6.9.1","@testing-library/react":"^16.3.2","@testing-library/user-event":"^14.6.1","@types/node":"^25.5.2","@types/react":"^19.2.13","@types/react-dom":"^19.2.3","@vitejs/plugin-react":"^6.0.1",clsx:"^2.1.1",eslint:"^10.2.0","eslint-config-next":"^16.2.2","happy-dom":"^20.7.0","lucide-react":"^1.0.1",next:"^16.2.2",react:"^19.2.4","react-dom":"^19.2.4","tailwind-merge":"^3.4.0",tailwindcss:"^4.1.18",typescript:"^6.0.2","@anthropic-ai/sdk":"^0.91.1",vitest:"^4.0.18"},dependencies:{"posthog-node":"^5.28.11"}}}];
2
2
 
3
3
  //# sourceMappingURL=package_json_%5Bjson%5D_cjs_0z7w.hh._.js.map
@@ -1,3 +1,3 @@
1
- module.exports=[18622,(a,b,c)=>{b.exports=a.x("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js",()=>require("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js"))},56704,(a,b,c)=>{b.exports=a.x("next/dist/server/app-render/work-async-storage.external.js",()=>require("next/dist/server/app-render/work-async-storage.external.js"))},32319,(a,b,c)=>{b.exports=a.x("next/dist/server/app-render/work-unit-async-storage.external.js",()=>require("next/dist/server/app-render/work-unit-async-storage.external.js"))},20635,(a,b,c)=>{b.exports=a.x("next/dist/server/app-render/action-async-storage.external.js",()=>require("next/dist/server/app-render/action-async-storage.external.js"))},24725,(a,b,c)=>{b.exports=a.x("next/dist/server/app-render/after-task-async-storage.external.js",()=>require("next/dist/server/app-render/after-task-async-storage.external.js"))},43285,(a,b,c)=>{b.exports=a.x("next/dist/server/app-render/dynamic-access-async-storage.external.js",()=>require("next/dist/server/app-render/dynamic-access-async-storage.external.js"))},42602,(a,b,c)=>{"use strict";b.exports=a.r(18622)},87924,(a,b,c)=>{"use strict";b.exports=a.r(42602).vendored["react-ssr"].ReactJsxRuntime},72131,(a,b,c)=>{"use strict";b.exports=a.r(42602).vendored["react-ssr"].React},38783,(a,b,c)=>{"use strict";b.exports=a.r(42602).vendored["react-ssr"].ReactServerDOMTurbopackClient},9270,(a,b,c)=>{"use strict";b.exports=a.r(42602).vendored.contexts.AppRouterContext},36313,(a,b,c)=>{"use strict";b.exports=a.r(42602).vendored.contexts.HooksClientContext},18341,(a,b,c)=>{"use strict";b.exports=a.r(42602).vendored.contexts.ServerInsertedHtml},35112,(a,b,c)=>{"use strict";b.exports=a.r(42602).vendored["react-ssr"].ReactDOM},66036,a=>{"use strict";a.s(["captureClientEvent",0,function(a,b){},"setClientTelemetryConfig",0,function(a){}])},88347,(a,b,c)=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});var d,e,f={ACTION_HMR_REFRESH:function(){return l},ACTION_NAVIGATE:function(){return i},ACTION_REFRESH:function(){return h},ACTION_RESTORE:function(){return j},ACTION_SERVER_ACTION:function(){return m},ACTION_SERVER_PATCH:function(){return k},PrefetchKind:function(){return n},ScrollBehavior:function(){return o}};for(var g in f)Object.defineProperty(c,g,{enumerable:!0,get:f[g]});let h="refresh",i="navigate",j="restore",k="server-patch",l="hmr-refresh",m="server-action";var n=((d={}).AUTO="auto",d.FULL="full",d),o=((e={})[e.Default=0]="Default",e[e.NoScroll=1]="NoScroll",e);("function"==typeof c.default||"object"==typeof c.default&&null!==c.default)&&void 0===c.default.__esModule&&(Object.defineProperty(c.default,"__esModule",{value:!0}),Object.assign(c.default,c),b.exports=c.default)},46058,(a,b,c)=>{"use strict";function d(a){if("function"!=typeof WeakMap)return null;var b=new WeakMap,c=new WeakMap;return(d=function(a){return a?c:b})(a)}c._=function(a,b){if(!b&&a&&a.__esModule)return a;if(null===a||"object"!=typeof a&&"function"!=typeof a)return{default:a};var c=d(b);if(c&&c.has(a))return c.get(a);var e={__proto__:null},f=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var g in a)if("default"!==g&&Object.prototype.hasOwnProperty.call(a,g)){var h=f?Object.getOwnPropertyDescriptor(a,g):null;h&&(h.get||h.set)?Object.defineProperty(e,g,h):e[g]=a[g]}return e.default=a,c&&c.set(a,e),e}},67009,(a,b,c)=>{"use strict";function d(a){return null!==a&&"object"==typeof a&&"then"in a&&"function"==typeof a.then}Object.defineProperty(c,"__esModule",{value:!0}),Object.defineProperty(c,"isThenable",{enumerable:!0,get:function(){return d}})},90841,(a,b,c)=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});var d={dispatchAppRouterAction:function(){return i},dispatchGestureState:function(){return j},refreshOnInstantNavigationUnlock:function(){return h},useActionQueue:function(){return k}};for(var e in d)Object.defineProperty(c,e,{enumerable:!0,get:d[e]});let f=a.r(46058)._(a.r(72131)),g=a.r(67009);a.r(88347);function h(){}function i(a){!0;throw Object.defineProperty(Error("Internal Next.js error: Router action dispatched before initialization."),"__NEXT_ERROR_CODE",{value:"E668",enumerable:!1,configurable:!0})}function j(a){!0;throw Object.defineProperty(Error("Internal Next.js error: Router action dispatched before initialization."),"__NEXT_ERROR_CODE",{value:"E668",enumerable:!1,configurable:!0})}function k(a){let[b,c]=f.default.useState(a.state),[d,e]=(0,f.useOptimistic)(b),h=(0,f.useMemo)(()=>d,[d]);return(0,g.isThenable)(h)?(0,f.use)(h):h}("function"==typeof c.default||"object"==typeof c.default&&null!==c.default)&&void 0===c.default.__esModule&&(Object.defineProperty(c.default,"__esModule",{value:!0}),Object.assign(c.default,c),b.exports=c.default)},20611,(a,b,c)=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0}),Object.defineProperty(c,"callServer",{enumerable:!0,get:function(){return g}});let d=a.r(72131),e=a.r(88347),f=a.r(90841);async function g(a,b){return new Promise((c,g)=>{(0,d.startTransition)(()=>{(0,f.dispatchAppRouterAction)({type:e.ACTION_SERVER_ACTION,actionId:a,actionArgs:b,resolve:c,reject:g})})})}("function"==typeof c.default||"object"==typeof c.default&&null!==c.default)&&void 0===c.default.__esModule&&(Object.defineProperty(c.default,"__esModule",{value:!0}),Object.assign(c.default,c),b.exports=c.default)},1722,(a,b,c)=>{"use strict";let d;Object.defineProperty(c,"__esModule",{value:!0}),Object.defineProperty(c,"findSourceMapURL",{enumerable:!0,get:function(){return d}});("function"==typeof c.default||"object"==typeof c.default&&null!==c.default)&&void 0===c.default.__esModule&&(Object.defineProperty(c.default,"__esModule",{value:!0}),Object.assign(c.default,c),b.exports=c.default)},5050,(a,b,c)=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});var d={callServer:function(){return f.callServer},createServerReference:function(){return h.createServerReference},findSourceMapURL:function(){return g.findSourceMapURL}};for(var e in d)Object.defineProperty(c,e,{enumerable:!0,get:d[e]});let f=a.r(20611),g=a.r(1722),h=a.r(38783)},57594,a=>{"use strict";var b=a.i(5050);let c=(0,b.createServerReference)("001510e3800b2119dc0f0781ca25904622b8c2293d",b.callServer,void 0,b.findSourceMapURL,"getTelemetryConfig");a.s(["getTelemetryConfig",0,c])},3171,a=>{"use strict";var b=a.i(87924),c=a.i(72131),d=a.i(57594),e=a.i(66036);a.s(["default",0,function({error:a,reset:f}){return(0,c.useEffect)(()=>{(0,d.getTelemetryConfig)().then(b=>{(0,e.setClientTelemetryConfig)(b),(0,e.captureClientEvent)("client_error",{error_message:a.message,error_name:a.name,error_digest:a.digest,boundary:"global"})}).catch(()=>{})},[a]),(0,b.jsx)("html",{children:(0,b.jsx)("body",{children:(0,b.jsx)("main",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",background:"#031035",color:"#f8fafc",fontFamily:"system-ui, sans-serif"},children:(0,b.jsxs)("div",{style:{textAlign:"center",padding:"2rem",border:"1px solid rgba(239,68,68,0.4)",borderRadius:"0.5rem",maxWidth:"500px"},children:[(0,b.jsx)("h2",{style:{color:"#ef4444",marginBottom:"0.5rem",fontSize:"1.25rem"},children:"Something went wrong"}),(0,b.jsx)("p",{style:{color:"#94a3b8",marginBottom:"1.5rem"},children:a.message||"An unexpected error occurred."}),(0,b.jsx)("button",{onClick:f,style:{padding:"0.5rem 1.25rem",background:"#3b82f6",color:"white",border:"none",borderRadius:"0.375rem",cursor:"pointer",fontSize:"0.875rem"},children:"Try again"})]})})})})}])}];
1
+ module.exports=[18622,(a,b,c)=>{b.exports=a.x("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js",()=>require("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js"))},56704,(a,b,c)=>{b.exports=a.x("next/dist/server/app-render/work-async-storage.external.js",()=>require("next/dist/server/app-render/work-async-storage.external.js"))},32319,(a,b,c)=>{b.exports=a.x("next/dist/server/app-render/work-unit-async-storage.external.js",()=>require("next/dist/server/app-render/work-unit-async-storage.external.js"))},20635,(a,b,c)=>{b.exports=a.x("next/dist/server/app-render/action-async-storage.external.js",()=>require("next/dist/server/app-render/action-async-storage.external.js"))},24725,(a,b,c)=>{b.exports=a.x("next/dist/server/app-render/after-task-async-storage.external.js",()=>require("next/dist/server/app-render/after-task-async-storage.external.js"))},43285,(a,b,c)=>{b.exports=a.x("next/dist/server/app-render/dynamic-access-async-storage.external.js",()=>require("next/dist/server/app-render/dynamic-access-async-storage.external.js"))},42602,(a,b,c)=>{"use strict";b.exports=a.r(18622)},87924,(a,b,c)=>{"use strict";b.exports=a.r(42602).vendored["react-ssr"].ReactJsxRuntime},72131,(a,b,c)=>{"use strict";b.exports=a.r(42602).vendored["react-ssr"].React},38783,(a,b,c)=>{"use strict";b.exports=a.r(42602).vendored["react-ssr"].ReactServerDOMTurbopackClient},9270,(a,b,c)=>{"use strict";b.exports=a.r(42602).vendored.contexts.AppRouterContext},36313,(a,b,c)=>{"use strict";b.exports=a.r(42602).vendored.contexts.HooksClientContext},18341,(a,b,c)=>{"use strict";b.exports=a.r(42602).vendored.contexts.ServerInsertedHtml},35112,(a,b,c)=>{"use strict";b.exports=a.r(42602).vendored["react-ssr"].ReactDOM},66036,a=>{"use strict";a.s(["captureClientEvent",0,function(a,b){},"setClientTelemetryConfig",0,function(a){}])},88347,(a,b,c)=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});var d,e,f={ACTION_HMR_REFRESH:function(){return l},ACTION_NAVIGATE:function(){return i},ACTION_REFRESH:function(){return h},ACTION_RESTORE:function(){return j},ACTION_SERVER_ACTION:function(){return m},ACTION_SERVER_PATCH:function(){return k},PrefetchKind:function(){return n},ScrollBehavior:function(){return o}};for(var g in f)Object.defineProperty(c,g,{enumerable:!0,get:f[g]});let h="refresh",i="navigate",j="restore",k="server-patch",l="hmr-refresh",m="server-action";var n=((d={}).AUTO="auto",d.FULL="full",d),o=((e={})[e.Default=0]="Default",e[e.NoScroll=1]="NoScroll",e);("function"==typeof c.default||"object"==typeof c.default&&null!==c.default)&&void 0===c.default.__esModule&&(Object.defineProperty(c.default,"__esModule",{value:!0}),Object.assign(c.default,c),b.exports=c.default)},46058,(a,b,c)=>{"use strict";function d(a){if("function"!=typeof WeakMap)return null;var b=new WeakMap,c=new WeakMap;return(d=function(a){return a?c:b})(a)}c._=function(a,b){if(!b&&a&&a.__esModule)return a;if(null===a||"object"!=typeof a&&"function"!=typeof a)return{default:a};var c=d(b);if(c&&c.has(a))return c.get(a);var e={__proto__:null},f=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var g in a)if("default"!==g&&Object.prototype.hasOwnProperty.call(a,g)){var h=f?Object.getOwnPropertyDescriptor(a,g):null;h&&(h.get||h.set)?Object.defineProperty(e,g,h):e[g]=a[g]}return e.default=a,c&&c.set(a,e),e}},67009,(a,b,c)=>{"use strict";function d(a){return null!==a&&"object"==typeof a&&"then"in a&&"function"==typeof a.then}Object.defineProperty(c,"__esModule",{value:!0}),Object.defineProperty(c,"isThenable",{enumerable:!0,get:function(){return d}})},90841,(a,b,c)=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});var d={dispatchAppRouterAction:function(){return i},dispatchGestureState:function(){return j},refreshOnInstantNavigationUnlock:function(){return h},useActionQueue:function(){return k}};for(var e in d)Object.defineProperty(c,e,{enumerable:!0,get:d[e]});let f=a.r(46058)._(a.r(72131)),g=a.r(67009);a.r(88347);function h(){}function i(a){!0;throw Object.defineProperty(Error("Internal Next.js error: Router action dispatched before initialization."),"__NEXT_ERROR_CODE",{value:"E668",enumerable:!1,configurable:!0})}function j(a){!0;throw Object.defineProperty(Error("Internal Next.js error: Router action dispatched before initialization."),"__NEXT_ERROR_CODE",{value:"E668",enumerable:!1,configurable:!0})}function k(a){let[b,c]=f.default.useState(a.state),[d,e]=(0,f.useOptimistic)(b),h=(0,f.useMemo)(()=>d,[d]);return(0,g.isThenable)(h)?(0,f.use)(h):h}("function"==typeof c.default||"object"==typeof c.default&&null!==c.default)&&void 0===c.default.__esModule&&(Object.defineProperty(c.default,"__esModule",{value:!0}),Object.assign(c.default,c),b.exports=c.default)},20611,(a,b,c)=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0}),Object.defineProperty(c,"callServer",{enumerable:!0,get:function(){return g}});let d=a.r(72131),e=a.r(88347),f=a.r(90841);async function g(a,b){return new Promise((c,g)=>{(0,d.startTransition)(()=>{(0,f.dispatchAppRouterAction)({type:e.ACTION_SERVER_ACTION,actionId:a,actionArgs:b,resolve:c,reject:g})})})}("function"==typeof c.default||"object"==typeof c.default&&null!==c.default)&&void 0===c.default.__esModule&&(Object.defineProperty(c.default,"__esModule",{value:!0}),Object.assign(c.default,c),b.exports=c.default)},1722,(a,b,c)=>{"use strict";let d;Object.defineProperty(c,"__esModule",{value:!0}),Object.defineProperty(c,"findSourceMapURL",{enumerable:!0,get:function(){return d}});("function"==typeof c.default||"object"==typeof c.default&&null!==c.default)&&void 0===c.default.__esModule&&(Object.defineProperty(c.default,"__esModule",{value:!0}),Object.assign(c.default,c),b.exports=c.default)},5050,(a,b,c)=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});var d={callServer:function(){return f.callServer},createServerReference:function(){return h.createServerReference},findSourceMapURL:function(){return g.findSourceMapURL}};for(var e in d)Object.defineProperty(c,e,{enumerable:!0,get:d[e]});let f=a.r(20611),g=a.r(1722),h=a.r(38783)},43463,a=>{"use strict";var b=a.i(5050);let c=(0,b.createServerReference)("0023e36be111cb5a102352dbb3d18fdcbd71df69ce",b.callServer,void 0,b.findSourceMapURL,"getTelemetryConfig");a.s(["getTelemetryConfig",0,c])},3171,a=>{"use strict";var b=a.i(87924),c=a.i(72131),d=a.i(43463),e=a.i(66036);a.s(["default",0,function({error:a,reset:f}){return(0,c.useEffect)(()=>{(0,d.getTelemetryConfig)().then(b=>{(0,e.setClientTelemetryConfig)(b),(0,e.captureClientEvent)("client_error",{error_message:a.message,error_name:a.name,error_digest:a.digest,boundary:"global"})}).catch(()=>{})},[a]),(0,b.jsx)("html",{children:(0,b.jsx)("body",{children:(0,b.jsx)("main",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",background:"#031035",color:"#f8fafc",fontFamily:"system-ui, sans-serif"},children:(0,b.jsxs)("div",{style:{textAlign:"center",padding:"2rem",border:"1px solid rgba(239,68,68,0.4)",borderRadius:"0.5rem",maxWidth:"500px"},children:[(0,b.jsx)("h2",{style:{color:"#ef4444",marginBottom:"0.5rem",fontSize:"1.25rem"},children:"Something went wrong"}),(0,b.jsx)("p",{style:{color:"#94a3b8",marginBottom:"1.5rem"},children:a.message||"An unexpected error occurred."}),(0,b.jsx)("button",{onClick:f,style:{padding:"0.5rem 1.25rem",background:"#3b82f6",color:"white",border:"none",borderRadius:"0.375rem",cursor:"pointer",fontSize:"0.875rem"},children:"Try again"})]})})})})}])}];
2
2
 
3
- //# sourceMappingURL=%5Broot-of-the-server%5D__0h3orxc._.js.map
3
+ //# sourceMappingURL=%5Broot-of-the-server%5D__0.f_cyx._.js.map
@@ -1,3 +1,3 @@
1
- module.exports=[14747,(a,b,c)=>{b.exports=a.x("path",()=>require("path"))},46786,(a,b,c)=>{b.exports=a.x("os",()=>require("os"))},27950,45481,87532,24451,a=>{"use strict";a.s(["FILTER_PRESETS",0,[{value:"all",label:"All"},{value:"last-hour",label:"Last Hour"},{value:"today",label:"Today"},{value:"last-7-days",label:"Last 7 Days"},{value:"last-30-days",label:"Last 30 Days"}],"ITEMS_PER_PAGE",0,25,"filterByDate",0,function(a,b,c){if("all"===b)return a;if("custom"===b){let b,d,e=c.from?((b=new Date(c.from)).setHours(0,0,0,0),b):null,f=c.to?((d=new Date(c.to)).setHours(23,59,59,999),d):null;return a.filter(a=>(!e||!(a.lastModified<e))&&(!f||!(a.lastModified>f)))}let d=function(a){let b=new Date;switch(a){case"last-hour":return new Date(b.getTime()-36e5);case"today":return new Date(b.getFullYear(),b.getMonth(),b.getDate());case"last-7-days":return new Date(b.getTime()-6048e5);case"last-30-days":return new Date(b.getTime()-2592e6);default:return null}}(b);return d?a.filter(a=>a.lastModified>=d):a},"rehydrateDates",0,function(a){return a.map(a=>({...a,lastModified:a.lastModified instanceof Date?a.lastModified:new Date(a.lastModified)}))}],27950);var b=a.i(72131);a.s(["useFilterState",0,function(a=[],c){let[d,e]=(0,b.useState)(c?.filterPreset??"all"),[f,g]=(0,b.useState)(c?.dateRange??{from:null,to:null}),[h,i]=(0,b.useState)(c?.currentPage??1),j=`${d}|${JSON.stringify(f)}|${JSON.stringify(a)}`,[k,l]=(0,b.useState)(j);j!==k&&(l(j),i(1));let m=(0,b.useCallback)(a=>{e(a),"custom"!==a&&g({from:null,to:null})},[]);return{filterPreset:d,dateRange:f,currentPage:h,setCurrentPage:i,handlePresetChange:m,handleDateRangeChange:(0,b.useCallback)((a,b)=>{e("custom"),g(c=>({...c,[a]:b?new Date(b):null}))},[]),clearFilters:(0,b.useCallback)(()=>{e("all"),g({from:null,to:null})},[])}}],45481);var c=a.i(70106);let d=(0,c.default)("search",[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]);a.s(["Search",0,d],87532);var e=a.i(87924);let f=(0,c.default)("calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]);a.s(["default",0,function({id:a,value:b,stringValue:c,onChange:d,"aria-label":g}){let h=null!=c?c:b?b.toISOString().split("T")[0]:"";return(0,e.jsxs)("div",{className:"relative group",children:[(0,e.jsx)("input",{type:"date",id:a,value:h,onChange:a=>d(a.target.value),"aria-label":g,className:"date-input px-3 py-2 pr-8 text-sm bg-input border border-border rounded-md text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent transition-all hover:border-primary/50 w-[200px]"}),(0,e.jsx)("label",{htmlFor:a,className:"absolute right-2.5 top-1/2 -translate-y-1/2 cursor-pointer pointer-events-auto z-10 p-1 rounded hover:bg-muted/50 transition-colors",onClick:b=>{b.preventDefault();let c=document.getElementById(a);c&&"function"==typeof c.showPicker?c.showPicker():c?.click()},children:(0,e.jsx)(f,{className:"w-4 h-4 text-primary group-hover:text-primary/80 transition-colors"})})]})}],24451)},90619,95947,a=>{"use strict";var b=a.i(50944),c=a.i(72131);function d(a){let b=a.getFullYear(),c=String(a.getMonth()+1).padStart(2,"0"),d=String(a.getDate()).padStart(2,"0");return`${b}-${c}-${d}`}function e(a){var b;if(!a||(b=a,!/^\d{4}-\d{2}-\d{2}$/.test(b)||isNaN(Date.parse(b))))return null;let[c,d,e]=a.split("-").map(Number);return new Date(c,d-1,e,12,0,0)}a.s(["useUrlParams",0,function(){let a=(0,b.useSearchParams)(),d=(0,b.useRouter)(),e=(0,b.usePathname)(),f=(0,c.useRef)(null),g=(0,c.useCallback)(b=>a.get(b),[a]),h=(0,c.useCallback)(()=>new URLSearchParams(a.toString()),[a]),i=(0,c.useCallback)(b=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{let c=new URLSearchParams(a.toString());for(let[a,d]of Object.entries(b))void 0===d||""===d?c.delete(a):c.set(a,d);let f=c.toString(),g=f?`${e}?${f}`:e;d.replace(g,{scroll:!1})},150)},[a,e,d]);return(0,c.useEffect)(()=>()=>{f.current&&clearTimeout(f.current)},[]),{get:g,getAll:h,setAll:i}}],90619),a.s(["dateRangeToParams",0,function(a){let b={};return a.from&&(b.from=d(a.from)),a.to&&(b.to=d(a.to)),b},"keywordsToParam",0,function(a){if(0!==a.length)return a.map(a=>encodeURIComponent(a)).join(",")},"pageToParam",0,function(a){return a<=1?void 0:String(a)},"paramToKeywords",0,function(a){return a?a.split(",").map(a=>decodeURIComponent(a.trim())).filter(a=>a.length>0):[]},"paramToPage",0,function(a){if(!a)return 1;let b=parseInt(a,10);return Number.isFinite(b)&&b>=1?b:1},"paramToPreset",0,function(a){return a&&["all","last-hour","today","last-7-days","last-30-days","custom"].includes(a)?a:"all"},"paramsToDateRange",0,function(a,b){return{from:e(a),to:e(b)}},"presetToParam",0,function(a){return"all"===a?void 0:a}],95947)},65967,a=>{"use strict";var b=a.i(87924),c=a.i(70106);let d=(0,c.default)("chevron-left",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),e=(0,c.default)("chevron-right",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);a.s(["default",0,function({currentPage:a,totalPages:c,onPageChange:f}){if(c<=1)return null;let g=a=>`px-3 py-2 text-sm rounded-md transition-colors flex items-center gap-1 bg-muted text-muted-foreground ${a?"opacity-50 cursor-not-allowed":"hover:bg-muted/80"}`;return(0,b.jsxs)("div",{className:"flex items-center justify-center gap-2 py-4",children:[(0,b.jsxs)("button",{onClick:()=>f(a-1),disabled:1===a,className:g(1===a),"aria-label":"Previous page",children:[(0,b.jsx)(d,{className:"w-4 h-4"}),(0,b.jsx)("span",{className:"hidden sm:inline",children:"Previous"})]}),(0,b.jsx)("div",{className:"flex items-center gap-1",children:(()=>{if(c<=7)return Array.from({length:c},(a,b)=>b+1);let b=[1],d=Math.max(2,a-1),e=Math.min(c-1,a+1);a<=3&&(e=Math.min(5,c-1)),a>=c-2&&(d=Math.max(2,c-4)),d>2&&b.push("ellipsis-start");for(let a=d;a<=e;a++)b.push(a);return e<c-1&&b.push("ellipsis-end"),b.push(c),b})().map(c=>"string"==typeof c?(0,b.jsx)("span",{className:"px-2 text-muted-foreground",children:"..."},c):(0,b.jsx)("button",{onClick:()=>f(c),className:`min-w-[2.5rem] px-3 py-2 text-sm rounded-md transition-colors ${a===c?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:bg-muted/80"}`,"aria-label":`Page ${c}`,"aria-current":a===c?"page":void 0,children:c},c))}),(0,b.jsxs)("button",{onClick:()=>f(a+1),disabled:a===c,className:g(a===c),"aria-label":"Next page",children:[(0,b.jsx)("span",{className:"hidden sm:inline",children:"Next"}),(0,b.jsx)(e,{className:"w-4 h-4"})]})]})}],65967)},33508,a=>{"use strict";let b=(0,a.i(70106).default)("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);a.s(["X",0,b],33508)},69349,a=>{"use strict";var b=a.i(87924),c=a.i(72131);a.i(46786),a.i(14747);var d=a.i(97895),e=a.i(27950),f=a.i(45481),g=a.i(90619),h=a.i(95947);let i=(0,a.i(70106).default)("folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);var j=a.i(87532),k=a.i(33508),l=a.i(38246),m=a.i(65967),n=a.i(24451);function o({date:a,formatted:c}){return(0,b.jsx)("span",{children:c||(0,d.formatDate)(a)})}a.s(["default",0,function({folders:a}){let d=(0,g.useUrlParams)(),p=(0,c.useRef)(!1),[q,r]=(0,c.useState)(()=>(0,h.paramToKeywords)(d.get("q"))),[s,t]=(0,c.useState)(""),{filterPreset:u,dateRange:v,currentPage:w,setCurrentPage:x,handlePresetChange:y,handleDateRangeChange:z,clearFilters:A}=(0,f.useFilterState)(q,{filterPreset:(0,h.paramToPreset)(d.get("preset")),dateRange:(0,h.paramsToDateRange)(d.get("from"),d.get("to")),currentPage:(0,h.paramToPage)(d.get("page"))});(0,c.useEffect)(()=>{if(!p.current){p.current=!0;return}d.setAll({preset:(0,h.presetToParam)(u),...(0,h.dateRangeToParams)(v),q:(0,h.keywordsToParam)(q),page:(0,h.pageToParam)(w)})},[u,v,q,w]);let B=a=>{let b=a.trim();b&&!q.includes(b)&&(r([...q,b]),t(""))},C=()=>{r([]),t("")},D=(0,c.useMemo)(()=>(0,e.rehydrateDates)(a),[a]),E=(0,c.useMemo)(()=>{let a=(0,e.filterByDate)(D,u,v);return q.length>0&&(a=a.filter(a=>{let b=a.name.toLowerCase();return q.every(a=>{let c=a.trim().toLowerCase().replace(/\//g,"-");return 0===c.length||b.includes(c)})})),a.sort((a,b)=>b.lastModified.getTime()-a.lastModified.getTime())},[D,u,v,q]),F=Math.max(1,Math.ceil(E.length/e.ITEMS_PER_PAGE));(0,c.useEffect)(()=>{w>F&&x(F)},[w,F,x]);let G=(w-1)*e.ITEMS_PER_PAGE,H=Math.min(G+e.ITEMS_PER_PAGE,E.length),I=E.slice(G,H);return(0,b.jsxs)("div",{className:"space-y-4",children:[(0,b.jsx)("div",{className:"bg-card border border-border rounded-lg p-4",children:(0,b.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,b.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,b.jsx)("span",{className:"text-sm font-medium text-foreground",children:"Filter by:"}),e.FILTER_PRESETS.map(a=>(0,b.jsx)("button",{onClick:()=>y(a.value),className:`px-3 py-1.5 text-sm rounded-md transition-colors ${u===a.value?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:bg-muted/80"}`,children:a.label},a.value))]}),(0,b.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,b.jsxs)("div",{className:"flex items-center gap-2",children:[(0,b.jsx)(j.Search,{className:"w-4 h-4 text-muted-foreground"}),(0,b.jsx)("span",{className:"text-sm font-medium text-foreground",children:"Search Keywords:"})]}),(0,b.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,b.jsxs)("div",{className:"flex items-center gap-2",children:[(0,b.jsx)("input",{type:"text",value:s,onChange:a=>t(a.target.value),onKeyDown:a=>{"Enter"===a.key&&(a.preventDefault(),B(s))},placeholder:"Enter keyword and press Enter",className:"px-3 py-2 text-sm bg-input border border-border rounded-md text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent transition-all hover:border-primary/50 w-[250px]","aria-label":"Add keyword"}),(0,b.jsx)("button",{onClick:()=>B(s),className:"px-3 py-2 text-sm bg-muted text-muted-foreground hover:bg-muted/80 rounded-md transition-colors","aria-label":"Add keyword",children:"Add"})]}),q.length>0&&(0,b.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[q.map((a,c)=>(0,b.jsxs)("div",{className:"flex items-center gap-1.5 px-3 py-1.5 bg-muted text-muted-foreground rounded-md text-sm",children:[(0,b.jsx)("span",{children:a}),(0,b.jsx)("button",{onClick:()=>{r(q.filter((a,b)=>b!==c))},className:"hover:text-foreground transition-colors p-0.5 rounded hover:bg-muted/80","aria-label":`Remove keyword ${a}`,children:(0,b.jsx)(k.X,{className:"w-3.5 h-3.5"})})]},c)),(0,b.jsx)("button",{onClick:C,className:"px-2 py-1.5 text-xs bg-muted text-muted-foreground hover:bg-muted/80 rounded-md transition-colors","aria-label":"Clear all keywords",children:"Clear all"})]})]})]}),(0,b.jsxs)("div",{className:"flex flex-wrap items-center gap-4",children:[(0,b.jsx)("span",{className:"text-sm font-medium text-foreground",children:"Custom Range:"}),(0,b.jsxs)("div",{className:"flex items-center gap-2",children:[(0,b.jsx)(n.default,{id:"date-from",value:v.from,onChange:a=>z("from",a),"aria-label":"Filter from date"}),(0,b.jsx)("span",{className:"text-muted-foreground",children:"to"}),(0,b.jsx)(n.default,{id:"date-to",value:v.to,onChange:a=>z("to",a),"aria-label":"Filter to date"})]}),("all"!==u||null!==v.from||null!==v.to||q.length>0)&&(0,b.jsx)("button",{onClick:()=>{A(),C()},className:"px-3 py-2 text-sm bg-muted text-muted-foreground hover:bg-muted/80 rounded-md transition-colors",children:"Clear"})]}),(0,b.jsx)("div",{className:"text-sm text-muted-foreground",children:0===E.length?(0,b.jsx)(b.Fragment,{children:"No projects found"}):(0,b.jsxs)(b.Fragment,{children:["Showing ",G+1,"-",H," of ",E.length," projects",E.length!==D.length&&(0,b.jsxs)("span",{className:"ml-1",children:["(filtered from ",D.length," total)"]}),q.length>0&&(0,b.jsxs)("span",{className:"ml-1",children:["with ",q.length," keyword",1!==q.length?"s":""]})]})})]})}),(0,b.jsxs)("div",{className:"bg-card border border-border rounded-lg overflow-hidden",children:[(0,b.jsx)("div",{className:"overflow-x-auto",children:(0,b.jsxs)("table",{className:"w-full",children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{className:"border-b border-border bg-muted/50",children:[(0,b.jsx)("th",{scope:"col",className:"px-4 py-3 text-left text-sm font-semibold text-foreground w-12",children:(0,b.jsx)("span",{className:"sr-only",children:"Icon"})}),(0,b.jsx)("th",{scope:"col",className:"px-4 py-3 text-left text-sm font-semibold text-foreground max-w-md",children:"Agent Root"}),(0,b.jsx)("th",{scope:"col",className:"px-4 py-3 text-left text-sm font-semibold text-foreground hidden md:table-cell",children:"Path"}),(0,b.jsx)("th",{scope:"col",className:"px-4 py-3 text-left text-sm font-semibold text-foreground",children:"Last Modified"})]})}),(0,b.jsx)("tbody",{children:0===I.length?(0,b.jsx)("tr",{children:(0,b.jsx)("td",{colSpan:4,className:"px-4 py-8 text-center text-muted-foreground",children:"No projects found matching the selected filter."})}):I.map(a=>{var c;return(0,b.jsxs)("tr",{className:"border-b border-border hover:bg-muted/50 transition-colors",children:[(0,b.jsx)("td",{className:"px-4 py-3",children:(0,b.jsx)(i,{className:"w-5 h-5 text-primary"})}),(0,b.jsx)("td",{className:"px-4 py-3 max-w-md",children:(0,b.jsx)(l.default,{href:`/project/${encodeURIComponent(a.name)}`,className:"font-semibold text-foreground hover:text-primary transition-colors break-words break-all inline-block max-w-full",children:(c=a.name,/^[A-Za-z]--/.test(c)?c[0]+":/"+c.slice(3).replace(/-/g,"/"):c.replace(/-/g,"/"))})}),(0,b.jsx)("td",{className:"px-4 py-3 text-sm text-muted-foreground hidden md:table-cell truncate max-w-md",children:a.path}),(0,b.jsx)("td",{className:"px-4 py-3 text-sm text-muted-foreground",children:(0,b.jsx)(o,{date:a.lastModified,formatted:a.lastModifiedFormatted})})]},a.name)})})]})}),E.length>0&&(0,b.jsx)(m.default,{currentPage:w,totalPages:F,onPageChange:x})]})]})}],69349)}];
1
+ module.exports=[14747,(a,b,c)=>{b.exports=a.x("path",()=>require("path"))},46786,(a,b,c)=>{b.exports=a.x("os",()=>require("os"))},27950,45481,33540,24451,a=>{"use strict";a.s(["FILTER_PRESETS",0,[{value:"all",label:"All"},{value:"last-hour",label:"Last Hour"},{value:"today",label:"Today"},{value:"last-7-days",label:"Last 7 Days"},{value:"last-30-days",label:"Last 30 Days"}],"ITEMS_PER_PAGE",0,25,"filterByDate",0,function(a,b,c){if("all"===b)return a;if("custom"===b){let b,d,e=c.from?((b=new Date(c.from)).setHours(0,0,0,0),b):null,f=c.to?((d=new Date(c.to)).setHours(23,59,59,999),d):null;return a.filter(a=>(!e||!(a.lastModified<e))&&(!f||!(a.lastModified>f)))}let d=function(a){let b=new Date;switch(a){case"last-hour":return new Date(b.getTime()-36e5);case"today":return new Date(b.getFullYear(),b.getMonth(),b.getDate());case"last-7-days":return new Date(b.getTime()-6048e5);case"last-30-days":return new Date(b.getTime()-2592e6);default:return null}}(b);return d?a.filter(a=>a.lastModified>=d):a},"rehydrateDates",0,function(a){return a.map(a=>({...a,lastModified:a.lastModified instanceof Date?a.lastModified:new Date(a.lastModified)}))}],27950);var b=a.i(72131);a.s(["useFilterState",0,function(a=[],c){let[d,e]=(0,b.useState)(c?.filterPreset??"all"),[f,g]=(0,b.useState)(c?.dateRange??{from:null,to:null}),[h,i]=(0,b.useState)(c?.currentPage??1),j=`${d}|${JSON.stringify(f)}|${JSON.stringify(a)}`,[k,l]=(0,b.useState)(j);j!==k&&(l(j),i(1));let m=(0,b.useCallback)(a=>{e(a),"custom"!==a&&g({from:null,to:null})},[]);return{filterPreset:d,dateRange:f,currentPage:h,setCurrentPage:i,handlePresetChange:m,handleDateRangeChange:(0,b.useCallback)((a,b)=>{e("custom"),g(c=>({...c,[a]:b?new Date(b):null}))},[]),clearFilters:(0,b.useCallback)(()=>{e("all"),g({from:null,to:null})},[])}}],45481);var c=a.i(64831);let d=(0,c.default)("search",[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]);a.s(["Search",0,d],33540);var e=a.i(87924);let f=(0,c.default)("calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]);a.s(["default",0,function({id:a,value:b,stringValue:c,onChange:d,"aria-label":g}){let h=null!=c?c:b?b.toISOString().split("T")[0]:"";return(0,e.jsxs)("div",{className:"relative group",children:[(0,e.jsx)("input",{type:"date",id:a,value:h,onChange:a=>d(a.target.value),"aria-label":g,className:"date-input px-3 py-2 pr-8 text-sm bg-input border border-border rounded-md text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent transition-all hover:border-primary/50 w-[200px]"}),(0,e.jsx)("label",{htmlFor:a,className:"absolute right-2.5 top-1/2 -translate-y-1/2 cursor-pointer pointer-events-auto z-10 p-1 rounded hover:bg-muted/50 transition-colors",onClick:b=>{b.preventDefault();let c=document.getElementById(a);c&&"function"==typeof c.showPicker?c.showPicker():c?.click()},children:(0,e.jsx)(f,{className:"w-4 h-4 text-primary group-hover:text-primary/80 transition-colors"})})]})}],24451)},90619,95947,a=>{"use strict";var b=a.i(50944),c=a.i(72131);function d(a){let b=a.getFullYear(),c=String(a.getMonth()+1).padStart(2,"0"),d=String(a.getDate()).padStart(2,"0");return`${b}-${c}-${d}`}function e(a){var b;if(!a||(b=a,!/^\d{4}-\d{2}-\d{2}$/.test(b)||isNaN(Date.parse(b))))return null;let[c,d,e]=a.split("-").map(Number);return new Date(c,d-1,e,12,0,0)}a.s(["useUrlParams",0,function(){let a=(0,b.useSearchParams)(),d=(0,b.useRouter)(),e=(0,b.usePathname)(),f=(0,c.useRef)(null),g=(0,c.useCallback)(b=>a.get(b),[a]),h=(0,c.useCallback)(()=>new URLSearchParams(a.toString()),[a]),i=(0,c.useCallback)(b=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{let c=new URLSearchParams(a.toString());for(let[a,d]of Object.entries(b))void 0===d||""===d?c.delete(a):c.set(a,d);let f=c.toString(),g=f?`${e}?${f}`:e;d.replace(g,{scroll:!1})},150)},[a,e,d]);return(0,c.useEffect)(()=>()=>{f.current&&clearTimeout(f.current)},[]),{get:g,getAll:h,setAll:i}}],90619),a.s(["dateRangeToParams",0,function(a){let b={};return a.from&&(b.from=d(a.from)),a.to&&(b.to=d(a.to)),b},"keywordsToParam",0,function(a){if(0!==a.length)return a.map(a=>encodeURIComponent(a)).join(",")},"pageToParam",0,function(a){return a<=1?void 0:String(a)},"paramToKeywords",0,function(a){return a?a.split(",").map(a=>decodeURIComponent(a.trim())).filter(a=>a.length>0):[]},"paramToPage",0,function(a){if(!a)return 1;let b=parseInt(a,10);return Number.isFinite(b)&&b>=1?b:1},"paramToPreset",0,function(a){return a&&["all","last-hour","today","last-7-days","last-30-days","custom"].includes(a)?a:"all"},"paramsToDateRange",0,function(a,b){return{from:e(a),to:e(b)}},"presetToParam",0,function(a){return"all"===a?void 0:a}],95947)},65967,a=>{"use strict";var b=a.i(87924),c=a.i(64831);let d=(0,c.default)("chevron-left",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),e=(0,c.default)("chevron-right",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);a.s(["default",0,function({currentPage:a,totalPages:c,onPageChange:f}){if(c<=1)return null;let g=a=>`px-3 py-2 text-sm rounded-md transition-colors flex items-center gap-1 bg-muted text-muted-foreground ${a?"opacity-50 cursor-not-allowed":"hover:bg-muted/80"}`;return(0,b.jsxs)("div",{className:"flex items-center justify-center gap-2 py-4",children:[(0,b.jsxs)("button",{onClick:()=>f(a-1),disabled:1===a,className:g(1===a),"aria-label":"Previous page",children:[(0,b.jsx)(d,{className:"w-4 h-4"}),(0,b.jsx)("span",{className:"hidden sm:inline",children:"Previous"})]}),(0,b.jsx)("div",{className:"flex items-center gap-1",children:(()=>{if(c<=7)return Array.from({length:c},(a,b)=>b+1);let b=[1],d=Math.max(2,a-1),e=Math.min(c-1,a+1);a<=3&&(e=Math.min(5,c-1)),a>=c-2&&(d=Math.max(2,c-4)),d>2&&b.push("ellipsis-start");for(let a=d;a<=e;a++)b.push(a);return e<c-1&&b.push("ellipsis-end"),b.push(c),b})().map(c=>"string"==typeof c?(0,b.jsx)("span",{className:"px-2 text-muted-foreground",children:"..."},c):(0,b.jsx)("button",{onClick:()=>f(c),className:`min-w-[2.5rem] px-3 py-2 text-sm rounded-md transition-colors ${a===c?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:bg-muted/80"}`,"aria-label":`Page ${c}`,"aria-current":a===c?"page":void 0,children:c},c))}),(0,b.jsxs)("button",{onClick:()=>f(a+1),disabled:a===c,className:g(a===c),"aria-label":"Next page",children:[(0,b.jsx)("span",{className:"hidden sm:inline",children:"Next"}),(0,b.jsx)(e,{className:"w-4 h-4"})]})]})}],65967)},74215,a=>{"use strict";let b=(0,a.i(64831).default)("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);a.s(["X",0,b],74215)},69349,a=>{"use strict";var b=a.i(87924),c=a.i(72131);a.i(46786),a.i(14747);var d=a.i(97895),e=a.i(27950),f=a.i(45481),g=a.i(90619),h=a.i(95947);let i=(0,a.i(64831).default)("folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);var j=a.i(33540),k=a.i(74215),l=a.i(38246),m=a.i(65967),n=a.i(24451);function o({date:a,formatted:c}){return(0,b.jsx)("span",{children:c||(0,d.formatDate)(a)})}a.s(["default",0,function({folders:a}){let d=(0,g.useUrlParams)(),p=(0,c.useRef)(!1),[q,r]=(0,c.useState)(()=>(0,h.paramToKeywords)(d.get("q"))),[s,t]=(0,c.useState)(""),{filterPreset:u,dateRange:v,currentPage:w,setCurrentPage:x,handlePresetChange:y,handleDateRangeChange:z,clearFilters:A}=(0,f.useFilterState)(q,{filterPreset:(0,h.paramToPreset)(d.get("preset")),dateRange:(0,h.paramsToDateRange)(d.get("from"),d.get("to")),currentPage:(0,h.paramToPage)(d.get("page"))});(0,c.useEffect)(()=>{if(!p.current){p.current=!0;return}d.setAll({preset:(0,h.presetToParam)(u),...(0,h.dateRangeToParams)(v),q:(0,h.keywordsToParam)(q),page:(0,h.pageToParam)(w)})},[u,v,q,w]);let B=a=>{let b=a.trim();b&&!q.includes(b)&&(r([...q,b]),t(""))},C=()=>{r([]),t("")},D=(0,c.useMemo)(()=>(0,e.rehydrateDates)(a),[a]),E=(0,c.useMemo)(()=>{let a=(0,e.filterByDate)(D,u,v);return q.length>0&&(a=a.filter(a=>{let b=a.name.toLowerCase();return q.every(a=>{let c=a.trim().toLowerCase().replace(/\//g,"-");return 0===c.length||b.includes(c)})})),a.sort((a,b)=>b.lastModified.getTime()-a.lastModified.getTime())},[D,u,v,q]),F=Math.max(1,Math.ceil(E.length/e.ITEMS_PER_PAGE));(0,c.useEffect)(()=>{w>F&&x(F)},[w,F,x]);let G=(w-1)*e.ITEMS_PER_PAGE,H=Math.min(G+e.ITEMS_PER_PAGE,E.length),I=E.slice(G,H);return(0,b.jsxs)("div",{className:"space-y-4",children:[(0,b.jsx)("div",{className:"bg-card border border-border rounded-lg p-4",children:(0,b.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,b.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,b.jsx)("span",{className:"text-sm font-medium text-foreground",children:"Filter by:"}),e.FILTER_PRESETS.map(a=>(0,b.jsx)("button",{onClick:()=>y(a.value),className:`px-3 py-1.5 text-sm rounded-md transition-colors ${u===a.value?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:bg-muted/80"}`,children:a.label},a.value))]}),(0,b.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,b.jsxs)("div",{className:"flex items-center gap-2",children:[(0,b.jsx)(j.Search,{className:"w-4 h-4 text-muted-foreground"}),(0,b.jsx)("span",{className:"text-sm font-medium text-foreground",children:"Search Keywords:"})]}),(0,b.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,b.jsxs)("div",{className:"flex items-center gap-2",children:[(0,b.jsx)("input",{type:"text",value:s,onChange:a=>t(a.target.value),onKeyDown:a=>{"Enter"===a.key&&(a.preventDefault(),B(s))},placeholder:"Enter keyword and press Enter",className:"px-3 py-2 text-sm bg-input border border-border rounded-md text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent transition-all hover:border-primary/50 w-[250px]","aria-label":"Add keyword"}),(0,b.jsx)("button",{onClick:()=>B(s),className:"px-3 py-2 text-sm bg-muted text-muted-foreground hover:bg-muted/80 rounded-md transition-colors","aria-label":"Add keyword",children:"Add"})]}),q.length>0&&(0,b.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[q.map((a,c)=>(0,b.jsxs)("div",{className:"flex items-center gap-1.5 px-3 py-1.5 bg-muted text-muted-foreground rounded-md text-sm",children:[(0,b.jsx)("span",{children:a}),(0,b.jsx)("button",{onClick:()=>{r(q.filter((a,b)=>b!==c))},className:"hover:text-foreground transition-colors p-0.5 rounded hover:bg-muted/80","aria-label":`Remove keyword ${a}`,children:(0,b.jsx)(k.X,{className:"w-3.5 h-3.5"})})]},c)),(0,b.jsx)("button",{onClick:C,className:"px-2 py-1.5 text-xs bg-muted text-muted-foreground hover:bg-muted/80 rounded-md transition-colors","aria-label":"Clear all keywords",children:"Clear all"})]})]})]}),(0,b.jsxs)("div",{className:"flex flex-wrap items-center gap-4",children:[(0,b.jsx)("span",{className:"text-sm font-medium text-foreground",children:"Custom Range:"}),(0,b.jsxs)("div",{className:"flex items-center gap-2",children:[(0,b.jsx)(n.default,{id:"date-from",value:v.from,onChange:a=>z("from",a),"aria-label":"Filter from date"}),(0,b.jsx)("span",{className:"text-muted-foreground",children:"to"}),(0,b.jsx)(n.default,{id:"date-to",value:v.to,onChange:a=>z("to",a),"aria-label":"Filter to date"})]}),("all"!==u||null!==v.from||null!==v.to||q.length>0)&&(0,b.jsx)("button",{onClick:()=>{A(),C()},className:"px-3 py-2 text-sm bg-muted text-muted-foreground hover:bg-muted/80 rounded-md transition-colors",children:"Clear"})]}),(0,b.jsx)("div",{className:"text-sm text-muted-foreground",children:0===E.length?(0,b.jsx)(b.Fragment,{children:"No projects found"}):(0,b.jsxs)(b.Fragment,{children:["Showing ",G+1,"-",H," of ",E.length," projects",E.length!==D.length&&(0,b.jsxs)("span",{className:"ml-1",children:["(filtered from ",D.length," total)"]}),q.length>0&&(0,b.jsxs)("span",{className:"ml-1",children:["with ",q.length," keyword",1!==q.length?"s":""]})]})})]})}),(0,b.jsxs)("div",{className:"bg-card border border-border rounded-lg overflow-hidden",children:[(0,b.jsx)("div",{className:"overflow-x-auto",children:(0,b.jsxs)("table",{className:"w-full",children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{className:"border-b border-border bg-muted/50",children:[(0,b.jsx)("th",{scope:"col",className:"px-4 py-3 text-left text-sm font-semibold text-foreground w-12",children:(0,b.jsx)("span",{className:"sr-only",children:"Icon"})}),(0,b.jsx)("th",{scope:"col",className:"px-4 py-3 text-left text-sm font-semibold text-foreground max-w-md",children:"Agent Root"}),(0,b.jsx)("th",{scope:"col",className:"px-4 py-3 text-left text-sm font-semibold text-foreground hidden md:table-cell",children:"Path"}),(0,b.jsx)("th",{scope:"col",className:"px-4 py-3 text-left text-sm font-semibold text-foreground",children:"Last Modified"})]})}),(0,b.jsx)("tbody",{children:0===I.length?(0,b.jsx)("tr",{children:(0,b.jsx)("td",{colSpan:4,className:"px-4 py-8 text-center text-muted-foreground",children:"No projects found matching the selected filter."})}):I.map(a=>{var c;return(0,b.jsxs)("tr",{className:"border-b border-border hover:bg-muted/50 transition-colors",children:[(0,b.jsx)("td",{className:"px-4 py-3",children:(0,b.jsx)(i,{className:"w-5 h-5 text-primary"})}),(0,b.jsx)("td",{className:"px-4 py-3 max-w-md",children:(0,b.jsx)(l.default,{href:`/project/${encodeURIComponent(a.name)}`,className:"font-semibold text-foreground hover:text-primary transition-colors break-words break-all inline-block max-w-full",children:(c=a.name,/^[A-Za-z]--/.test(c)?c[0]+":/"+c.slice(3).replace(/-/g,"/"):c.replace(/-/g,"/"))})}),(0,b.jsx)("td",{className:"px-4 py-3 text-sm text-muted-foreground hidden md:table-cell truncate max-w-md",children:a.path}),(0,b.jsx)("td",{className:"px-4 py-3 text-sm text-muted-foreground",children:(0,b.jsx)(o,{date:a.lastModified,formatted:a.lastModifiedFormatted})})]},a.name)})})]})}),E.length>0&&(0,b.jsx)(m.default,{currentPage:w,totalPages:F,onPageChange:x})]})]})}],69349)}];
2
2
 
3
- //# sourceMappingURL=%5Broot-of-the-server%5D__0m72uj7._.js.map
3
+ //# sourceMappingURL=%5Broot-of-the-server%5D__03rd.z8._.js.map