ref0-git 0.11.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/app/apps/github/generated/git-rest.ts +152 -3
  2. package/app/apps/github/migrations/postgres/0001_auth.sql +8 -1
  3. package/app/apps/github/migrations/sql/0005_repo_grants.sql +10 -0
  4. package/app/apps/github/src/clients/allowed.ts +9 -4
  5. package/app/apps/github/src/components/repos/your-repos.tsx +57 -11
  6. package/app/apps/github/src/context/context.ts +45 -2
  7. package/app/apps/github/src/context/repo-grants.ts +35 -0
  8. package/app/apps/github/src/hooks/repos.ts +14 -3
  9. package/app/apps/github/src/policy.ts +485 -92
  10. package/app/apps/github/src/routes/$owner/$repo/settings/access.tsx +1 -1
  11. package/app/apps/github/src/routes/index.tsx +2 -1
  12. package/app/apps/github/src/settings/access-page.tsx +308 -0
  13. package/app/apps/github/src/settings/access.ts +156 -0
  14. package/app/apps/github/src/settings/settings-layout.tsx +0 -16
  15. package/app/apps/github/src/signin/auth.ts +2 -0
  16. package/app/apps/github/src/signin/orgs.ts +57 -14
  17. package/app/apps/github/src/signin/repo-grants.ts +141 -0
  18. package/app/pnpm-workspace.yaml +2 -2
  19. package/dist/cli/child.mjs +73 -3
  20. package/dist/cli/commands.mjs +2 -0
  21. package/dist/cli/documents.mjs +42 -2
  22. package/dist/cli/keys.mjs +431 -0
  23. package/dist/cli/main.mjs +148 -0
  24. package/dist/cli/prompt.mjs +40 -1
  25. package/dist/cli/ref0-git.mjs +4 -141
  26. package/dist/cli/setup.mjs +115 -13
  27. package/dist/cli/sign-in.mjs +1 -1
  28. package/dist/cli/tools-node.mjs +20 -0
  29. package/dist/cli/tools.mjs +12 -0
  30. package/dist/init/app.mjs +3 -1
  31. package/dist/init/git-module.mjs +23 -9
  32. package/dist/init/metadata.mjs +1 -1
  33. package/dist/init/template.mjs +1 -0
  34. package/dist/init/templates.mjs +17 -12
  35. package/dist/init/versions.mjs +1 -1
  36. package/package.json +5 -5
@@ -1,6 +1,6 @@
1
1
  import { createFileRoute } from '@tanstack/react-router';
2
2
 
3
- import { AccessPage } from '../../../../settings/settings-layout.tsx';
3
+ import { AccessPage } from '../../../../settings/access-page.tsx';
4
4
 
5
5
  export const Route = createFileRoute('/$owner/$repo/settings/access')({ component: Access });
6
6
 
