| 1 | /** |
| 2 | * What Settings → Account says about deleting your account: what goes with |
| 3 | * it, why it cannot go yet, and what you type to confirm. Identity decides |
| 4 | * all of it again (`account_deletion.rs`); these say the same words first. |
| 5 | * No Workers or React imports, so it can be tested under Node. |
| 6 | */ |
| 7 | import type { AccountDeletion } from "@g1t/contracts"; |
| 8 | |
| 9 | const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`; |
| 10 | |
| 11 | /** `a`, `a and b`, `a, b and c`. */ |
| 12 | function list(items: string[]): string { |
| 13 | if (items.length <= 1) return items.join(""); |
| 14 | return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`; |
| 15 | } |
| 16 | |
| 17 | /** Why the account cannot be deleted, as one sentence, or null. */ |
| 18 | export function accountDeletionRefusal(deletion: AccountDeletion | null): string | null { |
| 19 | if (!deletion) return null; |
| 20 | if (deletion.protected) return `${deletion.username} is protected and can never be deleted.`; |
| 21 | const slugs = deletion.sole_owner_of.map((workspace) => workspace.slug); |
| 22 | if (slugs.length === 1) { |
| 23 | return `You are the only owner of ${slugs[0]}. Make someone else an owner of it, or delete it, first.`; |
| 24 | } |
| 25 | if (slugs.length > 1) { |
| 26 | return `You are the only owner of ${list(slugs)}. Make someone else an owner of each, or delete them, first.`; |
| 27 | } |
| 28 | return null; |
| 29 | } |
| 30 | |
| 31 | /** What deleting the account takes with it, one line each. Nothing it does not have is listed. */ |
| 32 | export function whatAccountDeletionTakes(deletion: AccountDeletion): string[] { |
| 33 | const lines: string[] = []; |
| 34 | if (deletion.workspaces > 0) lines.push(`Your membership of ${plural(deletion.workspaces, "workspace", "workspaces")}`); |
| 35 | if (deletion.repositories > 0) { |
| 36 | lines.push(`Your role on ${plural(deletion.repositories, "repository", "repositories")} you were added to`); |
| 37 | } |
| 38 | if (deletion.tokens > 0) lines.push(plural(deletion.tokens, "access token", "access tokens")); |
| 39 | if (deletion.ssh_keys > 0) lines.push(plural(deletion.ssh_keys, "SSH key", "SSH keys")); |
| 40 | if (deletion.applications > 0) { |
| 41 | lines.push(plural(deletion.applications, "connected application", "connected applications")); |
| 42 | } |
| 43 | return lines; |
| 44 | } |
| 45 | |
| 46 | /** Whether what was typed confirms the username: the username itself, in any case. */ |
| 47 | export function confirmsUsername(username: string, typed: string): boolean { |
| 48 | const value = typed.trim(); |
| 49 | return value !== "" && value.toLowerCase() === username.trim().toLowerCase(); |
| 50 | } |