Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions packages/app/src/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,21 @@ export async function installationToken(env: { GITHUB_APP_ID?: string; GITHUB_AP

export const githubHeaders = (token: string): HeadersInit => ({ Accept: "application/vnd.github+json", Authorization: `Bearer ${token}`, "User-Agent": "Factorize", "X-GitHub-Api-Version": "2022-11-28" });

/** Load every available page of a GitHub collection used by configuration UIs. */
export async function githubCollection<T>(url: string, token: string, fetcher: typeof fetch = fetch): Promise<T[]> {
const items: T[] = [];
for (let page = 1; ; page++) {
const separator = url.includes("?") ? "&" : "?";
const response = await fetcher(`${url}${separator}per_page=100&page=${page}`, { headers: githubHeaders(token) });
if (!response.ok) throw new Error(`GitHub collection could not be loaded (${response.status})`);
const batch = await response.json() as T[];
if (!Array.isArray(batch)) throw new Error("GitHub returned an invalid collection");
items.push(...batch);
if (batch.length < 100) break;
}
return items;
}

export async function signSetupState(value: { tenantId: string; userId: string; nonce: string; exp: number }, secret: string): Promise<string> {
const body = json64(value);
return `${body}.${(await hmac(body, secret)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "")}`;
Expand Down
8 changes: 2 additions & 6 deletions packages/app/src/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { LINEAR_ISSUE_PROJECT_QUERY, LINEAR_OPTION_QUERIES, LINEAR_PROJECTS_QUER
import { matchingIssue } from "./matcher";
import type { AmpConnectionInput, Env, ExeConnectionInput, FilterType, MatchRule, RunState, TailIntegrationInput } from "./types";
import { workingDirectoryFor, workspaceNameFor } from "./workspace";
import { githubClaimKey, githubHeaders, installationToken, normalizeRepository, renderGitHubPrompt } from "./github";
import { githubClaimKey, githubCollection, githubHeaders, installationToken, normalizeRepository, renderGitHubPrompt } from "./github";
import type { WorkItem } from "./types";
import { invokeCustomHandler } from "./custom-handler";
import { generateTailSecret, sanitizeTailEvent, signTailDelivery, suppressTailEvent, tailFingerprint, verifyTailDelivery } from "./cloudflare-tail";
Expand Down Expand Up @@ -1546,11 +1546,7 @@ export class TenantV2 extends DurableObject<Env> {
if (!repositoryResponse.ok) return new Response("GitHub repository is unavailable", { status: repositoryResponse.status });
const repository = await repositoryResponse.json() as { full_name?: string };
if (!repository.full_name) return new Response("GitHub repository is unavailable", { status: 404 });
const load = async (path: string) => {
const response = await fetch(`https://api.github.com/repos/${repository.full_name}/${path}?per_page=100`, { headers: githubHeaders(token) });
if (!response.ok) throw new Error(`GitHub ${path} could not be loaded`);
return await response.json() as Array<{ id: number; name?: string; login?: string }>;
};
const load = (path: string) => githubCollection<{ id: number; name?: string; login?: string }>(`https://api.github.com/repos/${repository.full_name}/${path}`, token);
const [labels, assignees] = await Promise.all([load("labels"), load("assignees")]);
return json({
statuses: [{ id: "open", name: "Open" }, { id: "closed", name: "Closed" }],
Expand Down
24 changes: 24 additions & 0 deletions packages/app/test/github-collection.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { describe, expect, it, vi } from "vitest";
import { githubCollection } from "../src/github";

describe("githubCollection", () => {
it("loads subsequent pages so all issue filter choices are available", async () => {
const first = Array.from({ length: 100 }, (_, id) => ({ id }));
const fetcher = vi.fn()
.mockResolvedValueOnce(Response.json(first))
.mockResolvedValueOnce(Response.json([{ id: 100 }]));

const result = await githubCollection<{ id: number }>("https://api.github.com/repos/acme/widgets/labels", "token", fetcher);

expect(result).toHaveLength(101);
expect(fetcher.mock.calls.map(call => call[0])).toEqual([
"https://api.github.com/repos/acme/widgets/labels?per_page=100&page=1",
"https://api.github.com/repos/acme/widgets/labels?per_page=100&page=2",
]);
});

it("rejects failed and malformed GitHub responses", async () => {
await expect(githubCollection("https://api.github.com/example", "token", vi.fn().mockResolvedValue(new Response(null, { status: 403 })))).rejects.toThrow("(403)");
await expect(githubCollection("https://api.github.com/example", "token", vi.fn().mockResolvedValue(Response.json({})))).rejects.toThrow("invalid collection");
});
});