@noldova/git.github 0.0.6 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/module.json CHANGED
@@ -1,16 +1,17 @@
1
1
  {
2
2
  "id": "git-github",
3
- "version": "0.0.6",
3
+ "version": "0.0.7",
4
4
  "displayName": "GitHub",
5
5
  "description": "Signs in to GitHub, shows its issues, pull requests and checks, and opens pull requests, and lets AI agents do the same through permission requests.",
6
6
  "parts": ["runtime", "window"],
7
- "dependencies": { "git": "0.0.6" },
8
- "noldovaDesktop": ">=0.0.11 <0.1.0",
7
+ "dependencies": { "git": "0.0.7" },
8
+ "noldovaDesktop": ">=0.0.17 <0.1.0",
9
9
  "contributes": {
10
10
  "methods": ["git-github.readSignIn", "git-github.startSignIn", "git-github.cancelSignIn", "git-github.signOut", "git-github.readReference",
11
- "git-github.readBranchPullRequest", "git-github.createPullRequest"],
11
+ "git-github.readBranchPullRequest", "git-github.createPullRequest",
12
+ "git-github.readAuthorAvatar", "git-github.readPullRequests", "git-github.readReviewRequests",
13
+ "git-github.readCommitComments", "git-github.readPullRequest", "git-github.readPullRequestThreads"],
12
14
  "events": ["git-github.signInChanged"],
13
- "settingsPages": ["git-github.account"],
14
15
  "tools": ["git_github_read", "git_github_pr_checks", "git_github_pr_create"]
15
16
  }
16
17
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noldova/git.github",
3
- "version": "0.0.6",
3
+ "version": "0.0.7",
4
4
  "description": "The GitHub module for apps on Noldova Desktop: the sign-in to GitHub, its issues, pull requests and checks, and agent tools that use GitHub through permission requests.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -35,16 +35,16 @@
35
35
  "registry": "https://registry.npmjs.org/"
36
36
  },
37
37
  "dependencies": {
38
- "@noldova/git.github.protocol": "0.0.6",
39
- "@noldova/git.protocol": "0.0.6",
40
- "@noldova/git.github.window": "0.0.6",
41
- "@noldova/git.hosting.protocol": "0.0.6"
38
+ "@noldova/git.github.protocol": "0.0.7",
39
+ "@noldova/git.protocol": "0.0.7",
40
+ "@noldova/git.github.window": "0.0.7",
41
+ "@noldova/git.hosting.protocol": "0.0.7"
42
42
  },
43
43
  "peerDependencies": {
44
- "@noldova/desktop.protocol": ">=0.0.11 <0.1.0",
45
- "@noldova/desktop.runtime": ">=0.0.11 <0.1.0",
46
- "@noldova/context.exceptions": ">=0.0.9 <0.1.0",
47
- "@noldova/context.json": ">=0.0.9 <0.1.0"
44
+ "@noldova/desktop.protocol": ">=0.0.17 <0.1.0",
45
+ "@noldova/desktop.runtime": ">=0.0.17 <0.1.0",
46
+ "@noldova/context.exceptions": ">=0.0.12 <0.1.0",
47
+ "@noldova/context.json": ">=0.0.12 <0.1.0"
48
48
  },
49
- "gitHead": "1c2798e01c4c0ae4f1757fd56b0cf7346a219f58"
49
+ "gitHead": "45f5b72338641052ee3e5354f0e39538b656b110"
50
50
  }
package/settings.json CHANGED
@@ -1,4 +1,3 @@
1
1
  {
2
- "settings": [],
3
- "pages": [{ "name": "git-github.account", "title": "GitHub" }]
2
+ "settings": []
4
3
  }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import { Resources } from "../resources.js";
