revdeck 0.14.0 → 0.16.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/dist/daemon.js CHANGED
@@ -702,6 +702,33 @@ rename to ${newPath}
702
702
  const endpoint = `projects/${this.projectRef}/repository/files/${encodeURIComponent(path12)}/raw`;
703
703
  return this.call([query(endpoint, { ref })]);
704
704
  }
705
+ async readiness() {
706
+ const errors = [];
707
+ let checks = [];
708
+ let approvals = null;
709
+ try {
710
+ const pipelines = await this.json([query(this.endpoint("/pipelines"), { per_page: 1 })]);
711
+ const pipeline = Array.isArray(pipelines) ? pipelines[0] : void 0;
712
+ if (pipeline) {
713
+ const status = pipeline.status === "success" ? "success" : pipeline.status === "failed" ? "failed" : pipeline.status === "running" || pipeline.status === "pending" || pipeline.status === "created" ? "pending" : pipeline.status === "canceled" ? "skipped" : "neutral";
714
+ checks = [{ id: String(pipeline.id), name: `Pipeline #${pipeline.id}`, status, url: pipeline.web_url ?? null }];
715
+ }
716
+ } catch (error) {
717
+ errors.push(`pipeline: ${messageOf(error)}`);
718
+ }
719
+ try {
720
+ const data = await this.json([this.endpoint("/approvals")]);
721
+ const required = Number(data.approvals_required);
722
+ approvals = {
723
+ approved: (data.approved_by ?? []).length,
724
+ required: Number.isFinite(required) ? required : null,
725
+ changesRequested: 0
726
+ };
727
+ } catch (error) {
728
+ errors.push(`approvals: ${messageOf(error)}`);
729
+ }
730
+ return { checks, approvals, errors, checkedAt: (/* @__PURE__ */ new Date()).toISOString() };
731
+ }
705
732
  async threads() {
706
733
  const discussions = await this.paged(this.endpoint("/discussions"));
707
734
  const threads = [];
@@ -825,6 +852,21 @@ rename to ${newPath}
825
852
  async reactToReview(emoji) {
826
853
  return this.toggleAward(this.endpoint("/award_emoji"), emoji);
827
854
  }
855
+ async submitReview(input) {
856
+ const note = await withTempJson(
857
+ { body: input.body },
858
+ async (file) => this.json(["--method", "POST", this.endpoint("/notes"), "--input", file])
859
+ );
860
+ if (input.verdict === "approve") {
861
+ await this.call(["--method", "POST", this.endpoint("/approve")]);
862
+ } else if (input.verdict === "request_changes") {
863
+ try {
864
+ await this.call(["--method", "POST", this.endpoint("/unapprove")]);
865
+ } catch {
866
+ }
867
+ }
868
+ return { id: String(note.id) };
869
+ }
828
870
  async updateNote(noteId, body) {
829
871
  await withTempJson({ body }, async (file) => {
830
872
  await this.call(["--method", "PUT", this.endpoint(`/notes/${encodeURIComponent(noteId)}`), "--input", file]);
@@ -910,6 +952,7 @@ var init_github = __esm({
910
952
  "use strict";
911
953
  init_diff();
912
954
  init_errors();
955
+ init_errors();
913
956
  init_exec();
914
957
  init_util();
915
958
  init_locale();
@@ -1065,6 +1108,40 @@ rename to ${newPath}
1065
1108
  const encoded = path12.split("/").map(encodeURIComponent).join("/");
1066
1109
  return this.call(["-H", "Accept: application/vnd.github.raw", query(`repos/${this.repo}/contents/${encoded}`, { ref })]);
1067
1110
  }
1111
+ async readiness() {
1112
+ const errors = [];
1113
+ let checks = [];
1114
+ let approvals = null;
1115
+ const info = await this.info();
1116
+ try {
1117
+ const data = await this.json([query(`repos/${this.repo}/commits/${encodeURIComponent(info.commit.head)}/check-runs`, { per_page: 100 })]);
1118
+ checks = (data.check_runs ?? []).map((run2) => ({
1119
+ id: String(run2.id),
1120
+ name: run2.name,
1121
+ status: run2.status !== "completed" ? "pending" : run2.conclusion === "success" ? "success" : run2.conclusion === "failure" || run2.conclusion === "timed_out" || run2.conclusion === "action_required" ? "failed" : run2.conclusion === "skipped" ? "skipped" : "neutral",
1122
+ url: run2.html_url ?? run2.details_url ?? null
1123
+ }));
1124
+ } catch (error) {
1125
+ errors.push(`checks: ${messageOf(error)}`);
1126
+ }
1127
+ try {
1128
+ const reviews = await this.paged(`${this.pullBase}/reviews`);
1129
+ const latest = /* @__PURE__ */ new Map();
1130
+ for (const review of reviews) {
1131
+ const login = review.user?.login;
1132
+ if (!login || review.state !== "APPROVED" && review.state !== "CHANGES_REQUESTED") continue;
1133
+ latest.set(login, review.state);
1134
+ }
1135
+ approvals = {
1136
+ approved: [...latest.values()].filter((state) => state === "APPROVED").length,
1137
+ required: null,
1138
+ changesRequested: [...latest.values()].filter((state) => state === "CHANGES_REQUESTED").length
1139
+ };
1140
+ } catch (error) {
1141
+ errors.push(`approvals: ${messageOf(error)}`);
1142
+ }
1143
+ return { checks, approvals, errors, checkedAt: (/* @__PURE__ */ new Date()).toISOString() };
1144
+ }
1068
1145
  async threads() {
1069
1146
  const nodes = [];
1070
1147
  let after = null;
@@ -1088,6 +1165,7 @@ rename to ${newPath}
1088
1165
  path: node.path,
1089
1166
  line: node.line ?? node.originalLine,
1090
1167
  side: node.diffSide === "LEFT" ? "old" : "new",
1168
+ ...node.isOutdated ? { outdated: true } : {},
1091
1169
  resolvable: true,
1092
1170
  resolved: node.isResolved,
1093
1171
  notes,
@@ -1211,6 +1289,14 @@ rename to ${newPath}
1211
1289
  async reactToReview(emoji) {
1212
1290
  return this.toggleReaction(`repos/${this.repo}/issues/${this.ref.number}/reactions`, emoji);
1213
1291
  }
1292
+ async submitReview(input) {
1293
+ const event = input.verdict === "approve" ? "APPROVE" : input.verdict === "request_changes" ? "REQUEST_CHANGES" : "COMMENT";
1294
+ const review = await withTempJson(
1295
+ { body: input.body, event },
1296
+ async (file) => this.json(["--method", "POST", `${this.pullBase}/reviews`, "--input", file])
1297
+ );
1298
+ return { id: String(review.id) };
1299
+ }
1214
1300
  async updateNote(noteId, body) {
1215
1301
  await withTempJson({ body }, async (file) => {
1216
1302
  await this.call(["--method", "PATCH", `repos/${this.repo}/pulls/comments/${encodeURIComponent(noteId)}`, "--input", file]);
@@ -1413,7 +1499,7 @@ async function writeFileAtomic(file, data, mode = 384, dirMode = 448) {
1413
1499
  init_redact();
1414
1500
 
1415
1501
  // src/version.ts
1416
- var VERSION = "0.14.0";
1502
+ var VERSION = "0.16.0";
1417
1503
  var PROTOCOL_VERSION = 2;
1418
1504
 
1419
1505
  // src/daemon/main.ts
@@ -3320,6 +3406,40 @@ function computeGroups(diff, custom = []) {
3320
3406
  return [...groups.values()].sort((left, right) => right.additions + right.deletions - (left.additions + left.deletions) || left.title.localeCompare(right.title));
3321
3407
  }
3322
3408
 
3409
+ // src/core/codeowners.ts
3410
+ function parseCodeowners(text2) {
3411
+ const entries = [];
3412
+ for (const raw of text2.replace(/\r\n/g, "\n").split("\n")) {
3413
+ const line = raw.trim();
3414
+ if (!line || line.startsWith("#")) continue;
3415
+ const [pattern, ...owners] = line.split(/\s+/);
3416
+ if (!pattern || !owners.length) continue;
3417
+ entries.push({ pattern, owners });
3418
+ }
3419
+ return entries;
3420
+ }
3421
+ function matches(path12, pattern) {
3422
+ const cleaned = pattern.replace(/^\/+/, "").replace(/\/+$/, "");
3423
+ if (!cleaned) return false;
3424
+ if (!cleaned.includes("/")) {
3425
+ const segment = cleaned.includes("*") || cleaned.includes("?") ? cleaned : cleaned.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3426
+ return new RegExp(`(^|/)${segment}(/|$)`).test(path12);
3427
+ }
3428
+ if (globToRegExp(cleaned).test(path12)) return true;
3429
+ return globToRegExp(`${cleaned}/**`).test(path12);
3430
+ }
3431
+ function codeownersFor(files, entries) {
3432
+ const result = [];
3433
+ for (const file of files) {
3434
+ let owners = [];
3435
+ for (const entry of entries) {
3436
+ if (matches(file, entry.pattern)) owners = entry.owners;
3437
+ }
3438
+ if (owners.length) result.push({ file, owners });
3439
+ }
3440
+ return result;
3441
+ }
3442
+
3323
3443
  // src/core/secrets.ts
3324
3444
  var PATTERNS = [
3325
3445
  { id: "aws-access-key", title: "AWS access key", regex: /\bAKIA[0-9A-Z]{16}\b/g },
@@ -4439,6 +4559,24 @@ ${body}` : `${marker}
4439
4559
 
4440
4560
  ${body}`;
4441
4561
  }
4562
+ function renderPublishedSummary(summary) {
4563
+ const lines = [];
4564
+ const title = summary.title.trim();
4565
+ lines.push(`## ${title || tr("\u0420\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442 \u0440\u0435\u0432\u044C\u044E", "Review result")}`);
4566
+ if (summary.scope.trim()) lines.push("", `\`${summary.scope.trim()}\``);
4567
+ if (summary.summary.trim()) lines.push("", summary.summary.trim());
4568
+ const section = (label, items) => {
4569
+ const list = (items ?? []).map((item) => item.trim()).filter(Boolean);
4570
+ if (!list.length) return;
4571
+ lines.push("", `### ${label}`);
4572
+ for (const item of list) lines.push(`- ${item}`);
4573
+ };
4574
+ section(tr("\u0427\u0442\u043E \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u043E", "What changed"), summary.changes);
4575
+ section(tr("\u041D\u0430 \u0447\u0442\u043E \u0441\u043C\u043E\u0442\u0440\u0435\u0442\u044C", "What to focus on"), summary.focus);
4576
+ section(tr("\u0427\u0442\u043E \u043F\u0440\u043E\u0432\u0435\u0440\u0435\u043D\u043E", "What was checked"), summary.coverage);
4577
+ section(tr("\u0427\u0442\u043E \u043D\u0435 \u043F\u0440\u043E\u0432\u0435\u0440\u0435\u043D\u043E", "Not checked"), summary.unknowns);
4578
+ return lines.join("\n").trim();
4579
+ }
4442
4580
  var ReviewService = class {
4443
4581
  events = new EventEmitter();
4444
4582
  store;
@@ -4456,6 +4594,8 @@ var ReviewService = class {
4456
4594
  previews = /* @__PURE__ */ new Map();
4457
4595
  /** Полные файлы для раскрытия diff; ключ включает head/base, коммит и путь. */
4458
4596
  fileContentCache = /* @__PURE__ */ new Map();
4597
+ readinessCache = /* @__PURE__ */ new Map();
4598
+ codeownersCache = /* @__PURE__ */ new Map();
4459
4599
  constructor(options) {
4460
4600
  this.store = options.store;
4461
4601
  this.runImpl = options.runImpl ?? run;
@@ -5254,6 +5394,83 @@ ${t("\u2026 \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442 \u0444\u0438\u0447\
5254
5394
  if (!found) return null;
5255
5395
  return { path: found.path, status: found.status, binary: found.binary, hunks: found.hunks };
5256
5396
  }
5397
+ /** CI/approvals платформы; кешируется на минуту, чтобы Overview не дёргал API на каждый рендер. */
5398
+ async readiness(id, force = false) {
5399
+ const cached = this.readinessCache.get(id);
5400
+ if (!force && cached && this.now().getTime() - cached.at < 6e4) return cached.value;
5401
+ const preview = this.previews.get(id);
5402
+ let provider;
5403
+ try {
5404
+ provider = preview && this.now().getTime() - preview.at < 60 * 6e4 ? await this.providerFactory(preview.ref, preview.root) : await this.providerFor(id);
5405
+ } catch (error) {
5406
+ return {
5407
+ checks: [],
5408
+ approvals: null,
5409
+ errors: [tr(`\u043D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0441\u044F \u043A \u043F\u043B\u0430\u0442\u0444\u043E\u0440\u043C\u0435: ${redact(messageOf(error))}`, `could not reach the platform: ${redact(messageOf(error))}`)],
5410
+ checkedAt: this.now().toISOString()
5411
+ };
5412
+ }
5413
+ let value;
5414
+ try {
5415
+ value = await provider.readiness();
5416
+ } catch (error) {
5417
+ value = {
5418
+ checks: [],
5419
+ approvals: null,
5420
+ errors: [tr(`\u043D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044C \u0433\u043E\u0442\u043E\u0432\u043D\u043E\u0441\u0442\u044C: ${redact(messageOf(error))}`, `could not read readiness: ${redact(messageOf(error))}`)],
5421
+ checkedAt: this.now().toISOString()
5422
+ };
5423
+ }
5424
+ this.readinessCache.set(id, { value, at: this.now().getTime() });
5425
+ return value;
5426
+ }
5427
+ /** CODEOWNERS из рабочей копии или head платформы; только чтение. */
5428
+ async codeowners(id, force = false) {
5429
+ const cached = this.codeownersCache.get(id);
5430
+ if (!force && cached && this.now().getTime() - cached.at < 5 * 6e4) return cached.value;
5431
+ const preview = this.previews.get(id);
5432
+ const stored = preview ? null : this.store.getReview(id);
5433
+ if (!preview && !stored) throw Object.assign(new Error(tr(`\u0440\u0435\u0432\u044C\u044E ${id} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u043E`, `review ${id} not found`)), { status: 404 });
5434
+ const info = preview?.view.info ?? this.store.info(id);
5435
+ const root = preview?.root ?? stored.row.root;
5436
+ const files = (preview?.diff ?? stored.snapshot.diff).map((file) => file.path);
5437
+ const candidates = [".github/CODEOWNERS", "CODEOWNERS", "docs/CODEOWNERS", ".gitlab/CODEOWNERS"];
5438
+ let text2 = null;
5439
+ let foundPath = null;
5440
+ for (const candidate of candidates) {
5441
+ try {
5442
+ text2 = await readConfigFile(root, candidate, 1e6);
5443
+ foundPath = candidate;
5444
+ break;
5445
+ } catch {
5446
+ }
5447
+ }
5448
+ if (text2 === null && info.commit.head) {
5449
+ try {
5450
+ const provider = preview ? await this.providerFactory(preview.ref, preview.root) : await this.providerFor(id);
5451
+ for (const candidate of candidates) {
5452
+ try {
5453
+ const raw = await provider.fileContent(candidate, info.commit.head);
5454
+ if (raw.trim()) {
5455
+ text2 = raw;
5456
+ foundPath = candidate;
5457
+ break;
5458
+ }
5459
+ } catch {
5460
+ }
5461
+ }
5462
+ } catch {
5463
+ }
5464
+ }
5465
+ const value = {
5466
+ found: text2 !== null,
5467
+ path: foundPath,
5468
+ matches: text2 === null ? [] : codeownersFor(files, parseCodeowners(text2)),
5469
+ errors: []
5470
+ };
5471
+ this.codeownersCache.set(id, { value, at: this.now().getTime() });
5472
+ return value;
5473
+ }
5257
5474
  /** Последняя версия revdeck в npm; force=true — ручная проверка из настроек. */
5258
5475
  async updateInfo(force = false) {
5259
5476
  return this.updates.check(force);
@@ -5679,16 +5896,33 @@ ${errors.join("\n")}`));
5679
5896
  return message;
5680
5897
  }
5681
5898
  // ---------------------------------------------------------------- publish
5682
- previewPublish(id, kind, ids) {
5899
+ previewPublish(id, kind, ids, verdict = "comment") {
5683
5900
  const review = this.getReview(id);
5684
5901
  const items = [];
5685
5902
  const warnings = [];
5686
5903
  const max = this.configOf(id)?.publish?.maxComments ?? 50;
5687
- for (const itemId of ids) {
5904
+ const reviewVerdict = verdict === "approve" || verdict === "request_changes" ? verdict : "comment";
5905
+ const targets = kind === "review" ? ["review"] : ids;
5906
+ for (const itemId of targets) {
5688
5907
  if (items.length >= max) {
5689
5908
  warnings.push(tr(`\u0434\u043E\u0441\u0442\u0438\u0433\u043D\u0443\u0442 \u043B\u0438\u043C\u0438\u0442 ${max} \u043A\u043E\u043C\u043C\u0435\u043D\u0442\u0430\u0440\u0438\u0435\u0432 \u0437\u0430 \u0440\u0430\u0437`, `limit of ${max} comments per batch reached`));
5690
5909
  break;
5691
5910
  }
5911
+ if (kind === "review") {
5912
+ const summary = this.store.getSummary(id);
5913
+ if (!summary) {
5914
+ warnings.push(tr("\u0432\u044B\u0436\u0438\u043C\u043A\u0438 \u0440\u0435\u0432\u044C\u044E \u043D\u0435\u0442: \u0441\u043D\u0430\u0447\u0430\u043B\u0430 \u0437\u0430\u043F\u0438\u0448\u0438\u0442\u0435 summary", "there is no review summary: write one first"));
5915
+ continue;
5916
+ }
5917
+ const body2 = renderPublishedSummary(summary);
5918
+ const check2 = sanitizeBody(body2, review.info.ref.platform, { host: review.info.ref.host });
5919
+ if (!check2.ok) {
5920
+ warnings.push(tr(`\u0432\u044B\u0436\u0438\u043C\u043A\u0430 \u0440\u0435\u0432\u044C\u044E: ${check2.reason}`, `review summary: ${check2.reason}`));
5921
+ continue;
5922
+ }
5923
+ items.push({ kind: "review", id: "review", body: body2, verdict: reviewVerdict });
5924
+ continue;
5925
+ }
5692
5926
  if (kind === "reply") {
5693
5927
  const thread = review.threads.find((item) => item.id === itemId);
5694
5928
  const draft = review.drafts.find((item) => item.threadId === itemId);
@@ -5769,9 +6003,9 @@ ${errors.join("\n")}`));
5769
6003
  const hash = canonicalHash(id, kind, items);
5770
6004
  return { reviewId: id, kind, items, hash, createdAt: this.now().toISOString() };
5771
6005
  }
5772
- approve(id, kind, ids, expectedHash) {
6006
+ approve(id, kind, ids, expectedHash, verdict = "comment") {
5773
6007
  this.assertWritable(id);
5774
- const preview = this.previewPublish(id, kind, ids);
6008
+ const preview = this.previewPublish(id, kind, ids, verdict);
5775
6009
  if (preview.plan.hash !== expectedHash) {
5776
6010
  throw new Error(tr("\u043D\u0430\u0431\u043E\u0440 \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0439 \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u0441\u044F \u043F\u043E\u0441\u043B\u0435 \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F: \u043E\u0431\u043D\u043E\u0432\u0438\u0442\u0435 \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u0443 \u0438 \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0434\u0438\u0442\u0435 \u0437\u0430\u043D\u043E\u0432\u043E", "the plan changed after confirmation: refresh and confirm again"));
5777
6011
  }
@@ -5820,6 +6054,15 @@ ${errors.join("\n")}`));
5820
6054
  const result = { kind: item.kind, id: item.id, ok: false };
5821
6055
  results.push(result);
5822
6056
  try {
6057
+ if (item.kind === "review") {
6058
+ const body = String(item.body ?? "").trim();
6059
+ if (!body) throw new Error(tr("\u043F\u0443\u0441\u0442\u0430\u044F \u0432\u044B\u0436\u0438\u043C\u043A\u0430 \u0440\u0435\u0432\u044C\u044E", "empty review summary"));
6060
+ const check = sanitizeBody(body, platform, { host: review.info.ref.host });
6061
+ if (!check.ok) throw new Error(check.reason);
6062
+ await provider.submitReview({ body, verdict: item.verdict ?? "comment" });
6063
+ result.ok = true;
6064
+ continue;
6065
+ }
5823
6066
  if (item.kind === "reply") {
5824
6067
  const thread = review.threads.find((entry) => entry.id === item.id);
5825
6068
  const draft = this.store.getDraft(id, item.id) ?? EMPTY_DRAFT(item.id);
@@ -6769,6 +7012,18 @@ data: ${JSON.stringify(event)}
6769
7012
  reply(res, 200, { ok: true, update });
6770
7013
  return;
6771
7014
  }
7015
+ if (req.method === "GET" && url.pathname === "/api/codeowners") {
7016
+ const review = url.searchParams.get("review") ?? "";
7017
+ const codeowners = await service.codeowners(review, url.searchParams.get("refresh") === "1");
7018
+ reply(res, 200, { ok: true, codeowners });
7019
+ return;
7020
+ }
7021
+ if (req.method === "GET" && url.pathname === "/api/readiness") {
7022
+ const review = url.searchParams.get("review") ?? "";
7023
+ const readiness = await service.readiness(review, url.searchParams.get("refresh") === "1");
7024
+ reply(res, 200, { ok: true, readiness });
7025
+ return;
7026
+ }
6772
7027
  if (req.method === "GET" && url.pathname === "/api/health") {
6773
7028
  reply(res, 200, { ok: true, version: options.version ?? "dev", reviews: service.listReviews().length });
6774
7029
  return;
@@ -7008,7 +7263,12 @@ data: ${JSON.stringify(event)}
7008
7263
  return;
7009
7264
  }
7010
7265
  case "/api/publish/preview": {
7011
- const preview = service.previewPublish(review, String(body.kind ?? "reply"), Array.isArray(body.ids) ? body.ids.map(String) : []);
7266
+ const preview = service.previewPublish(
7267
+ review,
7268
+ String(body.kind ?? "reply"),
7269
+ Array.isArray(body.ids) ? body.ids.map(String) : [],
7270
+ body.verdict === "approve" || body.verdict === "request_changes" ? body.verdict : "comment"
7271
+ );
7012
7272
  reply(res, 200, { ok: true, preview });
7013
7273
  return;
7014
7274
  }
@@ -7017,7 +7277,8 @@ data: ${JSON.stringify(event)}
7017
7277
  review,
7018
7278
  String(body.kind ?? "reply"),
7019
7279
  Array.isArray(body.ids) ? body.ids.map(String) : [],
7020
- String(body.hash ?? "")
7280
+ String(body.hash ?? ""),
7281
+ body.verdict === "approve" || body.verdict === "request_changes" ? body.verdict : "comment"
7021
7282
  );
7022
7283
  reply(res, 200, { ok: true, approval: { id: approval.id, expiresAt: approval.expiresAt } });
7023
7284
  return;