From 3b2bf3ef6d6daed8003f3123a7734e4c9db85732 Mon Sep 17 00:00:00 2001 From: scttbnsn <80784472+scttbnsn@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:09:18 -0500 Subject: [PATCH 1/3] feat(website): add cookieless PostHog page analytics Page views, web vitals and clicks on the download and source links go through e.codeswhat.com, only on dilated.app. Every event is rebuilt from an allowlist before it leaves the browser. posthog-js and web-vitals are vendored unchanged. The privacy page now describes the site analytics and keeps the claim that the app collects nothing. The e2e server now sends the CSP route's headers; it was reading the first route, which is the host redirect. --- scripts/verify.sh | 2 +- website/README.md | 9 + website/dist/analytics/client.mjs | 47 ++ website/dist/analytics/contract.mjs | 231 ++++++++++ website/dist/analytics/web-vitals-buffer.mjs | 46 ++ website/dist/assets/vendor/README.md | 14 + .../dist/assets/vendor/posthog-js-1.449.2.mjs | 2 + website/dist/assets/vendor/posthog-js-LICENSE | 417 ++++++++++++++++++ .../dist/assets/vendor/web-vitals-6.2.1.mjs | 2 + website/dist/assets/vendor/web-vitals-LICENSE | 202 +++++++++ website/dist/closed-lid-setup.html | 5 +- website/dist/index.html | 3 +- website/dist/privacy.html | 19 +- website/e2e/serve.mjs | 4 +- website/e2e/site.spec.mjs | 18 + website/tests/analytics.test.mjs | 315 +++++++++++++ website/tests/privacy.test.mjs | 19 +- website/vercel.json | 2 +- 18 files changed, 1339 insertions(+), 18 deletions(-) create mode 100644 website/dist/analytics/client.mjs create mode 100644 website/dist/analytics/contract.mjs create mode 100644 website/dist/analytics/web-vitals-buffer.mjs create mode 100644 website/dist/assets/vendor/README.md create mode 100644 website/dist/assets/vendor/posthog-js-1.449.2.mjs create mode 100644 website/dist/assets/vendor/posthog-js-LICENSE create mode 100644 website/dist/assets/vendor/web-vitals-6.2.1.mjs create mode 100644 website/dist/assets/vendor/web-vitals-LICENSE create mode 100644 website/tests/analytics.test.mjs diff --git a/scripts/verify.sh b/scripts/verify.sh index b41793c..5f09bb9 100755 --- a/scripts/verify.sh +++ b/scripts/verify.sh @@ -24,7 +24,7 @@ if [ -n "${DILATED_COVERAGE:-}" ]; then fi python3 -m unittest discover -s Tests/ReleaseTests node --test website/tests/*.test.mjs -for module in website/dist/*.mjs; do node --check "$module"; done +for module in website/dist/*.mjs website/dist/analytics/*.mjs; do node --check "$module"; done swift format lint --strict --recursive Sources Tests Package.swift design/menubar/generate.swift design/app-icon/generate.swift scripts/dmg/background.swift scripts/dmg/volume-icon.swift for script in scripts/build-app.sh scripts/swift-test.sh scripts/verify.sh scripts/verify-website-browsers.sh scripts/coverage-lcov.sh scripts/check-commit-msg.sh; do bash -n "$script"; done bash -n packaging/mas/dilated-power diff --git a/website/README.md b/website/README.md index 07e1bc7..d42a53a 100644 --- a/website/README.md +++ b/website/README.md @@ -16,6 +16,15 @@ https://dilated.app with `scripts/publish-website.py`. For local review, serve `dist/` from any static server, for example on `http://127.0.0.1:5173/`. +## Analytics + +The site sends cookieless PostHog page analytics through `e.codeswhat.com`, only +when served from `dilated.app`. Localhost, previews and test runs send nothing. +The code is `dist/analytics/` (`contract.mjs` is the allowlist every event is +rebuilt from). PostHog and web-vitals are vendored unchanged under +`dist/assets/vendor/`, with versions and hashes in its README. The app has no +analytics. + ## Release availability The checked-in page has no app download. The published site gets one from the diff --git a/website/dist/analytics/client.mjs b/website/dist/analytics/client.mjs new file mode 100644 index 0000000..ecc66d6 --- /dev/null +++ b/website/dist/analytics/client.mjs @@ -0,0 +1,47 @@ +// Cookieless page analytics. Loads only on the production host, so localhost, +// previews and test runs send nothing. +import posthog from '../assets/vendor/posthog-js-1.449.2.mjs'; +import { onCLS, onFCP, onINP, onLCP } from '../assets/vendor/web-vitals-6.2.1.mjs'; + +import { + POSTHOG_PROXY_HOST, + POSTHOG_UI_HOST, + buildCtaEvent, + buildPageviewEvent, + buildWebVitalsEvent, + canonicalizeAnalyticsRoute, + createPostHogOptions, + isProductionHost, +} from './contract.mjs'; +import { createWebVitalsReporter } from './web-vitals-buffer.mjs'; + +// Public write-only project key, same as the other CodesWhat sites. +const PROJECT_KEY = 'phc_mav2oHZzTVaC4mAFEqaLbGEff65uvGMy47LcWSNBFp9J'; // gitleaks:allow + +function capture(event) { + if (event) posthog.capture(event.event, event.properties); +} + +function start() { + const options = createPostHogOptions(PROJECT_KEY, POSTHOG_PROXY_HOST, POSTHOG_UI_HOST); + if (!options) return; + posthog.init(PROJECT_KEY, options); + + const path = location.pathname; + capture(buildPageviewEvent(path)); + + const vitals = createWebVitalsReporter(path, capture, buildWebVitalsEvent, canonicalizeAnalyticsRoute); + const record = metric => vitals.record(metric.name, metric.value); + onLCP(record); + onINP(record); + onCLS(record); + onFCP(record); + + document.addEventListener('click', event => { + const target = event.target instanceof Element ? event.target.closest('[data-cta]') : null; + if (!target) return; + capture(buildCtaEvent(location.pathname, target.dataset.cta, target.dataset.ctaPlacement)); + }); +} + +if (isProductionHost(location.hostname)) start(); diff --git a/website/dist/analytics/contract.mjs b/website/dist/analytics/contract.mjs new file mode 100644 index 0000000..3c56246 --- /dev/null +++ b/website/dist/analytics/contract.mjs @@ -0,0 +1,231 @@ +// Pure analytics contract: no DOM, importable from node. Everything the site +// sends to PostHog is rebuilt from the allowlists here by sanitizeEvent. + +export const POSTHOG_PROXY_HOST = 'https://e.codeswhat.com'; +export const POSTHOG_UI_HOST = 'https://us.posthog.com'; +export const PRODUCTION_HOST = 'dilated.app'; + +const SCHEMA_VERSION = 1; +const SITE = 'dilated'; +const SURFACE = 'marketing'; +const PROJECT_KEY_PATTERN = /^phc_[A-Za-z0-9_-]+$/u; +const COOKIELESS_DISTINCT_ID = '$posthog_cookieless'; + +const KNOWN_PATHS = new Set(['/', '/privacy', '/closed-lid-setup']); + +const FILE_ALIASES = new Map([ + ['/index.html', '/'], + ['/privacy.html', '/privacy'], + ['/closed-lid-setup.html', '/closed-lid-setup'], +]); + +const CTA_COMBINATIONS = new Set([ + 'download:availability', + 'release_history:availability', + 'sponsor:availability', + 'donate:availability', + 'closed_lid_setup_download:page', + 'github_repository:header', +]); + +const WEB_VITAL_NAMES = ['CLS', 'FCP', 'INP', 'LCP']; +const WEB_VITAL_KEYS = WEB_VITAL_NAMES.map(name => `$web_vitals_${name}_value`); + +export function isProductionHost(hostname) { + return hostname === PRODUCTION_HOST; +} + +function normalizedPath(rawPath) { + const withoutQuery = rawPath.split(/[?#]/u, 1)[0] || '/'; + if (!withoutQuery.startsWith('/')) return '/'; + if (withoutQuery.length > 1 && withoutQuery.endsWith('/')) { + return withoutQuery.slice(0, -1); + } + return withoutQuery; +} + +export function canonicalizeAnalyticsRoute(rawPath) { + const normalized = normalizedPath(rawPath); + const aliased = FILE_ALIASES.get(normalized) ?? normalized; + return { + normalizedPath: aliased, + path: KNOWN_PATHS.has(aliased) ? aliased : '/_other', + surface: SURFACE, + }; +} + +function baseProperties(rawPath) { + const { path, surface } = canonicalizeAnalyticsRoute(rawPath); + return { schema_version: SCHEMA_VERSION, site: SITE, surface, path }; +} + +// PostHog's Web analytics tables key off $pathname. It carries the canonical +// path, so it adds nothing the event wasn't already sending. +function navigationProperties(rawPath) { + const base = baseProperties(rawPath); + return { ...base, $pathname: base.path }; +} + +export function buildPageviewEvent(rawPath) { + return { event: '$pageview', properties: navigationProperties(rawPath) }; +} + +// posthog-js emits $pageleave itself once capture_pageleave is true. +export function buildPageleaveEvent(rawPath) { + return { event: '$pageleave', properties: navigationProperties(rawPath) }; +} + +export function buildCtaEvent(rawPath, ctaId, placement) { + if (!CTA_COMBINATIONS.has(`${ctaId}:${placement}`)) return null; + return { + event: 'cta activated', + properties: { ...baseProperties(rawPath), cta_id: ctaId, placement }, + }; +} + +export function buildWebVitalsEvent(rawPath, metrics) { + const properties = baseProperties(rawPath); + let metricCount = 0; + for (const name of WEB_VITAL_NAMES) { + const value = metrics[name]; + if (typeof value === 'number' && Number.isFinite(value) && value >= 0) { + properties[`$web_vitals_${name}_value`] = value; + metricCount += 1; + } + } + return metricCount === 0 ? null : { event: '$web_vitals', properties }; +} + +// $referring_domain is either "$direct" or a bare host (optionally with a +// port). Anything else is dropped rather than trimmed, so an unexpected shape +// can't leak a path. $referrer (the full URL) is never forwarded. +const HOSTNAME_PATTERN = + /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d{1,5})?$/iu; +const DIRECT_REFERRING_DOMAIN = '$direct'; + +function isAcceptableReferringDomain(value) { + return ( + typeof value === 'string' && (value === DIRECT_REFERRING_DOMAIN || HOSTNAME_PATTERN.test(value)) + ); +} + +function rawPathFromProperties(properties) { + if (typeof properties.path === 'string') return properties.path; + if (typeof properties.$current_url !== 'string') return undefined; + try { + return new URL(properties.$current_url).pathname; + } catch { + return undefined; + } +} + +export function sanitizeEvent(envelope) { + if (!envelope || typeof envelope.event !== 'string' || !envelope.properties) return null; + const rawPath = rawPathFromProperties(envelope.properties); + const key = envelope.properties.token; + // PostHog's cookieless ingestion hashes day + team + IP + $host + + // $raw_user_agent and drops the event if either of the last two is missing, + // so both must survive the allowlist rebuild. $ip is never forwarded. + const rawUserAgent = envelope.properties.$raw_user_agent; + const host = envelope.properties.$host; + if ( + typeof rawPath !== 'string' || + typeof key !== 'string' || + !PROJECT_KEY_PATTERN.test(key) || + envelope.properties.$cookieless_mode !== true || + envelope.properties.$process_person_profile !== false || + typeof rawUserAgent !== 'string' || + rawUserAgent === '' || + typeof host !== 'string' || + host === '' + ) { + return null; + } + + let sanitized; + if (envelope.event === '$pageview') { + sanitized = buildPageviewEvent(rawPath); + } else if (envelope.event === '$pageleave') { + sanitized = buildPageleaveEvent(rawPath); + } else if (envelope.event === 'cta activated') { + const ctaId = envelope.properties.cta_id; + const placement = envelope.properties.placement; + if (typeof ctaId !== 'string' || typeof placement !== 'string') return null; + sanitized = buildCtaEvent(rawPath, ctaId, placement); + } else if (envelope.event === '$web_vitals') { + const metrics = {}; + WEB_VITAL_KEYS.forEach((metricKey, index) => { + const value = envelope.properties[metricKey]; + if (typeof value === 'number') metrics[WEB_VITAL_NAMES[index]] = value; + }); + sanitized = buildWebVitalsEvent(rawPath, metrics); + } else { + return null; + } + + if (!sanitized) return null; + const output = { + event: sanitized.event, + properties: { + ...sanitized.properties, + token: key, + $cookieless_mode: true, + $process_person_profile: false, + $raw_user_agent: rawUserAgent, + $host: host, + }, + uuid: envelope.uuid, + }; + if (isAcceptableReferringDomain(envelope.properties.$referring_domain)) { + output.properties.$referring_domain = envelope.properties.$referring_domain; + } + if (envelope.properties.distinct_id === COOKIELESS_DISTINCT_ID) { + output.properties.distinct_id = COOKIELESS_DISTINCT_ID; + } + if (envelope.timestamp instanceof Date && Number.isFinite(envelope.timestamp.getTime())) { + output.timestamp = envelope.timestamp; + } + return output; +} + +export function createPostHogOptions(projectKey, proxyHost, uiHost) { + if ( + !projectKey || + !PROJECT_KEY_PATTERN.test(projectKey) || + proxyHost !== POSTHOG_PROXY_HOST || + uiHost !== POSTHOG_UI_HOST + ) { + return null; + } + return { + api_host: POSTHOG_PROXY_HOST, + ui_host: POSTHOG_UI_HOST, + autocapture: false, + rageclick: false, + capture_pageview: false, + capture_pageleave: true, + capture_heatmaps: false, + capture_dead_clicks: false, + capture_exceptions: false, + disable_session_recording: true, + disable_surveys: true, + disable_surveys_automatic_display: true, + disable_product_tours: true, + disable_web_experiments: true, + advanced_disable_flags: true, + cookieless_mode: 'always', + person_profiles: 'never', + persistence: 'memory', + disable_persistence: true, + respect_dnt: true, + save_campaign_params: false, + save_referrer: true, + disable_capture_url_hashes: true, + disable_scroll_properties: true, + mask_all_element_attributes: true, + mask_all_text: true, + capture_performance: false, + disable_external_dependency_loading: true, + before_send: sanitizeEvent, + }; +} diff --git a/website/dist/analytics/web-vitals-buffer.mjs b/website/dist/analytics/web-vitals-buffer.mjs new file mode 100644 index 0000000..fb310e2 --- /dev/null +++ b/website/dist/analytics/web-vitals-buffer.mjs @@ -0,0 +1,46 @@ +export const WEB_VITALS_FLUSH_DELAY_MS = 5_000; + +const WEB_VITAL_NAMES = new Set(['CLS', 'FCP', 'INP', 'LCP']); + +const defaultSchedule = (callback, delayMs) => setTimeout(callback, delayMs); +const defaultCancel = timer => clearTimeout(timer); + +// Collects the four vitals and emits one $web_vitals event: when all four have +// arrived, or WEB_VITALS_FLUSH_DELAY_MS after the first one, whichever is first. +export function createWebVitalsReporter( + initialPath, + emit, + buildEvent, + canonicalizePath, + schedule = defaultSchedule, + cancel = defaultCancel, +) { + const path = canonicalizePath(initialPath).normalizedPath; + const metrics = {}; + let timer; + let sent = false; + + const flush = () => { + if (sent) return; + sent = true; + if (timer !== undefined) { + cancel(timer); + timer = undefined; + } + const event = buildEvent(path, metrics); + if (event) emit(event); + }; + + return { + record(name, value) { + if (sent || !WEB_VITAL_NAMES.has(name)) return; + if (!Number.isFinite(value) || value < 0) return; + + metrics[name] = value; + if (timer === undefined) { + timer = schedule(flush, WEB_VITALS_FLUSH_DELAY_MS); + } + if (WEB_VITAL_NAMES.size === Object.keys(metrics).length) flush(); + }, + }; +} diff --git a/website/dist/assets/vendor/README.md b/website/dist/assets/vendor/README.md new file mode 100644 index 0000000..a3d93a1 --- /dev/null +++ b/website/dist/assets/vendor/README.md @@ -0,0 +1,14 @@ +# Vendored browser modules + +The site has no build step, so these ES modules are copied from their npm packages unchanged. Neither file has bare-specifier imports or dynamic `import()`, so a browser loads them as they are. + +| File | Source package | Version | Source file | sha256 | +| --- | --- | --- | --- | --- | +| `posthog-js-1.449.2.mjs` | `posthog-js` | 1.449.2 | `dist/module.slim.no-external.js` | `576c2c662b6729437bef4a5e43e81dcf96d84fd7cc0da0fc325d86db03a30d03` | +| `web-vitals-6.2.1.mjs` | `web-vitals` | 6.2.1 | `dist/web-vitals.js` | `bdf421fcbd62c2572c8b09096572262496e2bc54289bcae80c9fe94f6ca6769d` | + +The PostHog build is the slim, no-external variant: it has no session recording, surveys or other lazy-loaded extensions, and it never injects remote scripts. + +Licenses: `posthog-js-LICENSE` and `web-vitals-LICENSE`, copied from the packages. + +To update, run `npm pack @` in an empty directory outside the repo, copy the source file over, and update the version, name and hash here and in `analytics/client.mjs`. diff --git a/website/dist/assets/vendor/posthog-js-1.449.2.mjs b/website/dist/assets/vendor/posthog-js-1.449.2.mjs new file mode 100644 index 0000000..7033509 --- /dev/null +++ b/website/dist/assets/vendor/posthog-js-1.449.2.mjs @@ -0,0 +1,2 @@ +var e,t=["retriesPerformedSoFar"];function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;arguments.length>t;t++){var i=arguments[t];for(var s in i)({}).hasOwnProperty.call(i,s)&&(e[s]=i[s])}return e},i.apply(null,arguments)}function s(e,t,i,s,r,n,o){try{var a=e[n](o),l=a.value}catch(e){return void i(e)}a.done?t(l):Promise.resolve(l).then(s,r)}function r(e){return function(){var t=this,i=arguments;return new Promise(function(r,n){var o=e.apply(t,i);function a(e){s(o,r,n,a,l,"next",e)}function l(e){s(o,r,n,a,l,"throw",e)}a(void 0)})}}var n="0.11.0",o={DEBUG:(!1,!1),LIB_VERSION:(n,"1.449.2"),LIB_NAME:("browser-common","web"),JS_SDK_VERSION:n},a=o,l="$early_access_features",d="$active_feature_flags",u="$feature_flag_details",_="$feature_flag_errors",c="$feature_flag_evaluated_at",h="$feature_flag_request_id",p="$minimal_flag_called_events",g="$enabled_feature_flags",v="$stored_group_properties",f="$stored_person_properties",m="$flag_call_reported",y="$flag_call_reported_session_id",b="$feature_flag_payloads",w="$override_feature_flags",S="$override_feature_flag_payloads",P="visibilitychange",k="$autocapture_disabled_server_side",C="$surveys",I="$surveys_loaded_at",E="$surveys_activated",x="$surveys_activated_session",T="$surveys_activated_timestamps",F="$people_distinct_id",R="distinct_id",O="$device_id",M="$device_model",A="__alias",D="__cmpns",L="$fbc",N="$fbc_persistence",B="$fbp",U="$fbp_persistence",q="__timers",H="$heatmaps_enabled_server_side",G="$exception_capture_enabled_server_side",W="$error_tracking_suppression_rules",V="$error_tracking_capture_extension_exceptions",j="$web_vitals_enabled_server_side",z="$dead_clicks_enabled_server_side",K="$product_tours_enabled_server_side",J="$logs_capture_enabled_server_side",Y="$web_vitals_allowed_metrics",Q="$session_recording_remote_config",X="$session_recording_enabled_server_side",Z="$replay_sample_rate",ee="$replay_override_sampling",te="$replay_override_linked_flag",ie="$replay_override_url_trigger",se="$replay_override_event_trigger",re="$sesid",ne="$session_is_sampled",oe="$session_past_minimum_duration",ae="$session_recording_url_trigger_activated_session",le="$session_recording_event_trigger_activated_session",de="$debug_first_full_snapshot_timestamp",ue="$sess_rec_flush_size",_e="$groups",ce="ph_product_tours",he="$product_tours_activated",pe="$product_tours_activated_session",ge="$conversations_widget_session_id",ve="$conversations_ticket_id",fe="$conversations_widget_state",me="$conversations_user_traits",ye="$user_state",be="$client_session_props",we="$capture_rate_limit",Se="$initial_campaign_params",Pe="$initial_referrer_info",ke="$initial_person_info",Ce="$epp",Ie="$posthog_cookieless",Ee="$cookieless_mode",xe="$sdk_debug_extensions_init_method",Te="$sdk_debug_extensions_init_time_ms",$e="$sdk_debug_recording_script_not_loaded",Fe="$sdk_debug_replay_stale_config",Re="$sdk_debug_replay_event_trigger_status",Oe="$sdk_debug_replay_linked_flag_trigger_status",Me="$sdk_debug_replay_matched_recording_trigger_groups",Ae="$sdk_debug_replay_pending_trigger_conditions",De="$sdk_debug_replay_remote_trigger_matching_config",Le="$sdk_debug_replay_trigger_groups_count",Ne="$sdk_debug_replay_url_trigger_status",Be="$session_recording_start_reason",Ue="anonymous",qe="identified",He="identified_only",Ge="beforeunload",We="$pageview",Ve="$pageleave",je="$identify",ze="$groupidentify",Ke="u">typeof window?window:void 0,Je="u">typeof globalThis?globalThis:Ke,Ye=null==Je?void 0:Je.navigator,Qe=null==Je?void 0:Je.document,Xe=null==Je?void 0:Je.location,Ze=null==Je?void 0:Je.fetch,et=null!=Je&&Je.XMLHttpRequest&&"withCredentials"in new Je.XMLHttpRequest?Je.XMLHttpRequest:void 0,tt=null==Je?void 0:Je.AbortController,it=null==Je?void 0:Je.CompressionStream,st=null==Ye?void 0:Ye.userAgent,rt="undefined"!=typeof globalThis?globalThis:Ke;rt&&"undefined"==typeof self&&(rt.self=rt),rt&&"undefined"==typeof File&&(rt.File=function(){});var nt=null!=Ke?Ke:{},ot=function(e){return e.GZipJS="gzip-js",e.Base64="base64",e}({}),at=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"],lt=["token"];function dt(e,t){return-1!==e.indexOf(t)}var ut=function(e){return e.replace(/^\$/,"")},_t=Object.prototype,ct=_t.hasOwnProperty,ht=_t.toString,pt=Array.isArray||function(e){return"[object Array]"===ht.call(e)},gt=e=>"function"==typeof e,vt=e=>e===Object(e)&&!pt(e),ft=e=>{if(vt(e)){for(var t in e)if(ct.call(e,t))return!1;return!0}return!1},mt=e=>void 0===e,yt=e=>"[object String]"==ht.call(e),bt=e=>yt(e)&&0===e.trim().length,wt=e=>null===e,St=e=>mt(e)||wt(e),Pt=e=>"[object Number]"==ht.call(e)&&e==e,kt=e=>Pt(e)&&e>0,Ct=e=>"[object Boolean]"===ht.call(e),It=e=>dt(at,e),Et=e=>dt(lt,e);function xt(e){switch({}.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return function(e,t){try{return e instanceof t}catch(e){return!1}}(e,Error)}}var Tt=[!0,"true",1,"1","yes"],$t=e=>dt(Tt,e),Ft=[!1,"false",0,"0","no"],Rt=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","lightpanda","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],Ot=new Map,Mt=function(e,t){if(void 0===t&&(t=[]),!e)return!1;var i=function(e,t){for(var i="",s=0;t.length>s;s++){var r=t[s];i+=r.length+":"+r}return e.length+":"+e+"|"+t.length+":"+i}(e,t),s=Ot.get(i);if(void 0!==s)return s;var r=e.toLowerCase(),n=Rt.concat(t).some(e=>-1!==r.indexOf(e.toLowerCase()));return 256>Ot.size||Ot.clear(),Ot.set(i,n),n};function At(e,t,i,s,r){return t>i&&(s.warn("min cannot be greater than max."),t=i),Pt(e)?e>i?(s.warn(" cannot be greater than max: "+i+". Using max value instead."),i):t>e?(s.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(s.warn(" must be a number. using max or fallback. max: "+i+", fallback: "+r),At(null!=r?r:i,t,i,s))}var Dt="Mobile",Lt="Android",Nt="Tablet",Bt="Android Tablet",Ut="iPad",qt="Apple Watch",Ht="Safari",Gt="BlackBerry",Wt="Samsung Internet",Vt="Chrome",jt="Chrome iOS",zt="Internet Explorer",Kt="Internet Explorer Mobile",Jt="Opera",Yt="Microsoft Edge",Qt="Firefox",Xt="Firefox iOS",Zt="Nintendo",ei="PlayStation",ti="Xbox",ii="Android Mobile",si="Mobile Safari",ri="Windows",ni="Windows Phone",oi="Nokia",ai="Ouya",li="Generic tablet",di="Konqueror",ui="Oculus Browser",_i="Vivaldi",ci="Yandex",hi="Whale",pi="DuckDuckGo",gi="Pale Moon",vi="Waterfox",fi="Brave",mi="Claude",yi="Codex",bi="ChatGPT",wi="Google Search App",Si=new RegExp("Version/(\\d+(\\.\\d+)?)"),Pi=new RegExp("(Claude|Codex|ChatGPT)\\/(\\d+(\\.\\d+)?)"),ki=new RegExp(ti,"i"),Ci=new RegExp("PlayStation \\w+","i"),Ii=new RegExp("Nintendo \\w+","i"),Ei=new RegExp("BlackBerry|PlayBook|BB10","i"),xi={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"},Ti=function(e,t,i,s){t=t||"";var r=function(e){return null!=e&&e.brave?fi:null}(i);return r||(null!=s&&s.detectGoogleSearchApp&&dt(e,"GSA/")?wi:dt(e," OPR/")&&dt(e,"Mini")?"Opera Mini":dt(e," OPR/")?Jt:Ei.test(e)?Gt:dt(e,"IEMobile")||dt(e,"WPDesktop")?Kt:dt(e,"OculusBrowser")?ui:dt(e,"SamsungBrowser")?Wt:dt(e,"Edge")||dt(e,"Edg/")?Yt:dt(e,"Vivaldi/")?_i:dt(e,"YaBrowser/")?ci:dt(e,"Whale/")?hi:dt(e,"DuckDuckGo/")||dt(e,"Ddg/")?pi:dt(e,"Claude/")?mi:dt(e,"Codex/")?yi:dt(e,"ChatGPT/")?bi:dt(e,"FBIOS")?"Facebook Mobile":dt(e,"UCWEB")||dt(e,"UCBrowser")?"UC Browser":dt(e,"CriOS")?jt:dt(e,"CrMo")||dt(e,Vt)?Vt:dt(e,Lt)&&dt(e,Ht)?ii:dt(e,"FxiOS")?Xt:dt(e.toLowerCase(),di.toLowerCase())?di:dt(e,"Brave/")?fi:((e,t)=>t&&dt(t,"Apple")||function(e){return dt(e,Ht)&&!dt(e,Vt)&&!dt(e,Lt)}(e))(e,t)?dt(e,Dt)?si:Ht:dt(e,"PaleMoon/")?gi:dt(e,"Waterfox/")?vi:dt(e,Qt)?Qt:dt(e,"MSIE")||dt(e,"Trident/")?zt:dt(e,"Gecko")?Qt:"")},$i={[Kt]:[new RegExp("rv:(\\d+(\\.\\d+)?)")],[Yt]:[new RegExp("Edge?\\/(\\d+(\\.\\d+)?)")],[Vt]:[new RegExp("(Chrome|CrMo)\\/(\\d+(\\.\\d+)?)")],[jt]:[new RegExp("CriOS\\/(\\d+(\\.\\d+)?)")],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/(\\d+(\\.\\d+)?)")],[Ht]:[Si],[si]:[Si],[Jt]:[new RegExp("(Opera|OPR)\\/(\\d+(\\.\\d+)?)")],[Qt]:[new RegExp("Firefox\\/(\\d+(\\.\\d+)?)")],[Xt]:[new RegExp("FxiOS\\/(\\d+(\\.\\d+)?)")],[di]:[new RegExp("Konqueror[:/]?(\\d+(\\.\\d+)?)","i")],[Gt]:[new RegExp("BlackBerry (\\d+(\\.\\d+)?)"),Si],[ii]:[new RegExp("android\\s(\\d+(\\.\\d+)?)","i")],[Wt]:[new RegExp("SamsungBrowser\\/(\\d+(\\.\\d+)?)")],[ui]:[new RegExp("OculusBrowser\\/(\\d+(\\.\\d+)?)")],[_i]:[new RegExp("Vivaldi\\/(\\d+(\\.\\d+)?)")],[ci]:[new RegExp("YaBrowser\\/(\\d+(\\.\\d+)?)")],[hi]:[new RegExp("Whale\\/(\\d+(\\.\\d+)?)")],[fi]:[new RegExp("Brave\\/(\\d+(\\.\\d+)?)")],[mi]:[Pi],[yi]:[Pi],[bi]:[Pi],[pi]:[new RegExp("(DuckDuckGo|Ddg)\\/(\\d+(\\.\\d+)?)")],[gi]:[new RegExp("PaleMoon\\/(\\d+(\\.\\d+)?)")],[vi]:[new RegExp("Waterfox\\/(\\d+(\\.\\d+)?)")],[wi]:[new RegExp("GSA\\/(\\d+(\\.\\d+)?)")],[zt]:[new RegExp("(rv:|MSIE )(\\d+(\\.\\d+)?)")],Mozilla:[new RegExp("rv:(\\d+(\\.\\d+)?)")]},Fi=function(e,t,i,s){var r=$i[Ti(e,t,i,s)];if(mt(r))return null;for(var n=0;r.length>n;n++){var o=e.match(r[n]);if(o)return parseFloat(o[o.length-2])}return null},Ri=[[new RegExp("Xbox; Xbox (.*?)[);]","i"),e=>[ti,e&&e[1]||""]],[new RegExp(Zt,"i"),[Zt,""]],[new RegExp(ei,"i"),[ei,""]],[Ei,[Gt,""]],[new RegExp(ri,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[ni,""];if(new RegExp(Dt).test(t)&&!/IEMobile\b/.test(t))return["Windows Mobile",""];var i=/Windows NT ([0-9.]+)/i.exec(t);if(i&&i[1]){var s=xi[i[1]]||"";return/arm/i.test(t)&&(s="RT"),[ri,s]}return[ri,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>e&&e[3]?["iOS",[e[3],e[4],e[5]||"0"].join(".")]:["iOS",""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{var t="";return e&&e.length>=3&&(t=mt(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("(Android (\\d+)\\.(\\d+)\\.?(\\d+)?|Android)","i"),e=>e&&e[2]?[Lt,[e[2],e[3],e[4]||"0"].join(".")]:[Lt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{var t=["Mac OS X",""];return e&&e[1]&&(t[1]=[e[1],e[2],e[3]||"0"].join(".")),t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,["Chrome OS",""]],[/Linux|debian/i,["Linux",""]]],Oi=function(e){return Ii.test(e)?Zt:Ci.test(e)?ei:ki.test(e)?ti:new RegExp(ai,"i").test(e)?ai:new RegExp("(Windows Phone|WPDesktop)","i").test(e)?ni:/iPad/.test(e)?Ut:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?qt:Ei.test(e)?Gt:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(oi,"i").test(e)?oi:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(e)||/(kf[a-z]+)( bui|\)).+silk\//i.test(e)?"Kindle Fire":/(Android|ZTE)/i.test(e)?new RegExp(Dt).test(e)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(e)||/pixel[\daxl ]{1,6}/i.test(e)&&!/pixel c/i.test(e)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(e)||/lmy47v/i.test(e)&&!/QTAQZ3/i.test(e)?Lt:Bt:new RegExp("(pda|Mobile)","i").test(e)?"Generic mobile":new RegExp(Nt,"i").test(e)&&!new RegExp("Tablet pc","i").test(e)?li:""},Mi=/\bFBAV\/(\d+(?:\.\d+)*)/i,Ai=[[/\bInstagram(?:[ /](\d+(?:\.\d+)*))?\b/i,"Instagram"],[/\bBarcelona[ /](\d+(?:\.\d+)*)?/i,"Threads"],[/\b(?:MessengerForiOS|(?:FBAN|FB_IAB)\/Orca-Android)\b/i,"Messenger",Mi],[/\bFBAN\/EMA\b/i,"Facebook Lite",Mi],[/\b(?:FBIOS|(?:FBAN|FB_IAB)\/(?:FB4A|FBIOS))\b/i,"Facebook",Mi],[/\bLinkedInApp(?:\]?\/(\d+(?:\.\d+)*))?\b/i,"LinkedIn"],[/\bTwitter(?:Android| for (?:iPhone|iPad|Android))(?:\/(\d+(?:\.\d+)*))?\b/i,"Twitter"],[/\b(?:musical_ly|trill)(?:[_/](\d+\.\d+(?:\.\d+)*))?(?=\b|_)/i,"TikTok",/\bapp_version\/(\d+(?:\.\d+)*)/i],[/\b(?:MicroMessenger|WeChat)\/(\d+(?:\.\d+)*)?/i,"WeChat"],[/\bLine\/(\d+(?:\.\d+)*)?/i,"Line"],[/\bGSA\/(\d+(?:\.\d+)*)?/i,"Google"],[/\[Pinterest\/(?:iOS|Android)\b|\bPinterest(?: for (?:Android(?: Tablet)?|iOS))?\/(\d+(?:\.\d+)*)/i,"Pinterest"],[/\b(?:WA4A|WAiOS)\/(\d+(?:\.\d+)*)?/i,"WhatsApp"],[/\bSnapchat[ /](\d+(?:\.\d+)*)?/i,"Snapchat"],[/\bBing(?:Web|Sapphire)\/(\d+(?:\.\d+)*)?/i,"Bing"],[/\bNAVER\(inapp; search;/i,"Naver",/\bNAVER\(inapp; search;[^;)]*; (\d+(?:\.\d+)*)/i],[/\bKAKAOTALK[ /](\d+\.\d+(?:\.\d+)*)?/i,"KakaoTalk"]],Di=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Li(e,t){return"string"==typeof(i=e)&&Di.test(i)?e:t();var i}function Ni(e,t){var i=new Error(t);try{Object.defineProperty(i,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){}return i}function Bi(e){return e?e.split("#")[0]:e}var Ui,qi=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","bfcid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Hi="NativeGzipValidationError",Gi=e=>e.length>=2&&31===e[0]&&139===e[1],Wi=(e,t)=>e===ot.GZipJS||t===ot.GZipJS||"gzip"===t,Vi=e=>!(!e||"object"!=typeof e)&&"NotReadableError"===("name"in e?String(e.name):""),ji=e=>{throw Ni(Hi,"Native gzip produced invalid output: "+e)},zi=function(){var e=r(function*(e,t){18>e.size&&ji("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());Gi(i)&&8===i[2]||ji("invalid-header");var s=new DataView(yield e.slice(e.size-8).arrayBuffer());s.getUint32(0,!0)!==(e=>{for(var t=(()=>{if(Ui)return Ui;Ui=[];for(var e=0;256>e;e++){for(var t=e,i=0;8>i;i++)t=1&t?3988292384^t>>>1:t>>>1;Ui[e]=t>>>0}return Ui})(),i=4294967295,s=0;e.length>s;s++)i=t[255&(i^e[s])]^i>>>8;return(4294967295^i)>>>0})(t)&&ji("invalid-crc");var r=t.length>>>0;s.getUint32(4,!0)!==r&&ji("invalid-size")});return function(t,i){return e.apply(this,arguments)}}();function Ki(){return Ki=r(function*(e,t,i){void 0===t&&(t=!0);try{var s=(new TextEncoder).encode(e),n=new globalThis.CompressionStream("gzip"),o=n.writable.getWriter(),a=o.write(s).then(()=>o.close()).catch(function(){var e=r(function*(e){try{yield o.abort(e)}catch(e){}throw e});return function(t){return e.apply(this,arguments)}}()),l=new Response(n.readable).blob(),d=(yield Promise.all([l,a]))[0];return yield zi(d,s),d}catch(e){if(null!=i&&i.rethrow)throw e;return t&&console.error("Failed to gzip compress data",e),null}}),Ki.apply(this,arguments)}var Ji=function(e,t){var i=(void 0===t?{}:t).debugEnabled,s={_log(t){var s;try{s=typeof window>"u"?void 0:window}catch(e){return}for(var r=arguments.length,n=new Array(r>1?r-1:0),a=1;r>a;a++)n[a-1]=arguments[a];s&&(o.DEBUG||s.POSTHOG_DEBUG||i)&&!mt(s.console)&&s.console&&("__rrweb_original__"in s.console[t]?s.console[t].__rrweb_original__:s.console[t])(e,...n)},debug(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];s._log("debug",...t)},info(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];s._log("log",...t)},warn(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];s._log("warn",...t)},error(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];s._log("error",...t)},critical(){for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];console.error(e,...i)},uninitializedWarning(e){s.error("You must initialize PostHog before calling "+e)},createLogger:(t,i)=>Ji(e+" "+t,i)};return s},Yi=Ji("[PostHog.js]"),Qi=(e,t)=>Yi.createLogger(e,t);function Xi(e,t){pt(e)&&e.forEach(t)}function Zi(e,t){if(!St(e))if(pt(e))e.forEach(t);else if((e=>e instanceof FormData)(e))e.forEach((e,i)=>t(e,i));else for(var i in e)ct.call(e,i)&&t(e[i],i)}var es=function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;t>s;s++)i[s-1]=arguments[s];for(var r of i)for(var n in r)void 0!==r[n]&&(e[n]=r[n]);return e},ts=function(e){return function(){try{for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];return e.apply(this,i)}catch(e){Yi.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),Yi.critical(e)}}},is=function(e){var t={};return Zi(e,function(e,i){(yt(e)&&e.length>0||Pt(e))&&(t[i]=e)}),t};function ss(e){var t=i({},e);for(var s of["name","message","stack","cause","errors"])try{s in e&&(t[s]=e[s])}catch(e){}return t}var rs=["herokuapp.com","vercel.app","netlify.app"];function ns(e){var t=null==e?void 0:e.hostname;if(!yt(t))return!1;var i=t.split(".").slice(-2).join(".");for(var s of rs)if(i===s)return!1;return!0}function os(e,t,i,s){var r=null!=s?s:{},n=r.capture,o=r.passive;null==e||e.addEventListener(t,i,{capture:void 0!==n&&n,passive:void 0===o||o})}var as,ls,ds=e=>{if(Qe){try{for(var t=e+"=",i=Qe.cookie.split(";").filter(e=>e.length),s=0;i.length>s;s++){for(var r=i[s];" "==r.charAt(0);)r=r.substring(1,r.length);if(0===r.indexOf(t))return decodeURIComponent(r.substring(t.length,r.length))}}catch(e){}return null}},us=class e{constructor(e){if(this.bytes=e,16!==e.length)throw new TypeError("not 128-bit length")}static fromFieldsV7(t,i,s,r){if(!Number.isInteger(t)||!Number.isInteger(i)||!Number.isInteger(s)||!Number.isInteger(r)||0>t||0>i||0>s||0>r||t>0xffffffffffff||i>4095||s>1073741823||r>4294967295)throw new RangeError("invalid field value");var n=new Uint8Array(16);return n[0]=t/Math.pow(2,40),n[1]=t/Math.pow(2,32),n[2]=t/Math.pow(2,24),n[3]=t/Math.pow(2,16),n[4]=t/256,n[5]=t,n[6]=112|i>>>8,n[7]=i,n[8]=128|s>>>24,n[9]=s>>>16,n[10]=s>>>8,n[11]=s,n[12]=r>>>24,n[13]=r>>>16,n[14]=r>>>8,n[15]=r,new e(n)}toString(){for(var e="",t=0;this.bytes.length>t;t++)e=e+(this.bytes[t]>>>4).toString(16)+(15&this.bytes[t]).toString(16),3!==t&&5!==t&&7!==t&&9!==t||(e+="-");if(36!==e.length)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new e(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(var t=0;16>t;t++){var i=this.bytes[t]-e.bytes[t];if(0!==i)return Math.sign(i)}return 0}},_s=class{generate(){var e=this.generateOrAbort();if(!mt(e))return e;this._timestamp=0;var t=this.generateOrAbort();if(mt(t))throw new Error("Could not generate UUID after timestamp reset");return t}generateOrAbort(){var e=(()=>{var e=Date.now();return Pt(e)&&isFinite(e)?Math.min(Math.max(Math.floor(e),0),0xffffffffffff):0})();if(e>this._timestamp)this._timestamp=e,this._resetCounter();else{if(this._timestamp>=e+1e4)return;this._counter++,this._counter>4398046511103&&(this._timestamp++,this._resetCounter())}return us.fromFieldsV7(this._timestamp,Math.trunc(this._counter/Math.pow(2,30)),this._counter&Math.pow(2,30)-1,this._random.nextUint32())}_resetCounter(){this._counter=1024*this._random.nextUint32()+(1023&this._random.nextUint32())}constructor(){this._timestamp=0,this._counter=0,this._random=new hs}},cs=e=>{if("u">typeof UUIDV7_DENY_WEAK_RNG&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var t=0;e.length>t;t++)e[t]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return e},hs=class{nextUint32(){return this._buffer.length>this._cursor||((null!=as?as:as="u">typeof window&&!mt(window.crypto)&&crypto.getRandomValues?e=>{try{return crypto.getRandomValues(e)}catch(t){return cs(e)}}:cs)(this._buffer),this._cursor=0),this._buffer[this._cursor++]}constructor(){this._buffer=new Uint32Array(8),this._cursor=1/0}},ps=()=>gs().toString(),gs=()=>(ls||(ls=new _s)).generate(),vs="",fs=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;var ms=null,ys={_is_supported(){if(!wt(ms))return ms;if(ms=!1,Qe)try{var e="__ph_cookie_support_"+ps();ys._set(e,"xyz"),ms='"xyz"'===ds(e),ys._remove(e)}catch(e){ms=!1}return ms},_error(e){Yi.error("cookieStore error: "+e)},_get:ds,_parse(e){var t;try{t=JSON.parse(ys._get(e))||{}}catch(e){}return t},_set(e,t,i,s,r){if(!Qe)return!1;try{var n="",o="",a=function(e,t){if(t){var i=function(e,t){if(void 0===t&&(t=Qe),vs)return vs;if(!t)return"";if(["localhost","127.0.0.1"].includes(e))return"";for(var i=e.split("."),s=Math.min(i.length,8),r="dmn_chk_"+ps();!vs&&s--;){var n=i.slice(s).join("."),o=r+"=1;domain=."+n+";path=/";t.cookie=o+";max-age=3",t.cookie.includes(r)&&(t.cookie=o+";max-age=0",vs=n)}return vs}(e);if(!i){var s=(e=>{var t=e.match(fs);return t?t[0]:""})(e);s!==i&&Yi.info("Warning: cookie subdomain discovery mismatch",s,i),i=s}return i?"; domain=."+i:""}return""}(Qe.location.hostname,s);if(i){var l=new Date;l.setTime(l.getTime()+864e5*i),n="; expires="+l.toUTCString()}r&&(o="; secure");var d=e+"="+encodeURIComponent(JSON.stringify(t))+n+"; SameSite=Lax; path=/"+a+o;return d.length>3686.4&&Yi.warn("cookieStore warning: large cookie, len="+d.length),Qe.cookie=d,!0}catch(e){return!1}},_remove(e,t){if(null!=Qe&&Qe.cookie&&(!t||!wt(ds(e))))try{ys._set(e,"",-1,t)}catch(e){return}}},bs=null,ws={_is_supported(){if(!wt(bs))return bs;var e=!0;if(mt(Ke))e=!1;else try{var t="__mplssupport__";ws._set(t,"xyz"),'"xyz"'!==ws._get(t)&&(e=!1),ws._remove(t)}catch(t){e=!1}return e||Yi.error("localStorage unsupported; falling back to cookie store"),bs=e,e},_error(e){Yi.error("localStorage error: "+e)},_get(e){try{return null==Ke?void 0:Ke.localStorage.getItem(e)}catch(e){ws._error(e)}return null},_parse(e){try{return JSON.parse(ws._get(e))||{}}catch(e){}return null},_set(e,t){try{return null==Ke||Ke.localStorage.setItem(e,JSON.stringify(t)),!0}catch(e){ws._error(e)}return!1},_remove(e){try{null==Ke||Ke.localStorage.removeItem(e)}catch(e){ws._error(e)}}},Ss=[f,d,g,u,b,h,c,_,m],Ps=[O,R,re,ne,Ce,ke,N,ye],ks=e=>e+"_cpm",Cs=["__proto__","constructor","prototype"],Is=e=>{if(!vt(e))return{};var t={};return Object.keys(e).forEach(i=>{-1===Cs.indexOf(i)&&(t[i]=e[i])}),t},Es=function(e,t){void 0===t&&(t=[]);var i={};return[...Ps,...t].forEach(t=>{var s=e[t];mt(s)||wt(s)||""===s||(i[t]=s)}),i},xs=e=>{for(var t=5381,i=2166136261,s=0;e.length>s;s++){var r=e.charCodeAt(s);t=33*t^r,i=Math.imul(i^r,16777619)}return e.length.toString(36)+"."+(t>>>0).toString(36)+"."+(i>>>0).toString(36)},Ts=(e,t)=>({p:t,f:xs(JSON.stringify(e))}),$s=(e,t)=>{if(!t)return{properties:[],isValid:!1};try{var i=ys._parse(ks(e)),s=(null==i?void 0:i.f)===xs(t)&&pt(i.p);return{properties:s?i.p:[],isValid:s}}catch(e){return{properties:[],isValid:!1}}},Fs=(e,t)=>t+"|"+(ys._get(ks(e))||""),Rs={},Os={_is_supported:()=>!0,_error(e){Yi.error("memoryStorage error: "+e)},_get:e=>e in Rs?Rs[e]:null,_parse:e=>e in Rs?Rs[e]:null,_set:(e,t)=>(Rs[e]=t,!0),_remove(e){delete Rs[e]}},Ms=null,As={_is_supported(){if(!wt(Ms))return Ms;if(Ms=!0,mt(Ke))Ms=!1;else try{var e="__support__";As._set(e,"xyz"),'"xyz"'!==As._get(e)&&(Ms=!1),As._remove(e)}catch(e){Ms=!1}return Ms},_error(e){Yi.error("sessionStorage error: ",e)},_get(e){try{return null==Ke?void 0:Ke.sessionStorage.getItem(e)}catch(e){As._error(e)}return null},_parse(e){try{return JSON.parse(As._get(e))||null}catch(e){}return null},_set(e,t){try{return null==Ke||Ke.sessionStorage.setItem(e,JSON.stringify(t)),!0}catch(e){As._error(e)}return!1},_remove(e){try{null==Ke||Ke.sessionStorage.removeItem(e)}catch(e){As._error(e)}}},Ds=class{constructor(e){this._instance=e}get _config(){return this._instance.config}get consent(){return this._getDnt()?0:this._storedConsent}isOptedOut(){return"always"===this._config.cookieless_mode||this.isRejected()||-1===this.consent&&"on_reject"===this._config.cookieless_mode}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return 0===this.consent}isRejected(){return 0===this.consent||-1===this.consent&&this._config.opt_out_capturing_by_default}optInOut(e){this._storage._set(this._storageKey,e?1:0,this._config.cookie_expiration,this._config.cross_subdomain_cookie,this._config.secure_cookie)}reset(){this._storage._remove(this._storageKey,this._config.cross_subdomain_cookie)}get _storageKey(){var e=this._instance.config,t=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+t:"__ph_opt_in_out_"+t)}get _storedConsent(){var e=this._storage._get(this._storageKey);return $t(e)?1:dt(Ft,e)?0:-1}get _storage(){var e=this._config.opt_out_capturing_persistence_type,t="localStorage"===e?ws:ys,i=t._is_supported()?t:Os;if(!this._persistentStore||this._persistentStore!==i){this._persistentStore=i;var s="localStorage"===e?ys:ws;s._get(this._storageKey)&&(this._persistentStore._get(this._storageKey)||this.optInOut($t(s._get(this._storageKey))),s._remove(this._storageKey,this._config.cross_subdomain_cookie))}return this._persistentStore}_getDnt(){return!!this._config.respect_dnt&&[null==Ye?void 0:Ye.doNotTrack,null==Ye?void 0:Ye.msDoNotTrack,nt.doNotTrack,null==Ye?void 0:Ye.globalPrivacyControl].some(e=>$t(e))}},Ls=["next","previous","prev",">","<","→","←","›","‹","»","«","▶","◀","❯","❮"],Ns=(()=>[...Ls,"+","-","−","–"])(),Bs=e=>{var t,i=!(null==(t=e.instance.persistence)||!t.get_property(z)),s=e.instance.config.capture_dead_clicks;return Ct(s)?s:!!vt(s)||i},Us=Qi("[SegmentIntegration]");function qs(e,t,s){void 0===s&&(s=!0);var r=e.config.segment;if(!r)return t();var n,o=(e=>gt(e.register))(n=r)?{analytics:n}:n,a=o.analytics,l=o.filterProperties;!function(e,t,i,s){var r=t=>{var r=()=>t.anonymousId()||ps();e.config.get_device_id=r,s&&t.id()&&(e.register({distinct_id:t.id(),$device_id:r()}),e.persistence.set_property(ye,qe)),i(s?void 0:t.anonymousId()||void 0)},n=t.user();"then"in n&>(n.then)?n.then(r):r(n)}(e,a,s=>{a.register(function(e,t,s){var r=(void 0===s?{}:s).filterProperties;"undefined"!=typeof Promise&&Promise.resolve||Us.warn("This browser does not have Promise support, and can not use the segment integration");var n=(s,n)=>{if(!n)return s;var o=!!t&&s.event.anonymousId===t&&!s.event.userId;o||s.event.userId||s.event.anonymousId===e.get_distinct_id()||(Us.info("No userId set, resetting PostHog"),e.reset()),o||(t=void 0),s.event.userId&&s.event.userId!==e.get_distinct_id()&&(Us.info("UserId set, identifying with PostHog"),e.identify(s.event.userId));var a=e.calculateEventProperties(n,s.event.properties);if(!St(r)){var l=s.event.properties||{},d={};for(var u of Object.keys(a))ct.call(l,u)||(d[u]=a[u]);var _=((e,t)=>{var s=pt(e)?e:[e],r=i({},t);for(var n of s)try{if(r=n(r),St(r))return null}catch(e){return Us.error("Error in Segment filterProperties:",e),null}return r})(r,d);if(St(_))return s;a=_}return s.event.properties=Object.assign({},a,s.event.properties),s};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded(){return!0},load(){return Promise.resolve()},track(e){return n(e,e.event.event)},page(e){return n(e,We)},identify(e){return n(e,je)},screen(e){return n(e,"$screen")}}}(e,s,{filterProperties:l})).then(()=>{t()},e=>{Us.error("Failed to register the Segment integration",e),t()})},s)}var Hs="posthog-js";function Gs(e,t){var s=void 0===t?{}:t,r=s.organization,n=s.projectId,o=s.prefix,a=s.severityAllowList,l=void 0===a?["error"]:a,d=s.sendExceptionsToPostHog,u=void 0===d||d;return t=>{var s,a,d,_,c,h;if("*"!==l&&!l.includes(t.level)||!e.__loaded)return t;t.tags||(t.tags={});var p=e.requestRouter.endpointFor("ui","/project/"+e.config.token+"/person/"+e.get_distinct_id());t.tags["PostHog Person URL"]=p,e.sessionRecordingStarted()&&(t.tags["PostHog Recording URL"]=e.get_session_replay_url({withTimestamp:!0}));var g=(null==(s=t.exception)?void 0:s.values)||[],v=g.map(e=>i({},e,{stacktrace:e.stacktrace?i({},e.stacktrace,{type:"raw",frames:(e.stacktrace.frames||[]).map(e=>i({},e,{platform:"web:javascript"}))}):void 0})),f={$exception_message:(null==(a=g[0])?void 0:a.value)||t.message,$exception_type:null==(d=g[0])?void 0:d.type,$exception_level:t.level,$exception_list:v,$sentry_event_id:t.event_id,$sentry_exception:t.exception,$sentry_exception_message:(null==(_=g[0])?void 0:_.value)||t.message,$sentry_exception_type:null==(c=g[0])?void 0:c.type,$sentry_tags:t.tags};return r&&n&&(f.$sentry_url=(o||"https://sentry.io/organizations/")+r+"/issues/?project="+n+"&query="+t.event_id),u&&(null==(h=e.exceptions)||h.sendExceptionEvent(f)),t}}var Ws=class{constructor(e,t,i,s,r,n){this.name=Hs,this.setupOnce=function(o){o(Gs(e,{organization:t,projectId:i,prefix:s,severityAllowList:r,sendExceptionsToPostHog:null==n||n}))}}},Vs=class{constructor(e){this._onSessionIdChange=(e,t,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength||i.crossTabAdoption)&&(Yi.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:e,changeReason:i}),this._currentPageview=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this._setupSessionRotationHandler()}_setupSessionRotationHandler(){var e;this._unsubscribeSessionId=null==(e=this._instance.sessionManager)?void 0:e.onSessionId(this._onSessionIdChange)}destroy(){var e;null==(e=this._unsubscribeSessionId)||e.call(this),this._unsubscribeSessionId=void 0}doPageView(e,t){var i,s=this._previousPageViewProperties(e,t);return this._currentPageview={pathname:null!==(i=null==Ke?void 0:Ke.location.pathname)&&void 0!==i?i:"",pageViewId:t,timestamp:e},this._instance.scrollManager.resetContext(),s}doPageLeave(e){var t;return this._previousPageViewProperties(e,null==(t=this._currentPageview)?void 0:t.pageViewId)}doEvent(){var e;return{$pageview_id:null==(e=this._currentPageview)?void 0:e.pageViewId}}_previousPageViewProperties(e,t){var i=this._currentPageview;if(!i)return{$pageview_id:t};var s={$pageview_id:t,$prev_pageview_id:i.pageViewId},r=this._instance.scrollManager.getContext();if(r&&!this._instance.config.disable_scroll_properties){var n=r.maxScrollHeight,o=r.lastScrollY,a=r.maxScrollY,l=r.maxContentHeight,d=r.lastContentY,u=r.maxContentY;if(!(mt(n)||mt(o)||mt(a)||mt(l)||mt(d)||mt(u))){n=Math.ceil(n),o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),d=Math.ceil(d),u=Math.ceil(u);var _=n>1?At(o/n,0,1,Yi):1,c=n>1?At(a/n,0,1,Yi):1,h=l>1?At(d/l,0,1,Yi):1,p=l>1?At(u/l,0,1,Yi):1;s=es(s,{$prev_pageview_last_scroll:o,$prev_pageview_last_scroll_percentage:_,$prev_pageview_max_scroll:a,$prev_pageview_max_scroll_percentage:c,$prev_pageview_last_content:d,$prev_pageview_last_content_percentage:h,$prev_pageview_max_content:u,$prev_pageview_max_content_percentage:p})}}return i.pathname&&(s.$prev_pageview_pathname=i.pathname),i.timestamp&&(s.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),s}},js=["flags","surveys"],zs={[F]:{exposure:"hidden"},[A]:{exposure:"hidden"},[D]:{exposure:"hidden"},[q]:{exposure:"hidden"},[N]:{exposure:"hidden"},[U]:{exposure:"hidden"},[k]:{exposure:"event"},[H]:{exposure:"hidden"},[J]:{exposure:"hidden"},[G]:{exposure:"event"},[W]:{exposure:"hidden"},[V]:{exposure:"event"},[j]:{exposure:"event"},[z]:{exposure:"event"},[K]:{exposure:"hidden"},[Y]:{exposure:"event"},[Q]:{exposure:"hidden"},[X]:{exposure:"hidden"},[re]:{exposure:"hidden"},[ne]:{exposure:"event"},[Z]:{exposure:"event",shouldSkipFromEventProperties:e=>wt(e)},[oe]:{exposure:"event"},[ae]:{exposure:"event"},[le]:{exposure:"event"},[de]:{exposure:"event"},[ue]:{exposure:"hidden"},[g]:{exposure:"hidden",storageGroup:"flags"},[d]:{exposure:"hidden",storageGroup:"flags"},[l]:{exposure:"hidden"},[u]:{exposure:"hidden",storageGroup:"flags"},[b]:{exposure:"hidden",storageGroup:"flags"},[h]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[p]:{exposure:"hidden",storageGroup:"flags"},[w]:{exposure:"hidden"},[S]:{exposure:"hidden"},[f]:{exposure:"hidden"},[v]:{exposure:"hidden"},[C]:{exposure:"hidden",storageGroup:"surveys"},[I]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[E]:{exposure:"event"},[x]:{exposure:"hidden"},[T]:{exposure:"hidden"},[ce]:{exposure:"hidden"},[he]:{exposure:"hidden"},[pe]:{exposure:"hidden"},[ge]:{exposure:"event"},[ve]:{exposure:"event"},[fe]:{exposure:"event"},[me]:{exposure:"event"},[m]:{exposure:"hidden"},[y]:{exposure:"hidden"},[_e]:{exposure:"event"},[_]:{exposure:"hidden"},[c]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ye]:{exposure:"hidden"},[be]:{exposure:"hidden"},[we]:{exposure:"hidden"},[Se]:{exposure:"hidden"},[Pe]:{exposure:"hidden"},[ke]:{exposure:"hidden"},[Ce]:{exposure:"hidden"},[ee]:{exposure:"event"},[te]:{exposure:"event"},[ie]:{exposure:"event"},[se]:{exposure:"event"},[xe]:{exposure:"event"},[Te]:{exposure:"event"},[$e]:{exposure:"hidden"},[Fe]:{exposure:"hidden"},[Re]:{exposure:"hidden"},[Oe]:{exposure:"hidden"},[Me]:{exposure:"hidden"},[Ae]:{exposure:"hidden"},[De]:{exposure:"hidden"},[Le]:{exposure:"hidden"},[Ne]:{exposure:"hidden"},[Be]:{exposure:"event"}},Ks=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Js=e=>{var t=zs[e];if(t)return t;for(var i of Ks){var s=i[1];if(0===e.indexOf(i[0]))return s}};function Ys(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(e){return}}var Qs=e=>{var t,i=null==(t=typeof document>"u"?void 0:document)?void 0:t.createElement("a");return mt(i)?null:(i.href=e,i)},Xs=(e,t)=>{try{var i;return JSON.stringify(e,(e,t)=>xt(t)?(null!=i||(i=new WeakMap),i.has(t)||i.set(t,ss(t)),i.get(t)):"bigint"==typeof t?t.toString():t,t)}catch(t){return r=[],null!==(s=JSON.stringify(e,function(e,t){if("bigint"==typeof t)return t.toString();if("function"!=typeof t&&"symbol"!=typeof t){if(t instanceof Error)return{name:t.name,message:t.message,stack:t.stack};if(t&&"object"==typeof t){for(;r.length>0&&r[r.length-1]!==this;)r.pop();if(r.includes(t))return"[Circular]";r.push(t)}return t}}))&&void 0!==s?s:"null"}var s,r},Zs=function(e,t){for(var i,s=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;s.length>r;r++){var n=s[r].split(/=(.*)/);if(n[0]===t){i=n;break}}if(!pt(i)||2>i.length)return"";var o=i[1].replace(/\+/g," ");try{o=decodeURIComponent(o)}catch(e){Yi.error("Skipping decoding for malformed query param: "+o)}return o},er=function(e,t,i){if(!e||!t||!t.length)return e;for(var s=e.split(/#(.*)/),r=s[1],n=(s[0]||"").split(/\?(.*)/),o=n[1],a=n[0],l=(o||"").split("&"),d=[],u=0;l.length>u;u++){for(var _=l[u].split("?"),c=0;_.length>c&&!t.includes(_[c].split("=")[0]);)c++;d.push(_.length>c?_.slice(0,c).concat(_[c].split("=")[0]+"="+i).join("?"):l[u])}var h=a;return null!=o&&(h+="?"+d.join("&")),null!=r&&(h+="#"+r),h},tr=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","bfcid","irclid","_kx"],ir=(()=>["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...tr])(),sr="",rr=["li_fat_id"];function nr(e,t){var i=ir.concat(t||[]),s={};return Zi(i,function(t){var i=Zs(e,t);s[t]=i||null}),s}function or(e){var t=function(e){return e?0===e.search("https?://(.*)google.([^/?]*)")?"google":0===e.search("https?://(.*)bing.com")?"bing":0===e.search("https?://(.*)yahoo.com")?"yahoo":0===e.search("https?://(.*)duckduckgo.com")?"duckduckgo":null:null}(e),i="yahoo"!=t?"q":"p",s={};if(!wt(t)){s.$search_engine=t;var r=Qe?Zs(Qe.referrer,i):"";r.length&&(s.ph_keyword=r)}return s}function ar(){return navigator.language||navigator.userLanguage}var lr="$direct";function dr(){return(null==Qe?void 0:Qe.referrer)||lr}function ur(e,t,i){var s;void 0===i&&(i=!1);var r=e?[...tr,...t||[]]:[],n=null==(s=i?Bi(null==Xe?void 0:Xe.href):null==Xe?void 0:Xe.href)?void 0:s.substring(0,1e3);return{r:dr().substring(0,1e3),u:n?er(n,r,sr):void 0}}function _r(e,t){var i;void 0===t&&(t=!1);var s=e.r,r=e.u,n=t?Bi(r):r,o={$referrer:s,$referring_domain:null==s?void 0:s==lr?lr:null==(i=Qs(s))?void 0:i.host};if(n){o.$current_url=n;var a=Qs(n);o.$host=null==a?void 0:a.host,o.$pathname=null==a?void 0:a.pathname,es(o,nr(n))}return s&&es(o,or(s)),o}function cr(){try{return(new Date).getTimezoneOffset()}catch(e){return}}var hr={flags:c,surveys:I},pr=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],gr=e=>e+"_cookie_identity_change_pending",vr=e=>{var t="",i=0;for(var s of e){var r=encodeURIComponent(JSON.stringify(s).slice(1,-1)).length;if(i+r>1e3)break;t+=s,i+=r}return t},fr="main",mr=[g,d,u,b,h,c,p,f],yr=e=>-1!==mr.indexOf(e),br=[N,U],wr=e=>-1!==br.indexOf(e),Sr=(e,t)=>{try{return JSON.stringify(e)===JSON.stringify(t)}catch(i){return e===t}},Pr=e=>{if(!e)return{};var t=JSON.parse(e);return vt(t)?t:{}},kr=(e,t)=>{Zi(e,(i,s)=>{var r=Js(s);r&&"event"!==r.exposure||{}.hasOwnProperty.call(t,s)||delete e[s]})},Cr=class{constructor(e,t,s,r){if(void 0===s&&(s=!0),void 0===r&&(r=!e.cookieless_mode),this._slotState={},this._splitStorageEligible=!1,this._storesIdentityInCookie=!1,this._splitStorage=!1,this._cookieIdentityChangePending=!1,this._cookieSyncSuppressed=!1,this._pendingCrossTabFeatureFlagChanges=new Map,this._storageMigrationInProgress=!1,this._localIdentityChangePending=!1,this._crossTabFeatureFlagIdentityMismatch=!1,this._metaIdentifierChangePending=new Set,this._crossTabFeatureFlagHandlers=new Set,this._config=e,this._ownsSplitStorage=s,this.props={},this._campaign_params_url=void 0,this._name=(e=>{var t="";return e.token&&(t=e.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),e.persistence_name?"ph_"+e.persistence_name:"ph_"+t+"_posthog"})(e),this._disabled=e.disable_persistence||!!t,this._storage=this._buildStorage(e),this._splitStorage=this._resolveSplitStorage(e),this.load(r),this._markLoadedCrossTabFeatureFlagChangesPending(),e.debug&&Yi.info("Persistence loaded",e.persistence,i({},this.props)),this.update_config(e,e,t),this.save(),Ke){var n=()=>this.flush();os(Ke,"beforeunload",n,{capture:!1}),os(Ke,"pagehide",n,{capture:!1}),this._onStorage=e=>{if(this._splitStorageEligible&&(!e.storageArea||e.storageArea===(null==Ke?void 0:Ke.localStorage))&&e.key)if(e.key!==this._name){if(this._splitStorage){var t=js.find(t=>e.key===this._groupEntryName(t));t&&this._syncCrossTabFeatureFlagProperties(e.key,t)}}else this._syncCrossTabFeatureFlagProperties(e.key,fr)},os(Ke,"storage",this._onStorage)}}markCrossTabFeatureFlagChanges(e){Object.entries(e).forEach(e=>{var t=e[0],i=e[1],s=this._pendingCrossTabFeatureFlagChanges.get(t);if(yr(t)&&!0!==s)if(!0!==i){var r=new Set(s||[]);i.forEach(e=>r.add(e)),r.size&&this._setCrossTabFeatureFlagChangesPending(t,r)}else this._setCrossTabFeatureFlagChangesPending(t,!0)})}onCrossTabFeatureFlagChange(e){return this._crossTabFeatureFlagHandlers.add(e),()=>this._crossTabFeatureFlagHandlers.delete(e)}destroy(){this._onStorage&&Ke&&(Ke.removeEventListener("storage",this._onStorage),this._onStorage=void 0),this._crossTabFeatureFlagHandlers.clear()}_syncCrossTabFeatureFlagProperties(e,t,i){if(void 0===i&&(i=!0),this._disabled)return!1;var s,r;try{if(r=ws._get(e),wt(r)){var n=this._slotWriteState(t);return n.storageValue=null,t!==fr?n.persisted=!1:this._mergeMetaIdentifierProperties({}),!1}s=Pr(r)}catch(e){return!1}t===fr&&this._mergeMetaIdentifierProperties(s);var o=t===fr?s:ws._parse(this._name);if(o&&this._hasCrossTabFeatureFlagIdentityMismatch(o))return!1;var a=this._mergeCrossTabFeatureFlagProperties(s,t,i);return t===fr&&this._splitStorage&&!Sr(this._partitionProps().main,s)||this._rememberCrossTabStorageFingerprint(s,t,!0,r),a}_hasCrossTabFeatureFlagIdentityMismatch(e){var t=this.props[R],i=e[R];return!mt(t)&&!mt(i)&&t!==i}_rememberCrossTabStorageFingerprint(e,t,i,s){var r=this._slotWriteState(t);r.storageValue=s,t!==fr&&(r.persisted=i);try{r.fingerprint=this._entryFingerprint(e,t)}catch(e){r.fingerprint=void 0}}_mergeCrossTabFeatureFlagProperties(e,t,i){var s=!1;return mr.forEach(i=>{var r,n=null==(r=Js(i))?void 0:r.storageGroup;if(!(t===fr&&this._splitStorage&&n||t!==fr&&n!==t)){var o=i in e,a=this._mergePendingCrossTabFeatureFlagChanges(i,o?e[i]:void 0),l=this._pendingCrossTabFeatureFlagChanges.has(i)?i in this.props:o;l===i in this.props&&Sr(a,this.props[i])||(l?this._setProp(i,a,!1):this._deleteProp(i,!1),s=!0)}}),s&&i&&this._crossTabFeatureFlagHandlers.forEach(e=>e()),s}_mergeMetaIdentifierProperties(e){var t=this._storesIdentityInCookie&&this._config.cookieWinsOnConflict?[...Ps,...this._config.cookie_persisted_properties||[]]:[];br.forEach(i=>{this._metaIdentifierChangePending.has(i)||-1!==t.indexOf(i)||(i in e?Sr(e[i],this.props[i])||this._setProp(i,e[i],!1):i in this.props&&this._deleteProp(i,!1))})}_metaIdentifierCookieSyncEnabled(){return this._storesIdentityInCookie&&this._splitStorageEligible&&!this._config.cookieWinsOnConflict}_adoptMetaIdentifiersFromCookie(){if(this._metaIdentifierCookieSyncEnabled()){var e;try{e=ys._get(this._name)||void 0}catch(e){return}if(e&&e!==this._lastSeenMetaIdentifierCookieValue){var t;this._lastSeenMetaIdentifierCookieValue=e;try{t=Is(JSON.parse(e))}catch(e){return}br.forEach(e=>{!(e in t)||e in this.props||this._metaIdentifierChangePending.has(e)||this._setProp(e,t[e],!1)})}}}_rememberMetaIdentifierCookieValue(e){if(this._metaIdentifierCookieSyncEnabled())try{var t=JSON.stringify(Es(e,this._config.cookie_persisted_properties||[])),i=ys._get(this._name)||void 0;i===t&&(this._lastSeenMetaIdentifierCookieValue=i)}catch(e){}}_reconcileCrossTabFeatureFlagPropertiesBeforeWrite(){if(!this._splitStorageEligible)return!1;try{this._crossTabFeatureFlagIdentityMismatch=!1;var e,t=ws._get(this._name),i=this._slotWriteState(fr),s=!1,r=!1;if(t!==i.storageValue)if(wt(t))yt(i.storageValue)&&this._mergeMetaIdentifierProperties({}),i.storageValue=null;else{if(e=Pr(t),this._mergeMetaIdentifierProperties(e),this._crossTabFeatureFlagIdentityMismatch=!this._localIdentityChangePending&&this._hasCrossTabFeatureFlagIdentityMismatch(e),this._crossTabFeatureFlagIdentityMismatch)return!1;r=this._mergeCrossTabFeatureFlagProperties(e,fr,!1),!this._splitStorage||Sr(this._partitionProps().main,e)?this._rememberCrossTabStorageFingerprint(e,fr,!0,t):i.storageValue=t,s=!0}return this._splitStorage&&js.forEach(t=>{var i=ws._get(this._groupEntryName(t)),n=this._slotWriteState(t),o=e||{},a=s&&mr.some(e=>{var i;return(null==(i=Js(e))?void 0:i.storageGroup)===t&&e in o});if(i!==n.storageValue||a){if(wt(i))return n.storageValue=null,n.persisted=!1,void(a&&(r=this._mergeCrossTabFeatureFlagProperties(o,t,!1)||r));var l=Pr(i);r=this._mergeCrossTabFeatureFlagProperties(l,t,!1)||r,this._rememberCrossTabStorageFingerprint(l,t,!0,i)}}),r}catch(e){return!1}}_setCrossTabFeatureFlagChangesPending(e,t){this._pendingCrossTabFeatureFlagChanges.set(e,t);var i=Js(e);null!=i&&i.volatile||(this._slotWriteState((this._splitStorage?null==i?void 0:i.storageGroup:void 0)||fr).fingerprint=void 0,this._markGroupDirty(e))}_markAllCrossTabFeatureFlagChangesPending(){mr.forEach(e=>this._pendingCrossTabFeatureFlagChanges.set(e,!0))}_markLoadedCrossTabFeatureFlagChangesPending(){if(this._splitStorageEligible)try{var e=ws._get(this._name),t=Pr(e);this._slotWriteState(fr).storageValue=e,mr.forEach(e=>{var i,s=this._splitStorage?null==(i=Js(e))?void 0:i.storageGroup:void 0,r=s?ws._get(this._groupEntryName(s)):null;if(s){var n=this._slotWriteState(s);n.storageValue=r,n.persisted=!wt(r)}var o=s&&!wt(r)?Pr(r):t;e in this.props?this._markPendingCrossTabFeatureFlagChanges(e,o[e],this.props[e]):e in o&&this._setCrossTabFeatureFlagChangesPending(e,!0)})}catch(e){}}_mergePendingCrossTabFeatureFlagChanges(e,t){var s=this._pendingCrossTabFeatureFlagChanges.get(e);if(!s)return t;if(!0===s)return this.props[e];if("$active_feature_flags"===e){var r=new Set(pt(t)?t:[]),n=new Set(pt(this.props[e])?this.props[e]:[]);return s.forEach(e=>n.has(e)?r.add(e):r.delete(e)),Array.from(r)}var o=vt(t)?i({},t):{},a=vt(this.props[e])?this.props[e]:{};return s.forEach(e=>{e in a?o[e]=a[e]:delete o[e]}),o}_markPendingCrossTabFeatureFlagChanges(e,t,i){if(yr(e)){var s=this._pendingCrossTabFeatureFlagChanges.get(e);if(!0!==s){var r=t;if(this._splitStorageEligible)try{var n,o=this._splitStorage?null==(n=Js(e))?void 0:n.storageGroup:void 0,a=o?this._groupEntryName(o):this._name;r=Pr(ws._get(a))[e]}catch(e){}var l=new Set(s||[]);if("$active_feature_flags"===e){if(!mt(t)&&!pt(t)||!mt(r)&&!pt(r)||!pt(i))return void this._setCrossTabFeatureFlagChangesPending(e,!0);var d=new Set(t||[]),u=new Set(r||[]),_=new Set(i);new Set([...d,..._]).forEach(e=>{d.has(e)!==_.has(e)&&l.add(e)}),l.forEach(e=>{u.has(e)===_.has(e)&&l.delete(e)})}else{if(!vt(i))return void(Sr(r,i)?this._pendingCrossTabFeatureFlagChanges.delete(e):this._setCrossTabFeatureFlagChangesPending(e,!0));if(!mt(t)&&!vt(t)||mt(t)&&ft(i)&&mt(r))return void this._setCrossTabFeatureFlagChangesPending(e,!0);var c=vt(t)?t:{},h=vt(r)?r:{};new Set([...Object.keys(c),...Object.keys(i)]).forEach(e=>{e in c==e in i&&Sr(c[e],i[e])||l.add(e)}),l.forEach(e=>{e in h==e in i&&Sr(h[e],i[e])&&l.delete(e)})}l.size?this._setCrossTabFeatureFlagChangesPending(e,l):this._pendingCrossTabFeatureFlagChanges.delete(e)}}}_saveDebounceMs(){var e,t=null==(e=this._config)?void 0:e.persistence_save_debounce_ms;return Pt(t)&&t>0?t:0}_rememberCurrentCookieProperties(e){if(this._config.cookieWinsOnConflict&&"localstorage+cookie"===this._config.persistence.toLowerCase())if(e)try{var t=Es(e,this._config.cookie_persisted_properties||[]),i=Ts(t,this._config.cookie_persisted_properties||[]),s=JSON.stringify(t)+"|"+JSON.stringify(i),r=ys._get(this._name)||void 0;r&&Fs(this._name,r)===s&&(this._lastSeenCookiePropertiesFingerprint=s,this._lastSeenMainCookieValue=r)}catch(e){}else try{var n=ys._get(this._name)||void 0;this._lastSeenCookiePropertiesFingerprint=n?Fs(this._name,n):void 0,this._lastSeenMainCookieValue=n}catch(e){}}syncCookieProperties(){return this._syncCookieProperties(this._config)}_syncCookieProperties(e,t){if(void 0===t&&(t=!1),this._disabled&&!t||this._cookieSyncSuppressed||!e.cookieWinsOnConflict||"localstorage+cookie"!==e.persistence.toLowerCase())return!1;var i;try{i=ys._get(this._name)||void 0}catch(e){}if(!i||i===this._lastSeenMainCookieValue)return!1;var s,r=Fs(this._name,i);try{s=Is(JSON.parse(i))}catch(e){return!1}if((ys._get(this._name)||void 0)!==i)return!1;this._lastSeenCookiePropertiesFingerprint=r,this._lastSeenMainCookieValue=i;var n=$s(this._name,i),o=[...Ps,...n.properties],a={};if(Object.keys(s).forEach(e=>{var t=s[e];(mt(t)||wt(t)||""===t||"$user_state"===e&&"anonymous"!==t&&"identified"!==t)&&(a[e]=!0,delete s[e])}),ft(s))return!1;var l="distinct_id"in s||"anonymous"===s.$user_state||"identified"===s.$user_state,p=this.props,y=p[R],w=p[ye],S=es({},p);[...Ps,...e.cookie_persisted_properties||[]].forEach(e=>{if(-1!==o.indexOf(e)&&!(e in s)&&!a[e]&&(l||"distinct_id"!==e&&"$user_state"!==e)){var t=S[e];(n.isValid||-1===Ps.indexOf(e)||!1!==t&&0!==t)&&delete S[e]}}),this.props=es(S,s),mr.forEach(e=>{var t=e in this.props;e in p===t&&Sr(p[e],this.props[e])||(t?this._markPendingCrossTabFeatureFlagChanges(e,p[e],this.props[e]):this._setCrossTabFeatureFlagChangesPending(e,!0))}),!l||"$user_state"in s||"$user_state"in this.props||this._setProp(ye,Ue);var P=this.props[R],k=this.props[ye];return!l||P===y&&k===w||(this._localIdentityChangePending=!0,this._cookieIdentityChangePending=!0,As._set(gr(this._name),!0),this._deleteProp(f),this._deleteProp(d),this._deleteProp(g),this._deleteProp(u),this._deleteProp(b),this._deleteProp(h),this._deleteProp(c),this._deleteProp(_),this._deleteProp(m),"anonymous"!==k||"identified"!==w&&"anonymous"!==s.$user_state&&(mt(y)||P===y)||(kr(this.props,s),this._deleteProp(v)),"identified"===k?this.props.$user_id=P:delete this.props.$user_id,this._deleteProp(A)),!0}consumeCookieIdentityChange(){var e=gr(this._name),t=this._cookieIdentityChangePending||!!As._get(e);return this._cookieIdentityChangePending=!1,t&&As._remove(e),t}_beginCookieSyncSuppression(e){return void 0===e&&(e=!1),!(this._cookieSyncSuppressed||this._disabled&&!e||!this._config.cookieWinsOnConflict||"localstorage+cookie"!==this._config.persistence.toLowerCase()||(this._cookieSyncSuppressed=!0,0))}_publishSuppressedCookieSnapshot(){this._cookieSyncSuppressed&&(mt(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0),delete this._slotState[fr],this._writeNow(!0))}_endCookieSyncSuppression(e){if(void 0===e&&(e=!0),this._cookieSyncSuppressed)try{e?this._publishSuppressedCookieSnapshot():mt(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0)}finally{this._cookieSyncSuppressed=!1}}isDisabled(){return!!this._disabled}_buildStorage(e){-1===pr.indexOf(e.persistence.toLowerCase())&&(Yi.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var t,s=function(e,t,s){void 0===e&&(e=[]),void 0===t&&(t=!1),void 0===s&&(s=()=>!1);var r=[...Ps,...e];return i({},ws,{_parse(e){try{var i,n={};try{i=ys._get(e)||void 0,n=i?Is(JSON.parse(i)):{}}catch(e){}var o,a=JSON.parse(ws._get(e)||"{}");if(t){var l=$s(e,i),d=[...Ps,...l.properties],u={};Object.keys(n).forEach(e=>{var t=n[e];wt(t)||""===t||"$user_state"===e&&"anonymous"!==t&&"identified"!==t||(u[e]=t)});var _="distinct_id"in u||"anonymous"===u.$user_state||"identified"===u.$user_state;if(Object.keys(u).length>0){var c,h=a[R],p=null!==(c=a.$user_state)&&void 0!==c?c:"anonymous";r.forEach(e=>{if(-1!==d.indexOf(e)&&!(e in n)&&(_||"distinct_id"!==e&&"$user_state"!==e)){var t=a[e];(l.isValid||-1===Ps.indexOf(e)||!1!==t&&0!==t)&&delete a[e]}}),!_||"$user_state"in n||"$user_state"in a||(a[ye]=Ue),!_||("distinct_id"in u?u[R]:a[R])===h&&("$user_state"in u?u[ye]:a[ye])===p||(Ss.forEach(e=>delete a[e]),"identified"===u.$user_state&&"distinct_id"in u?a.$user_id=u[R]:delete a.$user_id,"identified"!==u.$user_state&&(delete a[_e],delete a[v]),delete a.__alias)}o=es(a,u)}else o=es(n,a);return s()||ws._set(e,o),o}catch(e){}return null},_set(i,s,r,n,o,a){var l=ws._set(i,s,void 0,void 0,a);try{var d=Es(s,e);if(Object.keys(d).length){if(t){var u=ks(i),_=Ts(d,e);if(ys._set(u,_,r,n,o,a),ys._get(u)!==JSON.stringify(_)){ys._remove(u,n);var c=Es(s);return ys._set(i,c,r,n,o,a),l}}ys._set(i,d,r,n,o,a)}}catch(e){ws._error(e)}return l},_remove(e,t){try{null==Ke||Ke.localStorage.removeItem(e),ys._remove(e,t),ys._remove(ks(e),t)}catch(e){ws._error(e)}}})}(e.cookie_persisted_properties||[],e.cookieWinsOnConflict,()=>!!this._disabled),r=!1,n=!1,o=e.persistence.toLowerCase();return"localstorage"===o&&ws._is_supported()?(t=ws,n=!0):"localstorage+cookie"===o&&s._is_supported()?(t=s,n=!0,r=!0):"sessionstorage"===o&&As._is_supported()?t=As:"memory"===o?t=Os:"cookie"===o&&ys._is_supported()?(t=ys,r=!0):s._is_supported()?(t=s,n=!0,r=!0):ys._is_supported()?(t=ys,r=!0):t=Os,this._splitStorageEligible=n,this._storesIdentityInCookie=r,t}_groupEntryName(e){return this._name+"__"+e}_resolveSplitStorage(e){return this._splitStorageEligible&&!!e.split_storage}properties(){var e={};return Zi(this.props,(t,i)=>{var s=Js(i);if(!s||"event"===s.exposure){if(null!=s&&null!=s.shouldSkipFromEventProperties&&s.shouldSkipFromEventProperties(t))return;e[i]=t}}),e}load(e){if(void 0===e&&(e=!1),!this._disabled||e){var t=this._config.cookieWinsOnConflict&&"localstorage+cookie"===this._config.persistence.toLowerCase(),i=t?ws._parse(this._name):null,s={};if(t)try{Zi(s=Is(ys._parse(this._name)),(e,t)=>{(mt(e)||wt(e)||""===e)&&delete s[t]})}catch(e){}var r=this._storage._parse(this._name);if(r&&(this.props=es({},r)),this._splitStorage&&this._loadGroupEntries(),t&&r){var n,o,a=null==i?void 0:i[R],l=null!==(n=null==i?void 0:i.$user_state)&&void 0!==n?n:"anonymous",d=r[R],u=null!==(o=r.$user_state)&&void 0!==o?o:"anonymous";if(d!==a||u!==l){this._cookieIdentityChangePending=!0,this._disabled||As._set(gr(this._name),!0);var _=es({},this.props);Ss.forEach(e=>delete _[e]),"anonymous"!==u||"identified"!==l&&"anonymous"!==s.$user_state&&(mt(a)||d===a)||(kr(_,s),delete _[v]),this.props=_;var c=new Set;Ss.forEach(e=>{var t,i=null==(t=Js(e))?void 0:t.storageGroup;i&&c.add(i)}),c.forEach(e=>{if(!this._disabled){var t={};Zi(this.props,(i,s)=>{var r;(null==(r=Js(s))?void 0:r.storageGroup)===e&&(t[s]=i)}),ft(t)?(ws._remove(this._groupEntryName(e)),this._slotState[e]={}):ws._set(this._groupEntryName(e),t)&&(this._slotState[e]={persisted:!0,fingerprint:this._entryFingerprint(t,e)})}})}}As._get(gr(this._name))&&(this._cookieIdentityChangePending=!0)}}_loadGroupEntries(){for(var e of js){var t=ws._parse(this._groupEntryName(e));if(t&&!ft(t)){var i=this._slotWriteState(e);i.persisted=!0,this._mainCarriesGroupKey(e)||(i.fingerprint=this._entryFingerprint(t,e)),this._groupEntryIsStale(e,t)||es(this.props,t)}}}_mainCarriesGroupKey(e){return Object.keys(this.props).some(t=>{var i;return(null==(i=Js(t))?void 0:i.storageGroup)===e})}_groupEntryIsStale(e,t){var i=hr[e];if(!i)return!1;var s=t[i],r=this.props[i];return Pt(s)&&Pt(r)&&r>s}refreshKey(e){this._refreshKeys([e])}_refreshKeys(e){if(!this._disabled){var t,i=!1,s=()=>(i||(t=this._storage._parse(this._name),i=!0),t);e.forEach(e=>{var t;if(!this._metaIdentifierChangePending.has(e)){var i=this._splitStorage?null==(t=Js(e))?void 0:t.storageGroup:void 0,r=i?ws._parse(this._groupEntryName(i)):s();if(r&&e in r)this._setProp(e,r[e],!1);else{if(i){var n=s();if(n&&e in n)return void this._setProp(e,n[e],!1)}this._deleteProp(e,!1)}}})}}refreshMetaIdentifiers(){this._disabled||(this._usesMetaIdentifierSnapshotRefresh()?this._refreshMetaIdentifiersIfStorageChanged():this._refreshKeys(br))}_refreshMetaIdentifiersIfStorageChanged(){var e=this._storageSnapshot();(mt(e)||e!==this._metaIdentifierStorageSnapshot)&&(this._refreshKeys(br),this._rememberMetaIdentifierStorageSnapshot(e))}_rememberMetaIdentifierStorageSnapshot(e){void 0===e&&(e=this._storageSnapshot()),this._metaIdentifierStorageSnapshot=0===this._metaIdentifierChangePending.size?e:void 0}refreshMetaIdentifiersBeforeCapture(){this._disabled||this._cookieSyncSuppressed||(this._usesMetaIdentifierSnapshotRefresh()||this._adoptMetaIdentifiersFromCookie(),this._refreshMetaIdentifiersIfStorageChanged())}_usesMetaIdentifierSnapshotRefresh(){return this._storage===ys||this._storage===As||this._storage===Os}_storageSnapshot(){var e=this._storage._get(this._name);return yt(e)?e:void 0}save(){if(!this._disabled){var e=this._saveDebounceMs();e>0?mt(this._pendingSaveTimer)&&(this._pendingSaveTimer=setTimeout(()=>{this._pendingSaveTimer=void 0,this._writeNow()},e)):this._writeNow()}}flush(){mt(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0,this._writeNow())}_writeNow(e){if(void 0===e&&(e=!1),!(this._disabled||this._cookieSyncSuppressed&&!e)){e||(this.syncCookieProperties(),this._usesMetaIdentifierSnapshotRefresh()&&this.refreshMetaIdentifiers());var t=!e&&!this._storageMigrationInProgress;t||(this._crossTabFeatureFlagIdentityMismatch=!1);var i=!!t&&this._reconcileCrossTabFeatureFlagPropertiesBeforeWrite();if(this._crossTabFeatureFlagIdentityMismatch)this._config.debug&&Yi.warn("skipping persistence write because storage belongs to a different distinct ID");else{if(e||this._adoptMetaIdentifiersFromCookie(),this._splitStorage)return this._writeNowSplit(),void(i&&this._crossTabFeatureFlagHandlers.forEach(e=>e()));var s=this._writeEntry(this._storage,this._name,this.props,fr);"written"===s&&(this._rememberCurrentCookieProperties(this.props),this._rememberMetaIdentifierCookieValue(this.props)),"failed"!==s&&(this._pendingCrossTabFeatureFlagChanges.clear(),this._localIdentityChangePending=!1,this._metaIdentifierChangePending.clear()),"written"===s&&this._rememberMetaIdentifierStorageSnapshot(),i&&this._crossTabFeatureFlagHandlers.forEach(e=>e())}}}_writeNowSplit(){var e=this,t=this._partitionProps(),i=t.main,s=t.groups,r=this._writeEntry(this._storage,this._name,i,fr);"written"===r&&(this._rememberCurrentCookieProperties(i),this._rememberMetaIdentifierCookieValue(i)),"failed"!==r&&(this._localIdentityChangePending=!1,this._metaIdentifierChangePending.clear(),mr.forEach(e=>{var t;null!=(t=Js(e))&&t.storageGroup||this._pendingCrossTabFeatureFlagChanges.delete(e)})),"written"===r&&this._rememberMetaIdentifierStorageSnapshot();var n=function(t){var i,r=s[t];if(ft(r)&&(null==(i=e._slotState[t])||!i.persisted))return mr.forEach(i=>{var s;(null==(s=Js(i))?void 0:s.storageGroup)===t&&e._pendingCrossTabFeatureFlagChanges.delete(i)}),1;var n=e._writeEntry(ws,e._groupEntryName(t),r,t);"failed"!==n&&mr.forEach(i=>{var s=Js(i);(null==s?void 0:s.storageGroup)!==t||"written"!==n&&s.volatile||e._pendingCrossTabFeatureFlagChanges.delete(i)})};for(var o of js)if(n(o))continue}_partitionProps(){var e={},t={flags:{},surveys:{}};return Zi(this.props,(i,s)=>{var r,n=null==(r=Js(s))?void 0:r.storageGroup;n?t[n][s]=i:e[s]=i}),{main:e,groups:t}}_entryFingerprint(e,t){if(t===fr)return JSON.stringify(e)+"|"+this._expire_days+"|"+this._cross_subdomain+"|"+this._secure;var i={};return Zi(e,(e,t)=>{var s;i[t]=null!=(s=Js(t))&&s.volatile?"__volatile__":e}),JSON.stringify(i)}_writeEntry(e,t,i,s){var r,n=this._slotWriteState(s);if(s!==fr&&!n.dirty&&!mt(n.fingerprint))return"skipped";try{if((r=this._entryFingerprint(i,s))===n.fingerprint)return n.dirty=!1,"skipped"}catch(e){r=void 0}return e._set(t,i,this._expire_days,this._cross_subdomain,this._secure,this._config.debug)?(n.dirty=!1,s!==fr&&(n.persisted=!0),mt(r)||(n.fingerprint=r),this._splitStorageEligible&&(n.storageValue=ws._get(t)),"written"):(this._config.debug&&Yi.warn('failed to persist storage entry "'+t+'"; will retry on next save'),"failed")}remove(e){var t=(void 0===e?{}:e).keepGroupEntries,i=void 0!==t&&t;if(this._markAllCrossTabFeatureFlagChangesPending(),mt(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0),this._storage._remove(this._name,!1),this._storage._remove(this._name,!0),!i&&this._ownsSplitStorage)for(var s of js)ws._remove(this._groupEntryName(s));i?delete this._slotState[fr]:this._slotState={},this._lastSeenCookiePropertiesFingerprint=void 0,this._lastSeenMainCookieValue=void 0,this._lastSeenMetaIdentifierCookieValue=void 0}clear(){this.remove(),this.props={}}register_once(e,t,i){if(vt(e)){this.syncCookieProperties(),mt(t)&&(t="None"),this._expire_days=mt(i)?this._default_expiry:i;var s=!1;if(Zi(e,(e,i)=>{this.props.hasOwnProperty(i)&&this.props[i]!==t||(this._setProp(i,e),s=!0)}),s)return this.save(),!0}return!1}register(e,t){if(vt(e)){this.syncCookieProperties(),this._expire_days=mt(t)?this._default_expiry:t;var i=!1;if(Zi(e,(t,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==t||vt(t)||pt(t))&&(this._setProp(s,t),i=!0)}),i)return this.save(),!0}return!1}unregister(e){this.syncCookieProperties();var t="string"==typeof e?[e]:e,i=!1;for(var s of t)s in this.props&&(this._deleteProp(s),i=!0);i&&this.save()}update_campaign_params(){var e=null==Qe?void 0:Qe.URL;if(e!==this._campaign_params_url){var t=function(e,t,i){if(!Qe)return{};var s,r=t?[...tr,...i||[]]:[],n=nr(er(Qe.URL,r,sr),e);return es((s={},Zi(rr,function(e){var t=ds(e);s[e]=t||null}),s),n)}(this._config.custom_campaign_params,this._config.mask_personal_data_properties,this._config.custom_personal_data_properties),i=!ft(is(t));return i&&this.register(t),this._campaign_params_url=e,i?t:void 0}}update_search_keyword(){var e;this.register((e=null==Qe?void 0:Qe.referrer)?or(e):{})}update_referrer_info(){var e;this.register_once({$referrer:dr(),$referring_domain:null!=Qe&&Qe.referrer&&(null==(e=Qs(Qe.referrer))?void 0:e.host)||lr},void 0)}set_initial_person_info(){if(!this.props.$initial_campaign_params&&!this.props.$initial_referrer_info){var e=ur(this._config.mask_personal_data_properties,this._config.custom_personal_data_properties,this._config.disable_capture_url_hashes);this.register_once({[ke]:this._storesIdentityInCookie?{r:vr(e.r),u:e.u?vr(e.u):void 0}:e},void 0)}}get_initial_props(){var e={};Zi([Pe,Se],t=>{var i=this.props[t];i&&Zi(i,function(t,i){e["$initial_"+ut(i)]=t})});var t=this.props[ke];return t&&es(e,function(e,t){void 0===t&&(t=!1);var i=_r(e,t),s={};return Zi(i,function(e,t){s["$initial_"+ut(t)]=e}),s}(t,this._config.disable_capture_url_hashes)),e}safe_merge(e){return Zi(this.props,function(t,i){i in e||(e[i]=t)}),e}update_config(e,t,s){var r=e.persistence!==t.persistence,n=!((e,t)=>{if(e.length!==t.length)return!1;var i=[...e].sort(),s=[...t].sort();return i.every((e,t)=>e===s[t])})(e.cookie_persisted_properties||[],t.cookie_persisted_properties||[]),o=r||n,a=e.cookieWinsOnConflict!==t.cookieWinsOnConflict,l=e.disable_persistence||!!s,d=!!this._disabled&&!l;l||this._syncCookieProperties(t,d),this._config=e,!l&&(r||n||a)&&(this._lastSeenCookiePropertiesFingerprint=void 0,this._lastSeenMainCookieValue=void 0,this._lastSeenMetaIdentifierCookieValue=void 0,this._syncCookieProperties(i({},e,{cookie_persisted_properties:t.cookie_persisted_properties}),d));var u=o||a?this._buildStorage(e):this._storage;this._truncateExistingPersonInfoForCookie();var _=this._resolveSplitStorage(e),c=o||_!==this._splitStorage,h=!l&&(c||e.cross_subdomain_cookie!==this._cross_subdomain||e.secure_cookie!==this._secure)&&this._beginCookieSyncSuppression(d);this._storageMigrationInProgress=c;try{if(this._default_expiry=this._expire_days=e.cookie_expiration,this.set_disabled(l),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),c){var p=this.props;this.clear(),this._storage=u,this._splitStorage=_,this.props=p,this.save()}else a&&(this._storage=u,l||(delete this._slotState[fr],this._writeNow()))}finally{this._storageMigrationInProgress=!1,h&&this._endCookieSyncSuppression()}}_truncateExistingPersonInfoForCookie(){var e=this.props[ke];if(this._storesIdentityInCookie&&vt(e)&&"string"==typeof e.r){var t=vr(e.r),s="string"==typeof e.u?vr(e.u):e.u;t===e.r&&s===e.u||this._setProp(ke,i({},e,{r:t,u:s}))}}set_disabled(e){this._disabled=e,this._disabled?this.remove():this.save()}set_cross_subdomain(e){e!==this._cross_subdomain&&(this._cross_subdomain=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this._secure&&(this._secure=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,t){var i=this.props.__timers||{};i[e]=t,this._setProp(q,i),this.save()}remove_event_timer(e){var t=this.props.__timers||{},i=t[e];return mt(i)||(delete t[e],this._setProp(q,t),this.save()),i}get_property(e){return this.props[e]}set_property(e,t){this._setProp(e,t),this.save()}_setProp(e,t,i){var s;void 0===i&&(i=!0);var r=this.props[e];this.props[e]=t,i&&("distinct_id"!==e&&"$user_state"!==e||r===t||(this._localIdentityChangePending=!0),wr(e)&&!Sr(r,t)&&this._metaIdentifierChangePending.add(e),this._markPendingCrossTabFeatureFlagChanges(e,r,t),null!=(s=Js(e))&&s.volatile||this._markGroupDirty(e))}_deleteProp(e,t){void 0===t&&(t=!0),delete this.props[e],t&&(yr(e)&&this._setCrossTabFeatureFlagChangesPending(e,!0),wr(e)&&this._metaIdentifierChangePending.add(e),this._markGroupDirty(e))}_markGroupDirty(e){var t,i=null==(t=Js(e))?void 0:t.storageGroup;i&&(this._slotWriteState(i).dirty=!0)}_slotWriteState(e){return this._slotState[e]||(this._slotState[e]={})}},Ir={GZipJS:"gzip-js",Base64:"base64"},Er={Activation:"events",Cancellation:"cancelEvents"},xr={Button:"button",Tab:"tab",Selector:"selector"},Tr={TopLeft:"top_left",TopRight:"top_right",TopCenter:"top_center",MiddleLeft:"middle_left",MiddleRight:"middle_right",MiddleCenter:"middle_center",Left:"left",Center:"center",Right:"right",NextToTrigger:"next_to_trigger"},$r={Top:"top",Left:"left",Right:"right",Bottom:"bottom"},Fr={Popover:"popover",API:"api",Widget:"widget",ExternalSurvey:"external_survey"},Rr={Open:"open",MultipleChoice:"multiple_choice",SingleChoice:"single_choice",Rating:"rating",Link:"link"},Or={NextQuestion:"next_question",End:"end",ResponseBased:"response_based",SpecificQuestion:"specific_question"},Mr={Once:"once",Recurring:"recurring",Always:"always"},Ar={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent",ABANDONED:"survey abandoned"},Dr={SURVEY_ID:"$survey_id",SURVEY_NAME:"$survey_name",SURVEY_RESPONSE:"$survey_response",SURVEY_ITERATION:"$survey_iteration",SURVEY_ITERATION_START_DATE:"$survey_iteration_start_date",SURVEY_PARTIALLY_COMPLETED:"$survey_partially_completed",SURVEY_SUBMISSION_ID:"$survey_submission_id",SURVEY_QUESTIONS:"$survey_questions",SURVEY_COMPLETED:"$survey_completed",PRODUCT_TOUR_ID:"$product_tour_id",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date",SURVEY_LANGUAGE:"$survey_language"},Lr={Popover:"popover",Inline:"inline"};function Nr(e){var t=!0;return{dispose(){if(t){t=!1;var i=e();i&>(i.then)&&i.then(void 0,()=>{})}}}}var Br={backgroundColor:"#ffffff",textColor:"#1d1f27",buttonColor:"#1d1f27",borderRadius:8,buttonBorderRadius:6,borderColor:"#e5e7eb",fontFamily:"system-ui",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",showOverlay:!0,whiteLabel:!1,dismissOnClickOutside:!0,zIndex:2147483646},Ur={SHOWN:"product tour shown",DISMISSED:"product tour dismissed",COMPLETED:"product tour completed",STEP_SHOWN:"product tour step shown",STEP_COMPLETED:"product tour step completed",BUTTON_CLICKED:"product tour button clicked",STEP_SELECTOR_FAILED:"product tour step selector failed",BANNER_CONTAINER_SELECTOR_FAILED:"product tour banner container selector failed",BANNER_ACTION_CLICKED:"product tour banner action clicked"},qr={TOUR_ID:"$product_tour_id",TOUR_NAME:"$product_tour_name",TOUR_ITERATION:"$product_tour_iteration",TOUR_RENDER_REASON:"$product_tour_render_reason",TOUR_STEP_ID:"$product_tour_step_id",TOUR_STEP_ORDER:"$product_tour_step_order",TOUR_STEP_TYPE:"$product_tour_step_type",TOUR_DISMISS_REASON:"$product_tour_dismiss_reason",TOUR_BUTTON_TEXT:"$product_tour_button_text",TOUR_BUTTON_ACTION:"$product_tour_button_action",TOUR_BUTTON_LINK:"$product_tour_button_link",TOUR_BUTTON_TOUR_ID:"$product_tour_button_tour_id",TOUR_STEPS_COUNT:"$product_tour_steps_count",TOUR_STEP_SELECTOR:"$product_tour_step_selector",TOUR_STEP_SELECTOR_FOUND:"$product_tour_step_selector_found",TOUR_STEP_ELEMENT_TAG:"$product_tour_step_element_tag",TOUR_STEP_ELEMENT_ID:"$product_tour_step_element_id",TOUR_STEP_ELEMENT_CLASSES:"$product_tour_step_element_classes",TOUR_STEP_ELEMENT_TEXT:"$product_tour_step_element_text",TOUR_ERROR:"$product_tour_error",TOUR_MATCHES_COUNT:"$product_tour_matches_count",TOUR_FAILURE_PHASE:"$product_tour_failure_phase",TOUR_WAITED_FOR_ELEMENT:"$product_tour_waited_for_element",TOUR_WAIT_DURATION_MS:"$product_tour_wait_duration_ms",TOUR_BANNER_SELECTOR:"$product_tour_banner_selector",TOUR_LINKED_SURVEY_ID:"$product_tour_linked_survey_id",USE_MANUAL_SELECTOR:"$use_manual_selector",INFERENCE_DATA_PRESENT:"$inference_data_present",TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Hr=Qi("[RateLimiter]"),Gr=class{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=e=>{var t=e.text;if(t&&t.length)try{(JSON.parse(t).quota_limited||[]).forEach(e=>{Hr.info((e||"events")+" is quota limited."),this.serverLimits[e]=(new Date).getTime()+6e4})}catch(e){return void Hr.warn('could not rate limit - continuing. Error: "'+(null==e?void 0:e.message)+'"',{text:t})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return(null==(e=this.instance.config.rate_limiting)?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max((null==(e=this.instance.config.rate_limiting)?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}get isClientRateLimited(){return 1>this._refilledBucket().tokens}clientRateLimitContext(e){var t;void 0===e&&(e=!1);var i=this._refilledBucket(),s=1>i.tokens;if(s||e||(i.tokens=Math.max(0,i.tokens-1)),s&&!e){var r=(Pt(i.dropped)?i.dropped:0)+1;i.dropped=r,!this.lastEventRateLimited&&this._captureWarning(r)&&(i.dropped=0)}return this.lastEventRateLimited=s,null==(t=this.instance.persistence)||t.set_property(we,i),{isRateLimited:s,remainingTokens:i.tokens}}_refilledBucket(){var e,t=this.captureEventsBurstLimit,s=this.captureEventsPerSecond,r=(new Date).getTime(),n=null==(e=this.instance.persistence)?void 0:e.get_property(we),o=n?i({},n):{tokens:t,last:r};return o.tokens+=Math.max(0,r-o.last)/1e3*s,o.last=Math.max(o.last,r),o.tokens>t&&(o.tokens=t),o}_isPropertyAllowed(e){var t=this.instance.config.property_denylist;return!pt(t)||!t.includes(e)}_triggeringPage(){var e;if(this._isPropertyAllowed("$current_url")&&this._isPropertyAllowed("$pathname")&&null!=Xe&&Xe.pathname)return""+(null!==(e=Xe.origin)&&void 0!==e?e:"")+Xe.pathname}_captureWarning(e){var t,i,s=this.captureEventsBurstLimit,r=this.captureEventsPerSecond,n=this._triggeringPage(),o=this._isPropertyAllowed("$session_id")?null==(t=(i=this.instance).get_session_id)?void 0:t.call(i):void 0,a=[e+" event(s) dropped since the last warning",n?"triggered on "+n:void 0,o?"session "+o:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+a+". Config is set to "+r+" events per second and "+s+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var t=this.serverLimits[e||"events"]||!1;return!1!==t&&(new Date).getTime()e(this.remoteConfig)):e()}_loadRemoteConfigJSON(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return Wr.info("Using preloaded remote config",this.remoteConfig),void this._onRemoteConfig(this.remoteConfig);if(this._instance._shouldDisableFlags())return void Wr.warn("Remote config is disabled. Falling back to local config.");this._loadRemoteConfigJs(e=>{if(!e)return Wr.info("No config found after loading remote JS config. Falling back to JSON."),void this._loadRemoteConfigJSON(e=>{this._onRemoteConfig(e.json,e)});this._onRemoteConfig(e)})}catch(e){Wr.error("Error loading remote config",e),this._onRemoteConfig()}}_onRemoteConfig(e,t){!e&&t&&(0===t.statusCode?t.error||Wr.warn("Failed to fetch remote config from PostHog."):Wr.error("Failed to fetch remote config from PostHog."));try{this._instance._onRemoteConfig(e?{ok:!0,config:e}:{ok:!1})}catch(e){Wr.error("Error applying remote config",e)}if(!1!==(null==e?void 0:e.hasFeatureFlags)&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;null==(i=this._instance.featureFlags)||i.ensureFlagsLoaded()}catch(e){Wr.error("Error loading feature flags",e)}}},jr=["fatal","error","warning","log","info","debug"],zr=Uint8Array,Kr=Uint16Array,Jr=Uint32Array,Yr=new zr([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Qr=new zr([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Xr=new zr([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Zr=function(e,t){for(var i=new Kr(31),s=0;31>s;++s)i[s]=t+=1<s;++s)for(var n=i[s];i[s+1]>n;++n)r[n]=n-i[s]<<5|s;return[i,r]},en=Zr(Yr,2),tn=en[1];en[0][28]=258,tn[258]=28;for(var sn=Zr(Qr,0)[1],rn=new Kr(32768),nn=0;32768>nn;++nn){var on=(43690&nn)>>>1|(21845&nn)<<1;rn[nn]=((65280&(on=(61680&(on=(52428&on)>>>2|(13107&on)<<2))>>>4|(3855&on)<<4))>>>8|(255&on)<<8)>>>1}var an=function(e,t,i){for(var s=e.length,r=0,n=new Kr(t);s>r;++r)++n[e[r]-1];var o,a=new Kr(t);for(r=0;t>r;++r)a[r]=a[r-1]+n[r-1]<<1;if(i){o=new Kr(1<r;++r)if(e[r])for(var d=r<<4|e[r],u=t-e[r],_=a[e[r]-1]++<=_;++_)o[rn[_]>>>l]=d}else for(o=new Kr(s),r=0;s>r;++r)o[r]=rn[a[e[r]-1]++]>>>15-e[r];return o},ln=new zr(288);for(nn=0;144>nn;++nn)ln[nn]=8;for(nn=144;256>nn;++nn)ln[nn]=9;for(nn=256;280>nn;++nn)ln[nn]=7;for(nn=280;288>nn;++nn)ln[nn]=8;var dn=new zr(32);for(nn=0;32>nn;++nn)dn[nn]=5;var un=an(ln,9,0),_n=an(dn,5,0),cn=function(e){return(e/8|0)+(7&e&&1)},hn=function(e,t,i){(null==t||0>t)&&(t=0),(null==i||i>e.length)&&(i=e.length);var s=new(e instanceof Kr?Kr:e instanceof Jr?Jr:zr)(i-t);return s.set(e.subarray(t,i)),s},pn=function(e,t,i){var s=t/8|0;e[s]|=i<<=7&t,e[s+1]|=i>>>8},gn=function(e,t,i){var s=t/8|0;e[s]|=i<<=7&t,e[s+1]|=i>>>8,e[s+2]|=i>>>16},vn=function(e,t){for(var i=[],s=0;e.length>s;++s)e[s]&&i.push({s:s,f:e[s]});var r=i.length,n=i.slice();if(!r)return[new zr(0),0];if(1==r){var o=new zr(i[0].s+1);return o[i[0].s]=1,[o,1]}i.sort(function(e,t){return e.f-t.f}),i.push({s:-1,f:25001});var a=i[0],l=i[1],d=0,u=1,_=2;for(i[0]={s:-1,f:a.f+l.f,l:a,r:l};u!=r-1;)a=i[i[_].f>i[d].f?d++:_++],l=i[d!=u&&i[_].f>i[d].f?d++:_++],i[u++]={s:-1,f:a.f+l.f,l:a,r:l};var c=n[0].s;for(s=1;r>s;++s)n[s].s>c&&(c=n[s].s);var h=new Kr(c+1),p=fn(i[u-1],h,0);if(p>t){s=0;var g=0,v=p-t,f=1<s;++s){var m=n[s].s;if(t>=h[m])break;g+=f-(1<>>=v;g>0;){var y=n[s].s;t>h[y]?g-=1<=0&&g;--s){var b=n[s].s;h[b]==t&&(--h[b],++g)}p=t}return[new zr(h),p]},fn=function(e,t,i){return-1==e.s?Math.max(fn(e.l,t,i+1),fn(e.r,t,i+1)):t[e.s]=i},mn=function(e){for(var t=e.length;t&&!e[--t];);for(var i=new Kr(++t),s=0,r=e[0],n=1,o=function(e){i[s++]=e},a=1;t>=a;++a)if(e[a]==r&&a!=t)++n;else{if(!r&&n>2){for(;n>138;n-=138)o(32754);n>2&&(o(n>10?n-11<<5|28690:n-3<<5|12305),n=0)}else if(n>3){for(o(r),--n;n>6;n-=6)o(8304);n>2&&(o(n-3<<5|8208),n=0)}for(;n--;)o(r);n=1,r=e[a]}return[i.subarray(0,s),t]},yn=function(e,t){for(var i=0,s=0;t.length>s;++s)i+=e[s]*t[s];return i},bn=function(e,t,i){var s=i.length,r=cn(t+2);e[r]=255&s,e[r+1]=s>>>8,e[r+2]=255^e[r],e[r+3]=255^e[r+1];for(var n=0;s>n;++n)e[r+n+4]=i[n];return 8*(r+4+s)},wn=function(e,t,i,s,r,n,o,a,l,d,u){pn(t,u++,i),++r[256];for(var _=vn(r,15),c=_[0],h=_[1],p=vn(n,15),g=p[0],v=p[1],f=mn(c),m=f[0],y=f[1],b=mn(g),w=b[0],S=b[1],P=new Kr(19),k=0;m.length>k;++k)P[31&m[k]]++;for(k=0;w.length>k;++k)P[31&w[k]]++;for(var C=vn(P,7),I=C[0],E=C[1],x=19;x>4&&!I[Xr[x-1]];--x);var T,F,R,O,M=d+5<<3,A=yn(r,ln)+yn(n,dn)+o,D=yn(r,c)+yn(n,g)+o+14+3*x+yn(P,I)+(2*P[16]+3*P[17]+7*P[18]);if(A>=M&&D>=M)return bn(t,u,e.subarray(l,l+d));if(pn(t,u,1+(A>D)),u+=2,A>D){T=an(c,h,0),F=c,R=an(g,v,0),O=g;var L=an(I,E,0);for(pn(t,u,y-257),pn(t,u+5,S-1),pn(t,u+10,x-4),u+=14,k=0;x>k;++k)pn(t,u+3*k,I[Xr[k]]);u+=3*x;for(var N=[m,w],B=0;2>B;++B){var U=N[B];for(k=0;U.length>k;++k)pn(t,u,L[q=31&U[k]]),u+=I[q],q>15&&(pn(t,u,U[k]>>>5&127),u+=U[k]>>>12)}}else T=un,F=ln,R=_n,O=dn;for(k=0;a>k;++k)if(s[k]>255){var q;gn(t,u,T[257+(q=s[k]>>>18&31)]),u+=F[q+257],q>7&&(pn(t,u,s[k]>>>23&31),u+=Yr[q]);var H=31&s[k];gn(t,u,R[H]),u+=O[H],H>3&&(gn(t,u,s[k]>>>5&8191),u+=Qr[H])}else gn(t,u,T[s[k]]),u+=F[s[k]];return gn(t,u,T[256]),u+F[256]},Sn=new Jr([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Pn=new zr(0),kn=function(){for(var e=new Jr(256),t=0;256>t;++t){for(var i=t,s=9;--s;)i=(1&i&&3988292384)^i>>>1;e[t]=i}return e}(),Cn=function(e,t,i){for(;i;++t)e[t]=i,i>>>=8};function In(e,t){void 0===t&&(t={});var i=function(){var e=4294967295;return{p(t){for(var i=e,s=0;t.length>s;++s)i=kn[255&i^t[s]]^i>>>8;e=i},d(){return 4294967295^e}}}(),s=e.length;i.p(e);var r,n,o,a,l,d,u=(a=10+((r=t).filename&&r.filename.length+1||0),l=8,function(e,t,i,s,r,n){var o=e.length,a=new zr(s+o+5*(1+Math.floor(o/7e3))+r),l=a.subarray(s,a.length-r),d=0;if(!t||8>o)for(var u=0;o>=u;u+=65535){var _=u+65535;o>_?d=bn(l,d,e.subarray(u,_)):(l[u]=n,d=bn(l,d,e.subarray(u,o)))}else{for(var c=Sn[t-1],h=c>>>13,p=8191&c,g=(1<u;++u){var T=b(u),F=32767&u,R=f[T];if(v[F]=R,f[T]=F,u>=E){var O=o-u;if((k>7e3||I>24576)&&O>423){d=wn(e,l,0,w,S,P,C,I,x,u-x,d),I=k=C=0,x=u;for(var M=0;286>M;++M)S[M]=0;for(M=0;30>M;++M)P[M]=0}var A=2,D=0,L=p,N=F-R&32767;if(O>2&&T==b(u-N))for(var B=Math.min(h,O)-1,U=Math.min(32767,u),q=Math.min(258,O);U>=N&&--L&&F!=R;){if(e[u+A]==e[u+A-N]){for(var H=0;q>H&&e[u+H]==e[u+H-N];++H);if(H>A){if(A=H,D=N,H>B)break;var G=Math.min(N,H-2),W=0;for(M=0;G>M;++M){var V=u-N+M+32768&32767,j=V-v[V]+32768&32767;j>W&&(W=j,R=V)}}}N+=(F=R)-(R=v[F])+32768&32767}if(D){w[I++]=268435456|tn[A]<<18|sn[D];var z=31&tn[A],K=31&sn[D];C+=Yr[z]+Qr[K],++S[257+z],++P[K],E=u+A,++k}else w[I++]=e[u],++S[e[u]]}}d=wn(e,l,n,w,S,P,C,I,x,u-x,d),n||(d=bn(l,d,Pn))}return hn(a,0,s+cn(d)+r)}(n=e,null==(o=t).level?6:o.level,null==o.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(n.length)))):12+o.mem,a,l,!d)),_=u.length;return function(e,t){var i=t.filename;if(e[0]=31,e[1]=139,e[2]=8,e[8]=2>t.level?4:9==t.level?2:0,e[9]=3,0!=t.mtime&&Cn(e,4,Math.floor(new Date(t.mtime||Date.now())/1e3)),i){e[3]=8;for(var s=0;i.length>=s;++s)e[s+10]=i.charCodeAt(s)}}(u,t),Cn(u,_-8,i.d()),Cn(u,_-4,s),u}var En=!!et||!!Ze,xn=new WeakMap,Tn="text/plain",$n=0,Fn=!1,Rn=(e,t)=>{var i=e.split("#"),s=i[1],r=i[0].split("?"),n=r[0],o=r[1];if(!o)return e;var a=o.split("&").filter(e=>e.split("=")[0]!==t).join("&");return n+(a?"?"+a:"")+(s?"#"+s:"")},On=function(e,t,s){var r;void 0===s&&(s=!0);var n=e.split("?"),o=n[0],a=n[1],l=i({},t),d=null!==(r=null==a?void 0:a.split("&").map(e=>{var t,i=e.split("="),r=i[0],n=s&&null!==(t=l[r])&&void 0!==t?t:i[1];return delete l[r],r+"="+n}))&&void 0!==r?r:[],u=function(e,t){var i,s;void 0===t&&(t="&");var r=[];return Zi(e,function(e,t){mt(e)||mt(t)||"undefined"===t||(i=encodeURIComponent((e=>e instanceof File)(e)?e.name:e.toString()),s=encodeURIComponent(t),r[r.length]=s+"="+i)}),r.join(t)}(l);return u&&d.push(u),d.length>0?o+"?"+d.join("&"):o},Mn=e=>{if(e._encodedBody)return e._encodedBody;var t=e.data,i=e.compression;if(t){if(i===Ir.GZipJS){var s=In(function(e){var t=e.length;if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);for(var i=new zr(e.length+(e.length>>>1)),s=0,r=function(e){i[s++]=e},n=0;t>n;++n){if(s+5>i.length){var o=new zr(s+8+(t-n<<1));o.set(i),i=o}var a=e.charCodeAt(n);128>a?r(a):2048>a?(r(192|a>>>6),r(128|63&a)):a>55295&&57344>a?(r(240|(a=65536+(1047552&a)|1023&e.charCodeAt(++n))>>>18),r(128|a>>>12&63),r(128|a>>>6&63),r(128|63&a)):(r(224|a>>>12),r(128|a>>>6&63),r(128|63&a))}return hn(i,0,s)}(Xs(t)),{mtime:0});return{contentType:Tn,body:s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength),estimatedSize:s.byteLength}}if(i===Ir.Base64){var r=(e=>"data="+encodeURIComponent("string"==typeof e?e:Xs(e)))(function(e){return e?btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(e,t)=>String.fromCharCode(parseInt(t,16)))):e}(Xs(t)));return{contentType:"application/x-www-form-urlencoded",body:r,estimatedSize:new Blob([r]).size}}var n=Xs(t);return{contentType:"application/json",body:n,estimatedSize:new Blob([n]).size}}},An=e=>{var t,s,r=()=>"sendBeacon"===e.transport?{url:On(e.url,{compression:Ir.Base64}),encodedBody:Mn(i({},e,{compression:Ir.Base64,_encodedBody:void 0}))}:{url:Rn(e.url,"compression"),encodedBody:Mn(i({},e,{compression:void 0,_encodedBody:void 0}))};try{t=Mn(e)}catch(t){if(Wi(e.compression,Zs(e.url,"compression")))return Yi.error("Failed to gzip request body, sending uncompressed payload",t),r();throw t}return t&&Wi(e.compression,Zs(e.url,"compression"))&&!((s=t.body)instanceof ArrayBuffer?Gi(new Uint8Array(s)):ArrayBuffer.isView(s)&&Gi(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(Fn=!0,r()):{url:e.url,encodedBody:t}},Dn=e=>{try{return An(e)}catch(t){return Yi.error(t),void(null==e.callback||e.callback({statusCode:0,error:t}))}},Ln=function(){var e=r(function*(e){var t=yield function(e,t,i){return Ki.apply(this,arguments)}(Xs(e.data),a.DEBUG,{rethrow:!0});if(!t)return e;var s=yield t.arrayBuffer();return i({},e,{_encodedBody:{contentType:Tn,body:s,estimatedSize:s.byteLength}})});return function(t){return e.apply(this,arguments)}}(),Nn=e=>Ni("AbortError","PostHog request timed out"+(e?" after "+e+"ms":"")),Bn=/Failed to fetch|NetworkError|Load failed/i,Un=e=>"TypeError"===(null==e?void 0:e.name)&&Bn.test((null==e?void 0:e.message)||""),qn=e=>{try{var t=function(e,t,i){if(void 0===t&&(t=Date.now()),void 0===i&&(i=3e5),"string"==typeof e&&e){var s=e.trim(),r=/^\d+\s*,/.test(s)?s.slice(0,s.indexOf(",")).trim():s;if(/^\d+$/.test(r)){var n=1e3*Math.min(Number(r),i/1e3);return n>0?n:void 0}if(/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(r)){var o=/^\w{3} \w{3} /.test(r)?r+" GMT":r,a=Date.parse(o)-t;if(Number.isFinite(a)&&a>0)return Math.min(a,i)}}}(e());return mt(t)?void 0:Math.min(t,3e4)}catch(e){return}},Hn=e=>{var t=Dn(e);if(t){var i=new et;xn.set(i,!0);var s=t.url,r=t.encodedBody;i.open(e.method||"GET",s,!0);var n=null!=r?r:{},o=n.contentType,a=n.body;Zi(e.headers,function(e,t){i.setRequestHeader(t,e)}),o&&i.setRequestHeader("Content-Type",o),e.timeout&&(i.timeout=e.timeout);var l=!1;i.ontimeout=()=>{l=!0},i.onloadend=()=>{if(l){var t=Nn(e.timeout);return Yi.warn(t),void(null==e.callback||e.callback({statusCode:0,error:t}))}var s={statusCode:i.status,text:i.responseText};if(200===i.status)try{s.json=JSON.parse(i.responseText)}catch(e){}null==e.callback||e.callback(s,qn(()=>i.getResponseHeader("Retry-After")))},null==e.onSend||e.onSend(s),i.send(a)}},Gn=e=>{var t=Dn(e);if(t){var s=t.url,r=t.encodedBody,n=null!=r?r:{},o=n.contentType,a=n.body,l=n.estimatedSize,d=new Headers;Zi(e.headers,function(e,t){d.append(t,e)}),o&&d.append("Content-Type",o);var u=null,_=!1;if(tt){var c=new tt;u={signal:c.signal,timeout:setTimeout(()=>{_=!0;try{c.abort(Nn(e.timeout))}catch(e){p(e)}},e.timeout)}}var h=!1,p=t=>{h||(h=!0,_&&"AbortError"===(null==t?void 0:t.name)||Un(t)?Yi.warn(t):Yi.error(t),null==e.callback||e.callback({statusCode:0,error:t}))},g=0,v=()=>{$n-=g,g=0,u&&clearTimeout(u.timeout)};try{var f,m=i({method:(null==e?void 0:e.method)||"GET",headers:d,referrerPolicy:"strict-origin",body:a,signal:null==(f=u)?void 0:f.signal},e.fetchOptions);null==e.onSend||e.onSend(s);var y=null!=l?l:mt(a)?0:void 0;m.keepalive="POST"===m.method&&!e._keepaliveDisabled&&!1!==m.keepalive&&m.body===a&&!mt(y)&&y>=0&&52428.8>$n+y,m.keepalive&&($n+=g=y),Ze(s,m).then(t=>t.text().then(i=>{if(!h){var s={statusCode:t.status,text:i};if(200===t.status)try{s.json=JSON.parse(i)}catch(e){Yi.error(e)}h=!0,v(),null==e.callback||e.callback(s,qn(()=>t.headers.get("Retry-After")))}})).catch(e=>{v(),p(e)}).finally(v)}catch(e){v(),p(e)}}},Wn=e=>{try{var t,s=An(e),r=s.url,n=s.encodedBody,o=null!=n?n:{},a=o.body,l=o.estimatedSize;if(!a)return;var d=a instanceof Blob?a:new Blob([a],{type:o.contentType});if(Ye.sendBeacon(r,d))return;var u=pt(e.data)?e.data:null==(t=e.data)?void 0:t.batch;if(pt(u)&&u.length>1&&(null!=l?l:0)>16384){var _=Math.ceil(u.length/2),c=t=>pt(e.data)?t:i({},e.data,{batch:t});return Wn(i({},e,{data:c(u.slice(0,_))})),void Wn(i({},e,{data:c(u.slice(_))}))}Yi.warn("Beacon of ~"+(null!=l?l:0)+" bytes was rejected by the browser, falling back to "+(Ze?"fetch":"XHR")),Ze?Gn(i({},e,{_keepaliveDisabled:!0})):Hn(e)}catch(e){Yi.warn("Beacon send failed",e)}},Vn=(e,t,s,r)=>{var n="query"===r?"POST"===t?"sent_at":"_":void 0;return On(s===Ir.GZipJS?Rn(e,"compression"):e,i({},n?{[n]:Date.now().toString()}:{},s===Ir.GZipJS?{}:{compression:s}))},jn=(()=>{var e=[];return Ze&&e.push({transport:"fetch",method:Gn}),et&&e.push({transport:"XHR",method:Hn}),null!=Ye&&Ye.sendBeacon&&e.push({transport:"sendBeacon",method:Wn}),e})(),zn=!En&&-1===(null==st?void 0:st.indexOf("MSIE"))&&-1===(null==st?void 0:st.indexOf("Mozilla"));function Kn(e,t,s){var r;s&&(t=i({},t,{callback:e=>s(e)})),e.__loaded?zn?e.__request_queue.push(t):e.rateLimiter.isServerRateLimited(t.batchKey)?t.fireCallbackOnDrop&&(null==t.callback||t.callback({statusCode:429})):(t.transport=t.transport||e.config.api_transport,t.headers=i({},e.config.request_headers,t.headers),t.compression="best-available"===t.compression?null!==(r=e.compression)&&void 0!==r?r:t.compressionFallback:t.compression,(mt(e.config.disable_beacon)?e.config.__preview_disable_beacon:e.config.disable_beacon)&&(t.disableTransport=["sendBeacon"]),t.fetchOptions=t.fetchOptions||e.config.fetch_options,null==t.onDispatch||t.onDispatch(),((e,t)=>{var s,r,n,o=i({},e,{callback:null!=t?t:t=>null==e.callback?void 0:e.callback(t)});o.timeout=o.timeout||6e4;var a,l,d,u,_,c=null!==(s=o.transport)&&void 0!==s?s:"fetch";"sendBeacon"===c&&mt(o.compression)&&o.data&&(o.compression=Ir.Base64),"POST"===o.method&&o.data&&("capture-body"===o.timestampMode?o.data={api_key:null!==(l=null==(_=(u=(pt(a=o.data)?a:[a]).map(e=>i({},e,e.timestamp instanceof Date&&!isNaN(e.timestamp.getTime())?{timestamp:e.timestamp.toISOString()}:{})))[0])||null==(d=_.properties)?void 0:d.token)&&void 0!==l?l:null==_?void 0:_.token,batch:u,sent_at:(new Date).toISOString()}:"body"===o.timestampMode&&(o.data=function(e,t){return void 0===t&&(t=(new Date).toISOString()),pt(e)?e.map(e=>i({},e,{sent_at:t})):i({},e,{sent_at:t})}(o.data))),o.url=Vn(o.url,o.method,o.compression,o.timestampMode);var h=jn.filter(e=>!o.disableTransport||!e.transport||!o.disableTransport.includes(e.transport)),p=null!==(r=null==(n=function(e,t){for(var i=0;e.length>i;i++)if(t(e[i]))return e[i]}(h,e=>e.transport===c))?void 0:n.method)&&void 0!==r?r:h[0].method;if(!p)throw new Error("No available transport method");var g=e=>{try{p(e)}catch(e){Un(e)?Yi.warn(e):Yi.error(e),null==o.callback||o.callback({statusCode:0,error:e})}};"sendBeacon"!==c&&!o.preferSyncCompression&&o.data&&o.compression===Ir.GZipJS&&it&&"undefined"!=typeof Promise&&!Fn?Ln(o).then(e=>{g(e)}).catch(t=>{if(Vi(t))return Fn=!0,void g(i({},o,{compression:void 0,url:Vn(e.url,e.method,void 0,e.timestampMode)}));(e=>{if(!e||"object"!=typeof e)return!1;var t="name"in e?String(e.name):"";return Vi(e)||t===Hi})(t)&&(Fn=!0),g(o)}):g(o)})(t,(i,r)=>{e.rateLimiter.checkForLimiting(i),400>i.statusCode||null==e.config.on_request_error||e.config.on_request_error(i),s?s(i,r):null==t.callback||t.callback(i)})):t.fireCallbackOnDrop&&(null==t.callback||t.callback({statusCode:0}))}var Jn=class{constructor(e,t){this._isPaused=!0,this._queue=[],this._flushTimeoutMs=At((null==t?void 0:t.flush_interval_ms)||3e3,250,5e3,Yi.createLogger("flush interval"),3e3),this._sendRequest=e}enqueue(e){this._queue.push(e),this._flushTimeout||this._setFlushTimeout()}unload(){this._clearFlushTimeout();var e=this._queue.length>0?this._formatQueue():{},t=Object.values(e);[...t.filter(e=>0===e.url.indexOf("/e")),...t.filter(e=>0!==e.url.indexOf("/e"))].map(e=>{this._sendRequestSafely(i({},e,{callback:void 0}),"sendBeacon")})}enable(){this._isPaused=!1,this._setFlushTimeout()}_setFlushTimeout(){this._isPaused||(this._flushTimeout=setTimeout(()=>{this._clearFlushTimeout(),this._flush()},this._flushTimeoutMs))}_flush(){if(this._queue.length>0){var e=this._formatQueue();for(var t in e)this._sendRequestSafely(e[t])}}_sendRequestSafely(e,t){try{this._sendRequest(e,t)}catch(e){Yi.error(e)}}_clearFlushTimeout(){clearTimeout(this._flushTimeout),this._flushTimeout=void 0}_formatQueue(){var e={},t={};Zi(this._queue,s=>{var r,n=s,o=((n?n.batchKey:null)||n.url)+(n.batchGroup?":"+n.batchGroup:"");mt(e[o])&&(e[o]=i({},n,{data:[],callback:void 0,fireCallbackOnDrop:void 0}),t[o]=[]),null==(r=e[o].data)||r.push(n.data),n.callback&&t[o].push(n.callback)});var s=function(){var i=t[r];i.length&&(e[r].callback=e=>{for(var t of i)t(e)})};for(var r in t)s();return this._queue=[],e}},Yn=class{constructor(e){this._instance=e,this._isPolling=!1,this._pollIntervalMs=3e3,this._queue=[],this._queue=[],this._areWeOnline=!0,this.resume()}resume(){if(!mt(Ke)&&"onLine"in Ke.navigator){if(this._areWeOnline=Ke.navigator.onLine,this._onlineListener)return;this._onlineListener=()=>{this._areWeOnline=!0,this._flush()},this._offlineListener=()=>{this._areWeOnline=!1},os(Ke,"online",this._onlineListener),os(Ke,"offline",this._offlineListener)}}get length(){return this._queue.length}retriableRequest(e,s){var r=e.retriesPerformedSoFar,n=function(e,t){if(null==e)return{};var i={};for(var s in e)if({}.hasOwnProperty.call(e,s)){if(-1!==t.indexOf(s))continue;i[s]=e[s]}return i}(e,t);kt(r)&&(n.url=On(n.url,{retry_count:r})),Kn(this._instance,s?i({},n,{transport:s}):n,(e,t)=>{if(200!==e.statusCode&&(400>e.statusCode||e.statusCode>=500)){if((0===e.statusCode?3:10)>(null!=r?r:0))return void this._enqueue(i({retriesPerformedSoFar:r},n),t);0===e.statusCode&&Yi.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(null!=r?r:0)+" retries.")}null==n.callback||n.callback(e)})}_enqueue(e,t){var i=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=i+1;var s=Math.max(function(e){var t=3e3*Math.pow(2,e),i=t/2,s=Math.min(18e5,t),r=(Math.random()-.5)*(s-i);return Math.ceil(s+r)}(i),null!=t?t:0),r=Date.now()+s;this._queue.push({retryAt:r,requestOptions:e});var n="Enqueued failed request for retry in "+s;navigator.onLine||(n+=" (Browser is offline)"),Yi.warn(n),this._isPolling||(this._isPolling=!0,this._poll())}_poll(){if(this._poller&&clearTimeout(this._poller),0===this._queue.length)return this._isPolling=!1,void(this._poller=void 0);this._poller=setTimeout(()=>{this._areWeOnline&&this._queue.length>0&&this._flush(),this._poll()},this._pollIntervalMs)}_flush(){var e=Date.now(),t=[],i=this._queue.filter(i=>e>i.retryAt||(t.push(i),!1));if(this._queue=t,i.length>0)for(var s of i)this.retriableRequest(s.requestOptions)}unload(){for(var e of(this._poller&&(clearTimeout(this._poller),this._poller=void 0),this._isPolling=!1,mt(Ke)||(this._onlineListener&&(Ke.removeEventListener("online",this._onlineListener),this._onlineListener=void 0),this._offlineListener&&(Ke.removeEventListener("offline",this._offlineListener),this._offlineListener=void 0)),this._queue)){var t=e.requestOptions;try{this._instance._send_request(i({},t,{callback:pt(t.data)?void 0:t.callback,transport:"sendBeacon"}))}catch(e){Yi.error(e)}}this._queue=[]}},Qn=class{constructor(e){this._instance=e,this._updateScrollData=()=>{var e,t,i,s;this._context||(this._context={});var r=this.scrollElement(),n=this.scrollY(),o=r?Math.max(0,r.scrollHeight-r.clientHeight):0,a=n+((null==r?void 0:r.clientHeight)||0),l=(null==r?void 0:r.scrollHeight)||0;this._context.lastScrollY=Math.ceil(n),this._context.maxScrollY=Math.max(n,null!==(e=this._context.maxScrollY)&&void 0!==e?e:0),this._context.maxScrollHeight=Math.max(o,null!==(t=this._context.maxScrollHeight)&&void 0!==t?t:0),this._context.lastContentY=a,this._context.maxContentY=Math.max(a,null!==(i=this._context.maxContentY)&&void 0!==i?i:0),this._context.maxContentHeight=Math.max(l,null!==(s=this._context.maxContentHeight)&&void 0!==s?s:0)}}get _scrollRoot(){return this._instance.config.scroll_root_selector}getContext(){return this._context}resetContext(){var e=this._context;return this._context=void 0,setTimeout(this._updateScrollData,0),e}startMeasuringScrollPosition(){os(Ke,"scroll",this._updateScrollData,{capture:!0}),os(Ke,"scrollend",this._updateScrollData,{capture:!0}),os(Ke,"resize",this._updateScrollData)}scrollElement(){var e;if(!this._scrollRoot)return null==Ke||null==(e=Ke.document)?void 0:e.documentElement;for(var t of pt(this._scrollRoot)?this._scrollRoot:[this._scrollRoot]){var i,s=null==Ke||null==(i=Ke.document)?void 0:i.querySelector(t);if(s)return s}}_scrollPosition(e){var t,i,s="y"===e?"scrollTop":"scrollLeft";if(this._scrollRoot){var r=this.scrollElement();return r&&r[s]||0}return Ke?"y"===e?Ke.scrollY||Ke.pageYOffset||(null==(t=Ke.document)||null==(t=t.documentElement)?void 0:t.scrollTop)||0:Ke.scrollX||Ke.pageXOffset||(null==(i=Ke.document)||null==(i=i.documentElement)?void 0:i.scrollLeft)||0:0}scrollY(){return this._scrollPosition("y")}scrollX(){return this._scrollPosition("x")}},Xn=e=>ur(null==e?void 0:e.config.mask_personal_data_properties,null==e?void 0:e.config.custom_personal_data_properties,null==e?void 0:e.config.disable_capture_url_hashes),Zn=class{constructor(e,t,i,s){this._onSessionIdCallback=e=>{var t=this._getStored();if(!t||t.sessionId!==e){var i={sessionId:e,props:this._sessionSourceParamGenerator(this._instance)};this._persistence.register({[be]:i})}},this._instance=e,this._sessionIdManager=t,this._persistence=i,this._sessionSourceParamGenerator=s||Xn,this._sessionIdManager.onSessionId(this._onSessionIdCallback)}_getStored(){return this._persistence.props[be]}getSetOnceProps(){var e,t=null==(e=this._getStored())?void 0:e.props;return t?"r"in t?_r(t,this._instance.config.disable_capture_url_hashes):{$referring_domain:t.referringDomain,$pathname:t.initialPathName,utm_source:t.utm_source,utm_campaign:t.utm_campaign,utm_medium:t.utm_medium,utm_content:t.utm_content,utm_term:t.utm_term}:{}}getSessionProps(){var e={};return Zi(is(this.getSetOnceProps()),(t,i)=>{"$current_url"===i&&(i="url"),e["$session_entry_"+ut(i)]=t}),e}},eo=class{on(e,t){return this._events[e]||(this._events[e]=[]),this._events[e].push(t),()=>{this._events[e]=this._events[e].filter(e=>e!==t)}}emit(e,t){for(var i of this._events[e]||[])i(t);for(var s of this._events["*"]||[])s(e,t)}constructor(){this._events={}}},to=Qi("[SessionId]"),io=864e5,so=class{on(e,t){return this._eventEmitter.on(e,t)}constructor(e,t,i){var s;if(this._lastPersistedActivityTimestamp=null,this._lastCookieSyncTimestamp=null,this._sessionIdChangedHandlers=[],this._beforeUnloadListener=void 0,this._destroyed=!1,this._eventEmitter=new eo,this._sessionHasBeenIdleTooLong=(e,t)=>!(!kt(e)||!kt(t))&&Math.abs(e-t)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if("always"===e.config.cookieless_mode)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this._config=e.config,this._persistence=e.persistence,this._windowId=void 0,this._sessionId=void 0,this._sessionStartTimestamp=null,this._pendingBootstrapSession=void 0,this._sessionActivityTimestamp=null,this._sessionIdGenerator=t||ps,this._windowIdGenerator=i||ps;var r=this._config.persistence_name||this._config.token;if(this._sessionTimeoutMs=1e3*At(this._config.session_idle_timeout_seconds||1800,60,36e3,to.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this._resetIdleTimer(),this._window_id_storage_key="ph_"+r+"_window_id",this._primary_window_exists_storage_key="ph_"+r+"_primary_window_exists",this._canUseSessionStorage()){var n=As._parse(this._window_id_storage_key),o=As._parse(this._primary_window_exists_storage_key);n&&!o?this._windowId=n:As._remove(this._window_id_storage_key),As._set(this._primary_window_exists_storage_key,!0)}null!=(s=this._config.bootstrap)&&s.sessionID&&this.setBootstrapSessionId(this._config.bootstrap.sessionID),this._listenToReloadWindow()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return mt(this._sessionIdChangedHandlers)&&(this._sessionIdChangedHandlers=[]),this._sessionIdChangedHandlers.push(e),this._sessionId&&e(this._sessionId,this._windowId),()=>{this._sessionIdChangedHandlers=this._sessionIdChangedHandlers.filter(t=>t!==e)}}_canUseSessionStorage(){return"memory"!==this._config.persistence&&!this._persistence._disabled&&As._is_supported()}_setWindowId(e){e!==this._windowId&&(this._windowId=e,this._canUseSessionStorage()&&As._set(this._window_id_storage_key,e))}_getWindowId(){return this._windowId?this._windowId:this._canUseSessionStorage()?As._parse(this._window_id_storage_key):null}_isActivityChangeBelowGranularity(e){var t=this._lastPersistedActivityTimestamp;return!wt(t)&&!wt(e)&&5e3>Math.abs(e-t)}_setSessionId(e,t,i){var s=t!==this._sessionActivityTimestamp,r=!(e!==this._sessionId||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=t,this._sessionId=e,r&&!s||r&&this._isActivityChangeBelowGranularity(t)||(this._lastPersistedActivityTimestamp=t,this._persistence.register({[re]:[t,e,i]}))}_useCrossTabRefreshHardening(){var e,t=null==(e=this._config)?void 0:e.persistence_save_debounce_ms;return kt(t)&&t>0}_refreshSessionIdFromStorage(){this._useCrossTabRefreshHardening()?this._persistence.refreshKey(re):(this._persistence.flush(),this._persistence.load())}_flushPendingActivityTimestamp(){var e;if(!wt(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this._lastPersistedActivityTimestamp){this._refreshSessionIdFromStorage();var t=this._getSessionId();t[1]===this._sessionId&&t[2]===this._sessionStartTimestamp&&(this._lastPersistedActivityTimestamp=this._sessionActivityTimestamp,this._persistence.register({[re]:[this._sessionActivityTimestamp,null!==(e=this._sessionId)&&void 0!==e?e:null,this._sessionStartTimestamp]}),this._persistence.flush())}}_freshestActivityTimestamp(){var e=this._getSessionId()[0],t=kt(e)?e:0,i=kt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(t,i)}_isSessionIdleAfterCrossTabRefresh(e){return this._refreshSessionIdFromStorage(),this._sessionHasBeenIdleTooLong(e,this._freshestActivityTimestamp())}_getSessionId(){var e=this._persistence.props[re];return pt(e)&&2===e.length&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this._lastPersistedActivityTimestamp=null,this._pendingBootstrapSession=void 0,clearTimeout(this._enforceIdleTimeout),this._enforceIdleTimeout=void 0,this._setSessionId(null,null,null)}setBootstrapSessionId(e,t){void 0===t&&(t=!1);var i=function(e,t){void 0===t&&(t=(new Date).getTime());try{var i=(e=>{var t=e.replace(/-/g,"");if(32!==t.length)throw new Error("Not a valid UUID");if("7"!==t[12])throw new Error("Not a UUIDv7");return parseInt(t.substring(0,12),16)})(e);return i>t+6e4?void to.error("Bootstrap sessionID cannot be in the future"):i}catch(e){return void to.error("Invalid sessionID in bootstrap",e)}}(e);return!mt(i)&&(t?this._pendingBootstrapSession={sessionId:e,sessionStartTimestamp:i}:this._setSessionId(e,(new Date).getTime(),i),!0)}destroy(){this._destroyed=!0,this._flushPendingActivityTimestamp(),clearTimeout(this._enforceIdleTimeout),this._enforceIdleTimeout=void 0,this._beforeUnloadListener&&Ke&&(Ke.removeEventListener(Ge,this._beforeUnloadListener,{capture:!1}),this._beforeUnloadListener=void 0),this._sessionIdChangedHandlers=[]}_listenToReloadWindow(){this._beforeUnloadListener=()=>{this._flushPendingActivityTimestamp(),this._canUseSessionStorage()&&As._remove(this._primary_window_exists_storage_key)},os(Ke,Ge,this._beforeUnloadListener,{capture:!1})}checkAndGetSessionAndWindowId(e,t,i){if(void 0===e&&(e=!1),void 0===t&&(t=null),void 0===i&&(i=!1),"always"===this._config.cookieless_mode)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var s=t||(new Date).getTime(),r=this._sessionId;if(i)this._lastCookieSyncTimestamp=s;else if(wt(this._lastCookieSyncTimestamp)||this._lastCookieSyncTimestamp>s||s-this._lastCookieSyncTimestamp>=1e3){var n,o;null==(n=(o=this._persistence).syncCookieProperties)||n.call(o),this._lastCookieSyncTimestamp=s}var a=this._getSessionId(),l=a[1],d=a[2],u=!mt(r)&&l!==r,_=this._freshestActivityTimestamp(),c=this._getWindowId(),h=this._pendingBootstrapSession,p=!!h&&(h.sessionStartTimestamp>s+6e4||s-h.sessionStartTimestamp>io),g=h?p:kt(d)&&Math.abs(s-d)>io,v=!1,f=u,m=!l||!!h,y=l,b=!m&&!e&&this._sessionHasBeenIdleTooLong(s,_);if(b){(b=this._isSessionIdleAfterCrossTabRefresh(s))||to.info("cross-tab refresh kept the session alive",{sessionId:l});var w=this._getSessionId();l=w[1],d=w[2],b||(m=!l||!!h)}if(m||b||g){f=!1;var S=h&&!p;l=S?h.sessionId:this._sessionIdGenerator(),c=this._windowIdGenerator(),to.info("new session ID assigned",{sessionId:l,windowId:c,bootstrapped:!!S,changeReason:{noSessionId:m,activityTimeout:b,sessionPastMaximumLength:g}}),d=S?h.sessionStartTimestamp:s,this._pendingBootstrapSession=void 0,v=!0}else c||(c=this._windowIdGenerator(),v=!0),(f=f||l!==y)&&(to.info("adopted cross-tab session id",{sessionId:l,windowId:c}),v=!0);var P=kt(_)&&e&&!g?_:s,k=kt(d)?d:(new Date).getTime();this._setWindowId(c),this._setSessionId(l,P,k),e||this._resetIdleTimer();var C={noSessionId:m,activityTimeout:b,sessionPastMaximumLength:g,crossTabAdoption:f};return v&&this._sessionIdChangedHandlers.forEach(e=>e(l,c,C)),{sessionId:l,windowId:c,sessionStartTimestamp:k,changeReason:v?C:void 0,lastActivityTimestamp:_}}_resetIdleTimer(){this._destroyed||(clearTimeout(this._enforceIdleTimeout),this._enforceIdleTimeout=setTimeout(()=>{if(!this._destroyed)if(this._isSessionIdleAfterCrossTabRefresh((new Date).getTime())){var e=this._sessionId;this.resetSessionId(),this._eventEmitter.emit("forcedIdleReset",{idleSessionId:e})}else this._resetIdleTimer()},1.1*this.sessionTimeoutMs))}},ro=Object.freeze(["2026-08-30","2026-08-29","2026-06-25","2026-05-30","2026-01-30","2025-11-30","2025-05-24"]);function no(){return(no=r(function*(){var e=null==Ye?void 0:Ye.userAgentData;if(null!=e&&e.getHighEntropyValues)try{var t,i=null==(t=yield e.getHighEntropyValues(["model"]))?void 0:t.model;return yt(i)&&i.length>0?i:void 0}catch(e){return void Yi.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",e)}})).apply(this,arguments)}function oo(e,t){var i="$survey_"+t+"/"+e.id;return e.current_iteration&&e.current_iteration>0&&(i="$survey_"+t+"/"+e.id+"/"+e.current_iteration),i}function ao(e,t,i){return Xs({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:i})}var lo,uo="custom",_o="i.posthog.com",co=/^\/static\//,ho=["/s/","/e/","/i/"],po=class{constructor(e){this._regionCache={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return"https://app.posthog.com"===e?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,t=null==(e=this.instance.config.ui_host)?void 0:e.replace(/\/$/,"");return t||(t=this.apiHost.replace("."+_o,".posthog.com")),"https://app.posthog.com"===t?"https://us.posthog.com":t}get region(){return this._regionCache[this.apiHost]||(this._regionCache[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":uo),this._regionCache[this.apiHost]}_staticAssetHostOverride(e){if(co.test(e)){var t=this.instance.config.asset_host;if("string"==typeof t)return t.trim().replace(/\/$/,"")||void 0}}_urlKey(e){var t=Qs(e);return t?t.protocol+"//"+t.host+t.pathname:void 0}_prepareEndpoint(e,t,i){if("ui"===e)return i;var s=i,r=this.instance.config.rewriteRequestPath;if(r){var n,o=(null==(n=Qs(i))?void 0:n.href)||i;s=r(new URL(o)).toString()}if(r&&"api"===e&&ho.some(e=>0===t.indexOf(e))){var a=this._urlKey(s);if(a){var l,d=this.apiHost,u=this._ingestionEndpoints;(null==(l=u)?void 0:l.apiHost)===d&&u.rewriteRequestPath===r||(this._ingestionEndpoints=u={apiHost:d,rewriteRequestPath:r,urls:new Set}),u.urls.add(a)}}return s}isIngestionEndpoint(e){var t=this._ingestionEndpoints,i=this._urlKey(e);return(null==t?void 0:t.apiHost)===this.apiHost&&t.rewriteRequestPath===this.instance.config.rewriteRequestPath&&!!i&&t.urls.has(i)}endpointFor(e,t){if(void 0===t&&(t=""),t&&(t="/"===t[0]?t:"/"+t),"ui"===e)return this._prepareEndpoint(e,t,this.uiHost+t);if("flags"===e)return this._prepareEndpoint(e,t,this.flagsApiHost+t);if("assets"===e){var i=this._staticAssetHostOverride(t);if(i)return this._prepareEndpoint(e,t,""+i+t)}if(this.region===uo)return this._prepareEndpoint(e,t,this.apiHost+t);var s=_o+t;switch(e){case"assets":return this._prepareEndpoint(e,t,"https://"+this.region+"-assets."+s);case"api":return this._prepareEndpoint(e,t,"https://"+this.region+"."+s)}}},go=Qi("[Surveys]"),vo={ignoreConditions:!1,ignoreDelay:!1,displayType:Lr.Popover},fo=Qi("[PostHog ExternalIntegrations]"),mo={intercom:"intercom-integration",crispChat:"crisp-chat-integration"},yo=class{constructor(e){this._instance=e}_loadScript(e,t){var i;null==(i=nt.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,e,e=>{if(e)return fo.error("failed to load script",e);t()})}startIfEnabledOrStop(){var e=this,t=function(){var t,s,r,n=i[0],o=i[1];!o||null!=(t=nt.__PosthogExtensions__)&&null!=(t=t.integrations)&&t[n]||e._loadScript(mo[n],()=>{var t;null==(t=nt.__PosthogExtensions__)||null==(t=t.integrations)||null==(t=t[n])||t.start(e._instance)}),!o&&null!=(s=nt.__PosthogExtensions__)&&null!=(s=s.integrations)&&s[n]&&(null==(r=nt.__PosthogExtensions__)||null==(r=r.integrations)||null==(r=r[n])||r.stop())};for(var i of Object.entries(null!==(s=this._instance.config.integrations)&&void 0!==s?s:{})){var s;t()}}},bo=()=>{var e;return null!=Ke&&null!=(e=Ke.performance)&&e.now?Ke.performance.now():Date.now()},wo=[],So=[50,75,100,150,200,300,400,500,750,1e3,1500,2e3,3e3,5e3,1e4],Po=[5,10,25,...So],ko=class{constructor(e){this._instance=e}initialize(){}get(e){var t=this._instance.persistence;if("string"==typeof e)return null==t?void 0:t.get_property(e);var i={};for(var s of e){var r=null==t?void 0:t.get_property(s);mt(r)||(i[s]=r)}return i}set(e,t){var i;null==(i=this._instance.persistence)||i.register("string"==typeof e?{[e]:t}:e)}remove(e){var t;null==(t=this._instance.persistence)||t.unregister(e)}},Co=class{constructor(e){this.instance=e,this._logger=Yi,this.kv=new ko(e),this.onSession=e=>Nr(this.instance.onSessionId(t=>{try{e(t)}catch(e){this._logger.error("Browser extension session listener failed",e)}})),this.onEvent=e=>Nr(this.instance._addCaptureHook((t,i)=>{if(i)try{e({event:t,properties:i.properties})}catch(e){this._logger.error("Browser extension event listener failed",e)}})),this.onRemoteConfig=e=>{var t=t=>{try{e(t)}catch(e){this._logger.error("Browser extension remote config listener failed",e)}},i=this.instance._internalEventEmitter.on("extensionsRemoteConfig",t);return this.instance._lastRemoteConfig&&t(this.instance._lastRemoteConfig),Nr(i)}}get logger(){return this._logger}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return null!==(e=this.instance.get_property("$device_id"))&&void 0!==e?e:this.distinctId}get deviceId(){var e=this.instance.get_property(O);return"string"==typeof e?e:void 0}get library(){return{name:a.LIB_NAME,version:a.LIB_VERSION}}get initialPersonProperties(){var e,t;return null!==(e=null==(t=this.instance.persistence)?void 0:t.get_initial_props())&&void 0!==e?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,t,i,s,r,n=null==(e=this.instance.sessionManager)?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:null!==(t=null==n?void 0:n.sessionId)&&void 0!==t?t:"",windowId:null!==(i=null==n?void 0:n.windowId)&&void 0!==i?i:"",sessionStartTimestamp:null!==(s=null==n?void 0:n.sessionStartTimestamp)&&void 0!==s?s:0,lastActivityTimestamp:null!==(r=null==n?void 0:n.lastActivityTimestamp)&&void 0!==r?r:0}}catch(e){return{sessionId:"",windowId:"",sessionStartTimestamp:0,lastActivityTimestamp:0}}}get isOptedOut(){return this.instance.has_opted_out_capturing()}get canCapture(){return gt(this.instance.is_capturing)?this.instance.is_capturing():!this.isOptedOut}get isRateLimited(){var e;return!(null==(e=this.instance.rateLimiter)||!e.isClientRateLimited)}get projectToken(){return this.instance.config.token}getExtension(e){var t;switch(e){case"featureFlags":case"featureFlagsCommon":t=this.instance.featureFlags;break;case"logs":t=this.instance.logs;break;case"surveys":t=this.instance.surveys;break;case"autocapture":t=this.instance.autocapture}return t}capture(e,t,s){if(!s)return this._notRateLimited(this.instance.capture(e,t));var r=i({timestamp:s.timestamp,uuid:s.uuid,$set:s.set,$set_once:s.setOnce},"unload"===s.delivery?{transport:"sendBeacon",send_instantly:!0}:{});return this._notRateLimited(this.instance.capture(e,t,r))}_notRateLimited(e){var t;return!mt(e)||!(null!=(t=this.instance.rateLimiter)&&t.lastEventRateLimited)}registerDynamicEventProperties(e){return Nr(this.instance._registerExtensionEventProperties(e))}sendRequest(e,t){var i=this;return r(function*(){var s;void 0===t&&(t={});var r=null!==(s=t.target)&&void 0!==s?s:"api",n=t.query?On(e,t.query):e,o=i.instance.requestRouter.endpointFor(r,n),a={method:t.method,url:o,data:t.body,headers:t.headers,timeout:t.timeoutMs,fireCallbackOnDrop:!0,transport:t.transport,compression:t.compression,compressionFallback:"flags"===t.target&&"best-available"===t.compression?ot.Base64:void 0,timestampMode:t.sentAt};return"api"===r&&"/i/v1/logs"===e&&(a.batchKey="logs"),"sendBeacon"===t.transport?(i.instance._send_request(a),{statusCode:202}):new Promise(e=>{var t,s,n;a.callback=e,"flags"===r&&null!=(t=i.instance.config.metrics)&&t.flags&&(a.onDispatch=()=>{s=bo()},a.onSend=e=>{n=(e=>{try{return(e=>{var t,i=null==Ke?void 0:Ke.PerformanceObserver,s=null==(t=Qs(e))?void 0:t.href;if(i&&s){var r,n,o,a=bo(),l={name:s,before:1/0,inFlight:!0},d=1/0,u=!1,_=()=>{u||(u=!0,clearTimeout(o),p.disconnect(),wo.splice(wo.indexOf(l),1))},c=!1,h=e=>{for(var t of e){var i=t.startTime;t.name!==s||(c?a>=i:a>i)||i>=l.before||r&&i>=r.startTime||(r=t)}if(r&&n&&d>=r.startTime){var o=n;_(),o(r)}},p=new i(e=>h(e.getEntriesByName(s,"resource")));for(var g of(p.observe({entryTypes:["resource"]}),wo))g.name===s&&(g.before=Math.min(g.before,a),c=c||g.inFlight);return wo.push(l),{take(e,t){u||(d=e,l.inFlight=!1,n=t,o=setTimeout(_,5e3),gt(p.takeRecords)&&h(p.takeRecords()))},stop:_}}})(e)}catch(e){return}})(e)},a.callback=t=>{var r;if(e(t),!mt(s)){var a=s,l=bo();try{var d=((e,t)=>{var i,s,r=t.statusCode||void 0,n={"server.address":(null!==(i=null==(s=Qs(e))?void 0:s.hostname)&&void 0!==i?i:e).replace(/^\[(.*)\]$/,"$1")};r&&(n["http.response.status_code"]=r);var o=((e,t)=>e?400>e?void 0:String(e):"AbortError"===(null==t?void 0:t.name)?"timeout":"_OTHER")(r,t.error);o&&(n["error.type"]=o);var a=Ys();return a&&(n["client.timezone"]=a),n})(o,t);if(i._recordFlagsHistogram("posthog.flags.request.duration",l-a,So,d),t.statusCode&&n)return void n.take(l,e=>i._recordFlagsSplit(e,a,l,d))}catch(e){Yi.error("Failed to record the /flags request timing",e)}null==(r=n)||r.stop()}}),i.instance._send_request(a)})})()}_recordFlagsSplit(e,t,i,s){if(e.responseEnd>=e.startTime)try{var r=Math.min(e.responseEnd,i);this._recordFlagsHistogram("posthog.flags.request.pre_send_duration",e.startTime-t,Po,s),this._recordFlagsHistogram("posthog.flags.request.network_duration",r-e.startTime,So,s),this._recordFlagsHistogram("posthog.flags.request.main_thread_duration",i-r,Po,s)}catch(e){Yi.error("Failed to record the /flags request timing split",e)}}_recordFlagsHistogram(e,t,s,r){var n;null==(n=this.instance.metrics)||n.histogram(e,t,{unit:"ms",attributes:i({},r),bounds:s})}},Io={},Eo=0,xo=()=>{},To='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',$o="Surveys module not available",Fo="sanitize_properties is deprecated. Use before_send instead",Ro="Invalid value for property_denylist config: ",Oo=["$recording_status","$sdk_debug_recording_script_not_loaded","$sdk_debug_replay_url_trigger_status","$sdk_debug_replay_event_trigger_status","$sdk_debug_replay_linked_flag_trigger_status","$sdk_debug_replay_rrweb_error","$sdk_debug_replay_internal_buffer_length","$sdk_debug_replay_flushed_size"],Mo=["$feature_flag_called","$$heatmap","$snapshot"],Ao=e=>"$"===e.charAt(0)&&!dt(Mo,e),Do=/^[A-Za-z0-9_-]{1,400}$/,Lo=/^fb\.[0-9]+\.[0-9]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?$/,No=/^fb\.[0-9]+\.[0-9]+\.[0-9]+$/,Bo=["token","distinct_id",Ee],Uo="posthog",qo=[...ro].sort()[ro.length-1],Ho=e=>{var t={};return e&&"unset"!==e?("2025-11-30">e||(t.strictMinimumDuration=!0),"2026-05-30">e||(t.canvasCapture={resolutionScale:.6}),"2026-06-25">e||(t.streamNetworkBody=!0),"2026-08-30">e||(t.captureJsonLd=!0),t):t},Go=e=>{var t;return i({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:ns(null==Qe?void 0:Qe.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:xo,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:null!=e?e:"unset",__preview_deferred_init_extensions:!1,__preview_replay_sync_fetch:!0,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:Xe&&yt(null==Xe?void 0:Xe.search)&&-1!==Xe.search.indexOf("__posthog_debug=true")||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,reuseAnonymousId:!1,disable_external_dependency_loading:!1,strict_script_versioning:"fallback",enable_recording_console_log:void 0,secure_cookie:"https:"===(null==Ke||null==(t=Ke.location)?void 0:t.protocol),ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,feature_flag_request_max_retries:1,surveys_request_timeout_ms:1e4,on_request_error(e){Yi.error("Bad HTTP status: "+e.statusCode+" "+e.text)},get_device_id:e=>e,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:He,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:3e3},error_tracking:{},_onCapture:xo},(e=>({rageclick:e&&e>="2026-05-30"?{content_ignorelist:Ns,ignore_text_selection:!0}:!e||"2025-11-30">e||{content_ignorelist:!0},capture_pageview:!e||"2025-05-24">e||"history_change",session_recording:Ho(e),external_scripts_inject_target:e&&e>="2026-01-30"?"head":"body",internal_or_test_user_hostname:e&&e>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:e&&e>="2026-05-30"?250:0,split_storage:!(!e||"2026-05-30">e),detect_google_search_app:!(!e||"2026-05-30">e),disable_capture_url_hashes:!(!e||"2026-06-25">e),cookieWinsOnConflict:!(!e||"unset"===e||"2026-08-29">e)}))(e))},Wo=[["process_person","person_profiles"],["xhr_headers","request_headers"],["cookie_name","persistence_name"],["disable_cookie","disable_persistence"],["__preview_disable_beacon","disable_beacon"],["store_google","save_campaign_params"],["verbose","debug"],["__preview_cookie_wins_on_conflict","cookieWinsOnConflict"]],Vo=e=>{var t={};for(var i of Wo){var s=i[0],r=i[1];mt(e[s])||(t[r]=e[s])}var n=es({},t,e),o=e.__preview_external_dependency_versioned_paths;return mt(o)||(mt(e.strict_script_versioning)&&(n.strict_script_versioning=!!o),yt(o)&&mt(e.asset_host)&&(n.asset_host=o)),pt(e.property_blacklist)&&(mt(e.property_denylist)?n.property_denylist=e.property_blacklist:pt(e.property_denylist)?n.property_denylist=[...e.property_blacklist,...e.property_denylist]:Yi.error(Ro+e.property_denylist)),n},jo=class{constructor(){this.__forceAllowLocalhost=!1}get _forceAllowLocalhost(){return this.__forceAllowLocalhost}set _forceAllowLocalhost(e){Yi.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},zo=(e=class e{_removeExtension(e){if(e){var t=this._extensions.indexOf(e);-1!==t&&this._extensions.splice(t,1)}}_replaceExtension(e,t){return this._removeExtension(e),this._extensions.push(t),null==t.initialize||t.initialize(),t}_inCookielessMode(){return"always"===this.config.cookieless_mode||"on_reject"===this.config.cookieless_mode&&this.consent.isRejected()}_warnIfHistoryAutocaptureMissing(){if(!this._hasWarnedAboutMissingHistoryAutocapture&&this._originalUserConfig&&"capture_pageview"in this._originalUserConfig&&!i({},e.__defaultExtensionClasses,this.config.__extensionClasses).historyAutocapture){var t=this.config.capture_pageview;("history_change"===t||vt(t)&&(t.path||t.search||t.hash&&!this.config.disable_capture_url_hashes))&&(this._hasWarnedAboutMissingHistoryAutocapture=!0,Yi.warn("capture_pageview is set to capture history changes, but the history autocapture extension is not loaded, so only the first pageview of each page load is captured. With the slim bundle, pass __extensionClasses: { historyAutocapture: AnalyticsExtensions.historyAutocapture } from 'posthog-js/dist/extension-bundles', or set capture_pageview: true to capture page loads only."))}}_warnIfVolatileIdentityWithoutStableId(){if(!(this._hasWarnedAboutVolatileIdentity||this.config.reuseAnonymousId||this.config.segment||this._inCookielessMode())){var e,t,i,s="memory"===this.config.persistence||"sessionStorage"===this.config.persistence;(s||this.config.disable_persistence)&&(this._hasStableInitialDistinctId||(s?(e="persistence is set to '"+this.config.persistence+"'",t="memory"===this.config.persistence?"on every page load":"for every new browser tab or window",i="Either set persistence to 'localStorage+cookie', keep this persistence and pass a stable ID through bootstrap.distinctID, or enable reuseAnonymousId."):(e="persistence is disabled (disable_persistence is true)",t="on every page load",i="Either set disable_persistence to false, keep persistence disabled and pass a stable ID through bootstrap.distinctID, or enable reuseAnonymousId."),this._hasWarnedAboutVolatileIdentity=!0,console.warn("[PostHog.js]",e+" but no bootstrap.distinctID was provided. PostHog will mint a new distinct ID "+t+", so calling identify() merges a new ID onto the person each time. A person can then pass the distinct-ID limit and its events stop appearing on person pages and the session tab. "+i)))}}_syncCookielessIdentity(){var e=this.persistence;if(e&&!this._isConsentTransition)if(this._inCookielessMode())"on_reject"===this.config.cookieless_mode&&"$posthog_cookieless"!==this.get_distinct_id()&&(this._sync_opt_out_with_persistence(),this._enterCookielessMode());else if("$posthog_cookieless"===this.get_distinct_id()){this._is_persistence_disabled()||e.load(!0);var t=this.get_distinct_id();if(!t||"$posthog_cookieless"===t){var i=this.config.get_device_id(ps());this.register({distinct_id:i,$device_id:i}),e.set_property(ye,Ue)}this._sync_opt_out_with_persistence()}}get decideEndpointWasHit(){var e,t;return null!==(e=null==(t=this.featureFlags)?void 0:t.hasLoadedFlags)&&void 0!==e&&e}get flagsEndpointWasHit(){var e,t;return null!==(e=null==(t=this.featureFlags)?void 0:t.hasLoadedFlags)&&void 0!==e&&e}constructor(){var t;this._botFilterWarned=!1,this._isPageUnloading=!1,this._isShutdown=!1,this.webPerformance=new jo,this._personProcessingSetOncePropertiesSent=!1,this.version=a.LIB_VERSION,this._sessionRegisteredPropKeys=new Set,this._sessionRegisteredPropertiesStorageKey="",this._internalEventEmitter=new eo,this._extensions=[],this._extensionEventPropertyProducers=[],this._replayDebugPropertiesPaused=!1,this._hasStableInitialDistinctId=!1,this._hasWarnedAboutVolatileIdentity=!1,this._hasWarnedAboutMissingHistoryAutocapture=!1,this._isConsentTransition=!1,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Go(),this.SentryIntegration=Ws,this.sentryIntegration=e=>function(e,t){var i=Gs(e,t);return{name:Hs,processEvent:e=>i(e)}}(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this._initialPageviewCaptured=!1,this._visibilityStateListener=null,this._initialPersonProfilesConfig=null,this._cachedPersonProperties=null,this.scrollManager=new Qn(this),this.pageViewManager=new Vs(this),this.rateLimiter=new Gr(this),this.requestRouter=new po(this),this.consent=new Ds(this),this.externalIntegrations=new yo(this);var i=null!==(t=e.__defaultExtensionClasses)&&void 0!==t?t:{};this.featureFlags=i.featureFlags&&new i.featureFlags(this),this.toolbar=i.toolbar&&new i.toolbar(this),this.surveys=i.surveys&&new i.surveys(this),this.conversations=i.conversations&&new i.conversations(this),this.logs=i.logs&&new i.logs(this),this.metrics=i.metrics&&new i.metrics(this),this.experiments=i.experiments&&new i.experiments(this),this.exceptions=i.exceptions&&new i.exceptions(this),this.people={set:(e,t,i)=>{var s=yt(e)?{[e]:t}:e;this.setPersonProperties(s),null==i||i({})},set_once:(e,t,i)=>{var s=yt(e)?{[e]:t}:e;this.setPersonProperties(void 0,s),null==i||i({})}},this.on("eventCaptured",e=>Yi.info('send "'+(null==e?void 0:e.event)+'"',e))}init(t,i,s){if(s&&s!==Uo){var r,n=null!==(r=Io[s])&&void 0!==r?r:new e;return n._init(t,i,s),Io[s]=n,Io[Uo][s]=n,n}return this._init(t,i,s)}_init(e,t,s){var r,n,o;void 0===t&&(t={});var l,d=yt(e)?e.trim():"";if(!d)return Yi.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return d!==(null==(l=this.config)?void 0:l.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+d+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=Go(t.defaults),t.debug=this._checkLocalStorageForDebug(t.debug),this._originalUserConfig=t,this._triggered_notifs=[],t.person_profiles?this._initialPersonProfilesConfig=t.person_profiles:t.process_person&&(this._initialPersonProfilesConfig=t.process_person);var u=Go(t.defaults),_=Vo(t),c=es({},u,_,{name:s,token:d});vt(u.rageclick)&&vt(_.rageclick)&&(c.rageclick=es({},u.rageclick,_.rageclick)),vt(u.session_recording)&&vt(_.session_recording)&&(c.session_recording=es({},u.session_recording,_.session_recording)),this.set_config(c),this.config.on_xhr_error&&Yi.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=t.disable_compression?void 0:Ir.GZipJS;var h=this._is_persistence_disabled(),p=!this._inCookielessMode();if(this.persistence=new Cr(this.config,h,!0,p),this.sessionPersistence="sessionStorage"===this.config.persistence||"memory"===this.config.persistence?this.persistence:new Cr(i({},this.config,{persistence:"sessionStorage"}),h,!1,p),this._sessionRegisteredPropertiesStorageKey="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties","memory"!==this.config.persistence&&!h&&As._is_supported()){var g=As._parse(this._sessionRegisteredPropertiesStorageKey);pt(g)&&g.forEach(e=>{yt(e)&&this._sessionRegisteredPropKeys.add(e)})}else As._remove(this._sessionRegisteredPropertiesStorageKey);var v=i({},this.persistence.props),f=i({},this.sessionPersistence.props);this.register({$initialization_time:(new Date).toISOString()}),this._requestQueue=new Jn((e,t)=>this._send_retriable_request(e,t),this.config.request_queue_config),this._retryQueue=new Yn(this),this.__request_queue=[];var m=this._inCookielessMode();m||(this.sessionManager=new so(this),this.sessionPropsManager=new Zn(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId((e,t,i)=>{(null!=i&&i.activityTimeout||null!=i&&i.sessionPastMaximumLength||null!=i&&i.crossTabAdoption)&&this._clearSessionRegisteredProps()})),this._enrollFeatureFlags(),this.config.__preview_deferred_init_extensions?(Yi.info("Deferring extension initialization to improve startup performance"),this._extensionInitTimeout=setTimeout(()=>{this._extensionInitTimeout=void 0,this._initExtensions(m)},0)):(Yi.info("Initializing extensions synchronously"),this._initExtensions(m)),a.DEBUG=a.DEBUG||this.config.debug,a.DEBUG&&Yi.info("Starting in debug mode",{this:this,config:t,thisC:i({},this.config),p:v,s:f}),!this.config.identity_distinct_id||null!=(r=t.bootstrap)&&r.distinctID||(t.bootstrap=i({},t.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0}));var y=null==(n=t.bootstrap)?void 0:n.distinctID;if(this._hasStableInitialDistinctId=!!y&&!bt(y),null!=(o=t.bootstrap)&&o.distinctID){var b=t.bootstrap.distinctID,w=this.get_distinct_id(),S=this.persistence.get_property(ye);if(t.bootstrap.isIdentifiedID&&null!=w&&w!==b&&"anonymous"===S)this.identify(b);else if(t.bootstrap.isIdentifiedID&&null!=w&&w!==b&&"identified"===S)Yi.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var P=this.config.get_device_id(ps()),k=t.bootstrap.isIdentifiedID?P:b;this.persistence.set_property(ye,t.bootstrap.isIdentifiedID?qe:Ue),this.register({distinct_id:b,$device_id:k})}}if(m)this.register_once({distinct_id:Ie,$device_id:null},"");else if(!this.get_distinct_id()){var C=this.config.get_device_id(ps());this.register_once({distinct_id:C,$device_id:C},""),this.persistence.set_property(ye,Ue)}return os(Ke,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),os(Ke,"pageshow",e=>{if(this._isPageUnloading=!1,!this._isShutdown){var t;if(e.persisted&&this.persistence){var i=this.persistence.get_property(R),s=this.persistence.get_property(ye);this.persistence.load(),this._processCookieIdentityChange()||i===this.persistence.get_property("distinct_id")&&s===this.persistence.get_property("$user_state")||this._processIdentityChange()}null==(t=this._retryQueue)||t.resume()}}),t.segment?qs(this,()=>this._loaded()):this._loaded(),gt(this.config._onCapture)&&this.config._onCapture!==xo&&(Yi.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",e=>this.config._onCapture(e.event,e))),this.config.ip&&Yi.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||function(){return no.apply(this,arguments)}().then(e=>{e&&this.register({[M]:e})}).catch(xo),this}_isSharedExtension(e){var t=e;return yt(t.name)&>(t.setup)}_enrollExtension(e,t){var i=this;this._isSharedExtension(e)?t.push(r(function*(){try{yield e.setup(i._getBrowserClientAdapter())}catch(t){Yi.error('Failed to set up extension "'+e.name+'"',t);try{yield null==e.dispose?void 0:e.dispose()}catch(t){Yi.error('Failed to dispose extension "'+e.name+'"',t)}}})):this._extensions.push(e)}_enrollFeatureFlags(){var t,i,s,n,o,a,l=this,d=null!==(t=null==(i=this.config.__extensionClasses)?void 0:i.featureFlags)&&void 0!==t?t:null==(s=e.__defaultExtensionClasses)?void 0:s.featureFlags;if(d)if(this.featureFlags&&this.featureFlags instanceof d||(null==(a=this._featureFlagsReloadingUnsubscribe)||a.call(this),this._featureFlagsReloadingUnsubscribe=void 0,this.featureFlags=new d(this)),gt(this.featureFlags.onReloading)&>(this.featureFlags.setup)){if(!this._featureFlagsReloadingUnsubscribe){this._featureFlagsReloadingUnsubscribe=this.featureFlags.onReloading(()=>{this._internalEventEmitter.emit("featureFlagsReloading",!0)});var u=this.featureFlags;r(function*(){try{yield u.setup(l._getBrowserClientAdapter())}catch(t){Yi.error("Failed to set up feature flags",t);var e=l._featureFlagsReloadingUnsubscribe;l._featureFlagsReloadingUnsubscribe=void 0;try{null==e||e()}catch(e){Yi.error("Failed to unsubscribe feature flag reloading",e)}try{yield u.dispose()}catch(e){Yi.error("Failed to dispose feature flags",e)}}})()}}else null==(n=(o=this.featureFlags).initialize)||n.call(o)}_initExtensions(t){var s,r,n,o,a,l,d,u,_=performance.now(),c=i({},e.__defaultExtensionClasses,this.config.__extensionClasses),h=[];c.exceptions&&this._extensions.push(this.exceptions=null!==(s=this.exceptions)&&void 0!==s?s:new c.exceptions(this)),c.historyAutocapture&&this._extensions.push(this.historyAutocapture=new c.historyAutocapture(this)),this._warnIfHistoryAutocaptureMissing(),c.tracingHeaders&&this._extensions.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this._extensions.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!t&&this._extensions.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||h.push(()=>{this.scrollManager.startMeasuringScrollPosition()}),c.autocapture&&this._enrollExtension(this.autocapture=new c.autocapture(this),h),c.surveys&&this._enrollExtension(this.surveys=null!==(r=this.surveys)&&void 0!==r?r:new c.surveys(this),h),c.logs&&this._enrollExtension(this.logs=null!==(n=this.logs)&&void 0!==n?n:new c.logs(this),h),c.metrics&&this._extensions.push(this.metrics=null!==(o=this.metrics)&&void 0!==o?o:new c.metrics(this)),c.conversations&&this._extensions.push(this.conversations=null!==(a=this.conversations)&&void 0!==a?a:new c.conversations(this)),c.productTours&&this._extensions.push(this.productTours=new c.productTours(this)),c.heatmaps&&this._extensions.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this._extensions.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this._extensions.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this._extensions.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Bs)),c.toolbar&&this._extensions.push(this.toolbar=null!==(l=this.toolbar)&&void 0!==l?l:new c.toolbar(this)),c.experiments&&this._extensions.push(this.experiments=null!==(d=this.experiments)&&void 0!==d?d:new c.experiments(this)),c.webMCP&&this._extensions.push(this.webMCP=null!==(u=this.webMCP)&&void 0!==u?u:new c.webMCP(this)),this._extensions.forEach(e=>{e.initialize&&h.push(()=>{null==e.initialize||e.initialize()})}),h.push(()=>{if(this._pendingRemoteConfig){var e=this._pendingRemoteConfig;this._pendingRemoteConfig=void 0,this._extensions.forEach(t=>null==t.onRemoteConfig?void 0:t.onRemoteConfig(e))}}),this._processInitTaskQueue(h,_)}_processInitTaskQueue(e,t){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-t>=30&&e.length>0)return void(this._extensionInitTimeout=setTimeout(()=>{this._extensionInitTimeout=void 0,this._processInitTaskQueue(e,t)},0));var i=e.shift();if(i)try{i()}catch(e){Yi.error("Error initializing extension:",e)}}var s=Math.round(performance.now()-t);this.register_for_session({[xe]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Te]:s}),this.config.__preview_deferred_init_extensions&&Yi.info("PostHog extensions initialized ("+s+"ms)")}_onRemoteConfig(e){if(!Qe||!Qe.body)return Yi.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this._onRemoteConfig(e)},500);if(this.config.__preview_deferred_init_extensions&&(this._pendingRemoteConfig=e),this._lastRemoteConfig=e,this.compression=void 0,e.ok){var t,i=e.config;i.supportedCompression&&!this.config.disable_compression&&(this.compression=dt(i.supportedCompression,Ir.GZipJS)?Ir.GZipJS:dt(i.supportedCompression,Ir.Base64)?Ir.Base64:void 0),null!=(t=i.analytics)&&t.endpoint&&(this.analyticsDefaultEndpoint=i.analytics.endpoint)}this.set_config({person_profiles:this._initialPersonProfilesConfig?this._initialPersonProfilesConfig:He}),this._internalEventEmitter.emit("extensionsRemoteConfig",e),this._extensions.forEach(t=>null==t.onRemoteConfig?void 0:t.onRemoteConfig(e))}_loaded(){try{this.config.loaded(this)}catch(e){Yi.critical("`loaded` function failed",e)}if(this._start_queue_if_opted_in(),this.config.internal_or_test_user_hostname&&null!=Xe&&Xe.hostname){var e=Xe.hostname,t=this.config.internal_or_test_user_hostname;("string"==typeof t?e===t:t.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this._inCookielessMode())&&this._captureInitialPageview()},1),this._remoteConfigLoader=new Vr(this),this._remoteConfigLoader.load()}_start_queue_if_opted_in(){var e;this.is_capturing()&&this.config.request_batching&&(null==(e=this._requestQueue)||e.enable())}_dom_loaded(){this.is_capturing()&&Xi(this.__request_queue,e=>this._send_retriable_request(e)),this.__request_queue=[],this._start_queue_if_opted_in()}_handle_unload(){var e,t,i,s,r;this._isPageUnloading=!0,null==(e=this.surveys)||null==e.handlePageUnload||e.handlePageUnload(),null==(t=this.metrics)||t.flush("sendBeacon"),this.config.request_batching?(this._shouldCapturePageleave()&&this.capture(Ve),null==(i=this.logs)||i.flushLogs("sendBeacon"),null==(s=this._requestQueue)||s.unload(),null==(r=this._retryQueue)||r.unload()):this._shouldCapturePageleave()&&this.capture(Ve,null,{transport:"sendBeacon"})}_send_request(e){Kn(this,e)}_send_retriable_request(e,t){this._retryQueue?this._retryQueue.retriableRequest(e,t):this._send_request(t?i({},e,{transport:t}):e)}_execute_array(e){Eo++;try{var t,i=[],s=[],r=[];Xi(e,e=>{if(e)if(pt(t=e[0]))r.push(e);else if(gt(e))try{e.call(this)}catch(t){Yi.error("Error executing queued PostHog call",e,t)}else pt(e)&&"alias"===t?i.push(e):pt(e)&&-1!==t.indexOf("capture")&>(this[t])?r.push(e):s.push(e)});var n=function(e,t){Xi(e,function(e){try{if(pt(e[0])){var i=t;Zi(e,function(e){i=i[e[0]].apply(i,e.slice(1))})}else t[e[0]].apply(t,e.slice(1))}catch(t){Yi.error("Error executing queued PostHog call",e,t)}})};n(i,this),n(s,this),n(r,this)}finally{Eo--}}push(t){if(Eo>0&&pt(t)&&yt(t[0])){var i=e.prototype[t[0]];gt(i)&&i.apply(this,t.slice(1))}else this._execute_array([t])}get _facebookClickIdChannel(){return{property:L,persistenceKey:N,cookieName:"_fbc",pattern:Lo,register:(e,t)=>{var i;return null==(i=this.persistence)?void 0:i.register({[N]:{value:e,delivered:t}})},unregister:()=>{var e;return null==(e=this.persistence)?void 0:e.unregister(N)}}}get _facebookBrowserIdChannel(){return{property:B,persistenceKey:U,cookieName:"_fbp",pattern:No,register:(e,t)=>{var i;return null==(i=this.persistence)?void 0:i.register({[U]:{value:e,delivered:t}})},unregister:()=>{var e;return null==(e=this.persistence)?void 0:e.unregister(U)}}}_getPersistedMetaIdentifier(e){var t,i=null==(t=this.persistence)?void 0:t.get_property(e.persistenceKey);return yt(i)&&e.pattern.test(i)?{value:i,delivered:!1}:vt(i)&&yt(i.value)&&e.pattern.test(i.value)?{value:i.value,delivered:!0===i.delivered}:void 0}_storeMetaIdentifier(e,t,i){return t===(null==i?void 0:i.value)?{value:t,pending:!i.delivered}:(e.register(t,!1),{value:t,pending:!0})}_readMetaCookie(e){if(this.config.save_campaign_params&&!this._inCookielessMode()){var t=ds(e.cookieName);return yt(t)&&e.pattern.test(t)?t:void 0}}_updateFacebookClickId(e,t,i,s){if(this.persistence){var r=this._facebookClickIdChannel,n=this._getPersistedMetaIdentifier(r);if(!s){if(i)return yt(t)&&Lo.test(t)?this._storeMetaIdentifier(r,t,n):void r.unregister();var o=yt(e)&&Do.test(e)?e:void 0,a=this._readMetaCookie(r);return a&&((e,t,i)=>{var s=e.split(".");if(t)return s[3]===t;if(!i)return!0;var r=i.value.split(".");return s[3]===r[3]||Number(s[2])>Number(r[2])})(a,o,n)?this._storeMetaIdentifier(r,a,n):o?(null==n?void 0:n.value.split(".")[3])===o?{value:n.value,pending:!n.delivered}:this._storeMetaIdentifier(r,"fb.1."+Date.now()+"."+o,n):n?{value:n.value,pending:!n.delivered}:void 0}r.unregister()}}_updateFacebookBrowserId(e,t,i){if(this.persistence){var s=this._facebookBrowserIdChannel,r=this._getPersistedMetaIdentifier(s);if(!i){if(t)return yt(e)&&No.test(e)?this._storeMetaIdentifier(s,e,r):void s.unregister();var n=this._readMetaCookie(s);return n?this._storeMetaIdentifier(s,n,r):r?{value:r.value,pending:!r.delivered}:void 0}s.unregister()}}_markMetaIdentifiersDelivered(e){if(this.persistence){var t=e=>{var t=e.value,i=this._getPersistedMetaIdentifier(e.channel);return(null==i?void 0:i.value)===t&&!i.delivered},i=e.filter(t);i.length&&(this.persistence.refreshMetaIdentifiers(),i.filter(t).forEach(e=>e.channel.register(e.value,!0)))}}capture(e,t,s){var r,n,o,a,l,d,u,_;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this._requestQueue)if(this.is_capturing())if(!mt(e)&&yt(e)){if(this._syncCookielessIdentity(),"$snapshot"!==e||!this._inCookielessMode()){var c=!this.config.opt_out_useragent_filter&&this._is_bot();if(c&&!this.config.__preview_capture_bot_pageviews)return this._botFilterWarned||(this._botFilterWarned=!0,console.warn('[PostHog.js] Events are being dropped because the user agent looks like a bot (first dropped event: "'+e+'"). Set `opt_out_useragent_filter: true` to capture them, e.g. in end-to-end tests. Note that logs from `captureLog` are not subject to this filter.')),void Yi.info('Event "'+e+'" was not captured because the user agent looks like a bot. Set `opt_out_useragent_filter: true` to capture it.');var h=null!=s&&s.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(null==h||!h.isRateLimited){var p;null!=t&&t.$current_url&&!yt(null==t?void 0:t.$current_url)&&(Yi.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),null==t||delete t.$current_url),"$exception"!==e||null!=s&&s._originatedFromCaptureException||Yi.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&(p=this.sessionPersistence.update_campaign_params()),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var g=new Date,v=(null==s?void 0:s.timestamp)||g,f=Li(null==s?void 0:s.uuid,ps),m={uuid:f,event:e,properties:this.calculateEventProperties(e,t||{},v,f)};"$pageview"===e&&this.config.__preview_capture_bot_pageviews&&c&&(m.event="$bot_pageview",m.properties.$browser_type="bot"),h&&(m.properties.$lib_rate_limit_remaining_tokens=h.remainingTokens);var y="$feature_flag_called"===e&&!1===m.properties.$feature_flag_has_experiment&&!0===this.get_property("$minimal_flag_called_events");null!=s&&s.$set&&!y&&(m.$set=null==s?void 0:s.$set);var b=vt(null==t?void 0:t.$set)?t.$set:void 0,w=pt(null==t?void 0:t.$unset)?t.$unset:[],S=(null==s?void 0:s.$unset)||[],P=e=>{var t,i=!(null==s||!s.$set)&&e in s.$set;return{hasProvided:i||!!b&&e in b,provided:i?null==s||null==(t=s.$set)?void 0:t[e]:null==b?void 0:b[e],unset:-1!==w.indexOf(e)||-1!==S.indexOf(e)}};this.persistence.refreshMetaIdentifiersBeforeCapture();var k=P(L),C=P(B),I=[{channel:this._facebookClickIdChannel,hasProvided:k.hasProvided,update:this._updateFacebookClickId(null==(r=p)?void 0:r.fbclid,k.provided,k.hasProvided,k.unset)},{channel:this._facebookBrowserIdChannel,hasProvided:C.hasProvided,update:this._updateFacebookBrowserId(C.provided,C.hasProvided,C.unset)}];for(var E of I){var x=E.channel,T=E.update;T&&!0===m.properties.$process_person_profile&&T.pending&&!E.hasProvided&&!y&&(m.$set=i({[x.property]:T.value},m.$set))}var F=null==s?void 0:s.$unset;F&&(m.$unset=F);var R=y?void 0:this._calculate_set_once_properties(null==s?void 0:s.$set_once,e!==ze,e===je);if(R&&(m.$set_once=R),null!=s&&s._noTruncate||(l=this.config.properties_string_max_length,d=m,u=e=>yt(e)?e.slice(0,l):e,_=new Set,m=function e(t,i){if(t!==Object(t))return u?u(t):t;if(!_.has(t)){var s;if(_.add(t),pt(t))s=[],Xi(t,t=>{s.push(e(t))});else{var r={};Zi(xt(t)?ss(t):t,(t,i)=>{_.has(t)||(r[i]=e(t,i))}),s=r}return s}}(d)),m.timestamp=v,mt(null==s?void 0:s.timestamp)||(m.properties.$event_time_override_provided=!0,m.properties.$event_time_override_system_time=g),y&&(m.properties=function(e,t){void 0===t&&(t=[]);var i={},s=t=>{void 0!==e[t]&&(i[t]=e[t])};return qi.forEach(s),t.forEach(s),i}(m.properties,Bo)),e===Ar.DISMISSED||e===Ar.SENT){var O=null==t?void 0:t[Dr.SURVEY_ID],M=null==t?void 0:t[Dr.SURVEY_ITERATION];(e=>{try{var t=(e=>((e,t)=>"seenSurvey_"+function(e){return e.current_iteration&&e.current_iteration>0?e.id+"_"+e.current_iteration:e.id}(t))(0,e))(e);if(localStorage.getItem(t))return;localStorage.setItem(t,"true")}catch(e){go.error("Failed to persist survey seen state",e)}})({id:O,current_iteration:M}),m.$set=i({},m.$set,{[oo({id:O,current_iteration:M},e===Ar.SENT?"responded":"dismissed")]:!0})}else e===Ar.SHOWN&&(m.$set=i({},m.$set,{[Dr.SURVEY_LAST_SEEN_DATE]:(new Date).toISOString()}));if(e===Ur.SHOWN){var A=null==t?void 0:t[qr.TOUR_TYPE];A&&(m.$set=i({},m.$set,{[qr.TOUR_LAST_SEEN_DATE+"/"+A]:(new Date).toISOString()}))}var D=i({},m.properties.$set,m.$set);if(ft(D)||this.setPersonPropertiesForFlags(D),!St(this.config.before_send)){var N=this._runBeforeSend(m);if(!N)return;(m=N).uuid=Li(m.uuid,ps)}this.sessionRecording&&!this._replayDebugPropertiesPaused&&Ao(e)&&(this._replayDebugPropertiesPaused=!0,setTimeout(()=>this._replayDebugPropertiesPaused=!1,3e4));var U=[];I.forEach(e=>{var t,i,s,r=e.channel,n=e.update,o=null!==(t=null==(i=m.$set)?void 0:i[r.property])&&void 0!==t?t:vt(null==(s=m.properties)?void 0:s.$set)?m.properties.$set[r.property]:void 0;null!=n&&n.pending&&o===n.value&&U.push({channel:r,value:n.value})}),this._internalEventEmitter.emit("eventCaptured",m);var q,H,G=null!==(n=null==s?void 0:s._url)&&void 0!==n?n:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),W="recordings"===(null==s?void 0:s._batchKey)||/\/s\/(?:\?|$)/.test(G),V=i({method:"POST",url:G,data:m,compression:"best-available",preferSyncCompression:null==s?void 0:s.send_instantly,timestampMode:W?"body":"capture-body",batchKey:null==s?void 0:s._batchKey},W&&null!=(o=m.properties)&&o.$session_id?{batchGroup:m.properties.$session_id+(m.properties.$window_id?"-"+m.properties.$window_id:"")}:{},null!=s&&s.transport?{transport:s.transport}:{},U.length?{fireCallbackOnDrop:!0,callback:e=>{e.statusCode>=200&&300>e.statusCode&&this._markMetaIdentifiersDelivered(U)}}:{});return!this.config.request_batching||s&&(null==s||!s._batchKey)||null!=s&&s.send_instantly?(!V.transport&&!V.callback&&ft(null!==(q=this.config.request_headers)&&void 0!==q?q:{})&&this._isPageUnloading&&(H="sendBeacon"),this._send_retriable_request(V,H)):this._requestQueue.enqueue(V),null==(a=this.featureFlags)||a.sendFlagCallsPendingCapture(),m}Yi.critical("This capture call is ignored due to client rate limiting.")}}else Yi.error("No event name provided to posthog.capture");else Yi.info('Event "'+e+'" was not captured because capturing is disabled (opted out or consent pending).');else Yi.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",t=>e(t.event,t))}getExtension(e){var t;return null==(t=this._browserClientAdapter)?void 0:t.getExtension(e)}_getBrowserClientAdapter(){var e;return null!==(e=this._browserClientAdapter)&&void 0!==e?e:this._browserClientAdapter=new Co(this)}_registerExtensionEventProperties(e){this._extensionEventPropertyProducers.push(e);var t=!0;return()=>{if(t){t=!1;var i=this._extensionEventPropertyProducers.indexOf(e);-1!==i&&this._extensionEventPropertyProducers.splice(i,1)}}}_processCookieIdentityChange(e){var t;return void 0===e&&(e=!0),!(null==(t=this.persistence)||!t.consumeCookieIdentityChange()||(this._processIdentityChange(e),0))}_processIdentityChange(e){var t,i,s;void 0===e&&(e=!0),this._cachedPersonProperties=null,"anonymous"===(null==(t=this.persistence)?void 0:t.get_property("$user_state"))&&(null==(s=this.sessionPersistence)||s.clear(),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys()),null==(i=this.featureFlags)||i.reset(),e&&this.reloadFeatureFlags()}calculateEventProperties(e,t,s,r,n){if(s=s||new Date,!this.persistence||!this.sessionPersistence)return t;this._syncCookielessIdentity(),this.persistence.syncCookieProperties(),this._processCookieIdentityChange();var a=n?void 0:this.persistence.remove_event_timer(e),l=i({},t);if(l.token=this.config.token,l.$config_defaults="latest"===this.config.defaults?qo:this.config.defaults,this._inCookielessMode()&&(l[Ee]=!0),"$snapshot"===e){var d=i({},this.persistence.properties(),this.sessionPersistence.properties());return l.distinct_id=d.distinct_id,(!yt(l.distinct_id)&&!Pt(l.distinct_id)||bt(l.distinct_id))&&Yi.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),l}var u,_=function(e,t,i,s){var r,n,a,l;if(void 0===s&&(s=!1),!st)return{};var d,u=e?[...tr,...t||[]]:[],_=function(e){for(var t=0;Ri.length>t;t++){var i=Ri[t],s=i[1],r=i[0].exec(e),n=r&&(gt(s)?s(r,e):s);if(n)return n}return["",""]}(st),c=_[0],h=_[1],p=function(e){for(var t=0;Ai.length>t;t++){var i,s=Ai[t],r=s[1],n=s[2],o=e.match(s[0]);if(o)return[r,(null==(i=n&&e.match(n)||o)?void 0:i[1])||""]}return["",""]}(st),g=p[0],v=p[1],f=null!=(d="u">typeof navigator?navigator:void 0)&&d.brave?{brave:!0}:{},m={};mt(i)||(m.detectGoogleSearchApp=i);var y={},b=null==(r=navigator)||null==(r=r.userAgentData)?void 0:r.platform,w=null==(n=navigator)?void 0:n.maxTouchPoints,S=null==Ke||null==(a=Ke.screen)?void 0:a.width,P=null==Ke||null==(l=Ke.screen)?void 0:l.height,k=null==Ke?void 0:Ke.devicePixelRatio;mt(b)||(y.userAgentDataPlatform=b),mt(w)||(y.maxTouchPoints=w),mt(S)||(y.screenWidth=S),mt(P)||(y.screenHeight=P),mt(k)||(y.devicePixelRatio=k);var C,I,E,x,T,F,R,O,M=es(is({$os:c,$os_version:h,$browser:Ti(st,navigator.vendor,f,m),$webview_app:g,$webview_app_version:v,$device:Oi(st),$device_type:(I=st,E=y,O=Oi(I),O===Ut||O===Bt||"Kobo"===O||"Kindle Fire"===O||O===li?Nt:O===Zt||O===ti||O===ei||O===ai?"Console":O===qt?"Wearable":O?Dt:"Android"===(null==E?void 0:E.userAgentDataPlatform)&&(null!==(x=null==E?void 0:E.maxTouchPoints)&&void 0!==x?x:0)>0?600>Math.min(null!==(T=null==E?void 0:E.screenWidth)&&void 0!==T?T:0,null!==(F=null==E?void 0:E.screenHeight)&&void 0!==F?F:0)/(null!==(R=null==E?void 0:E.devicePixelRatio)&&void 0!==R?R:1)?Dt:Nt:"Desktop"),$timezone:Ys(),$timezone_offset:cr()}),{$current_url:er(s?Bi(null==Xe?void 0:Xe.href):null==Xe?void 0:Xe.href,u,sr),$host:null==Xe?void 0:Xe.host,$pathname:null==Xe?void 0:Xe.pathname,$raw_user_agent:st.length>1e3?st.substring(0,997)+"...":st,$browser_version:Fi(st,navigator.vendor,f,m),$browser_language:ar(),$browser_language_prefix:(C=ar(),"string"==typeof C?C.split("-")[0]:void 0),$screen_height:null==Ke?void 0:Ke.screen.height,$screen_width:null==Ke?void 0:Ke.screen.width,$viewport_height:null==Ke?void 0:Ke.innerHeight,$viewport_width:null==Ke?void 0:Ke.innerWidth,$lib:o.LIB_NAME,$lib_version:o.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return o.SDK_DIST_CHANNEL&&(M.$sdk_dist_channel=o.SDK_DIST_CHANNEL),M}(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var c=this.sessionManager.checkAndGetSessionAndWindowId(n,s.getTime(),!0),h=c.windowId;l.$session_id=c.sessionId,l.$window_id=h}this.sessionPropsManager&&es(l,this.sessionPropsManager.getSessionProps());try{var p;if(this.sessionRecording){var g=this.sessionRecording.sdkDebugProperties,v=!this._replayDebugPropertiesPaused&&Ao(e);for(var f in g)(v||dt(Oo,f))&&(l[f]=g[f])}l.$sdk_debug_retry_queue_size=null==(p=this._retryQueue)?void 0:p.length}catch(e){l.$sdk_debug_error_capturing_properties=String(e)}if(this.requestRouter.region===uo&&(l.$lib_custom_api_host=this.config.api_host),u="$pageview"!==e||n?"$pageleave"!==e||n?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(s):this.pageViewManager.doPageView(s,r),l=es(l,u),"$pageview"===e&&Qe&&(l.title=Qe.title),!mt(a)){var m=s.getTime()-a;l.$duration=parseFloat((m/1e3).toFixed(3))}st&&this.config.opt_out_useragent_filter&&(l.$browser_type=this._is_bot()?"bot":"browser");var y=this.persistence.properties(),b=this.sessionPersistence.properties(),w=l.$groups,S=y.$groups;vt(w)&&!ft(w)&&(l.$groups=i({},vt(S)?S:{},w)),Zi(["$referrer","$referring_domain"],e=>{e in y&&delete b[e]});var P={};if(this._extensionEventPropertyProducers.length>0)for(var k of this._extensionEventPropertyProducers.slice())try{es(P,k())}catch(e){Yi.error("Failed to produce browser extension event properties",e)}(l=es({},_,y,b,i({},P,l))).$is_identified=this._isIdentified(),pt(this.config.property_denylist)?Zi(this.config.property_denylist,function(e){delete l[e]}):Yi.error(Ro+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var C=this.config.sanitize_properties;C&&(Yi.error(Fo),l=C(l,e));var I=this._hasPersonProcessing();return l.$process_person_profile=I,I&&!n&&this._requirePersonProcessing("_calculate_event_properties"),l}_calculate_set_once_properties(e,t,i){var s;if(void 0===t&&(t=!0),void 0===i&&(i=!1),!this.persistence||!this._hasPersonProcessing())return e;if(this._personProcessingSetOncePropertiesSent&&!i)return e;var r=es({},this.persistence.get_initial_props(),(null==(s=this.sessionPropsManager)?void 0:s.getSetOnceProps())||{},e||{}),n=this.config.sanitize_properties;return n&&(Yi.error(Fo),r=n(r,"$set_once")),t&&(this._personProcessingSetOncePropertiesSent=!0),ft(r)?void 0:r}register(e,t){var i;null==(i=this.persistence)||i.register(e,t)}register_once(e,t,i){var s;null==(s=this.persistence)||s.register_once(e,t,i)}register_for_session(e){var t,i;null==(t=this.persistence)||t.syncCookieProperties(),this._processCookieIdentityChange(),null==(i=this.sessionPersistence)||i.register(e),Object.keys(e).forEach(e=>this._sessionRegisteredPropKeys.add(e)),this._persistSessionRegisteredPropKeys()}unregister(e){var t;null==(t=this.persistence)||t.unregister(e)}unregister_for_session(e){var t;null==(t=this.sessionPersistence)||t.unregister(e),this._sessionRegisteredPropKeys.delete(e),this._persistSessionRegisteredPropKeys()}_register_single(e,t){this.register({[e]:t})}_clearSessionRegisteredProps(){this._sessionRegisteredPropKeys.forEach(e=>{var t;null==(t=this.sessionPersistence)||t.unregister(e)}),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys()}_persistSessionRegisteredPropKeys(){var e;if(this._sessionRegisteredPropertiesStorageKey)if("memory"===this.config.persistence||null!=(e=this.sessionPersistence)&&e._disabled||!As._is_supported())As._remove(this._sessionRegisteredPropertiesStorageKey);else{var t=[];this._sessionRegisteredPropKeys.forEach(e=>t.push(e)),t.length>0?As._set(this._sessionRegisteredPropertiesStorageKey,t):As._remove(this._sessionRegisteredPropertiesStorageKey)}}getFeatureFlag(e,t){var i;return null==(i=this.featureFlags)?void 0:i.getFeatureFlag(e,t)}getFeatureFlagPayload(e){var t;return null==(t=this.featureFlags)?void 0:t.getFeatureFlagPayload(e)}getFeatureFlagResult(e,t){var i;return null==(i=this.featureFlags)?void 0:i.getFeatureFlagResult(e,t)}getAllFeatureFlags(){var e,t;return null!==(e=null==(t=this.featureFlags)?void 0:t.getAllFeatureFlags())&&void 0!==e?e:[]}isFeatureEnabled(e,t){var i,s;return null!==(i=null==(s=this.featureFlags)?void 0:s.isFeatureEnabled(e,t))&&void 0!==i?i:null==t?void 0:t.defaultValue}reloadFeatureFlags(){var e;null==(e=this.featureFlags)||e.reloadFeatureFlags()}updateFlags(e,t,i){var s;null==(s=this.featureFlags)||s.updateFlags(e,t,i)}updateEarlyAccessFeatureEnrollment(e,t,i){var s;null==(s=this.featureFlags)||s.updateEarlyAccessFeatureEnrollment(e,t,i)}getEarlyAccessFeatures(e,t,i){var s;return void 0===t&&(t=!1),null==(s=this.featureFlags)?void 0:s.getEarlyAccessFeatures(e,t,i)}on(e,t){return this._internalEventEmitter.on(e,t)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:$o}),()=>{})}onSessionId(e){var t,i;return null!==(t=null==(i=this.sessionManager)?void 0:i.onSessionId(e))&&void 0!==t?t:()=>{}}getSurveys(e,t){void 0===t&&(t=!1),this.surveys?this.surveys.getSurveys(e,t):e([],{isLoaded:!1,error:$o})}getActiveMatchingSurveys(e,t){void 0===t&&(t=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,t):e([],{isLoaded:!1,error:$o})}onActiveMatchingSurveysChanged(e){return this.surveys?this.surveys.onActiveMatchingSurveysChanged(e):(e([],{isLoaded:!1,error:$o}),()=>{})}renderSurvey(e,t){var i;null==(i=this.surveys)||i.renderSurvey(e,t)}displaySurvey(e,t){var i;void 0===t&&(t=vo),null==(i=this.surveys)||i.displaySurvey(e,t)}cancelPendingSurvey(e){var t;null==(t=this.surveys)||t.cancelPendingSurvey(e)}canRenderSurvey(e){var t,i;return null!==(t=null==(i=this.surveys)?void 0:i.canRenderSurvey(e))&&void 0!==t?t:{visible:!1,disabledReason:$o}}canRenderSurveyAsync(e,t){var i,s;return void 0===t&&(t=!1),null!==(i=null==(s=this.surveys)?void 0:s.canRenderSurveyAsync(e,t))&&void 0!==i?i:Promise.resolve({visible:!1,disabledReason:$o})}_validateIdentifyId(e){return!e||bt(e)?(Yi.critical("Unique user id has not been set in posthog.identify"),!1):"$posthog_cookieless"===e?(Yi.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(Yi.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,t,i){if(!this.__loaded||!this.persistence)return Yi.uninitializedWarning("posthog.identify");if(Pt(e)&&(e=e.toString(),Yi.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this._validateIdentifyId(e)&&this._requirePersonProcessing("posthog.identify")){this._syncCookielessIdentity();var s=this.get_distinct_id(),r=this.persistence.syncCookieProperties()&&this.get_distinct_id()!==s,n=this._processCookieIdentityChange(!1),o=this.persistence._beginCookieSyncSuppression(),a=!1;try{var l=this.get_distinct_id();this.register({$user_id:e}),this.get_property("$device_id")||this.register_once({$had_persisted_distinct_id:!0,$device_id:l},""),e!==l&&e!==this.get_property("__alias")&&(this.unregister(A),this.register({distinct_id:e}));var d=(this.persistence.get_property("$user_state")||"anonymous")===Ue,u=e!==l,_=!u&&d;if(u&&d){var c,h=this.config.reuseAnonymousId?{distinct_id:e}:{distinct_id:e,$anon_distinct_id:l};this.persistence.set_property(ye,qe),this.setPersonPropertiesForFlags({$set:t||{},$set_once:i||{}},!1),this.config.cookieWinsOnConflict&&this.persistence._publishSuppressedCookieSnapshot(),this.capture("$identify",h,{$set:t||{},$set_once:i||{}})&&(this._cachedPersonProperties=ao(e,t,i)),null==(c=this.featureFlags)||c.setAnonymousDistinctId(this.config.reuseAnonymousId?void 0:l)}else if(_){this.persistence.set_property(ye,qe);var p=t||{},g=i||{};this.setPersonPropertiesForFlags({$set:p,$set_once:g},!1),this.config.cookieWinsOnConflict&&this.persistence._publishSuppressedCookieSnapshot(),this.capture("$set",{$set:p,$set_once:g})&&(this._cachedPersonProperties=ao(e,t,i))}else(t||i)&&this.setPersonProperties(t,i);u||r||n?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(m)):_&&(t||i)&&this.reloadFeatureFlags(),a=!0}finally{o&&this.persistence._endCookieSyncSuppression(a)}}}setPersonProperties(e,t){if((e||t)&&this._requirePersonProcessing("posthog.setPersonProperties")){var i=ao(this.get_distinct_id(),e,t);this._cachedPersonProperties!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:t||{}},!0),this.capture("$set",{$set:e||{},$set_once:t||{}})&&(this._cachedPersonProperties=i)):Yi.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var t,i=(pt(e)?e:[e]).filter(e=>yt(e)&&e.length>0);0!==i.length&&this._requirePersonProcessing("posthog.unsetPersonProperties")&&(null==(t=this.featureFlags)||t.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this._cachedPersonProperties=null)}group(e,t,s){var r;if(e&&t){null==(r=this.persistence)||r.syncCookieProperties(),this._processCookieIdentityChange();var n=this.getGroups(),o=n[e]!==t;if(o&&this.resetGroupPropertiesForFlags(e),this.register({$groups:i({},n,{[e]:t})}),(o||s)&&this._hasPersonProcessing()){var a={$group_type:e,$group_key:t};s&&(a.$group_set=s),this.capture(ze,a)}s&&this.setGroupPropertiesForFlags({[e]:s}),o&&!s&&this.reloadFeatureFlags()}else Yi.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,t){var i;void 0===t&&(t=!0),null==(i=this.featureFlags)||i.setPersonPropertiesForFlags(e,t)}resetPersonPropertiesForFlags(e){var t;void 0===e&&(e=!0),null==(t=this.featureFlags)||t.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,t){var i;void 0===t&&(t=!0),this._requirePersonProcessing("posthog.setGroupPropertiesForFlags")&&(null==(i=this.featureFlags)||i.setGroupPropertiesForFlags(e,t))}resetGroupPropertiesForFlags(e){var t;null==(t=this.featureFlags)||t.resetGroupPropertiesForFlags(e)}reset(e){var t=Ct(e)?e:null==e?void 0:e.resetDeviceID,i=Ct(e)||null==e?void 0:e.bootstrap;this._reset(t,!1,i)}_reset(e,t,s){var r,n,o,a,l;if(void 0===t&&(t=!1),Yi.info("reset"),!this.__loaded)return Yi.uninitializedWarning("posthog.reset");var d=null==s?void 0:s.sessionID;this.config.bootstrap=s||(null==(r=this._originalUserConfig)?void 0:r.bootstrap)||{},null==(n=this.featureFlags)||null==n.updateConfig||n.updateConfig(this.config,this._shouldDisableFlags());var u=this.get_property(O),_=this.get_property(M),c=this.get_property(Q);null==(o=this.sessionRecording)||o.flushBeforeIdentityReset();var h=this.is_capturing();t||this.consent.reset(),t||!h||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after.");var p=null==(a=this.persistence)||null==a._beginCookieSyncSuppression?void 0:a._beginCookieSyncSuppression(),g=this._isConsentTransition;this._isConsentTransition=g||t;var v=!1;try{var f,m,y,b,w,S,P,k,C,I,E,x,T;if(null==(f=this.persistence)||f.clear(),null==(m=this.sessionPersistence)||m.clear(),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys(),mt(c)||null==(y=this.persistence)||y.register({[Q]:c}),null==(b=this.surveys)||b.reset(),null==(w=this.featureFlags)||w.reset(),null==(S=this.conversations)||S.reset(),null==(P=this.logs)||P.reset(),null==(k=this.metrics)||k.reset(),null==(C=this.persistence)||C.set_property(ye,Ue),null==(I=this.sessionManager)||I.resetSessionId(),this._cachedPersonProperties=null,"always"===this.config.cookieless_mode)this.register_once({distinct_id:Ie,$device_id:null},"");else{var F=this.config.get_device_id(ps());this.register_once({distinct_id:F,$device_id:e?F:u},""),e||mt(_)||this.register({[M]:_})}if(this.register({$last_posthog_reset:(new Date).toISOString()},1),s)if(s.distinctID&&!this._inCookielessMode()&&(null==(T=this.persistence)||T.set_property(ye,s.isIdentifiedID?qe:Ue),this.register({distinct_id:s.distinctID})),null==(E=this.featureFlags)||E.initialize(),!(St(d)||null!=(x=this.sessionManager)&&x.setBootstrapSessionId(d,!0))){var R=i({},s);delete R.sessionID,this.config.bootstrap=R}delete this.config.identity_distinct_id,delete this.config.identity_hash,delete this.config.identity_claims,v=!0}finally{var A;this._isConsentTransition=g,p&&(null==(A=this.persistence)||null==A._endCookieSyncSuppression||A._endCookieSyncSuppression(v))}this._lastRemoteConfig&&(null==(l=this.conversations)||l.onRemoteConfig(this._lastRemoteConfig)),this.reloadFeatureFlags()}shutdown(e){var t=this;return r(function*(){if(t.__loaded){t._isShutdown=!0,clearTimeout(t._extensionInitTimeout),t._extensionInitTimeout=void 0;var e=t._featureFlagsReloadingUnsubscribe;for(var i of(t._featureFlagsReloadingUnsubscribe=void 0,[()=>{var e;return null==(e=t.sessionRecording)?void 0:e.dispose()},()=>{var e;return null==(e=t.logs)?void 0:e.flushLogs("sendBeacon")},()=>{var e;return null==(e=t.metrics)?void 0:e.flush("sendBeacon")},()=>{var e;return null==(e=t.metrics)?void 0:e.dispose()},()=>{var e;return null==(e=t.logs)?void 0:e.dispose()},()=>{var e;return null==(e=t.surveys)?void 0:e.dispose()},()=>{var e;return null==(e=t.autocapture)?void 0:e.dispose()},()=>null==e?void 0:e(),()=>{var e;return null==(e=t._requestQueue)?void 0:e.unload()},()=>{var e;return null==(e=t._retryQueue)?void 0:e.unload()},()=>{var e;return null==(e=t.featureFlags)?void 0:e.destroy()},()=>{var e;return null==(e=t.persistence)?void 0:e.destroy()},()=>{var e;return null==(e=t.sessionPersistence)?void 0:e.destroy()}]))try{var s=i();s&>(s.then)&&s.then(void 0,e=>{Yi.error("Error during shutdown",e)})}catch(e){Yi.error("Error during shutdown",e)}}else Yi.uninitializedWarning("posthog.shutdown")})()}setIdentity(e,t){var i;delete this.config.identity_claims,this.config.identity_distinct_id=e,this.config.identity_hash=t,this.alias(e),null==(i=this.conversations)||i._onIdentityChanged()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,delete this.config.identity_claims,null==(e=this.conversations)||e._onIdentityCleared()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,t;return null!==(e=null==(t=this.sessionManager)?void 0:t.checkAndGetSessionAndWindowId(!0).sessionId)&&void 0!==e?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var t=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=t.sessionStartTimestamp,s=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+t.sessionId);if(null!=e&&e.withTimestamp&&i){var r,n=null!==(r=e.timestampLookBack)&&void 0!==r?r:10;if(!i)return s;s+="?t="+Math.max(Math.floor(((new Date).getTime()-i)/1e3)-n,0)}return s}alias(e,t){return e===this.get_property("$people_distinct_id")?(Yi.critical("Attempting to create alias for existing People user - aborting."),-2):this._requirePersonProcessing("posthog.alias")?(mt(t)&&(t=this.get_distinct_id()),e!==t?(this._register_single(A,e),this.capture("$create_alias",{alias:e,distinct_id:t})):(Yi.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var t=i({},this.config);if(vt(e)){var s,r,n,o,l,d,u,_,c,h,p,g,v,f;es(this.config,Vo(e));var m=this._is_persistence_disabled();if(this.persistence){var y,b,w,S="sessionStorage"===this.config.persistence||"memory"===this.config.persistence;S&&this.sessionPersistence!==this.persistence&&(null==(b=this.sessionPersistence)||b.remove(),null==(w=this.sessionPersistence)||w.destroy()),this.persistence.update_config(this.config,t,m),S?this.sessionPersistence=this.persistence:this.sessionPersistence===this.persistence?this.sessionPersistence=new Cr(i({},this.config,{persistence:"sessionStorage"}),m,!1):null==(y=this.sessionPersistence)||y.update_config(i({},this.config,{persistence:"sessionStorage"}),i({},t,{persistence:"sessionStorage"}),m)}var P=this._checkLocalStorageForDebug(this.config.debug);Ct(P)&&(this.config.debug=P),Ct(this.config.debug)&&(this.config.debug?(a.DEBUG=!0,ws._is_supported()&&ws._set("ph_debug",!0),Yi.info("set_config",{config:e,oldConfig:t,newConfig:i({},this.config)})):(a.DEBUG=!1,ws._is_supported()&&ws._remove("ph_debug"))),null==(s=this.featureFlags)||null==s.updateConfig||s.updateConfig(this.config,this._shouldDisableFlags()),null==(r=this.exceptionObserver)||r.onConfigChange(),null==(n=this.exceptions)||n.onConfigChange(),null==(o=this.metrics)||o.onConfigChange(),null==(l=this.webMCP)||l.startIfEnabled(),null==(d=this.sessionRecording)||d.startIfEnabledOrStop(),null==(u=this.tracingHeaders)||u.startIfEnabledOrStop(),null==(_=this.autocapture)||_.startIfEnabled(),null==(c=this.heatmaps)||c.startIfEnabled(),("capture_pageview"in e||"disable_capture_url_hashes"in e)&&(null==(h=this.historyAutocapture)||h.startIfEnabledOrStop()),null==(p=this.exceptionObserver)||p.startIfEnabledOrStop(),null==(g=this.deadClicksAutocapture)||g.startIfEnabledOrStop(),null==(v=this.surveys)||v.loadIfEnabled(),this._sync_opt_out_with_persistence(),null==(f=this.externalIntegrations)||f.startIfEnabledOrStop(),!t.segment&&this.config.segment&&this.persistence&&qs(this,xo,!1)}}_overrideSDKInfo(e,t){a.LIB_NAME=e,a.LIB_VERSION=t}startSessionRecording(e){var t,i,s,r,n,o=!0===e,a={sampling:o||!(null==e||!e.sampling),linked_flag:o||!(null==e||!e.linked_flag),url_trigger:o||!(null==e||!e.url_trigger),event_trigger:o||!(null==e||!e.event_trigger)};Object.values(a).some(Boolean)&&(null==(t=this.sessionManager)||t.checkAndGetSessionAndWindowId(),a.sampling&&(null==(i=this.sessionRecording)||i.overrideSampling()),a.linked_flag&&(null==(s=this.sessionRecording)||s.overrideLinkedFlag()),a.url_trigger&&(null==(r=this.sessionRecording)||r.overrideTrigger("url")),a.event_trigger&&(null==(n=this.sessionRecording)||n.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!(null==(e=this.sessionRecording)||!e.started)}captureException(e,t){try{if(!this.exceptions)return;var s=this.exceptions.buildProperties(e,{handled:!0,syntheticException:new Error("PostHog syntheticException")});return this.exceptions.sendExceptionEvent(i({},s,t))}catch(e){return}}addExceptionStep(e,t){var i;null==(i=this.exceptions)||i.addExceptionStep(e,t)}captureLog(e){var t;null==(t=this.logs)||t.captureLog(e)}get logger(){var t,i;return null!==(t=null==(i=this.logs)?void 0:i.logger)&&void 0!==t?t:e._noopLogger}startExceptionAutocapture(e){this.set_config({capture_exceptions:null==e||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var t,i;return null!==(t=null==(i=this.toolbar)?void 0:i.loadToolbar(e))&&void 0!==t&&t}get_property(e){var t;return null==(t=this.persistence)?void 0:t.props[e]}getSessionProperty(e){var t;return null==(t=this.sessionPersistence)?void 0:t.props[e]}toString(){var e,t=null!==(e=this.config.name)&&void 0!==e?e:Uo;return t!==Uo&&(t="posthog."+t),t}_isIdentified(){var e,t;return"identified"===(null==(e=this.persistence)?void 0:e.get_property("$user_state"))||"identified"===(null==(t=this.sessionPersistence)?void 0:t.get_property("$user_state"))}_hasPersonProcessing(){var e,t;return!("never"===this.config.person_profiles||"identified_only"===this.config.person_profiles&&!this._isIdentified()&&ft(this.getGroups())&&(null==(e=this.persistence)||null==(e=e.props)||!e.__alias)&&(null==(t=this.persistence)||null==(t=t.props)||!t.$epp))}_shouldCapturePageleave(){return!0===this.config.capture_pageleave||"if_capture_pageview"===this.config.capture_pageleave&&!!this.config.capture_pageview}createPersonProfile(){this._hasPersonProcessing()||this._requirePersonProcessing("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this._requirePersonProcessing("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}_requirePersonProcessing(e){return"never"===this.config.person_profiles?(Yi.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this._warnIfVolatileIdentityWithoutStableId(),this._register_single(Ce,!0),!0)}_is_persistence_disabled(){if("always"===this.config.cookieless_mode)return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&"on_reject"!==this.config.cookieless_mode)}_sync_opt_out_with_persistence(){var e,t,i,s,r,n=this._is_persistence_disabled();return this.is_capturing()||null==(e=this.logs)||e._onOptOut(),(null==(t=this.persistence)?void 0:t._disabled)!==n&&(null==(i=this.persistence)||i.set_disabled(n)),(null==(s=this.sessionPersistence)?void 0:s._disabled)!==n&&(null==(r=this.sessionPersistence)||r.set_disabled(n)),this._persistSessionRegisteredPropKeys(),n}opt_in_capturing(t){var i,s,r,n;if("always"!==this.config.cookieless_mode){if(this._inCookielessMode()){var o,a,l,d,u,_;null==(o=this.sessionRecording)||o.dispose({discardBufferedEvents:!0}),this._reset(!0,!0),null==(a=this.sessionManager)||a.destroy(),null==(l=this.pageViewManager)||l.destroy(),this.sessionManager=new so(this),this.pageViewManager=new Vs(this),this.persistence&&(this.sessionPropsManager=new Zn(this,this.sessionManager,this.persistence));var c,h=null!==(d=null==(u=this.config.__extensionClasses)?void 0:u.sessionRecording)&&void 0!==d?d:null==(_=e.__defaultExtensionClasses)?void 0:_.sessionRecording;h&&(this.sessionRecording=this._replaceExtension(this.sessionRecording,new h(this)),this._lastRemoteConfig&&(null==(c=this.sessionRecording)||null==c.onRemoteConfig||c.onRemoteConfig(this._lastRemoteConfig)))}var p,g,v=1===this.consent.consent;v&&this._syncCookielessIdentity(),this.consent.optInOut(!0),this._sync_opt_out_with_persistence(),this._start_queue_if_opted_in(),null==(i=this.sessionRecording)||i.startIfEnabledOrStop(),"on_reject"==this.config.cookieless_mode&&(null==(p=this.surveys)||p.loadIfEnabled(),null==(g=this.conversations)||g.loadIfEnabled()),!v&&(mt(null==t?void 0:t.captureEventName)||null!=t&&t.captureEventName)&&this.capture(null!==(s=null==t?void 0:t.captureEventName)&&void 0!==s?s:"$opt_in",null==t?void 0:t.captureProperties,{send_instantly:!0}),null==(r=this.persistence)||r.syncCookieProperties(),this._processCookieIdentityChange(),null==(n=this.featureFlags)||n.sendFlagCallsPendingCapture(),this.config.capture_pageview&&this._captureInitialPageview()}else Yi.warn(To)}opt_out_capturing(){"always"!==this.config.cookieless_mode?(this.consent.optInOut(!1),this._sync_opt_out_with_persistence(),"on_reject"===this.config.cookieless_mode&&this._enterCookielessMode()):Yi.warn(To)}_enterCookielessMode(){var e,t,i=this.sessionRecording;null==i||i.dispose({discardBufferedEvents:!0}),"$posthog_cookieless"!==this.get_distinct_id()&&this._reset(!0,!0),this.register({distinct_id:Ie,$device_id:null}),this._removeExtension(i),this.sessionRecording=void 0,null==(e=this.sessionManager)||e.destroy(),null==(t=this.pageViewManager)||t.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this._captureInitialPageview(),this._start_queue_if_opted_in()}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return 1===e?"granted":0===e?"denied":"pending"}is_capturing(){return!this._isConsentTransition&&("always"===this.config.cookieless_mode||("on_reject"===this.config.cookieless_mode?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing()))}clear_opt_in_out_capturing(){this.consent.reset(),this._sync_opt_out_with_persistence()}_is_bot(){return Ye?function(e,t){if(!e)return!1;var i=e.userAgent;if(i&&Mt(i,t))return!0;try{var s=null==e?void 0:e.userAgentData;if(null!=s&&s.brands&&s.brands.some(e=>Mt(null==e?void 0:e.brand,t)))return!0}catch(e){}return!!e.webdriver}(Ye,this.config.custom_blocked_useragents):void 0}_captureInitialPageview(){Qe&&("visible"===Qe.visibilityState?this._initialPageviewCaptured||(this._initialPageviewCaptured=!0,this.capture(We,{title:Qe.title},{send_instantly:!0}),this._visibilityStateListener&&(Qe.removeEventListener(P,this._visibilityStateListener),this._visibilityStateListener=null)):this._visibilityStateListener||(this._visibilityStateListener=this._captureInitialPageview.bind(this),os(Qe,P,this._visibilityStateListener)))}debug(e){!1===e?(null==Ke||Ke.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(null==Ke||Ke.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}_shouldDisableFlags(){var e=this._originalUserConfig||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:!1!==this.config.advanced_disable_flags?!!this.config.advanced_disable_flags:!0===this.config.advanced_disable_decide?(Yi.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):function(e,t,i,s,r){var n=t in e&&!St(e[t]),o=i in e&&!St(e[i]);return n?e[t]:!!o&&(r&&r.warn("Config field '"+i+"' is deprecated. Please use '"+t+"' instead. The old field will be removed in a future major version."),e[i])}(e,"advanced_disable_flags","advanced_disable_decide",0,Yi)}_runBeforeSend(e){var t;if(St(this.config.before_send))return e;var i=Object.keys(null!==(t=e.properties)&&void 0!==t?t:{}).filter(Et),s=pt(this.config.before_send)?this.config.before_send:[this.config.before_send],r=e;for(var n of s)try{if(r=n(r),St(r)){var o="Event '"+e.event+"' was rejected in beforeSend function";return It(e.event)?Yi.warn(o+". This can cause unexpected behavior."):Yi.info(o),null}r.properties&&!ft(r.properties)||Yi.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}catch(t){return Yi.error("Error in beforeSend function for event '"+e.event+"':",t),null}for(var a of i)if(r.properties&&St(r.properties[a]))return Yi.warn("Event '"+e.event+"' had its '"+a+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return r}getPageViewId(){var e;return null==(e=this.pageViewManager._currentPageview)?void 0:e.pageViewId}captureTraceFeedback(e,t){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:t})}captureTraceMetric(e,t,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:t,$ai_metric_value:String(i)})}_checkLocalStorageForDebug(e){var t=Ct(e)&&!e,i=ws._is_supported()&&"true"===ws._get("ph_debug");return!t&&(!!i||e)}},e.__defaultExtensionClasses={},e._noopLogger={trace:lo=()=>{},debug:lo,info:lo,warn:lo,error:lo,fatal:lo},e);!function(e,t){for(var i=0;t.length>i;i++)e.prototype[t[i]]=ts(e.prototype[t[i]])}(zo,["identify"]);var Ko=function(){a.SDK_DIST_CHANNEL="npm";var e=Io[Uo]=new zo;return function(){function e(){e.done||(e.done=!0,zn=!1,Zi(Io,function(e){e._dom_loaded()}))}null!=Qe&&Qe.addEventListener?"complete"===Qe.readyState?e():os(Qe,"DOMContentLoaded",e,{capture:!1}):Ke&&Yi.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}(),e}();export{Ir as Compression,Br as DEFAULT_PRODUCT_TOUR_APPEARANCE,Lr as DisplaySurveyType,zo as PostHog,Ur as ProductTourEventName,qr as ProductTourEventProperties,Ar as SurveyEventName,Dr as SurveyEventProperties,Er as SurveyEventType,Tr as SurveyPosition,Or as SurveyQuestionBranchingType,Rr as SurveyQuestionType,Mr as SurveySchedule,$r as SurveyTabPosition,Fr as SurveyType,xr as SurveyWidgetType,Ko as default,Ko as posthog,jr as severityLevels}; +//# sourceMappingURL=module.slim.no-external.js.map \ No newline at end of file diff --git a/website/dist/assets/vendor/posthog-js-LICENSE b/website/dist/assets/vendor/posthog-js-LICENSE new file mode 100644 index 0000000..dd16ba3 --- /dev/null +++ b/website/dist/assets/vendor/posthog-js-LICENSE @@ -0,0 +1,417 @@ +Copyright 2020 Posthog / Hiberly, Inc. + +Copyright 2015 Mixpanel, Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this work except in compliance with the License. +You may obtain a copy of the License below, or at: + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +--- + +The @posthog/core package in packages/core is licensed under the MIT License below. +Third-party code remains subject to its respective notices in this file. +This owning notice is preserved from posthog-js-lite, from which @posthog/core was migrated: +https://github.com/PostHog/posthog-js-lite/blob/5fb7bee96f739b243dfea5589e2027f16629e8cd/LICENSE + +MIT License + +Copyright (c) 2022 PostHog (part of Hiberly Inc) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +packages/core/src/error-tracking/parsers/index.ts and its compiled distributions contain code +derived from TraceKit. This license only applies to the relevant code. + +MIT License + +Copyright (c) 2013 Onur Can Cakmak onur.cakmak@gmail.com and all TraceKit contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files(the 'Software'), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and / or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be included in all copies +or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF +CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--- + +packages/core/src/vendor/uuidv7.ts and its compiled distributions contain code from uuidv7: +https://github.com/LiosK/uuidv7/blob/f30b7a7faff73afbce0b27a46c638310f96912ba/src/index.ts + +Copyright 2021-2023 LiosK + +This code is licensed under the Apache License, Version 2.0, reproduced above. + +--- + +Some files in this codebase contain code from getsentry/sentry-javascript. +In such cases it is explicitly stated in the file header. This license only applies to the relevant code in such cases. + +MIT License + +Copyright (c) 2012 Functional Software, Inc. dba Sentry + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +Some files in this codebase contain code from getsentry/sentry-react-native. +In such cases it is explicitly stated in the file header. This license only applies to the relevant code in such cases. + +The MIT License (MIT) + +Copyright (c) 2017 Sentry + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +Some files in this codebase contain code from facebook/metro by Meta Platforms, Inc. and affiliates. +In such cases it is explicitly stated in the file header. This license only applies to the relevant code in such cases. + +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +Some files in this codebase contain code from expo/expo by 650 Industries, Inc. (aka Expo). +In such cases it is explicitly stated in the file header. This license only applies to the relevant code in such cases. + +The MIT License (MIT) + +Copyright (c) 2015-present 650 Industries, Inc. (aka Expo) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +Some files in this codebase contain code from agentcathq/agentcat-typescript-sdk (formerly MCPCat/mcpcat-typescript-sdk). +In such cases it is explicitly stated in the file header. This license only applies to the relevant code in such cases. + +MIT License + +Copyright (c) 2025 AgentCat, Inc. (formerly MCPcat) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/website/dist/assets/vendor/web-vitals-6.2.1.mjs b/website/dist/assets/vendor/web-vitals-6.2.1.mjs new file mode 100644 index 0000000..6af6f24 --- /dev/null +++ b/website/dist/assets/vendor/web-vitals-6.2.1.mjs @@ -0,0 +1,2 @@ +let t=-1;const n=()=>t,e=n=>{addEventListener("pageshow",e=>{e.persisted&&(t=e.timeStamp,n(e))},!0)},i=(t,n,e,i)=>{let o,s;return a=>{n.value>=0&&(a||i)&&(s=n.value-(o??0),(s||void 0===o)&&(o=n.value,n.delta=s,n.rating=((t,n)=>t>n[1]?"poor":t>n[0]?"needs-improvement":"good")(n.value,e),t(n)))}},o=t=>{requestAnimationFrame(()=>requestAnimationFrame(()=>t()))},s=()=>{const t=performance.getEntriesByType("navigation")[0];if(t&&t.responseStart>0&&t.responseStarts()?.activationStart??0;let r=-1;const c=new Set,f=()=>"hidden"!==document.visibilityState||document.prerendering?1/0:0,h=t=>{if("hidden"===document.visibilityState){if("visibilitychange"===t.type)for(const t of c)t();isFinite(r)||(r="visibilitychange"===t.type?t.timeStamp:0,removeEventListener("prerenderingchange",h,!0))}},d=(t=!1)=>{if(t&&(r=1/0),r<0){const t=a(),n=document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").find(n=>"hidden"===n.name&&n.startTime>=t)?.startTime;r=n??f(),addEventListener("visibilitychange",h,!0),addEventListener("prerenderingchange",h,!0),e(()=>{setTimeout(()=>{r=f()})})}return{get firstHiddenTime(){return r},onHidden(t){c.add(t)}}},l=(t,e=-1,i,o=0,r,c,f)=>{const h=s(),d=h?.navigationId||0;let l="navigate";i?l=i:n()>=0?l="back-forward-cache":h&&(document.prerendering||a()>0?l="prerender":document.wasDiscarded?l="restore":h.type&&(l=h.type.replace(/_/g,"-")));return{name:t,value:e,rating:"good",delta:0,entries:[],id:`v6-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:l,navigationId:o||d,navigationInteractionId:r,navigationURL:c||h?.name,navigationStartTime:f||0}},g=new WeakMap;function u(t,n){let e=g.get(n);return e||(e=new WeakMap,g.set(n,e)),e.get(t)||e.set(t,new n),e.get(t)}class v{t;i=0;o=[];h(t){if(t.hadRecentInput)return;const n=this.o[0],e=this.o.at(-1);this.i&&n&&e&&t.startTime-e.startTime<1e3&&t.startTime-n.startTime<5e3?(this.i+=t.value,this.o.push(t)):(this.i=t.value,this.o=[t]),this.t?.(t)}}const m=(t,n,e={})=>{try{const i=t.filter(t=>PerformanceObserver.supportedEntryTypes.includes(t));if(i.length>0){const t=new PerformanceObserver(t=>{queueMicrotask(()=>{const e=t.getEntries();i.length>1&&e.sort((t,n)=>t.startTime+t.duration-(n.startTime+n.duration)),n(e)})});for(const n of i)t.observe({type:n,buffered:!0,...e});return t}}catch{}},p=t=>globalThis.PerformanceObserver?.supportedEntryTypes?.includes("soft-navigation")&&"function"==typeof globalThis.PerformanceSoftNavigation?.prototype?.getLargestInteractionContentfulPaint&&t&&t.reportSoftNavs,b=(t,n)=>{if(t.set(n.navigationId,n),t.size>2){const n=t.keys().next().value;void 0!==n&&t.delete(n)}},T=t=>{let n=!1;return()=>{n||(t(),n=!0)}};class y{l}const _=t=>{document.prerendering?addEventListener("prerenderingchange",t,!0):t()},E=[1800,3e3],M=(t,s={})=>{const r=p(s);_(()=>{const c=u(s,y),f=d();let h,g=l("FCP");const v=m(["paint"],t=>{for(const n of t)"first-contentful-paint"===n.name&&(v.disconnect(),n.startTime{g=l("FCP",-1,"back-forward-cache",g.navigationId,g.navigationInteractionId,g.navigationURL,n()),h=i(t,g,E,s.reportAllChanges),o(()=>{g.value=performance.now()-e.timeStamp,h(!0)})})),r){m(["soft-navigation"],n=>{n.forEach(n=>{c.l&&n.navigationId&&b(c.l,n);const e=Math.max((n.presentationTime||n.paintTime||0)-n.startTime,0);g=l("FCP",e,"soft-navigation",n.navigationId,n.interactionId,n.name,n.startTime),h=i(t,g,E,s.reportAllChanges),h(!0)})},s)}})},L=[.1,.25],P=(t,s={})=>{const a=d();M(T(()=>{let r,c=l("CLS",0);const f=u(s,v),h=(n,e,o,a,h)=>{c=l("CLS",0,n,e,o,a,h),f.i=0,r=i(t,c,L,s.reportAllChanges)},d=(t=!1)=>{f.i>c.value&&(c.value=f.i,c.entries=f.o),r(t)},g=t=>{d(!0),h("soft-navigation",t.navigationId,t.interactionId,t.name,t.startTime)},b=t=>{for(const n of t)"soft-navigation"!==n.entryType?f.h(n):g(n);d()},T=["layout-shift"];p(s)&&T.push("soft-navigation");const y=m(T,b);y&&(r=i(t,c,L,s.reportAllChanges),a.onHidden(()=>{b(y.takeRecords()),r(!0)}),e(()=>{h("back-forward-cache",c.navigationId,c.navigationInteractionId,c.navigationURL,n()),o(r)}),setTimeout(r))}))};let w=0,I=1/0,k=0;const C=t=>{for(const n of t)n.interactionId&&(I=Math.min(I,n.interactionId),k=Math.max(k,n.interactionId),w=k?(k-I)/7+1:0)};let F;const N=()=>F?w:performance.interactionCount??0,B=()=>{"interactionCount"in performance||F||(F=m(["event"],C,{durationThreshold:0}))};class S{u=0;v=[];m=new Map;p;T;_(){return N()-this.u}M(){this.u=N(),this.v.length=0,this.m.clear()}L(t){const n=this._(),e=Math.min(this.v.length-1,Math.floor(n/50));return!n||-1!==e||"soft-navigation"!==t&&"back-forward-cache"!==t?this.v[e]:{P:8,id:-1,entries:[]}}h(t){if(this.p?.(t),!t.interactionId)return;const n=this.v.at(-1);let e=this.m.get(t.interactionId);if(e||this.v.length<10||t.duration>n.P){if(e?t.duration>e.P?(e.entries=[t],e.P=t.duration):t.duration===e.P&&t.startTime===e.entries[0].startTime&&e.entries.push(t):(e={id:t.interactionId,entries:[t],P:t.duration},this.m.set(e.id,e),this.v.push(e)),this.v.sort((t,n)=>n.P-t.P),this.v.length>10){const t=this.v.splice(10);for(const n of t)this.m.delete(n.id)}this.T?.(e)}}}const q=t=>{const n="requestIdleCallback"in globalThis?1e3:0,e=globalThis.requestIdleCallback||setTimeout,i=globalThis.cancelIdleCallback||clearTimeout;if("hidden"===document.visibilityState)t();else{const o=T(t);let s=-1;const a=()=>{i(s),o()};addEventListener("visibilitychange",a,{once:!0,capture:!0}),s=e(()=>{removeEventListener("visibilitychange",a,{capture:!0}),o()},{timeout:n})}},A=[200,500],x=(t,o={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;const s=d();_(()=>{B();let a,r=l("INP");const c=u(o,S),f=(n,e,s,f,h)=>{c.M(),r=l("INP",-1,n,e,s,f,h),a=i(t,r,A,o.reportAllChanges)},h=()=>{const t=c.L(r.navigationType);t&&t.P!==r.value&&(r.value=t.P,r.entries=t.entries,a())},d=t=>{h(),a(!0),f("soft-navigation",t.navigationId,t.interactionId,t.name,t.startTime)},g=(t,n=!1)=>{q(()=>{for(const n of t)"soft-navigation"!==n.entryType?c.h(n):d(n);h(),n&&a(!0)})},v=["event","first-input"];p(o)&&v.push("soft-navigation");const b=m(v,g,{...o,durationThreshold:o.durationThreshold??40});a=i(t,r,A,o.reportAllChanges),b&&(s.onHidden(()=>{g(b.takeRecords(),!0)}),e(()=>{f("back-forward-cache",r.navigationId,r.navigationInteractionId,r.navigationURL,n())}))})};class H{p;l;h(t){this.p?.(t)}}const O=[2500,4e3],U=(t,s={})=>{let r=!1;const c=p(s);_(()=>{let f,h=d(),g=l("LCP");const v=u(s,H),p=(n,e,o,a,c)=>{g=l("LCP",-1,n,e,o,a,c),f=i(t,g,O,s.reportAllChanges),r=!1,"soft-navigation"===n&&(h=d(!0))},T=t=>{v.l&&t.navigationId&&b(v.l,t),r||f(!0),p("soft-navigation",t.navigationId,t.interactionId,t.name,t.startTime);const n=t.getLargestInteractionContentfulPaint?.();n&&y([n])},y=t=>{s.reportAllChanges||c||(t=t.slice(-1));for(const n of t){if(!n)continue;if("soft-navigation"===n.entryType){T(n);continue}let t=0,e=[],i=n.startTime;if("largest-contentful-paint"===n.entryType)t=Math.max(n.startTime-a(),0),v.h(n),e=[n];else if("interaction-contentful-paint"===n.entryType){const o=n;if(!g.navigationId)continue;if("interactionId"in o&&o.interactionId!=g.navigationInteractionId)continue;i=o.largestContentfulPaint?.renderTime||0,t=Math.max(i-n.startTime,0),o.largestContentfulPaint&&(v.h(o.largestContentfulPaint),e=[o.largestContentfulPaint])}i{if(t.isTrusted&&!r){const t=g.id;q(()=>{if(!r){if(!c){E.disconnect();for(const t of a)removeEventListener(t,h,{capture:!0})}t===g.id&&(r=!0,f(!0))}})}};for(const t of a)addEventListener(t,h,{capture:!0});e(e=>{p("back-forward-cache",g.navigationId,g.navigationInteractionId,g.navigationURL,n()),f=i(t,g,O,s.reportAllChanges),o(()=>{g.value=performance.now()-e.timeStamp,r=!0,f(!0)})})}})},W=[800,1800],$=t=>{document.prerendering?_(()=>$(t)):"complete"!==document.readyState?addEventListener("load",()=>$(t),!0):setTimeout(t)},D=(t,o={})=>{const r=p(o);let c=l("TTFB"),f=i(t,c,W,o.reportAllChanges);$(()=>{const h=s();if(h){const s=h.responseStart;if(c.value=Math.max(s-a(),0),c.entries=[h],f(!0),e(()=>{c=l("TTFB",0,"back-forward-cache",c.navigationId,c.navigationInteractionId,c.navigationURL,n()),f=i(t,c,W,o.reportAllChanges),f(!0)}),r){m(["soft-navigation"],n=>{n.forEach(n=>{n.navigationId&&(c=l("TTFB",0,"soft-navigation",n.navigationId,n.interactionId,n.name,n.startTime),c.entries=[n],f=i(t,c,W,o.reportAllChanges),f(!0))})},o)}}})};export{L as CLSThresholds,E as FCPThresholds,A as INPThresholds,O as LCPThresholds,W as TTFBThresholds,P as onCLS,M as onFCP,x as onINP,U as onLCP,D as onTTFB}; +//# sourceMappingURL=web-vitals.js.map diff --git a/website/dist/assets/vendor/web-vitals-LICENSE b/website/dist/assets/vendor/web-vitals-LICENSE new file mode 100644 index 0000000..618d629 --- /dev/null +++ b/website/dist/assets/vendor/web-vitals-LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2020 Google LLC + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/website/dist/closed-lid-setup.html b/website/dist/closed-lid-setup.html index fe6f64d..242e428 100644 --- a/website/dist/closed-lid-setup.html +++ b/website/dist/closed-lid-setup.html @@ -17,18 +17,19 @@ +
dilated - +

