Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SourceControlAccountSettings.logic.ts

44 lines1.9 KB

1import type { SourceControlProviderAuth } from "@t3tools/contracts";
2import type { HostCredentialSettings } from "@t3tools/client-runtime/source-control-clients";
3​
4export type DiscoveredAccount = NonNullable<SourceControlProviderAuth["accounts"]>[number];
5​
6export interface HostAccountGroup {
7 readonly host: string;
8 readonly activeAccount: string | null;
9 readonly selectable: ReadonlyArray<string>;
10 readonly broken: ReadonlyArray<DiscoveredAccount>;
11 readonly environmentVariable: string | null;
13​
14export function groupHostAccounts(
15 accounts: ReadonlyArray<DiscoveredAccount>,
16): ReadonlyArray<HostAccountGroup> {
17 const hosts = [...new Set(accounts.map((entry) => entry.host))];
18 return hosts.map((host) => {
19 const entries = accounts.filter((entry) => entry.host === host);
20 const stored = entries.filter((entry) => entry.environmentVariable === undefined);
21 const selectable = stored.filter((entry) => entry.authenticated);
22 return {
23 host,
24 activeAccount: (selectable.find((entry) => entry.active) ?? selectable[0])?.account ?? null,
25 selectable: selectable.map((entry) => entry.account),
26 broken: stored.filter((entry) => !entry.authenticated),
27 environmentVariable:
28 entries.find((entry) => entry.environmentVariable)?.environmentVariable ?? null,
29 };
30 });
32​
33export function nextHostAccountChoices(
34 current: HostCredentialSettings["hosts"],
35 host: string,
36 change: { readonly enabled?: boolean; readonly account?: string | null },
37): HostCredentialSettings["hosts"] {
38 const previous = current[host];
39 const enabled = change.enabled ?? previous?.enabled ?? true;
40 const account = change.account === undefined ? previous?.account : (change.account ?? undefined);
41 const { [host]: _replaced, ...rest } = current;
42 if (enabled && account === undefined) return rest;
43 return { ...rest, [host]: { enabled, ...(account === undefined ? {} : { account }) } };