OXYGENHUB
# 1cc0ff44e5ca oxygenhub-vscode / src / hub.ts
11.2 KiB · last changed Releases view and Draft Release from a tag with notes from history (0.6.0) 1 month ago source blame history raw
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
26
export interface Session {
27
  base: string;
28
  token: string;
29
  username?: string;
30
}
31
32
export class HubClient {
33
  constructor(
34
    readonly base: string,
35
    private readonly token: string | undefined,
36
    private readonly fetchImpl: typeof fetch = fetch,
37
  ) {}
38
39
  private async request<T>(method: string, path: string, body?: unknown): Promise<T> {
40
    const headers: Record<string, string> = { accept: "application/json" };
41
    if (this.token) {
42
      headers.authorization = `Bearer ${this.token}`;
43
    }
44
    if (body !== undefined) {
45
      headers["content-type"] = "application/json";
46
    }
47
    const res = await this.fetchImpl(`${this.base}/api/v1${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
48
    if (res.status === 204) {
49
      return undefined as T;
50
    }
51
    const text = await res.text();
52
    if (!res.ok) {
53
      try {
54
        const p = JSON.parse(text) as api.Problem;
55
        throw new HubError(p.status, p.title, p.detail);
56
      } catch (e) {
57
        if (e instanceof HubError) {
58
          throw e;
59
        }
60
        throw new HubError(res.status, res.statusText, text);
61
      }
62
    }
63
    return (text ? JSON.parse(text) : undefined) as T;
64
  }
65
66
  me(): Promise<api.User> {
67
    return this.request("GET", "/user");
68
  }
69
70
  /** The caller's inbox: unread count and newest entries (needs user:read). */
71
  notifications(limit = 50): Promise<api.Inbox> {
72
    return this.request("GET", `/notifications?limit=${limit}`);
73
  }
74
75
  markNotificationRead(id: number): Promise<void> {
76
    return this.request("POST", `/notifications/${id}/read`);
77
  }
78
79
  markAllNotificationsRead(): Promise<void> {
80
    return this.request("POST", "/notifications/read");
81
  }
82
83
  repositories(): Promise<api.Repository[]> {
84
    return this.request("GET", "/repos");
85
  }
86
87
  repository(owner: string, name: string): Promise<api.Repository> {
88
    return this.request("GET", `/repos/${owner}/${name}`);
89
  }
90
91
  proposals(owner: string, name: string): Promise<api.Proposal[]> {
92
    return this.request("GET", `/repos/${owner}/${name}/proposals`);
93
  }
94
95
  proposal(owner: string, name: string, number: number): Promise<api.Proposal> {
96
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}`);
97
  }
98
99
  createProposal(owner: string, name: string, p: api.NewProposal): Promise<api.Proposal> {
100
    return this.request("POST", `/repos/${owner}/${name}/proposals`, p);
101
  }
102
103
  proposalComments(owner: string, name: string, number: number): Promise<api.Comment[]> {
104
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/comments`);
105
  }
106
107
  /** A comment; with `path` and `line` it is anchored to that line's atom in the projected state. */
108
  commentProposal(owner: string, name: string, number: number, body: string, path?: string, line?: number): Promise<api.Comment> {
109
    return this.request("POST", `/repos/${owner}/${name}/proposals/${number}/comments`, { body, path: path ?? null, line: line ?? null });
110
  }
111
112
  reviews(owner: string, name: string, number: number): Promise<api.Review[]> {
113
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/reviews`);
114
  }
115
116
  review(owner: string, name: string, number: number, verdict: "comment" | "changes" | "approve", body = ""): Promise<api.Review> {
117
    return this.request("POST", `/repos/${owner}/${name}/proposals/${number}/reviews`, { verdict, body });
118
  }
119
120
  /** The files a proposal changes, target state against projected state. */
