failproofai 1.0.13 → 1.0.14
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.
- package/.next/standalone/.next/BUILD_ID +1 -1
- package/.next/standalone/.next/build-manifest.json +44 -44
- package/.next/standalone/.next/prerender-manifest.json +3 -3
- package/.next/standalone/.next/required-server-files.json +1 -1
- package/.next/standalone/.next/server/app/_global-error/page/build-manifest.json +6 -6
- package/.next/standalone/.next/server/app/_global-error/page/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/server/app/_global-error/page.js +2 -3
- package/.next/standalone/.next/server/app/_global-error/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/_global-error.html +1 -1
- package/.next/standalone/.next/server/app/_global-error.rsc +2 -2
- package/.next/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found/page/build-manifest.json +6 -6
- package/.next/standalone/.next/server/app/_not-found/page/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/server/app/_not-found/page.js +3 -4
- package/.next/standalone/.next/server/app/_not-found/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/_not-found.html +1 -1
- package/.next/standalone/.next/server/app/_not-found.rsc +6 -6
- package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +6 -6
- package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +5 -5
- package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/api/audit/invite/route.js +3 -4
- package/.next/standalone/.next/server/app/api/audit/invite/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/audit/run/route.js +22 -23
- package/.next/standalone/.next/server/app/api/audit/run/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/audit/status/route.js +2 -3
- package/.next/standalone/.next/server/app/api/audit/status/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/auth/login-request/route.js +4 -5
- package/.next/standalone/.next/server/app/api/auth/login-request/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/auth/login-verify/route.js +4 -5
- package/.next/standalone/.next/server/app/api/auth/login-verify/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/auth/logout/route.js +4 -5
- package/.next/standalone/.next/server/app/api/auth/logout/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/auth/status/route.js +3 -4
- package/.next/standalone/.next/server/app/api/auth/status/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/download/[project]/[session]/route.js +2 -3
- package/.next/standalone/.next/server/app/api/download/[project]/[session]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/audit/page/build-manifest.json +6 -6
- package/.next/standalone/.next/server/app/audit/page/server-reference-manifest.json +2 -2
- package/.next/standalone/.next/server/app/audit/page.js +5 -6
- package/.next/standalone/.next/server/app/audit/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/audit/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/index.html +1 -1
- package/.next/standalone/.next/server/app/index.rsc +6 -6
- package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +5 -5
- package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +6 -6
- package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/page/build-manifest.json +6 -6
- package/.next/standalone/.next/server/app/page/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/server/app/page.js +4 -5
- package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/policies/page/build-manifest.json +6 -6
- package/.next/standalone/.next/server/app/policies/page/server-reference-manifest.json +14 -14
- package/.next/standalone/.next/server/app/policies/page.js +4 -5
- package/.next/standalone/.next/server/app/policies/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/policies/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/project/[name]/page/build-manifest.json +6 -6
- package/.next/standalone/.next/server/app/project/[name]/page/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/server/app/project/[name]/page.js +20 -21
- package/.next/standalone/.next/server/app/project/[name]/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/project/[name]/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/build-manifest.json +6 -6
- package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/react-loadable-manifest.json +2 -2
- package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/server-reference-manifest.json +2 -2
- package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page.js +8 -9
- package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/projects/page/build-manifest.json +6 -6
- package/.next/standalone/.next/server/app/projects/page/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/server/app/projects/page.js +6 -7
- package/.next/standalone/.next/server/app/projects/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/projects/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/settings/page/build-manifest.json +6 -6
- package/.next/standalone/.next/server/app/settings/page/server-reference-manifest.json +8 -8
- package/.next/standalone/.next/server/app/settings/page.js +3 -4
- package/.next/standalone/.next/server/app/settings/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/settings/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__1a2d0ewycsp6k._.js → [externals]__0h0p9dmv_e7r7._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__1am_1tz0o0aqz._.js → [externals]__1_407huhlmj1m._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__031qp1lkow_kc._.js → [externals]__1rlxpymm37wel._.js} +2 -2
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__03s1za0hn71yp._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__048f1wnr8pysf._.js +63 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__07a0sa6fuw5_b._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0l-oi4gdtmlo5._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0spt0kv8azrpl._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0yvyp5b7jmlc4._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__145vo_drnuvas._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1lh8c0mmhdrbj._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1oclamblhzhrf._.js +7 -7
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1qjnp3fa0e5g3._.js +3 -0
- package/.next/standalone/.next/server/chunks/[turbopack]_runtime.js +7 -9
- package/.next/standalone/.next/server/chunks/_02sa8fcu9_9xo._.js +1 -1
- package/.next/standalone/.next/server/chunks/_09dz7xva4ce_2._.js +18 -18
- package/.next/standalone/.next/server/chunks/_0hf5q4xzyg40j._.js +1 -1
- package/.next/standalone/.next/server/chunks/_0tovk6q0miud6._.js +1 -1
- package/.next/standalone/.next/server/chunks/_0trp3ycqv17cl._.js +1 -1
- package/.next/standalone/.next/server/chunks/_1-2owkp-1_987._.js +1 -1
- package/.next/standalone/.next/server/chunks/_13ltj8a9z92o8._.js +1 -1
- package/.next/standalone/.next/server/chunks/_15k37au70vjvg._.js +1 -1
- package/.next/standalone/.next/server/chunks/_18rfu4__wjhwb._.js +1 -1
- package/.next/standalone/.next/server/chunks/_19011-u44143j._.js +1 -1
- package/.next/standalone/.next/server/chunks/_1ek68lnh2daur._.js +2 -2
- package/.next/standalone/.next/server/chunks/_1fz8m31sndkcu._.js +1 -1
- package/.next/standalone/.next/server/chunks/_1ogwigfb0163w._.js +1 -1
- package/.next/standalone/.next/server/chunks/_1vslkoe35wok6._.js +1 -1
- package/.next/standalone/.next/server/chunks/lib_11qmqmccehybz._.js +1 -1
- package/.next/standalone/.next/server/chunks/lib_1sezqnatvr8j-._.js +1 -1
- package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_01r25oigsgz07._.js +1 -2
- package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_09z9-p77cu37y._.js +1 -2
- package/.next/standalone/.next/server/chunks/package_json_[json]_cjs_1nxcc4vkpxxu7._.js +1 -1
- package/.next/standalone/.next/server/chunks/src_hooks_0_em82s16zfym._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[externals]__0ilfh9mfnzsth._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/[externals]__0ohnuzsaozaca._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__097i34ct1o88x._.js → [externals]__12qr51qgrrt6o._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__021vebe-4il8s._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__08ch3staq3ejw._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0bigvy9xmv2ka._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0evgy902m9h5e._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0ezoipo-r7_5k._.js +14 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0h1jw32uvrhh0._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0h86bl2qf0k_o._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0pia5h3p8re4c._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__10v5cyxvj64j4._.js → [root-of-the-server]__0tfnj3v_mp6rv._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1-9s1nsw-5q8o._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1-ey9fgesfbc0._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__15bi9em2xe0x2._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__15usvs-ms-0hf._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__16gb3_92zvk5x._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1avi2kypusyb_._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__20dt376-socef._.js → [root-of-the-server]__1e00l_e_8r_-g._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1mc9-zlnh656_._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1ob2uzmms1adf._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1r7drlqli-ado._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0ed1zh4scn7-k._.js → [root-of-the-server]__1tq3x9i_3_860._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1utel1l1-u64v._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1vofkb2oq7p7e._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1vxwetblyf8vp._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1xwr4hi-on27i._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__2158020r_amn9._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[turbopack]_runtime.js +7 -9
- package/.next/standalone/.next/server/chunks/ssr/_0-f9uotv7v2n9._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_00e4_rvim31u_._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_0bseae9u7g98r._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_0eoura3_9gjb-._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/_0kqw2_f1ywmpo._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_0mouhaflye1ro._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_0ouu886szh6yj._.js +10 -10
- package/.next/standalone/.next/server/chunks/ssr/_0p1cb69sml__f._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/_0pedwblqdoh58._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_0tfqha481f033._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/_1_ozgifqv1ssi._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_1a516zcgtqius._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_1ddpc5gj57uuf._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_1djqs9i27e4kg._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_1ew6ra24vt-ij._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_1or8gixmrpv5i._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_1s8zk-upxzp00._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_1u9tpla2o6utw._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_1v4_ul3sj2lq_._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_1y3xzro8ca8t6._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_20hn4gn87nsjc._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_next-internal_server_app_policies_page_actions_1sp2-yo5_vm5f.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/app_087bt9wus25zs._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/app_0trz6ik19xz5_._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/app_1fvisnppn1unv._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/app_209u41o446my6._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/app_actions_get-scheduled-audit_ts_0ei9snixb5fd-._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/app_audit_0hku_y73ischw._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/app_audit__components_audit-dashboard_tsx_0p9ud47q0xq5w._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/app_global-error_tsx_1kp6l3x33jqb6._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/app_policies_hooks-client_tsx_19dqvpcz0uxur._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/app_settings_02tf1h47jmhhd._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/lib_16jvhmthj_k3a._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/node_modules_05vgn62--7c5e._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/node_modules_0dad4au22rq0p._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/node_modules_0gxlxpuufujz9._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/node_modules_0ptcnmeaxvd_a._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/{node_modules_html-to-image_es_index_1cmkmhnty0-x7.js → node_modules_html-to-image_es_index_0r9i9nq3-ei-l.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_0bz67659f5z-3._.js +4 -4
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_0-amwqbrge23p._.js +6 -0
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_0ocrceo0c9psx._.js +4 -4
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_1alv566ojmz5j._.js +4 -4
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_1et9oq9q9-y3v._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_1khq67j4vo9y4._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_client_components_0wpq8j32_ibz4._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_shared_lib_0ftnv26hg1lry._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/node_modules_posthog-node_dist_entrypoints_index_node_mjs_0dagmbznysrc2._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/node_modules_posthog-node_dist_entrypoints_index_node_mjs_11bnuznb72p7z._.js +1 -2
- package/.next/standalone/.next/server/chunks/ssr/package_json_[json]_cjs_013tntikdft59._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/src_hooks_0-q0ummbuhlg5._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/src_hooks_06kzv9ddabn3_._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/src_hooks_0agdmptetetdt._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/src_hooks_0g194syq7r7ql._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/src_hooks_0mdwgjisv4fub._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/src_hooks_1cv9_c4l1tzrm._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/src_hooks_1kx9e0dx_1-8o._.js +1 -1
- package/.next/standalone/.next/server/middleware-build-manifest.js +44 -44
- package/.next/standalone/.next/server/pages/404.html +1 -1
- package/.next/standalone/.next/server/pages/500.html +1 -1
- package/.next/standalone/.next/server/preview-props.json +3 -3
- package/.next/standalone/.next/server/server-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/server-reference-manifest.json +23 -23
- package/.next/standalone/.next/static/chunks/0tiuj32d-qcy3.js +1 -0
- package/.next/standalone/.next/static/chunks/0ztuix-ip2oiv.js +1 -0
- package/.next/standalone/.next/static/chunks/{40g_e46c1-j4k.js → 107jrtkeylnrv.js} +1 -1
- package/.next/standalone/.next/static/chunks/110hwwc6agsr8.js +1 -0
- package/.next/standalone/.next/static/chunks/19e9khxgv8fb8.js +1 -0
- package/.next/standalone/.next/static/chunks/1dudxmlwx2n3q.js +1 -0
- package/.next/standalone/.next/static/chunks/1i9zuw01f0ogt.js +22 -0
- package/.next/standalone/.next/static/chunks/2codb6nb412m9.js +1 -0
- package/.next/standalone/.next/static/chunks/2hqfk_jgesiw2.js +1 -0
- package/.next/standalone/.next/static/chunks/2k6xp6kdy7lmd.js +1 -0
- package/.next/standalone/.next/static/chunks/2maurwweshrsj.js +1 -0
- package/.next/standalone/.next/static/chunks/2wh64znsc_mo2.js +1 -0
- package/.next/standalone/.next/static/chunks/2wye36b3mbzpa.js +31 -0
- package/.next/standalone/.next/static/chunks/{0mm-e5t9denbu.js → 2zlfhyqvlvf7o.js} +1 -1
- package/.next/standalone/.next/static/chunks/3hk5y4kny2ktd.js +1 -0
- package/.next/standalone/.next/static/chunks/3i_9ugyh1q1o1.js +1 -0
- package/.next/standalone/.next/static/chunks/3o30fiw7llng3.js +1 -0
- package/.next/standalone/.next/static/chunks/3v49ogp389dun.js +1 -0
- package/.next/standalone/.next/static/chunks/41ujrab732qi3.css +2 -0
- package/.next/standalone/.next/static/chunks/435eshlryosz1.js +1 -0
- package/.next/standalone/.next/static/chunks/436g_rqa42mr7.js +1 -0
- package/.next/standalone/.next/static/chunks/436nql0jk__xy.js +1 -0
- package/.next/standalone/.next/static/chunks/{turbopack-3-ry682tkyiqk.js → turbopack-2u1d16houkiyo.js} +1 -1
- package/.next/standalone/SECURITY.md +19 -4
- package/.next/standalone/fp-cloud-cli/CHANGELOG.md +13 -3
- package/.next/standalone/fp-cloud-cli/README.md +14 -7
- package/.next/standalone/fp-cloud-cli/fp_cli/_version.py +1 -1
- package/.next/standalone/fp-cloud-cli/fp_cli/app.py +2 -8
- package/.next/standalone/fp-cloud-cli/fp_cli/auth.py +325 -3
- package/.next/standalone/fp-cloud-cli/fp_cli/cloud_output.py +3 -3
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/account_cmds.py +1 -11
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/auth_cmds.py +218 -51
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/orgs_cmds.py +1 -1
- package/.next/standalone/fp-cloud-cli/fp_cli/output.py +112 -135
- package/.next/standalone/fp-cloud-cli/fp_cli/permissions.py +10 -1
- package/.next/standalone/fp-cloud-cli/fp_cli/select.py +85 -6
- package/.next/standalone/fp-cloud-cli/fp_cli/theme.py +21 -21
- package/.next/standalone/fp-cloud-cli/pyproject.toml +1 -1
- package/.next/standalone/fp-cloud-cli/skill/SKILL.md +4 -4
- package/.next/standalone/fp-cloud-cli/skill/references/commands.md +4 -4
- package/.next/standalone/fp-cloud-cli/tests/fake_cloud_smoke.py +2 -2
- package/.next/standalone/fp-cloud-cli/tests/test_browser_login.py +943 -0
- package/.next/standalone/fp-cloud-cli/tests/test_cloud_account.py +0 -2
- package/.next/standalone/fp-cloud-cli/tests/test_cloud_agent.py +4 -8
- package/.next/standalone/fp-cloud-cli/tests/test_cloud_human_views.py +0 -4
- package/.next/standalone/fp-cloud-cli/tests/test_commands.py +3 -3
- package/.next/standalone/fp-cloud-cli/tests/test_dashboards_agent.py +3 -3
- package/.next/standalone/fp-cloud-cli/tests/test_facets.py +1 -1
- package/.next/standalone/fp-cloud-cli/tests/test_keys_queries.py +19 -2
- package/.next/standalone/fp-cloud-cli/tests/test_operator.py +1 -1
- package/.next/standalone/fp-cloud-cli/tests/test_orgs.py +1 -1
- package/.next/standalone/fp-cloud-cli/tests/test_output.py +19 -19
- package/.next/standalone/fp-cloud-cli/tests/test_round4_behaviour.py +3 -2
- package/.next/standalone/fp-cloud-cli/tests/test_screen_language.py +86 -25
- package/.next/standalone/fp-cloud-cli/tests/test_whoami.py +1 -1
- package/.next/standalone/fp-cloud-cli/uv.lock +200 -13
- package/.next/standalone/hermes-plugin/plugin.yaml +1 -1
- package/.next/standalone/node_modules/@next/env/package.json +1 -1
- package/.next/standalone/node_modules/next/dist/build/swc/index.js +1 -1
- package/.next/standalone/node_modules/next/dist/compiled/fast-jwt/index.js +3 -0
- package/.next/standalone/node_modules/next/dist/compiled/fast-jwt/package.json +1 -0
- package/.next/standalone/node_modules/next/dist/compiled/next-server/app-page-turbo-experimental.runtime.prod.js +23 -23
- package/.next/standalone/node_modules/next/dist/compiled/next-server/app-page-turbo.runtime.prod.js +23 -23
- package/.next/standalone/node_modules/next/dist/compiled/next-server/app-route-turbo.runtime.prod.js +1 -1
- package/.next/standalone/node_modules/next/dist/compiled/next-server/pages-turbo.runtime.prod.js +7 -7
- package/.next/standalone/node_modules/next/dist/lib/patch-incorrect-lockfile.js +3 -3
- package/.next/standalone/node_modules/next/dist/server/api-utils/node/api-resolver.js +8 -5
- package/.next/standalone/node_modules/next/dist/server/api-utils/node/try-get-preview-data.js +8 -2
- package/.next/standalone/node_modules/next/dist/server/app-render/app-render.js +52 -14
- package/.next/standalone/node_modules/next/dist/server/app-render/async-local-storage.js +1 -1
- package/.next/standalone/node_modules/next/dist/server/app-render/get-script-nonce-from-header.js +19 -3
- package/.next/standalone/node_modules/next/dist/server/app-render/turbopack-bootstrap-script.js +50 -0
- package/.next/standalone/node_modules/next/dist/server/base-server.js +8 -0
- package/.next/standalone/node_modules/next/dist/server/config.js +1 -1
- package/.next/standalone/node_modules/next/dist/server/dev/hot-reloader-turbopack.js +59 -10
- package/.next/standalone/node_modules/next/dist/server/dev/hot-reloader-webpack.js +1 -1
- package/.next/standalone/node_modules/next/dist/server/dev/turbopack-utils.js +15 -0
- package/.next/standalone/node_modules/next/dist/server/image-optimizer/detect-content-type.js +24 -20
- package/.next/standalone/node_modules/next/dist/server/lib/app-info-log.js +1 -1
- package/.next/standalone/node_modules/next/dist/server/lib/dev-bundler-service.js +3 -0
- package/.next/standalone/node_modules/next/dist/server/lib/router-server.js +1 -1
- package/.next/standalone/node_modules/next/dist/server/lib/start-server.js +1 -1
- package/.next/standalone/node_modules/next/dist/server/lib/trace/tracer.js +1 -1
- package/.next/standalone/node_modules/next/dist/server/next-server.js +10 -2
- package/.next/standalone/node_modules/next/dist/server/render.js +2 -2
- package/.next/standalone/node_modules/next/dist/server/route-modules/app-page/parse-request-headers.js +1 -2
- package/.next/standalone/node_modules/next/dist/server/send-response.js +12 -0
- package/.next/standalone/node_modules/next/dist/server/use-cache/use-cache-wrapper.js +69 -6
- package/.next/standalone/node_modules/next/dist/server/web/adapter.js +5 -1
- package/.next/standalone/node_modules/next/dist/telemetry/anonymous-meta.js +1 -1
- package/.next/standalone/node_modules/next/dist/telemetry/events/swc-load-failure.js +1 -1
- package/.next/standalone/node_modules/next/dist/telemetry/events/version.js +2 -2
- package/.next/standalone/node_modules/next/package.json +10 -10
- package/.next/standalone/package.json +11 -11
- package/.next/standalone/sdk/python/skill/SKILL.md +5 -0
- package/.next/standalone/sdk/python/uv.lock +79 -47
- package/.next/standalone/sdk/typescript/CHANGELOG.md +48 -5
- package/.next/standalone/sdk/typescript/integration/fixtures/langchain-dup-core/package-lock.json +0 -9
- package/.next/standalone/sdk/typescript/integration/fixtures/langchain-dup-core/package.json +2 -1
- package/.next/standalone/sdk/typescript/integration/fixtures/llamaindex-0.11/package-lock.json +72 -44
- package/.next/standalone/sdk/typescript/integration/fixtures/llamaindex-0.11/package.json +2 -1
- package/.next/standalone/sdk/typescript/integration/fixtures/llamaindex-0.12/package-lock.json +72 -44
- package/.next/standalone/sdk/typescript/integration/fixtures/llamaindex-0.12/package.json +3 -0
- package/.next/standalone/sdk/typescript/integration/fixtures/mastra-0/package-lock.json +18 -332
- package/.next/standalone/sdk/typescript/integration/fixtures/mastra-0/package.json +4 -2
- package/.next/standalone/sdk/typescript/integration/fixtures/mastra-1/package-lock.json +925 -296
- package/.next/standalone/sdk/typescript/integration/fixtures/mastra-1/package.json +3 -8
- package/.next/standalone/sdk/typescript/integration/fixtures/nextjs/package-lock.json +279 -277
- package/.next/standalone/sdk/typescript/integration/fixtures/nextjs/package.json +2 -2
- package/.next/standalone/server.js +1 -1
- package/dist/cli.mjs +22 -12
- package/dist/worker.mjs +1 -1
- package/hermes-plugin/plugin.yaml +1 -1
- package/package.json +11 -11
- package/src/hooks/delivery-health.ts +11 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__038kwryp970nh._.js +0 -3
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__08atcie7jzswm._.js +0 -3
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0car70pylmvor._.js +0 -3
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1j6kfp0vzu5rw._.js +0 -3
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1l0ayum_hqqsw._.js +0 -3
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1o9rznwc0w7og._.js +0 -3
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1v1-l-83czzsr._.js +0 -63
- package/.next/standalone/.next/server/chunks/node_modules_@opentelemetry_api_build_esm_index_0oo58a7rymoxh.js +0 -3
- package/.next/standalone/.next/server/chunks/node_modules_@opentelemetry_api_build_esm_index_1jp9ij0_ddtgk.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__075uro8t92s0_._.js +0 -14
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0alpzjn3450sr._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0aup10z2o8zc1._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0bioghlkjf7s7._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0nhm28v58ty9z._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0vse4qi496ol-._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__190xwrr5zrfi3._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1guwlpkyurdn9._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1jq2bh84rafc7._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1k96jctukf65_._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1sj-wn2jp6va5._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/_100nvr7rei3us._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/node_modules_@opentelemetry_api_build_esm_index_0ntwr8lzj6p2i.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_0janj0i6dqko7._.js +0 -6
- package/.next/standalone/.next/static/chunks/0rucj5pu307i4.js +0 -1
- package/.next/standalone/.next/static/chunks/1-0se0uwja_ny.js +0 -1
- package/.next/standalone/.next/static/chunks/1024g0jaymm46.js +0 -1
- package/.next/standalone/.next/static/chunks/165ezyyx0j1ft.js +0 -22
- package/.next/standalone/.next/static/chunks/173vw1xs-5m5g.js +0 -1
- package/.next/standalone/.next/static/chunks/20cme7d6wv6md.js +0 -1
- package/.next/standalone/.next/static/chunks/26c4gmdpsthv6.css +0 -2
- package/.next/standalone/.next/static/chunks/2_sj5ssr_m_wm.js +0 -1
- package/.next/standalone/.next/static/chunks/2mz-k_jt_76xt.js +0 -1
- package/.next/standalone/.next/static/chunks/2ojf3r8g4tn7s.js +0 -1
- package/.next/standalone/.next/static/chunks/2tjfp9dirxnku.js +0 -1
- package/.next/standalone/.next/static/chunks/2u1m0f-wnhz44.js +0 -1
- package/.next/standalone/.next/static/chunks/2ytnb83xmjn3u.js +0 -1
- package/.next/standalone/.next/static/chunks/2zyrjasvbmwpq.js +0 -1
- package/.next/standalone/.next/static/chunks/31fan-ze541d1.js +0 -1
- package/.next/standalone/.next/static/chunks/32s3y34p0t2pe.js +0 -1
- package/.next/standalone/.next/static/chunks/36re0fegaocq-.js +0 -1
- package/.next/standalone/.next/static/chunks/3fhk60ouw_ae6.js +0 -1
- package/.next/standalone/.next/static/chunks/3xgxl1s_in776.js +0 -31
- package/.next/standalone/.next/static/chunks/44yz8zx53euy1.js +0 -1
- package/.next/standalone/node_modules/next/dist/compiled/jsonwebtoken/index.js +0 -11
- package/.next/standalone/node_modules/next/dist/compiled/jsonwebtoken/package.json +0 -1
- package/.next/standalone/node_modules/next/dist/lib/semver-noop.js +0 -18
- /package/.next/standalone/.next/static/{4MgI0mZP1iVhhocpUivMm → -iBiSmrLiylRKLAg77zlQ}/_buildManifest.js +0 -0
- /package/.next/standalone/.next/static/{4MgI0mZP1iVhhocpUivMm → -iBiSmrLiylRKLAg77zlQ}/_clientMiddlewareManifest.js +0 -0
- /package/.next/standalone/.next/static/{4MgI0mZP1iVhhocpUivMm → -iBiSmrLiylRKLAg77zlQ}/_ssgManifest.js +0 -0
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
module.exports=[28864,e=>{"use strict";let t,r,i,s,n,a,o;var l,u=e.i(14747);function c(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var h=((l={}).AnonymousId="anonymous_id",l.DistinctId="distinct_id",l.Props="props",l.EnablePersonProcessing="enable_person_processing",l.PersonMode="person_mode",l.FeatureFlagDetails="feature_flag_details",l.FeatureFlags="feature_flags",l.FeatureFlagPayloads="feature_flag_payloads",l.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",l.BootstrapFeatureFlags="bootstrap_feature_flags",l.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",l.OverrideFeatureFlags="override_feature_flags",l.Queue="queue",l.AiQueue="ai_queue",l.AiCaptureQueue="ai_capture_queue",l.LogsQueue="logs_queue",l.OptedOut="opted_out",l.SessionId="session_id",l.SessionStartTimestamp="session_start_timestamp",l.SessionLastTimestamp="session_timestamp",l.PersonProperties="person_properties",l.GroupProperties="group_properties",l.InstalledAppBuild="installed_app_build",l.InstalledAppVersion="installed_app_version",l.SessionReplay="session_replay",l.PushRegistered="push_registered",l.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",l.SurveyLastSeenDate="survey_last_seen_date",l.SurveysInProgress="surveys_in_progress",l.SurveysSeen="surveys_seen",l.Surveys="surveys",l.RemoteConfig="remote_config",l.FlagsEndpointWasHit="flags_endpoint_was_hit",l.DeviceId="device_id",l);let d={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",LOCAL_EVALUATION_INCONCLUSIVE:"local_evaluation_inconclusive",QUOTA_LIMITED:"quota_limited",TIMEOUT:"timeout",CONNECTION_ERROR:"connection_error",UNKNOWN_ERROR:"unknown_error",apiError:e=>`api_error_${e}`};function f(e){let t=[];return JSON.stringify(e,function(e,r){if("bigint"==typeof r)return r.toString();if("function"!=typeof r&&"symbol"!=typeof r){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&"object"==typeof r){for(;t.length>0&&t[t.length-1]!==this;)t.pop();if(t.includes(r))return"[Circular]";t.push(r)}return r}})??"null"}let p=Array.isArray,g=Object.prototype;g.hasOwnProperty;let m=g.toString,y=p||function(e){return"[object Array]"===m.call(e)},_=e=>e===Object(e)&&!y(e),v=e=>void 0===e,b=e=>"[object String]"==m.call(e),w=e=>b(e)&&0===e.trim().length,x=e=>null===e,E=e=>v(e)||x(e),S=e=>"[object Number]"==m.call(e)&&e==e;function F(e){return null===e||"object"!=typeof e}function P(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function I(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return C(e,Error)}}function A(e){return"u">typeof Event&&C(e,Event)}function C(e,t){try{return e instanceof t}catch{return!1}}let k="Android",$="BlackBerry",O="Nintendo",M="PlayStation",T="Xbox",R="Windows",j="(\\d+(\\.\\d+)?)";RegExp("Version/"+j),RegExp("(Claude|Codex|ChatGPT)\\/"+j),RegExp(T,"i"),RegExp(M+" \\w+","i"),RegExp(O+" \\w+","i"),RegExp($+"|PlayBook|BB10","i");RegExp("rv:"+j),RegExp("Edge?\\/"+j),RegExp("(Chrome|CrMo)\\/"+j),RegExp("CriOS\\/"+j),RegExp("(UCBrowser|UCWEB)\\/"+j),RegExp("(Opera|OPR)\\/"+j),RegExp("Firefox\\/"+j),RegExp("FxiOS\\/"+j),RegExp("Konqueror[:/]?"+j,"i"),RegExp($+" "+j),RegExp("android\\s"+j,"i"),RegExp("SamsungBrowser\\/"+j),RegExp("OculusBrowser\\/"+j),RegExp("Vivaldi\\/"+j),RegExp("YaBrowser\\/"+j),RegExp("Whale\\/"+j),RegExp("Brave\\/"+j),RegExp("(DuckDuckGo|Ddg)\\/"+j),RegExp("PaleMoon\\/"+j),RegExp("Waterfox\\/"+j),RegExp("GSA\\/"+j),RegExp("(rv:|MSIE )"+j),RegExp("rv:"+j),RegExp(T+"; "+T+" (.*?)[);]","i"),RegExp(O,"i"),RegExp(M,"i"),RegExp(R,"i"),RegExp("("+k+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+k+")","i");let D=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function B(e,t){return"string"==typeof e&&D.test(e)?e:t()}function L(e,t){let r=Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function N(e){return e?e.split("#")[0]:e}async function q(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 U(){return new Date().toISOString()}function V(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}async function z(e,t,r){let i;try{return await Promise.race([e,new Promise((e,s)=>{i=V(()=>{try{r?.(),e()}catch(e){s(e)}},t)})])}finally{clearTimeout(i)}}function H(e){return Promise.all(e.map(e=>(e??Promise.resolve()).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}function W(e,t,r){return e&&r?t.length===Object.keys(r).length&&t.every(t=>e[t]===r[t]):e===r}class K{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){let r=t&&t.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(r,t,0).apply(e),s=this.buildParsingContext(t),n=this.parseStacktrace(i,s);return{$exception_list:this.convertToExceptionList(n,r),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&y(t.stacktrace.frames)&&(t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames));return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let r,i;if(null!=e.cause&&(r=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack)try{i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)}catch{}return{...e,cause:r,stack:i,errors:e.errors?.map(e=>this.parseStacktrace(e,t))}}applyChunkIds(e,t){return e.map(e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e))}applyCoercers(e,t){for(let r of this.coercers)if(r.match(e))return r.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let e of this.modifiers)t=await e(t);return t}convertToExceptionList(e,t){let r=[],i=(e,s,n)=>{let a=r.length,o=void 0===s?{type:"string"==typeof t.type&&t.type.length>0?t.type:"generic",..."boolean"==typeof t.handled?{handled:t.handled}:void 0===t.handled?{handled:!0}:{},synthetic:"boolean"==typeof t.synthetic?t.synthetic:e.synthetic,exception_id:a}:{type:"chained",source:n,synthetic:e.synthetic,exception_id:a,parent_id:s},l={type:e.type,value:e.value,mechanism:o};for(let t of(e.stack&&(l.stacktrace={type:"raw",frames:e.stack}),r.push(l),e.cause&&i(e.cause,a,"cause"),e.errors??[]))i(t,a,"member")};return i(e),r}buildParsingContext(e){return{chunkIdMap:function(e){let n=globalThis._posthogChunkIds,a=globalThis._debugIds;if(!n&&!a)return;let o=n?Object.keys(n):[],l=a?Object.keys(a):[];if(s&&W(n,o,r)&&W(a,l,i))return s;r=n?{...n}:void 0,i=a?{...a}:void 0,s={},t??={};let u=(r,i)=>{for(let n of r){let r=i[n];if(!r)continue;let a=t?.[n];if(a){s[a]=r;continue}let o=e(n);for(let e=o.length-1;e>=0;e--){let i=o[e]?.filename;if(i){s[i]=r,t[n]=i;break}}}};return a&&u(l,a),n&&u(o,n),s}(this.stackParser),skipFirstLines:e.skipFirstLines??1}}getAggregateErrors(e){try{if(I(e)){let t=Object.getPrototypeOf(e);for(let r=0;t&&r<100;r++){let r=Object.getOwnPropertyDescriptor(t,"constructor")?.value;if("function"==typeof r&&"AggregateError"===r.name){let t=e.errors;return y(t)?t:void 0}t=Object.getPrototypeOf(t)}}}catch{}}buildCoercingContext(e,t,r=0){let i=0,s=0,n=!1,a=new Set,o=[],l={},u=(e,t,r=0)=>{let u,h,d=c(t,r),f=d.apply;if(d.apply=t=>{o.push(e);try{return f(t)}finally{o.pop()}},r>4||r>0&&-1!==o.indexOf(e))return this.coerceFallback(d);let p="object"==typeof e&&null!==e||"function"==typeof e;if(0===r&&i>=50||p&&a.has(e))return;p&&a.add(e),0===r&&i++;let g=this.getAggregateErrors(e);n||=!!g;try{if(!(u=this.applyCoercers(e,d)))throw l}catch(e){if(e===l){0===r&&i--;return}if(!n)throw e;u=this.coerceFallback(d)}if(!g||i>=50)return u;try{h=g.length}catch{return u}if(!Number.isInteger(h)||h<0||h>0xffffffff)return u;let m=[];for(let e=0;i<50&&s<1e3&&e<h;e++){let r;s++;try{r=d.next(g[e])}catch{i++,r=this.coerceFallback(c(t+1))}r&&m.push(r)}return{...u,errors:m}},c=(r,i=0)=>({...t,syntheticException:0==r?t.syntheticException:void 0,mechanism:0==r?e:{},apply:e=>{let t=u(e,r,i+1);if(!t)throw l;return t},next:e=>u(e,r+1)}),h=c(r);return{...h,apply:e=>u(e,r)??this.coerceFallback(h)}}}e.s(["ErrorPropertiesBuilder",0,K],80446);let G=/^([a-z][a-z0-9.+-]+):/i,Q=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function J(e,t,r,i,s){let n={platform:e,filename:t,function:"<anonymous>"===r?"?":r,in_app:function(e){if(!e||"<anonymous>"===e)return!1;let t=G.exec(e);return!t||Q.includes(t[1].toLowerCase())}(t)};return v(i)||(n.lineno=i),v(s)||(n.colno=s),n}let Z=(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,X=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ee=/\((\S*)(?::(\d+))(?::(\d+))\)/,et=(e,t)=>{let r=Y.exec(e);if(r){let[,e,i,s]=r;return J(t,e,"?",+i,+s)}let i=X.exec(e);if(i){if(i[2]&&0===i[2].indexOf("eval")){let e=ee.exec(i[2]);e&&(i[2]=e[1],i[3]=e[2],i[4]=e[3])}let[e,r]=Z(i[1]||"?",i[2]);return J(t,r,e,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},er=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ei=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,es=(e,t)=>{let r=er.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let e=ei.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]=Z(i,e),J(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,ea=(e,t)=>{let r=en.exec(e);return r?J(t,r[2],r[1]||"?",+r[3],r[4]?+r[4]:void 0):void 0},eo=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,el=(e,t)=>{let r=eo.exec(e);return r?J(t,r[2],r[3]||"?",+r[1]):void 0},eu=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,ec=(e,t)=>{let r=eu.exec(e);return r?J(t,r[5],r[3]||r[4]||"?",+r[1],+r[2]):void 0},eh=/^\s*[-]{4,}$/,ed=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,ef=/^Promise\.(?:all|any)$/,ep=/^index \d+$/,eg=(e,t)=>{let r=e.match(ed);if(r){let e,i,s,n,a;if(r[1]){let t=(s=r[1]).lastIndexOf(".");if("."===s[t-1]&&t--,t>0){e=s.slice(0,t),i=s.slice(t+1);let r=e.indexOf(".Module");r>0&&(s=s.slice(r+1),e=e.slice(0,r))}n=void 0}i&&(n=e,a=i),"<anonymous>"===i&&(a=void 0,s=void 0),void 0===s&&(a=a||"?",s=n?`${n}.${a}`:a);let o=r[2]?.startsWith("file://")?r[2].slice(7):r[2],l="native"===r[5];return o?.match(/\/[A-Z]:/)&&(o=o.slice(1)),o||!r[5]||l||(o=r[5]),ef.test(s)&&ep.test(o||"")&&(o="node:internal/promise"),{filename:o?decodeURI(o):void 0,module:void 0,function:s,lineno:em(r[3]),colno:em(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(eh))return{filename:e,platform:t}};function em(e){return parseInt(e||"",10)||void 0}let ey=/\(error: (.*)\)/;function e_(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function ev(e,t){let r=t.start;for(;r>0&&e_(e[r-1],e[r-1+t.length]);)r--;return t.start-r}function eb(e,t){let r=t.start+t.length,i=r;for(;i<e.length&&e_(e[i],e[i-t.length]);)i++;return i-r}function ew(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 ex(){return eE("web:javascript",et,es)}function eE(e,...t){return(r,i=0)=>{let s=[],n=r.split("\n"),a=Math.min(n.length,i+1e3),o=[];for(let r=i;r<a;r++){let i=n[r];if(i.length>1024)continue;let a=ey.test(i)?i.replace(ey,"$1"):i;if(!a.match(/\S*Error: /)){for(let r of t){let t=r(a,e);if(t){s.push(t);let e=function(e){for(let t=1;t<=10;t++){let r=e.length-2*t;if(r<0)break;let i=!0;for(let s=0;s<t;s++)if(!e_(e[r+s],e[r+t+s])){i=!1;break}if(i){for(let i=0;i<t;i++)e[r+i]=e[r+t+i];return e.length=r+t,{start:r,length:t}}}}(s);if(e){for(let t=o.length-1;t>=0;t--){let r=o[t];if(r.start+r.length<=e.start)break;o.pop()}o.push(e)}break}}if(function(e,t){let r=t[0],i=e.length-(r?ev(e,r):0);for(let r of t)i-=eb(e,r);return i}(s,o)>=50)break}}let l=[...o].sort((e,t)=>t.start-e.start),u=l[l.length-1];if(u){let e=ev(s,u);for(let t of(s.splice(u.start-e,e),l))t.start-=e}for(let e of l)!function(e,t){let r=t.start+t.length,i=eb(e,t);i&&e.splice(r+i===e.length?r:t.start,i)}(s,e);return o.some(e=>0===e.start&&s.length===e.length)&&function(e){let t=e.map(e=>`${e.function}|${e.filename}|${e.lineno}|${e.colno}|${e.module}`),r=0;for(let e=1;e<t.length;e++)(function(e,t,r){for(let i=0;i<e.length;i++){let s=e[(t+i)%e.length],n=e[(r+i)%e.length];if(s!==n)return s<n}return!1})(t,e,r)&&(r=e);e.push(...e.splice(0,r))}(s),ew(s)}}class eS{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let r=b(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return P(e,"DOMException")}isDOMError(e){return P(e,"DOMError")}}e.s(["DOMExceptionCoercer",0,eS],29569);class eF{match(e){return!!P(e,"ErrorEvent")&&(void 0!=e.error||this._hasUsableMessage(e))}coerce(e,t){if(void 0!=e.error)return t.apply(e.error);let r=t.apply(e.message);return{...r,stack:this._buildLocationStack(e)??r.stack,synthetic:!0}}_hasUsableMessage(e){return b(e.message)&&e.message.length>0}_buildLocationStack(e){let t=e.lineno??0,r=e.colno??0;if(b(e.filename)&&0!==e.filename.length&&0!==t)return`Error
|
|
2
|
-
at ${e.filename}:${t}:${r}`}}e.s(["ErrorEventCoercer",0,eF],43179);let eP=["fatal","error","warning","log","info","debug"];function eI(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 eA{match(e){return"object"==typeof e&&null!==e}coerce(e,t){let r=this.getErrorPropertyFromObject(e);return r?t.apply(r):{type:this.getType(e),value:this.getValue(e),stack:this.getStack(e)??t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(A(e))return e.constructor.name;let t="name"in e?e.name:void 0;return b(t)&&!w(t)?t:"Error"}getValue(e){if("name"in e&&"string"==typeof e.name){let t=`'${e.name}' captured as exception`;return"message"in e&&"string"==typeof e.message&&(t+=` with message: '${e.message}'`),t}if("message"in e&&"string"==typeof e.message)return e.message;let t=this.getObjectClassName(e),r=eI(e);return`${t&&"Object"!==t?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return b(e)&&!w(e)&&eP.indexOf(e)>=0}getStack(e){try{if(b(e.stacktrace)&&e.stacktrace.length>0)return e.stacktrace;return b(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(I(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,eA],6881);class eC{match(e){return A(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${eI(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["EventCoercer",0,eC],80322);class ek{match(e){return F(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["PrimitiveCoercer",0,ek],80049);class e${match(e){return P(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!A(e))return!1;try{let t=e.detail;return null!=t&&"object"==typeof t&&"reason"in t}catch{return!1}}coerce(e,t){let r=this.getUnhandledRejectionReason(e);return F(r)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(r)}`,stack:t.syntheticException?.stack,synthetic:!0}:t.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&null!=e.detail&&"object"==typeof e.detail&&"reason"in e.detail)return e.detail.reason}catch{}return e}}e.s(["PromiseRejectionEventCoercer",0,e$],98689);let eO={MESSAGE:"$message",TIMESTAMP:"$timestamp"},eM=new Set([eO.MESSAGE,eO.TIMESTAMP]),eT={enabled:!0,max_bytes:32768};function eR(e){return e?{enabled:e.enabled??eT.enabled,max_bytes:function(e,t){if(!S(e)||1/0===e||-1/0===e)return t;let r=Math.floor(e);return r<0?t:r}(e.max_bytes,eT.max_bytes)}:{...eT}}function ej(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((r,i)=>(eM.has(i)?t.push(i):r[i]=e[i],r),{}),droppedKeys:t}}class eD{constructor(e){this._entries=[],this._totalBytes=0,this._config=eR(e)}setConfig(e){this._config=eR(e),this._trimToMaxBytes()}add(e){let t=function(e){let t;try{t=f(e)}catch{return}try{let e=JSON.parse(t);if(!_(e))return;let r=e[eO.MESSAGE],i=e[eO.TIMESTAMP];if(!b(r)||0===r.trim().length||!b(i)&&!S(i))return;return{step:e,json:t}}catch{return}}(e);if(!t)return;let r=eB(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 eB(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,eT,"EXCEPTION_STEP_INTERNAL_FIELDS",0,eO,"ExceptionStepsBuffer",0,eD,"getUtf8ByteLength",0,eB,"resolveExceptionStepsConfig",0,eR,"stripReservedExceptionStepFields",0,ej],52001),e.i(80446),e.s(["chromeStackLineParser",0,et,"createDefaultStackParser",0,ex,"createStackParser",0,eE,"geckoStackLineParser",0,es,"nodeStackLineParser",0,eg,"opera10StackLineParser",0,el,"opera11StackLineParser",0,ec,"reverseAndStripFrames",0,ew,"winjsStackLineParser",0,ea],70736),e.i(70736),e.i(29569);class eL{match(e){return I(e)}coerce(e,t){let r=this.getStack(e),i=void 0===r?t.syntheticException?.stack:void 0;return{type:this.getType(e),value:this.getMessage(e,t),stack:r??i,cause:e.cause?t.next(e.cause):void 0,synthetic:!!i}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let r=e.message;return r.error&&"string"==typeof r.error.message?String(r.error.message):String(r)}getStack(e){try{let t=e.stacktrace;if("string"==typeof t&&t.length>0)return t;let r=e.stack;return"string"==typeof r&&r.length>0?r:void 0}catch{return}}}e.s(["ErrorCoercer",0,eL],11475),e.i(11475),e.i(43179);let eN=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class eq{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(eN);return i&&(t=i[1],r=i[2]),[t,r]}}e.s(["StringCoercer",0,eq],45098),e.i(45098),e.i(6881),e.i(80322),e.i(80049),e.i(98689),e.s(["DOMExceptionCoercer",0,eS,"ErrorCoercer",0,eL,"ErrorEventCoercer",0,eF,"EventCoercer",0,eC,"ObjectCoercer",0,eA,"PrimitiveCoercer",0,ek,"PromiseRejectionEventCoercer",0,e$,"StringCoercer",0,eq],21854),e.i(21854);class eU{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(void 0!==t)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}}function eV(){if("u">typeof process){let e=process.env.POSTHOG_RELEASE_ID?.trim();if(e)return e}let e=globalThis._posthogReleaseId;return"string"==typeof e&&e.length>0?e:void 0}e.s(["ReduceableCache",0,eU],46986),e.i(46986),e.i(52001),e.s(["getInjectedReleaseId",0,eV],41508),e.i(41508),e.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,eT,"DOMExceptionCoercer",0,eS,"EXCEPTION_STEP_INTERNAL_FIELDS",0,eO,"ErrorCoercer",0,eL,"ErrorEventCoercer",0,eF,"ErrorPropertiesBuilder",0,K,"EventCoercer",0,eC,"ExceptionStepsBuffer",0,eD,"ObjectCoercer",0,eA,"PrimitiveCoercer",0,ek,"PromiseRejectionEventCoercer",0,e$,"ReduceableCache",0,eU,"StringCoercer",0,eq,"chromeStackLineParser",0,et,"createDefaultStackParser",0,ex,"createStackParser",0,eE,"geckoStackLineParser",0,es,"getInjectedReleaseId",0,eV,"getUtf8ByteLength",0,eB,"nodeStackLineParser",0,eg,"opera10StackLineParser",0,el,"opera11StackLineParser",0,ec,"resolveExceptionStepsConfig",0,eR,"reverseAndStripFrames",0,ew,"stripReservedExceptionStepFields",0,ej,"winjsStackLineParser",0,ea],96117);var ez=e.i(96117);let eH="0123456789abcdef";class eW{constructor(e){this.bytes=e}static ofInner(e){if(16===e.length)return new eW(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 eW(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 eW(e)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=eH.charAt(this.bytes[t]>>>4),e+=eH.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+=eH.charAt(this.bytes[t]>>>4),e+=eH.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 eW(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 eK{constructor(e){this.timestamp=0,this.counter=0,this.random=e??eG()}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 eW.fromFieldsV7(this.timestamp,Math.trunc(this.counter/0x40000000),0x3fffffff&this.counter,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,eW.ofInner(e)}}let eG=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),eQ=()=>eJ().toString(),eJ=()=>(n||(n=new eK)).generate();function eZ(e){let t={};if(e)for(let r of e.split(";")){let[e,...i]=r.trim().split("=");if(e){let r=i.join("=").trim();try{t[e.trim()]=decodeURIComponent(r)}catch{t[e.trim()]=r}}}return{get:e=>e in t?{value:t[e]}:void 0}}function eY(e){let t=e.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${t}_posthog`}function eX(e){let t=Date.now();return JSON.stringify({distinct_id:e,$device_id:e,$user_state:"anonymous",$sesid:[t,eQ(),t]})}function e0(e,t){let r=eY(t),i=e.get(r);return i?e2(i.value):null}function e1(e){if(!e)return;let t={};return e.sessionId&&(t.$session_id=e.sessionId),e.deviceId&&(t.$device_id=e.deviceId),Object.keys(t).length>0?t:void 0}function e2(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||"object"!=typeof t||!t.distinct_id)return null;let r=y(t.$sesid)?t.$sesid[1]:void 0;return{distinctId:String(t.distinct_id),isIdentified:"identified"===t.$user_state,sessionId:"string"==typeof r?r:void 0,deviceId:"string"==typeof t.$device_id?t.$device_id:void 0}}catch{return null}}let e3=e=>void 0===e?void 0:e.variant??e.enabled,e5=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}},e4=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","bfcid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],e6=(e,t=[])=>{let r={},i=t=>{void 0!==e[t]&&(r[t]=e[t])};return e4.forEach(i),t.forEach(i),r};class e8{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,t){for(let r of this.events[e]||[])r(t);for(let r of this.events["*"]||[])r(e,t)}}let e9=e=>{throw L("NativeGzipValidationError",`Native gzip produced invalid output: ${e}`)},e7=async(e,t)=>{e.size<18&&e9("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());r.length>=2&&31===r[0]&&139===r[1]&&8===r[2]||e9("invalid-header");let i=new DataView(await e.slice(e.size-8).arrayBuffer());i.getUint32(0,!0)!==(e=>{let t=(()=>{if(a)return a;a=[];for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t=1&t?0xedb88320^t>>>1:t>>>1;a[e]=t>>>0}return a})(),r=0xffffffff;for(let i=0;i<e.length;i++)r=t[(r^e[i])&255]^r>>>8;return(0xffffffff^r)>>>0})(t)&&e9("invalid-crc");let s=t.length>>>0;i.getUint32(4,!0)!==s&&e9("invalid-size")};async function te(e,t=!0,r){try{let t=new TextEncoder().encode(e),r=new globalThis.CompressionStream("gzip"),i=r.writable.getWriter(),s=i.write(t).then(()=>i.close()).catch(async e=>{try{await i.abort(e)}catch{}throw e}),n=new Response(r.readable).blob(),[a]=await Promise.all([n,s]);return await e7(a,t),a}catch(e){if(r?.rethrow)throw e;return t&&console.error("Failed to gzip compress data",e),null}}class tt{add(e){let t=eQ(),r=++this.nextId;return this.promiseByIds[t]={id:r,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map(e=>e.promise),t=e.length;for(;t>0;)await Promise.all(e),t=(e=Object.values(this.promiseByIds).map(e=>e.promise)).length}getPromises(e=[],t=this.nextId){let r=new Set(e);return Object.values(this.promiseByIds).filter(e=>e.id<=t&&!r.has(e.promise)).map(e=>e.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}let tr=(e,t,r)=>{function i(s,...n){t(()=>{(0,r[s])(e,...n)})}return{debug:(...e)=>{i("debug",...e)},info:(...e)=>{i("log",...e)},warn:(...e)=>{i("warn",...e)},error:(...e)=>{i("error",...e)},critical:(...t)=>{r.error(e,...t)},createLogger:i=>tr(`${e} ${i}`,t,r)}};class ti{record(e){if("too-large"===e.kind)return;if("retry-later"!==e.kind)return void this.reset();if(!e.retryAfterMs)return;let t=this.isOpen(),r=Date.now(),i=Math.min(e.retryAfterMs,3e5);if(!t){this._installedAt=r,this._until=r+i;return}this._until=Math.max(this._until,Math.min(r+i,this._installedAt+3e5))}remainingMs(){let e=Date.now();if(e<this._installedAt-5e3)return this.reset(),0;let t=Math.min(3e5,Math.max(0,this._until-e));return 0===t&&this.reset(),t}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}}class ts extends Error{constructor(e,t,r,i){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.responseBodyDeadline=r,this.abortController=i,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return function(e,t=Date.now()){if("string"!=typeof e||!e)return;let r=e.trim(),i=/^\d+\s*,/.test(r)?r.slice(0,r.indexOf(",")).trim():r;if(/^\d+$/.test(i)){let e=1e3*Math.min(Number(i),300);return e>0?e:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(i))return;let s=Date.parse(/^\w{3} \w{3} /.test(i)?i+" GMT":i)-t;if(Number.isFinite(s)&&!(s<=0))return Math.min(s,3e5)}(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let e=L("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e,t=new Promise((e,t)=>{this.responseBodyTimer=V(()=>{this._bodyReadTimedOut=!0;let e=L("AbortError","Response body read timed out");t(e),this.cancelResponseBody(e)},this.responseBodyDeadline-Date.now())});try{e=Promise.resolve(this.response.text())}catch(t){e=Promise.reject(t)}this.responseBodyTextPromise=Promise.race([e,t]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(e=>JSON.parse(e))}cancelResponseBody(e){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(e),(async()=>{try{await this.response.body?.cancel()}catch{}})()}}class tn extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}async function ta(e){if(e instanceof ts){let t="";try{t=await e.text}catch{e.bodyReadTimedOut&&(t="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function to(e){return e instanceof tn}function tl(e){if(e instanceof ts)return 502===e.status||504===e.status;if(!(e instanceof tn))return!1;let t=e.error;return"ECONNREFUSED"!==(t?.code??t?.cause?.code)}function tu(e){try{if("string"!=typeof e)return e instanceof Uint8Array?e.byteLength:e.size;if("u">typeof Buffer)return Buffer.byteLength(e,"utf8");return new TextEncoder().encode(e).length}catch{return 0}}function tc(e){return"object"==typeof e&&e instanceof ts&&413===e.status}function th(e){return e instanceof ts?408===e.status||429===e.status||e.status>=500:to(e)}function td(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}let tf="default";class tp{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new K([new eL,new eA,new eq,new ek],ex())}getEvaluationRuntime(){}get apiKey(){return this.projectToken}constructor(e,t={}){var r;this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new tt,this._events=new e8,this._isInitialized=!1;let i="string"==typeof e?e.trim():"",s="string"==typeof t.host?t.host.trim():"",n=!i;this._logger=function(e,t=e=>e()){return tr(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)),n&&this._logger.error("You must pass your PostHog project token. The client will be disabled."),this.projectToken=i,this.host=(r=s||"https://us.i.posthog.com",r?.replace(/\/+$/,"")),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:th},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||n,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(h.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(h.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(h.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let e=this.on("*",(e,t)=>this._logger.info(e,t));this.removeDebugCallback=()=>{e(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},r=this.mergeCommonEventProperties(t);var i=r;for(let e of Object.keys(t))(e.startsWith("$feature/")||"$active_feature_flags"===e)&&(i[e]=t[e]);return"$feature_flag_called"===e.event&&!1===r.$feature_flag_has_experiment&&this.isMinimalFlagCalledEventsEnabled()&&(r=e6(r)),{distinct_id:e.distinct_id,event:e.event,properties:r}}mergeCommonEventProperties(e){return{...e,...this.getCommonEventProperties()}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,r){this.wrap(()=>{let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",i,r)})}async identifyStatelessImmediate(e,t,r){let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",i,r)}captureStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",s,i)})}async captureStatelessImmediate(e,t,r,i){let s=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",s,i)}aliasStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",s,i)})}async aliasStatelessImmediate(e,t,r,i){let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",s,i)}groupIdentifyStateless(e,t,r,i,s,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...n||{}}});this.enqueue("capture",a,i)})}async groupIdentifyStatelessImmediate(e,t,r,i,s,n){let a=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...n||{}}});await this.sendImmediate("capture",a,i)}async getRemoteConfig(){await this._initPromise;let e=this.host;"https://us.i.posthog.com"===e?e="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===e&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.projectToken}/config`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,r,{type:"required",consume:e=>e.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(e=>{this._logger.error("Remote config could not be loaded",e),this._events.emit("error",e)})}async getFlags(e,t={},r={},i={},s={},n=!1){await this._initPromise;let a=`${this.host}/flags/?v=2${n?"&config=true":""}`,o={token:this.projectToken,distinct_id:e,groups:t,person_properties:r,group_properties:i,...s};r.$device_id&&(o.$device_id=r.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(o.evaluation_contexts=this.evaluationContexts);let l=this.getEvaluationRuntime();l&&(o.evaluation_runtime=l);let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(o)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,u,{type:"required",consume:e=>e.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:tl},this.featureFlagsRequestTimeoutMs).then(e=>({success:!0,response:(e=>{if("flags"in e){let t,r=Object.fromEntries(Object.entries(e.flags??{}).map(([e,t])=>[e,e3(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?e5(r):void 0]}));return{...e,featureFlags:r,featureFlagPayloads:i}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([e,t])=>[e,e5(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 ts)return{type:"api_error",statusCode:e.status};if(e instanceof tn){let t=e.error;return t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,r={},i={},s={},n){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(e,t,r,i,s,n);if(void 0===a)return{response:void 0,requestId:void 0};let o=e3(a.response);return void 0===o&&(o=!1),{response:o,requestId:a.requestId}}async getFeatureFlagDetailStateless(e,t,r={},i={},s={},n){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,r,i,s,n,[e]);if(void 0!==a)return{response:a.flags[e],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,r={},i={},s={},n){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(t,r,i,s,n,[e]);if(!a)return;let o=a[e];return void 0===o?null:o}async getFeatureFlagPayloadsStateless(e,t={},r={},i={},s,n){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,n)).payloads}async getFeatureFlagsStateless(e,t={},r={},i={},s,n){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,n)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},i={},s,n){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(e,t,r,i,s,n);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},r={},i={},s,n){await this._initPromise;let a={geoip_disable:s??this.disableGeoip};n&&(a.flag_keys_to_evaluate=n);let o=await this.getFlags(e,t,r,i,a);if(!o.success)return;let l=o.response;return(l.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),l.quotaLimited?.includes("feature_flags"))?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.projectToken}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},r=await this.fetchWithRetry(e,t,{type:"required",consume:e=>{if(200!==e.status||!e.json){let t=`Surveys API could not be loaded: ${e.status}`,r=Error(t);return this._logger.error(r),this._events.emit("error",Error(t)),Promise.resolve(void 0)}return e.json()}}).catch(e=>{this._logger.error("Surveys API could not be loaded",e),this._events.emit("error",e)}),i=r?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(h.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(h.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(h.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return tf}persistedQueueKeyForRoute(e){return h.Queue}getActiveQueueRoutes(){return[tf]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,r,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let s=this.prepareMessage(t,r);if(null===(s=this.processBeforeEnqueue(s)))return;s=this.normalizeMessage(s);let n=this.persistedQueueKeyForRoute(i??this.getQueueRouteKey(s)),a=this.getPersistedProperty(n)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:s}),this.setPersistedProperty(n,a),this._events.emit(e,s),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=V(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,r,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let s=this.prepareMessage(t,r);if(null!==(s=this.processBeforeEnqueue(s))){s=this.normalizeMessage(s);try{await this.sendBatch([s],void 0,i??this.getQueueRouteKey(s))}catch(e){this._events.emit("error",e)}}}normalizeMessage(e){let{type:t,library:r,library_version:i,...s}=e,n=td(s.properties)?s.properties:void 0;return void 0!==r&&n?.$lib===void 0&&(n={...n||{},$lib:r}),void 0!==i&&n?.$lib_version===void 0&&(n={...n||{},$lib_version:i}),n&&(s.properties=n),s.uuid=B(s.uuid,eQ),s}normalizeTimestampForWire(e){let t=e instanceof Date?e:"string"==typeof e?new Date(e):null;if(!t||Number.isNaN(t.getTime()))return e;let r=t.toISOString(),i="string"==typeof e?e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return i&&i.length>3?r.replace(/\.\d{3}Z$/,`.${i}Z`):r}prepareMessage(e,t){let r={...e,timestamp:t?.timestamp?t?.timestamp:U(),uuid:B(t?.uuid,eQ)};return(t?.disableGeoip??this.disableGeoip)&&(td(r.properties)||(r.properties={}),r.properties.$geoip_disable=!0),r.distinctId&&(r.distinct_id=r.distinctId,delete r.distinctId),r}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async e=>{await ta(e)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(e,t=[]){let r=t.filter(e=>!!e),i=0;for(;;){let t=this.promiseQueue.getPromises([...r,...this.flushPromises],e);if(0===t.length)return;i>0&&this._logger.debug(`flush() re-checking ${t.length} pending promise(s) before flushing`),await Promise.all(t.map(e=>e.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,r=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(r,[t,i])}).then(()=>H([t])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),H([i]).then(()=>{this.flushPromises.delete(i),this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this.flushPromise===i&&(this.flushPromise=null)}),i}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&""!==e&&(t["User-Agent"]=e),t}compressPayload(e){return te(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,t,r=tf){let i={api_key:this.projectToken,batch:e.map(e=>{if(!e)return e;let t=this.normalizeTimestampForWire(e.timestamp);return t===e.timestamp?e:{...e,timestamp:t}}),sent_at:U()};this.historicalMigration&&(i.historical_migration=!0);let s=f(i),n=`${this.host}${this.getBatchEndpointPath(r)}`,a=this.disableCompression?null:await this.compressPayload(s),o={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==a&&{"Content-Encoding":"gzip"}},body:a||s};await this.fetchWithRetry(n,o,{type:"successful-write"},t)}async _flush(){let e;this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(e=>this.getRouteQueue(e).length>0))return;let r=[];for(let i of t)try{await this._flushRoute(i,r)}catch(t){void 0===e&&(e=t)}if(void 0!==e)throw e;this._events.emit("flush",r)}async _flushRoute(e,t){let r=this.persistedQueueKeyForRoute(e),i=this.getPersistedProperty(r)||[];if(!i.length)return;let s=i.length,n=0;for(;i.length>0&&n<s;){let s=i.slice(0,this.maxBatchSize),a=s.map(e=>void 0===e.message?e.message:this.normalizeMessage(e.message)),o=async()=>{let e=this.getPersistedProperty(r)||[],t=[...s],n=e.filter(e=>{let r=e.message?.uuid,i=t.findIndex(t=>t===e||"string"==typeof r&&r.length>0&&t.message?.uuid===r);return -1===i||(t.splice(i,1),!1)});this.setPersistedProperty(r,n),i=n,this._dequeuedMessagesCount+=s.length,await this.flushStorage()},l={retryCheck:e=>!tc(e)&&th(e)};try{await this.sendBatch(a,l,e)}catch(e){if(tc(e)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this._logger.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw e instanceof tn||await o(),this._events.emit("error",e),e}await o(),t.push(...a),n+=a.length}}async _sendOtlpBatch({path:e,auth:t,payload:r}){let i;if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};try{i=JSON.stringify(r)}catch(t){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${e} batch; reporting it as too large`,t)),{kind:"too-large",measuredLocally:!0}}let s=tu(i);if(s>0xa00000)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${s} bytes: the endpoint accepts at most 10485760`)),{kind:"too-large",measuredLocally:!0};let n="bearer"===t?`${this.host}/i/v1/${e}`:`${this.host}/i/v1/${e}?token=${encodeURIComponent(this.projectToken)}`,a=this.disableCompression?null:await this.compressPayload(i),o=a||i,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",..."bearer"===t&&{Authorization:`Bearer ${this.projectToken}`},...null!==a&&{"Content-Encoding":"gzip"}},body:o};try{return await this.fetchWithRetry(n,l,{type:"successful-write"},{retryCheck:e=>!tc(e)&&(!(e instanceof ts)||void 0===e.retryAfterMs)&&th(e)}),{kind:"ok"}}catch(e){if(tc(e))return{kind:"too-large"};if(th(e)){let t=e instanceof ts?e.retryAfterMs:void 0;return{kind:"retry-later",error:e,...void 0!==t&&{retryAfterMs:t}}}return{kind:"fatal",error:e}}}async _sendLogsBatch(e){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:e})}async _sendMetricsBatch(e){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:e})}async _sendTracesBatch(e){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:e})}async fetchWithRetry(e,t,r,i,s){let n=tu(t.body?t.body:""),a={...this._retryOptions,...i},o=0;return await q(async()=>{let i,a,l;o++;let u=new AbortController,c=s??this.requestTimeout,h=Date.now()+c,d=new Promise((e,t)=>{i=V(()=>{let e=L("AbortError",`Request timed out after ${c}ms`);t(e),u.abort(e)},c)}),f=!1,p=()=>l??=(async()=>{try{await a?.body?.cancel()}catch{}})();try{let i;try{i=this.fetch(e,{signal:u.signal,...t})}catch(e){throw new tn(e)}i.then(e=>{u.signal.aborted&&!f&&Promise.resolve(e.body?.cancel()).catch(()=>{})}).catch(()=>{});try{a=await Promise.race([i,d]),f=!0}catch(e){throw new tn(e)}let s="no-cors"===t.mode,o="successful-write"===r.type?300:400;if(!s&&(a.status<200||a.status>=o))throw new ts(a,n,h,u);if("successful-write"===r.type){try{await Promise.race([p(),d])}catch{}return}try{return await Promise.race([r.consume(a),d])}catch(e){if(u.signal.aborted)throw new tn(e);throw e}}finally{clearTimeout(i),u.signal.aborted&&a&&p()}},{...a,retryCheck:e=>{let t=a.retryCheck(e);return t&&o<=a.retryCount&&e instanceof ts&&e.cancelResponseBody(),t}})}async _shutdown(e=3e4){await this._initPromise;let t=!1;if(this.clearFlushTimer(),!this.disabled)return z((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(e=>this.getRouteQueue(e).length>0);){let e=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===e){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(e){if(!("object"==typeof e&&(e instanceof ts||to(e))))throw e;await ta(e)}})(),e,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:e}),t=!0})}async shutdown(e=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}let tg="[Circular]",tm="[Truncated]",ty="[Unserializable]";function t_(e){let t="";for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i>=55296&&i<=56319){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(t+=e[r]+e[r+1],r++):t+="�"}else t+=i>=56320&&i<=57343?"�":e[r]}return t}function tv(e,t){if(!t)return e;let r=[];try{r=Object.keys(t)}catch{r=[]}for(let i of r){let r;try{r=t[i]}catch{r=ty}Object.defineProperty(e,i,{value:r,enumerable:!0,writable:!0,configurable:!0})}return e}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let tb=Object.prototype.propertyIsEnumerable;function tw(e,t){try{return tx(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function tx(e,t,r,i){let s=[];for(let n in e)if(tb.call(e,n)){if(!n){t?.debug("Dropping an attribute with an empty key");continue}if(s.length>=1e3||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let a=e[n];if(x(a)||v(a))continue;s.push({key:t_(n),value:function e(t,r,i,s){if(i.remainingNodes<=0)return{stringValue:tm};if(i.remainingNodes--,"[object Boolean]"===m.call(t))return{boolValue:t};if("bigint"==typeof t){let e,i;return e=t.toString(),t>=(i=BigInt("9223372036854775808"))||t<-i?(r?.debug(`Attribute ${e} is outside the int64 range; encoding it as a string`),{stringValue:e}):{intValue:e}}if("number"==typeof t){if(!Number.isFinite(t))return{stringValue:String(t)};if(Number.isInteger(t)){if(Number.isSafeInteger(t))return{intValue:String(t)};if("u"<typeof BigInt)return{stringValue:String(t)};let e=BigInt(t).toString();return t>=0x8000000000000000||t<-0x8000000000000000?(r?.debug(`Attribute ${e} is outside the int64 range; encoding it as a string`),{stringValue:e}):{intValue:e}}return{doubleValue:t}}if("string"==typeof t)return{stringValue:t_(t)};if("function"==typeof t)return{stringValue:"[Function]"};if("symbol"==typeof t)return{stringValue:String(t)};if("object"==typeof t&&null!==t){if(i.ancestors.has(t))return{stringValue:tg};if(s>=20)return{stringValue:tm};if(t instanceof Date){let e=Number.isFinite(t.getTime())?t.toISOString():String(t);return{stringValue:"string"==typeof e?t_(e):String(e)}}i.ancestors.add(t);try{try{let n=t.toJSON;if("function"==typeof n)return e(n.call(t),r,i,s+1)}catch{}if(y(t))return{arrayValue:{values:function(t,r,i,s){let n=[],a=Math.min(t.length,1e3),o=0;for(;o<a&&i.remainingNodes>0;o++)try{let a=o in t?t[o]:void 0;if(E(a))continue;n.push(e(a,r,i,s))}catch{n.push({stringValue:ty})}return t.length>o&&n.push({stringValue:tm}),n}(t,r,i,s+1)}};return{kvlistValue:{values:tx(t,r,i,s+1)}}}finally{i.ancestors.delete(t)}}return{stringValue:t_(String(t))}}(a,t,r,i)})}catch{s.push({key:t_(n),value:{stringValue:ty}})}}return s}function tE(e,t,r){return{...tv({},e.resourceAttributes),"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":r}}let tS=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function tF(e,t){let r=tv({},e),i={};for(let e of tS)Object.prototype.hasOwnProperty.call(r,e)&&(i[e]=r[e],delete r[e]);return[...tw(r,t),...tw(i,t)]}let tP={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};class tI{constructor(e){this._onFire=e,this._firesAt=0}get pending(){return!!this._timer}arm(e){this.clear(),this._firesAt=Date.now()+e,this._timer=V(()=>{this._timer=void 0,this._onFire()},e)}armNoEarlierThan(e){this._timer&&Date.now()+e<=this._firesAt||this.arm(e)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}function tA(){return .75+.25*Math.random()*2}function tC(e,t,r,i){let s=Math.min(Math.max(0,t-1),6),n=e*2**s;return Math.round((void 0===i?n:Math.min(n,Math.max(i,e)))*r)}let tk="0000000000000000",t$=tk+tk,tO=/^[0-9a-f]+$/;function tM(e){let t=function(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}(function(e){let t=new Uint8Array(e),r=globalThis.crypto;if(r&&"function"==typeof r.getRandomValues)try{return r.getRandomValues(t),t}catch{}for(let r=0;r<e;r++)t[r]=Math.floor(256*Math.random());return t}(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function tT(e,t,r){return"string"==typeof e&&e.length===t&&e!==r&&tO.test(e)}let tR=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function tj(e){let t=tD(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:1&parseInt(t.flags,16)?tL:tN}}function tD(e){if("string"!=typeof e)return;let t=tR.exec(e.trim());if(!t)return;let[,r,i,s,n,a]=t;if("ff"!==r&&("00"!==r||!a)&&tT(i,32,t$)&&tT(s,16,tk))return{version:r,traceId:i,spanId:s,flags:n}}function tB(e){return Array.isArray(e)&&1===e.length?e[0]:e}let tL="01",tN="00";function tq(e){if("string"!=typeof e)return;let t=e.trim();if(!t||/[^\x20-\x7e\t]/.test(t))return;let r=t.split(",");if(!(r.length>32)){for(let e of r)if(e.trim()&&!e.includes("="))return;return t.length<=512?t:function(e){let t=[...e],r=()=>t.reduce((e,t)=>e+t.length,0)+t.length-1;for(let e=t.length-1;e>=0&&r()>512;e--)t[e].length>128&&t.splice(e,1);for(;t.length&&r()>512;)t.pop();return t.length?t.join(","):void 0}(r)}}let tU=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function tV(e){return String(e)+"000000"}function tz(e,t,r,i){let s="";return i&&(s=Object.keys(i).sort().map(e=>`${JSON.stringify(e)}:${JSON.stringify(i[e])}`).join(",")),`${e}\0${t}\0${r??""}\0${s}`}class tH{constructor(e,t,r){this._instance=e,this._config=t,this._logger=r,this._series=new Map,this._flushTimer=new tI(()=>this.flush().catch(e=>{this._logger.error("Metrics flush failed:",e)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new ti,this._consecutiveFlushFailures=0,this._flushJitter=1,this._generation=0}count(e,t=1,r){this._capture({name:e,type:"count",value:t,unit:r?.unit,attributes:r?.attributes})}gauge(e,t,r){this._capture({name:e,type:"gauge",value:t,unit:r?.unit,attributes:r?.attributes})}histogram(e,t,r){this._capture({name:e,type:"histogram",value:t,unit:r?.unit,attributes:r?.attributes})}flush(){let e=this._flushPromise,t=(async()=>{e&&await e.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===t&&(this._flushPromise=null)});return this._flushPromise=t,t}drainWindow(){if(0===this._series.size)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=1,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){let t,r;if(this._instance.isDisabled||this._instance.optedOut)return;let i=this._runBeforeSend(e);if(null===i)return;if(!i.name||"string"!=typeof i.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof i.value||!Number.isFinite(i.value))return void this._logger.warn(`Dropping metric '${i.name}': value must be a finite number`);if("count"===i.type&&i.value<0)return void this._logger.warn(`Dropping count '${i.name}': counters are monotonic, value must be >= 0`);try{t=i.attributes?{...i.attributes}:void 0,r=tz(i.type,i.name,i.unit,t)}catch(e){this._logger.warn(`Dropping metric '${i.name}': attributes could not be serialized`,e);return}let s=this._series.get(r);if(!s){if(!this._admitNewSeries())return;s={name:i.name,type:i.type,unit:i.unit,attributes:t,windowStartMs:Date.now()},this._series.set(r,s)}let n=this._typeByName.get(i.name);void 0===n?this._typeByName.set(i.name,i.type):n===i.type||this._typeCollisionWarned.has(i.name)||(this._typeCollisionWarned.add(i.name),this._logger.warn(`Metric name '${i.name}' is already used as a ${n}; recording it as a ${i.type} too will blend both series in charts. Use a distinct name.`)),this._fold(s,i.value);let a=this._activeTraceContext();a&&(s.exemplar={...a,value:i.value,timeMs:Date.now()}),this._armFlushTimer()}_activeTraceContext(){try{let e=tj(this._instance.getActiveSpan?.()?.traceparent());if(e&&e.flags===tL)return{traceId:e.traceId,spanId:e.spanId}}catch{}}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush||(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:Array(tU.length+1).fill(0)});let r=e.hist;r.count+=1,r.sum+=t,r.min=Math.min(r.min,t),r.max=Math.max(r.max,t),r.bucketCounts[function(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}(t,tU)]+=1}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=y(t)?t:[t],i=e;for(let e of r)try{let t=e(i);if(!t)return this._logger.info("Metric was rejected in beforeSend function"),null;i=t}catch(e){return this._logger.error("Error in beforeSend function for metric:",e),null}return i}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(tC(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),0===this._series.size)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,r=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t===this._generation)switch(this._retryAfter.record(r),"retry-later"===r.kind?(this._consecutiveFlushFailures++,this._flushJitter=tA()):(this._consecutiveFlushFailures=0,this._flushJitter=1),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),r.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",r.error);return}}_buildPayload(e){var t,r,i,s;return t=this._buildMetrics(e),r=tE(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),s=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:tF(r)},scopeMetrics:[{scope:{name:i,version:s},metrics:t}]}]}}_buildMetrics(e){let t=tV(Date.now()),r=new Map;for(let s of e.values()){var i;let e=tz(s.type,s.name,s.unit,void 0),n=r.get(e);n||(n={name:s.name,...s.unit&&{unit:s.unit}},"count"===s.type?n.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===s.type?n.gauge={dataPoints:[]}:n.histogram={aggregationTemporality:1,dataPoints:[]},r.set(e,n));let a=tw(s.attributes??{},this._logger),o=tV(s.windowStartMs),l=(i=s.exemplar)?{exemplars:[{filteredAttributes:[],timeUnixNano:tV(i.timeMs),asDouble:i.value,traceId:i.traceId,spanId:i.spanId}]}:{};if("count"===s.type){let e={attributes:a,startTimeUnixNano:o,timeUnixNano:t,asDouble:s.total??0,...l};n.sum.dataPoints.push(e)}else if("gauge"===s.type){let e={attributes:a,timeUnixNano:t,asDouble:s.last??0,...l};n.gauge.dataPoints.push(e)}else if(s.hist){let e={attributes:a,startTimeUnixNano:o,timeUnixNano:t,count:s.hist.count,sum:s.hist.sum,min:s.hist.min,max:s.hist.max,bucketCounts:s.hist.bucketCounts,explicitBounds:tU,...l};n.histogram.dataPoints.push(e)}}return Array.from(r.values())}_mergeWindowBack(e){for(let[t,r]of e){let e=this._series.get(t);if(!e){this._admitNewSeries()&&this._series.set(t,r);continue}switch(e.windowStartMs=Math.min(e.windowStartMs,r.windowStartMs),e.exemplar=e.exemplar??r.exemplar,e.type){case"count":e.total=(e.total??0)+(r.total??0);break;case"gauge":break;case"histogram":if(r.hist)if(e.hist){e.hist.count+=r.hist.count,e.hist.sum+=r.hist.sum,e.hist.min=Math.min(e.hist.min,r.hist.min),e.hist.max=Math.max(e.hist.max,r.hist.max);for(let t=0;t<e.hist.bucketCounts.length;t++)e.hist.bucketCounts[t]+=r.hist.bucketCounts[t]}else e.hist=r.hist}}}}let tW="unknown";function tK(e,t,r,i){return"string"==typeof e&&e.trim()?e.length>r?e.slice(0,r):e:(i?.debug(`${t} must be a non-empty string; using "${tW}"`),tW)}function tG(e){if(null==e)return;let t=e;if(e instanceof Date)try{t=e.getTime()}catch{return}if("number"==typeof t&&Number.isFinite(t)&&!(t<0)&&!(t>0x8637bd05af6))return t}function tQ(e,t,r,i){let s=tG(e);return void 0===s?(void 0!==e&&i?.debug(`Span ${r} is out of range or not a valid time; using the derived time`),t):s}function tJ(){let e=globalThis.performance;return"function"==typeof e?.now?e.now():void 0}class tZ{constructor(e,t,r){for(let i of(this._onEnd=t,this._logger=r,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=e.traceId,this._spanId=e.spanId,this._parentSpanId=e.parentSpanId,this._traceState=e.traceState,this._traceFlags=e.traceFlags??tL,this._parentIsRemote=e.parentIsRemote??!1,this._name=e.name,this._kind=e.kind,this._autoKeys=new Set(e.autoAttributeKeys),this._maxAttributes=e.maxAttributes,this._maxEvents=e.maxEvents,this._maxAttributesPerEvent=e.maxAttributesPerEvent,this._maxAttributeValueLength=e.maxAttributeValueLength,this._attributes=Object.create(null),Object.keys(e.attributes)))this._writeAttribute(i,e.attributes[i]);this._startMono=e.backdated?void 0:tJ(),this._startTime=e.clockAnchor&&void 0!==this._startMono?e.clockAnchor.wall+(this._startMono-e.clockAnchor.mono):e.startTime,void 0!==this._startMono&&(this._clockAnchor=e.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(void 0!==this._startMono){let e=tJ();if(void 0!==e)return this._startTime+Math.max(0,e-this._startMono)}return Date.now()}_mutable(e){return!this._ended||(this._logger?.debug(`Ignoring ${e} on a span that has already ended`),!1)}_writeAttribute(e,t){if(E(t)){e in this._attributes&&!this._autoKeys.has(e)&&this._userAttributeCount--,delete this._attributes[e];return}if(!this._autoKeys.has(e)&&!(e in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[e]=t6(t,this._maxAttributeValueLength)}setAttribute(e,t){return this._mutable("setAttribute")&&this._writeAttribute(e,t),this}setAttributes(e){if(this._mutable("setAttributes")){let t=tv({},e);for(let e of Object.keys(t))this._writeAttribute(e,t[e])}return this}addEvent(e,t,r){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let i=t&&t8(t,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:tK(e,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:tQ(r,this._now(),"event timestamp",this._logger),...i&&{attributes:i.attributes,...i.dropped&&{droppedAttributesCount:i.dropped}}})}return this}setStatus(e,t){if(this._mutable("setStatus")){if("ok"!==e&&"error"!==e)return this._logger?.debug(`Ignoring unknown span status "${String(e)}"; expected "ok" or "error"`),this;this._status={code:e,...t&&{message:t4(t,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(e){if(!this._mutable("recordException"))return this;let{type:t,message:r,stack:i}=t7(e);return this.addEvent(tY,{"exception.type":t,"exception.message":r,...i&&{"exception.stacktrace":i}}),this.setStatus("error",r)}updateName(e){return this._mutable("updateName")&&(this._name=tK(e,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return function(e,t,r=tL){return`00-${e}-${t}-${r}`}(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(e){var t;if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let r=tQ(e,this._now(),"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:r<(t=this._startTime)?t:r,...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}}let tY="exception";function tX(e){return"number"!=typeof e||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),0xffffffff)}class t0{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}}let t1=new t0;class t2 extends t0{constructor(e,t){super(),this._traceparent=e,this._tracestate=t}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}}function t3(e,t){var r;let i=tB(e?.parent)??t,s=tD(r="string"==typeof i||null==i?i:t5(i,"traceparent"))&&r.trim();return s?new t2(s,tq("string"==typeof i||null==i?e?.tracestate:t5(i,"tracestate"))):t1}function t5(e,t){try{let r=e[t];return"function"==typeof r?r.call(e):void 0}catch{return}}function t4(e,t){return e.length>t?e.slice(0,t):e}function t6(e,t){return function e(t,r,i,s){if(null===t||"object"!=typeof t)return E(t)||i.remainingNodes<=0?t:(i.remainingNodes--,"string"==typeof t?t4(t,r):t);if(i.ancestors.has(t))return tg;if(i.remainingNodes<=0||s>=20)return t;i.remainingNodes--,i.ancestors.add(t);try{if(t instanceof Date)return t;let n=function(e){try{let t=e.toJSON;if("function"==typeof t)return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}(t);if(n.selfDescribed)return E(n.value)?String(n.value):e(n.value,r,i,s+1);if(y(t)){let n=Math.min(t.length,1e3),a=[];for(let o=0;o<n;o++)try{a.push(e(t[o],r,i,s+1))}catch{a.push(ty)}return t.length>n&&(a.length=t.length),a}let a={},o=0;for(let n of Object.keys(t)){let l;if(o>=1e3)break;try{l=e(t[n],r,i,s+1)}catch{l=ty}n&&!E(l)&&o++,Object.defineProperty(a,n,{value:l,enumerable:!0,writable:!0,configurable:!0})}return a}catch{return t}finally{i.ancestors.delete(t)}}(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function t8(e,t,r){let i;try{i=Object.keys(e)}catch{return{attributes:{},dropped:0}}let s={},n=0,a=0;for(let o of i){let i;if(n>=t){a++;continue}try{i=t6(e[o],r)}catch{i=ty}E(i)||(n++,Object.defineProperty(s,o,{value:i,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:s,dropped:a}}function t9(e,t,r){return t===t1?r(t):e.with(t,()=>r(t))}function t7(e){try{let t=function(e){try{let t=e.stack;return"string"==typeof t&&t?{stack:t}:{}}catch{return{}}}(e);if(I(e))return{type:e.name||"Error",message:e.message||"",...t};if("string"==typeof e)return{type:"string",message:e};if(e&&"object"==typeof e&&"string"==typeof e.message)return{type:"string"==typeof e.name?e.name:"Object",message:e.message,...t};return{type:typeof e,message:String(e)}}catch{return{type:typeof e,message:""}}}let re={internal:1,server:2,client:3,producer:4,consumer:5},rt={ok:1,error:2};function rr(e){if("string"==typeof e)return t_(e);try{return t_(String(e))}catch{return ty}}function ri(e){let t=Math.floor(e),r=Math.round((e-t)*1e6);return r>=1e6&&(t+=1,r=0),String(t)+String(r).padStart(6,"0")}function rs(){return tJ()??Date.now()}function rn(e){try{return e instanceof tZ}catch{return!1}}function ra(e,t){let r=tj(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:tq(t),traceFlags:r.flags,isRemote:!0}}function ro(e,t,r){e[t]!==r&&(e[t]=r)}class rl{constructor(e,t,r,i,s,n){this._instance=e,this._config=t,this._logger=r,this._getContext=i,this._contextManager=s,this._onSpanQueued=n,this._queue=[],this._flushTimer=new tI(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter=new ti,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=t.maxExportBatchSize}startSpan(e,t){var r,i;let s;if(this._instance.isDisabled||this._instance.optedOut)return t3(t,this._contextManager.active());let n=tB(t?.parent);if(n&&"string"!=typeof n&&!rn(n)){if(function(e){try{return"function"==typeof e.traceparent}catch{return!1}}(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),t3(t,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let a=this._resolveParent(n,t);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached — spans are being started and never ended`),t3(t,this._contextManager.active());let o=Date.now(),l=(r=t?.startTime,i=this._logger,void 0===(s=tG(r))?(void 0!==r&&i?.debug("Span startTime is out of range or not a valid time; using the current time"),o):(o-s>864e5?i?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):s>o&&i?.debug("Span startTime is in the future; the span may export with a zero duration"),s)),u=tM(8);this._liveSpans.set(u,rs());let c=this._autoContextAttributes();return new tZ({traceId:a?.traceId??tM(16),spanId:u,parentSpanId:a?.parentSpanId,traceState:a?.traceState,traceFlags:a?.traceFlags,parentIsRemote:a?.isRemote,name:tK(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:t?.kind??"internal",attributes:tv({...c},t?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:l,backdated:l!==o,clockAnchor:void 0===tG(t?.startTime)?a?.clockAnchor:void 0},(e,t)=>this._onSpanEnd(e,t),this._logger)}withSpan(e,t,r){let i=this.startSpan(e,"function"==typeof t?void 0:t);try{let e=t9(this._contextManager,i,"function"==typeof t?t:r);if(e&&"function"==typeof e.then)return e.then(e=>(i.end(),e),e=>{throw this._recordCallbackError(i,e),i.end(),e});return i.end(),e}catch(e){throw this._recordCallbackError(i,e),i.end(),e}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;){if(!this._queue.length)return;let e=this._flushPromise;if(!await (e??this._startFlush()))return}}_startFlush(){this._flushTimer.clear();let e=this._generation,t=Promise.resolve().then(()=>e===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===t&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=t,t}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(e,t){if("string"==typeof e){let r=ra(e,t?.tracestate);return r||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),r}if(rn(e))return e.childContext();let r=this._contextManager.active();return rn(r)?r.childContext():r instanceof t2?ra(r.traceparent(),r.tracestate()??void 0):void 0}_autoContextAttributes(){let e;try{e=this._getContext()}catch(e){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",e),{}}let t={};return e.distinctId&&(t.posthogDistinctId=e.distinctId),e.sessionId&&(t.sessionId=e.sessionId),e.currentUrl&&(t["url.full"]=e.currentUrl),e.screenName&&(t["screen.name"]=e.screenName),e.appState&&(t["app.state"]=e.appState),t}_recordCallbackError(e,t){if(!(e instanceof tZ))return;let{type:r,message:i,stack:s}=t7(t);e.addEvent("exception",{"exception.type":r,"exception.message":i,...s&&{"exception.stacktrace":s}}),e.statusIsExplicitlyOk||e.setStatus("error",i)}_evictAgedSpans(){let e=rs()-this._config.maxSpanAgeMs,t=0;for(let[r,i]of this._liveSpans){if(i>e)break;this._liveSpans.delete(r),t++}t&&this._recordDrop(t,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(e,t){if(!this._liveSpans.delete(e.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let r=this._runBeforeSpanSend(e,t);if(r){if(this._reportLimitDrops(r),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) — raise the flush frequency or reduce span volume`);this._queue.push(r);try{this._onSpanQueued?.()}catch(e){this._logger.debug("Span queue notification failed",e)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(e){let t=e.droppedAttributesCount??0,r=e.droppedEventsCount??0,i=0;for(let t of e.events)i+=t.droppedAttributesCount??0;(t||r||i)&&this._logger.debug(`Span limits discarded data from "${e.name}": ${t} attributes, ${r} events, ${i} event attributes`)}_runBeforeSpanSend(e,t){if(!this._config.beforeSpanSend.length)return e;let r={traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,traceState:e.traceState},i={startTime:e.startTime,endTime:e.endTime},s={attributes:e.droppedAttributesCount,events:e.droppedEventsCount},n=Object.keys(e.attributes),a={traceFlags:e.traceFlags,parentIsRemote:e.parentIsRemote},o=e.status&&{...e.status},l=e,u=e;try{var c,h,d;for(let e of this._config.beforeSpanSend){let t=e(l);if(!t)return this._recordDrop(1,"beforeSpanSend dropped it"),null;l=this._keepSpanIdentity(t,r)}if(!((c=u={traceId:r.traceId,spanId:r.spanId,parentSpanId:r.parentSpanId,traceState:r.traceState,name:l.name,kind:l.kind,status:l.status,attributes:l.attributes,events:l.events,startTime:l.startTime,endTime:l.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:s.attributes,droppedEventsCount:s.events}).attributes&&"object"==typeof c.attributes&&!Array.isArray(c.attributes)&&Array.isArray(c.events)&&void 0!==c.name&&void 0!==c.kind&&void 0!==c.startTime&&void 0!==c.endTime))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;u.name=tK(u.name,"Span name",this._config.maxAttributeValueLength,this._logger),u.status&&"ok"!==u.status.code&&"error"!==u.status.code&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),u.status=o),u.startTime=tG(u.startTime)??i.startTime,u.endTime=(h=tG(u.endTime)??i.endTime,d=u.startTime,h<d?d:h);let e=[];for(let t of u.events)try{e.push({...t,name:tK(t.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:tQ(t.timestamp,u.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return u.events=e,!function(e,t,r,i,s,n,a=[]){let o=0,l=0,u={};for(let i of function(e,t){if(!t.length)return Object.keys(e);let r=t.filter(t=>Object.prototype.propertyIsEnumerable.call(e,t)),i=new Set(r);return[...r,...Object.keys(e).filter(e=>!i.has(e))]}(e.attributes,a)){let s=e.attributes[i];if(!E(s)){if(!t.has(i)){if(o>=r){l++;continue}o++}Object.defineProperty(u,i,{value:t6(s,n),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=u,l&&(e.droppedAttributesCount=tX(e.droppedAttributesCount)+l);let c=0,h=0,d=[];for(let t of e.events){if(c>=i){h++;continue}if(c++,t.attributes){let e=t8(t.attributes,s,n);t.attributes=e.attributes,e.dropped&&(t.droppedAttributesCount=tX(t.droppedAttributesCount)+e.dropped)}d.push(t)}e.events=d,h&&(e.droppedEventsCount=tX(e.droppedEventsCount)+h),e.status?.message&&(e.status={...e.status,message:t4(function(e){try{return"string"==typeof e?e:String(e)}catch{return ty}}(e.status.message),n)})}(u,t,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,n),u}catch(e){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",e),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(e,t){(e.traceId!==t.traceId||e.spanId!==t.spanId||e.parentSpanId!==t.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{ro(e,"traceId",t.traceId),ro(e,"spanId",t.spanId),ro(e,"parentSpanId",t.parentSpanId),ro(e,"traceState",t.traceState)}catch{try{let r=Object.getOwnPropertyDescriptors(e);for(let e of["traceId","spanId","parentSpanId","traceState"])r[e]={value:t[e],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(e),r)}catch{;}}return e}_recordDrop(e,t){this._droppedSinceWarning+=e,this._dropReasons.add(t),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(e){let t=[];for(let r of e)try{t.push(function(e,t){var r;let i,s={traceId:e.traceId,spanId:e.spanId,name:rr(e.name),kind:(r=e.kind)&&Object.prototype.hasOwnProperty.call(re,r)?re[r]:re.internal,startTimeUnixNano:ri(e.startTime),endTimeUnixNano:ri(e.endTime),flags:(Number.isFinite(i=parseInt(e.traceFlags,16))?255&i:1)|256|512*!!e.parentIsRemote};e.parentSpanId&&(s.parentSpanId=e.parentSpanId),e.traceState&&(s.traceState=rr(e.traceState));let n=tw(e.attributes,t);n.length&&(s.attributes=n),e.events.length&&(s.events=e.events.map(e=>(function(e,t){let r={name:rr(e.name),timeUnixNano:ri(e.timestamp)};if(e.attributes){let i=tw(e.attributes,t);i.length&&(r.attributes=i)}let i=tX(e.droppedAttributesCount);return i&&(r.droppedAttributesCount=i),r})(e,t)));let a=tX(e.droppedAttributesCount);a&&(s.droppedAttributesCount=a);let o=tX(e.droppedEventsCount);return o&&(s.droppedEventsCount=o),e.status&&(s.status={code:rt[e.status.code],...e.status.message&&{message:rr(e.status.message)}}),s}(r,this._logger))}catch(e){this._logger.debug("Failed to encode a span; dropping it",e),this._recordDrop(1,"its attributes could not be encoded")}return t}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let e=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(e,"the user has opted out"),this._warnAboutDrops(),e}async _flushInner(){var e,t;if(!this._queue.length)return 0;let r=this._discardQueueIfConsentWithdrawn();if(r)return r;let i=function(e,t){for(let r of Object.keys(e))e[r]=t6(e[r],t);return e}((e=this._config,tE(e,this._instance.getLibraryId(),this._instance.getLibraryVersion())),this._config.maxAttributeValueLength),s=this._instance.getLibraryId(),n=this._instance.getLibraryVersion(),a=this._queue.length,o=0,l=1/0,u=this._generation;try{for(;a>0&&this._queue.length>0;){let e=this._discardQueueIfConsentWithdrawn();if(e)return o+e;let r=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,c=Math.max(1,Math.min(r,l,a,this._queue.length)),h=this._queue.slice(0,c),d=this._encodeBatch(h);if(!d.length){this._queue.splice(0,c),a-=c,o+=c,this._resetHeadBatchBudget();continue}let f=rs()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),p=await this._instance._sendTracesBatch((t=this._logger,{resourceSpans:[{resource:{attributes:tF(i,t)},scopeSpans:[{scope:{name:s,version:n},spans:d}]}]}));if(u!==this._generation)break;if(this._retryAfter.record(p),"ok"===p.kind){this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._queue.splice(0,c),a-=c,o+=c,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if("too-large"===p.kind){if(1===c){this._queue.splice(0,1),a-=1,o+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget();continue}let e=Math.max(1,Math.floor(c/2));p.measuredLocally?l=e:this._maxExportBatchSize=e,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${e}`);continue}if("retry-later"===p.kind){if(this._consecutiveFlushFailures++,this._flushJitter=tA(),this._headBatchSize=c,f&&(this._headBatchFailures++,this._headBatchChargeableAt=rs()+this._nextFlushDelay()),this._headBatchFailures<8)return this._logger.debug("Span export failed; retrying on the next flush",p.error),o;if(this._queue.splice(0,c),a-=c,o+=c,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(c,"the ingestion endpoint failed 8 times in a row"),this._retryAfter.isOpen())return o;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",p.error),this._queue.splice(0,c),a-=c,o+=c,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(c,"the ingestion endpoint rejected the batch")}return o}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(e=>{this._logger.debug("Background span flush failed",e)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){!this._flushTimer.pending&&this._queue.length&&this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(tC(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}}var ru=e.i(2157),rc=e.i(12714),rh=e.i(50227),rd=e.i(1457);let rf=new ez.ReduceableCache(25),rp=new ez.ReduceableCache(20);async function rg(e,t=rc.open,r){let i,s={};try{i=process.cwd()}catch{}for(let t=e.length-1;t>=0;t--){var n,a;let r=e[t],o=r?.filename;!(!r||"string"!=typeof o||"number"!=typeof r.lineno||(n=o).startsWith("node:")||n.endsWith(".min.js")||n.endsWith(".min.cjs")||n.endsWith(".min.mjs")||n.startsWith("data:")||void 0!==(a=r).lineno&&a.lineno>1e4||void 0!==a.colno&&a.colno>1e3)&&((0,rh.isAbsolute)(o)||void 0!==i)&&(s[o]||(s[o]=[]),s[o].push(r.lineno))}let o=Object.keys(s);if(0==o.length)return e;let l=[];for(let e of o){let n=rv(e,i);if(void 0===n||rp.get(n))continue;let a=s[e];if(!a)continue;a.sort((e,t)=>e-t);let o=function(e){if(!e.length)return[];let t=0,r=e[0];if("number"!=typeof r)return[];let i=rb(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=rb(r)),t++}return s}(a);if(o.every(e=>(function(e,t){let r=rf.get(e);if(void 0===r)return!1;for(let e=t[0];e<=t[1];e++)if(void 0===r[e])return!1;return!0})(n,e)))continue;let u=function(e,t,r){let i=e.get(t);return void 0===i?(e.set(t,r),r):i}(rf,n,{});l.push(ry(e,o,u,n,t,r))}return await Promise.all(l).catch(()=>{}),e&&e.length>0&&function(e,t,r){for(let i of e)if(i.filename&&void 0===i.context_line&&"number"==typeof i.lineno){let e=rv(i.filename,r),s=void 0===e?void 0:t.get(e);if(void 0===s)continue;!function(e,t,r){if(void 0===t.lineno||void 0===r)return;t.pre_context=[];for(let i=rw(e);i<e;i++){let e=r[i];if(void 0===e)return void r_(t);t.pre_context.push(e)}if(void 0===r[e])return r_(t);t.context_line=r[e];let i=function(e){return e+7}(e);t.post_context=[];for(let s=e+1;s<=i;s++){let e=r[s];if(void 0===e)break;t.post_context.push(e)}}(i.lineno,i,s)}}(e,rf,i),rf.reduce(),e}async function rm(e,t,r){let i,s=!1;try{i=await t(e,ru.constants.O_RDONLY|ru.constants.O_NONBLOCK);let n=await i.stat();if(!n.isFile())return;if(n.size>0xa00000)return void r?.debug(`Skipping source context for oversized file ${e}: ${n.size} bytes exceeds 10485760`);return s=!0,i}catch{return}finally{i&&!s&&await i.close().catch(()=>{})}}async function ry(e,t,r,i,s,n){let a=await rm(e,s,n);return void 0===a?void rp.set(i,1):new Promise(e=>{let s,n,o=!1;function l(t){o||(o=!0,t?.destroy(),a.close().then(e,e))}try{s=a.createReadStream({autoClose:!1,start:0,end:0x9fffff})}catch{rp.set(i,1),l();return}try{n=(0,rd.createInterface)({input:s})}catch{rp.set(i,1),l(s);return}let u=0,c=0,h=t[0];if(void 0===h)return void l(s);let d=h[0],f=h[1];function p(){rp.set(i,1),n.close(),n.removeAllListeners(),l(s)}s.on("error",p),n.on("error",p),n.on("close",()=>l(s)),n.on("line",e=>{if(!(++u<d)&&(r[u]=function(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let s=Math.max(t-60,0);s<5&&(s=0);let n=Math.min(s+140,i);return n>i-5&&(n=i),n===i&&(s=Math.max(n-140,0)),r=r.slice(s,n),s>0&&(r=`...${r}`),n<i&&(r+="..."),r}(e,0),u>=f)){if(c===t.length-1){n.close(),n.removeAllListeners();return}let e=t[++c];if(void 0===e){n.close(),n.removeAllListeners();return}d=e[0],f=e[1]}})})}function r_(e){delete e.pre_context,delete e.context_line,delete e.post_context}function rv(e,t){return(0,rh.isAbsolute)(e)?JSON.stringify([null,e]):void 0===t?void 0:JSON.stringify([t,e])}function rb(e){return[rw(e),e+7]}function rw(e){return Math.max(1,e-7)}class rx{active(){return this._active}with(e,t){let r=this._active;this._active=e;try{return t()}finally{this._active=r}}}let rE=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","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"],rS=new Map,rF=function(e,t=[]){if(!e)return!1;let r=function(e,t){let r="";for(let e=0;e<t.length;e++){let i=t[e];r+=i.length+":"+i}return e.length+":"+e+"|"+t.length+":"+r}(e,t),i=rS.get(r);if(void 0!==i)return i;let s=e.toLowerCase(),n=rE.concat(t).some(e=>-1!==s.indexOf(e.toLowerCase()));return rS.size>=256&&rS.clear(),rS.set(r,n),n};function rP(e,t){return"number"==typeof e&&Number.isInteger(e)&&e>=1?e:t}let rI=["service.name","service.version","deployment.environment"],rA={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",LOCAL_EVALUATION_INCONCLUSIVE:"local_evaluation_inconclusive",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};e.s(["FeatureFlagError",0,rA],58325);class rC{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._unresolvedFlags=Object.freeze({...e.unresolvedFlags}),this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e,t={}){let r=this._flags[e];return this._recordAccess(e),r?.enabled??t.defaultValue??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),t)return!!t.enabled&&(t.variant??!0)}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let r=this._flags[t];r&&(e[t]=r)}return this._cloneWith(e)}only(e){let t={},r=[];for(let i of e){let e=this._flags[i];e?t[i]=e:r.push(i)}return r.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${r.join(", ")}`),this._cloneWith(t)}get keys(){return Object.keys(this._flags)}get unresolvedFlags(){return this._unresolvedFlags}_getEventProperties(){let e={},t=[];for(let[r,i]of Object.entries(this._flags)){let s=!1!==i.enabled&&(i.variant??!0);e[`$feature/${r}`]=s,i.enabled&&t.push(r)}return t.length>0&&(t.sort(),e.$active_feature_flags=t),e}_cloneWith(e){return new rC({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),""===this._distinctId||this._isSlice&&!(e in this._flags))return;let t=this._flags[e],r=void 0===t?void 0:!1!==t.enabled&&(t.variant??!0),i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:r,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};t?.hasExperiment!==void 0&&(i.$feature_flag_has_experiment=t.hasExperiment),t?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let s=[];this._errorsWhileComputing&&s.push(rA.ERRORS_WHILE_COMPUTING),this._quotaLimited&&s.push(rA.QUOTA_LIMITED),void 0===t&&s.push(Object.prototype.hasOwnProperty.call(this._unresolvedFlags,e)?rA.LOCAL_EVALUATION_INCONCLUSIVE:rA.FLAG_MISSING),s.length>0&&(i.$feature_flag_error=s.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:r,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}}let rk=["exact","is_not","icontains","not_icontains","starts_with","not_starts_with","ends_with","not_ends_with","regex","not_regex"];class r$ extends Error{constructor(e,t="unsupported_definition"){super(e),this.name=this.constructor.name,this.reason=t,Object.setPrototypeOf(this,r$.prototype)}}function rO(e){try{return e()}catch(e){if(e instanceof r$)throw new r$(e.message,"missing_context");throw e}}function rM(e){if("boolean"==typeof e)return!0;if("string"==typeof e){let t=e.toLowerCase();return"true"===t||"false"===t}if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!rM(t in e?e[t]:null))return!1;return!0}function rT(e){if("boolean"==typeof e)return e;if("string"==typeof e)return"true"===e.toLowerCase();if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!rT(t in e?e[t]:null))return!1;return!0}function rR(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let r=e.charCodeAt(t+1);if(t+1>=e.length||r<56320||r>57343)throw new r$("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new r$("Cannot stringify an unpaired surrogate like the flags service")}}function rj(e,t=new Set){if(null!==e&&"boolean"!=typeof e){if("string"==typeof e)return void rR(e);if("number"==typeof e){if(!Number.isFinite(e))throw new r$(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new r$("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&rj(e[r],t)}finally{t.delete(e)}return}if("object"==typeof e){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&null!==r)throw new r$("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new r$("Cannot represent a circular object during local evaluation");t.add(e);try{for(let r of Object.keys(e))rR(r),rj(e[r],t)}finally{t.delete(e)}return}throw new r$(`Cannot represent ${typeof e} like the flags service`)}}function rD(e,t){let r=0,i=0;for(;r<e.length&&i<t.length;){let s=e.charCodeAt(r),n=t.charCodeAt(i),a=s>=55296&&s<=56319,o=n>=55296&&n<=56319,l=a?e.charCodeAt(r+1):0,u=o?t.charCodeAt(i+1):0,c=a?(s-55296)*1024+l-56320+65536:s,h=o?(n-55296)*1024+u-56320+65536:n;if(c!==h)return c-h;r+=a?2:1,i+=o?2:1}return e.length-t.length}function rB(e){return"string"==typeof e?(rR(e),e):function e(t,r=new Set){if(null===t)return"null";if("string"==typeof t)return rR(t),JSON.stringify(t);if("boolean"==typeof t)return t?"true":"false";if("number"==typeof t){if(!Number.isFinite(t))throw new r$(`Cannot stringify non-finite number ${t} like the flags service`);if(Number.isInteger(t))throw new r$(`Cannot distinguish integer ${t} from an integral JSON float during local evaluation`);return String(t)}if(Array.isArray(t)){if(r.has(t))throw new r$("Cannot stringify a circular array during local evaluation");r.add(t);try{let i=[];for(let s=0;s<t.length;s++)i.push(s in t?e(t[s],r):"null");return`[${i.join(",")}]`}finally{r.delete(t)}}if("object"==typeof t){let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&null!==i)throw new r$("Cannot stringify a non-JSON object like the flags service");if(r.has(t))throw new r$("Cannot stringify a circular object during local evaluation");r.add(t);try{let i=Object.keys(t);return i.forEach(rR),`{${i.sort(rD).map(i=>`${JSON.stringify(i)}:${e(t[i],r)}`).join(",")}}`}finally{r.delete(t)}}throw new r$(`Cannot stringify ${typeof t} like the flags service`)}(e)}let rL=/[\x20-\x2f:;=?@\x5b-\x60\x7b-\x7e]/;function rN(e){let t=new r$(e);return Object.defineProperty(t,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),t}function rq(e){return String(e).replace(/[A-Z]/g,e=>e.toLowerCase())}function rU(e,t,r){if(!/^\d+$/.test(e)||"strict"===r&&e.length>1&&"0"===e[0])throw new r$(`Invalid semver: ${t}`);return parseInt(e,10)}function rV(e,t="strict"){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new r$(`Invalid semver: ${e}`);let i=r.split("."),s=r=>void 0===r||""===r?0:rU(r,e,t);return[s(i[0]),s(i[1]),s(i[2])]}function rz(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 rH(e,t){let r=rV(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function rW(e,t){let[r,i,s]=rV(e,t);return{lower:[r,i,s],upper:r>0?[r+1,0,0]:i>0?[0,i+1,0]:[0,0,s+1]}}function rK(e,t){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new r$(`Invalid wildcard semver: ${e}`);let i=r.split("."),s=r=>{if("legacy-permissive"===t){let e=parseInt(r,10);if(!isNaN(e))return e}else try{return rU(r,e,t)}catch{}throw new r$(`Invalid wildcard semver: ${e}`)},n=s(i[0]);if(1===i.length)return{lower:[n,0,0],upper:[n+1,0,0]};let a=s(i[1]);return{lower:[n,a,0],upper:[n,a+1,0]}}function rG(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 r$(`${e} is in an invalid date format`)}throw new r$(`The date provided ${e} must be a string, number, or date object`)}function rQ(e){if("boolean"==typeof e)throw new r$("Date operations cannot be performed on boolean values");return function(e){let t=e.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),r=new Date(new Date().toISOString());if(!t||!t.groups)return null;let i=parseInt(t.groups.number);if(i>=1e4)return null;let s=t.groups.interval;if("h"===s)r.setUTCHours(r.getUTCHours()-i);else if("d"===s)r.setUTCDate(r.getUTCDate()-i);else if("w"===s)r.setUTCDate(r.getUTCDate()-7*i);else if("m"===s)r.setUTCMonth(r.getUTCMonth()-i);else{if("y"!==s)return null;r.setUTCFullYear(r.getUTCFullYear()-i)}return r}(String(e))??rG(e)}function rJ(e,t={}){let r=e.value,i=t.semverParsingPolicy??"strict";switch(e.operator||"exact"){case"exact":case"is_not":for(let e of Array.isArray(r)?r:[r])rB(e);return;case"is_set":case"is_not_set":case"icontains":case"not_icontains":case"starts_with":case"not_starts_with":case"ends_with":case"not_ends_with":case"regex":case"not_regex":case"gt":case"gte":case"lt":case"lte":return;case"is_date_after":case"is_date_before":rQ(r);return;case"semver_eq":case"semver_neq":case"semver_gt":case"semver_gte":case"semver_lt":case"semver_lte":rV(String(r),i);return;case"semver_tilde":rH(String(r),i);return;case"semver_caret":rW(String(r),i);return;case"semver_wildcard":rK(String(r),i);return;default:throw new r$(`Unknown operator: ${e.operator}`)}}async function rZ(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");return Array.from(new Uint8Array(await t.digest("SHA-1",new TextEncoder().encode(e)))).map(e=>e.toString(16).padStart(2,"0")).join("")}async function rY(e,t,r="",i="."){return parseInt((await rZ(`${e}${i}${t}${r}`)).slice(0,15),16)/0x1000000000000000}async function rX(e,t){if(null==e||null==e.id||null==e.exclusion_percentage)return;let r=Number(e.exclusion_percentage);if(!Number.isFinite(r))return;let i=Math.min(Math.max(r,0),100);if(!(100!==i&&await rY("holdout",t,"","-")>i/100))return`holdout-${e.id}`}function r0(e){let t=[],r=0;for(let i of e){let e=r+i.rollout_percentage/100;t.push({valueMin:r,valueMax:e,key:i.key}),r=e}return t}async function r1(e,t,r){let i=await rY(e,t,"variant");return r0(r).find(e=>i>=e.valueMin&&i<e.valueMax)?.key}function r2(e){return"client"===e||"server"===e?e:"all"}class r3 extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,r3.prototype)}}class r5 extends Error{constructor(e){super(e),this.reason="unsupported_definition",this.name=r5.name,Error.captureStackTrace(this,r5),Object.setPrototypeOf(this,r5.prototype)}}let r4=["experience_continuity","unsupported_definition","unresolved_dependency","missing_context"];function r6(e,t){return void 0===e||r4.indexOf(t)<r4.indexOf(e)?t:e}function r8(e,t){return t instanceof r$&&Symbol.for("posthog.requiresServerRegexEvaluation")in t&&Object.defineProperty(e,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),e}class r9{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:i,host:s,customHeaders:n,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.warnedUnresolvableFlags=new Map,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=r,this.host=s,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=n,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}currentDefinitions(){return{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}withEvaluationSnapshot(e){return e.definitions?e:{...e,evaluationCache:{},definitions:this.currentDefinitions()}}createEvaluationContext(e,t={},r={},i={},s={}){return{distinctId:e,groups:t,personProperties:r,groupProperties:i,evaluationCache:s}}async getFeatureFlag(e,t,r={},i={},s={}){let n,a;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return n;if(void 0!==(a=this.featureFlagsByKey[e])){let o=this.createEvaluationContext(t,r,i,s);try{n=(await this.computeFlagAndPayloadLocally(a,o)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${n}`))}catch(t){t instanceof r5||t instanceof r$?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e}: ${t}`))}}return n}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let r={},i={},s={},n=0==this.featureFlags.length,a=t?t.map(e=>this.featureFlagsByKey[e]).filter(Boolean):this.featureFlags,o=this.withEvaluationSnapshot({...e,definitions:void 0});return await Promise.all(a.map(async e=>{try{let{value:t,payload:s}=await this.computeFlagAndPayloadLocally(e,o,{skipLoadCheck:!0});r[e.key]=t,s&&(i[e.key]=s)}catch(t){t instanceof r5||t instanceof r$?(this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e.key}: ${t.message}`)),s[e.key]=t.reason):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e.key}: ${t}`)),n=!0}})),{response:r,payloads:i,unresolved:s,fallbackToFlags:n}}async computeFlagAndPayloadLocally(e,t,r={}){let i,{matchValue:s,skipLoadCheck:n=!1}=r;if(this.loadedSuccessfullyOnce&&(t=this.withEvaluationSnapshot(t)),n||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};e=(t=this.withEvaluationSnapshot(t)).definitions.featureFlagsByKey[e.key]??e,i=void 0!==s?s:await this.computeFlagValueLocally(e,t);let a=function(e,t){if(!1===t||null==t||!e)return null;let r=e["boolean"==typeof t?t.toString():t]||null;return null==r?null:e5(r)}(e.filters?.payloads,i);return{value:i,payload:a}}async computeFlagValueLocally(e,t){let{distinctId:r,groups:i,personProperties:s,groupProperties:n}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new r$("Flag has experience continuity enabled","experience_continuity");let a=(e.filters||{}).aggregation_group_type_index;if(void 0!=a){let r=t.definitions.groupTypeMapping[String(a)];if(!r)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${a} for feature flag ${e.key}`)),new r$("Flag has unknown group type index");if(!(r in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;"device_id"===e.bucketing_identifier&&(s?.$device_id===void 0||s?.$device_id===null||s?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let o=n[r];return await this.matchFeatureFlagProperties(e,i[r],o,t)}{let i=this.getBucketingValueForFlag(e,r,s);if(void 0===i)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new r$(`Can't compute feature flag: ${e.key} without $device_id`,r7(e,t.definitions)??"missing_context");return await this.matchFeatureFlagProperties(e,i,s,t)}}getBucketingValueForFlag(e,t,r){if(e.filters?.aggregation_group_type_index!=void 0)return t;if("device_id"===e.bucketing_identifier){let e=r?.$device_id;if(null==e||""===e)return;return e}return t}async evaluateFlagDependency(e,t,r){let{evaluationCache:i}=r,s=e.key;if(!r.definitions.featureFlagsByKey)throw new r$("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new r$(`Flag dependency property for '${s}' is missing required 'dependency_chain' field`);let n=e.dependency_chain;if(!Array.isArray(n))throw new r$(`Flag dependency property for '${s}' has an invalid 'dependency_chain' (expected array, got ${typeof n})`);if(0===n.length)throw new r$(`Circular dependency detected for flag '${s}' (empty dependency chain)`);let a=n.find(e=>!(e in i)&&!r.definitions.featureFlagsByKey[e]&&!r.definitions.filteredOutFlagKeys.has(e));if(void 0!==a)throw new r$(`Missing flag dependency '${a}' for flag '${s}'`);for(let e of n){if(!(e in i)){let t=r.definitions.featureFlagsByKey[e];if(t)if(t.active)try{let s=await this.computeFlagValueLocally(t,r);i[e]=s}catch(t){throw r8(new r$(`Error evaluating flag dependency '${e}' for flag '${s}': ${t}`,"unresolved_dependency"),t)}else i[e]=!1;else i[e]=!1}if(null==i[e])throw new r$(`Dependency '${e}' could not be evaluated`,"unresolved_dependency")}let o=i[s];return this.flagEvaluatesToExpectedValue(e.value,o)}flagEvaluatesToExpectedValue(e,t){return"boolean"==typeof e?e===t||"string"==typeof t&&""!==t&&!0===e:"string"==typeof e&&t===e}async matchFeatureFlagProperties(e,t,r,i){let s,n,a;i=this.withEvaluationSnapshot(i);let o=e.filters||{},l=await rX(o.holdout,t);if(void 0!==l)return l;let u=o.groups||[],c=o.aggregation_group_type_index,h=o.early_exit??!1,{groups:d,groupProperties:f}=i,p=new Set;for(let l of u){let u=t;try{let t=void 0!==l.aggregation_group_type_index?l.aggregation_group_type_index:c,n=r;if(t!==c&&null!=t){let r=i.definitions.groupTypeMapping[String(t)];if(!r||!(r in d)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${t} not available`));continue}if(!(r in f)){s=r6(s,"missing_context");continue}n=f[r],u=d[r]}let p=await this.isConditionMatch(e,u,l,n,i);if("match"===p){let t=l.variant,r=o.multivariate?.variants||[];a=t&&r.some(e=>e.key===t)?t:await this.getMatchingVariant(e,u)||!0;break}if(h&&"out_of_rollout_bound"===p){if(s)break;return!1}}catch(t){if(t instanceof r5)throw t;if(t instanceof r$){if(s=r6(s,t.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in t)if(n=t,h&&void 0!=l.rollout_percentage&&await rY(e.key,u)>l.rollout_percentage/100)p.add(!1);else{let t=o.multivariate?.variants||[],r=l.variant;p.add(r&&t.some(e=>e.key===r)?r:await this.getMatchingVariant(e,u)||!0)}}else throw t}}if(void 0!==a&&!(n&&[...p].some(e=>e!==a)))return a;if(s)throw r8(new r$("Can't determine if feature flag is enabled or not with given properties",s),n);return!1}async isConditionMatch(e,t,r,i,s){let n=(s=this.withEvaluationSnapshot(s)).definitions,a=r.rollout_percentage,o=e=>{this.logMsgIfDebug(()=>console.warn(e))};if((r.properties||[]).length>0){let t,l,u;for(let e of r.properties){let r=e.type,a=!1;try{if("cohort"===r){let t=await it(e,i,n.cohorts,this.debugMode,e=>this.evaluateFlagDependency(e,i,s),n.propertyMatchingVersion);a="not_in"===e.operator?!t:t}else if("flag"===r)a=await this.evaluateFlagDependency(e,i,s);else if(Object.prototype.hasOwnProperty.call(i,e.key))a=ie(e,i,o,n.propertyMatchingVersion);else{rJ(e),t=r6(t,"missing_context");continue}}catch(e){if(e instanceof r5){void 0===t&&(u??=e),t=r6(t,e.reason);continue}if(e instanceof r$){Symbol.for("posthog.requiresServerRegexEvaluation")in e&&(l=e),t=r6(t,e.reason);continue}throw e}if(!a)return"no_match"}if(u)throw u;if(t)throw r8(new r$(`Can't determine if a condition of flag ${e.key} matches`,t),l);if(void 0==a)return"match"}return void 0!=a&&await rY(e.key,t)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){return r1(e.key,t,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return r0(e.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(e){if(!this.evaluationContexts||0===this.evaluationContexts.length)return e;let t=new Set(this.evaluationContexts);return e.filter(e=>{let r=e.evaluation_contexts??e.evaluation_tags;return!r||0===r.length||r.some(e=>t.has(e))})}getEvaluationRuntimeForFlag(e){let t=this.featureFlagsByKey[e];return t?r2(t.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(e){return this.featureFlags.filter(t=>{var r;return(r=r2(t.evaluation_runtime))===e||"all"===r||"all"===e}).map(e=>e.key)}updateFlagState(e){let t=this.filterFlagsByEvaluationContexts(e.flags),r=t.reduce((e,t)=>(e[t.key]=t,e),{}),i=new Set(t.map(e=>e.key)),s=new Set(e.flags.filter(e=>!i.has(e.key)).map(e=>e.key));this.featureFlags=t,this.featureFlagsByKey=r,this.filteredOutFlagKeys=s,this.groupTypeMapping=e.group_type_mapping??e.groupTypeMapping??{},this.cohorts=e.cohorts,this.propertyMatchingVersion=e.property_matching_version??e.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((e.minimal_flag_called_events??e.minimalFlagCalledEvents)===!0)}warnAboutUnresolvableFlags(e){let t=[],r=[],i=new Map,s=this.currentDefinitions();for(let n of e){let e=r7(n,s);if(!e)continue;let a=JSON.stringify(n);i.set(n.key,a),this.warnedUnresolvableFlags.get(n.key)!==a&&("experience_continuity"===e?t.push(n.key):r.push(n.key))}if(this.warnedUnresolvableFlags=i,t.length>0){let e=this.strictLocalEvaluation?"With strictLocalEvaluation enabled these flags are left unresolved. To evaluate them locally, disable experience continuity on these flags in PostHog.":"Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).";console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled and cannot be resolved locally (reason: experience_continuity): ${t.join(", ")}. `+e)}if(r.length>0){let e=this.strictLocalEvaluation?"With strictLocalEvaluation enabled these flags are left unresolved when evaluation reaches that part.":"Evaluating these flags falls back to a server request when evaluation reaches that part.";console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) use something local evaluation does not support, such as a static cohort, an unknown operator, or a missing or circular flag dependency (reason: unsupported_definition): ${r.join(", ")}. ${e} To evaluate them locally, change these flags in PostHog or upgrade posthog-node.`)}}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();if(t)return this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags),!0;return!1}catch(e){return this.onError?.(Error(`Failed to load from cache: ${e}`)),!1}}async loadFeatureFlags(e=!1){if(!this.loadedSuccessfullyOnce||e)return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(e=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${e}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let e=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(6e4,e*2**this.backOffCount):e}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{if(this.cacheProvider&&!this.personalApiKey)return void await this.loadFromCache("Loaded flags from cache (cache-only reader)");let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(e){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${e}`))}if(!e&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new r3(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new r3(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new r3(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let r=await t.json()??{};if(!("flags"in r))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let i=r.group_type_mapping||{},s=!0===r.minimal_flag_called_events,n={flags:r.flags??[],group_type_mapping:i,cohorts:r.cohorts||{},minimal_flag_called_events:s,property_matching_version:r.property_matching_version,propertyMatchingVersion:r.property_matching_version,groupTypeMapping:i,minimalFlagCalledEvents:s};if(this.updateFlagState(n),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(e){this.onError?.(Error(`Failed to store in cache: ${e}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags);break}default:return}}catch(e){e instanceof r3&&this.onError?.(e)}finally{this.pollerStopped||null===this.pollingInterval||(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(e="GET",t){let r={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(r["If-None-Match"]=t),{method:e,headers:r}}async _requestFeatureFlagDefinitions(){if(!this.personalApiKey)throw new r3("A secretKey or personalApiKey is required to fetch feature flag definitions from PostHog.");let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),r=null;if(this.timeout&&"number"==typeof this.timeout){let e=new AbortController;r=V(()=>{e.abort()},this.timeout),t.signal=e.signal}try{let i=this.fetch,s=await i(e,t);if(200!==s.status)return clearTimeout(r),s;return{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{clearTimeout(r)}},json:async()=>{try{return await s.json()}finally{clearTimeout(r)}}}}catch(e){throw clearTimeout(r),e}}async stopPoller(e=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await z(t,e,()=>{throw Error(`Cache shutdown timeout after ${e}ms`)})}catch(e){this.onError?.(Error(`Error during cache shutdown: ${e}`))}}}function r7(e,t){if(!e.active)return;if(e.ensure_experience_continuity)return"experience_continuity";let r=e.filters||{},i=r.aggregation_group_type_index;return void 0==i||t.groupTypeMapping[String(i)]?(r.groups||[]).some(e=>(e.properties||[]).some(e=>(function e(t,r,i){if("flag"===t.type){let e=t.dependency_chain;return!Array.isArray(e)||0===e.length||e.some(e=>!r.featureFlagsByKey[e]&&!r.filteredOutFlagKeys.has(e))}if("cohort"!==t.type)try{return rJ(t),!1}catch(e){if(e instanceof r$)return!0;throw e}let s=String(t.value);return!(s in r.cohorts)||!i.has(s)&&(i.add(s),function t(r,i,s){return(r?.values??[]).some(r=>"values"in r?t(r,i,s):e(r,i,s))}(r.cohorts[s],r,i))})(e,t,new Set)))?"unsupported_definition":void 0:"unsupported_definition"}function ie(e,t,r,i){return function(e,t,r={}){try{return function(e,t,r){let i=e.key,s=e.value,n=e.operator||"exact",a=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,i)){if("is_not_set"===n)return!1;else if("is_set"===n)return!0}else throw new r$(`Property ${i} not found in propertyValues`,"missing_context");let o=t[i];if(void 0===o)throw r.warnFunction?.(`Property ${i} cannot have a value of undefined with the ${n} operator`),new r$(`Property ${i} is undefined in propertyValues`);if(null===o&&!rk.includes(n))return r.warnFunction?.(`Property ${i} cannot have a value of null with the ${n} operator`),!1;let l=(e,t)=>{if(2!==r.propertyMatchingVersion&&rM(e)||Array.isArray(e)&&0===e.length)return rO(()=>rj(t)),rT(e)===rT(t);if(2===r.propertyMatchingVersion&&"number"==typeof t&&rM(e))return rO(()=>rj(t)),!1;if(Array.isArray(e)){let r=rO(()=>rB(t)).toLowerCase();return e.some(e=>rB(e).toLowerCase()===r)}return rB(e).toLowerCase()===rO(()=>rB(t)).toLowerCase()},u=(e,t,r)=>{if("gt"===r)return e>t;if("gte"===r)return e>=t;if("lt"===r)return e<t;if("lte"===r)return e<=t;throw Error(`Invalid operator: ${r}`)},c=()=>rO(()=>rV(String(o),a)),h=()=>{let e=rV(String(s),a);return rz(c(),e)},d=({lower:e,upper:t})=>{let r=c();return rz(r,e)>=0&&0>rz(r,t)};switch(n){case"exact":return l(s,o);case"is_not":return!l(s,o);case"is_set":return!0;case"icontains":return rq(o).includes(rq(s));case"not_icontains":return!rq(o).includes(rq(s));case"starts_with":return rq(o).startsWith(rq(s));case"not_starts_with":return!rq(o).startsWith(rq(s));case"ends_with":return rq(o).endsWith(rq(s));case"not_ends_with":return!rq(o).endsWith(rq(s));case"regex":case"not_regex":{let e=function(e,t){let r;if(""===e)return!0;let i=function(e){let t=[],r=-1,i="";for(let s=0;s<e.length;s++){let n=e[s];if(n.charCodeAt(0)>127)return null;if("\\"===n){let t=e[++s];if(void 0===t)break;if("x"===t){if(!/^[\da-f]{2}$/i.test(e.slice(s+1,s+3)))return null;s+=2}else if(!"dDsSwWbBfnrtv".includes(t)&&!rL.test(t))return null;if(-1===r&&"bB".includes(t))return null;i="literal";continue}if("["===n){if(-1!==r)return null;r=s}else if("]"===n&&-1!==r){if(s===r+("^"===e[r+1]?2:1))return null;t.push(e.slice(r,s+1)),r=-1,i="literal";continue}else if(-1!==r){if(["&&","--","~~"].includes(e.slice(s,s+2)))return null;continue}else if("("===n&&"?"===e[s+1]){if(":"!==e[s+2])return null;s+=2}else if("{"===n){let t=/^\{(\d+)(?:,(\d*))?\}/.exec(e.slice(s));if(!t||["","|","("].includes(i)||t.slice(1).some(e=>Number(e)>0xffffffff))return null}else if("*+?}".includes(n)&&("+"===e[s+1]||"{"===e[s+1]))return null;if("*+?{".includes(n)&&["^","$","empty group"].includes(i))return null;i=")"===n&&["(","empty group"].includes(i)?"empty group":n}return t}(e);if(null===i)throw rN("Regex syntax requires server evaluation");try{r=new RegExp(e)}catch(e){if(e instanceof SyntaxError)return null;throw rN("Regex compilation requires server evaluation")}for(let e of i)try{RegExp(e,"u")}catch{throw rN("Regex character class syntax requires server evaluation")}for(let e=0;e<t.length;e++){let r=t[e];if(r.charCodeAt(0)>127||"\r"===r)throw rN("Regex matching for Unicode or carriage returns requires server evaluation")}try{return r.test(t)}catch{throw rN("Regex execution requires server evaluation")}}(String(s),String(o));if(null===e)return!1;return"regex"===n?e:!e}case"gt":case"gte":case"lt":case"lte":{let e="number"==typeof s?s:parseFloat(String(s)),t="number"==typeof o?o:null!=o?parseFloat(String(o)):0/0;if(Number.isFinite(e)&&Number.isFinite(t))return u(t,e,n);return u(String(o),String(s),n)}case"is_date_after":case"is_date_before":{let e=rQ(s),t=rO(()=>rG(o));return"is_date_before"===n?t<e:t>e}case"semver_eq":return 0===h();case"semver_neq":return 0!==h();case"semver_gt":return h()>0;case"semver_gte":return h()>=0;case"semver_lt":return 0>h();case"semver_lte":return 0>=h();case"semver_tilde":return d(rH(String(s),a));case"semver_caret":return d(rW(String(s),a));case"semver_wildcard":return d(rK(String(s),a));default:throw new r$(`Unknown operator: ${n}`)}}(e,t,r)}catch(t){throw t instanceof r$&&"missing_context"===t.reason&&rJ(e,r),t}}(e,t,{warnFunction:r,propertyMatchingVersion:i})}async function it(e,t,r,i=!1,s,n){let a=String(e.value);if(!(a in r))throw new r5(`cohort ${a} not found in local cohorts - likely a static cohort that requires server evaluation`);return ir(r[a],t,r,i,s,n)}async function ir(e,t,r,i=!1,s,n){let a,o;if(!e)return!0;let l=e.type,u=e.values;if(!u||0===u.length)return!0;if("values"in u[0]){for(let e of u)try{let a=await ir(e,t,r,i,s,n);if("AND"===l){if(!a)return!1}else if(a)return!0}catch(t){if(t instanceof r5)throw t;if(t instanceof r$)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),a=r6(a,t.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in t&&(o=t);else throw t}if(a)throw r8(new r$("Can't match cohort without a given cohort property value",a),o);return"AND"===l}for(let e of u)try{let a;if("cohort"===e.type)a=await it(e,t,r,i,s,n);else if("flag"===e.type){if(!s)throw new r$(`Flag dependency '${e.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);a=await s(e)}else a=ie(e,t,void 0,n);let o=e.negation||!1;if("AND"===l){if(!a&&!o||a&&o)return!1}else if(a&&!o||!a&&o)return!0}catch(t){if(t instanceof r5)throw t;if(t instanceof r$)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),a=r6(a,t.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in t&&(o=t);else throw t}if(a)throw r8(new r$("can't match cohort without a given cohort property value",a),o);return"AND"===l}let ii=["--unhandled-rejections","--unhandled_rejections"],is=new Set(["throw","strict","warn","warn-with-error-code","none"]),ia=[...globalThis.process?.execArgv??[]],io=globalThis.process?.env?.NODE_OPTIONS;function il(e){let t;for(let r=0;r<e.length;r++){let i=e[r],s=ii.find(e=>i===e||i.startsWith(`${e}=`));if(!s)continue;let n=i===s?e[++r]:i.slice(s.length+1);is.has(n)&&(t=n)}return t}let iu=function(e=ia,t=io){return il(e)??il(function(e){let t=[],r="",i=!1;for(let s=0;s<e.length;s++){let n=e[s];"\\"===n&&i&&s+1<e.length?r+=e[++s]:" "!==n||i?'"'===n?i=!i:r+=n:r&&(t.push(r),r="")}return r&&t.push(r),t}(t??""))??"throw"}();function ic(e,t,r){e(t,{mechanism:{type:"unhandledRejection"===r?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function ih(e,t,r,i,s){if(t>r&&(i.warn("min cannot be greater than max."),t=r),S(e))if(e>r)return i.warn(" cannot be greater than max: "+r+". Using max value instead."),r;else return e<t?(i.warn(" cannot be less than min: "+t+". Using min value instead."),t):e;return i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+s),ih(s??r,t,r,i)}class id{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=ih(e.bucketSize,0,100,e._logger),this._refillRate=ih(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=ih(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){let r=Math.floor((t-e.lastAccess)/this._refillInterval);if(r>0){let t=r*this._refillRate;e.tokens=Math.min(e.tokens+t,this._bucketSize),e.lastAccess=e.lastAccess+r*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),r=String(e),i=this._buckets[r];return i?this._applyRefill(i,t):(i={tokens:this._bucketSize,lastAccess:t},this._buckets[r]=i),0===i.tokens||(i.tokens--,0===i.tokens&&this._onBucketRateLimited?.(e),0===i.tokens)}stop(){this._buckets={}}}var ip=ez;let ig=class t{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new id({...function(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??1,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??10}}(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return _(e)&&"__posthog_previously_captured_error"in e&&!0===e.__posthog_previously_captured_error}static async buildEventMessage(e,t,r,i,s){let n={...s},a=e.buildFromUnknown(t,r);a.$exception_list=await e.modifyFrames(a.$exception_list);let o=ip.getInjectedReleaseId();return o&&(n.$release_id=o),{event:"$exception",distinctId:i,properties:{...a,...n},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(!function(t,r,i=iu){let s=globalThis.process;if(s){let n;if("strict"===i)return s.on("uncaughtExceptionMonitor",(e,r)=>ic(t,e,r));s.on("uncaughtException",(n=!1,Object.assign((i,s)=>{let a=e.g.process.listeners("uncaughtException").filter(e=>"domainUncaughtExceptionClear"!==e.name&&!0!==e._posthogErrorHandler).length;ic(t,i,s),n||0!==a||(n=!0,r(i))},{_posthogErrorHandler:!0})))}}(this.onException.bind(this),this.onFatalError.bind(this)),function(e,t=iu){let r=globalThis.process;r&&"throw"!==t&&"strict"!==t&&"warn-with-error-code"!==t&&r.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}(this.onException.bind(this)))}onException(e,r){this.client.addPendingPromise((async()=>{if(!t.isPreviouslyCapturedError(e)){let i=await t.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,r),s=i.properties,n=s?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(n)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:n}):this.client._capturePreparedEvent(i,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(2e3),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},im=/^[0-9a-f]{32}$/i,iy=/^[0-9a-f]{16}$/i;async function i_(){try{let t=await (o??=e.A(99332)),r=t.trace.getActiveSpan()?.spanContext(),i=r?.traceId,s=r?.spanId;if("string"==typeof i&&"string"==typeof s&&im.test(i)&&iy.test(s)&&!/^0+$/.test(i)&&!/^0+$/.test(s))return{$trace_id:i.toLowerCase(),$span_id:s.toLowerCase()}}catch{}return{}}class iv{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=null!==t?t:void 0}constructor(){this._memoryStorage={}}}let ib="analytics";class iw extends Error{constructor({requestId:e,drops:t,retryExhausted:r,cause:i}){super(iw.buildMessage(e,t,r,i)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=r,this.cause=i}static buildMessage(e,t,r,i){let s=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${r.length} undelivered`;return i instanceof Error&&(s+=` (${i.message})`),s}}function ix(e){if("boolean"==typeof e)return e;if("number"==typeof e)return 0!==e;if("string"==typeof e){let t=e.trim().toLowerCase();if("true"===t||"1"===t)return!0;if("false"===t||"0"===t)return!1}}let iE=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:ix},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:ix},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:ix},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(e){return"string"==typeof e?e:void 0}}],iS=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function iF(e,t,r){void 0===r||t in e||(e[t]=r)}function iP(e){var t;let r={..."object"==typeof(t=e.properties)&&null!==t&&!Array.isArray(t)?e.properties:{}},i={};for(let{property:e,optionKey:t,coerce:s}of iE)if(e in r){let n=s(r[e]);void 0!==n&&(i[t]=n),delete r[e]}let s={};for(let{property:e,field:t}of iS)if(e in r){let i=r[e];"string"==typeof i&&(s[t]=i),delete r[e]}return delete r.$lib,delete r.$lib_version,iF(r,"$set",e.$set),iF(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:function(e){if("string"==typeof e){let t=new Date(e);if(Number.isNaN(t.getTime()))return new Date().toISOString();let r=t.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?r.replace(/\.\d{3}Z$/,`.${i}Z`):r}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=null==e?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}(e.timestamp),...s,options:i,properties:r}}let iI=new Set([408,500,502,503,504]);class iA{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??3e4,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??(e=>new Promise(t=>V(t,e))),this.generateRequestId=t.generateRequestId??eQ,this.compress=t.compress??te}async sendV1Batch(e){if(0===e.length)return;let t=this.generateRequestId(),r=new Date(this.now()).toISOString(),{batch:i}=function(e,{createdAt:t,historicalMigration:r}){let i={created_at:t,batch:e.map(iP)};return r&&(i.historical_migration=!0),i}(e,{createdAt:r,historicalMigration:this.config.historicalMigration}),s=`${this.config.host}/i/v1/analytics/events`,n=[],a=i,o=Math.max(1,this.config.maxAttempts);for(let e=1;e<=o;e++){let i,l,u=e===o,c=f({created_at:r,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a});try{let{response:r,signal:o}=i=await this.sendOnce(s,c,e,t),{status:h}=r;if(h<200||h>=300)if(!u&&iI.has(h)){let t=this.parseRetryAfter(r);await i.waitFor(i.cancelBody()).catch(()=>{}),l=this.backoffDelay(e,t)}else{let e=await this.buildHttpError(r,h,i.waitFor);return this.surfaceBatchFailure(t,n,a,e)}else{let s;try{s=await i.waitFor(this.parseResponse(r))}catch(e){if(o.aborted)throw e;return this.surfaceBatchFailure(t,n,a,Error(`Capture V1 returned an unparseable ${h} response body`))}let c=this.classify(a,s,n);if(0===c.length)return this.surfacePartialDrops(t,n);if(u)return void this.onError(new iw({requestId:t,drops:n,retryExhausted:c.map(e=>e.uuid)}));a=c;let d=this.parseRetryAfter(r);l=this.backoffDelay(e,d)}}catch(r){if(i&&!i.signal.aborted)throw r;if(u)return this.surfaceBatchFailure(t,n,a,r);l=this.backoffDelay(e)}finally{i?.cleanup()}void 0!==l&&await this.sleep(l)}}async sendOnce(e,t,r,i){let s,n=this.buildHeaders(r,i),a=t;if(this.config.compressionEnabled){let e=await this.compress(t,this.config.isDebug);null!==e&&(a=e,n["Content-Encoding"]="gzip")}let o=new AbortController,l="waiting for response headers",u=new Promise((e,t)=>{s=V(()=>{let e=Error(`Capture V1 request timed out ${l} after ${this.config.requestTimeoutMs}ms`);e.name="AbortError",t(e),o.abort(e)},this.config.requestTimeoutMs)});try{let t,r=this.fetchFn(e,{method:"POST",headers:n,body:a,signal:o.signal}),i=!1;r.then(e=>{o.signal.aborted&&!i&&this.cancelBody(e)}).catch(()=>{});let c=await Promise.race([r,u]);i=!0,l="while reading the response body";let h=!1,d=()=>t??=this.cancelBody(c);return{response:c,signal:o.signal,waitFor:e=>Promise.race([e,u]),cancelBody:d,cleanup:()=>{!h&&(h=!0,clearTimeout(s),o.signal.aborted&&d())}}}catch(e){throw clearTimeout(s),e}}buildHeaders(e,t){let r=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":r,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(i["User-Agent"]=this.config.userAgent),i}classify(e,t,r){let i=t.results??{},s=[];for(let t of e){let e=i[t.uuid];e&&("drop"===e.result?r.push({uuid:t.uuid,details:e.details??void 0}):"retry"===e.result&&s.push(t))}return s}backoffDelay(e,t){let r=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return void 0===t?r:Math.max(r,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let r=t.trim();if(/^\d+$/.test(r)){let e=parseInt(r,10);return Number.isFinite(e)&&e>0?1e3*e:void 0}let i=Date.parse(r);if(Number.isNaN(i))return;let s=i-this.now();return s>0?s:void 0}async parseResponse(e){let t=JSON.parse(await e.text());if("object"!=typeof t||null===t||Array.isArray(t))throw Error("unexpected response shape");let r=t.results;if(void 0!==r&&("object"!=typeof r||null===r||Array.isArray(r)))throw Error("unexpected results shape");return{results:r??{}}}async buildHttpError(e,t,r){let i="";try{i=(await r(e.text())).slice(0,512)}catch{}let s=i?`: ${i}`:"";return Error(`Capture V1 request failed with HTTP ${t}${s}`)}surfaceBatchFailure(e,t,r,i){this.onError(new iw({requestId:e,drops:t,retryExhausted:r.map(e=>e.uuid),cause:i}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new iw({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}}let iC="ai-capture",ik="/i/v0/ai/batch/",i$=new TextEncoder;function iO(e){return i$.encode(f(e)).length}let iM=new Set;function iT(e,t){iM.has(e)||(iM.add(e),console.warn(`[PostHog] ${t}`))}class iR extends tp{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(e){this._distinctIdHasSentFlagCalls=new Map(Object.entries(e??{}))}constructor(e,t={}){var r,i;let s,n="string"==typeof e?e.trim():"",a={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:("string"==typeof(r=t.host)?r.trim():"")||"https://us.i.posthog.com",personalApiKey:("string"==typeof(i=t.secretKey??t.personalApiKey)?i.trim():"")||void 0};if(super(n,a),this._memoryStorage=new iv,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=a,this.captureMode="v0"===(s="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0)||"v1"===s?s:"v0",this.enableFullAiCapture=!0===a.enableFullAiCapture,this.privacyMode=!0===a.privacyMode,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof a.featureFlagsPollingInterval?Math.max(a.featureFlagsPollingInterval,100):null===a.featureFlagsPollingInterval?null:3e4,"number"==typeof a.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(a.waitUntilDebounceMs,0)),"number"==typeof a.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(a.waitUntilMaxWaitMs,0)),!this.disabled&&(a.personalApiKey||a.flagDefinitionCacheProvider)){if(a.personalApiKey?.includes("phc_"))throw Error('A project API key ("phc_...") was provided as secretKey or personalApiKey. Pass the project API key as the first constructor argument. For local evaluation, set secretKey (or the deprecated personalApiKey alias) to a server-only Project Secret API Key ("phs_...") or Personal API Key ("phx_...") with feature flag read access.');!1!==a.enableLocalEvaluation&&(this.featureFlagsPoller=new r9({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:a.personalApiKey,projectApiKey:n,timeout:a.requestTimeout??1e4,host:this.host,fetch:a.fetch,onError:e=>{this._events.emit("error",e)},onLoad:e=>{this._events.emit("localEvaluationFlagsLoaded",e)},onMinimalFlagCalledEvents:e=>{this._minimalFlagCalledEvents=e},customHeaders:this.getCustomHeaders(),cacheProvider:a.flagDefinitionCacheProvider,strictLocalEvaluation:a.strictLocalEvaluation,evaluationContexts:a.evaluationContexts??a.evaluationEnvironments}))}this.errorTracking=new ig(this,a,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=a.maxCacheSize||5e4}enqueue(e,t,r,i){super.enqueue(e,t,r,i),this.scheduleDebouncedFlush()}_flushEventsAndSpans(e=!1){let t=this.flushWithPendingPromises();return!this._traces||e&&this._traces.throttled?t:H([t,this._traces.flush().catch(()=>{})]).then(([e])=>{if("rejected"===e.status)throw e.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(e){let t=this._flushEventsAndSpans(e),r=this.options.waitUntil;if(r&&!this._waitUntilCycle)try{r(t.catch(()=>{}))}catch{}return t}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let t,r=new Promise(e=>{t=e});try{e(r)}catch{return}this._waitUntilCycle={resolve:t,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,r=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),t>=r)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=V(()=>{this.resolveWaitUntilFlush()},i)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){var t;return"v1"===this.captureMode&&"string"==typeof(t=e).event&&t.event.startsWith("$ai_")?"ai":ib}persistedQueueKeyForRoute(e){return e===iC?h.AiCaptureQueue:"ai"===e?h.AiQueue:h.Queue}getActiveQueueRoutes(){let e="v1"===this.captureMode?[ib,"ai"]:[ib];return this._aiCaptureRouteActive&&e.push(iC),e}getBatchEndpointPath(e){return e===iC?ik:super.getBatchEndpointPath(e)}async sendBatch(e,t,r=ib){if(r===iC)return this.sendAiCaptureBatch(e,t);if("v1"!==this.captureMode||"ai"===r)return super.sendBatch(e,t,r);let i=e.filter(e=>void 0!==e);await this.getV1Sender().sendV1Batch(i)}async sendAiCaptureBatch(e,t){let{batches:r,dropped:i}=function(e,t=8388608,r=5242880){let i=[],s=[],n=[],a=0;for(let o of e){if(void 0===o)continue;let e=iO(o);if(e>t){s.push({event:"string"==typeof o.event?o.event:"unknown",bytes:e});continue}n.length>0&&a+e>r&&(i.push(n),n=[],a=0),n.push(o),a+=e}return n.length>0&&i.push(n),{batches:i,dropped:s}}(e);for(let{event:e,bytes:t}of i){let r=`Event ${e} (${t} bytes) exceeds the 8MiB limit for ${ik}, dropping.`;this._logger.error(r),this._events.emit("error",Error(r))}for(let e of r)await this.sendAiSubBatch(e,t)}async sendAiSubBatch(e,t){try{await super.sendBatch(e,t,iC)}catch(i){if(!tc(i))throw i;if(1===e.length){let[t]=e,r="string"==typeof t.event?t.event:"unknown",i=`Event ${r} (${iO(t)} bytes) was rejected with 413 by ${ik} on its own, dropping.`;this._logger.error(i),this._events.emit("error",Error(i));return}let r=Math.ceil(e.length/2);await this.sendAiSubBatch(e.slice(0,r),t),await this.sendAiSubBatch(e.slice(r),t)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new iA({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:e=>this._events.emit("error",e),compress:e=>this.compressPayload(e)})),this._v1Sender}getLibraryVersion(){return"5.57.1"}get metrics(){var e;let t;return this._metrics||(this._metrics=new tH(this,(e=this.options.metrics,t=e?.resourceAttributes,{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1e3}),this._logger)),this._metrics}initializeSpanContextManager(){return new rx}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces){var e,t,r;let i,s;return this._traces||(this._traces=new rl(this,(e=this.options.traces,t=this.hostResourceAttributes(),r=this._logger,i=tv({...t},function(e){if(!(!e||"object"!=typeof e||Array.isArray(e)))try{if(rI.every(t=>!(t in e)||"string"==typeof e[t]))return e;let t={...e};for(let e of rI)e in t&&"string"!=typeof t[e]&&delete t[e];return t}catch{return}}(e?.resourceAttributes)),s=rP(e?.maxExportBatchSize,512),{serviceName:i?.["service.name"]??e?.serviceName,serviceVersion:i?.["service.version"]??e?.serviceVersion,environment:i?.["deployment.environment"]??e?.environment,resourceAttributes:i,beforeSpanSend:function(e,t){if(!e)return[];let r=[e].flat().filter(e=>!!e),i=r.filter(e=>"function"==typeof e);return i.length!==r.length&&t?.critical(`beforeSpanSend: ignoring ${r.length-i.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),i}(e?.beforeSpanSend,r),maxAttributesPerSpan:rP(e?.maxAttributesPerSpan,128),maxEventsPerSpan:rP(e?.maxEventsPerSpan,128),maxAttributesPerEvent:128,maxAttributeValueLength:rP(e?.maxAttributeValueLength,8192),flushIntervalMs:rP(e?.flushIntervalMs,5e3),maxExportBatchSize:s,maxQueueSize:Math.max(rP(e?.maxQueueSize,2048),s),maxLiveSpans:rP(e?.maxLiveSpans,1e4),maxSpanAgeMs:rP(e?.maxSpanAgeMs,36e5)}),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}}_tracingContext(){let e=this.context?.get();return{distinctId:e?.distinctId,sessionId:e?.sessionId}}startSpan(e,t){return this._tracesPipeline?.startSpan(e,t)??t3(t,this._spanContextManager.active())}withSpan(e,t,r){let i="function"==typeof t?void 0:t,s="function"==typeof t?t:r,n=this._tracesPipeline;return n?i?n.withSpan(e,i,s):n.withSpan(e,s):t9(this._spanContextManager,t3(i,this._spanContextManager.active()),s)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,r){"string"==typeof e&&this._logger.warn(t),"$exception"!==e.event||e._originatedFromCaptureException||this._logger.warn(r)}_sendPreparedEvent(e,t,r,i,s){return this.addPendingPromise(this._prepareEventMessage(t,i).then(({distinctId:t,event:i,properties:n,options:a})=>{let o={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},l={distinctId:t,event:i,properties:{...n,...this.getCommonEventProperties()}};return r?this.sendImmediate(e,l,o,s):this.enqueue(e,l,o,s)}).catch(e=>{e&&console.error(e)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}captureAi(e){if(this.disabled)return;let t=B(e.uuid,eQ);return this._sendPreparedAiEvent({...e,uuid:t},!1),t}async captureAiImmediate(e){if(this.disabled)return;let t=B(e.uuid,eQ);return await this._sendPreparedAiEvent({...e,uuid:t},!0),t}_sendPreparedAiEvent(e,t){return"string"!=typeof e?.event||e.event.startsWith("$ai_")||this._logger.debug(`captureAi called with non-AI event ${e.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",e,t,void 0,iC)}identify({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:n,...a}=t;this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:i||a,$set_once:s||{},$anon_distinct_id:n??void 0},disableGeoip:r},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:n,...a}=t;await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:i||a,$set_once:s||{},$anon_distinct_id:n??void 0},disableGeoip:r},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:r={}}){if(0===Object.keys(t).length&&0===Object.keys(r).length)return;let i={};Object.keys(t).length>0&&(i.$set=t),Object.keys(r).length>0&&(i.$set_once=r),this.capture({distinctId:e,event:"$set",properties:i})}unsetPersonProperties({distinctId:e,properties:t}){let r=(Array.isArray(t)?t:[t]).filter(e=>"string"==typeof e&&e.trim().length>0);0!==r.length&&this.capture({distinctId:e,event:"$set",properties:{$unset:r}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(e){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(e)}getFeatureFlagKeysByEvaluationRuntime(e){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(e)??[]}async waitForLocalEvaluationReady(e=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(t=>{let r=setTimeout(()=>{i(),t(!1)},e),i=this._events.on("localEvaluationFlagsLoaded",e=>{clearTimeout(r),i(),t(e>0)})})}_resolveDistinctId(e,t){return"string"==typeof e?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,r={},i){let s,n,a,o,l,u,c,h;if(this.disabled)return void this._logger.warn("The client is disabled");let d=r.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&e in this._flagOverrides){let t=this._flagOverrides[e];if(void 0===t)return;let r=this._payloadOverrides?.[e];return{key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:r}}let{groups:f,disableGeoip:p}=r,{onlyEvaluateLocally:g,personProperties:m,groupProperties:y}=r,_=this.addLocalPersonAndGroupProperties(t,f,m,y);m=_.allPersonProperties,y=_.allGroupProperties;let v=this.createFeatureFlagEvaluationContext(t,f,this.personPropertiesForLocalEvaluation(t,m),y);void 0==g&&(g=this.options.strictLocalEvaluation??!1);let b=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let t=this.featureFlagsPoller?.featureFlagsByKey[e];if(t)try{let r=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(t,v,{matchValue:i});if(r){b=!0;let i=r.value;l=t.id,c="Evaluated locally",h=t.has_experiment,s={key:e,enabled:!1!==i,variant:"string"==typeof i?i:void 0,payload:r.payload??void 0,reason:c,reasonCode:!1===t.active?"flag_disabled":void 0}}}catch(t){if(t instanceof r5||t instanceof r$)this._logger?.info(`${t.name} when computing flag locally: ${e}: ${t.message}`);else throw t}}if(!b&&!g){let t=await super.getFeatureFlagDetailsStateless(v.distinctId,v.groups,m,y,p,[e]);if(void 0===t)o=rA.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===t.minimalFlagCalledEvents,n=t.requestId,a=t.evaluatedAt;let r=[];t.errorsWhileComputingFlags&&r.push(rA.ERRORS_WHILE_COMPUTING),t.quotaLimited?.includes("feature_flags")&&r.push(rA.QUOTA_LIMITED);let i=t.flags[e];if(void 0===i)r.push(rA.FLAG_MISSING);else{let t;if(l=i.metadata?.id,u=i.metadata?.version,c=i.reason?.description??i.reason?.code,h=i.metadata?.has_experiment,i.metadata?.payload!==void 0)try{t=JSON.parse(i.metadata.payload)}catch{t=i.metadata.payload}s={key:e,enabled:i.enabled,variant:i.variant??void 0,payload:t,reason:c,reasonCode:i.reason?.code}}r.length>0&&(o=r.join(","))}}if(d){let r=void 0===s?void 0:!1!==s.enabled&&(s.variant??!0),i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:l,$feature_flag_version:u,$feature_flag_reason:c,locally_evaluated:b,[`$feature/${e}`]:r,$feature_flag_request_id:n,$feature_flag_evaluated_at:b?Date.now():a};if(void 0!==h&&(i.$feature_flag_has_experiment=h),b&&this.featureFlagsPoller){let e=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==e&&(i.$feature_flag_definitions_loaded_at=e)}o&&(i.$feature_flag_error=o),this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:r,groups:f,disableGeoip:p,properties:i})}return void 0!==s&&void 0!==this._payloadOverrides&&e in this._payloadOverrides&&(s={...s,payload:this._payloadOverrides[e]}),s}async getFeatureFlag(e,t,r){iT("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(void 0!==i)return!1!==i.enabled&&(i.variant??!0)}async getFeatureFlagPayload(e,t,r,i){if(iT("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request."),void 0!==this._payloadOverrides&&e in this._payloadOverrides)return this._payloadOverrides[e];let s=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:!1},r);if(void 0!==s)return s.payload??null}async getFeatureFlagResult(e,t,r){let{distinctId:i,options:s}=this._resolveDistinctId(t,r);return i?this._getFeatureFlagResult(e,i,{...s,sendFeatureFlagEvents:s?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let r=await t.json();if("string"==typeof r)try{return JSON.parse(r)}catch(e){}return r}async isFeatureEnabled(e,t,r){iT("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return void 0===i?void 0:!1!==i.enabled&&!!(i.variant??!0)}async getAllFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);return r?(await this.getAllFlagsAndPayloads(r,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads — pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:s,disableGeoip:n,flagKeys:a}=i||{},{onlyEvaluateLocally:o,personProperties:l,groupProperties:u}=i||{},c=this.addLocalPersonAndGroupProperties(r,s,l,u);l=c.allPersonProperties,u=c.allGroupProperties;let h=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,l),u);void 0==o&&(o=this.options.strictLocalEvaluation??!1);let d=await this.featureFlagsPoller?.getAllFlagsAndPayloads(h,a),f={},p={},g=!0;if(d&&(f=d.response,p=d.payloads,g=d.fallbackToFlags),g&&!o){let e=await super.getFeatureFlagsAndPayloadsStateless(h.distinctId,h.groups,l,u,n,a);f={...f,...e.flags||{}},p={...p,...e.payloads||{}}}return void 0!==this._flagOverrides&&(f={...f,...this._flagOverrides}),void 0!==this._payloadOverrides&&(p={...p,...this._payloadOverrides}),{featureFlags:f,featureFlagPayloads:p}}async evaluateFlags(e,t){let r,i,{distinctId:s,options:n}=this._resolveDistinctId(e,t);if(!s)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new rC({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new rC({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,flags:{}});let{groups:a,disableGeoip:o}=n||{},l=n?.flagKeys??void 0;if(l?.length===0)return new rC({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:a,disableGeoip:o,flags:{}});let{onlyEvaluateLocally:u,personProperties:c,groupProperties:h}=n||{},d=this.addLocalPersonAndGroupProperties(s,a,c,h);c=d.allPersonProperties,h=d.allGroupProperties;let f=this.createFeatureFlagEvaluationContext(s,a,this.personPropertiesForLocalEvaluation(s,c),h);void 0==u&&(u=this.options.strictLocalEvaluation??!1);let p=l?new Set(l):void 0,g={},m=!1,y=!1,_=await this.featureFlagsPoller?.getAllFlagsAndPayloads(f,l),v=new Set;if(_)for(let[e,t]of Object.entries(_.response)){let r=this.featureFlagsPoller?.featureFlagsByKey[e];g[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:_.payloads[e],id:r?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:r?.has_experiment},v.add(e)}let b=void 0!==p&&Array.from(p).some(e=>this.featureFlagsPoller?.featureFlagsByKey[e]===void 0);if((!_||_.fallbackToFlags||b)&&!u){let e=await super.getFeatureFlagDetailsStateless(f.distinctId,f.groups,c,h,o,l);if(e)for(let[t,s]of(this._minimalFlagCalledEvents=!0===e.minimalFlagCalledEvents,r=e.requestId,i=e.evaluatedAt,m=!!e.errorsWhileComputingFlags,y=Array.isArray(e.quotaLimited)&&e.quotaLimited.includes("feature_flags"),Object.entries(e.flags))){let e;if(!v.has(t)){if(s.metadata?.payload!==void 0)try{e=JSON.parse(s.metadata.payload)}catch{e=s.metadata.payload}g[t]={key:t,enabled:s.enabled,variant:s.variant,payload:e,id:s.metadata?.id,version:s.metadata?.version,reason:s.reason?.description??s.reason?.code,locallyEvaluated:!1,hasExperiment:s.metadata?.has_experiment}}}}if(void 0!==this._flagOverrides)for(let[e,t]of Object.entries(this._flagOverrides)){if(void 0===t){delete g[e];continue}let r=g[e];g[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:r?.payload,id:r?.id,version:r?.version,reason:r?.reason,locallyEvaluated:r?.locallyEvaluated??!1,hasExperiment:r?.hasExperiment}}if(void 0!==this._payloadOverrides)for(let[e,t]of Object.entries(this._payloadOverrides)){let r=g[e];r&&(g[e]={...r,payload:t})}if(void 0!==p)for(let e of Object.keys(g))p.has(e)||delete g[e];let w={};for(let[e,t]of Object.entries(_?.unresolved??{}))Object.prototype.hasOwnProperty.call(g,e)||(w[e]=t);return new rC({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:a,disableGeoip:o,flags:g,unresolvedFlags:w,requestId:r,evaluatedAt:i,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:m,quotaLimited:y})}_shouldSendMinimalFlagCalledEvent(e,t){return"$feature_flag_called"===e&&this._minimalFlagCalledEvents&&!1===t.$feature_flag_has_experiment}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:r,response:i,groups:s,disableGeoip:n,properties:a}=e,o=s&&Object.keys(s).length>0?`_${JSON.stringify(Object.entries(s).sort(([e],[t])=>e<t?-1:+(e>t)))}`:"",l=`${r}_${i}${o}`,u=this._distinctIdHasSentFlagCalls.get(t)??new Set;if(this._distinctIdHasSentFlagCalls.delete(t),this._distinctIdHasSentFlagCalls.set(t,u),!u.has(l)){for(u.add(l);this._distinctIdHasSentFlagCalls.size>Math.max(this.maxCacheSize,1);){let e=this._distinctIdHasSentFlagCalls.keys().next().value;if(void 0===e)break;this._distinctIdHasSentFlagCalls.delete(e)}this.capture({distinctId:t,event:"$feature_flag_called",properties:a,groups:s,disableGeoip:n})}}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),logWarning:e=>{!1!==this.options.featureFlagsLogWarnings&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:s}){this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:s},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:s}){await this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:s},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=e=>Object.fromEntries(e.map(e=>[e,!0]));if(!1===e){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(!1===e.flags?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):void 0!==e.flags&&(this._flagOverrides={...e.flags})),"payloads"in e&&(!1===e.payloads?this._payloadOverrides=void 0:void 0!==e.payloads&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if("flags"in e){let t=e.flags;if(!1===t||Array.isArray(t)||"object"==typeof t&&null!==t)return!0}if("payloads"in e){let t=e.payloads;if(!1===t||"object"==typeof t&&null!==t)return!0}return!1}withContext(e,t,r){return this.context?this.context.run(e,t,r):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??3e4),r=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await z(this._metrics.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._metrics.reset()),this._traces&&(await z(this._traces.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this._distinctIdHasSentFlagCalls.clear(),r?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let e=new AbortController;i=V(()=>{e.abort()},this.options.requestTimeout),r.signal=e.signal}try{return await this.fetch(t,r)}catch(e){this._events.emit("error",e);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let r={},i={};for(let[s,n]of Object.entries(e))if(P(n,"Object")&&t&&s in t){let e={};for(let[t,r]of Object.entries(n))e[String(t)]=String(r);i[String(s)]=e}else r[String(s)]=String(n);return{personProperties:r,groupProperties:i}}async getFeatureFlagsForEvent(e,t,r,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let s=i?.personProperties||{},n=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:n,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:a})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:n,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(e,t,s,n,r)).flags}addLocalPersonAndGroupProperties(e,t,r,i){let s={...r||{}},n={};if(t)for(let e of Object.keys(t))n[e]={$group_key:t[e],...i?.[e]||{}};return{allPersonProperties:s,allGroupProperties:n}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,r,i){return{distinctId:e,groups:t||{},personProperties:r||{},groupProperties:i||{},evaluationCache:{}}}captureException(e,t,r,i,s){if(!ig.isPreviouslyCapturedError(e)){let n=Error("PostHog syntheticException");this.addPendingPromise(ig.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:n},t,r).then(e=>this._capturePreparedEvent({...e,uuid:i,flags:s},!1)))}}async captureExceptionImmediate(e,t,r,i){if(!ig.isPreviouslyCapturedError(e)){let s=Error("PostHog syntheticException");return this.addPendingPromise(ig.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,r).then(e=>this.captureImmediate({...e,flags:i})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:r,event:i,properties:s,groups:n,flags:a,sendFeatureFlags:o,timestamp:l,disableGeoip:u,uuid:c}=e,h=this.context?.get(),d=t.includeContextProperties??!0,f=r||h?.distinctId,p=d?{...this.props,...h?.properties||{},...s||{}}:{...s||{}};"$exception"!==i||"$trace_id"in p||"$span_id"in p||Object.assign(p,await i_()),f||(f=eQ(),p.$process_person_profile=!1),d&&h?.sessionId&&!p.$session_id&&(p.$session_id=h.sessionId);let g=this._shouldSendMinimalFlagCalledEvent(i,p)?e6(p):p,m=this._runBeforeSend({distinctId:f,event:i,properties:g,groups:n,flags:a,sendFeatureFlags:o,timestamp:l,disableGeoip:u,uuid:c});if(!m)return Promise.reject(null);let y=await Promise.resolve().then(async()=>{if(a)return o&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(o){iT("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");var e=await this.getFeatureFlagsForEvent(m.distinctId,n,u,"object"==typeof o?o:void 0);if(!e)return{};let t={};for(let[r,i]of Object.entries(e))t[`$feature/${r}`]=i;let r=Object.keys(e).filter(t=>!1!==e[t]).sort();return r.length>0&&(t.$active_feature_flags=r),t}return{}}).catch(()=>({})).then(e=>{let t=m.groups||n;return{...e,...m.properties||{},...void 0!==t&&Object.keys(t).length>0?{$groups:t}:{}}});return"$pageview"===m.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof y.$raw_user_agent&&rF(y.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(m.event="$bot_pageview",y.$browser_type="bot"),{distinctId:m.distinctId,event:m.event,properties:y,options:{timestamp:m.timestamp,disableGeoip:m.disableGeoip,uuid:m.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let r=Array.isArray(t)?t:[t],i=e;for(let t of r)try{if(!(i=t(i)))return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!i.properties||0===Object.keys(i.properties).length){let e=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(e)}}catch(t){return this._logger.error(`Error in before_send function for event '${e.event}':`,t),null}return i}}var ij=e.i(78500);class iD{constructor(){this.storage=new ij.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,r){return this.storage.run(this.resolve(e,r),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let r=this.get()||{};return{distinctId:e.distinctId??r.distinctId,sessionId:e.sessionId??r.sessionId,properties:{...r.properties||{},...e.properties||{}}}}}class iB{active(){return this._storage.getStore()}with(e,t){return this._storage.run(e,t)}constructor(){this._storage=new ij.AsyncLocalStorage}}var iL=e.i(27028);let iN=(0,e.i(12057).promisify)(iL.gzip);async function iq(e,t=!0){try{let t=await iN(e);return new Uint8Array(t)}catch(e){return t&&console.error("Failed to gzip compress data",e),null}}var iU=e.i(60526),ip=ez;let iV="posthog-node";function iz(e,{organization:t,projectId:r,prefix:i,severityAllowList:s=["error"],sendExceptionsToPostHog:n=!0}={}){return a=>{if(!("*"===s||s.includes(a.level)))return a;a.tags||(a.tags={});let o=a.tags[iW.POSTHOG_ID_TAG];if(void 0===o)return a;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${o}`,l).toString();a.tags["PostHog Person URL"]=u;let c=a.exception?.values||[],h=c.map(e=>({...e,stacktrace:e.stacktrace?{...e.stacktrace,type:"raw",frames:(e.stacktrace.frames||[]).map(e=>({...e,platform:"node:javascript"}))}:void 0})),d={$exception_message:c[0]?.value||a.message,$exception_type:c[0]?.type,$exception_level:a.level,$exception_list:h,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:c[0]?.value||a.message,$sentry_exception_type:c[0]?.type,$sentry_tags:a.tags},f=ip.getInjectedReleaseId();return f&&(d.$release_id=f),t&&r&&(d.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+a.event_id),n&&e.capture({event:"$exception",distinctId:o,properties:d}),a}}function iH(e,t){let r=iz(e,t);return{name:iV,processEvent:e=>r(e)}}class iW{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,t,r,i,s){this.name=iV,this.name=iV,this.setupOnce=function(n,a){n(iz(e,{organization:t,projectId:a()?.getClient()?.getDsn()?.projectId,prefix:r,severityAllowList:i,sendExceptionsToPostHog:s??!0}))}}}e.s(["PostHogSentryIntegration",0,iW,"createEventProcessor",0,iz,"sentryIntegration",0,iH],91573);let iK=/[\x00-\x1f\x7f-\x9f]/g;function iG(e,t,r){null!=r&&""!==r&&(e[t]=r)}function iQ(e){return Array.isArray(e)?e[0]:e}function iJ(e){if(Array.isArray(e)){for(let t of e){let e=iJ(t);if(void 0!==e)return e}return}if("string"!=typeof e)return;let t=e.replace(iK,"").trim();if(t)return t.length>1e3?t.slice(0,1e3):t}function iZ(e,t){var r,i;let s,{sessionId:n,distinctId:a}=function(e){if(!e)return{};let t=iJ(e["x-posthog-session-id"]),r=iJ(e["x-posthog-distinct-id"]);return{...void 0!==t?{sessionId:t}:{},...void 0!==r?{distinctId:r}:{}}}(t.headers),o={},l=!0===e.options.disable_capture_url_hashes;return iG(o,"$current_url",(r=t.originalUrl||t.url,l?N(r):r)),iG(o,"$request_method",t.method),iG(o,"$request_path",(i=t.path,s=function(e){if(!e)return e;let t=e.indexOf("?"),r=e.indexOf("#");return -1===t||-1!==r&&r<t?e:`${e.slice(0,t)}${-1===r?"":e.slice(r)}`}(i),l?N(s):s)),iG(o,"$user_agent",iQ(t.headers["user-agent"])),iG(o,"$ip",function(e){let t=iQ(e.headers["x-forwarded-for"]);if(t){let e=t.split(",")[0].trim();if(e)return e}return e.socket?.remoteAddress}(t)),{...void 0!==n?{sessionId:n}:{},...void 0!==a?{distinctId:a}:{},properties:o}}function iY(e,t){var r;t.use((r=e,(e,t,i)=>{r.withContext(iZ(r,e),()=>i())}))}function iX(e,t){var r;t.use((r=e,(e,t,i,s)=>{if(ig.isPreviouslyCapturedError(e))return void s(e);let n=iZ(r,t),a=Error("Synthetic exception"),o={...void 0!==n.sessionId?{$session_id:n.sessionId}:{},...n.properties||{}};r.addPendingPromise(Promise.all([ig.buildEventMessage(r.getErrorPropertiesBuilder(),e,{mechanism:{type:"middleware",handled:!1},syntheticException:a},n.distinctId,o),i.headersSent||i.destroyed?Promise.resolve(i.headersSent?i.statusCode:void 0):new Promise(e=>{let t=t=>{clearTimeout(s),i.removeListener("finish",r),i.removeListener("close",r),e(t)},r=()=>t(i.headersSent?i.statusCode:void 0),s=setTimeout(()=>t(void 0),1e3);s.unref(),i.once("finish",r),i.once("close",r)})]).then(([e,t])=>(void 0!==t&&(e.properties={...e.properties,$response_status_code:t}),r._capturePreparedEvent(e,!1)))),s(e)}))}e.s(["setupExpressErrorHandler",0,iX,"setupExpressRequestContext",0,iY],93546),e.i(91573),e.i(93546),e.i(58325),e.s(["FeatureFlagError",0,d,"FeatureFlagEvaluations",0,rC,"PostHogSentryIntegration",0,iW,"cookieStateToProperties",0,e1,"cookieStoreFromHeader",0,eZ,"createEventProcessor",0,iz,"getPostHogCookieName",0,eY,"parsePostHogCookie",0,e2,"readPostHogCookie",0,e0,"sentryIntegration",0,iH,"serializePostHogCookie",0,eX,"setupExpressErrorHandler",0,iX,"setupExpressRequestContext",0,iY,"uuidv7",0,eQ],57564),e.i(57564),e.s(["FeatureFlagError",0,d,"FeatureFlagEvaluations",0,rC,"PostHog",0,class extends iR{getLibraryId(){return"posthog-node"}compressPayload(e){return iq(e,this.isDebug)}initializeContext(){return new iD}initializeSpanContextManager(){return new iB}hostResourceAttributes(){return function(){var e,t;let r,i,s;try{r=(0,iU.platform)(),i=(0,iU.release)()}catch{}return e=r,t=i,{...(s=function(e){if(e)return Object.prototype.hasOwnProperty.call(tP,e)?tP[e]:e}(e))?{"os.name":s}:{},...t?{"os.version":t}:{}}}()}createErrorPropertiesBuilder(){let e;return new ez.ErrorPropertiesBuilder([new ez.EventCoercer,new ez.ErrorCoercer,new ez.ObjectCoercer,new ez.StringCoercer,new ez.PrimitiveCoercer],ez.createStackParser("node:javascript",ez.nodeStackLineParser),[(e=function(e=process.argv[1]?(0,u.dirname)(process.argv[1]):process.cwd(),t="\\"===u.sep){let r=t?c(e):e;return e=>{if(!e)return;let i=t?c(e):e,{dir:s,base:n,ext:a}=u.posix.parse(i);(".js"===a||".mjs"===a||".cjs"===a)&&(n=n.slice(0,-1*a.length));let o=decodeURIComponent(n);s||(s=".");let l=s.lastIndexOf("/node_modules");if(l>-1)return`${s.slice(l+14).replace(/\//g,".")}:${o}`;if(s.startsWith(r)){let e=s.slice(r.length+1).replace(/\//g,".");return e?`${e}:${o}`:o}return o}}(),async t=>{for(let r of t)r.module=e(r.filename);return t}),e=>rg(e,void 0,this._logger),function(e=process.cwd()){u.sep;let t=e=>e,r=t(e);return async e=>{for(let i of e)!(!i.filename||i.filename.startsWith("node:")||i.filename.startsWith("data:"))&&(0,u.isAbsolute)(i.filename)&&(i.filename=t((0,u.relative)(r,t(i.filename))));return e}}()])}},"PostHogSentryIntegration",0,iW,"cookieStateToProperties",0,e1,"cookieStoreFromHeader",0,eZ,"createEventProcessor",0,iz,"getPostHogCookieName",0,eY,"parsePostHogCookie",0,e2,"readPostHogCookie",0,e0,"sentryIntegration",0,iH,"serializePostHogCookie",0,eX,"setupExpressErrorHandler",0,iX,"setupExpressRequestContext",0,iY,"uuidv7",0,eQ],28864)}];
|
|
1
|
+
module.exports=[28864,e=>{"use strict";let t,r,i,s,n,a;var o,l=e.i(14747);function u(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var c=((o={}).AnonymousId="anonymous_id",o.DistinctId="distinct_id",o.Props="props",o.EnablePersonProcessing="enable_person_processing",o.PersonMode="person_mode",o.FeatureFlagDetails="feature_flag_details",o.FeatureFlags="feature_flags",o.FeatureFlagPayloads="feature_flag_payloads",o.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",o.BootstrapFeatureFlags="bootstrap_feature_flags",o.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",o.OverrideFeatureFlags="override_feature_flags",o.Queue="queue",o.AiQueue="ai_queue",o.AiCaptureQueue="ai_capture_queue",o.LogsQueue="logs_queue",o.OptedOut="opted_out",o.SessionId="session_id",o.SessionStartTimestamp="session_start_timestamp",o.SessionLastTimestamp="session_timestamp",o.PersonProperties="person_properties",o.GroupProperties="group_properties",o.InstalledAppBuild="installed_app_build",o.InstalledAppVersion="installed_app_version",o.SessionReplay="session_replay",o.PushRegistered="push_registered",o.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",o.SurveyLastSeenDate="survey_last_seen_date",o.SurveysInProgress="surveys_in_progress",o.SurveysSeen="surveys_seen",o.Surveys="surveys",o.RemoteConfig="remote_config",o.FlagsEndpointWasHit="flags_endpoint_was_hit",o.DeviceId="device_id",o);let h={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",LOCAL_EVALUATION_INCONCLUSIVE:"local_evaluation_inconclusive",QUOTA_LIMITED:"quota_limited",TIMEOUT:"timeout",CONNECTION_ERROR:"connection_error",UNKNOWN_ERROR:"unknown_error",apiError:e=>`api_error_${e}`};function d(e,t){return -1!==e.indexOf(t)}function f(e){let t=[];return JSON.stringify(e,function(e,r){if("bigint"==typeof r)return r.toString();if("function"!=typeof r&&"symbol"!=typeof r){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&"object"==typeof r){for(;t.length>0&&t[t.length-1]!==this;)t.pop();if(t.includes(r))return"[Circular]";t.push(r)}return r}})??"null"}let p=Array.isArray,g=Object.prototype;g.hasOwnProperty;let m=g.toString,y=p||function(e){return"[object Array]"===m.call(e)},_=e=>void 0===e,v=e=>"[object String]"==m.call(e),b=e=>v(e)&&0===e.trim().length,w=e=>null===e,x=e=>_(e)||w(e);function S(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return E(e,Error)}}function F(e){return"u">typeof Event&&E(e,Event)}function E(e,t){try{return e instanceof t}catch{return!1}}let P=[!0,"true",1,"1","yes"],I=[!1,"false",0,"0","no"];function A(e,t,r){return e&&r?t.length===Object.keys(r).length&&t.every(t=>e[t]===r[t]):e===r}class k{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){let r=t&&t.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(r,t,0).apply(e),s=this.buildParsingContext(t),n=this.parseStacktrace(i,s);return{$exception_list:this.convertToExceptionList(n,r),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&y(t.stacktrace.frames)&&(t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames));return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let r,i;if(null!=e.cause&&(r=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack)try{i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)}catch{}return{...e,cause:r,stack:i,errors:e.errors?.map(e=>this.parseStacktrace(e,t))}}applyChunkIds(e,t){return e.map(e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e))}applyCoercers(e,t){for(let r of this.coercers)if(r.match(e))return r.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let e of this.modifiers)t=await e(t);return t}convertToExceptionList(e,t){let r=[],i=(e,s,n)=>{let a=r.length,o=void 0===s?{type:"string"==typeof t.type&&t.type.length>0?t.type:"generic",..."boolean"==typeof t.handled?{handled:t.handled}:void 0===t.handled?{handled:!0}:{},synthetic:"boolean"==typeof t.synthetic?t.synthetic:e.synthetic,exception_id:a}:{type:"chained",source:n,synthetic:e.synthetic,exception_id:a,parent_id:s},l={type:e.type,value:e.value,mechanism:o};for(let t of(e.stack&&(l.stacktrace={type:"raw",frames:e.stack}),r.push(l),e.cause&&i(e.cause,a,"cause"),e.errors??[]))i(t,a,"member")};return i(e),r}buildParsingContext(e){return{chunkIdMap:function(e){let n=globalThis._posthogChunkIds,a=globalThis._debugIds;if(!n&&!a)return;let o=n?Object.keys(n):[],l=a?Object.keys(a):[];if(s&&A(n,o,r)&&A(a,l,i))return s;r=n?{...n}:void 0,i=a?{...a}:void 0,s={},t??={};let u=(r,i)=>{for(let n of r){let r=i[n];if(!r)continue;let a=t?.[n];if(a){s[a]=r;continue}let o=e(n);for(let e=o.length-1;e>=0;e--){let i=o[e]?.filename;if(i){s[i]=r,t[n]=i;break}}}};return a&&u(l,a),n&&u(o,n),s}(this.stackParser),skipFirstLines:e.skipFirstLines??1}}getAggregateErrors(e){try{if(S(e)){let t=Object.getPrototypeOf(e);for(let r=0;t&&r<100;r++){let r=Object.getOwnPropertyDescriptor(t,"constructor")?.value;if("function"==typeof r&&"AggregateError"===r.name){let t=e.errors;return y(t)?t:void 0}t=Object.getPrototypeOf(t)}}}catch{}}buildCoercingContext(e,t,r=0){let i=0,s=0,n=!1,a=new Set,o=[],l={},u=(e,t,r=0)=>{let u,h,d=c(t,r),f=d.apply;if(d.apply=t=>{o.push(e);try{return f(t)}finally{o.pop()}},r>4||r>0&&-1!==o.indexOf(e))return this.coerceFallback(d);let p="object"==typeof e&&null!==e||"function"==typeof e;if(0===r&&i>=50||p&&a.has(e))return;p&&a.add(e),0===r&&i++;let g=this.getAggregateErrors(e);n||=!!g;try{if(!(u=this.applyCoercers(e,d)))throw l}catch(e){if(e===l){0===r&&i--;return}if(!n)throw e;u=this.coerceFallback(d)}if(!g||i>=50)return u;try{h=g.length}catch{return u}if(!Number.isInteger(h)||h<0||h>0xffffffff)return u;let m=[];for(let e=0;i<50&&s<1e3&&e<h;e++){let r;s++;try{r=d.next(g[e])}catch{i++,r=this.coerceFallback(c(t+1))}r&&m.push(r)}return{...u,errors:m}},c=(r,i=0)=>({...t,syntheticException:0==r?t.syntheticException:void 0,mechanism:0==r?e:{},apply:e=>{let t=u(e,r,i+1);if(!t)throw l;return t},next:e=>u(e,r+1)}),h=c(r);return{...h,apply:e=>u(e,r)??this.coerceFallback(h)}}}e.s(["ErrorPropertiesBuilder",0,k],80446),e.i(80446);let C=/^([a-z][a-z0-9.+-]+):/i,$=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function O(e,t,r,i,s){let n={platform:e,filename:t,function:"<anonymous>"===r?"?":r,in_app:function(e){if(!e||"<anonymous>"===e)return!1;let t=C.exec(e);return!t||$.includes(t[1].toLowerCase())}(t)};return _(i)||(n.lineno=i),_(s)||(n.colno=s),n}let T=(e,t)=>{let r=-1!==e.indexOf("safari-extension"),i=-1!==e.indexOf("safari-web-extension");return r||i?[-1!==e.indexOf("@")?e.split("@")[0]:"?",r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},M=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,R=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,j=/\((\S*)(?::(\d+))(?::(\d+))\)/,D=(e,t)=>{let r=M.exec(e);if(r){let[,e,i,s]=r;return O(t,e,"?",+i,+s)}let i=R.exec(e);if(i){if(i[2]&&0===i[2].indexOf("eval")){let e=j.exec(i[2]);e&&(i[2]=e[1],i[3]=e[2],i[4]=e[3])}let[e,r]=T(i[1]||"?",i[2]);return O(t,r,e,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},L=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,B=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,N=(e,t)=>{let r=L.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let e=B.exec(r[3]);e&&(r[1]=r[1]||"eval",r[3]=e[1],r[4]=e[2],r[5]="")}let e=r[3],i=r[1]||"?";return[i,e]=T(i,e),O(t,e,i,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}},q=/\(error: (.*)\)/;function U(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function H(e,t){let r=t.start;for(;r>0&&U(e[r-1],e[r-1+t.length]);)r--;return t.start-r}function K(e,t){let r=t.start+t.length,i=r;for(;i<e.length&&U(e[i],e[i-t.length]);)i++;return i-r}function V(e,...t){return(r,i=0)=>{let s=[],n=r.split("\n"),a=Math.min(n.length,i+1e3),o=[];for(let r=i;r<a;r++){let i=n[r];if(i.length>1024)continue;let a=q.test(i)?i.replace(q,"$1"):i;if(!a.match(/\S*Error: /)){for(let r of t){let t=r(a,e);if(t){s.push(t);let e=function(e){for(let t=1;t<=10;t++){let r=e.length-2*t;if(r<0)break;let i=!0;for(let s=0;s<t;s++)if(!U(e[r+s],e[r+t+s])){i=!1;break}if(i){for(let i=0;i<t;i++)e[r+i]=e[r+t+i];return e.length=r+t,{start:r,length:t}}}}(s);if(e){for(let t=o.length-1;t>=0;t--){let r=o[t];if(r.start+r.length<=e.start)break;o.pop()}o.push(e)}break}}if(function(e,t){let r=t[0],i=e.length-(r?H(e,r):0);for(let r of t)i-=K(e,r);return i}(s,o)>=50)break}}let l=[...o].sort((e,t)=>t.start-e.start),u=l[l.length-1];if(u){let e=H(s,u);for(let t of(s.splice(u.start-e,e),l))t.start-=e}for(let e of l)!function(e,t){let r=t.start+t.length,i=K(e,t);i&&e.splice(r+i===e.length?r:t.start,i)}(s,e);o.some(e=>0===e.start&&s.length===e.length)&&function(e){let t=e.map(e=>`${e.function}|${e.filename}|${e.lineno}|${e.colno}|${e.module}`),r=0;for(let e=1;e<t.length;e++)(function(e,t,r){for(let i=0;i<e.length;i++){let s=e[(t+i)%e.length],n=e[(r+i)%e.length];if(s!==n)return s<n}return!1})(t,e,r)&&(r=e);e.push(...e.splice(0,r))}(s);if(!s.length)return[];let c=Array.from(s);return c.reverse(),c.slice(0,50).map(e=>{var t;return{...e,filename:e.filename||((t=c)[t.length-1]||{}).filename,function:e.function||"?"}})}}let W=/^\s*[-]{4,}$/,z=/at (?:async (?!\((?!.*\)\s+\()))?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,G=/^Promise\.(?:all|any)$/,Q=/^index \d+$/,J=(e,t)=>{let r=e.match(z);if(r){let e,i,s,n,a;if(r[1]){let t=(s=r[1]).lastIndexOf(".");if("."===s[t-1]&&t--,t>0){e=s.slice(0,t),i=s.slice(t+1);let r=e.indexOf(".Module");r>0&&(s=s.slice(r+1),e=e.slice(0,r))}n=void 0}i&&(n=e,a=i),"<anonymous>"===i&&(a=void 0,s=void 0),void 0===s&&(a=a||"?",s=n?`${n}.${a}`:a);let o=r[2]?.startsWith("file://")?r[2].slice(7):r[2],l="native"===r[5];return o?.match(/\/[A-Z]:/)&&(o=o.slice(1)),o||!r[5]||l||(o=r[5]),G.test(s)&&Q.test(o||"")&&(o="node:internal/promise"),{filename:o?decodeURI(o):void 0,module:void 0,function:s,lineno:Z(r[3]),colno:Z(r[4]),in_app:function(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==e&&!e.includes("node_modules/")}(o||"",l),platform:t}}if(e.match(W))return{filename:e,platform:t}};function Z(e){return parseInt(e||"",10)||void 0}e.s(["createStackParser",0,V,"nodeStackLineParser",0,J],70736),e.i(70736),e.s([],29569),e.i(29569);class Y{match(e){return S(e)}coerce(e,t){let r=this.getStack(e),i=void 0===r?t.syntheticException?.stack:void 0;return{type:this.getType(e),value:this.getMessage(e,t),stack:r??i,cause:e.cause?t.next(e.cause):void 0,synthetic:!!i}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let r=e.message;return r.error&&"string"==typeof r.error.message?String(r.error.message):String(r)}getStack(e){try{let t=e.stacktrace;if("string"==typeof t&&t.length>0)return t;let r=e.stack;return"string"==typeof r&&r.length>0?r:void 0}catch{return}}}e.s(["ErrorCoercer",0,Y],11475),e.i(11475),e.s([],43179),e.i(43179);let X=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class ee{match(e){return"string"==typeof e}coerce(e,t){let[r,i]=this.getInfos(e);return{type:r??"Error",value:i??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",r=e,i=e.match(X);return i&&(t=i[1],r=i[2]),[t,r]}}e.s(["StringCoercer",0,ee],45098),e.i(45098);let et=["fatal","error","warning","log","info","debug"];function er(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let e=r.length;e>0;e--){let i=r.slice(0,e).join(", ");if(!(i.length>t)){if(e===r.length)return i;return i.length<=t?i:`${i.slice(0,t)}...`}}return""}class ei{match(e){return"object"==typeof e&&null!==e}coerce(e,t){let r=this.getErrorPropertyFromObject(e);return r?t.apply(r):{type:this.getType(e),value:this.getValue(e),stack:this.getStack(e)??t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(F(e))return e.constructor.name;let t="name"in e?e.name:void 0;return v(t)&&!b(t)?t:"Error"}getValue(e){if("name"in e&&"string"==typeof e.name){let t=`'${e.name}' captured as exception`;return"message"in e&&"string"==typeof e.message&&(t+=` with message: '${e.message}'`),t}if("message"in e&&"string"==typeof e.message)return e.message;let t=this.getObjectClassName(e),r=er(e);return`${t&&"Object"!==t?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return v(e)&&!b(e)&&et.indexOf(e)>=0}getStack(e){try{if(v(e.stacktrace)&&e.stacktrace.length>0)return e.stacktrace;return v(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(S(r))return r}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){return}}}e.s(["ObjectCoercer",0,ei],6881),e.i(6881);class es{match(e){return F(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${er(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["EventCoercer",0,es],80322),e.i(80322);class en{match(e){return null===e||"object"!=typeof e}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["PrimitiveCoercer",0,en],80049),e.i(80049),e.s([],98689),e.i(98689),e.s(["ErrorCoercer",0,Y,"EventCoercer",0,es,"ObjectCoercer",0,ei,"PrimitiveCoercer",0,en,"StringCoercer",0,ee],21854),e.i(21854);class ea{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(void 0!==t)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}}e.s(["ReduceableCache",0,ea],46986),e.i(46986);function eo(){if("u">typeof process){let e=process.env.POSTHOG_RELEASE_ID?.trim();if(e)return e}let e=globalThis._posthogReleaseId;return"string"==typeof e&&e.length>0?e:void 0}e.s([],52001),e.i(52001),e.s(["getInjectedReleaseId",0,eo],41508),e.i(41508),e.s(["ErrorCoercer",0,Y,"ErrorPropertiesBuilder",0,k,"EventCoercer",0,es,"ObjectCoercer",0,ei,"PrimitiveCoercer",0,en,"ReduceableCache",0,ea,"StringCoercer",0,ee,"createStackParser",0,V,"getInjectedReleaseId",0,eo,"nodeStackLineParser",0,J],96117);var el=e.i(96117),el=el,eu=e.i(2157),ec=e.i(12714),eh=e.i(50227),ed=e.i(1457);let ef=new el.ReduceableCache(25),ep=new el.ReduceableCache(20);async function eg(e,t=ec.open,r){let i,s={};try{i=process.cwd()}catch{}for(let t=e.length-1;t>=0;t--){var n,a;let r=e[t],o=r?.filename;!(!r||"string"!=typeof o||"number"!=typeof r.lineno||(n=o).startsWith("node:")||n.endsWith(".min.js")||n.endsWith(".min.cjs")||n.endsWith(".min.mjs")||n.startsWith("data:")||void 0!==(a=r).lineno&&a.lineno>1e4||void 0!==a.colno&&a.colno>1e3)&&((0,eh.isAbsolute)(o)||void 0!==i)&&(s[o]||(s[o]=[]),s[o].push(r.lineno))}let o=Object.keys(s);if(0==o.length)return e;let l=[];for(let e of o){let n=ev(e,i);if(void 0===n||ep.get(n))continue;let a=s[e];if(!a)continue;a.sort((e,t)=>e-t);let o=function(e){if(!e.length)return[];let t=0,r=e[0];if("number"!=typeof r)return[];let i=eb(r),s=[];for(;;){if(t===e.length-1){s.push(i);break}let r=e[t+1];if("number"!=typeof r)break;r<=i[1]?i[1]=r+7:(s.push(i),i=eb(r)),t++}return s}(a);if(o.every(e=>(function(e,t){let r=ef.get(e);if(void 0===r)return!1;for(let e=t[0];e<=t[1];e++)if(void 0===r[e])return!1;return!0})(n,e)))continue;let u=function(e,t,r){let i=e.get(t);return void 0===i?(e.set(t,r),r):i}(ef,n,{});l.push(ey(e,o,u,n,t,r))}return await Promise.all(l).catch(()=>{}),e&&e.length>0&&function(e,t,r){for(let i of e)if(i.filename&&void 0===i.context_line&&"number"==typeof i.lineno){let e=ev(i.filename,r),s=void 0===e?void 0:t.get(e);if(void 0===s)continue;!function(e,t,r){if(void 0===t.lineno||void 0===r)return;t.pre_context=[];for(let i=ew(e);i<e;i++){let e=r[i];if(void 0===e)return void e_(t);t.pre_context.push(e)}if(void 0===r[e])return e_(t);t.context_line=r[e];let i=function(e){return e+7}(e);t.post_context=[];for(let s=e+1;s<=i;s++){let e=r[s];if(void 0===e)break;t.post_context.push(e)}}(i.lineno,i,s)}}(e,ef,i),ef.reduce(),e}async function em(e,t,r){let i,s=!1;try{i=await t(e,eu.constants.O_RDONLY|eu.constants.O_NONBLOCK);let n=await i.stat();if(!n.isFile())return;if(n.size>0xa00000)return void r?.debug(`Skipping source context for oversized file ${e}: ${n.size} bytes exceeds 10485760`);return s=!0,i}catch{return}finally{i&&!s&&await i.close().catch(()=>{})}}async function ey(e,t,r,i,s,n){let a=await em(e,s,n);return void 0===a?void ep.set(i,1):new Promise(e=>{let s,n,o=!1;function l(t){o||(o=!0,t?.destroy(),a.close().then(e,e))}try{s=a.createReadStream({autoClose:!1,start:0,end:0x9fffff})}catch{ep.set(i,1),l();return}try{n=(0,ed.createInterface)({input:s})}catch{ep.set(i,1),l(s);return}let u=0,c=0,h=t[0];if(void 0===h)return void l(s);let d=h[0],f=h[1];function p(){ep.set(i,1),n.close(),n.removeAllListeners(),l(s)}s.on("error",p),n.on("error",p),n.on("close",()=>l(s)),n.on("line",e=>{if(!(++u<d)&&(r[u]=function(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let s=Math.max(t-60,0);s<5&&(s=0);let n=Math.min(s+140,i);return n>i-5&&(n=i),n===i&&(s=Math.max(n-140,0)),r=r.slice(s,n),s>0&&(r=`...${r}`),n<i&&(r+="..."),r}(e,0),u>=f)){if(c===t.length-1){n.close(),n.removeAllListeners();return}let e=t[++c];if(void 0===e){n.close(),n.removeAllListeners();return}d=e[0],f=e[1]}})})}function e_(e){delete e.pre_context,delete e.context_line,delete e.post_context}function ev(e,t){return(0,eh.isAbsolute)(e)?JSON.stringify([null,e]):void 0===t?void 0:JSON.stringify([t,e])}function eb(e){return[ew(e),e+7]}function ew(e){return Math.max(1,e-7)}class ex{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,t){for(let r of this.events[e]||[])r(t);for(let r of this.events["*"]||[])r(e,t)}}let eS=e=>void 0===e?void 0:e.variant??e.enabled,eF=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}},eE=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","bfcid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],eP=(e,t=[])=>{let r={},i=t=>{void 0!==e[t]&&(r[t]=e[t])};return eE.forEach(i),t.forEach(i),r},eI=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function eA(e,t){return"string"==typeof e&&eI.test(e)?e:t()}function ek(e,t){let r=Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function eC(e){return e?.replace(/\/+$/,"")}function e$(e){return e?e.split("#")[0]:e}async function eO(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(e=>setTimeout(e,t.retryDelay));try{return await e()}catch(e){if(r=e,!t.retryCheck(e))throw e}}throw r}function eT(){return new Date().toISOString()}function eM(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}async function eR(e,t,r){let i;try{return await Promise.race([e,new Promise((e,s)=>{i=eM(()=>{try{r?.(),e()}catch(e){s(e)}},t)})])}finally{clearTimeout(i)}}function ej(e){return Promise.all(e.map(e=>(e??Promise.resolve()).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}let eD=e=>{throw ek("NativeGzipValidationError",`Native gzip produced invalid output: ${e}`)},eL=async(e,t)=>{e.size<18&&eD("too-short");let r=new Uint8Array(await e.slice(0,10).arrayBuffer());r.length>=2&&31===r[0]&&139===r[1]&&8===r[2]||eD("invalid-header");let i=new DataView(await e.slice(e.size-8).arrayBuffer());i.getUint32(0,!0)!==(e=>{let t=(()=>{if(n)return n;n=[];for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t=1&t?0xedb88320^t>>>1:t>>>1;n[e]=t>>>0}return n})(),r=0xffffffff;for(let i=0;i<e.length;i++)r=t[(r^e[i])&255]^r>>>8;return(0xffffffff^r)>>>0})(t)&&eD("invalid-crc");let s=t.length>>>0;i.getUint32(4,!0)!==s&&eD("invalid-size")};async function eB(e,t=!0,r){try{let t=new TextEncoder().encode(e),r=new globalThis.CompressionStream("gzip"),i=r.writable.getWriter(),s=i.write(t).then(()=>i.close()).catch(async e=>{try{await i.abort(e)}catch{}throw e}),n=new Response(r.readable).blob(),[a]=await Promise.all([n,s]);return await eL(a,t),a}catch(e){if(r?.rethrow)throw e;return t&&console.error("Failed to gzip compress data",e),null}}let eN="0123456789abcdef";class eq{constructor(e){this.bytes=e}static ofInner(e){if(16===e.length)return new eq(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,r,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||e<0||t<0||r<0||i<0||e>0xffffffffffff||t>4095||r>0x3fffffff||i>0xffffffff)throw RangeError("invalid field value");let s=new Uint8Array(16);return s[0]=e/0x10000000000,s[1]=e/0x100000000,s[2]=e/0x1000000,s[3]=e/65536,s[4]=e/256,s[5]=e,s[6]=112|t>>>8,s[7]=t,s[8]=128|r>>>24,s[9]=r>>>16,s[10]=r>>>8,s[11]=r,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new eq(s)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("")}if(t){let e=new Uint8Array(16);for(let r=0;r<16;r+=4){let i=parseInt(t.substring(2*r,2*r+8),16);e[r+0]=i>>>24,e[r+1]=i>>>16,e[r+2]=i>>>8,e[r+3]=i}return new eq(e)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=eN.charAt(this.bytes[t]>>>4),e+=eN.charAt(15&this.bytes[t]),(3===t||5===t||7===t||9===t)&&(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=eN.charAt(this.bytes[t]>>>4),e+=eN.charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw Error("unreachable");if(e<=7)return this.bytes.every(e=>0===e)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(e=>255===e)?"MAX":"VAR_RESERVED";throw Error("unreachable")}getVersion(){return"VAR_10"===this.getVariant()?this.bytes[6]>>>4:void 0}clone(){return new eq(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(let t=0;t<16;t++){let r=this.bytes[t]-e.bytes[t];if(0!==r)return Math.sign(r)}return 0}}class eU{constructor(e){this.timestamp=0,this.counter=0,this.random=e??eH()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);return void 0===r&&(this.timestamp=0,r=this.generateOrAbortCore(e,t)),r}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>0x3ffffffffff&&(this.timestamp++,this.resetCounter())}return eq.fromFieldsV7(this.timestamp,Math.trunc(this.counter/0x40000000),0x3fffffff&this.counter,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,eq.ofInner(e)}}let eH=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),eK=()=>eV().toString(),eV=()=>(a||(a=new eU)).generate();class eW{add(e){let t=eK(),r=++this.nextId;return this.promiseByIds[t]={id:r,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map(e=>e.promise),t=e.length;for(;t>0;)await Promise.all(e),t=(e=Object.values(this.promiseByIds).map(e=>e.promise)).length}getPromises(e=[],t=this.nextId){let r=new Set(e);return Object.values(this.promiseByIds).filter(e=>e.id<=t&&!r.has(e.promise)).map(e=>e.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}let ez=(e,t,r)=>{function i(s,...n){t(()=>{(0,r[s])(e,...n)})}return{debug:(...e)=>{i("debug",...e)},info:(...e)=>{i("log",...e)},warn:(...e)=>{i("warn",...e)},error:(...e)=>{i("error",...e)},critical:(...t)=>{r.error(e,...t)},createLogger:i=>ez(`${e} ${i}`,t,r)}};function eG(e,t=Date.now(),r=3e5){if("string"!=typeof e||!e)return;let i=e.trim(),s=/^\d+\s*,/.test(i)?i.slice(0,i.indexOf(",")).trim():i;if(/^\d+$/.test(s)){let e=1e3*Math.min(Number(s),r/1e3);return e>0?e:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(s))return;let n=Date.parse(/^\w{3} \w{3} /.test(s)?s+" GMT":s)-t;if(Number.isFinite(n)&&!(n<=0))return Math.min(n,r)}class eQ{record(e){if("too-large"===e.kind)return;if("retry-later"!==e.kind)return void this.reset();if(!e.retryAfterMs)return;let t=this.isOpen(),r=Date.now(),i=Math.min(e.retryAfterMs,3e5);if(!t){this._installedAt=r,this._until=r+i;return}this._until=Math.max(this._until,Math.min(r+i,this._installedAt+3e5))}remainingMs(){let e=Date.now();if(e<this._installedAt-5e3)return this.reset(),0;let t=Math.min(3e5,Math.max(0,this._until-e));return 0===t&&this.reset(),t}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}}class eJ extends Error{constructor(e,t,r,i){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.responseBodyDeadline=r,this.abortController=i,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return eG(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let e=ek("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e,t=new Promise((e,t)=>{this.responseBodyTimer=eM(()=>{this._bodyReadTimedOut=!0;let e=ek("AbortError","Response body read timed out");t(e),this.cancelResponseBody(e)},this.responseBodyDeadline-Date.now())});try{e=Promise.resolve(this.response.text())}catch(t){e=Promise.reject(t)}this.responseBodyTextPromise=Promise.race([e,t]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(e=>JSON.parse(e))}cancelResponseBody(e){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(e),(async()=>{try{await this.response.body?.cancel()}catch{}})()}}class eZ extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}async function eY(e){if(e instanceof eJ){let t="";try{t=await e.text}catch{e.bodyReadTimedOut&&(t="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function eX(e){return e instanceof eZ}function e0(e){if(e instanceof eJ)return 502===e.status||504===e.status;if(!(e instanceof eZ))return!1;let t=e.error;return"ECONNREFUSED"!==(t?.code??t?.cause?.code)}function e1(e){try{if("string"!=typeof e)return e instanceof Uint8Array?e.byteLength:e.size;if("u">typeof Buffer)return Buffer.byteLength(e,"utf8");return new TextEncoder().encode(e).length}catch{return 0}}function e2(e){return"object"==typeof e&&e instanceof eJ&&413===e.status}function e3(e){return e instanceof eJ?408===e.status||429===e.status||e.status>=500:eX(e)}function e5(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}let e4="default";class e6{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new k([new Y,new ei,new ee,new en],V("web:javascript",D,N))}getEvaluationRuntime(){}get apiKey(){return this.projectToken}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new eW,this._events=new ex,this._isInitialized=!1;let r="string"==typeof e?e.trim():"",i="string"==typeof t.host?t.host.trim():"",s=!r;this._logger=function(e,t=e=>e()){return ez(e,t,function(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),s&&this._logger.error("You must pass your PostHog project token. The client will be disabled."),this.projectToken=r,this.host=eC(i||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1e3),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3e3,retryCheck:e3},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||s,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!("CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&"function"==typeof Response.prototype.blob)||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){return this.disabled?void this._logger.warn("The client is disabled"):this._isInitialized?e():void this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(c.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(c.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(c.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let e=this.on("*",(e,t)=>this._logger.info(e,t));this.removeDebugCallback=()=>{e(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},r=this.mergeCommonEventProperties(t);var i=r;for(let e of Object.keys(t))(e.startsWith("$feature/")||"$active_feature_flags"===e)&&(i[e]=t[e]);return"$feature_flag_called"===e.event&&!1===r.$feature_flag_has_experiment&&this.isMinimalFlagCalledEventsEnabled()&&(r=eP(r)),{distinct_id:e.distinct_id,event:e.event,properties:r}}mergeCommonEventProperties(e){return{...e,...this.getCommonEventProperties()}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,r){this.wrap(()=>{let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",i,r)})}async identifyStatelessImmediate(e,t,r){let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",i,r)}captureStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",s,i)})}async captureStatelessImmediate(e,t,r,i){let s=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",s,i)}aliasStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",s,i)})}async aliasStatelessImmediate(e,t,r,i){let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",s,i)}groupIdentifyStateless(e,t,r,i,s,n){this.wrap(()=>{let a=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...n||{}}});this.enqueue("capture",a,i)})}async groupIdentifyStatelessImmediate(e,t,r,i,s,n){let a=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...n||{}}});await this.sendImmediate("capture",a,i)}async getRemoteConfig(){await this._initPromise;let e=this.host;"https://us.i.posthog.com"===e?e="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===e&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.projectToken}/config`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,r,{type:"required",consume:e=>e.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(e=>{this._logger.error("Remote config could not be loaded",e),this._events.emit("error",e)})}async getFlags(e,t={},r={},i={},s={},n=!1){await this._initPromise;let a=`${this.host}/flags/?v=2${n?"&config=true":""}`,o={token:this.projectToken,distinct_id:e,groups:t,person_properties:r,group_properties:i,...s};r.$device_id&&(o.$device_id=r.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(o.evaluation_contexts=this.evaluationContexts);let l=this.getEvaluationRuntime();l&&(o.evaluation_runtime=l);let u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(o)};return this._logger.info("Flags URL",a),this.fetchWithRetry(a,u,{type:"required",consume:e=>e.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:e0},this.featureFlagsRequestTimeoutMs).then(e=>({success:!0,response:(e=>{if("flags"in e){let t,r=Object.fromEntries(Object.entries(e.flags??{}).map(([e,t])=>[e,eS(t)]).filter(([,e])=>void 0!==e)),i=Object.fromEntries(Object.keys(t=e.flags??{}).filter(e=>{let r=t[e];return r.enabled&&r.metadata&&void 0!==r.metadata.payload}).map(e=>{let r=t[e].metadata?.payload;return[e,r?eF(r):void 0]}));return{...e,featureFlags:r,featureFlagPayloads:i}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([e,t])=>[e,eF(t)])),i=Object.fromEntries(Object.entries(t).map(([e,t])=>{var i,s;return[e,{key:e,enabled:"string"==typeof(i=t)||i,variant:"string"==typeof i?i:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:(s=r[e])?JSON.stringify(s):void 0,description:void 0}}]}));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}})(e)})).catch(e=>(this._events.emit("error",e),{success:!1,error:this.categorizeRequestError(e)}))}categorizeRequestError(e){if(e instanceof eJ)return{type:"api_error",statusCode:e.status};if(e instanceof eZ){let t=e.error;return t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,r={},i={},s={},n){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(e,t,r,i,s,n);if(void 0===a)return{response:void 0,requestId:void 0};let o=eS(a.response);return void 0===o&&(o=!1),{response:o,requestId:a.requestId}}async getFeatureFlagDetailStateless(e,t,r={},i={},s={},n){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,r,i,s,n,[e]);if(void 0!==a)return{response:a.flags[e],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,r={},i={},s={},n){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(t,r,i,s,n,[e]);if(!a)return;let o=a[e];return void 0===o?null:o}async getFeatureFlagPayloadsStateless(e,t={},r={},i={},s,n){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,n)).payloads}async getFeatureFlagsStateless(e,t={},r={},i={},s,n){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,n)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},i={},s,n){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(e,t,r,i,s,n);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},r={},i={},s,n){await this._initPromise;let a={geoip_disable:s??this.disableGeoip};n&&(a.flag_keys_to_evaluate=n);let o=await this.getFlags(e,t,r,i,a);if(!o.success)return;let l=o.response;return(l.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),l.quotaLimited?.includes("feature_flags"))?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.projectToken}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},r=await this.fetchWithRetry(e,t,{type:"required",consume:e=>{if(200!==e.status||!e.json){let t=`Surveys API could not be loaded: ${e.status}`,r=Error(t);return this._logger.error(r),this._events.emit("error",Error(t)),Promise.resolve(void 0)}return e.json()}}).catch(e=>{this._logger.error("Surveys API could not be loaded",e),this._events.emit("error",e)}),i=r?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(c.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(c.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(c.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return e4}persistedQueueKeyForRoute(e){return c.Queue}getActiveQueueRoutes(){return[e4]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,r,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let s=this.prepareMessage(t,r);if(null===(s=this.processBeforeEnqueue(s)))return;s=this.normalizeMessage(s);let n=this.persistedQueueKeyForRoute(i??this.getQueueRouteKey(s)),a=this.getPersistedProperty(n)||[];a.length>=this.maxQueueSize&&(a.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),a.push({message:s}),this.setPersistedProperty(n,a),this._events.emit(e,s),a.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=eM(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,r,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let s=this.prepareMessage(t,r);if(null!==(s=this.processBeforeEnqueue(s))){s=this.normalizeMessage(s);try{await this.sendBatch([s],void 0,i??this.getQueueRouteKey(s))}catch(e){this._events.emit("error",e)}}}normalizeMessage(e){let{type:t,library:r,library_version:i,...s}=e,n=e5(s.properties)?s.properties:void 0;return void 0!==r&&n?.$lib===void 0&&(n={...n||{},$lib:r}),void 0!==i&&n?.$lib_version===void 0&&(n={...n||{},$lib_version:i}),n&&(s.properties=n),s.uuid=eA(s.uuid,eK),s}normalizeTimestampForWire(e){let t=e instanceof Date?e:"string"==typeof e?new Date(e):null;if(!t||Number.isNaN(t.getTime()))return e;let r=t.toISOString(),i="string"==typeof e?e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return i&&i.length>3?r.replace(/\.\d{3}Z$/,`.${i}Z`):r}prepareMessage(e,t){let r={...e,timestamp:t?.timestamp?t?.timestamp:eT(),uuid:eA(t?.uuid,eK)};return(t?.disableGeoip??this.disableGeoip)&&(e5(r.properties)||(r.properties={}),r.properties.$geoip_disable=!0),r.distinctId&&(r.distinct_id=r.distinctId,delete r.distinctId),r}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async e=>{await eY(e)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(e,t=[]){let r=t.filter(e=>!!e),i=0;for(;;){let t=this.promiseQueue.getPromises([...r,...this.flushPromises],e);if(0===t.length)return;i>0&&this._logger.debug(`flush() re-checking ${t.length} pending promise(s) before flushing`),await Promise.all(t.map(e=>e.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,r=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(r,[t,i])}).then(()=>ej([t])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),ej([i]).then(()=>{this.flushPromises.delete(i),this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this.flushPromise===i&&(this.flushPromise=null)}),i}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&""!==e&&(t["User-Agent"]=e),t}compressPayload(e){return eB(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,t,r=e4){let i={api_key:this.projectToken,batch:e.map(e=>{if(!e)return e;let t=this.normalizeTimestampForWire(e.timestamp);return t===e.timestamp?e:{...e,timestamp:t}}),sent_at:eT()};this.historicalMigration&&(i.historical_migration=!0);let s=f(i),n=`${this.host}${this.getBatchEndpointPath(r)}`,a=this.disableCompression?null:await this.compressPayload(s),o={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==a&&{"Content-Encoding":"gzip"}},body:a||s};await this.fetchWithRetry(n,o,{type:"successful-write"},t)}async _flush(){let e;this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(e=>this.getRouteQueue(e).length>0))return;let r=[];for(let i of t)try{await this._flushRoute(i,r)}catch(t){void 0===e&&(e=t)}if(void 0!==e)throw e;this._events.emit("flush",r)}async _flushRoute(e,t){let r=this.persistedQueueKeyForRoute(e),i=this.getPersistedProperty(r)||[];if(!i.length)return;let s=i.length,n=0;for(;i.length>0&&n<s;){let s=i.slice(0,this.maxBatchSize),a=s.map(e=>void 0===e.message?e.message:this.normalizeMessage(e.message)),o=async()=>{let e=this.getPersistedProperty(r)||[],t=[...s],n=e.filter(e=>{let r=e.message?.uuid,i=t.findIndex(t=>t===e||"string"==typeof r&&r.length>0&&t.message?.uuid===r);return -1===i||(t.splice(i,1),!1)});this.setPersistedProperty(r,n),i=n,this._dequeuedMessagesCount+=s.length,await this.flushStorage()},l={retryCheck:e=>!e2(e)&&e3(e)};try{await this.sendBatch(a,l,e)}catch(e){if(e2(e)&&a.length>1){this.maxBatchSize=Math.max(1,Math.floor(a.length/2)),this._logger.warn(`Received 413 when sending batch of size ${a.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw e instanceof eZ||await o(),this._events.emit("error",e),e}await o(),t.push(...a),n+=a.length}}async _sendOtlpBatch({path:e,auth:t,payload:r}){let i;if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};try{i=JSON.stringify(r)}catch(t){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${e} batch; reporting it as too large`,t)),{kind:"too-large",measuredLocally:!0}}let s=e1(i);if(s>0xa00000)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${e} batch of ${s} bytes: the endpoint accepts at most 10485760`)),{kind:"too-large",measuredLocally:!0};let n="bearer"===t?`${this.host}/i/v1/${e}`:`${this.host}/i/v1/${e}?token=${encodeURIComponent(this.projectToken)}`,a=this.disableCompression?null:await this.compressPayload(i),o=a||i,l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",..."bearer"===t&&{Authorization:`Bearer ${this.projectToken}`},...null!==a&&{"Content-Encoding":"gzip"}},body:o};try{return await this.fetchWithRetry(n,l,{type:"successful-write"},{retryCheck:e=>!e2(e)&&(!(e instanceof eJ)||void 0===e.retryAfterMs)&&e3(e)}),{kind:"ok"}}catch(e){if(e2(e))return{kind:"too-large"};if(e3(e)){let t=e instanceof eJ?e.retryAfterMs:void 0;return{kind:"retry-later",error:e,...void 0!==t&&{retryAfterMs:t}}}return{kind:"fatal",error:e}}}async _sendLogsBatch(e){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:e})}async _sendMetricsBatch(e){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:e})}async _sendTracesBatch(e){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:e})}async fetchWithRetry(e,t,r,i,s){let n=e1(t.body?t.body:""),a={...this._retryOptions,...i},o=0;return await eO(async()=>{let i,a,l;o++;let u=new AbortController,c=s??this.requestTimeout,h=Date.now()+c,d=new Promise((e,t)=>{i=eM(()=>{let e=ek("AbortError",`Request timed out after ${c}ms`);t(e),u.abort(e)},c)}),f=!1,p=()=>l??=(async()=>{try{await a?.body?.cancel()}catch{}})();try{let i;try{i=this.fetch(e,{signal:u.signal,...t})}catch(e){throw new eZ(e)}i.then(e=>{u.signal.aborted&&!f&&Promise.resolve(e.body?.cancel()).catch(()=>{})}).catch(()=>{});try{a=await Promise.race([i,d]),f=!0}catch(e){throw new eZ(e)}let s="no-cors"===t.mode,o="successful-write"===r.type?300:400;if(!s&&(a.status<200||a.status>=o))throw new eJ(a,n,h,u);if("successful-write"===r.type){try{await Promise.race([p(),d])}catch{}return}try{return await Promise.race([r.consume(a),d])}catch(e){if(u.signal.aborted)throw new eZ(e);throw e}}finally{clearTimeout(i),u.signal.aborted&&a&&p()}},{...a,retryCheck:e=>{let t=a.retryCheck(e);return t&&o<=a.retryCount&&e instanceof eJ&&e.cancelResponseBody(),t}})}async _shutdown(e=3e4){await this._initPromise;let t=!1;if(this.clearFlushTimer(),!this.disabled)return eR((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(e=>this.getRouteQueue(e).length>0);){let e=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===e){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(e){if(!("object"==typeof e&&(e instanceof eJ||eX(e))))throw e;await eY(e)}})(),e,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:e}),t=!0})}async shutdown(e=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}class e8{constructor(e){this._onFire=e,this._firesAt=0}get pending(){return!!this._timer}arm(e){this.clear(),this._firesAt=Date.now()+e,this._timer=eM(()=>{this._timer=void 0,this._onFire()},e)}armNoEarlierThan(e){this._timer&&Date.now()+e<=this._firesAt||this.arm(e)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}function e9(){return .75+.25*Math.random()*2}function e7(e,t,r,i){let s=Math.min(Math.max(0,t-1),6),n=e*2**s;return Math.round((void 0===i?n:Math.min(n,Math.max(i,e)))*r)}let te="[Circular]",tt="[Truncated]",tr="[Unserializable]";function ti(e){let t="";for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i>=55296&&i<=56319){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(t+=e[r]+e[r+1],r++):t+="�"}else t+=i>=56320&&i<=57343?"�":e[r]}return t}function ts(e,t){if(!t)return e;let r=[];try{r=Object.keys(t)}catch{r=[]}for(let i of r){let r;try{r=t[i]}catch{r=tr}Object.defineProperty(e,i,{value:r,enumerable:!0,writable:!0,configurable:!0})}return e}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let tn=Object.prototype.propertyIsEnumerable;function ta(e,t){try{return to(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function to(e,t,r,i){let s=[];for(let n in e)if(tn.call(e,n)){if(!n){t?.debug("Dropping an attribute with an empty key");continue}if(s.length>=1e3||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let a=e[n];if(w(a)||_(a))continue;s.push({key:ti(n),value:function e(t,r,i,s){if(i.remainingNodes<=0)return{stringValue:tt};if(i.remainingNodes--,"[object Boolean]"===m.call(t))return{boolValue:t};if("bigint"==typeof t){let e,i;return e=t.toString(),t>=(i=BigInt("9223372036854775808"))||t<-i?(r?.debug(`Attribute ${e} is outside the int64 range; encoding it as a string`),{stringValue:e}):{intValue:e}}if("number"==typeof t){if(!Number.isFinite(t))return{stringValue:String(t)};if(Number.isInteger(t)){if(Number.isSafeInteger(t))return{intValue:String(t)};if("u"<typeof BigInt)return{stringValue:String(t)};let e=BigInt(t).toString();return t>=0x8000000000000000||t<-0x8000000000000000?(r?.debug(`Attribute ${e} is outside the int64 range; encoding it as a string`),{stringValue:e}):{intValue:e}}return{doubleValue:t}}if("string"==typeof t)return{stringValue:ti(t)};if("function"==typeof t)return{stringValue:"[Function]"};if("symbol"==typeof t)return{stringValue:String(t)};if("object"==typeof t&&null!==t){if(i.ancestors.has(t))return{stringValue:te};if(s>=20)return{stringValue:tt};if(t instanceof Date){let e=Number.isFinite(t.getTime())?t.toISOString():String(t);return{stringValue:"string"==typeof e?ti(e):String(e)}}i.ancestors.add(t);try{try{let n=t.toJSON;if("function"==typeof n)return e(n.call(t),r,i,s+1)}catch{}if(y(t))return{arrayValue:{values:function(t,r,i,s){let n=[],a=Math.min(t.length,1e3),o=0;for(;o<a&&i.remainingNodes>0;o++)try{let a=o in t?t[o]:void 0;if(x(a))continue;n.push(e(a,r,i,s))}catch{n.push({stringValue:tr})}return t.length>o&&n.push({stringValue:tt}),n}(t,r,i,s+1)}};return{kvlistValue:{values:to(t,r,i,s+1)}}}finally{i.ancestors.delete(t)}}return{stringValue:ti(String(t))}}(a,t,r,i)})}catch{s.push({key:ti(n),value:{stringValue:tr}})}}return s}let tl="0000000000000000",tu=tl+tl,tc=/^[0-9a-f]+$/;function th(e){let t=function(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}(function(e){let t=new Uint8Array(e),r=globalThis.crypto;if(r&&"function"==typeof r.getRandomValues)try{return r.getRandomValues(t),t}catch{}for(let r=0;r<e;r++)t[r]=Math.floor(256*Math.random());return t}(e));return/[^0]/.test(t)?t:t.slice(0,-1)+"1"}function td(e,t,r){return"string"==typeof e&&e.length===t&&e!==r&&tc.test(e)}let tf=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function tp(e){let t=tg(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:1&parseInt(t.flags,16)?ty:t_}}function tg(e){if("string"!=typeof e)return;let t=tf.exec(e.trim());if(!t)return;let[,r,i,s,n,a]=t;if("ff"!==r&&("00"!==r||!a)&&td(i,32,tu)&&td(s,16,tl))return{version:r,traceId:i,spanId:s,flags:n}}function tm(e){return Array.isArray(e)&&1===e.length?e[0]:e}let ty="01",t_="00";function tv(e){if("string"!=typeof e)return;let t=e.trim();if(!t||/[^\x20-\x7e\t]/.test(t))return;let r=t.split(",");if(!(r.length>32)){for(let e of r)if(e.trim()&&!e.includes("="))return;return t.length<=512?t:function(e){let t=[...e],r=()=>t.reduce((e,t)=>e+t.length,0)+t.length-1;for(let e=t.length-1;e>=0&&r()>512;e--)t[e].length>128&&t.splice(e,1);for(;t.length&&r()>512;)t.pop();return t.length?t.join(","):void 0}(r)}}function tb(e,t,r){return{...ts({},e.resourceAttributes),"service.name":e.serviceName||"unknown_service",...e.environment&&{"deployment.environment":e.environment},...e.serviceVersion&&{"service.version":e.serviceVersion},"telemetry.sdk.name":t,"telemetry.sdk.version":r}}let tw=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function tx(e,t){let r=ts({},e),i={};for(let e of tw)Object.prototype.hasOwnProperty.call(r,e)&&(i[e]=r[e],delete r[e]);return[...ta(r,t),...ta(i,t)]}let tS={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"},tF=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function tE(e){return String(e)+"000000"}function tP(e,t,r,i){let s="";return i&&(s=Object.keys(i).sort().map(e=>`${JSON.stringify(e)}:${JSON.stringify(i[e])}`).join(",")),`${e}\0${t}\0${r??""}\0${s}`}class tI{constructor(e,t,r){this._instance=e,this._config=t,this._logger=r,this._series=new Map,this._flushTimer=new e8(()=>this.flush().catch(e=>{this._logger.error("Metrics flush failed:",e)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._boundsByHistogram=new Map,this._boundsConflictWarned=new Set,this._boundsCapWarned=!1,this._retryAfter=new eQ,this._consecutiveFlushFailures=0,this._flushJitter=1,this._generation=0}count(e,t=1,r){this._capture({name:e,type:"count",value:t,unit:r?.unit,attributes:r?.attributes})}gauge(e,t,r){this._capture({name:e,type:"gauge",value:t,unit:r?.unit,attributes:r?.attributes})}histogram(e,t,r){this._capture({name:e,type:"histogram",value:t,unit:r?.unit,attributes:r?.attributes,bounds:y(r?.bounds)?r.bounds.slice():r?.bounds})}flush(){let e=this._flushPromise,t=(async()=>{e&&await e.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===t&&(this._flushPromise=null)});return this._flushPromise=t,t}drainWindow(){if(0===this._series.size)return null;let e=this._series;return this._startWindow(),this._buildPayload(e)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=1,this._flushTimer.clear(),this._flushPromise=null,this._startWindow(),this._boundsByHistogram=new Map,this._boundsCapWarned=!1}_startWindow(){this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._boundsConflictWarned=new Set}_capture(e){var t;let r,i,s;if(this._instance.isDisabled||this._instance.optedOut)return;let n=this._runBeforeSend(e);if(null===n)return;if(!n.name||"string"!=typeof n.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof n.value||!Number.isFinite(n.value))return void this._logger.warn(`Dropping metric '${n.name}': value must be a finite number`);if("count"!==n.type&&"gauge"!==n.type&&"histogram"!==n.type)return void this._logger.warn(`Dropping metric '${n.name}': unknown type '${String(n.type)}'`);if("count"===n.type&&n.value<0)return void this._logger.warn(`Dropping count '${n.name}': counters are monotonic, value must be >= 0`);try{r=n.attributes?{...n.attributes}:void 0,i=tP(n.type,n.name,n.unit,r)}catch(e){this._logger.warn(`Dropping metric '${n.name}': attributes could not be serialized`,e);return}let a=this._series.get(i);if(!a&&!this._admitNewSeries()||"histogram"===n.type&&!(s=this._histogramBounds(n.name,n.unit,n.bounds)))return;a||(a={name:n.name,type:n.type,unit:n.unit,attributes:r,windowStartMs:Date.now(),hist:s&&{bounds:t=s,count:0,sum:0,min:1/0,max:-1/0,bucketCounts:Array(t.length+1).fill(0)}},this._series.set(i,a));let o=this._typeByName.get(n.name);void 0===o?this._typeByName.set(n.name,n.type):o===n.type||this._typeCollisionWarned.has(n.name)||(this._typeCollisionWarned.add(n.name),this._logger.warn(`Metric name '${n.name}' is already used as a ${o}; recording it as a ${n.type} too will blend both series in charts. Use a distinct name.`)),this._fold(a,n.value);let l=this._activeTraceContext();l&&(a.exemplar={...l,value:n.value,timeMs:Date.now()}),this._armFlushTimer()}_activeTraceContext(){try{let e=tp(this._instance.getActiveSpan?.()?.traceparent());if(e&&e.flags===ty)return{traceId:e.traceId,spanId:e.spanId}}catch{}}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush||(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_histogramBounds(e,t,r){if(void 0!==r&&!function(e){if(!y(e)||0===e.length)return!1;for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t])||t>0&&e[t]<=e[t-1])return!1;return!0}(r))return void this._logger.warn(`Dropping histogram '${e}': bounds must be a non-empty array of finite, strictly increasing numbers`);let i=tP("histogram",e,t,void 0),s=this._boundsByHistogram.get(i);if(s)return this._warnOnBoundsConflict(e,i,s,r),s;if(this._boundsByHistogram.size>=this._config.maxSeriesPerFlush){if(this._boundsCapWarned||(this._boundsCapWarned=!0,this._logger.warn(`Histogram bounds limit reached (${this._config.maxSeriesPerFlush} distinct histograms); new histograms that pass custom bounds are dropped. Reduce histogram name cardinality.`)),r&&!tA(r,tF))return;return tF}let n=r?r.slice():tF;return this._boundsByHistogram.set(i,n),n}_warnOnBoundsConflict(e,t,r,i){tA(r,i??tF)||this._boundsConflictWarned.has(t)||(this._boundsConflictWarned.add(t),this._logger.warn(`Histogram '${e}' already uses the bounds [${r.join(", ")}]; samples that pass different bounds are recorded in those buckets.`))}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{let r=e.hist;r.count+=1,r.sum+=t,r.min=Math.min(r.min,t),r.max=Math.max(r.max,t),r.bucketCounts[function(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}(t,r.bounds)]+=1}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=y(t)?t:[t],i=e;for(let e of r)try{let t=e(i);if(!t)return this._logger.info("Metric was rejected in beforeSend function"),null;i=t}catch(e){return this._logger.error("Error in beforeSend function for metric:",e),null}return i}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(e7(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),0===this._series.size)return;let e=this._series;this._startWindow();let t=this._generation,r=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t===this._generation)switch(this._retryAfter.record(r),"retry-later"===r.kind?(this._consecutiveFlushFailures++,this._flushJitter=e9()):(this._consecutiveFlushFailures=0,this._flushJitter=1),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),r.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",r.error);return}}_buildPayload(e){var t,r,i,s;return t=this._buildMetrics(e),r=tb(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),i=this._instance.getLibraryId(),s=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:tx(r)},scopeMetrics:[{scope:{name:i,version:s},metrics:t}]}]}}_buildMetrics(e){let t=tE(Date.now()),r=new Map;for(let s of e.values()){var i;let e=tP(s.type,s.name,s.unit,void 0),n=r.get(e);n||(n={name:s.name,...s.unit&&{unit:s.unit}},"count"===s.type?n.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===s.type?n.gauge={dataPoints:[]}:n.histogram={aggregationTemporality:1,dataPoints:[]},r.set(e,n));let a=ta(s.attributes??{},this._logger),o=tE(s.windowStartMs),l=(i=s.exemplar)?{exemplars:[{filteredAttributes:[],timeUnixNano:tE(i.timeMs),asDouble:i.value,traceId:i.traceId,spanId:i.spanId}]}:{};if("count"===s.type){let e={attributes:a,startTimeUnixNano:o,timeUnixNano:t,asDouble:s.total??0,...l};n.sum.dataPoints.push(e)}else if("gauge"===s.type){let e={attributes:a,timeUnixNano:t,asDouble:s.last??0,...l};n.gauge.dataPoints.push(e)}else{let e=s.hist,r={attributes:a,startTimeUnixNano:o,timeUnixNano:t,count:e.count,sum:e.sum,min:e.min,max:e.max,bucketCounts:e.bucketCounts,explicitBounds:e.bounds,...l};n.histogram.dataPoints.push(r)}}return Array.from(r.values())}_mergeWindowBack(e){for(let[t,r]of e){let e=this._series.get(t);if(!e){this._admitNewSeries()&&this._series.set(t,r);continue}switch(e.windowStartMs=Math.min(e.windowStartMs,r.windowStartMs),e.exemplar=e.exemplar??r.exemplar,e.type){case"count":e.total=(e.total??0)+(r.total??0);break;case"gauge":break;case"histogram":{let t=e.hist,i=r.hist;t.count+=i.count,t.sum+=i.sum,t.min=Math.min(t.min,i.min),t.max=Math.max(t.max,i.max);for(let e=0;e<t.bucketCounts.length;e++)t.bucketCounts[e]+=i.bucketCounts[e]}}}}}function tA(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}let tk="unknown";function tC(e,t,r,i){return"string"==typeof e&&e.trim()?e.length>r?e.slice(0,r):e:(i?.debug(`${t} must be a non-empty string; using "${tk}"`),tk)}function t$(e){if(null==e)return;let t=e;if(e instanceof Date)try{t=e.getTime()}catch{return}if("number"==typeof t&&Number.isFinite(t)&&!(t<0)&&!(t>0x8637bd05af6))return t}function tO(e,t,r,i){let s=t$(e);return void 0===s?(void 0!==e&&i?.debug(`Span ${r} is out of range or not a valid time; using the derived time`),t):s}function tT(){let e=globalThis.performance;return"function"==typeof e?.now?e.now():void 0}class tM{constructor(e,t,r){for(let i of(this._onEnd=t,this._logger=r,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=e.traceId,this._spanId=e.spanId,this._parentSpanId=e.parentSpanId,this._traceState=e.traceState,this._traceFlags=e.traceFlags??ty,this._parentIsRemote=e.parentIsRemote??!1,this._name=e.name,this._kind=e.kind,this._autoKeys=new Set(e.autoAttributeKeys),this._maxAttributes=e.maxAttributes,this._maxEvents=e.maxEvents,this._maxAttributesPerEvent=e.maxAttributesPerEvent,this._maxAttributeValueLength=e.maxAttributeValueLength,this._attributes=Object.create(null),Object.keys(e.attributes)))this._writeAttribute(i,e.attributes[i]);this._startMono=e.backdated?void 0:tT(),this._startTime=e.clockAnchor&&void 0!==this._startMono?e.clockAnchor.wall+(this._startMono-e.clockAnchor.mono):e.startTime,void 0!==this._startMono&&(this._clockAnchor=e.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(void 0!==this._startMono){let e=tT();if(void 0!==e)return this._startTime+Math.max(0,e-this._startMono)}return Date.now()}_mutable(e){return!this._ended||(this._logger?.debug(`Ignoring ${e} on a span that has already ended`),!1)}_writeAttribute(e,t){if(x(t)){e in this._attributes&&!this._autoKeys.has(e)&&this._userAttributeCount--,delete this._attributes[e];return}if(!this._autoKeys.has(e)&&!(e in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[e]=tH(t,this._maxAttributeValueLength)}setAttribute(e,t){return this._mutable("setAttribute")&&this._writeAttribute(e,t),this}setAttributes(e){if(this._mutable("setAttributes")){let t=ts({},e);for(let e of Object.keys(t))this._writeAttribute(e,t[e])}return this}addEvent(e,t,r){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let i=t&&tK(t,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:tC(e,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:tO(r,this._now(),"event timestamp",this._logger),...i&&{attributes:i.attributes,...i.dropped&&{droppedAttributesCount:i.dropped}}})}return this}setStatus(e,t){if(this._mutable("setStatus")){if("ok"!==e&&"error"!==e)return this._logger?.debug(`Ignoring unknown span status "${String(e)}"; expected "ok" or "error"`),this;this._status={code:e,...t&&{message:tU(t,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(e){if(!this._mutable("recordException"))return this;let{type:t,message:r,stack:i}=tW(e);return this.addEvent(tR,{"exception.type":t,"exception.message":r,...i&&{"exception.stacktrace":i}}),this.setStatus("error",r)}updateName(e){return this._mutable("updateName")&&(this._name=tC(e,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return function(e,t,r=ty){return`00-${e}-${t}-${r}`}(this._traceId,this._spanId,this._traceFlags)}get traceId(){return this._traceId}get spanId(){return this._spanId}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(e){var t;if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let r=tO(e,this._now(),"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:r<(t=this._startTime)?t:r,...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}}let tR="exception";function tj(e){return"number"!=typeof e||!Number.isFinite(e)||e<=0?0:Math.min(Math.floor(e),0xffffffff)}class tD{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}get traceId(){return null}get spanId(){return null}tracestate(){return null}end(){}}let tL=new tD;class tB extends tD{constructor(e,t){super(),this._traceparent=e,this._tracestate=t}traceparent(){return this._traceparent}get traceId(){return this._traceparent.split("-")[1]??null}get spanId(){return this._traceparent.split("-")[2]??null}tracestate(){return this._tracestate??null}}function tN(e,t){var r;let i=tm(e?.parent)??t,s=tg(r="string"==typeof i||null==i?i:tq(i,"traceparent"))&&r.trim();return s?new tB(s,tv("string"==typeof i||null==i?e?.tracestate:tq(i,"tracestate"))):tL}function tq(e,t){try{let r=e[t];return"function"==typeof r?r.call(e):void 0}catch{return}}function tU(e,t){return e.length>t?e.slice(0,t):e}function tH(e,t){return function e(t,r,i,s){if(null===t||"object"!=typeof t)return x(t)||i.remainingNodes<=0?t:(i.remainingNodes--,"string"==typeof t?tU(t,r):t);if(i.ancestors.has(t))return te;if(i.remainingNodes<=0||s>=20)return t;i.remainingNodes--,i.ancestors.add(t);try{if(t instanceof Date)return t;let n=function(e){try{let t=e.toJSON;if("function"==typeof t)return{selfDescribed:!0,value:t.call(e)}}catch{}return{selfDescribed:!1}}(t);if(n.selfDescribed)return x(n.value)?String(n.value):e(n.value,r,i,s+1);if(y(t)){let n=Math.min(t.length,1e3),a=[];for(let o=0;o<n;o++)try{a.push(e(t[o],r,i,s+1))}catch{a.push(tr)}return t.length>n&&(a.length=t.length),a}let a={},o=0;for(let n of Object.keys(t)){let l;if(o>=1e3)break;try{l=e(t[n],r,i,s+1)}catch{l=tr}n&&!x(l)&&o++,Object.defineProperty(a,n,{value:l,enumerable:!0,writable:!0,configurable:!0})}return a}catch{return t}finally{i.ancestors.delete(t)}}(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}function tK(e,t,r){let i;try{i=Object.keys(e)}catch{return{attributes:{},dropped:0}}let s={},n=0,a=0;for(let o of i){let i;if(n>=t){a++;continue}try{i=tH(e[o],r)}catch{i=tr}x(i)||(n++,Object.defineProperty(s,o,{value:i,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:s,dropped:a}}function tV(e,t,r){return t===tL?r(t):e.with(t,()=>r(t))}function tW(e){try{let t=function(e){try{let t=e.stack;return"string"==typeof t&&t?{stack:t}:{}}catch{return{}}}(e);if(S(e))return{type:e.name||"Error",message:e.message||"",...t};if("string"==typeof e)return{type:"string",message:e};if(e&&"object"==typeof e&&"string"==typeof e.message)return{type:"string"==typeof e.name?e.name:"Object",message:e.message,...t};return{type:typeof e,message:String(e)}}catch{return{type:typeof e,message:""}}}let tz={internal:1,server:2,client:3,producer:4,consumer:5},tG={ok:1,error:2};function tQ(e){if("string"==typeof e)return ti(e);try{return ti(String(e))}catch{return tr}}function tJ(e){let t=Math.floor(e),r=Math.round((e-t)*1e6);return r>=1e6&&(t+=1,r=0),String(t)+String(r).padStart(6,"0")}function tZ(){return tT()??Date.now()}function tY(e){try{return e instanceof tM}catch{return!1}}function tX(e,t){let r=tp(e);if(r)return{traceId:r.traceId,parentSpanId:r.spanId,traceState:tv(t),traceFlags:r.flags,isRemote:!0}}function t0(e,t,r){e[t]!==r&&(e[t]=r)}class t1{constructor(e,t,r,i,s,n){this._instance=e,this._config=t,this._logger=r,this._getContext=i,this._contextManager=s,this._onSpanQueued=n,this._queue=[],this._flushTimer=new e8(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter=new eQ,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=t.maxExportBatchSize}startSpan(e,t){var r,i;let s;if(this._instance.isDisabled||this._instance.optedOut)return tN(t,this._contextManager.active());let n=tm(t?.parent);if(n&&"string"!=typeof n&&!tY(n)){if(function(e){try{return"function"==typeof e.traceparent}catch{return!1}}(n))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),tN(t,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let a=this._resolveParent(n,t);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached — spans are being started and never ended`),tN(t,this._contextManager.active());let o=Date.now(),l=(r=t?.startTime,i=this._logger,void 0===(s=t$(r))?(void 0!==r&&i?.debug("Span startTime is out of range or not a valid time; using the current time"),o):(o-s>864e5?i?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):s>o&&i?.debug("Span startTime is in the future; the span may export with a zero duration"),s)),u=th(8);this._liveSpans.set(u,tZ());let c=this._autoContextAttributes();return new tM({traceId:a?.traceId??th(16),spanId:u,parentSpanId:a?.parentSpanId,traceState:a?.traceState,traceFlags:a?.traceFlags,parentIsRemote:a?.isRemote,name:tC(e,"Span name",this._config.maxAttributeValueLength,this._logger),kind:t?.kind??"internal",attributes:ts({...c},t?.attributes),autoAttributeKeys:Object.keys(c),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:l,backdated:l!==o,clockAnchor:void 0===t$(t?.startTime)?a?.clockAnchor:void 0},(e,t)=>this._onSpanEnd(e,t),this._logger)}withSpan(e,t,r){let i=this.startSpan(e,"function"==typeof t?void 0:t);try{let e=tV(this._contextManager,i,"function"==typeof t?t:r);if(e&&"function"==typeof e.then)return e.then(e=>(i.end(),e),e=>{throw this._recordCallbackError(i,e),i.end(),e});return i.end(),e}catch(e){throw this._recordCallbackError(i,e),i.end(),e}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;){if(!this._queue.length)return;let e=this._flushPromise;if(!await (e??this._startFlush()))return}}_startFlush(){this._flushTimer.clear();let e=this._generation,t=Promise.resolve().then(()=>e===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===t&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=t,t}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(e,t){if("string"==typeof e){let r=tX(e,t?.tracestate);return r||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),r}if(tY(e))return e.childContext();let r=this._contextManager.active();return tY(r)?r.childContext():r instanceof tB?tX(r.traceparent(),r.tracestate()??void 0):void 0}_autoContextAttributes(){let e;try{e=this._getContext()}catch(e){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",e),{}}let t={};return e.distinctId&&(t.posthogDistinctId=e.distinctId),e.sessionId&&(t.sessionId=e.sessionId),e.currentUrl&&(t["url.full"]=e.currentUrl),e.screenName&&(t["screen.name"]=e.screenName),e.appState&&(t["app.state"]=e.appState),t}_recordCallbackError(e,t){if(!(e instanceof tM))return;let{type:r,message:i,stack:s}=tW(t);e.addEvent("exception",{"exception.type":r,"exception.message":i,...s&&{"exception.stacktrace":s}}),e.statusIsExplicitlyOk||e.setStatus("error",i)}_evictAgedSpans(){let e=tZ()-this._config.maxSpanAgeMs,t=0;for(let[r,i]of this._liveSpans){if(i>e)break;this._liveSpans.delete(r),t++}t&&this._recordDrop(t,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(e,t){if(!this._liveSpans.delete(e.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let r=this._runBeforeSpanSend(e,t);if(r){if(this._reportLimitDrops(r),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) — raise the flush frequency or reduce span volume`);this._queue.push(r);try{this._onSpanQueued?.()}catch(e){this._logger.debug("Span queue notification failed",e)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(e){let t=e.droppedAttributesCount??0,r=e.droppedEventsCount??0,i=0;for(let t of e.events)i+=t.droppedAttributesCount??0;(t||r||i)&&this._logger.debug(`Span limits discarded data from "${e.name}": ${t} attributes, ${r} events, ${i} event attributes`)}_runBeforeSpanSend(e,t){if(!this._config.beforeSpanSend.length)return e;let r={traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,traceState:e.traceState},i={startTime:e.startTime,endTime:e.endTime},s={attributes:e.droppedAttributesCount,events:e.droppedEventsCount},n=Object.keys(e.attributes),a={traceFlags:e.traceFlags,parentIsRemote:e.parentIsRemote},o=e.status&&{...e.status},l=e,u=e;try{var c,h,d;for(let e of this._config.beforeSpanSend){let t=e(l);if(!t)return this._recordDrop(1,"beforeSpanSend dropped it"),null;l=this._keepSpanIdentity(t,r)}if(!((c=u={traceId:r.traceId,spanId:r.spanId,parentSpanId:r.parentSpanId,traceState:r.traceState,name:l.name,kind:l.kind,status:l.status,attributes:l.attributes,events:l.events,startTime:l.startTime,endTime:l.endTime,traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote,droppedAttributesCount:s.attributes,droppedEventsCount:s.events}).attributes&&"object"==typeof c.attributes&&!Array.isArray(c.attributes)&&Array.isArray(c.events)&&void 0!==c.name&&void 0!==c.kind&&void 0!==c.startTime&&void 0!==c.endTime))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;u.name=tC(u.name,"Span name",this._config.maxAttributeValueLength,this._logger),u.status&&"ok"!==u.status.code&&"error"!==u.status.code&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),u.status=o),u.startTime=t$(u.startTime)??i.startTime,u.endTime=(h=t$(u.endTime)??i.endTime,d=u.startTime,h<d?d:h);let e=[];for(let t of u.events)try{e.push({...t,name:tC(t.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:tO(t.timestamp,u.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return u.events=e,!function(e,t,r,i,s,n,a=[]){let o=0,l=0,u={};for(let i of function(e,t){if(!t.length)return Object.keys(e);let r=t.filter(t=>Object.prototype.propertyIsEnumerable.call(e,t)),i=new Set(r);return[...r,...Object.keys(e).filter(e=>!i.has(e))]}(e.attributes,a)){let s=e.attributes[i];if(!x(s)){if(!t.has(i)){if(o>=r){l++;continue}o++}Object.defineProperty(u,i,{value:tH(s,n),enumerable:!0,writable:!0,configurable:!0})}}e.attributes=u,l&&(e.droppedAttributesCount=tj(e.droppedAttributesCount)+l);let c=0,h=0,d=[];for(let t of e.events){if(c>=i){h++;continue}if(c++,t.attributes){let e=tK(t.attributes,s,n);t.attributes=e.attributes,e.dropped&&(t.droppedAttributesCount=tj(t.droppedAttributesCount)+e.dropped)}d.push(t)}e.events=d,h&&(e.droppedEventsCount=tj(e.droppedEventsCount)+h),e.status?.message&&(e.status={...e.status,message:tU(function(e){try{return"string"==typeof e?e:String(e)}catch{return tr}}(e.status.message),n)})}(u,t,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,n),u}catch(e){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",e),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(e,t){(e.traceId!==t.traceId||e.spanId!==t.spanId||e.parentSpanId!==t.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{t0(e,"traceId",t.traceId),t0(e,"spanId",t.spanId),t0(e,"parentSpanId",t.parentSpanId),t0(e,"traceState",t.traceState)}catch{try{let r=Object.getOwnPropertyDescriptors(e);for(let e of["traceId","spanId","parentSpanId","traceState"])r[e]={value:t[e],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(e),r)}catch{;}}return e}_recordDrop(e,t){this._droppedSinceWarning+=e,this._dropReasons.add(t),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(e){let t=[];for(let r of e)try{t.push(function(e,t){var r;let i,s={traceId:e.traceId,spanId:e.spanId,name:tQ(e.name),kind:(r=e.kind)&&Object.prototype.hasOwnProperty.call(tz,r)?tz[r]:tz.internal,startTimeUnixNano:tJ(e.startTime),endTimeUnixNano:tJ(e.endTime),flags:(Number.isFinite(i=parseInt(e.traceFlags,16))?255&i:1)|256|512*!!e.parentIsRemote};e.parentSpanId&&(s.parentSpanId=e.parentSpanId),e.traceState&&(s.traceState=tQ(e.traceState));let n=ta(e.attributes,t);n.length&&(s.attributes=n),e.events.length&&(s.events=e.events.map(e=>(function(e,t){let r={name:tQ(e.name),timeUnixNano:tJ(e.timestamp)};if(e.attributes){let i=ta(e.attributes,t);i.length&&(r.attributes=i)}let i=tj(e.droppedAttributesCount);return i&&(r.droppedAttributesCount=i),r})(e,t)));let a=tj(e.droppedAttributesCount);a&&(s.droppedAttributesCount=a);let o=tj(e.droppedEventsCount);return o&&(s.droppedEventsCount=o),e.status&&(s.status={code:tG[e.status.code],...e.status.message&&{message:tQ(e.status.message)}}),s}(r,this._logger))}catch(e){this._logger.debug("Failed to encode a span; dropping it",e),this._recordDrop(1,"its attributes could not be encoded")}return t}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let e=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(e,"the user has opted out"),this._warnAboutDrops(),e}async _flushInner(){var e,t;if(!this._queue.length)return 0;let r=this._discardQueueIfConsentWithdrawn();if(r)return r;let i=function(e,t){for(let r of Object.keys(e))e[r]=tH(e[r],t);return e}((e=this._config,tb(e,this._instance.getLibraryId(),this._instance.getLibraryVersion())),this._config.maxAttributeValueLength),s=this._instance.getLibraryId(),n=this._instance.getLibraryVersion(),a=this._queue.length,o=0,l=1/0,u=this._generation;try{for(;a>0&&this._queue.length>0;){let e=this._discardQueueIfConsentWithdrawn();if(e)return o+e;let r=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,c=Math.max(1,Math.min(r,l,a,this._queue.length)),h=this._queue.slice(0,c),d=this._encodeBatch(h);if(!d.length){this._queue.splice(0,c),a-=c,o+=c,this._resetHeadBatchBudget();continue}let f=tZ()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),p=await this._instance._sendTracesBatch((t=this._logger,{resourceSpans:[{resource:{attributes:tx(i,t)},scopeSpans:[{scope:{name:s,version:n},spans:d}]}]}));if(u!==this._generation)break;if(this._retryAfter.record(p),"ok"===p.kind){this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._queue.splice(0,c),a-=c,o+=c,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if("too-large"===p.kind){if(1===c){this._queue.splice(0,1),a-=1,o+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget();continue}let e=Math.max(1,Math.floor(c/2));p.measuredLocally?l=e:this._maxExportBatchSize=e,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${e}`);continue}if("retry-later"===p.kind){if(this._consecutiveFlushFailures++,this._flushJitter=e9(),this._headBatchSize=c,f&&(this._headBatchFailures++,this._headBatchChargeableAt=tZ()+this._nextFlushDelay()),this._headBatchFailures<8)return this._logger.debug("Span export failed; retrying on the next flush",p.error),o;if(this._queue.splice(0,c),a-=c,o+=c,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(c,"the ingestion endpoint failed 8 times in a row"),this._retryAfter.isOpen())return o;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",p.error),this._queue.splice(0,c),a-=c,o+=c,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(c,"the ingestion endpoint rejected the batch")}return o}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(e=>{this._logger.debug("Background span flush failed",e)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){!this._flushTimer.pending&&this._queue.length&&this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(e7(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}}class t2{active(){return this._active}with(e,t){let r=this._active;this._active=e;try{return t()}finally{this._active=r}}}let t3=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","lightpanda","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],t5=new Map,t4=function(e,t=[]){if(!e)return!1;let r=function(e,t){let r="";for(let e=0;e<t.length;e++){let i=t[e];r+=i.length+":"+i}return e.length+":"+e+"|"+t.length+":"+r}(e,t),i=t5.get(r);if(void 0!==i)return i;let s=e.toLowerCase(),n=t3.concat(t).some(e=>-1!==s.indexOf(e.toLowerCase()));return t5.size>=256&&t5.clear(),t5.set(r,n),n};function t6(e,t){return"number"==typeof e&&Number.isInteger(e)&&e>=1?e:t}let t8=["service.name","service.version","deployment.environment"],t9={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",LOCAL_EVALUATION_INCONCLUSIVE:"local_evaluation_inconclusive",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};e.s(["FeatureFlagError",0,t9],58325);class t7{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._unresolvedFlags=Object.freeze({...e.unresolvedFlags}),this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e,t={}){let r=this._flags[e];return this._recordAccess(e,t.sendFeatureFlagEvents),r?.enabled??t.defaultValue??!1}getFlag(e,t={}){let r=this._flags[e];if(this._recordAccess(e,t.sendFeatureFlagEvents),r)return!!r.enabled&&(r.variant??!0)}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let r=this._flags[t];r&&(e[t]=r)}return this._cloneWith(e)}only(e){let t={},r=[];for(let i of e){let e=this._flags[i];e?t[i]=e:r.push(i)}return r.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${r.join(", ")}`),this._cloneWith(t)}get keys(){return Object.keys(this._flags)}get unresolvedFlags(){return this._unresolvedFlags}_getEventProperties(){let e={},t=[];for(let[r,i]of Object.entries(this._flags)){let s=!1!==i.enabled&&(i.variant??!0);e[`$feature/${r}`]=s,i.enabled&&t.push(r)}return t.length>0&&(t.sort(),e.$active_feature_flags=t),e}_cloneWith(e){return new t7({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e,t){if(this._accessed.add(e),!this._host.resolveSendFeatureFlagEvents(t)||""===this._distinctId||this._isSlice&&!(e in this._flags))return;let r=this._flags[e],i=void 0===r?void 0:!1!==r.enabled&&(r.variant??!0),s={$feature_flag:e,$feature_flag_response:i,$feature_flag_id:r?.id,$feature_flag_version:r?.version,$feature_flag_reason:r?.reason,locally_evaluated:r?.locallyEvaluated??!1,[`$feature/${e}`]:i,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:r?.locallyEvaluated?Date.now():this._evaluatedAt};r?.hasExperiment!==void 0&&(s.$feature_flag_has_experiment=r.hasExperiment),r?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(s.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let n=[];this._errorsWhileComputing&&n.push(t9.ERRORS_WHILE_COMPUTING),this._quotaLimited&&n.push(t9.QUOTA_LIMITED),void 0===r&&n.push(Object.prototype.hasOwnProperty.call(this._unresolvedFlags,e)?t9.LOCAL_EVALUATION_INCONCLUSIVE:t9.FLAG_MISSING),n.length>0&&(s.$feature_flag_error=n.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:i,groups:this._groups,disableGeoip:this._disableGeoip,properties:s})}}let re=["exact","is_not","icontains","not_icontains","starts_with","not_starts_with","ends_with","not_ends_with","regex","not_regex"];class rt extends Error{constructor(e,t="unsupported_definition"){super(e),this.name=this.constructor.name,this.reason=t,Object.setPrototypeOf(this,rt.prototype)}}function rr(e){try{return e()}catch(e){if(e instanceof rt)throw new rt(e.message,"missing_context");throw e}}function ri(e){if("boolean"==typeof e)return!0;if("string"==typeof e){let t=e.toLowerCase();return"true"===t||"false"===t}if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!ri(t in e?e[t]:null))return!1;return!0}function rs(e){if("boolean"==typeof e)return e;if("string"==typeof e)return"true"===e.toLowerCase();if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(!rs(t in e?e[t]:null))return!1;return!0}function rn(e){for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let r=e.charCodeAt(t+1);if(t+1>=e.length||r<56320||r>57343)throw new rt("Cannot stringify an unpaired surrogate like the flags service");t++}else if(r>=56320&&r<=57343)throw new rt("Cannot stringify an unpaired surrogate like the flags service")}}function ra(e,t=new Set){if(null!==e&&"boolean"!=typeof e){if("string"==typeof e)return void rn(e);if("number"==typeof e){if(!Number.isFinite(e))throw new rt(`Cannot represent non-finite number ${e} like the flags service`);return}if(Array.isArray(e)){if(t.has(e))throw new rt("Cannot represent a circular array during local evaluation");t.add(e);try{for(let r=0;r<e.length;r++)r in e&&ra(e[r],t)}finally{t.delete(e)}return}if("object"==typeof e){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&null!==r)throw new rt("Cannot represent a non-JSON object like the flags service");if(t.has(e))throw new rt("Cannot represent a circular object during local evaluation");t.add(e);try{for(let r of Object.keys(e))rn(r),ra(e[r],t)}finally{t.delete(e)}return}throw new rt(`Cannot represent ${typeof e} like the flags service`)}}function ro(e,t){let r=0,i=0;for(;r<e.length&&i<t.length;){let s=e.charCodeAt(r),n=t.charCodeAt(i),a=s>=55296&&s<=56319,o=n>=55296&&n<=56319,l=a?e.charCodeAt(r+1):0,u=o?t.charCodeAt(i+1):0,c=a?(s-55296)*1024+l-56320+65536:s,h=o?(n-55296)*1024+u-56320+65536:n;if(c!==h)return c-h;r+=a?2:1,i+=o?2:1}return e.length-t.length}function rl(e){return"string"==typeof e?(rn(e),e):function e(t,r=new Set){if(null===t)return"null";if("string"==typeof t)return rn(t),JSON.stringify(t);if("boolean"==typeof t)return t?"true":"false";if("number"==typeof t){if(!Number.isFinite(t))throw new rt(`Cannot stringify non-finite number ${t} like the flags service`);if(Number.isInteger(t))throw new rt(`Cannot distinguish integer ${t} from an integral JSON float during local evaluation`);return String(t)}if(Array.isArray(t)){if(r.has(t))throw new rt("Cannot stringify a circular array during local evaluation");r.add(t);try{let i=[];for(let s=0;s<t.length;s++)i.push(s in t?e(t[s],r):"null");return`[${i.join(",")}]`}finally{r.delete(t)}}if("object"==typeof t){let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&null!==i)throw new rt("Cannot stringify a non-JSON object like the flags service");if(r.has(t))throw new rt("Cannot stringify a circular object during local evaluation");r.add(t);try{let i=Object.keys(t);return i.forEach(rn),`{${i.sort(ro).map(i=>`${JSON.stringify(i)}:${e(t[i],r)}`).join(",")}}`}finally{r.delete(t)}}throw new rt(`Cannot stringify ${typeof t} like the flags service`)}(e)}let ru=/[\x20-\x2f:;=?@\x5b-\x60\x7b-\x7e]/;function rc(e){let t=new rt(e);return Object.defineProperty(t,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),t}function rh(e){return String(e).replace(/[A-Z]/g,e=>e.toLowerCase())}function rd(e,t,r){if(!/^\d+$/.test(e)||"strict"===r&&e.length>1&&"0"===e[0])throw new rt(`Invalid semver: ${t}`);return parseInt(e,10)}function rf(e,t="strict"){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new rt(`Invalid semver: ${e}`);let i=r.split("."),s=r=>void 0===r||""===r?0:rd(r,e,t);return[s(i[0]),s(i[1]),s(i[2])]}function rp(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return -1;if(e[r]>t[r])return 1}return 0}function rg(e,t){let r=rf(e,t);return{lower:[r[0],r[1],r[2]],upper:[r[0],r[1]+1,0]}}function rm(e,t){let[r,i,s]=rf(e,t);return{lower:[r,i,s],upper:r>0?[r+1,0,0]:i>0?[0,i+1,0]:[0,0,s+1]}}function ry(e,t){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new rt(`Invalid wildcard semver: ${e}`);let i=r.split("."),s=r=>{if("legacy-permissive"===t){let e=parseInt(r,10);if(!isNaN(e))return e}else try{return rd(r,e,t)}catch{}throw new rt(`Invalid wildcard semver: ${e}`)},n=s(i[0]);if(1===i.length)return{lower:[n,0,0],upper:[n+1,0,0]};let a=s(i[1]);return{lower:[n,a,0],upper:[n,a+1,0]}}function r_(e){if(e instanceof Date)return e;if("string"==typeof e||"number"==typeof e){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new rt(`${e} is in an invalid date format`)}throw new rt(`The date provided ${e} must be a string, number, or date object`)}function rv(e){if("boolean"==typeof e)throw new rt("Date operations cannot be performed on boolean values");return function(e){let t=e.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),r=new Date(new Date().toISOString());if(!t||!t.groups)return null;let i=parseInt(t.groups.number);if(i>=1e4)return null;let s=t.groups.interval;if("h"===s)r.setUTCHours(r.getUTCHours()-i);else if("d"===s)r.setUTCDate(r.getUTCDate()-i);else if("w"===s)r.setUTCDate(r.getUTCDate()-7*i);else if("m"===s)r.setUTCMonth(r.getUTCMonth()-i);else{if("y"!==s)return null;r.setUTCFullYear(r.getUTCFullYear()-i)}return r}(String(e))??r_(e)}function rb(e,t={}){let r=e.value,i=t.semverParsingPolicy??"strict";switch(e.operator||"exact"){case"exact":case"is_not":for(let e of Array.isArray(r)?r:[r])rl(e);return;case"is_set":case"is_not_set":case"icontains":case"not_icontains":case"starts_with":case"not_starts_with":case"ends_with":case"not_ends_with":case"regex":case"not_regex":case"gt":case"gte":case"lt":case"lte":return;case"is_date_after":case"is_date_before":rv(r);return;case"semver_eq":case"semver_neq":case"semver_gt":case"semver_gte":case"semver_lt":case"semver_lte":rf(String(r),i);return;case"semver_tilde":rg(String(r),i);return;case"semver_caret":rm(String(r),i);return;case"semver_wildcard":ry(String(r),i);return;default:throw new rt(`Unknown operator: ${e.operator}`)}}async function rw(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");return Array.from(new Uint8Array(await t.digest("SHA-1",new TextEncoder().encode(e)))).map(e=>e.toString(16).padStart(2,"0")).join("")}async function rx(e,t,r="",i="."){return parseInt((await rw(`${e}${i}${t}${r}`)).slice(0,15),16)/0x1000000000000000}async function rS(e,t){if(null==e||null==e.id||null==e.exclusion_percentage)return;let r=Number(e.exclusion_percentage);if(!Number.isFinite(r))return;let i=Math.min(Math.max(r,0),100);if(!(100!==i&&await rx("holdout",t,"","-")>i/100))return`holdout-${e.id}`}function rF(e){let t=[],r=0;for(let i of e){let e=r+i.rollout_percentage/100;t.push({valueMin:r,valueMax:e,key:i.key}),r=e}return t}async function rE(e,t,r){let i=await rx(e,t,"variant");return rF(r).find(e=>i>=e.valueMin&&i<e.valueMax)?.key}function rP(e){return"client"===e||"server"===e?e:"all"}function rI(e,t){return e===t||"all"===e||"all"===t}class rA extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,rA.prototype)}}class rk extends Error{constructor(e,t="unsupported_definition"){super(e),this.reason=t,this.name=rk.name,Error.captureStackTrace(this,rk),Object.setPrototypeOf(this,rk.prototype)}}let rC=["experience_continuity","unsupported_definition","unresolved_dependency","missing_context"];function r$(e,t){return void 0===e||rC.indexOf(t)<rC.indexOf(e)?t:e}function rO(e,t){return t instanceof rt&&Symbol.for("posthog.requiresServerRegexEvaluation")in t&&Object.defineProperty(e,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),e}class rT{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:i,host:s,customHeaders:n,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.warnedUnresolvableFlags=new Map,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=r,this.host=s,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=n,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.evaluationContexts=a.evaluationContexts,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}currentDefinitions(){return{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}withEvaluationSnapshot(e){return e.definitions?e:{...e,evaluationCache:{},definitions:this.currentDefinitions()}}createEvaluationContext(e,t={},r={},i={},s={}){return{distinctId:e,groups:t,personProperties:r,groupProperties:i,evaluationCache:s}}async getFeatureFlag(e,t,r={},i={},s={}){let n,a;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return n;if(void 0!==(a=this.featureFlagsByKey[e])){let o=this.createEvaluationContext(t,r,i,s);try{n=(await this.computeFlagAndPayloadLocally(a,o)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${n}`))}catch(t){t instanceof rk||t instanceof rt?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e}: ${t}`))}}return n}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let r={},i={},s={},n=0==this.featureFlags.length,a=t?t.map(e=>this.featureFlagsByKey[e]).filter(Boolean):this.featureFlags,o=this.withEvaluationSnapshot({...e,definitions:void 0});return await Promise.all(a.map(async e=>{try{let{value:t,payload:s}=await this.computeFlagAndPayloadLocally(e,o,{skipLoadCheck:!0});r[e.key]=t,s&&(i[e.key]=s)}catch(t){t instanceof rk||t instanceof rt?(this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e.key}: ${t.message}`)),s[e.key]=t.reason):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e.key}: ${t}`)),rI(rP(e.evaluation_runtime),"server")&&(n=!0)}})),{response:r,payloads:i,unresolved:s,fallbackToFlags:n}}async computeFlagAndPayloadLocally(e,t,r={}){let i,{matchValue:s,skipLoadCheck:n=!1}=r;if(this.loadedSuccessfullyOnce&&(t=this.withEvaluationSnapshot(t)),n||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};e=(t=this.withEvaluationSnapshot(t)).definitions.featureFlagsByKey[e.key]??e,i=void 0!==s?s:await this.computeFlagValueLocally(e,t);let a=function(e,t){if(!1===t||null==t||!e)return null;let r=e["boolean"==typeof t?t.toString():t]||null;return null==r?null:eF(r)}(e.filters?.payloads,i);return{value:i,payload:a}}async computeFlagValueLocally(e,t){let{distinctId:r,groups:i,personProperties:s,groupProperties:n}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new rt("Flag has experience continuity enabled","experience_continuity");let a=(e.filters||{}).aggregation_group_type_index;if(void 0!=a){let r=t.definitions.groupTypeMapping[String(a)];if(!r)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${a} for feature flag ${e.key}`)),new rt("Flag has unknown group type index");if(!(r in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;"device_id"===e.bucketing_identifier&&(s?.$device_id===void 0||s?.$device_id===null||s?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let o=n[r];return await this.matchFeatureFlagProperties(e,i[r],o,t)}{let i=this.getBucketingValueForFlag(e,r,s);if(void 0===i)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new rt(`Can't compute feature flag: ${e.key} without $device_id`,rM(e,t.definitions)??"missing_context");return await this.matchFeatureFlagProperties(e,i,s,t)}}getBucketingValueForFlag(e,t,r){if(e.filters?.aggregation_group_type_index!=void 0)return t;if("device_id"===e.bucketing_identifier){let e=r?.$device_id;if(null==e||""===e)return;return e}return t}async evaluateFlagDependency(e,t,r){let{evaluationCache:i}=r,s=e.key;if(!r.definitions.featureFlagsByKey)throw new rt("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new rt(`Flag dependency property for '${s}' is missing required 'dependency_chain' field`);let n=e.dependency_chain;if(!Array.isArray(n))throw new rt(`Flag dependency property for '${s}' has an invalid 'dependency_chain' (expected array, got ${typeof n})`);if(0===n.length)throw new rt(`Circular dependency detected for flag '${s}' (empty dependency chain)`);let a=n.find(e=>!(e in i)&&!r.definitions.featureFlagsByKey[e]&&!r.definitions.filteredOutFlagKeys.has(e));if(void 0!==a)throw new rt(`Missing flag dependency '${a}' for flag '${s}'`);for(let e of n){if(!(e in i)){let t=r.definitions.featureFlagsByKey[e];if(t)if(t.active)try{let s=await this.computeFlagValueLocally(t,r);i[e]=s}catch(t){if(t instanceof rk)throw new rk(`Flag dependency '${e}' for flag '${s}' requires server evaluation: ${t.message}`,"unresolved_dependency");throw rO(new rt(`Error evaluating flag dependency '${e}' for flag '${s}': ${t}`,"unresolved_dependency"),t)}else i[e]=!1;else i[e]=!1}if(null==i[e])throw new rt(`Dependency '${e}' could not be evaluated`,"unresolved_dependency")}let o=i[s];return this.flagEvaluatesToExpectedValue(e.value,o)}flagEvaluatesToExpectedValue(e,t){return"boolean"==typeof e?e===t||"string"==typeof t&&""!==t&&!0===e:"string"==typeof e&&t===e}async matchFeatureFlagProperties(e,t,r,i){let s,n,a;i=this.withEvaluationSnapshot(i);let o=e.filters||{},l=await rS(o.holdout,t);if(void 0!==l)return l;let u=o.groups||[],c=o.aggregation_group_type_index,h=o.early_exit??!1,{groups:d,groupProperties:f}=i,p=new Set;for(let l of u){let u=t;try{let t=void 0!==l.aggregation_group_type_index?l.aggregation_group_type_index:c,n=r;if(t!==c&&null!=t){let r=i.definitions.groupTypeMapping[String(t)];if(!r||!(r in d)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${t} not available`));continue}if(!(r in f)){s=r$(s,"missing_context");continue}n=f[r],u=d[r]}let p=await this.isConditionMatch(e,u,l,n,i);if("match"===p){let t=l.variant,r=o.multivariate?.variants||[];a=t&&r.some(e=>e.key===t)?t:await this.getMatchingVariant(e,u)||!0;break}if(h&&"out_of_rollout_bound"===p){if(s)break;return!1}}catch(t){if(t instanceof rk){let r;try{r=rM(e,i.definitions)}catch{}let n=r$(r$(s,t.reason),r??t.reason);throw n===t.reason?t:new rk(t.message,n)}if(t instanceof rt){if(s=r$(s,t.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in t)if(n=t,h&&void 0!=l.rollout_percentage&&await rx(e.key,u)>l.rollout_percentage/100)p.add(!1);else{let t=o.multivariate?.variants||[],r=l.variant;p.add(r&&t.some(e=>e.key===r)?r:await this.getMatchingVariant(e,u)||!0)}}else throw t}}if(void 0!==a&&!(n&&[...p].some(e=>e!==a)))return a;if(s)throw rO(new rt("Can't determine if feature flag is enabled or not with given properties",s),n);return!1}async isConditionMatch(e,t,r,i,s){let n=(s=this.withEvaluationSnapshot(s)).definitions,a=r.rollout_percentage,o=e=>{this.logMsgIfDebug(()=>console.warn(e))};if((r.properties||[]).length>0){let t,l,u;for(let e of r.properties){let r=e.type,a=!1;try{if("cohort"===r){let t=await rj(e,i,n.cohorts,this.debugMode,e=>this.evaluateFlagDependency(e,i,s),n.propertyMatchingVersion);a="not_in"===e.operator?!t:t}else if("flag"===r)a=await this.evaluateFlagDependency(e,i,s);else if(Object.prototype.hasOwnProperty.call(i,e.key))a=rR(e,i,o,n.propertyMatchingVersion);else{rb(e),t=r$(t,"missing_context");continue}}catch(e){if(e instanceof rk){void 0===t&&(u??=e),t=r$(t,e.reason);continue}if(e instanceof rt){Symbol.for("posthog.requiresServerRegexEvaluation")in e&&(l=e),t=r$(t,e.reason);continue}if(void 0!==t)break;throw e}if(!a)return"no_match"}if(u)throw u;if(t)throw rO(new rt(`Can't determine if a condition of flag ${e.key} matches`,t),l);if(void 0==a)return"match"}return void 0!=a&&await rx(e.key,t)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){return rE(e.key,t,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return rF(e.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(e){if(!this.evaluationContexts||0===this.evaluationContexts.length)return e;let t=new Set(this.evaluationContexts);return e.filter(e=>{let r=e.evaluation_contexts??e.evaluation_tags;return!r||0===r.length||r.some(e=>t.has(e))})}getEvaluationRuntimeForFlag(e){let t=this.featureFlagsByKey[e];return t?rP(t.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(e){return this.featureFlags.filter(t=>rI(rP(t.evaluation_runtime),e)).map(e=>e.key)}updateFlagState(e){let t=this.filterFlagsByEvaluationContexts(e.flags),r=t.reduce((e,t)=>(e[t.key]=t,e),{}),i=new Set(t.map(e=>e.key)),s=new Set(e.flags.filter(e=>!i.has(e.key)).map(e=>e.key));this.featureFlags=t,this.featureFlagsByKey=r,this.filteredOutFlagKeys=s,this.groupTypeMapping=e.group_type_mapping??e.groupTypeMapping??{},this.cohorts=e.cohorts,this.propertyMatchingVersion=e.property_matching_version??e.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((e.minimal_flag_called_events??e.minimalFlagCalledEvents)===!0)}warnAboutUnresolvableFlags(e){let t=[],r=[],i=new Map,s=this.currentDefinitions();for(let n of e){if(!rI(rP(n.evaluation_runtime),"server"))continue;let e=rM(n,s);if(!e)continue;let a=JSON.stringify(n);i.set(n.key,a),this.warnedUnresolvableFlags.get(n.key)!==a&&("experience_continuity"===e?t.push(n.key):r.push(n.key))}if(this.warnedUnresolvableFlags=i,t.length>0){let e=this.strictLocalEvaluation?"With strictLocalEvaluation enabled these flags are left unresolved. To evaluate them locally, disable experience continuity on these flags in PostHog.":"Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).";console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled and cannot be resolved locally (reason: experience_continuity): ${t.join(", ")}. `+e)}if(r.length>0){let e=this.strictLocalEvaluation?"With strictLocalEvaluation enabled these flags are left unresolved when evaluation reaches that part.":"Evaluating these flags falls back to a server request when evaluation reaches that part.";console.warn(`[PostHog] You are using local evaluation but ${r.length} flag(s) use something local evaluation does not support, such as a static cohort, an unknown operator, or a missing or circular flag dependency (reason: unsupported_definition): ${r.join(", ")}. ${e} To evaluate them locally, change these flags in PostHog or upgrade posthog-node.`)}}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();if(t)return this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags),!0;return!1}catch(e){return this.onError?.(Error(`Failed to load from cache: ${e}`)),!1}}async loadFeatureFlags(e=!1){if(!this.loadedSuccessfullyOnce||e)return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(e=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${e}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let e=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(6e4,e*2**this.backOffCount):e}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{if(this.cacheProvider&&!this.personalApiKey)return void await this.loadFromCache("Loaded flags from cache (cache-only reader)");let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(e){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${e}`))}if(!e&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new rA(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new rA(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new rA(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let r=await t.json()??{};if(!("flags"in r))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let i=r.group_type_mapping||{},s=!0===r.minimal_flag_called_events,n={flags:r.flags??[],group_type_mapping:i,cohorts:r.cohorts||{},minimal_flag_called_events:s,property_matching_version:r.property_matching_version,propertyMatchingVersion:r.property_matching_version,groupTypeMapping:i,minimalFlagCalledEvents:s};if(this.updateFlagState(n),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(n)}catch(e){this.onError?.(Error(`Failed to store in cache: ${e}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags);break}default:return}}catch(e){e instanceof rA&&this.onError?.(e)}finally{this.pollerStopped||null===this.pollingInterval||(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(e="GET",t){let r={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(r["If-None-Match"]=t),{method:e,headers:r}}async _requestFeatureFlagDefinitions(){if(!this.personalApiKey)throw new rA("A secretKey or personalApiKey is required to fetch feature flag definitions from PostHog.");let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),r=null;if(this.timeout&&"number"==typeof this.timeout){let e=new AbortController;r=eM(()=>{e.abort()},this.timeout),t.signal=e.signal}try{let i=this.fetch,s=await i(e,t);if(200!==s.status)return clearTimeout(r),s;return{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{clearTimeout(r)}},json:async()=>{try{return await s.json()}finally{clearTimeout(r)}}}}catch(e){throw clearTimeout(r),e}}async stopPoller(e=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await eR(t,e,()=>{throw Error(`Cache shutdown timeout after ${e}ms`)})}catch(e){this.onError?.(Error(`Error during cache shutdown: ${e}`))}}}function rM(e,t){if(!e.active)return;if(e.ensure_experience_continuity)return"experience_continuity";let r=e.filters||{},i=r.aggregation_group_type_index;return void 0==i||t.groupTypeMapping[String(i)]?(r.groups||[]).some(e=>(e.properties||[]).some(e=>(function e(t,r,i){if("flag"===t.type){let e=t.dependency_chain;return!Array.isArray(e)||0===e.length||e.some(e=>!r.featureFlagsByKey[e]&&!r.filteredOutFlagKeys.has(e))}if("cohort"!==t.type)try{return rb(t),!1}catch(e){if(e instanceof rt)return!0;throw e}let s=String(t.value);return!(s in r.cohorts)||!i.has(s)&&(i.add(s),function t(r,i,s){return(r?.values??[]).some(r=>"values"in r?t(r,i,s):e(r,i,s))}(r.cohorts[s],r,i))})(e,t,new Set)))?"unsupported_definition":void 0:"unsupported_definition"}function rR(e,t,r,i){return function(e,t,r={}){try{return function(e,t,r){let i=e.key,s=e.value,n=e.operator||"exact",a=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,i)){if("is_not_set"===n)return!1;else if("is_set"===n)return!0}else throw new rt(`Property ${i} not found in propertyValues`,"missing_context");let o=t[i];if(void 0===o)throw r.warnFunction?.(`Property ${i} cannot have a value of undefined with the ${n} operator`),new rt(`Property ${i} is undefined in propertyValues`);if(null===o&&!re.includes(n))return r.warnFunction?.(`Property ${i} cannot have a value of null with the ${n} operator`),!1;let l=(e,t)=>{if(2!==r.propertyMatchingVersion&&ri(e)||Array.isArray(e)&&0===e.length)return rr(()=>ra(t)),rs(e)===rs(t);if(2===r.propertyMatchingVersion&&"number"==typeof t&&ri(e))return rr(()=>ra(t)),!1;if(Array.isArray(e)){let r=rr(()=>rl(t)).toLowerCase();return e.some(e=>rl(e).toLowerCase()===r)}return rl(e).toLowerCase()===rr(()=>rl(t)).toLowerCase()},u=(e,t,r)=>{if("gt"===r)return e>t;if("gte"===r)return e>=t;if("lt"===r)return e<t;if("lte"===r)return e<=t;throw Error(`Invalid operator: ${r}`)},c=()=>rr(()=>rf(String(o),a)),h=()=>{let e=rf(String(s),a);return rp(c(),e)},d=({lower:e,upper:t})=>{let r=c();return rp(r,e)>=0&&0>rp(r,t)};switch(n){case"exact":return l(s,o);case"is_not":return!l(s,o);case"is_set":return!0;case"icontains":return rh(o).includes(rh(s));case"not_icontains":return!rh(o).includes(rh(s));case"starts_with":return rh(o).startsWith(rh(s));case"not_starts_with":return!rh(o).startsWith(rh(s));case"ends_with":return rh(o).endsWith(rh(s));case"not_ends_with":return!rh(o).endsWith(rh(s));case"regex":case"not_regex":{let e=function(e,t){let r;if(""===e)return!0;let i=function(e){let t=[],r=-1,i="";for(let s=0;s<e.length;s++){let n=e[s];if(n.charCodeAt(0)>127)return null;if("\\"===n){let t=e[++s];if(void 0===t)break;if("x"===t){if(!/^[\da-f]{2}$/i.test(e.slice(s+1,s+3)))return null;s+=2}else if(!"dDsSwWbBfnrtv".includes(t)&&!ru.test(t))return null;if(-1===r&&"bB".includes(t))return null;i="literal";continue}if("["===n){if(-1!==r)return null;r=s}else if("]"===n&&-1!==r){if(s===r+("^"===e[r+1]?2:1))return null;t.push(e.slice(r,s+1)),r=-1,i="literal";continue}else if(-1!==r){if(["&&","--","~~"].includes(e.slice(s,s+2)))return null;continue}else if("("===n&&"?"===e[s+1]){if(":"!==e[s+2])return null;s+=2}else if("{"===n){let t=/^\{(\d+)(?:,(\d*))?\}/.exec(e.slice(s));if(!t||["","|","("].includes(i)||t.slice(1).some(e=>Number(e)>0xffffffff))return null}else if("*+?}".includes(n)&&("+"===e[s+1]||"{"===e[s+1]))return null;if("*+?{".includes(n)&&["^","$","empty group"].includes(i))return null;i=")"===n&&["(","empty group"].includes(i)?"empty group":n}return t}(e);if(null===i)throw rc("Regex syntax requires server evaluation");try{r=new RegExp(e)}catch(e){if(e instanceof SyntaxError)return null;throw rc("Regex compilation requires server evaluation")}for(let e of i)try{RegExp(e,"u")}catch{throw rc("Regex character class syntax requires server evaluation")}for(let e=0;e<t.length;e++){let r=t[e];if(r.charCodeAt(0)>127||"\r"===r)throw rc("Regex matching for Unicode or carriage returns requires server evaluation")}try{return r.test(t)}catch{throw rc("Regex execution requires server evaluation")}}(String(s),String(o));if(null===e)return!1;return"regex"===n?e:!e}case"gt":case"gte":case"lt":case"lte":{let e="number"==typeof s?s:parseFloat(String(s)),t="number"==typeof o?o:null!=o?parseFloat(String(o)):0/0;if(Number.isFinite(e)&&Number.isFinite(t))return u(t,e,n);return u(String(o),String(s),n)}case"is_date_after":case"is_date_before":{let e=rv(s),t=rr(()=>r_(o));return"is_date_before"===n?t<e:t>e}case"semver_eq":return 0===h();case"semver_neq":return 0!==h();case"semver_gt":return h()>0;case"semver_gte":return h()>=0;case"semver_lt":return 0>h();case"semver_lte":return 0>=h();case"semver_tilde":return d(rg(String(s),a));case"semver_caret":return d(rm(String(s),a));case"semver_wildcard":return d(ry(String(s),a));default:throw new rt(`Unknown operator: ${n}`)}}(e,t,r)}catch(t){throw t instanceof rt&&"missing_context"===t.reason&&rb(e,r),t}}(e,t,{warnFunction:r,propertyMatchingVersion:i})}async function rj(e,t,r,i=!1,s,n){let a=String(e.value);if(!(a in r))throw new rk(`cohort ${a} not found in local cohorts - likely a static cohort that requires server evaluation`);return rD(r[a],t,r,i,s,n)}async function rD(e,t,r,i=!1,s,n){let a,o;if(!e)return!0;let l=e.type,u=e.values;if(!u||0===u.length)return!0;if("values"in u[0]){for(let e of u)try{let a=await rD(e,t,r,i,s,n);if("AND"===l){if(!a)return!1}else if(a)return!0}catch(t){if(t instanceof rk)throw t;if(t instanceof rt)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),a=r$(a,t.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in t&&(o=t);else throw t}if(a)throw rO(new rt("Can't match cohort without a given cohort property value",a),o);return"AND"===l}for(let e of u)try{let a;if("cohort"===e.type)a=await rj(e,t,r,i,s,n);else if("flag"===e.type){if(!s)throw new rt(`Flag dependency '${e.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);a=await s(e)}else a=rR(e,t,void 0,n);let o=e.negation||!1;if("AND"===l){if(!a&&!o||a&&o)return!1}else if(a&&!o||!a&&o)return!0}catch(t){if(t instanceof rk)throw t;if(t instanceof rt)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),a=r$(a,t.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in t&&(o=t);else throw t}if(a)throw rO(new rt("can't match cohort without a given cohort property value",a),o);return"AND"===l}let rL=["--unhandled-rejections","--unhandled_rejections"],rB=new Set(["throw","strict","warn","warn-with-error-code","none"]),rN=[...globalThis.process?.execArgv??[]],rq=globalThis.process?.env?.NODE_OPTIONS;function rU(e){let t;for(let r=0;r<e.length;r++){let i=e[r],s=rL.find(e=>i===e||i.startsWith(`${e}=`));if(!s)continue;let n=i===s?e[++r]:i.slice(s.length+1);rB.has(n)&&(t=n)}return t}let rH=function(e=rN,t=rq){return rU(e)??rU(function(e){let t=[],r="",i=!1;for(let s=0;s<e.length;s++){let n=e[s];"\\"===n&&i&&s+1<e.length?r+=e[++s]:" "!==n||i?'"'===n?i=!i:r+=n:r&&(t.push(r),r="")}return r&&t.push(r),t}(t??""))??"throw"}(),rK={mechanism:{type:"onunhandledrejection",handled:!1}},rV={mechanism:{type:"onuncaughtexception",handled:!1}},rW=new Set(["HANGING_PROMISE_REJECTION","NEXT_PRERENDER_INTERRUPTED","DYNAMIC_SERVER_USAGE","BAILOUT_TO_CLIENT_SIDE_RENDERING"]),rz=Symbol.for("react.postpone"),rG=Symbol.for("next.unhandledRejectionFilter"),rQ=Symbol.for("posthog-node.exception-autocapture.v1"),rJ=globalThis;function rZ(e){return"function"==typeof e&&!0===e._posthogErrorHandler}function rY(e){return"object"==typeof e&&null!==e||"function"==typeof e}function rX(e){return Object.assign(e,{_posthogErrorHandler:!0})}function r0(e){return e.listeners("unhandledRejection").some(e=>!rZ(e))}function r1(e,t){return function e(t,r=0){try{if(!rY(t))return!1;if(t.$$typeof===rz||"string"==typeof t.digest&&rW.has(t.digest))return!0;return r<5&&e(t.cause,r+1)}catch{return!1}}(e)||"unhandledRejection"===t&&function(e){try{return rY(e)&&"AbortError"===e.name}catch{return!1}}(e)}function r2(e){let t=new Map;for(let r of e.clients){let e=t.get(r.key);e&&(void 0!==e.getContext()||void 0===r.getContext())||t.set(r.key,r)}for(let[r,i]of e.retired)t.has(r)||t.set(r,i);return[...t.values()]}function r3(e){"function"==typeof globalThis.setImmediate?setImmediate(e):setTimeout(e,0)}function r5(e,t,r,i){let s=e.capturedThisTurn.get(t)??new Map;s.has(r)||s.set(r,i),e.capturedThisTurn.set(t,s),e.turnResetScheduled||(e.turnResetScheduled=!0,r3(()=>{r3(()=>{e.capturedThisTurn.clear(),e.turnResetScheduled=!1})}))}function r4(e,t,r,i){let s=e.capturedThisTurn.get(t),n=[];for(let a of r2(e))s?.has(a.key)||i?.has(a.key)||(r5(e,t,a.key,"autocapture"),a.capture(t,r),n.push(a));return n}function r6(e,t){return e.deferred.get(t.exception)!==t?[]:(e.deferred.delete(t.exception),t.runInContext(()=>r4(e,t.exception,t.hint,t.skipKeys)))}function r8(e,t,r){let i;if(void 0!==(i=e.capturedThisTurn.get(t))&&r2(e).every(e=>i.has(e.key))||e.deferred.has(t))return;let s={exception:t,hint:r,skipKeys:new Set(e.capturedThisTurn.get(t)?.keys()),runInContext:function(){try{let e=globalThis.process,t=e?.getBuiltinModule?.("node:async_hooks"),r=t?.AsyncLocalStorage?.snapshot?.();if(r)return r}catch{}return e=>e()}()};e.deferred.set(t,s),r3(()=>r6(e,s))}async function r9(e,t){try{console.error(t)}catch{}ii();let r=new Set([...e.clients,...e.retired.values()]);await Promise.all([...r].map(e=>e.shutdown().catch(()=>void 0))),globalThis.process.exit(1)}function r7(e,t,r,i){let s="unhandledRejection"===r?rK:rV;if(!i){r1(t,r)||r8(e,t,s);return}let n=e.deferred.get(t);n?r6(e,n):r4(e,t,s)}function ie(e){try{return String(e)}catch{return typeof e}}function it(e){let t=globalThis.process;rJ[rG]&&"function"==typeof t.rawListeners&&t.rawListeners("unhandledRejection").includes(e)&&(Object.getPrototypeOf(t).removeListener.call(t,"unhandledRejection",e),t.listeners("unhandledRejection").includes(e)||t.prependListener("unhandledRejection",e))}function ir(e){let t=globalThis.process,r=[],i=(e,i)=>{t.on(e,i),r.push(()=>t.removeListener(e,i))},s=()=>r.forEach(e=>e());if("strict"===e.mode){let r=(t,r)=>r7(e,t,r,!0);return i("uncaughtExceptionMonitor",r),{remove:s,areInstalled:()=>t.listeners("uncaughtExceptionMonitor").includes(r)}}let n=rX((t,r)=>{let i=0===globalThis.process.listeners("uncaughtException").filter(e=>"domainUncaughtExceptionClear"!==e.name&&!rZ(e)).length;r7(e,t,r,i),i&&!e.calledFatalError&&(e.calledFatalError=!0,r9(e,t))});i("uncaughtException",n);let a="throw"===e.mode||"warn-with-error-code"===e.mode,o=a&&!t.versions?.bun,l=()=>t.listeners("unhandledRejection").includes(u),u=rX(t=>{a&&!r0(globalThis.process)&&l()?function(e,t){let r=globalThis.process;if("warn-with-error-code"===e.mode){r.emitWarning(`Unhandled promise rejection: ${ie(t)}`,"UnhandledPromiseRejectionWarning"),r.exitCode=1,r1(t,"unhandledRejection")||r4(e,t,rK);return}if(r.versions?.bun){r.exitCode=1,r4(e,t,rK),e.calledFatalError||(e.calledFatalError=!0,r9(e,t));return}let i=t instanceof Error?t:Object.assign(Error(`This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "${ie(t)}".`),{name:"UnhandledPromiseRejection",code:"ERR_UNHANDLED_REJECTION"}),s=r.emit;s.call(r,"uncaughtExceptionMonitor",i,"unhandledRejection"),s.call(r,"uncaughtException",i,"unhandledRejection")}(e,t):r1(t,"unhandledRejection")||r8(e,t,rK)});return i("newListener",rX((e,r)=>{rZ(r)||("unhandledRejection"===e?(l()||t.prependListener("unhandledRejection",u),queueMicrotask(()=>{let e;(e="function"==typeof t.rawListeners?t.rawListeners("unhandledRejection"):[]).includes(u)&&e[0]!==u&&(t.removeListener("unhandledRejection",u),t.prependListener("unhandledRejection",u)),it(u)})):"Next.UnhandledRejectionFilter.MacguffinEvent"===e&&queueMicrotask(()=>{l()||t.prependListener("unhandledRejection",u)}))})),o?(i("removeListener",rX(e=>{"unhandledRejection"===e&&l()&&!r0(t)&&t.removeListener("unhandledRejection",u)})),r0(t)&&t.prependListener("unhandledRejection",u)):t.prependListener("unhandledRejection",u),it(u),r.push(()=>{t.removeListener("unhandledRejection",u),"function"==typeof t.rawListeners&&t.rawListeners("unhandledRejection").includes(u)&&Object.getPrototypeOf(t).removeListener.call(t,"unhandledRejection",u)}),{remove:s,areInstalled:()=>t.listeners("uncaughtException").includes(n)&&(o||l())}}function ii(){let e=new Set,t=rJ[rQ];if(t)for(let r of[...t.deferred.values()])r6(t,r).forEach(t=>e.add(t));return e}let is=Symbol("capturedContext");function ia(e,t,r,i,s){if(t>r&&(i.warn("min cannot be greater than max."),t=r),"[object Number]"==m.call(e)&&e==e)if(e>r)return i.warn(" cannot be greater than max: "+r+". Using max value instead."),r;else return e<t?(i.warn(" cannot be less than min: "+t+". Using min value instead."),t):e;return i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+s),ia(s??r,t,r,i)}class io{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=ia(e.bucketSize,0,100,e._logger),this._refillRate=ia(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=ia(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){let r=Math.floor((t-e.lastAccess)/this._refillInterval);if(r>0){let t=r*this._refillRate;e.tokens=Math.min(e.tokens+t,this._bucketSize),e.lastAccess=e.lastAccess+r*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),r=String(e),i=this._buckets[r];return i?this._applyRefill(i,t):(i={tokens:this._bucketSize,lastAccess:t},this._buckets[r]=i),0===i.tokens||(i.tokens--,0===i.tokens&&this._onBucketRateLimited?.(e),0===i.tokens)}stop(){this._buckets={}}}var il=el;let iu=class e{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new io({...function(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??1,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??10}}(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return e===Object(e)&&!y(e)&&"__posthog_previously_captured_error"in e&&!0===e.__posthog_previously_captured_error}static async buildEventMessage(e,t,r,i,s,n){let a,o=(a=n?{...n,properties:{...n.properties}}:null,e=>Object.assign(e,{[is]:a})),l={...s},u=e.buildFromUnknown(t,r);u.$exception_list=await e.modifyFrames(u.$exception_list);let c=il.getInjectedReleaseId();return c&&(l.$release_id=c),o({event:"$exception",distinctId:i,properties:{...u,...l},_originatedFromCaptureException:!0})}get destinationKey(){return`${this.client.apiKey}@${this.client.host}`}startAutocaptureIfEnabled(){this.isEnabled()&&(this._autocaptureClient={key:this.destinationKey,capture:(e,t)=>this.onException(e,t),getContext:()=>this.client.getContext(),flush:()=>this.client.flush(),shutdown:()=>this.client.shutdown(2e3)},this._stopAutocapture=function(e,t=rH){if(!globalThis.process?.on)return()=>void 0;let r=rJ[rQ];if(r)r.listeners.areInstalled()||(r.listeners.remove(),r.listeners=ir(r));else{let e={mode:t,clients:new Set,retired:new Map,capturedThisTurn:new Map,deferred:new Map,turnResetScheduled:!1,calledFatalError:!1,listeners:{remove:()=>void 0,areInstalled:()=>!0}};e.listeners=ir(e),rJ[rQ]=e,r=e}r.clients.add(e),r.retired.delete(e.key);let i=r;return()=>{i.clients.delete(e)&&([...i.clients].some(t=>t.key===e.key)||i.retired.set(e.key,e))}}(this._autocaptureClient))}claimExplicitCapture(e){var t;let r;return t=this.destinationKey,!(r=rJ[rQ])||r.capturedThisTurn.get(e)?.get(t)!=="autocapture"&&(r5(r,e,t,"app"),r.deferred.get(e)?.skipKeys.add(t),!0)}capturePendingExceptions(){for(let e of ii())e!==this._autocaptureClient&&this.client.addPendingPromise(e.flush().catch(()=>void 0))}onException(t,r){this.client.addPendingPromise((async()=>{if(!e.isPreviouslyCapturedError(t)){let i=await e.buildEventMessage(this.client.getErrorPropertiesBuilder(),t,r,void 0,void 0,this.client.getContext()),s=i.properties,n=s?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(n)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:n}):this.client._capturePreparedEvent(i,!1)}})().catch(e=>{this._logger.error("Failed to capture an exception:",e)}))}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop(),this.capturePendingExceptions(),this._stopAutocapture?.(),this._stopAutocapture=void 0}},ic=/^[0-9a-f]{32}$/i,ih=/^[0-9a-f]{16}$/i,id=Symbol.for("opentelemetry.js.api.1"),ip=Symbol.for("OpenTelemetry Context Key SPAN");async function ig(){try{let e=globalThis[id],t=e?.context?.active().getValue(ip),r=t?.spanContext(),i=r?.traceId,s=r?.spanId;if("string"==typeof i&&"string"==typeof s&&ic.test(i)&&ih.test(s)&&!/^0+$/.test(i)&&!/^0+$/.test(s))return{$trace_id:i.toLowerCase(),$span_id:s.toLowerCase()}}catch{}return{}}class im{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=null!==t?t:void 0}constructor(){this._memoryStorage={}}}let iy=Symbol.for("posthog-node.context-listeners"),i_=globalThis,iv=i_[iy]??=new WeakMap;function ib(e,t=!1){for(let r of iv.get(e)??[])try{r(t)}catch{}}function iw(e){ib(e,!0)}let ix="analytics";class iS extends Error{constructor({requestId:e,drops:t,retryExhausted:r,cause:i}){super(iS.buildMessage(e,t,r,i)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=r,this.cause=i}static buildMessage(e,t,r,i){let s=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${r.length} undelivered`;return i instanceof Error&&(s+=` (${i.message})`),s}}function iF(e){if("boolean"==typeof e)return e;if("number"==typeof e)return 0!==e;if("string"==typeof e){let t=e.trim().toLowerCase();if("true"===t||"1"===t)return!0;if("false"===t||"0"===t)return!1}}let iE=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:iF},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:iF},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:iF},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(e){return"string"==typeof e?e:void 0}}],iP=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function iI(e,t,r){void 0===r||t in e||(e[t]=r)}function iA(e){var t;let r={..."object"==typeof(t=e.properties)&&null!==t&&!Array.isArray(t)?e.properties:{}},i={};for(let{property:e,optionKey:t,coerce:s}of iE)if(e in r){let n=s(r[e]);void 0!==n&&(i[t]=n),delete r[e]}let s={};for(let{property:e,field:t}of iP)if(e in r){let i=r[e];"string"==typeof i&&(s[t]=i),delete r[e]}return delete r.$lib,delete r.$lib_version,iI(r,"$set",e.$set),iI(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:function(e){if("string"==typeof e){let t=new Date(e);if(Number.isNaN(t.getTime()))return new Date().toISOString();let r=t.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?r.replace(/\.\d{3}Z$/,`.${i}Z`):r}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=null==e?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}(e.timestamp),...s,options:i,properties:r}}let ik=new Set([408,500,502,503,504]);class iC{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??3e4,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??(e=>new Promise(t=>eM(t,e))),this.generateRequestId=t.generateRequestId??eK,this.compress=t.compress??eB}async sendV1Batch(e){if(0===e.length)return;let t=this.generateRequestId(),r=new Date(this.now()).toISOString(),{batch:i}=function(e,{createdAt:t,historicalMigration:r}){let i={created_at:t,batch:e.map(iA)};return r&&(i.historical_migration=!0),i}(e,{createdAt:r,historicalMigration:this.config.historicalMigration}),s=`${this.config.host}/i/v1/analytics/events`,n=[],a=i,o=Math.max(1,this.config.maxAttempts);for(let e=1;e<=o;e++){let i,l,u=e===o,c=f({created_at:r,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a});try{let{response:r,signal:o}=i=await this.sendOnce(s,c,e,t),{status:h}=r;if(h<200||h>=300)if(!u&&ik.has(h)){let t=this.parseRetryAfter(r);await i.waitFor(i.cancelBody()).catch(()=>{}),l=this.backoffDelay(e,t)}else{let e=await this.buildHttpError(r,h,i.waitFor);return this.surfaceBatchFailure(t,n,a,e)}else{let s;try{s=await i.waitFor(this.parseResponse(r))}catch(e){if(o.aborted)throw e;return this.surfaceBatchFailure(t,n,a,Error(`Capture V1 returned an unparseable ${h} response body`))}let c=this.classify(a,s,n);if(0===c.length)return this.surfacePartialDrops(t,n);if(u)return void this.onError(new iS({requestId:t,drops:n,retryExhausted:c.map(e=>e.uuid)}));a=c;let d=this.parseRetryAfter(r);l=this.backoffDelay(e,d)}}catch(r){if(i&&!i.signal.aborted)throw r;if(u)return this.surfaceBatchFailure(t,n,a,r);l=this.backoffDelay(e)}finally{i?.cleanup()}void 0!==l&&await this.sleep(l)}}async sendOnce(e,t,r,i){let s,n=this.buildHeaders(r,i),a=t;if(this.config.compressionEnabled){let e=await this.compress(t,this.config.isDebug);null!==e&&(a=e,n["Content-Encoding"]="gzip")}let o=new AbortController,l="waiting for response headers",u=new Promise((e,t)=>{s=eM(()=>{let e=Error(`Capture V1 request timed out ${l} after ${this.config.requestTimeoutMs}ms`);e.name="AbortError",t(e),o.abort(e)},this.config.requestTimeoutMs)});try{let t,r=this.fetchFn(e,{method:"POST",headers:n,body:a,signal:o.signal}),i=!1;r.then(e=>{o.signal.aborted&&!i&&this.cancelBody(e)}).catch(()=>{});let c=await Promise.race([r,u]);i=!0,l="while reading the response body";let h=!1,d=()=>t??=this.cancelBody(c);return{response:c,signal:o.signal,waitFor:e=>Promise.race([e,u]),cancelBody:d,cleanup:()=>{!h&&(h=!0,clearTimeout(s),o.signal.aborted&&d())}}}catch(e){throw clearTimeout(s),e}}buildHeaders(e,t){let r=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":r,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(i["User-Agent"]=this.config.userAgent),i}classify(e,t,r){let i=t.results??{},s=[];for(let t of e){let e=i[t.uuid];e&&("drop"===e.result?r.push({uuid:t.uuid,details:e.details??void 0}):"retry"===e.result&&s.push(t))}return s}backoffDelay(e,t){let r=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return void 0===t?r:Math.max(r,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let r=t.trim();if(/^\d+$/.test(r)){let e=parseInt(r,10);return Number.isFinite(e)&&e>0?1e3*e:void 0}let i=Date.parse(r);if(Number.isNaN(i))return;let s=i-this.now();return s>0?s:void 0}async parseResponse(e){let t=JSON.parse(await e.text());if("object"!=typeof t||null===t||Array.isArray(t))throw Error("unexpected response shape");let r=t.results;if(void 0!==r&&("object"!=typeof r||null===r||Array.isArray(r)))throw Error("unexpected results shape");return{results:r??{}}}async buildHttpError(e,t,r){let i="";try{i=(await r(e.text())).slice(0,512)}catch{}let s=i?`: ${i}`:"";return Error(`Capture V1 request failed with HTTP ${t}${s}`)}surfaceBatchFailure(e,t,r,i){this.onError(new iS({requestId:e,drops:t,retryExhausted:r.map(e=>e.uuid),cause:i}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new iS({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}}let i$="ai-capture",iO="/i/v0/ai/batch/",iT=new TextEncoder;function iM(e){return iT.encode(f(e)).length}class iR extends Error{constructor(e){super(e.message,void 0===e.cause?void 0:{cause:e.cause}),this.name=function(e,t){if("missing_secret_key"===t||401===e)return"missing_api_key";if(void 0===e)return"network_error"===t?"service_unavailable":t.startsWith("invalid_")?"validation_error":"application_error";switch(e){case 400:return"validation_error";case 403:return"invalid_permission";case 404:return"not_found";case 409:return"template_outdated"===t?"validation_error":"concurrent_idempotent_requests";case 422:return"idempotency_key_reused"===t?"invalid_idempotent_request":"validation_error";case 429:return"quota_limited"===t?"monthly_quota_exceeded":"rate_limit_exceeded";case 503:return"service_unavailable";default:return"application_error"}}(e.statusCode,e.code),this.code=e.code,this.statusCode=e.statusCode,this.why=e.why,this.fix=e.fix,this.docsUrl=e.docsUrl,this.field=e.field,this.retryAfterMs=e.retryAfterMs}}let ij="https://us.posthog.com",iD="https://eu.posthog.com",iL={"https://us.i.posthog.com":ij,"https://us.posthog.com":ij,"https://app.posthog.com":ij,"https://eu.i.posthog.com":iD,"https://eu.posthog.com":iD},iB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,iN=/^[\x21-\x7e]{1,255}$/,iq=/^[a-zA-Z0-9_-]{1,400}$/,iU={to:!0,distinctId:!0,idempotencyKey:!0,maxRetries:!0},iH={name:"templateId",fields:iG(iU,{templateId:!0,templateData:!0}),why:"A template made in PostHog sets its own sender, subject and content, and follows the project's engagement setting.",howToSend:"send a template made in PostHog with templateId"},iK={name:"templateKey",fields:iG(iU,{templateKey:!0,subject:!0,from:!0,replyTo:!0,captureEngagement:!0,html:!0,text:!0}),why:"A send with templateKey takes its content from your code.",howToSend:"send content from your code with templateKey"};class iV{constructor(e,t){this.inFlight=new Set,this.config=e,this.hooks=t}send(e,...t){return this.track(this.sendUntracked(e,t))}get(e){return this.track(this.getUntracked(e))}track(e){return this.inFlight.add(e),e.finally(()=>this.inFlight.delete(e)),e}async drain(){for(;this.inFlight.size>0;)await Promise.all(this.inFlight)}async sendUntracked(e,t){try{var r=t;if(r.some(e=>void 0!==e))throw new iR({code:"invalid_form",message:"send takes one options object, so no email was sent. Put idempotencyKey and every other option in it."});let i=function(e,t){let r=e??{},{to:i,distinctId:s,idempotencyKey:n,maxRetries:a}=r;if("string"!=typeof i||!i.trim())throw iQ("invalid_recipient","to must be one email address as a nonempty string.","to");if(void 0!==s&&("string"!=typeof s||!s))throw iQ("invalid_distinct_id","distinctId must be a nonempty string.","distinctId");let o=function(e,t){if(void 0===e.templateId==(void 0===e.templateKey))throw new iR({code:"invalid_form",message:"Send either templateId, or templateKey with subject and html or text."});return void 0===e.templateKey?function(e,t){let{templateId:r,templateData:i}=e;if("string"!=typeof r||!iB.test(r))throw iQ("invalid_template_id","templateId must be the template's UUID.","templateId");if(void 0!==i&&("object"!=typeof i||null===i||Array.isArray(i)))throw iQ("invalid_template_data","templateData must be an object.","templateData");return iz(e,iH,iK),{template_id:r.toLowerCase(),message_data:i??{},...void 0!==t&&{distinct_id:t}}}(e,t):function(e,t){let{templateKey:r,subject:i,html:s,text:n,from:a,replyTo:o,captureEngagement:l}=e;if("string"!=typeof r||!iq.test(r))throw iQ("invalid_template_key","templateKey can only have letters, digits, hyphens (-) and underscores (_), at most 400.","templateKey");if(iz(e,iK,iH),"string"!=typeof i)throw iQ("invalid_form","A send with templateKey needs a subject.","subject");if(void 0!==s&&"string"!=typeof s)throw iQ("invalid_form","html must be a string.","html");if(void 0!==n&&"string"!=typeof n)throw iQ("invalid_form","text must be a string.","text");if(void 0===s&&void 0===n)throw iQ("invalid_form","A send with templateKey needs html, text or both.","html");let u=void 0!==o&&!(Array.isArray(o)&&0===o.length);return{template_key:r,subject:i,...void 0!==s&&{html:s},...void 0!==n&&{text:n},...void 0!==a&&{from:a},...u&&{reply_to:"string"==typeof o?[o]:o},capture_engagement:l??!0,...void 0!==t&&{distinct_id:t}}}(e,t)}(r,s);if(void 0!==n&&("string"!=typeof n||!iN.test(n)))throw iQ("invalid_idempotency_key","idempotencyKey must be 1 to 255 visible ASCII characters without spaces.","idempotencyKey");if(void 0!==a&&!iW(a))throw iQ("invalid_max_retries","maxRetries must be a nonnegative integer.","maxRetries");return{path:"/api/projects/@current/messaging/send/email/",body:f({...o,to:i}),idempotencyKey:n??globalThis.crypto.randomUUID(),maxRetries:iW(a)?a:t}}(e,this.config.maxRetries),{appHost:s,secretKey:n}=this.connect("no email was sent","Sending email needs secretKey, a project secret API key with the transactional_email:write scope."),a=this.headers(n,{"Content-Type":"application/json","Idempotency-Key":i.idempotencyKey}),o=await this.withRetries(i.maxRetries,async()=>(function({status:e,payload:t,retryAfterMs:r}){let i=iY(t);if(e>=200&&e<300){let t=iZ(i.message_id);if(!t)throw new iR({code:"api_error",message:"PostHog answered without a message ID.",statusCode:e});let r=[];if(Array.isArray(i.warnings))for(let e of i.warnings)null!==e&&"object"==typeof e&&r.push({code:iZ(e.code)??"warning",message:iZ(e.detail)??iZ(e.message)??"",fix:iZ(e.fix)});return{id:t,replayed:!0===i.replayed,warnings:r}}throw iX(i,e,r)})(await this.request(s+i.path,"POST",a,i.body)));for(let e of o.warnings)this.hooks.logger.warn(`PostHog email warning ${e.code}: ${e.message}`);return{data:o,error:null}}catch(e){return{data:null,error:i0(e,"Sending the email failed unexpectedly.")}}}async getUntracked(e){try{if("string"!=typeof e||!iB.test(e))throw iQ("invalid_message_id","id must be the message ID that send() returned.","id");let{appHost:t,secretKey:r}=this.connect("no email status was read","Reading an email status needs secretKey, a project secret API key with the transactional_email:read or transactional_email:write scope."),i=t+"/api/projects/@current/messaging/emails/{messageId}/".replace("{messageId}",e.toLowerCase()),s=this.headers(r,{});return{data:await this.withRetries(this.config.maxRetries,async()=>(function({status:e,payload:t,retryAfterMs:r}){let i=iY(t);if(e<200||e>=300)throw iX(i,e,r);let s=iZ(i.id),n=iZ(i.status),a=iZ(i.created_at),o=iZ(i.status_at);if(!s||!n||!a||!o)throw new iR({code:"api_error",message:"PostHog answered without an email status.",statusCode:e});return{id:s,status:n,createdAt:a,statusAt:o,reason:iZ(i.reason)??null}})(await this.request(i,"GET",s))),error:null}}catch(e){return{data:null,error:i0(e,"Reading the email status failed unexpectedly.")}}}connect(e,t){var r,i;let s;if(this.hooks.isDisabled())throw new iR({code:"client_disabled",message:`The PostHog client is disabled, so ${e}.`});if(this.hooks.isClosed())throw new iR({code:"client_closed",message:`The PostHog client is shut down, so ${e}.`});let n=(r=this.config.host,(s="string"==typeof(i=this.config.appHost)?eC(i.trim()):"")?iL[s]??s:iL[eC(r)]);if(!n)throw new iR({code:"missing_app_host",message:"The client's host is not PostHog Cloud, so the client can't tell where to send email. Set appHost to your PostHog app host on the client."});let a=this.config.secretKey?.trim();if(!a)throw new iR({code:"missing_secret_key",message:t});return{appHost:n,secretKey:a}}headers(e,t){let r={Authorization:`Bearer ${e}`,Accept:"application/json",...t};return this.hooks.userAgent&&(r["User-Agent"]=this.hooks.userAgent),this.config.migratedFrom&&(r["X-PostHog-Migrated-From"]=this.config.migratedFrom),r}async withRetries(e,t){for(let r=0;;r++){let i;try{return await t()}catch(e){i=e instanceof iR?e:new iR({code:"network_error",message:"The request to PostHog failed.",cause:e})}let s=function(e,t,r){if(!(t>=r)&&(void 0===e.statusCode?"network_error"===e.code:409===e.statusCode?"idempotency_key_in_flight"===e.code:429===e.statusCode?"quota_limited"!==e.code:503===e.statusCode)&&(void 0===e.retryAfterMs||!(e.retryAfterMs>3e4)))return Math.max(Math.min(3e4,1e3*2**t*(.8+.4*Math.random())),e.retryAfterMs??0)}(i,r,e);if(void 0===s)throw i;await new Promise(e=>setTimeout(e,s))}}async request(e,t,r,i){let s,n,a=new AbortController,o=this.config.requestTimeoutMs,l=new Promise((e,t)=>{s=setTimeout(()=>{let e=Error(`Email request timed out after ${o}ms`);e.name="AbortError",t(e),a.abort(e)},o)}),u=Promise.resolve().then(()=>this.hooks.fetch(e,{method:t,headers:r,...void 0===i?{}:{body:i},signal:a.signal}));u.then(e=>{a.signal.aborted&&Promise.resolve(e.body?.cancel()).catch(()=>{})}).catch(()=>{});try{let e;n=await Promise.race([u,l]);try{e=await Promise.race([n.text(),l])}catch(e){if(n.status>=200&&n.status<300)throw e;return{status:n.status,payload:null,retryAfterMs:iJ(n)}}return{status:n.status,payload:function(e){try{return JSON.parse(e)}catch{return null}}(e),retryAfterMs:iJ(n)}}finally{clearTimeout(s),a.signal.aborted&&n&&Promise.resolve(n.body?.cancel()).catch(()=>{})}}}function iW(e){return"number"==typeof e&&Number.isInteger(e)&&e>=0}function iz(e,t,r){let i=Object.entries(e).find(([e,r])=>void 0!==r&&!t.fields.has(e))?.[0];if(void 0===i)return;let s=`A send with ${t.name} doesn't take ${i}, so no email was sent.`;if(!r.fields.has(i))throw new iR({code:"invalid_form",message:s,field:i,fix:`Remove ${i} and send again.`});throw new iR({code:"invalid_form",message:s,field:i,why:t.why,fix:`Remove ${i}, or ${r.howToSend}.`})}function iG(...e){return new Set(e.flatMap(e=>Object.keys(e)))}function iQ(e,t,r){return new iR({code:e,message:t,field:r})}function iJ(e){try{return eG(e.headers?.get("retry-after"),Date.now(),Number.MAX_SAFE_INTEGER)}catch{return}}function iZ(e){return"string"==typeof e&&e?e:void 0}function iY(e){return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}function iX(e,t,r){return new iR({code:iZ(e.code)??"api_error",message:iZ(e.detail)??`PostHog answered HTTP ${t}.`,statusCode:t,why:iZ(e.why),fix:iZ(e.fix),docsUrl:iZ(e.docs_url),field:iZ(e.attr),retryAfterMs:r})}function i0(e,t){return e instanceof iR?e:new iR({code:"unexpected_error",message:t,cause:e})}let i1=new Set;function i2(e,t){i1.has(e)||(i1.add(e),console.warn(`[PostHog] ${t}`))}class i3 extends e6{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(e){this._distinctIdHasSentFlagCalls=new Map(Object.entries(e??{}))}constructor(e,t={}){var r,i;let s,n="string"==typeof e?e.trim():"",a={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:("string"==typeof(r=t.host)?r.trim():"")||"https://us.i.posthog.com",personalApiKey:("string"==typeof(i=t.secretKey??t.personalApiKey)?i.trim():"")||void 0};if(super(n,a),this._memoryStorage=new im,this._isShutdown=!1,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=a,this.captureMode="v0"===(s="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0)||"v1"===s?s:"v0",this.enableFullAiCapture=!0===a.enableFullAiCapture,this.privacyMode=!0===a.privacyMode,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof a.featureFlagsPollingInterval?Math.max(a.featureFlagsPollingInterval,100):null===a.featureFlagsPollingInterval?null:3e4,"number"==typeof a.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(a.waitUntilDebounceMs,0)),"number"==typeof a.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(a.waitUntilMaxWaitMs,0)),!this.disabled&&(a.personalApiKey||a.flagDefinitionCacheProvider)){if(a.personalApiKey?.includes("phc_"))throw Error('A project API key ("phc_...") was provided as secretKey or personalApiKey. Pass the project API key as the first constructor argument. For local evaluation, set secretKey (or the deprecated personalApiKey alias) to a server-only Project Secret API Key ("phs_...") or Personal API Key ("phx_...") with feature flag read access.');!1!==a.enableLocalEvaluation&&(this.featureFlagsPoller=new rT({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:a.personalApiKey,projectApiKey:n,timeout:a.requestTimeout??1e4,host:this.host,fetch:a.fetch,onError:e=>{this._events.emit("error",e)},onLoad:e=>{this._events.emit("localEvaluationFlagsLoaded",e)},onMinimalFlagCalledEvents:e=>{this._minimalFlagCalledEvents=e},customHeaders:this.getCustomHeaders(),cacheProvider:a.flagDefinitionCacheProvider,strictLocalEvaluation:a.strictLocalEvaluation,evaluationContexts:a.evaluationContexts??a.evaluationEnvironments}))}this.errorTracking=new iu(this,a,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=a.maxCacheSize||5e4}enqueue(e,t,r,i){super.enqueue(e,t,r,i),this.scheduleDebouncedFlush()}_flushEventsAndSpans(e=!1){let t=this.flushWithPendingPromises();return!this._traces||e&&this._traces.throttled?t:ej([t,this._traces.flush().catch(()=>{})]).then(([e])=>{if("rejected"===e.status)throw e.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this.errorTracking.capturePendingExceptions(),this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(e){let t=this._flushEventsAndSpans(e),r=this.options.waitUntil;if(r&&!this._waitUntilCycle)try{r(t.catch(()=>{}))}catch{}return t}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let t,r=new Promise(e=>{t=e});try{e(r)}catch{return}this._waitUntilCycle={resolve:t,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,r=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),t>=r)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=eM(()=>{this.resolveWaitUntilFlush()},i)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){var t;return"v1"===this.captureMode&&"string"==typeof(t=e).event&&t.event.startsWith("$ai_")?"ai":ix}persistedQueueKeyForRoute(e){return e===i$?c.AiCaptureQueue:"ai"===e?c.AiQueue:c.Queue}getActiveQueueRoutes(){let e="v1"===this.captureMode?[ix,"ai"]:[ix];return this._aiCaptureRouteActive&&e.push(i$),e}getBatchEndpointPath(e){return e===i$?iO:super.getBatchEndpointPath(e)}async sendBatch(e,t,r=ix){if(r===i$)return this.sendAiCaptureBatch(e,t);if("v1"!==this.captureMode||"ai"===r)return super.sendBatch(e,t,r);let i=e.filter(e=>void 0!==e);await this.getV1Sender().sendV1Batch(i)}async sendAiCaptureBatch(e,t){let{batches:r,dropped:i}=function(e,t=8388608,r=5242880){let i=[],s=[],n=[],a=0;for(let o of e){if(void 0===o)continue;let e=iM(o);if(e>t){s.push({event:"string"==typeof o.event?o.event:"unknown",bytes:e});continue}n.length>0&&a+e>r&&(i.push(n),n=[],a=0),n.push(o),a+=e}return n.length>0&&i.push(n),{batches:i,dropped:s}}(e);for(let{event:e,bytes:t}of i){let r=`Event ${e} (${t} bytes) exceeds the 8MiB limit for ${iO}, dropping.`;this._logger.error(r),this._events.emit("error",Error(r))}for(let e of r)await this.sendAiSubBatch(e,t)}async sendAiSubBatch(e,t){try{await super.sendBatch(e,t,i$)}catch(i){if(!e2(i))throw i;if(1===e.length){let[t]=e,r="string"==typeof t.event?t.event:"unknown",i=`Event ${r} (${iM(t)} bytes) was rejected with 413 by ${iO} on its own, dropping.`;this._logger.error(i),this._events.emit("error",Error(i));return}let r=Math.ceil(e.length/2);await this.sendAiSubBatch(e.slice(0,r),t),await this.sendAiSubBatch(e.slice(r),t)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new iC({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:e=>this._events.emit("error",e),compress:e=>this.compressPayload(e)})),this._v1Sender}getLibraryVersion(){return"5.63.1"}get metrics(){var e;let t;return this._metrics||(this._metrics=new tI(this,(e=this.options.metrics,t=e?.resourceAttributes,{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1e3}),this._logger)),this._metrics}get emails(){var e,t;return this._emails||(this._emails=new iV({secretKey:this.options.personalApiKey,host:this.host,appHost:this.options.appHost,requestTimeoutMs:"number"==typeof(e=this.options.emailRequestTimeoutMs)&&Number.isFinite(e)&&e>0?e:15e3,maxRetries:"number"==typeof(t=this.options.emailRequestMaxRetries)&&Number.isFinite(t)&&t>=0?Math.floor(t):2,migratedFrom:this.options.migratedFrom},{fetch:(e,t)=>this.fetch(e,t),isDisabled:()=>this.disabled,isClosed:()=>this._isShutdown,logger:this._logger,userAgent:this.getCustomUserAgent()||void 0})),this._emails}initializeSpanContextManager(){return new t2}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces){var e,t,r;let i,s;return this._traces||(this._traces=new t1(this,(e=this.options.traces,t=this.hostResourceAttributes(),r=this._logger,i=ts({...t},function(e){if(!(!e||"object"!=typeof e||Array.isArray(e)))try{if(t8.every(t=>!(t in e)||"string"==typeof e[t]))return e;let t={...e};for(let e of t8)e in t&&"string"!=typeof t[e]&&delete t[e];return t}catch{return}}(e?.resourceAttributes)),s=t6(e?.maxExportBatchSize,512),{serviceName:i?.["service.name"]??e?.serviceName,serviceVersion:i?.["service.version"]??e?.serviceVersion,environment:i?.["deployment.environment"]??e?.environment,resourceAttributes:i,beforeSpanSend:function(e,t){if(!e)return[];let r=[e].flat().filter(e=>!!e),i=r.filter(e=>"function"==typeof e);return i.length!==r.length&&t?.critical(`beforeSpanSend: ignoring ${r.length-i.length} of ${r.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),i}(e?.beforeSpanSend,r),maxAttributesPerSpan:t6(e?.maxAttributesPerSpan,128),maxEventsPerSpan:t6(e?.maxEventsPerSpan,128),maxAttributesPerEvent:128,maxAttributeValueLength:t6(e?.maxAttributeValueLength,8192),flushIntervalMs:t6(e?.flushIntervalMs,5e3),maxExportBatchSize:s,maxQueueSize:Math.max(t6(e?.maxQueueSize,2048),s),maxLiveSpans:t6(e?.maxLiveSpans,1e4),maxSpanAgeMs:t6(e?.maxSpanAgeMs,36e5)}),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}}_tracingContext(){let e=this.context?.get();return{distinctId:e?.distinctId,sessionId:e?.sessionId}}startSpan(e,t){return this._tracesPipeline?.startSpan(e,t)??tN(t,this._spanContextManager.active())}withSpan(e,t,r){let i="function"==typeof t?void 0:t,s="function"==typeof t?t:r,n=this._tracesPipeline;return n?i?n.withSpan(e,i,s):n.withSpan(e,s):tV(this._spanContextManager,tN(i,this._spanContextManager.active()),s)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,r){"string"==typeof e&&this._logger.warn(t),"$exception"!==e.event||e._originatedFromCaptureException||this._logger.warn(r)}_sendPreparedEvent(e,t,r,i,s){return this.addPendingPromise(this._prepareEventMessage(t,i).then(({distinctId:t,event:i,properties:n,options:a})=>{let o={timestamp:a.timestamp,disableGeoip:a.disableGeoip,uuid:a.uuid},l={distinctId:t,event:i,properties:{...n,...this.getCommonEventProperties()}};return r?this.sendImmediate(e,l,o,s):this.enqueue(e,l,o,s)}).catch(e=>{e&&console.error(e)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}captureAi(e){if(this.disabled)return;let t=eA(e.uuid,eK);return this._sendPreparedAiEvent({...e,uuid:t},!1),t}async captureAiImmediate(e){if(this.disabled)return;let t=eA(e.uuid,eK);return await this._sendPreparedAiEvent({...e,uuid:t},!0),t}_sendPreparedAiEvent(e,t){return"string"!=typeof e?.event||e.event.startsWith("$ai_")||this._logger.debug(`captureAi called with non-AI event ${e.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",e,t,void 0,i$)}identify({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:n,...a}=t;this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:i||a,$set_once:s||{},$anon_distinct_id:n??void 0},disableGeoip:r},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:n,...a}=t;await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:i||a,$set_once:s||{},$anon_distinct_id:n??void 0},disableGeoip:r},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:r={}}){if(0===Object.keys(t).length&&0===Object.keys(r).length)return;let i={};Object.keys(t).length>0&&(i.$set=t),Object.keys(r).length>0&&(i.$set_once=r),this.capture({distinctId:e,event:"$set",properties:i})}unsetPersonProperties({distinctId:e,properties:t}){let r=(Array.isArray(t)?t:[t]).filter(e=>"string"==typeof e&&e.trim().length>0);0!==r.length&&this.capture({distinctId:e,event:"$set",properties:{$unset:r}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(e){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(e)}getFeatureFlagKeysByEvaluationRuntime(e){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(e)??[]}async waitForLocalEvaluationReady(e=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(t=>{let r=setTimeout(()=>{i(),t(!1)},e),i=this._events.on("localEvaluationFlagsLoaded",e=>{clearTimeout(r),i(),t(e>0)})})}_resolveDistinctId(e,t){return"string"==typeof e?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,r={},i){let s,n,a,o,l,u,c,h;if(this.disabled)return void this._logger.warn("The client is disabled");let d=r.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&e in this._flagOverrides){let t=this._flagOverrides[e];if(void 0===t)return;let r=this._payloadOverrides?.[e];return{key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:r}}let{groups:f,disableGeoip:p}=r,{onlyEvaluateLocally:g,personProperties:m,groupProperties:y}=r,_=this.addLocalPersonAndGroupProperties(t,f,m,y);m=_.allPersonProperties,y=_.allGroupProperties;let v=this.createFeatureFlagEvaluationContext(t,f,this.personPropertiesForLocalEvaluation(t,m),y);void 0==g&&(g=this.options.strictLocalEvaluation??!1);let b=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let t=this.featureFlagsPoller?.featureFlagsByKey[e];if(t)try{let r=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(t,v,{matchValue:i});if(r){b=!0;let i=r.value;l=t.id,c="Evaluated locally",h=t.has_experiment,s={key:e,enabled:!1!==i,variant:"string"==typeof i?i:void 0,payload:r.payload??void 0,reason:c,reasonCode:!1===t.active?"flag_disabled":void 0}}}catch(t){if(t instanceof rk||t instanceof rt)this._logger?.info(`${t.name} when computing flag locally: ${e}: ${t.message}`);else throw t}}if(!b&&!g){let t=await super.getFeatureFlagDetailsStateless(v.distinctId,v.groups,m,y,p,[e]);if(void 0===t)o=t9.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===t.minimalFlagCalledEvents,n=t.requestId,a=t.evaluatedAt;let r=[];t.errorsWhileComputingFlags&&r.push(t9.ERRORS_WHILE_COMPUTING),t.quotaLimited?.includes("feature_flags")&&r.push(t9.QUOTA_LIMITED);let i=t.flags[e];if(void 0===i)r.push(t9.FLAG_MISSING);else{let t;if(l=i.metadata?.id,u=i.metadata?.version,c=i.reason?.description??i.reason?.code,h=i.metadata?.has_experiment,i.metadata?.payload!==void 0)try{t=JSON.parse(i.metadata.payload)}catch{t=i.metadata.payload}s={key:e,enabled:i.enabled,variant:i.variant??void 0,payload:t,reason:c,reasonCode:i.reason?.code}}r.length>0&&(o=r.join(","))}}if(d){let r=void 0===s?void 0:!1!==s.enabled&&(s.variant??!0),i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:l,$feature_flag_version:u,$feature_flag_reason:c,locally_evaluated:b,[`$feature/${e}`]:r,$feature_flag_request_id:n,$feature_flag_evaluated_at:b?Date.now():a};if(void 0!==h&&(i.$feature_flag_has_experiment=h),b&&this.featureFlagsPoller){let e=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==e&&(i.$feature_flag_definitions_loaded_at=e)}o&&(i.$feature_flag_error=o),this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:r,groups:f,disableGeoip:p,properties:i})}return void 0!==s&&void 0!==this._payloadOverrides&&e in this._payloadOverrides&&(s={...s,payload:this._payloadOverrides[e]}),s}async getFeatureFlag(e,t,r){i2("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(r?.sendFeatureFlagEvents)});if(void 0!==i)return!1!==i.enabled&&(i.variant??!0)}async getFeatureFlagPayload(e,t,r,i){if(i2("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request."),void 0!==this._payloadOverrides&&e in this._payloadOverrides)return this._payloadOverrides[e];let s=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:!1},r);if(void 0!==s)return s.payload??null}async getFeatureFlagResult(e,t,r){let{distinctId:i,options:s}=this._resolveDistinctId(t,r);return i?this._getFeatureFlagResult(e,i,{...s,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(s?.sendFeatureFlagEvents)}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let r=await t.json();if("string"==typeof r)try{return JSON.parse(r)}catch(e){}return r}async isFeatureEnabled(e,t,r){i2("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(r?.sendFeatureFlagEvents)});return void 0===i?void 0:!1!==i.enabled&&!!(i.variant??!0)}async getAllFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);return r?(await this.getAllFlagsAndPayloads(r,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads — pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:s,disableGeoip:n,flagKeys:a}=i||{},{onlyEvaluateLocally:o,personProperties:l,groupProperties:u}=i||{},c=this.addLocalPersonAndGroupProperties(r,s,l,u);l=c.allPersonProperties,u=c.allGroupProperties;let h=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,l),u);void 0==o&&(o=this.options.strictLocalEvaluation??!1);let d=await this.featureFlagsPoller?.getAllFlagsAndPayloads(h,a),f={},p={},g=!0;if(d&&(f=d.response,p=d.payloads,g=d.fallbackToFlags),g&&!o){let e=await super.getFeatureFlagsAndPayloadsStateless(h.distinctId,h.groups,l,u,n,a);f={...f,...e.flags||{}},p={...p,...e.payloads||{}}}return void 0!==this._flagOverrides&&(f={...f,...this._flagOverrides}),void 0!==this._payloadOverrides&&(p={...p,...this._payloadOverrides}),{featureFlags:f,featureFlagPayloads:p}}async evaluateFlags(e,t){let r,i,{distinctId:s,options:n}=this._resolveDistinctId(e,t);if(!s)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new t7({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new t7({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,flags:{}});let{groups:a,disableGeoip:o}=n||{},l=n?.flagKeys??void 0;if(l?.length===0)return new t7({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:a,disableGeoip:o,flags:{}});let{onlyEvaluateLocally:u,personProperties:c,groupProperties:h}=n||{},d=this.addLocalPersonAndGroupProperties(s,a,c,h);c=d.allPersonProperties,h=d.allGroupProperties;let f=this.createFeatureFlagEvaluationContext(s,a,this.personPropertiesForLocalEvaluation(s,c),h);void 0==u&&(u=this.options.strictLocalEvaluation??!1);let p=l?new Set(l):void 0,g={},m=!1,y=!1,_=await this.featureFlagsPoller?.getAllFlagsAndPayloads(f,l),v=new Set;if(_)for(let[e,t]of Object.entries(_.response)){let r=this.featureFlagsPoller?.featureFlagsByKey[e];g[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:_.payloads[e],id:r?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:r?.has_experiment},v.add(e)}let b=void 0!==p&&Array.from(p).some(e=>this.featureFlagsPoller?.featureFlagsByKey[e]===void 0);if((!_||_.fallbackToFlags||b)&&!u){let e=await super.getFeatureFlagDetailsStateless(f.distinctId,f.groups,c,h,o,l);if(e)for(let[t,s]of(this._minimalFlagCalledEvents=!0===e.minimalFlagCalledEvents,r=e.requestId,i=e.evaluatedAt,m=!!e.errorsWhileComputingFlags,y=Array.isArray(e.quotaLimited)&&e.quotaLimited.includes("feature_flags"),Object.entries(e.flags))){let e;if(!v.has(t)){if(s.metadata?.payload!==void 0)try{e=JSON.parse(s.metadata.payload)}catch{e=s.metadata.payload}g[t]={key:t,enabled:s.enabled,variant:s.variant,payload:e,id:s.metadata?.id,version:s.metadata?.version,reason:s.reason?.description??s.reason?.code,locallyEvaluated:!1,hasExperiment:s.metadata?.has_experiment}}}}if(void 0!==this._flagOverrides)for(let[e,t]of Object.entries(this._flagOverrides)){if(void 0===t){delete g[e];continue}let r=g[e];g[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:r?.payload,id:r?.id,version:r?.version,reason:r?.reason,locallyEvaluated:r?.locallyEvaluated??!1,hasExperiment:r?.hasExperiment}}if(void 0!==this._payloadOverrides)for(let[e,t]of Object.entries(this._payloadOverrides)){let r=g[e];r&&(g[e]={...r,payload:t})}if(void 0!==p)for(let e of Object.keys(g))p.has(e)||delete g[e];let w={};for(let[e,t]of Object.entries(_?.unresolved??{}))Object.prototype.hasOwnProperty.call(g,e)||(w[e]=t);return new t7({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:a,disableGeoip:o,flags:g,unresolvedFlags:w,requestId:r,evaluatedAt:i,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:m,quotaLimited:y})}_shouldSendMinimalFlagCalledEvent(e,t){return"$feature_flag_called"===e&&this._minimalFlagCalledEvents&&!1===t.$feature_flag_has_experiment}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:r,response:i,groups:s,disableGeoip:n,properties:a}=e,o=s&&Object.keys(s).length>0?`_${JSON.stringify(Object.entries(s).sort(([e],[t])=>e<t?-1:+(e>t)))}`:"",l=`${r}_${i}${o}`,u=this._distinctIdHasSentFlagCalls.get(t)??new Set;if(this._distinctIdHasSentFlagCalls.delete(t),this._distinctIdHasSentFlagCalls.set(t,u),!u.has(l)){for(u.add(l);this._distinctIdHasSentFlagCalls.size>Math.max(this.maxCacheSize,1);){let e=this._distinctIdHasSentFlagCalls.keys().next().value;if(void 0===e)break;this._distinctIdHasSentFlagCalls.delete(e)}this.capture({distinctId:t,event:"$feature_flag_called",properties:a,groups:s,disableGeoip:n})}}_resolveSendFeatureFlagEvents(e){return e??this.options.sendFeatureFlagEvent??!0}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),resolveSendFeatureFlagEvents:e=>this._resolveSendFeatureFlagEvents(e),logWarning:e=>{!1!==this.options.featureFlagsLogWarnings&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:s}){this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:s},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:s}){await this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:s},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=e=>Object.fromEntries(e.map(e=>[e,!0]));if(!1===e){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(!1===e.flags?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):void 0!==e.flags&&(this._flagOverrides={...e.flags})),"payloads"in e&&(!1===e.payloads?this._payloadOverrides=void 0:void 0!==e.payloads&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if("flags"in e){let t=e.flags;if(!1===t||Array.isArray(t)||"object"==typeof t&&null!==t)return!0}if("payloads"in e){let t=e.payloads;if(!1===t||"object"==typeof t&&null!==t)return!0}return!1}withContext(e,t,r){return this.context?this.context.run(e,()=>(ib(this),t()),r):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t),ib(this)}async _shutdown(e){let t=Date.now()+(e??3e4);this._isShutdown=!0;let r=this._emails?.drain(),i=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await eR(this._metrics.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._metrics.reset()),this._traces&&(await eR(this._traces.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._traces.reset());let s=Math.max(0,t-Date.now()),n=r?eR(r,s):void 0;try{return await super._shutdown(s)}finally{await n,this._distinctIdHasSentFlagCalls.clear(),i?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let e=new AbortController;i=eM(()=>{e.abort()},this.options.requestTimeout),r.signal=e.signal}try{return await this.fetch(t,r)}catch(e){this._events.emit("error",e);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let r={},i={};for(let[s,n]of Object.entries(e))if(function(e){return"[object Object]"===Object.prototype.toString.call(e)}(n)&&t&&s in t){let e={};for(let[t,r]of Object.entries(n))e[String(t)]=String(r);i[String(s)]=e}else r[String(s)]=String(n);return{personProperties:r,groupProperties:i}}async getFeatureFlagsForEvent(e,t,r,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let s=i?.personProperties||{},n=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:n,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:a})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:n,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(e,t,s,n,r)).flags}addLocalPersonAndGroupProperties(e,t,r,i){let s={...r||{}},n={};if(t)for(let e of Object.keys(t))n[e]={$group_key:t[e],...i?.[e]||{}};return{allPersonProperties:s,allGroupProperties:n}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,r,i){return{distinctId:e,groups:t||{},personProperties:r||{},groupProperties:i||{},evaluationCache:{}}}captureException(e,t,r,i,s){if(!iu.isPreviouslyCapturedError(e)&&this.errorTracking.claimExplicitCapture(e)){let n=Error("PostHog syntheticException");this.addPendingPromise(iu.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:n},t,r,this.getContext()).then(e=>this._capturePreparedEvent({...e,uuid:i,flags:s},!1)))}}async captureExceptionImmediate(e,t,r,i){if(!iu.isPreviouslyCapturedError(e)&&this.errorTracking.claimExplicitCapture(e)){let s=Error("PostHog syntheticException");return this.addPendingPromise(iu.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,r,this.getContext()).then(e=>this.captureImmediate({...e,flags:i})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){var r;let{distinctId:i,event:s,properties:n,groups:a,flags:o,sendFeatureFlags:l,timestamp:u,disableGeoip:c,uuid:h}=e,d=(r=this.context?.get(),is in e?e[is]??void 0:r),f=t.includeContextProperties??!0,p=i||d?.distinctId,g=f?{...this.props,...d?.properties||{},...n||{}}:{...n||{}};"$exception"!==s||"$trace_id"in g||"$span_id"in g||Object.assign(g,await ig()),p||(p=eK(),g.$process_person_profile=!1),f&&d?.sessionId&&!g.$session_id&&(g.$session_id=d.sessionId);let m=this._shouldSendMinimalFlagCalledEvent(s,g)?eP(g):g,y=this._runBeforeSend({distinctId:p,event:s,properties:m,groups:a,flags:o,sendFeatureFlags:l,timestamp:u,disableGeoip:c,uuid:h});if(!y)return Promise.reject(null);let _=await Promise.resolve().then(async()=>{if(o)return l&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),o._getEventProperties();if(l){i2("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");var e=await this.getFeatureFlagsForEvent(y.distinctId,a,c,"object"==typeof l?l:void 0);if(!e)return{};let t={};for(let[r,i]of Object.entries(e))t[`$feature/${r}`]=i;let r=Object.keys(e).filter(t=>!1!==e[t]).sort();return r.length>0&&(t.$active_feature_flags=r),t}return{}}).catch(()=>({})).then(e=>{let t=y.groups||a;return{...e,...y.properties||{},...void 0!==t&&Object.keys(t).length>0?{$groups:t}:{}}});return"$pageview"===y.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof _.$raw_user_agent&&t4(_.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(y.event="$bot_pageview",_.$browser_type="bot"),{distinctId:y.distinctId,event:y.event,properties:_,options:{timestamp:y.timestamp,disableGeoip:y.disableGeoip,uuid:y.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let r=Array.isArray(t)?t:[t],i=e;for(let t of r)try{if(!(i=t(i)))return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!i.properties||0===Object.keys(i.properties).length){let e=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(e)}}catch(t){return this._logger.error(`Error in before_send function for event '${e.event}':`,t),null}return i}}var i5=el,i4=el,i6=el,i8=el,i9=el,i7=el,se=el,st=el,sr=e.i(78500);let si=new WeakMap;function ss(e,t,r){let i=e&&si.get(e);return r?si.set(t,{signal:r,parent:i}):i&&si.set(t,i),t}class sn{constructor(){this.storage=new sr.AsyncLocalStorage}get(){let e=this.storage.getStore();return e&&function(e){let t=si.get(e);for(;t;){if(t.signal.aborted)return!1;t=t.parent}return!0}(e)?e:void 0}run(e,t,r){return this.storage.run(this.resolve(e,r),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){let r=this.get();return t?.fresh===!0?ss(void 0,{...e},t.signal):ss(r,{distinctId:e.distinctId??r?.distinctId,sessionId:e.sessionId??r?.sessionId,properties:{...r?.properties||{},...e.properties||{}}},t?.signal)}}class sa{active(){return this._storage.getStore()}with(e,t){return this._storage.run(e,t)}constructor(){this._storage=new sr.AsyncLocalStorage}}var so=e.i(27028);let sl=(0,e.i(12057).promisify)(so.gzip);async function su(e,t=!0){try{let t=await sl(e);return new Uint8Array(t)}catch(e){return t&&console.error("Failed to gzip compress data",e),null}}var sc=e.i(60526),il=el;let sh="posthog-node";function sd(e,{organization:t,projectId:r,prefix:i,severityAllowList:s=["error"],sendExceptionsToPostHog:n=!0}={}){return a=>{if(!("*"===s||s.includes(a.level)))return a;a.tags||(a.tags={});let o=a.tags[sp.POSTHOG_ID_TAG];if(void 0===o)return a;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${o}`,l).toString();a.tags["PostHog Person URL"]=u;let c=a.exception?.values||[],h=c.map(e=>({...e,stacktrace:e.stacktrace?{...e.stacktrace,type:"raw",frames:(e.stacktrace.frames||[]).map(e=>({...e,platform:"node:javascript"}))}:void 0})),d={$exception_message:c[0]?.value||a.message,$exception_type:c[0]?.type,$exception_level:a.level,$exception_list:h,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:c[0]?.value||a.message,$sentry_exception_type:c[0]?.type,$sentry_tags:a.tags},f=il.getInjectedReleaseId();return f&&(d.$release_id=f),t&&r&&(d.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+a.event_id),n&&e.capture({event:"$exception",distinctId:o,properties:d}),a}}function sf(e,t){let r=sd(e,t);return{name:sh,processEvent:e=>r(e)}}class sp{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(e,t,r,i,s){this.name=sh,this.name=sh,this.setupOnce=function(n,a){n(sd(e,{organization:t,projectId:a()?.getClient()?.getDsn()?.projectId,prefix:r,severityAllowList:i,sendExceptionsToPostHog:s??!0}))}}}function sg(e){let t={};if(e)for(let r of e.split(";")){let[e,...i]=r.trim().split("=");if(e){let r=i.join("=").trim();try{t[e.trim()]=decodeURIComponent(r)}catch{t[e.trim()]=r}}}return{get:e=>e in t?{value:t[e]}:void 0}}function sm(e){let t=e.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${t}_posthog`}function sy(e){let t=Date.now();return JSON.stringify({distinct_id:e,$device_id:e,$user_state:"anonymous",$sesid:[t,eK(),t]})}function s_(e,t){let r=sm(t),i=e.get(r);return i?sb(i.value):null}function sv(e){if(!e)return;let t={};return e.sessionId&&(t.$session_id=e.sessionId),e.deviceId&&(t.$device_id=e.deviceId),Object.keys(t).length>0?t:void 0}function sb(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||"object"!=typeof t||!t.distinct_id)return null;let r=y(t.$sesid)?t.$sesid:[],i=r[1];return{distinctId:String(t.distinct_id),isIdentified:"identified"===t.$user_state,sessionId:"string"==typeof i?i:void 0,sessionLastActivityTimestamp:sw(r[0]),sessionStartTimestamp:sw(r[2]),deviceId:"string"==typeof t.$device_id?t.$device_id:void 0}}catch{return null}}function sw(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}e.s(["PostHogSentryIntegration",0,sp,"createEventProcessor",0,sd,"sentryIntegration",0,sf],91573);let sx=/[\x00-\x1f\x7f-\x9f]/g;function sS(e,t,r){null!=r&&""!==r&&(e[t]=r)}function sF(e){return Array.isArray(e)?e[0]:e}function sE(e){if(Array.isArray(e)){for(let t of e){let e=sE(t);if(void 0!==e)return e}return}if("string"!=typeof e)return;let t=e.replace(sx,"").trim();if(t)return t.length>1e3?t.slice(0,1e3):t}function sP(e,t,r){return"number"==typeof e&&Number.isFinite(e)&&Math.abs(t-e)<=r}function sI(e,t){var r,i;let s,n,a=function(e,t){let r;if(!e)return{};let i=sE(e["x-posthog-session-id"]),s=sE(e["x-posthog-distinct-id"]),{sessionId:n,distinctId:a}=void 0===i&&void 0===s&&t?function(e,t,r=Date.now(),i=18e5,s=!1){try{let n;if("string"!=typeof e)return{};let a=sg(e.split(";").reverse().join(";")),o=a.get(sm(t))?.value,l=a.get("__ph_opt_in_out_"+t)?.value??"";if(!o||d(I,l)||s&&!d(P,l))return{};let u=JSON.parse(o);if(!u||"object"!=typeof u)return{};let c="identified"===u.$user_state?sE(u.distinct_id):void 0,h=u.$sesid;if(Array.isArray(h)&&(2===h.length||3===h.length)){let[e,t,s=e]=h;sP(e,r,i)&&sP(s,r,864e5)&&(n=sE(t))}return{...void 0!==n?{sessionId:n}:{},...void 0!==c?{distinctId:c}:{}}}catch{return{}}}(e.cookie,t.apiKey,Date.now(),"number"==typeof(r=t.sessionIdleTimeoutSeconds)&&Number.isFinite(r)&&0!==r?1e3*Math.min(Math.max(r,60),36e3):18e5,!0===t.optOutCapturingByDefault):{sessionId:i,distinctId:s};return{...void 0!==n?{sessionId:n}:{},...void 0!==a?{distinctId:a}:{}}}(t.headers,!0===(s=e.options.readPostHogCookie)?{apiKey:e.apiKey}:s&&"object"==typeof s?{apiKey:e.apiKey,sessionIdleTimeoutSeconds:s.sessionIdleTimeoutSeconds,optOutCapturingByDefault:s.optOutCapturingByDefault}:null),o=e.getContext(),l=o?.sessionId??a.sessionId,u=o?.distinctId??a.distinctId,c={},h=!0===e.options.disable_capture_url_hashes;return sS(c,"$current_url",(r=t.originalUrl||t.url,h?e$(r):r)),sS(c,"$request_method",t.method),sS(c,"$request_path",(i=t.path,n=function(e){if(!e)return e;let t=e.indexOf("?"),r=e.indexOf("#");return -1===t||-1!==r&&r<t?e:`${e.slice(0,t)}${-1===r?"":e.slice(r)}`}(i),h?e$(n):n)),sS(c,"$user_agent",sF(t.headers["user-agent"])),sS(c,"$ip",function(e){let t=sF(e.headers["x-forwarded-for"]);if(t){let e=t.split(",")[0].trim();if(e)return e}return e.socket?.remoteAddress}(t)),{...void 0!==l?{sessionId:l}:{},...void 0!==u?{distinctId:u}:{},properties:c}}function sA(e,t){var r;t.use((r=e,(e,t,i)=>{r.withContext(sI(r,e),()=>{ib(r,!0),i()})}))}function sk(e,t){var r;t.use((r=e,(e,t,i,s)=>{if(iu.isPreviouslyCapturedError(e))return void s(e);let n=sI(r,t),a=Error("Synthetic exception"),o={...void 0!==n.sessionId?{$session_id:n.sessionId}:{},...n.properties||{}};r.addPendingPromise(Promise.all([iu.buildEventMessage(r.getErrorPropertiesBuilder(),e,{mechanism:{type:"middleware",handled:!1},syntheticException:a},n.distinctId,o,r.getContext()),i.headersSent||i.destroyed?Promise.resolve(i.headersSent?i.statusCode:void 0):new Promise(e=>{let t=t=>{clearTimeout(s),i.removeListener("finish",r),i.removeListener("close",r),e(t)},r=()=>t(i.headersSent?i.statusCode:void 0),s=setTimeout(()=>t(void 0),1e3);s.unref(),i.once("finish",r),i.once("close",r)})]).then(([e,t])=>(void 0!==t&&(e.properties={...e.properties,$response_status_code:t}),r._capturePreparedEvent(e,!1)))),s(e)}))}e.s(["setupExpressErrorHandler",0,sk,"setupExpressRequestContext",0,sA],93546),e.i(91573),e.i(93546),e.i(58325),e.s(["EmailError",0,iR,"FeatureFlagError",0,h,"FeatureFlagEvaluations",0,t7,"PostHogSentryIntegration",0,sp,"cookieStateToProperties",0,sv,"cookieStoreFromHeader",0,sg,"createEventProcessor",0,sd,"enrichCurrentSpan",0,iw,"getPostHogCookieName",0,sm,"parsePostHogCookie",0,sb,"readPostHogCookie",0,s_,"sentryIntegration",0,sf,"serializePostHogCookie",0,sy,"setupExpressErrorHandler",0,sk,"setupExpressRequestContext",0,sA,"uuidv7",0,eK],57564),e.i(57564),e.s(["EmailError",0,iR,"FeatureFlagError",0,h,"FeatureFlagEvaluations",0,t7,"PostHog",0,class extends i3{getLibraryId(){return"posthog-node"}compressPayload(e){return su(e,this.isDebug)}initializeContext(){return new sn}initializeSpanContextManager(){return new sa}hostResourceAttributes(){return function(){var e,t;let r,i,s;try{r=(0,sc.platform)(),i=(0,sc.release)()}catch{}return e=r,t=i,{...(s=function(e){if(e)return Object.prototype.hasOwnProperty.call(tS,e)?tS[e]:e}(e))?{"os.name":s}:{},...t?{"os.version":t}:{}}}()}createErrorPropertiesBuilder(){let e;return new i5.ErrorPropertiesBuilder([new i4.EventCoercer,new i6.ErrorCoercer,new i8.ObjectCoercer,new i9.StringCoercer,new i7.PrimitiveCoercer],se.createStackParser("node:javascript",st.nodeStackLineParser),[(e=function(e=process.argv[1]?(0,l.dirname)(process.argv[1]):process.cwd(),t="\\"===l.sep){let r=t?u(e):e;return e=>{if(!e)return;let i=t?u(e):e,{dir:s,base:n,ext:a}=l.posix.parse(i);(".js"===a||".mjs"===a||".cjs"===a)&&(n=n.slice(0,-1*a.length));let o=decodeURIComponent(n);s||(s=".");let c=s.lastIndexOf("/node_modules");if(c>-1)return`${s.slice(c+14).replace(/\//g,".")}:${o}`;if(s.startsWith(r)){let e=s.slice(r.length+1).replace(/\//g,".");return e?`${e}:${o}`:o}return o}}(),async t=>{for(let r of t)r.module=e(r.filename);return t}),e=>eg(e,void 0,this._logger),function(e=process.cwd()){l.sep;let t=e=>e,r=t(e);return async e=>{for(let i of e)!(!i.filename||i.filename.startsWith("node:")||i.filename.startsWith("data:"))&&(0,l.isAbsolute)(i.filename)&&(i.filename=t((0,l.relative)(r,t(i.filename))));return e}}()])}},"PostHogSentryIntegration",0,sp,"cookieStateToProperties",0,sv,"cookieStoreFromHeader",0,sg,"createEventProcessor",0,sd,"enrichCurrentSpan",0,iw,"getPostHogCookieName",0,sm,"parsePostHogCookie",0,sb,"readPostHogCookie",0,s_,"sentryIntegration",0,sf,"serializePostHogCookie",0,sy,"setupExpressErrorHandler",0,sk,"setupExpressRequestContext",0,sA,"uuidv7",0,eK],28864)}];
|
|
3
2
|
|
|
4
3
|
//# sourceMappingURL=node_modules_posthog-node_dist_entrypoints_index_node_mjs_09z9-p77cu37y._.js.map
|