failproofai 1.0.3 → 1.0.4-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/.grok/hooks/failproofai.json +172 -0
- package/.next/standalone/.next/BUILD_ID +1 -1
- package/.next/standalone/.next/build-manifest.json +5 -5
- package/.next/standalone/.next/prerender-manifest.json +4 -4
- 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.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 +7 -7
- package/.next/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +6 -6
- package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +7 -7
- 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.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 +15 -15
- package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +15 -15
- package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +14 -14
- package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/api/audit/invite/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/audit/run/route.js +4 -4
- 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.nft.json +1 -1
- 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.nft.json +1 -1
- 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.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/download/[project]/[session]/route.js +1 -1
- 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.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 +15 -15
- package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +14 -14
- package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +15 -15
- package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- 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.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 +1 -1
- 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 +3 -3
- 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 +2 -2
- 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 +1 -1
- 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 +4 -4
- package/.next/standalone/.next/server/app/settings/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/settings/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/chunks/{[externals]__0u3wrvq._.js → [externals]__0_gzk8q._.js} +1 -1
- package/.next/standalone/.next/server/chunks/{[externals]__0-9ti7z._.js → [externals]__1zndo1i._.js} +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__07hor7h._.js +5 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__08dchfu._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0cuho4x._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0elsuli._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0gnj_qa._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0ljuzm_._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0o07qi9._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0w23bpg._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0x5c7sh._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0yik9_w._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1adacul._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1jg6s9m._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1s6qci9._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1xfm05z._.js +3 -0
- package/.next/standalone/.next/server/chunks/_09dz7xv._.js +1 -1
- package/.next/standalone/.next/server/chunks/_0tdy_6l._.js +3 -0
- package/.next/standalone/.next/server/chunks/_0tovk6q._.js +1 -1
- package/.next/standalone/.next/server/chunks/_0trp3yc._.js +1 -1
- package/.next/standalone/.next/server/chunks/_1ek68ln._.js +21 -14
- package/.next/standalone/.next/server/chunks/lib_grok-projects_ts_1i2epl_._.js +3 -0
- package/.next/standalone/.next/server/chunks/lib_qwen-projects_ts_0wu_a8e._.js +3 -0
- package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_01r25oi._.js +2 -2
- package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_09z9-p7._.js +2 -2
- package/.next/standalone/.next/server/chunks/package_json_[json]_cjs_1nxcc4v._.js +1 -1
- package/.next/standalone/.next/server/chunks/src_hooks_0iu54mz._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__013jr2b._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__01wy8d-._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__02npjtd._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0_4gcz8._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0d--wmy._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0da85px._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0ftmoxc._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0oa1lav._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0p-5p8u._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0qqrlf_._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0s11fx1._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0s740oi._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0n_lxhg._.js → [root-of-the-server]__0wvusu0._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__1b5jzxr._.js → [root-of-the-server]__16gamwq._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1bbk-si._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1c3ybxr._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1izi7zn._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1p2otjt._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1qapotl._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1zl_r0t._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__21bj7uw._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/_0-yi74u._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{_0v8eebd._.js → _00z5uuq._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{_1if9ixi._.js → _08f0jd2._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_08x1r5t._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_0wso5d3._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{_0j6gd_k._.js → _1byck5v._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/_1es2j7i._.js +155 -1
- package/.next/standalone/.next/server/chunks/ssr/_1u8-lu2._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_1zopuov._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_next-internal_server_app_policies_page_actions_1sp2-yo.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/app_audit__components_audit-dashboard_tsx_0p9ud47._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/app_global-error_tsx_1kp6l3x._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/app_policies_hooks-client_tsx_19dqvpc._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/app_settings_settings-client_tsx_20lq-mq._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/lib_cline-projects_ts_13_hbdd._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/lib_grok-projects_ts_0rc-d0o._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/lib_ori-projects_ts_04tofqo._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/lib_qwen-projects_ts_0w3i9o7._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/node_modules_posthog-node_dist_entrypoints_index_node_mjs_11bnuzn._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/src_hooks_builtin-policies_ts_09j2ndl._.js +1 -1
- package/.next/standalone/.next/server/middleware-build-manifest.js +5 -5
- 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/server-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/server-reference-manifest.json +19 -19
- package/.next/standalone/.next/static/chunks/{0ollg-nnu3t3e.js → 00gv0v91mycm-.js} +1 -1
- package/.next/standalone/.next/static/chunks/{354-n7p7labpn.js → 01hvwwrhvbzyh.js} +1 -1
- package/.next/standalone/.next/static/chunks/0hzmxwb2pvk5p.js +6 -0
- package/.next/standalone/.next/static/chunks/{0nm11ysn0153h.js → 0j884dwnwtyrt.js} +1 -1
- package/.next/standalone/.next/static/chunks/0mr9dg3bnloa1.js +1 -0
- package/.next/standalone/.next/static/chunks/0qn9khv0oo9ex.js +1 -0
- package/.next/standalone/.next/static/chunks/{2xm5mj1d21b4n.js → 1_2jsatfuthrw.js} +1 -1
- package/.next/standalone/.next/static/chunks/1_bxotmf9qngs.js +1 -0
- package/.next/standalone/.next/static/chunks/1eyl7fzkmnkf_.js +1 -0
- package/.next/standalone/.next/static/chunks/{42yfkhekx440s.js → 1po3lirgk2riw.js} +1 -1
- package/.next/standalone/.next/static/chunks/{40lpt2o2b283e.js → 2bnf_4pgyk1rq.js} +1 -1
- package/.next/standalone/.next/static/chunks/{1a6u7l3giejch.js → 2bvwsyu6x__ia.js} +1 -1
- package/.next/standalone/.next/static/chunks/{3l36d73kj18zw.js → 3_--3ibia6ba1.js} +1 -1
- package/.next/standalone/.next/static/chunks/3gf1jg-5m-u1t.css +2 -0
- package/.next/standalone/.next/static/chunks/{3pibxnbhjza7n.js → 3ws7eljkq25wg.js} +1 -1
- package/.next/standalone/.next/static/chunks/{turbopack-2x-o099q64i8h.js → turbopack-18qf4jodtft6b.js} +1 -1
- package/.next/standalone/.qwen/settings.json +251 -0
- package/.next/standalone/app/project/[name]/page.tsx +24 -4
- package/.next/standalone/assets/logos/cline.png +0 -0
- package/.next/standalone/assets/logos/grok-dark.svg +1 -0
- package/.next/standalone/assets/logos/grok-light.svg +1 -0
- package/.next/standalone/assets/logos/ori-dark.svg +1 -0
- package/.next/standalone/assets/logos/ori-light.svg +1 -0
- package/.next/standalone/assets/logos/qwen.svg +1 -0
- package/.next/standalone/lib/cli-registry.ts +33 -1
- package/.next/standalone/lib/cline-projects.ts +155 -0
- package/.next/standalone/lib/cline-sessions.ts +268 -0
- package/.next/standalone/lib/download-session.ts +37 -0
- package/.next/standalone/lib/grok-projects.ts +123 -0
- package/.next/standalone/lib/grok-sessions.ts +355 -0
- package/.next/standalone/lib/ori-projects.ts +141 -0
- package/.next/standalone/lib/ori-sessions.ts +221 -0
- package/.next/standalone/lib/projects.ts +27 -3
- package/.next/standalone/lib/qwen-projects.ts +106 -0
- package/.next/standalone/lib/qwen-sessions.ts +313 -0
- 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 +1 -1
- package/.next/standalone/node_modules/next/dist/compiled/next-server/app-page-turbo.runtime.prod.js +1 -1
- package/.next/standalone/node_modules/next/dist/compiled/next-server/app-route-turbo.runtime.prod.js +1 -1
- package/.next/standalone/node_modules/next/dist/compiled/next-server/pages-turbo.runtime.prod.js +5 -5
- package/.next/standalone/node_modules/next/dist/lib/patch-incorrect-lockfile.js +3 -3
- 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/image-optimizer.js +2 -2
- package/.next/standalone/node_modules/next/dist/server/lib/app-info-log.js +1 -1
- package/.next/standalone/node_modules/next/dist/server/lib/incremental-cache/file-system-cache.js +17 -4
- package/.next/standalone/node_modules/next/dist/server/lib/start-server.js +1 -1
- package/.next/standalone/node_modules/next/dist/shared/lib/router/utils/escape-path-delimiters.js +1 -1
- package/.next/standalone/node_modules/next/dist/telemetry/anonymous-meta.js +1 -1
- package/.next/standalone/node_modules/next/dist/telemetry/events/swc-load-failure.js +1 -1
- package/.next/standalone/node_modules/next/dist/telemetry/events/version.js +2 -2
- package/.next/standalone/node_modules/next/package.json +10 -10
- package/.next/standalone/package.json +11 -11
- package/.next/standalone/sdk/python/uv.lock +29 -29
- package/.next/standalone/server.js +1 -1
- package/README.md +38 -7
- package/bin/failproofai.mjs +24 -7
- package/dist/cli.mjs +20313 -17756
- package/dist/worker.mjs +8521 -6768
- package/lib/cli-registry.ts +33 -1
- package/lib/cline-projects.ts +155 -0
- package/lib/cline-sessions.ts +268 -0
- package/lib/download-session.ts +37 -0
- package/lib/grok-projects.ts +123 -0
- package/lib/grok-sessions.ts +355 -0
- package/lib/ori-projects.ts +141 -0
- package/lib/ori-sessions.ts +221 -0
- package/lib/projects.ts +27 -3
- package/lib/qwen-projects.ts +106 -0
- package/lib/qwen-sessions.ts +313 -0
- package/package.json +11 -11
- package/src/audit/cli-adapters/cline.ts +50 -0
- package/src/audit/cli-adapters/grok.ts +70 -0
- package/src/audit/cli-adapters/index.ts +24 -0
- package/src/audit/cli-adapters/ori.ts +55 -0
- package/src/audit/cli-adapters/qwen.ts +71 -0
- package/src/hooks/batch-expand.ts +380 -0
- package/src/hooks/batch-fanout.ts +142 -0
- package/src/hooks/builtin-policies.ts +6 -4
- package/src/hooks/enforcement-capability.ts +97 -0
- package/src/hooks/handler.ts +61 -5
- package/src/hooks/harness-cli.ts +3 -1
- package/src/hooks/integrations.ts +756 -2
- package/src/hooks/normalize-cli-payload.ts +126 -0
- package/src/hooks/policy-evaluator.ts +297 -6
- package/src/hooks/resolve-transcript-path.ts +10 -0
- package/src/hooks/risk-patterns.ts +26 -0
- package/src/hooks/tool-name-canonicalize.ts +64 -0
- package/src/hooks/types.ts +533 -2
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1le9jqc._.js +0 -3
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1p-qi2t._.js +0 -5
- package/.next/standalone/.next/server/chunks/_1-akg6w._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__00-s7h8._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__190won8._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1ctpynv._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1sc84bb._.js +0 -3
- package/.next/standalone/.next/static/chunks/03slu0c8_71y7.js +0 -1
- package/.next/standalone/.next/static/chunks/1-_zkmnm-jwei.js +0 -1
- package/.next/standalone/.next/static/chunks/1r9676mkvihto.js +0 -1
- package/.next/standalone/.next/static/chunks/30pct5s734jua.js +0 -6
- package/.next/standalone/.next/static/chunks/40nr6ehj4p3cw.css +0 -2
- package/.next/standalone/.next/static/chunks/41b5ptaocvi_l.js +0 -1
- /package/.next/standalone/.next/static/{JBYgkXkA1PS48m9P_hKNw → qJx3mbOQV-5ElrcRb4Sp7}/_buildManifest.js +0 -0
- /package/.next/standalone/.next/static/{JBYgkXkA1PS48m9P_hKNw → qJx3mbOQV-5ElrcRb4Sp7}/_clientMiddlewareManifest.js +0 -0
- /package/.next/standalone/.next/static/{JBYgkXkA1PS48m9P_hKNw → qJx3mbOQV-5ElrcRb4Sp7}/_ssgManifest.js +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
module.exports=[74493,a=>{"use strict";let b,c,d,e,f;var g,h=a.i(14747);function i(a){return a.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}let j=a=>void 0===a?void 0:a.variant??a.enabled,k=a=>{if("string"!=typeof a)return a;try{return JSON.parse(a)}catch{return a}},l=["$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","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],m=(a,b=[])=>{let c={},d=b=>{void 0!==a[b]&&(c[b]=a[b])};return l.forEach(d),b.forEach(d),c};var n=((g={}).AnonymousId="anonymous_id",g.DistinctId="distinct_id",g.Props="props",g.EnablePersonProcessing="enable_person_processing",g.PersonMode="person_mode",g.FeatureFlagDetails="feature_flag_details",g.FeatureFlags="feature_flags",g.FeatureFlagPayloads="feature_flag_payloads",g.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",g.BootstrapFeatureFlags="bootstrap_feature_flags",g.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",g.OverrideFeatureFlags="override_feature_flags",g.Queue="queue",g.AiQueue="ai_queue",g.AiCaptureQueue="ai_capture_queue",g.LogsQueue="logs_queue",g.OptedOut="opted_out",g.SessionId="session_id",g.SessionStartTimestamp="session_start_timestamp",g.SessionLastTimestamp="session_timestamp",g.PersonProperties="person_properties",g.GroupProperties="group_properties",g.InstalledAppBuild="installed_app_build",g.InstalledAppVersion="installed_app_version",g.SessionReplay="session_replay",g.PushRegistered="push_registered",g.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",g.SurveyLastSeenDate="survey_last_seen_date",g.SurveysSeen="surveys_seen",g.Surveys="surveys",g.RemoteConfig="remote_config",g.FlagsEndpointWasHit="flags_endpoint_was_hit",g.DeviceId="device_id",g);let o={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}`},p=a=>{let b=Error(`Native gzip produced invalid output: ${a}`);throw b.name="NativeGzipValidationError",b},q=async(a,c)=>{a.size<18&&p("too-short");let d=new Uint8Array(await a.slice(0,10).arrayBuffer());d.length>=2&&31===d[0]&&139===d[1]&&8===d[2]||p("invalid-header");let e=new DataView(await a.slice(a.size-8).arrayBuffer());e.getUint32(0,!0)!==(a=>{let c=(()=>{if(b)return b;b=[];for(let a=0;a<256;a++){let c=a;for(let a=0;a<8;a++)c=1&c?0xedb88320^c>>>1:c>>>1;b[a]=c>>>0}return b})(),d=0xffffffff;for(let b=0;b<a.length;b++)d=c[(d^a[b])&255]^d>>>8;return(0xffffffff^d)>>>0})(c)&&p("invalid-crc");let f=c.length>>>0;e.getUint32(4,!0)!==f&&p("invalid-size")};async function r(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 q(g,b),g}catch(a){if(c?.rethrow)throw a;return b&&console.error("Failed to gzip compress data",a),null}}let s="[Truncated]",t="[Unserializable]";function u(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 v(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"}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let w=Array.isArray,x=Object.prototype;x.hasOwnProperty;let y=x.toString,z=w||function(a){return"[object Array]"===y.call(a)},A=a=>a===Object(a)&&!z(a),B=a=>void 0===a,C=a=>"[object String]"==y.call(a),D=a=>C(a)&&0===a.trim().length,E=a=>null===a,F=a=>B(a)||E(a),G=a=>"[object Number]"==y.call(a)&&a==a;function H(a){return null===a||"object"!=typeof a}function I(a,b){return Object.prototype.toString.call(a)===`[object ${b}]`}function J(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 L(a,Error)}}function K(a){return"u">typeof Event&&L(a,Event)}function L(a,b){try{return a instanceof b}catch{return!1}}let M="Android",N="BlackBerry",O="Nintendo",P="PlayStation",Q="Xbox",R="Windows",S="(\\d+(\\.\\d+)?)";RegExp("Version/"+S),RegExp(Q,"i"),RegExp(P+" \\w+","i"),RegExp(O+" \\w+","i"),RegExp(N+"|PlayBook|BB10","i");RegExp("rv:"+S),RegExp("Edge?\\/"+S),RegExp("(Chrome|CrMo)\\/"+S),RegExp("CriOS\\/"+S),RegExp("(UCBrowser|UCWEB)\\/"+S),RegExp("(Opera|OPR)\\/"+S),RegExp("Firefox\\/"+S),RegExp("FxiOS\\/"+S),RegExp("Konqueror[:/]?"+S,"i"),RegExp(N+" "+S),RegExp("android\\s"+S,"i"),RegExp("SamsungBrowser\\/"+S),RegExp("OculusBrowser\\/"+S),RegExp("Vivaldi\\/"+S),RegExp("YaBrowser\\/"+S),RegExp("Whale\\/"+S),RegExp("Brave\\/"+S),RegExp("(DuckDuckGo|Ddg)\\/"+S),RegExp("PaleMoon\\/"+S),RegExp("Waterfox\\/"+S),RegExp("GSA\\/"+S),RegExp("(rv:|MSIE )"+S),RegExp("rv:"+S),RegExp(Q+"; "+Q+" (.*?)[);]","i"),RegExp(O,"i"),RegExp(P,"i"),RegExp(R,"i"),RegExp("("+M+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+M+")","i");let T=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function U(a,b){return"string"==typeof a&&T.test(a)?a:b()}function V(a){return a?a.split("#")[0]:a}async function W(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 X(){return new Date().toISOString()}function Y(a,b){let c=setTimeout(a,b);return c?.unref&&c?.unref(),c}async function Z(a,b,c){let d;try{return await Promise.race([a,new Promise((a,e)=>{d=Y(()=>{try{c?.(),a()}catch(a){e(a)}},b)})])}finally{clearTimeout(d)}}function $(a){return Promise.all(a.map(a=>(a??Promise.resolve()).then(a=>({status:"fulfilled",value:a}),a=>({status:"rejected",reason:a}))))}let _=Object.prototype.propertyIsEnumerable;function aa(a,b){try{return ab(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function ab(a,b,c,d){let e=[];for(let f in a)if(_.call(a,f)){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(E(g)||B(g))continue;e.push({key:u(f),value:function a(b,c,d,e){if(d.remainingNodes<=0)return{stringValue:s};if(d.remainingNodes--,"[object Boolean]"===y.call(b))return{boolValue:b};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:u(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:"[Circular]"};if(e>=20)return{stringValue:s};if(b instanceof Date){let a=Number.isFinite(b.getTime())?b.toISOString():String(b);return{stringValue:"string"==typeof a?u(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(z(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(F(g))continue;f.push(a(g,c,d,e))}catch{f.push({stringValue:t})}return b.length>h&&f.push({stringValue:s}),f}(b,c,d,e+1)}};return{kvlistValue:{values:ab(b,c,d,e+1)}}}finally{d.ancestors.delete(b)}}return{stringValue:u(String(b))}}(g,b,c,d)})}catch{e.push({key:u(f),value:{stringValue:t}})}}return e}let ac=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function ad(a){return String(a)+"000000"}function ae(a,b,c,d){let e="";return d&&(e=Object.keys(d).sort().map(a=>`${JSON.stringify(a)}:${JSON.stringify(d[a])}`).join(",")),`${a}\u0000${b}\u0000${c??""}\u0000${e}`}class af{constructor(a,b,c){this._instance=a,this._config=b,this._logger=c,this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,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._clearFlushTimer(),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=ae(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),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush||(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(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(ac.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,ac)]+=1}}}_runBeforeSend(a){let b=this._config.beforeSend;if(!b)return a;let c=z(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||(this._flushTimer=Y(()=>{this._flushTimer=void 0,this.flush().catch(a=>{this._logger.error("Metrics flush failed:",a)})},this._config.flushIntervalMs))}_clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}async _doFlush(){if(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(c.kind){case"ok":return;case"retry-later":this._mergeWindowBack(a),this._armFlushTimer();return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",c.error);return}}_buildPayload(a){var b,c,d,e,f,g,h;return e=this._buildMetrics(a),b=this._config,c=this._instance.getLibraryId(),d=this._instance.getLibraryVersion(),f={...b.resourceAttributes,"service.name":b.serviceName||"unknown_service",...b.environment&&{"deployment.environment":b.environment},...b.serviceVersion&&{"service.version":b.serviceVersion},"telemetry.sdk.name":c,"telemetry.sdk.version":d},g=this._instance.getLibraryId(),h=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:aa(f)},scopeMetrics:[{scope:{name:g,version:h},metrics:e}]}]}}_buildMetrics(a){let b=ad(Date.now()),c=new Map;for(let d of a.values()){let a=ae(d.type,d.name,d.unit,void 0),e=c.get(a);e||(e={name:d.name,...d.unit&&{unit:d.unit}},"count"===d.type?e.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===d.type?e.gauge={dataPoints:[]}:e.histogram={aggregationTemporality:1,dataPoints:[]},c.set(a,e));let f=aa(d.attributes??{},this._logger),g=ad(d.windowStartMs);if("count"===d.type){let a={attributes:f,startTimeUnixNano:g,timeUnixNano:b,asDouble:d.total??0};e.sum.dataPoints.push(a)}else if("gauge"===d.type){let a={attributes:f,timeUnixNano:b,asDouble:d.last??0};e.gauge.dataPoints.push(a)}else if(d.hist){let a={attributes:f,startTimeUnixNano:g,timeUnixNano:b,count:d.hist.count,sum:d.hist.sum,min:d.hist.min,max:d.hist.max,bucketCounts:d.hist.bucketCounts,explicitBounds:ac};e.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.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 ag="0123456789abcdef";class ah{constructor(a){this.bytes=a}static ofInner(a){if(16===a.length)return new ah(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 ah(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 ah(a)}throw SyntaxError("could not parse UUID string")}toString(){let a="";for(let b=0;b<this.bytes.length;b++)a+=ag.charAt(this.bytes[b]>>>4),a+=ag.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+=ag.charAt(this.bytes[b]>>>4),a+=ag.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 ah(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 ai{constructor(a){this.timestamp=0,this.counter=0,this.random=a??aj()}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 ah.fromFieldsV7(this.timestamp,Math.trunc(this.counter/0x40000000),this.counter&0x40000000-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let 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,ah.ofInner(a)}}let aj=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),ak=()=>al().toString(),al=()=>(c||(c=new ai)).generate();function am(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 an(a){let b=a.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${b}_posthog`}function ao(a){let b=Date.now();return JSON.stringify({distinct_id:a,$device_id:a,$user_state:"anonymous",$sesid:[b,ak(),b]})}function ap(a,b){let c=an(b),d=a.get(c);return d?ar(d.value):null}function aq(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 ar(a){if(!a)return null;try{let b=JSON.parse(a);if(!b||"object"!=typeof b||!b.distinct_id)return null;let c=z(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}}class as{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)}}class at{add(a){let b=ak(),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 au=(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=>au(`${a} ${d}`,b,c)}};class av{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&&z(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;return null!=a.cause&&(c=this.parseStacktrace(a.cause,b)),""!=a.stack&&null!=a.stack&&(d=this.applyChunkIds(this.stackParser(a.stack,a.synthetic?b.skipFirstLines:0),b.chunkIdMap)),{...a,cause:c,stack:d}}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={type:a.type,value:a.value,mechanism:{type:b.type??"generic",handled:b.handled??!0,synthetic:a.synthetic??!1}};a.stack&&(c.stacktrace={type:"raw",frames:a.stack});let d=[c];return null!=a.cause&&d.push(...this.convertToExceptionList(a.cause,{...b,handled:!0})),d}buildParsingContext(a){return{chunkIdMap:function(a){let b=globalThis._posthogChunkIds;if(!b)return;let c=Object.keys(b);return f&&c.length===e?f:(e=c.length,f=c.reduce((c,e)=>{d||(d={});let f=d[e];if(f)c[f[0]]=f[1];else{let f=a(e);for(let a=f.length-1;a>=0;a--){let g=f[a],h=g?.filename,i=b[e];if(h&&i){c[h]=i,d[e]=[h,i];break}}}return c},{}))}(this.stackParser),skipFirstLines:a.skipFirstLines??1}}buildCoercingContext(a,b,c=0){let d=(c,d)=>{if(d<=4){let e=this.buildCoercingContext(a,b,d);return this.applyCoercers(c,e)}};return{...b,syntheticException:0==c?b.syntheticException:void 0,mechanism:a,apply:a=>d(a,c),next:a=>d(a,c+1)}}}function aw(a,b,c,d,e){let f={platform:a,filename:b,function:"<anonymous>"===c?"?":c,in_app:!b?.startsWith("webkit-masked-url://")&&"<anonymous>"!==b};return B(d)||(f.lineno=d),B(e)||(f.colno=e),f}a.s(["ErrorPropertiesBuilder",0,av],6762);let ax=(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]},ay=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,az=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,aA=/\((\S*)(?::(\d+))(?::(\d+))\)/,aB=(a,b)=>{let c=ay.exec(a);if(c){let[,a,d,e]=c;return aw(b,a,"?",+d,+e)}let d=az.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]=ax(d[1]||"?",d[2]);return aw(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]=ax(d,a),aw(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?aw(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?aw(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?aw(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){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 aT(){return aU("web:javascript",aB,aE)}function aU(a,...b){return(c,d=0)=>{let e=[],f=c.split("\n");for(let c=d;c<f.length;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);break}}if(e.length>=50)break}}return aS(e)}}a.s(["createDefaultStackParser",0,aT,"createStackParser",0,aU,"reverseAndStripFrames",0,aS],67970);class aV{match(a){return this.isDOMException(a)||this.isDOMError(a)}coerce(a,b){let c=C(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 I(a,"DOMException")}isDOMError(a){return I(a,"DOMError")}}a.s(["DOMExceptionCoercer",0,aV],51671);class aW{match(a){return!!I(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 C(a.message)&&a.message.length>0}_buildLocationStack(a){let b=a.lineno??0,c=a.colno??0;if(C(a.filename)&&0!==a.filename.length&&0!==b)return`Error
|
|
2
|
-
at ${a.filename}:${b}:${c}`}}a.s(["ErrorEventCoercer",0,aW],75368);let aX=["fatal","error","warning","log","info","debug"];function aY(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 aZ{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(K(a))return a.constructor.name;let b="name"in a?a.name:void 0;return C(b)&&!D(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=aY(a);return`${b&&"Object"!==b?`'${b}'`:"Object"} captured as exception with keys: ${c}`}isSeverityLevel(a){return C(a)&&!D(a)&&aX.indexOf(a)>=0}getStack(a){try{if(C(a.stacktrace)&&a.stacktrace.length>0)return a.stacktrace;return C(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(J(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,aZ],93874);class a${match(a){return K(a)}coerce(a,b){let c=a.constructor.name;return{type:c,value:`${c} captured as exception with keys: ${aY(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["EventCoercer",0,a$],46980);class a_{match(a){return H(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,a_],28150);class a0{match(a){return I(a,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(a)}isCustomEventWrappingRejection(a){if(!K(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 H(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,a0],98140),a.s([],7610);let a1={MESSAGE:"$message",TIMESTAMP:"$timestamp"},a2=new Set([a1.MESSAGE,a1.TIMESTAMP]),a3={enabled:!0,max_bytes:32768};function a4(a){return a?{enabled:a.enabled??a3.enabled,max_bytes:function(a,b){if(!G(a)||a===1/0||a===-1/0)return b;let c=Math.floor(a);return c<0?b:c}(a.max_bytes,a3.max_bytes)}:{...a3}}function a5(a){if(!a)return{sanitizedProperties:{},droppedKeys:[]};let b=[];return{sanitizedProperties:Object.keys(a).reduce((c,d)=>(a2.has(d)?b.push(d):c[d]=a[d],c),{}),droppedKeys:b}}class a6{constructor(a){this._entries=[],this._totalBytes=0,this._config=a4(a)}setConfig(a){this._config=a4(a),this._trimToMaxBytes()}add(a){let b=function(a){let b;try{b=v(a)}catch{return}try{let a=JSON.parse(b);if(!A(a))return;let c=a[a1.MESSAGE],d=a[a1.TIMESTAMP];if(!C(c)||0===c.trim().length||!C(d)&&!G(d))return;return{step:a,json:b}}catch{return}}(a);if(!b)return;let c=a7(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 a7(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,a3,"EXCEPTION_STEP_INTERNAL_FIELDS",0,a1,"ExceptionStepsBuffer",0,a6,"getUtf8ByteLength",0,a7,"resolveExceptionStepsConfig",0,a4,"stripReservedExceptionStepFields",0,a5],97383),a.s([],48153);class a8{match(a){return J(a)}coerce(a,b){let c=this.getStack(a);return{type:this.getType(a),value:this.getMessage(a,b),stack:c??b.syntheticException?.stack,cause:a.cause?b.next(a.cause):void 0,synthetic:void 0===c}}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){return a.stacktrace||a.stack||void 0}}a.s(["ErrorCoercer",0,a8],10692);let a9=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class ba{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(a9);return d&&(b=d[1],c=d[2]),[b,c]}}a.s(["StringCoercer",0,ba],57802);class bb 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 bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let a=Error("Response body read timed out");a.name="AbortError",this.cancelResponseBody(a),this.responseBodyTextPromise=Promise.reject(a)}else{let a,b=new Promise((a,b)=>{this.responseBodyTimer=Y(()=>{this._bodyReadTimedOut=!0;let a=Error("Response body read timed out");a.name="AbortError",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 bc extends Error{constructor(a){super("Network error while fetching PostHog",a instanceof Error?{cause:a}:{}),this.error=a,this.name="PostHogFetchNetworkError"}}async function bd(a){if(a instanceof bb){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 be(a){return a instanceof bc}function bf(a){if(a instanceof bb)return 502===a.status||504===a.status;if(!(a instanceof bc))return!1;let b=a.error;return"ECONNREFUSED"!==(b?.code??b?.cause?.code)}function bg(a){return"object"==typeof a&&a instanceof bb&&413===a.status}function bh(a){return a instanceof bb?408===a.status||429===a.status||a.status>=500:be(a)}function bi(a){return null!==a&&"object"==typeof a&&!Array.isArray(a)}let bj="default";class bk{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new av([new a8,new aZ,new ba,new a_],aT())}constructor(a,b={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new at,this._events=new as,this._isInitialized=!1;const c="string"==typeof a?a.trim():"",d="string"==typeof b.host?b.host.trim():"",e=!c;this._logger=function(a,b=a=>a()){return au(a,b,function(a=console){return{log:a.log.bind(a),warn:a.warn.bind(a),error:a.error.bind(a),debug:a.debug.bind(a)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),e&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=c,this.host=function(a){return a?.replace(/\/+$/,"")}(d||"https://us.i.posthog.com"),this.flushAt=b.flushAt?Math.max(b.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,b.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,b.maxQueueSize??1e3),this.flushInterval=b.flushInterval??1e4,this.preloadFeatureFlags=b.preloadFeatureFlags??!0,this.defaultOptIn=b.defaultOptIn??!0,this.disableSurveys=b.disableSurveys??!1,this._retryOptions={retryCount:b.fetchRetryCount??3,retryDelay:b.fetchRetryDelay??3e3,retryCheck:bh},this.requestTimeout=b.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=b.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=b.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=b.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=b.disableGeoip??!0,this.disabled=(b.disabled??!1)||e,this.historicalMigration=b?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=b?.evaluationContexts??b?.evaluationEnvironments,b?.evaluationEnvironments&&!b?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!("CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&"function"==typeof Response.prototype.blob)||(b?.disableCompression??!1)}logMsgIfDebug(a){this.isDebug&&a()}wrap(a){return this.disabled?void this._logger.warn("The client is disabled"):this._isInitialized?a():void this._initPromise.then(()=>a())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(n.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(n.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(n.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={...b,...this.getCommonEventProperties()};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=m(c)),{distinct_id:a.distinct_id,event:a.event,properties:c}}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={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(h)};return this._logger.info("Flags URL",g),this.fetchWithRetry(g,i,{type:"required",consume:a=>a.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:bf},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,j(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?k(c):void 0]}));return{...a,featureFlags:c,featureFlagPayloads:d}}{let b=a.featureFlags??{},c=Object.fromEntries(Object.entries(a.featureFlagPayloads||{}).map(([a,b])=>[a,k(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 bb)return{type:"api_error",statusCode:a.status};if(a instanceof bc){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=j(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(n.Props)),this._props||{}}set props(a){this._props=a}async register(a){this.wrap(()=>{this.props={...this.props,...a},this.setPersistedProperty(n.Props,this.props)})}async unregister(a){this.wrap(()=>{delete this.props[a],this.setPersistedProperty(n.Props,this.props)})}processBeforeEnqueue(a){return a}async flushStorage(){}getQueueRouteKey(a){return bj}persistedQueueKeyForRoute(a){return n.Queue}getActiveQueueRoutes(){return[bj]}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=Y(()=>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=bi(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=U(e.uuid,ak),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:X(),uuid:U(b?.uuid,ak)};return(b?.disableGeoip??this.disableGeoip)&&(bi(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.flush().catch(async a=>{await bd(a)})}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(()=>$([b])).then(()=>(this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=d,this.flushPromise=d,this.flushPromises.add(d),this.addPendingPromise(d),$([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 r(a,this.isDebug)}getBatchEndpointPath(a){return"/batch/"}async sendBatch(a,b,c=bj){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:X()};this.historicalMigration&&(d.historical_migration=!0);let e=v(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=>!bg(a)&&bh(a)};try{await this.sendBatch(g,i,a)}catch(a){if(bg(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 bc||await h(),this._events.emit("error",a),a}await h(),b.push(...g),f+=g.length}}async _sendOtlpBatch({path:a,payload:b}){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let c=JSON.stringify(b),d=`${this.host}/i/v1/${a}?token=${encodeURIComponent(this.apiKey)}`,e=this.disableCompression?null:await this.compressPayload(c),f={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==e&&{"Content-Encoding":"gzip"}},body:e||c};try{return await this.fetchWithRetry(d,f,{type:"successful-write"},{retryCheck:a=>!bg(a)&&bh(a)}),{kind:"ok"}}catch(a){if(bg(a))return{kind:"too-large"};if(bh(a))return{kind:"retry-later",error:a};return{kind:"fatal",error:a}}}async _sendLogsBatch(a){return this._sendOtlpBatch({path:"logs",payload:a})}async _sendMetricsBatch(a){return this._sendOtlpBatch({path:"metrics",payload:a})}async fetchWithRetry(a,b,c,d,e){let f=b.body?b.body:"",g=-1;try{g=f instanceof Blob?f.size:f instanceof Uint8Array?f.byteLength:Buffer.byteLength(f,"utf8")}catch{g=f instanceof Blob?f.size:f instanceof Uint8Array?f.byteLength:new TextEncoder().encode(f).length}let h={...this._retryOptions,...d},i=0;return await W(async()=>{let d,f,h;i++;let j=new AbortController,k=e??this.requestTimeout,l=Date.now()+k,m=new Promise((a,b)=>{d=Y(()=>{let a=Error(`Request timed out after ${k}ms`);a.name="AbortError",b(a),j.abort(a)},k)}),n=!1,o=()=>h??=(async()=>{try{await f?.body?.cancel()}catch{}})();try{let d;try{d=this.fetch(a,{signal:j.signal,...b})}catch(a){throw new bc(a)}d.then(a=>{j.signal.aborted&&!n&&Promise.resolve(a.body?.cancel()).catch(()=>{})}).catch(()=>{});try{f=await Promise.race([d,m]),n=!0}catch(a){throw new bc(a)}if("no-cors"!==b.mode&&(f.status<200||f.status>=400))throw new bb(f,g,l,j);if("successful-write"===c.type){try{await Promise.race([o(),m])}catch{}return}try{return await Promise.race([c.consume(f),m])}catch(a){if(j.signal.aborted)throw new bc(a);throw a}}finally{clearTimeout(d),j.signal.aborted&&f&&o()}},{...h,retryCheck:a=>{let b=h.retryCheck(a);return b&&i<=h.retryCount&&a instanceof bb&&a.cancelResponseBody(),b}})}async _shutdown(a=3e4){await this._initPromise;let b=!1;if(this.clearFlushTimer(),!this.disabled)return Z((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 bb||be(a))))throw a;await bd(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}}a.i(48153),a.i(6762),a.i(67970),a.s(["chromeStackLineParser",0,aB,"createDefaultStackParser",0,aT,"createStackParser",0,aU,"geckoStackLineParser",0,aE,"nodeStackLineParser",0,aP,"opera10StackLineParser",0,aI,"opera11StackLineParser",0,aK,"reverseAndStripFrames",0,aS,"winjsStackLineParser",0,aG],64583),a.i(64583),a.i(7610),a.i(51671),a.i(10692),a.i(75368),a.i(57802),a.i(93874),a.i(46980),a.i(28150),a.i(98140),a.s(["DOMExceptionCoercer",0,aV,"ErrorCoercer",0,a8,"ErrorEventCoercer",0,aW,"EventCoercer",0,a$,"ObjectCoercer",0,aZ,"PrimitiveCoercer",0,a_,"PromiseRejectionEventCoercer",0,a0,"StringCoercer",0,ba],54253),a.i(54253);class bl{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 bm(){let a=globalThis._posthogReleaseId;return"string"==typeof a&&a.length>0?a:void 0}a.s(["ReduceableCache",0,bl],98966),a.i(98966),a.i(97383),a.s(["getInjectedReleaseId",0,bm],28861),a.i(28861),a.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,a3,"DOMExceptionCoercer",0,aV,"EXCEPTION_STEP_INTERNAL_FIELDS",0,a1,"ErrorCoercer",0,a8,"ErrorEventCoercer",0,aW,"ErrorPropertiesBuilder",0,av,"EventCoercer",0,a$,"ExceptionStepsBuffer",0,a6,"ObjectCoercer",0,aZ,"PrimitiveCoercer",0,a_,"PromiseRejectionEventCoercer",0,a0,"ReduceableCache",0,bl,"StringCoercer",0,ba,"chromeStackLineParser",0,aB,"createDefaultStackParser",0,aT,"createStackParser",0,aU,"geckoStackLineParser",0,aE,"getInjectedReleaseId",0,bm,"getUtf8ByteLength",0,a7,"nodeStackLineParser",0,aP,"opera10StackLineParser",0,aI,"opera11StackLineParser",0,aK,"resolveExceptionStepsConfig",0,a4,"reverseAndStripFrames",0,aS,"stripReservedExceptionStepFields",0,a5,"winjsStackLineParser",0,aG],60485);var bn=a.i(60485),bo=bn,bp=a.i(2157),bq=a.i(12714),br=a.i(50227),bs=a.i(1457);let bt=new bo.ReduceableCache(25),bu=new bo.ReduceableCache(20);async function bv(a,b=bq.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,br.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=bz(a,d);if(void 0===f||bu.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=bA(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=bA(c)),b++}return e}(g);if(h.every(a=>(function(a,b){let c=bt.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}(bt,f,{});i.push(bx(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=bz(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=bB(a);d<a;d++){let a=c[d];if(void 0===a)return void by(b);b.pre_context.push(a)}if(void 0===c[a])return by(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,bt,d),bt.reduce(),a}async function bw(a,b,c){let d,e=!1;try{d=await b(a,bp.constants.O_RDONLY|bp.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 bx(a,b,c,d,e,f){let g=await bw(a,e,f);return void 0===g?void bu.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{bu.set(d,1),i();return}try{f=(0,bs.createInterface)({input:e})}catch{bu.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(){bu.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 by(a){delete a.pre_context,delete a.context_line,delete a.post_context}function bz(a,b){return(0,br.isAbsolute)(a)?JSON.stringify([null,a]):void 0===b?void 0:JSON.stringify([b,a])}function bA(a){return[bB(a),a+7]}function bB(a){return Math.max(1,a-7)}let bC=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],bD=function(a,b=[]){if(!a)return!1;let c=a.toLowerCase();return bC.concat(b).some(a=>{let b=a.toLowerCase();return -1!==c.indexOf(b)})},bE={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};a.s(["FeatureFlagError",0,bE],46539);class bF{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 bF({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(bE.ERRORS_WHILE_COMPUTING),this._quotaLimited&&e.push(bE.QUOTA_LIMITED),void 0===b&&e.push(bE.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})}}async function bG(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("")}let bH=["is_not","is_set"];class bI extends Error{constructor(a){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=a,Object.setPrototypeOf(this,bI.prototype)}}function bJ(a,b){a.name=b.name,Error.captureStackTrace(a,b),Object.setPrototypeOf(a,b.prototype)}class bK extends Error{constructor(a){super(a),bJ(this,bK)}}class bL extends Error{constructor(a){super(a),bJ(this,bL)}}class bM{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.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.loadFeatureFlags()}debug(a=!0){this.debugMode=a}logMsgIfDebug(a){this.debugMode&&a()}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 bL||b instanceof bK?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={...a,evaluationCache:a.evaluationCache??{}};return await Promise.all(f.map(async a=>{try{let{value:b,payload:e}=await this.computeFlagAndPayloadLocally(a,g);c[a.key]=b,e&&(d[a.key]=e)}catch(b){b instanceof bL||b instanceof bK?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(f||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};d=void 0!==e?e:await this.computeFlagValueLocally(a,b);let g=this.getFeatureFlagPayload(a.key,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 bK("Flag has experience continuity enabled");let g=(a.filters||{}).aggregation_group_type_index;if(void 0!=g){let c=this.groupTypeMapping[String(g)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${g} for feature flag ${a.key}`)),new bK("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 bK(`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}getFeatureFlagPayload(a,b){let c=null;if(!1!==b&&null!=b&&("boolean"==typeof b?c=this.featureFlagsByKey?.[a]?.filters?.payloads?.[b.toString()]||null:"string"==typeof b&&(c=this.featureFlagsByKey?.[a]?.filters?.payloads?.[b]||null),null!=c)){if("object"==typeof c)return c;if("string"==typeof c)try{return JSON.parse(c)}catch{}return c}return null}async evaluateFlagDependency(a,b,c){let{evaluationCache:d}=c,e=a.key;if(!this.featureFlagsByKey)throw new bK("Feature flags not available for dependency evaluation");if(!("dependency_chain"in a))throw new bK(`Flag dependency property for '${e}' is missing required 'dependency_chain' field`);let f=a.dependency_chain;if(!Array.isArray(f))throw new bK(`Flag dependency property for '${e}' has an invalid 'dependency_chain' (expected array, got ${typeof f})`);if(0===f.length)throw new bK(`Circular dependency detected for flag '${e}' (empty dependency chain)`);for(let a of f){if(!(a in d)){let b=this.featureFlagsByKey[a];if(b)if(b.active)try{let e=await this.computeFlagValueLocally(b,c);d[a]=e}catch(b){throw new bK(`Error evaluating flag dependency '${a}' for flag '${e}': ${b}`)}else d[a]=!1;else throw new bK(`Missing flag dependency '${a}' for flag '${e}'`)}if(null==d[a])throw new bK(`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,f=a.filters||{},g=f.groups||[],h=f.aggregation_group_type_index,i=f.early_exit??!1,{groups:j,groupProperties:k}=d,l=!1;for(let m of g)try{let g=void 0!==m.aggregation_group_type_index?m.aggregation_group_type_index:h,n=c,o=b;if(g!==h&&null!=g){let b=this.groupTypeMapping[String(g)];if(!b||!(b in j)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${a.key}': group type index ${g} not available`));continue}if(!(b in k)){l=!0;continue}n=k[b],o=j[b]}let p=await this.isConditionMatch(a,o,m,n,d);if("match"===p){let b=m.variant,c=f.multivariate?.variants||[];e=b&&c.some(a=>a.key===b)?b:await this.getMatchingVariant(a,o)||!0;break}if(i&&"out_of_rollout_bound"===p)return!1}catch(a){if(a instanceof bL)throw a;if(a instanceof bK)l=!0;else throw a}if(void 0!==e)return e;if(l)throw new bK("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(a,b,c,d,e){let f=c.rollout_percentage,g=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 bP(a,d,this.cohorts,this.debugMode,a=>this.evaluateFlagDependency(a,d,e));c="not_in"===a.operator?!b:b}else c="flag"===b?await this.evaluateFlagDependency(a,d,e):bO(a,d,g);if(!c)return"no_match"}if(void 0==f)return"match"}return void 0!=f&&await bN(a.key,b)>f/100?"out_of_rollout_bound":"match"}async getMatchingVariant(a,b){let c=await bN(a.key,b,"variant"),d=this.variantLookupTable(a).find(a=>c>=a.valueMin&&c<a.valueMax);if(d)return d.key}variantLookupTable(a){let b=[],c=0,d=0,e=a.filters||{};return(e.multivariate?.variants||[]).forEach(a=>{d=c+a.rollout_percentage/100,b.push({valueMin:c,valueMax:d,key:a.key}),c=d}),b}updateFlagState(a){this.featureFlags=a.flags,this.featureFlagsByKey=a.flags.reduce((a,b)=>(a[b.key]=b,a),{}),this.groupTypeMapping=a.groupTypeMapping,this.cohorts=a.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(!0===a.minimalFlagCalledEvents)}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(b.flags),!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(){return this.shouldBeginExponentialBackoff?Math.min(6e4,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);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 bI(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new bI(`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 bI(`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={flags:c.flags??[],groupTypeMapping:c.group_type_mapping||{},cohorts:c.cohorts||{},minimalFlagCalledEvents:!0===c.minimal_flag_called_events};if(this.updateFlagState(d),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&a)try{await this.cacheProvider.onFlagDefinitionsReceived(d)}catch(a){this.onError?.(Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(d.flags);break}default:return}}catch(a){a instanceof bI&&this.onError?.(a)}finally{this.pollerStopped||(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=Y(()=>{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 Z(b,a,()=>{throw Error(`Cache shutdown timeout after ${a}ms`)})}catch(a){this.onError?.(Error(`Error during cache shutdown: ${a}`))}}}async function bN(a,b,c=""){return parseInt((await bG(`${a}.${b}${c}`)).slice(0,15),16)/0x1000000000000000}function bO(a,b,c){let d=a.key,e=a.value,f=a.operator||"exact";if(d in b){if("is_not_set"===f)return!1}else{if("is_not_set"===f)return!0;throw new bK(`Property ${d} not found in propertyValues`)}let g=b[d];if(null==g&&!bH.includes(f))return c&&c(`Property ${d} cannot have a value of null/undefined with the ${f} operator`),!1;function h(a,b){return Array.isArray(a)?a.map(a=>String(a).toLowerCase()).includes(String(b).toLowerCase()):String(a).toLowerCase()===String(b).toLowerCase()}function i(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 h(e,g);case"is_not":return!h(e,g);case"is_set":return d in b;case"icontains":return String(g).toLowerCase().includes(String(e).toLowerCase());case"not_icontains":return!String(g).toLowerCase().includes(String(e).toLowerCase());case"starts_with":return String(g).toLowerCase().startsWith(String(e).toLowerCase());case"not_starts_with":return!String(g).toLowerCase().startsWith(String(e).toLowerCase());case"ends_with":return String(g).toLowerCase().endsWith(String(e).toLowerCase());case"not_ends_with":return!String(g).toLowerCase().endsWith(String(e).toLowerCase());case"regex":return bR(String(e))&&null!==String(g).match(String(e));case"not_regex":return bR(String(e))&&null===String(g).match(String(e));case"gt":case"gte":case"lt":case"lte":{let a,b="number"==typeof e?e:parseFloat(String(e));if(a="number"==typeof g?g:null!=g?parseFloat(String(g)):NaN,Number.isFinite(b)&&Number.isFinite(a))return i(a,b,f);return i(String(g),String(e),f)}case"is_date_after":case"is_date_before":{if("boolean"==typeof e)throw new bK("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)return null;{if(!b.groups)return null;let a=parseInt(b.groups.number);if(a>=1e4)return null;let d=b.groups.interval;if("h"==d)c.setUTCHours(c.getUTCHours()-a);else if("d"==d)c.setUTCDate(c.getUTCDate()-a);else if("w"==d)c.setUTCDate(c.getUTCDate()-7*a);else if("m"==d)c.setUTCMonth(c.getUTCMonth()-a);else{if("y"!=d)return null;c.setUTCFullYear(c.getUTCFullYear()-a)}return c}}(String(e));if(null==a&&(a=bV(e)),null==a)throw new bK(`Invalid date: ${e}`);let b=bV(g);if(["is_date_before"].includes(f))return b<a;return b>a}case"semver_eq":return 0===bU(bT(String(g)),bT(String(e)));case"semver_neq":return 0!==bU(bT(String(g)),bT(String(e)));case"semver_gt":return bU(bT(String(g)),bT(String(e)))>0;case"semver_gte":return bU(bT(String(g)),bT(String(e)))>=0;case"semver_lt":return 0>bU(bT(String(g)),bT(String(e)));case"semver_lte":return 0>=bU(bT(String(g)),bT(String(e)));case"semver_tilde":{let a,b=bT(String(g)),{lower:c,upper:d}={lower:[(a=bT(String(e)))[0],a[1],a[2]],upper:[a[0],a[1]+1,0]};return bU(b,c)>=0&&0>bU(b,d)}case"semver_caret":{let a=bT(String(g)),{lower:b,upper:c}=function(a){let[b,c,d]=bT(a);return{lower:[b,c,d],upper:b>0?[b+1,0,0]:c>0?[0,c+1,0]:[0,0,d+1]}}(String(e));return bU(a,b)>=0&&0>bU(a,c)}case"semver_wildcard":{let a=bT(String(g)),{lower:b,upper:c}=function(a){let b,c,d=String(a).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!d)throw new bK(`Invalid wildcard semver: ${a}`);let e=d.split("."),f=b=>{try{return bS(b,a)}catch{throw new bK(`Invalid wildcard semver: ${a}`)}},g=f(e[0]);if(1===e.length)b=[g,0,0],c=[g+1,0,0];else{let a=f(e[1]);b=[g,a,0],c=[g,a+1,0]}return{lower:b,upper:c}}(String(e));return bU(a,b)>=0&&0>bU(a,c)}default:throw new bK(`Unknown operator: ${f}`)}}async function bP(a,b,c,d=!1,e){let f=String(a.value);if(!(f in c))throw new bL(`cohort ${f} not found in local cohorts - likely a static cohort that requires server evaluation`);return bQ(c[f],b,c,d,e)}async function bQ(a,b,c,d=!1,e){if(!a)return!0;let f=a.type,g=a.values;if(!g||0===g.length)return!0;let h=!1;if("values"in g[0]){for(let a of g)try{let g=await bQ(a,b,c,d,e);if("AND"===f){if(!g)return!1}else if(g)return!0}catch(b){if(b instanceof bL)throw b;if(b instanceof bK)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),h=!0;else throw b}if(h)throw new bK("Can't match cohort without a given cohort property value");return"AND"===f}for(let a of g)try{let g;if("cohort"===a.type)g=await bP(a,b,c,d,e);else if("flag"===a.type){if(!e)throw new bK(`Flag dependency '${a.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);g=await e(a)}else g=bO(a,b);let h=a.negation||!1;if("AND"===f){if(!g&&!h||g&&h)return!1}else if(g&&!h||!g&&h)return!0}catch(b){if(b instanceof bL)throw b;if(b instanceof bK)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),h=!0;else throw b}if(h)throw new bK("can't match cohort without a given cohort property value");return"AND"===f}function bR(a){try{return new RegExp(a),!0}catch(a){return!1}}function bS(a,b){if(!/^\d+$/.test(a)||a.length>1&&"0"===a[0])throw new bK(`Invalid semver: ${b}`);return parseInt(a,10)}function bT(a){let b=String(a).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!b||b.startsWith("."))throw new bK(`Invalid semver: ${a}`);let c=b.split("."),d=b=>void 0===b||""===b?0:bS(b,a);return[d(c[0]),d(c[1]),d(c[2])]}function bU(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 bV(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 bK(`${a} is in an invalid date format`)}throw new bK(`The date provided ${a} must be a string, number, or date object`)}let bW=["--unhandled-rejections","--unhandled_rejections"],bX=new Set(["throw","strict","warn","warn-with-error-code","none"]),bY=[...globalThis.process?.execArgv??[]],bZ=globalThis.process?.env?.NODE_OPTIONS;function b$(a){let b;for(let c=0;c<a.length;c++){let d=a[c],e=bW.find(a=>d===a||d.startsWith(`${a}=`));if(!e)continue;let f=d===e?a[++c]:d.slice(e.length+1);bX.has(f)&&(b=f)}return b}let b_=function(a=bY,b=bZ){return b$(a)??b$(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 b0(a,b,c){a(b,{mechanism:{type:"unhandledRejection"===c?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function b1(a,b,c,d,e){if(b>c&&(d.warn("min cannot be greater than max."),b=c),G(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),b1(e||c,b,c,d)}class b2{constructor(a){this._buckets={},this._onBucketRateLimited=a._onBucketRateLimited,this._bucketSize=b1(a.bucketSize,0,100,a._logger),this._refillRate=b1(a.refillRate,0,this._bucketSize,a._logger),this._refillInterval=b1(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 bo=bn;class b3{constructor(a,b,c){this.client=a,this._exceptionAutocaptureEnabled=b.enableExceptionAutocapture||!1,this._logger=c,this._rateLimiter=new b2({...function(a={}){return{refillRate:a.exceptionRateLimiterRefillRate??a.__exceptionRateLimiterRefillRate??1,bucketSize:a.exceptionRateLimiterBucketSize??a.__exceptionRateLimiterBucketSize??10}}(b),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(a){return A(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=bo.getInjectedReleaseId();return h&&(f.$release_id=h),{event:"$exception",distinctId:d,properties:{...g,...f},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(!function(b,c,d=b_){let e=globalThis.process;if(e){let f;if("strict"===d)return e.on("uncaughtExceptionMonitor",(a,c)=>b0(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;b0(b,d,e),f||0!==g||(f=!0,c(d))},{_posthogErrorHandler:!0})))}}(this.onException.bind(this),this.onFatalError.bind(this)),function(a,b=b_){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,b){this.client.addPendingPromise((async()=>{if(!b3.isPreviouslyCapturedError(a)){let c=await b3.buildEventMessage(this.client.getErrorPropertiesBuilder(),a,b),d=c.properties,e=d?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(e)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:e}):this.client._capturePreparedEvent(c,!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 b4{getProperty(a){return this._memoryStorage[a]}setProperty(a,b){this._memoryStorage[a]=null!==b?b:void 0}constructor(){this._memoryStorage={}}}let b5="analytics";class b6 extends Error{constructor({requestId:a,drops:b,retryExhausted:c,cause:d}){super(b6.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 b7(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 b8=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:b7},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:b7},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:b7},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(a){return"string"==typeof a?a:void 0}}],b9=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function ca(a,b,c){void 0===c||b in a||(a[b]=c)}function cb(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 b8)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 b9)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,ca(c,"$set",a.$set),ca(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 cc=new Set([408,500,502,503,504]);class cd{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=>Y(b,a))),this.generateRequestId=b.generateRequestId??ak,this.compress=b.compress??r}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(cb)};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=v({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&&cc.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 b6({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=Y(()=>{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 b6({requestId:a,drops:b,retryExhausted:c.map(a=>a.uuid),cause:d}))}surfacePartialDrops(a,b){b.length>0&&this.onError(new b6({requestId:a,drops:b,retryExhausted:[]}))}async cancelBody(a){try{await a.body?.cancel()}catch{}}}let ce="ai-capture",cf="/i/v0/ai/batch/",cg=new TextEncoder;function ch(a){return cg.encode(v(a)).length}let ci=new Set;function cj(a,b){ci.has(a)||(ci.add(a),console.warn(`[PostHog] ${b}`))}class ck extends bk{constructor(a,b={}){const c=function(a){return"string"==typeof a?a.trim():""}(a),d={...b,maxQueueSize:b.maxQueueSize??1e4,flushInterval:b.flushInterval??5e3,host:function(a){return("string"==typeof a?a.trim():"")||"https://us.i.posthog.com"}(b.host),personalApiKey:function(a){return("string"==typeof a?a.trim():"")||void 0}(b.secretKey??b.personalApiKey)};if(super(c,d),this._memoryStorage=new b4,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=d,this.captureMode=function(){let a="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return"v0"===a||"v1"===a?a:"v0"}(),this.enableFullAiCapture=!0===d.enableFullAiCapture,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof d.featureFlagsPollingInterval?Math.max(d.featureFlagsPollingInterval,100):3e4,"number"==typeof d.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(d.waitUntilDebounceMs,0)),"number"==typeof d.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(d.waitUntilMaxWaitMs,0)),!this.disabled&&d.personalApiKey){if(d.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!==d.enableLocalEvaluation&&(this.featureFlagsPoller=new bM({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:d.personalApiKey,projectApiKey:c,timeout:d.requestTimeout??1e4,host:this.host,fetch:d.fetch,onError:a=>{this._events.emit("error",a)},onLoad:a=>{this._events.emit("localEvaluationFlagsLoaded",a)},onMinimalFlagCalledEvents:a=>{this._minimalFlagCalledEvents=a},customHeaders:this.getCustomHeaders(),cacheProvider:d.flagDefinitionCacheProvider,strictLocalEvaluation:d.strictLocalEvaluation}))}this.errorTracking=new b3(this,d,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=d.maxCacheSize||5e4}enqueue(a,b,c,d){super.enqueue(a,b,c,d),this.scheduleDebouncedFlush()}async flush(){let a=this.flushWithPendingPromises(),b=this.options.waitUntil;if(b&&!this._waitUntilCycle)try{b(a.catch(()=>{}))}catch{}return a}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=Y(()=>{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.flushWithPendingPromises()}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":b5}persistedQueueKeyForRoute(a){return a===ce?n.AiCaptureQueue:"ai"===a?n.AiQueue:n.Queue}getActiveQueueRoutes(){let a="v1"===this.captureMode?[b5,"ai"]:[b5];return this._aiCaptureRouteActive&&a.push(ce),a}getBatchEndpointPath(a){return a===ce?cf:super.getBatchEndpointPath(a)}async sendBatch(a,b,c=b5){if(c===ce)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=ch(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 ${cf}, 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,ce)}catch(d){if(!bg(d))throw d;if(1===a.length){let[b]=a,c="string"==typeof b.event?b.event:"unknown",d=`Event ${c} (${ch(b)} bytes) was rejected with 413 by ${cf} 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 cd({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.50.0"}get metrics(){var a;let b;return this._metrics||(this._metrics=new af(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}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}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=U(a.uuid,ak);return this._sendPreparedAiEvent({...a,uuid:b},!1),b}async captureAiImmediate(a){if(this.disabled)return;let b=U(a.uuid,ak);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,ce)}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}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}}}catch(b){if(b instanceof bL||b instanceof bK)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=bE.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===b.minimalFlagCalledEvents,f=b.requestId,g=b.evaluatedAt;let c=[];b.errorsWhileComputingFlags&&c.push(bE.ERRORS_WHILE_COMPUTING),b.quotaLimited?.includes("feature_flags")&&c.push(bE.QUOTA_LIMITED);let d=b.flags[a];if(void 0===d)c.push(bE.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}}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){cj("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(cj("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){cj("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 bF({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new bF({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,flags:{}});let{groups:g,disableGeoip:h,flagKeys:i}=f||{},{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={},p=!1,q=!1,r=await this.featureFlagsPoller?.getAllFlagsAndPayloads(n,i),s=new Set;if(r)for(let[a,b]of Object.entries(r.response)){let c=this.featureFlagsPoller?.featureFlagsByKey[a];o[a]={key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:r.payloads[a],id:c?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:c?.has_experiment},s.add(a)}if((!r||r.fallbackToFlags)&&!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,p=!!a.errorsWhileComputingFlags,q=Array.isArray(a.quotaLimited)&&a.quotaLimited.includes("feature_flags"),Object.entries(a.flags))){let a;if(!s.has(b)){if(e.metadata?.payload!==void 0)try{a=JSON.parse(e.metadata.payload)}catch{a=e.metadata.payload}o[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 o[a];continue}let c=o[a];o[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=o[a];c&&(o[a]={...c,payload:b})}return new bF({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:o,requestId:c,evaluatedAt:d,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:p,quotaLimited:q})}_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}`;b in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[b].has(i)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[b]instanceof Set?this.distinctIdHasSentFlagCalls[b].add(i):this.distinctIdHasSentFlagCalls[b]=new Set([i]),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 Z(this._metrics.flush().catch(()=>{}),Math.max(0,b-Date.now())),this._metrics.reset());try{return await super._shutdown(Math.max(0,b-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},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=Y(()=>{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(I(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(!b3.isPreviouslyCapturedError(a)){let f=Error("PostHog syntheticException");this.addPendingPromise(b3.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(!b3.isPreviouslyCapturedError(a)){let e=Error("PostHog syntheticException");return this.addPendingPromise(b3.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(),n=b.includeContextProperties??!0,o=c||l?.distinctId,p=n?{...this.props,...l?.properties||{},...e||{}}:{...e||{}};o||(o=ak(),p.$process_person_profile=!1),n&&l?.sessionId&&!p.$session_id&&(p.$session_id=l.sessionId);let q=this._shouldSendMinimalFlagCalledEvent(d,p)?m(p):p,r=this._runBeforeSend({distinctId:o,event:d,properties:q,groups:f,flags:g,sendFeatureFlags:h,timestamp:i,disableGeoip:j,uuid:k});if(!r)return Promise.reject(null);let s=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){cj("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(r.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=r.groups||f;return{...a,...r.properties||{},...void 0!==b&&Object.keys(b).length>0?{$groups:b}:{}}});return"$pageview"===r.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof s.$raw_user_agent&&bD(s.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(r.event="$bot_pageview",s.$browser_type="bot"),{distinctId:r.distinctId,event:r.event,properties:s,options:{timestamp:r.timestamp,disableGeoip:r.disableGeoip,uuid:r.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 bo=bn,cl=a.i(78500);class cm{constructor(){this.storage=new cl.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||{}}}}}var cn=a.i(27028);let co=(0,a.i(12057).promisify)(cn.gzip);async function cp(a,b=!0){try{let b=await co(a);return new Blob([new Uint8Array(b)])}catch(a){return b&&console.error("Failed to gzip compress data",a),null}}var bo=bn;let cq="posthog-node";function cr(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[ct.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=bo.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 cs(a,b){let c=cr(a,b);return{name:cq,processEvent:a=>c(a)}}class ct{static #a=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(a,b,c,d,e){this.name=cq,this.name=cq,this.setupOnce=function(f,g){f(cr(a,{organization:b,projectId:g()?.getClient()?.getDsn()?.projectId,prefix:c,severityAllowList:d,sendExceptionsToPostHog:e??!0}))}}}a.s(["PostHogSentryIntegration",0,ct,"createEventProcessor",0,cr,"sentryIntegration",0,cs],9318);let cu=/[\x00-\x1f\x7f-\x9f]/g;function cv(a,b,c){null!=c&&""!==c&&(a[b]=c)}function cw(a){return Array.isArray(a)?a[0]:a}function cx(a){if(Array.isArray(a)){for(let b of a){let a=cx(b);if(void 0!==a)return a}return}if("string"!=typeof a)return;let b=a.replace(cu,"").trim();if(b)return b.length>1e3?b.slice(0,1e3):b}function cy(a,b){var c,d;let e,{sessionId:f,distinctId:g}=function(a){if(!a)return{};let b=cx(a["x-posthog-session-id"]),c=cx(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 cv(h,"$current_url",(c=b.originalUrl||b.url,i?V(c):c)),cv(h,"$request_method",b.method),cv(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?V(e):e)),cv(h,"$user_agent",cw(b.headers["user-agent"])),cv(h,"$ip",function(a){let b=cw(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 cz(a,b){var c;b.use((c=a,(a,b,d)=>{c.withContext(cy(c,a),()=>d())}))}function cA(a,b){var c;b.use((c=a,(a,b,d,e)=>{if(b3.isPreviouslyCapturedError(a))return void e(a);let f=cy(c,b),g=Error("Synthetic exception"),h={...void 0!==f.sessionId?{$session_id:f.sessionId}:{},...f.properties||{},$response_status_code:d.statusCode};c.addPendingPromise(b3.buildEventMessage(c.getErrorPropertiesBuilder(),a,{mechanism:{type:"middleware",handled:!1},syntheticException:g},f.distinctId,h).then(a=>c._capturePreparedEvent(a,!1))),e(a)}))}a.s(["setupExpressErrorHandler",0,cA,"setupExpressRequestContext",0,cz],40602),a.s([],51328);class cB extends ck{getLibraryId(){return"posthog-node"}compressPayload(a){return cp(a,this.isDebug)}initializeContext(){return new cm}createErrorPropertiesBuilder(){let a;return new bo.ErrorPropertiesBuilder([new bo.EventCoercer,new bo.ErrorCoercer,new bo.ObjectCoercer,new bo.StringCoercer,new bo.PrimitiveCoercer],bo.createStackParser("node:javascript",bo.nodeStackLineParser),[(a=function(a=process.argv[1]?(0,h.dirname)(process.argv[1]):process.cwd(),b="\\"===h.sep){let c=b?i(a):a;return a=>{if(!a)return;let d=b?i(a):a,{dir:e,base:f,ext:g}=h.posix.parse(d);(".js"===g||".mjs"===g||".cjs"===g)&&(f=f.slice(0,-1*g.length));let j=decodeURIComponent(f);e||(e=".");let k=e.lastIndexOf("/node_modules");if(k>-1)return`${e.slice(k+14).replace(/\//g,".")}:${j}`;if(e.startsWith(c)){let a=e.slice(c.length+1).replace(/\//g,".");return a?`${a}:${j}`:j}return j}}(),async b=>{for(let c of b)c.module=a(c.filename);return b}),a=>bv(a,void 0,this._logger),function(a=process.cwd()){h.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,h.isAbsolute)(d.filename)&&(d.filename=b((0,h.relative)(c,b(d.filename))));return a}}()])}}a.s(["PostHog",0,cB],81035),a.i(81035),a.i(51328),a.i(9318),a.i(40602),a.i(46539),a.s(["FeatureFlagError",0,o,"FeatureFlagEvaluations",0,bF,"PostHogSentryIntegration",0,ct,"cookieStateToProperties",0,aq,"cookieStoreFromHeader",0,am,"createEventProcessor",0,cr,"getPostHogCookieName",0,an,"parsePostHogCookie",0,ar,"readPostHogCookie",0,ap,"sentryIntegration",0,cs,"serializePostHogCookie",0,ao,"setupExpressErrorHandler",0,cA,"setupExpressRequestContext",0,cz,"uuidv7",0,ak],80456),a.i(80456),a.s(["FeatureFlagError",0,o,"FeatureFlagEvaluations",0,bF,"PostHog",0,cB,"PostHogSentryIntegration",0,ct,"cookieStateToProperties",0,aq,"cookieStoreFromHeader",0,am,"createEventProcessor",0,cr,"getPostHogCookieName",0,an,"parsePostHogCookie",0,ar,"readPostHogCookie",0,ap,"sentryIntegration",0,cs,"serializePostHogCookie",0,ao,"setupExpressErrorHandler",0,cA,"setupExpressRequestContext",0,cz,"uuidv7",0,ak],74493)}];
|
|
1
|
+
module.exports=[74493,a=>{"use strict";let b,c,d,e,f;var g,h=a.i(14747);function i(a){return a.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}let j=a=>void 0===a?void 0:a.variant??a.enabled,k=a=>{if("string"!=typeof a)return a;try{return JSON.parse(a)}catch{return a}},l=["$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","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],m=(a,b=[])=>{let c={},d=b=>{void 0!==a[b]&&(c[b]=a[b])};return l.forEach(d),b.forEach(d),c},n=["is_not","is_set"];class o extends Error{constructor(a){super(a),this.name=this.constructor.name,Object.setPrototypeOf(this,o.prototype)}}function p(a){try{return new RegExp(a),!0}catch{return!1}}function q(a,b,c){if(!/^\d+$/.test(a)||"strict"===c&&a.length>1&&"0"===a[0])throw new o(`Invalid semver: ${b}`);return parseInt(a,10)}function r(a,b="strict"){let c=String(a).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!c||c.startsWith("."))throw new o(`Invalid semver: ${a}`);let d=c.split("."),e=c=>void 0===c||""===c?0:q(c,a,b);return[e(d[0]),e(d[1]),e(d[2])]}function s(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 t(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 o(`${a} is in an invalid date format`)}throw new o(`The date provided ${a} must be a string, number, or date object`)}async function u(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 v(a,b,c=""){return parseInt((await u(`${a}.${b}${c}`)).slice(0,15),16)/0x1000000000000000}function w(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 x(a,b,c){let d=await v(a,b,"variant");return w(c).find(a=>d>=a.valueMin&&d<a.valueMax)?.key}var y=((g={}).AnonymousId="anonymous_id",g.DistinctId="distinct_id",g.Props="props",g.EnablePersonProcessing="enable_person_processing",g.PersonMode="person_mode",g.FeatureFlagDetails="feature_flag_details",g.FeatureFlags="feature_flags",g.FeatureFlagPayloads="feature_flag_payloads",g.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",g.BootstrapFeatureFlags="bootstrap_feature_flags",g.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",g.OverrideFeatureFlags="override_feature_flags",g.Queue="queue",g.AiQueue="ai_queue",g.AiCaptureQueue="ai_capture_queue",g.LogsQueue="logs_queue",g.OptedOut="opted_out",g.SessionId="session_id",g.SessionStartTimestamp="session_start_timestamp",g.SessionLastTimestamp="session_timestamp",g.PersonProperties="person_properties",g.GroupProperties="group_properties",g.InstalledAppBuild="installed_app_build",g.InstalledAppVersion="installed_app_version",g.SessionReplay="session_replay",g.PushRegistered="push_registered",g.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",g.SurveyLastSeenDate="survey_last_seen_date",g.SurveysSeen="surveys_seen",g.Surveys="surveys",g.RemoteConfig="remote_config",g.FlagsEndpointWasHit="flags_endpoint_was_hit",g.DeviceId="device_id",g);let z={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}`},A="[Truncated]",B="[Unserializable]";function C(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 D(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"}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let E=Array.isArray,F=Object.prototype;F.hasOwnProperty;let G=F.toString,H=E||function(a){return"[object Array]"===G.call(a)},I=a=>a===Object(a)&&!H(a),J=a=>void 0===a,K=a=>"[object String]"==G.call(a),L=a=>K(a)&&0===a.trim().length,M=a=>null===a,N=a=>J(a)||M(a),O=a=>"[object Number]"==G.call(a)&&a==a;function P(a){return null===a||"object"!=typeof a}function Q(a,b){return Object.prototype.toString.call(a)===`[object ${b}]`}function R(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 T(a,Error)}}function S(a){return"u">typeof Event&&T(a,Event)}function T(a,b){try{return a instanceof b}catch{return!1}}let U="Android",V="BlackBerry",W="Nintendo",X="PlayStation",Y="Xbox",Z="Windows",$="(\\d+(\\.\\d+)?)";RegExp("Version/"+$),RegExp(Y,"i"),RegExp(X+" \\w+","i"),RegExp(W+" \\w+","i"),RegExp(V+"|PlayBook|BB10","i");RegExp("rv:"+$),RegExp("Edge?\\/"+$),RegExp("(Chrome|CrMo)\\/"+$),RegExp("CriOS\\/"+$),RegExp("(UCBrowser|UCWEB)\\/"+$),RegExp("(Opera|OPR)\\/"+$),RegExp("Firefox\\/"+$),RegExp("FxiOS\\/"+$),RegExp("Konqueror[:/]?"+$,"i"),RegExp(V+" "+$),RegExp("android\\s"+$,"i"),RegExp("SamsungBrowser\\/"+$),RegExp("OculusBrowser\\/"+$),RegExp("Vivaldi\\/"+$),RegExp("YaBrowser\\/"+$),RegExp("Whale\\/"+$),RegExp("Brave\\/"+$),RegExp("(DuckDuckGo|Ddg)\\/"+$),RegExp("PaleMoon\\/"+$),RegExp("Waterfox\\/"+$),RegExp("GSA\\/"+$),RegExp("(rv:|MSIE )"+$),RegExp("rv:"+$),RegExp(Y+"; "+Y+" (.*?)[);]","i"),RegExp(W,"i"),RegExp(X,"i"),RegExp(Z,"i"),RegExp("("+U+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+U+")","i");let _=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function aa(a,b){return"string"==typeof a&&_.test(a)?a:b()}function ab(a,b){let c=Error(b);try{Object.defineProperty(c,"name",{value:a,writable:!0,enumerable:!0,configurable:!0})}catch{}return c}function ac(a){return a?a.split("#")[0]:a}async function ad(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 ae(){return new Date().toISOString()}function af(a,b){let c=setTimeout(a,b);return c?.unref&&c?.unref(),c}async function ag(a,b,c){let d;try{return await Promise.race([a,new Promise((a,e)=>{d=af(()=>{try{c?.(),a()}catch(a){e(a)}},b)})])}finally{clearTimeout(d)}}function ah(a){return Promise.all(a.map(a=>(a??Promise.resolve()).then(a=>({status:"fulfilled",value:a}),a=>({status:"rejected",reason:a}))))}let ai=a=>{throw ab("NativeGzipValidationError",`Native gzip produced invalid output: ${a}`)},aj=async(a,c)=>{a.size<18&&ai("too-short");let d=new Uint8Array(await a.slice(0,10).arrayBuffer());d.length>=2&&31===d[0]&&139===d[1]&&8===d[2]||ai("invalid-header");let e=new DataView(await a.slice(a.size-8).arrayBuffer());e.getUint32(0,!0)!==(a=>{let c=(()=>{if(b)return b;b=[];for(let a=0;a<256;a++){let c=a;for(let a=0;a<8;a++)c=1&c?0xedb88320^c>>>1:c>>>1;b[a]=c>>>0}return b})(),d=0xffffffff;for(let b=0;b<a.length;b++)d=c[(d^a[b])&255]^d>>>8;return(0xffffffff^d)>>>0})(c)&&ai("invalid-crc");let f=c.length>>>0;e.getUint32(4,!0)!==f&&ai("invalid-size")};async function ak(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 aj(g,b),g}catch(a){if(c?.rethrow)throw a;return b&&console.error("Failed to gzip compress data",a),null}}let al=Object.prototype.propertyIsEnumerable;function am(a,b){try{return an(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function an(a,b,c,d){let e=[];for(let f in a)if(al.call(a,f)){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(M(g)||J(g))continue;e.push({key:C(f),value:function a(b,c,d,e){if(d.remainingNodes<=0)return{stringValue:A};if(d.remainingNodes--,"[object Boolean]"===G.call(b))return{boolValue:b};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:C(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:"[Circular]"};if(e>=20)return{stringValue:A};if(b instanceof Date){let a=Number.isFinite(b.getTime())?b.toISOString():String(b);return{stringValue:"string"==typeof a?C(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(H(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(N(g))continue;f.push(a(g,c,d,e))}catch{f.push({stringValue:B})}return b.length>h&&f.push({stringValue:A}),f}(b,c,d,e+1)}};return{kvlistValue:{values:an(b,c,d,e+1)}}}finally{d.ancestors.delete(b)}}return{stringValue:C(String(b))}}(g,b,c,d)})}catch{e.push({key:C(f),value:{stringValue:B}})}}return e}let ao=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function ap(a){return String(a)+"000000"}function aq(a,b,c,d){let e="";return d&&(e=Object.keys(d).sort().map(a=>`${JSON.stringify(a)}:${JSON.stringify(d[a])}`).join(",")),`${a}\u0000${b}\u0000${c??""}\u0000${e}`}class ar{constructor(a,b,c){this._instance=a,this._config=b,this._logger=c,this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,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._clearFlushTimer(),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=aq(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),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush||(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(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(ao.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,ao)]+=1}}}_runBeforeSend(a){let b=this._config.beforeSend;if(!b)return a;let c=H(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||(this._flushTimer=af(()=>{this._flushTimer=void 0,this.flush().catch(a=>{this._logger.error("Metrics flush failed:",a)})},this._config.flushIntervalMs))}_clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}async _doFlush(){if(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(c.kind){case"ok":return;case"retry-later":this._mergeWindowBack(a),this._armFlushTimer();return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",c.error);return}}_buildPayload(a){var b,c,d,e,f,g,h;return e=this._buildMetrics(a),b=this._config,c=this._instance.getLibraryId(),d=this._instance.getLibraryVersion(),f={...b.resourceAttributes,"service.name":b.serviceName||"unknown_service",...b.environment&&{"deployment.environment":b.environment},...b.serviceVersion&&{"service.version":b.serviceVersion},"telemetry.sdk.name":c,"telemetry.sdk.version":d},g=this._instance.getLibraryId(),h=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:am(f)},scopeMetrics:[{scope:{name:g,version:h},metrics:e}]}]}}_buildMetrics(a){let b=ap(Date.now()),c=new Map;for(let d of a.values()){let a=aq(d.type,d.name,d.unit,void 0),e=c.get(a);e||(e={name:d.name,...d.unit&&{unit:d.unit}},"count"===d.type?e.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===d.type?e.gauge={dataPoints:[]}:e.histogram={aggregationTemporality:1,dataPoints:[]},c.set(a,e));let f=am(d.attributes??{},this._logger),g=ap(d.windowStartMs);if("count"===d.type){let a={attributes:f,startTimeUnixNano:g,timeUnixNano:b,asDouble:d.total??0};e.sum.dataPoints.push(a)}else if("gauge"===d.type){let a={attributes:f,timeUnixNano:b,asDouble:d.last??0};e.gauge.dataPoints.push(a)}else if(d.hist){let a={attributes:f,startTimeUnixNano:g,timeUnixNano:b,count:d.hist.count,sum:d.hist.sum,min:d.hist.min,max:d.hist.max,bucketCounts:d.hist.bucketCounts,explicitBounds:ao};e.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.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 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),this.counter&0x40000000-1,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=()=>(c||(c=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 aA(a){let b=Date.now();return JSON.stringify({distinct_id:a,$device_id:a,$user_state:"anonymous",$sesid:[b,aw(),b]})}function aB(a,b){let c=az(b),d=a.get(c);return d?aD(d.value):null}function aC(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 aD(a){if(!a)return null;try{let b=JSON.parse(a);if(!b||"object"!=typeof b||!b.distinct_id)return null;let c=H(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}}class aE{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)}}class aF{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 aG=(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=>aG(`${a} ${d}`,b,c)}};class aH{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&&H(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;return null!=a.cause&&(c=this.parseStacktrace(a.cause,b)),""!=a.stack&&null!=a.stack&&(d=this.applyChunkIds(this.stackParser(a.stack,a.synthetic?b.skipFirstLines:0),b.chunkIdMap)),{...a,cause:c,stack:d}}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={type:a.type,value:a.value,mechanism:{type:b.type??"generic",handled:b.handled??!0,synthetic:a.synthetic??!1}};a.stack&&(c.stacktrace={type:"raw",frames:a.stack});let d=[c];return null!=a.cause&&d.push(...this.convertToExceptionList(a.cause,{...b,handled:!0})),d}buildParsingContext(a){return{chunkIdMap:function(a){let b=globalThis._posthogChunkIds;if(!b)return;let c=Object.keys(b);return f&&c.length===e?f:(e=c.length,f=c.reduce((c,e)=>{d||(d={});let f=d[e];if(f)c[f[0]]=f[1];else{let f=a(e);for(let a=f.length-1;a>=0;a--){let g=f[a],h=g?.filename,i=b[e];if(h&&i){c[h]=i,d[e]=[h,i];break}}}return c},{}))}(this.stackParser),skipFirstLines:a.skipFirstLines??1}}buildCoercingContext(a,b,c=0){let d=(c,d)=>{if(d<=4){let e=this.buildCoercingContext(a,b,d);return this.applyCoercers(c,e)}};return{...b,syntheticException:0==c?b.syntheticException:void 0,mechanism:a,apply:a=>d(a,c),next:a=>d(a,c+1)}}}function aI(a,b,c,d,e){let f={platform:a,filename:b,function:"<anonymous>"===c?"?":c,in_app:!b?.startsWith("webkit-masked-url://")&&"<anonymous>"!==b};return J(d)||(f.lineno=d),J(e)||(f.colno=e),f}a.s(["ErrorPropertiesBuilder",0,aH],6762);let aJ=(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]},aK=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,aL=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,aM=/\((\S*)(?::(\d+))(?::(\d+))\)/,aN=(a,b)=>{let c=aK.exec(a);if(c){let[,a,d,e]=c;return aI(b,a,"?",+d,+e)}let d=aL.exec(a);if(d){if(d[2]&&0===d[2].indexOf("eval")){let a=aM.exec(d[2]);a&&(d[2]=a[1],d[3]=a[2],d[4]=a[3])}let[a,c]=aJ(d[1]||"?",d[2]);return aI(b,c,a,d[3]?+d[3]:void 0,d[4]?+d[4]:void 0)}},aO=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,aP=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,aQ=(a,b)=>{let c=aO.exec(a);if(c){if(c[3]&&c[3].indexOf(" > eval")>-1){let a=aP.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]=aJ(d,a),aI(b,a,d,c[4]?+c[4]:void 0,c[5]?+c[5]:void 0)}},aR=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,aS=(a,b)=>{let c=aR.exec(a);return c?aI(b,c[2],c[1]||"?",+c[3],c[4]?+c[4]:void 0):void 0},aT=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,aU=(a,b)=>{let c=aT.exec(a);return c?aI(b,c[2],c[3]||"?",+c[1]):void 0},aV=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,aW=(a,b)=>{let c=aV.exec(a);return c?aI(b,c[5],c[3]||c[4]||"?",+c[1],+c[2]):void 0},aX=/^\s*[-]{4,}$/,aY=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,aZ=/^Promise\.(?:all|any)$/,a$=/^index \d+$/,a_=(a,b)=>{let c=a.match(aY);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]),aZ.test(e)&&a$.test(h||"")&&(h="node:internal/promise"),{filename:h?decodeURI(h):void 0,module:void 0,function:e,lineno:a0(c[3]),colno:a0(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(aX))return{filename:a,platform:b}};function a0(a){return parseInt(a||"",10)||void 0}let a1=/\(error: (.*)\)/;function a2(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 a3(){return a4("web:javascript",aN,aQ)}function a4(a,...b){return(c,d=0)=>{let e=[],f=c.split("\n");for(let c=d;c<f.length;c++){let d=f[c];if(d.length>1024)continue;let g=a1.test(d)?d.replace(a1,"$1"):d;if(!g.match(/\S*Error: /)){for(let c of b){let b=c(g,a);if(b){e.push(b);break}}if(e.length>=50)break}}return a2(e)}}a.s(["createDefaultStackParser",0,a3,"createStackParser",0,a4,"reverseAndStripFrames",0,a2],67970);class a5{match(a){return this.isDOMException(a)||this.isDOMError(a)}coerce(a,b){let c=K(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 Q(a,"DOMException")}isDOMError(a){return Q(a,"DOMError")}}a.s(["DOMExceptionCoercer",0,a5],51671);class a6{match(a){return!!Q(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 K(a.message)&&a.message.length>0}_buildLocationStack(a){let b=a.lineno??0,c=a.colno??0;if(K(a.filename)&&0!==a.filename.length&&0!==b)return`Error
|
|
2
|
+
at ${a.filename}:${b}:${c}`}}a.s(["ErrorEventCoercer",0,a6],75368);let a7=["fatal","error","warning","log","info","debug"];function a8(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 a9{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(S(a))return a.constructor.name;let b="name"in a?a.name:void 0;return K(b)&&!L(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=a8(a);return`${b&&"Object"!==b?`'${b}'`:"Object"} captured as exception with keys: ${c}`}isSeverityLevel(a){return K(a)&&!L(a)&&a7.indexOf(a)>=0}getStack(a){try{if(K(a.stacktrace)&&a.stacktrace.length>0)return a.stacktrace;return K(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(R(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,a9],93874);class ba{match(a){return S(a)}coerce(a,b){let c=a.constructor.name;return{type:c,value:`${c} captured as exception with keys: ${a8(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["EventCoercer",0,ba],46980);class bb{match(a){return P(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,bb],28150);class bc{match(a){return Q(a,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(a)}isCustomEventWrappingRejection(a){if(!S(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 P(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,bc],98140),a.s([],7610);let bd={MESSAGE:"$message",TIMESTAMP:"$timestamp"},be=new Set([bd.MESSAGE,bd.TIMESTAMP]),bf={enabled:!0,max_bytes:32768};function bg(a){return a?{enabled:a.enabled??bf.enabled,max_bytes:function(a,b){if(!O(a)||a===1/0||a===-1/0)return b;let c=Math.floor(a);return c<0?b:c}(a.max_bytes,bf.max_bytes)}:{...bf}}function bh(a){if(!a)return{sanitizedProperties:{},droppedKeys:[]};let b=[];return{sanitizedProperties:Object.keys(a).reduce((c,d)=>(be.has(d)?b.push(d):c[d]=a[d],c),{}),droppedKeys:b}}class bi{constructor(a){this._entries=[],this._totalBytes=0,this._config=bg(a)}setConfig(a){this._config=bg(a),this._trimToMaxBytes()}add(a){let b=function(a){let b;try{b=D(a)}catch{return}try{let a=JSON.parse(b);if(!I(a))return;let c=a[bd.MESSAGE],d=a[bd.TIMESTAMP];if(!K(c)||0===c.trim().length||!K(d)&&!O(d))return;return{step:a,json:b}}catch{return}}(a);if(!b)return;let c=bj(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 bj(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,bf,"EXCEPTION_STEP_INTERNAL_FIELDS",0,bd,"ExceptionStepsBuffer",0,bi,"getUtf8ByteLength",0,bj,"resolveExceptionStepsConfig",0,bg,"stripReservedExceptionStepFields",0,bh],97383),a.s([],48153);class bk{match(a){return R(a)}coerce(a,b){let c=this.getStack(a);return{type:this.getType(a),value:this.getMessage(a,b),stack:c??b.syntheticException?.stack,cause:a.cause?b.next(a.cause):void 0,synthetic:void 0===c}}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){return a.stacktrace||a.stack||void 0}}a.s(["ErrorCoercer",0,bk],10692);let bl=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class bm{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(bl);return d&&(b=d[1],c=d[2]),[b,c]}}a.s(["StringCoercer",0,bm],57802);class bn 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 bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let a=ab("AbortError","Response body read timed out");this.cancelResponseBody(a),this.responseBodyTextPromise=Promise.reject(a)}else{let a,b=new Promise((a,b)=>{this.responseBodyTimer=af(()=>{this._bodyReadTimedOut=!0;let a=ab("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 bo extends Error{constructor(a){super("Network error while fetching PostHog",a instanceof Error?{cause:a}:{}),this.error=a,this.name="PostHogFetchNetworkError"}}async function bp(a){if(a instanceof bn){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 bq(a){return a instanceof bo}function br(a){if(a instanceof bn)return 502===a.status||504===a.status;if(!(a instanceof bo))return!1;let b=a.error;return"ECONNREFUSED"!==(b?.code??b?.cause?.code)}function bs(a){return"object"==typeof a&&a instanceof bn&&413===a.status}function bt(a){return a instanceof bn?408===a.status||429===a.status||a.status>=500:bq(a)}function bu(a){return null!==a&&"object"==typeof a&&!Array.isArray(a)}let bv="default";class bw{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new aH([new bk,new a9,new bm,new bb],a3())}constructor(a,b={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new aF,this._events=new aE,this._isInitialized=!1;const c="string"==typeof a?a.trim():"",d="string"==typeof b.host?b.host.trim():"",e=!c;this._logger=function(a,b=a=>a()){return aG(a,b,function(a=console){return{log:a.log.bind(a),warn:a.warn.bind(a),error:a.error.bind(a),debug:a.debug.bind(a)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),e&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=c,this.host=function(a){return a?.replace(/\/+$/,"")}(d||"https://us.i.posthog.com"),this.flushAt=b.flushAt?Math.max(b.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,b.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,b.maxQueueSize??1e3),this.flushInterval=b.flushInterval??1e4,this.preloadFeatureFlags=b.preloadFeatureFlags??!0,this.defaultOptIn=b.defaultOptIn??!0,this.disableSurveys=b.disableSurveys??!1,this._retryOptions={retryCount:b.fetchRetryCount??3,retryDelay:b.fetchRetryDelay??3e3,retryCheck:bt},this.requestTimeout=b.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=b.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=b.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=b.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=b.disableGeoip??!0,this.disabled=(b.disabled??!1)||e,this.historicalMigration=b?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=b?.evaluationContexts??b?.evaluationEnvironments,b?.evaluationEnvironments&&!b?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!("CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&"function"==typeof Response.prototype.blob)||(b?.disableCompression??!1)}logMsgIfDebug(a){this.isDebug&&a()}wrap(a){return this.disabled?void this._logger.warn("The client is disabled"):this._isInitialized?a():void this._initPromise.then(()=>a())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(y.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(y.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(y.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={...b,...this.getCommonEventProperties()};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=m(c)),{distinct_id:a.distinct_id,event:a.event,properties:c}}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={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(h)};return this._logger.info("Flags URL",g),this.fetchWithRetry(g,i,{type:"required",consume:a=>a.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:br},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,j(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?k(c):void 0]}));return{...a,featureFlags:c,featureFlagPayloads:d}}{let b=a.featureFlags??{},c=Object.fromEntries(Object.entries(a.featureFlagPayloads||{}).map(([a,b])=>[a,k(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 bn)return{type:"api_error",statusCode:a.status};if(a instanceof bo){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=j(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(y.Props)),this._props||{}}set props(a){this._props=a}async register(a){this.wrap(()=>{this.props={...this.props,...a},this.setPersistedProperty(y.Props,this.props)})}async unregister(a){this.wrap(()=>{delete this.props[a],this.setPersistedProperty(y.Props,this.props)})}processBeforeEnqueue(a){return a}async flushStorage(){}getQueueRouteKey(a){return bv}persistedQueueKeyForRoute(a){return y.Queue}getActiveQueueRoutes(){return[bv]}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=af(()=>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=bu(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=aa(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:ae(),uuid:aa(b?.uuid,aw)};return(b?.disableGeoip??this.disableGeoip)&&(bu(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.flush().catch(async a=>{await bp(a)})}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(()=>ah([b])).then(()=>(this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=d,this.flushPromise=d,this.flushPromises.add(d),this.addPendingPromise(d),ah([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 ak(a,this.isDebug)}getBatchEndpointPath(a){return"/batch/"}async sendBatch(a,b,c=bv){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:ae()};this.historicalMigration&&(d.historical_migration=!0);let e=D(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=>!bs(a)&&bt(a)};try{await this.sendBatch(g,i,a)}catch(a){if(bs(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 bo||await h(),this._events.emit("error",a),a}await h(),b.push(...g),f+=g.length}}async _sendOtlpBatch({path:a,payload:b}){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let c=JSON.stringify(b),d=`${this.host}/i/v1/${a}?token=${encodeURIComponent(this.apiKey)}`,e=this.disableCompression?null:await this.compressPayload(c),f={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==e&&{"Content-Encoding":"gzip"}},body:e||c};try{return await this.fetchWithRetry(d,f,{type:"successful-write"},{retryCheck:a=>!bs(a)&&bt(a)}),{kind:"ok"}}catch(a){if(bs(a))return{kind:"too-large"};if(bt(a))return{kind:"retry-later",error:a};return{kind:"fatal",error:a}}}async _sendLogsBatch(a){return this._sendOtlpBatch({path:"logs",payload:a})}async _sendMetricsBatch(a){return this._sendOtlpBatch({path:"metrics",payload:a})}async fetchWithRetry(a,b,c,d,e){let f=b.body?b.body:"",g=-1;try{g=f instanceof Blob?f.size:f instanceof Uint8Array?f.byteLength:Buffer.byteLength(f,"utf8")}catch{g=f instanceof Blob?f.size:f instanceof Uint8Array?f.byteLength:new TextEncoder().encode(f).length}let h={...this._retryOptions,...d},i=0;return await ad(async()=>{let d,f,h;i++;let j=new AbortController,k=e??this.requestTimeout,l=Date.now()+k,m=new Promise((a,b)=>{d=af(()=>{let a=ab("AbortError",`Request timed out after ${k}ms`);b(a),j.abort(a)},k)}),n=!1,o=()=>h??=(async()=>{try{await f?.body?.cancel()}catch{}})();try{let d;try{d=this.fetch(a,{signal:j.signal,...b})}catch(a){throw new bo(a)}d.then(a=>{j.signal.aborted&&!n&&Promise.resolve(a.body?.cancel()).catch(()=>{})}).catch(()=>{});try{f=await Promise.race([d,m]),n=!0}catch(a){throw new bo(a)}if("no-cors"!==b.mode&&(f.status<200||f.status>=400))throw new bn(f,g,l,j);if("successful-write"===c.type){try{await Promise.race([o(),m])}catch{}return}try{return await Promise.race([c.consume(f),m])}catch(a){if(j.signal.aborted)throw new bo(a);throw a}}finally{clearTimeout(d),j.signal.aborted&&f&&o()}},{...h,retryCheck:a=>{let b=h.retryCheck(a);return b&&i<=h.retryCount&&a instanceof bn&&a.cancelResponseBody(),b}})}async _shutdown(a=3e4){await this._initPromise;let b=!1;if(this.clearFlushTimer(),!this.disabled)return ag((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 bn||bq(a))))throw a;await bp(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}}a.i(48153),a.i(6762),a.i(67970),a.s(["chromeStackLineParser",0,aN,"createDefaultStackParser",0,a3,"createStackParser",0,a4,"geckoStackLineParser",0,aQ,"nodeStackLineParser",0,a_,"opera10StackLineParser",0,aU,"opera11StackLineParser",0,aW,"reverseAndStripFrames",0,a2,"winjsStackLineParser",0,aS],64583),a.i(64583),a.i(7610),a.i(51671),a.i(10692),a.i(75368),a.i(57802),a.i(93874),a.i(46980),a.i(28150),a.i(98140),a.s(["DOMExceptionCoercer",0,a5,"ErrorCoercer",0,bk,"ErrorEventCoercer",0,a6,"EventCoercer",0,ba,"ObjectCoercer",0,a9,"PrimitiveCoercer",0,bb,"PromiseRejectionEventCoercer",0,bc,"StringCoercer",0,bm],54253),a.i(54253);class bx{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 by(){let a=globalThis._posthogReleaseId;return"string"==typeof a&&a.length>0?a:void 0}a.s(["ReduceableCache",0,bx],98966),a.i(98966),a.i(97383),a.s(["getInjectedReleaseId",0,by],28861),a.i(28861),a.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,bf,"DOMExceptionCoercer",0,a5,"EXCEPTION_STEP_INTERNAL_FIELDS",0,bd,"ErrorCoercer",0,bk,"ErrorEventCoercer",0,a6,"ErrorPropertiesBuilder",0,aH,"EventCoercer",0,ba,"ExceptionStepsBuffer",0,bi,"ObjectCoercer",0,a9,"PrimitiveCoercer",0,bb,"PromiseRejectionEventCoercer",0,bc,"ReduceableCache",0,bx,"StringCoercer",0,bm,"chromeStackLineParser",0,aN,"createDefaultStackParser",0,a3,"createStackParser",0,a4,"geckoStackLineParser",0,aQ,"getInjectedReleaseId",0,by,"getUtf8ByteLength",0,bj,"nodeStackLineParser",0,a_,"opera10StackLineParser",0,aU,"opera11StackLineParser",0,aW,"resolveExceptionStepsConfig",0,bg,"reverseAndStripFrames",0,a2,"stripReservedExceptionStepFields",0,bh,"winjsStackLineParser",0,aS],60485);var bz=a.i(60485),bA=bz,bB=a.i(2157),bC=a.i(12714),bD=a.i(50227),bE=a.i(1457);let bF=new bA.ReduceableCache(25),bG=new bA.ReduceableCache(20);async function bH(a,b=bC.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,bD.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=bL(a,d);if(void 0===f||bG.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=bM(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=bM(c)),b++}return e}(g);if(h.every(a=>(function(a,b){let c=bF.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}(bF,f,{});i.push(bJ(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=bL(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=bN(a);d<a;d++){let a=c[d];if(void 0===a)return void bK(b);b.pre_context.push(a)}if(void 0===c[a])return bK(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,bF,d),bF.reduce(),a}async function bI(a,b,c){let d,e=!1;try{d=await b(a,bB.constants.O_RDONLY|bB.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 bJ(a,b,c,d,e,f){let g=await bI(a,e,f);return void 0===g?void bG.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{bG.set(d,1),i();return}try{f=(0,bE.createInterface)({input:e})}catch{bG.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(){bG.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 bK(a){delete a.pre_context,delete a.context_line,delete a.post_context}function bL(a,b){return(0,bD.isAbsolute)(a)?JSON.stringify([null,a]):void 0===b?void 0:JSON.stringify([b,a])}function bM(a){return[bN(a),a+7]}function bN(a){return Math.max(1,a-7)}let bO=["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"],bP=function(a,b=[]){if(!a)return!1;let c=a.toLowerCase();return bO.concat(b).some(a=>{let b=a.toLowerCase();return -1!==c.indexOf(b)})},bQ={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};a.s(["FeatureFlagError",0,bQ],46539);class bR{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 bR({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(bQ.ERRORS_WHILE_COMPUTING),this._quotaLimited&&e.push(bQ.QUOTA_LIMITED),void 0===b&&e.push(bQ.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})}}class bS extends Error{constructor(a){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=a,Object.setPrototypeOf(this,bS.prototype)}}class bT extends Error{constructor(a){super(a),function(a,b){a.name=b.name,Error.captureStackTrace(a,b),Object.setPrototypeOf(a,b.prototype)}(this,bT)}}class bU{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()}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 bT||b instanceof o?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={...a,evaluationCache:a.evaluationCache??{}};return await Promise.all(f.map(async a=>{try{let{value:b,payload:e}=await this.computeFlagAndPayloadLocally(a,g);c[a.key]=b,e&&(d[a.key]=e)}catch(b){b instanceof bT||b instanceof o?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(f||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};d=void 0!==e?e:await this.computeFlagValueLocally(a,b);let g=this.getFeatureFlagPayload(a.key,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 o("Flag has experience continuity enabled");let g=(a.filters||{}).aggregation_group_type_index;if(void 0!=g){let c=this.groupTypeMapping[String(g)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${g} for feature flag ${a.key}`)),new o("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 o(`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}getFeatureFlagPayload(a,b){var c=this.featureFlagsByKey?.[a]?.filters?.payloads;if(!1===b||null==b||!c)return null;let d=c["boolean"==typeof b?b.toString():b]||null;return null==d?null:k(d)}async evaluateFlagDependency(a,b,c){let{evaluationCache:d}=c,e=a.key;if(!this.featureFlagsByKey)throw new o("Feature flags not available for dependency evaluation");if(!("dependency_chain"in a))throw new o(`Flag dependency property for '${e}' is missing required 'dependency_chain' field`);let f=a.dependency_chain;if(!Array.isArray(f))throw new o(`Flag dependency property for '${e}' has an invalid 'dependency_chain' (expected array, got ${typeof f})`);if(0===f.length)throw new o(`Circular dependency detected for flag '${e}' (empty dependency chain)`);for(let a of f){if(!(a in d)){let b=this.featureFlagsByKey[a];if(b)if(b.active)try{let e=await this.computeFlagValueLocally(b,c);d[a]=e}catch(b){throw new o(`Error evaluating flag dependency '${a}' for flag '${e}': ${b}`)}else d[a]=!1;else if(this.filteredOutFlagKeys.has(a))d[a]=!1;else throw new o(`Missing flag dependency '${a}' for flag '${e}'`)}if(null==d[a])throw new o(`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,f=a.filters||{},g=f.groups||[],h=f.aggregation_group_type_index,i=f.early_exit??!1,{groups:j,groupProperties:k}=d,l=!1;for(let m of g)try{let g=void 0!==m.aggregation_group_type_index?m.aggregation_group_type_index:h,n=c,o=b;if(g!==h&&null!=g){let b=this.groupTypeMapping[String(g)];if(!b||!(b in j)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${a.key}': group type index ${g} not available`));continue}if(!(b in k)){l=!0;continue}n=k[b],o=j[b]}let p=await this.isConditionMatch(a,o,m,n,d);if("match"===p){let b=m.variant,c=f.multivariate?.variants||[];e=b&&c.some(a=>a.key===b)?b:await this.getMatchingVariant(a,o)||!0;break}if(i&&"out_of_rollout_bound"===p){if(l)break;return!1}}catch(a){if(a instanceof bT)throw a;if(a instanceof o)l=!0;else throw a}if(void 0!==e)return e;if(l)throw new o("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(a,b,c,d,e){let f=c.rollout_percentage,g=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 bW(a,d,this.cohorts,this.debugMode,a=>this.evaluateFlagDependency(a,d,e));c="not_in"===a.operator?!b:b}else c="flag"===b?await this.evaluateFlagDependency(a,d,e):bV(a,d,g);if(!c)return"no_match"}if(void 0==f)return"match"}return void 0!=f&&await v(a.key,b)>f/100?"out_of_rollout_bound":"match"}async getMatchingVariant(a,b){return x(a.key,b,a.filters?.multivariate?.variants||[])}variantLookupTable(a){return w(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))})}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.groupTypeMapping,this.cohorts=a.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(!0===a.minimalFlagCalledEvents)}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(){return this.shouldBeginExponentialBackoff?Math.min(6e4,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);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 bS(`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.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new bS(`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 bS(`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={flags:c.flags??[],groupTypeMapping:c.group_type_mapping||{},cohorts:c.cohorts||{},minimalFlagCalledEvents:!0===c.minimal_flag_called_events};if(this.updateFlagState(d),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&a)try{await this.cacheProvider.onFlagDefinitionsReceived(d)}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 bS&&this.onError?.(a)}finally{this.pollerStopped||(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=af(()=>{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 ag(b,a,()=>{throw Error(`Cache shutdown timeout after ${a}ms`)})}catch(a){this.onError?.(Error(`Error during cache shutdown: ${a}`))}}}function bV(a,b,c){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 throw new o(`Property ${d} not found in propertyValues`);let h=b[d];if(null==h&&!n.includes(f))return c.warnFunction?.(`Property ${d} cannot have a value of null/undefined with the ${f} operator`),!1;let i=(a,b)=>Array.isArray(a)?a.map(a=>String(a).toLowerCase()).includes(String(b).toLowerCase()):String(a).toLowerCase()===String(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 String(h).toLowerCase().includes(String(e).toLowerCase());case"not_icontains":return!String(h).toLowerCase().includes(String(e).toLowerCase());case"starts_with":return String(h).toLowerCase().startsWith(String(e).toLowerCase());case"not_starts_with":return!String(h).toLowerCase().startsWith(String(e).toLowerCase());case"ends_with":return String(h).toLowerCase().endsWith(String(e).toLowerCase());case"not_ends_with":return!String(h).toLowerCase().endsWith(String(e).toLowerCase());case"regex":return p(String(e))&&null!==String(h).match(String(e));case"not_regex":return p(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)):NaN;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 o("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=t(e));let b=t(h);return"is_date_before"===f?b<a:b>a}case"semver_eq":return 0===s(r(String(h),g),r(String(e),g));case"semver_neq":return 0!==s(r(String(h),g),r(String(e),g));case"semver_gt":return s(r(String(h),g),r(String(e),g))>0;case"semver_gte":return s(r(String(h),g),r(String(e),g))>=0;case"semver_lt":return 0>s(r(String(h),g),r(String(e),g));case"semver_lte":return 0>=s(r(String(h),g),r(String(e),g));case"semver_tilde":{let a,b=r(String(h),g),{lower:c,upper:d}={lower:[(a=r(String(e),g))[0],a[1],a[2]],upper:[a[0],a[1]+1,0]};return s(b,c)>=0&&0>s(b,d)}case"semver_caret":{let a=r(String(h),g),{lower:b,upper:c}=function(a,b){let[c,d,e]=r(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 s(a,b)>=0&&0>s(a,c)}case"semver_wildcard":{let a=r(String(h),g),{lower:b,upper:c}=function(a,b){let c=String(a).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!c)throw new o(`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 q(c,a,b)}catch{}throw new o(`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 s(a,b)>=0&&0>s(a,c)}default:throw new o(`Unknown operator: ${f}`)}}(a,b,{warnFunction:c})}async function bW(a,b,c,d=!1,e){let f=String(a.value);if(!(f in c))throw new bT(`cohort ${f} not found in local cohorts - likely a static cohort that requires server evaluation`);return bX(c[f],b,c,d,e)}async function bX(a,b,c,d=!1,e){if(!a)return!0;let f=a.type,g=a.values;if(!g||0===g.length)return!0;let h=!1;if("values"in g[0]){for(let a of g)try{let g=await bX(a,b,c,d,e);if("AND"===f){if(!g)return!1}else if(g)return!0}catch(b){if(b instanceof bT)throw b;if(b instanceof o)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),h=!0;else throw b}if(h)throw new o("Can't match cohort without a given cohort property value");return"AND"===f}for(let a of g)try{let g;if("cohort"===a.type)g=await bW(a,b,c,d,e);else if("flag"===a.type){if(!e)throw new o(`Flag dependency '${a.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);g=await e(a)}else g=bV(a,b);let h=a.negation||!1;if("AND"===f){if(!g&&!h||g&&h)return!1}else if(g&&!h||!g&&h)return!0}catch(b){if(b instanceof bT)throw b;if(b instanceof o)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),h=!0;else throw b}if(h)throw new o("can't match cohort without a given cohort property value");return"AND"===f}let bY=["--unhandled-rejections","--unhandled_rejections"],bZ=new Set(["throw","strict","warn","warn-with-error-code","none"]),b$=[...globalThis.process?.execArgv??[]],b_=globalThis.process?.env?.NODE_OPTIONS;function b0(a){let b;for(let c=0;c<a.length;c++){let d=a[c],e=bY.find(a=>d===a||d.startsWith(`${a}=`));if(!e)continue;let f=d===e?a[++c]:d.slice(e.length+1);bZ.has(f)&&(b=f)}return b}let b1=function(a=b$,b=b_){return b0(a)??b0(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 b2(a,b,c){a(b,{mechanism:{type:"unhandledRejection"===c?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function b3(a,b,c,d,e){if(b>c&&(d.warn("min cannot be greater than max."),b=c),O(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),b3(e||c,b,c,d)}class b4{constructor(a){this._buckets={},this._onBucketRateLimited=a._onBucketRateLimited,this._bucketSize=b3(a.bucketSize,0,100,a._logger),this._refillRate=b3(a.refillRate,0,this._bucketSize,a._logger),this._refillInterval=b3(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 bA=bz;class b5{constructor(a,b,c){this.client=a,this._exceptionAutocaptureEnabled=b.enableExceptionAutocapture||!1,this._logger=c,this._rateLimiter=new b4({...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 I(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=bA.getInjectedReleaseId();return h&&(f.$release_id=h),{event:"$exception",distinctId:d,properties:{...g,...f},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(!function(b,c,d=b1){let e=globalThis.process;if(e){let f;if("strict"===d)return e.on("uncaughtExceptionMonitor",(a,c)=>b2(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;b2(b,d,e),f||0!==g||(f=!0,c(d))},{_posthogErrorHandler:!0})))}}(this.onException.bind(this),this.onFatalError.bind(this)),function(a,b=b1){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,b){this.client.addPendingPromise((async()=>{if(!b5.isPreviouslyCapturedError(a)){let c=await b5.buildEventMessage(this.client.getErrorPropertiesBuilder(),a,b),d=c.properties,e=d?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(e)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:e}):this.client._capturePreparedEvent(c,!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 b6{getProperty(a){return this._memoryStorage[a]}setProperty(a,b){this._memoryStorage[a]=null!==b?b:void 0}constructor(){this._memoryStorage={}}}let b7="analytics";class b8 extends Error{constructor({requestId:a,drops:b,retryExhausted:c,cause:d}){super(b8.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 b9(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 ca=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:b9},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:b9},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:b9},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(a){return"string"==typeof a?a:void 0}}],cb=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function cc(a,b,c){void 0===c||b in a||(a[b]=c)}function cd(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 ca)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 cb)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,cc(c,"$set",a.$set),cc(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 ce=new Set([408,500,502,503,504]);class cf{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=>af(b,a))),this.generateRequestId=b.generateRequestId??aw,this.compress=b.compress??ak}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(cd)};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=D({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&&ce.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 b8({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=af(()=>{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 b8({requestId:a,drops:b,retryExhausted:c.map(a=>a.uuid),cause:d}))}surfacePartialDrops(a,b){b.length>0&&this.onError(new b8({requestId:a,drops:b,retryExhausted:[]}))}async cancelBody(a){try{await a.body?.cancel()}catch{}}}let cg="ai-capture",ch="/i/v0/ai/batch/",ci=new TextEncoder;function cj(a){return ci.encode(D(a)).length}let ck=new Set;function cl(a,b){ck.has(a)||(ck.add(a),console.warn(`[PostHog] ${b}`))}class cm extends bw{constructor(a,b={}){const c=function(a){return"string"==typeof a?a.trim():""}(a),d={...b,maxQueueSize:b.maxQueueSize??1e4,flushInterval:b.flushInterval??5e3,host:function(a){return("string"==typeof a?a.trim():"")||"https://us.i.posthog.com"}(b.host),personalApiKey:function(a){return("string"==typeof a?a.trim():"")||void 0}(b.secretKey??b.personalApiKey)};if(super(c,d),this._memoryStorage=new b6,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=d,this.captureMode=function(){let a="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return"v0"===a||"v1"===a?a:"v0"}(),this.enableFullAiCapture=!0===d.enableFullAiCapture,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof d.featureFlagsPollingInterval?Math.max(d.featureFlagsPollingInterval,100):3e4,"number"==typeof d.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(d.waitUntilDebounceMs,0)),"number"==typeof d.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(d.waitUntilMaxWaitMs,0)),!this.disabled&&d.personalApiKey){if(d.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!==d.enableLocalEvaluation&&(this.featureFlagsPoller=new bU({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:d.personalApiKey,projectApiKey:c,timeout:d.requestTimeout??1e4,host:this.host,fetch:d.fetch,onError:a=>{this._events.emit("error",a)},onLoad:a=>{this._events.emit("localEvaluationFlagsLoaded",a)},onMinimalFlagCalledEvents:a=>{this._minimalFlagCalledEvents=a},customHeaders:this.getCustomHeaders(),cacheProvider:d.flagDefinitionCacheProvider,strictLocalEvaluation:d.strictLocalEvaluation,evaluationContexts:d.evaluationContexts??d.evaluationEnvironments}))}this.errorTracking=new b5(this,d,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=d.maxCacheSize||5e4}enqueue(a,b,c,d){super.enqueue(a,b,c,d),this.scheduleDebouncedFlush()}async flush(){let a=this.flushWithPendingPromises(),b=this.options.waitUntil;if(b&&!this._waitUntilCycle)try{b(a.catch(()=>{}))}catch{}return a}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=af(()=>{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.flushWithPendingPromises()}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":b7}persistedQueueKeyForRoute(a){return a===cg?y.AiCaptureQueue:"ai"===a?y.AiQueue:y.Queue}getActiveQueueRoutes(){let a="v1"===this.captureMode?[b7,"ai"]:[b7];return this._aiCaptureRouteActive&&a.push(cg),a}getBatchEndpointPath(a){return a===cg?ch:super.getBatchEndpointPath(a)}async sendBatch(a,b,c=b7){if(c===cg)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=cj(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 ${ch}, 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,cg)}catch(d){if(!bs(d))throw d;if(1===a.length){let[b]=a,c="string"==typeof b.event?b.event:"unknown",d=`Event ${c} (${cj(b)} bytes) was rejected with 413 by ${ch} 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 cf({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.51.4"}get metrics(){var a;let b;return this._metrics||(this._metrics=new ar(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}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}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=aa(a.uuid,aw);return this._sendPreparedAiEvent({...a,uuid:b},!1),b}async captureAiImmediate(a){if(this.disabled)return;let b=aa(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,cg)}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}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:p}=c,{onlyEvaluateLocally:q,personProperties:r,groupProperties:s}=c,t=this.addLocalPersonAndGroupProperties(b,n,r,s);r=t.allPersonProperties,s=t.allGroupProperties;let u=this.createFeatureFlagEvaluationContext(b,n,this.personPropertiesForLocalEvaluation(b,r),s);void 0==q&&(q=this.options.strictLocalEvaluation??!1);let v=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let b=this.featureFlagsPoller?.featureFlagsByKey[a];if(b)try{let c=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(b,u,{matchValue:d});if(c){v=!0;let d=c.value;i=b.id,k="Evaluated locally",l=b.has_experiment,e={key:a,enabled:!1!==d,variant:"string"==typeof d?d:void 0,payload:c.payload??void 0}}}catch(b){if(b instanceof bT||b instanceof o)this._logger?.info(`${b.name} when computing flag locally: ${a}: ${b.message}`);else throw b}}if(!v&&!q){let b=await super.getFeatureFlagDetailsStateless(u.distinctId,u.groups,r,s,p,[a]);if(void 0===b)h=bQ.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===b.minimalFlagCalledEvents,f=b.requestId,g=b.evaluatedAt;let c=[];b.errorsWhileComputingFlags&&c.push(bQ.ERRORS_WHILE_COMPUTING),b.quotaLimited?.includes("feature_flags")&&c.push(bQ.QUOTA_LIMITED);let d=b.flags[a];if(void 0===d)c.push(bQ.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}}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:v,[`$feature/${a}`]:c,$feature_flag_request_id:f,$feature_flag_evaluated_at:v?Date.now():g};if(void 0!==l&&(d.$feature_flag_has_experiment=l),v&&this.featureFlagsPoller){let a=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==a&&(d.$feature_flag_definitions_loaded_at=a)}h&&(d.$feature_flag_error=h),this._captureFlagCalledEventIfNeeded({distinctId:b,key:a,response:c,groups:n,disableGeoip:p,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){cl("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(cl("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){cl("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 bR({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new bR({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,flags:{}});let{groups:g,disableGeoip:h}=f||{},i=f?.flagKeys??void 0;if(i?.length===0)return new bR({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 bR({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}`;b in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[b].has(i)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[b]instanceof Set?this.distinctIdHasSentFlagCalls[b].add(i):this.distinctIdHasSentFlagCalls[b]=new Set([i]),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 ag(this._metrics.flush().catch(()=>{}),Math.max(0,b-Date.now())),this._metrics.reset());try{return await super._shutdown(Math.max(0,b-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},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=af(()=>{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(Q(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(!b5.isPreviouslyCapturedError(a)){let f=Error("PostHog syntheticException");this.addPendingPromise(b5.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(!b5.isPreviouslyCapturedError(a)){let e=Error("PostHog syntheticException");return this.addPendingPromise(b5.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(),n=b.includeContextProperties??!0,o=c||l?.distinctId,p=n?{...this.props,...l?.properties||{},...e||{}}:{...e||{}};o||(o=aw(),p.$process_person_profile=!1),n&&l?.sessionId&&!p.$session_id&&(p.$session_id=l.sessionId);let q=this._shouldSendMinimalFlagCalledEvent(d,p)?m(p):p,r=this._runBeforeSend({distinctId:o,event:d,properties:q,groups:f,flags:g,sendFeatureFlags:h,timestamp:i,disableGeoip:j,uuid:k});if(!r)return Promise.reject(null);let s=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){cl("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(r.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=r.groups||f;return{...a,...r.properties||{},...void 0!==b&&Object.keys(b).length>0?{$groups:b}:{}}});return"$pageview"===r.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof s.$raw_user_agent&&bP(s.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(r.event="$bot_pageview",s.$browser_type="bot"),{distinctId:r.distinctId,event:r.event,properties:s,options:{timestamp:r.timestamp,disableGeoip:r.disableGeoip,uuid:r.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 bA=bz,cn=a.i(78500);class co{constructor(){this.storage=new cn.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||{}}}}}var cp=a.i(27028);let cq=(0,a.i(12057).promisify)(cp.gzip);async function cr(a,b=!0){try{let b=await cq(a);return new Uint8Array(b)}catch(a){return b&&console.error("Failed to gzip compress data",a),null}}var bA=bz;let cs="posthog-node";function ct(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[cv.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=bA.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 cu(a,b){let c=ct(a,b);return{name:cs,processEvent:a=>c(a)}}class cv{static #a=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(a,b,c,d,e){this.name=cs,this.name=cs,this.setupOnce=function(f,g){f(ct(a,{organization:b,projectId:g()?.getClient()?.getDsn()?.projectId,prefix:c,severityAllowList:d,sendExceptionsToPostHog:e??!0}))}}}a.s(["PostHogSentryIntegration",0,cv,"createEventProcessor",0,ct,"sentryIntegration",0,cu],9318);let cw=/[\x00-\x1f\x7f-\x9f]/g;function cx(a,b,c){null!=c&&""!==c&&(a[b]=c)}function cy(a){return Array.isArray(a)?a[0]:a}function cz(a){if(Array.isArray(a)){for(let b of a){let a=cz(b);if(void 0!==a)return a}return}if("string"!=typeof a)return;let b=a.replace(cw,"").trim();if(b)return b.length>1e3?b.slice(0,1e3):b}function cA(a,b){var c,d;let e,{sessionId:f,distinctId:g}=function(a){if(!a)return{};let b=cz(a["x-posthog-session-id"]),c=cz(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 cx(h,"$current_url",(c=b.originalUrl||b.url,i?ac(c):c)),cx(h,"$request_method",b.method),cx(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?ac(e):e)),cx(h,"$user_agent",cy(b.headers["user-agent"])),cx(h,"$ip",function(a){let b=cy(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 cB(a,b){var c;b.use((c=a,(a,b,d)=>{c.withContext(cA(c,a),()=>d())}))}function cC(a,b){var c;b.use((c=a,(a,b,d,e)=>{if(b5.isPreviouslyCapturedError(a))return void e(a);let f=cA(c,b),g=Error("Synthetic exception"),h={...void 0!==f.sessionId?{$session_id:f.sessionId}:{},...f.properties||{},$response_status_code:d.statusCode};c.addPendingPromise(b5.buildEventMessage(c.getErrorPropertiesBuilder(),a,{mechanism:{type:"middleware",handled:!1},syntheticException:g},f.distinctId,h).then(a=>c._capturePreparedEvent(a,!1))),e(a)}))}a.s(["setupExpressErrorHandler",0,cC,"setupExpressRequestContext",0,cB],40602),a.s([],51328);class cD extends cm{getLibraryId(){return"posthog-node"}compressPayload(a){return cr(a,this.isDebug)}initializeContext(){return new co}createErrorPropertiesBuilder(){let a;return new bA.ErrorPropertiesBuilder([new bA.EventCoercer,new bA.ErrorCoercer,new bA.ObjectCoercer,new bA.StringCoercer,new bA.PrimitiveCoercer],bA.createStackParser("node:javascript",bA.nodeStackLineParser),[(a=function(a=process.argv[1]?(0,h.dirname)(process.argv[1]):process.cwd(),b="\\"===h.sep){let c=b?i(a):a;return a=>{if(!a)return;let d=b?i(a):a,{dir:e,base:f,ext:g}=h.posix.parse(d);(".js"===g||".mjs"===g||".cjs"===g)&&(f=f.slice(0,-1*g.length));let j=decodeURIComponent(f);e||(e=".");let k=e.lastIndexOf("/node_modules");if(k>-1)return`${e.slice(k+14).replace(/\//g,".")}:${j}`;if(e.startsWith(c)){let a=e.slice(c.length+1).replace(/\//g,".");return a?`${a}:${j}`:j}return j}}(),async b=>{for(let c of b)c.module=a(c.filename);return b}),a=>bH(a,void 0,this._logger),function(a=process.cwd()){h.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,h.isAbsolute)(d.filename)&&(d.filename=b((0,h.relative)(c,b(d.filename))));return a}}()])}}a.s(["PostHog",0,cD],81035),a.i(81035),a.i(51328),a.i(9318),a.i(40602),a.i(46539),a.s(["FeatureFlagError",0,z,"FeatureFlagEvaluations",0,bR,"PostHogSentryIntegration",0,cv,"cookieStateToProperties",0,aC,"cookieStoreFromHeader",0,ay,"createEventProcessor",0,ct,"getPostHogCookieName",0,az,"parsePostHogCookie",0,aD,"readPostHogCookie",0,aB,"sentryIntegration",0,cu,"serializePostHogCookie",0,aA,"setupExpressErrorHandler",0,cC,"setupExpressRequestContext",0,cB,"uuidv7",0,aw],80456),a.i(80456),a.s(["FeatureFlagError",0,z,"FeatureFlagEvaluations",0,bR,"PostHog",0,cD,"PostHogSentryIntegration",0,cv,"cookieStateToProperties",0,aC,"cookieStoreFromHeader",0,ay,"createEventProcessor",0,ct,"getPostHogCookieName",0,az,"parsePostHogCookie",0,aD,"readPostHogCookie",0,aB,"sentryIntegration",0,cu,"serializePostHogCookie",0,aA,"setupExpressErrorHandler",0,cC,"setupExpressRequestContext",0,cB,"uuidv7",0,aw],74493)}];
|
|
3
3
|
|
|
4
4
|
//# sourceMappingURL=node_modules_posthog-node_dist_entrypoints_index_node_mjs_11bnuzn._.js.map
|