MAC APP STORE COMPANION

Closed-lid setup.

-

Download Closed-Lid Setup for Mac

+

Download Closed-Lid Setup for Mac

Free. Requires macOS 26 or later on Apple Silicon. Signed with Developer ID and notarized by Apple.

Set it up

    diff --git a/website/dist/index.html b/website/dist/index.html index 6eb8ed9..c7dd053 100644 --- a/website/dist/index.html +++ b/website/dist/index.html @@ -50,6 +50,7 @@ + @@ -118,7 +119,7 @@

    Let it finish.

    The screen can sleep.

    Keeping your Mac awake doesn't have to keep the display on.

    Stop is a full stop.

    Clears every hold. Automation waits until you explicitly resume it.

    Power gets a say.

    Battery and Low Power Mode guards help put a limit on late nights.

    -
    Dilated app icon: yellow with pixel eyes

    PUBLIC BETA.

    Try the
    public beta.

    Dilated is a free public beta for macOS 26+ on Apple Silicon. From CodesWhat, under MIT.

    Closed-lid mode is experimental. Hardware recovery checks remain incomplete. If the download details don't load, see the release history for published builds and their verification status.

    Release history

    Free and open source. If it saves you time, you can sponsor it on GitHub or donate directly.

    PUBLIC BETA · MACOS 26+ · APPLE SILICON · MIT LICENSE

    +
    Dilated app icon: yellow with pixel eyes

    PUBLIC BETA.

    Try the
    public beta.

    Dilated is a free public beta for macOS 26+ on Apple Silicon. From CodesWhat, under MIT.

    Closed-lid mode is experimental. Hardware recovery checks remain incomplete. If the download details don't load, see the release history for published builds and their verification status.

    Release history

    Free and open source. If it saves you time, you can sponsor it on GitHub or donate directly.

    PUBLIC BETA · MACOS 26+ · APPLE SILICON · MIT LICENSE

