OXYGENHUB

Coverage / src/hub.ts 96.7%

526 of 544 lines run, 49 of 87 functions, 109 of 145 branches · run #24 on main · run missed

10×
// The hub client: typed fetch over /api/v1 (hub spec §12.1) using the
20×
// generated types in hubapi.d.ts, plus URL helpers. No vscode imports,
30×
// so it is tested with plain Node against a real hub.
41×
5
import type * as api from "./hubapi";
61×
70×
export class HubError extends Error {
80×
  constructor(
90×
    readonly status: number,
100×
    readonly title: string,
110×
    readonly detail: string,
120×
  ) {
130×
    super(`${status} ${title}: ${detail}`);
140×
  }
153×
}
163×
173×
/** `https://hub/owner/name` → { base, owner, name }; undefined for anything else. */
183×
export function parseRepoUrl(url: string): { base: string; owner: string; name: string } | undefined {
193×
  const m = /^(https?:\/\/[^/]+)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/?$/.exec(url.trim());
203×
  if (!m || m[2] === "api") {
210×
    return undefined;
220×
  }
233×
  return { base: m[1], owner: m[2], name: m[3] };
241×
}
251×
261×
import { readFileSync } from "node:fs";
271×
import * as http from "node:http";
281×
import * as https from "node:https";
291×
import * as tls from "node:tls";
301×
311×
export interface Session {
321×
  base: string;
331×
  token: string;
341×
  username?: string;
351×
}
361×
371×
export class HubClient {
381×
  constructor(
391×
    readonly base: string,
401×
    private readonly token: string | undefined,
411×
    private readonly fetchImpl: typeof fetch = fetch,
421×
  ) {}
431×
441×
  private async request<T>(method: string, path: string, body?: unknown): Promise<T> {
451×
    const headers: Record<string, string> = { accept: "application/json" };
461×
    if (this.token) {
471×
      headers.authorization = `Bearer ${this.token}`;
481×
    }
491×
    if (body !== undefined) {
501×
      headers["content-type"] = "application/json";
511×
    }
521×
    const res = await this.fetchImpl(`${this.base}/api/v1${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
531×
    if (res.status === 204) {
541×
      return undefined as T;
551×
    }
561×
    const text = await res.text();
571×
    if (!res.ok) {
581×
      try {
591×
        const p = JSON.parse(text) as api.Problem;
601×
        throw new HubError(p.status, p.title, p.detail);
611×
      } catch (e) {
621×
        if (e instanceof HubError) {
631×
          throw e;
641×
        }
651×
        throw new HubError(res.status, res.statusText, text);
661×
      }
671×
    }
681×
    return (text ? JSON.parse(text) : undefined) as T;
691×
  }
701×
711×
  me(): Promise<api.User> {
721×
    return this.request("GET", "/user");
731×
  }
741×
751×
  /** The caller's inbox: unread count and newest entries (needs user:read). */
761×
  notifications(limit = 50): Promise<api.Inbox> {
771×
    return this.request("GET", `/notifications?limit=${limit}`);
781×
  }
791×
801×
  markNotificationRead(id: number): Promise<void> {
811×
    return this.request("POST", `/notifications/${id}/read`);
821×
  }
831×
841×
  markAllNotificationsRead(): Promise<void> {
851×
    return this.request("POST", "/notifications/read");
861×
  }
871×
881×
  /** Recent OxygenFlow runs, newest first. */
891×
  flowRuns(owner: string, name: string, limit = 15): Promise<api.FlowRun[]> {
901×
    return this.request("GET", `/repos/${owner}/${name}/flow/runs?limit=${limit}`);
911×
  }
921×
931×
  /** A run with its jobs. */
941×
  flowRun(owner: string, name: string, number: number): Promise<api.FlowRun> {
951×
    return this.request("GET", `/repos/${owner}/${name}/flow/runs/${number}`);
961×
  }
971×
981×
  /** A job's log lines after `after` (a line's seq). */
991×
  flowLog(owner: string, name: string, number: number, job: string, after = 0): Promise<api.FlowLogLine[]> {
1001×
    return this.request("GET", `/repos/${owner}/${name}/flow/runs/${number}/jobs/${encodeURIComponent(job)}/log?after=${after}&limit=2000`);
1011×
  }
1021×
1031×
  /** Run the pipeline of a bookmark's current state, or of one change. */
1041×
  startFlowRun(owner: string, name: string, target: { bookmark?: string; change?: string }): Promise<{ number: number; url: string }> {
1051×
    return this.request("POST", `/repos/${owner}/${name}/flow/runs`, target);
1061×
  }
1071×
1081×
  rerunFlowRun(owner: string, name: string, number: number): Promise<{ number: number; url: string }> {
1091×
    return this.request("POST", `/repos/${owner}/${name}/flow/runs/${number}/rerun`);
1101×
  }
1111×
1121×
  repositories(): Promise<api.Repository[]> {
1131×
    return this.request("GET", "/repos");
1141×
  }
1151×
1161×
  repository(owner: string, name: string): Promise<api.Repository> {
1171×
    return this.request("GET", `/repos/${owner}/${name}`);
1181×
  }
1191×
1201×
  proposals(owner: string, name: string): Promise<api.Proposal[]> {
1211×
    return this.request("GET", `/repos/${owner}/${name}/proposals`);
1221×
  }
1231×
1241×
  proposal(owner: string, name: string, number: number): Promise<api.Proposal> {
1251×
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}`);
1261×
  }
1271×
1281×
  createProposal(owner: string, name: string, p: api.NewProposal): Promise<api.Proposal> {
1291×
    return this.request("POST", `/repos/${owner}/${name}/proposals`, p);
1301×
  }
1311×
1321×
  proposalComments(owner: string, name: string, number: number): Promise<api.Comment[]> {
1331×
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/comments`);
1341×
  }
1351×
1361×
  /** A comment; with `path` and `line` it is anchored to that line's atom in the projected state. */
1371×
  commentProposal(owner: string, name: string, number: number, body: string, path?: string, line?: number): Promise<api.Comment> {
1381×
    return this.request("POST", `/repos/${owner}/${name}/proposals/${number}/comments`, { body, path: path ?? null, line: line ?? null });
1391×
  }
1401×
1411×
  reviews(owner: string, name: string, number: number): Promise<api.Review[]> {
1421×
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/reviews`);
1431×
  }
