OXYGENHUB
# 95f69b4a3ac2 oxygenhub-vscode / src / hub.ts
9.9 KiB · last changed New Issue from Selection (0.5.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
  search(q: string): Promise<{ kind: string; repository: string; number: number; title: string }[]> {
178
    return this.request("GET", `/search?q=${encodeURIComponent(q)}`);
179
  }
180
}
181
182
/** Web URLs on the hub for things the remote provider is asked about. */
183
export function hubUrl(base: string, owner: string, name: string, target: { kind: string; [k: string]: unknown }): string {
184
  const repo = `${base}/${owner}/${name}`;
185
  switch (target.kind) {
186
    case "repository":
187
      return repo;
188
    case "bookmark":
189
      return `${repo}/tree/${encodeURIComponent(String(target.name))}`;
190
    case "change":
191
      return `${repo}/change/${target.hash}`;
192
    case "file": {
193
      const end = typeof target.endLine === "number" && target.endLine !== target.line ? `-L${target.endLine}` : "";
194
      const line = typeof target.line === "number" ? `#L${target.line}${end}` : "";
195
      return `${repo}/file/${encodeURIComponent(String(target.reference))}/${String(target.path)}${line}`;
196
    }
197
    case "proposals":
198
      return `${repo}/proposals`;
199
    case "issues":
200
      return `${repo}/issues`;
201
    case "proposal":
202
      return `${repo}/proposal/${target.number}`;
203
    case "issue":
204
      return `${repo}/issue/${target.number}`;
205
    default:
206
      return repo;
207
  }
208
}
209
210
/** Which of the proposals need the signed-in user: not theirs, and not yet sealed by them. */
211
export function needsMe(p: import("./hubapi").Proposal, username: string | undefined): boolean {
212
  if (!username || p.author === username) {
213
    return false;
214
  }
215
  if (p.state !== "open") {
216
    return false;
217
  }
218
  const mine = p.approvals.find((a) => a.account === username);
219
  return !mine || !mine.sealed;
220
}
221
222
/** Which proposal, side and file a diff document shows. */
223
export interface DiffRef {
224
  base: string;
225
  owner: string;
226
  name: string;
227
  number: number;
228
  side: "base" | "head";
229
  path: string;
230
}
231
232
/** The query string of a diff document's URI. */
233
export function encodeDiffQuery(r: DiffRef): string {
234
  return new URLSearchParams({ hub: r.base, owner: r.owner, name: r.name, number: String(r.number), side: r.side }).toString();
235
}
236
237
/** Parse a diff document's query and path back; undefined if it is not one. */
238
export function decodeDiffQuery(query: string, path: string): DiffRef | undefined {
239
  const q = new URLSearchParams(query);
240
  const number = Number(q.get("number"));
241
  const side = q.get("side");
242
  const [base, owner, name] = [q.get("hub"), q.get("owner"), q.get("name")];
243
  if (!base || !owner || !name || !Number.isInteger(number) || number < 1 || (side !== "base" && side !== "head")) {
244
    return undefined;
245
  }
246
  return { base, owner, name, number, side, path: path.replace(/^\/+/, "") };
247
}
248
249
/** What a hub page URL points at, for opening it in the editor instead of a browser. */
250
export type HubTarget = { kind: "proposal" | "issue"; base: string; owner: string; name: string; number: number } | { kind: "other"; url: string };
251
252
export function hubTarget(url: string): HubTarget {
253
  const m = /^(https?:\/\/[^/]+)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/(proposal|issue)\/(\d+)(?:[/?#].*)?$/.exec(url);
254
  if (!m) {
255
    return { kind: "other", url };
256
  }
257
  return { kind: m[4] as "proposal" | "issue", base: m[1], owner: m[2], name: m[3], number: Number(m[5]) };
258
}