Coverage / src/hub.ts 95.1%
353 of 371 lines run, 24 of 59 functions, 70 of 98 branches · run #22 on main · run missed
| 1 | 0× | // The hub client: typed fetch over /api/v1 (hub spec §12.1) using the |
| 2 | 0× | // generated types in hubapi.d.ts, plus URL helpers. No vscode imports, |
| 3 | 0× | // so it is tested with plain Node against a real hub. |
| 4 | 1× | |
| 5 | import type * as api from "./hubapi"; | |
| 6 | 1× | |
| 7 | 0× | export class HubError extends Error { |
| 8 | 0× | constructor( |
| 9 | 0× | readonly status: number, |
| 10 | 0× | readonly title: string, |
| 11 | 0× | readonly detail: string, |
| 12 | 0× | ) { |
| 13 | 0× | super(`${status} ${title}: ${detail}`); |
| 14 | 0× | } |
| 15 | 3× | } |
| 16 | 3× | |
| 17 | 3× | /** `https://hub/owner/name` → { base, owner, name }; undefined for anything else. */ |
| 18 | 3× | export function parseRepoUrl(url: string): { base: string; owner: string; name: string } | undefined { |
| 19 | 3× | const m = /^(https?:\/\/[^/]+)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/?$/.exec(url.trim()); |
| 20 | 3× | if (!m || m[2] === "api") { |
| 21 | 0× | return undefined; |
| 22 | 0× | } |
| 23 | 3× | return { base: m[1], owner: m[2], name: m[3] }; |
| 24 | 1× | } |
| 25 | 1× | |
| 26 | 1× | import { readFileSync } from "node:fs"; |
| 27 | 1× | import * as http from "node:http"; |
| 28 | 1× | import * as https from "node:https"; |
| 29 | 1× | import * as tls from "node:tls"; |
| 30 | 1× | |
| 31 | 1× | export interface Session { |
| 32 | 1× | base: string; |
| 33 | 1× | token: string; |
| 34 | 1× | username?: string; |
| 35 | 1× | } |
| 36 | 1× | |
| 37 | 1× | export class HubClient { |
| 38 | 1× | constructor( |
| 39 | 1× | readonly base: string, |
| 40 | 1× | private readonly token: string | undefined, |
| 41 | 1× | private readonly fetchImpl: typeof fetch = fetch, |
| 42 | 1× | ) {} |
| 43 | 1× | |
| 44 | 1× | private async request<T>(method: string, path: string, body?: unknown): Promise<T> { |
| 45 | 1× | const headers: Record<string, string> = { accept: "application/json" }; |
| 46 | 1× | if (this.token) { |
| 47 | 1× | headers.authorization = `Bearer ${this.token}`; |
| 48 | 1× | } |
| 49 | 1× | if (body !== undefined) { |
| 50 | 1× | headers["content-type"] = "application/json"; |
| 51 | 1× | } |
| 52 | 1× | const res = await this.fetchImpl(`${this.base}/api/v1${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) }); |
| 53 | 1× | if (res.status === 204) { |
| 54 | 1× | return undefined as T; |
| 55 | 1× | } |
| 56 | 1× | const text = await res.text(); |
| 57 | 1× | if (!res.ok) { |
| 58 | 1× | try { |
| 59 | 1× | const p = JSON.parse(text) as api.Problem; |
| 60 | 1× | throw new HubError(p.status, p.title, p.detail); |
| 61 | 1× | } catch (e) { |
| 62 | 1× | if (e instanceof HubError) { |
| 63 | 1× | throw e; |
| 64 | 1× | } |
| 65 | 1× | throw new HubError(res.status, res.statusText, text); |
| 66 | 1× | } |
| 67 | 1× | } |
| 68 | 1× | return (text ? JSON.parse(text) : undefined) as T; |
| 69 | 1× | } |
| 70 | 1× | |
| 71 | 1× | me(): Promise<api.User> { |
| 72 | 1× | return this.request("GET", "/user"); |
| 73 | 1× | } |
| 74 | 1× | |
| 75 | 1× | /** The caller's inbox: unread count and newest entries (needs user:read). */ |
| 76 | 1× | notifications(limit = 50): Promise<api.Inbox> { |
| 77 | 1× | return this.request("GET", `/notifications?limit=${limit}`); |
| 78 | 1× | } |
| 79 | 1× | |
| 80 | 1× | markNotificationRead(id: number): Promise<void> { |
| 81 | 1× | return this.request("POST", `/notifications/${id}/read`); |
| 82 | 1× | } |
| 83 | 1× | |
| 84 | 1× | markAllNotificationsRead(): Promise<void> { |
| 85 | 1× | return this.request("POST", "/notifications/read"); |
| 86 | 1× | } |
| 87 | 1× | |
| 88 | 1× | /** Recent OxygenFlow runs, newest first. */ |
| 89 | 1× | flowRuns(owner: string, name: string, limit = 15): Promise<api.FlowRun[]> { |
| 90 | 1× | return this.request("GET", `/repos/${owner}/${name}/flow/runs?limit=${limit}`); |
| 91 | 1× | } |
| 92 | 1× | |
| 93 | 1× | /** A run with its jobs. */ |
| 94 | 1× | flowRun(owner: string, name: string, number: number): Promise<api.FlowRun> { |
| 95 | 1× | return this.request("GET", `/repos/${owner}/${name}/flow/runs/${number}`); |
| 96 | 1× | } |
| 97 | 1× | |
| 98 | 1× | /** A job's log lines after `after` (a line's seq). */ |
| 99 | 1× | flowLog(owner: string, name: string, number: number, job: string, after = 0): Promise<api.FlowLogLine[]> { |
| 100 | 1× | return this.request("GET", `/repos/${owner}/${name}/flow/runs/${number}/jobs/${encodeURIComponent(job)}/log?after=${after}&limit=2000`); |
| 101 | 1× | } |
| 102 | 1× | |
| 103 | 1× | /** Run the pipeline of a bookmark's current state, or of one change. */ |
| 104 | 1× | startFlowRun(owner: string, name: string, target: { bookmark?: string; change?: string }): Promise<{ number: number; url: string }> { |
| 105 | 1× | return this.request("POST", `/repos/${owner}/${name}/flow/runs`, target); |
| 106 | 1× | } |
| 107 | 1× | |
| 108 | 1× | rerunFlowRun(owner: string, name: string, number: number): Promise<{ number: number; url: string }> { |
| 109 | 1× | return this.request("POST", `/repos/${owner}/${name}/flow/runs/${number}/rerun`); |
| 110 | 1× | } |
| 111 | 1× | |
| 112 | 1× | repositories(): Promise<api.Repository[]> { |
| 113 | 1× | return this.request("GET", "/repos"); |
| 114 | 1× | } |
| 115 | 1× | |
| 116 | 1× | repository(owner: string, name: string): Promise<api.Repository> { |
| 117 | 1× | return this.request("GET", `/repos/${owner}/${name}`); |
| 118 | 1× | } |
| 119 | 1× | |
| 120 | 1× | proposals(owner: string, name: string): Promise<api.Proposal[]> { |
| 121 | 1× | return this.request("GET", `/repos/${owner}/${name}/proposals`); |
| 122 | 1× | } |
| 123 | 1× | |
| 124 | 1× | proposal(owner: string, name: string, number: number): Promise<api.Proposal> { |
| 125 | 1× | return this.request("GET", `/repos/${owner}/${name}/proposals/${number}`); |
| 126 | 1× | } |
| 127 | 1× | |
| 128 | 1× | createProposal(owner: string, name: string, p: api.NewProposal): Promise<api.Proposal> { |
| 129 | 1× | return this.request("POST", `/repos/${owner}/${name}/proposals`, p); |
| 130 | 1× | } |
| 131 | 1× | |
| 132 | 1× | proposalComments(owner: string, name: string, number: number): Promise<api.Comment[]> { |
| 133 | 1× | return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/comments`); |
| 134 | 1× | } |
| 135 | 1× | |
| 136 | 1× | /** A comment; with `path` and `line` it is anchored to that line's atom in the projected state. */ |
| 137 | 1× | commentProposal(owner: string, name: string, number: number, body: string, path?: string, line?: number): Promise<api.Comment> { |
| 138 | 1× | return this.request("POST", `/repos/${owner}/${name}/proposals/${number}/comments`, { body, path: path ?? null, line: line ?? null }); |
| 139 | 1× | } |
| 140 | 1× | |
| 141 | 1× | reviews(owner: string, name: string, number: number): Promise<api.Review[]> { |
| 142 | 1× | return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/reviews`); |
| 143 | 1× | } |
| 144 | 1× | |
| 145 | 1× | review(owner: string, name: string, number: number, verdict: "comment" | "changes" | "approve", body = ""): Promise<api.Review> { |
| 146 | 1× | return this.request("POST", `/repos/${owner}/${name}/proposals/${number}/reviews`, { verdict, body }); |
| 147 | 1× | } |
| 148 | 1× | |
| 149 | 1× | /** The files a proposal changes, target state against projected state. */ |
| 150 | 1× | proposalFiles(owner: string, name: string, number: number): Promise<api.ProposalFile[]> { |
| 151 | 1× | return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/files`); |
| 152 | 1× | } |
| 153 | 1× | |
| 154 | 1× | /** A file's text on one side of a proposal; undefined when it does not exist there. */ |
| 155 | 1× | async proposalContent(owner: string, name: string, number: number, side: "base" | "head", path: string): Promise<string | undefined> { |
| 156 | 1× | const headers: Record<string, string> = {}; |
| 157 | 1× | if (this.token) { |
| 158 | 1× | headers.authorization = `Bearer ${this.token}`; |
| 159 | 1× | } |
| 160 | 1× | const res = await this.fetchImpl(`${this.base}/api/v1/repos/${owner}/${name}/proposals/${number}/content/${side}/${path.split("/").map(encodeURIComponent).join("/")}`, { headers }); |
| 161 | 1× | if (res.status === 404) { |
| 162 | 1× | return undefined; |
| 163 | 1× | } |
| 164 | 1× | if (!res.ok) { |
| 165 | 1× | throw new HubError(res.status, res.statusText, await res.text()); |
| 166 | 1× | } |
| 167 | 1× | return res.text(); |
| 168 | 1× | } |
| 169 | 1× | |
| 170 | 1× | proposalChecks(owner: string, name: string, number: number): Promise<api.Check[]> { |
| 171 | 1× | return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/checks`); |
| 172 | 1× | } |
| 173 | 1× | |
| 174 | 1× | issues(owner: string, name: string, state: "open" | "closed" | "all" = "open"): Promise<api.Issue[]> { |
| 175 | 1× | return this.request("GET", `/repos/${owner}/${name}/issues?state=${state}`); |
| 176 | 1× | } |
| 177 | 1× | |
| 178 | 1× | issue(owner: string, name: string, number: number): Promise<api.Issue> { |
| 179 | 1× | return this.request("GET", `/repos/${owner}/${name}/issues/${number}`); |
| 180 | 1× | } |
| 181 | 1× | |
| 182 | 1× | createIssue(owner: string, name: string, title: string, body = ""): Promise<api.Issue> { |
| 183 | 1× | return this.request("POST", `/repos/${owner}/${name}/issues`, { title, body }); |
| 184 | 1× | } |
| 185 | 1× | |
| 186 | 1× | issueComments(owner: string, name: string, number: number): Promise<api.Comment[]> { |
| 187 | 1× | return this.request("GET", `/repos/${owner}/${name}/issues/${number}/comments`); |
| 188 | 1× | } |
| 189 | 1× | |
| 190 | 1× | commentIssue(owner: string, name: string, number: number, body: string): Promise<api.Comment> { |
| 191 | 1× | return this.request("POST", `/repos/${owner}/${name}/issues/${number}/comments`, { body }); |
| 192 | 1× | } |
| 193 | 1× | |
| 194 | 1× | setIssueState(owner: string, name: string, number: number, state: "open" | "closed", reason = ""): Promise<api.Issue> { |
| 195 | 1× | return this.request("POST", `/repos/${owner}/${name}/issues/${number}`, { state, reason }); |
| 196 | 1× | } |
| 197 | 1× | |
| 198 | 1× | history(owner: string, name: string, reference: string, limit = 50): Promise<api.History> { |
| 199 | 1× | return this.request("GET", `/repos/${owner}/${name}/history/${encodeURIComponent(reference)}?limit=${limit}`); |
| 200 | 1× | } |
| 201 | 1× | |
| 202 | 1× | bookmarks(owner: string, name: string): Promise<api.Bookmark[]> { |
| 203 | 1× | return this.request("GET", `/repos/${owner}/${name}/bookmarks`); |
| 204 | 1× | } |
| 205 | 1× | |
| 206 | 1× | /** What the repository takes from and diffuses to (oxygenhub#153). */ |
| 207 | 1× | diffusion(owner: string, name: string): Promise<api.Diffusion> { |
| 208 | 1× | return this.request("GET", `/repos/${owner}/${name}/diffusion`); |
| 209 | 1× | } |
| 210 | 1× | |
| 211 | 1× | releases(owner: string, name: string): Promise<api.Release[]> { |
| 212 | 1× | return this.request("GET", `/repos/${owner}/${name}/releases`); |
| 213 | 1× | } |
| 214 | 1× | |
| 215 | 1× | createRelease(owner: string, name: string, r: api.NewRelease): Promise<api.Release> { |
| 216 | 1× | return this.request("POST", `/repos/${owner}/${name}/releases`, r); |
| 217 | 1× | } |
| 218 | 1× | |
| 219 | 1× | tags(owner: string, name: string): Promise<api.Tag[]> { |
| 220 | 1× | return this.request("GET", `/repos/${owner}/${name}/tags`); |
| 221 | 1× | } |
| 222 | 1× | |
| 223 | 1× | search(q: string): Promise<{ kind: string; repository: string; number: number; title: string }[]> { |
| 224 | 1× | return this.request("GET", `/search?q=${encodeURIComponent(q)}`); |
| 225 | 1× | } |
| 226 | 1× | } |
| 227 | 1× | |
| 228 | 1× | /** Web URLs on the hub for things the remote provider is asked about. */ |
| 229 | 1× | export function hubUrl(base: string, owner: string, name: string, target: { kind: string; [k: string]: unknown }): string { |
| 230 | 1× | const repo = `${base}/${owner}/${name}`; |
| 231 | 1× | switch (target.kind) { |
| 232 | 1× | case "repository": |
| 233 | 1× | return repo; |
| 234 | 1× | case "bookmark": |
| 235 | 1× | return `${repo}/tree/${encodeURIComponent(String(target.name))}`; |
| 236 | 1× | case "change": |
| 237 | 1× | return `${repo}/change/${target.hash}`; |
| 238 | 1× | case "file": { |
| 239 | 0× | const end = typeof target.endLine === "number" && target.endLine !== target.line ? `-L${target.endLine}` : ""; |
| 240 | 0× | const line = typeof target.line === "number" ? `#L${target.line}${end}` : ""; |
| 241 | 0× | // A state address (`hash+hash`) keeps its `+`, as the hub writes permalinks. |
| 242 | 0× | return `${repo}/file/${encodeURIComponent(String(target.reference)).replace(/%2B/g, "+")}/${String(target.path)}${line}`; |
| 243 | 0× | } |
| 244 | 1× | case "proposals": |
| 245 | 1× | return `${repo}/proposals`; |
| 246 | 1× | case "issues": |
| 247 | 1× | return `${repo}/issues`; |
| 248 | 1× | case "proposal": |
| 249 | 1× | return `${repo}/proposal/${target.number}`; |
| 250 | 1× | case "issue": |
| 251 | 1× | return `${repo}/issue/${target.number}`; |
| 252 | 1× | case "diffusion": |
| 253 | 1× | return `${repo}/diffusion`; |
| 254 | 1× | default: |
| 255 | 1× | return repo; |
| 256 | 1× | } |
| 257 | 1× | } |
| 258 | 3× | |
| 259 | 3× | /** Which of the proposals need the signed-in user: not theirs, and not yet sealed by them. */ |
| 260 | 3× | export function needsMe(p: import("./hubapi").Proposal, username: string | undefined): boolean { |
| 261 | 5× | if (!username || p.author === username) { |
| 262 | 1× | return false; |
| 263 | 1× | } |
| 264 | 5× | if (p.state !== "open") { |
| 265 | 1× | return false; |
| 266 | 1× | } |
| 267 | 3× | const mine = p.approvals.find((a) => a.account === username); |
| 268 | 5× | return !mine || !mine.sealed; |
| 269 | 1× | } |
| 270 | 1× | |
| 271 | 1× | /** Which proposal, side and file a diff document shows. */ |
| 272 | 1× | export interface DiffRef { |
| 273 | 1× | base: string; |
| 274 | 1× | owner: string; |
| 275 | 1× | name: string; |
| 276 | 1× | number: number; |
| 277 | 1× | side: "base" | "head"; |
| 278 | 1× | path: string; |
| 279 | 1× | } |
| 280 | 1× | |
| 281 | 1× | /** The query string of a diff document's URI. */ |
| 282 | 1× | export function encodeDiffQuery(r: DiffRef): string { |
| 283 | 1× | return new URLSearchParams({ hub: r.base, owner: r.owner, name: r.name, number: String(r.number), side: r.side }).toString(); |
| 284 | 4× | } |
| 285 | 4× | |
| 286 | 4× | /** Parse a diff document's query and path back; undefined if it is not one. */ |
| 287 | 4× | export function decodeDiffQuery(query: string, path: string): DiffRef | undefined { |
| 288 | 4× | const q = new URLSearchParams(query); |
| 289 | 4× | const number = Number(q.get("number")); |
| 290 | 4× | const side = q.get("side"); |
| 291 | 4× | const [base, owner, name] = [q.get("hub"), q.get("owner"), q.get("name")]; |
| 292 | 4× | if (!base || !owner || !name || !Number.isInteger(number) || number < 1 || (side !== "base" && side !== "head")) { |
| 293 | 3× | return undefined; |
| 294 | 3× | } |
| 295 | 4× | return { base, owner, name, number, side, path: path.replace(/^\/+/, "") }; |
| 296 | 4× | } |
| 297 | 3× | |
| 298 | 3× | /** What a hub page URL points at, for opening it in the editor instead of a browser. */ |
| 299 | 3× | export type HubTarget = { kind: "proposal" | "issue"; base: string; owner: string; name: string; number: number } | { kind: "other"; url: string }; |
| 300 | 3× | |
| 301 | 3× | export function hubTarget(url: string): HubTarget { |
| 302 | 4× | const m = /^(https?:\/\/[^/]+)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/(proposal|issue)\/(\d+)(?:[/?#].*)?$/.exec(url); |
| 303 | 4× | if (!m) { |
| 304 | 2× | return { kind: "other", url }; |
| 305 | 2× | } |
| 306 | 4× | return { kind: m[4] as "proposal" | "issue", base: m[1], owner: m[2], name: m[3], number: Number(m[5]) }; |
| 307 | 4× | } |
| 308 | 3× | |
| 309 | 3× | /** |
| 310 | 3× | * Release notes from history: the changes in `current` that `previous` |
| 311 | 3× | * does not have, newest first, one line each (the message's subject). |
| 312 | 3× | */ |
| 313 | 3× | export function releaseNotes(current: api.ChangeSummary[], previous: api.ChangeSummary[], sinceTag?: string): string { |
| 314 | 3× | const seen = new Set(previous.map((c) => c.hash)); |
| 315 | 3× | const lines = current |
| 316 | 3× | .filter((c) => !seen.has(c.hash)) |
| 317 | 3× | .sort((a, b) => b.when_ms - a.when_ms) |
| 318 | 3× | .map((c) => `- ${c.message.split("\n")[0].trim()} (${c.hash.slice(0, 12)})`); |
| 319 | 3× | const head = sinceTag ? `Changes since ${sinceTag}:` : "Changes:"; |
| 320 | 3× | return lines.length ? `${head}\n\n${lines.join("\n")}\n` : "No changes since the last release.\n"; |
| 321 | 10× | } |
| 322 | 10× | |
| 323 | 10× | /** Whether a tag name reads as a pre-release (`v1.0-rc1`, `2.0.0-beta.2`, `alpha`). */ |
| 324 | 10× | export function looksPrerelease(tag: string): boolean { |
| 325 | 10× | return /(^|[-.+_])(alpha|beta|rc|pre|preview|dev)\d*([-.+_]|$)/i.test(tag) || /-(a|b|rc)\d+$/i.test(tag); |
| 326 | 10× | } |
| 327 | 3× | |
| 328 | 3× | /** |
| 329 | 3× | * A `fetch` that also trusts the CA certificate in `caFile`, for a hub with a |
| 330 | 3× | * self-signed certificate (Node's `fetch` takes no CA). The file is read on |
| 331 | 3× | * each request, so a renewed certificate needs no reload. |
| 332 | 3× | */ |
| 333 | 3× | export function fetchTrusting(caFile: string): typeof fetch { |
| 334 | 2× | return ((input: string | URL | Request, init?: RequestInit) => |
| 335 | 4× | new Promise<Response>((resolve, reject) => { |
| 336 | 4× | const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url); |
| 337 | 4× | const secure = url.protocol === "https:"; |
| 338 | 4× | let ca: string[] | undefined; |
| 339 | 4× | if (secure) { |
| 340 | 4× | try { |
| 341 | 4× | ca = [...tls.rootCertificates, readFileSync(caFile, "utf8")]; |
| 342 | 4× | } catch (e) { |
| 343 | 1× | reject(new Error(`cannot read the hub's CA file ${caFile}: ${(e as Error).message}`)); |
| 344 | 1× | return; |
| 345 | 1× | } |
| 346 | 4× | } |
| 347 | 3× | const headers: Record<string, string> = {}; |
| 348 | 4× | new Headers(init?.headers).forEach((v, k) => (headers[k] = v)); |
| 349 | 4× | const req = (secure ? https : http).request(url, { method: init?.method ?? "GET", headers, ca }, (res) => { |
| 350 | 3× | const chunks: Buffer[] = []; |
| 351 | 3× | res.on("data", (c: Buffer) => chunks.push(c)); |
| 352 | 3× | res.on("error", reject); |
| 353 | 3× | res.on("end", () => { |
| 354 | 3× | const status = res.statusCode ?? 0; |
| 355 | 3× | const out = new Headers(); |
| 356 | 3× | for (const [k, v] of Object.entries(res.headers)) { |
| 357 | 13× | if (v !== undefined) { |
| 358 | 13× | out.set(k, Array.isArray(v) ? v.join(", ") : String(v)); |
| 359 | 13× | } |
| 360 | 13× | } |
| 361 | 3× | const empty = status === 204 || status === 304; |
| 362 | 3× | resolve(new Response(empty ? null : Buffer.concat(chunks), { status, headers: out })); |
| 363 | 3× | }); |
| 364 | 4× | }); |
| 365 | 4× | req.on("error", (e) => reject(Object.assign(new Error(`fetch failed: ${e.message}`), { cause: e }))); |
| 366 | 4× | if (init?.body !== undefined && init.body !== null) { |
| 367 | 1× | req.write(typeof init.body === "string" ? init.body : Buffer.from(init.body as ArrayBuffer)); |
| 368 | 1× | } |
| 369 | 4× | req.end(); |
| 370 | 2× | })) as typeof fetch; |
| 371 | 2× | } |