121
  proposalFiles(owner: string, name: string, number: number): Promise<api.ProposalFile[]> {
122
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/files`);
123
  }
124
125
  /** A file's text on one side of a proposal; undefined when it does not exist there. */
126
  async proposalContent(owner: string, name: string, number: number, side: "base" | "head", path: string): Promise<string | undefined> {
127
    const headers: Record<string, string> = {};
128
    if (this.token) {
129
      headers.authorization = `Bearer ${this.token}`;
130
    }
131
    const res = await this.fetchImpl(`${this.base}/api/v1/repos/${owner}/${name}/proposals/${number}/content/${side}/${path.split("/").map(encodeURIComponent).join("/")}`, { headers });
132
    if (res.status === 404) {
133
      return undefined;
134
    }
135
    if (!res.ok) {
136
      throw new HubError(res.status, res.statusText, await res.text());
137
    }
138
    return res.text();
139
  }
140
141
  proposalChecks(owner: string, name: string, number: number): Promise<api.Check[]> {
142
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/checks`);
143
  }
144
145
  issues(owner: string, name: string, state: "open" | "closed" | "all" = "open"): Promise<api.Issue[]> {
146
    return this.request("GET", `/repos/${owner}/${name}/issues?state=${state}`);
147
  }
148
149
  issue(owner: string, name: string, number: number): Promise<api.Issue> {
150
    return this.request("GET", `/repos/${owner}/${name}/issues/${number}`);
151
  }
152
153
  createIssue(owner: string, name: string, title: string, body = ""): Promise<api.Issue> {
154
    return this.request("POST", `/repos/${owner}/${name}/issues`, { title, body });
155
  }
156
157
  issueComments(owner: string, name: string, number: number): Promise<api.Comment[]> {
158
    return this.request("GET", `/repos/${owner}/${name}/issues/${number}/comments`);
159
  }
160
161
  commentIssue(owner: string, name: string, number: number, body: string): Promise<api.Comment> {
162
    return this.request("POST", `/repos/${owner}/${name}/issues/${number}/comments`, { body });
163
  }
164
165
  setIssueState(owner: string, name: string, number: number, state: "open" | "closed", reason = ""): Promise<api.Issue> {
166
    return this.request("POST", `/repos/${owner}/${name}/issues/${number}`, { state, reason });
167
  }
168
169
  history(owner: string, name: string, reference: string, limit = 50): Promise<api.History> {
170
    return this.request("GET", `/repos/${owner}/${name}/history/${encodeURIComponent(reference)}?limit=${limit}`);
171
  }
172
173
  bookmarks(owner: string, name: string): Promise<api.Bookmark[]> {
174
    return this.request("GET", `/repos/${owner}/${name}/bookmarks`);
175
  }
176
177
  releases(owner: string, name: string): Promise<api.Release[]> {
178
    return this.request("GET", `/repos/${owner}/${name}/releases`);
179
  }
180
181
  createRelease(owner: string, name: string, r: api.NewRelease): Promise<api.Release> {
182
    return this.request("POST", `/repos/${owner}/${name}/releases`, r);
183
  }
184
185
  tags(owner: string, name: string): Promise<api.Tag[]> {
186
    return this.request("GET", `/repos/${owner}/${name}/tags`);
187
  }
188
189
  search(q: string): Promise<{ kind: string; repository: string; number: number; title: string }[]> {
190
    return this.request("GET", `/search?q=${encodeURIComponent(q)}`);
191
  }