9
+ import { SignInRefusedException } from "./sign-in-refused.exception.js";
10
+ export class SignInAnswerTooLargeException extends SignInRefusedException {
11
+ url;
12
+ constructor(url) {
13
+ super(Resources.formatSignInAnswerTooLarge(url));
14
+ this.url = url;
15
+ }
16
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ export class NewestItems {
9
+ items;
10
+ hasMore;
11
+ constructor(items, hasMore) {
12
+ this.items = items;
13
+ this.hasMore = hasMore;
14
+ }
15
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ export class ReviewSearchAnswer {
9
+ rows;
10
+ isCut;
11
+ constructor(rows, isCut) {
12
+ this.rows = rows;
13
+ this.isCut = isCut;
14
+ }
15
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ export class ReviewSearch {
9
+ token;
10
+ startedAt;
11
+ answer;
12
+ constructor(token, startedAt, answer) {
13
+ this.token = token;
14
+ this.startedAt = startedAt;
15
+ this.answer = answer;
16
+ }
17
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ export class ReviewVerdict {
9
+ login;
10
+ state;
11
+ constructor(login, state) {
12
+ this.login = login;
13
+ this.state = state;
14
+ }
15
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ export class SignInMethod {
9
+ name;
10
+ run;
11
+ constructor(name, run) {
12
+ this.name = name;
13
+ this.run = run;
14
+ }
15
+ }
package/src/resources.js CHANGED
@@ -23,6 +23,7 @@ export class Resources {
23
23
  static scopeSeparator = ",";
24
24
  static requestTimeout = 30_000;
25
25
  static avatarHost = "avatars.githubusercontent.com";
26
+ static noReplyPattern = /^(?:(\d{1,12})\+)?([a-z\d](?:[a-z\d-]{0,38}))@users\.noreply\.github\.com$/u;
26
27
  static httpsProtocol = "https:";
27
28
  static avatarSizeParameter = "s";
28
29
  static avatarSize = "64";
@@ -48,6 +49,8 @@ export class Resources {
48
49
  static avatarRedirectedAway = `the avatar server redirected more than ${Resources.avatarRedirects} times, or off its host`;
49
50
  static tokenNotForgotten = "The GitHub token couldn't be removed from this computer's secrets; it is no longer used.";
50
51
  static manualRedirect = "manual";
52
+ static apiRedirects = 1;
53
+ static movedMessage = "GitHub answered that this was moved to an address the module doesn't follow. If the repository was renamed or transferred, update the remote to its new address.";
51
54
  static intervalField = "interval";
52
55
  static expiresInField = "expires_in";
53
56
  static pendingError = "authorization_pending";
@@ -64,6 +67,8 @@ export class Resources {
64
67
  static freshFor = 60_000;
65
68
  static cacheSize = 500;
66
69
  static maximumKeptLength = 262_144;
70
+ static maximumAnswerBytes = 8 * 1_024 * 1_024;
71
+ static maximumSignInAnswerBytes = 65_536;
67
72
  static rateLimitRemainingHeader = "x-ratelimit-remaining";
68
73
  static rateLimitResetHeader = "x-ratelimit-reset";
69
74
  static noneRemaining = "0";
@@ -74,6 +79,8 @@ export class Resources {
74
79
  static notPlannedReason = "not_planned";
75
80
  static pullRequestField = "pull_request";
76
81
  static itemsField = "items";
82
+ static commitIdField = "commit_id";
83
+ static originalCommitIdField = "original_commit_id";
77
84
  static numberField = "number";
78
85
  static checkRunsField = "check_runs";
79
86
  static stateField = "state";
@@ -88,6 +95,7 @@ export class Resources {
88
95
  static mergedAtField = "merged_at";
89
96
  static draftField = "draft";
90
97
  static userField = "user";
98
+ static authorField = "author";
91
99
  static loginField = "login";
92
100
  static avatarUrlField = "avatar_url";
93
101
  static titleField = "title";
@@ -95,12 +103,27 @@ export class Resources {
95
103
  static createdAtField = "created_at";
96
104
  static closedAtField = "closed_at";
97
105
  static commentsField = "comments";
106
+ static commitsField = "commits";
107
+ static reviewCommentsField = "review_comments";
108
+ static autoMergeField = "auto_merge";
109
+ static mergeMethodField = "merge_method";
110
+ static mergeableStateField = "mergeable_state";
111
+ static requestedReviewersField = "requested_reviewers";
112
+ static requestedTeamsField = "requested_teams";
113
+ static startedAtField = "started_at";
114
+ static completedAtField = "completed_at";
115
+ static idField = "id";
116
+ static inReplyToIdField = "in_reply_to_id";
117
+ static pathField = "path";
118
+ static lineField = "line";
119
+ static originalLineField = "original_line";
98
120
  static statusField = "status";
99
121
  static conclusionField = "conclusion";
100
122
  static nameField = "name";
101
123
  static signedOutMessage = "Sign in to GitHub first.";
102
124
  static unreachableMessage = "GitHub couldn't be reached.";
103
125
  static unreadableAnswerMessage = "GitHub's answer couldn't be read.";
126
+ static answerTooLargeMessage = `GitHub's answer is over ${Resources.maximumAnswerBytes / Resources.bytesPerKibibyte / Resources.bytesPerKibibyte} MiB, more than the module reads.`;
104
127
  static notFoundMessage = "GitHub has no such repository, or the sign-in can't see it.";
105
128
  static refusedPullRequestMessage = "GitHub refused the pull request: the branch may already have one, or have no commits the base lacks.";
106
129
  static otherHostMessage = "The repository isn't on github.com.";
@@ -142,7 +165,7 @@ export class Resources {
142
165
  static maximumBranchLength = 255;
143
166
  static maximumBodyLength = 65_536;
144
167
  static notBlankPattern = "\\S";
145
- static oneLinePattern = "^[^\\r\\n\\u2028\\u2029]*\\S[^\\r\\n\\u2028\\u2029]*$";
168
+ static oneLinePattern = "^[^\\r\\n\\v\\f\\u0085\\u2028\\u2029]*[^\\s\\u0085][^\\r\\n\\v\\f\\u0085\\u2028\\u2029]*$";
146
169
  static createToolDeadline = 60_000;
147
170
  static createToolMaximumDeadline = 120_000;
148
171
  static branchLabel = "Branch";
@@ -193,14 +216,31 @@ export class Resources {
193
216
  static repositoryPathPattern = /^[A-Za-z0-9-]+\/(?!\.\.?$)[A-Za-z0-9._-]+$/;
194
217
  static repositoryPathSeparator = "/";
195
218
  static pullsPath = "pulls";
219
+ static openPullsPath = "pulls?state=open&sort=updated&direction=desc&per_page=21";
196
220
  static checkRunsPageSize = 100;
197
221
  static reviewsPageSize = 100;
222
+ static commentsPageSize = 100;
223
+ static newestCommentsCount = 100;
198
224
  static approvedReview = "APPROVED";
199
225
  static changesRequestedReview = "CHANGES_REQUESTED";
200
226
  static dismissedReview = "DISMISSED";
227
+ static commentedReview = "COMMENTED";
228
+ static pendingReview = "PENDING";
229
+ static approvedLabel = "Approved";
230
+ static changesRequestedLabel = "Changes requested";
231
+ static commentedLabel = "Commented";
232
+ static reviewRequestedLabel = "Review requested";
233
+ static dirtyMergeableState = "dirty";
234
+ static unknownMergeableState = "unknown";
235
+ static ghostLogin = "ghost";
201
236
  static authorAssociationField = "author_association";
202
237
  static reviewerAssociations = ["OWNER", "MEMBER", "COLLABORATOR"];
203
238
  static totalCountField = "total_count";
239
+ static incompleteResultsField = "incomplete_results";
240
+ static repositoryUrlField = "repository_url";
241
+ static reviewRequestsPath = "/search/issues?q=is%3Apr+is%3Aopen+review-requested%3A%40me&sort=updated&order=desc&per_page=100";
242
+ static repositoryApiPrefix = "https://api.github.com/repos/";
243
+ static reviewRequestsHeldFor = 60_000;
204
244
  static objectType = "object";
205
245
  static stringType = "string";
206
246
  static booleanType = "boolean";
@@ -255,6 +295,9 @@ export class Resources {
255
295
  static formatSignInError(error) {
256
296
  return `GitHub ended the sign-in with the error ${error}.`;
257
297
  }
298
+ static formatSignInAnswerTooLarge(url) {
299
+ return `GitHub's answer to the sign-in's request to ${url} is over ${Resources.maximumSignInAnswerBytes / Resources.bytesPerKibibyte} KiB, more than the module reads.`;
300
+ }
258
301
  static formatSignInRequestRefused(url, status) {
259
302
  return `GitHub refused the sign-in's request to ${url} (${status}).`;
260
303
  }
@@ -273,6 +316,30 @@ export class Resources {
273
316
  static formatHeadFilter(owner, branch) {
274
317
  return `${owner}:${branch}`;
275
318
  }
319
+ static formatCommitPath(commit) {
320
+ return `commits/${commit}`;
321
+ }
322
+ static formatCommitCommentsPath(commit) {
323
+ return `commits/${commit}/comments?per_page=${Resources.commentsPageSize}`;
324
+ }
325
+ static formatCommitPullsPath(commit) {
326
+ return `commits/${commit}/${Resources.pullsPath}?per_page=1`;
327
+ }
328
+ static formatPullCommentsPath(number) {
329
+ return `${Resources.pullsPath}/${number}/comments?per_page=${Resources.commentsPageSize}`;
330
+ }
331
+ static formatAccountAvatar(id, login) {
332
+ return id === null ? `https://${Resources.avatarHost}/${login}` : `https://${Resources.avatarHost}/u/${id}?v=4`;
333
+ }
334
+ static formatIssueCommentsPath(number, page) {
335
+ return Resources.formatPagePath(`issues/${number}/comments?per_page=${Resources.commentsPageSize}`, page);
336
+ }
337
+ static formatPullCommentsPagePath(number, page) {
338
+ return Resources.formatPagePath(Resources.formatPullCommentsPath(number), page);
339
+ }
340
+ static formatPagePath(path, page) {
341
+ return page === 1 ? path : `${path}&page=${page}`;
342
+ }
276
343
  static formatIssuePath(number) {
277
344
  return `issues/${number}`;
278
345
  }
@@ -283,8 +350,7 @@ export class Resources {
283
350
  return `${Resources.pullsPath}?head=${head}&state=all&per_page=1`;
284
351
  }
285
352
  static formatReviewsPath(number, page) {
286
- const path = `${Resources.pullsPath}/${number}/reviews?per_page=${Resources.reviewsPageSize}`;
287
- return page === 1 ? path : `${path}&page=${page}`;
353
+ return Resources.formatPagePath(`${Resources.pullsPath}/${number}/reviews?per_page=${Resources.reviewsPageSize}`, page);
288
354
  }
289
355
  static formatCheckRunsPath(commit, page) {
290
356
  const path = `commits/${commit}/check-runs?per_page=${Resources.checkRunsPageSize}`;
@@ -8,9 +8,10 @@
8
8
  import { JsonException } from "@noldova/context.json";
9
9
  import { Failure, FailureCode, ShellClients } from "@noldova/desktop.protocol";
10
10
  import { MethodFailureException } from "@noldova/desktop.runtime";
11
- import { BranchQuery, HostingProtocolException, HostReference, PullRequestDraft, SignInState } from "@noldova/git.hosting.protocol";
11
+ import { AuthorQuery, BranchQuery, CommitQuery, HostAvatar, HostingProtocolException, HostReference, PullRequestDraft, RepositoryQuery, SignInState } from "@noldova/git.hosting.protocol";
12
12
  import { GitHubNames } from "@noldova/git.github.protocol";
13
13
  import { GitNames, GitRepositories } from "@noldova/git.protocol";
14
+ import { SignInMethod } from "./models/sign-in-method.js";
14
15
  import { Resources } from "./resources.js";
15
16
  import { GitHubAccess } from "./services/github-access.js";
16
17
  import { GitHubApi } from "./services/github-api.js";
@@ -38,19 +39,37 @@ export class RuntimePart {
38
39
  });
39
40
  const reads = new GitHubReads(api, signIn, avatars);
40
41
  const methods = [
41
- [GitHubNames.readSignInMethod, () => signIn.current],
42
- [GitHubNames.startSignInMethod, () => signIn.startAsync()],
43
- [GitHubNames.cancelSignInMethod, () => signIn.cancel()],
44
- [GitHubNames.signOutMethod, () => signIn.signOutAsync()]
42
+ new SignInMethod(GitHubNames.readSignInMethod, () => signIn.current),
43
+ new SignInMethod(GitHubNames.startSignInMethod, () => signIn.startAsync()),
44
+ new SignInMethod(GitHubNames.cancelSignInMethod, () => signIn.cancel()),
45
+ new SignInMethod(GitHubNames.signOutMethod, () => signIn.signOutAsync())
45
46
  ];
46
- for (const [name, run] of methods)
47
- context.registerMethod(name, { handleAsync: async () => (await run()).toJson() });
47
+ for (const method of methods)
48
+ context.registerMethod(method.name, { handleAsync: async () => (await method.run()).toJson() });
48
49
  context.registerMethod(GitHubNames.readReferenceMethod, {
49
50
  handleAsync: async (request) => (await reads.readShownReferenceAsync(RuntimePart.read(request, HostReference.fromJson), request.signal))?.toJson() ?? null
50
51
  });
51
52
  context.registerMethod(GitHubNames.readBranchPullRequestMethod, {
52
53
  handleAsync: async (request) => (await reads.readBranchPullRequestAsync(RuntimePart.read(request, BranchQuery.fromJson), request.signal)).toJson()
53
54
  });
55
+ context.registerMethod(GitHubNames.readAuthorAvatarMethod, {
56
+ handleAsync: async (request) => new HostAvatar(await reads.readAuthorAvatarAsync(RuntimePart.read(request, AuthorQuery.fromJson), request.signal)).toJson()
57
+ });
58
+ context.registerMethod(GitHubNames.readPullRequestsMethod, {
59
+ handleAsync: async (request) => (await reads.readPullRequestsAsync(RuntimePart.read(request, RepositoryQuery.fromJson), request.signal)).toJson()
60
+ });
61
+ context.registerMethod(GitHubNames.readReviewRequestsMethod, {
62
+ handleAsync: async (request) => (await reads.readReviewRequestsAsync(RuntimePart.read(request, RepositoryQuery.fromJson), request.signal)).toJson()
63
+ });
64
+ context.registerMethod(GitHubNames.readCommitCommentsMethod, {
65
+ handleAsync: async (request) => (await reads.readCommitCommentsAsync(RuntimePart.read(request, CommitQuery.fromJson), request.signal)).toJson()
66
+ });
67
+ context.registerMethod(GitHubNames.readPullRequestMethod, {
68
+ handleAsync: async (request) => (await reads.readPullRequestAsync(RuntimePart.read(request, HostReference.fromJson), request.signal))?.toJson() ?? null
69
+ });
70
+ context.registerMethod(GitHubNames.readPullRequestThreadsMethod, {
71
+ handleAsync: async (request) => (await reads.readPullRequestThreadsAsync(RuntimePart.read(request, HostReference.fromJson), request.signal)).toJson()
72
+ });
54
73
  context.registerMethod(GitHubNames.createPullRequestMethod, {
55
74
  handleAsync: async (request) => (await reads.createPullRequestAsync(RuntimePart.read(RuntimePart.fromWindow(request), PullRequestDraft.fromJson), request.signal)).toJson()
56
75
  });
@@ -0,0 +1,27 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ export class AnswerText {
9
+ static async readAsync(response, limit) {
10
+ const body = response.body;
11
+ if (body === null)
12
+ return "";
13
+ const reader = body.getReader();
14
+ const decoder = new TextDecoder();
15
+ let length = 0;
16
+ let text = "";
17
+ for (let read = await reader.read(); !read.done; read = await reader.read()) {
18
+ length += read.value.length;
19
+ if (length > limit) {
20
+ await reader.cancel();
21
+ return null;
22
+ }
23
+ text += decoder.decode(read.value, { stream: true });
24
+ }
25
+ return text + decoder.decode();
26
+ }
27
+ }
@@ -11,6 +11,7 @@ import { MethodFailureException } from "@noldova/desktop.runtime";
11
11
  import { HostingProtocolException } from "@noldova/git.hosting.protocol";
12
12
  import { CachedAnswer } from "../models/cached-answer.js";
13
13
  import { Resources } from "../resources.js";
14
+ import { AnswerText } from "./answer-text.js";
14
15
  export class GitHubApi {
15
16
  fetcher;
16
17
  answers = new Map();
@@ -32,7 +33,7 @@ export class GitHubApi {
32
33
  const tag = cached?.tag ?? null;
33
34
  if (tag !== null)
34
35
  headers[Resources.ifNoneMatchHeader] = tag;
35
- const response = await this.fetchAsync(url, { headers }, signal);
36
+ const response = await this.followAsync(url, { headers }, signal);
36
37
  if (response.status === Resources.notModifiedStatus && cached !== undefined)
37
38
  return this.reuse(url, cached, now, token);
38
39
  if (response.status === Resources.notFoundStatus) {
@@ -100,7 +101,7 @@ export class GitHubApi {
100
101
  async fetchAsync(url, init, signal) {
101
102
  let response;
102
103
  try {
103
- response = await this.fetcher(url, { ...init, signal: AbortSignal.any([signal, AbortSignal.timeout(Resources.requestTimeout)]) });
104
+ response = await this.fetcher(url, { ...init, redirect: Resources.manualRedirect, signal: AbortSignal.any([signal, AbortSignal.timeout(Resources.requestTimeout)]) });
104
105
  }
105
106
  catch (error) {
106
107
  throw GitHubApi.unreachable(error, signal);
@@ -112,6 +113,24 @@ export class GitHubApi {
112
113
  }
113
114
  return response;
114
115
  }
116
+ async followAsync(first, init, signal) {
117
+ let url = first;
118
+ for (let hop = 0; hop <= Resources.apiRedirects; hop++) {
119
+ const response = await this.fetchAsync(url, init, signal);
120
+ if (!Resources.redirectStatuses.includes(response.status))
121
+ return response;
122
+ await GitHubApi.dropBodyAsync(response);
123
+ const next = GitHubApi.apiUrlOf(response.headers.get(Resources.locationHeader), url);
124
+ if (next === null)
125
+ break;
126
+ url = next.href;
127
+ }
128
+ throw GitHubApi.failure(FailureCode.Unavailable, Resources.movedMessage);
129
+ }
130
+ static apiUrlOf(address, base) {
131
+ const url = address === null ? null : URL.parse(address, base);
132
+ return url !== null && url.origin === Resources.apiUrl && url.username.length === 0 && url.password.length === 0 ? url : null;
133
+ }
115
134
  static headersOf(token) {
116
135
  return {
117
136
  [Resources.acceptHeader]: Resources.gitHubJsonType, [Resources.authorizationHeader]: Resources.formatBearer(token), [Resources.userAgentHeader]: Resources.userAgent,
@@ -123,18 +142,24 @@ export class GitHubApi {
123
142
  await GitHubApi.dropBodyAsync(response);
124
143
  throw GitHubApi.failure(FailureCode.Unavailable, GitHubApi.rateLimitedMessage(response.headers.get(Resources.rateLimitResetHeader)));
125
144
  }
145
+ if (Resources.redirectStatuses.includes(response.status)) {
146
+ await GitHubApi.dropBodyAsync(response);
147
+ throw GitHubApi.failure(FailureCode.Unavailable, Resources.movedMessage);
148
+ }
126
149
  if (!response.ok) {
127
150
  await GitHubApi.dropBodyAsync(response);
128
151
  throw GitHubApi.failure(FailureCode.Unavailable, Resources.formatRefusedRequest(response.status));
129
152
  }
130
153
  let body;
131
154
  try {
132
- body = await response.text();
155
+ body = await AnswerText.readAsync(response, Resources.maximumAnswerBytes);
133
156
  }
134
157
  catch (error) {
135
158
  throw GitHubApi.unreachable(error, signal);
136
159
  }
137
160
  signal.throwIfAborted();
161
+ if (body === null)
162
+ throw GitHubApi.failure(FailureCode.Unavailable, Resources.answerTooLargeMessage);
138
163
  return body;
139
164
  }
140
165
  static async dropBodyAsync(response) {
@@ -8,6 +8,7 @@
8
8
  import { JsonException, JsonReader } from "@noldova/context.json";
9
9
  import { DeviceCode, HostAccount, HostingProtocolException } from "@noldova/git.hosting.protocol";
10
10
  import { GitHubNames } from "@noldova/git.github.protocol";
11
+ import { SignInAnswerTooLargeException } from "../exceptions/sign-in-answer-too-large.exception.js";
11
12
  import { SignInAnswerUnreadableException } from "../exceptions/sign-in-answer-unreadable.exception.js";
12
13
  import { SignInDeniedException } from "../exceptions/sign-in-denied.exception.js";
13
14
  import { SignInErrorException } from "../exceptions/sign-in-error.exception.js";
@@ -19,6 +20,7 @@ import { AccountRead } from "../models/account-read.js";
19
20
  import { DeviceGrant } from "../models/device-grant.js";
20
21
  import { DevicePoll } from "../models/device-poll.js";
21
22
  import { Resources } from "../resources.js";
23
+ import { AnswerText } from "./answer-text.js";
22
24
  export class GitHubDeviceFlow {
23
25
  fetcher;
24
26
  avatars;
@@ -86,7 +88,7 @@ export class GitHubDeviceFlow {
86
88
  async fetchAsync(url, init, signal) {
87
89
  let response;
88
90
  try {
89
- response = await this.fetcher(url, { ...init, signal: AbortSignal.any([signal, AbortSignal.timeout(Resources.requestTimeout)]) });
91
+ response = await this.fetcher(url, { ...init, redirect: Resources.manualRedirect, signal: AbortSignal.any([signal, AbortSignal.timeout(Resources.requestTimeout)]) });
90
92
  }
91
93
  catch (error) {
92
94
  throw GitHubDeviceFlow.unreachable(url, error, signal);
@@ -101,12 +103,14 @@ export class GitHubDeviceFlow {
101
103
  }
102
104
  let text;
103
105
  try {
104
- text = await response.text();
106
+ text = await AnswerText.readAsync(response, Resources.maximumSignInAnswerBytes);
105
107
  }
106
108
  catch (error) {
107
109
  throw GitHubDeviceFlow.unreachable(url, error, signal);
108
110
  }
109
111
  signal.throwIfAborted();
112
+ if (text === null)
113
+ throw new SignInAnswerTooLargeException(url);
110
114
  return GitHubDeviceFlow.read(() => JsonReader.parse(text));
111
115
  }
112
116
  static async dropBodyAsync(response) {
@@ -6,15 +6,20 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  import { FailureCode } from "@noldova/desktop.protocol";
9
- import { BranchPullRequest, CheckState, HostChanges, HostCheck, HostItem, HostPerson, HostReference, ReferenceKind, ReferenceState, ReviewDecision } from "@noldova/git.hosting.protocol";
9
+ import { BranchPullRequest, CheckState, HostBuild, HostChanges, HostCheck, HostComment, HostCommitComments, HostItem, HostPerson, HostPullRequest, HostPullRequestList, HostPullRequestRow, HostPullRequestThreads, HostReference, HostReviewer, HostReviewRequest, HostReviewRequestList, HostThread, ReferenceKind, ReferenceState, ReviewDecision, ThreadStatus } from "@noldova/git.hosting.protocol";
10
10
  import { GitHubNames } from "@noldova/git.github.protocol";
11
11
  import { GitHubRepository } from "../models/github-repository.js";
12
+ import { NewestItems } from "../models/newest-items.js";
13
+ import { ReviewSearchAnswer } from "../models/review-search-answer.js";
14
+ import { ReviewSearch } from "../models/review-search.js";
15
+ import { ReviewVerdict } from "../models/review-verdict.js";
12
16
  import { Resources } from "../resources.js";
13
17
  import { GitHubApi } from "./github-api.js";
14
18
  export class GitHubReads {
15
19
  api;
16
20
  signIn;
17
21
  avatars;
22
+ reviewSearch = null;
18
23
  constructor(api, signIn, avatars) {
19
24
  this.api = api;
20
25
  this.signIn = signIn;
@@ -49,6 +54,109 @@ export class GitHubReads {
49
54
  });
50
55
  return this.signIn.token === token ? answer : none;
51
56
  }
57
+ async readPullRequestsAsync(query, signal) {
58
+ const none = new HostPullRequestList([], false);
59
+ const token = this.signIn.token;
60
+ const repository = GitHubRepository.parse(query.path);
61
+ if (token === null)
62
+ return HostPullRequestList.signedOut();
63
+ if (query.host !== Resources.host || repository === null)
64
+ return none;
65
+ const list = await this.askAsync(token, async () => {
66
+ const pulls = await this.api.getAsync(repository.pathOf(Resources.openPullsPath), token, signal);
67
+ const read = pulls === null ? [] : GitHubApi.read(() => pulls.readObjectArray(Resources.itemsField));
68
+ const rows = await Promise.all(read.slice(0, HostPullRequestList.maximumRows).map(t => this.readRowAsync(repository, t, token, signal)));
69
+ return new HostPullRequestList(rows, read.length > HostPullRequestList.maximumRows);
70
+ });
71
+ return this.signIn.token === token ? list : HostPullRequestList.signedOut();
72
+ }
73
+ async readReviewRequestsAsync(query, signal) {
74
+ const token = this.signIn.token;
75
+ const repository = GitHubRepository.parse(query.path);
76
+ if (token === null)
77
+ return HostReviewRequestList.signedOut();
78
+ if (query.host !== Resources.host || repository === null)
79
+ return new HostReviewRequestList([], false);
80
+ const { rows, isCut } = await this.searchReviewRequestsAsync(token);
81
+ signal.throwIfAborted();
82
+ if (this.signIn.token !== token)
83
+ return HostReviewRequestList.signedOut();
84
+ const key = GitHubReads.repositoryKeyOf(repository.owner, repository.name);
85
+ return new HostReviewRequestList(rows.filter(t => GitHubReads.repositoryKeyOf(t.reference.owner, t.reference.repository) === key)
86
+ .toSorted((a, b) => b.createdAt - a.createdAt), isCut);
87
+ }
88
+ async readCommitCommentsAsync(query, signal) {
89
+ const none = HostCommitComments.none();
90
+ const token = this.signIn.token;
91
+ const repository = GitHubRepository.parse(query.path);
92
+ if (query.host !== Resources.host || token === null || repository === null)
93
+ return none;
94
+ const answer = await this.askAsync(token, async () => {
95
+ const [own, pulls] = await Promise.all([this.api.getAsync(repository.pathOf(Resources.formatCommitCommentsPath(query.commit)), token, signal),
96
+ this.api.getAsync(repository.pathOf(Resources.formatCommitPullsPath(query.commit)), token, signal)]);
97
+ const commitComments = own === null ? [] : GitHubApi.read(() => own.readObjectArray(Resources.itemsField));
98
+ const pull = pulls === null ? undefined : GitHubApi.read(() => pulls.readObjectArray(Resources.itemsField))[0];
99
+ const reviews = pull === undefined ? null
100
+ : await this.api.getAsync(repository.pathOf(Resources.formatPullCommentsPath(GitHubApi.read(() => pull.readInteger(Resources.numberField)))), token, signal);
101
+ const reviewComments = reviews === null ? [] : GitHubApi.read(() => reviews.readObjectArray(Resources.itemsField));
102
+ return GitHubApi.read(() => GitHubReads.commitCommentsOf(query.commit, commitComments, reviewComments));
103
+ });
104
+ return this.signIn.token === token ? answer : none;
105
+ }
106
+ async readAuthorAvatarAsync(query, signal) {
107
+ if (query.host !== Resources.host)
108
+ return null;
109
+ const email = query.email.trim().toLowerCase();
110
+ if (Resources.noReplyPattern.test(email))
111
+ return this.avatars.readAsync(email.replace(Resources.noReplyPattern, (_email, id, login) => Resources.formatAccountAvatar(id ?? null, login)), signal);
112
+ const token = this.signIn.token;
113
+ const repository = GitHubRepository.parse(query.path);
114
+ if (token === null || repository === null)
115
+ return null;
116
+ const address = await this.askAsync(token, async () => {
117
+ const commit = await this.api.getAsync(repository.pathOf(Resources.formatCommitPath(query.commit)), token, signal);
118
+ return commit === null ? null : GitHubApi.read(() => commit.readNullableObject(Resources.authorField)?.readNullableString(Resources.avatarUrlField) ?? null);
119
+ });
120
+ const avatar = await this.avatars.readAsync(address, signal);
121
+ return this.signIn.token === token ? avatar : null;
122
+ }
123
+ async readPullRequestAsync(reference, signal) {
124
+ const token = this.signIn.token;
125
+ const repository = GitHubRepository.parse(Resources.formatRepositoryName(reference.owner, reference.repository));
126
+ if (reference.host !== GitHubNames.moduleId || token === null || repository === null)
127
+ return null;
128
+ const pullRequest = await this.askAsync(token, async () => {
129
+ const pull = await this.api.getAsync(repository.pathOf(Resources.formatPullPath(reference.number)), token, signal);
130
+ if (pull === null)
131
+ return null;
132
+ const commit = GitHubApi.read(() => pull.readObject(Resources.headField).readString(Resources.shaField));
133
+ const [avatar, reviews, runs] = await Promise.all([this.avatars.readAsync(GitHubApi.read(() => GitHubReads.avatarUrlOf(pull)), signal),
134
+ this.readReviewsAsync(repository, reference.number, token, signal), this.readCheckRunsAsync(repository, commit, token, signal)]);
135
+ signal.throwIfAborted();
136
+ return GitHubApi.read(() => GitHubReads.pullRequestPageOf(reference, pull, avatar, reviews, runs));
137
+ });
138
+ return this.signIn.token === token ? pullRequest : null;
139
+ }
140
+ async readPullRequestThreadsAsync(reference, signal) {
141
+ const none = new HostPullRequestThreads([], false);
142
+ const token = this.signIn.token;
143
+ const repository = GitHubRepository.parse(Resources.formatRepositoryName(reference.owner, reference.repository));
144
+ if (reference.host !== GitHubNames.moduleId || token === null || repository === null)
145
+ return none;
146
+ const threads = await this.askAsync(token, async () => {
147
+ const pull = await this.api.getAsync(repository.pathOf(Resources.formatPullPath(reference.number)), token, signal);
148
+ if (pull === null)
149
+ return none;
150
+ const conversationCount = GitHubApi.read(() => pull.readInteger(Resources.commentsField));
151
+ const reviewCount = GitHubApi.read(() => pull.readInteger(Resources.reviewCommentsField));
152
+ const [conversation, reviews] = await Promise.all([
153
+ this.readNewestAsync(page => repository.pathOf(Resources.formatIssueCommentsPath(reference.number, page)), conversationCount, token, signal),
154
+ this.readNewestAsync(page => repository.pathOf(Resources.formatPullCommentsPagePath(reference.number, page)), reviewCount, token, signal)
155
+ ]);
156
+ return GitHubApi.read(() => new HostPullRequestThreads(GitHubReads.threadsOf(conversation.items, reviews.items), conversation.hasMore || reviews.hasMore));
157
+ });
158
+ return this.signIn.token === token ? threads : none;
159
+ }
52
160
  async createPullRequestAsync(draft, signal) {
53
161
  const token = this.signIn.token;
54
162
  if (token === null)
@@ -85,33 +193,84 @@ export class GitHubReads {
85
193
  return this.signIn.token === token ? item : null;
86
194
  }
87
195
  async readChecksAsync(repository, commit, token, signal) {
88
- const checks = [];
196
+ const runs = await this.readCheckRunsAsync(repository, commit, token, signal);
197
+ return GitHubApi.read(() => runs.map(GitHubReads.checkOf));
198
+ }
199
+ async readCheckRunsAsync(repository, commit, token, signal) {
200
+ const runs = [];
89
201
  for (let page = 1;; page++) {
90
- const runs = await this.api.getAsync(repository.pathOf(Resources.formatCheckRunsPath(commit, page)), token, signal);
91
- if (runs === null)
92
- return checks;
93
- const total = GitHubApi.read(() => runs.readInteger(Resources.totalCountField));
94
- const read = GitHubApi.read(() => runs.readObjectArray(Resources.checkRunsField).map(GitHubReads.checkOf));
95
- checks.push(...read);
96
- if (read.length === 0 || checks.length >= total)
97
- return checks;
202
+ const answer = await this.api.getAsync(repository.pathOf(Resources.formatCheckRunsPath(commit, page)), token, signal);
203
+ if (answer === null)
204
+ return runs;
205
+ const total = GitHubApi.read(() => answer.readInteger(Resources.totalCountField));
206
+ const read = GitHubApi.read(() => answer.readObjectArray(Resources.checkRunsField));
207
+ runs.push(...read);
208
+ if (read.length === 0 || runs.length >= total)
209
+ return runs;
98
210
  }
99
211
  }
212
+ readReviewsAsync(repository, number, token, signal) {
213
+ return this.readPagesAsync(page => repository.pathOf(Resources.formatReviewsPath(number, page)), Resources.reviewsPageSize, token, signal);
214
+ }
215
+ async readNewestAsync(pathOf, count, token, signal) {
216
+ const kept = Resources.newestCommentsCount;
217
+ const first = count <= kept ? 1 : Math.floor((count - kept) / Resources.commentsPageSize) + 1;
218
+ const items = [];
219
+ for (let page = first;; page++) {
220
+ const answer = await this.api.getAsync(pathOf(page), token, signal);
221
+ const read = answer === null ? [] : GitHubApi.read(() => answer.readObjectArray(Resources.itemsField));
222
+ items.push(...read);
223
+ if (read.length < Resources.commentsPageSize)
224
+ return new NewestItems(items.slice(-kept), first > 1 || items.length > kept);
225
+ }
226
+ }
227
+ async readPagesAsync(pathOf, pageSize, token, signal) {
228
+ const items = [];
229
+ for (let page = 1;; page++) {
230
+ const answer = await this.api.getAsync(pathOf(page), token, signal);
231
+ const read = answer === null ? [] : GitHubApi.read(() => answer.readObjectArray(Resources.itemsField));
232
+ items.push(...read);
233
+ if (read.length < pageSize)
234
+ return items;
235
+ }
236
+ }
237
+ async readRowAsync(repository, pull, token, signal) {
238
+ const number = GitHubApi.read(() => pull.readInteger(Resources.numberField));
239
+ const head = GitHubApi.read(() => pull.readObject(Resources.headField));
240
+ const commit = GitHubApi.read(() => head.readString(Resources.shaField));
241
+ const [checks, verdicts] = await Promise.all([this.readChecksAsync(repository, commit, token, signal), this.readVerdictsAsync(repository, number, token, signal)]);
242
+ return GitHubApi.read(() => HostPullRequestRow.of(new HostReference(GitHubNames.moduleId, repository.owner, repository.name, number), pull.readString(Resources.titleField), pull.readString(Resources.htmlUrlField), pull.readBoolean(Resources.draftField), verdicts.filter(t => t === Resources.approvedReview).length, checks, head.readString(Resources.refField), pull.readObject(Resources.baseField).readString(Resources.refField)));
243
+ }
100
244
  async readReviewDecisionAsync(repository, number, token, signal) {
245
+ const verdicts = await this.readVerdictsAsync(repository, number, token, signal);
246
+ return verdicts.includes(Resources.changesRequestedReview) ? ReviewDecision.ChangesRequested
247
+ : verdicts.includes(Resources.approvedReview) ? ReviewDecision.Approved : ReviewDecision.Waiting;
248
+ }
249
+ async readVerdictsAsync(repository, number, token, signal) {
101
250
  const latest = new Map();
102
251
  for (let page = 1;; page++) {
103
252
  const reviews = await this.api.getAsync(repository.pathOf(Resources.formatReviewsPath(number, page)), token, signal);
104
253
  const read = reviews === null ? []
105
254
  : GitHubApi.read(() => reviews.readObjectArray(Resources.itemsField).map(GitHubReads.reviewOf));
106
- for (const [login, state] of read)
255
+ for (const { login, state } of read)
107
256
  if (login !== null && (state === Resources.approvedReview || state === Resources.changesRequestedReview || state === Resources.dismissedReview))
108
257
  latest.set(login, state);
109
258
  if (read.length < Resources.reviewsPageSize)
110
259
  break;
111
260
  }
112
- const verdicts = [...latest.values()];
113
- return verdicts.includes(Resources.changesRequestedReview) ? ReviewDecision.ChangesRequested
114
- : verdicts.includes(Resources.approvedReview) ? ReviewDecision.Approved : ReviewDecision.Waiting;
261
+ return [...latest.values()];
262
+ }
263
+ searchReviewRequestsAsync(token) {
264
+ const now = Date.now();
265
+ const held = this.reviewSearch;
266
+ if (held !== null && held.token === token && now - held.startedAt < Resources.reviewRequestsHeldFor)
267
+ return held.answer;
268
+ const answer = this.askAsync(token, async () => {
269
+ const found = await this.api.getAsync(Resources.reviewRequestsPath, token, new AbortController().signal);
270
+ return found === null ? new ReviewSearchAnswer([], false) : GitHubApi.read(() => GitHubReads.reviewSearchOf(found));
271
+ });
272
+ this.reviewSearch = new ReviewSearch(token, now, answer);
273
+ return answer;
115
274
  }
116
275
  async askAsync(token, ask) {
117
276
  try {
@@ -123,6 +282,32 @@ export class GitHubReads {
123
282
  throw error;
124
283
  }
125
284
  }
285
+ static reviewSearchOf(found) {
286
+ const items = found.readObjectArray(Resources.itemsField);
287
+ const rows = [];
288
+ for (const item of items) {
289
+ const address = item.readString(Resources.repositoryUrlField);
290
+ const repository = address.startsWith(Resources.repositoryApiPrefix)
291
+ ? GitHubRepository.parse(address.slice(Resources.repositoryApiPrefix.length)) : null;
292
+ if (repository !== null)
293
+ rows.push(new HostReviewRequest(new HostReference(GitHubNames.moduleId, repository.owner, repository.name, item.readInteger(Resources.numberField)), item.readString(Resources.titleField), item.readString(Resources.htmlUrlField), item.hasField(Resources.draftField) && item.readBoolean(Resources.draftField), Date.parse(item.readString(Resources.createdAtField))));
294
+ }
295
+ return new ReviewSearchAnswer(rows, found.readInteger(Resources.totalCountField) > items.length || found.readBoolean(Resources.incompleteResultsField));
296
+ }
297
+ static commitCommentsOf(commit, commitComments, reviewComments) {
298
+ const onCommit = reviewComments.filter(t => [Resources.commitIdField, Resources.originalCommitIdField]
299
+ .some(field => t.hasField(field) && t.readNullableString(field) === commit));
300
+ const first = commitComments[0] ?? onCommit[0];
301
+ const url = first === undefined ? null : URL.parse(first.readString(Resources.htmlUrlField));
302
+ if (url === null || url.protocol !== Resources.httpsProtocol || url.hostname !== Resources.host || url.username.length > 0 || url.password.length > 0)
303
+ return HostCommitComments.none();
304
+ const count = commitComments.length + onCommit.length;
305
+ return new HostCommitComments(Math.min(count, HostCommitComments.maximumCount), count > HostCommitComments.maximumCount
306
+ || commitComments.length >= Resources.commentsPageSize || reviewComments.length >= Resources.commentsPageSize, url.href);
307
+ }
308
+ static repositoryKeyOf(owner, name) {
309
+ return `${owner}/${name}`.toLowerCase();
310
+ }
126
311
  static avatarUrlOf(item) {
127
312
  return item.readNullableObject(Resources.userField)?.readNullableString(Resources.avatarUrlField) ?? null;
128
313
  }
@@ -153,6 +338,80 @@ export class GitHubReads {
153
338
  const author = user === null ? null : new HostPerson(user.readNonBlankString(Resources.loginField), avatar, GitHubReads.profileOf(user));
154
339
  return new HostItem(reference, kind, state, item.readString(Resources.titleField), item.readString(Resources.htmlUrlField), author, Date.parse(item.readString(Resources.createdAtField)), closedAt, item.readInteger(Resources.commentsField), changes);
155
340
  }
341
+ static pullRequestPageOf(reference, pull, avatar, reviews, runs) {
342
+ const autoMerge = pull.readNullableObject(Resources.autoMergeField);
343
+ const mergeableState = pull.readString(Resources.mergeableStateField);
344
+ return new HostPullRequest(GitHubReads.pullRequestOf(reference, pull, avatar), GitHubReads.reviewersOf(pull, reviews), [], runs.map(GitHubReads.buildOf), autoMerge !== null, pull.readNullableString(Resources.bodyField) ?? "", pull.readInteger(Resources.commitsField), [], autoMerge === null ? null : autoMerge.readString(Resources.mergeMethodField), mergeableState === Resources.unknownMergeableState ? null : mergeableState === Resources.dirtyMergeableState);
345
+ }
346
+ static reviewersOf(pull, reviews) {
347
+ const author = pull.readNullableObject(Resources.userField)?.readNonBlankString(Resources.loginField) ?? null;
348
+ const people = new Map();
349
+ const verdicts = new Map();
350
+ for (const review of reviews) {
351
+ const user = review.readNullableObject(Resources.userField);
352
+ const state = review.readString(Resources.stateField);
353
+ if (user === null || state === Resources.pendingReview)
354
+ continue;
355
+ const person = GitHubReads.personOf(user);
356
+ if (person.login === author)
357
+ continue;
358
+ people.set(person.login, person);
359
+ if (state !== Resources.commentedReview)
360
+ verdicts.set(person.login, state);
361
+ }
362
+ const asked = pull.readObjectArray(Resources.requestedReviewersField).map(GitHubReads.personOf);
363
+ const askedLogins = new Set(asked.map(t => t.login));
364
+ const reviewed = [...people.values()].filter(t => !askedLogins.has(t.login)).map(t => {
365
+ const state = verdicts.get(t.login);
366
+ return state === Resources.approvedReview ? new HostReviewer(t, 1, Resources.approvedLabel, false)
367
+ : state === Resources.changesRequestedReview ? new HostReviewer(t, -1, Resources.changesRequestedLabel, false)
368
+ : new HostReviewer(t, 0, Resources.commentedLabel, false);
369
+ });
370
+ const teams = pull.readObjectArray(Resources.requestedTeamsField).map(GitHubReads.teamOf);
371
+ return [...reviewed, ...[...asked, ...teams].map(t => new HostReviewer(t, 0, Resources.reviewRequestedLabel, false))];
372
+ }
373
+ static buildOf(run) {
374
+ const check = GitHubReads.checkOf(run);
375
+ const startedAt = run.readNullableString(Resources.startedAtField);
376
+ const completedAt = run.readNullableString(Resources.completedAtField);
377
+ const isFinished = check.state !== CheckState.Queued && check.state !== CheckState.Running;
378
+ return new HostBuild(check.name, check.state, check.url, startedAt === null ? null : Date.parse(startedAt), completedAt === null || !isFinished ? null : Date.parse(completedAt));
379
+ }
380
+ static threadsOf(conversation, reviews) {
381
+ const onFiles = new Map();
382
+ for (const comment of reviews.filter(GitHubReads.hasText)) {
383
+ const replyTo = comment.hasField(Resources.inReplyToIdField) ? comment.readNullableInteger(Resources.inReplyToIdField) : null;
384
+ const root = replyTo ?? comment.readInteger(Resources.idField);
385
+ const held = onFiles.get(root);
386
+ onFiles.set(root, held === undefined
387
+ ? new HostThread(GitHubReads.fileThreadIdOf(root), ThreadStatus.None, comment.readNonBlankString(Resources.pathField), comment.readNullableInteger(Resources.lineField) ?? comment.readNullableInteger(Resources.originalLineField), [GitHubReads.commentOf(comment, null)])
388
+ : new HostThread(held.id, held.state, held.path, held.line, [...held.comments, GitHubReads.commentOf(comment, held.comments.some(t => t.id === replyTo) ? replyTo : null)]));
389
+ }
390
+ const threads = [...conversation.filter(GitHubReads.hasText).map(t => new HostThread(GitHubReads.conversationThreadIdOf(t.readInteger(Resources.idField)), ThreadStatus.None, null, null, [GitHubReads.commentOf(t, null)])), ...onFiles.values()];
391
+ return threads.toSorted((a, b) => GitHubReads.startOf(a) - GitHubReads.startOf(b));
392
+ }
393
+ static conversationThreadIdOf(commentId) {
394
+ return commentId * 2;
395
+ }
396
+ static fileThreadIdOf(rootId) {
397
+ return rootId * 2 + 1;
398
+ }
399
+ static hasText(comment) {
400
+ return (comment.readNullableString(Resources.bodyField) ?? "").trim().length > 0;
401
+ }
402
+ static startOf(thread) {
403
+ return Math.min(...thread.comments.map(t => t.publishedAt));
404
+ }
405
+ static commentOf(comment, parent) {
406
+ const user = comment.readNullableObject(Resources.userField);
407
+ return new HostComment(comment.readInteger(Resources.idField), parent, user === null ? new HostPerson(Resources.ghostLogin, null, null) : GitHubReads.personOf(user), Date.parse(comment.readString(Resources.createdAtField)), comment.readString(Resources.bodyField));
408
+ }
409
+ static teamOf(team) {
410
+ return new HostPerson(team.readNonBlankString(Resources.nameField), null, GitHubReads.profileOf(team));
411
+ }
412
+ static personOf(user) {
413
+ return new HostPerson(user.readNonBlankString(Resources.loginField), null, GitHubReads.profileOf(user));
414
+ }
156
415
  static checkOf(run) {
157
416
  const status = run.readString(Resources.statusField);
158
417
  const state = status !== Resources.completedCheckStatus ? (status === Resources.runningCheckStatus ? CheckState.Running : CheckState.Queued)
@@ -162,7 +421,7 @@ export class GitHubReads {
162
421
  static reviewOf(review) {
163
422
  const login = review.readNullableObject(Resources.userField)?.readString(Resources.loginField) ?? null;
164
423
  const isReviewer = Resources.reviewerAssociations.includes(review.readString(Resources.authorAssociationField));
165
- return [isReviewer ? login : null, review.readString(Resources.stateField)];
424
+ return new ReviewVerdict(isReviewer ? login : null, review.readString(Resources.stateField));
166
425
  }
167
426
  static conclusionOf(conclusion) {
168
427
  return Resources.succeededConclusions.includes(conclusion) ? CheckState.Succeeded