diff --git a/website/dist/privacy.html b/website/dist/privacy.html index 998894f..02fd869 100644 --- a/website/dist/privacy.html +++ b/website/dist/privacy.html @@ -3,13 +3,13 @@ - + Privacy · Dilated - + @@ -17,17 +17,18 @@ +
dilated - +
-

EFFECTIVE 2026-11-03

+

EFFECTIVE 2026-11-17

Privacy.

- +

What stays on your Mac

Your settings, timers, history, statistics and holds live on your Mac and nowhere else. The direct build keeps them in ~/Library/Application Support/Dilated. The Mac App Store build keeps them in its sandbox container. Nothing is uploaded, and there's no copy on our side to ask for.

@@ -44,7 +45,11 @@

Permissions, and why Dilated asks

Network use

The direct build checks for updates with Sparkle. It requests https://dilated.app/updates/appcast.xml and verifies the signed feed before installing anything. Sparkle's system profile option is off, so the request carries the usual HTTP details (your IP address, the app name and version, your macOS version) and no hardware or usage profile. Like any web host, ours can see that request in its server logs.

The Mac App Store build has no update code and makes no network requests. The App Store delivers its updates.

-

This website sets no cookies and loads no third-party scripts, fonts or trackers. Your browser fetches the page and, on the home page, a small file with the current release details, all from dilated.app.