192
}
193
194
/** Web URLs on the hub for things the remote provider is asked about. */
195
export function hubUrl(base: string, owner: string, name: string, target: { kind: string; [k: string]: unknown }): string {
196
  const repo = `${base}/${owner}/${name}`;
197
  switch (target.kind) {
198
    case "repository":
199
      return repo;
200
    case "bookmark":
201
      return `${repo}/tree/${encodeURIComponent(String(target.name))}`;
202
    case "change":
203
      return `${repo}/change/${target.hash}`;
204
    case "file": {
205
      const end = typeof target.endLine === "number" && target.endLine !== target.line ? `-L${target.endLine}` : "";
206
      const line = typeof target.line === "number" ? `#L${target.line}${end}` : "";
207
      return `${repo}/file/${encodeURIComponent(String(target.reference))}/${String(target.path)}${line}`;
208
    }
209
    case "proposals":
210
      return `${repo}/proposals`;
211
    case "issues":
212
      return `${repo}/issues`;
213
    case "proposal":
214
      return `${repo}/proposal/${target.number}`;
215
    case "issue":
216
      return `${repo}/issue/${target.number}`;
217
    default:
218
      return repo;
219
  }
220
}
221
222
/** Which of the proposals need the signed-in user: not theirs, and not yet sealed by them. */
223
export function needsMe(p: import("./hubapi").Proposal, username: string | undefined): boolean {
224
  if (!username || p.author === username) {
225
    return false;
226
  }
227
  if (p.state !== "open") {
228
    return false;
229
  }
230
  const mine = p.approvals.find((a) => a.account === username);
231
  return !mine || !mine.sealed;
232
}
233
234
/** Which proposal, side and file a diff document shows. */
235
export interface DiffRef {
236
  base: string;
237
  owner: string;
238
  name: string;
239
  number: number;
240
  side: "base" | "head";
241
  path: string;
242
}
243
244
/** The query string of a diff document's URI. */
245
export function encodeDiffQuery(r: DiffRef): string {
246
  return new URLSearchParams({ hub: r.base, owner: r.owner, name: r.name, number: String(r.number), side: r.side }).toString();
247
}
248
249
/** Parse a diff document's query and path back; undefined if it is not one. */
250
export function decodeDiffQuery(query: string, path: string): DiffRef | undefined {
251
  const q = new URLSearchParams(query);
252
  const number = Number(q.get("number"));
253
  const side = q.get("side");
254
  const [base, owner, name] = [q.get("hub"), q.get("owner"), q.get("name")];
255
  if (!base || !owner || !name || !Number.isInteger(number) || number < 1 || (side !== "base" && side !== "head")) {
256
    return undefined;
257
  }
258
  return { base, owner, name, number, side, path: path.replace(/^\/+/, "") };
259
}
260
261
/** What a hub page URL points at, for opening it in the editor instead of a browser. */
262
export type HubTarget = { kind: "proposal" | "issue"; base: string; owner: string; name: string; number: number } | { kind: "other"; url: string };
263
264
export function hubTarget(url: string): HubTarget {
265
  const m = /^(https?:\/\/[^/]+)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/(proposal|issue)\/(\d+)(?:[/?#].*)?$/.exec(url);
266
  if (!m) {
267
    return { kind: "other", url };
268
  }
269
  return { kind: m[4] as "proposal" | "issue", base: m[1], owner: m[2], name: m[3], number: Number(m[5]) };
270
}
271
272
/**
273
 * Release notes from history: the changes in `current` that `previous`
274
 * does not have, newest first, one line each (the message's subject).
275
 */
276
export function releaseNotes(current: api.ChangeSummary[], previous: api.ChangeSummary[], sinceTag?: string): string {
277
  const seen = new Set(previous.map((c) => c.hash));
278
  const lines = current
279
    .filter((c) => !seen.has(c.hash))
280
    .sort((a, b) => b.when_ms - a.when_ms)
281
    .map((c) => `- ${c.message.split("\n")[0].trim()} (${c.hash.slice(0, 12)})`);
282
  const head = sinceTag ? `Changes since ${sinceTag}:` : "Changes:";
283
  return lines.length ? `${head}\n\n${lines.join("\n")}\n` : "No changes since the last release.\n";
284
}
285
286
/** Whether a tag name reads as a pre-release (`v1.0-rc1`, `2.0.0-beta.2`, `alpha`). */
287
export function looksPrerelease(tag: string): boolean {
288
  return /(^|[-.+_])(alpha|beta|rc|pre|preview|dev)\d*([-.+_]|$)/i.test(tag) || /-(a|b|rc)\d+$/i.test(tag);
289
}