@@ -22,6 +22,7 @@ export const Route = createFileRoute('/')({
22
22
  const owners = [
23
23
  { kind: 'viewer' as const, login },
24
24
  ...orgs.map((org) => ({ kind: 'org' as const, login: org })),
25
+ { kind: 'shared' as const, login },
25
26
  ];
26
27
 
27
28
  await Promise.all(
@@ -33,7 +34,7 @@ export const Route = createFileRoute('/')({
33
34
  component: Home,
34
35
  });
35
36
 
36
- /** The viewer's repositories and their orgs'. */
37
+ /** The viewer's repositories, their orgs', and those shared with them. */
37
38
  function Home() {
38
39
  const { viewer } = Route.useRouteContext();
39
40
  const navigate = Route.useNavigate();
@@ -0,0 +1,308 @@
1
+ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
2
+ import { LockIcon } from 'lucide-react';
3
+ import { useState, type FormEvent } from 'react';
4
+ import { toast } from 'sonner';
5
+
6
+ import { useClients } from '../clients/clients.ts';
7
+ import type { RepoPlace } from '../code/places.ts';
8
+ import { ConfirmAction } from '../components/confirm-action.tsx';
9
+ import { LoadFailed } from '../components/states/states.tsx';
10
+ import { UserAvatar } from '../components/user-avatar.tsx';
11
+ import { Alert, AlertDescription } from '../components/ui/alert.tsx';
12
+ import { Button } from '../components/ui/button.tsx';
13
+ import { Field, FieldError, FieldGroup, FieldLabel } from '../components/ui/field.tsx';
14
+ import { Input } from '../components/ui/input.tsx';
15
+ import {
16
+ Select,
17
+ SelectContent,
18
+ SelectGroup,
19
+ SelectItem,
20
+ SelectTrigger,
21
+ SelectValue,
22
+ } from '../components/ui/select.tsx';
23
+ import { Skeleton } from '../components/ui/skeleton.tsx';
24
+ import {
25
+ Table,
26
+ TableBody,
27
+ TableCell,
28
+ TableHead,
29
+ TableHeader,
30
+ TableRow,
31
+ } from '../components/ui/table.tsx';
32
+ import { useAllowed } from '../hooks/allowed.ts';
33
+ import {
34
+ accessKey,
35
+ collaboratorList,
36
+ grantRole,
37
+ removePerson,
38
+ roles,
39
+ teamList,
40
+ type Person,
41
+ type Role,
42
+ } from './access.ts';
43
+
44
+ /** A role's name, as the settings show it. */
45
+ const roleName = (role: Role) => roles.find(([each]) => each === role)?.[1] ?? role;
46
+
47
+ /** A role picked from `roles`, labelled `label`, for the field `id`. */
48
+ function RolePicker({
49
+ id,
50
+ label,
51
+ role,
52
+ disabled = false,
53
+ onPick,
54
+ }: {
55
+ readonly id: string;
56
+ readonly label: string;
57
+ readonly role: Role;
58
+ readonly disabled?: boolean;
59
+ readonly onPick: (role: Role) => void;
60
+ }) {
61
+ return (
62
+ <Select<Role>
63
+ items={roles.map(([value, name]) => ({ value, label: name }))}
64
+ value={role}
65
+ disabled={disabled}
66
+ onValueChange={(picked: Role | null) => {
67
+ if (picked !== null && picked !== role) onPick(picked);
68
+ }}
69
+ >
70
+ <SelectTrigger id={id} aria-label={label} className="w-28">
71
+ <SelectValue />
72
+ </SelectTrigger>
73
+ <SelectContent>
74
+ <SelectGroup>
75
+ {roles.map(([value, name]) => (
76
+ <SelectItem key={value} value={value}>
77
+ {name}
78
+ </SelectItem>
79
+ ))}
80
+ </SelectGroup>
81
+ </SelectContent>
82
+ </Select>
83
+ );
84
+ }
85
+
86
+ /**
87
+ * One person with access: the repo's owner reads Owner, with no control; anyone else their role,
88
+ * a picker for whoever may change it, and Remove, asked in a dialog first, for whoever may remove
89
+ * them.
90
+ */
91
+ function PersonRow({
92
+ place,
93
+ person,
94
+ changes,
95
+ removes,
96
+ }: {
97
+ readonly place: RepoPlace;
98
+ readonly person: Person;
99
+ readonly changes: boolean;
100
+ readonly removes: boolean;
101
+ }) {
102
+ const clients = useClients();
103
+ const client = useQueryClient();
104
+ const refresh = () => client.invalidateQueries({ queryKey: accessKey(place) });
105
+ const changed = useMutation({
106
+ mutationFn: (role: Role) => grantRole(clients, place, person.login, role),
107
+ onSuccess: refresh,
108
+ });
109
+ const removed = useMutation({
110
+ mutationFn: () => removePerson(clients, place, person.login),
111
+ onSuccess: refresh,
112
+ });
113
+ const owner = person.login.toLowerCase() === place.owner.toLowerCase();
114
+ const failed = changed.error ?? removed.error;
115
+
116
+ return (
117
+ <TableRow>
118
+ <TableCell className="whitespace-normal">
119
+ <div className="flex flex-col gap-1">
120
+ <span className="flex items-center gap-2">
121
+ <UserAvatar login={person.login} upload={person.upload} size="sm" account="user" />
122
+ <a href={`/${person.login}`} className="font-medium hover:underline">
123
+ {person.login}
124
+ </a>
125
+ </span>
126
+ {failed !== null && (
127
+ <Alert variant="destructive">
128
+ <AlertDescription>{failed.message}</AlertDescription>
129
+ </Alert>
130
+ )}
131
+ </div>
132
+ </TableCell>
133
+ <TableCell>
134
+ {owner ? (
135
+ <span className="text-muted-foreground">Owner</span>
136
+ ) : changes ? (
137
+ <RolePicker
138
+ id={`access-role-${person.login}`}
139
+ label={`${person.login}'s role`}
140
+ role={person.role}
141
+ disabled={changed.isPending}
142
+ onPick={(role) => changed.mutate(role)}
143
+ />
144
+ ) : (
145
+ roleName(person.role)
146
+ )}
147
+ </TableCell>
148
+ <TableCell className="text-right">
149
+ {removes && !owner && (
150
+ <ConfirmAction
151
+ label="Remove"
152
+ title={`Remove ${person.login}'s access to ${place.owner}/${place.repo}?`}
153
+ description="They can't read or change it any more, unless the host lets them some other way."
154
+ confirm="Remove access"
155
+ disabled={removed.isPending}
156
+ onConfirm={() => removed.mutate()}
157
+ />
158
+ )}
159
+ </TableCell>
160
+ </TableRow>
161
+ );
162
+ }
163
+
164
+ /** Gives someone, by their login, a role on the repo at once: there's no invitation to accept. */
165
+ function AddPerson({ place }: { readonly place: RepoPlace }) {
166
+ const clients = useClients();
167
+ const client = useQueryClient();
168
+ const [login, setLogin] = useState('');
169
+ const [role, setRole] = useState<Role>('write');
170
+ const [tried, setTried] = useState(false);
171
+ const added = useMutation({
172
+ mutationFn: () => grantRole(clients, place, login.trim(), role),
173
+ onSuccess: async () => {
174
+ toast.success(`Gave ${login.trim()} ${roleName(role)} access`);
175
+ setLogin('');
176
+ setTried(false);
177
+ await client.invalidateQueries({ queryKey: accessKey(place) });
178
+ },
179
+ });
180
+ const problem = login.trim() === '' ? 'Enter the login of someone who has signed up' : undefined;
181
+
182
+ const submit = (event: FormEvent<HTMLFormElement>) => {
183
+ event.preventDefault();
184
+ setTried(true);
185
+
186
+ if (problem === undefined && !added.isPending) added.mutate();
187
+ };
188
+
189
+ return (
190
+ <form noValidate aria-label="Add people" onSubmit={submit} className="flex flex-col gap-3">
191
+ <FieldGroup className="flex-row flex-wrap items-end gap-3">
192
+ <Field data-invalid={tried && problem !== undefined} className="min-w-48 flex-1">
193
+ <FieldLabel htmlFor="access-login">Login</FieldLabel>
194
+ <Input
195
+ id="access-login"
196
+ autoComplete="off"
197
+ aria-invalid={tried && problem !== undefined}
198
+ value={login}
199
+ onChange={(event) => setLogin(event.target.value)}
200
+ />
201
+ {tried && <FieldError>{problem}</FieldError>}
202
+ </Field>
203
+ <Field className="w-auto">
204
+ <FieldLabel htmlFor="access-role">Role</FieldLabel>
205
+ <RolePicker id="access-role" label="Role" role={role} onPick={setRole} />
206
+ </Field>
207
+ <Button type="submit" disabled={added.isPending}>
208
+ Add
209
+ </Button>
210
+ </FieldGroup>
211
+ {added.error !== null && (
212
+ <Alert variant="destructive">
213
+ <AlertDescription>{added.error.message}</AlertDescription>
214
+ </Alert>
215
+ )}
216
+ </form>
217
+ );
218
+ }
219
+
220
+ /** The owning org's teams with access, read only, drawn only where the host lists some. */
221
+ function TeamList({ place }: { readonly place: RepoPlace }) {
222
+ const teams = useQuery(teamList(useClients(), place));
223
+ if (teams.data === undefined || teams.data.length === 0) return null;
224
+
225
+ return (
226
+ <Table aria-label="Teams with access" className="border">
227
+ <TableHeader>
228
+ <TableRow>
229
+ <TableHead>Team</TableHead>
230
+ <TableHead>Role</TableHead>
231
+ </TableRow>
232
+ </TableHeader>
233
+ <TableBody>
234
+ {teams.data.map((team) => (
235
+ <TableRow key={team.slug}>
236
+ <TableCell className="font-medium">{team.name}</TableCell>
237
+ <TableCell>{roleName(team.role)}</TableCell>
238
+ </TableRow>
239
+ ))}
240
+ </TableBody>
241
+ </Table>
242
+ );
243
+ }
244
+
245
+ /**
246
+ * Who may read and write the repo, as the host's grants say (#1998): its people, the owner first,
247
+ * and its teams, with Add, a role's change and Remove for whoever the drop-in lets make each call.
248
+ * It's drawn inside the settings, which open only for the repo's admins, as GitHub's do: an admin
249
+ * whose token is too narrow for a change sees the list alone. A host that shares no repos keeps it
250
+ * to its policy, and the page says so.
251
+ */
252
+ export function AccessPage({ place }: { readonly place: RepoPlace }) {
253
+ const clients = useClients();
254
+ const access = useQuery(collaboratorList(clients, place));
255
+ const allowed = useAllowed(place);
256
+ const changes = allowed.has('collaborator.create');
257
+
258
+ return (
259
+ <section aria-label="Collaborators and teams" className="flex flex-col gap-3">
260
+ <h2 className="text-lg font-semibold">Collaborators and teams</h2>
261
+ {access.error !== null ? (
262
+ <LoadFailed message={access.error.message} />
263
+ ) : access.data === undefined ? (
264
+ <Skeleton className="h-24" />
265
+ ) : access.data.kind === 'host' ? (
266
+ <Alert>
267
+ <LockIcon />
268
+ <AlertDescription>
269
+ Access is set by the host. Who may read and write {place.owner}/{place.repo} is decided
270
+ by its policy, and can't be changed here.
271
+ </AlertDescription>
272
+ </Alert>
273
+ ) : (
274
+ <>
275
+ {changes && <AddPerson place={place} />}
276
+ <Table aria-label="People with access" className="border">
277
+ <TableHeader>
278
+ <TableRow>
279
+ <TableHead>Person</TableHead>
280
+ <TableHead>Role</TableHead>
281
+ <TableHead>
282
+ <span className="sr-only">Remove</span>
283
+ </TableHead>
284
+ </TableRow>
285
+ </TableHeader>
286
+ <TableBody>
287
+ {access.data.people.map((person) => (
288
+ <PersonRow
289
+ key={person.login}
290
+ place={place}
291
+ person={person}
292
+ changes={changes}
293
+ removes={allowed.has('collaborator.delete')}
294
+ />
295
+ ))}
296
+ </TableBody>
297
+ </Table>
298
+ {access.data.more && (
299
+ <p className="text-sm text-muted-foreground">
300
+ More people have access than are shown here.
301
+ </p>
302
+ )}
303
+ <TeamList place={place} />
304
+ </>
305
+ )}
306
+ </section>
307
+ );
308
+ }
@@ -0,0 +1,156 @@
1
+ import type { components } from '@octokit/openapi-types';
2
+ import { queryOptions } from '@tanstack/react-query';
3
+
4
+ import type { Clients } from '../clients/clients.ts';
5
+ import type { RepoPlace } from '../code/places.ts';
6
+ import { everyPage, failure } from '../hooks/answers.ts';
7
+ import { uploadOf } from '../hooks/avatars.ts';
8
+
9
+ type RestCollaborator = components['schemas']['collaborator'];
10
+
11
+ type RestTeam = components['schemas']['team'];
12
+
13
+ /** A role a repo's grant gives, as the settings name it. */
14
+ export type Role = 'read' | 'write' | 'admin';
15
+
16
+ /** The roles in the order the settings offer them, each with its name. */
17
+ export const roles: readonly (readonly [Role, string])[] = [
18
+ ['read', 'Read'],
19
+ ['write', 'Write'],
20
+ ['admin', 'Admin'],
21
+ ];
22
+
23
+ /** GitHub's `permission` a write names for each role. */
24
+ const permissionOf: Readonly<Record<Role, 'pull' | 'push' | 'admin'>> = {
25
+ read: 'pull',
26
+ write: 'push',
27
+ admin: 'admin',
28
+ };
29
+
30
+ /** The role GitHub's `role_name` or `permission` names, `read` for one it holds less than write. */
31
+ const roleOf = (name: string): Role =>
32
+ name === 'admin' ? 'admin' : name === 'write' || name === 'push' ? 'write' : 'read';
33
+
34
+ /** One person with access to the repo, as its settings list them. */
35
+ export interface Person {
36
+ readonly login: string;
37
+ /** Their uploaded picture, or `null` for none, as `uploadOf` reads the answer's `avatar_url`. */
38
+ readonly upload: string | null;
39
+ readonly role: Role;
40
+ }
41
+
42
+ /** One of the owning org's teams with access to the repo, as its settings list them. */
43
+ export interface Team {
44
+ readonly slug: string;
45
+ readonly name: string;
46
+ readonly role: Role;
47
+ }
48
+
49
+ /**
50
+ * Who the repo is shared with: its people, the owner first, as the drop-in lists them, and whether
51
+ * more were left past what's read; or `host` where the host shares no repos, whose drop-in answers
52
+ * the list 404 on a repo the settings already read.
53
+ */
54
+ export type Access =
55
+ | { readonly kind: 'host' }
56
+ | { readonly kind: 'shared'; readonly people: readonly Person[]; readonly more: boolean };
57
+
58
+ const personOf = (person: RestCollaborator): Person => ({
59
+ login: person.login,
60
+ upload: uploadOf(person.avatar_url),
61
+ role: roleOf(person.role_name),
62
+ });
63
+
64
+ const teamOf = (team: RestTeam): Team => ({
65
+ slug: team.slug,
66
+ name: team.name,
67
+ role: roleOf(team.permission),
68
+ });
69
+
70
+ /** The query key of the repo's people and teams, which each change refreshes. */
71
+ export const accessKey = (place: RepoPlace) => ['access', place.owner, place.repo] as const;
72
+
73
+ /** Thrown inside the list's read for its 404, which `collaboratorList` answers as `host`. */
74
+ class NotShared extends Error {}
75
+
76
+ /**
77
+ * Whether the repo still reads for the caller, asked now: a collaborator route's 404 means the
78
+ * host shares no repos, or no one signed up as the login, only while it does. Otherwise the repo
79
+ * is gone, or out of the caller's reach, since the page's cached read of it.
80
+ */
81
+ const stillReads = async (clients: Clients, place: RepoPlace) =>
82
+ (await clients.github.GET('/repos/{owner}/{repo}', { params: { path: place } })).response.ok;
83
+
84
+ /**
85
+ * The repo's people, every page to `pagesMost`, or `host` where the host shares no repos: a 404 on
86
+ * a repo that no longer reads fails as the 404 it is.
87
+ */
88
+ export const collaboratorList = (clients: Clients, place: RepoPlace) =>
89
+ queryOptions({
90
+ queryKey: [...accessKey(place), 'people'],
91
+ queryFn: async (): Promise<Access> => {
92
+ try {
93
+ const people = await everyPage(async (after) => {
94
+ // `after` is the drop-in's cursor, which GitHub's types don't name: a spread passes it.
95
+ const answer = await clients.github.GET('/repos/{owner}/{repo}/collaborators', {
96
+ params: { path: place, query: { ...{ per_page: 100, after } } },
97
+ });
98
+
99
+ if (answer.response.status === 404 && (await stillReads(clients, place))) {
100
+ throw new NotShared();
101
+ }
102
+
103
+ if (answer.data === undefined) throw failure("Who has access didn't load", answer);
104
+
105
+ return { rows: answer.data.map(personOf), link: answer.response.headers.get('link') };
106
+ });
107
+
108
+ return { kind: 'shared', people: people.rows, more: people.more };
109
+ } catch (error) {
110
+ if (error instanceof NotShared) return { kind: 'host' };
111
+
112
+ throw error;
113
+ }
114
+ },
115
+ });
116
+
117
+ /** The repo's teams, their first 100, which a host with no teams lists empty. */
118
+ export const teamList = (clients: Clients, place: RepoPlace) =>
119
+ queryOptions({
120
+ queryKey: [...accessKey(place), 'teams'],
121
+ queryFn: async (): Promise<readonly Team[]> => {
122
+ const answer = await clients.github.GET('/repos/{owner}/{repo}/teams', {
123
+ params: { path: place, query: { per_page: 100 } },
124
+ });
125
+ if (answer.response.status === 404) return [];
126
+
127
+ if (answer.data === undefined) throw failure("The teams didn't load", answer);
128
+
129
+ return answer.data.map(teamOf);
130
+ },
131
+ });
132
+
133
+ /**
134
+ * Gives `login` `role` on the repo, at once, as the drop-in grants it: a new person or a changed
135
+ * role alike. A login no one signed up as says so, while the repo still reads.
136
+ */
137
+ export const grantRole = async (clients: Clients, place: RepoPlace, login: string, role: Role) => {
138
+ const answer = await clients.github.PUT('/repos/{owner}/{repo}/collaborators/{username}', {
139
+ params: { path: { ...place, username: login } },
140
+ body: { permission: permissionOf[role] },
141
+ });
142
+
143
+ if (answer.response.status === 404 && (await stillReads(clients, place))) {
144
+ throw new Error(`No one has signed up as ${login}`);
145
+ }
146
+
147
+ if (!answer.response.ok) throw failure(`${login} wasn't given access`, answer);
148
+ };
149
+
150
+ /** Takes `login`'s access to the repo away. */
151
+ export const removePerson = async (clients: Clients, place: RepoPlace, login: string) => {
152
+ const answer = await clients.github.DELETE('/repos/{owner}/{repo}/collaborators/{username}', {
153
+ params: { path: { ...place, username: login } },
154
+ });
155
+ if (!answer.response.ok) throw failure(`${login}'s access wasn't removed`, answer);
156
+ };
@@ -98,19 +98,3 @@ export function SettingsLayout({
98
98
  </div>
99
99
  );
100
100
  }
101
-
102
- /** Who may read and write the repo: the host's policy decides, and nothing here changes it. */
103
- export function AccessPage({ place }: { readonly place: RepoPlace }) {
104
- return (
105
- <section aria-label="Collaborators and teams" className="flex flex-col gap-3">
106
- <h2 className="text-lg font-semibold">Collaborators and teams</h2>
107
- <Alert>
108
- <LockIcon />
109
- <AlertDescription>
110
- Access is set by the host. Who may read and write {place.owner}/{place.repo} is decided by
111
- its policy, and can't be changed here.
112
- </AlertDescription>
113
- </Alert>
114
- </section>
115
- );
116
- }
@@ -31,6 +31,7 @@ import {
31
31
  import { revokeRetrying } from './revoke.ts';
32
32
  import { open, seal } from './seal.ts';
33
33
  import { avatarTable, avatars } from './avatars.ts';
34
+ import { repoGrantTable } from './repo-grants.ts';
34
35
  import { type Unborn, forgetUnborn } from './unborn.ts';
35
36
 
36
37
  /** A Kysely dialect, and the SQL it speaks, as Better Auth takes one: libSQL's, or Postgres's. */
@@ -440,6 +441,7 @@ export const starterAuth = (options: StarterAuthOptions): Auth => {
440
441
  }),
441
442
  ownerNames(),
442
443
  avatarTable(),
444
+ repoGrantTable(),
443
445
  // A credential ID names one passkey only, since the plugin finds a sign-in's passkey by it.
444
446
  // Its schema only indexes the column, so this makes it unique, in each dialect's migration.
445
447
  {
@@ -2,6 +2,7 @@ import type { PeopleAccountKind, PeopleFound, PeopleOrgRole } from '@ref0/github
2
2
  import type { DBAdapter } from 'better-auth';
3
3
 
4
4
  import type { Accounts, Membership } from '../context/context.ts';
5
+ import { idsPerRead } from './avatars.ts';
5
6
  import { isHeld } from './owner-names.ts';
6
7
 
7
8
  /**
@@ -23,21 +24,29 @@ export interface LoginsPage {
23
24
  }
24
25
 
25
26
  /**
26
- * A person who has signed up: the name they go by, which is their login when they gave none, and
27
- * their row's ID, which a rename keeps.
27
+ * A person who has signed up: the name they go by, which is their login when they gave none, their
28
+ * row's ID, which a rename keeps, and their login as it's stored, whatever case it was asked in.
28
29
  */
29
30
  export interface SignedUp {
30
31
  readonly name: string;
31
32
  readonly id: string;
33
+ readonly login: string;
32
34
  }
33
35
 
36
+ /**
37
+ * The host's people and orgs. Each lookup finds a login or an org asked in any case, as GitHub's
38
+ * do, but `held`, which only that spelling passes, since Git keeps `ACME/app` apart from
39
+ * `acme/app`.
40
+ */
34
41
  export interface Orgs extends Accounts {
35
- /** Whether a person or an org holds `login`, so a repo may be made under it. */
42
+ /** Whether a person or an org holds `login` as it's spelled, so a repo may be made under it. */
36
43
  readonly held: (login: string) => Promise<boolean>;
37
44
  /** The person who signed up as `login`, or `undefined` when no one has. */
38
45
  readonly person: (login: string) => Promise<SignedUp | undefined>;
39
- /** Whether an org was made as `login`. */
40
- readonly org: (login: string) => Promise<boolean>;
46
+ /** The login an org was made as, asked as `login`, or `undefined` when none was. */
47
+ readonly org: (login: string) => Promise<string | undefined>;
48
+ /** The login of each person whose row ID is one of `ids`, by ID, leaving out IDs no one holds. */
49
+ readonly loginsById: (ids: readonly string[]) => Promise<ReadonlyMap<string, string>>;
41
50
  /** Which of `logins` belong to the org `org`, in any role, each once, in login order. */
42
51
  readonly among: (org: string, logins: readonly string[]) => Promise<readonly string[]>;
43
52
  /**
@@ -77,6 +86,21 @@ interface Row {
77
86
 
78
87
  interface PersonRow extends Row {
79
88
  readonly name: string;
89
+ readonly username: string;
90
+ }
91
+
92
+ interface OrgRow extends Row {
93
+ readonly slug: string;
94
+ }
95
+
96
+ /**
97
+ * `login` as a lookup matches it: sign-up and the org plugin store each login and slug lowercased,
98
+ * so a login asked in any case finds its row.
99
+ */
100
+ const folded = (login: string) => login.toLowerCase();
101
+
102
+ interface PersonLogin extends Row {
103
+ readonly username: string;
80
104
  }
81
105
 
82
106
  interface MemberRow {
@@ -118,22 +142,23 @@ export const orgsOver = (adapterOf: () => Promise<OrgsAdapter>): Orgs => {
118
142
 
119
143
  return adapter.findOne<PersonRow>({
120
144
  model: 'user',
121
- where: [{ field: 'username', value: login }],
145
+ where: [{ field: 'username', value: folded(login) }],
122
146
  });
123
147
  };
124
148
 
125
149
  const personId = async (login: string) => (await personRow(login))?.id;
126
150
 
127
- const orgId = async (login: string) => {
151
+ const orgRow = async (login: string) => {
128
152
  const adapter = await adapterOf();
129
- const row = await adapter.findOne<Row>({
153
+
154
+ return adapter.findOne<OrgRow>({
130
155
  model: 'organization',
131
- where: [{ field: 'slug', value: login }],
156
+ where: [{ field: 'slug', value: folded(login) }],
132
157
  });
133
-
134
- return row?.id;
135
158
  };
136
159
 
160
+ const orgId = async (login: string) => (await orgRow(login))?.id;
161
+
137
162
  /** The person `login`'s member row in the org `org`, or `undefined` when they aren't in it. */
138
163
  const memberRow = async (org: string, login: string) => {
139
164
  const [organizationId, userId] = await Promise.all([orgId(org), personId(login)]);
@@ -176,9 +201,27 @@ export const orgsOver = (adapterOf: () => Promise<OrgsAdapter>): Orgs => {
176
201
  person: async (login) => {
177
202
  const row = await personRow(login);
178
203
 
179
- return row === null ? undefined : { name: row.name, id: row.id };
204
+ return row === null ? undefined : { name: row.name, id: row.id, login: row.username };
205
+ },
206
+ org: async (login) => (await orgRow(login))?.slug,
207
+ loginsById: async (ids) => {
208
+ const adapter = await adapterOf();
209
+ const reads = Array.from({ length: Math.ceil(ids.length / idsPerRead) }, (_, n) =>
210
+ ids.slice(n * idsPerRead, (n + 1) * idsPerRead),
211
+ );
212
+ const rows = await Promise.all(
213
+ reads.map((some) =>
214
+ adapter.findMany<PersonLogin>({
215
+ model: 'user',
216
+ where: [{ field: 'id', operator: 'in', value: [...some] }],
217
+ select: ['id', 'username'],
218
+ limit: some.length,
219
+ }),
220
+ ),
221
+ );
222
+
223
+ return new Map(rows.flat().map((row) => [row.id, row.username]));
180
224
  },
181
- org: async (login) => (await orgId(login)) !== undefined,
182
225
  account: async (login) => {
183
226
  const [userId, organizationId] = await Promise.all([personId(login), orgId(login)]);
184
227
  if (userId !== undefined) return { kind: 'user', id: userId };
@@ -193,7 +236,7 @@ export const orgsOver = (adapterOf: () => Promise<OrgsAdapter>): Orgs => {
193
236
  : { admin: isAdmin(row), since: new Date(row.createdAt).getTime() };
194
237
  },
195
238
  among: async (org, logins) => {
196
- const asked = [...new Set(logins)];
239
+ const asked = [...new Set(logins.map(folded))];
197
240
  const organizationId = asked.length === 0 ? undefined : await orgId(org);
198
241
  if (organizationId === undefined) return [];
199
242