1441×
1451×
  review(owner: string, name: string, number: number, verdict: "comment" | "changes" | "approve", body = ""): Promise<api.Review> {
1461×
    return this.request("POST", `/repos/${owner}/${name}/proposals/${number}/reviews`, { verdict, body });
1471×
  }
1481×
1491×
  /** The files a proposal changes, target state against projected state. */
1501×
  proposalFiles(owner: string, name: string, number: number): Promise<api.ProposalFile[]> {
1511×
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/files`);
1521×
  }
1531×
1541×
  /** A file's text on one side of a proposal; undefined when it does not exist there. */
1551×
  async proposalContent(owner: string, name: string, number: number, side: "base" | "head", path: string): Promise<string | undefined> {
1561×
    const headers: Record<string, string> = {};
1571×
    if (this.token) {
1581×
      headers.authorization = `Bearer ${this.token}`;
1591×
    }
1601×
    const res = await this.fetchImpl(`${this.base}/api/v1/repos/${owner}/${name}/proposals/${number}/content/${side}/${path.split("/").map(encodeURIComponent).join("/")}`, { headers });
1611×
    if (res.status === 404) {
1621×
      return undefined;
1631×
    }
1641×
    if (!res.ok) {
1651×
      throw new HubError(res.status, res.statusText, await res.text());
1661×
    }
1671×
    return res.text();
1681×
  }
1691×
1701×
  proposalChecks(owner: string, name: string, number: number): Promise<api.Check[]> {
1711×
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/checks`);
1721×
  }
1731×
1741×
  issues(owner: string, name: string, state: "open" | "closed" | "all" = "open"): Promise<api.Issue[]> {
1751×
    return this.request("GET", `/repos/${owner}/${name}/issues?state=${state}`);
1761×
  }
