import type { RepoAccess, Team, TeamAccess } from './org-settings-types.js';
export type Level = 'none' | TeamAccess;
export const rank: Record<Level, number> = { none: 0, read: 1, write: 2, admin: 3 };
export const levelLabel: Record<Level, string> = { none: 'No access', read: 'Read', write: 'Write', admin: 'Admin' };
export const byslug = (teams: Team[], slug: string | null) => (slug ? teams.find((t) => t.slug === slug) : undefined);
// Parents nearest first; the seen set guards against a cycle in hand-edited data.
export const ancestors = (teams: Team[], team: Team) => {
const chain: Team[] = [];
const seen = new Set([team.slug]);
let parent = byslug(teams, team.parent);
while (parent && !seen.has(parent.slug)) {
chain.push(parent);
seen.add(parent.slug);
parent = byslug(teams, parent.parent);
}
return chain;
};
export type Grant = { level: TeamAccess; from: Team };
// What a team gets from its parents, the highest level per repository.
export const inheritedRepos = (teams: Team[], team: Team) => {
const out: Record<string, Grant> = {};
for (const a of ancestors(teams, team))
for (const [repo, level] of Object.entries(a.repos)) if (!out[repo] || rank[level] > rank[out[repo].level]) out[repo] = { level, from: a };
return out;
};
export const effectiveRepos = (teams: Team[], team: Team) => {
const out: Record<string, Grant> = { ...inheritedRepos(teams, team) };
for (const [repo, level] of Object.entries(team.repos)) if (!out[repo] || rank[level] >= rank[out[repo].level]) out[repo] = { level, from: team };
return out;
};
export type Reach = { level: Level; source: string };
export const personAccess = (teams: Team[], person: { handle: string; role: string }, base: RepoAccess, repos: string[]) => {
const out: Record<string, Reach> = {};
const own = person.role === 'Owner' ? ({ level: 'admin', source: 'Owner of the organization' } as const) : ({ level: base, source: 'Base access for members' } as const);
const mine = teams.filter((t) => t.members.includes(person.handle));
for (const repo of repos) {
let best: Reach = { level: own.level, source: own.source };
for (const t of mine) {
const g = effectiveRepos(teams, t)[repo];
if (g && rank[g.level] > rank[best.level]) best = { level: g.level, source: g.from === t ? t.name : `${t.name}, from ${g.from.name}` };
}
out[repo] = best;
}
return out;
};