@app-vitals/agent-admin 1.77.0 → 1.79.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.
@@ -0,0 +1,179 @@
1
+ /**
2
+ * admin/src/github-agent-installation-crawler.ts
3
+ * Crawl each agent App's own installation repos into the repo cache (GLC-1.5).
4
+ *
5
+ * A PageSource over the installer client's single-page installation listing,
6
+ * fed through the same resumable engine (crawlRepos) and completeness check as
7
+ * the lookup crawl, under appKind "agent" and appRef = the agent's GH_APP_ID.
8
+ * Scheduling is not here (GLC-1.4).
9
+ */
10
+
11
+ import type { Clock } from "./clock.ts";
12
+ import type { SnapshotKey } from "./github-repo-cache.ts";
13
+ import {
14
+ type CrawlResult,
15
+ type CrawlStore,
16
+ crawlRepos,
17
+ type PageSource,
18
+ type RepoPage,
19
+ } from "./github-repo-crawler.ts";
20
+ import { identityOf } from "./installation-repos-service.ts";
21
+ import {
22
+ AppNotInstalledError,
23
+ type AppIdentity,
24
+ type InstallationAgentRecord,
25
+ type InstallationRepoClient,
26
+ matchInstallation,
27
+ } from "./installation-ports.ts";
28
+
29
+ /**
30
+ * SnapshotKey.accountId for an agent with no account (the deployment-wide
31
+ * installer/App pair). The cache requires a non-empty accountId.
32
+ */
33
+ export const DEPLOYMENT_WIDE_ACCOUNT_KEY = "deployment";
34
+
35
+ /** The slice of the installer client the crawl needs. */
36
+ export type AgentInstallationClient = Pick<
37
+ InstallationRepoClient,
38
+ "listOrgInstallations"
39
+ > &
40
+ Required<Pick<InstallationRepoClient, "listInstallationRepositoriesPage">>;
41
+
42
+ export interface AgentInstallationPageSource extends PageSource {
43
+ /** The agent App's installation id on the org; throws AppNotInstalledError. Cached. */
44
+ resolveInstallationId(): Promise<number>;
45
+ }
46
+
47
+ export interface AgentInstallationSourceOptions {
48
+ client: AgentInstallationClient;
49
+ org: string;
50
+ appId: number;
51
+ identity?: AppIdentity;
52
+ }
53
+
54
+ /**
55
+ * PageSource over the agent App's installation repositories on `org`. The
56
+ * installation id is resolved lazily, once per source.
57
+ *
58
+ * The enterprise endpoint returns a bare array without total_count, so
59
+ * totalCount is (page - 1) * perPage + repos.length: exact on the last page
60
+ * because every earlier page is full. If rows duplicated or shifted between
61
+ * pages, the engine sees fewer distinct rows than this total and marks the
62
+ * crawl incomplete.
63
+ */
64
+ export function agentInstallationPageSource(
65
+ opts: AgentInstallationSourceOptions,
66
+ ): AgentInstallationPageSource {
67
+ const { client, org, appId, identity } = opts;
68
+ let installationId: Promise<number> | undefined;
69
+ const resolveInstallationId = (): Promise<number> => {
70
+ installationId ??= client
71
+ .listOrgInstallations(org, identity?.accountId)
72
+ .then((installs) => {
73
+ const found = matchInstallation(installs, appId, identity);
74
+ if (!found) throw new AppNotInstalledError(appId, org);
75
+ return found.id;
76
+ });
77
+ // Do not cache a failure: a later page or run may succeed.
78
+ installationId.catch(() => {
79
+ installationId = undefined;
80
+ });
81
+ return installationId;
82
+ };
83
+ return {
84
+ resolveInstallationId,
85
+ async fetchPage(page: number): Promise<RepoPage> {
86
+ const id = await resolveInstallationId();
87
+ const res = await client.listInstallationRepositoriesPage(
88
+ org,
89
+ id,
90
+ page,
91
+ identity?.accountId,
92
+ );
93
+ return {
94
+ repos: res.repos.map((r) => ({
95
+ githubId: r.id,
96
+ fullName: r.fullName,
97
+ archived: r.archived,
98
+ })),
99
+ totalCount: (page - 1) * res.perPage + res.repos.length,
100
+ hasNext: res.hasNext,
101
+ };
102
+ },
103
+ };
104
+ }
105
+
106
+ export type AgentInstallationCrawlResult =
107
+ | CrawlResult
108
+ /** The agent App has no installation on the org; recorded as an empty, complete snapshot. */
109
+ | { outcome: "not_installed"; pagesFetched: 0; swept: number }
110
+ /** The agent has no GH_APP_ID; nothing was read or written. */
111
+ | { outcome: "skipped_no_app_id"; pagesFetched: 0 };
112
+
113
+ export interface CrawlAgentInstallationOptions {
114
+ agent: Pick<
115
+ InstallationAgentRecord,
116
+ "accountId" | "appId" | "clientId" | "slug"
117
+ >;
118
+ org: string;
119
+ client: AgentInstallationClient;
120
+ store: CrawlStore;
121
+ clock: Clock;
122
+ maxPages?: number;
123
+ backoffMs?: (attempts: number) => number;
124
+ }
125
+
126
+ /** Crawl one agent App's installation repos on one org into the cache. */
127
+ export async function crawlAgentInstallation(
128
+ opts: CrawlAgentInstallationOptions,
129
+ ): Promise<AgentInstallationCrawlResult> {
130
+ const { agent, org, client, store, clock } = opts;
131
+ if (agent.appId === undefined) {
132
+ return { outcome: "skipped_no_app_id", pagesFetched: 0 };
133
+ }
134
+ const key: SnapshotKey = {
135
+ accountId: agent.accountId || DEPLOYMENT_WIDE_ACCOUNT_KEY,
136
+ appKind: "agent",
137
+ appRef: String(agent.appId),
138
+ org,
139
+ };
140
+ const source = agentInstallationPageSource({
141
+ client,
142
+ org,
143
+ appId: agent.appId,
144
+ identity: identityOf(agent),
145
+ });
146
+ try {
147
+ await source.resolveInstallationId();
148
+ } catch (err) {
149
+ if (!(err instanceof AppNotInstalledError)) {
150
+ // Let the engine record GitHub failures and rate limits on the snapshot.
151
+ return crawlRepos({ ...engineOpts(), key, source });
152
+ }
153
+ // Not installed: an empty, complete snapshot (stale rows swept), no error.
154
+ const now = clock.now();
155
+ const snap = await store.upsertSnapshot(key, {
156
+ crawlStartedAt: now,
157
+ crawlPage: 0,
158
+ completedAt: now,
159
+ totalCount: 0,
160
+ lastError: null,
161
+ attempts: 0,
162
+ nextAttemptAt: null,
163
+ rateLimitResetAt: null,
164
+ lastTickAt: now,
165
+ });
166
+ const swept = await store.sweepGeneration(snap.id);
167
+ return { outcome: "not_installed", pagesFetched: 0, swept };
168
+ }
169
+ return crawlRepos({ ...engineOpts(), key, source });
170
+
171
+ function engineOpts() {
172
+ return {
173
+ store,
174
+ clock,
175
+ ...(opts.maxPages === undefined ? {} : { maxPages: opts.maxPages }),
176
+ ...(opts.backoffMs === undefined ? {} : { backoffMs: opts.backoffMs }),
177
+ };
178
+ }
179
+ }
@@ -0,0 +1,343 @@
1
+ /**
2
+ * admin/src/github-agent-installation-crawler.unit.test.ts
3
+ * Unit tests for the agent-App installation PageSource and the
4
+ * crawlAgentInstallation orchestrator, against fake pages and an in-memory
5
+ * CrawlStore.
6
+ */
7
+
8
+ import { beforeEach, describe, expect, it } from "bun:test";
9
+ import { GithubEnterpriseError } from "./github-enterprise-client.ts";
10
+ import {
11
+ agentInstallationPageSource,
12
+ crawlAgentInstallation,
13
+ DEPLOYMENT_WIDE_ACCOUNT_KEY,
14
+ type AgentInstallationClient,
15
+ } from "./github-agent-installation-crawler.ts";
16
+ import type {
17
+ CachedRepoInput,
18
+ SnapshotKey,
19
+ SnapshotProgress,
20
+ } from "./github-repo-cache.ts";
21
+ import type { CrawlSnapshot, CrawlStore } from "./github-repo-crawler.ts";
22
+ import { AppNotInstalledError } from "./installation-ports.ts";
23
+
24
+ const T0 = new Date("2026-11-20T12:00:00Z");
25
+ const clock = { now: () => new Date(T0) };
26
+
27
+ class MemoryStore implements CrawlStore {
28
+ keys: SnapshotKey[] = [];
29
+ snap: CrawlSnapshot | null = null;
30
+ rows = new Map<number, { fullName: string; seenAt: Date }>();
31
+ async getSnapshot(key: SnapshotKey) {
32
+ this.keys.push(key);
33
+ return this.snap ? { ...this.snap } : null;
34
+ }
35
+ async upsertSnapshot(key: SnapshotKey, progress: SnapshotProgress = {}) {
36
+ this.keys.push(key);
37
+ const base: CrawlSnapshot = this.snap ?? {
38
+ id: "s1",
39
+ crawlPage: 0,
40
+ crawlStartedAt: null,
41
+ completedAt: null,
42
+ totalCount: null,
43
+ lastError: null,
44
+ attempts: 0,
45
+ nextAttemptAt: null,
46
+ rateLimitResetAt: null,
47
+ lastTickAt: null,
48
+ };
49
+ const next = { ...base } as Record<string, unknown>;
50
+ for (const [k, v] of Object.entries(progress)) {
51
+ if (v !== undefined) next[k] = v;
52
+ }
53
+ this.snap = next as unknown as CrawlSnapshot;
54
+ return { ...this.snap };
55
+ }
56
+ async upsertRepos(_id: string, repos: CachedRepoInput[], seenAt: Date) {
57
+ for (const r of repos) {
58
+ this.rows.set(Number(r.githubId), { fullName: r.fullName, seenAt });
59
+ }
60
+ return repos.length;
61
+ }
62
+ async countReposSeenSince(_id: string, since: Date) {
63
+ return [...this.rows.values()].filter((r) => r.seenAt >= since).length;
64
+ }
65
+ async sweepGeneration(_id: string) {
66
+ const since = this.snap?.crawlStartedAt;
67
+ let n = 0;
68
+ for (const [id, r] of this.rows) {
69
+ if (since && r.seenAt < since) {
70
+ this.rows.delete(id);
71
+ n++;
72
+ }
73
+ }
74
+ return n;
75
+ }
76
+ }
77
+
78
+ interface FakeClientOpts {
79
+ installs?: { id: number; appId?: number; appSlug?: string; clientId?: string }[];
80
+ total?: number;
81
+ perPage?: number;
82
+ failPage?: (page: number) => Error | undefined;
83
+ }
84
+
85
+ function fakeClient(o: FakeClientOpts = {}) {
86
+ const perPage = o.perPage ?? 2;
87
+ const total = o.total ?? 5;
88
+ const calls = { installs: 0, pages: [] as number[] };
89
+ const client: AgentInstallationClient = {
90
+ async listOrgInstallations() {
91
+ calls.installs++;
92
+ return o.installs ?? [{ id: 501, appId: 777 }];
93
+ },
94
+ async listInstallationRepositoriesPage(_org, installationId, page) {
95
+ expect(installationId).toBe(501);
96
+ calls.pages.push(page);
97
+ const err = o.failPage?.(page);
98
+ if (err) throw err;
99
+ const start = (page - 1) * perPage;
100
+ const ids = Array.from({ length: total }, (_, i) => i + 1).slice(
101
+ start,
102
+ start + perPage,
103
+ );
104
+ return {
105
+ repos: ids.map((id) => ({ id, fullName: `acme/r${id}` })),
106
+ hasNext: start + perPage < total,
107
+ perPage,
108
+ };
109
+ },
110
+ };
111
+ return { client, calls };
112
+ }
113
+
114
+ const agent = (over: Record<string, unknown> = {}) => ({
115
+ id: "a1",
116
+ accountId: "acc",
117
+ appId: 777,
118
+ ...over,
119
+ });
120
+
121
+ describe("agentInstallationPageSource", () => {
122
+ it("maps a page and reports totalCount from the page position", async () => {
123
+ const { client } = fakeClient({ total: 5 });
124
+ const src = agentInstallationPageSource({
125
+ client,
126
+ org: "acme",
127
+ appId: 777,
128
+ });
129
+ const p1 = await src.fetchPage(1);
130
+ expect(p1.repos.map((r) => r.fullName)).toEqual(["acme/r1", "acme/r2"]);
131
+ expect(p1.hasNext).toBe(true);
132
+ const p3 = await src.fetchPage(3);
133
+ // (3-1)*2 + 1 row on the last page
134
+ expect(p3.totalCount).toBe(5);
135
+ expect(p3.hasNext).toBe(false);
136
+ });
137
+
138
+ it("carries archived through to the cache input", async () => {
139
+ const src = agentInstallationPageSource({
140
+ client: {
141
+ listOrgInstallations: async () => [{ id: 501, appId: 777 }],
142
+ listInstallationRepositoriesPage: async () => ({
143
+ repos: [{ id: 9, fullName: "acme/x", archived: true }],
144
+ hasNext: false,
145
+ perPage: 100,
146
+ }),
147
+ },
148
+ org: "acme",
149
+ appId: 777,
150
+ });
151
+ expect((await src.fetchPage(1)).repos).toEqual([
152
+ { githubId: 9, fullName: "acme/x", archived: true },
153
+ ]);
154
+ });
155
+
156
+ it("resolves the installation once and caches it", async () => {
157
+ const { client, calls } = fakeClient();
158
+ const src = agentInstallationPageSource({ client, org: "acme", appId: 777 });
159
+ await src.fetchPage(1);
160
+ await src.fetchPage(2);
161
+ await src.resolveInstallationId();
162
+ expect(calls.installs).toBe(1);
163
+ });
164
+
165
+ it("matches by identity (client id) before app id", async () => {
166
+ const { client } = fakeClient({
167
+ installs: [
168
+ { id: 900, appId: 777, clientId: "Iv1.other" },
169
+ { id: 501, clientId: "Iv1.mine" },
170
+ ],
171
+ });
172
+ const src = agentInstallationPageSource({
173
+ client,
174
+ org: "acme",
175
+ appId: 777,
176
+ identity: { clientId: "Iv1.mine" },
177
+ });
178
+ expect(await src.resolveInstallationId()).toBe(501);
179
+ });
180
+
181
+ it("throws AppNotInstalledError when no installation matches", async () => {
182
+ const { client } = fakeClient({ installs: [{ id: 1, appId: 5 }] });
183
+ const src = agentInstallationPageSource({ client, org: "acme", appId: 777 });
184
+ await expect(src.fetchPage(1)).rejects.toBeInstanceOf(AppNotInstalledError);
185
+ });
186
+ });
187
+
188
+ describe("crawlAgentInstallation", () => {
189
+ let store: MemoryStore;
190
+ beforeEach(() => {
191
+ store = new MemoryStore();
192
+ });
193
+
194
+ it("crawls under appKind agent with appRef = String(appId)", async () => {
195
+ const { client } = fakeClient({ total: 5 });
196
+ const res = await crawlAgentInstallation({
197
+ agent: agent(),
198
+ org: "acme",
199
+ client,
200
+ store,
201
+ clock,
202
+ });
203
+ expect(res.outcome).toBe("complete");
204
+ expect(store.keys[0]).toEqual({
205
+ accountId: "acc",
206
+ appKind: "agent",
207
+ appRef: "777",
208
+ org: "acme",
209
+ });
210
+ expect(store.rows.size).toBe(5);
211
+ expect(store.snap?.completedAt).not.toBeNull();
212
+ });
213
+
214
+ it("uses the deployment-wide key when the agent has no account", async () => {
215
+ const { client } = fakeClient();
216
+ await crawlAgentInstallation({
217
+ agent: agent({ accountId: null }),
218
+ org: "acme",
219
+ client,
220
+ store,
221
+ clock,
222
+ });
223
+ expect(store.keys[0]?.accountId).toBe(DEPLOYMENT_WIDE_ACCOUNT_KEY);
224
+ });
225
+
226
+ it("is incomplete (engine completeness check) when rows shift mid-crawl", async () => {
227
+ const { client } = fakeClient({ total: 5 });
228
+ const dup: AgentInstallationClient = {
229
+ listOrgInstallations: client.listOrgInstallations,
230
+ async listInstallationRepositoriesPage(org, id, page) {
231
+ const res = await client.listInstallationRepositoriesPage(org, id, page);
232
+ // page 2 repeats a row from page 1 and loses its own
233
+ return page === 2
234
+ ? { ...res, repos: [res.repos[0], { id: 1, fullName: "acme/r1" }].filter((r): r is NonNullable<typeof r> => !!r) }
235
+ : res;
236
+ },
237
+ };
238
+ const res = await crawlAgentInstallation({
239
+ agent: agent(),
240
+ org: "acme",
241
+ client: dup,
242
+ store,
243
+ clock,
244
+ });
245
+ expect(res.outcome).toBe("incomplete");
246
+ expect(store.snap?.completedAt).toBeNull();
247
+ });
248
+
249
+ it("resumes: a second run continues from the saved page", async () => {
250
+ const { client, calls } = fakeClient({ total: 5 });
251
+ const first = await crawlAgentInstallation({
252
+ agent: agent(),
253
+ org: "acme",
254
+ client,
255
+ store,
256
+ clock,
257
+ maxPages: 1,
258
+ });
259
+ expect(first.outcome).toBe("in_progress");
260
+ const second = await crawlAgentInstallation({
261
+ agent: agent(),
262
+ org: "acme",
263
+ client,
264
+ store,
265
+ clock,
266
+ });
267
+ expect(second.outcome).toBe("complete");
268
+ expect(calls.pages).toEqual([1, 1, 2, 3]);
269
+ });
270
+
271
+ it("records not-installed as a completed empty snapshot, not an error", async () => {
272
+ store.rows.set(1, { fullName: "acme/stale", seenAt: new Date(0) });
273
+ const { client, calls } = fakeClient({ installs: [] });
274
+ const res = await crawlAgentInstallation({
275
+ agent: agent(),
276
+ org: "acme",
277
+ client,
278
+ store,
279
+ clock,
280
+ });
281
+ expect(res).toEqual({ outcome: "not_installed", pagesFetched: 0, swept: 1 });
282
+ expect(calls.pages).toEqual([]);
283
+ expect(store.rows.size).toBe(0);
284
+ expect(store.snap).toMatchObject({
285
+ totalCount: 0,
286
+ lastError: null,
287
+ attempts: 0,
288
+ nextAttemptAt: null,
289
+ });
290
+ expect(store.snap?.completedAt).toEqual(T0);
291
+ });
292
+
293
+ it("skips agents without GH_APP_ID and never touches the store or client", async () => {
294
+ const { client, calls } = fakeClient();
295
+ const res = await crawlAgentInstallation({
296
+ agent: agent({ appId: undefined }),
297
+ org: "acme",
298
+ client,
299
+ store,
300
+ clock,
301
+ });
302
+ expect(res).toEqual({ outcome: "skipped_no_app_id", pagesFetched: 0 });
303
+ expect(store.keys).toEqual([]);
304
+ expect(calls.installs).toBe(0);
305
+ });
306
+
307
+ it("ends the run cleanly on a rate limit", async () => {
308
+ const { client } = fakeClient({
309
+ failPage: () =>
310
+ new GithubEnterpriseError("rate_limit", "slow down", {
311
+ status: 429,
312
+ retryAfterSeconds: 30,
313
+ }),
314
+ });
315
+ const res = await crawlAgentInstallation({
316
+ agent: agent(),
317
+ org: "acme",
318
+ client,
319
+ store,
320
+ clock,
321
+ });
322
+ expect(res).toMatchObject({
323
+ outcome: "rate_limited",
324
+ rateLimitResetAt: new Date(T0.getTime() + 30_000),
325
+ });
326
+ expect(store.snap?.attempts).toBe(0);
327
+ });
328
+
329
+ it("records a GitHub failure as failed", async () => {
330
+ const { client } = fakeClient({
331
+ failPage: () => new GithubEnterpriseError("server", "boom"),
332
+ });
333
+ const res = await crawlAgentInstallation({
334
+ agent: agent(),
335
+ org: "acme",
336
+ client,
337
+ store,
338
+ clock,
339
+ });
340
+ expect(res.outcome).toBe("failed");
341
+ expect(store.snap?.attempts).toBe(1);
342
+ });
343
+ });
@@ -0,0 +1,100 @@
1
+ /**
2
+ * admin/src/github-enterprise-client-page.unit.test.ts
3
+ * GithubEnterpriseClient.listInstallationRepositoriesPage: one page, Link-header
4
+ * driven hasNext, archived passthrough, validation.
5
+ */
6
+
7
+ import { describe, expect, it } from "bun:test";
8
+ import { generateKeyPairSync } from "node:crypto";
9
+ import { GithubEnterpriseClient } from "./github-enterprise-client.ts";
10
+
11
+ const { privateKey } = generateKeyPairSync("rsa", {
12
+ modulusLength: 2048,
13
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
14
+ publicKeyEncoding: { type: "spki", format: "pem" },
15
+ });
16
+
17
+ function make(repoResp: () => Response) {
18
+ const paths: string[] = [];
19
+ const fetchFn = (async (input: RequestInfo | URL) => {
20
+ const u = new URL(input.toString());
21
+ paths.push(`${u.pathname}${u.search}`);
22
+ if (u.pathname.endsWith("/installation"))
23
+ return Response.json({ id: 1 });
24
+ if (u.pathname.endsWith("/access_tokens"))
25
+ return Response.json(
26
+ { token: "t", expires_at: "2099-01-01T00:00:00Z" },
27
+ { status: 201 },
28
+ );
29
+ return repoResp();
30
+ }) as typeof fetch;
31
+ return {
32
+ paths,
33
+ client: new GithubEnterpriseClient({
34
+ appId: "1",
35
+ enterprise: "ent",
36
+ privateKey,
37
+ apiBase: "https://ghe.test",
38
+ fetchFn,
39
+ }),
40
+ };
41
+ }
42
+
43
+ describe("listInstallationRepositoriesPage", () => {
44
+ it("fetches only the requested page and reads the Link header", async () => {
45
+ const { client, paths } = make(() =>
46
+ Response.json([{ id: 1, name: "a", full_name: "o/a", archived: true }], {
47
+ headers: { link: '<https://x?page=3>; rel="next"' },
48
+ }),
49
+ );
50
+ const res = await client.listInstallationRepositoriesPage("o", 5, 2);
51
+ expect(res).toEqual({
52
+ repos: [{ id: 1, name: "a", fullName: "o/a", archived: true }],
53
+ hasNext: true,
54
+ perPage: 100,
55
+ });
56
+ expect(paths.filter((p) => p.includes("/repositories"))).toEqual([
57
+ "/enterprises/ent/apps/organizations/o/installations/5/repositories?per_page=100&page=2",
58
+ ]);
59
+ });
60
+
61
+ it("without a Link header, hasNext is whether the page is full", async () => {
62
+ const full = Array.from({ length: 100 }, (_, i) => ({
63
+ id: i,
64
+ name: "n",
65
+ full_name: "o/n",
66
+ }));
67
+ expect(
68
+ (await make(() => Response.json(full)).client.listInstallationRepositoriesPage("o", 5, 1)).hasNext,
69
+ ).toBe(true);
70
+ expect(
71
+ (await make(() => Response.json(full.slice(0, 3))).client.listInstallationRepositoriesPage("o", 5, 1)).hasNext,
72
+ ).toBe(false);
73
+ });
74
+
75
+ it("maps a 429 to a rate_limit error with retry-after", async () => {
76
+ const { client } = make(
77
+ () =>
78
+ new Response(JSON.stringify({ message: "limit" }), {
79
+ status: 429,
80
+ headers: { "retry-after": "12" },
81
+ }),
82
+ );
83
+ const err = await client
84
+ .listInstallationRepositoriesPage("o", 5, 1)
85
+ .catch((e) => e);
86
+ expect(err.kind).toBe("rate_limit");
87
+ expect(err.retryAfterSeconds).toBe(12);
88
+ });
89
+
90
+ it("rejects a bad page or installation id before any request", async () => {
91
+ const { client, paths } = make(() => Response.json([]));
92
+ expect(
93
+ (await client.listInstallationRepositoriesPage("o", 5, 0).catch((e) => e)).kind,
94
+ ).toBe("validation");
95
+ expect(
96
+ (await client.listInstallationRepositoriesPage("o", Number.NaN, 1).catch((e) => e)).kind,
97
+ ).toBe("validation");
98
+ expect(paths).toEqual([]);
99
+ });
100
+ });
@@ -174,6 +174,14 @@ export interface AccessibleRepository {
174
174
  fullName: string;
175
175
  }
