failproofai 1.0.12-beta.2 → 1.0.13-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/standalone/.next/BUILD_ID +1 -1
- package/.next/standalone/.next/build-manifest.json +13 -13
- 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 +2 -2
- 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 -1
- 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 +2 -2
- 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 +4 -3
- 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 +3 -3
- package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
- package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/api/audit/invite/route.js +6 -5
- 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 +27 -26
- 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 +4 -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 +6 -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 +6 -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 +6 -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 +6 -5
- 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 +4 -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 +2 -2
- package/.next/standalone/.next/server/app/audit/page/server-reference-manifest.json +2 -2
- package/.next/standalone/.next/server/app/audit/page.js +7 -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 +3 -3
- package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +3 -3
- package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/page/build-manifest.json +2 -2
- package/.next/standalone/.next/server/app/page/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/server/app/page.js +6 -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 +2 -2
- package/.next/standalone/.next/server/app/policies/page/server-reference-manifest.json +14 -14
- package/.next/standalone/.next/server/app/policies/page.js +5 -4
- 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 +2 -2
- 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 +21 -20
- 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 +2 -2
- 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 +10 -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 +2 -2
- package/.next/standalone/.next/server/app/projects/page/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/server/app/projects/page.js +7 -6
- 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 +2 -2
- package/.next/standalone/.next/server/app/settings/page/server-reference-manifest.json +8 -8
- package/.next/standalone/.next/server/app/settings/page.js +6 -5
- 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/{[externals]__0vt9i6fqinjne._.js → [externals]__1h83uo-b1b6-2._.js} +1 -1
- package/.next/standalone/.next/server/chunks/[externals]__214wn4wh2x79y._.js +3 -0
- package/.next/standalone/.next/server/chunks/{[externals]__1rlxpymm37wel._.js → [root-of-the-server]__031qp1lkow_kc._.js} +2 -2
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__038kwryp970nh._.js +3 -0
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0_hsnj_a2mvl_._.js → [root-of-the-server]__03s1za0hn71yp._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0wg9dk8x8bnau._.js → [root-of-the-server]__07a0sa6fuw5_b._.js} +2 -2
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__08atcie7jzswm._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__08dchfudh2_4f._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0car70pylmvor._.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]__12kq3x-h7t7i1._.js → [root-of-the-server]__0yvyp5b7jmlc4._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__02vous7mpi2xm._.js → [root-of-the-server]__145vo_drnuvas._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[externals]__0h0p9dmv_e7r7._.js → [root-of-the-server]__1a2d0ewycsp6k._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[externals]__1_407huhlmj1m._.js → [root-of-the-server]__1am_1tz0o0aqz._.js} +2 -2
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__03i5o4a840guz._.js → [root-of-the-server]__1gxfzuvpyw30j._.js} +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1j6kfp0vzu5rw._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1l0ayum_hqqsw._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1lh8c0mmhdrbj._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1o9rznwc0w7og._.js +3 -0
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__0f_4g-vazrvxv._.js → [root-of-the-server]__1o_622x0fglpr._.js} +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1oclamblhzhrf._.js +68 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1v1-l-83czzsr._.js +63 -0
- package/.next/standalone/.next/server/chunks/{[root-of-the-server]__1a5zkndjwlc13._.js → [root-of-the-server]__1wwi53kkqhnfi._.js} +1 -1
- package/.next/standalone/.next/server/chunks/{_1y590mjzpkbos._.js → _02sa8fcu9_9xo._.js} +2 -2
- 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/_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/node_modules_@opentelemetry_api_build_esm_index_0oo58a7rymoxh.js +3 -0
- package/.next/standalone/.next/server/chunks/node_modules_@opentelemetry_api_build_esm_index_1jp9ij0_ddtgk.js +3 -0
- package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_01r25oigsgz07._.js +2 -2
- package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_09z9-p77cu37y._.js +2 -2
- package/.next/standalone/.next/server/chunks/package_json_[json]_cjs_1nxcc4vkpxxu7._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0ffu2-38y03ic._.js → [root-of-the-server]__021vebe-4il8s._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__075uro8t92s0_._.js +14 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__08ch3staq3ejw._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{[externals]__12qr51qgrrt6o._.js → [root-of-the-server]__097i34ct1o88x._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0alpzjn3450sr._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0aup10z2o8zc1._.js +3 -0
- 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]__0bioghlkjf7s7._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__01j58mdcdw0vn._.js → [root-of-the-server]__0ed1zh4scn7-k._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0naevg4bcoh54._.js → [root-of-the-server]__0evgy902m9h5e._.js} +2 -2
- 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]__00l2u6j86cb8y._.js → [root-of-the-server]__0mhtkwwx1pxcq._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0nhm28v58ty9z._.js +3 -0
- 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]__0vse4qi496ol-._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__17r4zrwanhp6r._.js → [root-of-the-server]__0yb3u36xjy3b9._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0g8b0kyorya-t._.js → [root-of-the-server]__0ywj2u6ovfm_5._.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]__0zn1d4blhd3bu._.js → [root-of-the-server]__10v5cyxvj64j4._.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]__190xwrr5zrfi3._.js +3 -0
- 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]__1vx7o8ukefudh._.js → [root-of-the-server]__1guwlpkyurdn9._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1k96jctukf65_._.js +3 -0
- 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]__1sj-wn2jp6va5._.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]__1s2-ck3k3rsoo._.js → [root-of-the-server]__20dt376-socef._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__1lnfv02ucky7m._.js → [root-of-the-server]__2158020r_amn9._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{_1fw0_nzkae5ao._.js → _0bc4f4quq6w47._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/_0bseae9u7g98r._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_0eoura3_9gjb-._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_0mouhaflye1ro._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_0ouu886szh6yj._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_0pedwblqdoh58._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_1_ozgifqv1ssi._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_1djqs9i27e4kg._.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_actions_get-scheduled-audit_ts_0ei9snixb5fd-._.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_components_project-list_tsx_1ke6anr0vt64h._.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/{node_modules_09s4n108bqreq._.js → node_modules_0ptcnmeaxvd_a._.js} +22 -2
- package/.next/standalone/.next/server/chunks/ssr/node_modules_@opentelemetry_api_build_esm_index_0ntwr8lzj6p2i.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/{node_modules_html-to-image_es_index_1fv03uigni8s5.js → node_modules_html-to-image_es_index_1jwgv0pf-gy96.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_0bz67659f5z-3._.js +32 -0
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_0janj0i6dqko7._.js +3 -3
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_0ocrceo0c9psx._.js +32 -0
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_1alv566ojmz5j._.js +32 -0
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_1khq67j4vo9y4._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_shared_lib_0ftnv26hg1lry._.js +3 -0
- 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 +2 -2
- package/.next/standalone/.next/server/chunks/ssr/package_json_[json]_cjs_013tntikdft59._.js +1 -1
- package/.next/standalone/.next/server/middleware-build-manifest.js +13 -13
- package/.next/standalone/.next/server/middleware.js +2 -2
- 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/0cbom4-ijx_a_.js +1 -0
- package/.next/standalone/.next/static/chunks/0u5weo5jdn2s8.js +1 -0
- package/.next/standalone/.next/static/chunks/{1c_jf6g5wnslk.js → 18-icoqze51kl.js} +1 -1
- package/.next/standalone/.next/static/chunks/2d-u90dt4-8rd.js +6 -0
- package/.next/standalone/.next/static/chunks/2n-bzb7pxe7hu.js +1 -0
- package/.next/standalone/.next/static/chunks/{2o6d37j425uci.js → 2zc7lg-jq353g.js} +1 -1
- package/.next/standalone/.next/static/chunks/{0tbm3vjm62h-2.js → 33djjf12bhcsv.js} +1 -1
- package/.next/standalone/.next/static/chunks/{42xptz88mtq3x.js → 38u_i3j5funpi.js} +1 -1
- package/.next/standalone/.next/static/chunks/{20py8k1gd_i1m.js → 3symuj7t4js-c.js} +1 -1
- package/.next/standalone/.next/static/chunks/{0ay__-d2h1xb5.js → 3vzut6zpdrvtx.js} +1 -1
- package/.next/standalone/.next/static/chunks/{063al_q720fkj.js → 3xgxl1s_in776.js} +2 -2
- package/.next/standalone/SECURITY.md +20 -4
- package/.next/standalone/fp-cloud-cli/CHANGELOG.md +34 -1
- package/.next/standalone/fp-cloud-cli/README.md +120 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/_version.py +1 -1
- package/.next/standalone/fp-cloud-cli/fp_cli/app.py +15 -1
- package/.next/standalone/fp-cloud-cli/fp_cli/client.py +198 -7
- package/.next/standalone/fp-cloud-cli/fp_cli/cloud_output.py +523 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/_cloud.py +45 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/_write.py +3 -1
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/account_cmds.py +171 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/agent_cmds.py +80 -7
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/alerts_cmds.py +23 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/audits_cmds.py +2 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/contracts_cmds.py +67 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/dashboards_cmds.py +159 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/evaluators_cmds.py +380 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/events_cmds.py +14 -1
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/incidents_cmds.py +82 -6
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/list_cmds.py +4 -1
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/orgs_cmds.py +17 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/policies_cmds.py +143 -1
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/queries_cmds.py +70 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/sentiment_cmds.py +49 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/sessions_cmds.py +95 -1
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/settings_cmds.py +2 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/usage_cmds.py +21 -1
- package/.next/standalone/fp-cloud-cli/fp_cli/commands/users_cmds.py +14 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/errors.py +3 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/evaluator_spec.py +266 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/output.py +187 -81
- package/.next/standalone/fp-cloud-cli/fp_cli/theme.py +21 -24
- package/.next/standalone/fp-cloud-cli/skill/SKILL.md +124 -23
- package/.next/standalone/fp-cloud-cli/skill/agents/openai.yaml +2 -1
- package/.next/standalone/fp-cloud-cli/skill/references/commands.md +168 -16
- package/.next/standalone/fp-cloud-cli/tests/fake_cloud_smoke.py +312 -0
- package/.next/standalone/fp-cloud-cli/tests/test_cloud_account.py +125 -0
- package/.next/standalone/fp-cloud-cli/tests/test_cloud_agent.py +253 -0
- package/.next/standalone/fp-cloud-cli/tests/test_cloud_human_views.py +287 -0
- package/.next/standalone/fp-cloud-cli/tests/test_cloud_observability.py +116 -0
- package/.next/standalone/fp-cloud-cli/tests/test_cloud_transport.py +141 -0
- 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_evaluator_authoring.py +449 -0
- package/.next/standalone/fp-cloud-cli/tests/test_facets.py +1 -1
- package/.next/standalone/fp-cloud-cli/tests/test_help_table_coverage.py +15 -0
- 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 +37 -37
- package/.next/standalone/fp-cloud-cli/tests/test_round4_behaviour.py +144 -0
- package/.next/standalone/fp-cloud-cli/tests/test_screen_language.py +80 -0
- package/.next/standalone/fp-cloud-cli/tests/test_session_reevaluate.py +33 -0
- package/.next/standalone/fp-cloud-cli/tests/test_staging_parity.py +198 -0
- package/.next/standalone/fp-cloud-cli/tests/test_whoami.py +1 -1
- package/.next/standalone/fp-cloud-cli/uv.lock +4 -4
- 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/next-server/app-page-turbo-experimental.runtime.prod.js +24 -24
- package/.next/standalone/node_modules/next/dist/compiled/next-server/app-page-turbo.runtime.prod.js +26 -26
- package/.next/standalone/node_modules/next/dist/compiled/next-server/app-route-turbo.runtime.prod.js +3 -3
- package/.next/standalone/node_modules/next/dist/compiled/next-server/pages-turbo.runtime.prod.js +13 -13
- package/.next/standalone/node_modules/next/dist/lib/patch-incorrect-lockfile.js +3 -3
- package/.next/standalone/node_modules/next/dist/server/app-render/app-render.js +41 -40
- 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/dynamic-rendering-validation.js +814 -0
- package/.next/standalone/node_modules/next/dist/server/app-render/dynamic-rendering.js +1 -799
- package/.next/standalone/node_modules/next/dist/server/base-server.js +39 -5
- 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 +2 -2
- package/.next/standalone/node_modules/next/dist/server/dev/hot-reloader-webpack.js +1 -1
- package/.next/standalone/node_modules/next/dist/server/lib/app-info-log.js +1 -1
- package/.next/standalone/node_modules/next/dist/server/lib/dedupe-fetch.js +4 -43
- package/.next/standalone/node_modules/next/dist/server/lib/patch-fetch-symbol.js +13 -0
- package/.next/standalone/node_modules/next/dist/server/lib/patch-fetch.js +3 -7
- package/.next/standalone/node_modules/next/dist/server/lib/router-server.js +3 -3
- package/.next/standalone/node_modules/next/dist/server/lib/router-utils/instrumentation-globals.external.js +77 -12
- package/.next/standalone/node_modules/next/dist/server/lib/start-server.js +1 -1
- package/.next/standalone/node_modules/next/dist/server/lib/trace/constants.js +12 -0
- package/.next/standalone/node_modules/next/dist/server/lib/trace/tracer.js +30 -14
- package/.next/standalone/node_modules/next/dist/server/next-server.js +10 -11
- package/.next/standalone/node_modules/next/dist/server/route-modules/pages/pages-handler.js +29 -23
- package/.next/standalone/node_modules/next/dist/server/route-modules/route-module.js +85 -8
- package/.next/standalone/node_modules/next/dist/server/use-cache/use-cache-wrapper.js +1 -1
- package/.next/standalone/node_modules/next/dist/server/web/adapter.js +124 -65
- package/.next/standalone/node_modules/next/dist/server/web/forward-trace-context.js +102 -0
- 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/node_modules/react/cjs/react.production.js +1 -1
- package/.next/standalone/node_modules/react/package.json +1 -1
- package/.next/standalone/node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.js +1 -1
- package/.next/standalone/node_modules/react-dom/cjs/react-dom-server-legacy.node.production.js +1 -1
- package/.next/standalone/node_modules/react-dom/cjs/react-dom-server.browser.production.js +31 -27
- package/.next/standalone/node_modules/react-dom/cjs/react-dom-server.edge.production.js +33 -27
- package/.next/standalone/node_modules/react-dom/cjs/react-dom-server.node.production.js +38 -30
- package/.next/standalone/node_modules/react-dom/cjs/react-dom.production.js +1 -1
- package/.next/standalone/node_modules/react-dom/package.json +2 -2
- package/.next/standalone/package.json +10 -10
- package/.next/standalone/sdk/python/CHANGELOG.md +8 -4
- package/.next/standalone/sdk/python/failproofai_sdk/evaluator/source.py +2 -2
- package/.next/standalone/sdk/python/pyproject.toml +2 -7
- package/.next/standalone/sdk/python/skill/references/frameworks.md +0 -15
- package/.next/standalone/sdk/python/tests/test_docs.py +1 -4
- package/.next/standalone/sdk/python/tests/test_evaluator_source.py +1 -1
- package/.next/standalone/sdk/python/tests/test_packaging.py +4 -7
- package/.next/standalone/sdk/python/tests/test_zero_dependencies.py +2 -13
- package/.next/standalone/sdk/python/uv.lock +43 -905
- package/.next/standalone/sdk/typescript/CHANGELOG.md +52 -0
- package/.next/standalone/sdk/typescript/integration/fixtures/ai-5/package-lock.json +7 -7
- package/.next/standalone/sdk/typescript/integration/fixtures/ai-5/package.json +2 -2
- package/.next/standalone/sdk/typescript/integration/fixtures/ai-6/package-lock.json +7 -7
- package/.next/standalone/sdk/typescript/integration/fixtures/ai-6/package.json +1 -1
- package/.next/standalone/sdk/typescript/integration/fixtures/ai-7/package-lock.json +7 -7
- package/.next/standalone/sdk/typescript/integration/fixtures/ai-7/package.json +1 -1
- package/.next/standalone/sdk/typescript/integration/fixtures/langchain-1/package-lock.json +4 -4
- package/.next/standalone/sdk/typescript/integration/fixtures/langchain-1/package.json +1 -1
- package/.next/standalone/sdk/typescript/integration/fixtures/langchain-dup-core/package-lock.json +4 -4
- package/.next/standalone/sdk/typescript/integration/fixtures/langchain-dup-core/package.json +1 -1
- package/.next/standalone/sdk/typescript/integration/fixtures/llamaindex-0.11/package-lock.json +3 -3
- package/.next/standalone/sdk/typescript/integration/fixtures/llamaindex-0.11/package.json +3 -0
- package/.next/standalone/sdk/typescript/integration/fixtures/llamaindex-0.12/package-lock.json +4 -4
- package/.next/standalone/sdk/typescript/integration/fixtures/llamaindex-0.12/package.json +1 -1
- package/.next/standalone/sdk/typescript/integration/fixtures/mastra-0/package-lock.json +25 -25
- package/.next/standalone/sdk/typescript/integration/fixtures/mastra-0/package.json +1 -1
- package/.next/standalone/sdk/typescript/integration/fixtures/mastra-1/package-lock.json +34 -22
- package/.next/standalone/sdk/typescript/integration/fixtures/mastra-1/package.json +3 -2
- package/.next/standalone/sdk/typescript/integration/fixtures/nextjs/package-lock.json +10 -10
- package/.next/standalone/sdk/typescript/integration/fixtures/nextjs/package.json +1 -1
- package/.next/standalone/sdk/typescript/integration/fixtures/runtimes/deno-npm.ts +1 -1
- package/.next/standalone/sdk/typescript/integration/fixtures/runtimes/package-lock.json +7 -7
- package/.next/standalone/sdk/typescript/integration/fixtures/runtimes/package.json +1 -1
- package/.next/standalone/server.js +1 -1
- package/README.md +0 -6
- package/dist/cli.mjs +87 -38
- package/dist/worker.mjs +73 -28
- package/hermes-plugin/plugin.yaml +1 -1
- package/openclaw-plugin/daemon-client.js +254 -0
- package/openclaw-plugin/hooks.js +187 -0
- package/openclaw-plugin/index.js +17 -211
- package/package.json +10 -10
- package/scripts/sync-agent-cli-harnesses-prompt.md +26 -31
- package/src/hooks/agent-skill.ts +3 -0
- package/src/hooks/enforcement-capability.ts +1 -1
- package/src/hooks/fp-home.ts +1 -1
- package/src/hooks/handler.ts +22 -3
- package/src/hooks/integrations.ts +5 -2
- package/src/hooks/semantic/intent.ts +127 -24
- package/src/hooks/semantic/jev-review.ts +21 -2
- package/.next/standalone/.codex/hooks.json +0 -76
- package/.next/standalone/.cursor/hooks.json +0 -47
- package/.next/standalone/.factory/hooks.json +0 -112
- package/.next/standalone/.next/server/chunks/[externals]__1x24dzcbbq6-g._.js +0 -3
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0__a_je8fsn65._.js +0 -3
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0l-oi4gdtmlo5._.js +0 -3
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0t9ufnv5hi2hq._.js +0 -327
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1aaw59g-5uty7._.js +0 -322
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1hqpg6vgmfexv._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[externals]__0ilfh9mfnzsth._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[externals]__0ohnuzsaozaca._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0pwj2h2efe5f-._.js +0 -14
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_0zuikgt2xho-v._.js +0 -271
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_158jo-9mwvgad._.js +0 -291
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_19r82zsxo2jj1._.js +0 -291
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_1dupwucoqt5qm._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_shared_lib_03w27x2kh17_8._.js +0 -23
- package/.next/standalone/.next/static/chunks/1my3-5p47t7r-.js +0 -1
- package/.next/standalone/.next/static/chunks/21hckpmsc4g70.js +0 -6
- package/.next/standalone/.next/static/chunks/2hmex93ppj1ke.js +0 -1
- package/.next/standalone/.next/static/chunks/40oworn_-x12p.js +0 -1
- package/.next/standalone/.opencode/opencode.json +0 -4
- package/.next/standalone/.opencode/plugins/failproofai.mjs +0 -210
- package/.next/standalone/.pi/settings.json +0 -5
- package/.next/standalone/node_modules/react/cjs/react.development.js +0 -1330
- package/scripts/dev-hook.mjs +0 -333
- /package/.next/standalone/.next/static/{LHCtFxVG0mdvd4lsXAOFC → 1n2dyfTQb0MDajeqlipJy}/_buildManifest.js +0 -0
- /package/.next/standalone/.next/static/{LHCtFxVG0mdvd4lsXAOFC → 1n2dyfTQb0MDajeqlipJy}/_clientMiddlewareManifest.js +0 -0
- /package/.next/standalone/.next/static/{LHCtFxVG0mdvd4lsXAOFC → 1n2dyfTQb0MDajeqlipJy}/_ssgManifest.js +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
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",QUOTA_LIMITED:"quota_limited",TIMEOUT:"timeout",CONNECTION_ERROR:"connection_error",UNKNOWN_ERROR:"unknown_error",apiError:a=>`api_error_${a}`};function m(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 n=Array.isArray,o=Object.prototype;o.hasOwnProperty;let p=o.toString,q=n||function(a){return"[object Array]"===p.call(a)},r=a=>a===Object(a)&&!q(a),s=a=>void 0===a,t=a=>"[object String]"==p.call(a),u=a=>t(a)&&0===a.trim().length,v=a=>null===a,w=a=>s(a)||v(a),x=a=>"[object Number]"==p.call(a)&&a==a;function y(a){return null===a||"object"!=typeof a}function z(a,b){return Object.prototype.toString.call(a)===`[object ${b}]`}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 C(a,Error)}}function B(a){return"u">typeof Event&&C(a,Event)}function C(a,b){try{return a instanceof b}catch{return!1}}let D="Android",E="BlackBerry",F="Nintendo",G="PlayStation",H="Xbox",I="Windows",J="(\\d+(\\.\\d+)?)";RegExp("Version/"+J),RegExp("(Claude|Codex|ChatGPT)\\/"+J),RegExp(H,"i"),RegExp(G+" \\w+","i"),RegExp(F+" \\w+","i"),RegExp(E+"|PlayBook|BB10","i");RegExp("rv:"+J),RegExp("Edge?\\/"+J),RegExp("(Chrome|CrMo)\\/"+J),RegExp("CriOS\\/"+J),RegExp("(UCBrowser|UCWEB)\\/"+J),RegExp("(Opera|OPR)\\/"+J),RegExp("Firefox\\/"+J),RegExp("FxiOS\\/"+J),RegExp("Konqueror[:/]?"+J,"i"),RegExp(E+" "+J),RegExp("android\\s"+J,"i"),RegExp("SamsungBrowser\\/"+J),RegExp("OculusBrowser\\/"+J),RegExp("Vivaldi\\/"+J),RegExp("YaBrowser\\/"+J),RegExp("Whale\\/"+J),RegExp("Brave\\/"+J),RegExp("(DuckDuckGo|Ddg)\\/"+J),RegExp("PaleMoon\\/"+J),RegExp("Waterfox\\/"+J),RegExp("GSA\\/"+J),RegExp("(rv:|MSIE )"+J),RegExp("rv:"+J),RegExp(H+"; "+H+" (.*?)[);]","i"),RegExp(F,"i"),RegExp(G,"i"),RegExp(I,"i"),RegExp("("+D+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+D+")","i");let K=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function L(a,b){return"string"==typeof a&&K.test(a)?a:b()}function M(a,b){let c=Error(b);try{Object.defineProperty(c,"name",{value:a,writable:!0,enumerable:!0,configurable:!0})}catch{}return c}function N(a){return a?a.split("#")[0]:a}async function O(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 P(){return new Date().toISOString()}function Q(a,b){let c=setTimeout(a,b);return c?.unref&&c?.unref(),c}async function R(a,b,c){let d;try{return await Promise.race([a,new Promise((a,e)=>{d=Q(()=>{try{c?.(),a()}catch(a){e(a)}},b)})])}finally{clearTimeout(d)}}function S(a){return Promise.all(a.map(a=>(a??Promise.resolve()).then(a=>({status:"fulfilled",value:a}),a=>({status:"rejected",reason:a}))))}function T(a,b,c){return a&&c?b.length===Object.keys(c).length&&b.every(b=>a[b]===c[b]):a===c}class U{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&&q(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&&T(f,h,c)&&T(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 q(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,U],6762);let V=/^([a-z][a-z0-9.+-]+):/i,W=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function X(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=V.exec(a);return!b||W.includes(b[1].toLowerCase())}(b)};return s(d)||(f.lineno=d),s(e)||(f.colno=e),f}let Y=(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]},Z=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,$=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,_=/\((\S*)(?::(\d+))(?::(\d+))\)/,aa=(a,b)=>{let c=Z.exec(a);if(c){let[,a,d,e]=c;return X(b,a,"?",+d,+e)}let d=$.exec(a);if(d){if(d[2]&&0===d[2].indexOf("eval")){let a=_.exec(d[2]);a&&(d[2]=a[1],d[3]=a[2],d[4]=a[3])}let[a,c]=Y(d[1]||"?",d[2]);return X(b,c,a,d[3]?+d[3]:void 0,d[4]?+d[4]:void 0)}},ab=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ac=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ad=(a,b)=>{let c=ab.exec(a);if(c){if(c[3]&&c[3].indexOf(" > eval")>-1){let a=ac.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]=Y(d,a),X(b,a,d,c[4]?+c[4]:void 0,c[5]?+c[5]:void 0)}},ae=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,af=(a,b)=>{let c=ae.exec(a);return c?X(b,c[2],c[1]||"?",+c[3],c[4]?+c[4]:void 0):void 0},ag=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,ah=(a,b)=>{let c=ag.exec(a);return c?X(b,c[2],c[3]||"?",+c[1]):void 0},ai=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,aj=(a,b)=>{let c=ai.exec(a);return c?X(b,c[5],c[3]||c[4]||"?",+c[1],+c[2]):void 0},ak=/^\s*[-]{4,}$/,al=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,am=/^Promise\.(?:all|any)$/,an=/^index \d+$/,ao=(a,b)=>{let c=a.match(al);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]),am.test(e)&&an.test(h||"")&&(h="node:internal/promise"),{filename:h?decodeURI(h):void 0,module:void 0,function:e,lineno:ap(c[3]),colno:ap(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(ak))return{filename:a,platform:b}};function ap(a){return parseInt(a||"",10)||void 0}let aq=/\(error: (.*)\)/;function ar(a,b){return a.filename===b.filename&&a.function===b.function&&a.module===b.module&&a.lineno===b.lineno&&a.colno===b.colno}function as(a,b){let c=b.start;for(;c>0&&ar(a[c-1],a[c-1+b.length]);)c--;return b.start-c}function at(a,b){let c=b.start+b.length,d=c;for(;d<a.length&&ar(a[d],a[d-b.length]);)d++;return d-c}function au(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 av(){return aw("web:javascript",aa,ad)}function aw(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=aq.test(d)?d.replace(aq,"$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(!ar(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?as(a,c):0);for(let c of b)d-=at(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=as(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=at(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),au(e)}}class ax{match(a){return this.isDOMException(a)||this.isDOMError(a)}coerce(a,b){let c=t(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 z(a,"DOMException")}isDOMError(a){return z(a,"DOMError")}}a.s(["DOMExceptionCoercer",0,ax],51671);class ay{match(a){return!!z(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 t(a.message)&&a.message.length>0}_buildLocationStack(a){let b=a.lineno??0,c=a.colno??0;if(t(a.filename)&&0!==a.filename.length&&0!==b)return`Error
|
|
2
|
-
at ${a.filename}:${b}:${c}`}}a.s(["ErrorEventCoercer",0,ay],75368);let az=["fatal","error","warning","log","info","debug"];function aA(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 aB{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 t(b)&&!u(b)?b:"Error"}getValue(a){if("name"in a&&"string"==typeof a.name){let b=`'${a.name}' captured as exception`;return"message"in a&&"string"==typeof a.message&&(b+=` with message: '${a.message}'`),b}if("message"in a&&"string"==typeof a.message)return a.message;let b=this.getObjectClassName(a),c=aA(a);return`${b&&"Object"!==b?`'${b}'`:"Object"} captured as exception with keys: ${c}`}isSeverityLevel(a){return t(a)&&!u(a)&&az.indexOf(a)>=0}getStack(a){try{if(t(a.stacktrace)&&a.stacktrace.length>0)return a.stacktrace;return t(a.stack)&&a.stack.length>0?a.stack:void 0}catch{return}}getErrorPropertyFromObject(a){for(let b in a)if(Object.prototype.hasOwnProperty.call(a,b)){let c=a[b];if(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,aB],93874);class aC{match(a){return B(a)}coerce(a,b){let c=a.constructor.name;return{type:c,value:`${c} captured as exception with keys: ${aA(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["EventCoercer",0,aC],46980);class aD{match(a){return y(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,aD],28150);class aE{match(a){return z(a,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(a)}isCustomEventWrappingRejection(a){if(!B(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 y(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,aE],98140);let aF={MESSAGE:"$message",TIMESTAMP:"$timestamp"},aG=new Set([aF.MESSAGE,aF.TIMESTAMP]),aH={enabled:!0,max_bytes:32768};function aI(a){return a?{enabled:a.enabled??aH.enabled,max_bytes:function(a,b){if(!x(a)||1/0===a||-1/0===a)return b;let c=Math.floor(a);return c<0?b:c}(a.max_bytes,aH.max_bytes)}:{...aH}}function aJ(a){if(!a)return{sanitizedProperties:{},droppedKeys:[]};let b=[];return{sanitizedProperties:Object.keys(a).reduce((c,d)=>(aG.has(d)?b.push(d):c[d]=a[d],c),{}),droppedKeys:b}}class aK{constructor(a){this._entries=[],this._totalBytes=0,this._config=aI(a)}setConfig(a){this._config=aI(a),this._trimToMaxBytes()}add(a){let b=function(a){let b;try{b=m(a)}catch{return}try{let a=JSON.parse(b);if(!r(a))return;let c=a[aF.MESSAGE],d=a[aF.TIMESTAMP];if(!t(c)||0===c.trim().length||!t(d)&&!x(d))return;return{step:a,json:b}}catch{return}}(a);if(!b)return;let c=aL(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 aL(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,aH,"EXCEPTION_STEP_INTERNAL_FIELDS",0,aF,"ExceptionStepsBuffer",0,aK,"getUtf8ByteLength",0,aL,"resolveExceptionStepsConfig",0,aI,"stripReservedExceptionStepFields",0,aJ],97383),a.i(6762),a.s(["chromeStackLineParser",0,aa,"createDefaultStackParser",0,av,"createStackParser",0,aw,"geckoStackLineParser",0,ad,"nodeStackLineParser",0,ao,"opera10StackLineParser",0,ah,"opera11StackLineParser",0,aj,"reverseAndStripFrames",0,au,"winjsStackLineParser",0,af],64583),a.i(64583),a.i(51671);class aM{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,aM],10692),a.i(10692),a.i(75368);let aN=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class aO{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(aN);return d&&(b=d[1],c=d[2]),[b,c]}}a.s(["StringCoercer",0,aO],57802),a.i(57802),a.i(93874),a.i(46980),a.i(28150),a.i(98140),a.s(["DOMExceptionCoercer",0,ax,"ErrorCoercer",0,aM,"ErrorEventCoercer",0,ay,"EventCoercer",0,aC,"ObjectCoercer",0,aB,"PrimitiveCoercer",0,aD,"PromiseRejectionEventCoercer",0,aE,"StringCoercer",0,aO],54253),a.i(54253);class aP{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 aQ(){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,aP],98966),a.i(98966),a.i(97383),a.s(["getInjectedReleaseId",0,aQ],28861),a.i(28861),a.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,aH,"DOMExceptionCoercer",0,ax,"EXCEPTION_STEP_INTERNAL_FIELDS",0,aF,"ErrorCoercer",0,aM,"ErrorEventCoercer",0,ay,"ErrorPropertiesBuilder",0,U,"EventCoercer",0,aC,"ExceptionStepsBuffer",0,aK,"ObjectCoercer",0,aB,"PrimitiveCoercer",0,aD,"PromiseRejectionEventCoercer",0,aE,"ReduceableCache",0,aP,"StringCoercer",0,aO,"chromeStackLineParser",0,aa,"createDefaultStackParser",0,av,"createStackParser",0,aw,"geckoStackLineParser",0,ad,"getInjectedReleaseId",0,aQ,"getUtf8ByteLength",0,aL,"nodeStackLineParser",0,ao,"opera10StackLineParser",0,ah,"opera11StackLineParser",0,aj,"resolveExceptionStepsConfig",0,aI,"reverseAndStripFrames",0,au,"stripReservedExceptionStepFields",0,aJ,"winjsStackLineParser",0,af],60485);var aR=a.i(60485);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=()=>(f||(f=new aU)).generate();function aY(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 aZ(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,aW(),b]})}function a_(a,b){let c=aZ(b),d=a.get(c);return d?a1(d.value):null}function a0(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 a1(a){if(!a)return null;try{let b=JSON.parse(a);if(!b||"object"!=typeof b||!b.distinct_id)return null;let c=q(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 a2=a=>void 0===a?void 0:a.variant??a.enabled,a3=a=>{if("string"!=typeof a)return a;try{return JSON.parse(a)}catch{return a}},a4=["$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","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],a5=(a,b=[])=>{let c={},d=b=>{void 0!==a[b]&&(c[b]=a[b])};return a4.forEach(d),b.forEach(d),c};class a6{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 a7=a=>{throw M("NativeGzipValidationError",`Native gzip produced invalid output: ${a}`)},a8=async(a,b)=>{a.size<18&&a7("too-short");let c=new Uint8Array(await a.slice(0,10).arrayBuffer());c.length>=2&&31===c[0]&&139===c[1]&&8===c[2]||a7("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)&&a7("invalid-crc");let e=b.length>>>0;d.getUint32(4,!0)!==e&&a7("invalid-size")};async function a9(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 a8(g,b),g}catch(a){if(c?.rethrow)throw a;return b&&console.error("Failed to gzip compress data",a),null}}class ba{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 bb=(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=>bb(`${a} ${d}`,b,c)}};class bc{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 bd 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=M("AbortError","Response body read timed out");this.cancelResponseBody(a),this.responseBodyTextPromise=Promise.reject(a)}else{let a,b=new Promise((a,b)=>{this.responseBodyTimer=Q(()=>{this._bodyReadTimedOut=!0;let a=M("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 be extends Error{constructor(a){super("Network error while fetching PostHog",a instanceof Error?{cause:a}:{}),this.error=a,this.name="PostHogFetchNetworkError"}}async function bf(a){if(a instanceof bd){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 bg(a){return a instanceof be}function bh(a){if(a instanceof bd)return 502===a.status||504===a.status;if(!(a instanceof be))return!1;let b=a.error;return"ECONNREFUSED"!==(b?.code??b?.cause?.code)}function bi(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 bj(a){return"object"==typeof a&&a instanceof bd&&413===a.status}function bk(a){return a instanceof bd?408===a.status||429===a.status||a.status>=500:bg(a)}function bl(a){return null!==a&&"object"==typeof a&&!Array.isArray(a)}let bm="default";class bn{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new U([new aM,new aB,new aO,new aD],av())}getEvaluationRuntime(){}constructor(a,b={}){var c;this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new ba,this._events=new a6,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 bb(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's api key. The client will be disabled."),this.apiKey=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:bk},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(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=a5(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.apiKey}/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.apiKey,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:bh},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,a2(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?a3(c):void 0]}));return{...a,featureFlags:c,featureFlagPayloads:d}}{let b=a.featureFlags??{},c=Object.fromEntries(Object.entries(a.featureFlagPayloads||{}).map(([a,b])=>[a,a3(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 bd)return{type:"api_error",statusCode:a.status};if(a instanceof be){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=a2(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.apiKey}`,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 bm}persistedQueueKeyForRoute(a){return k.Queue}getActiveQueueRoutes(){return[bm]}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=Q(()=>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=bl(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=L(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:P(),uuid:L(b?.uuid,aW)};return(b?.disableGeoip??this.disableGeoip)&&(bl(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 bf(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(()=>S([b])).then(()=>(this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=d,this.flushPromise=d,this.flushPromises.add(d),this.addPendingPromise(d),S([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 a9(a,this.isDebug)}getBatchEndpointPath(a){return"/batch/"}async sendBatch(a,b,c=bm){let d={api_key:this.apiKey,batch:a.map(a=>{if(!a)return a;let b=this.normalizeTimestampForWire(a.timestamp);return b===a.timestamp?a:{...a,timestamp:b}}),sent_at:P()};this.historicalMigration&&(d.historical_migration=!0);let e=m(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=>!bj(a)&&bk(a)};try{await this.sendBatch(g,i,a)}catch(a){if(bj(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 be||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=bi(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.apiKey)}`,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.apiKey}`},...null!==g&&{"Content-Encoding":"gzip"}},body:h};try{return await this.fetchWithRetry(f,i,{type:"successful-write"},{retryCheck:a=>!bj(a)&&(!(a instanceof bd)||void 0===a.retryAfterMs)&&bk(a)}),{kind:"ok"}}catch(a){if(bj(a))return{kind:"too-large"};if(bk(a)){let b=a instanceof bd?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=bi(b.body?b.body:""),g={...this._retryOptions,...d},h=0;return await O(async()=>{let d,g,i;h++;let j=new AbortController,k=e??this.requestTimeout,l=Date.now()+k,m=new Promise((a,b)=>{d=Q(()=>{let a=M("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 be(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 be(a)}let e="no-cors"===b.mode,h="successful-write"===c.type?300:400;if(!e&&(g.status<200||g.status>=h))throw new bd(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 be(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 bd&&a.cancelResponseBody(),b}})}async _shutdown(a=3e4){await this._initPromise;let b=!1;if(this.clearFlushTimer(),!this.disabled)return R((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 bd||bg(a))))throw a;await bf(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 bo="[Circular]",bp="[Truncated]",bq="[Unserializable]";function br(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 bs(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=bq}Object.defineProperty(a,d,{value:c,enumerable:!0,writable:!0,configurable:!0})}return a}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let bt=Object.prototype.propertyIsEnumerable;function bu(a,b){try{return bv(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function bv(a,b,c,d){let e=[];for(let f in a)if(bt.call(a,f)){if(!f){b?.debug("Dropping an attribute with an empty key");continue}if(e.length>=1e3||c.remainingNodes<=0){b?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let g=a[f];if(v(g)||s(g))continue;e.push({key:br(f),value:function a(b,c,d,e){if(d.remainingNodes<=0)return{stringValue:bp};if(d.remainingNodes--,"[object Boolean]"===p.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:br(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:bo};if(e>=20)return{stringValue:bp};if(b instanceof Date){let a=Number.isFinite(b.getTime())?b.toISOString():String(b);return{stringValue:"string"==typeof a?br(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(q(b))return{arrayValue:{values:function(b,c,d,e){let f=[],g=Math.min(b.length,1e3),h=0;for(;h<g&&d.remainingNodes>0;h++)try{let g=h in b?b[h]:void 0;if(w(g))continue;f.push(a(g,c,d,e))}catch{f.push({stringValue:bq})}return b.length>h&&f.push({stringValue:bp}),f}(b,c,d,e+1)}};return{kvlistValue:{values:bv(b,c,d,e+1)}}}finally{d.ancestors.delete(b)}}return{stringValue:br(String(b))}}(g,b,c,d)})}catch{e.push({key:br(f),value:{stringValue:bq}})}}return e}function bw(a,b,c){return{...bs({},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 bx=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function by(a,b){let c=bs({},a),d={};for(let a of bx)Object.prototype.hasOwnProperty.call(c,a)&&(d[a]=c[a],delete c[a]);return[...bu(c,b),...bu(d,b)]}let bz={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 bA{constructor(a){this._onFire=a,this._firesAt=0}get pending(){return!!this._timer}arm(a){this.clear(),this._firesAt=Date.now()+a,this._timer=Q(()=>{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 bB(){return .75+.25*Math.random()*2}function bC(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 bD="0000000000000000",bE=bD+bD,bF=/^[0-9a-f]+$/;function bG(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 bH(a,b,c){return"string"==typeof a&&a.length===b&&a!==c&&bF.test(a)}let bI=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function bJ(a){let b=bK(a);return b&&{traceId:b.traceId,spanId:b.spanId,flags:1&parseInt(b.flags,16)?bM:bN}}function bK(a){if("string"!=typeof a)return;let b=bI.exec(a.trim());if(!b)return;let[,c,d,e,f,g]=b;if("ff"!==c&&("00"!==c||!g)&&bH(d,32,bE)&&bH(e,16,bD))return{version:c,traceId:d,spanId:e,flags:f}}function bL(a){return Array.isArray(a)&&1===a.length?a[0]:a}let bM="01",bN="00";function bO(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 bP=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function bQ(a){return String(a)+"000000"}function bR(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 bS{constructor(a,b,c){this._instance=a,this._config=b,this._logger=c,this._series=new Map,this._flushTimer=new bA(()=>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 bc,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=bR(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=bJ(this._instance.getActiveSpan?.()?.traceparent());if(a&&a.flags===bM)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(bP.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,bP)]+=1}}}_runBeforeSend(a){let b=this._config.beforeSend;if(!b)return a;let c=q(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(bC(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=bB()):(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=bw(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),d=this._instance.getLibraryId(),e=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:by(c)},scopeMetrics:[{scope:{name:d,version:e},metrics:b}]}]}}_buildMetrics(a){let b=bQ(Date.now()),c=new Map;for(let e of a.values()){var d;let a=bR(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=bu(e.attributes??{},this._logger),h=bQ(e.windowStartMs),i=(d=e.exemplar)?{exemplars:[{filteredAttributes:[],timeUnixNano:bQ(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:bP,...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 bT="unknown";function bU(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 "${bT}"`),bT)}function bV(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 bW(a,b,c,d){let e=bV(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 bX(){let a=globalThis.performance;return"function"==typeof a?.now?a.now():void 0}class bY{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??bM,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:bX(),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=bX();if(void 0!==a)return this._startTime+Math.max(0,a-this._startMono)}return Date.now()}_mutable(a){return!this._ended||(this._logger?.debug(`Ignoring ${a} on a span that has already ended`),!1)}_writeAttribute(a,b){if(w(b)){a in this._attributes&&!this._autoKeys.has(a)&&this._userAttributeCount--,delete this._attributes[a];return}if(!this._autoKeys.has(a)&&!(a in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[a]=b5(b,this._maxAttributeValueLength)}setAttribute(a,b){return this._mutable("setAttribute")&&this._writeAttribute(a,b),this}setAttributes(a){if(this._mutable("setAttributes")){let b=bs({},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&&b6(b,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:bU(a,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:bW(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:b4(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}=b8(a);return this.addEvent(bZ,{"exception.type":b,"exception.message":c,...d&&{"exception.stacktrace":d}}),this.setStatus("error",c)}updateName(a){return this._mutable("updateName")&&(this._name=bU(a,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return function(a,b,c=bM){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=bW(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 bZ="exception";function b$(a){return"number"!=typeof a||!Number.isFinite(a)||a<=0?0:Math.min(Math.floor(a),0xffffffff)}class b_{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 b0=new b_;class b1 extends b_{constructor(a,b){super(),this._traceparent=a,this._tracestate=b}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}}function b2(a,b){var c;let d=bL(a?.parent)??b,e=bK(c="string"==typeof d||null==d?d:b3(d,"traceparent"))&&c.trim();return e?new b1(e,bO("string"==typeof d||null==d?a?.tracestate:b3(d,"tracestate"))):b0}function b3(a,b){try{let c=a[b];return"function"==typeof c?c.call(a):void 0}catch{return}}function b4(a,b){return a.length>b?a.slice(0,b):a}function b5(a,b){return function a(b,c,d,e){if(null===b||"object"!=typeof b)return w(b)||d.remainingNodes<=0?b:(d.remainingNodes--,"string"==typeof b?b4(b,c):b);if(d.ancestors.has(b))return bo;if(d.remainingNodes<=0||e>=20)return b;d.remainingNodes--,d.ancestors.add(b);try{if(b instanceof Date)return b;let f=function(a){try{let b=a.toJSON;if("function"==typeof b)return{selfDescribed:!0,value:b.call(a)}}catch{}return{selfDescribed:!1}}(b);if(f.selfDescribed)return w(f.value)?String(f.value):a(f.value,c,d,e+1);if(q(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(bq)}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=bq}f&&!w(i)&&h++,Object.defineProperty(g,f,{value:i,enumerable:!0,writable:!0,configurable:!0})}return g}catch{return b}finally{d.ancestors.delete(b)}}(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}function b6(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=b5(a[h],c)}catch{d=bq}w(d)||(f++,Object.defineProperty(e,h,{value:d,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:e,dropped:g}}function b7(a,b,c){return b===b0?c(b):a.with(b,()=>c(b))}function b8(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 b9={internal:1,server:2,client:3,producer:4,consumer:5},ca={ok:1,error:2};function cb(a){if("string"==typeof a)return br(a);try{return br(String(a))}catch{return bq}}function cc(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 cd(){return bX()??Date.now()}function ce(a){try{return a instanceof bY}catch{return!1}}function cf(a,b){let c=bJ(a);if(c)return{traceId:c.traceId,parentSpanId:c.spanId,traceState:bO(b),traceFlags:c.flags,isRemote:!0}}function cg(a,b,c){a[b]!==c&&(a[b]=c)}class ch{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 bA(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter=new bc,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 b2(b,this._contextManager.active());let f=bL(b?.parent);if(f&&"string"!=typeof f&&!ce(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"),b2(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`),b2(b,this._contextManager.active());let h=Date.now(),i=(c=b?.startTime,d=this._logger,void 0===(e=bV(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=bG(8);this._liveSpans.set(j,cd());let k=this._autoContextAttributes();return new bY({traceId:g?.traceId??bG(16),spanId:j,parentSpanId:g?.parentSpanId,traceState:g?.traceState,traceFlags:g?.traceFlags,parentIsRemote:g?.isRemote,name:bU(a,"Span name",this._config.maxAttributeValueLength,this._logger),kind:b?.kind??"internal",attributes:bs({...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===bV(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=b7(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=cf(a,b?.tracestate);return c||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),c}if(ce(a))return a.childContext();let c=this._contextManager.active();return ce(c)?c.childContext():c instanceof b1?cf(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 bY))return;let{type:c,message:d,stack:e}=b8(b);a.addEvent("exception",{"exception.type":c,"exception.message":d,...e&&{"exception.stacktrace":e}}),a.statusIsExplicitlyOk||a.setStatus("error",d)}_evictAgedSpans(){let a=cd()-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=bU(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=bV(j.startTime)??d.startTime,j.endTime=(l=bV(j.endTime)??d.endTime,m=j.startTime,l<m?m:l);let a=[];for(let b of j.events)try{a.push({...b,name:bU(b.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:bW(b.timestamp,j.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return j.events=a,!function(a,b,c,d,e,f,g=[]){let h=0,i=0,j={};for(let d of function(a,b){if(!b.length)return Object.keys(a);let c=b.filter(b=>Object.prototype.propertyIsEnumerable.call(a,b)),d=new Set(c);return[...c,...Object.keys(a).filter(a=>!d.has(a))]}(a.attributes,g)){let e=a.attributes[d];if(!w(e)){if(!b.has(d)){if(h>=c){i++;continue}h++}Object.defineProperty(j,d,{value:b5(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=b6(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:b4(function(a){try{return"string"==typeof a?a:String(a)}catch{return bq}}(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{cg(a,"traceId",b.traceId),cg(a,"spanId",b.spanId),cg(a,"parentSpanId",b.parentSpanId),cg(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:cb(a.name),kind:(c=a.kind)&&Object.prototype.hasOwnProperty.call(b9,c)?b9[c]:b9.internal,startTimeUnixNano:cc(a.startTime),endTimeUnixNano:cc(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=cb(a.traceState));let f=bu(a.attributes,b);f.length&&(e.attributes=f),a.events.length&&(e.events=a.events.map(a=>(function(a,b){let c={name:cb(a.name),timeUnixNano:cc(a.timestamp)};if(a.attributes){let d=bu(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:ca[a.status.code],...a.status.message&&{message:cb(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]=b5(a[c],b);return a}((a=this._config,bw(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=cd()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),o=await this._instance._sendTracesBatch((b=this._logger,{resourceSpans:[{resource:{attributes:by(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=bB(),this._headBatchSize=k,n&&(this._headBatchFailures++,this._headBatchChargeableAt=cd()+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(bC(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}}var ci=a.i(2157),cj=a.i(12714),ck=a.i(50227),cl=a.i(1457);let cm=new aR.ReduceableCache(25),cn=new aR.ReduceableCache(20);async function co(a,b=cj.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,ck.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=cs(a,d);if(void 0===f||cn.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=ct(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=ct(c)),b++}return e}(g);if(h.every(a=>(function(a,b){let c=cm.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}(cm,f,{});i.push(cq(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=cs(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=cu(a);d<a;d++){let a=c[d];if(void 0===a)return void cr(b);b.pre_context.push(a)}if(void 0===c[a])return cr(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,cm,d),cm.reduce(),a}async function cp(a,b,c){let d,e=!1;try{d=await b(a,ci.constants.O_RDONLY|ci.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 cq(a,b,c,d,e,f){let g=await cp(a,e,f);return void 0===g?void cn.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{cn.set(d,1),i();return}try{f=(0,cl.createInterface)({input:e})}catch{cn.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(){cn.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 cr(a){delete a.pre_context,delete a.context_line,delete a.post_context}function cs(a,b){return(0,ck.isAbsolute)(a)?JSON.stringify([null,a]):void 0===b?void 0:JSON.stringify([b,a])}function ct(a){return[cu(a),a+7]}function cu(a){return Math.max(1,a-7)}class cv{active(){return this._active}with(a,b){let c=this._active;this._active=a;try{return b()}finally{this._active=c}}}let cw=["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"],cx=new Map,cy=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=cx.get(c);if(void 0!==d)return d;let e=a.toLowerCase(),f=cw.concat(b).some(a=>-1!==e.indexOf(a.toLowerCase()));return cx.size>=256&&cx.clear(),cx.set(c,f),f};function cz(a,b){return"number"==typeof a&&Number.isInteger(a)&&a>=1?a:b}let cA=["service.name","service.version","deployment.environment"],cB={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};a.s(["FeatureFlagError",0,cB],46539);class cC{constructor(a){this._host=a.host,this._distinctId=a.distinctId,this._groups=a.groups,this._disableGeoip=a.disableGeoip,this._flags=a.flags,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)}_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 cC({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(cB.ERRORS_WHILE_COMPUTING),this._quotaLimited&&e.push(cB.QUOTA_LIMITED),void 0===b&&e.push(cB.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 cD=["is_not","is_set"];class cE extends Error{constructor(a){super(a),this.name=this.constructor.name,Object.setPrototypeOf(this,cE.prototype)}}function cF(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(!cF(b in a?a[b]:null))return!1;return!0}function cG(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(!cG(b in a?a[b]:null))return!1;return!0}function cH(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 cE("Cannot stringify an unpaired surrogate like the flags service");b++}else if(c>=56320&&c<=57343)throw new cE("Cannot stringify an unpaired surrogate like the flags service")}}function cI(a,b=new Set){if(null!==a&&"boolean"!=typeof a){if("string"==typeof a)return void cH(a);if("number"==typeof a){if(!Number.isFinite(a))throw new cE(`Cannot represent non-finite number ${a} like the flags service`);return}if(Array.isArray(a)){if(b.has(a))throw new cE("Cannot represent a circular array during local evaluation");b.add(a);try{for(let c=0;c<a.length;c++)c in a&&cI(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 cE("Cannot represent a non-JSON object like the flags service");if(b.has(a))throw new cE("Cannot represent a circular object during local evaluation");b.add(a);try{for(let c of Object.keys(a))cH(c),cI(a[c],b)}finally{b.delete(a)}return}throw new cE(`Cannot represent ${typeof a} like the flags service`)}}function cJ(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 cK(a){return"string"==typeof a?(cH(a),a):function a(b,c=new Set){if(null===b)return"null";if("string"==typeof b)return cH(b),JSON.stringify(b);if("boolean"==typeof b)return b?"true":"false";if("number"==typeof b){if(!Number.isFinite(b))throw new cE(`Cannot stringify non-finite number ${b} like the flags service`);if(Number.isInteger(b))throw new cE(`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 cE("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 cE("Cannot stringify a non-JSON object like the flags service");if(c.has(b))throw new cE("Cannot stringify a circular object during local evaluation");c.add(b);try{let d=Object.keys(b);return d.forEach(cH),`{${d.sort(cJ).map(d=>`${JSON.stringify(d)}:${a(b[d],c)}`).join(",")}}`}finally{c.delete(b)}}throw new cE(`Cannot stringify ${typeof b} like the flags service`)}(a)}function cL(a){try{return new RegExp(a),!0}catch{return!1}}function cM(a){return String(a).replace(/[A-Z]/g,a=>a.toLowerCase())}function cN(a,b,c){if(!/^\d+$/.test(a)||"strict"===c&&a.length>1&&"0"===a[0])throw new cE(`Invalid semver: ${b}`);return parseInt(a,10)}function cO(a,b="strict"){let c=String(a).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!c||c.startsWith("."))throw new cE(`Invalid semver: ${a}`);let d=c.split("."),e=c=>void 0===c||""===c?0:cN(c,a,b);return[e(d[0]),e(d[1]),e(d[2])]}function cP(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 cQ(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 cE(`${a} is in an invalid date format`)}throw new cE(`The date provided ${a} must be a string, number, or date object`)}async function cR(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 cS(a,b,c="",d="."){return parseInt((await cR(`${a}${d}${b}${c}`)).slice(0,15),16)/0x1000000000000000}async function cT(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 cS("holdout",b,"","-")>d/100))return`holdout-${a.id}`}function cU(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 cV(a,b,c){let d=await cS(a,b,"variant");return cU(c).find(a=>d>=a.valueMin&&d<a.valueMax)?.key}function cW(a){return"client"===a||"server"===a?a:"all"}class cX extends Error{constructor(a){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=a,Object.setPrototypeOf(this,cX.prototype)}}class cY extends Error{constructor(a){super(a),this.name=cY.name,Error.captureStackTrace(this,cY),Object.setPrototypeOf(this,cY.prototype)}}class cZ{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.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()}withEvaluationSnapshot(a){return a.definitions?a:{...a,evaluationCache:{},definitions:{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}}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 cY||b instanceof cE?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=0==this.featureFlags.length,f=b?b.map(a=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,g=this.withEvaluationSnapshot({...a,definitions:void 0});return await Promise.all(f.map(async a=>{try{let{value:b,payload:e}=await this.computeFlagAndPayloadLocally(a,g,{skipLoadCheck:!0});c[a.key]=b,e&&(d[a.key]=e)}catch(b){b instanceof cY||b instanceof cE?this.logMsgIfDebug(()=>console.debug(`${b.name} when computing flag locally: ${a.key}: ${b.message}`)):b instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${a.key}: ${b}`)),e=!0}})),{response:c,payloads:d,fallbackToFlags:e}}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:a3(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 cE("Flag has experience continuity enabled");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 cE("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 cE(`Can't compute feature flag: ${a.key} without $device_id`);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 cE("Feature flags not available for dependency evaluation");if(!("dependency_chain"in a))throw new cE(`Flag dependency property for '${e}' is missing required 'dependency_chain' field`);let f=a.dependency_chain;if(!Array.isArray(f))throw new cE(`Flag dependency property for '${e}' has an invalid 'dependency_chain' (expected array, got ${typeof f})`);if(0===f.length)throw new cE(`Circular dependency detected for flag '${e}' (empty dependency chain)`);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 new cE(`Error evaluating flag dependency '${a}' for flag '${e}': ${b}`)}else d[a]=!1;else if(c.definitions.filteredOutFlagKeys.has(a))d[a]=!1;else throw new cE(`Missing flag dependency '${a}' for flag '${e}'`)}if(null==d[a])throw new cE(`Dependency '${a}' could not be evaluated`)}let g=d[e];return this.flagEvaluatesToExpectedValue(a.value,g)}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;d=this.withEvaluationSnapshot(d);let f=a.filters||{},g=await cT(f.holdout,b);if(void 0!==g)return g;let h=f.groups||[],i=f.aggregation_group_type_index,j=f.early_exit??!1,{groups:k,groupProperties:l}=d,m=!1;for(let g of h)try{let h=void 0!==g.aggregation_group_type_index?g.aggregation_group_type_index:i,n=c,o=b;if(h!==i&&null!=h){let b=d.definitions.groupTypeMapping[String(h)];if(!b||!(b in k)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${a.key}': group type index ${h} not available`));continue}if(!(b in l)){m=!0;continue}n=l[b],o=k[b]}let p=await this.isConditionMatch(a,o,g,n,d);if("match"===p){let b=g.variant,c=f.multivariate?.variants||[];e=b&&c.some(a=>a.key===b)?b:await this.getMatchingVariant(a,o)||!0;break}if(j&&"out_of_rollout_bound"===p){if(m)break;return!1}}catch(a){if(a instanceof cY)throw a;if(a instanceof cE)m=!0;else throw a}if(void 0!==e)return e;if(m)throw new cE("Can't determine if feature flag is enabled or not with given properties");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){for(let a of c.properties){let b=a.type,c=!1;if("cohort"===b){let b=await c_(a,d,f.cohorts,this.debugMode,a=>this.evaluateFlagDependency(a,d,e),f.propertyMatchingVersion);c="not_in"===a.operator?!b:b}else c="flag"===b?await this.evaluateFlagDependency(a,d,e):c$(a,d,h,f.propertyMatchingVersion);if(!c)return"no_match"}if(void 0==g)return"match"}return void 0!=g&&await cS(a.key,b)>g/100?"out_of_rollout_bound":"match"}async getMatchingVariant(a,b){return cV(a.key,b,a.filters?.multivariate?.variants||[])}variantLookupTable(a){return cU(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?cW(b.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(a){return this.featureFlags.filter(b=>{var c;return(c=cW(b.evaluation_runtime))===a||"all"===c||"all"===a}).map(a=>a.key)}updateFlagState(a){let b=this.filterFlagsByEvaluationContexts(a.flags);this.featureFlags=b,this.featureFlagsByKey=b.reduce((a,b)=>(a[b.key]=b,a),{});let c=new Set(b.map(a=>a.key));this.filteredOutFlagKeys=new Set(a.flags.filter(a=>!c.has(a.key)).map(a=>a.key)),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)}warnAboutExperienceContinuityFlags(a){if(this.strictLocalEvaluation)return;let b=a.filter(a=>a.ensure_experience_continuity);b.length>0&&console.warn(`[PostHog] You are using local evaluation but ${b.length} flag(s) have experience continuity enabled: ${b.map(a=>a.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(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.warnAboutExperienceContinuityFlags(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{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 cX(`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 cX(`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 cX(`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.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(a){a instanceof cX&&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(){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=Q(()=>{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 R(b,a,()=>{throw Error(`Cache shutdown timeout after ${a}ms`)})}catch(a){this.onError?.(Error(`Error during cache shutdown: ${a}`))}}}function c$(a,b,c,d){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 cE(`Property ${d} not found in propertyValues`);let h=b[d];if(void 0===h)return c.warnFunction?.(`Property ${d} cannot have a value of undefined with the ${f} operator`),"is_not"===f;if(null===h&&!cD.includes(f)&&"exact"!==f&&"is_not"!==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&&cF(a)||Array.isArray(a)&&0===a.length)return cI(b),cG(a)===cG(b);if(2===c.propertyMatchingVersion&&"number"==typeof b&&cF(a))return cI(b),!1;if(Array.isArray(a)){let c=cK(b).toLowerCase();return a.some(a=>cK(a).toLowerCase()===c)}return cK(a).toLowerCase()===cK(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}`)};switch(f){case"exact":return i(e,h);case"is_not":return!i(e,h);case"is_set":return!0;case"icontains":return cM(h).includes(cM(e));case"not_icontains":return!cM(h).includes(cM(e));case"starts_with":return cM(h).startsWith(cM(e));case"not_starts_with":return!cM(h).startsWith(cM(e));case"ends_with":return cM(h).endsWith(cM(e));case"not_ends_with":return!cM(h).endsWith(cM(e));case"regex":return cL(String(e))&&null!==String(h).match(String(e));case"not_regex":return cL(String(e))&&null===String(h).match(String(e));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":{if("boolean"==typeof e)throw new cE("Date operations cannot be performed on boolean values");let a=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(e));null==a&&(a=cQ(e));let b=cQ(h);return"is_date_before"===f?b<a:b>a}case"semver_eq":return 0===cP(cO(String(h),g),cO(String(e),g));case"semver_neq":return 0!==cP(cO(String(h),g),cO(String(e),g));case"semver_gt":return cP(cO(String(h),g),cO(String(e),g))>0;case"semver_gte":return cP(cO(String(h),g),cO(String(e),g))>=0;case"semver_lt":return 0>cP(cO(String(h),g),cO(String(e),g));case"semver_lte":return 0>=cP(cO(String(h),g),cO(String(e),g));case"semver_tilde":{let a,b=cO(String(h),g),{lower:c,upper:d}={lower:[(a=cO(String(e),g))[0],a[1],a[2]],upper:[a[0],a[1]+1,0]};return cP(b,c)>=0&&0>cP(b,d)}case"semver_caret":{let a=cO(String(h),g),{lower:b,upper:c}=function(a,b){let[c,d,e]=cO(a,b);return{lower:[c,d,e],upper:c>0?[c+1,0,0]:d>0?[0,d+1,0]:[0,0,e+1]}}(String(e),g);return cP(a,b)>=0&&0>cP(a,c)}case"semver_wildcard":{let a=cO(String(h),g),{lower:b,upper:c}=function(a,b){let c=String(a).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!c)throw new cE(`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 cN(c,a,b)}catch{}throw new cE(`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]}}(String(e),g);return cP(a,b)>=0&&0>cP(a,c)}default:throw new cE(`Unknown operator: ${f}`)}}(a,b,{warnFunction:c,propertyMatchingVersion:d})}async function c_(a,b,c,d=!1,e,f){let g=String(a.value);if(!(g in c))throw new cY(`cohort ${g} not found in local cohorts - likely a static cohort that requires server evaluation`);return c0(c[g],b,c,d,e,f)}async function c0(a,b,c,d=!1,e,f){if(!a)return!0;let g=a.type,h=a.values;if(!h||0===h.length)return!0;let i=!1;if("values"in h[0]){for(let a of h)try{let h=await c0(a,b,c,d,e,f);if("AND"===g){if(!h)return!1}else if(h)return!0}catch(b){if(b instanceof cY)throw b;if(b instanceof cE)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),i=!0;else throw b}if(i)throw new cE("Can't match cohort without a given cohort property value");return"AND"===g}for(let a of h)try{let h;if("cohort"===a.type)h=await c_(a,b,c,d,e,f);else if("flag"===a.type){if(!e)throw new cE(`Flag dependency '${a.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);h=await e(a)}else h=c$(a,b,void 0,f);let i=a.negation||!1;if("AND"===g){if(!h&&!i||h&&i)return!1}else if(h&&!i||!h&&i)return!0}catch(b){if(b instanceof cY)throw b;if(b instanceof cE)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),i=!0;else throw b}if(i)throw new cE("can't match cohort without a given cohort property value");return"AND"===g}let c1=["--unhandled-rejections","--unhandled_rejections"],c2=new Set(["throw","strict","warn","warn-with-error-code","none"]),c3=[...globalThis.process?.execArgv??[]],c4=globalThis.process?.env?.NODE_OPTIONS;function c5(a){let b;for(let c=0;c<a.length;c++){let d=a[c],e=c1.find(a=>d===a||d.startsWith(`${a}=`));if(!e)continue;let f=d===e?a[++c]:d.slice(e.length+1);c2.has(f)&&(b=f)}return b}let c6=function(a=c3,b=c4){return c5(a)??c5(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 c7(a,b,c){a(b,{mechanism:{type:"unhandledRejection"===c?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function c8(a,b,c,d,e){if(b>c&&(d.warn("min cannot be greater than max."),b=c),x(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),c8(e??c,b,c,d)}class c9{constructor(a){this._buckets={},this._onBucketRateLimited=a._onBucketRateLimited,this._bucketSize=c8(a.bucketSize,0,100,a._logger),this._refillRate=c8(a.refillRate,0,this._bucketSize,a._logger),this._refillInterval=c8(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 da=aR;let db=class b{constructor(a,b,c){this.client=a,this._exceptionAutocaptureEnabled=b.enableExceptionAutocapture||!1,this._logger=c,this._rateLimiter=new c9({...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 r(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=da.getInjectedReleaseId();return h&&(f.$release_id=h),{event:"$exception",distinctId:d,properties:{...g,...f},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(!function(b,c,d=c6){let e=globalThis.process;if(e){let f;if("strict"===d)return e.on("uncaughtExceptionMonitor",(a,c)=>c7(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;c7(b,d,e),f||0!==g||(f=!0,c(d))},{_posthogErrorHandler:!0})))}}(this.onException.bind(this),this.onFatalError.bind(this)),function(a,b=c6){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()}};class dc{getProperty(a){return this._memoryStorage[a]}setProperty(a,b){this._memoryStorage[a]=null!==b?b:void 0}constructor(){this._memoryStorage={}}}let dd="analytics";class de extends Error{constructor({requestId:a,drops:b,retryExhausted:c,cause:d}){super(de.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 df(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 dg=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:df},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:df},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:df},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(a){return"string"==typeof a?a:void 0}}],dh=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function di(a,b,c){void 0===c||b in a||(a[b]=c)}function dj(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 dg)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 dh)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,di(c,"$set",a.$set),di(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 dk=new Set([408,500,502,503,504]);class dl{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=>Q(b,a))),this.generateRequestId=b.generateRequestId??aW,this.compress=b.compress??a9}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(dj)};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=m({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&&dk.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 de({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=Q(()=>{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 de({requestId:a,drops:b,retryExhausted:c.map(a=>a.uuid),cause:d}))}surfacePartialDrops(a,b){b.length>0&&this.onError(new de({requestId:a,drops:b,retryExhausted:[]}))}async cancelBody(a){try{await a.body?.cancel()}catch{}}}let dm="ai-capture",dn="/i/v0/ai/batch/",dp=new TextEncoder;function dq(a){return dp.encode(m(a)).length}let dr=new Set;function ds(a,b){dr.has(a)||(dr.add(a),console.warn(`[PostHog] ${b}`))}class dt extends bn{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 dc,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.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){if(g.personalApiKey.includes("phc_"))throw Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');!1!==g.enableLocalEvaluation&&(this.featureFlagsPoller=new cZ({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 db(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:S([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=Q(()=>{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":dd}persistedQueueKeyForRoute(a){return a===dm?k.AiCaptureQueue:"ai"===a?k.AiQueue:k.Queue}getActiveQueueRoutes(){let a="v1"===this.captureMode?[dd,"ai"]:[dd];return this._aiCaptureRouteActive&&a.push(dm),a}getBatchEndpointPath(a){return a===dm?dn:super.getBatchEndpointPath(a)}async sendBatch(a,b,c=dd){if(c===dm)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=dq(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 ${dn}, 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,dm)}catch(d){if(!bj(d))throw d;if(1===a.length){let[b]=a,c="string"==typeof b.event?b.event:"unknown",d=`Event ${c} (${dq(b)} bytes) was rejected with 413 by ${dn} 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 dl({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.55.1"}get metrics(){var a;let b;return this._metrics||(this._metrics=new bS(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 cv}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 ch(this,(a=this.options.traces,b=this.hostResourceAttributes(),c=this._logger,d=bs({...b},function(a){if(!(!a||"object"!=typeof a||Array.isArray(a)))try{if(cA.every(b=>!(b in a)||"string"==typeof a[b]))return a;let b={...a};for(let a of cA)a in b&&"string"!=typeof b[a]&&delete b[a];return b}catch{return}}(a?.resourceAttributes)),e=cz(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:cz(a?.maxAttributesPerSpan,128),maxEventsPerSpan:cz(a?.maxEventsPerSpan,128),maxAttributesPerEvent:128,maxAttributeValueLength:cz(a?.maxAttributeValueLength,8192),flushIntervalMs:cz(a?.flushIntervalMs,5e3),maxExportBatchSize:e,maxQueueSize:Math.max(cz(a?.maxQueueSize,2048),e),maxLiveSpans:cz(a?.maxLiveSpans,1e4),maxSpanAgeMs:cz(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)??b2(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):b7(this._spanContextManager,b2(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=L(a.uuid,aW);return this._sendPreparedAiEvent({...a,uuid:b},!1),b}async captureAiImmediate(a){if(this.disabled)return;let b=L(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,dm)}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 cY||b instanceof cE)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=cB.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===b.minimalFlagCalledEvents,f=b.requestId,g=b.evaluatedAt;let c=[];b.errorsWhileComputingFlags&&c.push(cB.ERRORS_WHILE_COMPUTING),b.quotaLimited?.includes("feature_flags")&&c.push(cB.QUOTA_LIMITED);let d=b.flags[a];if(void 0===d)c.push(cB.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){ds("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(ds("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){ds("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 cC({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new cC({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,flags:{}});let{groups:g,disableGeoip:h}=f||{},i=f?.flagKeys??void 0;if(i?.length===0)return new cC({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];return new cC({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:p,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 R(this._metrics.flush().catch(()=>{}),Math.max(0,b-Date.now())),this._metrics.reset()),this._traces&&(await R(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=Q(()=>{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(z(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(!db.isPreviouslyCapturedError(a)){let f=Error("PostHog syntheticException");this.addPendingPromise(db.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(!db.isPreviouslyCapturedError(a)){let e=Error("PostHog syntheticException");return this.addPendingPromise(db.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||{}};n||(n=aW(),o.$process_person_profile=!1),m&&l?.sessionId&&!o.$session_id&&(o.$session_id=l.sessionId);let p=this._shouldSendMinimalFlagCalledEvent(d,o)?a5(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){ds("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&&cy(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 du=a.i(78500);class dv{constructor(){this.storage=new du.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 dw{active(){return this._storage.getStore()}with(a,b){return this._storage.run(a,b)}constructor(){this._storage=new du.AsyncLocalStorage}}var dx=a.i(27028);let dy=(0,a.i(12057).promisify)(dx.gzip);async function dz(a,b=!0){try{let b=await dy(a);return new Uint8Array(b)}catch(a){return b&&console.error("Failed to gzip compress data",a),null}}var dA=a.i(60526),da=aR;let dB="posthog-node";function dC(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[dE.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=da.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 dD(a,b){let c=dC(a,b);return{name:dB,processEvent:a=>c(a)}}class dE{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(a,b,c,d,e){this.name=dB,this.name=dB,this.setupOnce=function(f,g){f(dC(a,{organization:b,projectId:g()?.getClient()?.getDsn()?.projectId,prefix:c,severityAllowList:d,sendExceptionsToPostHog:e??!0}))}}}a.s(["PostHogSentryIntegration",0,dE,"createEventProcessor",0,dC,"sentryIntegration",0,dD],9318);let dF=/[\x00-\x1f\x7f-\x9f]/g;function dG(a,b,c){null!=c&&""!==c&&(a[b]=c)}function dH(a){return Array.isArray(a)?a[0]:a}function dI(a){if(Array.isArray(a)){for(let b of a){let a=dI(b);if(void 0!==a)return a}return}if("string"!=typeof a)return;let b=a.replace(dF,"").trim();if(b)return b.length>1e3?b.slice(0,1e3):b}function dJ(a,b){var c,d;let e,{sessionId:f,distinctId:g}=function(a){if(!a)return{};let b=dI(a["x-posthog-session-id"]),c=dI(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 dG(h,"$current_url",(c=b.originalUrl||b.url,i?N(c):c)),dG(h,"$request_method",b.method),dG(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?N(e):e)),dG(h,"$user_agent",dH(b.headers["user-agent"])),dG(h,"$ip",function(a){let b=dH(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 dK(a,b){var c;b.use((c=a,(a,b,d)=>{c.withContext(dJ(c,a),()=>d())}))}function dL(a,b){var c;b.use((c=a,(a,b,d,e)=>{if(db.isPreviouslyCapturedError(a))return void e(a);let f=dJ(c,b),g=Error("Synthetic exception"),h={...void 0!==f.sessionId?{$session_id:f.sessionId}:{},...f.properties||{}};c.addPendingPromise(Promise.all([db.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,dL,"setupExpressRequestContext",0,dK],40602),a.i(9318),a.i(40602),a.i(46539),a.s(["FeatureFlagError",0,l,"FeatureFlagEvaluations",0,cC,"PostHogSentryIntegration",0,dE,"cookieStateToProperties",0,a0,"cookieStoreFromHeader",0,aY,"createEventProcessor",0,dC,"getPostHogCookieName",0,aZ,"parsePostHogCookie",0,a1,"readPostHogCookie",0,a_,"sentryIntegration",0,dD,"serializePostHogCookie",0,a$,"setupExpressErrorHandler",0,dL,"setupExpressRequestContext",0,dK,"uuidv7",0,aW],80456),a.i(80456),a.s(["FeatureFlagError",0,l,"FeatureFlagEvaluations",0,cC,"PostHog",0,class extends dt{getLibraryId(){return"posthog-node"}compressPayload(a){return dz(a,this.isDebug)}initializeContext(){return new dv}initializeSpanContextManager(){return new dw}hostResourceAttributes(){return function(){var a,b;let c,d,e;try{c=(0,dA.platform)(),d=(0,dA.release)()}catch{}return a=c,b=d,{...(e=function(a){if(a)return Object.prototype.hasOwnProperty.call(bz,a)?bz[a]:a}(a))?{"os.name":e}:{},...b?{"os.version":b}:{}}}()}createErrorPropertiesBuilder(){let a;return new aR.ErrorPropertiesBuilder([new aR.EventCoercer,new aR.ErrorCoercer,new aR.ObjectCoercer,new aR.StringCoercer,new aR.PrimitiveCoercer],aR.createStackParser("node:javascript",aR.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=>co(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,dE,"cookieStateToProperties",0,a0,"cookieStoreFromHeader",0,aY,"createEventProcessor",0,dC,"getPostHogCookieName",0,aZ,"parsePostHogCookie",0,a1,"readPostHogCookie",0,a_,"sentryIntegration",0,dD,"serializePostHogCookie",0,a$,"setupExpressErrorHandler",0,dL,"setupExpressRequestContext",0,dK,"uuidv7",0,aW],74493)}];
|
|
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],6762);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(6762),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)}];
|
|
3
3
|
|
|
4
4
|
//# sourceMappingURL=node_modules_posthog-node_dist_entrypoints_index_node_mjs_11bnuznb72p7z._.js.map
|