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