176
176
 
177
+ /** One page of an installation's repositories. */
178
+ export interface InstallationRepositoriesPage {
179
+ repos: (AccessibleRepository & { archived?: boolean })[];
180
+ hasNext: boolean;
181
+ /** The page size requested; every page but the last is full. */
182
+ perPage: number;
183
+ }
184
+
177
185
  export interface SetRepositorySelectionInput {
178
186
  repositorySelection: "all" | "selected";
179
187
  /** Simple repo names (max 50); required when repositorySelection is "selected". */
@@ -365,6 +373,43 @@ export class GithubEnterpriseClient {
365
373
  return rows.map(toRepository);
366
374
  }
367
375
 
376
+ /**
377
+ * One page (1-based) of the repositories an installation can access. The
378
+ * endpoint returns a bare array with no total_count, so callers that need a
379
+ * total derive it from the page position (see GLC-1.5).
380
+ */
381
+ async listInstallationRepositoriesPage(
382
+ org: string,
383
+ installationId: number,
384
+ page: number,
385
+ ): Promise<InstallationRepositoriesPage> {
386
+ if (!Number.isInteger(page) || page < 1) {
387
+ throw new GithubEnterpriseError("validation", "page must be a positive integer");
388
+ }
389
+ const context = "GitHub installation repositories";
390
+ const path = this.repositoriesPath(org, installationId);
391
+ const { token } = await this.getInstallationToken();
392
+ const res = await this.request<RawRepository[]>(
393
+ "GET",
394
+ `${path}?per_page=${PER_PAGE}&page=${page}`,
395
+ token,
396
+ context,
397
+ );
398
+ if (!Array.isArray(res.data)) {
399
+ throw new GithubEnterpriseError("unexpected", `${context}: response is not a list`);
400
+ }
401
+ const link = res.headers.get("link");
402
+ const hasNext = link !== null ? /rel="next"/.test(link) : res.data.length >= PER_PAGE;
403
+ return {
404
+ repos: res.data.map((r) => ({
405
+ ...toRepository(r),
406
+ ...(typeof r.archived === "boolean" ? { archived: r.archived } : {}),
407
+ })),
408
+ hasNext,
409
+ perPage: PER_PAGE,
410
+ };
411
+ }
412
+
368
413
  /** Grant an installation access to repositories, in batches of at most 50. */
369
414
  async addRepositories(
370
415
  org: string,
@@ -520,6 +565,7 @@ interface RawRepository {
520
565
  id: number;
521
566
  name: string;
522
567
  full_name: string;
568
+ archived?: boolean;
523
569
  }
524
570
 
525
571
  function toRepository(r: RawRepository): AccessibleRepository {