1771×
1781×
  issue(owner: string, name: string, number: number): Promise<api.Issue> {
1791×
    return this.request("GET", `/repos/${owner}/${name}/issues/${number}`);
1801×
  }
1811×
1821×
  createIssue(owner: string, name: string, title: string, body = ""): Promise<api.Issue> {
1831×
    return this.request("POST", `/repos/${owner}/${name}/issues`, { title, body });
1841×
  }
1851×
1861×
  issueComments(owner: string, name: string, number: number): Promise<api.Comment[]> {
1871×
    return this.request("GET", `/repos/${owner}/${name}/issues/${number}/comments`);
1881×
  }
1891×
1901×
  commentIssue(owner: string, name: string, number: number, body: string): Promise<api.Comment> {
1911×
    return this.request("POST", `/repos/${owner}/${name}/issues/${number}/comments`, { body });
1921×
  }
1931×
1941×
  setIssueState(owner: string, name: string, number: number, state: "open" | "closed", reason = ""): Promise<api.Issue> {
1951×
    return this.request("POST", `/repos/${owner}/${name}/issues/${number}`, { state, reason });
1961×
  }
1971×
1981×
  history(owner: string, name: string, reference: string, limit = 50): Promise<api.History> {
1991×
    return this.request("GET", `/repos/${owner}/${name}/history/${encodeURIComponent(reference)}?limit=${limit}`);
2001×
  }
2011×
2021×
  bookmarks(owner: string, name: string): Promise<api.Bookmark[]> {
2031×
    return this.request("GET", `/repos/${owner}/${name}/bookmarks`);
2041×
  }
2051×
2061×
  /** What the repository takes from and diffuses to (oxygenhub#153). */
2071×
  diffusion(owner: string, name: string): Promise<api.Diffusion> {
2081×
    return this.request("GET", `/repos/${owner}/${name}/diffusion`);
2091×
  }
2101×
2111×
  releases(owner: string, name: string): Promise<api.Release[]> {
2121×
    return this.request("GET", `/repos/${owner}/${name}/releases`);
2131×
  }
2141×
2151×
  createRelease(owner: string, name: string, r: api.NewRelease): Promise<api.Release> {
2161×
    return this.request("POST", `/repos/${owner}/${name}/releases`, r);
2171×
  }
2181×
2191×
  tags(owner: string, name: string): Promise<api.Tag[]> {
2201×
    return this.request("GET", `/repos/${owner}/${name}/tags`);
2211×
  }
2221×
2231×
  search(q: string): Promise<{ kind: string; repository: string; number: number; title: string }[]> {
2241×
    return this.request("GET", `/search?q=${encodeURIComponent(q)}`);
2251×
  }
2261×
2271×
  /** The caller's drops, newest first (oxygenhub#280). */
2281×
  drops(): Promise<api.Drop[]> {
2291×
    return this.request("GET", "/drops");
2301×
  }
2311×
2321×
  /** Someone's public drops. */
2331×
  userDrops(user: string): Promise<api.Drop[]> {
2341×
    return this.request("GET", `/users/${encodeURIComponent(user)}/drops`);
2351×
  }
2361×
2371×
  /** A drop with each text file's content. */
2381×
  drop(id: string): Promise<api.Drop> {
2391×
    return this.request("GET", `/drops/${id}`);
2401×
  }
2411×
2421×
  createDrop(d: api.NewDrop): Promise<api.Drop> {
2431×
    return this.request("POST", "/drops", d);
2441×
  }
2451×
2461×
  /** Change a drop: its title, description, visibility, or files (content null removes one). */
2471×
  editDrop(id: string, e: api.DropEdit): Promise<api.Drop> {
2481×
    return this.request("PATCH", `/drops/${id}`, e);
2491×
  }
2501×
2511×
  deleteDrop(id: string): Promise<void> {
2521×
    return this.request("DELETE", `/drops/${id}`);
2531×
  }
2541×
2551×
  /** A copy of a drop, history and all, as the caller's (oxygenhub#349). */
2561×
  forkDrop(id: string): Promise<api.Drop> {
2571×
    return this.request("POST", `/drops/${id}/fork`);
2581×
  }
