failproofai 0.0.14-beta.1 → 0.0.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/standalone/.next/BUILD_ID +1 -1
- package/.next/standalone/.next/build-manifest.json +3 -3
- package/.next/standalone/.next/prerender-manifest.json +3 -3
- package/.next/standalone/.next/required-server-files.json +1 -1
- package/.next/standalone/.next/server/app/_global-error/page/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 +2 -2
- package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +7 -7
- package/.next/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +3 -3
- package/.next/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +3 -3
- package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- 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 +14 -14
- package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +14 -14
- package/.next/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +4 -4
- package/.next/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +9 -9
- package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +3 -3
- package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/api/audit/invite/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/audit/run/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/reminder/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.nft.json +1 -1
- 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 +14 -14
- package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +14 -14
- package/.next/standalone/.next/server/app/index.segments/_head.segment.rsc +4 -4
- package/.next/standalone/.next/server/app/index.segments/_index.segment.rsc +9 -9
- package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
- 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/server-reference-manifest.json +8 -8
- 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/server-reference-manifest.json +1 -1
- 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/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.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/server-reference-manifest.json +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/chunks/[root-of-the-server]__0--lkk6._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0-219ec._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__04_h-a5._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__06cuf1y._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__08w4wmd._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0g6bbuw._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0jnjf2t._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0q-v9z2._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0q0qzx1._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0q2nbsl._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0rv7m0k._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__16le-kd._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__17g9wh7._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1ffkmds._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1fwl2mz._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1legmza._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1mrihkj._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1myjm-d._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1qb590j._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1qxztj-._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1shcqgr._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1xuedea._.js +1 -1
- package/.next/standalone/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_17k9e3w.js +4 -4
- package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_01r25oi._.js +1 -1
- package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_09z9-p7._.js +1 -1
- package/.next/standalone/.next/server/chunks/package_json_[json]_cjs_1nxcc4v._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__015_i4t._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__030k0c6._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__03lv-pe._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__05r_17v._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0e2l3c1._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0hci7t3._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0hdsupo._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0p84xee._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0qeuy9c._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0s89hoe._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0ynf7tx._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0brjczq._.js → [root-of-the-server]__0zf8xlq._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__170799-._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__17ai7sy._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1nq7ivq._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0wp9w6i._.js → [root-of-the-server]__1s2b6h0._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1tkjqka._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/_05whahf._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_1kje4fm._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/app_audit__components_audit-dashboard_tsx_0p9ud47._.js +2 -2
- 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/lib_0xkhw_v._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{node_modules_html-to-image_es_index_12rjfea.js → node_modules_html-to-image_es_index_0gkzjaa.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/node_modules_posthog-node_dist_entrypoints_index_node_mjs_11bnuzn._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/src_hooks_1ezd2jf._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/src_hooks_1tnuifj._.js +1 -1
- package/.next/standalone/.next/server/middleware-build-manifest.js +3 -3
- 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 +10 -10
- package/.next/standalone/.next/static/chunks/06z_ex1ts3n4s.js +1 -0
- package/.next/standalone/.next/static/chunks/0o0ut0ugd0_-s.js +1 -0
- package/.next/standalone/.next/static/chunks/0xl97x-874k-u.js +1 -0
- package/.next/standalone/.next/static/chunks/19d7hqx8udopz.js +1 -0
- package/.next/standalone/.next/static/chunks/{0emg30_6svycu.js → 29o4j32z643_a.js} +1 -1
- package/.next/standalone/.next/static/chunks/{1359o5785rmve.js → 2uh_4k4m296z5.js} +2 -2
- package/.next/standalone/.next/static/chunks/370sj2lgkw5ey.js +1 -0
- package/.next/standalone/.next/static/chunks/{0d5lypu1zs21r.js → 3s8aaig91937v.js} +1 -1
- package/.next/standalone/.next/static/chunks/3w7g0n0iwwnbs.js +1 -0
- package/.next/standalone/.next/static/chunks/{0o9wpnze1ey8y.js → 42oeva1-w0z2d.js} +1 -1
- package/.next/standalone/app/audit/_components/how-to-improve-section.tsx +11 -2
- package/.next/standalone/app/components/copy-button.tsx +22 -6
- package/.next/standalone/app/components/log-viewer/entry-row.tsx +8 -3
- package/.next/standalone/app/components/raw-log-viewer.tsx +33 -15
- package/.next/standalone/app/policies/hooks-client.tsx +1 -1
- package/.next/standalone/{ci/cli-integration → integration-suite}/README.md +25 -7
- package/.next/standalone/integration-suite/ci-entrypoint.sh +164 -0
- package/.next/standalone/{ci/cli-integration → integration-suite}/run.sh +4 -4
- package/.next/standalone/lib/entry-keys.ts +36 -0
- package/.next/standalone/lib/format-duration.ts +23 -9
- package/.next/standalone/package.json +5 -4
- package/.next/standalone/server.js +1 -1
- package/dist/cli.mjs +342 -106
- package/lib/entry-keys.ts +36 -0
- package/lib/format-duration.ts +23 -9
- package/package.json +5 -4
- package/scripts/translate-docs/cli.ts +6 -0
- package/scripts/translate-docs/mdx-translator.ts +30 -19
- package/scripts/translate-docs/readme-translator.ts +31 -21
- package/scripts/translate-docs/translator.ts +142 -7
- package/scripts/translate-docs/types.ts +6 -0
- package/scripts/translate-docs/validate-translation.ts +132 -0
- package/scripts/validate-mdx.ts +80 -11
- package/src/audit/cli.ts +12 -6
- package/src/auth/cli.ts +14 -5
- package/src/hooks/builtin-policies.ts +168 -50
- package/src/hooks/configure-wizard.ts +238 -22
- package/src/hooks/custom-hooks-loader.ts +70 -4
- package/src/hooks/handler.ts +4 -1
- package/src/hooks/policy-types.ts +8 -0
- package/src/hooks/tui.ts +95 -28
- package/.next/standalone/.next/static/chunks/20tuctw38jbgw.js +0 -1
- package/.next/standalone/.next/static/chunks/2ldhnaweu9ew3.js +0 -1
- package/.next/standalone/.next/static/chunks/2vav_x0_336ds.js +0 -1
- package/.next/standalone/.next/static/chunks/3cg7x0joi2b98.js +0 -1
- package/.next/standalone/.next/static/chunks/3k87p-tijud-4.js +0 -1
- package/.next/standalone/.next/static/chunks/3kmaqcp7rldad.js +0 -1
- /package/.next/standalone/.next/static/{LkN-JjmhKGmL-WklH7WVi → WQRKgSfFekLcC_pvyzp4S}/_buildManifest.js +0 -0
- /package/.next/standalone/.next/static/{LkN-JjmhKGmL-WklH7WVi → WQRKgSfFekLcC_pvyzp4S}/_clientMiddlewareManifest.js +0 -0
- /package/.next/standalone/.next/static/{LkN-JjmhKGmL-WklH7WVi → WQRKgSfFekLcC_pvyzp4S}/_ssgManifest.js +0 -0
- /package/.next/standalone/{ci/cli-integration → integration-suite}/Dockerfile +0 -0
- /package/.next/standalone/{ci/cli-integration → integration-suite}/canary-policies.mjs +0 -0
- /package/.next/standalone/{ci/cli-integration → integration-suite}/capture-tokens.sh +0 -0
- /package/.next/standalone/{ci/cli-integration → integration-suite}/inject-tokens.sh +0 -0
- /package/.next/standalone/{ci/cli-integration → integration-suite}/install-clis.sh +0 -0
- /package/.next/standalone/{ci/cli-integration → integration-suite}/probe-cli.sh +0 -0
- /package/.next/standalone/{ci/cli-integration → integration-suite}/report.js +0 -0
|
@@ -1,3 +1,3 @@
|
|
|
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}};var l=((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.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.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 m={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}`},n=a=>{let b=Error(`Native gzip produced invalid output: ${a}`);throw b.name="NativeGzipValidationError",b},o=async(a,c)=>{a.size<18&&n("too-short");let d=new Uint8Array(await a.slice(0,10).arrayBuffer());d.length>=2&&31===d[0]&&139===d[1]&&8===d[2]||n("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)&&n("invalid-crc");let f=c.length>>>0;e.getUint32(4,!0)!==f&&n("invalid-size")};async function p(a,b=!0,c){try{let b=new TextEncoder().encode(a),c=new 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 o(g,b),g}catch(a){if(c?.rethrow)throw a;return b&&console.error("Failed to gzip compress data",a),null}}function q(a){let b=[];return JSON.stringify(a,function(a,c){if("bigint"==typeof c)return c.toString();if("function"!=typeof c&&"symbol"!=typeof c){if(c instanceof Error)return{name:c.name,message:c.message,stack:c.stack};if(c&&"object"==typeof c){for(;b.length>0&&b[b.length-1]!==this;)b.pop();if(b.includes(c))return"[Circular]";b.push(c)}return c}})??"null"}let r=Array.isArray,s=Object.prototype;s.hasOwnProperty;let t=s.toString,u=r||function(a){return"[object Array]"===t.call(a)},v=a=>a===Object(a)&&!u(a),w=a=>void 0===a,x=a=>"[object String]"==t.call(a),y=a=>null===a,z=a=>"[object Number]"==t.call(a)&&a==a;function A(a){return null===a||"object"!=typeof a}function B(a,b){return Object.prototype.toString.call(a)===`[object ${b}]`}function C(a){return"u">typeof Event&&function(a,b){try{return a instanceof b}catch{return!1}}(a,Event)}let D="Android",E="BlackBerry",F="Nintendo",G="PlayStation",H="Xbox",I="Windows",J="(\\d+(\\.\\d+)?)";RegExp("Version/"+J),RegExp(H,"i"),RegExp(G+" \\w+","i"),RegExp(F+" \\w+","i"),RegExp(E+"|PlayBook|BB10","i");RegExp("rv:"+J),RegExp("Edge?\\/"+J),RegExp("(Chrome|CrMo)\\/"+J),RegExp("CriOS\\/"+J),RegExp("(UCBrowser|UCWEB)\\/"+J),RegExp("(Opera|OPR)\\/"+J),RegExp("Firefox\\/"+J),RegExp("FxiOS\\/"+J),RegExp("Konqueror[:/]?"+J,"i"),RegExp(E+" "+J),RegExp("android\\s"+J,"i"),RegExp("SamsungBrowser\\/"+J),RegExp("OculusBrowser\\/"+J),RegExp("Vivaldi\\/"+J),RegExp("YaBrowser\\/"+J),RegExp("Whale\\/"+J),RegExp("Brave\\/"+J),RegExp("(DuckDuckGo|Ddg)\\/"+J),RegExp("PaleMoon\\/"+J),RegExp("Waterfox\\/"+J),RegExp("GSA\\/"+J),RegExp("(rv:|MSIE )"+J),RegExp("rv:"+J),RegExp(H+"; "+H+" (.*?)[);]","i"),RegExp(F,"i"),RegExp(G,"i"),RegExp(I,"i"),RegExp("("+D+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+D+")","i");let K=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function L(a,b){return"string"==typeof a&&K.test(a)?a:b()}function M(a){return a?a.split("#")[0]:a}async function N(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 O(){return new Date().toISOString()}function P(a,b){let c=setTimeout(a,b);return c?.unref&&c?.unref(),c}let Q=a=>a instanceof Error;function R(a){return Promise.all(a.map(a=>(a??Promise.resolve()).then(a=>({status:"fulfilled",value:a}),a=>({status:"rejected",reason:a}))))}function S(a){let b=[];for(let c in a){let d=a[c];y(d)||w(d)||b.push({key:c,value:function a(b){if("[object Boolean]"===t.call(b))return{boolValue:b};if("number"==typeof b)return Number.isFinite(b)?Number.isInteger(b)?{intValue:b}:{doubleValue:b}:{stringValue:String(b)};if("string"==typeof b)return{stringValue:b};if(u(b))return{arrayValue:{values:b.map(b=>a(b))}};try{return{stringValue:JSON.stringify(b)}}catch{return{stringValue:String(b)}}}(d)})}return b}let T=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function U(a){return String(a)+"000000"}function V(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 W{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=V(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(T.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,T)]+=1}}}_runBeforeSend(a){let b=this._config.beforeSend;if(!b)return a;let c=u(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=P(()=>{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:S(f)},scopeMetrics:[{scope:{name:g,version:h},metrics:e}]}]}}_buildMetrics(a){let b=U(Date.now()),c=new Map;for(let d of a.values()){let a=V(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=S(d.attributes??{}),g=U(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:T};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 X="0123456789abcdef";class Y{constructor(a){this.bytes=a}static ofInner(a){if(16===a.length)return new Y(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 Y(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 Y(a)}throw SyntaxError("could not parse UUID string")}toString(){let a="";for(let b=0;b<this.bytes.length;b++)a+=X.charAt(this.bytes[b]>>>4),a+=X.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+=X.charAt(this.bytes[b]>>>4),a+=X.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 Y(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 Z{constructor(a){this.timestamp=0,this.counter=0,this.random=a??$()}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 Y.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,Y.ofInner(a)}}let $=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),_=()=>aa().toString(),aa=()=>(c||(c=new Z)).generate();function ab(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 ac(a){let b=a.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${b}_posthog`}function ad(a){let b=Date.now();return JSON.stringify({distinct_id:a,$device_id:a,$user_state:"anonymous",$sesid:[b,_(),b]})}function ae(a,b){let c=ac(b),d=a.get(c);return d?ag(d.value):null}function af(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 ag(a){if(!a)return null;try{let b=JSON.parse(a);if(!b||"object"!=typeof b||!b.distinct_id)return null;let c=u(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 ah{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 ai{add(a){let b=_(),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 aj=(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=>aj(`${a} ${d}`,b,c)}};class ak{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&&u(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 al(a,b,c,d,e){let f={platform:a,filename:b,function:"<anonymous>"===c?"?":c,in_app:!0};return w(d)||(f.lineno=d),w(e)||(f.colno=e),f}a.s(["ErrorPropertiesBuilder",0,ak],6762);let am=(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]},an=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ao=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ap=/\((\S*)(?::(\d+))(?::(\d+))\)/,aq=(a,b)=>{let c=an.exec(a);if(c){let[,a,d,e]=c;return al(b,a,"?",+d,+e)}let d=ao.exec(a);if(d){if(d[2]&&0===d[2].indexOf("eval")){let a=ap.exec(d[2]);a&&(d[2]=a[1],d[3]=a[2],d[4]=a[3])}let[a,c]=am(d[1]||"?",d[2]);return al(b,c,a,d[3]?+d[3]:void 0,d[4]?+d[4]:void 0)}},ar=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,as=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,at=(a,b)=>{let c=ar.exec(a);if(c){if(c[3]&&c[3].indexOf(" > eval")>-1){let a=as.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]=am(d,a),al(b,a,d,c[4]?+c[4]:void 0,c[5]?+c[5]:void 0)}},au=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,av=(a,b)=>{let c=au.exec(a);return c?al(b,c[2],c[1]||"?",+c[3],c[4]?+c[4]:void 0):void 0},aw=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,ax=(a,b)=>{let c=aw.exec(a);return c?al(b,c[2],c[3]||"?",+c[1]):void 0},ay=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,az=(a,b)=>{let c=ay.exec(a);return c?al(b,c[5],c[3]||c[4]||"?",+c[1],+c[2]):void 0},aA=/^\s*[-]{4,}$/,aB=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,aC=(a,b)=>{let c=a.match(aB);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]),{filename:h?decodeURI(h):void 0,module:void 0,function:e,lineno:aD(c[3]),colno:aD(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(aA))return{filename:a,platform:b}};function aD(a){return parseInt(a||"",10)||void 0}let aE=/\(error: (.*)\)/;function aF(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 aG(){return aH("web:javascript",aq,at)}function aH(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=aE.test(d)?d.replace(aE,"$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 aF(e)}}a.s(["createDefaultStackParser",0,aG,"createStackParser",0,aH,"reverseAndStripFrames",0,aF],67970);class aI{match(a){return this.isDOMException(a)||this.isDOMError(a)}coerce(a,b){let c=x(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 B(a,"DOMException")}isDOMError(a){return B(a,"DOMError")}}a.s(["DOMExceptionCoercer",0,aI],51671);class aJ{match(a){return a instanceof Error}coerce(a,b){return{type:this.getType(a),value:this.getMessage(a,b),stack:this.getStack(a),cause:a.cause?b.next(a.cause):void 0,synthetic:!1}}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,aJ],10692);class aK{match(a){return B(a,"ErrorEvent")&&void 0!=a.error}coerce(a,b){let c=b.apply(a.error);return c||{type:"ErrorEvent",value:a.message,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["ErrorEventCoercer",0,aK],75368);let aL=["fatal","error","warning","log","info","debug"];function aM(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 aN{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:b.syntheticException?.stack,level:this.isSeverityLevel(a.level)?a.level:"error",synthetic:!0}}getType(a){return C(a)?a.constructor.name:"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=aM(a);return`${b&&"Object"!==b?`'${b}'`:"Object"} captured as exception with keys: ${c}`}isSeverityLevel(a){return x(a)&&!(x(a)&&0===a.trim().length)&&aL.indexOf(a)>=0}getErrorPropertyFromObject(a){for(let b in a)if(Object.prototype.hasOwnProperty.call(a,b)){let c=a[b];if(Q(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,aN],93874);class aO{match(a){return C(a)}coerce(a,b){let c=a.constructor.name;return{type:c,value:`${c} captured as exception with keys: ${aM(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["EventCoercer",0,aO],46980);class aP{match(a){return A(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,aP],28150);class aQ{match(a){return B(a,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(a)}isCustomEventWrappingRejection(a){if(!C(a))return!1;try{let b=a.detail;return null!=b&&"object"==typeof b&&"reason"in b}catch{return!1}}coerce(a,b){let c=this.getUnhandledRejectionReason(a);return A(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,aQ],98140),a.s([],7610);let aR={MESSAGE:"$message",TIMESTAMP:"$timestamp"},aS=new Set([aR.MESSAGE,aR.TIMESTAMP]),aT={enabled:!0,max_bytes:32768};function aU(a){return a?{enabled:a.enabled??aT.enabled,max_bytes:function(a,b){if(!z(a)||a===1/0||a===-1/0)return b;let c=Math.floor(a);return c<0?b:c}(a.max_bytes,aT.max_bytes)}:{...aT}}function aV(a){if(!a)return{sanitizedProperties:{},droppedKeys:[]};let b=[];return{sanitizedProperties:Object.keys(a).reduce((c,d)=>(aS.has(d)?b.push(d):c[d]=a[d],c),{}),droppedKeys:b}}class aW{constructor(a){this._entries=[],this._totalBytes=0,this._config=aU(a)}setConfig(a){this._config=aU(a),this._trimToMaxBytes()}add(a){let b=function(a){let b;try{b=q(a)}catch{return}try{let a=JSON.parse(b);if(!v(a))return;let c=a[aR.MESSAGE],d=a[aR.TIMESTAMP];if(!x(c)||0===c.trim().length||!x(d)&&!z(d))return;return{step:a,json:b}}catch{return}}(a);if(!b)return;let c=aX(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 aX(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,aT,"EXCEPTION_STEP_INTERNAL_FIELDS",0,aR,"ExceptionStepsBuffer",0,aW,"getUtf8ByteLength",0,aX,"resolveExceptionStepsConfig",0,aU,"stripReservedExceptionStepFields",0,aV],97383),a.s([],48153);let aY=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class aZ{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(aY);return d&&(b=d[1],c=d[2]),[b,c]}}a.s(["StringCoercer",0,aZ],57802);class a$ extends Error{constructor(a,b){super("HTTP error while fetching PostHog: status="+a.status+", reqByteLength="+b),this.response=a,this.reqByteLength=b,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}}class a_ extends Error{constructor(a){super("Network error while fetching PostHog",a instanceof Error?{cause:a}:{}),this.error=a,this.name="PostHogFetchNetworkError"}}async function a0(a){if(a instanceof a$){let b="";try{b=await a.text}catch{}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 a1(a){return a instanceof a_}function a2(a){if(a instanceof a$)return 502===a.status||504===a.status;if(!(a instanceof a_))return!1;let b=a.error;return"ECONNREFUSED"!==(b?.code??b?.cause?.code)}function a3(a){return"object"==typeof a&&a instanceof a$&&413===a.status}function a4(a){return a instanceof a$?408===a.status||429===a.status||a.status>=500:a1(a)}function a5(a){return null!==a&&"object"==typeof a&&!Array.isArray(a)}let a6="default";class a7{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new ak([new aJ,new aN,new aZ,new aP],aG())}constructor(a,b={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new ai,this._events=new ah,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 aj(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:a4},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(l.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(l.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(l.OptedOut,!0)})}on(a,b){return this._events.on(a,b)}debug(a=!0){if(this.removeDebugCallback?.(),a){let a=this.on("*",(a,b)=>this._logger.info(a,b));this.removeDebugCallback=()=>{a(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(a){let b=a.properties||{},c={...b,...this.getCommonEventProperties()};for(let a of Object.keys(b))(a.startsWith("$feature/")||"$active_feature_flags"===a)&&(c[a]=b[a]);return{distinct_id:a.distinct_id,event:a.event,properties:c}}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,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(a=>a.json()).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,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:a2},this.featureFlagsRequestTimeoutMs).then(a=>a.json()).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 a$)return{type:"api_error",statusCode:a.status};if(a instanceof a_){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).then(a=>{if(200!==a.status||!a.json){let b=`Surveys API could not be loaded: ${a.status}`,c=Error(b);this._logger.error(c),this._events.emit("error",Error(b));return}return a.json()}).catch(a=>{this._logger.error("Surveys API could not be loaded",a),this._events.emit("error",a)}),d=c?.surveys;return d&&this._logger.info("Surveys fetched from API: ",JSON.stringify(d)),d??[]}get props(){return this._props||(this._props=this.getPersistedProperty(l.Props)),this._props||{}}set props(a){this._props=a}async register(a){this.wrap(()=>{this.props={...this.props,...a},this.setPersistedProperty(l.Props,this.props)})}async unregister(a){this.wrap(()=>{delete this.props[a],this.setPersistedProperty(l.Props,this.props)})}processBeforeEnqueue(a){return a}async flushStorage(){}getQueueRouteKey(a){return a6}persistedQueueKeyForRoute(a){return l.Queue}getActiveQueueRoutes(){return[a6]}getRouteQueue(a){return this.getPersistedProperty(this.persistedQueueKeyForRoute(a))||[]}enqueue(a,b,c){this.wrap(()=>{if(this.optedOut)return void this._events.emit(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let d=this.prepareMessage(b,c);if(null===(d=this.processBeforeEnqueue(d)))return;d=this.normalizeMessage(d);let e=this.persistedQueueKeyForRoute(this.getQueueRouteKey(d)),f=this.getPersistedProperty(e)||[];f.length>=this.maxQueueSize&&(f.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),f.push({message:d}),this.setPersistedProperty(e,f),this._events.emit(a,d),f.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=P(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(a,b,c){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 d=this.prepareMessage(b,c);if(null!==(d=this.processBeforeEnqueue(d))){d=this.normalizeMessage(d);try{await this.sendBatch([d],void 0,this.getQueueRouteKey(d))}catch(a){this._events.emit("error",a)}}}normalizeMessage(a){let{type:b,library:c,library_version:d,...e}=a,f=a5(e.properties)?e.properties:void 0;return void 0!==c&&f?.$lib===void 0&&(f={...f||{},$lib:c}),void 0!==d&&f?.$lib_version===void 0&&(f={...f||{},$lib_version:d}),f&&(e.properties=f),e.uuid=L(e.uuid,_),e}prepareMessage(a,b){let c={...a,timestamp:b?.timestamp?b?.timestamp:O(),uuid:L(b?.uuid,_)};return(b?.disableGeoip??this.disableGeoip)&&(a5(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 a0(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(()=>R([b])).then(()=>(this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=d,this.flushPromise=d,this.flushPromises.add(d),this.addPendingPromise(d),R([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}async sendBatch(a,b,c=a6){let d={api_key:this.apiKey,batch:a,sent_at:O()};this.historicalMigration&&(d.historical_migration=!0);let e=q(d),f=`${this.host}/batch/`,g=this.disableCompression?null:await p(e,this.isDebug),h={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==g&&{"Content-Encoding":"gzip"}},body:g||e},i=await this.fetchWithRetry(f,h,b);await i.body?.cancel()?.catch(()=>{})}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)||[]).slice(e.length);this.setPersistedProperty(c,a),d=a,this._dequeuedMessagesCount+=e.length,await this.flushStorage()},i={retryCheck:a=>!a3(a)&&a4(a)};try{await this.sendBatch(g,i,a)}catch(a){if(a3(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 a_||await h(),this._events.emit("error",a),a}await h(),b.push(...g),f+=g.length}}async _sendLogsBatch(a){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let b=JSON.stringify(a),c=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,d=this.disableCompression?null:await p(b,this.isDebug),e={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==d&&{"Content-Encoding":"gzip"}},body:d||b};try{return await this.fetchWithRetry(c,e,{retryCheck:a=>!a3(a)&&a4(a)}),{kind:"ok"}}catch(a){if(a3(a))return{kind:"too-large"};if(a instanceof a_)return{kind:"retry-later",error:a};return{kind:"fatal",error:a}}}async _sendMetricsBatch(a){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let b=JSON.stringify(a),c=`${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`,d=this.disableCompression?null:await p(b,this.isDebug),e={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==d&&{"Content-Encoding":"gzip"}},body:d||b};try{return await this.fetchWithRetry(c,e,{retryCheck:a=>!a3(a)&&a4(a)}),{kind:"ok"}}catch(a){if(a3(a))return{kind:"too-large"};if(a4(a))return{kind:"retry-later",error:a};return{kind:"fatal",error:a}}}async fetchWithRetry(a,b,c,d){let e=b.body?b.body:"",f=-1;try{f=e instanceof Blob?e.size:Buffer.byteLength(e,"utf8")}catch{f=e instanceof Blob?e.size:new TextEncoder().encode(e).length}return await N(async()=>{let c=new AbortController,e=P(()=>c.abort(),d??this.requestTimeout),g=null;try{g=await this.fetch(a,{signal:c.signal,...b})}catch(a){throw new a_(a)}finally{clearTimeout(e)}if("no-cors"!==b.mode&&(g.status<200||g.status>=400))throw new a$(g,f);return g},{...this._retryOptions,...c})}async _shutdown(a=3e4){let b;await this._initPromise;let c=!1;if(this.clearFlushTimer(),this.disabled)return;let d=async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(a=>this.getRouteQueue(a).length>0);){let a=this._dequeuedMessagesCount;if(await this.flush(),c)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 a$||a1(a))))throw a;await a0(a)}};try{return await Promise.race([new Promise((d,e)=>{b=P(()=>{this._logger.error("Timed out while shutting down PostHog"),c=!0,e("Timeout while shutting down PostHog. Some events may not have been sent.")},a)}),d()])}finally{clearTimeout(b)}}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,aq,"createDefaultStackParser",0,aG,"createStackParser",0,aH,"geckoStackLineParser",0,at,"nodeStackLineParser",0,aC,"opera10StackLineParser",0,ax,"opera11StackLineParser",0,az,"reverseAndStripFrames",0,aF,"winjsStackLineParser",0,av],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,aI,"ErrorCoercer",0,aJ,"ErrorEventCoercer",0,aK,"EventCoercer",0,aO,"ObjectCoercer",0,aN,"PrimitiveCoercer",0,aP,"PromiseRejectionEventCoercer",0,aQ,"StringCoercer",0,aZ],54253),a.i(54253);class a8{constructor(a){this._maxSize=a,this._cache=new Map}get(a){let b=this._cache.get(a);if(void 0!==b)return this._cache.delete(a),this._cache.set(a,b),b}set(a,b){this._cache.set(a,b)}reduce(){for(;this._cache.size>=this._maxSize;){let a=this._cache.keys().next().value;a&&this._cache.delete(a)}}}a.s(["ReduceableCache",0,a8],98966),a.i(98966),a.i(97383),a.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,aT,"DOMExceptionCoercer",0,aI,"EXCEPTION_STEP_INTERNAL_FIELDS",0,aR,"ErrorCoercer",0,aJ,"ErrorEventCoercer",0,aK,"ErrorPropertiesBuilder",0,ak,"EventCoercer",0,aO,"ExceptionStepsBuffer",0,aW,"ObjectCoercer",0,aN,"PrimitiveCoercer",0,aP,"PromiseRejectionEventCoercer",0,aQ,"ReduceableCache",0,a8,"StringCoercer",0,aZ,"chromeStackLineParser",0,aq,"createDefaultStackParser",0,aG,"createStackParser",0,aH,"geckoStackLineParser",0,at,"getUtf8ByteLength",0,aX,"nodeStackLineParser",0,aC,"opera10StackLineParser",0,ax,"opera11StackLineParser",0,az,"resolveExceptionStepsConfig",0,aU,"reverseAndStripFrames",0,aF,"stripReservedExceptionStepFields",0,aV,"winjsStackLineParser",0,av],60485);var a9=a.i(60485),ba=a9,bb=a.i(2157),bc=a.i(1457);let bd=new ba.ReduceableCache(25),be=new ba.ReduceableCache(20);async function bf(a){let b={};for(let e=a.length-1;e>=0;e--){var c,d;let f=a[e],g=f?.filename;!(!f||"string"!=typeof g||"number"!=typeof f.lineno||(c=g).startsWith("node:")||c.endsWith(".min.js")||c.endsWith(".min.cjs")||c.endsWith(".min.mjs")||c.startsWith("data:")||void 0!==(d=f).lineno&&d.lineno>1e4||void 0!==d.colno&&d.colno>1e3)&&(b[g]||(b[g]=[]),b[g].push(f.lineno))}let e=Object.keys(b);if(0==e.length)return a;let f=[];for(let a of e){if(be.get(a))continue;let c=b[a];if(!c)continue;c.sort((a,b)=>a-b);let d=function(a){if(!a.length)return[];let b=0,c=a[0];if("number"!=typeof c)return[];let d=bh(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=bh(c)),b++}return e}(c);if(d.every(b=>(function(a,b){let c=bd.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})(a,b)))continue;let e=function(a,b,c){let d=a.get(b);return void 0===d?(a.set(b,c),c):d}(bd,a,{});f.push(function(a,b,c){return new Promise(d=>{let e=(0,bb.createReadStream)(a),f=(0,bc.createInterface)({input:e});function g(){e.destroy(),d()}let h=0,i=0,j=b[0];if(void 0===j)return void g();let k=j[0],l=j[1];function m(){be.set(a,1),f.close(),f.removeAllListeners(),g()}e.on("error",m),f.on("error",m),f.on("close",g),f.on("line",a=>{if(!(++h<k)&&(c[h]=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),h>=l)){if(i===b.length-1){f.close(),f.removeAllListeners();return}let a=b[++i];if(void 0===a){f.close(),f.removeAllListeners();return}k=a[0],l=a[1]}})})}(a,d,e))}return await Promise.all(f).catch(()=>{}),a&&a.length>0&&function(a,b){for(let c of a)if(c.filename&&void 0===c.context_line&&"number"==typeof c.lineno){let a=b.get(c.filename);if(void 0===a)continue;!function(a,b,c){if(void 0===b.lineno||void 0===c)return;b.pre_context=[];for(let d=bi(a);d<a;d++){let a=c[d];if(void 0===a)return void bg(b);b.pre_context.push(a)}if(void 0===c[a])return bg(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)}}(c.lineno,c,a)}}(a,bd),bd.reduce(),a}function bg(a){delete a.pre_context,delete a.context_line,delete a.post_context}function bh(a){return[bi(a),a+7]}function bi(a){return Math.max(1,a-7)}let bj=["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"],bk=function(a,b=[]){if(!a)return!1;let c=a.toLowerCase();return bj.concat(b).some(a=>{let b=a.toLowerCase();return -1!==c.indexOf(b)})},bl={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};a.s(["FeatureFlagError",0,bl],46539);class bm{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){let b=this._flags[a];return this._recordAccess(a),b?.enabled??!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 bm({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?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(d.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let e=[];this._errorsWhileComputing&&e.push(bl.ERRORS_WHILE_COMPUTING),this._quotaLimited&&e.push(bl.QUOTA_LIMITED),void 0===b&&e.push(bl.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 bn(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 bo=["is_not","is_set"];class bp extends Error{constructor(a){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=a,Object.setPrototypeOf(this,bp.prototype)}}function bq(a,b){a.name=b.name,Error.captureStackTrace(a,b),Object.setPrototypeOf(a,b.prototype)}class br extends Error{constructor(a){super(a),bq(this,br)}}class bs extends Error{constructor(a){super(a),bq(this,bs)}}class bt{constructor({pollingInterval:a,personalApiKey:b,projectApiKey:c,timeout:d,host:e,customHeaders:f,...g}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,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.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 bs||b instanceof br?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 bs||b instanceof br?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 br("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 br("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 br(`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 br("Feature flags not available for dependency evaluation");if(!("dependency_chain"in a))throw new br(`Flag dependency property for '${e}' is missing required 'dependency_chain' field`);let f=a.dependency_chain;if(!Array.isArray(f))throw new br(`Flag dependency property for '${e}' has an invalid 'dependency_chain' (expected array, got ${typeof f})`);if(0===f.length)throw new br(`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 br(`Error evaluating flag dependency '${a}' for flag '${e}': ${b}`)}else d[a]=!1;else throw new br(`Missing flag dependency '${a}' for flag '${e}'`)}if(null==d[a])throw new br(`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 bs)throw a;if(a instanceof br)l=!0;else throw a}if(void 0!==e)return e;if(l)throw new br("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 bu(a.key,b)>f/100?"out_of_rollout_bound":"match"}async getMatchingVariant(a,b){let c=await bu(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}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),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());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 bp(`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={};return;case 403:throw this.beginBackoff(),new bp(`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 bp(`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||{}};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 bp&&this.onError?.(a)}}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}}_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=P(()=>{a.abort()},this.timeout),b.signal=a.signal}try{return(0,this.fetch)(a,b)}finally{clearTimeout(c)}}async stopPoller(a=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let b=this.cacheProvider.shutdown();b instanceof Promise&&await Promise.race([b,new Promise((b,c)=>setTimeout(()=>c(Error(`Cache shutdown timeout after ${a}ms`)),a))])}catch(a){this.onError?.(Error(`Error during cache shutdown: ${a}`))}}}async function bu(a,b,c=""){return parseInt((await bn(`${a}.${b}${c}`)).slice(0,15),16)/0x1000000000000000}function bv(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 br(`Property ${d} not found in propertyValues`)}let g=b[d];if(null==g&&!bo.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"regex":return by(String(e))&&null!==String(g).match(String(e));case"not_regex":return by(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 br("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=bC(e)),null==a)throw new br(`Invalid date: ${e}`);let b=bC(g);if(["is_date_before"].includes(f))return b<a;return b>a}case"semver_eq":return 0===bB(bA(String(g)),bA(String(e)));case"semver_neq":return 0!==bB(bA(String(g)),bA(String(e)));case"semver_gt":return bB(bA(String(g)),bA(String(e)))>0;case"semver_gte":return bB(bA(String(g)),bA(String(e)))>=0;case"semver_lt":return 0>bB(bA(String(g)),bA(String(e)));case"semver_lte":return 0>=bB(bA(String(g)),bA(String(e)));case"semver_tilde":{let a,b=bA(String(g)),{lower:c,upper:d}={lower:[(a=bA(String(e)))[0],a[1],a[2]],upper:[a[0],a[1]+1,0]};return bB(b,c)>=0&&0>bB(b,d)}case"semver_caret":{let a=bA(String(g)),{lower:b,upper:c}=function(a){let[b,c,d]=bA(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 bB(a,b)>=0&&0>bB(a,c)}case"semver_wildcard":{let a=bA(String(g)),{lower:b,upper:c}=function(a){let b,c,d=String(a).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!d)throw new br(`Invalid wildcard semver: ${a}`);let e=d.split("."),f=b=>{try{return bz(b,a)}catch{throw new br(`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 bB(a,b)>=0&&0>bB(a,c)}default:throw new br(`Unknown operator: ${f}`)}}async function bw(a,b,c,d=!1,e){let f=String(a.value);if(!(f in c))throw new bs(`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 bs)throw b;if(b instanceof br)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),h=!0;else throw b}if(h)throw new br("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 br(`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 bs)throw b;if(b instanceof br)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),h=!0;else throw b}if(h)throw new br("can't match cohort without a given cohort property value");return"AND"===f}function by(a){try{return new RegExp(a),!0}catch(a){return!1}}function bz(a,b){if(!/^\d+$/.test(a)||a.length>1&&"0"===a[0])throw new br(`Invalid semver: ${b}`);return parseInt(a,10)}function bA(a){let b=String(a).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!b||b.startsWith("."))throw new br(`Invalid semver: ${a}`);let c=b.split("."),d=b=>void 0===b||""===b?0:bz(b,a);return[d(c[0]),d(c[1]),d(c[2])]}function bB(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 bC(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 br(`${a} is in an invalid date format`)}throw new br(`The date provided ${a} must be a string, number, or date object`)}function bD(a,b,c,d,e){if(b>c&&(d.warn("min cannot be greater than max."),b=c),z(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),bD(e||c,b,c,d)}class bE{constructor(a){this._buckets={},this._onBucketRateLimited=a._onBucketRateLimited,this._bucketSize=bD(a.bucketSize,0,100,a._logger),this._refillRate=bD(a.refillRate,0,this._bucketSize,a._logger),this._refillInterval=bD(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={}}}class bF{constructor(a,b,c){this.client=a,this._exceptionAutocaptureEnabled=b.enableExceptionAutocapture||!1,this._logger=c,this._rateLimiter=new bE({...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 v(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);return g.$exception_list=await a.modifyFrames(g.$exception_list),{event:"$exception",distinctId:d,properties:{...g,...f},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled()){var b,c,d;let e;b=this.onException.bind(this),c=this.onFatalError.bind(this),globalThis.process?.on("uncaughtException",(e=!1,Object.assign(d=>{let f=a.g.process.listeners("uncaughtException").filter(a=>"domainUncaughtExceptionClear"!==a.name&&!0!==a._posthogErrorHandler).length;b(d,{mechanism:{type:"onuncaughtexception",handled:!1}}),e||0!==f||(e=!0,c(d))},{_posthogErrorHandler:!0}))),d=this.onException.bind(this),globalThis.process?.on("unhandledRejection",a=>d(a,{mechanism:{type:"onunhandledrejection",handled:!1}}))}}onException(a,b){this.client.addPendingPromise((async()=>{if(!bF.isPreviouslyCapturedError(a)){let c=await bF.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),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class bG{getProperty(a){return this._memoryStorage[a]}setProperty(a,b){this._memoryStorage[a]=null!==b?b:void 0}constructor(){this._memoryStorage={}}}let bH="analytics";class bI extends Error{constructor({requestId:a,drops:b,retryExhausted:c,cause:d}){super(bI.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 bJ(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 bK=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:bJ},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:bJ},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:bJ},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(a){return"string"==typeof a?a:void 0}}],bL=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function bM(a,b,c){void 0===c||b in a||(a[b]=c)}function bN(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 bK)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 bL)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,bM(c,"$set",a.$set),bM(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)return Number.isNaN(new Date(a).getTime())?new Date().toISOString():a;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 bO=new Set([408,500,502,503,504]);class bP{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=>P(b,a))),this.generateRequestId=b.generateRequestId??_,this.compress=b.compress??p}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(bN)};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=q({created_at:c,...this.config.historicalMigration?{historical_migration:!0}:{},batch:g});try{d=await this.sendOnce(e,k,a,b)}catch(c){if(j)return this.surfaceBatchFailure(b,f,g,c);await this.sleep(this.backoffDelay(a));continue}let{status:l}=d;if(l<200||l>=300){if(!j&&bO.has(l)){let b=this.parseRetryAfter(d);await this.cancelBody(d),await this.sleep(this.backoffDelay(a,b));continue}let c=await this.buildHttpError(d,l);return this.surfaceBatchFailure(b,f,g,c)}try{i=await this.parseResponse(d)}catch{return this.surfaceBatchFailure(b,f,g,Error(`Capture V1 returned an unparseable ${l} response body`))}let m=this.classify(g,i,f);if(0===m.length)return this.surfacePartialDrops(b,f);if(j)return void this.onError(new bI({requestId:b,drops:f,retryExhausted:m.map(a=>a.uuid)}));g=m;let n=this.parseRetryAfter(d);await this.sleep(this.backoffDelay(a,n))}}async sendOnce(a,b,c,d){let e=this.buildHeaders(c,d),f=b;if(this.config.compressionEnabled){let a=await this.compress(b,this.config.isDebug);null!==a&&(f=a,e["Content-Encoding"]="gzip")}let g=new AbortController,h=P(()=>g.abort(),this.config.requestTimeoutMs);try{return await this.fetchFn(a,{method:"POST",headers:e,body:f,signal:g.signal})}finally{clearTimeout(h)}}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){let c="";try{c=(await a.text()).slice(0,512)}catch{}let d=c?`: ${c}`:"";return Error(`Capture V1 request failed with HTTP ${b}${d}`)}surfaceBatchFailure(a,b,c,d){this.onError(new bI({requestId:a,drops:b,retryExhausted:c.map(a=>a.uuid),cause:d}))}surfacePartialDrops(a,b){b.length>0&&this.onError(new bI({requestId:a,drops:b,retryExhausted:[]}))}async cancelBody(a){await a.body?.cancel()?.catch(()=>{})}}let bQ=new Set;function bR(a,b){bQ.has(a)||(bQ.add(a),console.warn(`[PostHog] ${b}`))}class bS extends a7{constructor(a,b={}){const c=function(a){return"string"==typeof a?a.trim():""}(a),d={...b,maxQueueSize:b.maxQueueSize??1e4,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 bG,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.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 bt({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)},customHeaders:this.getCustomHeaders(),cacheProvider:d.flagDefinitionCacheProvider,strictLocalEvaluation:d.strictLocalEvaluation}))}this.errorTracking=new bF(this,d,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=d.maxCacheSize||5e4}enqueue(a,b,c){super.enqueue(a,b,c),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=P(()=>{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":bH}persistedQueueKeyForRoute(a){return"ai"===a?l.AiQueue:l.Queue}getActiveQueueRoutes(){return"v1"===this.captureMode?[bH,"ai"]:[bH]}async sendBatch(a,b,c=bH){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)}getV1Sender(){return this._v1Sender||(this._v1Sender=new bP({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)})),this._v1Sender}getLibraryVersion(){return"5.44.0"}get metrics(){var a;let b;return this._metrics||(this._metrics=new W(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){return this.addPendingPromise(this._prepareEventMessage(b,d).then(({distinctId:b,event:d,properties:e,options:f})=>{let g={timestamp:f.timestamp,disableGeoip:f.disableGeoip,uuid:f.uuid},h={distinctId:b,event:d,properties:{...e,...this.getCommonEventProperties()}};return c?this.sendImmediate(a,h,g):this.enqueue(a,h,g)}).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)}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;if(this.disabled)return void this._logger.warn("The client is disabled");let l=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:m,disableGeoip:n}=c,{onlyEvaluateLocally:o,personProperties:p,groupProperties:q}=c,r=this.addLocalPersonAndGroupProperties(b,m,p,q);p=r.allPersonProperties,q=r.allGroupProperties;let s=this.createFeatureFlagEvaluationContext(b,m,this.personPropertiesForLocalEvaluation(b,p),q);void 0==o&&(o=this.options.strictLocalEvaluation??!1);let t=!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,s,{matchValue:d});if(c){t=!0;let d=c.value;i=b.id,k="Evaluated locally",e={key:a,enabled:!1!==d,variant:"string"==typeof d?d:void 0,payload:c.payload??void 0}}}catch(b){if(b instanceof bs||b instanceof br)this._logger?.info(`${b.name} when computing flag locally: ${a}: ${b.message}`);else throw b}}if(!t&&!o){let b=await super.getFeatureFlagDetailsStateless(s.distinctId,s.groups,p,q,n,[a]);if(void 0===b)h=bl.UNKNOWN_ERROR;else{f=b.requestId,g=b.evaluatedAt;let c=[];b.errorsWhileComputingFlags&&c.push(bl.ERRORS_WHILE_COMPUTING),b.quotaLimited?.includes("feature_flags")&&c.push(bl.QUOTA_LIMITED);let d=b.flags[a];if(void 0===d)c.push(bl.FLAG_MISSING);else{let b;if(i=d.metadata?.id,j=d.metadata?.version,k=d.reason?.description??d.reason?.code,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,payload:b}}c.length>0&&(h=c.join(","))}}if(l){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:t,[`$feature/${a}`]:c,$feature_flag_request_id:f,$feature_flag_evaluated_at:t?Date.now():g};if(t&&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:m,disableGeoip:n,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){bR("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(bR("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){bR("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 bm({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new bm({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},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(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}}}}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}}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 bm({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:o,requestId:c,evaluatedAt:d,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:p,quotaLimited:q})}_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 Promise.race([this._metrics.flush().catch(()=>{}),new Promise(a=>P(a,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=P(()=>{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(B(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(!bF.isPreviouslyCapturedError(a)){let f=Error("PostHog syntheticException");this.addPendingPromise(bF.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(!bF.isPreviouslyCapturedError(a)){let e=Error("PostHog syntheticException");return this.addPendingPromise(bF.buildEventMessage(this.getErrorPropertiesBuilder(),a,{syntheticException:e},b,c).then(a=>this.captureImmediate({...a,flags:d})))}}async prepareEventMessage(a){return this._prepareEventMessage(a)}async _prepareEventMessage(a,b={}){let{distinctId:c,event:d,properties:e,groups:f,flags:g,sendFeatureFlags:h,timestamp:i,disableGeoip:j,uuid:k}=a,l=this.context?.get(),m=b.includeContextProperties??!0,n=c||l?.distinctId,o=m?{...this.props,...l?.properties||{},...e||{}}:{...e||{}};n||(n=_(),o.$process_person_profile=!1),m&&l?.sessionId&&!o.$session_id&&(o.$session_id=l.sessionId);let p=this._runBeforeSend({distinctId:n,event:d,properties:o,groups:f,flags:g,sendFeatureFlags:h,timestamp:i,disableGeoip:j,uuid:k});if(!p)return Promise.reject(null);let q=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){bR("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(p.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=p.groups||f;return{...a,...p.properties||{},...void 0!==b&&Object.keys(b).length>0?{$groups:b}:{}}});return"$pageview"===p.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof q.$raw_user_agent&&bk(q.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(p.event="$bot_pageview",q.$browser_type="bot"),{distinctId:p.distinctId,event:p.event,properties:q,options:{timestamp:p.timestamp,disableGeoip:p.disableGeoip,uuid:p.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){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)}}return d}}var ba=a9,bT=a.i(78500);class bU{constructor(){this.storage=new bT.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||{}}}}}let bV=/[\x00-\x1f\x7f-\x9f]/g;function bW(a,b,c){null!=c&&""!==c&&(a[b]=c)}function bX(a){return Array.isArray(a)?a[0]:a}function bY(a){if(Array.isArray(a)){for(let b of a){let a=bY(b);if(void 0!==a)return a}return}if("string"!=typeof a)return;let b=a.replace(bV,"").trim();if(b)return b.length>1e3?b.slice(0,1e3):b}function bZ(a,b){var c,d;let e,{sessionId:f,distinctId:g}=function(a){if(!a)return{};let b=bY(a["x-posthog-session-id"]),c=bY(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 bW(h,"$current_url",(c=b.originalUrl||b.url,i?M(c):c)),bW(h,"$request_method",b.method),bW(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?M(e):e)),bW(h,"$user_agent",bX(b.headers["user-agent"])),bW(h,"$ip",function(a){let b=bX(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 b$(a,b){var c;b.use((c=a,(a,b,d)=>{c.withContext(bZ(c,a),()=>d())}))}function b_(a,b){var c;b.use((c=a,(a,b,d,e)=>{if(bF.isPreviouslyCapturedError(a))return void e(a);let f=bZ(c,b),g=Error("Synthetic exception"),h={...void 0!==f.sessionId?{$session_id:f.sessionId}:{},...f.properties||{},$response_status_code:d.statusCode};c.addPendingPromise(bF.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,b_,"setupExpressRequestContext",0,b$],40602),a.s([],51328);class b0 extends bS{getLibraryId(){return"posthog-node"}initializeContext(){return new bU}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}),bf,function(a=process.cwd()){let b="\\"===h.sep,c=a=>b?a.replace(/\\/g,"/"):a,d=c(a);return async a=>{for(let b of a)!(!b.filename||b.filename.startsWith("node:")||b.filename.startsWith("data:"))&&(0,h.isAbsolute)(b.filename)&&(b.filename=c((0,h.relative)(d,c(b.filename))));return a}}()])}}a.s(["PostHog",0,b0],81035),a.i(81035),a.i(51328);let b1="posthog-node";function b2(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[b4.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};return 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 b3(a,b){let c=b2(a,b);return{name:b1,processEvent:a=>c(a)}}class b4{static #a=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(a,b,c,d,e){this.name=b1,this.name=b1,this.setupOnce=function(f,g){f(b2(a,{organization:b,projectId:g()?.getClient()?.getDsn()?.projectId,prefix:c,severityAllowList:d,sendExceptionsToPostHog:e??!0}))}}}a.s(["PostHogSentryIntegration",0,b4,"createEventProcessor",0,b2,"sentryIntegration",0,b3],9318),a.i(9318),a.i(40602),a.i(46539),a.s(["FeatureFlagError",0,m,"FeatureFlagEvaluations",0,bm,"PostHogSentryIntegration",0,b4,"cookieStateToProperties",0,af,"cookieStoreFromHeader",0,ab,"createEventProcessor",0,b2,"getPostHogCookieName",0,ac,"parsePostHogCookie",0,ag,"readPostHogCookie",0,ae,"sentryIntegration",0,b3,"serializePostHogCookie",0,ad,"setupExpressErrorHandler",0,b_,"setupExpressRequestContext",0,b$,"uuidv7",0,_],80456),a.i(80456),a.s(["FeatureFlagError",0,m,"FeatureFlagEvaluations",0,bm,"PostHog",0,b0,"PostHogSentryIntegration",0,b4,"cookieStateToProperties",0,af,"cookieStoreFromHeader",0,ab,"createEventProcessor",0,b2,"getPostHogCookieName",0,ac,"parsePostHogCookie",0,ag,"readPostHogCookie",0,ae,"sentryIntegration",0,b3,"serializePostHogCookie",0,ad,"setupExpressErrorHandler",0,b_,"setupExpressRequestContext",0,b$,"uuidv7",0,_],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","$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.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.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}}function s(a){let b=[];return JSON.stringify(a,function(a,c){if("bigint"==typeof c)return c.toString();if("function"!=typeof c&&"symbol"!=typeof c){if(c instanceof Error)return{name:c.name,message:c.message,stack:c.stack};if(c&&"object"==typeof c){for(;b.length>0&&b[b.length-1]!==this;)b.pop();if(b.includes(c))return"[Circular]";b.push(c)}return c}})??"null"}let t=Array.isArray,u=Object.prototype;u.hasOwnProperty;let v=u.toString,w=t||function(a){return"[object Array]"===v.call(a)},x=a=>a===Object(a)&&!w(a),y=a=>void 0===a,z=a=>"[object String]"==v.call(a),A=a=>null===a,B=a=>"[object Number]"==v.call(a)&&a==a;function C(a){return null===a||"object"!=typeof a}function D(a,b){return Object.prototype.toString.call(a)===`[object ${b}]`}function E(a){return"u">typeof Event&&function(a,b){try{return a instanceof b}catch{return!1}}(a,Event)}let F="Android",G="BlackBerry",H="Nintendo",I="PlayStation",J="Xbox",K="Windows",L="(\\d+(\\.\\d+)?)";RegExp("Version/"+L),RegExp(J,"i"),RegExp(I+" \\w+","i"),RegExp(H+" \\w+","i"),RegExp(G+"|PlayBook|BB10","i");RegExp("rv:"+L),RegExp("Edge?\\/"+L),RegExp("(Chrome|CrMo)\\/"+L),RegExp("CriOS\\/"+L),RegExp("(UCBrowser|UCWEB)\\/"+L),RegExp("(Opera|OPR)\\/"+L),RegExp("Firefox\\/"+L),RegExp("FxiOS\\/"+L),RegExp("Konqueror[:/]?"+L,"i"),RegExp(G+" "+L),RegExp("android\\s"+L,"i"),RegExp("SamsungBrowser\\/"+L),RegExp("OculusBrowser\\/"+L),RegExp("Vivaldi\\/"+L),RegExp("YaBrowser\\/"+L),RegExp("Whale\\/"+L),RegExp("Brave\\/"+L),RegExp("(DuckDuckGo|Ddg)\\/"+L),RegExp("PaleMoon\\/"+L),RegExp("Waterfox\\/"+L),RegExp("GSA\\/"+L),RegExp("(rv:|MSIE )"+L),RegExp("rv:"+L),RegExp(J+"; "+J+" (.*?)[);]","i"),RegExp(H,"i"),RegExp(I,"i"),RegExp(K,"i"),RegExp("("+F+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+F+")","i");let M=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function N(a,b){return"string"==typeof a&&M.test(a)?a:b()}function O(a){return a?a.split("#")[0]:a}async function P(a,b){let c=null;for(let d=0;d<b.retryCount+1;d++){d>0&&await new Promise(a=>setTimeout(a,b.retryDelay));try{return await a()}catch(a){if(c=a,!b.retryCheck(a))throw a}}throw c}function Q(){return new Date().toISOString()}function R(a,b){let c=setTimeout(a,b);return c?.unref&&c?.unref(),c}let S=a=>a instanceof Error;function T(a){return Promise.all(a.map(a=>(a??Promise.resolve()).then(a=>({status:"fulfilled",value:a}),a=>({status:"rejected",reason:a}))))}function U(a){let b=[];for(let c in a){let d=a[c];A(d)||y(d)||b.push({key:c,value:function a(b){if("[object Boolean]"===v.call(b))return{boolValue:b};if("number"==typeof b)return Number.isFinite(b)?Number.isInteger(b)?{intValue:b}:{doubleValue:b}:{stringValue:String(b)};if("string"==typeof b)return{stringValue:b};if(w(b))return{arrayValue:{values:b.map(b=>a(b))}};try{return{stringValue:JSON.stringify(b)}}catch{return{stringValue:String(b)}}}(d)})}return b}let V=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function W(a){return String(a)+"000000"}function X(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 Y{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=X(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(V.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,V)]+=1}}}_runBeforeSend(a){let b=this._config.beforeSend;if(!b)return a;let c=w(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=R(()=>{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:U(f)},scopeMetrics:[{scope:{name:g,version:h},metrics:e}]}]}}_buildMetrics(a){let b=W(Date.now()),c=new Map;for(let d of a.values()){let a=X(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=U(d.attributes??{}),g=W(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:V};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 Z="0123456789abcdef";class ${constructor(a){this.bytes=a}static ofInner(a){if(16===a.length)return new $(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 $(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 $(a)}throw SyntaxError("could not parse UUID string")}toString(){let a="";for(let b=0;b<this.bytes.length;b++)a+=Z.charAt(this.bytes[b]>>>4),a+=Z.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+=Z.charAt(this.bytes[b]>>>4),a+=Z.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 $(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 _{constructor(a){this.timestamp=0,this.counter=0,this.random=a??aa()}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 $.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,$.ofInner(a)}}let aa=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),ab=()=>ac().toString(),ac=()=>(c||(c=new _)).generate();function ad(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 ae(a){let b=a.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${b}_posthog`}function af(a){let b=Date.now();return JSON.stringify({distinct_id:a,$device_id:a,$user_state:"anonymous",$sesid:[b,ab(),b]})}function ag(a,b){let c=ae(b),d=a.get(c);return d?ai(d.value):null}function ah(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 ai(a){if(!a)return null;try{let b=JSON.parse(a);if(!b||"object"!=typeof b||!b.distinct_id)return null;let c=w(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 aj{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 ak{add(a){let b=ab(),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 al=(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=>al(`${a} ${d}`,b,c)}};class am{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&&w(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 an(a,b,c,d,e){let f={platform:a,filename:b,function:"<anonymous>"===c?"?":c,in_app:!0};return y(d)||(f.lineno=d),y(e)||(f.colno=e),f}a.s(["ErrorPropertiesBuilder",0,am],6762);let ao=(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]},ap=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,aq=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ar=/\((\S*)(?::(\d+))(?::(\d+))\)/,as=(a,b)=>{let c=ap.exec(a);if(c){let[,a,d,e]=c;return an(b,a,"?",+d,+e)}let d=aq.exec(a);if(d){if(d[2]&&0===d[2].indexOf("eval")){let a=ar.exec(d[2]);a&&(d[2]=a[1],d[3]=a[2],d[4]=a[3])}let[a,c]=ao(d[1]||"?",d[2]);return an(b,c,a,d[3]?+d[3]:void 0,d[4]?+d[4]:void 0)}},at=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,au=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,av=(a,b)=>{let c=at.exec(a);if(c){if(c[3]&&c[3].indexOf(" > eval")>-1){let a=au.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]=ao(d,a),an(b,a,d,c[4]?+c[4]:void 0,c[5]?+c[5]:void 0)}},aw=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ax=(a,b)=>{let c=aw.exec(a);return c?an(b,c[2],c[1]||"?",+c[3],c[4]?+c[4]:void 0):void 0},ay=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,az=(a,b)=>{let c=ay.exec(a);return c?an(b,c[2],c[3]||"?",+c[1]):void 0},aA=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,aB=(a,b)=>{let c=aA.exec(a);return c?an(b,c[5],c[3]||c[4]||"?",+c[1],+c[2]):void 0},aC=/^\s*[-]{4,}$/,aD=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,aE=(a,b)=>{let c=a.match(aD);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]),{filename:h?decodeURI(h):void 0,module:void 0,function:e,lineno:aF(c[3]),colno:aF(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(aC))return{filename:a,platform:b}};function aF(a){return parseInt(a||"",10)||void 0}let aG=/\(error: (.*)\)/;function aH(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 aI(){return aJ("web:javascript",as,av)}function aJ(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=aG.test(d)?d.replace(aG,"$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 aH(e)}}a.s(["createDefaultStackParser",0,aI,"createStackParser",0,aJ,"reverseAndStripFrames",0,aH],67970);class aK{match(a){return this.isDOMException(a)||this.isDOMError(a)}coerce(a,b){let c=z(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 D(a,"DOMException")}isDOMError(a){return D(a,"DOMError")}}a.s(["DOMExceptionCoercer",0,aK],51671);class aL{match(a){return a instanceof Error}coerce(a,b){return{type:this.getType(a),value:this.getMessage(a,b),stack:this.getStack(a),cause:a.cause?b.next(a.cause):void 0,synthetic:!1}}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,aL],10692);class aM{match(a){return D(a,"ErrorEvent")&&void 0!=a.error}coerce(a,b){let c=b.apply(a.error);return c||{type:"ErrorEvent",value:a.message,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["ErrorEventCoercer",0,aM],75368);let aN=["fatal","error","warning","log","info","debug"];function aO(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 aP{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:b.syntheticException?.stack,level:this.isSeverityLevel(a.level)?a.level:"error",synthetic:!0}}getType(a){return E(a)?a.constructor.name:"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=aO(a);return`${b&&"Object"!==b?`'${b}'`:"Object"} captured as exception with keys: ${c}`}isSeverityLevel(a){return z(a)&&!(z(a)&&0===a.trim().length)&&aN.indexOf(a)>=0}getErrorPropertyFromObject(a){for(let b in a)if(Object.prototype.hasOwnProperty.call(a,b)){let c=a[b];if(S(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,aP],93874);class aQ{match(a){return E(a)}coerce(a,b){let c=a.constructor.name;return{type:c,value:`${c} captured as exception with keys: ${aO(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["EventCoercer",0,aQ],46980);class aR{match(a){return C(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,aR],28150);class aS{match(a){return D(a,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(a)}isCustomEventWrappingRejection(a){if(!E(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 C(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,aS],98140),a.s([],7610);let aT={MESSAGE:"$message",TIMESTAMP:"$timestamp"},aU=new Set([aT.MESSAGE,aT.TIMESTAMP]),aV={enabled:!0,max_bytes:32768};function aW(a){return a?{enabled:a.enabled??aV.enabled,max_bytes:function(a,b){if(!B(a)||a===1/0||a===-1/0)return b;let c=Math.floor(a);return c<0?b:c}(a.max_bytes,aV.max_bytes)}:{...aV}}function aX(a){if(!a)return{sanitizedProperties:{},droppedKeys:[]};let b=[];return{sanitizedProperties:Object.keys(a).reduce((c,d)=>(aU.has(d)?b.push(d):c[d]=a[d],c),{}),droppedKeys:b}}class aY{constructor(a){this._entries=[],this._totalBytes=0,this._config=aW(a)}setConfig(a){this._config=aW(a),this._trimToMaxBytes()}add(a){let b=function(a){let b;try{b=s(a)}catch{return}try{let a=JSON.parse(b);if(!x(a))return;let c=a[aT.MESSAGE],d=a[aT.TIMESTAMP];if(!z(c)||0===c.trim().length||!z(d)&&!B(d))return;return{step:a,json:b}}catch{return}}(a);if(!b)return;let c=aZ(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 aZ(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,aV,"EXCEPTION_STEP_INTERNAL_FIELDS",0,aT,"ExceptionStepsBuffer",0,aY,"getUtf8ByteLength",0,aZ,"resolveExceptionStepsConfig",0,aW,"stripReservedExceptionStepFields",0,aX],97383),a.s([],48153);let a$=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class a_{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(a$);return d&&(b=d[1],c=d[2]),[b,c]}}a.s(["StringCoercer",0,a_],57802);class a0 extends Error{constructor(a,b){super("HTTP error while fetching PostHog: status="+a.status+", reqByteLength="+b),this.response=a,this.reqByteLength=b,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}}class a1 extends Error{constructor(a){super("Network error while fetching PostHog",a instanceof Error?{cause:a}:{}),this.error=a,this.name="PostHogFetchNetworkError"}}async function a2(a){if(a instanceof a0){let b="";try{b=await a.text}catch{}console.error(`Error while flushing PostHog: message=${a.message}, response body=${b}`,a)}else console.error("Error while flushing PostHog",a);return Promise.resolve()}function a3(a){return a instanceof a1}function a4(a){if(a instanceof a0)return 502===a.status||504===a.status;if(!(a instanceof a1))return!1;let b=a.error;return"ECONNREFUSED"!==(b?.code??b?.cause?.code)}function a5(a){return"object"==typeof a&&a instanceof a0&&413===a.status}function a6(a){return a instanceof a0?408===a.status||429===a.status||a.status>=500:a3(a)}function a7(a){return null!==a&&"object"==typeof a&&!Array.isArray(a)}let a8="default";class a9{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new am([new aL,new aP,new a_,new aR],aI())}constructor(a,b={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new ak,this._events=new aj,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 al(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:a6},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,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(a=>a.json()).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,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:a4},this.featureFlagsRequestTimeoutMs).then(a=>a.json()).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 a0)return{type:"api_error",statusCode:a.status};if(a instanceof a1){let b=a.error;return b instanceof Error&&("AbortError"===b.name||"TimeoutError"===b.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagDetailStateless(a,b,c,d,e,f);if(void 0===g)return{response:void 0,requestId:void 0};let h=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).then(a=>{if(200!==a.status||!a.json){let b=`Surveys API could not be loaded: ${a.status}`,c=Error(b);this._logger.error(c),this._events.emit("error",Error(b));return}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 a8}persistedQueueKeyForRoute(a){return n.Queue}getActiveQueueRoutes(){return[a8]}getRouteQueue(a){return this.getPersistedProperty(this.persistedQueueKeyForRoute(a))||[]}enqueue(a,b,c){this.wrap(()=>{if(this.optedOut)return void this._events.emit(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let d=this.prepareMessage(b,c);if(null===(d=this.processBeforeEnqueue(d)))return;d=this.normalizeMessage(d);let e=this.persistedQueueKeyForRoute(this.getQueueRouteKey(d)),f=this.getPersistedProperty(e)||[];f.length>=this.maxQueueSize&&(f.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),f.push({message:d}),this.setPersistedProperty(e,f),this._events.emit(a,d),f.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=R(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(a,b,c){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 d=this.prepareMessage(b,c);if(null!==(d=this.processBeforeEnqueue(d))){d=this.normalizeMessage(d);try{await this.sendBatch([d],void 0,this.getQueueRouteKey(d))}catch(a){this._events.emit("error",a)}}}normalizeMessage(a){let{type:b,library:c,library_version:d,...e}=a,f=a7(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=N(e.uuid,ab),e}prepareMessage(a,b){let c={...a,timestamp:b?.timestamp?b?.timestamp:Q(),uuid:N(b?.uuid,ab)};return(b?.disableGeoip??this.disableGeoip)&&(a7(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 a2(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(()=>T([b])).then(()=>(this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=d,this.flushPromise=d,this.flushPromises.add(d),this.addPendingPromise(d),T([d]).then(()=>{this.flushPromises.delete(d),this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this.flushPromise===d&&(this.flushPromise=null)}),d}getCustomHeaders(){let a=this.getCustomUserAgent(),b={};return a&&""!==a&&(b["User-Agent"]=a),b}async sendBatch(a,b,c=a8){let d={api_key:this.apiKey,batch:a,sent_at:Q()};this.historicalMigration&&(d.historical_migration=!0);let e=s(d),f=`${this.host}/batch/`,g=this.disableCompression?null:await r(e,this.isDebug),h={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==g&&{"Content-Encoding":"gzip"}},body:g||e},i=await this.fetchWithRetry(f,h,b);await i.body?.cancel()?.catch(()=>{})}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)||[]).slice(e.length);this.setPersistedProperty(c,a),d=a,this._dequeuedMessagesCount+=e.length,await this.flushStorage()},i={retryCheck:a=>!a5(a)&&a6(a)};try{await this.sendBatch(g,i,a)}catch(a){if(a5(a)&&g.length>1){this.maxBatchSize=Math.max(1,Math.floor(g.length/2)),this._logger.warn(`Received 413 when sending batch of size ${g.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw a instanceof a1||await h(),this._events.emit("error",a),a}await h(),b.push(...g),f+=g.length}}async _sendLogsBatch(a){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let b=JSON.stringify(a),c=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,d=this.disableCompression?null:await r(b,this.isDebug),e={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==d&&{"Content-Encoding":"gzip"}},body:d||b};try{return await this.fetchWithRetry(c,e,{retryCheck:a=>!a5(a)&&a6(a)}),{kind:"ok"}}catch(a){if(a5(a))return{kind:"too-large"};if(a instanceof a1)return{kind:"retry-later",error:a};return{kind:"fatal",error:a}}}async _sendMetricsBatch(a){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let b=JSON.stringify(a),c=`${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`,d=this.disableCompression?null:await r(b,this.isDebug),e={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==d&&{"Content-Encoding":"gzip"}},body:d||b};try{return await this.fetchWithRetry(c,e,{retryCheck:a=>!a5(a)&&a6(a)}),{kind:"ok"}}catch(a){if(a5(a))return{kind:"too-large"};if(a6(a))return{kind:"retry-later",error:a};return{kind:"fatal",error:a}}}async fetchWithRetry(a,b,c,d){let e=b.body?b.body:"",f=-1;try{f=e instanceof Blob?e.size:Buffer.byteLength(e,"utf8")}catch{f=e instanceof Blob?e.size:new TextEncoder().encode(e).length}return await P(async()=>{let c=new AbortController,e=R(()=>c.abort(),d??this.requestTimeout),g=null;try{g=await this.fetch(a,{signal:c.signal,...b})}catch(a){throw new a1(a)}finally{clearTimeout(e)}if("no-cors"!==b.mode&&(g.status<200||g.status>=400))throw new a0(g,f);return g},{...this._retryOptions,...c})}async _shutdown(a=3e4){let b;await this._initPromise;let c=!1;if(this.clearFlushTimer(),this.disabled)return;let d=async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(a=>this.getRouteQueue(a).length>0);){let a=this._dequeuedMessagesCount;if(await this.flush(),c)break;if(this._dequeuedMessagesCount===a){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(a){if(!("object"==typeof a&&(a instanceof a0||a3(a))))throw a;await a2(a)}};try{return await Promise.race([new Promise((d,e)=>{b=R(()=>{this._logger.error("Timed out while shutting down PostHog"),c=!0,e("Timeout while shutting down PostHog. Some events may not have been sent.")},a)}),d()])}finally{clearTimeout(b)}}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,as,"createDefaultStackParser",0,aI,"createStackParser",0,aJ,"geckoStackLineParser",0,av,"nodeStackLineParser",0,aE,"opera10StackLineParser",0,az,"opera11StackLineParser",0,aB,"reverseAndStripFrames",0,aH,"winjsStackLineParser",0,ax],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,aK,"ErrorCoercer",0,aL,"ErrorEventCoercer",0,aM,"EventCoercer",0,aQ,"ObjectCoercer",0,aP,"PrimitiveCoercer",0,aR,"PromiseRejectionEventCoercer",0,aS,"StringCoercer",0,a_],54253),a.i(54253);class ba{constructor(a){this._maxSize=a,this._cache=new Map}get(a){let b=this._cache.get(a);if(void 0!==b)return this._cache.delete(a),this._cache.set(a,b),b}set(a,b){this._cache.set(a,b)}reduce(){for(;this._cache.size>=this._maxSize;){let a=this._cache.keys().next().value;a&&this._cache.delete(a)}}}a.s(["ReduceableCache",0,ba],98966),a.i(98966),a.i(97383),a.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,aV,"DOMExceptionCoercer",0,aK,"EXCEPTION_STEP_INTERNAL_FIELDS",0,aT,"ErrorCoercer",0,aL,"ErrorEventCoercer",0,aM,"ErrorPropertiesBuilder",0,am,"EventCoercer",0,aQ,"ExceptionStepsBuffer",0,aY,"ObjectCoercer",0,aP,"PrimitiveCoercer",0,aR,"PromiseRejectionEventCoercer",0,aS,"ReduceableCache",0,ba,"StringCoercer",0,a_,"chromeStackLineParser",0,as,"createDefaultStackParser",0,aI,"createStackParser",0,aJ,"geckoStackLineParser",0,av,"getUtf8ByteLength",0,aZ,"nodeStackLineParser",0,aE,"opera10StackLineParser",0,az,"opera11StackLineParser",0,aB,"resolveExceptionStepsConfig",0,aW,"reverseAndStripFrames",0,aH,"stripReservedExceptionStepFields",0,aX,"winjsStackLineParser",0,ax],60485);var bb=a.i(60485),bc=bb,bd=a.i(2157),be=a.i(1457);let bf=new bc.ReduceableCache(25),bg=new bc.ReduceableCache(20);async function bh(a){let b={};for(let e=a.length-1;e>=0;e--){var c,d;let f=a[e],g=f?.filename;!(!f||"string"!=typeof g||"number"!=typeof f.lineno||(c=g).startsWith("node:")||c.endsWith(".min.js")||c.endsWith(".min.cjs")||c.endsWith(".min.mjs")||c.startsWith("data:")||void 0!==(d=f).lineno&&d.lineno>1e4||void 0!==d.colno&&d.colno>1e3)&&(b[g]||(b[g]=[]),b[g].push(f.lineno))}let e=Object.keys(b);if(0==e.length)return a;let f=[];for(let a of e){if(bg.get(a))continue;let c=b[a];if(!c)continue;c.sort((a,b)=>a-b);let d=function(a){if(!a.length)return[];let b=0,c=a[0];if("number"!=typeof c)return[];let d=bj(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=bj(c)),b++}return e}(c);if(d.every(b=>(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})(a,b)))continue;let e=function(a,b,c){let d=a.get(b);return void 0===d?(a.set(b,c),c):d}(bf,a,{});f.push(function(a,b,c){return new Promise(d=>{let e=(0,bd.createReadStream)(a),f=(0,be.createInterface)({input:e});function g(){e.destroy(),d()}let h=0,i=0,j=b[0];if(void 0===j)return void g();let k=j[0],l=j[1];function m(){bg.set(a,1),f.close(),f.removeAllListeners(),g()}e.on("error",m),f.on("error",m),f.on("close",g),f.on("line",a=>{if(!(++h<k)&&(c[h]=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),h>=l)){if(i===b.length-1){f.close(),f.removeAllListeners();return}let a=b[++i];if(void 0===a){f.close(),f.removeAllListeners();return}k=a[0],l=a[1]}})})}(a,d,e))}return await Promise.all(f).catch(()=>{}),a&&a.length>0&&function(a,b){for(let c of a)if(c.filename&&void 0===c.context_line&&"number"==typeof c.lineno){let a=b.get(c.filename);if(void 0===a)continue;!function(a,b,c){if(void 0===b.lineno||void 0===c)return;b.pre_context=[];for(let d=bk(a);d<a;d++){let a=c[d];if(void 0===a)return void bi(b);b.pre_context.push(a)}if(void 0===c[a])return bi(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)}}(c.lineno,c,a)}}(a,bf),bf.reduce(),a}function bi(a){delete a.pre_context,delete a.context_line,delete a.post_context}function bj(a){return[bk(a),a+7]}function bk(a){return Math.max(1,a-7)}let bl=["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"],bm=function(a,b=[]){if(!a)return!1;let c=a.toLowerCase();return bl.concat(b).some(a=>{let b=a.toLowerCase();return -1!==c.indexOf(b)})},bn={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};a.s(["FeatureFlagError",0,bn],46539);class bo{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){let b=this._flags[a];return this._recordAccess(a),b?.enabled??!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 bo({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(bn.ERRORS_WHILE_COMPUTING),this._quotaLimited&&e.push(bn.QUOTA_LIMITED),void 0===b&&e.push(bn.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 bp(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 bq=["is_not","is_set"];class br extends Error{constructor(a){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=a,Object.setPrototypeOf(this,br.prototype)}}function bs(a,b){a.name=b.name,Error.captureStackTrace(a,b),Object.setPrototypeOf(a,b.prototype)}class bt extends Error{constructor(a){super(a),bs(this,bt)}}class bu extends Error{constructor(a){super(a),bs(this,bu)}}class bv{constructor({pollingInterval:a,personalApiKey:b,projectApiKey:c,timeout:d,host:e,customHeaders:f,...g}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,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 bu||b instanceof bt?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 bu||b instanceof bt?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 bt("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 bt("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 bt(`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 bt("Feature flags not available for dependency evaluation");if(!("dependency_chain"in a))throw new bt(`Flag dependency property for '${e}' is missing required 'dependency_chain' field`);let f=a.dependency_chain;if(!Array.isArray(f))throw new bt(`Flag dependency property for '${e}' has an invalid 'dependency_chain' (expected array, got ${typeof f})`);if(0===f.length)throw new bt(`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 bt(`Error evaluating flag dependency '${a}' for flag '${e}': ${b}`)}else d[a]=!1;else throw new bt(`Missing flag dependency '${a}' for flag '${e}'`)}if(null==d[a])throw new bt(`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 bu)throw a;if(a instanceof bt)l=!0;else throw a}if(void 0!==e)return e;if(l)throw new bt("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 by(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):bx(a,d,g);if(!c)return"no_match"}if(void 0==f)return"match"}return void 0!=f&&await bw(a.key,b)>f/100?"out_of_rollout_bound":"match"}async getMatchingVariant(a,b){let c=await bw(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),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());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 br(`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 br(`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 br(`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 br&&this.onError?.(a)}}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}}_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=R(()=>{a.abort()},this.timeout),b.signal=a.signal}try{return(0,this.fetch)(a,b)}finally{clearTimeout(c)}}async stopPoller(a=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let b=this.cacheProvider.shutdown();b instanceof Promise&&await Promise.race([b,new Promise((b,c)=>setTimeout(()=>c(Error(`Cache shutdown timeout after ${a}ms`)),a))])}catch(a){this.onError?.(Error(`Error during cache shutdown: ${a}`))}}}async function bw(a,b,c=""){return parseInt((await bp(`${a}.${b}${c}`)).slice(0,15),16)/0x1000000000000000}function bx(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 bt(`Property ${d} not found in propertyValues`)}let g=b[d];if(null==g&&!bq.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"regex":return bA(String(e))&&null!==String(g).match(String(e));case"not_regex":return bA(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 bt("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=bE(e)),null==a)throw new bt(`Invalid date: ${e}`);let b=bE(g);if(["is_date_before"].includes(f))return b<a;return b>a}case"semver_eq":return 0===bD(bC(String(g)),bC(String(e)));case"semver_neq":return 0!==bD(bC(String(g)),bC(String(e)));case"semver_gt":return bD(bC(String(g)),bC(String(e)))>0;case"semver_gte":return bD(bC(String(g)),bC(String(e)))>=0;case"semver_lt":return 0>bD(bC(String(g)),bC(String(e)));case"semver_lte":return 0>=bD(bC(String(g)),bC(String(e)));case"semver_tilde":{let a,b=bC(String(g)),{lower:c,upper:d}={lower:[(a=bC(String(e)))[0],a[1],a[2]],upper:[a[0],a[1]+1,0]};return bD(b,c)>=0&&0>bD(b,d)}case"semver_caret":{let a=bC(String(g)),{lower:b,upper:c}=function(a){let[b,c,d]=bC(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 bD(a,b)>=0&&0>bD(a,c)}case"semver_wildcard":{let a=bC(String(g)),{lower:b,upper:c}=function(a){let b,c,d=String(a).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!d)throw new bt(`Invalid wildcard semver: ${a}`);let e=d.split("."),f=b=>{try{return bB(b,a)}catch{throw new bt(`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 bD(a,b)>=0&&0>bD(a,c)}default:throw new bt(`Unknown operator: ${f}`)}}async function by(a,b,c,d=!1,e){let f=String(a.value);if(!(f in c))throw new bu(`cohort ${f} not found in local cohorts - likely a static cohort that requires server evaluation`);return bz(c[f],b,c,d,e)}async function bz(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 bz(a,b,c,d,e);if("AND"===f){if(!g)return!1}else if(g)return!0}catch(b){if(b instanceof bu)throw b;if(b instanceof bt)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),h=!0;else throw b}if(h)throw new bt("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 by(a,b,c,d,e);else if("flag"===a.type){if(!e)throw new bt(`Flag dependency '${a.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);g=await e(a)}else g=bx(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 bu)throw b;if(b instanceof bt)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),h=!0;else throw b}if(h)throw new bt("can't match cohort without a given cohort property value");return"AND"===f}function bA(a){try{return new RegExp(a),!0}catch(a){return!1}}function bB(a,b){if(!/^\d+$/.test(a)||a.length>1&&"0"===a[0])throw new bt(`Invalid semver: ${b}`);return parseInt(a,10)}function bC(a){let b=String(a).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!b||b.startsWith("."))throw new bt(`Invalid semver: ${a}`);let c=b.split("."),d=b=>void 0===b||""===b?0:bB(b,a);return[d(c[0]),d(c[1]),d(c[2])]}function bD(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 bE(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 bt(`${a} is in an invalid date format`)}throw new bt(`The date provided ${a} must be a string, number, or date object`)}function bF(a,b,c,d,e){if(b>c&&(d.warn("min cannot be greater than max."),b=c),B(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),bF(e||c,b,c,d)}class bG{constructor(a){this._buckets={},this._onBucketRateLimited=a._onBucketRateLimited,this._bucketSize=bF(a.bucketSize,0,100,a._logger),this._refillRate=bF(a.refillRate,0,this._bucketSize,a._logger),this._refillInterval=bF(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={}}}class bH{constructor(a,b,c){this.client=a,this._exceptionAutocaptureEnabled=b.enableExceptionAutocapture||!1,this._logger=c,this._rateLimiter=new bG({...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 x(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);return g.$exception_list=await a.modifyFrames(g.$exception_list),{event:"$exception",distinctId:d,properties:{...g,...f},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled()){var b,c,d;let e;b=this.onException.bind(this),c=this.onFatalError.bind(this),globalThis.process?.on("uncaughtException",(e=!1,Object.assign(d=>{let f=a.g.process.listeners("uncaughtException").filter(a=>"domainUncaughtExceptionClear"!==a.name&&!0!==a._posthogErrorHandler).length;b(d,{mechanism:{type:"onuncaughtexception",handled:!1}}),e||0!==f||(e=!0,c(d))},{_posthogErrorHandler:!0}))),d=this.onException.bind(this),globalThis.process?.on("unhandledRejection",a=>d(a,{mechanism:{type:"onunhandledrejection",handled:!1}}))}}onException(a,b){this.client.addPendingPromise((async()=>{if(!bH.isPreviouslyCapturedError(a)){let c=await bH.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 bI{getProperty(a){return this._memoryStorage[a]}setProperty(a,b){this._memoryStorage[a]=null!==b?b:void 0}constructor(){this._memoryStorage={}}}let bJ="analytics";class bK extends Error{constructor({requestId:a,drops:b,retryExhausted:c,cause:d}){super(bK.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 bL(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 bM=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:bL},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:bL},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:bL},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(a){return"string"==typeof a?a:void 0}}],bN=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function bO(a,b,c){void 0===c||b in a||(a[b]=c)}function bP(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 bM)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 bN)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,bO(c,"$set",a.$set),bO(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)return Number.isNaN(new Date(a).getTime())?new Date().toISOString():a;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 bQ=new Set([408,500,502,503,504]);class bR{constructor(a,b){this.config=a,this.maxBackoffMs=a.maxBackoffMs??3e4,this.fetchFn=b.fetch,this.onError=b.onError,this.now=b.now??Date.now,this.sleep=b.sleep??(a=>new Promise(b=>R(b,a))),this.generateRequestId=b.generateRequestId??ab,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(bP)};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=s({created_at:c,...this.config.historicalMigration?{historical_migration:!0}:{},batch:g});try{d=await this.sendOnce(e,k,a,b)}catch(c){if(j)return this.surfaceBatchFailure(b,f,g,c);await this.sleep(this.backoffDelay(a));continue}let{status:l}=d;if(l<200||l>=300){if(!j&&bQ.has(l)){let b=this.parseRetryAfter(d);await this.cancelBody(d),await this.sleep(this.backoffDelay(a,b));continue}let c=await this.buildHttpError(d,l);return this.surfaceBatchFailure(b,f,g,c)}try{i=await this.parseResponse(d)}catch{return this.surfaceBatchFailure(b,f,g,Error(`Capture V1 returned an unparseable ${l} response body`))}let m=this.classify(g,i,f);if(0===m.length)return this.surfacePartialDrops(b,f);if(j)return void this.onError(new bK({requestId:b,drops:f,retryExhausted:m.map(a=>a.uuid)}));g=m;let n=this.parseRetryAfter(d);await this.sleep(this.backoffDelay(a,n))}}async sendOnce(a,b,c,d){let e=this.buildHeaders(c,d),f=b;if(this.config.compressionEnabled){let a=await this.compress(b,this.config.isDebug);null!==a&&(f=a,e["Content-Encoding"]="gzip")}let g=new AbortController,h=R(()=>g.abort(),this.config.requestTimeoutMs);try{return await this.fetchFn(a,{method:"POST",headers:e,body:f,signal:g.signal})}finally{clearTimeout(h)}}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){let c="";try{c=(await a.text()).slice(0,512)}catch{}let d=c?`: ${c}`:"";return Error(`Capture V1 request failed with HTTP ${b}${d}`)}surfaceBatchFailure(a,b,c,d){this.onError(new bK({requestId:a,drops:b,retryExhausted:c.map(a=>a.uuid),cause:d}))}surfacePartialDrops(a,b){b.length>0&&this.onError(new bK({requestId:a,drops:b,retryExhausted:[]}))}async cancelBody(a){await a.body?.cancel()?.catch(()=>{})}}let bS=new Set;function bT(a,b){bS.has(a)||(bS.add(a),console.warn(`[PostHog] ${b}`))}class bU extends a9{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 bI,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.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 bv({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 bH(this,d,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=d.maxCacheSize||5e4}enqueue(a,b,c){super.enqueue(a,b,c),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=R(()=>{this.resolveWaitUntilFlush()},d)}_consumeWaitUntilCycle(){let a=this._waitUntilCycle;return a&&(clearTimeout(a.timer),this._waitUntilCycle=void 0),a?.resolve}async resolveWaitUntilFlush(){let a=this._consumeWaitUntilCycle();try{await this.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":bJ}persistedQueueKeyForRoute(a){return"ai"===a?n.AiQueue:n.Queue}getActiveQueueRoutes(){return"v1"===this.captureMode?[bJ,"ai"]:[bJ]}async sendBatch(a,b,c=bJ){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)}getV1Sender(){return this._v1Sender||(this._v1Sender=new bR({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)})),this._v1Sender}getLibraryVersion(){return"5.46.0"}get metrics(){var a;let b;return this._metrics||(this._metrics=new Y(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){return this.addPendingPromise(this._prepareEventMessage(b,d).then(({distinctId:b,event:d,properties:e,options:f})=>{let g={timestamp:f.timestamp,disableGeoip:f.disableGeoip,uuid:f.uuid},h={distinctId:b,event:d,properties:{...e,...this.getCommonEventProperties()}};return c?this.sendImmediate(a,h,g):this.enqueue(a,h,g)}).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)}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 bu||b instanceof bt)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=bn.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===b.minimalFlagCalledEvents,f=b.requestId,g=b.evaluatedAt;let c=[];b.errorsWhileComputingFlags&&c.push(bn.ERRORS_WHILE_COMPUTING),b.quotaLimited?.includes("feature_flags")&&c.push(bn.QUOTA_LIMITED);let d=b.flags[a];if(void 0===d)c.push(bn.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,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){bT("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(bT("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){bT("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 bo({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new bo({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 bo({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 Promise.race([this._metrics.flush().catch(()=>{}),new Promise(a=>R(a,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=R(()=>{a.abort()},this.options.requestTimeout),c.signal=a.signal}try{return await this.fetch(b,c)}catch(a){this._events.emit("error",a);return}finally{d&&clearTimeout(d)}}extractPropertiesFromEvent(a,b){if(!a)return{personProperties:{},groupProperties:{}};let c={},d={};for(let[e,f]of Object.entries(a))if(D(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(!bH.isPreviouslyCapturedError(a)){let f=Error("PostHog syntheticException");this.addPendingPromise(bH.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(!bH.isPreviouslyCapturedError(a)){let e=Error("PostHog syntheticException");return this.addPendingPromise(bH.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=ab(),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){bT("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&&bm(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){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)}}return d}}var bc=bb,bV=a.i(78500);class bW{constructor(){this.storage=new bV.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||{}}}}}let bX=/[\x00-\x1f\x7f-\x9f]/g;function bY(a,b,c){null!=c&&""!==c&&(a[b]=c)}function bZ(a){return Array.isArray(a)?a[0]:a}function b$(a){if(Array.isArray(a)){for(let b of a){let a=b$(b);if(void 0!==a)return a}return}if("string"!=typeof a)return;let b=a.replace(bX,"").trim();if(b)return b.length>1e3?b.slice(0,1e3):b}function b_(a,b){var c,d;let e,{sessionId:f,distinctId:g}=function(a){if(!a)return{};let b=b$(a["x-posthog-session-id"]),c=b$(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 bY(h,"$current_url",(c=b.originalUrl||b.url,i?O(c):c)),bY(h,"$request_method",b.method),bY(h,"$request_path",(d=b.path,e=function(a){if(!a)return a;let b=a.indexOf("?"),c=a.indexOf("#");return -1===b||-1!==c&&c<b?a:`${a.slice(0,b)}${-1===c?"":a.slice(c)}`}(d),i?O(e):e)),bY(h,"$user_agent",bZ(b.headers["user-agent"])),bY(h,"$ip",function(a){let b=bZ(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 b0(a,b){var c;b.use((c=a,(a,b,d)=>{c.withContext(b_(c,a),()=>d())}))}function b1(a,b){var c;b.use((c=a,(a,b,d,e)=>{if(bH.isPreviouslyCapturedError(a))return void e(a);let f=b_(c,b),g=Error("Synthetic exception"),h={...void 0!==f.sessionId?{$session_id:f.sessionId}:{},...f.properties||{},$response_status_code:d.statusCode};c.addPendingPromise(bH.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,b1,"setupExpressRequestContext",0,b0],40602),a.s([],51328);class b2 extends bU{getLibraryId(){return"posthog-node"}initializeContext(){return new bW}createErrorPropertiesBuilder(){let a;return new bc.ErrorPropertiesBuilder([new bc.EventCoercer,new bc.ErrorCoercer,new bc.ObjectCoercer,new bc.StringCoercer,new bc.PrimitiveCoercer],bc.createStackParser("node:javascript",bc.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}),bh,function(a=process.cwd()){let b="\\"===h.sep,c=a=>b?a.replace(/\\/g,"/"):a,d=c(a);return async a=>{for(let b of a)!(!b.filename||b.filename.startsWith("node:")||b.filename.startsWith("data:"))&&(0,h.isAbsolute)(b.filename)&&(b.filename=c((0,h.relative)(d,c(b.filename))));return a}}()])}}a.s(["PostHog",0,b2],81035),a.i(81035),a.i(51328);let b3="posthog-node";function b4(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[b6.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};return 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 b5(a,b){let c=b4(a,b);return{name:b3,processEvent:a=>c(a)}}class b6{static #a=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(a,b,c,d,e){this.name=b3,this.name=b3,this.setupOnce=function(f,g){f(b4(a,{organization:b,projectId:g()?.getClient()?.getDsn()?.projectId,prefix:c,severityAllowList:d,sendExceptionsToPostHog:e??!0}))}}}a.s(["PostHogSentryIntegration",0,b6,"createEventProcessor",0,b4,"sentryIntegration",0,b5],9318),a.i(9318),a.i(40602),a.i(46539),a.s(["FeatureFlagError",0,o,"FeatureFlagEvaluations",0,bo,"PostHogSentryIntegration",0,b6,"cookieStateToProperties",0,ah,"cookieStoreFromHeader",0,ad,"createEventProcessor",0,b4,"getPostHogCookieName",0,ae,"parsePostHogCookie",0,ai,"readPostHogCookie",0,ag,"sentryIntegration",0,b5,"serializePostHogCookie",0,af,"setupExpressErrorHandler",0,b1,"setupExpressRequestContext",0,b0,"uuidv7",0,ab],80456),a.i(80456),a.s(["FeatureFlagError",0,o,"FeatureFlagEvaluations",0,bo,"PostHog",0,b2,"PostHogSentryIntegration",0,b6,"cookieStateToProperties",0,ah,"cookieStoreFromHeader",0,ad,"createEventProcessor",0,b4,"getPostHogCookieName",0,ae,"parsePostHogCookie",0,ai,"readPostHogCookie",0,ag,"sentryIntegration",0,b5,"serializePostHogCookie",0,af,"setupExpressErrorHandler",0,b1,"setupExpressRequestContext",0,b0,"uuidv7",0,ab],74493)}];
|
|
2
2
|
|
|
3
3
|
//# sourceMappingURL=node_modules_posthog-node_dist_entrypoints_index_node_mjs_11bnuzn._.js.map
|