walkdiff 0.13.0 → 0.14.0

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/walkdiff.mjs CHANGED
@@ -10,7 +10,7 @@ import { Language, Parser } from "web-tree-sitter";
10
10
  import { LineCounter, isMap, isPair, isScalar, isSeq, parse, parseAllDocuments, parseDocument } from "yaml";
11
11
  import { Kind, parse as parse$1, print } from "graphql";
12
12
  import { homedir, tmpdir } from "node:os";
13
- import { existsSync, readFileSync } from "node:fs";
13
+ import { existsSync, readFileSync, rmSync } from "node:fs";
14
14
  import { parse as parse$2 } from "smol-toml";
15
15
  import Anthropic from "@anthropic-ai/sdk";
16
16
  import { betaZodOutputFormat } from "@anthropic-ai/sdk/helpers/beta/zod";
@@ -1431,6 +1431,19 @@ const LogLevel = {
1431
1431
  var HistoryUnavailableError = class extends Error {
1432
1432
  name = "HistoryUnavailableError";
1433
1433
  };
1434
+ z.object({
1435
+ url: z.url(),
1436
+ host: z.enum(GitHostKind),
1437
+ /** `owner/repo#12` or `group/project!12`. */
1438
+ displayName: z.string(),
1439
+ /** `owner/repo` or `group/subgroup/project`. */
1440
+ repository: z.string(),
1441
+ number: z.number().int().positive(),
1442
+ title: z.string(),
1443
+ author: z.string(),
1444
+ draft: z.boolean(),
1445
+ updatedAt: z.iso.datetime({ offset: true })
1446
+ });
1434
1447
  // packages/engine/src/blobs.ts
1435
1448
  const NEWLINE = 10;
1436
1449
  /**
@@ -14501,6 +14514,114 @@ function displayName(ref) {
14501
14514
  const separator = ref.host === GitHostKind.GitHub ? "#" : "!";
14502
14515
  return `${repositoryPath(ref)}${separator}${ref.number}`;
14503
14516
  }
14517
+ // packages/providers/src/trustedHosts.ts
14518
+ const TRUSTED_GITHUB_HOSTS_VARIABLE = "WALKDIFF_TRUSTED_GITHUB_HOSTS";
14519
+ const TRUSTED_GITLAB_HOSTS_VARIABLE = "WALKDIFF_TRUSTED_GITLAB_HOSTS";
14520
+ const GITHUB_DOT_COM_ORIGIN$1 = "https://github.com";
14521
+ const GITLAB_DOT_COM_ORIGIN = "https://gitlab.com";
14522
+ /**
14523
+ * Whether this link's host may receive the token for its kind of host. Links are pasted by
14524
+ * hand and their kind is read from the path, so neither the host name nor the kind can be
14525
+ * taken on trust: `https://evil.example/a/b/pull/1` would otherwise receive a GitHub token,
14526
+ * and `https://gitlab.com/a/b/pull/1` would receive a GitHub token at GitLab. Comparing
14527
+ * whole origins also keeps a token off plain http and off look-alikes such as
14528
+ * `github.com.evil.example`.
14529
+ */
14530
+ function isTrustedHost(ref, trusted) {
14531
+ return ref.host === GitHostKind.GitHub ? ref.webOrigin === GITHUB_DOT_COM_ORIGIN$1 || trusted.github.includes(ref.webOrigin) : ref.webOrigin === GITLAB_DOT_COM_ORIGIN || trusted.gitlab.includes(ref.webOrigin);
14532
+ }
14533
+ /**
14534
+ * The kind of host at a trusted origin, or undefined for any other origin. A git remote's URL
14535
+ * doesn't show the kind the way a PR link's path does, so only the hosts the user trusts can be
14536
+ * told apart, and those are the only ones that get a token anyway.
14537
+ */
14538
+ function trustedHostKind(origin, trusted) {
14539
+ if (origin === GITHUB_DOT_COM_ORIGIN$1 || trusted.github.includes(origin)) return GitHostKind.GitHub;
14540
+ if (origin === GITLAB_DOT_COM_ORIGIN || trusted.gitlab.includes(origin)) return GitHostKind.GitLab;
14541
+ }
14542
+ // packages/providers/src/remoteUrl.ts
14543
+ /**
14544
+ * A git remote Walkdiff can't use. The message never repeats the remote itself, which can carry a
14545
+ * token, as in `https://user:token@github.com/acme/app.git`.
14546
+ */
14547
+ var InvalidRemoteUrlError = class extends Error {
14548
+ name = "InvalidRemoteUrlError";
14549
+ };
14550
+ const REMOTE_PROTOCOLS = /* @__PURE__ */ new Set([
14551
+ "https:",
14552
+ "http:",
14553
+ "ssh:",
14554
+ "git+ssh:"
14555
+ ]);
14556
+ const SSH_PROTOCOLS = /* @__PURE__ */ new Set(["ssh:", "git+ssh:"]);
14557
+ const SCP_LIKE_REMOTE = /^(?:[^@/]+@)?(?<host>[^:/]+):(?<path>[^/].*)$/;
14558
+ const GIT_SUFFIX = /\.git$/;
14559
+ const GITHUB_PATH_SEGMENTS = 2;
14560
+ const MIN_GITLAB_PATH_SEGMENTS = 2;
14561
+ /**
14562
+ * The repository a git remote points at, such as `git@github.com:acme/app.git` or
14563
+ * `https://gitlab.example.com/group/sub/app.git`. A remote over SSH is taken to have its web pages
14564
+ * over HTTPS on the same host name.
14565
+ *
14566
+ * # Errors
14567
+ *
14568
+ * Throws an `InvalidRemoteUrlError` when the remote can't be read, or its host isn't github.com,
14569
+ * gitlab.com or a host the user trusts, since only those can be told apart.
14570
+ */
14571
+ function parseRemoteUrl(remote, trusted) {
14572
+ const { webOrigin, segments } = remoteLocation(remote.trim());
14573
+ switch (trustedHostKind(webOrigin, trusted)) {
14574
+ case GitHostKind.GitHub: {
14575
+ const [owner, repo] = segments;
14576
+ if (segments.length !== GITHUB_PATH_SEGMENTS || owner === void 0 || repo === void 0) throw new InvalidRemoteUrlError(`A GitHub remote should end in owner/repo, at ${webOrigin}.`);
14577
+ return {
14578
+ host: GitHostKind.GitHub,
14579
+ webOrigin,
14580
+ owner,
14581
+ repo
14582
+ };
14583
+ }
14584
+ case GitHostKind.GitLab:
14585
+ if (segments.length < MIN_GITLAB_PATH_SEGMENTS) throw new InvalidRemoteUrlError(`A GitLab remote should end in group/project, at ${webOrigin}.`);
14586
+ return {
14587
+ host: GitHostKind.GitLab,
14588
+ webOrigin,
14589
+ projectPath: segments.join("/")
14590
+ };
14591
+ case void 0: throw new InvalidRemoteUrlError(`Walkdiff can't tell whether ${webOrigin} is GitHub or GitLab. If you trust it, add it to ${TRUSTED_GITHUB_HOSTS_VARIABLE} or ${TRUSTED_GITLAB_HOSTS_VARIABLE}.`);
14592
+ }
14593
+ }
14594
+ function remoteLocation(remote) {
14595
+ const url = URL.canParse(remote) ? new URL(remote) : void 0;
14596
+ if (url !== void 0 && REMOTE_PROTOCOLS.has(url.protocol)) return {
14597
+ webOrigin: SSH_PROTOCOLS.has(url.protocol) ? `https://${url.hostname}` : url.origin,
14598
+ segments: pathSegments(decodeURIComponent(url.pathname))
14599
+ };
14600
+ const scpLike = SCP_LIKE_REMOTE.exec(remote)?.groups;
14601
+ if (scpLike?.host !== void 0 && scpLike.path !== void 0) return {
14602
+ webOrigin: `https://${scpLike.host.toLowerCase()}`,
14603
+ segments: pathSegments(scpLike.path)
14604
+ };
14605
+ throw new InvalidRemoteUrlError("Walkdiff reads remotes over HTTPS or SSH, such as git@github.com:owner/repo.git.");
14606
+ }
14607
+ function pathSegments(path) {
14608
+ return path.replace(GIT_SUFFIX, "").split("/").filter((segment) => segment !== "");
14609
+ }
14610
+ // packages/providers/src/pullRequestDirectory.ts
14611
+ var NotSignedInError = class extends Error {
14612
+ name = "NotSignedInError";
14613
+ };
14614
+ /** A listing named and numbered from its own link, which every host gives. */
14615
+ function listingFrom(details) {
14616
+ const ref = parsePullRequestUrl(details.url);
14617
+ return {
14618
+ ...details,
14619
+ host: ref.host,
14620
+ displayName: displayName(ref),
14621
+ repository: repositoryPath(ref),
14622
+ number: ref.number
14623
+ };
14624
+ }
14504
14625
  // packages/providers/src/gitHost.ts
14505
14626
  const COVERAGE_ARCHIVE_NAME = /cov|lcov|cobertura/i;
14506
14627
  const MAX_COVERAGE_ARCHIVE_BYTES = 209715200;
@@ -14850,13 +14971,13 @@ function inStackOrder(members) {
14850
14971
  return ordered;
14851
14972
  }
14852
14973
  // packages/providers/src/github.ts
14853
- const GITHUB_DOT_COM_ORIGIN$1 = "https://github.com";
14974
+ const GITHUB_DOT_COM_ORIGIN = "https://github.com";
14854
14975
  const GITHUB_DOT_COM_API = "https://api.github.com";
14855
14976
  const GITHUB_API_VERSION = "2022-11-28";
14856
14977
  const GITHUB_GIT_USERNAME = "x-access-token";
14857
14978
  const USER_AGENT = "walkdiff-review";
14858
- const AUTH_HINT$1 = "Set GITHUB_TOKEN (or GH_TOKEN) to a token that can read this repository; posting comments also needs pull-requests: write.";
14859
- const DELETED_USER_LOGIN = "ghost";
14979
+ const AUTH_HINT$3 = "Set GITHUB_TOKEN (or GH_TOKEN) to a token that can read this repository; posting comments also needs pull-requests: write.";
14980
+ const DELETED_USER_LOGIN$1 = "ghost";
14860
14981
  const branchTipSchema = z.object({
14861
14982
  ref: z.string(),
14862
14983
  sha: commitShaSchema
@@ -14905,8 +15026,8 @@ pull_requests: z.array(z.object({
14905
15026
  state: z.string(),
14906
15027
  merged_at: z.string().nullable()
14907
15028
  })) });
14908
- const OPEN_STATE$1 = "open";
14909
- const PULLS_PER_PAGE = 100;
15029
+ const OPEN_STATE$2 = "open";
15030
+ const PULLS_PER_PAGE$1 = 100;
14910
15031
  const issueCommentSchema = z.object({
14911
15032
  id: z.number().int(),
14912
15033
  body: z.string().nullable()
@@ -14978,7 +15099,7 @@ var GitHubHost = class {
14978
15099
  #ref;
14979
15100
  #token;
14980
15101
  #authHint;
14981
- constructor(ref, token, authHint = AUTH_HINT$1) {
15102
+ constructor(ref, token, authHint = AUTH_HINT$3) {
14982
15103
  this.#ref = ref;
14983
15104
  this.#token = token;
14984
15105
  this.#authHint = authHint;
@@ -14996,7 +15117,7 @@ var GitHubHost = class {
14996
15117
  number: pull.number,
14997
15118
  title: pull.title,
14998
15119
  description: pull.body ?? "",
14999
- author: pull.user?.login ?? DELETED_USER_LOGIN,
15120
+ author: pull.user?.login ?? DELETED_USER_LOGIN$1,
15000
15121
  baseRef: pull.base.ref,
15001
15122
  headRef: pull.head.ref,
15002
15123
  baseSha: pull.base.sha,
@@ -15033,7 +15154,7 @@ var GitHubHost = class {
15033
15154
  }, conversationResponseSchema)).repository.pullRequest;
15034
15155
  return {
15035
15156
  reviewers: latestReviews.nodes.map((review) => ({
15036
- name: review.author?.login ?? DELETED_USER_LOGIN,
15157
+ name: review.author?.login ?? DELETED_USER_LOGIN$1,
15037
15158
  state: REVIEWER_STATES$1.get(review.state) ?? ReviewerState.Other
15038
15159
  })),
15039
15160
  threads: reviewThreads.nodes.map((thread) => ({
@@ -15044,7 +15165,7 @@ var GitHubHost = class {
15044
15165
  isResolved: thread.isResolved,
15045
15166
  isOutdated: thread.isOutdated,
15046
15167
  comments: thread.comments.nodes.map((comment) => ({
15047
- author: comment.author?.login ?? DELETED_USER_LOGIN,
15168
+ author: comment.author?.login ?? DELETED_USER_LOGIN$1,
15048
15169
  body: comment.bodyText,
15049
15170
  createdAt: comment.createdAt,
15050
15171
  url: comment.url
@@ -15109,12 +15230,12 @@ var GitHubHost = class {
15109
15230
  }, this.#openPullRequests(repoApi));
15110
15231
  }
15111
15232
  async #hostStack(repoApi, stackNumber) {
15112
- const open = (await this.#get(`${repoApi}/stacks/${stackNumber}`, stackSchema)).pull_requests.filter((pull) => pull.state === OPEN_STATE$1 && pull.merged_at === null).map((pull) => pull.number);
15233
+ const open = (await this.#get(`${repoApi}/stacks/${stackNumber}`, stackSchema)).pull_requests.filter((pull) => pull.state === OPEN_STATE$2 && pull.merged_at === null).map((pull) => pull.number);
15113
15234
  const kept = keptAround(open, open.indexOf(this.#ref.number));
15114
15235
  return stackFromHost((await Promise.all(kept.map((number) => this.#get(`${repoApi}/pulls/${number}`, listedPullSchema)))).map((pull) => stackCandidate$1(pull).member), this.#ref.number);
15115
15236
  }
15116
15237
  #openPullRequests(repoApi) {
15117
- const list = async (filter) => (await this.#get(`${repoApi}/pulls?state=${OPEN_STATE$1}&per_page=${PULLS_PER_PAGE}&${filter}`, z.array(listedPullSchema))).map(stackCandidate$1);
15238
+ const list = async (filter) => (await this.#get(`${repoApi}/pulls?state=${OPEN_STATE$2}&per_page=${PULLS_PER_PAGE$1}&${filter}`, z.array(listedPullSchema))).map(stackCandidate$1);
15118
15239
  return {
15119
15240
  withHead: (branch) => list(`head=${encodeURIComponent(`${this.#ref.owner}:${branch}`)}`),
15120
15241
  withBase: (branch) => list(`base=${encodeURIComponent(branch)}`)
@@ -15141,7 +15262,7 @@ var GitHubHost = class {
15141
15262
  }
15142
15263
  #repoApi() {
15143
15264
  const { owner, repo, webOrigin } = this.#ref;
15144
- return `${apiBase(webOrigin)}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
15265
+ return `${githubApiBase(webOrigin)}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
15145
15266
  }
15146
15267
  async #mergeBase(repoApi, base, head) {
15147
15268
  return (await this.#get(`${repoApi}/compare/${base}...${head}`, compareSchema)).merge_base_commit.sha;
@@ -15164,13 +15285,7 @@ var GitHubHost = class {
15164
15285
  });
15165
15286
  }
15166
15287
  #headers() {
15167
- const headers = {
15168
- Accept: "application/vnd.github+json",
15169
- "X-GitHub-Api-Version": GITHUB_API_VERSION,
15170
- "User-Agent": USER_AGENT
15171
- };
15172
- if (this.#token !== void 0) headers.Authorization = `Bearer ${this.#token}`;
15173
- return headers;
15288
+ return githubHeaders(this.#token);
15174
15289
  }
15175
15290
  #gitAuth() {
15176
15291
  return this.#token === void 0 ? void 0 : {
@@ -15193,14 +15308,14 @@ function withUnplacedComments$1(review) {
15193
15308
  /** GitHub calls a merged PR closed, telling them apart only by `merged_at`. */
15194
15309
  function githubState(pull) {
15195
15310
  if (pull.merged_at !== null) return PullRequestState.Merged;
15196
- return pull.state === OPEN_STATE$1 ? PullRequestState.Open : PullRequestState.Closed;
15311
+ return pull.state === OPEN_STATE$2 ? PullRequestState.Open : PullRequestState.Closed;
15197
15312
  }
15198
15313
  function stackCandidate$1(pull) {
15199
15314
  return {
15200
15315
  member: {
15201
15316
  number: pull.number,
15202
15317
  title: pull.title,
15203
- author: pull.user?.login ?? DELETED_USER_LOGIN,
15318
+ author: pull.user?.login ?? DELETED_USER_LOGIN$1,
15204
15319
  headRef: pull.head.ref,
15205
15320
  baseRef: pull.base.ref
15206
15321
  },
@@ -15208,10 +15323,18 @@ function stackCandidate$1(pull) {
15208
15323
  };
15209
15324
  }
15210
15325
  function graphqlUrl(webOrigin) {
15211
- return webOrigin === GITHUB_DOT_COM_ORIGIN$1 ? `${GITHUB_DOT_COM_API}/graphql` : `${webOrigin}/api/graphql`;
15326
+ return webOrigin === GITHUB_DOT_COM_ORIGIN ? `${GITHUB_DOT_COM_API}/graphql` : `${webOrigin}/api/graphql`;
15212
15327
  }
15213
- function apiBase(webOrigin) {
15214
- return webOrigin === GITHUB_DOT_COM_ORIGIN$1 ? GITHUB_DOT_COM_API : `${webOrigin}/api/v3`;
15328
+ function githubHeaders(token) {
15329
+ return {
15330
+ Accept: "application/vnd.github+json",
15331
+ "X-GitHub-Api-Version": GITHUB_API_VERSION,
15332
+ "User-Agent": USER_AGENT,
15333
+ ...token === void 0 ? {} : { Authorization: `Bearer ${token}` }
15334
+ };
15335
+ }
15336
+ function githubApiBase(webOrigin) {
15337
+ return webOrigin === GITHUB_DOT_COM_ORIGIN ? GITHUB_DOT_COM_API : `${webOrigin}/api/v3`;
15215
15338
  }
15216
15339
  function githubReviewComment(comment) {
15217
15340
  if (comment.range === null) return {
@@ -15236,10 +15359,60 @@ function githubReviewComment(comment) {
15236
15359
  body: comment.body
15237
15360
  };
15238
15361
  }
15362
+ // packages/providers/src/githubDirectory.ts
15363
+ const AUTH_HINT$2 = "Set GITHUB_TOKEN (or GH_TOKEN) to a token that can read this repository, or sign in with the GitHub CLI.";
15364
+ const DELETED_USER_LOGIN = "ghost";
15365
+ const PULLS_PER_PAGE = 100;
15366
+ const AWAITING_MY_REVIEW_QUERY = "is:open is:pr review-requested:@me archived:false";
15367
+ /** A PR as both the pulls list and search results give it. */
15368
+ const listedSchema$1 = z.object({
15369
+ html_url: z.url(),
15370
+ title: z.string(),
15371
+ user: z.object({ login: z.string() }).nullable(),
15372
+ draft: z.boolean().default(false),
15373
+ updated_at: z.string()
15374
+ });
15375
+ const searchSchema = z.object({ items: z.array(listedSchema$1) });
15376
+ var GitHubDirectory = class {
15377
+ #repository;
15378
+ #token;
15379
+ constructor(repository, token) {
15380
+ this.#repository = repository;
15381
+ this.#token = token;
15382
+ }
15383
+ async openFromBranch(branch) {
15384
+ const { owner, repo, webOrigin } = this.#repository;
15385
+ const head = encodeURIComponent(`${owner}:${branch}`);
15386
+ const url = `${githubApiBase(webOrigin)}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls?state=open&head=${head}&per_page=${PULLS_PER_PAGE}`;
15387
+ return (await this.#get(url, z.array(listedSchema$1))).map(toListing$1);
15388
+ }
15389
+ async awaitingMyReview() {
15390
+ if (this.#token === void 0) throw new NotSignedInError(`Walkdiff needs your GitHub login to find PRs waiting for your review. ${AUTH_HINT$2}`);
15391
+ const url = `${githubApiBase(this.#repository.webOrigin)}/search/issues?q=${encodeURIComponent(AWAITING_MY_REVIEW_QUERY)}&sort=updated&order=desc&per_page=50`;
15392
+ return (await this.#get(url, searchSchema)).items.map(toListing$1);
15393
+ }
15394
+ #get(url, schema) {
15395
+ return getJson({
15396
+ url,
15397
+ headers: githubHeaders(this.#token),
15398
+ schema,
15399
+ authHint: AUTH_HINT$2
15400
+ });
15401
+ }
15402
+ };
15403
+ function toListing$1(pull) {
15404
+ return listingFrom({
15405
+ url: pull.html_url,
15406
+ title: pull.title,
15407
+ author: pull.user?.login ?? DELETED_USER_LOGIN,
15408
+ draft: pull.draft,
15409
+ updatedAt: pull.updated_at
15410
+ });
15411
+ }
15239
15412
  // packages/providers/src/gitlab.ts
15240
15413
  const GITLAB_GIT_USERNAME = "oauth2";
15241
15414
  const APPROVAL_REFUSED_STATUS = 401;
15242
- const AUTH_HINT = "Set GITLAB_TOKEN to a token with the read_api and read_repository scopes; posting comments needs the api scope.";
15415
+ const AUTH_HINT$1 = "Set GITLAB_TOKEN to a token with the read_api and read_repository scopes; posting comments needs the api scope.";
15243
15416
  const mergeRequestSchema = z.object({
15244
15417
  web_url: z.url(),
15245
15418
  iid: z.number().int().positive(),
@@ -15273,8 +15446,8 @@ const listedMergeRequestSchema = z.object({
15273
15446
  target_project_id: z.number().int()
15274
15447
  });
15275
15448
  const projectSchema = z.object({ default_branch: z.string() });
15276
- const OPEN_STATE = "opened";
15277
- const MERGE_REQUESTS_PER_PAGE = 100;
15449
+ const OPEN_STATE$1 = "opened";
15450
+ const MERGE_REQUESTS_PER_PAGE$1 = 100;
15278
15451
  const STACK_MEMBER_FIELDS = "iid title author { username } sourceBranch targetBranch";
15279
15452
  const STACK_QUERY = `query($project: ID!, $iid: String!) {
15280
15453
  project(fullPath: $project) { mergeRequest(iid: $iid) { ${STACK_MEMBER_FIELDS} stack { ${STACK_MEMBER_FIELDS} } } }
@@ -15302,7 +15475,7 @@ const noteSchema = z.object({
15302
15475
  body: z.string().nullable()
15303
15476
  });
15304
15477
  const DISCUSSIONS_PER_PAGE = 100;
15305
- const userSchema = z.object({ username: z.string() });
15478
+ const userSchema$1 = z.object({ username: z.string() });
15306
15479
  const discussionSchema = z.object({
15307
15480
  id: z.string(),
15308
15481
  individual_note: z.boolean(),
@@ -15311,7 +15484,7 @@ const discussionSchema = z.object({
15311
15484
  body: z.string(),
15312
15485
  created_at: z.string(),
15313
15486
  system: z.boolean(),
15314
- author: userSchema,
15487
+ author: userSchema$1,
15315
15488
  resolvable: z.boolean().optional(),
15316
15489
  resolved: z.boolean().optional(),
15317
15490
  position: z.object({
@@ -15322,11 +15495,11 @@ const discussionSchema = z.object({
15322
15495
  }).nullable().optional()
15323
15496
  }))
15324
15497
  });
15325
- const approvalsSchema = z.object({ approved_by: z.array(z.object({ user: userSchema })) });
15498
+ const approvalsSchema = z.object({ approved_by: z.array(z.object({ user: userSchema$1 })) });
15326
15499
  /** Only `user_has_approved`: on GitLab Free, `user_can_approve` reads false for merge requests the user can approve. */
15327
15500
  const ownApprovalSchema = z.object({ user_has_approved: z.boolean() });
15328
15501
  const reviewersSchema = z.array(z.object({
15329
- user: userSchema,
15502
+ user: userSchema$1,
15330
15503
  state: z.string().nullable().optional()
15331
15504
  }));
15332
15505
  const REVIEWER_STATES = /* @__PURE__ */ new Map([
@@ -15364,7 +15537,7 @@ var GitLabHost = class {
15364
15537
  #ref;
15365
15538
  #token;
15366
15539
  #authHint;
15367
- constructor(ref, token, authHint = AUTH_HINT) {
15540
+ constructor(ref, token, authHint = AUTH_HINT$1) {
15368
15541
  this.#ref = ref;
15369
15542
  this.#token = token;
15370
15543
  this.#authHint = authHint;
@@ -15566,7 +15739,7 @@ var GitLabHost = class {
15566
15739
  return gitlabFileHistory((url, schema) => this.#get(url, schema), this.#projectApi(), request);
15567
15740
  }
15568
15741
  #openMergeRequests(projectApi) {
15569
- const list = async (filter) => (await this.#get(`${projectApi}/merge_requests?state=${OPEN_STATE}&per_page=${MERGE_REQUESTS_PER_PAGE}&${filter}`, z.array(listedMergeRequestSchema))).map(stackCandidate);
15742
+ const list = async (filter) => (await this.#get(`${projectApi}/merge_requests?state=${OPEN_STATE$1}&per_page=${MERGE_REQUESTS_PER_PAGE$1}&${filter}`, z.array(listedMergeRequestSchema))).map(stackCandidate);
15570
15743
  return {
15571
15744
  withHead: (branch) => list(`source_branch=${encodeURIComponent(branch)}`),
15572
15745
  withBase: (branch) => list(`target_branch=${encodeURIComponent(branch)}`)
@@ -15602,8 +15775,7 @@ var GitLabHost = class {
15602
15775
  }]);
15603
15776
  }
15604
15777
  #projectApi() {
15605
- const { webOrigin, projectPath } = this.#ref;
15606
- return `${webOrigin}/api/v4/projects/${encodeURIComponent(projectPath)}`;
15778
+ return gitlabProjectApi(this.#ref);
15607
15779
  }
15608
15780
  #mergeRequestApi() {
15609
15781
  return `${this.#projectApi()}/merge_requests/${this.#ref.number}`;
@@ -15618,7 +15790,7 @@ var GitLabHost = class {
15618
15790
  });
15619
15791
  }
15620
15792
  #headers() {
15621
- return this.#token === void 0 ? {} : { "PRIVATE-TOKEN": this.#token };
15793
+ return gitlabHeaders(this.#token);
15622
15794
  }
15623
15795
  #gitAuth() {
15624
15796
  return this.#token === void 0 ? void 0 : {
@@ -15628,6 +15800,15 @@ var GitLabHost = class {
15628
15800
  }
15629
15801
  };
15630
15802
  /** GitLab's "locked" is an open merge request in the middle of being merged. */
15803
+ function gitlabHeaders(token) {
15804
+ return token === void 0 ? {} : { "PRIVATE-TOKEN": token };
15805
+ }
15806
+ function gitlabApiBase(webOrigin) {
15807
+ return `${webOrigin}/api/v4`;
15808
+ }
15809
+ function gitlabProjectApi({ webOrigin, projectPath }) {
15810
+ return `${gitlabApiBase(webOrigin)}/projects/${encodeURIComponent(projectPath)}`;
15811
+ }
15631
15812
  function gitlabState(state) {
15632
15813
  if (state === MERGED_STATE) return PullRequestState.Merged;
15633
15814
  return state === CLOSED_STATE ? PullRequestState.Closed : PullRequestState.Open;
@@ -15670,21 +15851,68 @@ function gitlabNote(comment) {
15670
15851
  const last = number(range.end);
15671
15852
  return first === last ? comment.body : `Lines ${first}–${last}${range.side === LineSide.Old ? " (before)" : ""}:\n\n${comment.body}`;
15672
15853
  }
15673
- // packages/providers/src/trustedHosts.ts
15674
- const TRUSTED_GITHUB_HOSTS_VARIABLE = "WALKDIFF_TRUSTED_GITHUB_HOSTS";
15675
- const TRUSTED_GITLAB_HOSTS_VARIABLE = "WALKDIFF_TRUSTED_GITLAB_HOSTS";
15676
- const GITHUB_DOT_COM_ORIGIN = "https://github.com";
15677
- const GITLAB_DOT_COM_ORIGIN = "https://gitlab.com";
15678
- /**
15679
- * Whether this link's host may receive the token for its kind of host. Links are pasted by
15680
- * hand and their kind is read from the path, so neither the host name nor the kind can be
15681
- * taken on trust: `https://evil.example/a/b/pull/1` would otherwise receive a GitHub token,
15682
- * and `https://gitlab.com/a/b/pull/1` would receive a GitHub token at GitLab. Comparing
15683
- * whole origins also keeps a token off plain http and off look-alikes such as
15684
- * `github.com.evil.example`.
15685
- */
15686
- function isTrustedHost(ref, trusted) {
15687
- return ref.host === GitHostKind.GitHub ? ref.webOrigin === GITHUB_DOT_COM_ORIGIN || trusted.github.includes(ref.webOrigin) : ref.webOrigin === GITLAB_DOT_COM_ORIGIN || trusted.gitlab.includes(ref.webOrigin);
15854
+ // packages/providers/src/gitlabDirectory.ts
15855
+ const AUTH_HINT = "Set GITLAB_TOKEN to a token with the read_api scope.";
15856
+ const OPEN_STATE = "opened";
15857
+ const MERGE_REQUESTS_PER_PAGE = 100;
15858
+ const listedSchema = z.object({
15859
+ web_url: z.url(),
15860
+ title: z.string(),
15861
+ author: z.object({ username: z.string() }),
15862
+ draft: z.boolean().default(false),
15863
+ updated_at: z.string(),
15864
+ source_project_id: z.number().int(),
15865
+ target_project_id: z.number().int()
15866
+ });
15867
+ const userSchema = z.object({ username: z.string() });
15868
+ var GitLabDirectory = class {
15869
+ #project;
15870
+ #token;
15871
+ constructor(project, token) {
15872
+ this.#project = project;
15873
+ this.#token = token;
15874
+ }
15875
+ async openFromBranch(branch) {
15876
+ const url = `${gitlabProjectApi(this.#project)}/merge_requests?state=${OPEN_STATE}&source_branch=${encodeURIComponent(branch)}&per_page=${MERGE_REQUESTS_PER_PAGE}`;
15877
+ return (await this.#get(url, z.array(listedSchema))).filter((mergeRequest) => mergeRequest.source_project_id === mergeRequest.target_project_id).map(toListing);
15878
+ }
15879
+ /**
15880
+ * GitLab keeps a reviewer on a merge request after they review it, so unlike GitHub this also
15881
+ * lists merge requests the user has already reviewed and that are still open.
15882
+ */
15883
+ async awaitingMyReview() {
15884
+ if (this.#token === void 0) throw new NotSignedInError(`Walkdiff needs your GitLab login to find merge requests waiting for your review. ${AUTH_HINT}`);
15885
+ const api = gitlabApiBase(this.#project.webOrigin);
15886
+ const { username } = await this.#get(`${api}/user`, userSchema);
15887
+ const url = `${api}/merge_requests?state=${OPEN_STATE}&scope=all&reviewer_username=${encodeURIComponent(username)}&order_by=updated_at&sort=desc&per_page=50`;
15888
+ return (await this.#get(url, z.array(listedSchema))).map(toListing);
15889
+ }
15890
+ #get(url, schema) {
15891
+ return getJson({
15892
+ url,
15893
+ headers: gitlabHeaders(this.#token),
15894
+ schema,
15895
+ authHint: AUTH_HINT
15896
+ });
15897
+ }
15898
+ };
15899
+ function toListing(mergeRequest) {
15900
+ return listingFrom({
15901
+ url: mergeRequest.web_url,
15902
+ title: mergeRequest.title,
15903
+ author: mergeRequest.author.username,
15904
+ draft: mergeRequest.draft,
15905
+ updatedAt: mergeRequest.updated_at
15906
+ });
15907
+ }
15908
+ // packages/providers/src/pullRequestDirectoryFor.ts
15909
+ /** Like `gitHostFor`, the token only goes to a host the user trusts for it. */
15910
+ function pullRequestDirectoryFor(repository, tokens) {
15911
+ const trusted = isTrustedHost(repository, tokens.trustedOrigins);
15912
+ switch (repository.host) {
15913
+ case GitHostKind.GitHub: return new GitHubDirectory(repository, trusted ? tokens.github : void 0);
15914
+ case GitHostKind.GitLab: return new GitLabDirectory(repository, trusted ? tokens.gitlab : void 0);
15915
+ }
15688
15916
  }
15689
15917
  // packages/providers/src/gitHostFor.ts
15690
15918
  /**
@@ -16088,6 +16316,13 @@ async function isReadable(path) {
16088
16316
  return false;
16089
16317
  }
16090
16318
  }
16319
+ // packages/cli/src/version.ts
16320
+ const MANIFEST_PATH = firstExisting([resolve(import.meta.dirname, "package.json"), resolve(import.meta.dirname, "../../../package.json")]);
16321
+ const manifestSchema = z.object({ version: z.string().min(1) });
16322
+ /** The running Walkdiff's version, read from its package.json. */
16323
+ function walkdiffVersion(manifestPath = MANIFEST_PATH) {
16324
+ return manifestSchema.parse(JSON.parse(readFileSync(manifestPath, "utf8"))).version;
16325
+ }
16091
16326
  // packages/cli/src/server.ts
16092
16327
  const LOOPBACK_HOST = "127.0.0.1";
16093
16328
  const INDEX_FILE = "index.html";
@@ -16229,6 +16464,48 @@ async function attachCoverage(store, id, reports, write) {
16229
16464
  });
16230
16465
  return store.get(id);
16231
16466
  }
16467
+ // packages/cli/src/app/pullRequestLookup.ts
16468
+ const PullRequestLookup = {
16469
+ FromBranch: "fromBranch",
16470
+ AwaitingMyReview: "awaitingMyReview"
16471
+ };
16472
+ const BAD_REQUEST = 400;
16473
+ const FORBIDDEN = 403;
16474
+ const BAD_GATEWAY = 502;
16475
+ const OK = 200;
16476
+ /**
16477
+ * Answers a plugin asking which PRs it could review, from the git remote of the repository it has
16478
+ * open: the open PRs from a branch (`remote` and `branch`), or those waiting for the user's review
16479
+ * on that remote's host (`remote` alone).
16480
+ */
16481
+ async function lookUpPullRequests(lookup, query, context) {
16482
+ const remote = query.get("remote") ?? "";
16483
+ const branch = query.get("branch") ?? "";
16484
+ if (remote === "") return failure(BAD_REQUEST, "Ask with the repository's git remote, as remote=<url>.");
16485
+ if (lookup === PullRequestLookup.FromBranch && branch === "") return failure(BAD_REQUEST, "Ask with the branch, as branch=<name>.");
16486
+ try {
16487
+ const directory = await context.directoryFor(parseRemoteUrl(remote, context.trustedOrigins));
16488
+ const listed = lookup === PullRequestLookup.FromBranch ? await directory.openFromBranch(branch) : await directory.awaitingMyReview();
16489
+ return {
16490
+ status: OK,
16491
+ body: listed
16492
+ };
16493
+ } catch (error) {
16494
+ return failureFor(error);
16495
+ }
16496
+ }
16497
+ function failureFor(error) {
16498
+ if (error instanceof InvalidRemoteUrlError) return failure(BAD_REQUEST, error.message);
16499
+ if (error instanceof NotSignedInError) return failure(FORBIDDEN, error.message);
16500
+ if (error instanceof HostApiError) return failure(BAD_GATEWAY, error.message);
16501
+ throw error;
16502
+ }
16503
+ function failure(status, error) {
16504
+ return {
16505
+ status,
16506
+ body: { error }
16507
+ };
16508
+ }
16232
16509
  // packages/cli/src/app/stackStatus.ts
16233
16510
  /**
16234
16511
  * A grouped stack with each member's state read from its host now, bottom first. One member's
@@ -16390,6 +16667,7 @@ async function approve({ member, host, analyzed }, body) {
16390
16667
  };
16391
16668
  }
16392
16669
  }
16670
+ const PULL_REQUEST_LOOKUPS = /* @__PURE__ */ new Map([["/api/pull-requests", PullRequestLookup.FromBranch], ["/api/review-requests", PullRequestLookup.AwaitingMyReview]]);
16393
16671
  const API_KEY_META = "walkdiff-api-key";
16394
16672
  const HOME_META = "walkdiff-home";
16395
16673
  const REVIEW_ID_META = "walkdiff-review-id";
@@ -16410,6 +16688,8 @@ var AppPortInUseError = class extends Error {
16410
16688
  async function startAppServer(store, service, options) {
16411
16689
  const { port, log, apiKey = newApiKey(), env = {}, offline = false } = options;
16412
16690
  const hostFor = options.hostFor ?? ((ref) => Promise.resolve(gitHostFor(ref, readHostTokens(env))));
16691
+ const directoryFor = options.directoryFor ?? ((repository) => Promise.resolve(pullRequestDirectoryFor(repository, readHostTokens(env))));
16692
+ const { trustedOrigins } = readHostTokens(env);
16413
16693
  const allowedHosts = /* @__PURE__ */ new Set();
16414
16694
  const context = {
16415
16695
  store,
@@ -16419,6 +16699,8 @@ async function startAppServer(store, service, options) {
16419
16699
  env,
16420
16700
  offline,
16421
16701
  hostFor,
16702
+ directoryFor,
16703
+ trustedOrigins,
16422
16704
  writeReport: options.writeReport ?? writeReport,
16423
16705
  describeChecks: options.describeChecks ?? (() => describeChecks())
16424
16706
  };
@@ -16437,6 +16719,10 @@ async function startAppServer(store, service, options) {
16437
16719
  close: () => new Promise((done, fail) => server.close((error) => error ? fail(error) : done()))
16438
16720
  };
16439
16721
  }
16722
+ /**
16723
+ * A key for the API. Made fresh each run and kept only in memory and in the connection file, which
16724
+ * is removed when the app stops, so it lasts only as long as the process.
16725
+ */
16440
16726
  function newApiKey() {
16441
16727
  return randomBytes(API_KEY_BYTES).toString("hex");
16442
16728
  }
@@ -16471,6 +16757,30 @@ async function handleApi(request, response, pathname, context) {
16471
16757
  return;
16472
16758
  }
16473
16759
  const method = request.method ?? "GET";
16760
+ if (pathname === "/api/info" && method === "GET") {
16761
+ sendJson(response, 200, {
16762
+ apiVersion: 1,
16763
+ reportSchemaVersion: 11,
16764
+ version: walkdiffVersion()
16765
+ });
16766
+ return;
16767
+ }
16768
+ const reportData = /^\/api\/reviews\/(\d+)\/report$/.exec(pathname);
16769
+ if (reportData !== null && method === "GET") {
16770
+ await sendReportData(response, Number(reportData[1]), context);
16771
+ return;
16772
+ }
16773
+ const lookup = PULL_REQUEST_LOOKUPS.get(pathname);
16774
+ if (lookup !== void 0 && method === "GET") {
16775
+ const answer = await lookUpPullRequests(lookup, new URL(request.url ?? "/", "http://localhost").searchParams, context);
16776
+ sendJson(response, answer.status, answer.body);
16777
+ return;
16778
+ }
16779
+ const changedFile = /^\/api\/reviews\/(\d+)\/file$/.exec(pathname);
16780
+ if (changedFile !== null && method === "GET") {
16781
+ await sendChangedFile(request, response, Number(changedFile[1]), context);
16782
+ return;
16783
+ }
16474
16784
  if (pathname === "/api/reviews") {
16475
16785
  if (method === "GET") {
16476
16786
  sendJson(response, 200, context.service.list());
@@ -16782,6 +17092,72 @@ async function sendReportPage(response, id, context) {
16782
17092
  }
16783
17093
  sendHtml(response, withReviewId(withMeta(page.replace(REPORT_FILE_POLICY_TAG, ""), context.apiKey), id), REPORT_PAGE_POLICY);
16784
17094
  }
17095
+ /** A review's report as data, as its page shows it. */
17096
+ async function sendReportData(response, id, context) {
17097
+ const model = await readReviewModel(context.store.reportDirOf(id));
17098
+ if (model === void 0) {
17099
+ sendJson(response, 404, { error: "This review has no report. Refresh it to create one." });
17100
+ return;
17101
+ }
17102
+ sendJson(response, 200, model);
17103
+ }
17104
+ const FileSide = {
17105
+ Base: "base",
17106
+ Head: "head"
17107
+ };
17108
+ function isFileSide(value) {
17109
+ return value === FileSide.Base || value === FileSide.Head;
17110
+ }
17111
+ /**
17112
+ * One of a review's changed files at the PR's merge base or head, from the repository the app
17113
+ * fetched its commits into, for showing a diff of a PR that isn't checked out. Only the PR's
17114
+ * changed files can be read, so this never serves anything else from the repository.
17115
+ */
17116
+ async function sendChangedFile(request, response, id, context) {
17117
+ const query = new URL(request.url ?? "/", "http://localhost").searchParams;
17118
+ const side = query.get("side");
17119
+ const path = query.get("path");
17120
+ if (!isFileSide(side) || path === null || path === "") {
17121
+ sendJson(response, 400, { error: "Ask for side=base or side=head, and a path." });
17122
+ return;
17123
+ }
17124
+ const model = await readReviewModel(context.store.reportDirOf(id));
17125
+ const repoDir = context.store.repoDirOf(id);
17126
+ if (model === void 0 || repoDir === void 0) {
17127
+ sendJson(response, 404, { error: "This review's files aren't available. Refresh it to fetch them." });
17128
+ return;
17129
+ }
17130
+ if (!model.files.some(({ diff }) => diff.path === path || "previousPath" in diff && diff.previousPath === path)) {
17131
+ sendJson(response, 404, { error: "That file isn't one this PR changes." });
17132
+ return;
17133
+ }
17134
+ const commit = side === FileSide.Base ? model.pullRequest.mergeBaseSha : model.pullRequest.headSha;
17135
+ const [blob] = await readBlobs(repoDir, [{
17136
+ commit,
17137
+ path
17138
+ }]);
17139
+ if (blob === void 0) {
17140
+ sendJson(response, 404, { error: `That file doesn't exist at the PR's ${side}.` });
17141
+ return;
17142
+ }
17143
+ sendJson(response, 200, {
17144
+ path,
17145
+ side,
17146
+ commit,
17147
+ text: blob.toString("utf8")
17148
+ });
17149
+ }
17150
+ /** Undefined when there's no report, it's gone from disk, or it was written in an older format. */
17151
+ async function readReviewModel(reportDir) {
17152
+ if (reportDir === void 0) return void 0;
17153
+ try {
17154
+ const parsed = reviewModelSchema.safeParse(JSON.parse(await readFile(join(reportDir, REVIEW_MODEL_FILE), "utf8")));
17155
+ return parsed.success ? parsed.data : void 0;
17156
+ } catch (error) {
17157
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return void 0;
17158
+ throw error;
17159
+ }
17160
+ }
16785
17161
  /** Undefined when the file is gone, which happens after the cache folder is cleared. */
16786
17162
  async function readReportPage(reportDir) {
16787
17163
  try {
@@ -16840,6 +17216,32 @@ function sendText(response, status, body) {
16840
17216
  });
16841
17217
  response.end(body);
16842
17218
  }
17219
+ // packages/cli/src/app/connectionFile.ts
17220
+ /**
17221
+ * How editor plugins find a running app: its address and the key its API requires, in a file
17222
+ * only the user can read. The key is otherwise created fresh each run and never stored, so this
17223
+ * file is the one place it's written down; it's removed when the app stops. A file left by an app
17224
+ * that crashed points at nothing, which a plugin finds out from `GET /api/info`.
17225
+ */
17226
+ const CONNECTION_FILE = "app.json";
17227
+ const OWNER_ONLY = 384;
17228
+ async function writeConnectionFile(dataDir, connection) {
17229
+ const path = join(dataDir, CONNECTION_FILE);
17230
+ await rm(path, { force: true });
17231
+ await writeFile(path, `${JSON.stringify(connection, null, 2)}\n`, { mode: OWNER_ONLY });
17232
+ return path;
17233
+ }
17234
+ /** Removes the file when the process ends, including on Ctrl+C, which would otherwise skip `exit`. */
17235
+ function removeOnExit(path) {
17236
+ const remove = () => rmSync(path, { force: true });
17237
+ process.once("exit", remove);
17238
+ for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => {
17239
+ remove();
17240
+ process.exit(signal === "SIGINT" ? EXIT_ON_SIGINT : EXIT_ON_SIGTERM);
17241
+ });
17242
+ }
17243
+ const EXIT_ON_SIGINT = 130;
17244
+ const EXIT_ON_SIGTERM = 143;
16843
17245
  // packages/cli/src/app/stacks.ts
16844
17246
  /** One row per PR, however its URL was pasted (`/files`, trailing slash, and so on). */
16845
17247
  function canonicalUrl(ref) {
@@ -17072,10 +17474,11 @@ function urlsByStack(reviews) {
17072
17474
  }
17073
17475
  return grouped;
17074
17476
  }
17075
- function summarize({ model, reportDir }) {
17477
+ function summarize({ model, reportDir, repoDir }) {
17076
17478
  const units = model.files.flatMap(changedUnitsOf);
17077
17479
  return {
17078
17480
  reportDir,
17481
+ repoDir,
17079
17482
  title: model.pullRequest.title,
17080
17483
  author: model.pullRequest.author,
17081
17484
  securityLevel: model.risk.securityLevel,
@@ -17119,7 +17522,8 @@ const MIGRATIONS = [
17119
17522
  `ALTER TABLE reviews ADD COLUMN detected_stack TEXT`,
17120
17523
  `ALTER TABLE reviews ADD COLUMN dismissed_stack_members TEXT`,
17121
17524
  `ALTER TABLE reviews ADD COLUMN head_sha TEXT`,
17122
- `ALTER TABLE reviews ADD COLUMN base_ref TEXT`
17525
+ `ALTER TABLE reviews ADD COLUMN base_ref TEXT`,
17526
+ `ALTER TABLE reviews ADD COLUMN repo_dir TEXT`
17123
17527
  ];
17124
17528
  const attachedCoverageSchema = z.object({
17125
17529
  headSha: z.string(),
@@ -17144,6 +17548,7 @@ const reviewRowSchema = z.object({
17144
17548
  status: z.enum(ReviewStatus),
17145
17549
  error: z.string().nullable(),
17146
17550
  report_dir: z.string().nullable(),
17551
+ repo_dir: z.string().nullable(),
17147
17552
  ai: z.number(),
17148
17553
  title: z.string().nullable(),
17149
17554
  author: z.string().nullable(),
@@ -17191,6 +17596,10 @@ var ReviewStore = class {
17191
17596
  reportDirOf(id) {
17192
17597
  return this.#parsedRow(id)?.report_dir ?? void 0;
17193
17598
  }
17599
+ /** Undefined for reviews made before the app kept it, until they're refreshed. */
17600
+ repoDirOf(id) {
17601
+ return this.#parsedRow(id)?.repo_dir ?? void 0;
17602
+ }
17194
17603
  add(review) {
17195
17604
  const now = this.#timestamp();
17196
17605
  const { lastInsertRowid } = this.#db.prepare("INSERT INTO reviews (url, host, display_name, status, ai, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)").run(review.url, review.host, review.displayName, ReviewStatus.Queued, review.ai ? 1 : 0, now, now);
@@ -17206,8 +17615,8 @@ var ReviewStore = class {
17206
17615
  this.#db.prepare("UPDATE reviews SET status = ?, error = NULL, updated_at = ? WHERE id = ?").run(status, this.#timestamp(), id);
17207
17616
  }
17208
17617
  markReady(id, analysis) {
17209
- this.#db.prepare(`UPDATE reviews SET status = ?, error = NULL, report_dir = ?, title = ?, author = ?, security_level = ?,
17210
- units_to_review = ?, untouched_references = ?, findings = ?, coverage_source = ?, head_sha = ?, base_ref = ?, updated_at = ? WHERE id = ?`).run(ReviewStatus.Ready, analysis.reportDir, analysis.title, analysis.author, analysis.securityLevel, analysis.unitsToReview, analysis.untouchedReferences, analysis.findings, analysis.coverageSource, analysis.head.headSha, analysis.head.baseRef, this.#timestamp(), id);
17618
+ this.#db.prepare(`UPDATE reviews SET status = ?, error = NULL, report_dir = ?, repo_dir = ?, title = ?, author = ?, security_level = ?,
17619
+ units_to_review = ?, untouched_references = ?, findings = ?, coverage_source = ?, head_sha = ?, base_ref = ?, updated_at = ? WHERE id = ?`).run(ReviewStatus.Ready, analysis.reportDir, analysis.repoDir, analysis.title, analysis.author, analysis.securityLevel, analysis.unitsToReview, analysis.untouchedReferences, analysis.findings, analysis.coverageSource, analysis.head.headSha, analysis.head.baseRef, this.#timestamp(), id);
17211
17620
  }
17212
17621
  /** Records what the last detection found; undefined clears it, for a PR that now stands alone. */
17213
17622
  saveDetection(id, stack) {
@@ -17464,8 +17873,9 @@ async function serveReportOnPreferredPort(reportDir, port) {
17464
17873
  }
17465
17874
  async function reviewPullRequest(options, deps) {
17466
17875
  const ref = parsePullRequestUrl(options.url ?? await detectPullRequestUrl(deps.env));
17876
+ const { model } = await analyzePullRequest(ref, options, deps);
17467
17877
  return {
17468
- model: await analyzePullRequest(ref, options, deps),
17878
+ model,
17469
17879
  reportDir: options.outDir ?? defaultReportDir(deps.cacheDir, ref)
17470
17880
  };
17471
17881
  }
@@ -17499,17 +17909,21 @@ async function analyzePullRequest(ref, options, deps) {
17499
17909
  const history = options.network ? (request) => host.fetchFileHistory(request) : offlineHistory;
17500
17910
  const { pullRequest } = snapshot;
17501
17911
  deps.reportStep(AnalysisStep.FetchingCommits);
17502
- return analyzeChange({
17503
- repoDir: await fetchCommits({
17504
- cacheDir: deps.cacheDir,
17505
- cloneUrl: snapshot.cloneUrl,
17506
- credentials: snapshot.gitAuth,
17507
- commits: [pullRequest.mergeBaseSha, pullRequest.headSha]
17508
- }),
17509
- pullRequest,
17510
- ref,
17511
- history
17512
- }, options, deps);
17912
+ const repoDir = await fetchCommits({
17913
+ cacheDir: deps.cacheDir,
17914
+ cloneUrl: snapshot.cloneUrl,
17915
+ credentials: snapshot.gitAuth,
17916
+ commits: [pullRequest.mergeBaseSha, pullRequest.headSha]
17917
+ });
17918
+ return {
17919
+ model: await analyzeChange({
17920
+ repoDir,
17921
+ pullRequest,
17922
+ ref,
17923
+ history
17924
+ }, options, deps),
17925
+ repoDir
17926
+ };
17513
17927
  }
17514
17928
  async function offlineHistory() {
17515
17929
  throw new HistoryUnavailableError("offline mode: the host was not asked");
@@ -17604,10 +18018,11 @@ async function runApp(options, deps) {
17604
18018
  const store = new ReviewStore(join(dataDir, DATABASE_FILE), deps.now);
17605
18019
  store.markInterrupted();
17606
18020
  const hostFor = async (ref) => gitHostFor(ref, await hostTokensFor(ref, deps.env, runCommand));
17607
- const server = await startAppServer(store, new ReviewService(store, {
18021
+ const directoryFor = async (repository) => pullRequestDirectoryFor(repository, await hostTokensFor(repository, deps.env, runCommand));
18022
+ const service = new ReviewService(store, {
17608
18023
  generate: async ({ ref, ai, attachedCoverage, reportStep }) => {
17609
18024
  const settings = store.getSettings();
17610
- const model = await analyzePullRequest(ref, {
18025
+ const { model, repoDir } = await analyzePullRequest(ref, {
17611
18026
  network: options.network,
17612
18027
  coveragePath: void 0,
17613
18028
  attachedCoverage,
@@ -17624,18 +18039,30 @@ async function runApp(options, deps) {
17624
18039
  await writeReport(model, reportDir);
17625
18040
  return {
17626
18041
  model,
17627
- reportDir
18042
+ reportDir,
18043
+ repoDir
17628
18044
  };
17629
18045
  },
17630
18046
  findStack: async (ref) => (await hostFor(ref)).fetchStack(),
17631
18047
  log: deps.log
17632
- }), {
18048
+ });
18049
+ const apiKey = newApiKey();
18050
+ const server = await startAppServer(store, service, {
17633
18051
  port: options.port,
17634
18052
  log: deps.log,
17635
18053
  env: deps.env,
17636
18054
  offline: !options.network,
17637
- hostFor
18055
+ hostFor,
18056
+ directoryFor,
18057
+ apiKey
17638
18058
  });
18059
+ removeOnExit(await writeConnectionFile(dataDir, {
18060
+ url: server.url,
18061
+ apiKey,
18062
+ apiVersion: 1,
18063
+ version: walkdiffVersion(),
18064
+ pid: process.pid
18065
+ }));
17639
18066
  deps.log(`Walkdiff is running at ${server.url} (Ctrl+C to stop)`, { fields: { url: server.url } });
17640
18067
  if (options.open && canOpenBrowser(process.platform, deps.env)) openBrowser(server.url, deps.log);
17641
18068
  const scanners = await findInstalledScanners();
@@ -17818,13 +18245,6 @@ async function runComment(options, deps) {
17818
18245
  deps.log(`Could not post the summary comment (this token may be read-only): ${error.message}`, { level: LogLevel.Warn });
17819
18246
  }
17820
18247
  }
17821
- // packages/cli/src/version.ts
17822
- const MANIFEST_PATH = firstExisting([resolve(import.meta.dirname, "package.json"), resolve(import.meta.dirname, "../../../package.json")]);
17823
- const manifestSchema = z.object({ version: z.string().min(1) });
17824
- /** The running Walkdiff's version, read from its package.json. */
17825
- function walkdiffVersion(manifestPath = MANIFEST_PATH) {
17826
- return manifestSchema.parse(JSON.parse(readFileSync(manifestPath, "utf8"))).version;
17827
- }
17828
18248
  // packages/cli/src/main.ts
17829
18249
  const EXIT_FAILURE = 1;
17830
18250
  const EXIT_USAGE = 2;