2591×
2601×
  starDrop(id: string, on: boolean): Promise<api.DropStars> {
2611×
    return this.request(on ? "PUT" : "DELETE", `/drops/${id}/star`);
2621×
  }
2631×
2641×
  dropComments(id: string): Promise<api.DropComment[]> {
2651×
    return this.request("GET", `/drops/${id}/comments`);
2661×
  }
2671×
2681×
  commentDrop(id: string, body: string): Promise<api.DropComment> {
2691×
    return this.request("POST", `/drops/${id}/comments`, { body });
2701×
  }
2711×
2721×
  deleteDropComment(id: string, n: number): Promise<void> {
2731×
    return this.request("DELETE", `/drops/${id}/comments/${n}`);
2741×
  }
2751×
2761×
  /** Approve or reject a job waiting on its approval rules (oxygenflow#57). */
2771×
  decideFlowJob(owner: string, name: string, number: number, job: string, approve: boolean): Promise<unknown> {
2781×
    return this.request("POST", `/repos/${owner}/${name}/flow/runs/${number}/jobs/${encodeURIComponent(job)}/${approve ? "approve" : "reject"}`);
2791×
  }
2801×
2811×
  /** Make a queued or running run urgent, with why (oxygenhub#244). */
2821×
  expediteFlowRun(owner: string, name: string, number: number, reason: string): Promise<unknown> {
2831×
    return this.request("POST", `/repos/${owner}/${name}/flow/runs/${number}/expedite`, { reason });
2841×
  }
2851×
2861×
  cancelFlowRun(owner: string, name: string, number: number): Promise<unknown> {
2871×
    return this.request("POST", `/repos/${owner}/${name}/flow/runs/${number}/cancel`);
2881×
  }
2891×
2901×
  /** The reports a job published (oxygenhub#348). */
2911×
  jobReports(owner: string, name: string, number: number, job: string): Promise<api.Report[]> {
2921×
    return this.request("GET", `/repos/${owner}/${name}/flow/runs/${number}/jobs/${encodeURIComponent(job)}/reports`);
2931×
  }
2941×
2951×
  /** Test reports on a bookmark, newest first. */
2961×
  testReports(owner: string, name: string, bookmark?: string, limit = 1): Promise<api.TestReport[]> {
2971×
    const q = new URLSearchParams({ limit: String(limit), ...(bookmark ? { bookmark } : {}) });
2981×
    return this.request("GET", `/repos/${owner}/${name}/tests?${q}`);
2991×
  }
3001×
3011×
  testReport(owner: string, name: string, id: number): Promise<api.TestReportDetail> {
3021×
    return this.request("GET", `/repos/${owner}/${name}/tests/${id}`);
3031×
  }
3041×
3051×
  /** Make a draft ready for review, or turn an open proposal back into a draft (#313). */
3061×
  setProposalDraft(owner: string, name: string, number: number, draft: boolean): Promise<api.Proposal> {
3071×
    return this.request("PATCH", `/repos/${owner}/${name}/proposals/${number}`, { draft });
3081×
  }
3091×
3101×
  /** The dashboard's proposals; with `landable`, also what the caller can land now (#311). */
3111×
  userProposals(landable = false): Promise<api.UserProposals> {
3121×
    return this.request("GET", `/user/proposals${landable ? "?landable=true" : ""}`);
3131×
  }
3141×
3151×
  /** What a release's trust page shows: signatures, builds and the audit (#79). */
3161×
  releaseTrust(owner: string, name: string, tag: string): Promise<ReleaseTrust> {
3171×
    return this.request("GET", `/repos/${owner}/${name}/releases/trust/${encodeURIComponent(tag)}`);
3181×
  }
3191×
3201×
  orgs(): Promise<api.Organisation[]> {
3211×
    return this.request("GET", "/user/orgs");
3221×
  }
3231×
3241×
  createRepository(r: api.NewRepository): Promise<api.Repository> {
3251×
    return this.request("POST", "/repos", r);
3261×
  }
