: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
// Keeps the repository in the URL: forwards a repo-less product URL (old links, the product root) to a
// repository, remembers the last repository used per project so the root reopens it, and switches
// repository from any page of the product.
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
import { ApiConfig } from 'lib/api'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { teamLogic } from 'scenes/teamLogic'
import { engineeringAnalyticsSources } from '../generated/api'
import type { GitHubSourceApi } from '../generated/api.schemas'
import { pickForwardRepo, repoFromPath, repoPathFor, switchRepoPath } from '../lib/repoScope'
import { scopeFromValue, scopeToValue } from '../lib/scope'
const projectId = (): string => String(ApiConfig.getCurrentProjectId())
const EVENT_REPO_SWITCHED = 'engineering analytics repo switched'
// The repo-less paths that forward. A repo path never forwards.
const LEGACY_PATHS = [
'/engineering-analytics/overview',
'/engineering-analytics/pull-requests',
'/engineering-analytics/workflows',
'/engineering-analytics/tests',
'/engineering-analytics/deploys',
'/engineering-analytics/teams',
'/engineering-analytics/authors',
'/engineering-analytics/teams/:ownerTeam',
'/engineering-analytics/authors/:handle',
]
const REPO_PATHS = [
'/engineering-analytics/repos/:repoOwner/:repoName/overview',
'/engineering-analytics/repos/:repoOwner/:repoName/pull-requests',
'/engineering-analytics/repos/:repoOwner/:repoName/workflows',
'/engineering-analytics/repos/:repoOwner/:repoName/tests',
'/engineering-analytics/repos/:repoOwner/:repoName/deploys',
'/engineering-analytics/repos/:repoOwner/:repoName/teams',
'/engineering-analytics/repos/:repoOwner/:repoName/authors',
'/engineering-analytics/repos/:repoOwner/:repoName/teams/:ownerTeam',
'/engineering-analytics/repos/:repoOwner/:repoName/authors/:handle',
'/engineering-analytics/repos/:repoOwner/:repoName/pull-requests/:number',
'/engineering-analytics/repos/:repoOwner/:repoName/pull-requests/:number/ci-explorer',
'/engineering-analytics/repos/:repoOwner/:repoName/actions/runs/:runId',
'/engineering-analytics/repos/:repoOwner/:repoName/actions/workflows/:workflowName',
]
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface repoScopeLogicValues {
currentTeamId: number | null // teamLogic
githubSources: GitHubSourceApi[] | null
githubSourcesLoading: boolean
hasMultipleSources: boolean
lastRepo: string | null
lastRepoByTeam: Record<string, string>
pendingForward: boolean
selectedScope: string | null
sourceOptions: {
label: string
value: string
}[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface repoScopeLogicActions {
clearPendingForward: () => {
value: true
}
forwardToRepo: () => {
value: true
}
loadGithubSources: () => any
loadGithubSourcesFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadGithubSourcesSuccess: (
githubSources: GitHubSourceApi[],
payload?: any
) => {
githubSources: GitHubSourceApi[]
payload?: any
}
noRepoToForward: () => {
value: true
}
rememberRepo: (
teamId: number,
repo: string
) => {
repo: string
teamId: number
}
switchRepo: (scopeValue: string) => {
scopeValue: string
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface repoScopeLogicMeta {
__keaTypeGenInternalSelectorTypes: {
lastRepo: (lastRepoByTeam: Record<string, string>, currentTeamId: number | null) => string | null
hasMultipleSources: (githubSources: GitHubSourceApi[] | null) => boolean
sourceOptions: (githubSources: GitHubSourceApi[] | null) => {
label: string
value: string
}[]
selectedScope: (
githubSources: GitHubSourceApi[] | null,
location: {
hash: string
pathname: string
search: string
},
searchParams: Record<string, any>
) => string | null
}
}
export type repoScopeLogicType = MakeLogicType<
repoScopeLogicValues,
repoScopeLogicActions,
Record<string, any>,
repoScopeLogicMeta
>
export const repoScopeLogic = kea<repoScopeLogicType>([
path(['products', 'engineering_analytics', 'frontend', 'scenes', 'repoScopeLogic']),
connect(() => ({
values: [teamLogic, ['currentTeamId']],
})),
actions({
forwardToRepo: true,
clearPendingForward: true,
// Nothing to forward to: the repo-less page stays and loads its own connect or empty state.
noRepoToForward: true,
rememberRepo: (teamId: number, repo: string) => ({ teamId, repo }),
switchRepo: (scopeValue: string) => ({ scopeValue }),
}),
loaders({
githubSources: [
null as GitHubSourceApi[] | null,
{
loadGithubSources: async (): Promise<GitHubSourceApi[]> =>
await engineeringAnalyticsSources(projectId()),
},
],
}),
reducers({
lastRepoByTeam: [
{} as Record<string, string>,
{ persist: true, prefix: 'engineering_analytics_' },
{ rememberRepo: (state, { teamId, repo }) => ({ ...state, [teamId]: repo }) },
],
// A forward asked for before the repository list loaded waits for it.
pendingForward: [false, { forwardToRepo: () => true, clearPendingForward: () => false }],
}),
selectors({
lastRepo: [
(s) => [s.lastRepoByTeam, s.currentTeamId],
(lastRepoByTeam: Record<string, string>, currentTeamId: number | null): string | null =>
currentTeamId ? (lastRepoByTeam[currentTeamId] ?? null) : null,
],
hasMultipleSources: [
(s) => [s.githubSources],
(githubSources: GitHubSourceApi[] | null): boolean => (githubSources ?? []).length > 1,
],
// One option per selectable (source, repo). The value encodes both so a multi-repo source's repos are
// distinct entries; the label is the repo (falling back to prefix).
sourceOptions: [
(s) => [s.githubSources],
(githubSources: GitHubSourceApi[] | null): { value: string; label: string }[] =>
(githubSources ?? []).map((source) => ({
value: scopeToValue(source.id, source.repo),
label: source.repo || source.prefix || `source ${source.id.slice(0, 8)}`,
})),
],
selectedScope: [
(s) => [s.githubSources, router.selectors.location, router.selectors.searchParams],
(
githubSources: GitHubSourceApi[] | null,
location: { pathname: string },
searchParams: Record<string, any>
): string | null => {
const repo = repoFromPath(removeProjectIdIfPresent(location.pathname))
const sourceId: string | undefined = searchParams.source
// A repo-less page highlights the legacy source its ?source names, if any.
const match = (githubSources ?? []).find((source) =>
repo
? source.repo.toLowerCase() === repo.toLowerCase() && (!sourceId || source.id === sourceId)
: !source.repo && source.id === sourceId
)
return match ? scopeToValue(match.id, match.repo) : null
},
],
}),
listeners(({ actions, values }) => {
const forward = (): void => {
actions.clearPendingForward()
const pathname = removeProjectIdIfPresent(router.values.location.pathname)
// The person may have moved on while the repository list loaded.
if (!pathname.startsWith('/engineering-analytics/') || repoFromPath(pathname)) {
return
}
const { repo, source, ...searchParams } = router.values.searchParams
const target = pickForwardRepo(values.githubSources ?? [], { repo, sourceId: source }, values.lastRepo)
// Nothing connected, or only a legacy source with no repository name.
if (!target) {
actions.noRepoToForward()
return
}
router.actions.replace(
repoPathFor(pathname, target),
source ? { ...searchParams, source } : searchParams,
router.values.hashParams
)
}
return {
forwardToRepo: () => {
if (values.githubSources) {
forward()
} else if (!values.githubSourcesLoading) {
actions.loadGithubSources()
}
},
loadGithubSourcesSuccess: () => {
if (values.pendingForward) {
forward()
}
},
loadGithubSourcesFailure: () => {
actions.clearPendingForward()
actions.noRepoToForward()
},
// The same page in the picked repository, or the list tab when the page is about one entity.
// The path names the repository; `?source` only rides along when two sources sync it, or when
// a legacy source names no repository and its pages stay repo-less.
switchRepo: ({ scopeValue }) => {
const { sourceId, repo } = scopeFromValue(scopeValue)
posthog.capture(EVENT_REPO_SWITCHED, { repository_count: values.sourceOptions.length })
const pathname = removeProjectIdIfPresent(router.values.location.pathname)
const { repo: _repo, source: _source, ...searchParams } = router.values.searchParams
const sameRepo = (other: string | null): boolean => other?.toLowerCase() === repo?.toLowerCase()
const sourcesOfRepo = (values.githubSources ?? []).filter((source) => sameRepo(source.repo))
router.actions.push(
// Another source of the repository on screen keeps the page, entity pages included.
repo && sameRepo(repoFromPath(pathname)) ? pathname : switchRepoPath(pathname, repo),
!repo || sourcesOfRepo.length > 1 ? { ...searchParams, source: sourceId } : searchParams,
router.values.hashParams
)
},
}
}),
urlToAction(({ actions, values }) => ({
...Object.fromEntries(LEGACY_PATHS.map((pattern) => [pattern, () => actions.forwardToRepo()])),
...Object.fromEntries(
REPO_PATHS.map((pattern) => [
pattern,
({ repoOwner, repoName }: Record<string, string | undefined>) => {
const repo = `${repoOwner}/${repoName}`
if (values.currentTeamId && values.lastRepo !== repo) {
actions.rememberRepo(values.currentTeamId, repo)
}
},
])
),
})),
// The repository switcher in every page's title needs the list, whether or not a forward asked for it.
afterMount(({ actions, values }) => {
if (!values.githubSources && !values.githubSourcesLoading) {
actions.loadGithubSources()
}
}),
])