failproofai 1.0.13 → 1.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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]__05-glpesefmmi._.js +3 -0
- 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]__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/_0ge1hz9485xpp._.js +3 -0
- 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/_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_0e3yg5gbcfsai.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/05g1pu2r8o5q3.js +1 -0
- package/.next/standalone/.next/static/chunks/{0mm-e5t9denbu.js → 098vx6twrn-vk.js} +1 -1
- package/.next/standalone/.next/static/chunks/0oxlfb02aqo3e.js +1 -0
- package/.next/standalone/.next/static/chunks/0p14j2e6dnj1x.js +1 -0
- 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/12ys9uaq6i1h2.js +6 -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/1osrmi14e2jub.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/2o8j51ujh1ox4.js +1 -0
- package/.next/standalone/.next/static/chunks/2zwsbp8xyfv__.js +1 -0
- package/.next/standalone/.next/static/chunks/34rjkinfk6d4p.js +31 -0
- package/.next/standalone/.next/static/chunks/38lnk75xvqiug.js +1 -0
- package/.next/standalone/.next/static/chunks/{1-0se0uwja_ny.js → 3d6_vjbvr0c2n.js} +1 -1
- 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/41ujrab732qi3.css +2 -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/assets/logos/failproof-dark.png +0 -0
- package/.next/standalone/assets/logos/failproof-light.png +0 -0
- package/.next/standalone/fp-cloud-cli/CHANGELOG.md +34 -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-http/node.js +7 -2
- 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 +12 -12
- 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 +319 -317
- package/.next/standalone/sdk/typescript/integration/fixtures/nextjs/package.json +3 -3
- package/.next/standalone/server.js +1 -1
- package/README.md +174 -83
- package/dist/cli.mjs +23 -13
- package/dist/worker.mjs +1 -1
- package/hermes-plugin/plugin.yaml +1 -1
- package/openclaw-plugin/daemon-client.js +95 -26
- package/openclaw-plugin/hooks.js +4 -1
- package/package.json +12 -12
- 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/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/40g_e46c1-j4k.js +0 -6
- 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 → -AugwIGiiIYcahO4J7mdM}/_buildManifest.js +0 -0
- /package/.next/standalone/.next/static/{4MgI0mZP1iVhhocpUivMm → -AugwIGiiIYcahO4J7mdM}/_clientMiddlewareManifest.js +0 -0
- /package/.next/standalone/.next/static/{4MgI0mZP1iVhhocpUivMm → -AugwIGiiIYcahO4J7mdM}/_ssgManifest.js +0 -0
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
module.exports=[74493,a=>{"use strict";let b,c,d,e,f,g,h;var i,j=a.i(14747);function k(a){return a.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var l=((i={}).AnonymousId="anonymous_id",i.DistinctId="distinct_id",i.Props="props",i.EnablePersonProcessing="enable_person_processing",i.PersonMode="person_mode",i.FeatureFlagDetails="feature_flag_details",i.FeatureFlags="feature_flags",i.FeatureFlagPayloads="feature_flag_payloads",i.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",i.BootstrapFeatureFlags="bootstrap_feature_flags",i.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",i.OverrideFeatureFlags="override_feature_flags",i.Queue="queue",i.AiQueue="ai_queue",i.AiCaptureQueue="ai_capture_queue",i.LogsQueue="logs_queue",i.OptedOut="opted_out",i.SessionId="session_id",i.SessionStartTimestamp="session_start_timestamp",i.SessionLastTimestamp="session_timestamp",i.PersonProperties="person_properties",i.GroupProperties="group_properties",i.InstalledAppBuild="installed_app_build",i.InstalledAppVersion="installed_app_version",i.SessionReplay="session_replay",i.PushRegistered="push_registered",i.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",i.SurveyLastSeenDate="survey_last_seen_date",i.SurveysInProgress="surveys_in_progress",i.SurveysSeen="surveys_seen",i.Surveys="surveys",i.RemoteConfig="remote_config",i.FlagsEndpointWasHit="flags_endpoint_was_hit",i.DeviceId="device_id",i);let m={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",LOCAL_EVALUATION_INCONCLUSIVE:"local_evaluation_inconclusive",QUOTA_LIMITED:"quota_limited",TIMEOUT:"timeout",CONNECTION_ERROR:"connection_error",UNKNOWN_ERROR:"unknown_error",apiError:a=>`api_error_${a}`};function n(a){let b=[];return JSON.stringify(a,function(a,c){if("bigint"==typeof c)return c.toString();if("function"!=typeof c&&"symbol"!=typeof c){if(c instanceof Error)return{name:c.name,message:c.message,stack:c.stack};if(c&&"object"==typeof c){for(;b.length>0&&b[b.length-1]!==this;)b.pop();if(b.includes(c))return"[Circular]";b.push(c)}return c}})??"null"}let o=Array.isArray,p=Object.prototype;p.hasOwnProperty;let q=p.toString,r=o||function(a){return"[object Array]"===q.call(a)},s=a=>a===Object(a)&&!r(a),t=a=>void 0===a,u=a=>"[object String]"==q.call(a),v=a=>u(a)&&0===a.trim().length,w=a=>null===a,x=a=>t(a)||w(a),y=a=>"[object Number]"==q.call(a)&&a==a;function z(a){return null===a||"object"!=typeof a}function A(a,b){return Object.prototype.toString.call(a)===`[object ${b}]`}function B(a){switch(Object.prototype.toString.call(a)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return D(a,Error)}}function C(a){return"u">typeof Event&&D(a,Event)}function D(a,b){try{return a instanceof b}catch{return!1}}let E="Android",F="BlackBerry",G="Nintendo",H="PlayStation",I="Xbox",J="Windows",K="(\\d+(\\.\\d+)?)";RegExp("Version/"+K),RegExp("(Claude|Codex|ChatGPT)\\/"+K),RegExp(I,"i"),RegExp(H+" \\w+","i"),RegExp(G+" \\w+","i"),RegExp(F+"|PlayBook|BB10","i");RegExp("rv:"+K),RegExp("Edge?\\/"+K),RegExp("(Chrome|CrMo)\\/"+K),RegExp("CriOS\\/"+K),RegExp("(UCBrowser|UCWEB)\\/"+K),RegExp("(Opera|OPR)\\/"+K),RegExp("Firefox\\/"+K),RegExp("FxiOS\\/"+K),RegExp("Konqueror[:/]?"+K,"i"),RegExp(F+" "+K),RegExp("android\\s"+K,"i"),RegExp("SamsungBrowser\\/"+K),RegExp("OculusBrowser\\/"+K),RegExp("Vivaldi\\/"+K),RegExp("YaBrowser\\/"+K),RegExp("Whale\\/"+K),RegExp("Brave\\/"+K),RegExp("(DuckDuckGo|Ddg)\\/"+K),RegExp("PaleMoon\\/"+K),RegExp("Waterfox\\/"+K),RegExp("GSA\\/"+K),RegExp("(rv:|MSIE )"+K),RegExp("rv:"+K),RegExp(I+"; "+I+" (.*?)[);]","i"),RegExp(G,"i"),RegExp(H,"i"),RegExp(J,"i"),RegExp("("+E+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+E+")","i");let L=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function M(a,b){return"string"==typeof a&&L.test(a)?a:b()}function N(a,b){let c=Error(b);try{Object.defineProperty(c,"name",{value:a,writable:!0,enumerable:!0,configurable:!0})}catch{}return c}function O(a){return a?a.split("#")[0]:a}async function P(a,b){let c=null;for(let d=0;d<b.retryCount+1;d++){d>0&&await new Promise(a=>setTimeout(a,b.retryDelay));try{return await a()}catch(a){if(c=a,!b.retryCheck(a))throw a}}throw c}function Q(){return new Date().toISOString()}function R(a,b){let c=setTimeout(a,b);return c?.unref&&c?.unref(),c}async function S(a,b,c){let d;try{return await Promise.race([a,new Promise((a,e)=>{d=R(()=>{try{c?.(),a()}catch(a){e(a)}},b)})])}finally{clearTimeout(d)}}function T(a){return Promise.all(a.map(a=>(a??Promise.resolve()).then(a=>({status:"fulfilled",value:a}),a=>({status:"rejected",reason:a}))))}function U(a,b,c){return a&&c?b.length===Object.keys(c).length&&b.every(b=>a[b]===c[b]):a===c}class V{constructor(a,b,c=[]){this.coercers=a,this.stackParser=b,this.modifiers=c}buildFromUnknown(a,b={}){let c=b&&b.mechanism||{handled:!0,type:"generic"},d=this.buildCoercingContext(c,b,0).apply(a),e=this.buildParsingContext(b),f=this.parseStacktrace(d,e);return{$exception_list:this.convertToExceptionList(f,c),$exception_level:"error"}}async modifyFrames(a){for(let b of a)b.stacktrace&&b.stacktrace.frames&&r(b.stacktrace.frames)&&(b.stacktrace.frames=await this.applyModifiers(b.stacktrace.frames));return a}coerceFallback(a){return{type:"Error",value:"Unknown error",stack:a.syntheticException?.stack,synthetic:!0}}parseStacktrace(a,b){let c,d;if(null!=a.cause&&(c=this.parseStacktrace(a.cause,b)),""!=a.stack&&null!=a.stack)try{d=this.applyChunkIds(this.stackParser(a.stack,a.synthetic?b.skipFirstLines:0),b.chunkIdMap)}catch{}return{...a,cause:c,stack:d,errors:a.errors?.map(a=>this.parseStacktrace(a,b))}}applyChunkIds(a,b){return a.map(a=>(a.filename&&b&&(a.chunk_id=b[a.filename]),a))}applyCoercers(a,b){for(let c of this.coercers)if(c.match(a))return c.coerce(a,b);return this.coerceFallback(b)}async applyModifiers(a){let b=a;for(let a of this.modifiers)b=await a(b);return b}convertToExceptionList(a,b){let c=[],d=(a,e,f)=>{let g=c.length,h=void 0===e?{type:"string"==typeof b.type&&b.type.length>0?b.type:"generic",..."boolean"==typeof b.handled?{handled:b.handled}:void 0===b.handled?{handled:!0}:{},synthetic:"boolean"==typeof b.synthetic?b.synthetic:a.synthetic,exception_id:g}:{type:"chained",source:f,synthetic:a.synthetic,exception_id:g,parent_id:e},i={type:a.type,value:a.value,mechanism:h};for(let b of(a.stack&&(i.stacktrace={type:"raw",frames:a.stack}),c.push(i),a.cause&&d(a.cause,g,"cause"),a.errors??[]))d(b,g,"member")};return d(a),c}buildParsingContext(a){return{chunkIdMap:function(a){let f=globalThis._posthogChunkIds,g=globalThis._debugIds;if(!f&&!g)return;let h=f?Object.keys(f):[],i=g?Object.keys(g):[];if(e&&U(f,h,c)&&U(g,i,d))return e;c=f?{...f}:void 0,d=g?{...g}:void 0,e={},b??={};let j=(c,d)=>{for(let f of c){let c=d[f];if(!c)continue;let g=b?.[f];if(g){e[g]=c;continue}let h=a(f);for(let a=h.length-1;a>=0;a--){let d=h[a]?.filename;if(d){e[d]=c,b[f]=d;break}}}};return g&&j(i,g),f&&j(h,f),e}(this.stackParser),skipFirstLines:a.skipFirstLines??1}}getAggregateErrors(a){try{if(B(a)){let b=Object.getPrototypeOf(a);for(let c=0;b&&c<100;c++){let c=Object.getOwnPropertyDescriptor(b,"constructor")?.value;if("function"==typeof c&&"AggregateError"===c.name){let b=a.errors;return r(b)?b:void 0}b=Object.getPrototypeOf(b)}}}catch{}}buildCoercingContext(a,b,c=0){let d=0,e=0,f=!1,g=new Set,h=[],i={},j=(a,b,c=0)=>{let j,l,m=k(b,c),n=m.apply;if(m.apply=b=>{h.push(a);try{return n(b)}finally{h.pop()}},c>4||c>0&&-1!==h.indexOf(a))return this.coerceFallback(m);let o="object"==typeof a&&null!==a||"function"==typeof a;if(0===c&&d>=50||o&&g.has(a))return;o&&g.add(a),0===c&&d++;let p=this.getAggregateErrors(a);f||=!!p;try{if(!(j=this.applyCoercers(a,m)))throw i}catch(a){if(a===i){0===c&&d--;return}if(!f)throw a;j=this.coerceFallback(m)}if(!p||d>=50)return j;try{l=p.length}catch{return j}if(!Number.isInteger(l)||l<0||l>0xffffffff)return j;let q=[];for(let a=0;d<50&&e<1e3&&a<l;a++){let c;e++;try{c=m.next(p[a])}catch{d++,c=this.coerceFallback(k(b+1))}c&&q.push(c)}return{...j,errors:q}},k=(c,d=0)=>({...b,syntheticException:0==c?b.syntheticException:void 0,mechanism:0==c?a:{},apply:a=>{let b=j(a,c,d+1);if(!b)throw i;return b},next:a=>j(a,c+1)}),l=k(c);return{...l,apply:a=>j(a,c)??this.coerceFallback(l)}}}a.s(["ErrorPropertiesBuilder",0,V],39564);let W=/^([a-z][a-z0-9.+-]+):/i,X=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function Y(a,b,c,d,e){let f={platform:a,filename:b,function:"<anonymous>"===c?"?":c,in_app:function(a){if(!a||"<anonymous>"===a)return!1;let b=W.exec(a);return!b||X.includes(b[1].toLowerCase())}(b)};return t(d)||(f.lineno=d),t(e)||(f.colno=e),f}let Z=(a,b)=>{let c=-1!==a.indexOf("safari-extension"),d=-1!==a.indexOf("safari-web-extension");return c||d?[-1!==a.indexOf("@")?a.split("@")[0]:"?",c?`safari-extension:${b}`:`safari-web-extension:${b}`]:[a,b]},$=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,_=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,aa=/\((\S*)(?::(\d+))(?::(\d+))\)/,ab=(a,b)=>{let c=$.exec(a);if(c){let[,a,d,e]=c;return Y(b,a,"?",+d,+e)}let d=_.exec(a);if(d){if(d[2]&&0===d[2].indexOf("eval")){let a=aa.exec(d[2]);a&&(d[2]=a[1],d[3]=a[2],d[4]=a[3])}let[a,c]=Z(d[1]||"?",d[2]);return Y(b,c,a,d[3]?+d[3]:void 0,d[4]?+d[4]:void 0)}},ac=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ad=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ae=(a,b)=>{let c=ac.exec(a);if(c){if(c[3]&&c[3].indexOf(" > eval")>-1){let a=ad.exec(c[3]);a&&(c[1]=c[1]||"eval",c[3]=a[1],c[4]=a[2],c[5]="")}let a=c[3],d=c[1]||"?";return[d,a]=Z(d,a),Y(b,a,d,c[4]?+c[4]:void 0,c[5]?+c[5]:void 0)}},af=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ag=(a,b)=>{let c=af.exec(a);return c?Y(b,c[2],c[1]||"?",+c[3],c[4]?+c[4]:void 0):void 0},ah=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,ai=(a,b)=>{let c=ah.exec(a);return c?Y(b,c[2],c[3]||"?",+c[1]):void 0},aj=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,ak=(a,b)=>{let c=aj.exec(a);return c?Y(b,c[5],c[3]||c[4]||"?",+c[1],+c[2]):void 0},al=/^\s*[-]{4,}$/,am=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,an=/^Promise\.(?:all|any)$/,ao=/^index \d+$/,ap=(a,b)=>{let c=a.match(am);if(c){let a,d,e,f,g;if(c[1]){let b=(e=c[1]).lastIndexOf(".");if("."===e[b-1]&&b--,b>0){a=e.slice(0,b),d=e.slice(b+1);let c=a.indexOf(".Module");c>0&&(e=e.slice(c+1),a=a.slice(0,c))}f=void 0}d&&(f=a,g=d),"<anonymous>"===d&&(g=void 0,e=void 0),void 0===e&&(g=g||"?",e=f?`${f}.${g}`:g);let h=c[2]?.startsWith("file://")?c[2].slice(7):c[2],i="native"===c[5];return h?.match(/\/[A-Z]:/)&&(h=h.slice(1)),h||!c[5]||i||(h=c[5]),an.test(e)&&ao.test(h||"")&&(h="node:internal/promise"),{filename:h?decodeURI(h):void 0,module:void 0,function:e,lineno:aq(c[3]),colno:aq(c[4]),in_app:function(a,b=!1){return!(b||a&&!a.startsWith("/")&&!a.match(/^[A-Z]:/)&&!a.startsWith(".")&&!a.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==a&&!a.includes("node_modules/")}(h||"",i),platform:b}}if(a.match(al))return{filename:a,platform:b}};function aq(a){return parseInt(a||"",10)||void 0}let ar=/\(error: (.*)\)/;function as(a,b){return a.filename===b.filename&&a.function===b.function&&a.module===b.module&&a.lineno===b.lineno&&a.colno===b.colno}function at(a,b){let c=b.start;for(;c>0&&as(a[c-1],a[c-1+b.length]);)c--;return b.start-c}function au(a,b){let c=b.start+b.length,d=c;for(;d<a.length&&as(a[d],a[d-b.length]);)d++;return d-c}function av(a){if(!a.length)return[];let b=Array.from(a);return b.reverse(),b.slice(0,50).map(a=>{var c;return{...a,filename:a.filename||((c=b)[c.length-1]||{}).filename,function:a.function||"?"}})}function aw(){return ax("web:javascript",ab,ae)}function ax(a,...b){return(c,d=0)=>{let e=[],f=c.split("\n"),g=Math.min(f.length,d+1e3),h=[];for(let c=d;c<g;c++){let d=f[c];if(d.length>1024)continue;let g=ar.test(d)?d.replace(ar,"$1"):d;if(!g.match(/\S*Error: /)){for(let c of b){let b=c(g,a);if(b){e.push(b);let a=function(a){for(let b=1;b<=10;b++){let c=a.length-2*b;if(c<0)break;let d=!0;for(let e=0;e<b;e++)if(!as(a[c+e],a[c+b+e])){d=!1;break}if(d){for(let d=0;d<b;d++)a[c+d]=a[c+b+d];return a.length=c+b,{start:c,length:b}}}}(e);if(a){for(let b=h.length-1;b>=0;b--){let c=h[b];if(c.start+c.length<=a.start)break;h.pop()}h.push(a)}break}}if(function(a,b){let c=b[0],d=a.length-(c?at(a,c):0);for(let c of b)d-=au(a,c);return d}(e,h)>=50)break}}let i=[...h].sort((a,b)=>b.start-a.start),j=i[i.length-1];if(j){let a=at(e,j);for(let b of(e.splice(j.start-a,a),i))b.start-=a}for(let a of i)!function(a,b){let c=b.start+b.length,d=au(a,b);d&&a.splice(c+d===a.length?c:b.start,d)}(e,a);return h.some(a=>0===a.start&&e.length===a.length)&&function(a){let b=a.map(a=>`${a.function}|${a.filename}|${a.lineno}|${a.colno}|${a.module}`),c=0;for(let a=1;a<b.length;a++)(function(a,b,c){for(let d=0;d<a.length;d++){let e=a[(b+d)%a.length],f=a[(c+d)%a.length];if(e!==f)return e<f}return!1})(b,a,c)&&(c=a);a.push(...a.splice(0,c))}(e),av(e)}}class ay{match(a){return this.isDOMException(a)||this.isDOMError(a)}coerce(a,b){let c=u(a.stack);return{type:this.getType(a),value:this.getValue(a),stack:c?a.stack:void 0,cause:a.cause?b.next(a.cause):void 0,synthetic:!1}}getType(a){return this.isDOMError(a)?"DOMError":"DOMException"}getValue(a){let b=a.name||(this.isDOMError(a)?"DOMError":"DOMException");return a.message?`${b}: ${a.message}`:b}isDOMException(a){return A(a,"DOMException")}isDOMError(a){return A(a,"DOMError")}}a.s(["DOMExceptionCoercer",0,ay],51671);class az{match(a){return!!A(a,"ErrorEvent")&&(void 0!=a.error||this._hasUsableMessage(a))}coerce(a,b){if(void 0!=a.error)return b.apply(a.error);let c=b.apply(a.message);return{...c,stack:this._buildLocationStack(a)??c.stack,synthetic:!0}}_hasUsableMessage(a){return u(a.message)&&a.message.length>0}_buildLocationStack(a){let b=a.lineno??0,c=a.colno??0;if(u(a.filename)&&0!==a.filename.length&&0!==b)return`Error
|
|
2
|
-
at ${a.filename}:${b}:${c}`}}a.s(["ErrorEventCoercer",0,az],75368);let aA=["fatal","error","warning","log","info","debug"];function aB(a,b=40){let c=Object.keys(a);if(c.sort(),!c.length)return"[object has no keys]";for(let a=c.length;a>0;a--){let d=c.slice(0,a).join(", ");if(!(d.length>b)){if(a===c.length)return d;return d.length<=b?d:`${d.slice(0,b)}...`}}return""}class aC{match(a){return"object"==typeof a&&null!==a}coerce(a,b){let c=this.getErrorPropertyFromObject(a);return c?b.apply(c):{type:this.getType(a),value:this.getValue(a),stack:this.getStack(a)??b.syntheticException?.stack,level:this.isSeverityLevel(a.level)?a.level:"error",synthetic:!0}}getType(a){if(C(a))return a.constructor.name;let b="name"in a?a.name:void 0;return u(b)&&!v(b)?b:"Error"}getValue(a){if("name"in a&&"string"==typeof a.name){let b=`'${a.name}' captured as exception`;return"message"in a&&"string"==typeof a.message&&(b+=` with message: '${a.message}'`),b}if("message"in a&&"string"==typeof a.message)return a.message;let b=this.getObjectClassName(a),c=aB(a);return`${b&&"Object"!==b?`'${b}'`:"Object"} captured as exception with keys: ${c}`}isSeverityLevel(a){return u(a)&&!v(a)&&aA.indexOf(a)>=0}getStack(a){try{if(u(a.stacktrace)&&a.stacktrace.length>0)return a.stacktrace;return u(a.stack)&&a.stack.length>0?a.stack:void 0}catch{return}}getErrorPropertyFromObject(a){for(let b in a)if(Object.prototype.hasOwnProperty.call(a,b)){let c=a[b];if(B(c))return c}}getObjectClassName(a){try{let b=Object.getPrototypeOf(a);return b?b.constructor.name:void 0}catch(a){return}}}a.s(["ObjectCoercer",0,aC],93874);class aD{match(a){return C(a)}coerce(a,b){let c=a.constructor.name;return{type:c,value:`${c} captured as exception with keys: ${aB(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["EventCoercer",0,aD],46980);class aE{match(a){return z(a)}coerce(a,b){return{type:"Error",value:`Primitive value captured as exception: ${String(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["PrimitiveCoercer",0,aE],28150);class aF{match(a){return A(a,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(a)}isCustomEventWrappingRejection(a){if(!C(a))return!1;try{let b=a.detail;return null!=b&&"object"==typeof b&&"reason"in b}catch{return!1}}coerce(a,b){let c=this.getUnhandledRejectionReason(a);return z(c)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(c)}`,stack:b.syntheticException?.stack,synthetic:!0}:b.apply(c)}getUnhandledRejectionReason(a){try{if("reason"in a)return a.reason;if("detail"in a&&null!=a.detail&&"object"==typeof a.detail&&"reason"in a.detail)return a.detail.reason}catch{}return a}}a.s(["PromiseRejectionEventCoercer",0,aF],98140);let aG={MESSAGE:"$message",TIMESTAMP:"$timestamp"},aH=new Set([aG.MESSAGE,aG.TIMESTAMP]),aI={enabled:!0,max_bytes:32768};function aJ(a){return a?{enabled:a.enabled??aI.enabled,max_bytes:function(a,b){if(!y(a)||1/0===a||-1/0===a)return b;let c=Math.floor(a);return c<0?b:c}(a.max_bytes,aI.max_bytes)}:{...aI}}function aK(a){if(!a)return{sanitizedProperties:{},droppedKeys:[]};let b=[];return{sanitizedProperties:Object.keys(a).reduce((c,d)=>(aH.has(d)?b.push(d):c[d]=a[d],c),{}),droppedKeys:b}}class aL{constructor(a){this._entries=[],this._totalBytes=0,this._config=aJ(a)}setConfig(a){this._config=aJ(a),this._trimToMaxBytes()}add(a){let b=function(a){let b;try{b=n(a)}catch{return}try{let a=JSON.parse(b);if(!s(a))return;let c=a[aG.MESSAGE],d=a[aG.TIMESTAMP];if(!u(c)||0===c.trim().length||!u(d)&&!y(d))return;return{step:a,json:b}}catch{return}}(a);if(!b)return;let c=aM(b.json);c>this._config.max_bytes||(this._entries.push({step:b.step,bytes:c}),this._totalBytes+=c,this._trimToMaxBytes())}getAttachable(){return this._entries.map(a=>a.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 a=this._entries.shift();a&&(this._totalBytes-=a.bytes)}}}function aM(a){if("u">typeof TextEncoder)return new TextEncoder().encode(a).length;let b=encodeURIComponent(a),c=0;for(let a=0;a<b.length;a++)"%"===b[a]?(c+=1,a+=2):c+=1;return c}a.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,aI,"EXCEPTION_STEP_INTERNAL_FIELDS",0,aG,"ExceptionStepsBuffer",0,aL,"getUtf8ByteLength",0,aM,"resolveExceptionStepsConfig",0,aJ,"stripReservedExceptionStepFields",0,aK],97383),a.i(39564),a.s(["chromeStackLineParser",0,ab,"createDefaultStackParser",0,aw,"createStackParser",0,ax,"geckoStackLineParser",0,ae,"nodeStackLineParser",0,ap,"opera10StackLineParser",0,ai,"opera11StackLineParser",0,ak,"reverseAndStripFrames",0,av,"winjsStackLineParser",0,ag],64583),a.i(64583),a.i(51671);class aN{match(a){return B(a)}coerce(a,b){let c=this.getStack(a),d=void 0===c?b.syntheticException?.stack:void 0;return{type:this.getType(a),value:this.getMessage(a,b),stack:c??d,cause:a.cause?b.next(a.cause):void 0,synthetic:!!d}}getType(a){return a.name||a.constructor.name}getMessage(a,b){let c=a.message;return c.error&&"string"==typeof c.error.message?String(c.error.message):String(c)}getStack(a){try{let b=a.stacktrace;if("string"==typeof b&&b.length>0)return b;let c=a.stack;return"string"==typeof c&&c.length>0?c:void 0}catch{return}}}a.s(["ErrorCoercer",0,aN],10692),a.i(10692),a.i(75368);let aO=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class aP{match(a){return"string"==typeof a}coerce(a,b){let[c,d]=this.getInfos(a);return{type:c??"Error",value:d??a,stack:b.syntheticException?.stack,synthetic:!0}}getInfos(a){let b="Error",c=a,d=a.match(aO);return d&&(b=d[1],c=d[2]),[b,c]}}a.s(["StringCoercer",0,aP],57802),a.i(57802),a.i(93874),a.i(46980),a.i(28150),a.i(98140),a.s(["DOMExceptionCoercer",0,ay,"ErrorCoercer",0,aN,"ErrorEventCoercer",0,az,"EventCoercer",0,aD,"ObjectCoercer",0,aC,"PrimitiveCoercer",0,aE,"PromiseRejectionEventCoercer",0,aF,"StringCoercer",0,aP],54253),a.i(54253);class aQ{constructor(a){this._maxSize=a,this._cache=new Map}get(a){let b=this._cache.get(a);if(void 0!==b)return this._cache.delete(a),this._cache.set(a,b),b}set(a,b){this._cache.set(a,b)}reduce(){for(;this._cache.size>=this._maxSize;){let a=this._cache.keys().next().value;a&&this._cache.delete(a)}}}function aR(){if("u">typeof process){let a=process.env.POSTHOG_RELEASE_ID?.trim();if(a)return a}let a=globalThis._posthogReleaseId;return"string"==typeof a&&a.length>0?a:void 0}a.s(["ReduceableCache",0,aQ],98966),a.i(98966),a.i(97383),a.s(["getInjectedReleaseId",0,aR],28861),a.i(28861),a.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,aI,"DOMExceptionCoercer",0,ay,"EXCEPTION_STEP_INTERNAL_FIELDS",0,aG,"ErrorCoercer",0,aN,"ErrorEventCoercer",0,az,"ErrorPropertiesBuilder",0,V,"EventCoercer",0,aD,"ExceptionStepsBuffer",0,aL,"ObjectCoercer",0,aC,"PrimitiveCoercer",0,aE,"PromiseRejectionEventCoercer",0,aF,"ReduceableCache",0,aQ,"StringCoercer",0,aP,"chromeStackLineParser",0,ab,"createDefaultStackParser",0,aw,"createStackParser",0,ax,"geckoStackLineParser",0,ae,"getInjectedReleaseId",0,aR,"getUtf8ByteLength",0,aM,"nodeStackLineParser",0,ap,"opera10StackLineParser",0,ai,"opera11StackLineParser",0,ak,"resolveExceptionStepsConfig",0,aJ,"reverseAndStripFrames",0,av,"stripReservedExceptionStepFields",0,aK,"winjsStackLineParser",0,ag],60485);var aS=a.i(60485);let aT="0123456789abcdef";class aU{constructor(a){this.bytes=a}static ofInner(a){if(16===a.length)return new aU(a);throw TypeError("not 128-bit length")}static fromFieldsV7(a,b,c,d){if(!Number.isInteger(a)||!Number.isInteger(b)||!Number.isInteger(c)||!Number.isInteger(d)||a<0||b<0||c<0||d<0||a>0xffffffffffff||b>4095||c>0x3fffffff||d>0xffffffff)throw RangeError("invalid field value");let e=new Uint8Array(16);return e[0]=a/0x10000000000,e[1]=a/0x100000000,e[2]=a/0x1000000,e[3]=a/65536,e[4]=a/256,e[5]=a,e[6]=112|b>>>8,e[7]=b,e[8]=128|c>>>24,e[9]=c>>>16,e[10]=c>>>8,e[11]=c,e[12]=d>>>24,e[13]=d>>>16,e[14]=d>>>8,e[15]=d,new aU(e)}static parse(a){let b;switch(a.length){case 32:b=/^[0-9a-f]{32}$/i.exec(a)?.[0];break;case 36:b=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(a)?.slice(1,6).join("");break;case 38:b=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(a)?.slice(1,6).join("");break;case 45:b=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(a)?.slice(1,6).join("")}if(b){let a=new Uint8Array(16);for(let c=0;c<16;c+=4){let d=parseInt(b.substring(2*c,2*c+8),16);a[c+0]=d>>>24,a[c+1]=d>>>16,a[c+2]=d>>>8,a[c+3]=d}return new aU(a)}throw SyntaxError("could not parse UUID string")}toString(){let a="";for(let b=0;b<this.bytes.length;b++)a+=aT.charAt(this.bytes[b]>>>4),a+=aT.charAt(15&this.bytes[b]),(3===b||5===b||7===b||9===b)&&(a+="-");return a}toHex(){let a="";for(let b=0;b<this.bytes.length;b++)a+=aT.charAt(this.bytes[b]>>>4),a+=aT.charAt(15&this.bytes[b]);return a}toJSON(){return this.toString()}getVariant(){let a=this.bytes[8]>>>4;if(a<0)throw Error("unreachable");if(a<=7)return this.bytes.every(a=>0===a)?"NIL":"VAR_0";if(a<=11)return"VAR_10";if(a<=13)return"VAR_110";if(a<=15)return this.bytes.every(a=>255===a)?"MAX":"VAR_RESERVED";throw Error("unreachable")}getVersion(){return"VAR_10"===this.getVariant()?this.bytes[6]>>>4:void 0}clone(){return new aU(this.bytes.slice(0))}equals(a){return 0===this.compareTo(a)}compareTo(a){for(let b=0;b<16;b++){let c=this.bytes[b]-a.bytes[b];if(0!==c)return Math.sign(c)}return 0}}class aV{constructor(a){this.timestamp=0,this.counter=0,this.random=a??aW()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(a,b){let c=this.generateOrAbortCore(a,b);return void 0===c&&(this.timestamp=0,c=this.generateOrAbortCore(a,b)),c}generateOrAbortCore(a,b){if(!Number.isInteger(a)||a<1||a>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(b<0||b>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(a>this.timestamp)this.timestamp=a,this.resetCounter();else{if(!(a+b>=this.timestamp))return;this.counter++,this.counter>0x3ffffffffff&&(this.timestamp++,this.resetCounter())}return aU.fromFieldsV7(this.timestamp,Math.trunc(this.counter/0x40000000),0x3fffffff&this.counter,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let a=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return a[6]=64|a[6]>>>4,a[8]=128|a[8]>>>2,aU.ofInner(a)}}let aW=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),aX=()=>aY().toString(),aY=()=>(f||(f=new aV)).generate();function aZ(a){let b={};if(a)for(let c of a.split(";")){let[a,...d]=c.trim().split("=");if(a){let c=d.join("=").trim();try{b[a.trim()]=decodeURIComponent(c)}catch{b[a.trim()]=c}}}return{get:a=>a in b?{value:b[a]}:void 0}}function a$(a){let b=a.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${b}_posthog`}function a_(a){let b=Date.now();return JSON.stringify({distinct_id:a,$device_id:a,$user_state:"anonymous",$sesid:[b,aX(),b]})}function a0(a,b){let c=a$(b),d=a.get(c);return d?a2(d.value):null}function a1(a){if(!a)return;let b={};return a.sessionId&&(b.$session_id=a.sessionId),a.deviceId&&(b.$device_id=a.deviceId),Object.keys(b).length>0?b:void 0}function a2(a){if(!a)return null;try{let b=JSON.parse(a);if(!b||"object"!=typeof b||!b.distinct_id)return null;let c=r(b.$sesid)?b.$sesid[1]:void 0;return{distinctId:String(b.distinct_id),isIdentified:"identified"===b.$user_state,sessionId:"string"==typeof c?c:void 0,deviceId:"string"==typeof b.$device_id?b.$device_id:void 0}}catch{return null}}let a3=a=>void 0===a?void 0:a.variant??a.enabled,a4=a=>{if("string"!=typeof a)return a;try{return JSON.parse(a)}catch{return a}},a5=["$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"],a6=(a,b=[])=>{let c={},d=b=>{void 0!==a[b]&&(c[b]=a[b])};return a5.forEach(d),b.forEach(d),c};class a7{constructor(){this.events={},this.events={}}on(a,b){return this.events[a]||(this.events[a]=[]),this.events[a].push(b),()=>{this.events[a]=this.events[a].filter(a=>a!==b)}}emit(a,b){for(let c of this.events[a]||[])c(b);for(let c of this.events["*"]||[])c(a,b)}}let a8=a=>{throw N("NativeGzipValidationError",`Native gzip produced invalid output: ${a}`)},a9=async(a,b)=>{a.size<18&&a8("too-short");let c=new Uint8Array(await a.slice(0,10).arrayBuffer());c.length>=2&&31===c[0]&&139===c[1]&&8===c[2]||a8("invalid-header");let d=new DataView(await a.slice(a.size-8).arrayBuffer());d.getUint32(0,!0)!==(a=>{let b=(()=>{if(g)return g;g=[];for(let a=0;a<256;a++){let b=a;for(let a=0;a<8;a++)b=1&b?0xedb88320^b>>>1:b>>>1;g[a]=b>>>0}return g})(),c=0xffffffff;for(let d=0;d<a.length;d++)c=b[(c^a[d])&255]^c>>>8;return(0xffffffff^c)>>>0})(b)&&a8("invalid-crc");let e=b.length>>>0;d.getUint32(4,!0)!==e&&a8("invalid-size")};async function ba(a,b=!0,c){try{let b=new TextEncoder().encode(a),c=new globalThis.CompressionStream("gzip"),d=c.writable.getWriter(),e=d.write(b).then(()=>d.close()).catch(async a=>{try{await d.abort(a)}catch{}throw a}),f=new Response(c.readable).blob(),[g]=await Promise.all([f,e]);return await a9(g,b),g}catch(a){if(c?.rethrow)throw a;return b&&console.error("Failed to gzip compress data",a),null}}class bb{add(a){let b=aX(),c=++this.nextId;return this.promiseByIds[b]={id:c,promise:a},a.catch(()=>{}).finally(()=>{delete this.promiseByIds[b]}),a}async join(){let a=Object.values(this.promiseByIds).map(a=>a.promise),b=a.length;for(;b>0;)await Promise.all(a),b=(a=Object.values(this.promiseByIds).map(a=>a.promise)).length}getPromises(a=[],b=this.nextId){let c=new Set(a);return Object.values(this.promiseByIds).filter(a=>a.id<=b&&!c.has(a.promise)).map(a=>a.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}let bc=(a,b,c)=>{function d(e,...f){b(()=>{(0,c[e])(a,...f)})}return{debug:(...a)=>{d("debug",...a)},info:(...a)=>{d("log",...a)},warn:(...a)=>{d("warn",...a)},error:(...a)=>{d("error",...a)},critical:(...b)=>{c.error(a,...b)},createLogger:d=>bc(`${a} ${d}`,b,c)}};class bd{record(a){if("too-large"===a.kind)return;if("retry-later"!==a.kind)return void this.reset();if(!a.retryAfterMs)return;let b=this.isOpen(),c=Date.now(),d=Math.min(a.retryAfterMs,3e5);if(!b){this._installedAt=c,this._until=c+d;return}this._until=Math.max(this._until,Math.min(c+d,this._installedAt+3e5))}remainingMs(){let a=Date.now();if(a<this._installedAt-5e3)return this.reset(),0;let b=Math.min(3e5,Math.max(0,this._until-a));return 0===b&&this.reset(),b}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}}class be extends Error{constructor(a,b,c,d){super("HTTP error while fetching PostHog: status="+a.status+", reqByteLength="+b),this.response=a,this.reqByteLength=b,this.responseBodyDeadline=c,this.abortController=d,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return function(a,b=Date.now()){if("string"!=typeof a||!a)return;let c=a.trim(),d=/^\d+\s*,/.test(c)?c.slice(0,c.indexOf(",")).trim():c;if(/^\d+$/.test(d)){let a=1e3*Math.min(Number(d),300);return a>0?a:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(d))return;let e=Date.parse(/^\w{3} \w{3} /.test(d)?d+" GMT":d)-b;if(Number.isFinite(e)&&!(e<=0))return Math.min(e,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 a=N("AbortError","Response body read timed out");this.cancelResponseBody(a),this.responseBodyTextPromise=Promise.reject(a)}else{let a,b=new Promise((a,b)=>{this.responseBodyTimer=R(()=>{this._bodyReadTimedOut=!0;let a=N("AbortError","Response body read timed out");b(a),this.cancelResponseBody(a)},this.responseBodyDeadline-Date.now())});try{a=Promise.resolve(this.response.text())}catch(b){a=Promise.reject(b)}this.responseBodyTextPromise=Promise.race([a,b]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(a=>JSON.parse(a))}cancelResponseBody(a){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(a),(async()=>{try{await this.response.body?.cancel()}catch{}})()}}class bf extends Error{constructor(a){super("Network error while fetching PostHog",a instanceof Error?{cause:a}:{}),this.error=a,this.name="PostHogFetchNetworkError"}}async function bg(a){if(a instanceof be){let b="";try{b=await a.text}catch{a.bodyReadTimedOut&&(b="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${a.message}, response body=${b}`,a)}else console.error("Error while flushing PostHog",a);return Promise.resolve()}function bh(a){return a instanceof bf}function bi(a){if(a instanceof be)return 502===a.status||504===a.status;if(!(a instanceof bf))return!1;let b=a.error;return"ECONNREFUSED"!==(b?.code??b?.cause?.code)}function bj(a){try{if("string"!=typeof a)return a instanceof Uint8Array?a.byteLength:a.size;if("u">typeof Buffer)return Buffer.byteLength(a,"utf8");return new TextEncoder().encode(a).length}catch{return 0}}function bk(a){return"object"==typeof a&&a instanceof be&&413===a.status}function bl(a){return a instanceof be?408===a.status||429===a.status||a.status>=500:bh(a)}function bm(a){return null!==a&&"object"==typeof a&&!Array.isArray(a)}let bn="default";class bo{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new V([new aN,new aC,new aP,new aE],aw())}getEvaluationRuntime(){}get apiKey(){return this.projectToken}constructor(a,b={}){var c;this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new bb,this._events=new a7,this._isInitialized=!1;let d="string"==typeof a?a.trim():"",e="string"==typeof b.host?b.host.trim():"",f=!d;this._logger=function(a,b=a=>a()){return bc(a,b,function(a=console){return{log:a.log.bind(a),warn:a.warn.bind(a),error:a.error.bind(a),debug:a.debug.bind(a)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),f&&this._logger.error("You must pass your PostHog project token. The client will be disabled."),this.projectToken=d,this.host=(c=e||"https://us.i.posthog.com",c?.replace(/\/+$/,"")),this.flushAt=b.flushAt?Math.max(b.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,b.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,b.maxQueueSize??1e3),this.flushInterval=b.flushInterval??1e4,this.preloadFeatureFlags=b.preloadFeatureFlags??!0,this.defaultOptIn=b.defaultOptIn??!0,this.disableSurveys=b.disableSurveys??!1,this._retryOptions={retryCount:b.fetchRetryCount??3,retryDelay:b.fetchRetryDelay??3e3,retryCheck:bl},this.requestTimeout=b.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=b.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=b.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=b.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=b.disableGeoip??!0,this.disabled=(b.disabled??!1)||f,this.historicalMigration=b?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=b?.evaluationContexts??b?.evaluationEnvironments,b?.evaluationEnvironments&&!b?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!("CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&"function"==typeof Response.prototype.blob)||(b?.disableCompression??!1)}logMsgIfDebug(a){this.isDebug&&a()}wrap(a){return this.disabled?void this._logger.warn("The client is disabled"):this._isInitialized?a():void this._initPromise.then(()=>a())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(l.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(l.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(l.OptedOut,!0)})}on(a,b){return this._events.on(a,b)}debug(a=!0){if(this.removeDebugCallback?.(),a){let a=this.on("*",(a,b)=>this._logger.info(a,b));this.removeDebugCallback=()=>{a(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(a){let b=a.properties||{},c=this.mergeCommonEventProperties(b);var d=c;for(let a of Object.keys(b))(a.startsWith("$feature/")||"$active_feature_flags"===a)&&(d[a]=b[a]);return"$feature_flag_called"===a.event&&!1===c.$feature_flag_has_experiment&&this.isMinimalFlagCalledEventsEnabled()&&(c=a6(c)),{distinct_id:a.distinct_id,event:a.event,properties:c}}mergeCommonEventProperties(a){return{...a,...this.getCommonEventProperties()}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(a){return this.promiseQueue.add(a)}identifyStateless(a,b,c){this.wrap(()=>{let d={...this.buildPayload({distinct_id:a,event:"$identify",properties:b})};this.enqueue("identify",d,c)})}async identifyStatelessImmediate(a,b,c){let d={...this.buildPayload({distinct_id:a,event:"$identify",properties:b})};await this.sendImmediate("identify",d,c)}captureStateless(a,b,c,d){this.wrap(()=>{let e=this.buildPayload({distinct_id:a,event:b,properties:c});this.enqueue("capture",e,d)})}async captureStatelessImmediate(a,b,c,d){let e=this.buildPayload({distinct_id:a,event:b,properties:c});await this.sendImmediate("capture",e,d)}aliasStateless(a,b,c,d){this.wrap(()=>{let e=this.buildPayload({event:"$create_alias",distinct_id:b,properties:{...c||{},distinct_id:b,alias:a}});this.enqueue("alias",e,d)})}async aliasStatelessImmediate(a,b,c,d){let e=this.buildPayload({event:"$create_alias",distinct_id:b,properties:{...c||{},distinct_id:b,alias:a}});await this.sendImmediate("alias",e,d)}groupIdentifyStateless(a,b,c,d,e,f){this.wrap(()=>{let g=this.buildPayload({distinct_id:e||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{},...f||{}}});this.enqueue("capture",g,d)})}async groupIdentifyStatelessImmediate(a,b,c,d,e,f){let g=this.buildPayload({distinct_id:e||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{},...f||{}}});await this.sendImmediate("capture",g,d)}async getRemoteConfig(){await this._initPromise;let a=this.host;"https://us.i.posthog.com"===a?a="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===a&&(a="https://eu-assets.i.posthog.com");let b=`${a}/array/${this.projectToken}/config`,c={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(b,c,{type:"required",consume:a=>a.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(a=>{this._logger.error("Remote config could not be loaded",a),this._events.emit("error",a)})}async getFlags(a,b={},c={},d={},e={},f=!1){await this._initPromise;let g=`${this.host}/flags/?v=2${f?"&config=true":""}`,h={token:this.projectToken,distinct_id:a,groups:b,person_properties:c,group_properties:d,...e};c.$device_id&&(h.$device_id=c.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(h.evaluation_contexts=this.evaluationContexts);let i=this.getEvaluationRuntime();i&&(h.evaluation_runtime=i);let j={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(h)};return this._logger.info("Flags URL",g),this.fetchWithRetry(g,j,{type:"required",consume:a=>a.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:bi},this.featureFlagsRequestTimeoutMs).then(a=>({success:!0,response:(a=>{if("flags"in a){let b,c=Object.fromEntries(Object.entries(a.flags??{}).map(([a,b])=>[a,a3(b)]).filter(([,a])=>void 0!==a)),d=Object.fromEntries(Object.keys(b=a.flags??{}).filter(a=>{let c=b[a];return c.enabled&&c.metadata&&void 0!==c.metadata.payload}).map(a=>{let c=b[a].metadata?.payload;return[a,c?a4(c):void 0]}));return{...a,featureFlags:c,featureFlagPayloads:d}}{let b=a.featureFlags??{},c=Object.fromEntries(Object.entries(a.featureFlagPayloads||{}).map(([a,b])=>[a,a4(b)])),d=Object.fromEntries(Object.entries(b).map(([a,b])=>{var d,e;return[a,{key:a,enabled:"string"==typeof(d=b)||d,variant:"string"==typeof d?d:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:(e=c[a])?JSON.stringify(e):void 0,description:void 0}}]}));return{...a,featureFlags:b,featureFlagPayloads:c,flags:d}}})(a)})).catch(a=>(this._events.emit("error",a),{success:!1,error:this.categorizeRequestError(a)}))}categorizeRequestError(a){if(a instanceof be)return{type:"api_error",statusCode:a.status};if(a instanceof bf){let b=a.error;return b instanceof Error&&("AbortError"===b.name||"TimeoutError"===b.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagDetailStateless(a,b,c,d,e,f);if(void 0===g)return{response:void 0,requestId:void 0};let h=a3(g.response);return void 0===h&&(h=!1),{response:h,requestId:g.requestId}}async getFeatureFlagDetailStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagDetailsStateless(b,c,d,e,f,[a]);if(void 0!==g)return{response:g.flags[a],requestId:g.requestId,evaluatedAt:g.evaluatedAt}}async getFeatureFlagPayloadStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagPayloadsStateless(b,c,d,e,f,[a]);if(!g)return;let h=g[a];return void 0===h?null:h}async getFeatureFlagPayloadsStateless(a,b={},c={},d={},e,f){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(a,b,c,d,e,f)).payloads}async getFeatureFlagsStateless(a,b={},c={},d={},e,f){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(a,b,c,d,e,f)}async getFeatureFlagsAndPayloadsStateless(a,b={},c={},d={},e,f){await this._initPromise;let g=await this.getFeatureFlagDetailsStateless(a,b,c,d,e,f);return g?{flags:g.featureFlags,payloads:g.featureFlagPayloads,requestId:g.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(a,b={},c={},d={},e,f){await this._initPromise;let g={geoip_disable:e??this.disableGeoip};f&&(g.flag_keys_to_evaluate=f);let h=await this.getFlags(a,b,c,d,g);if(!h.success)return;let i=h.response;return(i.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),i.quotaLimited?.includes("feature_flags"))?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:i?.requestId,quotaLimited:i.quotaLimited}):i}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let a=`${this.host}/api/surveys/?token=${this.projectToken}`,b={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},c=await this.fetchWithRetry(a,b,{type:"required",consume:a=>{if(200!==a.status||!a.json){let b=`Surveys API could not be loaded: ${a.status}`,c=Error(b);return this._logger.error(c),this._events.emit("error",Error(b)),Promise.resolve(void 0)}return a.json()}}).catch(a=>{this._logger.error("Surveys API could not be loaded",a),this._events.emit("error",a)}),d=c?.surveys;return d&&this._logger.info("Surveys fetched from API: ",JSON.stringify(d)),d??[]}get props(){return this._props||(this._props=this.getPersistedProperty(l.Props)),this._props||{}}set props(a){this._props=a}async register(a){this.wrap(()=>{this.props={...this.props,...a},this.setPersistedProperty(l.Props,this.props)})}async unregister(a){this.wrap(()=>{delete this.props[a],this.setPersistedProperty(l.Props,this.props)})}processBeforeEnqueue(a){return a}async flushStorage(){}getQueueRouteKey(a){return bn}persistedQueueKeyForRoute(a){return l.Queue}getActiveQueueRoutes(){return[bn]}getRouteQueue(a){return this.getPersistedProperty(this.persistedQueueKeyForRoute(a))||[]}enqueue(a,b,c,d){this.wrap(()=>{if(this.optedOut)return void this._events.emit(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let e=this.prepareMessage(b,c);if(null===(e=this.processBeforeEnqueue(e)))return;e=this.normalizeMessage(e);let f=this.persistedQueueKeyForRoute(d??this.getQueueRouteKey(e)),g=this.getPersistedProperty(f)||[];g.length>=this.maxQueueSize&&(g.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),g.push({message:e}),this.setPersistedProperty(f,g),this._events.emit(a,e),g.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=R(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(a,b,c,d){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let e=this.prepareMessage(b,c);if(null!==(e=this.processBeforeEnqueue(e))){e=this.normalizeMessage(e);try{await this.sendBatch([e],void 0,d??this.getQueueRouteKey(e))}catch(a){this._events.emit("error",a)}}}normalizeMessage(a){let{type:b,library:c,library_version:d,...e}=a,f=bm(e.properties)?e.properties:void 0;return void 0!==c&&f?.$lib===void 0&&(f={...f||{},$lib:c}),void 0!==d&&f?.$lib_version===void 0&&(f={...f||{},$lib_version:d}),f&&(e.properties=f),e.uuid=M(e.uuid,aX),e}normalizeTimestampForWire(a){let b=a instanceof Date?a:"string"==typeof a?new Date(a):null;if(!b||Number.isNaN(b.getTime()))return a;let c=b.toISOString(),d="string"==typeof a?a.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return d&&d.length>3?c.replace(/\.\d{3}Z$/,`.${d}Z`):c}prepareMessage(a,b){let c={...a,timestamp:b?.timestamp?b?.timestamp:Q(),uuid:M(b?.uuid,aX)};return(b?.disableGeoip??this.disableGeoip)&&(bm(c.properties)||(c.properties={}),c.properties.$geoip_disable=!0),c.distinctId&&(c.distinct_id=c.distinctId,delete c.distinctId),c}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async a=>{await bg(a)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(a,b=[]){let c=b.filter(a=>!!a),d=0;for(;;){let b=this.promiseQueue.getPromises([...c,...this.flushPromises],a);if(0===b.length)return;d>0&&this._logger.debug(`flush() re-checking ${b.length} pending promise(s) before flushing`),await Promise.all(b.map(a=>a.catch(()=>{}))),d++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(a){if(this.disabled)return Promise.resolve();if(!a&&this.pendingFlushPromise)return this.pendingFlushPromise;let b=this.flushPromise,c=this.promiseQueue.maxId,d=Promise.resolve().then(()=>{if(a)return this.waitForPendingPromises(c,[b,d])}).then(()=>T([b])).then(()=>(this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=d,this.flushPromise=d,this.flushPromises.add(d),this.addPendingPromise(d),T([d]).then(()=>{this.flushPromises.delete(d),this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this.flushPromise===d&&(this.flushPromise=null)}),d}getCustomHeaders(){let a=this.getCustomUserAgent(),b={};return a&&""!==a&&(b["User-Agent"]=a),b}compressPayload(a){return ba(a,this.isDebug)}getBatchEndpointPath(a){return"/batch/"}async sendBatch(a,b,c=bn){let d={api_key:this.projectToken,batch:a.map(a=>{if(!a)return a;let b=this.normalizeTimestampForWire(a.timestamp);return b===a.timestamp?a:{...a,timestamp:b}}),sent_at:Q()};this.historicalMigration&&(d.historical_migration=!0);let e=n(d),f=`${this.host}${this.getBatchEndpointPath(c)}`,g=this.disableCompression?null:await this.compressPayload(e),h={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==g&&{"Content-Encoding":"gzip"}},body:g||e};await this.fetchWithRetry(f,h,{type:"successful-write"},b)}async _flush(){let a;this.clearFlushTimer(),await this._initPromise;let b=this.getActiveQueueRoutes();if(!b.some(a=>this.getRouteQueue(a).length>0))return;let c=[];for(let d of b)try{await this._flushRoute(d,c)}catch(b){void 0===a&&(a=b)}if(void 0!==a)throw a;this._events.emit("flush",c)}async _flushRoute(a,b){let c=this.persistedQueueKeyForRoute(a),d=this.getPersistedProperty(c)||[];if(!d.length)return;let e=d.length,f=0;for(;d.length>0&&f<e;){let e=d.slice(0,this.maxBatchSize),g=e.map(a=>void 0===a.message?a.message:this.normalizeMessage(a.message)),h=async()=>{let a=this.getPersistedProperty(c)||[],b=[...e],f=a.filter(a=>{let c=a.message?.uuid,d=b.findIndex(b=>b===a||"string"==typeof c&&c.length>0&&b.message?.uuid===c);return -1===d||(b.splice(d,1),!1)});this.setPersistedProperty(c,f),d=f,this._dequeuedMessagesCount+=e.length,await this.flushStorage()},i={retryCheck:a=>!bk(a)&&bl(a)};try{await this.sendBatch(g,i,a)}catch(a){if(bk(a)&&g.length>1){this.maxBatchSize=Math.max(1,Math.floor(g.length/2)),this._logger.warn(`Received 413 when sending batch of size ${g.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw a instanceof bf||await h(),this._events.emit("error",a),a}await h(),b.push(...g),f+=g.length}}async _sendOtlpBatch({path:a,auth:b,payload:c}){let d;if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};try{d=JSON.stringify(c)}catch(b){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${a} batch; reporting it as too large`,b)),{kind:"too-large",measuredLocally:!0}}let e=bj(d);if(e>0xa00000)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${a} batch of ${e} bytes: the endpoint accepts at most 10485760`)),{kind:"too-large",measuredLocally:!0};let f="bearer"===b?`${this.host}/i/v1/${a}`:`${this.host}/i/v1/${a}?token=${encodeURIComponent(this.projectToken)}`,g=this.disableCompression?null:await this.compressPayload(d),h=g||d,i={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",..."bearer"===b&&{Authorization:`Bearer ${this.projectToken}`},...null!==g&&{"Content-Encoding":"gzip"}},body:h};try{return await this.fetchWithRetry(f,i,{type:"successful-write"},{retryCheck:a=>!bk(a)&&(!(a instanceof be)||void 0===a.retryAfterMs)&&bl(a)}),{kind:"ok"}}catch(a){if(bk(a))return{kind:"too-large"};if(bl(a)){let b=a instanceof be?a.retryAfterMs:void 0;return{kind:"retry-later",error:a,...void 0!==b&&{retryAfterMs:b}}}return{kind:"fatal",error:a}}}async _sendLogsBatch(a){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:a})}async _sendMetricsBatch(a){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:a})}async _sendTracesBatch(a){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:a})}async fetchWithRetry(a,b,c,d,e){let f=bj(b.body?b.body:""),g={...this._retryOptions,...d},h=0;return await P(async()=>{let d,g,i;h++;let j=new AbortController,k=e??this.requestTimeout,l=Date.now()+k,m=new Promise((a,b)=>{d=R(()=>{let a=N("AbortError",`Request timed out after ${k}ms`);b(a),j.abort(a)},k)}),n=!1,o=()=>i??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let d;try{d=this.fetch(a,{signal:j.signal,...b})}catch(a){throw new bf(a)}d.then(a=>{j.signal.aborted&&!n&&Promise.resolve(a.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([d,m]),n=!0}catch(a){throw new bf(a)}let e="no-cors"===b.mode,h="successful-write"===c.type?300:400;if(!e&&(g.status<200||g.status>=h))throw new be(g,f,l,j);if("successful-write"===c.type){try{await Promise.race([o(),m])}catch{}return}try{return await Promise.race([c.consume(g),m])}catch(a){if(j.signal.aborted)throw new bf(a);throw a}}finally{clearTimeout(d),j.signal.aborted&&g&&o()}},{...g,retryCheck:a=>{let b=g.retryCheck(a);return b&&h<=g.retryCount&&a instanceof be&&a.cancelResponseBody(),b}})}async _shutdown(a=3e4){await this._initPromise;let b=!1;if(this.clearFlushTimer(),!this.disabled)return S((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(a=>this.getRouteQueue(a).length>0);){let a=this._dequeuedMessagesCount;if(await this.flush(),b)break;if(this._dequeuedMessagesCount===a){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(a){if(!("object"==typeof a&&(a instanceof be||bh(a))))throw a;await bg(a)}})(),a,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:a}),b=!0})}async shutdown(a=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(a).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}let bp="[Circular]",bq="[Truncated]",br="[Unserializable]";function bs(a){let b="";for(let c=0;c<a.length;c++){let d=a.charCodeAt(c);if(d>=55296&&d<=56319){let d=a.charCodeAt(c+1);d>=56320&&d<=57343?(b+=a[c]+a[c+1],c++):b+="�"}else b+=d>=56320&&d<=57343?"�":a[c]}return b}function bt(a,b){if(!b)return a;let c=[];try{c=Object.keys(b)}catch{c=[]}for(let d of c){let c;try{c=b[d]}catch{c=br}Object.defineProperty(a,d,{value:c,enumerable:!0,writable:!0,configurable:!0})}return a}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let bu=Object.prototype.propertyIsEnumerable;function bv(a,b){try{return bw(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function bw(a,b,c,d){let e=[];for(let f in a)if(bu.call(a,f)){if(!f){b?.debug("Dropping an attribute with an empty key");continue}if(e.length>=1e3||c.remainingNodes<=0){b?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let g=a[f];if(w(g)||t(g))continue;e.push({key:bs(f),value:function a(b,c,d,e){if(d.remainingNodes<=0)return{stringValue:bq};if(d.remainingNodes--,"[object Boolean]"===q.call(b))return{boolValue:b};if("bigint"==typeof b){let a,d;return a=b.toString(),b>=(d=BigInt("9223372036854775808"))||b<-d?(c?.debug(`Attribute ${a} is outside the int64 range; encoding it as a string`),{stringValue:a}):{intValue:a}}if("number"==typeof b){if(!Number.isFinite(b))return{stringValue:String(b)};if(Number.isInteger(b)){if(Number.isSafeInteger(b))return{intValue:String(b)};if("u"<typeof BigInt)return{stringValue:String(b)};let a=BigInt(b).toString();return b>=0x8000000000000000||b<-0x8000000000000000?(c?.debug(`Attribute ${a} is outside the int64 range; encoding it as a string`),{stringValue:a}):{intValue:a}}return{doubleValue:b}}if("string"==typeof b)return{stringValue:bs(b)};if("function"==typeof b)return{stringValue:"[Function]"};if("symbol"==typeof b)return{stringValue:String(b)};if("object"==typeof b&&null!==b){if(d.ancestors.has(b))return{stringValue:bp};if(e>=20)return{stringValue:bq};if(b instanceof Date){let a=Number.isFinite(b.getTime())?b.toISOString():String(b);return{stringValue:"string"==typeof a?bs(a):String(a)}}d.ancestors.add(b);try{try{let f=b.toJSON;if("function"==typeof f)return a(f.call(b),c,d,e+1)}catch{}if(r(b))return{arrayValue:{values:function(b,c,d,e){let f=[],g=Math.min(b.length,1e3),h=0;for(;h<g&&d.remainingNodes>0;h++)try{let g=h in b?b[h]:void 0;if(x(g))continue;f.push(a(g,c,d,e))}catch{f.push({stringValue:br})}return b.length>h&&f.push({stringValue:bq}),f}(b,c,d,e+1)}};return{kvlistValue:{values:bw(b,c,d,e+1)}}}finally{d.ancestors.delete(b)}}return{stringValue:bs(String(b))}}(g,b,c,d)})}catch{e.push({key:bs(f),value:{stringValue:br}})}}return e}function bx(a,b,c){return{...bt({},a.resourceAttributes),"service.name":a.serviceName||"unknown_service",...a.environment&&{"deployment.environment":a.environment},...a.serviceVersion&&{"service.version":a.serviceVersion},"telemetry.sdk.name":b,"telemetry.sdk.version":c}}let by=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function bz(a,b){let c=bt({},a),d={};for(let a of by)Object.prototype.hasOwnProperty.call(c,a)&&(d[a]=c[a],delete c[a]);return[...bv(c,b),...bv(d,b)]}let bA={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 bB{constructor(a){this._onFire=a,this._firesAt=0}get pending(){return!!this._timer}arm(a){this.clear(),this._firesAt=Date.now()+a,this._timer=R(()=>{this._timer=void 0,this._onFire()},a)}armNoEarlierThan(a){this._timer&&Date.now()+a<=this._firesAt||this.arm(a)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}function bC(){return .75+.25*Math.random()*2}function bD(a,b,c,d){let e=Math.min(Math.max(0,b-1),6),f=a*2**e;return Math.round((void 0===d?f:Math.min(f,Math.max(d,a)))*c)}let bE="0000000000000000",bF=bE+bE,bG=/^[0-9a-f]+$/;function bH(a){let b=function(a){let b="";for(let c=0;c<a.length;c++)b+=a[c].toString(16).padStart(2,"0");return b}(function(a){let b=new Uint8Array(a),c=globalThis.crypto;if(c&&"function"==typeof c.getRandomValues)try{return c.getRandomValues(b),b}catch{}for(let c=0;c<a;c++)b[c]=Math.floor(256*Math.random());return b}(a));return/[^0]/.test(b)?b:b.slice(0,-1)+"1"}function bI(a,b,c){return"string"==typeof a&&a.length===b&&a!==c&&bG.test(a)}let bJ=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function bK(a){let b=bL(a);return b&&{traceId:b.traceId,spanId:b.spanId,flags:1&parseInt(b.flags,16)?bN:bO}}function bL(a){if("string"!=typeof a)return;let b=bJ.exec(a.trim());if(!b)return;let[,c,d,e,f,g]=b;if("ff"!==c&&("00"!==c||!g)&&bI(d,32,bF)&&bI(e,16,bE))return{version:c,traceId:d,spanId:e,flags:f}}function bM(a){return Array.isArray(a)&&1===a.length?a[0]:a}let bN="01",bO="00";function bP(a){if("string"!=typeof a)return;let b=a.trim();if(!b||/[^\x20-\x7e\t]/.test(b))return;let c=b.split(",");if(!(c.length>32)){for(let a of c)if(a.trim()&&!a.includes("="))return;return b.length<=512?b:function(a){let b=[...a],c=()=>b.reduce((a,b)=>a+b.length,0)+b.length-1;for(let a=b.length-1;a>=0&&c()>512;a--)b[a].length>128&&b.splice(a,1);for(;b.length&&c()>512;)b.pop();return b.length?b.join(","):void 0}(c)}}let bQ=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function bR(a){return String(a)+"000000"}function bS(a,b,c,d){let e="";return d&&(e=Object.keys(d).sort().map(a=>`${JSON.stringify(a)}:${JSON.stringify(d[a])}`).join(",")),`${a}\0${b}\0${c??""}\0${e}`}class bT{constructor(a,b,c){this._instance=a,this._config=b,this._logger=c,this._series=new Map,this._flushTimer=new bB(()=>this.flush().catch(a=>{this._logger.error("Metrics flush failed:",a)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new bd,this._consecutiveFlushFailures=0,this._flushJitter=1,this._generation=0}count(a,b=1,c){this._capture({name:a,type:"count",value:b,unit:c?.unit,attributes:c?.attributes})}gauge(a,b,c){this._capture({name:a,type:"gauge",value:b,unit:c?.unit,attributes:c?.attributes})}histogram(a,b,c){this._capture({name:a,type:"histogram",value:b,unit:c?.unit,attributes:c?.attributes})}flush(){let a=this._flushPromise,b=(async()=>{a&&await a.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===b&&(this._flushPromise=null)});return this._flushPromise=b,b}drainWindow(){if(0===this._series.size)return null;let a=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(a)}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(a){let b,c;if(this._instance.isDisabled||this._instance.optedOut)return;let d=this._runBeforeSend(a);if(null===d)return;if(!d.name||"string"!=typeof d.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof d.value||!Number.isFinite(d.value))return void this._logger.warn(`Dropping metric '${d.name}': value must be a finite number`);if("count"===d.type&&d.value<0)return void this._logger.warn(`Dropping count '${d.name}': counters are monotonic, value must be >= 0`);try{b=d.attributes?{...d.attributes}:void 0,c=bS(d.type,d.name,d.unit,b)}catch(a){this._logger.warn(`Dropping metric '${d.name}': attributes could not be serialized`,a);return}let e=this._series.get(c);if(!e){if(!this._admitNewSeries())return;e={name:d.name,type:d.type,unit:d.unit,attributes:b,windowStartMs:Date.now()},this._series.set(c,e)}let f=this._typeByName.get(d.name);void 0===f?this._typeByName.set(d.name,d.type):f===d.type||this._typeCollisionWarned.has(d.name)||(this._typeCollisionWarned.add(d.name),this._logger.warn(`Metric name '${d.name}' is already used as a ${f}; recording it as a ${d.type} too will blend both series in charts. Use a distinct name.`)),this._fold(e,d.value);let g=this._activeTraceContext();g&&(e.exemplar={...g,value:d.value,timeMs:Date.now()}),this._armFlushTimer()}_activeTraceContext(){try{let a=bK(this._instance.getActiveSpan?.()?.traceparent());if(a&&a.flags===bN)return{traceId:a.traceId,spanId:a.spanId}}catch{}}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush||(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(a,b){switch(a.type){case"count":a.total=(a.total??0)+b;break;case"gauge":a.last=b;break;case"histogram":{a.hist||(a.hist={count:0,sum:0,min:b,max:b,bucketCounts:Array(bQ.length+1).fill(0)});let c=a.hist;c.count+=1,c.sum+=b,c.min=Math.min(c.min,b),c.max=Math.max(c.max,b),c.bucketCounts[function(a,b){for(let c=0;c<b.length;c++)if(a<=b[c])return c;return b.length}(b,bQ)]+=1}}}_runBeforeSend(a){let b=this._config.beforeSend;if(!b)return a;let c=r(b)?b:[b],d=a;for(let a of c)try{let b=a(d);if(!b)return this._logger.info("Metric was rejected in beforeSend function"),null;d=b}catch(a){return this._logger.error("Error in beforeSend function for metric:",a),null}return d}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(bD(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),0===this._series.size)return;let a=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let b=this._generation,c=await this._instance._sendMetricsBatch(this._buildPayload(a));if(b===this._generation)switch(this._retryAfter.record(c),"retry-later"===c.kind?(this._consecutiveFlushFailures++,this._flushJitter=bC()):(this._consecutiveFlushFailures=0,this._flushJitter=1),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),c.kind){case"ok":return;case"retry-later":this._mergeWindowBack(a),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",c.error);return}}_buildPayload(a){var b,c,d,e;return b=this._buildMetrics(a),c=bx(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),d=this._instance.getLibraryId(),e=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:bz(c)},scopeMetrics:[{scope:{name:d,version:e},metrics:b}]}]}}_buildMetrics(a){let b=bR(Date.now()),c=new Map;for(let e of a.values()){var d;let a=bS(e.type,e.name,e.unit,void 0),f=c.get(a);f||(f={name:e.name,...e.unit&&{unit:e.unit}},"count"===e.type?f.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===e.type?f.gauge={dataPoints:[]}:f.histogram={aggregationTemporality:1,dataPoints:[]},c.set(a,f));let g=bv(e.attributes??{},this._logger),h=bR(e.windowStartMs),i=(d=e.exemplar)?{exemplars:[{filteredAttributes:[],timeUnixNano:bR(d.timeMs),asDouble:d.value,traceId:d.traceId,spanId:d.spanId}]}:{};if("count"===e.type){let a={attributes:g,startTimeUnixNano:h,timeUnixNano:b,asDouble:e.total??0,...i};f.sum.dataPoints.push(a)}else if("gauge"===e.type){let a={attributes:g,timeUnixNano:b,asDouble:e.last??0,...i};f.gauge.dataPoints.push(a)}else if(e.hist){let a={attributes:g,startTimeUnixNano:h,timeUnixNano:b,count:e.hist.count,sum:e.hist.sum,min:e.hist.min,max:e.hist.max,bucketCounts:e.hist.bucketCounts,explicitBounds:bQ,...i};f.histogram.dataPoints.push(a)}}return Array.from(c.values())}_mergeWindowBack(a){for(let[b,c]of a){let a=this._series.get(b);if(!a){this._admitNewSeries()&&this._series.set(b,c);continue}switch(a.windowStartMs=Math.min(a.windowStartMs,c.windowStartMs),a.exemplar=a.exemplar??c.exemplar,a.type){case"count":a.total=(a.total??0)+(c.total??0);break;case"gauge":break;case"histogram":if(c.hist)if(a.hist){a.hist.count+=c.hist.count,a.hist.sum+=c.hist.sum,a.hist.min=Math.min(a.hist.min,c.hist.min),a.hist.max=Math.max(a.hist.max,c.hist.max);for(let b=0;b<a.hist.bucketCounts.length;b++)a.hist.bucketCounts[b]+=c.hist.bucketCounts[b]}else a.hist=c.hist}}}}let bU="unknown";function bV(a,b,c,d){return"string"==typeof a&&a.trim()?a.length>c?a.slice(0,c):a:(d?.debug(`${b} must be a non-empty string; using "${bU}"`),bU)}function bW(a){if(null==a)return;let b=a;if(a instanceof Date)try{b=a.getTime()}catch{return}if("number"==typeof b&&Number.isFinite(b)&&!(b<0)&&!(b>0x8637bd05af6))return b}function bX(a,b,c,d){let e=bW(a);return void 0===e?(void 0!==a&&d?.debug(`Span ${c} is out of range or not a valid time; using the derived time`),b):e}function bY(){let a=globalThis.performance;return"function"==typeof a?.now?a.now():void 0}class bZ{constructor(a,b,c){for(let d of(this._onEnd=b,this._logger=c,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=a.traceId,this._spanId=a.spanId,this._parentSpanId=a.parentSpanId,this._traceState=a.traceState,this._traceFlags=a.traceFlags??bN,this._parentIsRemote=a.parentIsRemote??!1,this._name=a.name,this._kind=a.kind,this._autoKeys=new Set(a.autoAttributeKeys),this._maxAttributes=a.maxAttributes,this._maxEvents=a.maxEvents,this._maxAttributesPerEvent=a.maxAttributesPerEvent,this._maxAttributeValueLength=a.maxAttributeValueLength,this._attributes=Object.create(null),Object.keys(a.attributes)))this._writeAttribute(d,a.attributes[d]);this._startMono=a.backdated?void 0:bY(),this._startTime=a.clockAnchor&&void 0!==this._startMono?a.clockAnchor.wall+(this._startMono-a.clockAnchor.mono):a.startTime,void 0!==this._startMono&&(this._clockAnchor=a.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(void 0!==this._startMono){let a=bY();if(void 0!==a)return this._startTime+Math.max(0,a-this._startMono)}return Date.now()}_mutable(a){return!this._ended||(this._logger?.debug(`Ignoring ${a} on a span that has already ended`),!1)}_writeAttribute(a,b){if(x(b)){a in this._attributes&&!this._autoKeys.has(a)&&this._userAttributeCount--,delete this._attributes[a];return}if(!this._autoKeys.has(a)&&!(a in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[a]=b6(b,this._maxAttributeValueLength)}setAttribute(a,b){return this._mutable("setAttribute")&&this._writeAttribute(a,b),this}setAttributes(a){if(this._mutable("setAttributes")){let b=bt({},a);for(let a of Object.keys(b))this._writeAttribute(a,b[a])}return this}addEvent(a,b,c){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let d=b&&b7(b,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:bV(a,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:bX(c,this._now(),"event timestamp",this._logger),...d&&{attributes:d.attributes,...d.dropped&&{droppedAttributesCount:d.dropped}}})}return this}setStatus(a,b){if(this._mutable("setStatus")){if("ok"!==a&&"error"!==a)return this._logger?.debug(`Ignoring unknown span status "${String(a)}"; expected "ok" or "error"`),this;this._status={code:a,...b&&{message:b5(b,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(a){if(!this._mutable("recordException"))return this;let{type:b,message:c,stack:d}=b9(a);return this.addEvent(b$,{"exception.type":b,"exception.message":c,...d&&{"exception.stacktrace":d}}),this.setStatus("error",c)}updateName(a){return this._mutable("updateName")&&(this._name=bV(a,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return function(a,b,c=bN){return`00-${a}-${b}-${c}`}(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(a){var b;if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let c=bX(a,this._now(),"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:c<(b=this._startTime)?b:c,...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}}let b$="exception";function b_(a){return"number"!=typeof a||!Number.isFinite(a)||a<=0?0:Math.min(Math.floor(a),0xffffffff)}class b0{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 b1=new b0;class b2 extends b0{constructor(a,b){super(),this._traceparent=a,this._tracestate=b}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}}function b3(a,b){var c;let d=bM(a?.parent)??b,e=bL(c="string"==typeof d||null==d?d:b4(d,"traceparent"))&&c.trim();return e?new b2(e,bP("string"==typeof d||null==d?a?.tracestate:b4(d,"tracestate"))):b1}function b4(a,b){try{let c=a[b];return"function"==typeof c?c.call(a):void 0}catch{return}}function b5(a,b){return a.length>b?a.slice(0,b):a}function b6(a,b){return function a(b,c,d,e){if(null===b||"object"!=typeof b)return x(b)||d.remainingNodes<=0?b:(d.remainingNodes--,"string"==typeof b?b5(b,c):b);if(d.ancestors.has(b))return bp;if(d.remainingNodes<=0||e>=20)return b;d.remainingNodes--,d.ancestors.add(b);try{if(b instanceof Date)return b;let f=function(a){try{let b=a.toJSON;if("function"==typeof b)return{selfDescribed:!0,value:b.call(a)}}catch{}return{selfDescribed:!1}}(b);if(f.selfDescribed)return x(f.value)?String(f.value):a(f.value,c,d,e+1);if(r(b)){let f=Math.min(b.length,1e3),g=[];for(let h=0;h<f;h++)try{g.push(a(b[h],c,d,e+1))}catch{g.push(br)}return b.length>f&&(g.length=b.length),g}let g={},h=0;for(let f of Object.keys(b)){let i;if(h>=1e3)break;try{i=a(b[f],c,d,e+1)}catch{i=br}f&&!x(i)&&h++,Object.defineProperty(g,f,{value:i,enumerable:!0,writable:!0,configurable:!0})}return g}catch{return b}finally{d.ancestors.delete(b)}}(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}function b7(a,b,c){let d;try{d=Object.keys(a)}catch{return{attributes:{},dropped:0}}let e={},f=0,g=0;for(let h of d){let d;if(f>=b){g++;continue}try{d=b6(a[h],c)}catch{d=br}x(d)||(f++,Object.defineProperty(e,h,{value:d,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:e,dropped:g}}function b8(a,b,c){return b===b1?c(b):a.with(b,()=>c(b))}function b9(a){try{let b=function(a){try{let b=a.stack;return"string"==typeof b&&b?{stack:b}:{}}catch{return{}}}(a);if(B(a))return{type:a.name||"Error",message:a.message||"",...b};if("string"==typeof a)return{type:"string",message:a};if(a&&"object"==typeof a&&"string"==typeof a.message)return{type:"string"==typeof a.name?a.name:"Object",message:a.message,...b};return{type:typeof a,message:String(a)}}catch{return{type:typeof a,message:""}}}let ca={internal:1,server:2,client:3,producer:4,consumer:5},cb={ok:1,error:2};function cc(a){if("string"==typeof a)return bs(a);try{return bs(String(a))}catch{return br}}function cd(a){let b=Math.floor(a),c=Math.round((a-b)*1e6);return c>=1e6&&(b+=1,c=0),String(b)+String(c).padStart(6,"0")}function ce(){return bY()??Date.now()}function cf(a){try{return a instanceof bZ}catch{return!1}}function cg(a,b){let c=bK(a);if(c)return{traceId:c.traceId,parentSpanId:c.spanId,traceState:bP(b),traceFlags:c.flags,isRemote:!0}}function ch(a,b,c){a[b]!==c&&(a[b]=c)}class ci{constructor(a,b,c,d,e,f){this._instance=a,this._config=b,this._logger=c,this._getContext=d,this._contextManager=e,this._onSpanQueued=f,this._queue=[],this._flushTimer=new bB(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter=new bd,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=b.maxExportBatchSize}startSpan(a,b){var c,d;let e;if(this._instance.isDisabled||this._instance.optedOut)return b3(b,this._contextManager.active());let f=bM(b?.parent);if(f&&"string"!=typeof f&&!cf(f)){if(function(a){try{return"function"==typeof a.traceparent}catch{return!1}}(f))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),b3(b,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let g=this._resolveParent(f,b);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached — spans are being started and never ended`),b3(b,this._contextManager.active());let h=Date.now(),i=(c=b?.startTime,d=this._logger,void 0===(e=bW(c))?(void 0!==c&&d?.debug("Span startTime is out of range or not a valid time; using the current time"),h):(h-e>864e5?d?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):e>h&&d?.debug("Span startTime is in the future; the span may export with a zero duration"),e)),j=bH(8);this._liveSpans.set(j,ce());let k=this._autoContextAttributes();return new bZ({traceId:g?.traceId??bH(16),spanId:j,parentSpanId:g?.parentSpanId,traceState:g?.traceState,traceFlags:g?.traceFlags,parentIsRemote:g?.isRemote,name:bV(a,"Span name",this._config.maxAttributeValueLength,this._logger),kind:b?.kind??"internal",attributes:bt({...k},b?.attributes),autoAttributeKeys:Object.keys(k),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:i,backdated:i!==h,clockAnchor:void 0===bW(b?.startTime)?g?.clockAnchor:void 0},(a,b)=>this._onSpanEnd(a,b),this._logger)}withSpan(a,b,c){let d=this.startSpan(a,"function"==typeof b?void 0:b);try{let a=b8(this._contextManager,d,"function"==typeof b?b:c);if(a&&"function"==typeof a.then)return a.then(a=>(d.end(),a),a=>{throw this._recordCallbackError(d,a),d.end(),a});return d.end(),a}catch(a){throw this._recordCallbackError(d,a),d.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;){if(!this._queue.length)return;let a=this._flushPromise;if(!await (a??this._startFlush()))return}}_startFlush(){this._flushTimer.clear();let a=this._generation,b=Promise.resolve().then(()=>a===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===b&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=b,b}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(a,b){if("string"==typeof a){let c=cg(a,b?.tracestate);return c||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),c}if(cf(a))return a.childContext();let c=this._contextManager.active();return cf(c)?c.childContext():c instanceof b2?cg(c.traceparent(),c.tracestate()??void 0):void 0}_autoContextAttributes(){let a;try{a=this._getContext()}catch(a){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",a),{}}let b={};return a.distinctId&&(b.posthogDistinctId=a.distinctId),a.sessionId&&(b.sessionId=a.sessionId),a.currentUrl&&(b["url.full"]=a.currentUrl),a.screenName&&(b["screen.name"]=a.screenName),a.appState&&(b["app.state"]=a.appState),b}_recordCallbackError(a,b){if(!(a instanceof bZ))return;let{type:c,message:d,stack:e}=b9(b);a.addEvent("exception",{"exception.type":c,"exception.message":d,...e&&{"exception.stacktrace":e}}),a.statusIsExplicitlyOk||a.setStatus("error",d)}_evictAgedSpans(){let a=ce()-this._config.maxSpanAgeMs,b=0;for(let[c,d]of this._liveSpans){if(d>a)break;this._liveSpans.delete(c),b++}b&&this._recordDrop(b,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(a,b){if(!this._liveSpans.delete(a.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let c=this._runBeforeSpanSend(a,b);if(c){if(this._reportLimitDrops(c),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) — raise the flush frequency or reduce span volume`);this._queue.push(c);try{this._onSpanQueued?.()}catch(a){this._logger.debug("Span queue notification failed",a)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(a){let b=a.droppedAttributesCount??0,c=a.droppedEventsCount??0,d=0;for(let b of a.events)d+=b.droppedAttributesCount??0;(b||c||d)&&this._logger.debug(`Span limits discarded data from "${a.name}": ${b} attributes, ${c} events, ${d} event attributes`)}_runBeforeSpanSend(a,b){if(!this._config.beforeSpanSend.length)return a;let c={traceId:a.traceId,spanId:a.spanId,parentSpanId:a.parentSpanId,traceState:a.traceState},d={startTime:a.startTime,endTime:a.endTime},e={attributes:a.droppedAttributesCount,events:a.droppedEventsCount},f=Object.keys(a.attributes),g={traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote},h=a.status&&{...a.status},i=a,j=a;try{var k,l,m;for(let a of this._config.beforeSpanSend){let b=a(i);if(!b)return this._recordDrop(1,"beforeSpanSend dropped it"),null;i=this._keepSpanIdentity(b,c)}if(!((k=j={traceId:c.traceId,spanId:c.spanId,parentSpanId:c.parentSpanId,traceState:c.traceState,name:i.name,kind:i.kind,status:i.status,attributes:i.attributes,events:i.events,startTime:i.startTime,endTime:i.endTime,traceFlags:g.traceFlags,parentIsRemote:g.parentIsRemote,droppedAttributesCount:e.attributes,droppedEventsCount:e.events}).attributes&&"object"==typeof k.attributes&&!Array.isArray(k.attributes)&&Array.isArray(k.events)&&void 0!==k.name&&void 0!==k.kind&&void 0!==k.startTime&&void 0!==k.endTime))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;j.name=bV(j.name,"Span name",this._config.maxAttributeValueLength,this._logger),j.status&&"ok"!==j.status.code&&"error"!==j.status.code&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),j.status=h),j.startTime=bW(j.startTime)??d.startTime,j.endTime=(l=bW(j.endTime)??d.endTime,m=j.startTime,l<m?m:l);let a=[];for(let b of j.events)try{a.push({...b,name:bV(b.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:bX(b.timestamp,j.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return j.events=a,!function(a,b,c,d,e,f,g=[]){let h=0,i=0,j={};for(let d of function(a,b){if(!b.length)return Object.keys(a);let c=b.filter(b=>Object.prototype.propertyIsEnumerable.call(a,b)),d=new Set(c);return[...c,...Object.keys(a).filter(a=>!d.has(a))]}(a.attributes,g)){let e=a.attributes[d];if(!x(e)){if(!b.has(d)){if(h>=c){i++;continue}h++}Object.defineProperty(j,d,{value:b6(e,f),enumerable:!0,writable:!0,configurable:!0})}}a.attributes=j,i&&(a.droppedAttributesCount=b_(a.droppedAttributesCount)+i);let k=0,l=0,m=[];for(let b of a.events){if(k>=d){l++;continue}if(k++,b.attributes){let a=b7(b.attributes,e,f);b.attributes=a.attributes,a.dropped&&(b.droppedAttributesCount=b_(b.droppedAttributesCount)+a.dropped)}m.push(b)}a.events=m,l&&(a.droppedEventsCount=b_(a.droppedEventsCount)+l),a.status?.message&&(a.status={...a.status,message:b5(function(a){try{return"string"==typeof a?a:String(a)}catch{return br}}(a.status.message),f)})}(j,b,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,f),j}catch(a){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",a),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(a,b){(a.traceId!==b.traceId||a.spanId!==b.spanId||a.parentSpanId!==b.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{ch(a,"traceId",b.traceId),ch(a,"spanId",b.spanId),ch(a,"parentSpanId",b.parentSpanId),ch(a,"traceState",b.traceState)}catch{try{let c=Object.getOwnPropertyDescriptors(a);for(let a of["traceId","spanId","parentSpanId","traceState"])c[a]={value:b[a],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(a),c)}catch{;}}return a}_recordDrop(a,b){this._droppedSinceWarning+=a,this._dropReasons.add(b),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(a){let b=[];for(let c of a)try{b.push(function(a,b){var c;let d,e={traceId:a.traceId,spanId:a.spanId,name:cc(a.name),kind:(c=a.kind)&&Object.prototype.hasOwnProperty.call(ca,c)?ca[c]:ca.internal,startTimeUnixNano:cd(a.startTime),endTimeUnixNano:cd(a.endTime),flags:(Number.isFinite(d=parseInt(a.traceFlags,16))?255&d:1)|256|512*!!a.parentIsRemote};a.parentSpanId&&(e.parentSpanId=a.parentSpanId),a.traceState&&(e.traceState=cc(a.traceState));let f=bv(a.attributes,b);f.length&&(e.attributes=f),a.events.length&&(e.events=a.events.map(a=>(function(a,b){let c={name:cc(a.name),timeUnixNano:cd(a.timestamp)};if(a.attributes){let d=bv(a.attributes,b);d.length&&(c.attributes=d)}let d=b_(a.droppedAttributesCount);return d&&(c.droppedAttributesCount=d),c})(a,b)));let g=b_(a.droppedAttributesCount);g&&(e.droppedAttributesCount=g);let h=b_(a.droppedEventsCount);return h&&(e.droppedEventsCount=h),a.status&&(e.status={code:cb[a.status.code],...a.status.message&&{message:cc(a.status.message)}}),e}(c,this._logger))}catch(a){this._logger.debug("Failed to encode a span; dropping it",a),this._recordDrop(1,"its attributes could not be encoded")}return b}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let a=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(a,"the user has opted out"),this._warnAboutDrops(),a}async _flushInner(){var a,b;if(!this._queue.length)return 0;let c=this._discardQueueIfConsentWithdrawn();if(c)return c;let d=function(a,b){for(let c of Object.keys(a))a[c]=b6(a[c],b);return a}((a=this._config,bx(a,this._instance.getLibraryId(),this._instance.getLibraryVersion())),this._config.maxAttributeValueLength),e=this._instance.getLibraryId(),f=this._instance.getLibraryVersion(),g=this._queue.length,h=0,i=1/0,j=this._generation;try{for(;g>0&&this._queue.length>0;){let a=this._discardQueueIfConsentWithdrawn();if(a)return h+a;let c=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,k=Math.max(1,Math.min(c,i,g,this._queue.length)),l=this._queue.slice(0,k),m=this._encodeBatch(l);if(!m.length){this._queue.splice(0,k),g-=k,h+=k,this._resetHeadBatchBudget();continue}let n=ce()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),o=await this._instance._sendTracesBatch((b=this._logger,{resourceSpans:[{resource:{attributes:bz(d,b)},scopeSpans:[{scope:{name:e,version:f},spans:m}]}]}));if(j!==this._generation)break;if(this._retryAfter.record(o),"ok"===o.kind){this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._queue.splice(0,k),g-=k,h+=k,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if("too-large"===o.kind){if(1===k){this._queue.splice(0,1),g-=1,h+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget();continue}let a=Math.max(1,Math.floor(k/2));o.measuredLocally?i=a:this._maxExportBatchSize=a,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${a}`);continue}if("retry-later"===o.kind){if(this._consecutiveFlushFailures++,this._flushJitter=bC(),this._headBatchSize=k,n&&(this._headBatchFailures++,this._headBatchChargeableAt=ce()+this._nextFlushDelay()),this._headBatchFailures<8)return this._logger.debug("Span export failed; retrying on the next flush",o.error),h;if(this._queue.splice(0,k),g-=k,h+=k,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(k,"the ingestion endpoint failed 8 times in a row"),this._retryAfter.isOpen())return h;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",o.error),this._queue.splice(0,k),g-=k,h+=k,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(k,"the ingestion endpoint rejected the batch")}return h}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(a=>{this._logger.debug("Background span flush failed",a)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){!this._flushTimer.pending&&this._queue.length&&this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(bD(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}}var cj=a.i(2157),ck=a.i(12714),cl=a.i(50227),cm=a.i(1457);let cn=new aS.ReduceableCache(25),co=new aS.ReduceableCache(20);async function cp(a,b=ck.open,c){let d,e={};try{d=process.cwd()}catch{}for(let b=a.length-1;b>=0;b--){var f,g;let c=a[b],h=c?.filename;!(!c||"string"!=typeof h||"number"!=typeof c.lineno||(f=h).startsWith("node:")||f.endsWith(".min.js")||f.endsWith(".min.cjs")||f.endsWith(".min.mjs")||f.startsWith("data:")||void 0!==(g=c).lineno&&g.lineno>1e4||void 0!==g.colno&&g.colno>1e3)&&((0,cl.isAbsolute)(h)||void 0!==d)&&(e[h]||(e[h]=[]),e[h].push(c.lineno))}let h=Object.keys(e);if(0==h.length)return a;let i=[];for(let a of h){let f=ct(a,d);if(void 0===f||co.get(f))continue;let g=e[a];if(!g)continue;g.sort((a,b)=>a-b);let h=function(a){if(!a.length)return[];let b=0,c=a[0];if("number"!=typeof c)return[];let d=cu(c),e=[];for(;;){if(b===a.length-1){e.push(d);break}let c=a[b+1];if("number"!=typeof c)break;c<=d[1]?d[1]=c+7:(e.push(d),d=cu(c)),b++}return e}(g);if(h.every(a=>(function(a,b){let c=cn.get(a);if(void 0===c)return!1;for(let a=b[0];a<=b[1];a++)if(void 0===c[a])return!1;return!0})(f,a)))continue;let j=function(a,b,c){let d=a.get(b);return void 0===d?(a.set(b,c),c):d}(cn,f,{});i.push(cr(a,h,j,f,b,c))}return await Promise.all(i).catch(()=>{}),a&&a.length>0&&function(a,b,c){for(let d of a)if(d.filename&&void 0===d.context_line&&"number"==typeof d.lineno){let a=ct(d.filename,c),e=void 0===a?void 0:b.get(a);if(void 0===e)continue;!function(a,b,c){if(void 0===b.lineno||void 0===c)return;b.pre_context=[];for(let d=cv(a);d<a;d++){let a=c[d];if(void 0===a)return void cs(b);b.pre_context.push(a)}if(void 0===c[a])return cs(b);b.context_line=c[a];let d=function(a){return a+7}(a);b.post_context=[];for(let e=a+1;e<=d;e++){let a=c[e];if(void 0===a)break;b.post_context.push(a)}}(d.lineno,d,e)}}(a,cn,d),cn.reduce(),a}async function cq(a,b,c){let d,e=!1;try{d=await b(a,cj.constants.O_RDONLY|cj.constants.O_NONBLOCK);let f=await d.stat();if(!f.isFile())return;if(f.size>0xa00000)return void c?.debug(`Skipping source context for oversized file ${a}: ${f.size} bytes exceeds 10485760`);return e=!0,d}catch{return}finally{d&&!e&&await d.close().catch(()=>{})}}async function cr(a,b,c,d,e,f){let g=await cq(a,e,f);return void 0===g?void co.set(d,1):new Promise(a=>{let e,f,h=!1;function i(b){h||(h=!0,b?.destroy(),g.close().then(a,a))}try{e=g.createReadStream({autoClose:!1,start:0,end:0x9fffff})}catch{co.set(d,1),i();return}try{f=(0,cm.createInterface)({input:e})}catch{co.set(d,1),i(e);return}let j=0,k=0,l=b[0];if(void 0===l)return void i(e);let m=l[0],n=l[1];function o(){co.set(d,1),f.close(),f.removeAllListeners(),i(e)}e.on("error",o),f.on("error",o),f.on("close",()=>i(e)),f.on("line",a=>{if(!(++j<m)&&(c[j]=function(a,b){let c=a,d=c.length;if(d<=150)return c;b>d&&(b=d);let e=Math.max(b-60,0);e<5&&(e=0);let f=Math.min(e+140,d);return f>d-5&&(f=d),f===d&&(e=Math.max(f-140,0)),c=c.slice(e,f),e>0&&(c=`...${c}`),f<d&&(c+="..."),c}(a,0),j>=n)){if(k===b.length-1){f.close(),f.removeAllListeners();return}let a=b[++k];if(void 0===a){f.close(),f.removeAllListeners();return}m=a[0],n=a[1]}})})}function cs(a){delete a.pre_context,delete a.context_line,delete a.post_context}function ct(a,b){return(0,cl.isAbsolute)(a)?JSON.stringify([null,a]):void 0===b?void 0:JSON.stringify([b,a])}function cu(a){return[cv(a),a+7]}function cv(a){return Math.max(1,a-7)}class cw{active(){return this._active}with(a,b){let c=this._active;this._active=a;try{return b()}finally{this._active=c}}}let cx=["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"],cy=new Map,cz=function(a,b=[]){if(!a)return!1;let c=function(a,b){let c="";for(let a=0;a<b.length;a++){let d=b[a];c+=d.length+":"+d}return a.length+":"+a+"|"+b.length+":"+c}(a,b),d=cy.get(c);if(void 0!==d)return d;let e=a.toLowerCase(),f=cx.concat(b).some(a=>-1!==e.indexOf(a.toLowerCase()));return cy.size>=256&&cy.clear(),cy.set(c,f),f};function cA(a,b){return"number"==typeof a&&Number.isInteger(a)&&a>=1?a:b}let cB=["service.name","service.version","deployment.environment"],cC={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",LOCAL_EVALUATION_INCONCLUSIVE:"local_evaluation_inconclusive",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};a.s(["FeatureFlagError",0,cC],46539);class cD{constructor(a){this._host=a.host,this._distinctId=a.distinctId,this._groups=a.groups,this._disableGeoip=a.disableGeoip,this._flags=a.flags,this._unresolvedFlags=Object.freeze({...a.unresolvedFlags}),this._requestId=a.requestId,this._evaluatedAt=a.evaluatedAt,this._flagDefinitionsLoadedAt=a.flagDefinitionsLoadedAt,this._errorsWhileComputing=a.errorsWhileComputing??!1,this._quotaLimited=a.quotaLimited??!1,this._accessed=a.accessed??new Set,this._isSlice=a.isSlice??!1}isEnabled(a,b={}){let c=this._flags[a];return this._recordAccess(a),c?.enabled??b.defaultValue??!1}getFlag(a){let b=this._flags[a];if(this._recordAccess(a),b)return!!b.enabled&&(b.variant??!0)}getFlagPayload(a){return this._flags[a]?.payload}onlyAccessed(){let a={};for(let b of this._accessed){let c=this._flags[b];c&&(a[b]=c)}return this._cloneWith(a)}only(a){let b={},c=[];for(let d of a){let a=this._flags[d];a?b[d]=a:c.push(d)}return c.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${c.join(", ")}`),this._cloneWith(b)}get keys(){return Object.keys(this._flags)}get unresolvedFlags(){return this._unresolvedFlags}_getEventProperties(){let a={},b=[];for(let[c,d]of Object.entries(this._flags)){let e=!1!==d.enabled&&(d.variant??!0);a[`$feature/${c}`]=e,d.enabled&&b.push(c)}return b.length>0&&(b.sort(),a.$active_feature_flags=b),a}_cloneWith(a){return new cD({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:a,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(a){if(this._accessed.add(a),""===this._distinctId||this._isSlice&&!(a in this._flags))return;let b=this._flags[a],c=void 0===b?void 0:!1!==b.enabled&&(b.variant??!0),d={$feature_flag:a,$feature_flag_response:c,$feature_flag_id:b?.id,$feature_flag_version:b?.version,$feature_flag_reason:b?.reason,locally_evaluated:b?.locallyEvaluated??!1,[`$feature/${a}`]:c,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:b?.locallyEvaluated?Date.now():this._evaluatedAt};b?.hasExperiment!==void 0&&(d.$feature_flag_has_experiment=b.hasExperiment),b?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(d.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let e=[];this._errorsWhileComputing&&e.push(cC.ERRORS_WHILE_COMPUTING),this._quotaLimited&&e.push(cC.QUOTA_LIMITED),void 0===b&&e.push(Object.prototype.hasOwnProperty.call(this._unresolvedFlags,a)?cC.LOCAL_EVALUATION_INCONCLUSIVE:cC.FLAG_MISSING),e.length>0&&(d.$feature_flag_error=e.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:a,response:c,groups:this._groups,disableGeoip:this._disableGeoip,properties:d})}}let cE=["exact","is_not","icontains","not_icontains","starts_with","not_starts_with","ends_with","not_ends_with","regex","not_regex"];class cF extends Error{constructor(a,b="unsupported_definition"){super(a),this.name=this.constructor.name,this.reason=b,Object.setPrototypeOf(this,cF.prototype)}}function cG(a){try{return a()}catch(a){if(a instanceof cF)throw new cF(a.message,"missing_context");throw a}}function cH(a){if("boolean"==typeof a)return!0;if("string"==typeof a){let b=a.toLowerCase();return"true"===b||"false"===b}if(!Array.isArray(a))return!1;for(let b=0;b<a.length;b++)if(!cH(b in a?a[b]:null))return!1;return!0}function cI(a){if("boolean"==typeof a)return a;if("string"==typeof a)return"true"===a.toLowerCase();if(!Array.isArray(a))return!1;for(let b=0;b<a.length;b++)if(!cI(b in a?a[b]:null))return!1;return!0}function cJ(a){for(let b=0;b<a.length;b++){let c=a.charCodeAt(b);if(c>=55296&&c<=56319){let c=a.charCodeAt(b+1);if(b+1>=a.length||c<56320||c>57343)throw new cF("Cannot stringify an unpaired surrogate like the flags service");b++}else if(c>=56320&&c<=57343)throw new cF("Cannot stringify an unpaired surrogate like the flags service")}}function cK(a,b=new Set){if(null!==a&&"boolean"!=typeof a){if("string"==typeof a)return void cJ(a);if("number"==typeof a){if(!Number.isFinite(a))throw new cF(`Cannot represent non-finite number ${a} like the flags service`);return}if(Array.isArray(a)){if(b.has(a))throw new cF("Cannot represent a circular array during local evaluation");b.add(a);try{for(let c=0;c<a.length;c++)c in a&&cK(a[c],b)}finally{b.delete(a)}return}if("object"==typeof a){let c=Object.getPrototypeOf(a);if(c!==Object.prototype&&null!==c)throw new cF("Cannot represent a non-JSON object like the flags service");if(b.has(a))throw new cF("Cannot represent a circular object during local evaluation");b.add(a);try{for(let c of Object.keys(a))cJ(c),cK(a[c],b)}finally{b.delete(a)}return}throw new cF(`Cannot represent ${typeof a} like the flags service`)}}function cL(a,b){let c=0,d=0;for(;c<a.length&&d<b.length;){let e=a.charCodeAt(c),f=b.charCodeAt(d),g=e>=55296&&e<=56319,h=f>=55296&&f<=56319,i=g?a.charCodeAt(c+1):0,j=h?b.charCodeAt(d+1):0,k=g?(e-55296)*1024+i-56320+65536:e,l=h?(f-55296)*1024+j-56320+65536:f;if(k!==l)return k-l;c+=g?2:1,d+=h?2:1}return a.length-b.length}function cM(a){return"string"==typeof a?(cJ(a),a):function a(b,c=new Set){if(null===b)return"null";if("string"==typeof b)return cJ(b),JSON.stringify(b);if("boolean"==typeof b)return b?"true":"false";if("number"==typeof b){if(!Number.isFinite(b))throw new cF(`Cannot stringify non-finite number ${b} like the flags service`);if(Number.isInteger(b))throw new cF(`Cannot distinguish integer ${b} from an integral JSON float during local evaluation`);return String(b)}if(Array.isArray(b)){if(c.has(b))throw new cF("Cannot stringify a circular array during local evaluation");c.add(b);try{let d=[];for(let e=0;e<b.length;e++)d.push(e in b?a(b[e],c):"null");return`[${d.join(",")}]`}finally{c.delete(b)}}if("object"==typeof b){let d=Object.getPrototypeOf(b);if(d!==Object.prototype&&null!==d)throw new cF("Cannot stringify a non-JSON object like the flags service");if(c.has(b))throw new cF("Cannot stringify a circular object during local evaluation");c.add(b);try{let d=Object.keys(b);return d.forEach(cJ),`{${d.sort(cL).map(d=>`${JSON.stringify(d)}:${a(b[d],c)}`).join(",")}}`}finally{c.delete(b)}}throw new cF(`Cannot stringify ${typeof b} like the flags service`)}(a)}let cN=/[\x20-\x2f:;=?@\x5b-\x60\x7b-\x7e]/;function cO(a){let b=new cF(a);return Object.defineProperty(b,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),b}function cP(a){return String(a).replace(/[A-Z]/g,a=>a.toLowerCase())}function cQ(a,b,c){if(!/^\d+$/.test(a)||"strict"===c&&a.length>1&&"0"===a[0])throw new cF(`Invalid semver: ${b}`);return parseInt(a,10)}function cR(a,b="strict"){let c=String(a).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!c||c.startsWith("."))throw new cF(`Invalid semver: ${a}`);let d=c.split("."),e=c=>void 0===c||""===c?0:cQ(c,a,b);return[e(d[0]),e(d[1]),e(d[2])]}function cS(a,b){for(let c=0;c<3;c++){if(a[c]<b[c])return -1;if(a[c]>b[c])return 1}return 0}function cT(a,b){let c=cR(a,b);return{lower:[c[0],c[1],c[2]],upper:[c[0],c[1]+1,0]}}function cU(a,b){let[c,d,e]=cR(a,b);return{lower:[c,d,e],upper:c>0?[c+1,0,0]:d>0?[0,d+1,0]:[0,0,e+1]}}function cV(a,b){let c=String(a).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!c)throw new cF(`Invalid wildcard semver: ${a}`);let d=c.split("."),e=c=>{if("legacy-permissive"===b){let a=parseInt(c,10);if(!isNaN(a))return a}else try{return cQ(c,a,b)}catch{}throw new cF(`Invalid wildcard semver: ${a}`)},f=e(d[0]);if(1===d.length)return{lower:[f,0,0],upper:[f+1,0,0]};let g=e(d[1]);return{lower:[f,g,0],upper:[f,g+1,0]}}function cW(a){if(a instanceof Date)return a;if("string"==typeof a||"number"==typeof a){let b=new Date(a);if(!isNaN(b.valueOf()))return b;throw new cF(`${a} is in an invalid date format`)}throw new cF(`The date provided ${a} must be a string, number, or date object`)}function cX(a){if("boolean"==typeof a)throw new cF("Date operations cannot be performed on boolean values");return function(a){let b=a.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),c=new Date(new Date().toISOString());if(!b||!b.groups)return null;let d=parseInt(b.groups.number);if(d>=1e4)return null;let e=b.groups.interval;if("h"===e)c.setUTCHours(c.getUTCHours()-d);else if("d"===e)c.setUTCDate(c.getUTCDate()-d);else if("w"===e)c.setUTCDate(c.getUTCDate()-7*d);else if("m"===e)c.setUTCMonth(c.getUTCMonth()-d);else{if("y"!==e)return null;c.setUTCFullYear(c.getUTCFullYear()-d)}return c}(String(a))??cW(a)}function cY(a,b={}){let c=a.value,d=b.semverParsingPolicy??"strict";switch(a.operator||"exact"){case"exact":case"is_not":for(let a of Array.isArray(c)?c:[c])cM(a);return;case"is_set":case"is_not_set":case"icontains":case"not_icontains":case"starts_with":case"not_starts_with":case"ends_with":case"not_ends_with":case"regex":case"not_regex":case"gt":case"gte":case"lt":case"lte":return;case"is_date_after":case"is_date_before":cX(c);return;case"semver_eq":case"semver_neq":case"semver_gt":case"semver_gte":case"semver_lt":case"semver_lte":cR(String(c),d);return;case"semver_tilde":cT(String(c),d);return;case"semver_caret":cU(String(c),d);return;case"semver_wildcard":cV(String(c),d);return;default:throw new cF(`Unknown operator: ${a.operator}`)}}async function cZ(a){let b=globalThis.crypto?.subtle;if(!b)throw Error("SubtleCrypto API not available");return Array.from(new Uint8Array(await b.digest("SHA-1",new TextEncoder().encode(a)))).map(a=>a.toString(16).padStart(2,"0")).join("")}async function c$(a,b,c="",d="."){return parseInt((await cZ(`${a}${d}${b}${c}`)).slice(0,15),16)/0x1000000000000000}async function c_(a,b){if(null==a||null==a.id||null==a.exclusion_percentage)return;let c=Number(a.exclusion_percentage);if(!Number.isFinite(c))return;let d=Math.min(Math.max(c,0),100);if(!(100!==d&&await c$("holdout",b,"","-")>d/100))return`holdout-${a.id}`}function c0(a){let b=[],c=0;for(let d of a){let a=c+d.rollout_percentage/100;b.push({valueMin:c,valueMax:a,key:d.key}),c=a}return b}async function c1(a,b,c){let d=await c$(a,b,"variant");return c0(c).find(a=>d>=a.valueMin&&d<a.valueMax)?.key}function c2(a){return"client"===a||"server"===a?a:"all"}class c3 extends Error{constructor(a){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=a,Object.setPrototypeOf(this,c3.prototype)}}class c4 extends Error{constructor(a){super(a),this.reason="unsupported_definition",this.name=c4.name,Error.captureStackTrace(this,c4),Object.setPrototypeOf(this,c4.prototype)}}let c5=["experience_continuity","unsupported_definition","unresolved_dependency","missing_context"];function c6(a,b){return void 0===a||c5.indexOf(b)<c5.indexOf(a)?b:a}function c7(a,b){return b instanceof cF&&Symbol.for("posthog.requiresServerRegexEvaluation")in b&&Object.defineProperty(a,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),a}class c8{constructor({pollingInterval:a,personalApiKey:b,projectApiKey:c,timeout:d,host:e,customHeaders:f,...g}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.warnedUnresolvableFlags=new Map,this.pollingInterval=a,this.personalApiKey=b,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=d,this.projectApiKey=c,this.host=e,this.poller=void 0,this.fetch=g.fetch||fetch,this.onError=g.onError,this.customHeaders=f,this.onLoad=g.onLoad,this.onMinimalFlagCalledEvents=g.onMinimalFlagCalledEvents,this.cacheProvider=g.cacheProvider,this.strictLocalEvaluation=g.strictLocalEvaluation??!1,this.evaluationContexts=g.evaluationContexts,this.loadFeatureFlags()}debug(a=!0){this.debugMode=a}logMsgIfDebug(a){this.debugMode&&a()}currentDefinitions(){return{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}withEvaluationSnapshot(a){return a.definitions?a:{...a,evaluationCache:{},definitions:this.currentDefinitions()}}createEvaluationContext(a,b={},c={},d={},e={}){return{distinctId:a,groups:b,personProperties:c,groupProperties:d,evaluationCache:e}}async getFeatureFlag(a,b,c={},d={},e={}){let f,g;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return f;if(void 0!==(g=this.featureFlagsByKey[a])){let h=this.createEvaluationContext(b,c,d,e);try{f=(await this.computeFlagAndPayloadLocally(g,h)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${a} -> ${f}`))}catch(b){b instanceof c4||b instanceof cF?this.logMsgIfDebug(()=>console.debug(`${b.name} when computing flag locally: ${a}: ${b.message}`)):b instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${a}: ${b}`))}}return f}async getAllFlagsAndPayloads(a,b){await this.loadFeatureFlags();let c={},d={},e={},f=0==this.featureFlags.length,g=b?b.map(a=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,h=this.withEvaluationSnapshot({...a,definitions:void 0});return await Promise.all(g.map(async a=>{try{let{value:b,payload:e}=await this.computeFlagAndPayloadLocally(a,h,{skipLoadCheck:!0});c[a.key]=b,e&&(d[a.key]=e)}catch(b){b instanceof c4||b instanceof cF?(this.logMsgIfDebug(()=>console.debug(`${b.name} when computing flag locally: ${a.key}: ${b.message}`)),e[a.key]=b.reason):b instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${a.key}: ${b}`)),f=!0}})),{response:c,payloads:d,unresolved:e,fallbackToFlags:f}}async computeFlagAndPayloadLocally(a,b,c={}){let d,{matchValue:e,skipLoadCheck:f=!1}=c;if(this.loadedSuccessfullyOnce&&(b=this.withEvaluationSnapshot(b)),f||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};a=(b=this.withEvaluationSnapshot(b)).definitions.featureFlagsByKey[a.key]??a,d=void 0!==e?e:await this.computeFlagValueLocally(a,b);let g=function(a,b){if(!1===b||null==b||!a)return null;let c=a["boolean"==typeof b?b.toString():b]||null;return null==c?null:a4(c)}(a.filters?.payloads,d);return{value:d,payload:g}}async computeFlagValueLocally(a,b){let{distinctId:c,groups:d,personProperties:e,groupProperties:f}=b;if(!a.active)return!1;if(a.ensure_experience_continuity)throw new cF("Flag has experience continuity enabled","experience_continuity");let g=(a.filters||{}).aggregation_group_type_index;if(void 0!=g){let c=b.definitions.groupTypeMapping[String(g)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${g} for feature flag ${a.key}`)),new cF("Flag has unknown group type index");if(!(c in d))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${a.key} without group names passed in`)),!1;"device_id"===a.bucketing_identifier&&(e?.$device_id===void 0||e?.$device_id===null||e?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${a.key}`));let h=f[c];return await this.matchFeatureFlagProperties(a,d[c],h,b)}{let d=this.getBucketingValueForFlag(a,c,e);if(void 0===d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${a.key} without $device_id, falling back to server evaluation`)),new cF(`Can't compute feature flag: ${a.key} without $device_id`,c9(a,b.definitions)??"missing_context");return await this.matchFeatureFlagProperties(a,d,e,b)}}getBucketingValueForFlag(a,b,c){if(a.filters?.aggregation_group_type_index!=void 0)return b;if("device_id"===a.bucketing_identifier){let a=c?.$device_id;if(null==a||""===a)return;return a}return b}async evaluateFlagDependency(a,b,c){let{evaluationCache:d}=c,e=a.key;if(!c.definitions.featureFlagsByKey)throw new cF("Feature flags not available for dependency evaluation");if(!("dependency_chain"in a))throw new cF(`Flag dependency property for '${e}' is missing required 'dependency_chain' field`);let f=a.dependency_chain;if(!Array.isArray(f))throw new cF(`Flag dependency property for '${e}' has an invalid 'dependency_chain' (expected array, got ${typeof f})`);if(0===f.length)throw new cF(`Circular dependency detected for flag '${e}' (empty dependency chain)`);let g=f.find(a=>!(a in d)&&!c.definitions.featureFlagsByKey[a]&&!c.definitions.filteredOutFlagKeys.has(a));if(void 0!==g)throw new cF(`Missing flag dependency '${g}' for flag '${e}'`);for(let a of f){if(!(a in d)){let b=c.definitions.featureFlagsByKey[a];if(b)if(b.active)try{let e=await this.computeFlagValueLocally(b,c);d[a]=e}catch(b){throw c7(new cF(`Error evaluating flag dependency '${a}' for flag '${e}': ${b}`,"unresolved_dependency"),b)}else d[a]=!1;else d[a]=!1}if(null==d[a])throw new cF(`Dependency '${a}' could not be evaluated`,"unresolved_dependency")}let h=d[e];return this.flagEvaluatesToExpectedValue(a.value,h)}flagEvaluatesToExpectedValue(a,b){return"boolean"==typeof a?a===b||"string"==typeof b&&""!==b&&!0===a:"string"==typeof a&&b===a}async matchFeatureFlagProperties(a,b,c,d){let e,f,g;d=this.withEvaluationSnapshot(d);let h=a.filters||{},i=await c_(h.holdout,b);if(void 0!==i)return i;let j=h.groups||[],k=h.aggregation_group_type_index,l=h.early_exit??!1,{groups:m,groupProperties:n}=d,o=new Set;for(let i of j){let j=b;try{let b=void 0!==i.aggregation_group_type_index?i.aggregation_group_type_index:k,f=c;if(b!==k&&null!=b){let c=d.definitions.groupTypeMapping[String(b)];if(!c||!(c in m)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${a.key}': group type index ${b} not available`));continue}if(!(c in n)){e=c6(e,"missing_context");continue}f=n[c],j=m[c]}let o=await this.isConditionMatch(a,j,i,f,d);if("match"===o){let b=i.variant,c=h.multivariate?.variants||[];g=b&&c.some(a=>a.key===b)?b:await this.getMatchingVariant(a,j)||!0;break}if(l&&"out_of_rollout_bound"===o){if(e)break;return!1}}catch(b){if(b instanceof c4)throw b;if(b instanceof cF){if(e=c6(e,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b)if(f=b,l&&void 0!=i.rollout_percentage&&await c$(a.key,j)>i.rollout_percentage/100)o.add(!1);else{let b=h.multivariate?.variants||[],c=i.variant;o.add(c&&b.some(a=>a.key===c)?c:await this.getMatchingVariant(a,j)||!0)}}else throw b}}if(void 0!==g&&!(f&&[...o].some(a=>a!==g)))return g;if(e)throw c7(new cF("Can't determine if feature flag is enabled or not with given properties",e),f);return!1}async isConditionMatch(a,b,c,d,e){let f=(e=this.withEvaluationSnapshot(e)).definitions,g=c.rollout_percentage,h=a=>{this.logMsgIfDebug(()=>console.warn(a))};if((c.properties||[]).length>0){let b,i,j;for(let a of c.properties){let c=a.type,g=!1;try{if("cohort"===c){let b=await db(a,d,f.cohorts,this.debugMode,a=>this.evaluateFlagDependency(a,d,e),f.propertyMatchingVersion);g="not_in"===a.operator?!b:b}else if("flag"===c)g=await this.evaluateFlagDependency(a,d,e);else if(Object.prototype.hasOwnProperty.call(d,a.key))g=da(a,d,h,f.propertyMatchingVersion);else{cY(a),b=c6(b,"missing_context");continue}}catch(a){if(a instanceof c4){void 0===b&&(j??=a),b=c6(b,a.reason);continue}if(a instanceof cF){Symbol.for("posthog.requiresServerRegexEvaluation")in a&&(i=a),b=c6(b,a.reason);continue}throw a}if(!g)return"no_match"}if(j)throw j;if(b)throw c7(new cF(`Can't determine if a condition of flag ${a.key} matches`,b),i);if(void 0==g)return"match"}return void 0!=g&&await c$(a.key,b)>g/100?"out_of_rollout_bound":"match"}async getMatchingVariant(a,b){return c1(a.key,b,a.filters?.multivariate?.variants||[])}variantLookupTable(a){return c0(a.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(a){if(!this.evaluationContexts||0===this.evaluationContexts.length)return a;let b=new Set(this.evaluationContexts);return a.filter(a=>{let c=a.evaluation_contexts??a.evaluation_tags;return!c||0===c.length||c.some(a=>b.has(a))})}getEvaluationRuntimeForFlag(a){let b=this.featureFlagsByKey[a];return b?c2(b.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(a){return this.featureFlags.filter(b=>{var c;return(c=c2(b.evaluation_runtime))===a||"all"===c||"all"===a}).map(a=>a.key)}updateFlagState(a){let b=this.filterFlagsByEvaluationContexts(a.flags),c=b.reduce((a,b)=>(a[b.key]=b,a),{}),d=new Set(b.map(a=>a.key)),e=new Set(a.flags.filter(a=>!d.has(a.key)).map(a=>a.key));this.featureFlags=b,this.featureFlagsByKey=c,this.filteredOutFlagKeys=e,this.groupTypeMapping=a.group_type_mapping??a.groupTypeMapping??{},this.cohorts=a.cohorts,this.propertyMatchingVersion=a.property_matching_version??a.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((a.minimal_flag_called_events??a.minimalFlagCalledEvents)===!0)}warnAboutUnresolvableFlags(a){let b=[],c=[],d=new Map,e=this.currentDefinitions();for(let f of a){let a=c9(f,e);if(!a)continue;let g=JSON.stringify(f);d.set(f.key,g),this.warnedUnresolvableFlags.get(f.key)!==g&&("experience_continuity"===a?b.push(f.key):c.push(f.key))}if(this.warnedUnresolvableFlags=d,b.length>0){let a=this.strictLocalEvaluation?"With strictLocalEvaluation enabled these flags are left unresolved. To evaluate them locally, disable experience continuity on these flags in PostHog.":"Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).";console.warn(`[PostHog] You are using local evaluation but ${b.length} flag(s) have experience continuity enabled and cannot be resolved locally (reason: experience_continuity): ${b.join(", ")}. `+a)}if(c.length>0){let a=this.strictLocalEvaluation?"With strictLocalEvaluation enabled these flags are left unresolved when evaluation reaches that part.":"Evaluating these flags falls back to a server request when evaluation reaches that part.";console.warn(`[PostHog] You are using local evaluation but ${c.length} flag(s) use something local evaluation does not support, such as a static cohort, an unknown operator, or a missing or circular flag dependency (reason: unsupported_definition): ${c.join(", ")}. ${a} To evaluate them locally, change these flags in PostHog or upgrade posthog-node.`)}}async loadFromCache(a){if(!this.cacheProvider)return!1;try{let b=await this.cacheProvider.getFlagDefinitions();if(b)return this.updateFlagState(b),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${a} (${b.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags),!0;return!1}catch(a){return this.onError?.(Error(`Failed to load from cache: ${a}`)),!1}}async loadFeatureFlags(a=!1){if(!this.loadedSuccessfullyOnce||a)return!a&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(a=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${a}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let a=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(6e4,a*2**this.backOffCount):a}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{if(this.cacheProvider&&!this.personalApiKey)return void await this.loadFromCache("Loaded flags from cache (cache-only reader)");let a=!0;if(this.cacheProvider)try{a=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(a){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${a}`))}if(!a&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let b=await this._requestFeatureFlagDefinitions();if(!b)return;switch(b.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=b.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new c3(`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 c3(`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 c3(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let c=await b.json()??{};if(!("flags"in c))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(c)}`));this.flagsEtag=b.headers?.get("ETag")??void 0;let d=c.group_type_mapping||{},e=!0===c.minimal_flag_called_events,f={flags:c.flags??[],group_type_mapping:d,cohorts:c.cohorts||{},minimal_flag_called_events:e,property_matching_version:c.property_matching_version,propertyMatchingVersion:c.property_matching_version,groupTypeMapping:d,minimalFlagCalledEvents:e};if(this.updateFlagState(f),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&a)try{await this.cacheProvider.onFlagDefinitionsReceived(f)}catch(a){this.onError?.(Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags);break}default:return}}catch(a){a instanceof c3&&this.onError?.(a)}finally{this.pollerStopped||null===this.pollingInterval||(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(a="GET",b){let c={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return b&&(c["If-None-Match"]=b),{method:a,headers:c}}async _requestFeatureFlagDefinitions(){if(!this.personalApiKey)throw new c3("A secretKey or personalApiKey is required to fetch feature flag definitions from PostHog.");let a=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,b=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),c=null;if(this.timeout&&"number"==typeof this.timeout){let a=new AbortController;c=R(()=>{a.abort()},this.timeout),b.signal=a.signal}try{let d=this.fetch,e=await d(a,b);if(200!==e.status)return clearTimeout(c),e;return{status:e.status,headers:e.headers,body:e.body,text:async()=>{try{return await e.text()}finally{clearTimeout(c)}},json:async()=>{try{return await e.json()}finally{clearTimeout(c)}}}}catch(a){throw clearTimeout(c),a}}async stopPoller(a=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let b=this.cacheProvider.shutdown();b instanceof Promise&&await S(b,a,()=>{throw Error(`Cache shutdown timeout after ${a}ms`)})}catch(a){this.onError?.(Error(`Error during cache shutdown: ${a}`))}}}function c9(a,b){if(!a.active)return;if(a.ensure_experience_continuity)return"experience_continuity";let c=a.filters||{},d=c.aggregation_group_type_index;return void 0==d||b.groupTypeMapping[String(d)]?(c.groups||[]).some(a=>(a.properties||[]).some(a=>(function a(b,c,d){if("flag"===b.type){let a=b.dependency_chain;return!Array.isArray(a)||0===a.length||a.some(a=>!c.featureFlagsByKey[a]&&!c.filteredOutFlagKeys.has(a))}if("cohort"!==b.type)try{return cY(b),!1}catch(a){if(a instanceof cF)return!0;throw a}let e=String(b.value);return!(e in c.cohorts)||!d.has(e)&&(d.add(e),function b(c,d,e){return(c?.values??[]).some(c=>"values"in c?b(c,d,e):a(c,d,e))}(c.cohorts[e],c,d))})(a,b,new Set)))?"unsupported_definition":void 0:"unsupported_definition"}function da(a,b,c,d){return function(a,b,c={}){try{return function(a,b,c){let d=a.key,e=a.value,f=a.operator||"exact",g=c.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(b,d)){if("is_not_set"===f)return!1;else if("is_set"===f)return!0}else throw new cF(`Property ${d} not found in propertyValues`,"missing_context");let h=b[d];if(void 0===h)throw c.warnFunction?.(`Property ${d} cannot have a value of undefined with the ${f} operator`),new cF(`Property ${d} is undefined in propertyValues`);if(null===h&&!cE.includes(f))return c.warnFunction?.(`Property ${d} cannot have a value of null with the ${f} operator`),!1;let i=(a,b)=>{if(2!==c.propertyMatchingVersion&&cH(a)||Array.isArray(a)&&0===a.length)return cG(()=>cK(b)),cI(a)===cI(b);if(2===c.propertyMatchingVersion&&"number"==typeof b&&cH(a))return cG(()=>cK(b)),!1;if(Array.isArray(a)){let c=cG(()=>cM(b)).toLowerCase();return a.some(a=>cM(a).toLowerCase()===c)}return cM(a).toLowerCase()===cG(()=>cM(b)).toLowerCase()},j=(a,b,c)=>{if("gt"===c)return a>b;if("gte"===c)return a>=b;if("lt"===c)return a<b;if("lte"===c)return a<=b;throw Error(`Invalid operator: ${c}`)},k=()=>cG(()=>cR(String(h),g)),l=()=>{let a=cR(String(e),g);return cS(k(),a)},m=({lower:a,upper:b})=>{let c=k();return cS(c,a)>=0&&0>cS(c,b)};switch(f){case"exact":return i(e,h);case"is_not":return!i(e,h);case"is_set":return!0;case"icontains":return cP(h).includes(cP(e));case"not_icontains":return!cP(h).includes(cP(e));case"starts_with":return cP(h).startsWith(cP(e));case"not_starts_with":return!cP(h).startsWith(cP(e));case"ends_with":return cP(h).endsWith(cP(e));case"not_ends_with":return!cP(h).endsWith(cP(e));case"regex":case"not_regex":{let a=function(a,b){let c;if(""===a)return!0;let d=function(a){let b=[],c=-1,d="";for(let e=0;e<a.length;e++){let f=a[e];if(f.charCodeAt(0)>127)return null;if("\\"===f){let b=a[++e];if(void 0===b)break;if("x"===b){if(!/^[\da-f]{2}$/i.test(a.slice(e+1,e+3)))return null;e+=2}else if(!"dDsSwWbBfnrtv".includes(b)&&!cN.test(b))return null;if(-1===c&&"bB".includes(b))return null;d="literal";continue}if("["===f){if(-1!==c)return null;c=e}else if("]"===f&&-1!==c){if(e===c+("^"===a[c+1]?2:1))return null;b.push(a.slice(c,e+1)),c=-1,d="literal";continue}else if(-1!==c){if(["&&","--","~~"].includes(a.slice(e,e+2)))return null;continue}else if("("===f&&"?"===a[e+1]){if(":"!==a[e+2])return null;e+=2}else if("{"===f){let b=/^\{(\d+)(?:,(\d*))?\}/.exec(a.slice(e));if(!b||["","|","("].includes(d)||b.slice(1).some(a=>Number(a)>0xffffffff))return null}else if("*+?}".includes(f)&&("+"===a[e+1]||"{"===a[e+1]))return null;if("*+?{".includes(f)&&["^","$","empty group"].includes(d))return null;d=")"===f&&["(","empty group"].includes(d)?"empty group":f}return b}(a);if(null===d)throw cO("Regex syntax requires server evaluation");try{c=new RegExp(a)}catch(a){if(a instanceof SyntaxError)return null;throw cO("Regex compilation requires server evaluation")}for(let a of d)try{RegExp(a,"u")}catch{throw cO("Regex character class syntax requires server evaluation")}for(let a=0;a<b.length;a++){let c=b[a];if(c.charCodeAt(0)>127||"\r"===c)throw cO("Regex matching for Unicode or carriage returns requires server evaluation")}try{return c.test(b)}catch{throw cO("Regex execution requires server evaluation")}}(String(e),String(h));if(null===a)return!1;return"regex"===f?a:!a}case"gt":case"gte":case"lt":case"lte":{let a="number"==typeof e?e:parseFloat(String(e)),b="number"==typeof h?h:null!=h?parseFloat(String(h)):0/0;if(Number.isFinite(a)&&Number.isFinite(b))return j(b,a,f);return j(String(h),String(e),f)}case"is_date_after":case"is_date_before":{let a=cX(e),b=cG(()=>cW(h));return"is_date_before"===f?b<a:b>a}case"semver_eq":return 0===l();case"semver_neq":return 0!==l();case"semver_gt":return l()>0;case"semver_gte":return l()>=0;case"semver_lt":return 0>l();case"semver_lte":return 0>=l();case"semver_tilde":return m(cT(String(e),g));case"semver_caret":return m(cU(String(e),g));case"semver_wildcard":return m(cV(String(e),g));default:throw new cF(`Unknown operator: ${f}`)}}(a,b,c)}catch(b){throw b instanceof cF&&"missing_context"===b.reason&&cY(a,c),b}}(a,b,{warnFunction:c,propertyMatchingVersion:d})}async function db(a,b,c,d=!1,e,f){let g=String(a.value);if(!(g in c))throw new c4(`cohort ${g} not found in local cohorts - likely a static cohort that requires server evaluation`);return dc(c[g],b,c,d,e,f)}async function dc(a,b,c,d=!1,e,f){let g,h;if(!a)return!0;let i=a.type,j=a.values;if(!j||0===j.length)return!0;if("values"in j[0]){for(let a of j)try{let g=await dc(a,b,c,d,e,f);if("AND"===i){if(!g)return!1}else if(g)return!0}catch(b){if(b instanceof c4)throw b;if(b instanceof cF)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),g=c6(g,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b&&(h=b);else throw b}if(g)throw c7(new cF("Can't match cohort without a given cohort property value",g),h);return"AND"===i}for(let a of j)try{let g;if("cohort"===a.type)g=await db(a,b,c,d,e,f);else if("flag"===a.type){if(!e)throw new cF(`Flag dependency '${a.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);g=await e(a)}else g=da(a,b,void 0,f);let h=a.negation||!1;if("AND"===i){if(!g&&!h||g&&h)return!1}else if(g&&!h||!g&&h)return!0}catch(b){if(b instanceof c4)throw b;if(b instanceof cF)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),g=c6(g,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b&&(h=b);else throw b}if(g)throw c7(new cF("can't match cohort without a given cohort property value",g),h);return"AND"===i}let dd=["--unhandled-rejections","--unhandled_rejections"],de=new Set(["throw","strict","warn","warn-with-error-code","none"]),df=[...globalThis.process?.execArgv??[]],dg=globalThis.process?.env?.NODE_OPTIONS;function dh(a){let b;for(let c=0;c<a.length;c++){let d=a[c],e=dd.find(a=>d===a||d.startsWith(`${a}=`));if(!e)continue;let f=d===e?a[++c]:d.slice(e.length+1);de.has(f)&&(b=f)}return b}let di=function(a=df,b=dg){return dh(a)??dh(function(a){let b=[],c="",d=!1;for(let e=0;e<a.length;e++){let f=a[e];"\\"===f&&d&&e+1<a.length?c+=a[++e]:" "!==f||d?'"'===f?d=!d:c+=f:c&&(b.push(c),c="")}return c&&b.push(c),b}(b??""))??"throw"}();function dj(a,b,c){a(b,{mechanism:{type:"unhandledRejection"===c?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function dk(a,b,c,d,e){if(b>c&&(d.warn("min cannot be greater than max."),b=c),y(a))if(a>c)return d.warn(" cannot be greater than max: "+c+". Using max value instead."),c;else return a<b?(d.warn(" cannot be less than min: "+b+". Using min value instead."),b):a;return d.warn(" must be a number. using max or fallback. max: "+c+", fallback: "+e),dk(e??c,b,c,d)}class dl{constructor(a){this._buckets={},this._onBucketRateLimited=a._onBucketRateLimited,this._bucketSize=dk(a.bucketSize,0,100,a._logger),this._refillRate=dk(a.refillRate,0,this._bucketSize,a._logger),this._refillInterval=dk(a.refillInterval,0,864e5,a._logger)}_applyRefill(a,b){let c=Math.floor((b-a.lastAccess)/this._refillInterval);if(c>0){let b=c*this._refillRate;a.tokens=Math.min(a.tokens+b,this._bucketSize),a.lastAccess=a.lastAccess+c*this._refillInterval}}consumeRateLimit(a){let b=Date.now(),c=String(a),d=this._buckets[c];return d?this._applyRefill(d,b):(d={tokens:this._bucketSize,lastAccess:b},this._buckets[c]=d),0===d.tokens||(d.tokens--,0===d.tokens&&this._onBucketRateLimited?.(a),0===d.tokens)}stop(){this._buckets={}}}var dm=aS;let dn=class b{constructor(a,b,c){this.client=a,this._exceptionAutocaptureEnabled=b.enableExceptionAutocapture||!1,this._logger=c,this._rateLimiter=new dl({...function(a={}){return{refillRate:a.exceptionRateLimiterRefillRate??a.__exceptionRateLimiterRefillRate??1,bucketSize:a.exceptionRateLimiterBucketSize??a.__exceptionRateLimiterBucketSize??10}}(b),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(a){return s(a)&&"__posthog_previously_captured_error"in a&&!0===a.__posthog_previously_captured_error}static async buildEventMessage(a,b,c,d,e){let f={...e},g=a.buildFromUnknown(b,c);g.$exception_list=await a.modifyFrames(g.$exception_list);let h=dm.getInjectedReleaseId();return h&&(f.$release_id=h),{event:"$exception",distinctId:d,properties:{...g,...f},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(!function(b,c,d=di){let e=globalThis.process;if(e){let f;if("strict"===d)return e.on("uncaughtExceptionMonitor",(a,c)=>dj(b,a,c));e.on("uncaughtException",(f=!1,Object.assign((d,e)=>{let g=a.g.process.listeners("uncaughtException").filter(a=>"domainUncaughtExceptionClear"!==a.name&&!0!==a._posthogErrorHandler).length;dj(b,d,e),f||0!==g||(f=!0,c(d))},{_posthogErrorHandler:!0})))}}(this.onException.bind(this),this.onFatalError.bind(this)),function(a,b=di){let c=globalThis.process;c&&"throw"!==b&&"strict"!==b&&"warn-with-error-code"!==b&&c.on("unhandledRejection",b=>{a(b,{mechanism:{type:"onunhandledrejection",handled:!1}})})}(this.onException.bind(this)))}onException(a,c){this.client.addPendingPromise((async()=>{if(!b.isPreviouslyCapturedError(a)){let d=await b.buildEventMessage(this.client.getErrorPropertiesBuilder(),a,c),e=d.properties,f=e?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(f)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:f}):this.client._capturePreparedEvent(d,!1)}})())}async onFatalError(a){console.error(a),await this.client.shutdown(2e3),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},dp=/^[0-9a-f]{32}$/i,dq=/^[0-9a-f]{16}$/i;async function dr(){try{let b=await (h??=a.A(38676)),c=b.trace.getActiveSpan()?.spanContext(),d=c?.traceId,e=c?.spanId;if("string"==typeof d&&"string"==typeof e&&dp.test(d)&&dq.test(e)&&!/^0+$/.test(d)&&!/^0+$/.test(e))return{$trace_id:d.toLowerCase(),$span_id:e.toLowerCase()}}catch{}return{}}class ds{getProperty(a){return this._memoryStorage[a]}setProperty(a,b){this._memoryStorage[a]=null!==b?b:void 0}constructor(){this._memoryStorage={}}}let dt="analytics";class du extends Error{constructor({requestId:a,drops:b,retryExhausted:c,cause:d}){super(du.buildMessage(a,b,c,d)),this.name="CaptureV1Error",this.requestId=a,this.drops=b,this.retryExhausted=c,this.cause=d}static buildMessage(a,b,c,d){let e=`Capture V1 batch ${a} did not fully deliver: ${b.length} dropped, ${c.length} undelivered`;return d instanceof Error&&(e+=` (${d.message})`),e}}function dv(a){if("boolean"==typeof a)return a;if("number"==typeof a)return 0!==a;if("string"==typeof a){let b=a.trim().toLowerCase();if("true"===b||"1"===b)return!0;if("false"===b||"0"===b)return!1}}let dw=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:dv},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:dv},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:dv},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(a){return"string"==typeof a?a:void 0}}],dx=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function dy(a,b,c){void 0===c||b in a||(a[b]=c)}function dz(a){var b;let c={..."object"==typeof(b=a.properties)&&null!==b&&!Array.isArray(b)?a.properties:{}},d={};for(let{property:a,optionKey:b,coerce:e}of dw)if(a in c){let f=e(c[a]);void 0!==f&&(d[b]=f),delete c[a]}let e={};for(let{property:a,field:b}of dx)if(a in c){let d=c[a];"string"==typeof d&&(e[b]=d),delete c[a]}return delete c.$lib,delete c.$lib_version,dy(c,"$set",a.$set),dy(c,"$set_once",a.$set_once),{event:String(a.event??""),uuid:String(a.uuid??""),distinct_id:String(a.distinct_id??""),timestamp:function(a){if("string"==typeof a){let b=new Date(a);if(Number.isNaN(b.getTime()))return new Date().toISOString();let c=b.toISOString(),d=a.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return d&&d.length>3?c.replace(/\.\d{3}Z$/,`.${d}Z`):c}if(a instanceof Date)return Number.isNaN(a.getTime())?new Date().toISOString():a.toISOString();let b=null==a?new Date:new Date(a);return Number.isNaN(b.getTime())?new Date().toISOString():b.toISOString()}(a.timestamp),...e,options:d,properties:c}}let dA=new Set([408,500,502,503,504]);class dB{constructor(a,b){this.config=a,this.maxBackoffMs=a.maxBackoffMs??3e4,this.fetchFn=b.fetch,this.onError=b.onError,this.now=b.now??Date.now,this.sleep=b.sleep??(a=>new Promise(b=>R(b,a))),this.generateRequestId=b.generateRequestId??aX,this.compress=b.compress??ba}async sendV1Batch(a){if(0===a.length)return;let b=this.generateRequestId(),c=new Date(this.now()).toISOString(),{batch:d}=function(a,{createdAt:b,historicalMigration:c}){let d={created_at:b,batch:a.map(dz)};return c&&(d.historical_migration=!0),d}(a,{createdAt:c,historicalMigration:this.config.historicalMigration}),e=`${this.config.host}/i/v1/analytics/events`,f=[],g=d,h=Math.max(1,this.config.maxAttempts);for(let a=1;a<=h;a++){let d,i,j=a===h,k=n({created_at:c,...this.config.historicalMigration?{historical_migration:!0}:{},batch:g});try{let{response:c,signal:h}=d=await this.sendOnce(e,k,a,b),{status:l}=c;if(l<200||l>=300)if(!j&&dA.has(l)){let b=this.parseRetryAfter(c);await d.waitFor(d.cancelBody()).catch(()=>{}),i=this.backoffDelay(a,b)}else{let a=await this.buildHttpError(c,l,d.waitFor);return this.surfaceBatchFailure(b,f,g,a)}else{let e;try{e=await d.waitFor(this.parseResponse(c))}catch(a){if(h.aborted)throw a;return this.surfaceBatchFailure(b,f,g,Error(`Capture V1 returned an unparseable ${l} response body`))}let k=this.classify(g,e,f);if(0===k.length)return this.surfacePartialDrops(b,f);if(j)return void this.onError(new du({requestId:b,drops:f,retryExhausted:k.map(a=>a.uuid)}));g=k;let m=this.parseRetryAfter(c);i=this.backoffDelay(a,m)}}catch(c){if(d&&!d.signal.aborted)throw c;if(j)return this.surfaceBatchFailure(b,f,g,c);i=this.backoffDelay(a)}finally{d?.cleanup()}void 0!==i&&await this.sleep(i)}}async sendOnce(a,b,c,d){let e,f=this.buildHeaders(c,d),g=b;if(this.config.compressionEnabled){let a=await this.compress(b,this.config.isDebug);null!==a&&(g=a,f["Content-Encoding"]="gzip")}let h=new AbortController,i="waiting for response headers",j=new Promise((a,b)=>{e=R(()=>{let a=Error(`Capture V1 request timed out ${i} after ${this.config.requestTimeoutMs}ms`);a.name="AbortError",b(a),h.abort(a)},this.config.requestTimeoutMs)});try{let b,c=this.fetchFn(a,{method:"POST",headers:f,body:g,signal:h.signal}),d=!1;c.then(a=>{h.signal.aborted&&!d&&this.cancelBody(a)}).catch(()=>{});let k=await Promise.race([c,j]);d=!0,i="while reading the response body";let l=!1,m=()=>b??=this.cancelBody(k);return{response:k,signal:h.signal,waitFor:a=>Promise.race([a,j]),cancelBody:m,cleanup:()=>{!l&&(l=!0,clearTimeout(e),h.signal.aborted&&m())}}}catch(a){throw clearTimeout(e),a}}buildHeaders(a,b){let c=`${this.config.libraryId}/${this.config.libraryVersion}`,d={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":c,"PostHog-Attempt":String(a),"PostHog-Request-Id":b,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(d["User-Agent"]=this.config.userAgent),d}classify(a,b,c){let d=b.results??{},e=[];for(let b of a){let a=d[b.uuid];a&&("drop"===a.result?c.push({uuid:b.uuid,details:a.details??void 0}):"retry"===a.result&&e.push(b))}return e}backoffDelay(a,b){let c=Math.min(this.config.initialRetryDelayMs*2**(a-1),this.maxBackoffMs);return void 0===b?c:Math.max(c,Math.min(b,this.maxBackoffMs))}parseRetryAfter(a){let b=a.headers?.get("Retry-After");if(!b)return;let c=b.trim();if(/^\d+$/.test(c)){let a=parseInt(c,10);return Number.isFinite(a)&&a>0?1e3*a:void 0}let d=Date.parse(c);if(Number.isNaN(d))return;let e=d-this.now();return e>0?e:void 0}async parseResponse(a){let b=JSON.parse(await a.text());if("object"!=typeof b||null===b||Array.isArray(b))throw Error("unexpected response shape");let c=b.results;if(void 0!==c&&("object"!=typeof c||null===c||Array.isArray(c)))throw Error("unexpected results shape");return{results:c??{}}}async buildHttpError(a,b,c){let d="";try{d=(await c(a.text())).slice(0,512)}catch{}let e=d?`: ${d}`:"";return Error(`Capture V1 request failed with HTTP ${b}${e}`)}surfaceBatchFailure(a,b,c,d){this.onError(new du({requestId:a,drops:b,retryExhausted:c.map(a=>a.uuid),cause:d}))}surfacePartialDrops(a,b){b.length>0&&this.onError(new du({requestId:a,drops:b,retryExhausted:[]}))}async cancelBody(a){try{await a.body?.cancel()}catch{}}}let dC="ai-capture",dD="/i/v0/ai/batch/",dE=new TextEncoder;function dF(a){return dE.encode(n(a)).length}let dG=new Set;function dH(a,b){dG.has(a)||(dG.add(a),console.warn(`[PostHog] ${b}`))}class dI extends bo{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(a){this._distinctIdHasSentFlagCalls=new Map(Object.entries(a??{}))}constructor(a,b={}){var c,d;let e,f="string"==typeof a?a.trim():"",g={...b,maxQueueSize:b.maxQueueSize??1e4,flushInterval:b.flushInterval??5e3,host:("string"==typeof(c=b.host)?c.trim():"")||"https://us.i.posthog.com",personalApiKey:("string"==typeof(d=b.secretKey??b.personalApiKey)?d.trim():"")||void 0};if(super(f,g),this._memoryStorage=new ds,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=g,this.captureMode="v0"===(e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0)||"v1"===e?e:"v0",this.enableFullAiCapture=!0===g.enableFullAiCapture,this.privacyMode=!0===g.privacyMode,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof g.featureFlagsPollingInterval?Math.max(g.featureFlagsPollingInterval,100):null===g.featureFlagsPollingInterval?null:3e4,"number"==typeof g.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(g.waitUntilDebounceMs,0)),"number"==typeof g.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(g.waitUntilMaxWaitMs,0)),!this.disabled&&(g.personalApiKey||g.flagDefinitionCacheProvider)){if(g.personalApiKey?.includes("phc_"))throw Error('A project API key ("phc_...") was provided as secretKey or personalApiKey. Pass the project API key as the first constructor argument. For local evaluation, set secretKey (or the deprecated personalApiKey alias) to a server-only Project Secret API Key ("phs_...") or Personal API Key ("phx_...") with feature flag read access.');!1!==g.enableLocalEvaluation&&(this.featureFlagsPoller=new c8({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:g.personalApiKey,projectApiKey:f,timeout:g.requestTimeout??1e4,host:this.host,fetch:g.fetch,onError:a=>{this._events.emit("error",a)},onLoad:a=>{this._events.emit("localEvaluationFlagsLoaded",a)},onMinimalFlagCalledEvents:a=>{this._minimalFlagCalledEvents=a},customHeaders:this.getCustomHeaders(),cacheProvider:g.flagDefinitionCacheProvider,strictLocalEvaluation:g.strictLocalEvaluation,evaluationContexts:g.evaluationContexts??g.evaluationEnvironments}))}this.errorTracking=new dn(this,g,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=g.maxCacheSize||5e4}enqueue(a,b,c,d){super.enqueue(a,b,c,d),this.scheduleDebouncedFlush()}_flushEventsAndSpans(a=!1){let b=this.flushWithPendingPromises();return!this._traces||a&&this._traces.throttled?b:T([b,this._traces.flush().catch(()=>{})]).then(([a])=>{if("rejected"===a.status)throw a.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(a){let b=this._flushEventsAndSpans(a),c=this.options.waitUntil;if(c&&!this._waitUntilCycle)try{c(b.catch(()=>{}))}catch{}return b}scheduleDebouncedFlush(){let a=this.options.waitUntil;if(!a||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let b,c=new Promise(a=>{b=a});try{a(c)}catch{return}this._waitUntilCycle={resolve:b,startedAt:Date.now(),timer:void 0}}let b=Date.now()-this._waitUntilCycle.startedAt,c=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),b>=c)return void this.resolveWaitUntilFlush();let d=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=R(()=>{this.resolveWaitUntilFlush()},d)}_consumeWaitUntilCycle(){let a=this._waitUntilCycle;return a&&(clearTimeout(a.timer),this._waitUntilCycle=void 0),a?.resolve}async resolveWaitUntilFlush(){let a=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{a?.()}}getPersistedProperty(a){return this._memoryStorage.getProperty(a)}setPersistedProperty(a,b){return this._memoryStorage.setProperty(a,b)}fetch(a,b){return this.options.fetch?this.options.fetch(a,b):fetch(a,b)}getQueueRouteKey(a){var b;return"v1"===this.captureMode&&"string"==typeof(b=a).event&&b.event.startsWith("$ai_")?"ai":dt}persistedQueueKeyForRoute(a){return a===dC?l.AiCaptureQueue:"ai"===a?l.AiQueue:l.Queue}getActiveQueueRoutes(){let a="v1"===this.captureMode?[dt,"ai"]:[dt];return this._aiCaptureRouteActive&&a.push(dC),a}getBatchEndpointPath(a){return a===dC?dD:super.getBatchEndpointPath(a)}async sendBatch(a,b,c=dt){if(c===dC)return this.sendAiCaptureBatch(a,b);if("v1"!==this.captureMode||"ai"===c)return super.sendBatch(a,b,c);let d=a.filter(a=>void 0!==a);await this.getV1Sender().sendV1Batch(d)}async sendAiCaptureBatch(a,b){let{batches:c,dropped:d}=function(a,b=8388608,c=5242880){let d=[],e=[],f=[],g=0;for(let h of a){if(void 0===h)continue;let a=dF(h);if(a>b){e.push({event:"string"==typeof h.event?h.event:"unknown",bytes:a});continue}f.length>0&&g+a>c&&(d.push(f),f=[],g=0),f.push(h),g+=a}return f.length>0&&d.push(f),{batches:d,dropped:e}}(a);for(let{event:a,bytes:b}of d){let c=`Event ${a} (${b} bytes) exceeds the 8MiB limit for ${dD}, dropping.`;this._logger.error(c),this._events.emit("error",Error(c))}for(let a of c)await this.sendAiSubBatch(a,b)}async sendAiSubBatch(a,b){try{await super.sendBatch(a,b,dC)}catch(d){if(!bk(d))throw d;if(1===a.length){let[b]=a,c="string"==typeof b.event?b.event:"unknown",d=`Event ${c} (${dF(b)} bytes) was rejected with 413 by ${dD} on its own, dropping.`;this._logger.error(d),this._events.emit("error",Error(d));return}let c=Math.ceil(a.length/2);await this.sendAiSubBatch(a.slice(0,c),b),await this.sendAiSubBatch(a.slice(c),b)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new dB({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(a,b)=>this.fetch(a,b),onError:a=>this._events.emit("error",a),compress:a=>this.compressPayload(a)})),this._v1Sender}getLibraryVersion(){return"5.57.1"}get metrics(){var a;let b;return this._metrics||(this._metrics=new bT(this,(a=this.options.metrics,b=a?.resourceAttributes,{serviceName:b?.["service.name"]??a?.serviceName,serviceVersion:b?.["service.version"]??a?.serviceVersion,environment:b?.["deployment.environment"]??a?.environment,resourceAttributes:b,beforeSend:a?.beforeSend,flushIntervalMs:a?.flushIntervalMs??1e4,maxSeriesPerFlush:a?.maxSeriesPerFlush??1e3}),this._logger)),this._metrics}initializeSpanContextManager(){return new cw}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces){var a,b,c;let d,e;return this._traces||(this._traces=new ci(this,(a=this.options.traces,b=this.hostResourceAttributes(),c=this._logger,d=bt({...b},function(a){if(!(!a||"object"!=typeof a||Array.isArray(a)))try{if(cB.every(b=>!(b in a)||"string"==typeof a[b]))return a;let b={...a};for(let a of cB)a in b&&"string"!=typeof b[a]&&delete b[a];return b}catch{return}}(a?.resourceAttributes)),e=cA(a?.maxExportBatchSize,512),{serviceName:d?.["service.name"]??a?.serviceName,serviceVersion:d?.["service.version"]??a?.serviceVersion,environment:d?.["deployment.environment"]??a?.environment,resourceAttributes:d,beforeSpanSend:function(a,b){if(!a)return[];let c=[a].flat().filter(a=>!!a),d=c.filter(a=>"function"==typeof a);return d.length!==c.length&&b?.critical(`beforeSpanSend: ignoring ${c.length-d.length} of ${c.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),d}(a?.beforeSpanSend,c),maxAttributesPerSpan:cA(a?.maxAttributesPerSpan,128),maxEventsPerSpan:cA(a?.maxEventsPerSpan,128),maxAttributesPerEvent:128,maxAttributeValueLength:cA(a?.maxAttributeValueLength,8192),flushIntervalMs:cA(a?.flushIntervalMs,5e3),maxExportBatchSize:e,maxQueueSize:Math.max(cA(a?.maxQueueSize,2048),e),maxLiveSpans:cA(a?.maxLiveSpans,1e4),maxSpanAgeMs:cA(a?.maxSpanAgeMs,36e5)}),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}}_tracingContext(){let a=this.context?.get();return{distinctId:a?.distinctId,sessionId:a?.sessionId}}startSpan(a,b){return this._tracesPipeline?.startSpan(a,b)??b3(b,this._spanContextManager.active())}withSpan(a,b,c){let d="function"==typeof b?void 0:b,e="function"==typeof b?b:c,f=this._tracesPipeline;return f?d?f.withSpan(a,d,e):f.withSpan(a,e):b8(this._spanContextManager,b3(d,this._spanContextManager.active()),e)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let a=super.getCommonEventProperties();return(this.options.isServer??!0)&&(a.$is_server=!0),a}enable(){return super.optIn()}disable(){return super.optOut()}debug(a=!0){super.debug(a),this.featureFlagsPoller?.debug(a)}_warnIfInvalidCapture(a,b,c){"string"==typeof a&&this._logger.warn(b),"$exception"!==a.event||a._originatedFromCaptureException||this._logger.warn(c)}_sendPreparedEvent(a,b,c,d,e){return this.addPendingPromise(this._prepareEventMessage(b,d).then(({distinctId:b,event:d,properties:f,options:g})=>{let h={timestamp:g.timestamp,disableGeoip:g.disableGeoip,uuid:g.uuid},i={distinctId:b,event:d,properties:{...f,...this.getCommonEventProperties()}};return c?this.sendImmediate(a,i,h,e):this.enqueue(a,i,h,e)}).catch(a=>{a&&console.error(a)}))}_capturePreparedEvent(a,b){return this._sendPreparedEvent("capture",a,b)}capture(a){this._warnIfInvalidCapture(a,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(a,!1)}async captureImmediate(a){return this._warnIfInvalidCapture(a,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(a,!0)}captureAi(a){if(this.disabled)return;let b=M(a.uuid,aX);return this._sendPreparedAiEvent({...a,uuid:b},!1),b}async captureAiImmediate(a){if(this.disabled)return;let b=M(a.uuid,aX);return await this._sendPreparedAiEvent({...a,uuid:b},!0),b}_sendPreparedAiEvent(a,b){return"string"!=typeof a?.event||a.event.startsWith("$ai_")||this._logger.debug(`captureAi called with non-AI event ${a.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",a,b,void 0,dC)}identify({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;this._sendPreparedEvent("identify",{distinctId:a,event:"$identify",properties:{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},disableGeoip:c},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;await this._sendPreparedEvent("identify",{distinctId:a,event:"$identify",properties:{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},disableGeoip:c},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:a,properties:b={},propertiesOnce:c={}}){if(0===Object.keys(b).length&&0===Object.keys(c).length)return;let d={};Object.keys(b).length>0&&(d.$set=b),Object.keys(c).length>0&&(d.$set_once=c),this.capture({distinctId:a,event:"$set",properties:d})}unsetPersonProperties({distinctId:a,properties:b}){let c=(Array.isArray(b)?b:[b]).filter(a=>"string"==typeof a&&a.trim().length>0);0!==c.length&&this.capture({distinctId:a,event:"$set",properties:{$unset:c}})}alias(a){this._sendPreparedEvent("alias",{distinctId:a.distinctId,event:"$create_alias",properties:{distinct_id:a.distinctId,alias:a.alias},disableGeoip:a.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(a){await this._sendPreparedEvent("alias",{distinctId:a.distinctId,event:"$create_alias",properties:{distinct_id:a.distinctId,alias:a.alias},disableGeoip:a.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(a){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(a)}getFeatureFlagKeysByEvaluationRuntime(a){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(a)??[]}async waitForLocalEvaluationReady(a=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(b=>{let c=setTimeout(()=>{d(),b(!1)},a),d=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(c),d(),b(a>0)})})}_resolveDistinctId(a,b){return"string"==typeof a?{distinctId:a,options:b}:{distinctId:this.context?.get()?.distinctId,options:a}}async _getFeatureFlagResult(a,b,c={},d){let e,f,g,h,i,j,k,l;if(this.disabled)return void this._logger.warn("The client is disabled");let m=c.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&a in this._flagOverrides){let b=this._flagOverrides[a];if(void 0===b)return;let c=this._payloadOverrides?.[a];return{key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:c}}let{groups:n,disableGeoip:o}=c,{onlyEvaluateLocally:p,personProperties:q,groupProperties:r}=c,s=this.addLocalPersonAndGroupProperties(b,n,q,r);q=s.allPersonProperties,r=s.allGroupProperties;let t=this.createFeatureFlagEvaluationContext(b,n,this.personPropertiesForLocalEvaluation(b,q),r);void 0==p&&(p=this.options.strictLocalEvaluation??!1);let u=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let b=this.featureFlagsPoller?.featureFlagsByKey[a];if(b)try{let c=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(b,t,{matchValue:d});if(c){u=!0;let d=c.value;i=b.id,k="Evaluated locally",l=b.has_experiment,e={key:a,enabled:!1!==d,variant:"string"==typeof d?d:void 0,payload:c.payload??void 0,reason:k,reasonCode:!1===b.active?"flag_disabled":void 0}}}catch(b){if(b instanceof c4||b instanceof cF)this._logger?.info(`${b.name} when computing flag locally: ${a}: ${b.message}`);else throw b}}if(!u&&!p){let b=await super.getFeatureFlagDetailsStateless(t.distinctId,t.groups,q,r,o,[a]);if(void 0===b)h=cC.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===b.minimalFlagCalledEvents,f=b.requestId,g=b.evaluatedAt;let c=[];b.errorsWhileComputingFlags&&c.push(cC.ERRORS_WHILE_COMPUTING),b.quotaLimited?.includes("feature_flags")&&c.push(cC.QUOTA_LIMITED);let d=b.flags[a];if(void 0===d)c.push(cC.FLAG_MISSING);else{let b;if(i=d.metadata?.id,j=d.metadata?.version,k=d.reason?.description??d.reason?.code,l=d.metadata?.has_experiment,d.metadata?.payload!==void 0)try{b=JSON.parse(d.metadata.payload)}catch{b=d.metadata.payload}e={key:a,enabled:d.enabled,variant:d.variant??void 0,payload:b,reason:k,reasonCode:d.reason?.code}}c.length>0&&(h=c.join(","))}}if(m){let c=void 0===e?void 0:!1!==e.enabled&&(e.variant??!0),d={$feature_flag:a,$feature_flag_response:c,$feature_flag_id:i,$feature_flag_version:j,$feature_flag_reason:k,locally_evaluated:u,[`$feature/${a}`]:c,$feature_flag_request_id:f,$feature_flag_evaluated_at:u?Date.now():g};if(void 0!==l&&(d.$feature_flag_has_experiment=l),u&&this.featureFlagsPoller){let a=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==a&&(d.$feature_flag_definitions_loaded_at=a)}h&&(d.$feature_flag_error=h),this._captureFlagCalledEventIfNeeded({distinctId:b,key:a,response:c,groups:n,disableGeoip:o,properties:d})}return void 0!==e&&void 0!==this._payloadOverrides&&a in this._payloadOverrides&&(e={...e,payload:this._payloadOverrides[a]}),e}async getFeatureFlag(a,b,c){dH("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let d=await this._getFeatureFlagResult(a,b,{...c,sendFeatureFlagEvents:c?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(void 0!==d)return!1!==d.enabled&&(d.variant??!0)}async getFeatureFlagPayload(a,b,c,d){if(dH("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request."),void 0!==this._payloadOverrides&&a in this._payloadOverrides)return this._payloadOverrides[a];let e=await this._getFeatureFlagResult(a,b,{...d,sendFeatureFlagEvents:!1},c);if(void 0!==e)return e.payload??null}async getFeatureFlagResult(a,b,c){let{distinctId:d,options:e}=this._resolveDistinctId(b,c);return d?this._getFeatureFlagResult(a,d,{...e,sendFeatureFlagEvents:e?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}async getRemoteConfigPayload(a){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let b=await this._requestRemoteConfigPayload(a);if(!b)return;let c=await b.json();if("string"==typeof c)try{return JSON.parse(c)}catch(a){}return c}async isFeatureEnabled(a,b,c){dH("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let d=await this._getFeatureFlagResult(a,b,{...c,sendFeatureFlagEvents:c?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return void 0===d?void 0:!1!==d.enabled&&!!(d.variant??!0)}async getAllFlags(a,b){let{distinctId:c,options:d}=this._resolveDistinctId(a,b);return c?(await this.getAllFlagsAndPayloads(c,d)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(a,b){let{distinctId:c,options:d}=this._resolveDistinctId(a,b);if(!c)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads — pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:e,disableGeoip:f,flagKeys:g}=d||{},{onlyEvaluateLocally:h,personProperties:i,groupProperties:j}=d||{},k=this.addLocalPersonAndGroupProperties(c,e,i,j);i=k.allPersonProperties,j=k.allGroupProperties;let l=this.createFeatureFlagEvaluationContext(c,e,this.personPropertiesForLocalEvaluation(c,i),j);void 0==h&&(h=this.options.strictLocalEvaluation??!1);let m=await this.featureFlagsPoller?.getAllFlagsAndPayloads(l,g),n={},o={},p=!0;if(m&&(n=m.response,o=m.payloads,p=m.fallbackToFlags),p&&!h){let a=await super.getFeatureFlagsAndPayloadsStateless(l.distinctId,l.groups,i,j,f,g);n={...n,...a.flags||{}},o={...o,...a.payloads||{}}}return void 0!==this._flagOverrides&&(n={...n,...this._flagOverrides}),void 0!==this._payloadOverrides&&(o={...o,...this._payloadOverrides}),{featureFlags:n,featureFlagPayloads:o}}async evaluateFlags(a,b){let c,d,{distinctId:e,options:f}=this._resolveDistinctId(a,b);if(!e)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new cD({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new cD({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,flags:{}});let{groups:g,disableGeoip:h}=f||{},i=f?.flagKeys??void 0;if(i?.length===0)return new cD({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:{}});let{onlyEvaluateLocally:j,personProperties:k,groupProperties:l}=f||{},m=this.addLocalPersonAndGroupProperties(e,g,k,l);k=m.allPersonProperties,l=m.allGroupProperties;let n=this.createFeatureFlagEvaluationContext(e,g,this.personPropertiesForLocalEvaluation(e,k),l);void 0==j&&(j=this.options.strictLocalEvaluation??!1);let o=i?new Set(i):void 0,p={},q=!1,r=!1,s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(n,i),t=new Set;if(s)for(let[a,b]of Object.entries(s.response)){let c=this.featureFlagsPoller?.featureFlagsByKey[a];p[a]={key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:s.payloads[a],id:c?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:c?.has_experiment},t.add(a)}let u=void 0!==o&&Array.from(o).some(a=>this.featureFlagsPoller?.featureFlagsByKey[a]===void 0);if((!s||s.fallbackToFlags||u)&&!j){let a=await super.getFeatureFlagDetailsStateless(n.distinctId,n.groups,k,l,h,i);if(a)for(let[b,e]of(this._minimalFlagCalledEvents=!0===a.minimalFlagCalledEvents,c=a.requestId,d=a.evaluatedAt,q=!!a.errorsWhileComputingFlags,r=Array.isArray(a.quotaLimited)&&a.quotaLimited.includes("feature_flags"),Object.entries(a.flags))){let a;if(!t.has(b)){if(e.metadata?.payload!==void 0)try{a=JSON.parse(e.metadata.payload)}catch{a=e.metadata.payload}p[b]={key:b,enabled:e.enabled,variant:e.variant,payload:a,id:e.metadata?.id,version:e.metadata?.version,reason:e.reason?.description??e.reason?.code,locallyEvaluated:!1,hasExperiment:e.metadata?.has_experiment}}}}if(void 0!==this._flagOverrides)for(let[a,b]of Object.entries(this._flagOverrides)){if(void 0===b){delete p[a];continue}let c=p[a];p[a]={key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:c?.payload,id:c?.id,version:c?.version,reason:c?.reason,locallyEvaluated:c?.locallyEvaluated??!1,hasExperiment:c?.hasExperiment}}if(void 0!==this._payloadOverrides)for(let[a,b]of Object.entries(this._payloadOverrides)){let c=p[a];c&&(p[a]={...c,payload:b})}if(void 0!==o)for(let a of Object.keys(p))o.has(a)||delete p[a];let v={};for(let[a,b]of Object.entries(s?.unresolved??{}))Object.prototype.hasOwnProperty.call(p,a)||(v[a]=b);return new cD({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:p,unresolvedFlags:v,requestId:c,evaluatedAt:d,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:q,quotaLimited:r})}_shouldSendMinimalFlagCalledEvent(a,b){return"$feature_flag_called"===a&&this._minimalFlagCalledEvents&&!1===b.$feature_flag_has_experiment}_captureFlagCalledEventIfNeeded(a){let{distinctId:b,key:c,response:d,groups:e,disableGeoip:f,properties:g}=a,h=e&&Object.keys(e).length>0?`_${JSON.stringify(Object.entries(e).sort(([a],[b])=>a<b?-1:+(a>b)))}`:"",i=`${c}_${d}${h}`,j=this._distinctIdHasSentFlagCalls.get(b)??new Set;if(this._distinctIdHasSentFlagCalls.delete(b),this._distinctIdHasSentFlagCalls.set(b,j),!j.has(i)){for(j.add(i);this._distinctIdHasSentFlagCalls.size>Math.max(this.maxCacheSize,1);){let a=this._distinctIdHasSentFlagCalls.keys().next().value;if(void 0===a)break;this._distinctIdHasSentFlagCalls.delete(a)}this.capture({distinctId:b,event:"$feature_flag_called",properties:g,groups:e,disableGeoip:f})}}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:a=>this._captureFlagCalledEventIfNeeded(a),logWarning:a=>{!1!==this.options.featureFlagsLogWarnings&&console.warn(`[PostHog] ${a}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:a,groupKey:b,properties:c,distinctId:d,disableGeoip:e}){this._sendPreparedEvent("capture",{distinctId:d||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{}},disableGeoip:e},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:a,groupKey:b,properties:c,distinctId:d,disableGeoip:e}){await this._sendPreparedEvent("capture",{distinctId:d||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{}},disableGeoip:e},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(a){let b=a=>Object.fromEntries(a.map(a=>[a,!0]));if(!1===a){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(a)){this._flagOverrides=b(a);return}if(this._isFeatureFlagOverrideOptions(a)){"flags"in a&&(!1===a.flags?this._flagOverrides=void 0:Array.isArray(a.flags)?this._flagOverrides=b(a.flags):void 0!==a.flags&&(this._flagOverrides={...a.flags})),"payloads"in a&&(!1===a.payloads?this._payloadOverrides=void 0:void 0!==a.payloads&&(this._payloadOverrides={...a.payloads}));return}this._flagOverrides={...a}}_isFeatureFlagOverrideOptions(a){if("object"!=typeof a||null===a||Array.isArray(a))return!1;if("flags"in a){let b=a.flags;if(!1===b||Array.isArray(b)||"object"==typeof b&&null!==b)return!0}if("payloads"in a){let b=a.payloads;if(!1===b||"object"==typeof b&&null!==b)return!0}return!1}withContext(a,b,c){return this.context?this.context.run(a,b,c):b()}getContext(){return this.context?.get()}enterContext(a,b){this.context?.enter(a,b)}async _shutdown(a){let b=Date.now()+(a??3e4),c=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(a),this.errorTracking.shutdown(),this._metrics&&(await S(this._metrics.flush().catch(()=>{}),Math.max(0,b-Date.now())),this._metrics.reset()),this._traces&&(await S(this._traces.flush().catch(()=>{}),Math.max(0,b-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,b-Date.now()))}finally{this._distinctIdHasSentFlagCalls.clear(),c?.()}}async _requestRemoteConfigPayload(a){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let b=`${this.host}/api/projects/@current/feature_flags/${a}/remote_config?token=${encodeURIComponent(this.apiKey)}`,c={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},d=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let a=new AbortController;d=R(()=>{a.abort()},this.options.requestTimeout),c.signal=a.signal}try{return await this.fetch(b,c)}catch(a){this._events.emit("error",a);return}finally{d&&clearTimeout(d)}}extractPropertiesFromEvent(a,b){if(!a)return{personProperties:{},groupProperties:{}};let c={},d={};for(let[e,f]of Object.entries(a))if(A(f,"Object")&&b&&e in b){let a={};for(let[b,c]of Object.entries(f))a[String(b)]=String(c);d[String(e)]=a}else c[String(e)]=String(f);return{personProperties:c,groupProperties:d}}async getFeatureFlagsForEvent(a,b,c,d){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let e=d?.personProperties||{},f=d?.groupProperties||{},g=d?.flagKeys;if(d?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let d={};for(let[a,c]of Object.entries(b||{}))d[a]=String(c);return await this.getAllFlags(a,{groups:d,personProperties:e,groupProperties:f,disableGeoip:c,onlyEvaluateLocally:!0,flagKeys:g})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let d={};for(let[a,c]of Object.entries(b||{}))d[a]=String(c);return await this.getAllFlags(a,{groups:d,personProperties:e,groupProperties:f,disableGeoip:c,onlyEvaluateLocally:!0,flagKeys:g})}return(await super.getFeatureFlagsStateless(a,b,e,f,c)).flags}addLocalPersonAndGroupProperties(a,b,c,d){let e={...c||{}},f={};if(b)for(let a of Object.keys(b))f[a]={$group_key:b[a],...d?.[a]||{}};return{allPersonProperties:e,allGroupProperties:f}}personPropertiesForLocalEvaluation(a,b){return{distinct_id:a,...b||{}}}createFeatureFlagEvaluationContext(a,b,c,d){return{distinctId:a,groups:b||{},personProperties:c||{},groupProperties:d||{},evaluationCache:{}}}captureException(a,b,c,d,e){if(!dn.isPreviouslyCapturedError(a)){let f=Error("PostHog syntheticException");this.addPendingPromise(dn.buildEventMessage(this.getErrorPropertiesBuilder(),a,{syntheticException:f},b,c).then(a=>this._capturePreparedEvent({...a,uuid:d,flags:e},!1)))}}async captureExceptionImmediate(a,b,c,d){if(!dn.isPreviouslyCapturedError(a)){let e=Error("PostHog syntheticException");return this.addPendingPromise(dn.buildEventMessage(this.getErrorPropertiesBuilder(),a,{syntheticException:e},b,c).then(a=>this.captureImmediate({...a,flags:d})))}}async prepareEventMessage(a){return this._prepareEventMessage(a)}async _prepareEventMessage(a,b={}){let{distinctId:c,event:d,properties:e,groups:f,flags:g,sendFeatureFlags:h,timestamp:i,disableGeoip:j,uuid:k}=a,l=this.context?.get(),m=b.includeContextProperties??!0,n=c||l?.distinctId,o=m?{...this.props,...l?.properties||{},...e||{}}:{...e||{}};"$exception"!==d||"$trace_id"in o||"$span_id"in o||Object.assign(o,await dr()),n||(n=aX(),o.$process_person_profile=!1),m&&l?.sessionId&&!o.$session_id&&(o.$session_id=l.sessionId);let p=this._shouldSendMinimalFlagCalledEvent(d,o)?a6(o):o,q=this._runBeforeSend({distinctId:n,event:d,properties:p,groups:f,flags:g,sendFeatureFlags:h,timestamp:i,disableGeoip:j,uuid:k});if(!q)return Promise.reject(null);let r=await Promise.resolve().then(async()=>{if(g)return h&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),g._getEventProperties();if(h){dH("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");var a=await this.getFeatureFlagsForEvent(q.distinctId,f,j,"object"==typeof h?h:void 0);if(!a)return{};let b={};for(let[c,d]of Object.entries(a))b[`$feature/${c}`]=d;let c=Object.keys(a).filter(b=>!1!==a[b]).sort();return c.length>0&&(b.$active_feature_flags=c),b}return{}}).catch(()=>({})).then(a=>{let b=q.groups||f;return{...a,...q.properties||{},...void 0!==b&&Object.keys(b).length>0?{$groups:b}:{}}});return"$pageview"===q.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof r.$raw_user_agent&&cz(r.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(q.event="$bot_pageview",r.$browser_type="bot"),{distinctId:q.distinctId,event:q.event,properties:r,options:{timestamp:q.timestamp,disableGeoip:q.disableGeoip,uuid:q.uuid}}}_runBeforeSend(a){let b=this.options.before_send;if(!b)return a;let c=Array.isArray(b)?b:[b],d=a;for(let b of c)try{if(!(d=b(d)))return this._logger.info(`Event '${a.event}' was rejected in beforeSend function`),null;if(!d.properties||0===Object.keys(d.properties).length){let a=`Event '${d.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(a)}}catch(b){return this._logger.error(`Error in before_send function for event '${a.event}':`,b),null}return d}}var dJ=a.i(78500);class dK{constructor(){this.storage=new dJ.AsyncLocalStorage}get(){return this.storage.getStore()}run(a,b,c){return this.storage.run(this.resolve(a,c),b)}enter(a,b){this.storage.enterWith(this.resolve(a,b))}resolve(a,b){if(b?.fresh===!0)return a;let c=this.get()||{};return{distinctId:a.distinctId??c.distinctId,sessionId:a.sessionId??c.sessionId,properties:{...c.properties||{},...a.properties||{}}}}}class dL{active(){return this._storage.getStore()}with(a,b){return this._storage.run(a,b)}constructor(){this._storage=new dJ.AsyncLocalStorage}}var dM=a.i(27028);let dN=(0,a.i(12057).promisify)(dM.gzip);async function dO(a,b=!0){try{let b=await dN(a);return new Uint8Array(b)}catch(a){return b&&console.error("Failed to gzip compress data",a),null}}var dP=a.i(60526),dm=aS;let dQ="posthog-node";function dR(a,{organization:b,projectId:c,prefix:d,severityAllowList:e=["error"],sendExceptionsToPostHog:f=!0}={}){return g=>{if(!("*"===e||e.includes(g.level)))return g;g.tags||(g.tags={});let h=g.tags[dT.POSTHOG_ID_TAG];if(void 0===h)return g;let i=a.options.host??"https://us.i.posthog.com",j=new URL(`/project/${a.apiKey}/person/${h}`,i).toString();g.tags["PostHog Person URL"]=j;let k=g.exception?.values||[],l=k.map(a=>({...a,stacktrace:a.stacktrace?{...a.stacktrace,type:"raw",frames:(a.stacktrace.frames||[]).map(a=>({...a,platform:"node:javascript"}))}:void 0})),m={$exception_message:k[0]?.value||g.message,$exception_type:k[0]?.type,$exception_level:g.level,$exception_list:l,$sentry_event_id:g.event_id,$sentry_exception:g.exception,$sentry_exception_message:k[0]?.value||g.message,$sentry_exception_type:k[0]?.type,$sentry_tags:g.tags},n=dm.getInjectedReleaseId();return n&&(m.$release_id=n),b&&c&&(m.$sentry_url=(d||"https://sentry.io/organizations/")+b+"/issues/?project="+c+"&query="+g.event_id),f&&a.capture({event:"$exception",distinctId:h,properties:m}),g}}function dS(a,b){let c=dR(a,b);return{name:dQ,processEvent:a=>c(a)}}class dT{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(a,b,c,d,e){this.name=dQ,this.name=dQ,this.setupOnce=function(f,g){f(dR(a,{organization:b,projectId:g()?.getClient()?.getDsn()?.projectId,prefix:c,severityAllowList:d,sendExceptionsToPostHog:e??!0}))}}}a.s(["PostHogSentryIntegration",0,dT,"createEventProcessor",0,dR,"sentryIntegration",0,dS],9318);let dU=/[\x00-\x1f\x7f-\x9f]/g;function dV(a,b,c){null!=c&&""!==c&&(a[b]=c)}function dW(a){return Array.isArray(a)?a[0]:a}function dX(a){if(Array.isArray(a)){for(let b of a){let a=dX(b);if(void 0!==a)return a}return}if("string"!=typeof a)return;let b=a.replace(dU,"").trim();if(b)return b.length>1e3?b.slice(0,1e3):b}function dY(a,b){var c,d;let e,{sessionId:f,distinctId:g}=function(a){if(!a)return{};let b=dX(a["x-posthog-session-id"]),c=dX(a["x-posthog-distinct-id"]);return{...void 0!==b?{sessionId:b}:{},...void 0!==c?{distinctId:c}:{}}}(b.headers),h={},i=!0===a.options.disable_capture_url_hashes;return dV(h,"$current_url",(c=b.originalUrl||b.url,i?O(c):c)),dV(h,"$request_method",b.method),dV(h,"$request_path",(d=b.path,e=function(a){if(!a)return a;let b=a.indexOf("?"),c=a.indexOf("#");return -1===b||-1!==c&&c<b?a:`${a.slice(0,b)}${-1===c?"":a.slice(c)}`}(d),i?O(e):e)),dV(h,"$user_agent",dW(b.headers["user-agent"])),dV(h,"$ip",function(a){let b=dW(a.headers["x-forwarded-for"]);if(b){let a=b.split(",")[0].trim();if(a)return a}return a.socket?.remoteAddress}(b)),{...void 0!==f?{sessionId:f}:{},...void 0!==g?{distinctId:g}:{},properties:h}}function dZ(a,b){var c;b.use((c=a,(a,b,d)=>{c.withContext(dY(c,a),()=>d())}))}function d$(a,b){var c;b.use((c=a,(a,b,d,e)=>{if(dn.isPreviouslyCapturedError(a))return void e(a);let f=dY(c,b),g=Error("Synthetic exception"),h={...void 0!==f.sessionId?{$session_id:f.sessionId}:{},...f.properties||{}};c.addPendingPromise(Promise.all([dn.buildEventMessage(c.getErrorPropertiesBuilder(),a,{mechanism:{type:"middleware",handled:!1},syntheticException:g},f.distinctId,h),d.headersSent||d.destroyed?Promise.resolve(d.headersSent?d.statusCode:void 0):new Promise(a=>{let b=b=>{clearTimeout(e),d.removeListener("finish",c),d.removeListener("close",c),a(b)},c=()=>b(d.headersSent?d.statusCode:void 0),e=setTimeout(()=>b(void 0),1e3);e.unref(),d.once("finish",c),d.once("close",c)})]).then(([a,b])=>(void 0!==b&&(a.properties={...a.properties,$response_status_code:b}),c._capturePreparedEvent(a,!1)))),e(a)}))}a.s(["setupExpressErrorHandler",0,d$,"setupExpressRequestContext",0,dZ],40602),a.i(9318),a.i(40602),a.i(46539),a.s(["FeatureFlagError",0,m,"FeatureFlagEvaluations",0,cD,"PostHogSentryIntegration",0,dT,"cookieStateToProperties",0,a1,"cookieStoreFromHeader",0,aZ,"createEventProcessor",0,dR,"getPostHogCookieName",0,a$,"parsePostHogCookie",0,a2,"readPostHogCookie",0,a0,"sentryIntegration",0,dS,"serializePostHogCookie",0,a_,"setupExpressErrorHandler",0,d$,"setupExpressRequestContext",0,dZ,"uuidv7",0,aX],80456),a.i(80456),a.s(["FeatureFlagError",0,m,"FeatureFlagEvaluations",0,cD,"PostHog",0,class extends dI{getLibraryId(){return"posthog-node"}compressPayload(a){return dO(a,this.isDebug)}initializeContext(){return new dK}initializeSpanContextManager(){return new dL}hostResourceAttributes(){return function(){var a,b;let c,d,e;try{c=(0,dP.platform)(),d=(0,dP.release)()}catch{}return a=c,b=d,{...(e=function(a){if(a)return Object.prototype.hasOwnProperty.call(bA,a)?bA[a]:a}(a))?{"os.name":e}:{},...b?{"os.version":b}:{}}}()}createErrorPropertiesBuilder(){let a;return new aS.ErrorPropertiesBuilder([new aS.EventCoercer,new aS.ErrorCoercer,new aS.ObjectCoercer,new aS.StringCoercer,new aS.PrimitiveCoercer],aS.createStackParser("node:javascript",aS.nodeStackLineParser),[(a=function(a=process.argv[1]?(0,j.dirname)(process.argv[1]):process.cwd(),b="\\"===j.sep){let c=b?k(a):a;return a=>{if(!a)return;let d=b?k(a):a,{dir:e,base:f,ext:g}=j.posix.parse(d);(".js"===g||".mjs"===g||".cjs"===g)&&(f=f.slice(0,-1*g.length));let h=decodeURIComponent(f);e||(e=".");let i=e.lastIndexOf("/node_modules");if(i>-1)return`${e.slice(i+14).replace(/\//g,".")}:${h}`;if(e.startsWith(c)){let a=e.slice(c.length+1).replace(/\//g,".");return a?`${a}:${h}`:h}return h}}(),async b=>{for(let c of b)c.module=a(c.filename);return b}),a=>cp(a,void 0,this._logger),function(a=process.cwd()){j.sep;let b=a=>a,c=b(a);return async a=>{for(let d of a)!(!d.filename||d.filename.startsWith("node:")||d.filename.startsWith("data:"))&&(0,j.isAbsolute)(d.filename)&&(d.filename=b((0,j.relative)(c,b(d.filename))));return a}}()])}},"PostHogSentryIntegration",0,dT,"cookieStateToProperties",0,a1,"cookieStoreFromHeader",0,aZ,"createEventProcessor",0,dR,"getPostHogCookieName",0,a$,"parsePostHogCookie",0,a2,"readPostHogCookie",0,a0,"sentryIntegration",0,dS,"serializePostHogCookie",0,a_,"setupExpressErrorHandler",0,d$,"setupExpressRequestContext",0,dZ,"uuidv7",0,aX],74493)}];
|
|
1
|
+
module.exports=[74493,a=>{"use strict";let b,c,d,e,f,g;var h,i=a.i(14747);function j(a){return a.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var k=((h={}).AnonymousId="anonymous_id",h.DistinctId="distinct_id",h.Props="props",h.EnablePersonProcessing="enable_person_processing",h.PersonMode="person_mode",h.FeatureFlagDetails="feature_flag_details",h.FeatureFlags="feature_flags",h.FeatureFlagPayloads="feature_flag_payloads",h.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",h.BootstrapFeatureFlags="bootstrap_feature_flags",h.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",h.OverrideFeatureFlags="override_feature_flags",h.Queue="queue",h.AiQueue="ai_queue",h.AiCaptureQueue="ai_capture_queue",h.LogsQueue="logs_queue",h.OptedOut="opted_out",h.SessionId="session_id",h.SessionStartTimestamp="session_start_timestamp",h.SessionLastTimestamp="session_timestamp",h.PersonProperties="person_properties",h.GroupProperties="group_properties",h.InstalledAppBuild="installed_app_build",h.InstalledAppVersion="installed_app_version",h.SessionReplay="session_replay",h.PushRegistered="push_registered",h.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",h.SurveyLastSeenDate="survey_last_seen_date",h.SurveysInProgress="surveys_in_progress",h.SurveysSeen="surveys_seen",h.Surveys="surveys",h.RemoteConfig="remote_config",h.FlagsEndpointWasHit="flags_endpoint_was_hit",h.DeviceId="device_id",h);let l={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",EVALUATION_FAILED:"evaluation_failed",LOCAL_EVALUATION_INCONCLUSIVE:"local_evaluation_inconclusive",QUOTA_LIMITED:"quota_limited",TIMEOUT:"timeout",CONNECTION_ERROR:"connection_error",UNKNOWN_ERROR:"unknown_error",apiError:a=>`api_error_${a}`};function m(a,b){return -1!==a.indexOf(b)}function n(a){let b=[];return JSON.stringify(a,function(a,c){if("bigint"==typeof c)return c.toString();if("function"!=typeof c&&"symbol"!=typeof c){if(c instanceof Error)return{name:c.name,message:c.message,stack:c.stack};if(c&&"object"==typeof c){for(;b.length>0&&b[b.length-1]!==this;)b.pop();if(b.includes(c))return"[Circular]";b.push(c)}return c}})??"null"}let o=Array.isArray,p=Object.prototype,q=p.hasOwnProperty,r=p.toString,s=o||function(a){return"[object Array]"===r.call(a)},t=a=>void 0===a,u=a=>"[object String]"==r.call(a),v=a=>u(a)&&0===a.trim().length,w=a=>null===a,x=a=>t(a)||w(a),y=a=>"[object Number]"==r.call(a)&&a==a,z=a=>"[object Boolean]"===r.call(a);function A(a){switch(Object.prototype.toString.call(a)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return D(a,Error)}}function B(a){return"u">typeof Event&&D(a,Event)}function C(a){return"[object Object]"===Object.prototype.toString.call(a)}function D(a,b){try{return a instanceof b}catch{return!1}}let E=[!0,"true",1,"1","yes"],F=[!1,"false",0,"0","no"];function G(a,b,c){return a&&c?b.length===Object.keys(c).length&&b.every(b=>a[b]===c[b]):a===c}class H{constructor(a,b,c=[]){this.coercers=a,this.stackParser=b,this.modifiers=c}buildFromUnknown(a,b={}){let c=b&&b.mechanism||{handled:!0,type:"generic"},d=this.buildCoercingContext(c,b,0).apply(a),e=this.buildParsingContext(b),f=this.parseStacktrace(d,e);return{$exception_list:this.convertToExceptionList(f,c),$exception_level:"error"}}async modifyFrames(a){for(let b of a)b.stacktrace&&b.stacktrace.frames&&s(b.stacktrace.frames)&&(b.stacktrace.frames=await this.applyModifiers(b.stacktrace.frames));return a}coerceFallback(a){return{type:"Error",value:"Unknown error",stack:a.syntheticException?.stack,synthetic:!0}}parseStacktrace(a,b){let c,d;if(null!=a.cause&&(c=this.parseStacktrace(a.cause,b)),""!=a.stack&&null!=a.stack)try{d=this.applyChunkIds(this.stackParser(a.stack,a.synthetic?b.skipFirstLines:0),b.chunkIdMap)}catch{}return{...a,cause:c,stack:d,errors:a.errors?.map(a=>this.parseStacktrace(a,b))}}applyChunkIds(a,b){return a.map(a=>(a.filename&&b&&(a.chunk_id=b[a.filename]),a))}applyCoercers(a,b){for(let c of this.coercers)if(c.match(a))return c.coerce(a,b);return this.coerceFallback(b)}async applyModifiers(a){let b=a;for(let a of this.modifiers)b=await a(b);return b}convertToExceptionList(a,b){let c=[],d=(a,e,f)=>{let g=c.length,h=void 0===e?{type:"string"==typeof b.type&&b.type.length>0?b.type:"generic",..."boolean"==typeof b.handled?{handled:b.handled}:void 0===b.handled?{handled:!0}:{},synthetic:"boolean"==typeof b.synthetic?b.synthetic:a.synthetic,exception_id:g}:{type:"chained",source:f,synthetic:a.synthetic,exception_id:g,parent_id:e},i={type:a.type,value:a.value,mechanism:h};for(let b of(a.stack&&(i.stacktrace={type:"raw",frames:a.stack}),c.push(i),a.cause&&d(a.cause,g,"cause"),a.errors??[]))d(b,g,"member")};return d(a),c}buildParsingContext(a){return{chunkIdMap:function(a){let f=globalThis._posthogChunkIds,g=globalThis._debugIds;if(!f&&!g)return;let h=f?Object.keys(f):[],i=g?Object.keys(g):[];if(e&&G(f,h,c)&&G(g,i,d))return e;c=f?{...f}:void 0,d=g?{...g}:void 0,e={},b??={};let j=(c,d)=>{for(let f of c){let c=d[f];if(!c)continue;let g=b?.[f];if(g){e[g]=c;continue}let h=a(f);for(let a=h.length-1;a>=0;a--){let d=h[a]?.filename;if(d){e[d]=c,b[f]=d;break}}}};return g&&j(i,g),f&&j(h,f),e}(this.stackParser),skipFirstLines:a.skipFirstLines??1}}getAggregateErrors(a){try{if(A(a)){let b=Object.getPrototypeOf(a);for(let c=0;b&&c<100;c++){let c=Object.getOwnPropertyDescriptor(b,"constructor")?.value;if("function"==typeof c&&"AggregateError"===c.name){let b=a.errors;return s(b)?b:void 0}b=Object.getPrototypeOf(b)}}}catch{}}buildCoercingContext(a,b,c=0){let d=0,e=0,f=!1,g=new Set,h=[],i={},j=(a,b,c=0)=>{let j,l,m=k(b,c),n=m.apply;if(m.apply=b=>{h.push(a);try{return n(b)}finally{h.pop()}},c>4||c>0&&-1!==h.indexOf(a))return this.coerceFallback(m);let o="object"==typeof a&&null!==a||"function"==typeof a;if(0===c&&d>=50||o&&g.has(a))return;o&&g.add(a),0===c&&d++;let p=this.getAggregateErrors(a);f||=!!p;try{if(!(j=this.applyCoercers(a,m)))throw i}catch(a){if(a===i){0===c&&d--;return}if(!f)throw a;j=this.coerceFallback(m)}if(!p||d>=50)return j;try{l=p.length}catch{return j}if(!Number.isInteger(l)||l<0||l>0xffffffff)return j;let q=[];for(let a=0;d<50&&e<1e3&&a<l;a++){let c;e++;try{c=m.next(p[a])}catch{d++,c=this.coerceFallback(k(b+1))}c&&q.push(c)}return{...j,errors:q}},k=(c,d=0)=>({...b,syntheticException:0==c?b.syntheticException:void 0,mechanism:0==c?a:{},apply:a=>{let b=j(a,c,d+1);if(!b)throw i;return b},next:a=>j(a,c+1)}),l=k(c);return{...l,apply:a=>j(a,c)??this.coerceFallback(l)}}}a.s(["ErrorPropertiesBuilder",0,H],6762),a.i(6762);let I=/^([a-z][a-z0-9.+-]+):/i,J=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function K(a,b,c,d,e){let f={platform:a,filename:b,function:"<anonymous>"===c?"?":c,in_app:function(a){if(!a||"<anonymous>"===a)return!1;let b=I.exec(a);return!b||J.includes(b[1].toLowerCase())}(b)};return t(d)||(f.lineno=d),t(e)||(f.colno=e),f}let L=(a,b)=>{let c=-1!==a.indexOf("safari-extension"),d=-1!==a.indexOf("safari-web-extension");return c||d?[-1!==a.indexOf("@")?a.split("@")[0]:"?",c?`safari-extension:${b}`:`safari-web-extension:${b}`]:[a,b]},M=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,N=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,O=/\((\S*)(?::(\d+))(?::(\d+))\)/,P=(a,b)=>{let c=M.exec(a);if(c){let[,a,d,e]=c;return K(b,a,"?",+d,+e)}let d=N.exec(a);if(d){if(d[2]&&0===d[2].indexOf("eval")){let a=O.exec(d[2]);a&&(d[2]=a[1],d[3]=a[2],d[4]=a[3])}let[a,c]=L(d[1]||"?",d[2]);return K(b,c,a,d[3]?+d[3]:void 0,d[4]?+d[4]:void 0)}},Q=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,R=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,S=(a,b)=>{let c=Q.exec(a);if(c){if(c[3]&&c[3].indexOf(" > eval")>-1){let a=R.exec(c[3]);a&&(c[1]=c[1]||"eval",c[3]=a[1],c[4]=a[2],c[5]="")}let a=c[3],d=c[1]||"?";return[d,a]=L(d,a),K(b,a,d,c[4]?+c[4]:void 0,c[5]?+c[5]:void 0)}},T=/\(error: (.*)\)/;function U(a,b){return a.filename===b.filename&&a.function===b.function&&a.module===b.module&&a.lineno===b.lineno&&a.colno===b.colno}function V(a,b){let c=b.start;for(;c>0&&U(a[c-1],a[c-1+b.length]);)c--;return b.start-c}function W(a,b){let c=b.start+b.length,d=c;for(;d<a.length&&U(a[d],a[d-b.length]);)d++;return d-c}function X(a,...b){return(c,d=0)=>{let e=[],f=c.split("\n"),g=Math.min(f.length,d+1e3),h=[];for(let c=d;c<g;c++){let d=f[c];if(d.length>1024)continue;let g=T.test(d)?d.replace(T,"$1"):d;if(!g.match(/\S*Error: /)){for(let c of b){let b=c(g,a);if(b){e.push(b);let a=function(a){for(let b=1;b<=10;b++){let c=a.length-2*b;if(c<0)break;let d=!0;for(let e=0;e<b;e++)if(!U(a[c+e],a[c+b+e])){d=!1;break}if(d){for(let d=0;d<b;d++)a[c+d]=a[c+b+d];return a.length=c+b,{start:c,length:b}}}}(e);if(a){for(let b=h.length-1;b>=0;b--){let c=h[b];if(c.start+c.length<=a.start)break;h.pop()}h.push(a)}break}}if(function(a,b){let c=b[0],d=a.length-(c?V(a,c):0);for(let c of b)d-=W(a,c);return d}(e,h)>=50)break}}let i=[...h].sort((a,b)=>b.start-a.start),j=i[i.length-1];if(j){let a=V(e,j);for(let b of(e.splice(j.start-a,a),i))b.start-=a}for(let a of i)!function(a,b){let c=b.start+b.length,d=W(a,b);d&&a.splice(c+d===a.length?c:b.start,d)}(e,a);h.some(a=>0===a.start&&e.length===a.length)&&function(a){let b=a.map(a=>`${a.function}|${a.filename}|${a.lineno}|${a.colno}|${a.module}`),c=0;for(let a=1;a<b.length;a++)(function(a,b,c){for(let d=0;d<a.length;d++){let e=a[(b+d)%a.length],f=a[(c+d)%a.length];if(e!==f)return e<f}return!1})(b,a,c)&&(c=a);a.push(...a.splice(0,c))}(e);if(!e.length)return[];let k=Array.from(e);return k.reverse(),k.slice(0,50).map(a=>{var b;return{...a,filename:a.filename||((b=k)[b.length-1]||{}).filename,function:a.function||"?"}})}}let Y=/^\s*[-]{4,}$/,Z=/at (?:async (?!\((?!.*\)\s+\()))?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,$=/^Promise\.(?:all|any)$/,_=/^index \d+$/,aa=(a,b)=>{let c=a.match(Z);if(c){let a,d,e,f,g;if(c[1]){let b=(e=c[1]).lastIndexOf(".");if("."===e[b-1]&&b--,b>0){a=e.slice(0,b),d=e.slice(b+1);let c=a.indexOf(".Module");c>0&&(e=e.slice(c+1),a=a.slice(0,c))}f=void 0}d&&(f=a,g=d),"<anonymous>"===d&&(g=void 0,e=void 0),void 0===e&&(g=g||"?",e=f?`${f}.${g}`:g);let h=c[2]?.startsWith("file://")?c[2].slice(7):c[2],i="native"===c[5];return h?.match(/\/[A-Z]:/)&&(h=h.slice(1)),h||!c[5]||i||(h=c[5]),$.test(e)&&_.test(h||"")&&(h="node:internal/promise"),{filename:h?decodeURI(h):void 0,module:void 0,function:e,lineno:ab(c[3]),colno:ab(c[4]),in_app:function(a,b=!1){return!(b||a&&!a.startsWith("/")&&!a.match(/^[A-Z]:/)&&!a.startsWith(".")&&!a.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==a&&!a.includes("node_modules/")}(h||"",i),platform:b}}if(a.match(Y))return{filename:a,platform:b}};function ab(a){return parseInt(a||"",10)||void 0}a.s(["createStackParser",0,X,"nodeStackLineParser",0,aa],64583),a.i(64583),a.s([],51671),a.i(51671);class ac{match(a){return A(a)}coerce(a,b){let c=this.getStack(a),d=void 0===c?b.syntheticException?.stack:void 0;return{type:this.getType(a),value:this.getMessage(a,b),stack:c??d,cause:a.cause?b.next(a.cause):void 0,synthetic:!!d}}getType(a){return a.name||a.constructor.name}getMessage(a,b){let c=a.message;return c.error&&"string"==typeof c.error.message?String(c.error.message):String(c)}getStack(a){try{let b=a.stacktrace;if("string"==typeof b&&b.length>0)return b;let c=a.stack;return"string"==typeof c&&c.length>0?c:void 0}catch{return}}}a.s(["ErrorCoercer",0,ac],10692),a.i(10692),a.s([],75368),a.i(75368);let ad=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class ae{match(a){return"string"==typeof a}coerce(a,b){let[c,d]=this.getInfos(a);return{type:c??"Error",value:d??a,stack:b.syntheticException?.stack,synthetic:!0}}getInfos(a){let b="Error",c=a,d=a.match(ad);return d&&(b=d[1],c=d[2]),[b,c]}}a.s(["StringCoercer",0,ae],57802),a.i(57802);let af=["fatal","error","warning","log","info","debug"];function ag(a,b=40){let c=Object.keys(a);if(c.sort(),!c.length)return"[object has no keys]";let d="";for(let a of c){let c=d?`${d}, ${a}`:a;if(c.length>b)break;d=c}return d}class ah{match(a){return"object"==typeof a&&null!==a}coerce(a,b){let c=this.getErrorPropertyFromObject(a);return c?b.apply(c):{type:this.getType(a),value:this.getValue(a),stack:this.getStack(a)??b.syntheticException?.stack,level:this.isSeverityLevel(a.level)?a.level:"error",synthetic:!0}}getType(a){if(B(a))return a.constructor.name;let b="name"in a?a.name:void 0;return u(b)&&!v(b)?b:"Error"}getValue(a){if("name"in a&&"string"==typeof a.name){let b=`'${a.name}' captured as exception`;return"message"in a&&"string"==typeof a.message&&(b+=` with message: '${a.message}'`),b}if("message"in a&&"string"==typeof a.message)return a.message;let b=this.getObjectClassName(a),c=ag(a);return`${b&&"Object"!==b?`'${b}'`:"Object"} captured as exception with keys: ${c}`}isSeverityLevel(a){return u(a)&&!v(a)&&af.indexOf(a)>=0}getStack(a){try{if(u(a.stacktrace)&&a.stacktrace.length>0)return a.stacktrace;return u(a.stack)&&a.stack.length>0?a.stack:void 0}catch{return}}getErrorPropertyFromObject(a){for(let b in a)if(Object.prototype.hasOwnProperty.call(a,b)){let c=a[b];if(A(c))return c}}getObjectClassName(a){try{let b=Object.getPrototypeOf(a);return b?b.constructor.name:void 0}catch(a){return}}}a.s(["ObjectCoercer",0,ah],93874),a.i(93874);class ai{match(a){return B(a)}coerce(a,b){let c=a.constructor.name;return{type:c,value:`${c} captured as exception with keys: ${ag(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["EventCoercer",0,ai],46980),a.i(46980);class aj{match(a){return null===a||"object"!=typeof a}coerce(a,b){return{type:"Error",value:`Primitive value captured as exception: ${String(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["PrimitiveCoercer",0,aj],28150),a.i(28150),a.s([],98140),a.i(98140),a.s(["ErrorCoercer",0,ac,"EventCoercer",0,ai,"ObjectCoercer",0,ah,"PrimitiveCoercer",0,aj,"StringCoercer",0,ae],54253),a.i(54253);class ak{constructor(a){this._maxSize=a,this._cache=new Map}get(a){let b=this._cache.get(a);if(void 0!==b)return this._cache.delete(a),this._cache.set(a,b),b}set(a,b){this._cache.set(a,b)}reduce(){for(;this._cache.size>=this._maxSize;){let a=this._cache.keys().next().value;a&&this._cache.delete(a)}}}a.s(["ReduceableCache",0,ak],98966),a.i(98966);function al(){if("u">typeof process){let a=process.env.POSTHOG_RELEASE_ID?.trim();if(a)return a}let a=globalThis._posthogReleaseId;return"string"==typeof a&&a.length>0?a:void 0}a.s([],97383),a.i(97383),a.s(["getInjectedReleaseId",0,al],28861),a.i(28861),a.s(["ErrorCoercer",0,ac,"ErrorPropertiesBuilder",0,H,"EventCoercer",0,ai,"ObjectCoercer",0,ah,"PrimitiveCoercer",0,aj,"ReduceableCache",0,ak,"StringCoercer",0,ae,"createStackParser",0,X,"getInjectedReleaseId",0,al,"nodeStackLineParser",0,aa],60485);var am=a.i(60485),am=am,an=a.i(2157),ao=a.i(12714),ap=a.i(50227),aq=a.i(1457);let ar=new am.ReduceableCache(25),as=new am.ReduceableCache(20);async function at(a,b=ao.open,c){let d,e={};try{d=process.cwd()}catch{}for(let b=a.length-1;b>=0;b--){var f,g;let c=a[b],h=c?.filename;!(!c||"string"!=typeof h||"number"!=typeof c.lineno||(f=h).startsWith("node:")||f.endsWith(".min.js")||f.endsWith(".min.cjs")||f.endsWith(".min.mjs")||f.startsWith("data:")||void 0!==(g=c).lineno&&g.lineno>1e4||void 0!==g.colno&&g.colno>1e3)&&((0,ap.isAbsolute)(h)||void 0!==d)&&(e[h]||(e[h]=[]),e[h].push(c.lineno))}let h=Object.keys(e);if(0==h.length)return a;let i=[];for(let a of h){let f=ax(a,d);if(void 0===f||as.get(f))continue;let g=e[a];if(!g)continue;g.sort((a,b)=>a-b);let h=function(a){if(!a.length)return[];let b=0,c=a[0];if("number"!=typeof c)return[];let d=ay(c),e=[];for(;;){if(b===a.length-1){e.push(d);break}let c=a[b+1];if("number"!=typeof c)break;c<=d[1]?d[1]=c+7:(e.push(d),d=ay(c)),b++}return e}(g);if(h.every(a=>(function(a,b){let c=ar.get(a);if(void 0===c)return!1;for(let a=b[0];a<=b[1];a++)if(void 0===c[a])return!1;return!0})(f,a)))continue;let j=function(a,b,c){let d=a.get(b);return void 0===d?(a.set(b,c),c):d}(ar,f,{});i.push(av(a,h,j,f,b,c))}return await Promise.all(i).catch(()=>{}),a&&a.length>0&&function(a,b,c){for(let d of a)if(d.filename&&void 0===d.context_line&&"number"==typeof d.lineno){let a=ax(d.filename,c),e=void 0===a?void 0:b.get(a);if(void 0===e)continue;!function(a,b,c){if(void 0===b.lineno||void 0===c)return;b.pre_context=[];for(let d=az(a);d<a;d++){let a=c[d];if(void 0===a)return void aw(b);b.pre_context.push(a)}if(void 0===c[a])return aw(b);b.context_line=c[a];let d=function(a){return a+7}(a);b.post_context=[];for(let e=a+1;e<=d;e++){let a=c[e];if(void 0===a)break;b.post_context.push(a)}}(d.lineno,d,e)}}(a,ar,d),ar.reduce(),a}async function au(a,b,c){let d,e=!1;try{d=await b(a,an.constants.O_RDONLY|an.constants.O_NONBLOCK);let f=await d.stat();if(!f.isFile())return;if(f.size>0xa00000)return void c?.debug(`Skipping source context for oversized file ${a}: ${f.size} bytes exceeds 10485760`);return e=!0,d}catch{return}finally{d&&!e&&await d.close().catch(()=>{})}}async function av(a,b,c,d,e,f){let g=await au(a,e,f);return void 0===g?void as.set(d,1):new Promise(a=>{let e,f,h=!1;function i(b){h||(h=!0,b?.destroy(),g.close().then(a,a))}try{e=g.createReadStream({autoClose:!1,start:0,end:0x9fffff})}catch{as.set(d,1),i();return}try{f=(0,aq.createInterface)({input:e})}catch{as.set(d,1),i(e);return}let j=0,k=0,l=b[0];if(void 0===l)return void i(e);let m=l[0],n=l[1];function o(){as.set(d,1),f.close(),f.removeAllListeners(),i(e)}e.on("error",o),f.on("error",o),f.on("close",()=>i(e)),f.on("line",a=>{if(!(++j<m)&&(c[j]=function(a,b){let c=a,d=c.length;if(d<=150)return c;b>d&&(b=d);let e=Math.max(b-60,0);e<5&&(e=0);let f=Math.min(e+140,d);return f>d-5&&(f=d),f===d&&(e=Math.max(f-140,0)),c=c.slice(e,f),e>0&&(c=`...${c}`),f<d&&(c+="..."),c}(a,0),j>=n)){if(k===b.length-1){f.close(),f.removeAllListeners();return}let a=b[++k];if(void 0===a){f.close(),f.removeAllListeners();return}m=a[0],n=a[1]}})})}function aw(a){delete a.pre_context,delete a.context_line,delete a.post_context}function ax(a,b){return(0,ap.isAbsolute)(a)?JSON.stringify([null,a]):void 0===b?void 0:JSON.stringify([b,a])}function ay(a){return[az(a),a+7]}function az(a){return Math.max(1,a-7)}class aA{constructor(){this.events={},this.events={}}on(a,b){return this.events[a]||(this.events[a]=[]),this.events[a].push(b),()=>{this.events[a]=this.events[a].filter(a=>a!==b)}}emit(a,b){for(let c of this.events[a]||[])c(b);for(let c of this.events["*"]||[])c(a,b)}}let aB=a=>void 0===a||!0===a.failed?void 0:a.variant??a.enabled,aC=a=>{if("string"!=typeof a)return a;try{return JSON.parse(a)}catch{return a}},aD=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","bfcid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],aE=(a,b=[])=>{let c={},d=b=>{void 0!==a[b]&&(c[b]=a[b])};return aD.forEach(d),b.forEach(d),c},aF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function aG(a,b){return"string"==typeof a&&aF.test(a)?a:b()}function aH(a,b){let c=Error(b);try{Object.defineProperty(c,"name",{value:a,writable:!0,enumerable:!0,configurable:!0})}catch{}return c}function aI(a){return a?.replace(/\/+$/,"")}function aJ(a){return a?a.split("#")[0]:a}async function aK(a,b){let c=null;for(let d=0;d<b.retryCount+1;d++){d>0&&await new Promise(a=>setTimeout(a,b.retryDelay));try{return await a()}catch(a){if(c=a,!b.retryCheck(a))throw a}}throw c}function aL(){return new Date().toISOString()}function aM(a,b){let c=setTimeout(a,b);return c?.unref&&c?.unref(),c}async function aN(a,b,c){let d;try{return await Promise.race([a,new Promise((a,e)=>{d=aM(()=>{try{c?.(),a()}catch(a){e(a)}},b)})])}finally{clearTimeout(d)}}function aO(a){return Promise.all(a.map(a=>(a??Promise.resolve()).then(a=>({status:"fulfilled",value:a}),a=>({status:"rejected",reason:a}))))}let aP=a=>{throw aH("NativeGzipValidationError",`Native gzip produced invalid output: ${a}`)},aQ=async(a,b)=>{a.size<18&&aP("too-short");let c=new Uint8Array(await a.slice(0,10).arrayBuffer());c.length>=2&&31===c[0]&&139===c[1]&&8===c[2]||aP("invalid-header");let d=new DataView(await a.slice(a.size-8).arrayBuffer());d.getUint32(0,!0)!==(a=>{let b=(()=>{if(f)return f;f=[];for(let a=0;a<256;a++){let b=a;for(let a=0;a<8;a++)b=1&b?0xedb88320^b>>>1:b>>>1;f[a]=b>>>0}return f})(),c=0xffffffff;for(let d=0;d<a.length;d++)c=b[(c^a[d])&255]^c>>>8;return(0xffffffff^c)>>>0})(b)&&aP("invalid-crc");let e=b.length>>>0;d.getUint32(4,!0)!==e&&aP("invalid-size")};async function aR(a,b=!0,c){try{let b=new TextEncoder().encode(a),c=new globalThis.CompressionStream("gzip"),d=c.writable.getWriter(),e=d.write(b).then(()=>d.close()).catch(async a=>{try{await d.abort(a)}catch{}throw a}),f=new Response(c.readable).blob(),[g]=await Promise.all([f,e]);return await aQ(g,b),g}catch(a){if(c?.rethrow)throw a;return b&&console.error("Failed to gzip compress data",a),null}}let aS="0123456789abcdef";class aT{constructor(a){this.bytes=a}static ofInner(a){if(16===a.length)return new aT(a);throw TypeError("not 128-bit length")}static fromFieldsV7(a,b,c,d){if(!Number.isInteger(a)||!Number.isInteger(b)||!Number.isInteger(c)||!Number.isInteger(d)||a<0||b<0||c<0||d<0||a>0xffffffffffff||b>4095||c>0x3fffffff||d>0xffffffff)throw RangeError("invalid field value");let e=new Uint8Array(16);return e[0]=a/0x10000000000,e[1]=a/0x100000000,e[2]=a/0x1000000,e[3]=a/65536,e[4]=a/256,e[5]=a,e[6]=112|b>>>8,e[7]=b,e[8]=128|c>>>24,e[9]=c>>>16,e[10]=c>>>8,e[11]=c,e[12]=d>>>24,e[13]=d>>>16,e[14]=d>>>8,e[15]=d,new aT(e)}static parse(a){let b;switch(a.length){case 32:b=/^[0-9a-f]{32}$/i.exec(a)?.[0];break;case 36:b=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(a)?.slice(1,6).join("");break;case 38:b=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(a)?.slice(1,6).join("");break;case 45:b=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(a)?.slice(1,6).join("")}if(b){let a=new Uint8Array(16);for(let c=0;c<16;c+=4){let d=parseInt(b.substring(2*c,2*c+8),16);a[c+0]=d>>>24,a[c+1]=d>>>16,a[c+2]=d>>>8,a[c+3]=d}return new aT(a)}throw SyntaxError("could not parse UUID string")}toString(){let a="";for(let b=0;b<this.bytes.length;b++)a+=aS.charAt(this.bytes[b]>>>4),a+=aS.charAt(15&this.bytes[b]),(3===b||5===b||7===b||9===b)&&(a+="-");return a}toHex(){let a="";for(let b=0;b<this.bytes.length;b++)a+=aS.charAt(this.bytes[b]>>>4),a+=aS.charAt(15&this.bytes[b]);return a}toJSON(){return this.toString()}getVariant(){let a=this.bytes[8]>>>4;if(a<0)throw Error("unreachable");if(a<=7)return this.bytes.every(a=>0===a)?"NIL":"VAR_0";if(a<=11)return"VAR_10";if(a<=13)return"VAR_110";if(a<=15)return this.bytes.every(a=>255===a)?"MAX":"VAR_RESERVED";throw Error("unreachable")}getVersion(){return"VAR_10"===this.getVariant()?this.bytes[6]>>>4:void 0}clone(){return new aT(this.bytes.slice(0))}equals(a){return 0===this.compareTo(a)}compareTo(a){for(let b=0;b<16;b++){let c=this.bytes[b]-a.bytes[b];if(0!==c)return Math.sign(c)}return 0}}class aU{constructor(a){this.timestamp=0,this.counter=0,this.random=a??aV()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(a,b){let c=this.generateOrAbortCore(a,b);return void 0===c&&(this.timestamp=0,c=this.generateOrAbortCore(a,b)),c}generateOrAbortCore(a,b){if(!Number.isInteger(a)||a<1||a>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(b<0||b>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(a>this.timestamp)this.timestamp=a,this.resetCounter();else{if(!(a+b>=this.timestamp))return;this.counter++,this.counter>0x3ffffffffff&&(this.timestamp++,this.resetCounter())}return aT.fromFieldsV7(this.timestamp,Math.trunc(this.counter/0x40000000),0x3fffffff&this.counter,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let a=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return a[6]=64|a[6]>>>4,a[8]=128|a[8]>>>2,aT.ofInner(a)}}let aV=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),aW=()=>aX().toString(),aX=()=>(g||(g=new aU)).generate();class aY{add(a){let b=aW(),c=++this.nextId;return this.promiseByIds[b]={id:c,promise:a},a.catch(()=>{}).finally(()=>{delete this.promiseByIds[b]}),a}async join(){let a=Object.values(this.promiseByIds).map(a=>a.promise),b=a.length;for(;b>0;)await Promise.all(a),b=(a=Object.values(this.promiseByIds).map(a=>a.promise)).length}getPromises(a=[],b=this.nextId){let c=new Set(a);return Object.values(this.promiseByIds).filter(a=>a.id<=b&&!c.has(a.promise)).map(a=>a.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}let aZ=(a,b,c)=>{function d(e,...f){b(()=>{(0,c[e])(a,...f)})}return{debug:(...a)=>{d("debug",...a)},info:(...a)=>{d("log",...a)},warn:(...a)=>{d("warn",...a)},error:(...a)=>{d("error",...a)},critical:(...b)=>{c.error(a,...b)},createLogger:d=>aZ(`${a} ${d}`,b,c)}};function a$(a,b=Date.now(),c=3e5){if("string"!=typeof a||!a)return;let d=a.trim(),e=/^\d+\s*,/.test(d)?d.slice(0,d.indexOf(",")).trim():d;if(/^\d+$/.test(e)){let a=1e3*Math.min(Number(e),c/1e3);return a>0?a:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(e))return;let f=Date.parse(/^\w{3} \w{3} /.test(e)?e+" GMT":e)-b;if(Number.isFinite(f)&&!(f<=0))return Math.min(f,c)}class a_{record(a){if("too-large"===a.kind)return;if("retry-later"!==a.kind)return void this.reset();if(!a.retryAfterMs)return;let b=this.isOpen(),c=Date.now(),d=Math.min(a.retryAfterMs,3e5);if(!b){this._installedAt=c,this._until=c+d;return}this._until=Math.max(this._until,Math.min(c+d,this._installedAt+3e5))}remainingMs(){let a=Date.now();if(a<this._installedAt-5e3)return this.reset(),0;let b=Math.min(3e5,Math.max(0,this._until-a));return 0===b&&this.reset(),b}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}}class a0 extends Error{constructor(a,b,c,d){super("HTTP error while fetching PostHog: status="+a.status+", reqByteLength="+b),this.response=a,this.reqByteLength=b,this.responseBodyDeadline=c,this.abortController=d,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return a$(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let a=aH("AbortError","Response body read timed out");this.cancelResponseBody(a),this.responseBodyTextPromise=Promise.reject(a)}else{let a,b=new Promise((a,b)=>{this.responseBodyTimer=aM(()=>{this._bodyReadTimedOut=!0;let a=aH("AbortError","Response body read timed out");b(a),this.cancelResponseBody(a)},this.responseBodyDeadline-Date.now())});try{a=Promise.resolve(this.response.text())}catch(b){a=Promise.reject(b)}this.responseBodyTextPromise=Promise.race([a,b]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(a=>JSON.parse(a))}cancelResponseBody(a){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(a),(async()=>{try{await this.response.body?.cancel()}catch{}})()}}class a1 extends Error{constructor(a){super("Network error while fetching PostHog",a instanceof Error?{cause:a}:{}),this.error=a,this.name="PostHogFetchNetworkError"}}async function a2(a){if(a instanceof a0){let b="";try{b=await a.text}catch{a.bodyReadTimedOut&&(b="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${a.message}, response body=${b}`,a)}else console.error("Error while flushing PostHog",a);return Promise.resolve()}function a3(a){return a instanceof a1}function a4(a){if(a instanceof a0)return 502===a.status||504===a.status;if(!(a instanceof a1))return!1;let b=a.error;return"ECONNREFUSED"!==(b?.code??b?.cause?.code)}function a5(a){try{if("string"!=typeof a)return a instanceof Uint8Array?a.byteLength:a.size;if("u">typeof Buffer)return Buffer.byteLength(a,"utf8");return new TextEncoder().encode(a).length}catch{return 0}}function a6(a){return"object"==typeof a&&a instanceof a0&&413===a.status}function a7(a){return a instanceof a0?408===a.status||429===a.status||a.status>=500:a3(a)}function a8(a){return null!==a&&"object"==typeof a&&!Array.isArray(a)}let a9="default";class ba{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new H([new ac,new ah,new ae,new aj],X("web:javascript",P,S))}getEvaluationRuntime(){}getFlagsResponseFormat(){return{version:2,read:a=>(a=>{if("flags"in a){let b,c=Object.fromEntries(Object.entries(a.flags??{}).map(([a,b])=>[a,aB(b)]).filter(([,a])=>void 0!==a)),d=Object.fromEntries(Object.keys(b=a.flags??{}).filter(a=>{let c=b[a];return!c.failed&&c.enabled&&c.metadata&&void 0!==c.metadata.payload}).map(a=>{let c=b[a].metadata?.payload;return[a,c?aC(c):void 0]}));return{...a,featureFlags:c,featureFlagPayloads:d}}{let b=a.featureFlags??{},c=Object.fromEntries(Object.entries(a.featureFlagPayloads||{}).map(([a,b])=>[a,aC(b)])),d=Object.fromEntries(Object.entries(b).map(([a,b])=>{var d,e;return[a,{key:a,enabled:"string"==typeof(d=b)||d,variant:"string"==typeof d?d:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:(e=c[a])?JSON.stringify(e):void 0,description:void 0}}]}));return{...a,featureFlags:b,featureFlagPayloads:c,flags:d}}})(a)}}get apiKey(){return this.projectToken}constructor(a,b={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new aY,this._events=new aA,this._isInitialized=!1;let c="string"==typeof a?a.trim():"",d="string"==typeof b.host?b.host.trim():"",e=!c;this._logger=function(a,b=a=>a()){return aZ(a,b,function(a=console){return{log:a.log.bind(a),warn:a.warn.bind(a),error:a.error.bind(a),debug:a.debug.bind(a)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),e&&this._logger.error("You must pass your PostHog project token. The client will be disabled."),this.projectToken=c,this.host=aI(d||"https://us.i.posthog.com"),this.flushAt=b.flushAt?Math.max(b.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,b.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,b.maxQueueSize??1e3),this.flushInterval=b.flushInterval??1e4,this.preloadFeatureFlags=b.preloadFeatureFlags??!0,this.defaultOptIn=b.defaultOptIn??!0,this.disableSurveys=b.disableSurveys??!1,this._retryOptions={retryCount:b.fetchRetryCount??3,retryDelay:b.fetchRetryDelay??3e3,retryCheck:a7},this.requestTimeout=b.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=b.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=b.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=b.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=b.disableGeoip??!0,this.disabled=(b.disabled??!1)||e,this.historicalMigration=b?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=b?.evaluationContexts??b?.evaluationEnvironments,b?.evaluationEnvironments&&!b?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!("CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&"function"==typeof Response.prototype.blob)||(b?.disableCompression??!1)}logMsgIfDebug(a){this.isDebug&&a()}wrap(a){return this.disabled?void this._logger.warn("The client is disabled"):this._isInitialized?a():void this._initPromise.then(()=>a())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(k.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(k.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(k.OptedOut,!0)})}on(a,b){return this._events.on(a,b)}debug(a=!0){if(this.removeDebugCallback?.(),a){let a=this.on("*",(a,b)=>this._logger.info(a,b));this.removeDebugCallback=()=>{a(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(a){let b=a.properties||{},c=this.mergeCommonEventProperties(b);var d=c;for(let a of Object.keys(b))(a.startsWith("$feature/")||"$active_feature_flags"===a)&&(d[a]=b[a]);return"$feature_flag_called"===a.event&&!1===c.$feature_flag_has_experiment&&this.isMinimalFlagCalledEventsEnabled()&&(c=aE(c)),{distinct_id:a.distinct_id,event:a.event,properties:c}}mergeCommonEventProperties(a){return{...a,...this.getCommonEventProperties()}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(a){return this.promiseQueue.add(a)}identifyStateless(a,b,c){this.wrap(()=>{let d={...this.buildPayload({distinct_id:a,event:"$identify",properties:b})};this.enqueue("identify",d,c)})}async identifyStatelessImmediate(a,b,c){let d={...this.buildPayload({distinct_id:a,event:"$identify",properties:b})};await this.sendImmediate("identify",d,c)}captureStateless(a,b,c,d){this.wrap(()=>{let e=this.buildPayload({distinct_id:a,event:b,properties:c});this.enqueue("capture",e,d)})}async captureStatelessImmediate(a,b,c,d){let e=this.buildPayload({distinct_id:a,event:b,properties:c});await this.sendImmediate("capture",e,d)}aliasStateless(a,b,c,d){this.wrap(()=>{let e=this.buildPayload({event:"$create_alias",distinct_id:b,properties:{...c||{},distinct_id:b,alias:a}});this.enqueue("alias",e,d)})}async aliasStatelessImmediate(a,b,c,d){let e=this.buildPayload({event:"$create_alias",distinct_id:b,properties:{...c||{},distinct_id:b,alias:a}});await this.sendImmediate("alias",e,d)}groupIdentifyStateless(a,b,c,d,e,f){this.wrap(()=>{let g=this.buildPayload({distinct_id:e||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{},...f||{}}});this.enqueue("capture",g,d)})}async groupIdentifyStatelessImmediate(a,b,c,d,e,f){let g=this.buildPayload({distinct_id:e||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{},...f||{}}});await this.sendImmediate("capture",g,d)}async getRemoteConfig(){await this._initPromise;let a=this.host;"https://us.i.posthog.com"===a?a="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===a&&(a="https://eu-assets.i.posthog.com");let b=`${a}/array/${this.projectToken}/config`,c={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(b,c,{type:"required",consume:a=>a.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(a=>{this._logger.error("Remote config could not be loaded",a),this._events.emit("error",a)})}async getFlags(a,b={},c={},d={},e={},f=!1){await this._initPromise;let g=this.getFlagsResponseFormat(),h=`${this.host}/flags/?v=${g.version}${f?"&config=true":""}`,i={token:this.projectToken,distinct_id:a,groups:b,person_properties:c,group_properties:d,...e};c.$device_id&&(i.$device_id=c.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(i.evaluation_contexts=this.evaluationContexts);let j=this.getEvaluationRuntime();j&&(i.evaluation_runtime=j);let k={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(i)};return this._logger.info("Flags URL",h),this.fetchWithRetry(h,k,{type:"required",consume:a=>a.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:a4},this.featureFlagsRequestTimeoutMs).then(a=>({success:!0,response:g.read(a)})).catch(a=>(this._events.emit("error",a),{success:!1,error:this.categorizeRequestError(a)}))}categorizeRequestError(a){if(a instanceof a0)return{type:"api_error",statusCode:a.status};if(a instanceof a1){let b=a.error;return b instanceof Error&&("AbortError"===b.name||"TimeoutError"===b.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagDetailStateless(a,b,c,d,e,f);if(void 0===g)return{response:void 0,requestId:void 0};let h=aB(g.response);return void 0===h&&(h=!1),{response:h,requestId:g.requestId}}async getFeatureFlagDetailStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagDetailsStateless(b,c,d,e,f,[a]);if(void 0!==g)return{response:g.flags[a],requestId:g.requestId,evaluatedAt:g.evaluatedAt}}async getFeatureFlagPayloadStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagPayloadsStateless(b,c,d,e,f,[a]);if(!g)return;let h=g[a];return void 0===h?null:h}async getFeatureFlagPayloadsStateless(a,b={},c={},d={},e,f){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(a,b,c,d,e,f)).payloads}async getFeatureFlagsStateless(a,b={},c={},d={},e,f){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(a,b,c,d,e,f)}async getFeatureFlagsAndPayloadsStateless(a,b={},c={},d={},e,f){await this._initPromise;let g=await this.getFeatureFlagDetailsStateless(a,b,c,d,e,f);return g?{flags:g.featureFlags,payloads:g.featureFlagPayloads,requestId:g.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(a,b={},c={},d={},e,f){await this._initPromise;let g={geoip_disable:e??this.disableGeoip};f&&(g.flag_keys_to_evaluate=f);let h=await this.getFlags(a,b,c,d,g);if(!h.success)return;let i=h.response;return(i.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),i.quotaLimited?.includes("feature_flags"))?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:i?.requestId,quotaLimited:i.quotaLimited}):i}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let a=`${this.host}/api/surveys/?token=${this.projectToken}`,b={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},c=await this.fetchWithRetry(a,b,{type:"required",consume:a=>{if(200!==a.status||!a.json){let b=`Surveys API could not be loaded: ${a.status}`,c=Error(b);return this._logger.error(c),this._events.emit("error",Error(b)),Promise.resolve(void 0)}return a.json()}}).catch(a=>{this._logger.error("Surveys API could not be loaded",a),this._events.emit("error",a)}),d=c?.surveys;return d&&this._logger.info("Surveys fetched from API: ",JSON.stringify(d)),d??[]}get props(){return this._props||(this._props=this.getPersistedProperty(k.Props)),this._props||{}}set props(a){this._props=a}async register(a){this.wrap(()=>{this.props={...this.props,...a},this.setPersistedProperty(k.Props,this.props)})}async unregister(a){this.wrap(()=>{delete this.props[a],this.setPersistedProperty(k.Props,this.props)})}processBeforeEnqueue(a){return a}async flushStorage(){}getQueueRouteKey(a){return a9}persistedQueueKeyForRoute(a){return k.Queue}getActiveQueueRoutes(){return[a9]}getRouteQueue(a){return this.getPersistedProperty(this.persistedQueueKeyForRoute(a))||[]}enqueue(a,b,c,d){this.wrap(()=>{if(this.optedOut)return void this._events.emit(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let e=this.prepareMessage(b,c);if(null===(e=this.processBeforeEnqueue(e)))return;e=this.normalizeMessage(e);let f=this.persistedQueueKeyForRoute(d??this.getQueueRouteKey(e)),g=this.getPersistedProperty(f)||[];g.length>=this.maxQueueSize&&(g.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),g.push({message:e}),this.setPersistedProperty(f,g),this._events.emit(a,e),g.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=aM(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(a,b,c,d){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let e=this.prepareMessage(b,c);if(null!==(e=this.processBeforeEnqueue(e))){e=this.normalizeMessage(e);try{await this.sendBatch([e],void 0,d??this.getQueueRouteKey(e))}catch(a){this._events.emit("error",a)}}}normalizeMessage(a){let{type:b,library:c,library_version:d,...e}=a,f=a8(e.properties)?e.properties:void 0;return void 0!==c&&f?.$lib===void 0&&(f={...f||{},$lib:c}),void 0!==d&&f?.$lib_version===void 0&&(f={...f||{},$lib_version:d}),f&&(e.properties=f),e.uuid=aG(e.uuid,aW),e}normalizeTimestampForWire(a){let b=a instanceof Date?a:"string"==typeof a?new Date(a):null;if(!b||Number.isNaN(b.getTime()))return a;let c=b.toISOString(),d="string"==typeof a?a.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return d&&d.length>3?c.replace(/\.\d{3}Z$/,`.${d}Z`):c}prepareMessage(a,b){let c={...a,timestamp:b?.timestamp?b?.timestamp:aL(),uuid:aG(b?.uuid,aW)};return(b?.disableGeoip??this.disableGeoip)&&(a8(c.properties)||(c.properties={}),c.properties.$geoip_disable=!0),c.distinctId&&(c.distinct_id=c.distinctId,delete c.distinctId),c}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async a=>{await a2(a)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(a,b=[]){let c=b.filter(a=>!!a),d=0;for(;;){let b=this.promiseQueue.getPromises([...c,...this.flushPromises],a);if(0===b.length)return;d>0&&this._logger.debug(`flush() re-checking ${b.length} pending promise(s) before flushing`),await Promise.all(b.map(a=>a.catch(()=>{}))),d++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(a){if(this.disabled)return Promise.resolve();if(!a&&this.pendingFlushPromise)return this.pendingFlushPromise;let b=this.flushPromise,c=this.promiseQueue.maxId,d=Promise.resolve().then(()=>{if(a)return this.waitForPendingPromises(c,[b,d])}).then(()=>aO([b])).then(()=>(this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=d,this.flushPromise=d,this.flushPromises.add(d),this.addPendingPromise(d),aO([d]).then(()=>{this.flushPromises.delete(d),this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this.flushPromise===d&&(this.flushPromise=null)}),d}getCustomHeaders(){let a=this.getCustomUserAgent(),b={};return a&&""!==a&&(b["User-Agent"]=a),b}compressPayload(a){return aR(a,this.isDebug)}getBatchEndpointPath(a){return"/batch/"}async sendBatch(a,b,c=a9){let d={api_key:this.projectToken,batch:a.map(a=>{if(!a)return a;let b=this.normalizeTimestampForWire(a.timestamp);return b===a.timestamp?a:{...a,timestamp:b}}),sent_at:aL()};this.historicalMigration&&(d.historical_migration=!0);let e=n(d),f=`${this.host}${this.getBatchEndpointPath(c)}`,g=this.disableCompression?null:await this.compressPayload(e),h={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==g&&{"Content-Encoding":"gzip"}},body:g||e};await this.fetchWithRetry(f,h,{type:"successful-write"},b)}async _flush(){let a;this.clearFlushTimer(),await this._initPromise;let b=this.getActiveQueueRoutes();if(!b.some(a=>this.getRouteQueue(a).length>0))return;let c=[];for(let d of b)try{await this._flushRoute(d,c)}catch(b){void 0===a&&(a=b)}if(void 0!==a)throw a;this._events.emit("flush",c)}async _flushRoute(a,b){let c=this.persistedQueueKeyForRoute(a),d=this.getPersistedProperty(c)||[];if(!d.length)return;let e=d.length,f=0;for(;d.length>0&&f<e;){let e=d.slice(0,this.maxBatchSize),g=e.map(a=>void 0===a.message?a.message:this.normalizeMessage(a.message)),h=async()=>{let a=this.getPersistedProperty(c)||[],b=[...e],f=a.filter(a=>{let c=a.message?.uuid,d=b.findIndex(b=>b===a||"string"==typeof c&&c.length>0&&b.message?.uuid===c);return -1===d||(b.splice(d,1),!1)});this.setPersistedProperty(c,f),d=f,this._dequeuedMessagesCount+=e.length,await this.flushStorage()},i={retryCheck:a=>!a6(a)&&a7(a)};try{await this.sendBatch(g,i,a)}catch(a){if(a6(a)&&g.length>1){this.maxBatchSize=Math.max(1,Math.floor(g.length/2)),this._logger.warn(`Received 413 when sending batch of size ${g.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw a instanceof a1||await h(),this._events.emit("error",a),a}await h(),b.push(...g),f+=g.length}}async _sendOtlpBatch({path:a,auth:b,payload:c}){let d;if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};try{d=JSON.stringify(c)}catch(b){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${a} batch; reporting it as too large`,b)),{kind:"too-large",measuredLocally:!0}}let e=a5(d);if(e>0xa00000)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${a} batch of ${e} bytes: the endpoint accepts at most 10485760`)),{kind:"too-large",measuredLocally:!0};let f="bearer"===b?`${this.host}/i/v1/${a}`:`${this.host}/i/v1/${a}?token=${encodeURIComponent(this.projectToken)}`,g=this.disableCompression?null:await this.compressPayload(d),h=g||d,i={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",..."bearer"===b&&{Authorization:`Bearer ${this.projectToken}`},...null!==g&&{"Content-Encoding":"gzip"}},body:h};try{return await this.fetchWithRetry(f,i,{type:"successful-write"},{retryCheck:a=>!a6(a)&&(!(a instanceof a0)||void 0===a.retryAfterMs)&&a7(a)}),{kind:"ok"}}catch(a){if(a6(a))return{kind:"too-large"};if(a7(a)){let b=a instanceof a0?a.retryAfterMs:void 0;return{kind:"retry-later",error:a,...void 0!==b&&{retryAfterMs:b}}}return{kind:"fatal",error:a}}}async _sendLogsBatch(a){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:a})}async _sendMetricsBatch(a){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:a})}async _sendTracesBatch(a){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:a})}async fetchWithRetry(a,b,c,d,e){let f=a5(b.body?b.body:""),g={...this._retryOptions,...d},h=0;return await aK(async()=>{let d,g,i;h++;let j=new AbortController,k=e??this.requestTimeout,l=Date.now()+k,m=new Promise((a,b)=>{d=aM(()=>{let a=aH("AbortError",`Request timed out after ${k}ms`);b(a),j.abort(a)},k)}),n=!1,o=()=>i??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let d;try{d=this.fetch(a,{signal:j.signal,...b})}catch(a){throw new a1(a)}d.then(a=>{j.signal.aborted&&!n&&Promise.resolve(a.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([d,m]),n=!0}catch(a){throw new a1(a)}let e="no-cors"===b.mode,h="successful-write"===c.type?300:400;if(!e&&(g.status<200||g.status>=h))throw new a0(g,f,l,j);if("successful-write"===c.type){try{await Promise.race([o(),m])}catch{}return}try{return await Promise.race([c.consume(g),m])}catch(a){if(j.signal.aborted)throw new a1(a);throw a}}finally{clearTimeout(d),j.signal.aborted&&g&&o()}},{...g,retryCheck:a=>{let b=g.retryCheck(a);return b&&h<=g.retryCount&&a instanceof a0&&a.cancelResponseBody(),b}})}async _shutdown(a=3e4){await this._initPromise;let b=!1;if(this.clearFlushTimer(),!this.disabled)return aN((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(a=>this.getRouteQueue(a).length>0);){let a=this._dequeuedMessagesCount;if(await this.flush(),b)break;if(this._dequeuedMessagesCount===a){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(a){if(!("object"==typeof a&&(a instanceof a0||a3(a))))throw a;await a2(a)}})(),a,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:a}),b=!0})}async shutdown(a=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(a).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}let bb="[Circular]",bc="[Truncated]",bd="[Unserializable]";function be(a){let b="";for(let c=0;c<a.length;c++){let d=a.charCodeAt(c);if(d>=55296&&d<=56319){let d=a.charCodeAt(c+1);d>=56320&&d<=57343?(b+=a[c]+a[c+1],c++):b+="�"}else b+=d>=56320&&d<=57343?"�":a[c]}return b}function bf(a,b){if(!b)return a;let c=[];try{c=Object.keys(b)}catch{c=[]}for(let d of c){let c;try{c=b[d]}catch{c=bd}Object.defineProperty(a,d,{value:c,enumerable:!0,writable:!0,configurable:!0})}return a}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let bg=Object.prototype.propertyIsEnumerable;function bh(a,b){try{return bi(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function bi(a,b,c,d){let e=[];for(let f in a)if(bg.call(a,f)){if(!f){b?.debug("Dropping an attribute with an empty key");continue}if(e.length>=1e3||c.remainingNodes<=0){b?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let g=a[f];if(w(g)||t(g))continue;e.push({key:be(f),value:function a(b,c,d,e){if(d.remainingNodes<=0)return{stringValue:bc};if(d.remainingNodes--,z(b))return{boolValue:b};if("bigint"==typeof b){let a,d;return a=b.toString(),b>=(d=BigInt("9223372036854775808"))||b<-d?(c?.debug(`Attribute ${a} is outside the int64 range; encoding it as a string`),{stringValue:a}):{intValue:a}}if("number"==typeof b){if(!Number.isFinite(b))return{stringValue:String(b)};if(Number.isInteger(b)){if(Number.isSafeInteger(b))return{intValue:String(b)};if("u"<typeof BigInt)return{stringValue:String(b)};let a=BigInt(b).toString();return b>=0x8000000000000000||b<-0x8000000000000000?(c?.debug(`Attribute ${a} is outside the int64 range; encoding it as a string`),{stringValue:a}):{intValue:a}}return{doubleValue:b}}if("string"==typeof b)return{stringValue:be(b)};if("function"==typeof b)return{stringValue:"[Function]"};if("symbol"==typeof b)return{stringValue:String(b)};if("object"==typeof b&&null!==b){if(d.ancestors.has(b))return{stringValue:bb};if(e>=20)return{stringValue:bc};if(b instanceof Date){let a=Number.isFinite(b.getTime())?b.toISOString():String(b);return{stringValue:"string"==typeof a?be(a):String(a)}}d.ancestors.add(b);try{try{let f=b.toJSON;if("function"==typeof f)return a(f.call(b),c,d,e+1)}catch{}if(s(b))return{arrayValue:{values:function(b,c,d,e){let f=[],g=Math.min(b.length,1e3),h=0;for(;h<g&&d.remainingNodes>0;h++)try{let g=h in b?b[h]:void 0;if(x(g))continue;f.push(a(g,c,d,e))}catch{f.push({stringValue:bd})}return b.length>h&&f.push({stringValue:bc}),f}(b,c,d,e+1)}};return{kvlistValue:{values:bi(b,c,d,e+1)}}}finally{d.ancestors.delete(b)}}return{stringValue:be(String(b))}}(g,b,c,d)})}catch{e.push({key:be(f),value:{stringValue:bd}})}}return e}function bj(a,b,c){return{...bf({},a.resourceAttributes),"service.name":a.serviceName||"unknown_service",...a.environment&&{"deployment.environment":a.environment},...a.serviceVersion&&{"service.version":a.serviceVersion},"telemetry.sdk.name":b,"telemetry.sdk.version":c}}let bk=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function bl(a,b){let c=bf({},a),d={};for(let a of bk)Object.prototype.hasOwnProperty.call(c,a)&&(d[a]=c[a],delete c[a]);return[...bh(c,b),...bh(d,b)]}let bm={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"},bn={text:"INFO",number:9},bo={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:bn,warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}};class bp{constructor(a){this._onFire=a,this._firesAt=0}get pending(){return!!this._timer}arm(a){this.clear(),this._firesAt=Date.now()+a,this._timer=aM(()=>{this._timer=void 0,this._onFire()},a)}armNoEarlierThan(a){this._timer&&Date.now()+a<=this._firesAt||this.arm(a)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}function bq(){return .75+.25*Math.random()*2}function br(a,b,c,d){let e=Math.min(Math.max(0,b-1),6),f=a*2**e;return Math.round((void 0===d?f:Math.min(f,Math.max(d,a)))*c)}class bs{constructor(a,b,c,d,e,f=()=>Promise.resolve(),g,h=()=>!1){this._instance=a,this._config=b,this._logger=c,this._getContext=d,this._onReady=e,this._waitForStoragePersist=f,this._scopeName=g,this._isConsentWithdrawn=h,this._flushTimer=new bp(()=>this._flushInBackground()),this._flushPromise=null,this._evictedSinceAdvance=0,this._queueGeneration=0,this._backgroundFlushPromise=null,this._retryAfter=new a_,this._consecutiveFlushFailures=0,this._flushJitter=1,this._intervalWindowStart=0,this._intervalLogCount=0,this._droppedWarned=!1,this._maxBufferSize=b.maxBufferSize,this._maxQueueSize=Math.max(b.maxQueueSize??b.maxBufferSize,b.maxBufferSize),this._flushIntervalMs=b.flushIntervalMs,this._maxBatchRecordsPerPost=b.maxBatchRecordsPerPost,this._rateCapWindowMs=b.rateCapWindowMs,this._maxLogsPerInterval=b.maxLogsPerInterval}clearQueue(){this._queueGeneration++,this._instance.setPersistedProperty(k.LogsQueue,[])}get throttled(){return this._retryAfter.isOpen()}reset(){this._flushTimer.clear(),this._intervalWindowStart=0,this._intervalLogCount=0,this._droppedWarned=!1,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter.reset(),this._maxBatchRecordsPerPost=this._config.maxBatchRecordsPerPost}onReconnect(){if(this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter.isOpen()){this._hasQueuedRecords()&&this._armFlushTimer();return}this._flushInBackground()}captureLog(a,b){if(this._instance.isDisabled||this._instance.optedOut||!a?.body)return;let c=this._runBeforeSend(a);if(null===c)return;if(!c.body)return void this._logger.info("Log was rejected in beforeSend function");if(!this._checkRateLimit())return;let d={record:function(a,b,c,d){let{text:e,number:f}=bo[a.level||"info"]||bn,g=function(a=Date.now()){return String(a)+"000000"}(y(d)?d:void 0),h={};b.distinctId&&(h.posthogDistinctId=b.distinctId),b.sessionId&&(h.sessionId=b.sessionId),b.windowId&&(h["window.id"]=b.windowId),x(b.sessionStartTimestamp)||(h.sessionStartTimestamp=String(b.sessionStartTimestamp)),x(b.lastActivityTimestamp)||(h.lastActivityTimestamp=String(b.lastActivityTimestamp)),b.currentUrl&&(h["url.full"]=b.currentUrl),b.screenName&&(h["screen.name"]=b.screenName),b.appState&&(h["app.state"]=b.appState),b.activeFeatureFlags&&b.activeFeatureFlags.length>0&&(h.feature_flags=b.activeFeatureFlags);let i={...h},j=a.attributes;if(j){let a=[];try{a=Object.keys(j)}catch{a=[]}for(let b of a){let a;try{a=j[b]}catch{a=bd}Object.defineProperty(i,b,{value:a,enumerable:!0,writable:!0,configurable:!0})}}let k={timeUnixNano:g,observedTimeUnixNano:g,severityNumber:f,severityText:e,body:{stringValue:function(a){try{return be(String(a))}catch{return bd}}(a.body)},attributes:bh(i,c)};return a.trace_id&&(k.traceId=a.trace_id),a.span_id&&(k.spanId=a.span_id),t(a.trace_flags)||(k.flags=a.trace_flags),k}(c,b?.context??this._getContext(),this._logger,b?.occurredAtMs)};this._onReady(()=>this._enqueue(d))}_runBeforeSend(a){let b=this._config.beforeSend;if(!b)return a;let c=s(b)?b:[b],d=a;for(let a of c)try{let b=a(d);if(!b)return this._logger.info("Log was rejected in beforeSend function"),null;d=b}catch(a){return this._logger.error("Error in beforeSend function for log:",a),null}return d}_checkRateLimit(){if(void 0===this._maxLogsPerInterval)return!0;let a=Date.now(),b=a-this._intervalWindowStart;return((b>=this._rateCapWindowMs||b<0)&&(this._intervalWindowStart=a,this._intervalLogCount=0,this._droppedWarned=!1),this._intervalLogCount>=this._maxLogsPerInterval)?(this._droppedWarned||(this._logger.warn(`captureLog dropping logs: exceeded ${this._maxLogsPerInterval} logs per ${this._rateCapWindowMs}ms`),this._droppedWarned=!0),!1):(this._intervalLogCount++,!0)}async flush(){if(!this._instance.isDisabled)return this._flushPromise||(this._flushPromise=this._flushInner().finally(()=>{this._flushPromise=null})),this._flushPromise}async _flushInner(){if(this._flushTimer.clear(),this._discardQueueIfConsentWithdrawn())return;let a=this._instance.getPersistedProperty(k.LogsQueue)??[];if(0===a.length)return;let b=a.length,c=0;for(;a.length>0&&c<b;){var d,e,f,g;if(this._discardQueueIfConsentWithdrawn())return;let b=this._queueGeneration;this._evictedSinceAdvance=0;let h=Math.min(a.length,this._maxBatchRecordsPerPost),i=a.slice(0,h),j=(d=i.map(a=>a.record),e=this._buildResourceAttributes(),f=this._scopeName??this._instance.getLibraryId(),g=this._instance.getLibraryVersion(),{resourceLogs:[{resource:{attributes:bl(e)},scopeLogs:[{scope:{name:f,version:g},logRecords:d}]}]}),l=await this._instance._sendLogsBatch(j);if(this._queueGeneration!==b)return;if("too-large"===l.kind&&i.length>1){this._maxBatchRecordsPerPost=Math.max(1,Math.floor(i.length/2)),this._logger.warn(`Logs batch of size ${i.length} was too large for the ingestion endpoint, reducing batch size to ${this._maxBatchRecordsPerPost}`);continue}if(this._retryAfter.record(l),this._flushTimer.pending&&this._flushTimer.arm(Math.max(this._flushIntervalMs,this._retryAfter.remainingMs())),"retry-later"===l.kind||("too-large"===l.kind?this._logger.warn("Dropping a single log record with batch size 1 — the record is larger than the server cap and cannot be split further."):"ok"===l.kind&&this._maxBatchRecordsPerPost<this._config.maxBatchRecordsPerPost&&(this._maxBatchRecordsPerPost=Math.min(this._config.maxBatchRecordsPerPost,this._maxBatchRecordsPerPost+1)),await this._persistQueueAdvance(i.length),a=this._instance.getPersistedProperty(k.LogsQueue)??[],c+=i.length,"fatal"===l.kind))throw l.error}}_discardQueueIfConsentWithdrawn(){return!!this._isConsentWithdrawn()&&(this._hasQueuedRecords()&&this.clearQueue(),!0)}async _persistQueueAdvance(a){let b=Math.max(0,a-this._evictedSinceAdvance),c=this._instance.getPersistedProperty(k.LogsQueue)??[];this._instance.setPersistedProperty(k.LogsQueue,c.slice(b)),await this._waitForStoragePersist()}_buildResourceAttributes(){var a;return a=this._config,bj(a,this._instance.getLibraryId(),this._instance.getLibraryVersion())}_enqueue(a){if(this._instance.optedOut)return;let b=this._instance.getPersistedProperty(k.LogsQueue)??[];(b.length>=this._maxQueueSize&&(b.shift(),this._evictedSinceAdvance++,this._logger.info("Logs queue is full, dropping oldest record.")),b.push(a),this._instance.setPersistedProperty(k.LogsQueue,b),b.length>=this._maxBufferSize&&!this._retryAfter.isOpen())?this._flushInBackground():this._armFlushTimer()}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(Math.max(this._flushIntervalMs,this._retryAfter.remainingMs()))}_nextFlushDelay(){return Math.max(br(this._flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}_hasQueuedRecords(){let a=this._instance.getPersistedProperty(k.LogsQueue);return!!a&&a.length>0}async shutdown(a){this._flushTimer.clear();let b=this.flush().catch(()=>{});void 0===a?await b:await aN(b,a)}async flushWithTimeout(a){let b=this.flush();await aN(b,a,()=>{b.catch(()=>{})})}flushInBackground(){if(this._backgroundFlushPromise)return this._backgroundFlushPromise;let a=this.flush().then(()=>{this._consecutiveFlushFailures=0,this._flushJitter=1},a=>{this._consecutiveFlushFailures++,this._flushJitter=bq(),this._logger.error("PostHog logs flush failed:",a)}).finally(()=>{this._backgroundFlushPromise===a&&(this._backgroundFlushPromise=null),!this._instance.isDisabled&&this._hasQueuedRecords()&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())});return this._backgroundFlushPromise=a,a}_flushInBackground(){this.flushInBackground()}}let bt="0000000000000000",bu=bt+bt,bv=/^[0-9a-f]+$/;function bw(a){let b=function(a){let b="";for(let c=0;c<a.length;c++)b+=a[c].toString(16).padStart(2,"0");return b}(function(a){let b=new Uint8Array(a),c=globalThis.crypto;if(c&&"function"==typeof c.getRandomValues)try{return c.getRandomValues(b),b}catch{}for(let c=0;c<a;c++)b[c]=Math.floor(256*Math.random());return b}(a));return/[^0]/.test(b)?b:b.slice(0,-1)+"1"}function bx(a,b,c){return"string"==typeof a&&a.length===b&&a!==c&&bv.test(a)}let by=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function bz(a){let b=bA(a);return b&&{traceId:b.traceId,spanId:b.spanId,flags:1&parseInt(b.flags,16)?bC:bD}}function bA(a){if("string"!=typeof a)return;let b=by.exec(a.trim());if(!b)return;let[,c,d,e,f,g]=b;if("ff"!==c&&("00"!==c||!g)&&bx(d,32,bu)&&bx(e,16,bt))return{version:c,traceId:d,spanId:e,flags:f}}function bB(a){return Array.isArray(a)&&1===a.length?a[0]:a}let bC="01",bD="00";function bE(a){if("string"!=typeof a)return;let b=a.trim();if(!b||/[^\x20-\x7e\t]/.test(b))return;let c=b.split(",");if(!(c.length>32)){for(let a of c)if(a.trim()&&!a.includes("="))return;return b.length<=512?b:function(a){let b=[...a],c=()=>b.reduce((a,b)=>a+b.length,0)+b.length-1;for(let a=b.length-1;a>=0&&c()>512;a--)b[a].length>128&&b.splice(a,1);for(;b.length&&c()>512;)b.pop();return b.length?b.join(","):void 0}(c)}}let bF=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function bG(a){return String(a)+"000000"}function bH(a,b,c,d){let e="";return d&&(e=Object.keys(d).sort().map(a=>`${JSON.stringify(a)}:${JSON.stringify(d[a])}`).join(",")),`${a}\0${b}\0${c??""}\0${e}`}class bI{constructor(a,b,c){this._instance=a,this._config=b,this._logger=c,this._series=new Map,this._flushTimer=new bp(()=>this.flush().catch(a=>{this._logger.error("Metrics flush failed:",a)})),this._flushPromise=null,this._queuedFlush=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._boundsByHistogram=new Map,this._boundsConflictWarned=new Set,this._boundsCapWarned=!1,this._retryAfter=new a_,this._consecutiveFlushFailures=0,this._flushJitter=1,this._generation=0}count(a,b=1,c){this._capture({name:a,type:"count",value:b,unit:c?.unit,attributes:c?.attributes})}gauge(a,b,c){this._capture({name:a,type:"gauge",value:b,unit:c?.unit,attributes:c?.attributes})}histogram(a,b,c){this._capture({name:a,type:"histogram",value:b,unit:c?.unit,attributes:c?.attributes,bounds:s(c?.bounds)?c.bounds.slice():c?.bounds})}flush(){let a=this._flushPromise,b=(async()=>{a&&await a.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===b&&(this._flushPromise=null)});return this._flushPromise=b,b}flushCoalesced(){return this._isBackingOff()?this._flushPromise??Promise.resolve():(this._queuedFlush||(this._queuedFlush=(this._flushPromise??Promise.resolve()).catch(()=>{}).then(()=>(this._queuedFlush=null,this._isBackingOff()?void 0:this.flush()))),this._queuedFlush)}_isBackingOff(){return this._consecutiveFlushFailures>0||this._retryAfter.remainingMs()>0}drainWindow(){if(0===this._series.size)return null;let a=this._series;return this._startWindow(),this._buildPayload(a)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=1,this._flushTimer.clear(),this._flushPromise=null,this._queuedFlush=null,this._startWindow(),this._boundsByHistogram=new Map,this._boundsCapWarned=!1}_startWindow(){this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._boundsConflictWarned=new Set}_capture(a){var b;let c,d,e;if(this._instance.isDisabled||this._instance.optedOut)return;let f=this._runBeforeSend(a);if(null===f)return;if(!f.name||"string"!=typeof f.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof f.value||!Number.isFinite(f.value))return void this._logger.warn(`Dropping metric '${f.name}': value must be a finite number`);if("count"!==f.type&&"gauge"!==f.type&&"histogram"!==f.type)return void this._logger.warn(`Dropping metric '${f.name}': unknown type '${String(f.type)}'`);if("count"===f.type&&f.value<0)return void this._logger.warn(`Dropping count '${f.name}': counters are monotonic, value must be >= 0`);try{c=f.attributes?{...f.attributes}:void 0,d=bH(f.type,f.name,f.unit,c)}catch(a){this._logger.warn(`Dropping metric '${f.name}': attributes could not be serialized`,a);return}let g=this._series.get(d);if(!g&&!this._admitNewSeries()||"histogram"===f.type&&!(e=this._histogramBounds(f.name,f.unit,f.bounds)))return;g||(g={name:f.name,type:f.type,unit:f.unit,attributes:c,windowStartMs:Date.now(),hist:e&&{bounds:b=e,count:0,sum:0,min:1/0,max:-1/0,bucketCounts:Array(b.length+1).fill(0)}},this._series.set(d,g));let h=this._typeByName.get(f.name);void 0===h?this._typeByName.set(f.name,f.type):h===f.type||this._typeCollisionWarned.has(f.name)||(this._typeCollisionWarned.add(f.name),this._logger.warn(`Metric name '${f.name}' is already used as a ${h}; recording it as a ${f.type} too will blend both series in charts. Use a distinct name.`)),this._fold(g,f.value);let i=this._activeTraceContext();i&&(g.exemplar={...i,value:f.value,timeMs:Date.now()}),this._armFlushTimer()}_activeTraceContext(){try{let a=bz(this._instance.getActiveSpan?.()?.traceparent());if(a&&a.flags===bC)return{traceId:a.traceId,spanId:a.spanId}}catch{}}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush||(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_histogramBounds(a,b,c){if(void 0!==c&&!function(a){if(!s(a)||0===a.length)return!1;for(let b=0;b<a.length;b++)if(!Number.isFinite(a[b])||b>0&&a[b]<=a[b-1])return!1;return!0}(c))return void this._logger.warn(`Dropping histogram '${a}': bounds must be a non-empty array of finite, strictly increasing numbers`);let d=bH("histogram",a,b,void 0),e=this._boundsByHistogram.get(d);if(e)return this._warnOnBoundsConflict(a,d,e,c),e;if(this._boundsByHistogram.size>=this._config.maxSeriesPerFlush){if(this._boundsCapWarned||(this._boundsCapWarned=!0,this._logger.warn(`Histogram bounds limit reached (${this._config.maxSeriesPerFlush} distinct histograms); new histograms that pass custom bounds are dropped. Reduce histogram name cardinality.`)),c&&!bJ(c,bF))return;return bF}let f=c?c.slice():bF;return this._boundsByHistogram.set(d,f),f}_warnOnBoundsConflict(a,b,c,d){bJ(c,d??bF)||this._boundsConflictWarned.has(b)||(this._boundsConflictWarned.add(b),this._logger.warn(`Histogram '${a}' already uses the bounds [${c.join(", ")}]; samples that pass different bounds are recorded in those buckets.`))}_fold(a,b){switch(a.type){case"count":a.total=(a.total??0)+b;break;case"gauge":a.last=b;break;case"histogram":{let c=a.hist;c.count+=1,c.sum+=b,c.min=Math.min(c.min,b),c.max=Math.max(c.max,b),c.bucketCounts[function(a,b){for(let c=0;c<b.length;c++)if(a<=b[c])return c;return b.length}(b,c.bounds)]+=1}}}_runBeforeSend(a){let b=this._config.beforeSend;if(!b)return a;let c=s(b)?b:[b],d=a;for(let a of c)try{let b=a(d);if(!b)return this._logger.info("Metric was rejected in beforeSend function"),null;d=b}catch(a){return this._logger.error("Error in beforeSend function for metric:",a),null}return d}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(br(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),0===this._series.size)return;let a=this._series;this._startWindow();let b=this._generation,c=await this._instance._sendMetricsBatch(this._buildPayload(a));if(b===this._generation)switch(this._retryAfter.record(c),"retry-later"===c.kind?(this._consecutiveFlushFailures++,this._flushJitter=bq()):(this._consecutiveFlushFailures=0,this._flushJitter=1),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),c.kind){case"ok":return;case"retry-later":this._mergeWindowBack(a),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",c.error);return}}_buildPayload(a){var b,c,d,e;return b=this._buildMetrics(a),c=bj(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),d=this._instance.getLibraryId(),e=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:bl(c)},scopeMetrics:[{scope:{name:d,version:e},metrics:b}]}]}}_buildMetrics(a){let b=bG(Date.now()),c=new Map;for(let e of a.values()){var d;let a=bH(e.type,e.name,e.unit,void 0),f=c.get(a);f||(f={name:e.name,...e.unit&&{unit:e.unit}},"count"===e.type?f.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===e.type?f.gauge={dataPoints:[]}:f.histogram={aggregationTemporality:1,dataPoints:[]},c.set(a,f));let g=bh(e.attributes??{},this._logger),h=bG(e.windowStartMs),i=(d=e.exemplar)?{exemplars:[{filteredAttributes:[],timeUnixNano:bG(d.timeMs),asDouble:d.value,traceId:d.traceId,spanId:d.spanId}]}:{};if("count"===e.type){let a={attributes:g,startTimeUnixNano:h,timeUnixNano:b,asDouble:e.total??0,...i};f.sum.dataPoints.push(a)}else if("gauge"===e.type){let a={attributes:g,timeUnixNano:b,asDouble:e.last??0,...i};f.gauge.dataPoints.push(a)}else{let a=e.hist,c={attributes:g,startTimeUnixNano:h,timeUnixNano:b,count:a.count,sum:a.sum,min:a.min,max:a.max,bucketCounts:a.bucketCounts,explicitBounds:a.bounds,...i};f.histogram.dataPoints.push(c)}}return Array.from(c.values())}_mergeWindowBack(a){for(let[b,c]of a){let a=this._series.get(b);if(!a){this._admitNewSeries()&&this._series.set(b,c);continue}switch(a.windowStartMs=Math.min(a.windowStartMs,c.windowStartMs),a.exemplar=a.exemplar??c.exemplar,a.type){case"count":a.total=(a.total??0)+(c.total??0);break;case"gauge":break;case"histogram":{let b=a.hist,d=c.hist;b.count+=d.count,b.sum+=d.sum,b.min=Math.min(b.min,d.min),b.max=Math.max(b.max,d.max);for(let a=0;a<b.bucketCounts.length;a++)b.bucketCounts[a]+=d.bucketCounts[a]}}}}}function bJ(a,b){if(a===b)return!0;if(a.length!==b.length)return!1;for(let c=0;c<a.length;c++)if(a[c]!==b[c])return!1;return!0}let bK="unknown";function bL(a,b,c,d){return"string"==typeof a&&a.trim()?a.length>c?a.slice(0,c):a:(d?.debug(`${b} must be a non-empty string; using "${bK}"`),bK)}function bM(a){if(null==a)return;let b=a;if(a instanceof Date)try{b=a.getTime()}catch{return}if("number"==typeof b&&Number.isFinite(b)&&!(b<0)&&!(b>0x8637bd05af6))return b}function bN(a,b,c,d){let e=bM(a);return void 0===e?(void 0!==a&&d?.debug(`Span ${c} is out of range or not a valid time; using the derived time`),b):e}function bO(){let a=globalThis.performance;return"function"==typeof a?.now?a.now():void 0}class bP{constructor(a,b,c){for(let d of(this._onEnd=b,this._logger=c,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=a.traceId,this._spanId=a.spanId,this._parentSpanId=a.parentSpanId,this._traceState=a.traceState,this._traceFlags=a.traceFlags??bC,this._parentIsRemote=a.parentIsRemote??!1,this._name=a.name,this._kind=a.kind,this._autoKeys=new Set(a.autoAttributeKeys),this._maxAttributes=a.maxAttributes,this._maxEvents=a.maxEvents,this._maxAttributesPerEvent=a.maxAttributesPerEvent,this._maxAttributeValueLength=a.maxAttributeValueLength,this._attributes=Object.create(null),Object.keys(a.attributes)))this._writeAttribute(d,a.attributes[d]);this._startMono=a.backdated?void 0:bO(),this._startTime=a.clockAnchor&&void 0!==this._startMono?a.clockAnchor.wall+(this._startMono-a.clockAnchor.mono):a.startTime,void 0!==this._startMono&&(this._clockAnchor=a.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(void 0!==this._startMono){let a=bO();if(void 0!==a)return this._startTime+Math.max(0,a-this._startMono)}return Date.now()}_mutable(a){return!this._ended||(this._logger?.debug(`Ignoring ${a} on a span that has already ended`),!1)}_writeAttribute(a,b){if(x(b)){a in this._attributes&&!this._autoKeys.has(a)&&this._userAttributeCount--,delete this._attributes[a];return}if(!this._autoKeys.has(a)&&!(a in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[a]=bY(b,this._maxAttributeValueLength)}setAttribute(a,b){return this._mutable("setAttribute")&&this._writeAttribute(a,b),this}setAttributes(a){if(this._mutable("setAttributes")){let b=bf({},a);for(let a of Object.keys(b))this._writeAttribute(a,b[a])}return this}addEvent(a,b,c){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let d=b&&bZ(b,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:bL(a,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:bN(c,this._now(),"event timestamp",this._logger),...d&&{attributes:d.attributes,...d.dropped&&{droppedAttributesCount:d.dropped}}})}return this}setStatus(a,b){if(this._mutable("setStatus")){if("ok"!==a&&"error"!==a)return this._logger?.debug(`Ignoring unknown span status "${String(a)}"; expected "ok" or "error"`),this;this._status={code:a,...b&&{message:bX(b,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(a){if(!this._mutable("recordException"))return this;let{type:b,message:c,stack:d}=b_(a);return this.addEvent(bQ,{"exception.type":b,"exception.message":c,...d&&{"exception.stacktrace":d}}),this.setStatus("error",c)}updateName(a){return this._mutable("updateName")&&(this._name=bL(a,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return function(a,b,c=bC){return`00-${a}-${b}-${c}`}(this._traceId,this._spanId,this._traceFlags)}get traceId(){return this._traceId}get spanId(){return this._spanId}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(a){var b;if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let c=bN(a,this._now(),"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:c<(b=this._startTime)?b:c,...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}}let bQ="exception";function bR(a){return"number"!=typeof a||!Number.isFinite(a)||a<=0?0:Math.min(Math.floor(a),0xffffffff)}class bS{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}get traceId(){return null}get spanId(){return null}tracestate(){return null}end(){}}let bT=new bS;class bU extends bS{constructor(a,b){super(),this._traceparent=a,this._tracestate=b}traceparent(){return this._traceparent}get traceId(){return this._traceparent.split("-")[1]??null}get spanId(){return this._traceparent.split("-")[2]??null}tracestate(){return this._tracestate??null}}function bV(a,b){var c;let d=bB(a?.parent)??b,e=bA(c="string"==typeof d||null==d?d:bW(d,"traceparent"))&&c.trim();return e?new bU(e,bE("string"==typeof d||null==d?a?.tracestate:bW(d,"tracestate"))):bT}function bW(a,b){try{let c=a[b];return"function"==typeof c?c.call(a):void 0}catch{return}}function bX(a,b){return a.length>b?a.slice(0,b):a}function bY(a,b){return function a(b,c,d,e){if(null===b||"object"!=typeof b)return x(b)||d.remainingNodes<=0?b:(d.remainingNodes--,"string"==typeof b?bX(b,c):b);if(d.ancestors.has(b))return bb;if(d.remainingNodes<=0||e>=20)return b;d.remainingNodes--,d.ancestors.add(b);try{if(b instanceof Date)return b;let f=function(a){try{let b=a.toJSON;if("function"==typeof b)return{selfDescribed:!0,value:b.call(a)}}catch{}return{selfDescribed:!1}}(b);if(f.selfDescribed)return x(f.value)?String(f.value):a(f.value,c,d,e+1);if(s(b)){let f=Math.min(b.length,1e3),g=[];for(let h=0;h<f;h++)try{g.push(a(b[h],c,d,e+1))}catch{g.push(bd)}return b.length>f&&(g.length=b.length),g}let g={},h=0;for(let f of Object.keys(b)){let i;if(h>=1e3)break;try{i=a(b[f],c,d,e+1)}catch{i=bd}f&&!x(i)&&h++,Object.defineProperty(g,f,{value:i,enumerable:!0,writable:!0,configurable:!0})}return g}catch{return b}finally{d.ancestors.delete(b)}}(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}function bZ(a,b,c){let d;try{d=Object.keys(a)}catch{return{attributes:{},dropped:0}}let e={},f=0,g=0;for(let h of d){let d;if(f>=b){g++;continue}try{d=bY(a[h],c)}catch{d=bd}x(d)||(f++,Object.defineProperty(e,h,{value:d,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:e,dropped:g}}function b$(a,b,c){return b===bT?c(b):a.with(b,()=>c(b))}function b_(a){try{let b=function(a){try{let b=a.stack;return"string"==typeof b&&b?{stack:b}:{}}catch{return{}}}(a);if(A(a))return{type:a.name||"Error",message:a.message||"",...b};if("string"==typeof a)return{type:"string",message:a};if(a&&"object"==typeof a&&"string"==typeof a.message)return{type:"string"==typeof a.name?a.name:"Object",message:a.message,...b};return{type:typeof a,message:String(a)}}catch{return{type:typeof a,message:""}}}let b0={internal:1,server:2,client:3,producer:4,consumer:5},b1={ok:1,error:2};function b2(a){if("string"==typeof a)return be(a);try{return be(String(a))}catch{return bd}}function b3(a){let b=Math.floor(a),c=Math.round((a-b)*1e6);return c>=1e6&&(b+=1,c=0),String(b)+String(c).padStart(6,"0")}function b4(){return bO()??Date.now()}function b5(a){try{return a instanceof bP}catch{return!1}}function b6(a,b){let c=bz(a);if(c)return{traceId:c.traceId,parentSpanId:c.spanId,traceState:bE(b),traceFlags:c.flags,isRemote:!0}}function b7(a,b,c){a[b]!==c&&(a[b]=c)}class b8{constructor(a,b,c,d,e,f){this._instance=a,this._config=b,this._logger=c,this._getContext=d,this._contextManager=e,this._onSpanQueued=f,this._queue=[],this._flushTimer=new bp(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter=new a_,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=b.maxExportBatchSize}startSpan(a,b){var c,d;let e;if(this._instance.isDisabled||this._instance.optedOut)return bV(b,this._contextManager.active());let f=bB(b?.parent);if(f&&"string"!=typeof f&&!b5(f)){if(function(a){try{return"function"==typeof a.traceparent}catch{return!1}}(f))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),bV(b,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let g=this._resolveParent(f,b);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached — spans are being started and never ended`),bV(b,this._contextManager.active());let h=Date.now(),i=(c=b?.startTime,d=this._logger,void 0===(e=bM(c))?(void 0!==c&&d?.debug("Span startTime is out of range or not a valid time; using the current time"),h):(h-e>864e5?d?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):e>h&&d?.debug("Span startTime is in the future; the span may export with a zero duration"),e)),j=bw(8);this._liveSpans.set(j,b4());let k=this._autoContextAttributes();return new bP({traceId:g?.traceId??bw(16),spanId:j,parentSpanId:g?.parentSpanId,traceState:g?.traceState,traceFlags:g?.traceFlags,parentIsRemote:g?.isRemote,name:bL(a,"Span name",this._config.maxAttributeValueLength,this._logger),kind:b?.kind??"internal",attributes:bf({...k},b?.attributes),autoAttributeKeys:Object.keys(k),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:i,backdated:i!==h,clockAnchor:void 0===bM(b?.startTime)?g?.clockAnchor:void 0},(a,b)=>this._onSpanEnd(a,b),this._logger)}withSpan(a,b,c){let d=this.startSpan(a,"function"==typeof b?void 0:b);try{let a=b$(this._contextManager,d,"function"==typeof b?b:c);if(a&&"function"==typeof a.then)return a.then(a=>(d.end(),a),a=>{throw this._recordCallbackError(d,a),d.end(),a});return d.end(),a}catch(a){throw this._recordCallbackError(d,a),d.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;){if(!this._queue.length)return;let a=this._flushPromise;if(!await (a??this._startFlush()))return}}_startFlush(){this._flushTimer.clear();let a=this._generation,b=Promise.resolve().then(()=>a===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===b&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=b,b}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(a,b){if("string"==typeof a){let c=b6(a,b?.tracestate);return c||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),c}if(b5(a))return a.childContext();let c=this._contextManager.active();return b5(c)?c.childContext():c instanceof bU?b6(c.traceparent(),c.tracestate()??void 0):void 0}_autoContextAttributes(){let a;try{a=this._getContext()}catch(a){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",a),{}}let b={};return a.distinctId&&(b.posthogDistinctId=a.distinctId),a.sessionId&&(b.sessionId=a.sessionId),a.currentUrl&&(b["url.full"]=a.currentUrl),a.screenName&&(b["screen.name"]=a.screenName),a.appState&&(b["app.state"]=a.appState),b}_recordCallbackError(a,b){if(!(a instanceof bP))return;let{type:c,message:d,stack:e}=b_(b);a.addEvent("exception",{"exception.type":c,"exception.message":d,...e&&{"exception.stacktrace":e}}),a.statusIsExplicitlyOk||a.setStatus("error",d)}_evictAgedSpans(){let a=b4()-this._config.maxSpanAgeMs,b=0;for(let[c,d]of this._liveSpans){if(d>a)break;this._liveSpans.delete(c),b++}b&&this._recordDrop(b,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(a,b){if(!this._liveSpans.delete(a.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let c=this._runBeforeSpanSend(a,b);if(c){if(this._reportLimitDrops(c),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) — raise the flush frequency or reduce span volume`);this._queue.push(c);try{this._onSpanQueued?.()}catch(a){this._logger.debug("Span queue notification failed",a)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(a){let b=a.droppedAttributesCount??0,c=a.droppedEventsCount??0,d=0;for(let b of a.events)d+=b.droppedAttributesCount??0;(b||c||d)&&this._logger.debug(`Span limits discarded data from "${a.name}": ${b} attributes, ${c} events, ${d} event attributes`)}_runBeforeSpanSend(a,b){if(!this._config.beforeSpanSend.length)return a;let c={traceId:a.traceId,spanId:a.spanId,parentSpanId:a.parentSpanId,traceState:a.traceState},d={startTime:a.startTime,endTime:a.endTime},e={attributes:a.droppedAttributesCount,events:a.droppedEventsCount},f=Object.keys(a.attributes),g={traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote},h=a.status&&{...a.status},i=a,j=a;try{var k,l,m;for(let a of this._config.beforeSpanSend){let b=a(i);if(!b)return this._recordDrop(1,"beforeSpanSend dropped it"),null;i=this._keepSpanIdentity(b,c)}if(!((k=j={traceId:c.traceId,spanId:c.spanId,parentSpanId:c.parentSpanId,traceState:c.traceState,name:i.name,kind:i.kind,status:i.status,attributes:i.attributes,events:i.events,startTime:i.startTime,endTime:i.endTime,traceFlags:g.traceFlags,parentIsRemote:g.parentIsRemote,droppedAttributesCount:e.attributes,droppedEventsCount:e.events}).attributes&&"object"==typeof k.attributes&&!Array.isArray(k.attributes)&&Array.isArray(k.events)&&void 0!==k.name&&void 0!==k.kind&&void 0!==k.startTime&&void 0!==k.endTime))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;j.name=bL(j.name,"Span name",this._config.maxAttributeValueLength,this._logger),j.status&&"ok"!==j.status.code&&"error"!==j.status.code&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),j.status=h),j.startTime=bM(j.startTime)??d.startTime,j.endTime=(l=bM(j.endTime)??d.endTime,m=j.startTime,l<m?m:l);let a=[];for(let b of j.events)try{a.push({...b,name:bL(b.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:bN(b.timestamp,j.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return j.events=a,!function(a,b,c,d,e,f,g=[]){let h=0,i=0,j={};for(let d of function(a,b){if(!b.length)return Object.keys(a);let c=b.filter(b=>Object.prototype.propertyIsEnumerable.call(a,b)),d=new Set(c);return[...c,...Object.keys(a).filter(a=>!d.has(a))]}(a.attributes,g)){let e=a.attributes[d];if(!x(e)){if(!b.has(d)){if(h>=c){i++;continue}h++}Object.defineProperty(j,d,{value:bY(e,f),enumerable:!0,writable:!0,configurable:!0})}}a.attributes=j,i&&(a.droppedAttributesCount=bR(a.droppedAttributesCount)+i);let k=0,l=0,m=[];for(let b of a.events){if(k>=d){l++;continue}if(k++,b.attributes){let a=bZ(b.attributes,e,f);b.attributes=a.attributes,a.dropped&&(b.droppedAttributesCount=bR(b.droppedAttributesCount)+a.dropped)}m.push(b)}a.events=m,l&&(a.droppedEventsCount=bR(a.droppedEventsCount)+l),a.status?.message&&(a.status={...a.status,message:bX(function(a){try{return"string"==typeof a?a:String(a)}catch{return bd}}(a.status.message),f)})}(j,b,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,f),j}catch(a){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",a),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(a,b){(a.traceId!==b.traceId||a.spanId!==b.spanId||a.parentSpanId!==b.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{b7(a,"traceId",b.traceId),b7(a,"spanId",b.spanId),b7(a,"parentSpanId",b.parentSpanId),b7(a,"traceState",b.traceState)}catch{try{let c=Object.getOwnPropertyDescriptors(a);for(let a of["traceId","spanId","parentSpanId","traceState"])c[a]={value:b[a],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(a),c)}catch{;}}return a}_recordDrop(a,b){this._droppedSinceWarning+=a,this._dropReasons.add(b),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(a){let b=[];for(let c of a)try{b.push(function(a,b){var c;let d,e={traceId:a.traceId,spanId:a.spanId,name:b2(a.name),kind:(c=a.kind)&&Object.prototype.hasOwnProperty.call(b0,c)?b0[c]:b0.internal,startTimeUnixNano:b3(a.startTime),endTimeUnixNano:b3(a.endTime),flags:(Number.isFinite(d=parseInt(a.traceFlags,16))?255&d:1)|256|512*!!a.parentIsRemote};a.parentSpanId&&(e.parentSpanId=a.parentSpanId),a.traceState&&(e.traceState=b2(a.traceState));let f=bh(a.attributes,b);f.length&&(e.attributes=f),a.events.length&&(e.events=a.events.map(a=>(function(a,b){let c={name:b2(a.name),timeUnixNano:b3(a.timestamp)};if(a.attributes){let d=bh(a.attributes,b);d.length&&(c.attributes=d)}let d=bR(a.droppedAttributesCount);return d&&(c.droppedAttributesCount=d),c})(a,b)));let g=bR(a.droppedAttributesCount);g&&(e.droppedAttributesCount=g);let h=bR(a.droppedEventsCount);return h&&(e.droppedEventsCount=h),a.status&&(e.status={code:b1[a.status.code],...a.status.message&&{message:b2(a.status.message)}}),e}(c,this._logger))}catch(a){this._logger.debug("Failed to encode a span; dropping it",a),this._recordDrop(1,"its attributes could not be encoded")}return b}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let a=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(a,"the user has opted out"),this._warnAboutDrops(),a}async _flushInner(){var a,b;if(!this._queue.length)return 0;let c=this._discardQueueIfConsentWithdrawn();if(c)return c;let d=function(a,b){for(let c of Object.keys(a))a[c]=bY(a[c],b);return a}((a=this._config,bj(a,this._instance.getLibraryId(),this._instance.getLibraryVersion())),this._config.maxAttributeValueLength),e=this._instance.getLibraryId(),f=this._instance.getLibraryVersion(),g=this._queue.length,h=0,i=1/0,j=this._generation;try{for(;g>0&&this._queue.length>0;){let a=this._discardQueueIfConsentWithdrawn();if(a)return h+a;let c=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,k=Math.max(1,Math.min(c,i,g,this._queue.length)),l=this._queue.slice(0,k),m=this._encodeBatch(l);if(!m.length){this._queue.splice(0,k),g-=k,h+=k,this._resetHeadBatchBudget();continue}let n=b4()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),o=await this._instance._sendTracesBatch((b=this._logger,{resourceSpans:[{resource:{attributes:bl(d,b)},scopeSpans:[{scope:{name:e,version:f},spans:m}]}]}));if(j!==this._generation)break;if(this._retryAfter.record(o),"ok"===o.kind){this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._queue.splice(0,k),g-=k,h+=k,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if("too-large"===o.kind){if(1===k){this._queue.splice(0,1),g-=1,h+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget();continue}let a=Math.max(1,Math.floor(k/2));o.measuredLocally?i=a:this._maxExportBatchSize=a,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${a}`);continue}if("retry-later"===o.kind){if(this._consecutiveFlushFailures++,this._flushJitter=bq(),this._headBatchSize=k,n&&(this._headBatchFailures++,this._headBatchChargeableAt=b4()+this._nextFlushDelay()),this._headBatchFailures<8)return this._logger.debug("Span export failed; retrying on the next flush",o.error),h;if(this._queue.splice(0,k),g-=k,h+=k,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(k,"the ingestion endpoint failed 8 times in a row"),this._retryAfter.isOpen())return h;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",o.error),this._queue.splice(0,k),g-=k,h+=k,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(k,"the ingestion endpoint rejected the batch")}return h}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(a=>{this._logger.debug("Background span flush failed",a)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){!this._flushTimer.pending&&this._queue.length&&this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(br(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}}class b9{active(){return this._active}with(a,b){let c=this._active;this._active=a;try{return b()}finally{this._active=c}}}let ca=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","lightpanda","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],cb=new Map,cc=function(a,b=[]){if(!a)return!1;let c=function(a,b){let c="";for(let a=0;a<b.length;a++){let d=b[a];c+=d.length+":"+d}return a.length+":"+a+"|"+b.length+":"+c}(a,b),d=cb.get(c);if(void 0!==d)return d;let e=a.toLowerCase(),f=ca.concat(b).some(a=>-1!==e.indexOf(a.toLowerCase()));return cb.size>=256&&cb.clear(),cb.set(c,f),f};function cd(a){let b=a?.resourceAttributes;return{serviceName:b?.["service.name"]??a?.serviceName,serviceVersion:b?.["service.version"]??a?.serviceVersion,environment:b?.["deployment.environment"]??a?.environment,resourceAttributes:b,beforeSend:a?.beforeSend,flushIntervalMs:a?.flushIntervalMs??1e4,maxSeriesPerFlush:a?.maxSeriesPerFlush??1e3}}function ce(a,b){return"number"==typeof a&&Number.isInteger(a)&&a>=1?a:b}let cf=["service.name","service.version","deployment.environment"];function cg(a,b,c){let d=bf({...b},function(a){if(!(!a||"object"!=typeof a||Array.isArray(a)))try{if(cf.every(b=>!(b in a)||"string"==typeof a[b]))return a;let b={...a};for(let a of cf)a in b&&"string"!=typeof b[a]&&delete b[a];return b}catch{return}}(a?.resourceAttributes)),e=ce(a?.maxExportBatchSize,512);return{serviceName:d?.["service.name"]??a?.serviceName,serviceVersion:d?.["service.version"]??a?.serviceVersion,environment:d?.["deployment.environment"]??a?.environment,resourceAttributes:d,beforeSpanSend:function(a,b){if(!a)return[];let c=[a].flat().filter(a=>!!a),d=c.filter(a=>"function"==typeof a);return d.length!==c.length&&b?.critical(`beforeSpanSend: ignoring ${c.length-d.length} of ${c.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),d}(a?.beforeSpanSend,c),maxAttributesPerSpan:ce(a?.maxAttributesPerSpan,128),maxEventsPerSpan:ce(a?.maxEventsPerSpan,128),maxAttributesPerEvent:128,maxAttributeValueLength:ce(a?.maxAttributeValueLength,8192),flushIntervalMs:ce(a?.flushIntervalMs,5e3),maxExportBatchSize:e,maxQueueSize:Math.max(ce(a?.maxQueueSize,2048),e),maxLiveSpans:ce(a?.maxLiveSpans,1e4),maxSpanAgeMs:ce(a?.maxSpanAgeMs,36e5)}}let ch={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",LOCAL_EVALUATION_INCONCLUSIVE:"local_evaluation_inconclusive",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};a.s(["FeatureFlagError",0,ch],46539);class ci{constructor(a){this._host=a.host,this._distinctId=a.distinctId,this._groups=a.groups,this._disableGeoip=a.disableGeoip,this._flags=a.flags,this._unresolvedFlags=Object.freeze({...a.unresolvedFlags}),this._requestId=a.requestId,this._evaluatedAt=a.evaluatedAt,this._flagDefinitionsLoadedAt=a.flagDefinitionsLoadedAt,this._errorsWhileComputing=a.errorsWhileComputing??!1,this._quotaLimited=a.quotaLimited??!1,this._accessed=a.accessed??new Set,this._isSlice=a.isSlice??!1}isEnabled(a,b={}){let c=this._flags[a];return this._recordAccess(a,b.sendFeatureFlagEvents),c?.enabled??b.defaultValue??!1}getFlag(a,b={}){let c=this._flags[a];if(this._recordAccess(a,b.sendFeatureFlagEvents),c)return!!c.enabled&&(c.variant??!0)}getFlagPayload(a){return this._flags[a]?.payload}onlyAccessed(){let a={};for(let b of this._accessed){let c=this._flags[b];c&&(a[b]=c)}return this._cloneWith(a)}only(a){let b={},c=[];for(let d of a){let a=this._flags[d];a?b[d]=a:c.push(d)}return c.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${c.join(", ")}`),this._cloneWith(b)}get keys(){return Object.keys(this._flags)}get unresolvedFlags(){return this._unresolvedFlags}_getEventProperties(){let a={},b=[];for(let[c,d]of Object.entries(this._flags)){let e=!1!==d.enabled&&(d.variant??!0);a[`$feature/${c}`]=e,d.enabled&&b.push(c)}return b.length>0&&(b.sort(),a.$active_feature_flags=b),a}_cloneWith(a){return new ci({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:a,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(a,b){if(this._accessed.add(a),!this._host.resolveSendFeatureFlagEvents(b)||""===this._distinctId||this._isSlice&&!(a in this._flags))return;let c=this._flags[a],d=void 0===c?void 0:!1!==c.enabled&&(c.variant??!0),e={$feature_flag:a,$feature_flag_response:d,$feature_flag_id:c?.id,$feature_flag_version:c?.version,$feature_flag_reason:c?.reason,locally_evaluated:c?.locallyEvaluated??!1,[`$feature/${a}`]:d,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:c?.locallyEvaluated?Date.now():this._evaluatedAt};c?.hasExperiment!==void 0&&(e.$feature_flag_has_experiment=c.hasExperiment),c?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(e.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let f=[];this._errorsWhileComputing&&f.push(ch.ERRORS_WHILE_COMPUTING),this._quotaLimited&&f.push(ch.QUOTA_LIMITED),void 0===c&&f.push(Object.prototype.hasOwnProperty.call(this._unresolvedFlags,a)?ch.LOCAL_EVALUATION_INCONCLUSIVE:ch.FLAG_MISSING),f.length>0&&(e.$feature_flag_error=f.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:a,response:d,groups:this._groups,disableGeoip:this._disableGeoip,properties:e,record:c?.parsed})}}let cj=new WeakMap;class ck extends Error{constructor(a){super(a),this.field=a}}function cl(a){let b=cj.get(a);return b||{value:a.variant??a.enabled??null,failed:!0===a.failed,reason:a.reason&&{code:a.reason.code,conditionIndex:a.reason.condition_index,description:a.reason.description},metadata:{id:a.metadata?.id,version:a.metadata?.version,configVersion:1,description:a.metadata?.description,hasExperiment:a.metadata?.has_experiment}}}function cm(a,b){return{detail:{key:a,enabled:!1,variant:void 0,reason:void 0,metadata:void 0,failed:!0},record:{value:null,failed:!0,unreadableField:b,metadata:{}}}}function cn(a){cq(a.key,"key",u)}function co(a){let b=cq(a,"reason",C);if(void 0!==b)return{code:cq(b.code,"reason.code",u),conditionIndex:cr(b.condition_index,"reason.condition_index"),description:cq(b.description,"reason.description",u)}}function cp(a){return{id:cr(a?.id,"metadata.id"),version:cr(a?.version,"metadata.version"),description:cq(a?.description,"metadata.description",u),hasExperiment:cq(a?.has_experiment,"metadata.has_experiment",z)}}function cq(a,b,c){if(!x(a)){if(c(a))return a;throw new ck(b)}}function cr(a,b){return cq(a,b,a=>y(a)&&Number.isInteger(a))}let cs="experiment_split",ct="experiment",cu=new Map([["targeting_match",new Set(["targeted_release","percentage_rollout"])],[cs,new Set([ct])],["rollout_miss",new Set(["percentage_rollout",ct])],["experiment_paused",new Set([ct])],["holdout",new Set([ct])]]),cv=["$feature_flag_config_version","$feature_flag_reason_code","$feature_flag_rule_id","$feature_flag_rule_type","$feature_flag_variant_key"],cw=new Set([...cv,"$feature_flag_reason","$feature_flag_forced_variant","$feature_flag_experiment_id"]),cx=new Set(["$feature_flag_config_version","$feature_flag_reason_code","$feature_flag_rule_type","$experiment_exposure_source","$feature_flag_experiment_id","$feature_flag_forced_variant"]),cy=["$feature_flag_id","$feature_flag_version","$feature_flag_request_id","$feature_flag_evaluated_at"],cz=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,cA=["exact","is_not","icontains","not_icontains","starts_with","not_starts_with","ends_with","not_ends_with","regex","not_regex"];class cB extends Error{constructor(a,b="unsupported_definition"){super(a),this.name=this.constructor.name,this.reason=b,Object.setPrototypeOf(this,cB.prototype)}}function cC(a){try{return a()}catch(a){if(a instanceof cB)throw new cB(a.message,"missing_context");throw a}}function cD(a){if("boolean"==typeof a)return!0;if("string"==typeof a){let b=a.toLowerCase();return"true"===b||"false"===b}if(!Array.isArray(a))return!1;for(let b=0;b<a.length;b++)if(!cD(b in a?a[b]:null))return!1;return!0}function cE(a){if("boolean"==typeof a)return a;if("string"==typeof a)return"true"===a.toLowerCase();if(!Array.isArray(a))return!1;for(let b=0;b<a.length;b++)if(!cE(b in a?a[b]:null))return!1;return!0}function cF(a){for(let b=0;b<a.length;b++){let c=a.charCodeAt(b);if(c>=55296&&c<=56319){let c=a.charCodeAt(b+1);if(b+1>=a.length||c<56320||c>57343)throw new cB("Cannot stringify an unpaired surrogate like the flags service");b++}else if(c>=56320&&c<=57343)throw new cB("Cannot stringify an unpaired surrogate like the flags service")}}function cG(a,b=new Set){if(null!==a&&"boolean"!=typeof a){if("string"==typeof a)return void cF(a);if("number"==typeof a){if(!Number.isFinite(a))throw new cB(`Cannot represent non-finite number ${a} like the flags service`);return}if(Array.isArray(a)){if(b.has(a))throw new cB("Cannot represent a circular array during local evaluation");b.add(a);try{for(let c=0;c<a.length;c++)c in a&&cG(a[c],b)}finally{b.delete(a)}return}if("object"==typeof a){let c=Object.getPrototypeOf(a);if(c!==Object.prototype&&null!==c)throw new cB("Cannot represent a non-JSON object like the flags service");if(b.has(a))throw new cB("Cannot represent a circular object during local evaluation");b.add(a);try{for(let c of Object.keys(a))cF(c),cG(a[c],b)}finally{b.delete(a)}return}throw new cB(`Cannot represent ${typeof a} like the flags service`)}}function cH(a,b){let c=0,d=0;for(;c<a.length&&d<b.length;){let e=a.charCodeAt(c),f=b.charCodeAt(d),g=e>=55296&&e<=56319,h=f>=55296&&f<=56319,i=g?a.charCodeAt(c+1):0,j=h?b.charCodeAt(d+1):0,k=g?(e-55296)*1024+i-56320+65536:e,l=h?(f-55296)*1024+j-56320+65536:f;if(k!==l)return k-l;c+=g?2:1,d+=h?2:1}return a.length-b.length}function cI(a){return"string"==typeof a?(cF(a),a):function a(b,c=new Set){if(null===b)return"null";if("string"==typeof b)return cF(b),JSON.stringify(b);if("boolean"==typeof b)return b?"true":"false";if("number"==typeof b){if(!Number.isFinite(b))throw new cB(`Cannot stringify non-finite number ${b} like the flags service`);if(Number.isInteger(b))throw new cB(`Cannot distinguish integer ${b} from an integral JSON float during local evaluation`);return String(b)}if(Array.isArray(b)){if(c.has(b))throw new cB("Cannot stringify a circular array during local evaluation");c.add(b);try{let d=[];for(let e=0;e<b.length;e++)d.push(e in b?a(b[e],c):"null");return`[${d.join(",")}]`}finally{c.delete(b)}}if("object"==typeof b){let d=Object.getPrototypeOf(b);if(d!==Object.prototype&&null!==d)throw new cB("Cannot stringify a non-JSON object like the flags service");if(c.has(b))throw new cB("Cannot stringify a circular object during local evaluation");c.add(b);try{let d=Object.keys(b);return d.forEach(cF),`{${d.sort(cH).map(d=>`${JSON.stringify(d)}:${a(b[d],c)}`).join(",")}}`}finally{c.delete(b)}}throw new cB(`Cannot stringify ${typeof b} like the flags service`)}(a)}let cJ=/[\x20-\x2f:;=?@\x5b-\x60\x7b-\x7e]/;function cK(a){let b=new cB(a);return Object.defineProperty(b,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),b}function cL(a){return String(a).replace(/[A-Z]/g,a=>a.toLowerCase())}function cM(a,b,c){if(!/^\d+$/.test(a)||"strict"===c&&a.length>1&&"0"===a[0])throw new cB(`Invalid semver: ${b}`);return parseInt(a,10)}function cN(a,b="strict"){let c=String(a).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!c||c.startsWith("."))throw new cB(`Invalid semver: ${a}`);let d=c.split("."),e=c=>void 0===c||""===c?0:cM(c,a,b);return[e(d[0]),e(d[1]),e(d[2])]}function cO(a,b){for(let c=0;c<3;c++){if(a[c]<b[c])return -1;if(a[c]>b[c])return 1}return 0}function cP(a,b){let c=cN(a,b);return{lower:[c[0],c[1],c[2]],upper:[c[0],c[1]+1,0]}}function cQ(a,b){let[c,d,e]=cN(a,b);return{lower:[c,d,e],upper:c>0?[c+1,0,0]:d>0?[0,d+1,0]:[0,0,e+1]}}function cR(a,b){let c=String(a).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!c)throw new cB(`Invalid wildcard semver: ${a}`);let d=c.split("."),e=c=>{if("legacy-permissive"===b){let a=parseInt(c,10);if(!isNaN(a))return a}else try{return cM(c,a,b)}catch{}throw new cB(`Invalid wildcard semver: ${a}`)},f=e(d[0]);if(1===d.length)return{lower:[f,0,0],upper:[f+1,0,0]};let g=e(d[1]);return{lower:[f,g,0],upper:[f,g+1,0]}}function cS(a){if(a instanceof Date)return a;if("string"==typeof a||"number"==typeof a){let b=new Date(a);if(!isNaN(b.valueOf()))return b;throw new cB(`${a} is in an invalid date format`)}throw new cB(`The date provided ${a} must be a string, number, or date object`)}function cT(a){if("boolean"==typeof a)throw new cB("Date operations cannot be performed on boolean values");return function(a){let b=a.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),c=new Date(new Date().toISOString());if(!b||!b.groups)return null;let d=parseInt(b.groups.number);if(d>=1e4)return null;let e=b.groups.interval;if("h"===e)c.setUTCHours(c.getUTCHours()-d);else if("d"===e)c.setUTCDate(c.getUTCDate()-d);else if("w"===e)c.setUTCDate(c.getUTCDate()-7*d);else if("m"===e){var f,g,h=c,i=d;let a=h.getUTCFullYear(),b=h.getUTCMonth(),e=h.getUTCDate();for(let c=1;c<=i&&e>28;c++)e=Math.min(e,new Date(Date.UTC(a,b-c+1,0)).getUTCDate());h.setUTCFullYear(a,b-i,e)}else{let a,b;if("y"!==e)return null;f=c,g=d,a=f.getUTCMonth(),b=g>0&&1===a&&29===f.getUTCDate()?28:f.getUTCDate(),f.setUTCFullYear(f.getUTCFullYear()-g,a,b)}return c}(String(a))??cS(a)}function cU(a,b={}){let c=a.value,d=b.semverParsingPolicy??"strict";switch(a.operator||"exact"){case"exact":case"is_not":for(let a of Array.isArray(c)?c:[c])cI(a);return;case"is_set":case"is_not_set":case"icontains":case"not_icontains":case"starts_with":case"not_starts_with":case"ends_with":case"not_ends_with":case"regex":case"not_regex":case"gt":case"gte":case"lt":case"lte":return;case"is_date_after":case"is_date_before":cT(c);return;case"semver_eq":case"semver_neq":case"semver_gt":case"semver_gte":case"semver_lt":case"semver_lte":cN(String(c),d);return;case"semver_tilde":cP(String(c),d);return;case"semver_caret":cQ(String(c),d);return;case"semver_wildcard":cR(String(c),d);return;default:throw new cB(`Unknown operator: ${a.operator}`)}}async function cV(a){let b=globalThis.crypto?.subtle;if(!b)throw Error("SubtleCrypto API not available");return Array.from(new Uint8Array(await b.digest("SHA-1",new TextEncoder().encode(a)))).map(a=>a.toString(16).padStart(2,"0")).join("")}async function cW(a,b,c="",d="."){return parseInt((await cV(`${a}${d}${b}${c}`)).slice(0,15),16)/0x1000000000000000}async function cX(a,b){if(null==a||null==a.id||null==a.exclusion_percentage)return;let c=Number(a.exclusion_percentage);if(!Number.isFinite(c))return;let d=Math.min(Math.max(c,0),100);if(!(100!==d&&await cW("holdout",b,"","-")>d/100))return`holdout-${a.id}`}function cY(a){let b=[],c=0;for(let d of a){let a=c+d.rollout_percentage/100;b.push({valueMin:c,valueMax:a,key:d.key}),c=a}return b}async function cZ(a,b,c){let d=await cW(a,b,"variant");return cY(c).find(a=>d>=a.valueMin&&d<a.valueMax)?.key}function c$(a){return"client"===a||"server"===a?a:"all"}function c_(a,b){return a===b||"all"===a||"all"===b}class c0 extends Error{constructor(a){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=a,Object.setPrototypeOf(this,c0.prototype)}}class c1 extends Error{constructor(a,b="unsupported_definition"){super(a),this.reason=b,this.name=c1.name,Error.captureStackTrace(this,c1),Object.setPrototypeOf(this,c1.prototype)}}let c2=["experience_continuity","unsupported_definition","unresolved_dependency","missing_context"];function c3(a,b){return void 0===a||c2.indexOf(b)<c2.indexOf(a)?b:a}function c4(a,b){return b instanceof cB&&Symbol.for("posthog.requiresServerRegexEvaluation")in b&&Object.defineProperty(a,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),a}class c5{constructor({pollingInterval:a,personalApiKey:b,projectApiKey:c,timeout:d,host:e,customHeaders:f,...g}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.warnedUnresolvableFlags=new Map,this.pollingInterval=a,this.personalApiKey=b,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=d,this.projectApiKey=c,this.host=e,this.poller=void 0,this.fetch=g.fetch||fetch,this.onError=g.onError,this.customHeaders=f,this.onLoad=g.onLoad,this.onMinimalFlagCalledEvents=g.onMinimalFlagCalledEvents,this.cacheProvider=g.cacheProvider,this.strictLocalEvaluation=g.strictLocalEvaluation??!1,this.evaluationContexts=g.evaluationContexts,this.loadFeatureFlags()}debug(a=!0){this.debugMode=a}logMsgIfDebug(a){this.debugMode&&a()}currentDefinitions(){return{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}withEvaluationSnapshot(a){return a.definitions?a:{...a,evaluationCache:{},definitions:this.currentDefinitions()}}createEvaluationContext(a,b={},c={},d={},e={}){return{distinctId:a,groups:b,personProperties:c,groupProperties:d,evaluationCache:e}}async getFeatureFlag(a,b,c={},d={},e={}){let f,g;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return f;if(void 0!==(g=this.featureFlagsByKey[a])){let h=this.createEvaluationContext(b,c,d,e);try{f=(await this.computeFlagAndPayloadLocally(g,h)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${a} -> ${f}`))}catch(b){b instanceof c1||b instanceof cB?this.logMsgIfDebug(()=>console.debug(`${b.name} when computing flag locally: ${a}: ${b.message}`)):b instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${a}: ${b}`))}}return f}async getAllFlagsAndPayloads(a,b){await this.loadFeatureFlags();let c={},d={},e={},f=0==this.featureFlags.length,g=b?b.map(a=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,h=this.withEvaluationSnapshot({...a,definitions:void 0});return await Promise.all(g.map(async a=>{try{let{value:b,payload:e}=await this.computeFlagAndPayloadLocally(a,h,{skipLoadCheck:!0});c[a.key]=b,e&&(d[a.key]=e)}catch(b){b instanceof c1||b instanceof cB?(this.logMsgIfDebug(()=>console.debug(`${b.name} when computing flag locally: ${a.key}: ${b.message}`)),e[a.key]=b.reason):b instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${a.key}: ${b}`)),c_(c$(a.evaluation_runtime),"server")&&(f=!0)}})),{response:c,payloads:d,unresolved:e,fallbackToFlags:f}}async computeFlagAndPayloadLocally(a,b,c={}){let d,{matchValue:e,skipLoadCheck:f=!1}=c;if(this.loadedSuccessfullyOnce&&(b=this.withEvaluationSnapshot(b)),f||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};a=(b=this.withEvaluationSnapshot(b)).definitions.featureFlagsByKey[a.key]??a,d=void 0!==e?e:await this.computeFlagValueLocally(a,b);let g=function(a,b){if(!1===b||null==b||!a)return null;let c=a["boolean"==typeof b?b.toString():b]||null;return null==c?null:aC(c)}(a.filters?.payloads,d);return{value:d,payload:g}}async computeFlagValueLocally(a,b){let{distinctId:c,groups:d,personProperties:e,groupProperties:f}=b;if(!a.active)return!1;if(a.ensure_experience_continuity)throw new cB("Flag has experience continuity enabled","experience_continuity");let g=(a.filters||{}).aggregation_group_type_index;if(void 0!=g){let c=b.definitions.groupTypeMapping[String(g)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${g} for feature flag ${a.key}`)),new cB("Flag has unknown group type index");if(!(c in d))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${a.key} without group names passed in`)),!1;"device_id"===a.bucketing_identifier&&(e?.$device_id===void 0||e?.$device_id===null||e?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${a.key}`));let h=f[c];return await this.matchFeatureFlagProperties(a,d[c],h,b)}{let d=this.getBucketingValueForFlag(a,c,e);if(void 0===d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${a.key} without $device_id, falling back to server evaluation`)),new cB(`Can't compute feature flag: ${a.key} without $device_id`,c6(a,b.definitions)??"missing_context");return await this.matchFeatureFlagProperties(a,d,e,b)}}getBucketingValueForFlag(a,b,c){if(a.filters?.aggregation_group_type_index!=void 0)return b;if("device_id"===a.bucketing_identifier){let a=c?.$device_id;if(null==a||""===a)return;return a}return b}async evaluateFlagDependency(a,b,c){let{evaluationCache:d}=c,e=a.key;if(!c.definitions.featureFlagsByKey)throw new cB("Feature flags not available for dependency evaluation");if(!("dependency_chain"in a))throw new cB(`Flag dependency property for '${e}' is missing required 'dependency_chain' field`);let f=a.dependency_chain;if(!Array.isArray(f))throw new cB(`Flag dependency property for '${e}' has an invalid 'dependency_chain' (expected array, got ${typeof f})`);if(0===f.length)throw new cB(`Circular dependency detected for flag '${e}' (empty dependency chain)`);let g=f.find(a=>!(a in d)&&!c.definitions.featureFlagsByKey[a]&&!c.definitions.filteredOutFlagKeys.has(a));if(void 0!==g)throw new cB(`Missing flag dependency '${g}' for flag '${e}'`);for(let a of f){if(!(a in d)){let b=c.definitions.featureFlagsByKey[a];if(b)if(b.active)try{let e=await this.computeFlagValueLocally(b,c);d[a]=e}catch(b){if(b instanceof c1)throw new c1(`Flag dependency '${a}' for flag '${e}' requires server evaluation: ${b.message}`,"unresolved_dependency");throw c4(new cB(`Error evaluating flag dependency '${a}' for flag '${e}': ${b}`,"unresolved_dependency"),b)}else d[a]=!1;else d[a]=!1}if(null==d[a])throw new cB(`Dependency '${a}' could not be evaluated`,"unresolved_dependency")}let h=d[e];return this.flagEvaluatesToExpectedValue(a.value,h)}flagEvaluatesToExpectedValue(a,b){return"boolean"==typeof a?a===b||"string"==typeof b&&""!==b&&!0===a:"string"==typeof a&&b===a}async matchFeatureFlagProperties(a,b,c,d){let e,f,g;d=this.withEvaluationSnapshot(d);let h=a.filters||{},i=await cX(h.holdout,b);if(void 0!==i)return i;let j=h.groups||[],k=h.aggregation_group_type_index,l=h.early_exit??!1,{groups:m,groupProperties:n}=d,o=new Set;for(let i of j){let j=b;try{let b=void 0!==i.aggregation_group_type_index?i.aggregation_group_type_index:k,f=c;if(b!==k&&null!=b){let c=d.definitions.groupTypeMapping[String(b)];if(!c||!(c in m)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${a.key}': group type index ${b} not available`));continue}if(!(c in n)){e=c3(e,"missing_context");continue}f=n[c],j=m[c]}let o=await this.isConditionMatch(a,j,i,f,d);if("match"===o){let b=i.variant,c=h.multivariate?.variants||[];g=b&&c.some(a=>a.key===b)?b:await this.getMatchingVariant(a,j)||!0;break}if(l&&"out_of_rollout_bound"===o){if(e)break;return!1}}catch(b){if(b instanceof c1){let c;try{c=c6(a,d.definitions)}catch{}let f=c3(c3(e,b.reason),c??b.reason);throw f===b.reason?b:new c1(b.message,f)}if(b instanceof cB){if(e=c3(e,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b)if(f=b,l&&void 0!=i.rollout_percentage&&await cW(a.key,j)>i.rollout_percentage/100)o.add(!1);else{let b=h.multivariate?.variants||[],c=i.variant;o.add(c&&b.some(a=>a.key===c)?c:await this.getMatchingVariant(a,j)||!0)}}else throw b}}if(void 0!==g&&!(f&&[...o].some(a=>a!==g)))return g;if(e)throw c4(new cB("Can't determine if feature flag is enabled or not with given properties",e),f);return!1}async isConditionMatch(a,b,c,d,e){let f=(e=this.withEvaluationSnapshot(e)).definitions,g=c.rollout_percentage,h=a=>{this.logMsgIfDebug(()=>console.warn(a))};if((c.properties||[]).length>0){let b,i,j;for(let a of c.properties){let c=a.type,g=!1;try{if("cohort"===c)g=await c8(a,d,f.cohorts,this.debugMode,a=>this.evaluateFlagDependency(a,d,e),f.propertyMatchingVersion);else if("flag"===c)g=await this.evaluateFlagDependency(a,d,e);else if(Object.prototype.hasOwnProperty.call(d,a.key))g=c7(a,d,h,f.propertyMatchingVersion);else{cU(a),b=c3(b,"missing_context");continue}}catch(a){if(a instanceof c1){void 0===b&&(j??=a),b=c3(b,a.reason);continue}if(a instanceof cB){Symbol.for("posthog.requiresServerRegexEvaluation")in a&&(i=a),b=c3(b,a.reason);continue}if(void 0!==b)break;throw a}if(!g)return"no_match"}if(j)throw j;if(b)throw c4(new cB(`Can't determine if a condition of flag ${a.key} matches`,b),i);if(void 0==g)return"match"}return void 0!=g&&await cW(a.key,b)>g/100?"out_of_rollout_bound":"match"}async getMatchingVariant(a,b){return cZ(a.key,b,a.filters?.multivariate?.variants||[])}variantLookupTable(a){return cY(a.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(a){if(!this.evaluationContexts||0===this.evaluationContexts.length)return a;let b=new Set(this.evaluationContexts);return a.filter(a=>{let c=a.evaluation_contexts??a.evaluation_tags;return!c||0===c.length||c.some(a=>b.has(a))})}getEvaluationRuntimeForFlag(a){let b=this.featureFlagsByKey[a];return b?c$(b.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(a){return this.featureFlags.filter(b=>c_(c$(b.evaluation_runtime),a)).map(a=>a.key)}updateFlagState(a){let b=this.filterFlagsByEvaluationContexts(a.flags),c=b.reduce((a,b)=>(a[b.key]=b,a),{}),d=new Set(b.map(a=>a.key)),e=new Set(a.flags.filter(a=>!d.has(a.key)).map(a=>a.key));this.featureFlags=b,this.featureFlagsByKey=c,this.filteredOutFlagKeys=e,this.groupTypeMapping=a.group_type_mapping??a.groupTypeMapping??{},this.cohorts=a.cohorts,this.propertyMatchingVersion=a.property_matching_version??a.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((a.minimal_flag_called_events??a.minimalFlagCalledEvents)===!0)}warnAboutUnresolvableFlags(a){let b=[],c=[],d=new Map,e=this.currentDefinitions();for(let f of a){if(!c_(c$(f.evaluation_runtime),"server"))continue;let a=c6(f,e);if(!a)continue;let g=JSON.stringify(f);d.set(f.key,g),this.warnedUnresolvableFlags.get(f.key)!==g&&("experience_continuity"===a?b.push(f.key):c.push(f.key))}if(this.warnedUnresolvableFlags=d,b.length>0){let a=this.strictLocalEvaluation?"With strictLocalEvaluation enabled these flags are left unresolved. To evaluate them locally, disable experience continuity on these flags in PostHog.":"Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).";console.warn(`[PostHog] You are using local evaluation but ${b.length} flag(s) have experience continuity enabled and cannot be resolved locally (reason: experience_continuity): ${b.join(", ")}. `+a)}if(c.length>0){let a=this.strictLocalEvaluation?"With strictLocalEvaluation enabled these flags are left unresolved when evaluation reaches that part.":"Evaluating these flags falls back to a server request when evaluation reaches that part.";console.warn(`[PostHog] You are using local evaluation but ${c.length} flag(s) use something local evaluation does not support, such as a static cohort, an unknown operator, or a missing or circular flag dependency (reason: unsupported_definition): ${c.join(", ")}. ${a} To evaluate them locally, change these flags in PostHog or upgrade posthog-node.`)}}async loadFromCache(a){if(!this.cacheProvider)return!1;try{let b=await this.cacheProvider.getFlagDefinitions();if(b)return this.updateFlagState(b),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${a} (${b.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags),!0;return!1}catch(a){return this.onError?.(Error(`Failed to load from cache: ${a}`)),!1}}async loadFeatureFlags(a=!1){if(!this.loadedSuccessfullyOnce||a)return!a&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(a=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${a}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let a=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(6e4,a*2**this.backOffCount):a}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{if(this.cacheProvider&&!this.personalApiKey)return void await this.loadFromCache("Loaded flags from cache (cache-only reader)");let a=!0;if(this.cacheProvider)try{a=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(a){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${a}`))}if(!a&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let b=await this._requestFeatureFlagDefinitions();if(!b)return;switch(b.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=b.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new c0(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new c0(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new c0(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let c=await b.json()??{};if(!("flags"in c))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(c)}`));this.flagsEtag=b.headers?.get("ETag")??void 0;let d=c.group_type_mapping||{},e=!0===c.minimal_flag_called_events,f={flags:c.flags??[],group_type_mapping:d,cohorts:c.cohorts||{},minimal_flag_called_events:e,property_matching_version:c.property_matching_version,propertyMatchingVersion:c.property_matching_version,groupTypeMapping:d,minimalFlagCalledEvents:e};if(this.updateFlagState(f),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&a)try{await this.cacheProvider.onFlagDefinitionsReceived(f)}catch(a){this.onError?.(Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags);break}default:return}}catch(a){a instanceof c0&&this.onError?.(a)}finally{this.pollerStopped||null===this.pollingInterval||(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(a="GET",b){let c={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return b&&(c["If-None-Match"]=b),{method:a,headers:c}}async _requestFeatureFlagDefinitions(){if(!this.personalApiKey)throw new c0("A secretKey or personalApiKey is required to fetch feature flag definitions from PostHog.");let a=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,b=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),c=null;if(this.timeout&&"number"==typeof this.timeout){let a=new AbortController;c=aM(()=>{a.abort()},this.timeout),b.signal=a.signal}try{let d=this.fetch,e=await d(a,b);if(200!==e.status)return clearTimeout(c),e;return{status:e.status,headers:e.headers,body:e.body,text:async()=>{try{return await e.text()}finally{clearTimeout(c)}},json:async()=>{try{return await e.json()}finally{clearTimeout(c)}}}}catch(a){throw clearTimeout(c),a}}async stopPoller(a=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let b=this.cacheProvider.shutdown();b instanceof Promise&&await aN(b,a,()=>{throw Error(`Cache shutdown timeout after ${a}ms`)})}catch(a){this.onError?.(Error(`Error during cache shutdown: ${a}`))}}}function c6(a,b){if(!a.active)return;if(a.ensure_experience_continuity)return"experience_continuity";let c=a.filters||{},d=c.aggregation_group_type_index;return void 0==d||b.groupTypeMapping[String(d)]?(c.groups||[]).some(a=>(a.properties||[]).some(a=>(function a(b,c,d){if("flag"===b.type){let a=b.dependency_chain;return!Array.isArray(a)||0===a.length||a.some(a=>!c.featureFlagsByKey[a]&&!c.filteredOutFlagKeys.has(a))}if("cohort"!==b.type)try{return cU(b),!1}catch(a){if(a instanceof cB)return!0;throw a}let e=String(b.value);return!(e in c.cohorts)||!d.has(e)&&(d.add(e),function b(c,d,e){return(c?.values??[]).some(c=>"values"in c?b(c,d,e):a(c,d,e))}(c.cohorts[e],c,d))})(a,b,new Set)))?"unsupported_definition":void 0:"unsupported_definition"}function c7(a,b,c,d){return function(a,b,c={}){try{return function(a,b,c){let d=a.key,e=a.value,f=a.operator||"exact",g=c.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(b,d)){if("is_not_set"===f)return!1;else if("is_set"===f)return!0}else throw new cB(`Property ${d} not found in propertyValues`,"missing_context");let h=b[d];if(void 0===h)throw c.warnFunction?.(`Property ${d} cannot have a value of undefined with the ${f} operator`),new cB(`Property ${d} is undefined in propertyValues`);if(null===h&&!cA.includes(f))return c.warnFunction?.(`Property ${d} cannot have a value of null with the ${f} operator`),!1;let i=(a,b)=>{if(2!==c.propertyMatchingVersion&&cD(a)||Array.isArray(a)&&0===a.length)return cC(()=>cG(b)),cE(a)===cE(b);if(2===c.propertyMatchingVersion&&"number"==typeof b&&cD(a))return cC(()=>cG(b)),!1;if(Array.isArray(a)){let c=cC(()=>cI(b)).toLowerCase();return a.some(a=>cI(a).toLowerCase()===c)}return cI(a).toLowerCase()===cC(()=>cI(b)).toLowerCase()},j=(a,b,c)=>{if("gt"===c)return a>b;if("gte"===c)return a>=b;if("lt"===c)return a<b;if("lte"===c)return a<=b;throw Error(`Invalid operator: ${c}`)},k=()=>cC(()=>cN(String(h),g)),l=()=>{let a=cN(String(e),g);return cO(k(),a)},m=({lower:a,upper:b})=>{let c=k();return cO(c,a)>=0&&0>cO(c,b)};switch(f){case"exact":return i(e,h);case"is_not":return!i(e,h);case"is_set":return!0;case"icontains":return cL(h).includes(cL(e));case"not_icontains":return!cL(h).includes(cL(e));case"starts_with":return cL(h).startsWith(cL(e));case"not_starts_with":return!cL(h).startsWith(cL(e));case"ends_with":return cL(h).endsWith(cL(e));case"not_ends_with":return!cL(h).endsWith(cL(e));case"regex":case"not_regex":{let a=function(a,b){let c;if(""===a)return!0;let d=function(a){let b=[],c=-1,d="";for(let e=0;e<a.length;e++){let f=a[e];if(f.charCodeAt(0)>127)return null;if("\\"===f){let b=a[++e];if(void 0===b)break;if("x"===b){if(!/^[\da-f]{2}$/i.test(a.slice(e+1,e+3)))return null;e+=2}else if(!"dDsSwWbBfnrtv".includes(b)&&!cJ.test(b))return null;if(-1===c&&"bB".includes(b))return null;d="literal";continue}if("["===f){if(-1!==c)return null;c=e}else if("]"===f&&-1!==c){if(e===c+("^"===a[c+1]?2:1))return null;b.push(a.slice(c,e+1)),c=-1,d="literal";continue}else if(-1!==c){if(["&&","--","~~"].includes(a.slice(e,e+2)))return null;continue}else if("("===f&&"?"===a[e+1]){if(":"!==a[e+2])return null;e+=2}else if("{"===f){let b=/^\{(\d+)(?:,(\d*))?\}/.exec(a.slice(e));if(!b||["","|","("].includes(d)||b.slice(1).some(a=>Number(a)>0xffffffff))return null}else if("*+?}".includes(f)&&("+"===a[e+1]||"{"===a[e+1]))return null;if("*+?{".includes(f)&&["^","$","empty group"].includes(d))return null;d=")"===f&&["(","empty group"].includes(d)?"empty group":f}return b}(a);if(null===d)throw cK("Regex syntax requires server evaluation");try{c=new RegExp(a)}catch(a){if(a instanceof SyntaxError)return null;throw cK("Regex compilation requires server evaluation")}for(let a of d)try{RegExp(a,"u")}catch{throw cK("Regex character class syntax requires server evaluation")}for(let a=0;a<b.length;a++){let c=b[a];if(c.charCodeAt(0)>127||"\r"===c)throw cK("Regex matching for Unicode or carriage returns requires server evaluation")}try{return c.test(b)}catch{throw cK("Regex execution requires server evaluation")}}(String(e),String(h));if(null===a)return!1;return"regex"===f?a:!a}case"gt":case"gte":case"lt":case"lte":{let a="number"==typeof e?e:parseFloat(String(e)),b="number"==typeof h?h:null!=h?parseFloat(String(h)):0/0;if(Number.isFinite(a)&&Number.isFinite(b))return j(b,a,f);return j(String(h),String(e),f)}case"is_date_after":case"is_date_before":{let a=cT(e),b=cC(()=>cS(h));return"is_date_before"===f?b<a:b>a}case"semver_eq":return 0===l();case"semver_neq":return 0!==l();case"semver_gt":return l()>0;case"semver_gte":return l()>=0;case"semver_lt":return 0>l();case"semver_lte":return 0>=l();case"semver_tilde":return m(cP(String(e),g));case"semver_caret":return m(cQ(String(e),g));case"semver_wildcard":return m(cR(String(e),g));default:throw new cB(`Unknown operator: ${f}`)}}(a,b,c)}catch(b){throw b instanceof cB&&"missing_context"===b.reason&&cU(a,c),b}}(a,b,{warnFunction:c,propertyMatchingVersion:d})}async function c8(a,b,c,d=!1,e,f){let g=String(a.value);if(!(g in c))throw new c1(`cohort ${g} not found in local cohorts - likely a static cohort that requires server evaluation`);let h=c[g],i=await c9(h,b,c,d,e,f);return"not_in"===a.operator?!i:i}async function c9(a,b,c,d=!1,e,f){let g,h;if(!a||0===Object.keys(a).length)return!0;let i="property"===a.type?"AND":a.type;if("AND"!==i&&"OR"!==i)throw new c1(`Unsupported cohort property group type: ${a.type}`);let j=a.values;if(!j||0===j.length)return"AND"===i;if("values"in j[0]){for(let a of j)try{let g=await c9(a,b,c,d,e,f);if("AND"===i){if(!g)return!1}else if(g)return!0}catch(b){if(b instanceof c1)throw b;if(b instanceof cB)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),g=c3(g,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b&&(h=b);else throw b}if(g)throw c4(new cB("Can't match cohort without a given cohort property value",g),h);return"AND"===i}for(let a of j)try{let g;if("cohort"===a.type)g=await c8(a,b,c,d,e,f);else if("flag"===a.type){if(!e)throw new cB(`Flag dependency '${a.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);g=await e(a)}else g=c7(a,b,void 0,f);let h=a.negation||!1;if("AND"===i){if(!g&&!h||g&&h)return!1}else if(g&&!h||!g&&h)return!0}catch(b){if(b instanceof c1)throw b;if(b instanceof cB)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),g=c3(g,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b&&(h=b);else throw b}if(g)throw c4(new cB("can't match cohort without a given cohort property value",g),h);return"AND"===i}let da=["--unhandled-rejections","--unhandled_rejections"],db=new Set(["throw","strict","warn","warn-with-error-code","none"]),dc=[...globalThis.process?.execArgv??[]],dd=globalThis.process?.env?.NODE_OPTIONS;function de(a){let b;for(let c=0;c<a.length;c++){let d=a[c],e=da.find(a=>d===a||d.startsWith(`${a}=`));if(!e)continue;let f=d===e?a[++c]:d.slice(e.length+1);db.has(f)&&(b=f)}return b}let df=function(a=dc,b=dd){return de(a)??de(function(a){let b=[],c="",d=!1;for(let e=0;e<a.length;e++){let f=a[e];"\\"===f&&d&&e+1<a.length?c+=a[++e]:" "!==f||d?'"'===f?d=!d:c+=f:c&&(b.push(c),c="")}return c&&b.push(c),b}(b??""))??"throw"}(),dg={mechanism:{type:"onunhandledrejection",handled:!1}},dh={mechanism:{type:"onuncaughtexception",handled:!1}},di=new Set(["HANGING_PROMISE_REJECTION","NEXT_PRERENDER_INTERRUPTED","DYNAMIC_SERVER_USAGE","BAILOUT_TO_CLIENT_SIDE_RENDERING"]),dj=Symbol.for("react.postpone"),dk=Symbol.for("next.unhandledRejectionFilter"),dl=Symbol.for("posthog-node.exception-autocapture.v1"),dm=globalThis;function dn(a){return"function"==typeof a&&!0===a._posthogErrorHandler}function dp(a){return"object"==typeof a&&null!==a||"function"==typeof a}function dq(a){return Object.assign(a,{_posthogErrorHandler:!0})}function dr(a){return a.listeners("unhandledRejection").some(a=>!dn(a))}function ds(a,b){return function a(b,c=0){try{if(!dp(b))return!1;if(b.$$typeof===dj||"string"==typeof b.digest&&di.has(b.digest))return!0;return c<5&&a(b.cause,c+1)}catch{return!1}}(a)||"unhandledRejection"===b&&function(a){try{return dp(a)&&"AbortError"===a.name}catch{return!1}}(a)}function dt(a){let b=new Map;for(let c of a.clients){let a=b.get(c.key);a&&(void 0!==a.getContext()||void 0===c.getContext())||b.set(c.key,c)}for(let[c,d]of a.retired)b.has(c)||b.set(c,d);return[...b.values()]}function du(a){"function"==typeof globalThis.setImmediate?setImmediate(a):setTimeout(a,0)}function dv(a,b,c,d){let e=a.capturedThisTurn.get(b)??new Map;e.has(c)||e.set(c,d),a.capturedThisTurn.set(b,e),a.turnResetScheduled||(a.turnResetScheduled=!0,du(()=>{du(()=>{a.capturedThisTurn.clear(),a.turnResetScheduled=!1})}))}function dw(a,b,c,d){let e=a.capturedThisTurn.get(b),f=[];for(let g of dt(a))e?.has(g.key)||d?.has(g.key)||(dv(a,b,g.key,"autocapture"),g.capture(b,c),f.push(g));return f}function dx(a,b){return a.deferred.get(b.exception)!==b?[]:(a.deferred.delete(b.exception),b.runInContext(()=>dw(a,b.exception,b.hint,b.skipKeys)))}function dy(a,b,c){let d;if(void 0!==(d=a.capturedThisTurn.get(b))&&dt(a).every(a=>d.has(a.key))||a.deferred.has(b))return;let e={exception:b,hint:c,skipKeys:new Set(a.capturedThisTurn.get(b)?.keys()),runInContext:function(){try{let a=globalThis.process,b=a?.getBuiltinModule?.("node:async_hooks"),c=b?.AsyncLocalStorage?.snapshot?.();if(c)return c}catch{}return a=>a()}()};a.deferred.set(b,e),du(()=>dx(a,e))}async function dz(a,b){try{console.error(b)}catch{}dE();let c=new Set([...a.clients,...a.retired.values()]);await Promise.all([...c].map(a=>a.shutdown().catch(()=>void 0))),globalThis.process.exit(1)}function dA(a,b,c,d){let e="unhandledRejection"===c?dg:dh;if(!d){ds(b,c)||dy(a,b,e);return}let f=a.deferred.get(b);f?dx(a,f):dw(a,b,e)}function dB(a){try{return String(a)}catch{return typeof a}}function dC(a){let b=globalThis.process;dm[dk]&&"function"==typeof b.rawListeners&&b.rawListeners("unhandledRejection").includes(a)&&(Object.getPrototypeOf(b).removeListener.call(b,"unhandledRejection",a),b.listeners("unhandledRejection").includes(a)||b.prependListener("unhandledRejection",a))}function dD(a){let b=globalThis.process,c=[],d=(a,d)=>{b.on(a,d),c.push(()=>b.removeListener(a,d))},e=()=>c.forEach(a=>a());if("strict"===a.mode){let c=(b,c)=>dA(a,b,c,!0);return d("uncaughtExceptionMonitor",c),{remove:e,areInstalled:()=>b.listeners("uncaughtExceptionMonitor").includes(c)}}let f=dq((b,c)=>{let d=0===globalThis.process.listeners("uncaughtException").filter(a=>"domainUncaughtExceptionClear"!==a.name&&!dn(a)).length;dA(a,b,c,d),d&&!a.calledFatalError&&(a.calledFatalError=!0,dz(a,b))});d("uncaughtException",f);let g="throw"===a.mode||"warn-with-error-code"===a.mode,h=g&&!b.versions?.bun,i=()=>b.listeners("unhandledRejection").includes(j),j=dq(b=>{g&&!dr(globalThis.process)&&i()?function(a,b){let c=globalThis.process;if("warn-with-error-code"===a.mode){c.emitWarning(`Unhandled promise rejection: ${dB(b)}`,"UnhandledPromiseRejectionWarning"),c.exitCode=1,ds(b,"unhandledRejection")||dw(a,b,dg);return}if(c.versions?.bun){c.exitCode=1,dw(a,b,dg),a.calledFatalError||(a.calledFatalError=!0,dz(a,b));return}let d=b instanceof Error?b:Object.assign(Error(`This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "${dB(b)}".`),{name:"UnhandledPromiseRejection",code:"ERR_UNHANDLED_REJECTION"}),e=c.emit;e.call(c,"uncaughtExceptionMonitor",d,"unhandledRejection"),e.call(c,"uncaughtException",d,"unhandledRejection")}(a,b):ds(b,"unhandledRejection")||dy(a,b,dg)});return d("newListener",dq((a,c)=>{dn(c)||("unhandledRejection"===a?(i()||b.prependListener("unhandledRejection",j),queueMicrotask(()=>{let a;(a="function"==typeof b.rawListeners?b.rawListeners("unhandledRejection"):[]).includes(j)&&a[0]!==j&&(b.removeListener("unhandledRejection",j),b.prependListener("unhandledRejection",j)),dC(j)})):"Next.UnhandledRejectionFilter.MacguffinEvent"===a&&queueMicrotask(()=>{i()||b.prependListener("unhandledRejection",j)}))})),h?(d("removeListener",dq(a=>{"unhandledRejection"===a&&i()&&!dr(b)&&b.removeListener("unhandledRejection",j)})),dr(b)&&b.prependListener("unhandledRejection",j)):b.prependListener("unhandledRejection",j),dC(j),c.push(()=>{b.removeListener("unhandledRejection",j),"function"==typeof b.rawListeners&&b.rawListeners("unhandledRejection").includes(j)&&Object.getPrototypeOf(b).removeListener.call(b,"unhandledRejection",j)}),{remove:e,areInstalled:()=>b.listeners("uncaughtException").includes(f)&&(h||i())}}function dE(){let a=new Set,b=dm[dl];if(b)for(let c of[...b.deferred.values()])dx(b,c).forEach(b=>a.add(b));return a}let dF=Symbol("capturedContext");function dG(a,b,c,d,e){if(b>c&&(d.warn("min cannot be greater than max."),b=c),y(a))if(a>c)return d.warn(" cannot be greater than max: "+c+". Using max value instead."),c;else return a<b?(d.warn(" cannot be less than min: "+b+". Using min value instead."),b):a;return d.warn(" must be a number. using max or fallback. max: "+c+", fallback: "+e),dG(e??c,b,c,d)}class dH{constructor(a){this._buckets={},this._onBucketRateLimited=a._onBucketRateLimited,this._bucketSize=dG(a.bucketSize,0,100,a._logger),this._refillRate=dG(a.refillRate,0,this._bucketSize,a._logger),this._refillInterval=dG(a.refillInterval,0,864e5,a._logger)}_applyRefill(a,b){let c=Math.floor((b-a.lastAccess)/this._refillInterval);if(c>0){let b=c*this._refillRate;a.tokens=Math.min(a.tokens+b,this._bucketSize),a.lastAccess=a.lastAccess+c*this._refillInterval}}consumeRateLimit(a){let b=Date.now(),c=String(a),d=this._buckets[c];return d?this._applyRefill(d,b):(d={tokens:this._bucketSize,lastAccess:b},this._buckets[c]=d),0===d.tokens||(d.tokens--,0===d.tokens&&this._onBucketRateLimited?.(a),0===d.tokens)}stop(){this._buckets={}}}var dI=am;let dJ=class a{constructor(a,b,c){this.client=a,this._exceptionAutocaptureEnabled=b.enableExceptionAutocapture||!1,this._logger=c,this._rateLimiter=new dH({...function(a={}){return{refillRate:a.exceptionRateLimiterRefillRate??a.__exceptionRateLimiterRefillRate??1,bucketSize:a.exceptionRateLimiterBucketSize??a.__exceptionRateLimiterBucketSize??10}}(b),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(a){return a===Object(a)&&!s(a)&&"__posthog_previously_captured_error"in a&&!0===a.__posthog_previously_captured_error}static async buildEventMessage(a,b,c,d,e,f){let g,h=(g=f?{...f,properties:{...f.properties}}:null,a=>Object.assign(a,{[dF]:g})),i={...e},j=a.buildFromUnknown(b,c);j.$exception_list=await a.modifyFrames(j.$exception_list);let k=dI.getInjectedReleaseId();return k&&(i.$release_id=k),h({event:"$exception",distinctId:d,properties:{...j,...i},_originatedFromCaptureException:!0})}get destinationKey(){return`${this.client.apiKey}@${this.client.host}`}startAutocaptureIfEnabled(){this.isEnabled()&&(this._autocaptureClient={key:this.destinationKey,capture:(a,b)=>this.onException(a,b),getContext:()=>this.client.getContext(),flush:()=>this.client.flush(),shutdown:()=>this.client.shutdown(2e3)},this._stopAutocapture=function(a,b=df){if(!globalThis.process?.on)return()=>void 0;let c=dm[dl];if(c)c.listeners.areInstalled()||(c.listeners.remove(),c.listeners=dD(c));else{let a={mode:b,clients:new Set,retired:new Map,capturedThisTurn:new Map,deferred:new Map,turnResetScheduled:!1,calledFatalError:!1,listeners:{remove:()=>void 0,areInstalled:()=>!0}};a.listeners=dD(a),dm[dl]=a,c=a}c.clients.add(a),c.retired.delete(a.key);let d=c;return()=>{d.clients.delete(a)&&([...d.clients].some(b=>b.key===a.key)||d.retired.set(a.key,a))}}(this._autocaptureClient))}claimExplicitCapture(a){var b;let c;return b=this.destinationKey,!(c=dm[dl])||c.capturedThisTurn.get(a)?.get(b)!=="autocapture"&&(dv(c,a,b,"app"),c.deferred.get(a)?.skipKeys.add(b),!0)}capturePendingExceptions(){for(let a of dE())a!==this._autocaptureClient&&this.client.addPendingPromise(a.flush().catch(()=>void 0))}onException(b,c){this.client.addPendingPromise((async()=>{if(!a.isPreviouslyCapturedError(b)){let d=await a.buildEventMessage(this.client.getErrorPropertiesBuilder(),b,c,void 0,void 0,this.client.getContext()),e=d.properties,f=e?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(f)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:f}):this.client._capturePreparedEvent(d,!1)}})().catch(a=>{this._logger.error("Failed to capture an exception:",a)}))}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop(),this.capturePendingExceptions(),this._stopAutocapture?.(),this._stopAutocapture=void 0}},dK=/^[0-9a-f]{32}$/i,dL=/^[0-9a-f]{16}$/i,dM=Symbol.for("opentelemetry.js.api.1"),dN=Symbol.for("OpenTelemetry Context Key SPAN");async function dO(){try{let a=globalThis[dM],b=a?.context?.active().getValue(dN),c=b?.spanContext(),d=c?.traceId,e=c?.spanId;if("string"==typeof d&&"string"==typeof e&&dK.test(d)&&dL.test(e)&&!/^0+$/.test(d)&&!/^0+$/.test(e))return{$trace_id:d.toLowerCase(),$span_id:e.toLowerCase()}}catch{}return{}}class dP{getProperty(a){return this._memoryStorage[a]}setProperty(a,b){this._memoryStorage[a]=null!==b?b:void 0}constructor(){this._memoryStorage={}}}let dQ=Symbol.for("posthog-node.context-listeners"),dR=globalThis,dS=dR[dQ]??=new WeakMap;function dT(a,b=!1){for(let c of dS.get(a)??[])try{c(b)}catch{}}function dU(a){dT(a,!0)}let dV="analytics";class dW extends Error{constructor({requestId:a,drops:b,retryExhausted:c,cause:d}){super(dW.buildMessage(a,b,c,d)),this.name="CaptureV1Error",this.requestId=a,this.drops=b,this.retryExhausted=c,this.cause=d}static buildMessage(a,b,c,d){let e=`Capture V1 batch ${a} did not fully deliver: ${b.length} dropped, ${c.length} undelivered`;return d instanceof Error&&(e+=` (${d.message})`),e}}function dX(a){if("boolean"==typeof a)return a;if("number"==typeof a)return 0!==a;if("string"==typeof a){let b=a.trim().toLowerCase();if("true"===b||"1"===b)return!0;if("false"===b||"0"===b)return!1}}let dY=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:dX},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:dX},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:dX},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(a){return"string"==typeof a?a:void 0}}],dZ=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function d$(a,b,c){void 0===c||b in a||(a[b]=c)}function d_(a){var b;let c={..."object"==typeof(b=a.properties)&&null!==b&&!Array.isArray(b)?a.properties:{}},d={};for(let{property:a,optionKey:b,coerce:e}of dY)if(a in c){let f=e(c[a]);void 0!==f&&(d[b]=f),delete c[a]}let e={};for(let{property:a,field:b}of dZ)if(a in c){let d=c[a];"string"==typeof d&&(e[b]=d),delete c[a]}return delete c.$lib,delete c.$lib_version,d$(c,"$set",a.$set),d$(c,"$set_once",a.$set_once),{event:String(a.event??""),uuid:String(a.uuid??""),distinct_id:String(a.distinct_id??""),timestamp:function(a){if("string"==typeof a){let b=new Date(a);if(Number.isNaN(b.getTime()))return new Date().toISOString();let c=b.toISOString(),d=a.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return d&&d.length>3?c.replace(/\.\d{3}Z$/,`.${d}Z`):c}if(a instanceof Date)return Number.isNaN(a.getTime())?new Date().toISOString():a.toISOString();let b=null==a?new Date:new Date(a);return Number.isNaN(b.getTime())?new Date().toISOString():b.toISOString()}(a.timestamp),...e,options:d,properties:c}}let d0=new Set([404,408,429,500,502,503,504]);class d1{constructor(a,b){this.config=a,this.maxBackoffMs=a.maxBackoffMs??3e4,this.fetchFn=b.fetch,this.onError=b.onError,this.now=b.now??Date.now,this.sleep=b.sleep??(a=>new Promise(b=>aM(b,a))),this.generateRequestId=b.generateRequestId??aW,this.compress=b.compress??aR}async sendV1Batch(a){if(0===a.length)return;let b=this.generateRequestId(),c=new Date(this.now()).toISOString(),{batch:d}=function(a,{createdAt:b,historicalMigration:c}){let d={created_at:b,batch:a.map(d_)};return c&&(d.historical_migration=!0),d}(a,{createdAt:c,historicalMigration:this.config.historicalMigration}),e=`${this.config.host}/i/v1/analytics/events`,f=[],g=d,h=Math.max(1,this.config.maxAttempts);for(let a=1;a<=h;a++){let d,i,j=a===h,k=n({created_at:c,...this.config.historicalMigration?{historical_migration:!0}:{},batch:g});try{let{response:c,signal:h}=d=await this.sendOnce(e,k,a,b),{status:l}=c;if(l<200||l>=300)if(!j&&d0.has(l)){let b=this.parseRetryAfter(c);await d.waitFor(d.cancelBody()).catch(()=>{}),i=this.backoffDelay(a,b)}else{let a=await this.buildHttpError(c,l,d.waitFor);return this.surfaceBatchFailure(b,f,g,a)}else{let e;try{e=await d.waitFor(this.parseResponse(c))}catch(a){if(h.aborted)throw a;return this.surfaceBatchFailure(b,f,g,Error(`Capture V1 returned an unparseable ${l} response body`))}let k=this.classify(g,e,f);if(0===k.length)return this.surfacePartialDrops(b,f);if(j)return void this.onError(new dW({requestId:b,drops:f,retryExhausted:k.map(a=>a.uuid)}));g=k;let m=this.parseRetryAfter(c);i=this.backoffDelay(a,m)}}catch(c){if(d&&!d.signal.aborted)throw c;if(j)return this.surfaceBatchFailure(b,f,g,c);i=this.backoffDelay(a)}finally{d?.cleanup()}void 0!==i&&await this.sleep(i)}}async sendOnce(a,b,c,d){let e,f=this.buildHeaders(c,d),g=b;if(this.config.compressionEnabled){let a=await this.compress(b,this.config.isDebug);null!==a&&(g=a,f["Content-Encoding"]="gzip")}let h=new AbortController,i="waiting for response headers",j=new Promise((a,b)=>{e=aM(()=>{let a=Error(`Capture V1 request timed out ${i} after ${this.config.requestTimeoutMs}ms`);a.name="AbortError",b(a),h.abort(a)},this.config.requestTimeoutMs)});try{let b,c=this.fetchFn(a,{method:"POST",headers:f,body:g,signal:h.signal}),d=!1;c.then(a=>{h.signal.aborted&&!d&&this.cancelBody(a)}).catch(()=>{});let k=await Promise.race([c,j]);d=!0,i="while reading the response body";let l=!1,m=()=>b??=this.cancelBody(k);return{response:k,signal:h.signal,waitFor:a=>Promise.race([a,j]),cancelBody:m,cleanup:()=>{!l&&(l=!0,clearTimeout(e),h.signal.aborted&&m())}}}catch(a){throw clearTimeout(e),a}}buildHeaders(a,b){let c=`${this.config.libraryId}/${this.config.libraryVersion}`,d={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":c,"PostHog-Attempt":String(a),"PostHog-Request-Id":b,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(d["User-Agent"]=this.config.userAgent),d}classify(a,b,c){let d=b.results??{},e=[];for(let b of a){let a=d[b.uuid];a&&("drop"===a.result?c.push({uuid:b.uuid,details:a.details??void 0}):"retry"===a.result&&e.push(b))}return e}backoffDelay(a,b){let c=Math.min(this.config.initialRetryDelayMs*2**(a-1),this.maxBackoffMs);return void 0===b?c:Math.max(c,Math.min(b,this.maxBackoffMs))}parseRetryAfter(a){let b=a.headers?.get("Retry-After");if(!b)return;let c=b.trim();if(/^\d+$/.test(c)){let a=parseInt(c,10);return Number.isFinite(a)&&a>0?1e3*a:void 0}let d=Date.parse(c);if(Number.isNaN(d))return;let e=d-this.now();return e>0?e:void 0}async parseResponse(a){let b=JSON.parse(await a.text());if("object"!=typeof b||null===b||Array.isArray(b))throw Error("unexpected response shape");let c=b.results;if(void 0!==c&&("object"!=typeof c||null===c||Array.isArray(c)))throw Error("unexpected results shape");return{results:c??{}}}async buildHttpError(a,b,c){let d="";try{d=(await c(a.text())).slice(0,512)}catch{}let e=d?`: ${d}`:"";return Error(`Capture V1 request failed with HTTP ${b}${e}`)}surfaceBatchFailure(a,b,c,d){this.onError(new dW({requestId:a,drops:b,retryExhausted:c.map(a=>a.uuid),cause:d}))}surfacePartialDrops(a,b){b.length>0&&this.onError(new dW({requestId:a,drops:b,retryExhausted:[]}))}async cancelBody(a){try{await a.body?.cancel()}catch{}}}let d2="ai-capture",d3="/i/v0/ai/batch/",d4=new TextEncoder;function d5(a){return d4.encode(n(a)).length}class d6 extends Error{constructor(a){super(a.message,void 0===a.cause?void 0:{cause:a.cause}),this.name=function(a,b){if("missing_secret_key"===b||401===a)return"missing_api_key";if(void 0===a)return"network_error"===b?"service_unavailable":b.startsWith("invalid_")||d7.has(b)?"validation_error":"application_error";if("attachment_upload_failed"===b)return a>=500?"service_unavailable":"application_error";switch(a){case 400:return"validation_error";case 403:return"invalid_permission";case 404:return"not_found";case 409:return"template_outdated"===b?"validation_error":"concurrent_idempotent_requests";case 422:return"idempotency_key_reused"===b?"invalid_idempotent_request":"validation_error";case 429:return"quota_limited"===b?"monthly_quota_exceeded":"rate_limit_exceeded";case 503:return"service_unavailable";default:return"application_error"}}(a.statusCode,a.code),this.code=a.code,this.statusCode=a.statusCode,this.why=a.why,this.fix=a.fix,this.docsUrl=a.docsUrl,this.field=a.field,this.retryAfterMs=a.retryAfterMs}}let d7=new Set(["too_many_attachments","message_too_large"]),d8=/^[A-Za-z0-9+/]*={0,2}$/;async function d9(a){return Promise.all(a.map(async(a,b)=>({...a,sha256:await ed(a.bytes),field:`attachments__${b}`})))}function ea({sha256:a,filename:b,contentType:c,contentId:d}){return{sha256:a,filename:b,...void 0!==c&&{content_type:c},...void 0!==d&&{content_id:d}}}function eb(a,b){var c,d;let e;if("object"!=typeof a||null===a||Array.isArray(a)||ArrayBuffer.isView(a))throw ee("An attachment is an object with filename and content. Pass the file's bytes as its content.",`attachments__${b}`);let{filename:f,content:g,contentType:h,contentId:i,path:j,...k}=a;if(void 0!==j)throw ee("PostHog can't fetch an attachment from a path or URL. Read the file and pass its content instead.",`attachments__${b}__path`);let l=Object.entries(k).find(([,a])=>void 0!==a)?.[0];if(void 0!==l)throw ee(`An attachment takes filename, content, contentType and contentId, not ${l}.`,`attachments__${b}__${l}`);if("string"!=typeof f||""===f)throw ee("An attachment needs a filename, such as 'invoice.pdf'.",`attachments__${b}__filename`);if("string"!=typeof g&&!(g instanceof Uint8Array))throw ee("An attachment needs content: a Buffer, a Uint8Array or a Base64 string.",`attachments__${b}__content`);if("string"==typeof g&&!((c=g).length%4==0&&d8.test(c)))throw ee("An attachment's content string must be Base64. Pass text as a Buffer or a Uint8Array.",`attachments__${b}__content`);if(void 0!==h&&"string"!=typeof h)throw ee("An attachment's contentType must be a string, such as 'application/pdf'.",`attachments__${b}__contentType`);if(void 0!==i&&"string"!=typeof i)throw ee("An attachment's contentId must be a string.",`attachments__${b}__contentId`);let m="string"==typeof g?(e=(d=g).endsWith("==")?2:+!!d.endsWith("="),d.length/4*3-e):g.byteLength;if(0===m)throw ee("An attachment needs at least one byte.",`attachments__${b}__content`);return{filename:f,content:g,size:m,...void 0!==h&&{contentType:h},...void 0!==i&&{contentId:i}}}function ec(a,b,c){if(0===a.length)return;let d=new TextEncoder;if([...a,...b.map(a=>d.encode(a).byteLength)].reduce((a,b)=>a+Math.ceil(4*Math.ceil(b/3)*78/76),65536+75*Math.ceil(d.encode(c).byteLength/42))>4e7)throw new d6({code:"message_too_large",message:"These files make the email larger than 40 MB after Base64 encoding, about 29 MB of files, so no email was sent.",field:"attachments",why:"PostHog's email provider takes emails up to 40 MB, and Base64 encoding makes each file about a third larger.",fix:"Send fewer or smaller files, or link to large files from the email body."})}async function ed(a){return Array.from(new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",a)),a=>a.toString(16).padStart(2,"0")).join("")}function ee(a,b){return new d6({code:"invalid_attachment",message:a,field:b})}let ef="https://us.posthog.com",eg="https://eu.posthog.com",eh={"https://us.i.posthog.com":ef,"https://us.posthog.com":ef,"https://app.posthog.com":ef,"https://eu.i.posthog.com":eg,"https://eu.posthog.com":eg},ei=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ej=/^[\x21-\x7e]{1,255}$/,ek=/^[a-zA-Z0-9_-]{1,400}$/,el={to:!0,distinctId:!0,idempotencyKey:!0,maxRetries:!0},em={name:"templateId",fields:ey(el,{templateId:!0,templateData:!0}),why:"A template made in PostHog sets its own sender, subject and content, and follows the project's engagement setting.",howToSend:"send a template made in PostHog with templateId"},en={name:"templateKey",fields:ey(el,{templateKey:!0,subject:!0,from:!0,replyTo:!0,captureEngagement:!0,cc:!0,bcc:!0,attachments:!0,sensitive:!0,tracking:!0,html:!0,text:!0,react:!0}),why:"A send with templateKey takes its content from your code.",howToSend:"send content from your code with templateKey"};class eo{constructor(a,b){this.inFlight=new Set,this.config=a,this.hooks=b}send(a,...b){return this.track(this.sendUntracked(a,b))}get(a){return this.track(this.getUntracked(a))}setPreferences(a){return this.track(this.setPreferencesUntracked(a))}track(a){return this.inFlight.add(a),a.finally(()=>this.inFlight.delete(a)),a}async drain(){for(;this.inFlight.size>0;)await Promise.all(this.inFlight)}async sendUntracked(a,b){try{let e,f;var c,d=b;if(d.some(a=>void 0!==a))throw new d6({code:"invalid_form",message:"send takes one options object, so no email was sent. Put idempotencyKey and every other option in it."});let g=function(a,b){let c=a??{},{to:d,distinctId:e,idempotencyKey:f,maxRetries:g}=c;if("string"!=typeof d||!d.trim())throw ez("invalid_recipient","to must be one email address as a nonempty string.","to");if(void 0!==e&&("string"!=typeof e||!e))throw ez("invalid_distinct_id","distinctId must be a nonempty string.","distinctId");let{content:h,files:i}=function(a,b){if(void 0===a.templateId==(void 0===a.templateKey))throw new d6({code:"invalid_form",message:"Send either templateId, or templateKey with subject and html, text or react."});return void 0===a.templateKey?{content:function(a,b){let{templateId:c,templateData:d}=a;if("string"!=typeof c||!ei.test(c))throw ez("invalid_template_id","templateId must be the template's UUID.","templateId");if(void 0!==d&&("object"!=typeof d||null===d||Array.isArray(d)))throw ez("invalid_template_data","templateData must be an object.","templateData");return ex(a,em,en),{template_id:c.toLowerCase(),message_data:d??{},...void 0!==b&&{distinct_id:b}}}(a,b),files:[]}:function(a,b){let{templateKey:c,subject:d,html:e,text:f,react:g}=a;if("string"!=typeof c||!ek.test(c))throw ez("invalid_template_key","templateKey can only have letters, digits, hyphens (-) and underscores (_), at most 400.","templateKey");if(ex(a,en,em),"string"!=typeof d)throw ez("invalid_form","A send with templateKey needs a subject.","subject");if(void 0!==e&&"string"!=typeof e)throw ez("invalid_form","html must be a string.","html");if(void 0!==f&&"string"!=typeof f)throw ez("invalid_form","text must be a string.","text");if(void 0!==g){var h=g,i=e;if(!et(h))throw ez("invalid_form","react must be a React element, such as <WelcomeEmail />.","react");if(void 0!==i)throw new d6({code:"invalid_form",message:"A send with react renders its own html, so it takes no html. No email was sent.",field:"html",fix:"Remove html to send the rendered react element, or remove react to send your html."})}else if(void 0===e&&void 0===f)throw ez("invalid_form","A send with templateKey needs html, text or react.","html");let j=void 0===a.attachments?[]:function(a,{html:b,text:c,subject:d}){if(!Array.isArray(a))throw ee("attachments must be a list of files.","attachments");if(a.length>10)throw new d6({code:"too_many_attachments",message:"An email carries at most 10 files, so no email was sent.",field:"attachments",fix:"Attach at most 10 files, and link to any others from the email body."});let e=Array.from(a,eb);return ec(e.map(({size:a})=>a),[b??"",c||b||""],d),e.map(({content:a,size:b,...c})=>({...c,bytes:"string"==typeof a?function(a){if("u">typeof Buffer)return Buffer.from(a,"base64");let b=atob(a),c=new Uint8Array(b.length);for(let a=0;a<b.length;a++)c[a]=b.charCodeAt(a);return c}(a):new Uint8Array(a)}))}(a.attachments,{html:e,text:f,subject:d});return{content:{template_key:c,subject:d,...void 0!==e&&{html:e},...void 0!==f&&{text:f},...function(a){let{from:b,replyTo:c,cc:d,bcc:e,captureEngagement:f,sensitive:g,tracking:h}=a;return{...void 0!==b&&{from:b},...void 0!==c&&eq("reply_to",er(c)),...void 0!==d&&eq("cc",er(d)),...void 0!==e&&eq("bcc",er(e)),...void 0!==f&&{capture_engagement:f},...void 0!==g&&{sensitive:g},...void 0!==h&&{tracking:h}}}(a),...void 0!==b&&{distinct_id:b}},files:j}}(a,b)}(c,e);if(void 0!==f&&("string"!=typeof f||!ej.test(f)))throw ez("invalid_idempotency_key","idempotencyKey must be 1 to 255 visible ASCII characters without spaces.","idempotencyKey");if(void 0!==g&&!ep(g))throw ez("invalid_max_retries","maxRetries must be a nonnegative integer.","maxRetries");return{content:JSON.parse(n({...h,to:d})),files:i,react:et(c.react)?c.react:void 0,idempotencyKey:f??globalThis.crypto.randomUUID(),maxRetries:ep(g)?g:b}}(a,this.config.maxRetries),{appHost:h,secretKey:i}=this.connect("no email was sent","Sending email needs secretKey, a project secret API key with the transactional_email:write scope."),j=void 0===g.react?g.content:await eu(g.content,g.react,this.config.requestTimeoutMs);void 0!==g.react&&(c=g.files,e="string"==typeof j.html?j.html:"",f="string"==typeof j.text?j.text:"",ec(c.map(({bytes:a})=>a.byteLength),[e,f||e],"string"==typeof j.subject?j.subject:""));let k=await this.uploadAttachments(g,h,i),l=n({...j,...eq("attachments",k)}),m=this.headers(i,{"Content-Type":"application/json","Idempotency-Key":g.idempotencyKey}),o=await this.withRetries(g.maxRetries,async()=>(function({status:a,text:b,retryAfterMs:c}){let d=eD(eA(b));if(a>=200&&a<300){let b=eC(d.message_id);if(!b)throw new d6({code:"api_error",message:"PostHog answered without a message ID.",statusCode:a});let c=[];if(Array.isArray(d.warnings))for(let a of d.warnings)null!==a&&"object"==typeof a&&c.push({code:eC(a.code)??"warning",message:eC(a.detail)??eC(a.message)??"",fix:eC(a.fix)});return{id:b,replayed:!0===d.replayed,warnings:c}}throw eE(d,a,c)})(await this.request(h+"/api/projects/@current/messaging/send/email/","POST",m,l)));for(let a of o.warnings)this.hooks.logger.warn(`PostHog email warning ${a.code}: ${a.message}`);return{data:o,error:null}}catch(a){return{data:null,error:eF(a,"Sending the email failed unexpectedly.")}}}async getUntracked(a){try{if("string"!=typeof a||!ei.test(a))throw ez("invalid_message_id","id must be the message ID that send() returned.","id");let{appHost:b,secretKey:c}=this.connect("no email status was read","Reading an email status needs secretKey, a project secret API key with the transactional_email:read or transactional_email:write scope."),d=b+"/api/projects/@current/messaging/emails/{messageId}/".replace("{messageId}",a.toLowerCase()),e=this.headers(c,{});return{data:await this.withRetries(this.config.maxRetries,async()=>(function({status:a,text:b,retryAfterMs:c}){let d=eD(eA(b));if(a<200||a>=300)throw eE(d,a,c);let e=eC(d.id),f=eC(d.status),g=eC(d.created_at),h=eC(d.status_at);if(!e||!f||!g||!h)throw new d6({code:"api_error",message:"PostHog answered without an email status.",statusCode:a});return{id:e,status:f,createdAt:g,statusAt:h,reason:eC(d.reason)??null}})(await this.request(d,"GET",e))),error:null}}catch(a){return{data:null,error:eF(a,"Reading the email status failed unexpectedly.")}}}async uploadAttachments({files:a,maxRetries:b},c,d){if(0===a.length)return[];let e=await d9(a),f=new Map;for(let a of e)f.has(a.sha256)||f.set(a.sha256,a);let g=[...f.values()],h=n({files:g.map(({sha256:a,bytes:b})=>({sha256:a,size:b.byteLength}))}),i=this.headers(d,{"Content-Type":"application/json"}),j=await this.withRetries(b,async()=>(function({status:a,text:b,retryAfterMs:c},d){var e,f,g;let h=eD(eA(b));if(404===a)throw eE({code:"not_found",...h,attr:eC(h.attr)??"attachments"},a,c);if(a<200||a>=300){let b;throw eE({...h,attr:(e=eC(h.attr),f=d,(b=void 0===e?null:/^files(?:__(\d+))?(?:__|$)/.exec(e))?void 0===b[1]?"attachments":f[Number(b[1])]?.field??"attachments":e)},a,c)}let i=Array.isArray(h.files)?h.files.map(eD):[],j=[];for(let{sha256:b,bytes:c,field:e}of d){let d=i.find(a=>a.sha256===b);if(d?.status==="present")continue;let f=eC(d?.url);if(d?.status!=="upload"||!f||!(null!==(g=d.headers)&&"object"==typeof g&&!Array.isArray(g)&&Object.values(g).every(a=>"string"==typeof a)))throw new d6({code:"api_error",message:"PostHog answered without telling where to upload every file.",statusCode:a});j.push({url:f,headers:d.headers,bytes:c,field:e})}return j})(await this.request(c+"/api/projects/@current/messaging/attachments/uploads/","POST",i,h),g)),k=c.toLowerCase().startsWith("http://")?void 0:j.find(({url:a})=>!a.toLowerCase().startsWith("https://"));if(k)throw new d6({code:"api_error",message:`PostHog named an upload URL for ${k.field} that isn't https, so the file would travel unencrypted. No email was sent.`,field:k.field,fix:"Make your PostHog's file storage URL use https. For local development over plain HTTP, set appHost to your http app host."});for(let a of j)await this.withRetries(b,()=>this.uploadFile(a));return e.map(ea)}async uploadFile({url:a,headers:b,bytes:c,field:d}){let e;try{e=await this.request(a,"PUT",b,c,"manual")}catch(a){if(a instanceof Error&&"AbortError"===a.name)throw new d6({code:"network_error",message:`The upload of ${d} timed out after ${this.config.requestTimeoutMs}ms, so no email was sent.`,fix:"Raise emailRequestTimeoutMs on the client, or send smaller files.",field:d,cause:a});throw new d6({code:"network_error",message:`The upload of ${d} didn't reach PostHog's file storage, so no email was sent.`,field:d,cause:a})}if(e.status>=300&&e.status<400)throw new d6({code:"attachment_upload_failed",message:`PostHog's file storage redirected the upload of ${d} elsewhere. The SDK uploads only to the URL PostHog signed, so no email was sent.`,statusCode:e.status,fix:"Make your PostHog's file storage URL point straight at the storage, over https.",field:d});if(e.status<200||e.status>=300)throw new d6({code:"attachment_upload_failed",message:`PostHog's file storage refused the upload of ${d}, so no email was sent. ${function({status:a,text:b}){let c=/<Code>([^<]{1,100})<\/Code>/.exec(b)?.[1],d=/<Message>([^<]{1,300})<\/Message>/.exec(b)?.[1],e=`It answered HTTP ${a}${c?` ${c}`:""}${d?`: ${d}`:""}`;return e.endsWith(".")?e:`${e}.`}(e)}`,statusCode:e.status,fix:"Send the email again. Each send asks for new upload URLs.",field:d,retryAfterMs:e.retryAfterMs})}async setPreferencesUntracked(a){try{let b=function(a){let{to:b,allMarketing:c,topics:d}=a??{};if("string"!=typeof b||!b.trim())throw ez("invalid_recipient","to must be one email address as a nonempty string.","to");if(void 0!==c&&"boolean"!=typeof c)throw ez("invalid_preferences","allMarketing must be true or false.","allMarketing");if(void 0!==d&&("object"!=typeof d||null===d||Array.isArray(d)||!Object.values(d).every(a=>"boolean"==typeof a)))throw ez("invalid_preferences","topics must map each topic key to true or false.","topics");let e=void 0!==d&&Object.keys(d).length>0;if(void 0===c&&!e)throw ez("invalid_preferences","Set allMarketing, topics, or both.","topics");return n({identifier:b,...void 0===c?{}:{all_marketing:c},...e?{topics:d}:{}})}(a),{appHost:c,secretKey:d}=this.connect("no preferences changed","Setting email preferences needs secretKey, a project secret API key with the messaging_preference:write scope."),e=this.headers(d,{"Content-Type":"application/json"});return{data:await this.withRetries(this.config.maxRetries,async()=>(function({status:a,text:b,retryAfterMs:c}){let d=eD(eA(b));if(a<200||a>=300)throw eE(d,a,c);let e=eC(d.identifier),f=d.all_marketing,g=d.topics;if(!e||null!==f&&"boolean"!=typeof f||null===g||"object"!=typeof g||Array.isArray(g)||!Object.values(g).every(a=>"boolean"==typeof a))throw new d6({code:"api_error",message:"PostHog answered without the preferences.",statusCode:a});return{to:e,allMarketing:f,topics:g}})(await this.request(c+"/api/projects/@current/messaging/preferences/","POST",e,b))),error:null}}catch(a){return{data:null,error:eF(a,"Setting the email preferences failed unexpectedly.")}}}connect(a,b){var c,d;let e;if(this.hooks.isDisabled())throw new d6({code:"client_disabled",message:`The PostHog client is disabled, so ${a}.`});if(this.hooks.isClosed())throw new d6({code:"client_closed",message:`The PostHog client is shut down, so ${a}.`});let f=(c=this.config.host,(e="string"==typeof(d=this.config.appHost)?aI(d.trim()):"")?eh[e]??e:eh[aI(c)]);if(!f)throw new d6({code:"missing_app_host",message:"The client's host is not PostHog Cloud, so the client can't tell where to send email. Set appHost to your PostHog app host on the client."});let g=this.config.secretKey?.trim();if(!g)throw new d6({code:"missing_secret_key",message:b});return{appHost:f,secretKey:g}}headers(a,b){let c={Authorization:`Bearer ${a}`,Accept:"application/json",...b};return this.hooks.userAgent&&(c["User-Agent"]=this.hooks.userAgent),this.config.migratedFrom&&(c["X-PostHog-Migrated-From"]=this.config.migratedFrom),c}async withRetries(a,b){for(let c=0;;c++){let d;try{return await b()}catch(a){d=a instanceof d6?a:new d6({code:"network_error",message:"The request to PostHog failed.",cause:a})}let e=function(a,b,c){if(!(b>=c)&&(void 0===a.statusCode?"network_error"===a.code:"attachment_upload_failed"===a.code?429===a.statusCode||a.statusCode>=500:409===a.statusCode?"idempotency_key_in_flight"===a.code:429===a.statusCode?"quota_limited"!==a.code&&"upload_quota_exceeded"!==a.code:503===a.statusCode)&&(void 0===a.retryAfterMs||!(a.retryAfterMs>3e4)))return Math.max(Math.min(3e4,1e3*2**b*(.8+.4*Math.random())),a.retryAfterMs??0)}(d,c,a);if(void 0===e)throw d;await new Promise(a=>setTimeout(a,e))}}async request(a,b,c,d,e){let f,g,h=new AbortController,i=this.config.requestTimeoutMs,j=new Promise((a,b)=>{f=setTimeout(()=>{let a=Error(`Email request timed out after ${i}ms`);a.name="AbortError",b(a),h.abort(a)},i)}),k=Promise.resolve().then(()=>this.hooks.fetch(a,{method:b,headers:c,...void 0===d?{}:{body:d},...e?{redirect:e}:{},signal:h.signal}));k.then(a=>{h.signal.aborted&&Promise.resolve(a.body?.cancel()).catch(()=>{})}).catch(()=>{});try{let a;g=await Promise.race([k,j]);try{a=await Promise.race([g.text(),j])}catch(a){if(g.status>=200&&g.status<300)throw a;return{status:g.status,text:"",retryAfterMs:eB(g)}}return{status:g.status,text:a,retryAfterMs:eB(g)}}finally{clearTimeout(f),h.signal.aborted&&g&&Promise.resolve(g.body?.cancel()).catch(()=>{})}}}function ep(a){return"number"==typeof a&&Number.isInteger(a)&&a>=0}function eq(a,b){return Array.isArray(b)&&0===b.length?{}:{[a]:b}}function er(a){return"string"==typeof a?[a]:a}let es=[Symbol.for("react.element"),Symbol.for("react.transitional.element")];function et(a){return"object"==typeof a&&null!==a&&"$$typeof"in a&&es.includes(a.$$typeof)&&"type"in a&&"props"in a}async function eu(a,b,c){let{render:d,toPlainText:e}=await ew();try{let f=await ev(d(b),c,"Rendering the react element");return{...a,html:f,...void 0===a.text&&{text:e(f)}}}catch(a){throw new d6({code:"react_render_failed",message:"Rendering the react element failed, so no email was sent.",cause:a})}}async function ev(a,b,c){let d,e=new Promise((a,e)=>{d=setTimeout(()=>e(Error(`${c} took longer than ${b}ms.`)),b)});try{return await Promise.race([a,e])}finally{clearTimeout(d)}}async function ew(){try{return await Promise.resolve().then(()=>{let a=Error("Cannot find module '@react-email/render'");throw a.code="MODULE_NOT_FOUND",a})}catch(a){throw new d6({code:"missing_react_renderer",message:"react needs the @react-email/render package, which isn't installed or failed to load, so no email was sent.",fix:"Install @react-email/render with react and react-dom next to posthog-node, or render the email yourself and send html.",cause:a})}}function ex(a,b,c){let d=Object.entries(a).find(([a,c])=>void 0!==c&&!b.fields.has(a))?.[0];if(void 0===d)return;let e=`A send with ${b.name} doesn't take ${d}, so no email was sent.`;if(!c.fields.has(d))throw new d6({code:"invalid_form",message:e,field:d,fix:`Remove ${d} and send again.`});throw new d6({code:"invalid_form",message:e,field:d,why:b.why,fix:`Remove ${d}, or ${c.howToSend}.`})}function ey(...a){return new Set(a.flatMap(a=>Object.keys(a)))}function ez(a,b,c){return new d6({code:a,message:b,field:c})}function eA(a){try{return JSON.parse(a)}catch{return null}}function eB(a){try{return a$(a.headers?.get("retry-after"),Date.now(),Number.MAX_SAFE_INTEGER)}catch{return}}function eC(a){return"string"==typeof a&&a?a:void 0}function eD(a){return null===a||"object"!=typeof a||Array.isArray(a)?{}:a}function eE(a,b,c){return new d6({code:eC(a.code)??"api_error",message:eC(a.detail)??`PostHog answered HTTP ${b}.`,statusCode:b,why:eC(a.why),fix:eC(a.fix),docsUrl:eC(a.docs_url),field:eC(a.attr),retryAfterMs:c})}function eF(a,b){return a instanceof d6?a:new d6({code:"unexpected_error",message:b,cause:a})}let eG=new Set;function eH(a,b){eG.has(a)||(eG.add(a),console.warn(`[PostHog] ${b}`))}class eI extends ba{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(a){this._distinctIdHasSentFlagCalls=new Map(Object.entries(a??{}))}constructor(a,b={}){var c,d;let e,f="string"==typeof a?a.trim():"",g={...b,maxQueueSize:b.maxQueueSize??1e4,flushInterval:b.flushInterval??5e3,host:("string"==typeof(c=b.host)?c.trim():"")||"https://us.i.posthog.com",personalApiKey:("string"==typeof(d=b.secretKey??b.personalApiKey)?d.trim():"")||void 0};if(super(f,g),this._memoryStorage=new dP,this._isShutdown=!1,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this._loggedFlagsResponseWithoutTypedValues=!1,this._experimentExposuresReported=new Map,this.options=g,this.captureMode="v0"===(e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0)||"v1"===e?e:"v0",this.enableFullAiCapture=!0===g.enableFullAiCapture,this.privacyMode=!0===g.privacyMode,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof g.featureFlagsPollingInterval?Math.max(g.featureFlagsPollingInterval,100):null===g.featureFlagsPollingInterval?null:3e4,"number"==typeof g.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(g.waitUntilDebounceMs,0)),"number"==typeof g.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(g.waitUntilMaxWaitMs,0)),!this.disabled&&(g.personalApiKey||g.flagDefinitionCacheProvider)){if(g.personalApiKey?.includes("phc_"))throw Error('A project API key ("phc_...") was provided as secretKey or personalApiKey. Pass the project API key as the first constructor argument. For local evaluation, set secretKey (or the deprecated personalApiKey alias) to a server-only Project Secret API Key ("phs_...") or Personal API Key ("phx_...") with feature flag read access.');!1!==g.enableLocalEvaluation&&(this.featureFlagsPoller=new c5({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:g.personalApiKey,projectApiKey:f,timeout:g.requestTimeout??1e4,host:this.host,fetch:g.fetch,onError:a=>{this._events.emit("error",a)},onLoad:a=>{this._events.emit("localEvaluationFlagsLoaded",a)},onMinimalFlagCalledEvents:a=>{this._minimalFlagCalledEvents=a},customHeaders:this.getCustomHeaders(),cacheProvider:g.flagDefinitionCacheProvider,strictLocalEvaluation:g.strictLocalEvaluation,evaluationContexts:g.evaluationContexts??g.evaluationEnvironments}))}this.errorTracking=new dJ(this,g,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=g.maxCacheSize||5e4}enqueue(a,b,c,d){super.enqueue(a,b,c,d),this.scheduleDebouncedFlush()}_flushEventsAndSpans(a=!1){let b=this.flushWithPendingPromises(),c=[];return(this._traces&&!(a&&this._traces.throttled)&&c.push(this._traces.flush().catch(()=>{})),this._logs&&!(a&&this._logs.throttled)&&c.push(this._logs.flushInBackground()),0===c.length)?b:aO([b,...c]).then(([a])=>{if("rejected"===a.status)throw a.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this.errorTracking.capturePendingExceptions(),this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(a){let b=this._flushEventsAndSpans(a),c=this.options.waitUntil;if(c&&!this._waitUntilCycle)try{c(b.catch(()=>{}))}catch{}return b}_flushMetricsWithinInvocation(){let a=this.options.waitUntil;if(a&&this._metrics)try{a(this._metrics.flushCoalesced().catch(()=>{}))}catch{}}scheduleDebouncedFlush(){let a=this.options.waitUntil;if(!a||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let b,c=new Promise(a=>{b=a});try{a(c)}catch{return}this._waitUntilCycle={resolve:b,startedAt:Date.now(),timer:void 0}}let b=Date.now()-this._waitUntilCycle.startedAt,c=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),b>=c)return void this.resolveWaitUntilFlush();let d=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=aM(()=>{this.resolveWaitUntilFlush()},d)}_consumeWaitUntilCycle(){let a=this._waitUntilCycle;return a&&(clearTimeout(a.timer),this._waitUntilCycle=void 0),a?.resolve}async resolveWaitUntilFlush(){let a=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{a?.()}}getPersistedProperty(a){return this._memoryStorage.getProperty(a)}setPersistedProperty(a,b){return this._memoryStorage.setProperty(a,b)}fetch(a,b){return this.options.fetch?this.options.fetch(a,b):fetch(a,b)}getQueueRouteKey(a){var b;return"v1"===this.captureMode&&"string"==typeof(b=a).event&&b.event.startsWith("$ai_")?"ai":dV}persistedQueueKeyForRoute(a){return a===d2?k.AiCaptureQueue:"ai"===a?k.AiQueue:k.Queue}getActiveQueueRoutes(){let a="v1"===this.captureMode?[dV,"ai"]:[dV];return this._aiCaptureRouteActive&&a.push(d2),a}getBatchEndpointPath(a){return a===d2?d3:super.getBatchEndpointPath(a)}async sendBatch(a,b,c=dV){if(c===d2)return this.sendAiCaptureBatch(a,b);if("v1"!==this.captureMode||"ai"===c)return super.sendBatch(a,b,c);let d=a.filter(a=>void 0!==a);await this.getV1Sender().sendV1Batch(d)}async sendAiCaptureBatch(a,b){let{batches:c,dropped:d}=function(a,b=8388608,c=5242880){let d=[],e=[],f=[],g=0;for(let h of a){if(void 0===h)continue;let a=d5(h);if(a>b){e.push({event:"string"==typeof h.event?h.event:"unknown",bytes:a});continue}f.length>0&&g+a>c&&(d.push(f),f=[],g=0),f.push(h),g+=a}return f.length>0&&d.push(f),{batches:d,dropped:e}}(a);for(let{event:a,bytes:b}of d){let c=`Event ${a} (${b} bytes) exceeds the 8MiB limit for ${d3}, dropping.`;this._logger.error(c),this._events.emit("error",Error(c))}for(let a of c)await this.sendAiSubBatch(a,b)}async sendAiSubBatch(a,b){try{await super.sendBatch(a,b,d2)}catch(d){if(!a6(d))throw d;if(1===a.length){let[b]=a,c="string"==typeof b.event?b.event:"unknown",d=`Event ${c} (${d5(b)} bytes) was rejected with 413 by ${d3} on its own, dropping.`;this._logger.error(d),this._events.emit("error",Error(d));return}let c=Math.ceil(a.length/2);await this.sendAiSubBatch(a.slice(0,c),b),await this.sendAiSubBatch(a.slice(c),b)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new d1({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(a,b)=>this.fetch(a,b),onError:a=>this._events.emit("error",a),compress:a=>this.compressPayload(a)})),this._v1Sender}getLibraryVersion(){return"5.73.0"}get metrics(){return this._metrics||(this._metrics=new bI(this,cd(this.options.metrics),this._logger)),this._metrics}get _logsPipeline(){if(!this._logs){let a=function(a,b={}){let{rateCap:c,...d}=a??{},e=a?.rateCap?.windowMs??1e4,f=a?.rateCap&&"maxLogs"in a.rateCap?a.rateCap.maxLogs:1e4,g=void 0!==f&&f>0&&e>0?f:void 0,h=a?.maxBatchRecordsPerPost;return{...d,serviceName:a?.serviceName??b.serviceName,maxBufferSize:a?.maxBufferSize??100,flushIntervalMs:a?.flushIntervalMs??3e3,maxBatchRecordsPerPost:Number.isInteger(h)&&h>0?h:100,rateCapWindowMs:e,maxLogsPerInterval:g,maxQueueSize:g??1e4,backgroundFlushBudgetMs:25e3,terminationFlushBudgetMs:2e3,resourceAttributes:{...b.hostResourceAttributes,...a?.resourceAttributes}}}(this.options.logs,{serviceName:this._resolveServiceName()??void 0,hostResourceAttributes:this.hostResourceAttributes()});this._logs=new bs(this,a,this._logger,()=>this._logContext(),a=>a(),void 0,void 0,()=>this.disabled||this.optedOut)}return this._logs}_logContext(){let a=this.context?.get();return{distinctId:a?.distinctId,sessionId:a?.sessionId}}captureLog(a){let b=a;if(!a.trace_id&&!a.span_id){let c=this.getActiveSpan(),d=c?.traceId,e=c?.spanId;if(d&&e){let f=parseInt(c?.traceparent()?.split("-")[3]??"",16);b={...a,trace_id:d,span_id:e,...void 0===a.trace_flags&&!Number.isNaN(f)&&{trace_flags:f}}}}this._logsPipeline.captureLog(b),this.scheduleDebouncedFlush()}get logger(){if(!this._captureLogger){let a=a=>(b,c)=>this.captureLog({body:b,level:a,attributes:c});this._captureLogger={trace:a("trace"),debug:a("debug"),info:a("info"),warn:a("warn"),error:a("error"),fatal:a("fatal")}}return this._captureLogger}get emails(){var a,b;return this._emails||(this._emails=new eo({secretKey:this.options.personalApiKey,host:this.host,appHost:this.options.appHost,requestTimeoutMs:"number"==typeof(a=this.options.emailRequestTimeoutMs)&&Number.isFinite(a)&&a>0?a:15e3,maxRetries:"number"==typeof(b=this.options.emailRequestMaxRetries)&&Number.isFinite(b)&&b>=0?Math.floor(b):2,migratedFrom:this.options.migratedFrom},{fetch:(a,b)=>this.fetch(a,b),isDisabled:()=>this.disabled,isClosed:()=>this._isShutdown,logger:this._logger,userAgent:this.getCustomUserAgent()||void 0})),this._emails}initializeSpanContextManager(){return new b9}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces)return this._traces||(this._traces=new b8(this,cg(this.options.traces,this.hostResourceAttributes(),this._logger),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}_tracingContext(){let a=this.context?.get();return{distinctId:a?.distinctId,sessionId:a?.sessionId}}startSpan(a,b){return this._tracesPipeline?.startSpan(a,b)??bV(b,this._spanContextManager.active())}withSpan(a,b,c){let d="function"==typeof b?void 0:b,e="function"==typeof b?b:c,f=this._tracesPipeline;return f?d?f.withSpan(a,d,e):f.withSpan(a,e):b$(this._spanContextManager,bV(d,this._spanContextManager.active()),e)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getFlagsResponseFormat(){let a=super.getFlagsResponseFormat();return{version:4,read:b=>{let{body:c,withoutTypedValues:d}=function(a){if(!C(a))return{body:a,withoutTypedValues:!1};let b=a.flags;if(!C(b)){let b=a.featureFlags;return{body:a,withoutTypedValues:C(b)&&Object.keys(b).length>0}}let c=!1,d=Object.fromEntries(Object.entries(b).map(([a,b])=>{C(b)&&!q.call(b,"value")&&(c=!0);let{detail:d,record:e}=function(a,b){try{if(C(b)&&!q.call(b,"value")){var c;let a,d,e,f,g;return c=b,cn(c),a=cq(c.enabled,"enabled",z),d=cq(c.variant,"variant",u),e=!0===cq(c.failed,"failed",z),f=co(c.reason),g=cp(cq(c.metadata,"metadata",C)),{detail:c,record:{value:d??a??null,failed:e,reason:f,metadata:{...g,configVersion:1}}}}return function(a,b){var c;if(!C(b))throw new ck("record");cn(b);let d=function(a){if(w(a)||z(a)||u(a)||C(a)||y(a)&&Number.isFinite(a))return a;throw new ck("value")}(b.value),e=!0===cq(b.failed,"failed",z),f=co(b.reason),g=cq(b.metadata,"metadata",C),h={...cp(g),configVersion:cr(g?.config_version,"metadata.config_version"),ruleType:cq(g?.rule_type,"metadata.rule_type",u),ruleId:cq(g?.rule_id,"metadata.rule_id",u),variantKey:cq(g?.variant_key,"metadata.variant_key",u),forcedVariant:cq(g?.forced_variant,"metadata.forced_variant",z)};cr(g?.experiment_id,"metadata.experiment_id");let i=e?null:d,{enabled:j,variant:k,payload:l}=w(c=i)||z(c)?{enabled:!0===c,variant:void 0,payload:void 0}:u(c)?{enabled:!0,variant:c,payload:void 0}:{enabled:!0,variant:void 0,payload:JSON.stringify(c)},m={key:a,enabled:j,variant:k,reason:f&&{code:f.code,condition_index:f.conditionIndex,description:f.description},metadata:g||void 0!==l?{id:h.id,version:h.version,description:h.description,payload:e?null:l??g?.payload,has_experiment:h.hasExperiment}:void 0};return e&&(m.failed=!0),{detail:m,record:{value:i,failed:e,reason:f,metadata:h}}}(a,b)}catch(b){if(b instanceof ck)return cm(a,b.field);if(b instanceof RangeError)return cm(a,"value");throw b}}(a,b);return cj.set(d,e),[a,d]}));return{body:{...a,flags:d},withoutTypedValues:c}}(b);return d&&!this._loggedFlagsResponseWithoutTypedValues&&(this._loggedFlagsResponseWithoutTypedValues=!0,this._logger.info("[FEATURE FLAGS] The /flags response has no typed flag values, so the server may not support /flags?v=4. Its flags are read as config version 1.")),a.read(c)}}}getCommonEventProperties(){let a=super.getCommonEventProperties();return(this.options.isServer??!0)&&(a.$is_server=!0),a}enable(){return super.optIn()}disable(){return super.optOut()}debug(a=!0){super.debug(a),this.featureFlagsPoller?.debug(a)}_warnIfInvalidCapture(a,b,c){"string"==typeof a&&this._logger.warn(b),"$exception"!==a.event||a._originatedFromCaptureException||this._logger.warn(c)}_sendPreparedEvent(a,b,c,d,e){return this.addPendingPromise(this._prepareEventMessage(b,d).then(({distinctId:b,event:f,properties:g,options:h})=>{(this.disabled||this.optedOut)&&d?.onCaptureFailed?.();let i={timestamp:h.timestamp,disableGeoip:h.disableGeoip,uuid:h.uuid},j={distinctId:b,event:f,properties:{...g,...this.getCommonEventProperties()}};return c?this.sendImmediate(a,j,i,e):this.enqueue(a,j,i,e)}).catch(a=>{a&&(console.error(a),d?.onCaptureFailed?.())}))}_capturePreparedEvent(a,b){return this._sendPreparedEvent("capture",a,b)}capture(a){this._warnIfInvalidCapture(a,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(a,!1)}async captureImmediate(a){return this._warnIfInvalidCapture(a,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(a,!0)}captureAi(a){if(this.disabled)return;let b=aG(a.uuid,aW);return this._sendPreparedAiEvent({...a,uuid:b},!1),b}async captureAiImmediate(a){if(this.disabled)return;let b=aG(a.uuid,aW);return await this._sendPreparedAiEvent({...a,uuid:b},!0),b}_sendPreparedAiEvent(a,b){return"string"!=typeof a?.event||a.event.startsWith("$ai_")||this._logger.debug(`captureAi called with non-AI event ${a.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",a,b,void 0,d2)}identify({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;this._sendPreparedEvent("identify",{distinctId:a,event:"$identify",properties:{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},disableGeoip:c},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;await this._sendPreparedEvent("identify",{distinctId:a,event:"$identify",properties:{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},disableGeoip:c},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:a,properties:b={},propertiesOnce:c={}}){if(0===Object.keys(b).length&&0===Object.keys(c).length)return;let d={};Object.keys(b).length>0&&(d.$set=b),Object.keys(c).length>0&&(d.$set_once=c),this.capture({distinctId:a,event:"$set",properties:d})}unsetPersonProperties({distinctId:a,properties:b}){let c=(Array.isArray(b)?b:[b]).filter(a=>"string"==typeof a&&a.trim().length>0);0!==c.length&&this.capture({distinctId:a,event:"$set",properties:{$unset:c}})}alias(a){this._sendPreparedEvent("alias",{distinctId:a.distinctId,event:"$create_alias",properties:{distinct_id:a.distinctId,alias:a.alias},disableGeoip:a.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(a){await this._sendPreparedEvent("alias",{distinctId:a.distinctId,event:"$create_alias",properties:{distinct_id:a.distinctId,alias:a.alias},disableGeoip:a.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(a){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(a)}getFeatureFlagKeysByEvaluationRuntime(a){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(a)??[]}async waitForLocalEvaluationReady(a=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(b=>{let c=setTimeout(()=>{d(),b(!1)},a),d=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(c),d(),b(a>0)})})}_resolveDistinctId(a,b){return"string"==typeof a?{distinctId:a,options:b}:{distinctId:this.context?.get()?.distinctId,options:a}}async getFeatureFlagDetailsStateless(a,b={},c={},d={},e,f){let g=await super.getFeatureFlagDetailsStateless(a,b,c,d,e,f);if(void 0!==g&&!C(g.flags)){let a="/flags response has a non-object `flags` field, treating it as a failed request";this._logger.warn(`[FEATURE FLAGS] ${a}`),this._events.emit("error",Error(a));return}return g}async _getFeatureFlagResult(a,b,c={},d){let e,f,g,h,i,j,k,l,m;if(this.disabled)return void this._logger.warn("The client is disabled");let n=c.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&a in this._flagOverrides){let b=this._flagOverrides[a];if(void 0===b)return;let c=this._payloadOverrides?.[a];return{key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:c}}let{groups:o,disableGeoip:p}=c,{onlyEvaluateLocally:q,personProperties:r,groupProperties:s}=c,t=this.addLocalPersonAndGroupProperties(b,o,r,s);r=t.allPersonProperties,s=t.allGroupProperties;let u=this.createFeatureFlagEvaluationContext(b,o,this.personPropertiesForLocalEvaluation(b,r),s);void 0==q&&(q=this.options.strictLocalEvaluation??!1);let v=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let b=this.featureFlagsPoller?.featureFlagsByKey[a];if(b)try{let c=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(b,u,{matchValue:d});if(c){v=!0;let d=c.value;i=b.id,k="Evaluated locally",l=b.has_experiment,e={key:a,enabled:!1!==d,variant:"string"==typeof d?d:void 0,payload:c.payload??void 0,reason:k,reasonCode:!1===b.active?"flag_disabled":void 0}}}catch(b){if(b instanceof c1||b instanceof cB)this._logger?.info(`${b.name} when computing flag locally: ${a}: ${b.message}`);else throw b}}if(!v&&!q){let b=await this.getFeatureFlagDetailsStateless(u.distinctId,u.groups,r,s,p,[a]);if(void 0===b)h=ch.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===b.minimalFlagCalledEvents,f=b.requestId,g=b.evaluatedAt;let c=[];b.errorsWhileComputingFlags&&c.push(ch.ERRORS_WHILE_COMPUTING),b.quotaLimited?.includes("feature_flags")&&c.push(ch.QUOTA_LIMITED);let d=b.flags[a];if(void 0===d)c.push(ch.FLAG_MISSING);else{let b;if(i=d.metadata?.id,j=d.metadata?.version,k=d.reason?.description??d.reason?.code,l=d.metadata?.has_experiment,d.metadata?.payload!==void 0)try{b=JSON.parse(d.metadata.payload)}catch{b=d.metadata.payload}e={key:a,enabled:d.enabled,variant:d.variant??void 0,payload:b,reason:k,reasonCode:d.reason?.code},m=cl(d)}void 0!==d&&cj.get(d)?.unreadableField!==void 0?(h=ch.UNKNOWN_ERROR,f=void 0,g=void 0):c.length>0&&(h=c.join(","))}}if(n){let c=void 0===e?void 0:!1!==e.enabled&&(e.variant??!0),d={$feature_flag:a,$feature_flag_response:c,$feature_flag_id:i,$feature_flag_version:j,$feature_flag_reason:k,locally_evaluated:v,[`$feature/${a}`]:c,$feature_flag_request_id:f,$feature_flag_evaluated_at:v?Date.now():g};if(void 0!==l&&(d.$feature_flag_has_experiment=l),v&&this.featureFlagsPoller){let a=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==a&&(d.$feature_flag_definitions_loaded_at=a)}h&&(d.$feature_flag_error=h),this._captureFlagCalledEventIfNeeded({distinctId:b,key:a,response:c,groups:o,disableGeoip:p,properties:d,record:m})}return void 0!==e&&void 0!==this._payloadOverrides&&a in this._payloadOverrides&&(e={...e,payload:this._payloadOverrides[a]}),e}async getFeatureFlag(a,b,c){eH("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let d=await this._getFeatureFlagResult(a,b,{...c,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(c?.sendFeatureFlagEvents)});if(void 0!==d)return!1!==d.enabled&&(d.variant??!0)}async getFeatureFlagPayload(a,b,c,d){if(eH("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request."),void 0!==this._payloadOverrides&&a in this._payloadOverrides)return this._payloadOverrides[a];let e=await this._getFeatureFlagResult(a,b,{...d,sendFeatureFlagEvents:!1},c);if(void 0!==e)return e.payload??null}async getFeatureFlagResult(a,b,c){let{distinctId:d,options:e}=this._resolveDistinctId(b,c);return d?this._getFeatureFlagResult(a,d,{...e,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(e?.sendFeatureFlagEvents)}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}async getRemoteConfigPayload(a){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let b=await this._requestRemoteConfigPayload(a);if(!b)return;let c=await b.json();if("string"==typeof c)try{return JSON.parse(c)}catch(a){}return c}async isFeatureEnabled(a,b,c){eH("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let d=await this._getFeatureFlagResult(a,b,{...c,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(c?.sendFeatureFlagEvents)});return void 0===d?void 0:!1!==d.enabled&&!!(d.variant??!0)}async getAllFlags(a,b){let{distinctId:c,options:d}=this._resolveDistinctId(a,b);return c?(await this.getAllFlagsAndPayloads(c,d)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(a,b){let{distinctId:c,options:d}=this._resolveDistinctId(a,b);if(!c)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads — pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:e,disableGeoip:f,flagKeys:g}=d||{},{onlyEvaluateLocally:h,personProperties:i,groupProperties:j}=d||{},k=this.addLocalPersonAndGroupProperties(c,e,i,j);i=k.allPersonProperties,j=k.allGroupProperties;let l=this.createFeatureFlagEvaluationContext(c,e,this.personPropertiesForLocalEvaluation(c,i),j);void 0==h&&(h=this.options.strictLocalEvaluation??!1);let m=await this.featureFlagsPoller?.getAllFlagsAndPayloads(l,g),n={},o={},p=!0;if(m&&(n=m.response,o=m.payloads,p=m.fallbackToFlags),p&&!h){let a=await super.getFeatureFlagsAndPayloadsStateless(l.distinctId,l.groups,i,j,f,g);n={...n,...a.flags||{}},o={...o,...a.payloads||{}}}return void 0!==this._flagOverrides&&(n={...n,...this._flagOverrides}),void 0!==this._payloadOverrides&&(o={...o,...this._payloadOverrides}),{featureFlags:n,featureFlagPayloads:o}}async evaluateFlags(a,b){let c,d,{distinctId:e,options:f}=this._resolveDistinctId(a,b);if(!e)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new ci({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new ci({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,flags:{}});let{groups:g,disableGeoip:h}=f||{},i=f?.flagKeys??void 0;if(i?.length===0)return new ci({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:{}});let{onlyEvaluateLocally:j,personProperties:k,groupProperties:l}=f||{},m=this.addLocalPersonAndGroupProperties(e,g,k,l);k=m.allPersonProperties,l=m.allGroupProperties;let n=this.createFeatureFlagEvaluationContext(e,g,this.personPropertiesForLocalEvaluation(e,k),l);void 0==j&&(j=this.options.strictLocalEvaluation??!1);let o=i?new Set(i):void 0,p={},q=!1,r=!1,s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(n,i),t=new Set;if(s)for(let[a,b]of Object.entries(s.response)){let c=this.featureFlagsPoller?.featureFlagsByKey[a];p[a]={key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:s.payloads[a],id:c?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:c?.has_experiment},t.add(a)}let u=void 0!==o&&Array.from(o).some(a=>this.featureFlagsPoller?.featureFlagsByKey[a]===void 0);if((!s||s.fallbackToFlags||u)&&!j){let a=await this.getFeatureFlagDetailsStateless(n.distinctId,n.groups,k,l,h,i);if(a)for(let[b,e]of(this._minimalFlagCalledEvents=!0===a.minimalFlagCalledEvents,c=a.requestId,d=a.evaluatedAt,q=!!a.errorsWhileComputingFlags,r=Array.isArray(a.quotaLimited)&&a.quotaLimited.includes("feature_flags"),Object.entries(a.flags))){let a;if(!t.has(b)){if(e.metadata?.payload!==void 0)try{a=JSON.parse(e.metadata.payload)}catch{a=e.metadata.payload}p[b]={key:b,enabled:e.enabled,variant:e.variant,payload:a,id:e.metadata?.id,version:e.metadata?.version,reason:e.reason?.description??e.reason?.code,locallyEvaluated:!1,hasExperiment:e.metadata?.has_experiment,parsed:cl(e)}}}}if(void 0!==this._flagOverrides)for(let[a,b]of Object.entries(this._flagOverrides)){if(void 0===b){delete p[a];continue}let c=p[a];p[a]={key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:c?.payload,id:c?.id,version:c?.version,reason:c?.reason,locallyEvaluated:c?.locallyEvaluated??!1,hasExperiment:c?.hasExperiment}}if(void 0!==this._payloadOverrides)for(let[a,b]of Object.entries(this._payloadOverrides)){let c=p[a];c&&(p[a]={...c,payload:b})}if(void 0!==o)for(let a of Object.keys(p))o.has(a)||delete p[a];let v={};for(let[a,b]of Object.entries(s?.unresolved??{}))Object.prototype.hasOwnProperty.call(p,a)||(v[a]=b);return new ci({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:p,unresolvedFlags:v,requestId:c,evaluatedAt:d,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:q,quotaLimited:r})}_shouldSendMinimalFlagCalledEvent(a,b){return"$feature_flag_called"===a&&this._minimalFlagCalledEvents&&!1===b.$feature_flag_has_experiment}_captureFlagCalledEventIfNeeded(a){let{distinctId:b,key:c,response:d,groups:e,disableGeoip:f,properties:g,record:h}=a,i=function(a){let{key:b,response:c,groups:d,record:e}=a,f=function(a){if(void 0===a||void 0!==a.unreadableField||2!==a.metadata.configVersion)return;let b=a.reason?.code||void 0,c={reasonCode:b,ruleId:void 0,ruleType:void 0,variantKey:void 0},d=void 0===b?void 0:cu.get(b);if(a.failed||void 0===d)return c;let{ruleId:e,ruleType:f,variantKey:g}=a.metadata;return void 0!==e&&cz.test(e)&&void 0!==f&&d.has(f)?b!==cs?{...c,ruleId:e,ruleType:f}:void 0===g?c:{reasonCode:b,ruleId:e,ruleType:f,variantKey:g}:c}(e);if(void 0===f)return;let{reasonCode:g,ruleId:h,ruleType:i,variantKey:j}=f,k=Object.entries(d??{}).sort(([a],[b])=>a<b?-1:+(a>b)),l={$feature_flag_config_version:2};void 0!==g&&(l.$feature_flag_reason_code=g),void 0!==h&&(l.$feature_flag_rule_id=h,l.$feature_flag_rule_type=i),void 0!==j&&(l.$feature_flag_variant_key=j);let{$feature_flag_reason:m,...n}=a.properties;Object.assign(n,l);let o={event:"$feature_flag_called",dedupeKey:JSON.stringify([b,c??null,k,2,g??null,h??null,i??null,j??null]),properties:n,capture:{removed:cw,pinned:l}};if(void 0===j)return{flagCalled:o,exposure:void 0};let p={$feature_flag:b,$feature_flag_response:c,$feature_flag_variant_key:j,$feature_flag_rule_id:h,locally_evaluated:!0===n.locally_evaluated},q={};for(let a of cy)void 0!==n[a]&&(q[a]=n[a]);return Object.assign(q,p),{flagCalled:o,exposure:{event:"$experiment_exposure",dedupeKey:JSON.stringify([b,k,2,h,j]),properties:q,capture:{removed:cx,pinned:p}}}}({key:c,response:d,groups:e,properties:g,record:h});if(void 0!==i){this._captureFlagEventOnce(this._distinctIdHasSentFlagCalls,b,i.flagCalled,a),void 0!==i.exposure&&this._captureFlagEventOnce(this._experimentExposuresReported,String(b),i.exposure,a);return}let j=e&&Object.keys(e).length>0?`_${JSON.stringify(Object.entries(e).sort(([a],[b])=>a<b?-1:+(a>b)))}`:"",k=`${c}_${d}${j}`;void 0!==this._reserveFlagEventKey(this._distinctIdHasSentFlagCalls,b,k)&&this.capture({distinctId:b,event:"$feature_flag_called",properties:g,groups:e,disableGeoip:f})}_reserveFlagEventKey(a,b,c){let d=a.get(b)??new Set;if(a.delete(b),a.set(b,d),!d.has(c)){for(d.add(c);a.size>Math.max(this.maxCacheSize,1);){let b=a.keys().next().value;if(void 0===b)break;a.delete(b)}return d}}_captureFlagEventOnce(a,b,c,d){let e=this._reserveFlagEventKey(a,b,c.dedupeKey);if(void 0===e)return;let f=!1,g=()=>{f||(f=!0,e.delete(c.dedupeKey))};try{if(this.disabled||this.optedOut)return void g();this._sendPreparedEvent("capture",{distinctId:d.distinctId,event:c.event,properties:c.properties,groups:d.groups,disableGeoip:d.disableGeoip},!1,{flagEvent:c.capture,onCaptureFailed:g})}catch(a){this._logger.error(`[FEATURE FLAGS] Failed to capture ${c.event}:`,a),g()}}_resolveSendFeatureFlagEvents(a){return a??this.options.sendFeatureFlagEvent??!0}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:a=>this._captureFlagCalledEventIfNeeded(a),resolveSendFeatureFlagEvents:a=>this._resolveSendFeatureFlagEvents(a),logWarning:a=>{!1!==this.options.featureFlagsLogWarnings&&console.warn(`[PostHog] ${a}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:a,groupKey:b,properties:c,distinctId:d,disableGeoip:e}){this._sendPreparedEvent("capture",{distinctId:d||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{}},disableGeoip:e},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:a,groupKey:b,properties:c,distinctId:d,disableGeoip:e}){await this._sendPreparedEvent("capture",{distinctId:d||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{}},disableGeoip:e},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(a){let b=a=>Object.fromEntries(a.map(a=>[a,!0]));if(!1===a){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(a)){this._flagOverrides=b(a);return}if(this._isFeatureFlagOverrideOptions(a)){"flags"in a&&(!1===a.flags?this._flagOverrides=void 0:Array.isArray(a.flags)?this._flagOverrides=b(a.flags):void 0!==a.flags&&(this._flagOverrides={...a.flags})),"payloads"in a&&(!1===a.payloads?this._payloadOverrides=void 0:void 0!==a.payloads&&(this._payloadOverrides={...a.payloads}));return}this._flagOverrides={...a}}_isFeatureFlagOverrideOptions(a){if("object"!=typeof a||null===a||Array.isArray(a))return!1;if("flags"in a){let b=a.flags;if(!1===b||Array.isArray(b)||"object"==typeof b&&null!==b)return!0}if("payloads"in a){let b=a.payloads;if(!1===b||"object"==typeof b&&null!==b)return!0}return!1}withContext(a,b,c){return this.context?this.context.run(a,()=>(dT(this),b()),c):b()}getContext(){return this.context?.get()}enterContext(a,b){this.context?.enter(a,b),dT(this)}async _shutdown(a){let b=Date.now()+(a??3e4);this._isShutdown=!0;let c=this._emails?.drain(),d=this._logs,e=d?aN(d.flush().catch(()=>{}),Math.max(0,b-Date.now())).then(()=>{d.reset(),d.clearQueue()}):void 0,f=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(a),this.errorTracking.shutdown(),this._metrics&&(await aN(this._metrics.flush().catch(()=>{}),Math.max(0,b-Date.now())),this._metrics.reset()),this._traces&&(await aN(this._traces.flush().catch(()=>{}),Math.max(0,b-Date.now())),this._traces.reset());let g=Math.max(0,b-Date.now()),h=c?aN(c,g):void 0;try{return await super._shutdown(g)}finally{await h,await e,this._distinctIdHasSentFlagCalls.clear(),this._experimentExposuresReported.clear(),f?.()}}async _requestRemoteConfigPayload(a){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let b=`${this.host}/api/projects/@current/feature_flags/${a}/remote_config?token=${encodeURIComponent(this.apiKey)}`,c={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},d=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let a=new AbortController;d=aM(()=>{a.abort()},this.options.requestTimeout),c.signal=a.signal}try{return await this.fetch(b,c)}catch(a){this._events.emit("error",a);return}finally{d&&clearTimeout(d)}}extractPropertiesFromEvent(a,b){if(!a)return{personProperties:{},groupProperties:{}};let c={},d={};for(let[e,f]of Object.entries(a))if(C(f)&&b&&e in b){let a={};for(let[b,c]of Object.entries(f))a[String(b)]=String(c);d[String(e)]=a}else c[String(e)]=String(f);return{personProperties:c,groupProperties:d}}async getFeatureFlagsForEvent(a,b,c,d){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let e=d?.personProperties||{},f=d?.groupProperties||{},g=d?.flagKeys;if(d?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let d={};for(let[a,c]of Object.entries(b||{}))d[a]=String(c);return await this.getAllFlags(a,{groups:d,personProperties:e,groupProperties:f,disableGeoip:c,onlyEvaluateLocally:!0,flagKeys:g})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let d={};for(let[a,c]of Object.entries(b||{}))d[a]=String(c);return await this.getAllFlags(a,{groups:d,personProperties:e,groupProperties:f,disableGeoip:c,onlyEvaluateLocally:!0,flagKeys:g})}return(await super.getFeatureFlagsStateless(a,b,e,f,c)).flags}addLocalPersonAndGroupProperties(a,b,c,d){let e={...c||{}},f={};if(b)for(let a of Object.keys(b))f[a]={$group_key:b[a],...d?.[a]||{}};return{allPersonProperties:e,allGroupProperties:f}}personPropertiesForLocalEvaluation(a,b){return{distinct_id:a,...b||{}}}createFeatureFlagEvaluationContext(a,b,c,d){return{distinctId:a,groups:b||{},personProperties:c||{},groupProperties:d||{},evaluationCache:{}}}captureException(a,b,c,d,e){if(!dJ.isPreviouslyCapturedError(a)&&this.errorTracking.claimExplicitCapture(a)){let f=Error("PostHog syntheticException");this.addPendingPromise(dJ.buildEventMessage(this.getErrorPropertiesBuilder(),a,{syntheticException:f},b,c,this.getContext()).then(a=>this._capturePreparedEvent({...a,uuid:d,flags:e},!1)))}}async captureExceptionImmediate(a,b,c,d){if(!dJ.isPreviouslyCapturedError(a)&&this.errorTracking.claimExplicitCapture(a)){let e=Error("PostHog syntheticException");return this.addPendingPromise(dJ.buildEventMessage(this.getErrorPropertiesBuilder(),a,{syntheticException:e},b,c,this.getContext()).then(a=>this.captureImmediate({...a,flags:d})))}}async prepareEventMessage(a){return this._prepareEventMessage(a)}_serviceNameProperties(){let a=this._resolveServiceName();return a?{service_name:a}:{}}_resolveServiceName(){return void 0===this._serviceName&&(this._serviceName=(this.options.traces?cg(this.options.traces,this.hostResourceAttributes()).serviceName:void 0)||cd(this.options.metrics).serviceName||null),this._serviceName}async _prepareEventMessage(a,b={}){var c;let{distinctId:d,event:e,properties:f,groups:g,flags:h,sendFeatureFlags:i,timestamp:j,disableGeoip:k,uuid:l}=a,m=(c=this.context?.get(),dF in a?a[dF]??void 0:c),n=b.includeContextProperties??!0,o=d||m?.distinctId,p=n?{...this._serviceNameProperties(),...this.props,...m?.properties||{},...f||{}}:{...this._serviceNameProperties(),...f||{}};"$exception"!==e||"$trace_id"in p||"$span_id"in p||Object.assign(p,await dO()),o||(o=aW(),p.$process_person_profile=!1),n&&m?.sessionId&&!p.$session_id&&(p.$session_id=m.sessionId);let q=b.flagEvent,r=q?{...Object.fromEntries(Object.entries(p).filter(([a])=>!q.removed.has(a))),...q.pinned}:p,s=this._shouldSendMinimalFlagCalledEvent(e,r)?q?function(a){let b=aE(a);for(let c of cv)void 0!==a[c]&&(b[c]=a[c]);return b}(r):aE(r):r,t=this._runBeforeSend({distinctId:o,event:e,properties:s,groups:g,flags:h,sendFeatureFlags:i,timestamp:j,disableGeoip:k,uuid:l},b.onCaptureFailed);if(!t)return Promise.reject(null);let u=await Promise.resolve().then(async()=>{if(h)return i&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),h._getEventProperties();if(i){eH("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");var a=await this.getFeatureFlagsForEvent(t.distinctId,g,k,"object"==typeof i?i:void 0);if(!a)return{};let b={};for(let[c,d]of Object.entries(a))b[`$feature/${c}`]=d;let c=Object.keys(a).filter(b=>!1!==a[b]).sort();return c.length>0&&(b.$active_feature_flags=c),b}return{}}).catch(()=>({})).then(a=>{let b=t.groups||g;return{...a,...t.properties||{},...void 0!==b&&Object.keys(b).length>0?{$groups:b}:{}}});return"$pageview"===t.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof u.$raw_user_agent&&cc(u.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(t.event="$bot_pageview",u.$browser_type="bot"),{distinctId:t.distinctId,event:t.event,properties:u,options:{timestamp:t.timestamp,disableGeoip:t.disableGeoip,uuid:t.uuid}}}_runBeforeSend(a,b){let c=this.options.before_send;if(!c)return a;let d=Array.isArray(c)?c:[c],e=a;for(let c of d)try{if(!(e=c(e)))return this._logger.info(`Event '${a.event}' was rejected in beforeSend function`),null;if(!e.properties||0===Object.keys(e.properties).length){let a=`Event '${e.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(a)}}catch(c){return this._logger.error(`Error in before_send function for event '${a.event}':`,c),b?.(),null}return e}}var eJ=am,eK=am,eL=am,eM=am,eN=am,eO=am,eP=am,eQ=am,eR=a.i(78500);let eS=Symbol.for("posthog-node.context-lifetimes"),eT=globalThis,eU=eT[eS]??=new WeakMap;function eV(a,b,c){let d=a&&eU.get(a);return c?eU.set(b,{signal:c,parent:d}):d&&eU.set(b,d),b}class eW{constructor(){this.storage=new eR.AsyncLocalStorage}get(){let a=this.storage.getStore();return a&&function(a){let b=eU.get(a);for(;b;){if(b.signal.aborted)return!1;b=b.parent}return!0}(a)?a:void 0}run(a,b,c){return this.storage.run(this.resolve(a,c),b)}enter(a,b){this.storage.enterWith(this.resolve(a,b))}resolve(a,b){let c=this.get();return b?.fresh===!0?eV(void 0,{...a},b.signal):eV(c,{distinctId:a.distinctId??c?.distinctId,sessionId:a.sessionId??c?.sessionId,properties:{...c?.properties||{},...a.properties||{}}},b?.signal)}}class eX{active(){return this._storage.getStore()}with(a,b){return this._storage.run(a,b)}constructor(){this._storage=new eR.AsyncLocalStorage}}var eY=a.i(27028);let eZ=(0,a.i(12057).promisify)(eY.gzip);async function e$(a,b=!0){try{let b=await eZ(a);return new Uint8Array(b)}catch(a){return b&&console.error("Failed to gzip compress data",a),null}}var e_=a.i(60526),dI=am;let e0="posthog-node";function e1(a,{organization:b,projectId:c,prefix:d,severityAllowList:e=["error"],sendExceptionsToPostHog:f=!0}={}){return g=>{if(!("*"===e||e.includes(g.level)))return g;g.tags||(g.tags={});let h=g.tags[e3.POSTHOG_ID_TAG];if(void 0===h)return g;let i=a.options.host??"https://us.i.posthog.com",j=new URL(`/project/${a.apiKey}/person/${h}`,i).toString();g.tags["PostHog Person URL"]=j;let k=g.exception?.values||[],l=k.map(a=>({...a,stacktrace:a.stacktrace?{...a.stacktrace,type:"raw",frames:(a.stacktrace.frames||[]).map(a=>({...a,platform:"node:javascript"}))}:void 0})),m={$exception_message:k[0]?.value||g.message,$exception_type:k[0]?.type,$exception_level:g.level,$exception_list:l,$sentry_event_id:g.event_id,$sentry_exception:g.exception,$sentry_exception_message:k[0]?.value||g.message,$sentry_exception_type:k[0]?.type,$sentry_tags:g.tags},n=dI.getInjectedReleaseId();return n&&(m.$release_id=n),b&&c&&(m.$sentry_url=(d||"https://sentry.io/organizations/")+b+"/issues/?project="+c+"&query="+g.event_id),f&&a.capture({event:"$exception",distinctId:h,properties:m}),g}}function e2(a,b){let c=e1(a,b);return{name:e0,processEvent:a=>c(a)}}class e3{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(a,b,c,d,e){this.name=e0,this.name=e0,this.setupOnce=function(f,g){f(e1(a,{organization:b,projectId:g()?.getClient()?.getDsn()?.projectId,prefix:c,severityAllowList:d,sendExceptionsToPostHog:e??!0}))}}}function e4(a){let b={};if(a)for(let c of a.split(";")){let[a,...d]=c.trim().split("=");if(a){let c=d.join("=").trim();try{b[a.trim()]=decodeURIComponent(c)}catch{b[a.trim()]=c}}}return{get:a=>a in b?{value:b[a]}:void 0}}function e5(a){let b=a.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${b}_posthog`}function e6(a){let b=Date.now();return JSON.stringify({distinct_id:a,$device_id:a,$user_state:"anonymous",$sesid:[b,aW(),b]})}function e7(a,b){let c=e5(b),d=a.get(c);return d?e9(d.value):null}function e8(a){if(!a)return;let b={};return a.sessionId&&(b.$session_id=a.sessionId),a.deviceId&&(b.$device_id=a.deviceId),Object.keys(b).length>0?b:void 0}function e9(a){if(!a)return null;try{let b=JSON.parse(a);if(!b||"object"!=typeof b||!b.distinct_id)return null;let c=s(b.$sesid)?b.$sesid:[],d=c[1];return{distinctId:String(b.distinct_id),isIdentified:"identified"===b.$user_state,sessionId:"string"==typeof d?d:void 0,sessionLastActivityTimestamp:fa(c[0]),sessionStartTimestamp:fa(c[2]),deviceId:"string"==typeof b.$device_id?b.$device_id:void 0}}catch{return null}}function fa(a){return"number"==typeof a&&Number.isFinite(a)?a:void 0}a.s(["PostHogSentryIntegration",0,e3,"createEventProcessor",0,e1,"sentryIntegration",0,e2],9318);let fb=/[\x00-\x1f\x7f-\x9f]/g;function fc(a){let b=a.options.readPostHogCookie;return!0===b?{apiKey:a.apiKey}:b&&"object"==typeof b?{apiKey:a.apiKey,sessionIdleTimeoutSeconds:b.sessionIdleTimeoutSeconds,optOutCapturingByDefault:b.optOutCapturingByDefault}:null}function fd(a,b,c){null!=c&&""!==c&&(a[b]=c)}function fe(a){return Array.isArray(a)?a[0]:a}function ff(a){if(Array.isArray(a)){for(let b of a){let a=ff(b);if(void 0!==a)return a}return}if("string"!=typeof a)return;let b=a.replace(fb,"").trim();if(b)return b.length>1e3?b.slice(0,1e3):b}function fg(a,b,c){return"number"==typeof a&&Number.isFinite(a)&&Math.abs(b-a)<=c}function fh(a,b){let c;if(!a)return{};let d=ff(a["x-posthog-session-id"]),e=ff(a["x-posthog-distinct-id"]),{sessionId:f,distinctId:g}=void 0===d&&void 0===e&&b?function(a,b,c=Date.now(),d=18e5,e=!1){try{let f;if("string"!=typeof a)return{};let g=e4(a.split(";").reverse().join(";")),h=g.get(e5(b))?.value,i=g.get("__ph_opt_in_out_"+b)?.value??"";if(!h||m(F,i)||e&&!m(E,i))return{};let j=JSON.parse(h);if(!j||"object"!=typeof j)return{};let k="identified"===j.$user_state?ff(j.distinct_id):void 0,l=j.$sesid;if(Array.isArray(l)&&(2===l.length||3===l.length)){let[a,b,e=a]=l;fg(a,c,d)&&fg(e,c,864e5)&&(f=ff(b))}return{...void 0!==f?{sessionId:f}:{},...void 0!==k?{distinctId:k}:{}}}catch{return{}}}(a.cookie,b.apiKey,Date.now(),"number"==typeof(c=b.sessionIdleTimeoutSeconds)&&Number.isFinite(c)&&0!==c?1e3*Math.min(Math.max(c,60),36e3):18e5,!0===b.optOutCapturingByDefault):{sessionId:d,distinctId:e};return{...void 0!==f?{sessionId:f}:{},...void 0!==g?{distinctId:g}:{}}}function fi(a,b){let c=function(a){if(!a)return a;let b=a.indexOf("?"),c=a.indexOf("#");return -1===b||-1!==c&&c<b?a:`${a.slice(0,b)}${-1===c?"":a.slice(c)}`}(a);return b?aJ(c):c}function fj(a,b){var c;let d=fh(b.headers,fc(a)),e=a.getContext(),f=e?.sessionId??d.sessionId,g=e?.distinctId??d.distinctId,h={},i=!0===a.options.disable_capture_url_hashes;return fd(h,"$current_url",(c=b.originalUrl||b.url,i?aJ(c):c)),fd(h,"$request_method",b.method),fd(h,"$request_path",fi(b.path,i)),fd(h,"$user_agent",fe(b.headers["user-agent"])),fd(h,"$ip",function(a){let b=fe(a.headers["x-forwarded-for"]);if(b){let a=b.split(",")[0].trim();if(a)return a}return a.socket?.remoteAddress}(b)),{...void 0!==f?{sessionId:f}:{},...void 0!==g?{distinctId:g}:{},properties:h}}function fk(a,b){var c;b.use((c=a,(a,b,d)=>{c.withContext(fj(c,a),()=>{dT(c,!0),d()})}))}function fl(a,b){var c;b.use((c=a,(a,b,d,e)=>{if(dJ.isPreviouslyCapturedError(a))return void e(a);let f=fj(c,b),g=Error("Synthetic exception"),h={...void 0!==f.sessionId?{$session_id:f.sessionId}:{},...f.properties||{}};c.addPendingPromise(Promise.all([dJ.buildEventMessage(c.getErrorPropertiesBuilder(),a,{mechanism:{type:"middleware",handled:!1},syntheticException:g},f.distinctId,h,c.getContext()),d.headersSent||d.destroyed?Promise.resolve(d.headersSent?d.statusCode:void 0):new Promise(a=>{let b=b=>{clearTimeout(e),d.removeListener("finish",c),d.removeListener("close",c),a(b)},c=()=>b(d.headersSent?d.statusCode:void 0),e=setTimeout(()=>b(void 0),1e3);e.unref(),d.once("finish",c),d.once("close",c)})]).then(([a,b])=>(void 0!==b&&(a.properties={...a.properties,$response_status_code:b}),c._capturePreparedEvent(a,!1)))),e(a)}))}a.s(["setupExpressErrorHandler",0,fl,"setupExpressRequestContext",0,fk],40602);let fm="http.server.request.duration",fn="http.server.request.count",fo=[.005,.01,.025,.05,.075,.1,.25,.5,.75,1,2.5,5,7.5,10],fp=new Set(["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","QUERY","TRACE"]);function fq(a,b,c,d={}){return fr(a,b,c,d)}async function fr(a,b,c,d,e){var f;let g;if(d.ignore?.(b))return c();let h=fh((f=b.headers,g={},f.forEach((a,b)=>{g[b.toLowerCase()]=a}),g),fc(a)),i=a.getContext(),j=!0===a.options.disable_capture_url_hashes,k=function(a){try{return new URL(a.url).pathname}catch{return}}(b),l={};fd(l,"$request_method",b.method),fd(l,"$request_path",k?fi(k,j):void 0),fd(l,"$user_agent",b.headers.get("user-agent")??void 0);let m=i?.sessionId??h.sessionId,n=i?.distinctId??h.distinctId,o={...void 0!==m?{sessionId:m}:{},...void 0!==n?{distinctId:n}:{},properties:l},p=b.method.toUpperCase(),q=fp.has(p)?p:"_OTHER",r="_OTHER"===q?"HTTP":q,s=performance.now(),t=new AbortController,u=!1;try{return await a.withContext(o,()=>(dT(a,!0),a.withSpan(r,{kind:"server",parent:b.headers.get("traceparent")??void 0,tracestate:b.headers.get("tracestate")??void 0,attributes:{"http.request.method":q,..."_OTHER"===q?{"http.request.method_original":b.method}:{},...k?{"url.path":k}:{}}},async f=>{var g,h,i;let j,k,l,m,n=!1;try{k=await c()}catch(a){n=!0,l=a}try{m=d.getRoute?.(b,k)}catch{}let p=n?500:k?.status??500;if(m&&(f.updateName(`${r} ${m}`),f.setAttribute("http.route",m)),f.setAttribute("http.response.status_code",p),!n&&p>=500){let a;try{a=e?.()}catch{}null!=a?f.recordException(a):f.setStatus("error")}let v={"http.request.method":q,"http.response.status_code":p,...m?{"http.route":m}:{}};if(a.metrics.histogram(fm,(performance.now()-s)/1e3,{unit:"s",attributes:v,bounds:fo}),a.metrics.count(fn,1,{attributes:v}),a._flushMetricsWithinInvocation(),n)throw l;return k?.body&&"HEAD"!==q?(u=!0,g=k,h=b=>a.withContext(o,b,{signal:t.signal}),i=()=>t.abort(),j=g.body.getReader(),new Response(new ReadableStream({async pull(a){try{let{done:b,value:c}=await h(()=>j.read());b?(a.close(),i()):a.enqueue(c)}catch(b){i(),a.error(b)}},async cancel(a){try{await h(()=>j.cancel(a))}finally{i()}}}),g)):k})),{signal:t.signal})}finally{u||t.abort()}}function fs(a,b={}){return async(c,d)=>{c.res=await fr(a,c.req.raw,async()=>(await d(),c.res),{...b,getRoute:()=>c.req.routePath&&"/*"!==c.req.routePath?c.req.routePath:void 0},()=>c.error)}}a.s(["HTTP_SERVER_REQUEST_COUNT_METRIC",0,fn,"HTTP_SERVER_REQUEST_DURATION_METRIC",0,fm,"instrumentRequest",0,fq,"posthogHonoMiddleware",0,fs],3157),a.i(9318),a.i(40602),a.i(3157),a.i(46539),a.s(["EmailError",0,d6,"FeatureFlagError",0,l,"FeatureFlagEvaluations",0,ci,"HTTP_SERVER_REQUEST_COUNT_METRIC",0,fn,"HTTP_SERVER_REQUEST_DURATION_METRIC",0,fm,"PostHogSentryIntegration",0,e3,"cookieStateToProperties",0,e8,"cookieStoreFromHeader",0,e4,"createEventProcessor",0,e1,"enrichCurrentSpan",0,dU,"getPostHogCookieName",0,e5,"instrumentRequest",0,fq,"parsePostHogCookie",0,e9,"posthogHonoMiddleware",0,fs,"readPostHogCookie",0,e7,"sentryIntegration",0,e2,"serializePostHogCookie",0,e6,"setupExpressErrorHandler",0,fl,"setupExpressRequestContext",0,fk,"uuidv7",0,aW],80456),a.i(80456),a.s(["EmailError",0,d6,"FeatureFlagError",0,l,"FeatureFlagEvaluations",0,ci,"HTTP_SERVER_REQUEST_COUNT_METRIC",0,fn,"HTTP_SERVER_REQUEST_DURATION_METRIC",0,fm,"PostHog",0,class extends eI{getLibraryId(){return"posthog-node"}compressPayload(a){return e$(a,this.isDebug)}initializeContext(){return new eW}initializeSpanContextManager(){return new eX}hostResourceAttributes(){return function(){var a,b;let c,d,e;try{c=(0,e_.platform)(),d=(0,e_.release)()}catch{}return a=c,b=d,{...(e=function(a){if(a)return Object.prototype.hasOwnProperty.call(bm,a)?bm[a]:a}(a))?{"os.name":e}:{},...b?{"os.version":b}:{}}}()}createErrorPropertiesBuilder(){let a;return new eJ.ErrorPropertiesBuilder([new eK.EventCoercer,new eL.ErrorCoercer,new eM.ObjectCoercer,new eN.StringCoercer,new eO.PrimitiveCoercer],eP.createStackParser("node:javascript",eQ.nodeStackLineParser),[(a=function(a=process.argv[1]?(0,i.dirname)(process.argv[1]):process.cwd(),b="\\"===i.sep){let c=b?j(a):a;return a=>{if(!a)return;let d=b?j(a):a,{dir:e,base:f,ext:g}=i.posix.parse(d);(".js"===g||".mjs"===g||".cjs"===g)&&(f=f.slice(0,-1*g.length));let h=decodeURIComponent(f);e||(e=".");let k=e.lastIndexOf("/node_modules");if(k>-1)return`${e.slice(k+14).replace(/\//g,".")}:${h}`;if(e.startsWith(c)){let a=e.slice(c.length+1).replace(/\//g,".");return a?`${a}:${h}`:h}return h}}(),async b=>{for(let c of b)c.module=a(c.filename);return b}),a=>at(a,void 0,this._logger),function(a=process.cwd()){i.sep;let b=a=>a,c=b(a);return async a=>{for(let d of a)!(!d.filename||d.filename.startsWith("node:")||d.filename.startsWith("data:"))&&(0,i.isAbsolute)(d.filename)&&(d.filename=b((0,i.relative)(c,b(d.filename))));return a}}()])}},"PostHogSentryIntegration",0,e3,"cookieStateToProperties",0,e8,"cookieStoreFromHeader",0,e4,"createEventProcessor",0,e1,"enrichCurrentSpan",0,dU,"getPostHogCookieName",0,e5,"instrumentRequest",0,fq,"parsePostHogCookie",0,e9,"posthogHonoMiddleware",0,fs,"readPostHogCookie",0,e7,"sentryIntegration",0,e2,"serializePostHogCookie",0,e6,"setupExpressErrorHandler",0,fl,"setupExpressRequestContext",0,fk,"uuidv7",0,aW],74493)}];
|
|
3
2
|
|
|
4
3
|
//# sourceMappingURL=node_modules_posthog-node_dist_entrypoints_index_node_mjs_11bnuznb72p7z._.js.map
|