3271×
3281×
  /** The assistants a new repository under `owner` may ask for its starting files (#347). */
3291×
  starterAssistants(owner: string): Promise<api.StarterAssistants> {
3301×
    return this.request("GET", `/user/starter?owner=${encodeURIComponent(owner)}`);
3311×
  }
3321×
3331×
  startStarter(owner: string, name: string, r: api.StarterRequest): Promise<api.StarterStatus> {
3341×
    return this.request("POST", `/repos/${owner}/${name}/starter`, r);
3351×
  }
3361×
3371×
  starterStatus(owner: string, name: string): Promise<api.StarterStatus> {
3381×
    return this.request("GET", `/repos/${owner}/${name}/starter`);
3391×
  }
3401×
3411×
  /** A file's bytes from the hub (a release asset), with the session's token. */
3421×
  async download(url: string): Promise<Uint8Array> {
3431×
    const headers: Record<string, string> = {};
3441×
    if (this.token && url.startsWith(this.base + "/")) {
3451×
      headers.authorization = `Bearer ${this.token}`;
3461×
    }
3471×
    const res = await this.fetchImpl(url, { headers });
3481×
    if (!res.ok) {
3491×
      throw new HubError(res.status, res.statusText, await res.text());
3501×
    }
3511×
    return new Uint8Array(await res.arrayBuffer());
3521×
  }
