Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

5.8 KB
Raw Blame
import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'

import { makeNavigateWrapper } from '~/toolbar/shared/utils'

const replaceWithWildcard = (part: string): string => {
    // replace uuids
    if (part.match(/^([a-f]|[0-9]){8}-([a-f]|[0-9]){4}-([a-f]|[0-9]){4}-([a-f]|[0-9]){4}-([a-f]|[0-9]){12}$/)) {
        return '*'
    }

    // replace digits
    if (part.match(/^[0-9]+$/)) {
        return '*'
    }

    // Replace long values
    if (part.length > 24) {
        return '*'
    }

    return part
}

const autoWildcardHref = (url: string): string => {
    const urlParts = url.split('?')

    url = urlParts[0]
        .split('/')
        .map((part) => replaceWithWildcard(part))
        .join('/')

    // Iterate over query params and do the same for their values
    if (urlParts.length > 1) {
        const queryParams = urlParts[1].split('&')

        for (let i = 0; i < queryParams.length; i++) {
            const [key, value] = queryParams[i].split('=')
            queryParams[i] = `${key}=${replaceWithWildcard(value)}`
        }

        url = `${url}?${queryParams.join('&')}`
    }

    return url
}
/**
 * Sometimes we are able to set the href before the posthog init fragment is removed
 * we never want to store it as it will mean the heatmap URL is too specific and doesn't match
 * this ensures we never store it
 */
export function withoutPostHogInit(href: string): string {
    try {
        // we can't use `new URL(href)` because it behaves differently between browsers
        // and e.g. converts `https://*.example.com/` to `https://%2A.example.com/`
        const firstHash = href.indexOf('#')
        if (firstHash === -1) {
            return href
        }
        return href
            .replace(/__posthog=\{[^}]*}[^#]*/, '')
            .replace('##', '#')
            .replace(/#$/, '')
    } catch {
        return href
    }
}

// A pattern that does not end in a wildcard only matches the URLs it spells out. A trailing slash is
// the common way to get this by accident, and it drops every deeper page from the match.
// a trailing slash is the common way to land on a pattern that matches nothing, and it takes its own
// advice: the fix is to remove it or cover what sits below it, not to add a wildcard anywhere
export function endsWithTrailingSlash(wildcardHref: string): boolean {
    return wildcardHref.endsWith('/')
}

export function isTooSpecificWildcardHref(wildcardHref: string): boolean {
    // judge the stored string, not a trimmed copy of it: the match runs on what is in the box, so a
    // pattern ending in a space matches nothing and must still warn
    return wildcardHref.trim().length > 0 && !wildcardHref.endsWith('*')
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface currentPageLogicValues {
    autoWildcardEnabled: boolean
    href: string
    wildcardHref: string
    wildcardHrefEndsWithSlash: boolean
    wildcardHrefTooSpecific: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface currentPageLogicActions {
    autoWildcardHref: () => {
        value: true
    }
    setAutoWildcardEnabled: (enabled: boolean) => {
        enabled: boolean
    }
    setHref: (href: string) => {
        href: string
    }
    setWildcardHref: (href: string) => {
        href: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface currentPageLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        wildcardHrefTooSpecific: (wildcardHref: string) => boolean
        wildcardHrefEndsWithSlash: (wildcardHref: string) => boolean
    }
}

export type currentPageLogicType = MakeLogicType<
    currentPageLogicValues,
    currentPageLogicActions,
    Record<string, any>,
    currentPageLogicMeta
>

export const currentPageLogic = kea<currentPageLogicType>([
    path(['toolbar', 'stats', 'currentPageLogic']),

    actions(() => ({
        setHref: (href: string) => ({ href }),
        setWildcardHref: (href: string) => ({ href }),
        autoWildcardHref: true,
        setAutoWildcardEnabled: (enabled: boolean) => ({ enabled }),
    })),
    reducers(() => ({
        href: [withoutPostHogInit(window.location.href), { setHref: (_, { href }) => withoutPostHogInit(href) }],
        wildcardHref: [
            withoutPostHogInit(window.location.href),
            {
                setHref: (_, { href }) => withoutPostHogInit(href),
                setWildcardHref: (_, { href }) => withoutPostHogInit(href),
            },
        ],
        autoWildcardEnabled: [
            false,
            { persist: true },
            {
                setAutoWildcardEnabled: (_, { enabled }) => enabled,
            },
        ],
    })),

    selectors(() => ({
        wildcardHrefTooSpecific: [
            (s) => [s.wildcardHref],
            (wildcardHref: string): boolean => isTooSpecificWildcardHref(wildcardHref),
        ],
        wildcardHrefEndsWithSlash: [
            (s) => [s.wildcardHref],
            (wildcardHref: string): boolean => endsWithTrailingSlash(wildcardHref),
        ],
    })),

    listeners(({ actions, values }) => ({
        autoWildcardHref: () => {
            actions.setWildcardHref(autoWildcardHref(values.wildcardHref))
        },
    })),

    afterMount(({ actions, values, cache }) => {
        if (values.autoWildcardEnabled) {
            actions.autoWildcardHref()
        }
        cache.disposables.add(
            makeNavigateWrapper((): void => {
                if (window.location.href !== values.href) {
                    actions.setHref(withoutPostHogInit(window.location.href))
                    if (values.autoWildcardEnabled) {
                        actions.autoWildcardHref()
                    }
                }
            }, '__ph_current_page_logic_wrapped__'),
            'historyProxy'
        )
    }),
])