+

Your browser fetches the page and, on the home page, a small file with the current release details, from dilated.app.

+ +

This website

+

The site uses cookieless PostHog page analytics. Events go through e.codeswhat.com to PostHog's US cloud. There are no cookies and nothing is stored in your browser, and there are no person profiles. No IP address is stored: PostHog hashes it with your user agent and a daily rotating salt to count daily visitors, then discards it.

+

It records only the page path, the referring domain, page-load performance (web vitals) and clicks on the download and source links. No query strings, no full referrer URLs, no text you type. The app itself sends nothing to PostHog.

Closed-lid companion

Closed-lid mode is optional. It needs a sudo rule limited to pmset -a disablesleep 0 and pmset -a disablesleep 1, and nothing else. The direct build installs the rule when you choose to. The App Store build can't run sudo from its sandbox, so it uses a separate Closed-Lid Setup companion that installs the same rule, a small script (dilated-power) and a LaunchAgent that restores normal sleep if the app disappears. All of it runs locally and none of it uses the network.

@@ -58,7 +63,7 @@

Closed-lid companion

Contact

Questions about any of this: security@codeswhat.com. Dilated is MIT licensed and the source is public, so you can check these claims against the code.

- +
diff --git a/website/e2e/serve.mjs b/website/e2e/serve.mjs index f83141f..bbb1048 100644 --- a/website/e2e/serve.mjs +++ b/website/e2e/serve.mjs @@ -1,5 +1,5 @@ // Dependency-free static server for website/dist. It sends the headers from the -// first route in vercel.json, so the production CSP applies to every page here. +// vercel.json route that carries the CSP, so the production CSP applies to every page here. import { createServer } from 'node:http'; import { readFileSync } from 'node:fs'; import { readFile } from 'node:fs/promises'; @@ -11,7 +11,7 @@ const distRoot = join(websiteRoot, 'dist'); const port = Number(process.env.PORT ?? 4791); const config = JSON.parse(readFileSync(join(websiteRoot, 'vercel.json'), 'utf8')); -const headers = config.routes[0].headers; +const headers = config.routes.find(route => route.headers?.['Content-Security-Policy']).headers; const types = { '.html': 'text/html; charset=utf-8', diff --git a/website/e2e/site.spec.mjs b/website/e2e/site.spec.mjs index b27635b..ca0c4e3 100644 --- a/website/e2e/site.spec.mjs +++ b/website/e2e/site.spec.mjs @@ -482,3 +482,21 @@ test.describe('discoverability', () => { } }); }); + +test.describe('analytics', () => { + for (const path of ['/', '/privacy', '/closed-lid-setup']) { + test(`${path} loads the analytics module under the CSP and sends nothing off localhost`, async ({ page, baseURL, failures }) => { + const external = []; + page.on('request', request => { + if (!request.url().startsWith(new URL(baseURL).origin) && !request.url().startsWith('data:')) external.push(request.url()); + }); + const module = page.waitForResponse(response => new URL(response.url()).pathname === '/analytics/client.mjs'); + failures.allow(`${baseURL}/releases/latest.json`); + await page.goto(path); + expect((await module).status()).toBe(200); + await page.waitForLoadState('networkidle'); + await page.waitForTimeout(500); + expect(external.filter(url => url.includes('codeswhat.com'))).toEqual([]); + }); + } +}); diff --git a/website/tests/analytics.test.mjs b/website/tests/analytics.test.mjs new file mode 100644 index 0000000..a1d3499 --- /dev/null +++ b/website/tests/analytics.test.mjs @@ -0,0 +1,315 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { readFile } from 'node:fs/promises'; + +import { + POSTHOG_PROXY_HOST, + POSTHOG_UI_HOST, + buildCtaEvent, + buildPageleaveEvent, + buildPageviewEvent, + buildWebVitalsEvent, + canonicalizeAnalyticsRoute, + createPostHogOptions, + isProductionHost, + sanitizeEvent, +} from '../dist/analytics/contract.mjs'; +import { WEB_VITALS_FLUSH_DELAY_MS, createWebVitalsReporter } from '../dist/analytics/web-vitals-buffer.mjs'; + +const KEY = 'phc_mav2oHZzTVaC4mAFEqaLbGEff65uvGMy47LcWSNBFp9J'; // gitleaks:allow +const UA = 'Mozilla/5.0 (Macintosh)'; +const TIMESTAMP = new Date('2026-11-17T12:00:00Z'); + +const envelope = (event, properties = {}, extra = {}) => ({ + event, + uuid: '0192f1b2-0000-7000-8000-000000000001', + timestamp: TIMESTAMP, + properties: { + token: KEY, + distinct_id: '$posthog_cookieless', + $current_url: 'https://dilated.app/privacy?utm_source=x&email=a@b.c#frag', + $cookieless_mode: true, + $process_person_profile: false, + $raw_user_agent: UA, + $host: 'dilated.app', + ...properties, + }, + ...extra, +}); + +const leaky = { + $referrer: 'https://news.example.com/private/path?token=1', + $ip: '203.0.113.9', + utm_source: 'newsletter', + utm_campaign: 'launch', + gclid: 'abc', + fbclid: 'def', + $set: { email: 'a@b.c' }, + $device_id: 'device', + $session_id: 'session', + $title: 'Privacy', + email: 'a@b.c', +}; + +test('canonical paths cover the three pages, aliases and the /_other bucket', () => { + const path = raw => canonicalizeAnalyticsRoute(raw).path; + assert.equal(path('/'), '/'); + assert.equal(path('/privacy'), '/privacy'); + assert.equal(path('/closed-lid-setup'), '/closed-lid-setup'); + assert.equal(path('/privacy/'), '/privacy'); + assert.equal(path('/privacy?utm_source=x#top'), '/privacy'); + assert.equal(path('/#availability'), '/'); + assert.equal(path('/index.html'), '/'); + assert.equal(path('/privacy.html'), '/privacy'); + assert.equal(path('/closed-lid-setup.html'), '/closed-lid-setup'); + assert.equal(path('/releases/latest.json'), '/_other'); + assert.equal(path('/privacy/secret'), '/_other'); + assert.equal(path('privacy'), '/'); + assert.equal(path(''), '/'); + assert.equal(canonicalizeAnalyticsRoute('/x').surface, 'marketing'); +}); + +test('pageview and pageleave carry the base properties and $pathname', () => { + for (const build of [buildPageviewEvent, buildPageleaveEvent]) { + const { properties } = build('/privacy.html?x=1'); + assert.deepEqual(properties, { + schema_version: 1, + site: 'dilated', + surface: 'marketing', + path: '/privacy', + $pathname: '/privacy', + }); + } + assert.equal(buildPageviewEvent('/').event, '$pageview'); + assert.equal(buildPageleaveEvent('/').event, '$pageleave'); +}); + +test('the CTA allowlist accepts the real combinations and rejects everything else', () => { + const accepted = [ + ['download', 'availability'], + ['release_history', 'availability'], + ['sponsor', 'availability'], + ['donate', 'availability'], + ['closed_lid_setup_download', 'page'], + ['github_repository', 'header'], + ]; + for (const [id, placement] of accepted) { + const event = buildCtaEvent('/', id, placement); + assert.equal(event.event, 'cta activated'); + assert.deepEqual(event.properties, { + schema_version: 1, site: 'dilated', surface: 'marketing', path: '/', cta_id: id, placement, + }); + } + assert.equal(buildCtaEvent('/', 'download', 'header'), null); + assert.equal(buildCtaEvent('/', 'github_repository', 'availability'), null); + assert.equal(buildCtaEvent('/', 'unknown', 'availability'), null); + assert.equal(buildCtaEvent('/', undefined, undefined), null); +}); + +test('web vitals events keep only finite non-negative metrics', () => { + const event = buildWebVitalsEvent('/privacy', { LCP: 1200, CLS: 0, INP: -1, FCP: Number.NaN }); + assert.equal(event.event, '$web_vitals'); + assert.deepEqual(event.properties, { + schema_version: 1, site: 'dilated', surface: 'marketing', path: '/privacy', + $web_vitals_CLS_value: 0, $web_vitals_LCP_value: 1200, + }); + assert.equal(buildWebVitalsEvent('/', {}), null); + assert.equal(buildWebVitalsEvent('/', { LCP: -5 }), null); +}); + +test('sanitizeEvent rebuilds a pageview from the allowlist and drops everything else', () => { + const output = sanitizeEvent(envelope('$pageview', { ...leaky, $referring_domain: 'news.example.com' })); + assert.deepEqual(Object.keys(output).sort(), ['event', 'properties', 'timestamp', 'uuid']); + assert.deepEqual(output.properties, { + schema_version: 1, + site: 'dilated', + surface: 'marketing', + path: '/privacy', + $pathname: '/privacy', + token: KEY, + $cookieless_mode: true, + $process_person_profile: false, + $raw_user_agent: UA, + $host: 'dilated.app', + $referring_domain: 'news.example.com', + distinct_id: '$posthog_cookieless', + }); + assert.equal(output.timestamp, TIMESTAMP); + assert.equal(output.uuid, '0192f1b2-0000-7000-8000-000000000001'); + for (const key of Object.keys(leaky)) assert.ok(!(key in output.properties), key); + assert.ok(!('$current_url' in output.properties)); +}); + +test('sanitizeEvent handles each event type', () => { + assert.equal(sanitizeEvent(envelope('$pageleave')).event, '$pageleave'); + assert.equal(sanitizeEvent(envelope('$pageleave')).properties.$pathname, '/privacy'); + + const cta = sanitizeEvent(envelope('cta activated', { cta_id: 'github_repository', placement: 'header' })); + assert.equal(cta.properties.cta_id, 'github_repository'); + assert.equal(cta.properties.placement, 'header'); + assert.equal(sanitizeEvent(envelope('cta activated', { cta_id: 'download', placement: 'header' })), null); + assert.equal(sanitizeEvent(envelope('cta activated', { cta_id: 1, placement: 'header' })), null); + + const vitals = sanitizeEvent(envelope('$web_vitals', { + $web_vitals_LCP_value: 900, $web_vitals_CLS_value: 0.01, $web_vitals_LCP_event: { big: 'object' }, + })); + assert.equal(vitals.properties.$web_vitals_LCP_value, 900); + assert.equal(vitals.properties.$web_vitals_CLS_value, 0.01); + assert.ok(!('$web_vitals_LCP_event' in vitals.properties)); + assert.equal(sanitizeEvent(envelope('$web_vitals')), null); + + assert.equal(sanitizeEvent(envelope('$autocapture')), null); + assert.equal(sanitizeEvent(envelope('$exception')), null); + assert.equal(sanitizeEvent(envelope('custom event')), null); +}); + +test('sanitizeEvent canonicalizes the path from $current_url, preferring an explicit path property', () => { + const unknown = sanitizeEvent(envelope('$pageview', { $current_url: 'https://dilated.app/some/secret/page?x=1' })); + assert.equal(unknown.properties.path, '/_other'); + const aliased = sanitizeEvent(envelope('$pageview', { $current_url: 'https://dilated.app/index.html' })); + assert.equal(aliased.properties.path, '/'); + assert.equal(sanitizeEvent(envelope('$pageview', { $current_url: 'not a url' })), null); + assert.equal(sanitizeEvent(envelope('$pageview', { $current_url: undefined })), null); +}); + +test('referring domain is kept only as $direct or a bare hostname', () => { + const referring = value => sanitizeEvent(envelope('$pageview', { $referring_domain: value })).properties.$referring_domain; + assert.equal(referring('$direct'), '$direct'); + assert.equal(referring('github.com'), 'github.com'); + assert.equal(referring('localhost:5173'), 'localhost:5173'); + for (const bad of ['https://github.com/path', 'github.com/path', 'a b', '', 42, null, 'x.com?q=1', '$other']) { + assert.equal(referring(bad), undefined, String(bad)); + } +}); + +test('the distinct id survives only as the cookieless sentinel; a bad timestamp is dropped', () => { + assert.equal(sanitizeEvent(envelope('$pageview', { distinct_id: 'person-123' })).properties.distinct_id, undefined); + assert.equal(sanitizeEvent(envelope('$pageview', { distinct_id: undefined })).properties.distinct_id, undefined); + assert.equal('timestamp' in sanitizeEvent(envelope('$pageview', {}, { timestamp: new Date('nope') })), false); + assert.equal('timestamp' in sanitizeEvent(envelope('$pageview', {}, { timestamp: '2026-11-17' })), false); +}); + +test('sanitizeEvent rejects envelopes missing a required field', () => { + assert.equal(sanitizeEvent(null), null); + assert.equal(sanitizeEvent({}), null); + assert.equal(sanitizeEvent({ event: '$pageview' }), null); + assert.equal(sanitizeEvent(envelope('$pageview', { token: 'not-a-key' })), null); + assert.equal(sanitizeEvent(envelope('$pageview', { token: undefined })), null); + assert.equal(sanitizeEvent(envelope('$pageview', { $cookieless_mode: undefined })), null); + assert.equal(sanitizeEvent(envelope('$pageview', { $cookieless_mode: 'true' })), null); + assert.equal(sanitizeEvent(envelope('$pageview', { $process_person_profile: true })), null); + assert.equal(sanitizeEvent(envelope('$pageview', { $process_person_profile: undefined })), null); + assert.equal(sanitizeEvent(envelope('$pageview', { $raw_user_agent: '' })), null); + assert.equal(sanitizeEvent(envelope('$pageview', { $raw_user_agent: undefined })), null); + assert.equal(sanitizeEvent(envelope('$pageview', { $host: '' })), null); + assert.equal(sanitizeEvent(envelope('$pageview', { $host: undefined })), null); +}); + +test('createPostHogOptions returns the cookieless, no-persistence, no-campaign shape', () => { + const options = createPostHogOptions(KEY, POSTHOG_PROXY_HOST, POSTHOG_UI_HOST); + assert.equal(options.api_host, 'https://e.codeswhat.com'); + assert.equal(options.ui_host, 'https://us.posthog.com'); + assert.equal(options.cookieless_mode, 'always'); + assert.equal(options.person_profiles, 'never'); + assert.equal(options.persistence, 'memory'); + assert.equal(options.disable_persistence, true); + assert.equal(options.autocapture, false); + assert.equal(options.capture_pageview, false); + assert.equal(options.capture_pageleave, true); + assert.equal(options.advanced_disable_flags, true); + assert.equal(options.disable_session_recording, true); + assert.equal(options.respect_dnt, true); + assert.equal(options.save_referrer, true); + assert.equal(options.save_campaign_params, false); + assert.equal(options.capture_performance, false); + assert.equal(options.disable_external_dependency_loading, true); + assert.equal(options.before_send, sanitizeEvent); + + assert.equal(createPostHogOptions(undefined, POSTHOG_PROXY_HOST, POSTHOG_UI_HOST), null); + assert.equal(createPostHogOptions('bad', POSTHOG_PROXY_HOST, POSTHOG_UI_HOST), null); + assert.equal(createPostHogOptions(KEY, 'https://example.com', POSTHOG_UI_HOST), null); + assert.equal(createPostHogOptions(KEY, POSTHOG_PROXY_HOST, 'https://example.com'), null); +}); + +test('analytics only run on the production host', () => { + assert.equal(isProductionHost('dilated.app'), true); + for (const host of ['localhost', '127.0.0.1', 'dilated-website.vercel.app', 'www.dilated.app', 'dilated.app.evil.com', '']) { + assert.equal(isProductionHost(host), false, host); + } +}); + +test('the web vitals buffer flushes after 5s or when all four metrics arrive, once', () => { + const emitted = []; + const timers = []; + const make = () => createWebVitalsReporter( + '/privacy.html?x=1', + event => emitted.push(event), + buildWebVitalsEvent, + canonicalizeAnalyticsRoute, + (callback, delay) => { timers.push({ callback, delay, cancelled: false }); return timers.length - 1; }, + id => { timers[id].cancelled = true; }, + ); + + const partial = make(); + partial.record('LCP', 1000); + partial.record('LCP', 1100); + partial.record('bogus', 1); + partial.record('CLS', -1); + partial.record('FCP', Number.NaN); + assert.equal(timers.length, 1); + assert.equal(timers[0].delay, WEB_VITALS_FLUSH_DELAY_MS); + assert.equal(WEB_VITALS_FLUSH_DELAY_MS, 5000); + assert.equal(emitted.length, 0); + timers[0].callback(); + assert.equal(emitted.length, 1); + assert.equal(emitted[0].properties.path, '/privacy'); + assert.equal(emitted[0].properties.$web_vitals_LCP_value, 1100); + partial.record('INP', 10); + timers[0].callback(); + assert.equal(emitted.length, 1); + + emitted.length = 0; + timers.length = 0; + const full = make(); + for (const name of ['LCP', 'INP', 'CLS', 'FCP']) full.record(name, 1); + assert.equal(emitted.length, 1); + assert.equal(timers[0].cancelled, true); + assert.equal(Object.keys(emitted[0].properties).filter(key => key.startsWith('$web_vitals_')).length, 4); +}); + +test('vercel.json allows e.codeswhat.com in script-src and connect-src and nothing else new', async () => { + const config = JSON.parse(await readFile(new URL('../vercel.json', import.meta.url), 'utf8')); + const csp = config.routes.find(route => route.headers?.['Content-Security-Policy']).headers['Content-Security-Policy']; + const directives = Object.fromEntries(csp.split(';').map(part => { + const [name, ...values] = part.trim().split(/\s+/); + return [name, values]; + })); + assert.deepEqual(directives['script-src'], ["'self'", 'https://e.codeswhat.com']); + assert.deepEqual(directives['connect-src'], ["'self'", 'https://e.codeswhat.com']); + for (const [name, values] of Object.entries(directives)) { + if (name === 'script-src' || name === 'connect-src') continue; + assert.ok(!values.some(value => value.includes('codeswhat.com')), `${name} must not allow the proxy`); + } + assert.deepEqual(directives['default-src'], ["'self'"]); + assert.deepEqual(directives['style-src'], ["'self'"]); + assert.deepEqual(directives['img-src'], ["'self'"]); +}); + +test('every page wires the client module and its data-cta attributes are allowlisted', async () => { + const pages = { 'index.html': ['./analytics/client.mjs', 4], 'privacy.html': ['/analytics/client.mjs', 1], 'closed-lid-setup.html': ['/analytics/client.mjs', 2] }; + for (const [name, [src, count]] of Object.entries(pages)) { + const html = await readFile(new URL(`../dist/${name}`, import.meta.url), 'utf8'); + assert.ok(html.includes(``), `${name} loads the client`); + const ctas = [...html.matchAll(/data-cta="([^"]+)" data-cta-placement="([^"]+)"/g)]; + assert.equal(ctas.length, count, name); + for (const [, id, placement] of ctas) assert.ok(buildCtaEvent('/', id, placement), `${name}: ${id}:${placement}`); + } +}); + +test('the vendored modules load as-is: no bare-specifier or dynamic imports', async () => { + for (const name of ['posthog-js-1.449.2.mjs', 'web-vitals-6.2.1.mjs']) { + const source = await readFile(new URL(`../dist/assets/vendor/${name}`, import.meta.url), 'utf8'); + assert.doesNotMatch(source, /\bimport\s*\(/, name); + assert.doesNotMatch(source, /(?:^|[;}\s])import\s*(?:[\w*{][^;]*?\s)?from\s*["']/, name); + } +}); diff --git a/website/tests/privacy.test.mjs b/website/tests/privacy.test.mjs index c8fc2de..d61ca2d 100644 --- a/website/tests/privacy.test.mjs +++ b/website/tests/privacy.test.mjs @@ -14,13 +14,24 @@ test('privacy.html exists with a title, h1 and the canonical https://dilated.app assert.match(privacy, /

Privacy\.<\/h1>/); assert.match(privacy, //); assert.match(privacy, //); - assert.match(privacy, /EFFECTIVE 2026-11-03/); + assert.match(privacy, /EFFECTIVE 2026-11-17/); }); -test('privacy.html reuses the site stylesheet and loads no script or third-party resource', () => { +test('privacy.html reuses the site stylesheet and loads only the same-origin analytics module', () => { assert.match(privacy, //); - assert.doesNotMatch(privacy, /]*(?:href|src)="https?:\/\/(?!dilated\.app\/)/); + const scripts = [...privacy.matchAll(/]*>/g)].map(match => match[0]); + assert.deepEqual(scripts, ['