3531×
}
3541×
3551×
/** A release's trust report (the web's, not in the generated types). */
3561×
export interface ReleaseTrust {
3571×
  repository: string;
3581×
  tag: string;
3591×
  title: string;
3601×
  release_url: string;
3611×
  heads: string[];
3621×
  tag_signer?: { key: string; name: string; email: string; account?: string | null } | null;
3631×
  /** `valid`, `unsigned`, `invalid: …` or `revoked`. */
3641×
  tag_signature: string;
3651×
  since?: string | null;
3661×
  changes: number;
3671×
  authors: { who: { name: string; email: string; account?: string | null }; changes: number; signed: number; sealed: number; unsigned: number; revoked: number; invalid: number }[];
3681×
  assets: { name: string; size: number; blake3: string; url: string; build?: { run: number; job: string; run_url: string; same_state_as_tag: boolean } | null }[];
3691×
  audit: { verdict: "pass" | "warn" | "fail"; title: string; detail: string }[];
3701×
  generated_ms: number;
3711×
}
3721×
3731×
/** A release's trust report as Markdown, for a preview beside the code. */
3741×
export function trustMarkdown(t: ReleaseTrust): string {
3751×
  const glyph = { pass: "✔", warn: "!", fail: "✘" } as const;
3761×
  const out = [`# Trust: ${t.title || t.tag}`, "", `${t.repository} · tag \`${t.tag}\` · ${t.heads.map((h) => h.slice(0, 12)).join("+")}`, ""];
3771×
  const signer = t.tag_signer ? `${t.tag_signer.name} <${t.tag_signer.email}>` : "";
3781×
  out.push(`- Tag signature: **${t.tag_signature}**${signer ? ` by ${signer}` : ""}`);
3791×
  out.push(`- ${t.changes} change${t.changes === 1 ? "" : "s"}${t.since ? ` since ${t.since}` : ""}`, "");
3801×
  out.push("## Audit", "");
3811×
  for (const c of t.audit) {
3821×
    out.push(`- ${glyph[c.verdict]} **${c.title}**${c.detail ? ` — ${c.detail}` : ""}`);
3831×
  }
3841×
  if (t.authors.length) {
3851×
    out.push("", "## Authors", "", "| Author | Changes | Signed | Sealed | Unsigned | Revoked | Invalid |", "|---|---:|---:|---:|---:|---:|---:|");
3861×
    for (const a of t.authors) {
3871×
      out.push(`| ${a.who.account ?? a.who.name} | ${a.changes} | ${a.signed} | ${a.sealed} | ${a.unsigned} | ${a.revoked} | ${a.invalid} |`);
3881×
    }
3891×
  }
3901×
  if (t.assets.length) {
3911×
    out.push("", "## Assets", "");
3921×
    for (const a of t.assets) {
3931×
      const build = a.build ? `built by [run #${a.build.run}](${a.build.run_url}) ${a.build.job}${a.build.same_state_as_tag ? "" : " (not the tagged state)"}` : "no attested build";
3941×
      out.push(`- \`${a.name}\` · BLAKE3 \`${a.blake3.slice(0, 16)}…\` · ${build}`);
3951×
    }
3961×
  }
3971×
  out.push("", `[The release](${t.release_url})`, "");
3981×
  return out.join("\n");
3991×
}
4001×
4011×
/** Web URLs on the hub for things the remote provider is asked about. */
4021×
export function hubUrl(base: string, owner: string, name: string, target: { kind: string; [k: string]: unknown }): string {
4031×
  const repo = `${base}/${owner}/${name}`;
4041×
  switch (target.kind) {
4051×
    case "repository":
4061×
      return repo;
4071×
    case "bookmark":
4081×
      return `${repo}/tree/${encodeURIComponent(String(target.name))}`;
4091×
    case "change":
4101×
      return `${repo}/change/${target.hash}`;
4111×
    case "file": {
4120×
      const end = typeof target.endLine === "number" && target.endLine !== target.line ? `-L${target.endLine}` : "";
4130×
      const line = typeof target.line === "number" ? `#L${target.line}${end}` : "";
4140×
      // A state address (`hash+hash`) keeps its `+`, as the hub writes permalinks.
4150×
      return `${repo}/file/${encodeURIComponent(String(target.reference)).replace(/%2B/g, "+")}/${String(target.path)}${line}`;
4160×
    }
4171×
    case "proposals":
4181×
      return `${repo}/proposals`;
4191×
    case "issues":
4201×
      return `${repo}/issues`;
4211×
    case "proposal":
4221×
      return `${repo}/proposal/${target.number}`;
4231×
    case "issue":
4241×
      return `${repo}/issue/${target.number}`;
4251×
    case "diffusion":
4261×
      return `${repo}/diffusion`;
4271×
    default:
4281×
      return repo;
4291×
  }
4301×
}
4315×
4325×
/** Which of the proposals need the signed-in user: not theirs, and not yet sealed by them. */
4335×
export function needsMe(p: import("./hubapi").Proposal, username: string | undefined): boolean {
4345×
  if (!username || p.author === username) {
4351×
    return false;
4361×
  }
4375×
  if (p.state !== "open") {
4381×
    return false;
4391×
  }
4403×
  const mine = p.approvals.find((a) => a.account === username);
4415×
  return !mine || !mine.sealed;
4421×
}
4431×
4441×
/** Which proposal, side and file a diff document shows. */
4451×
export interface DiffRef {
4461×
  base: string;
4471×
  owner: string;
4481×
  name: string;
4491×
  number: number;
4501×
  side: "base" | "head";
4511×
  path: string;
4521×
}
4531×
4541×
/** The query string of a diff document's URI. */
4551×
export function encodeDiffQuery(r: DiffRef): string {
4561×
  return new URLSearchParams({ hub: r.base, owner: r.owner, name: r.name, number: String(r.number), side: r.side }).toString();
4571×
}
4583×
4593×
/** Parse a diff document's query and path back; undefined if it is not one. */
4603×
export function decodeDiffQuery(query: string, path: string): DiffRef | undefined {
4614×
  const q = new URLSearchParams(query);
4624×
  const number = Number(q.get("number"));
4634×
  const side = q.get("side");
4644×
  const [base, owner, name] = [q.get("hub"), q.get("owner"), q.get("name")];
4654×
  if (!base || !owner || !name || !Number.isInteger(number) || number < 1 || (side !== "base" && side !== "head")) {
4663×
    return undefined;
4673×
  }
4684×
  return { base, owner, name, number, side, path: path.replace(/^\/+/, "") };
4694×
}
4704×
4714×
/** What a hub page URL points at, for opening it in the editor instead of a browser. */
4724×
export type HubTarget = { kind: "proposal" | "issue"; base: string; owner: string; name: string; number: number } | { kind: "other"; url: string };
4734×
4744×
export function hubTarget(url: string): HubTarget {
4754×
  const m = /^(https?:\/\/[^/]+)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/(proposal|issue)\/(\d+)(?:[/?#].*)?$/.exec(url);
4764×
  if (!m) {
4772×
    return { kind: "other", url };
4782×
  }
4794×
  return { kind: m[4] as "proposal" | "issue", base: m[1], owner: m[2], name: m[3], number: Number(m[5]) };
4803×
}
4813×
4823×
/**
4833×
 * Release notes from history: the changes in `current` that `previous`
4843×
 * does not have, newest first, one line each (the message's subject).
4853×
 */
4863×
export function releaseNotes(current: api.ChangeSummary[], previous: api.ChangeSummary[], sinceTag?: string): string {
4873×
  const seen = new Set(previous.map((c) => c.hash));
4883×
  const lines = current
4893×
    .filter((c) => !seen.has(c.hash))
4903×
    .sort((a, b) => b.when_ms - a.when_ms)
4913×
    .map((c) => `- ${c.message.split("\n")[0].trim()} (${c.hash.slice(0, 12)})`);
4923×
  const head = sinceTag ? `Changes since ${sinceTag}:` : "Changes:";
4933×
  return lines.length ? `${head}\n\n${lines.join("\n")}\n` : "No changes since the last release.\n";
49410×
}
49510×
49610×
/** Whether a tag name reads as a pre-release (`v1.0-rc1`, `2.0.0-beta.2`, `alpha`). */
49710×
export function looksPrerelease(tag: string): boolean {
49810×
  return /(^|[-.+_])(alpha|beta|rc|pre|preview|dev)\d*([-.+_]|$)/i.test(tag) || /-(a|b|rc)\d+$/i.test(tag);
49910×
}
5003×
5013×
/**
5023×
 * A `fetch` that also trusts the CA certificate in `caFile`, for a hub with a
5033×
 * self-signed certificate (Node's `fetch` takes no CA). The file is read on
5043×
 * each request, so a renewed certificate needs no reload.
5053×
 */
5063×
export function fetchTrusting(caFile: string): typeof fetch {
5072×
  return ((input: string | URL | Request, init?: RequestInit) =>
5084×
    new Promise<Response>((resolve, reject) => {
5094×
      const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url);
5104×
      const secure = url.protocol === "https:";
5114×
      let ca: string[] | undefined;
5124×
      if (secure) {
5134×
        try {
5144×
          ca = [...tls.rootCertificates, readFileSync(caFile, "utf8")];
5154×
        } catch (e) {
5161×
          reject(new Error(`cannot read the hub's CA file ${caFile}: ${(e as Error).message}`));
5171×
          return;
5181×
        }
5194×
      }
5203×
      const headers: Record<string, string> = {};
5214×
      new Headers(init?.headers).forEach((v, k) => (headers[k] = v));
5224×
      const req = (secure ? https : http).request(url, { method: init?.method ?? "GET", headers, ca }, (res) => {
5233×
        const chunks: Buffer[] = [];
5243×
        res.on("data", (c: Buffer) => chunks.push(c));
5253×
        res.on("error", reject);
5263×
        res.on("end", () => {
5273×
          const status = res.statusCode ?? 0;
5283×
          const out = new Headers();
5293×
          for (const [k, v] of Object.entries(res.headers)) {
53013×
            if (v !== undefined) {
53113×
              out.set(k, Array.isArray(v) ? v.join(", ") : String(v));
53213×
            }
53313×
          }
5343×
          const empty = status === 204 || status === 304;
5353×
          resolve(new Response(empty ? null : Buffer.concat(chunks), { status, headers: out }));
5363×
        });
5374×
      });
5384×
      req.on("error", (e) => reject(Object.assign(new Error(`fetch failed: ${e.message}`), { cause: e })));
5394×
      if (init?.body !== undefined && init.body !== null) {
5401×
        req.write(typeof init.body === "string" ? init.body : Buffer.from(init.body as ArrayBuffer));
5411×
      }
5424×
      req.end();
5432×
    })) as typeof fetch;
5442×
}