@theholocron/holocron-plugin-github 5.0.0-alpha.38 → 5.0.0-alpha.380

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/index.mjs CHANGED
@@ -1,48 +1,74 @@
1
1
  import { createRequire } from "node:module";
2
+ import { AuthError, MissingTokenError, ProviderApiError, connectionProbe, createFeatureResolver } from "@theholocron/cli";
2
3
  import { createGitHubClient, createGitHubClient as createGitHubClient$1 } from "@theholocron/github-client";
3
- import { AuthError, createFeatureResolver } from "@theholocron/cli";
4
4
  import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
5
5
  import { dirname, join } from "node:path";
6
- //#region src/auth.ts
6
+ import { findRootSync } from "@theholocron/fs-utils";
7
+ import { ProviderApiError as ProviderApiError$1 } from "@theholocron/http-client";
8
+ import { errorMessage } from "@theholocron/misc-utils";
9
+ // src/auth.ts
10
+ /** Resolves the token for read-only GitHub access (`HOLOCRON_READ_TOKEN`, keyring key `github.read`). */
7
11
  const resolveReadToken = createFeatureResolver({
8
12
  envName: "HOLOCRON_READ_TOKEN",
9
13
  keyringKey: "github.read"
10
14
  });
15
+ /** Resolves the token for issue operations (`HOLOCRON_ISSUES_TOKEN`, keyring key `github.issues`). */
11
16
  const resolveIssuesToken = createFeatureResolver({
12
17
  envName: "HOLOCRON_ISSUES_TOKEN",
13
18
  keyringKey: "github.issues"
14
19
  });
20
+ /** Resolves the token for syncing repo files and settings (`HOLOCRON_SYNC_TOKEN`, keyring key `github.sync`). */
15
21
  const resolveSyncToken = createFeatureResolver({
16
22
  envName: "HOLOCRON_SYNC_TOKEN",
17
23
  keyringKey: "github.sync"
18
24
  });
25
+ /** Resolves the token for release operations (`HOLOCRON_RELEASE_TOKEN`, keyring key `github.release`). */
19
26
  const resolveReleaseToken = createFeatureResolver({
20
27
  envName: "HOLOCRON_RELEASE_TOKEN",
21
28
  keyringKey: "github.release"
22
29
  });
30
+ /** Resolves the repo-scoped admin token (`HOLOCRON_ADMIN_TOKEN`, keyring key `github.admin`). */
23
31
  const resolveAdminToken = createFeatureResolver({
24
32
  envName: "HOLOCRON_ADMIN_TOKEN",
25
33
  keyringKey: "github.admin"
26
34
  });
35
+ /** Resolves the org-level secrets token (`HOLOCRON_SECRETS_TOKEN`, keyring key `github.secrets`). */
36
+ const resolveSecretsToken = createFeatureResolver({
37
+ envName: "HOLOCRON_SECRETS_TOKEN",
38
+ keyringKey: "github.secrets"
39
+ });
40
+ /** Resolves the token for deployment operations (`HOLOCRON_DEPLOY_TOKEN`, keyring key `github.deploy`). */
27
41
  const resolveDeployToken = createFeatureResolver({
28
42
  envName: "HOLOCRON_DEPLOY_TOKEN",
29
43
  keyringKey: "github.deploy"
30
44
  });
45
+ /**
46
+ * Resolves the token for the user-sync files in the org's private config repo (`HOLOCRON_USER_SYNC_TOKEN`, keyring
47
+ * key `github.user-sync`).
48
+ */
49
+ const resolveUserSyncToken = createFeatureResolver({
50
+ envName: "HOLOCRON_USER_SYNC_TOKEN",
51
+ keyringKey: "github.user-sync"
52
+ });
53
+ /** Resolves the org-level token (`HOLOCRON_ORG_TOKEN`, keyring key `github.org`). */
31
54
  const resolveOrgToken = createFeatureResolver({
32
55
  envName: "HOLOCRON_ORG_TOKEN",
33
56
  keyringKey: "github.org"
34
57
  });
35
- //#endregion
36
- //#region src/capabilities/ci.ts
58
+ // src/capabilities/ci.ts
59
+ /** The GitHub implementation of the `ci` capability, backed by GitHub Actions workflow runs. */
37
60
  var GitHubCi = class {
38
61
  client;
39
62
  opts;
63
+ /** Capability key, always `"ci"`. */
40
64
  key = "ci";
65
+ /** Provider name, always `"github"`. */
41
66
  providerName = "github";
42
67
  constructor(client, opts) {
43
68
  this.client = client;
44
69
  this.opts = opts;
45
70
  }
71
+ /** Lists workflow runs for the repo, optionally filtered by branch, status and limit. */
46
72
  async listRuns(filter) {
47
73
  return (await this.client.workflows.listRuns(this.opts.repo, {
48
74
  branch: filter?.branch,
@@ -50,6 +76,7 @@ var GitHubCi = class {
50
76
  status: filter?.status
51
77
  })).map((r) => this.mapRun(r));
52
78
  }
79
+ /** Fetches one workflow run by id. */
53
80
  async getRun(id) {
54
81
  const raw = await this.client.workflows.getRun(this.opts.repo, id);
55
82
  return this.mapRun(raw);
@@ -77,17 +104,20 @@ var GitHubCi = class {
77
104
  }
78
105
  }
79
106
  };
80
- //#endregion
81
- //#region src/capabilities/environments.ts
107
+ // src/capabilities/environments.ts
108
+ /** The GitHub implementation of the `environments` capability, managing a repo's deployment environments. */
82
109
  var GitHubEnvironments = class {
83
110
  client;
84
111
  opts;
112
+ /** Capability key, always `"environments"`. */
85
113
  key = "environments";
114
+ /** Provider name, always `"github"`. */
86
115
  providerName = "github";
87
116
  constructor(client, opts) {
88
117
  this.client = client;
89
118
  this.opts = opts;
90
119
  }
120
+ /** Lists the repo's environments with their wait timer, self-review rule and required reviewers. */
91
121
  async listEnvironments() {
92
122
  return (await this.client.environments.listEnvironments(this.opts.repo)).map((e) => ({
93
123
  name: e.name,
@@ -96,6 +126,7 @@ var GitHubEnvironments = class {
96
126
  reviewers: this.flattenReviewers(e.protection_rules)
97
127
  }));
98
128
  }
129
+ /** Creates or updates an environment, sending only the settings the given environment defines. */
99
130
  async upsertEnvironment(env) {
100
131
  const body = {};
101
132
  if (env.waitTimer !== void 0) body.wait_timer = env.waitTimer;
@@ -106,6 +137,7 @@ var GitHubEnvironments = class {
106
137
  }));
107
138
  await this.client.environments.upsertEnvironment(this.opts.repo, env.name, body);
108
139
  }
140
+ /** Deletes the named environment. */
109
141
  async deleteEnvironment(name) {
110
142
  await this.client.environments.deleteEnvironment(this.opts.repo, name);
111
143
  }
@@ -119,11 +151,313 @@ var GitHubEnvironments = class {
119
151
  }));
120
152
  }
121
153
  };
122
- //#endregion
123
- //#region src/capabilities/issues.ts
154
+ // src/capabilities/issues-migration.ts
155
+ /**
156
+ * Export and import of GitHub issues for `holocron migrate`.
157
+ *
158
+ * GitHub holds less than a planning tool, so what does not fit is named in each result's `dropped` list rather than
159
+ * lost quietly:
160
+ * - priority is a label (`priority: high`), because on GitHub it lives in a project field, not on the issue;
161
+ * - an import cannot backdate an issue or a comment, and cannot post as someone else, so the original date and
162
+ * author go in the text;
163
+ * - an import does not set parent or blocked-by links (they need GraphQL node ids of issues made in the same run);
164
+ * - an assignee is not mapped (a Linear user is not a GitHub login).
165
+ * A migrated issue ends with `<!-- holocron:migrated-from <url> -->`, which is how a second run finds it.
166
+ */
167
+ const MARKER = /<!-- holocron:migrated-from (\S+) -->/;
168
+ const PRIORITY_LABEL = /^priority\s*[:/-]\s*(urgent|high|medium|low)$/i;
169
+ const LINK_QUERY = `query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) {
170
+ issue(number: $number) { parent { number } blockedBy(first: 50) { nodes { number } } } } }`;
171
+ /** Splits `priority: high` labels from the rest. */
172
+ function splitLabels(names) {
173
+ let priority;
174
+ const labels = [];
175
+ for (const name of names) {
176
+ const match = PRIORITY_LABEL.exec(name);
177
+ if (match) priority = match[1].toLowerCase();
178
+ else labels.push(name);
179
+ }
180
+ return {
181
+ labels,
182
+ ...priority ? { priority } : {}
183
+ };
184
+ }
185
+ function categoryOf(issue) {
186
+ if (issue.state === "closed") return "done";
187
+ const names = issue.labels.map((l) => l.name.toLowerCase());
188
+ if (names.some((n) => n === "status:in-review" || n === "status: in review")) return "in-review";
189
+ if (names.some((n) => n === "status:in-progress" || n === "status: in progress")) return "in-progress";
190
+ return "open";
191
+ }
192
+ /** How many issues an export fetches at once. GitHub's secondary rate limit punishes bursts of requests, not volume. */
193
+ const EXPORT_CONCURRENCY = 4;
194
+ /** Runs `fn` over `items`, at most `limit` at a time, and returns the results in the order of `items`. */
195
+ async function mapLimit(items, limit, fn) {
196
+ const results = new Array(items.length);
197
+ let next = 0;
198
+ const worker = async () => {
199
+ while (next < items.length) {
200
+ const at = next++;
201
+ results[at] = await fn(items[at]);
202
+ }
203
+ };
204
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
205
+ return results;
206
+ }
207
+ /** GitHub's own answer to a burst of requests (403 or 429 naming the secondary limit) becomes a message that says what to do. */
208
+ function explainSecondaryLimit(err) {
209
+ if (err instanceof ProviderApiError && (err.status === 403 || err.status === 429) && String(err.details).includes("secondary rate limit")) return /* @__PURE__ */ new Error("GitHub's secondary rate limit stopped the export. It limits bursts of requests, not the hourly quota, and nothing has been written. Wait a couple of minutes and run the command again.");
210
+ return err;
211
+ }
212
+ /** Reads the issues `selector` names, with their comments, priority label, parent and blockers. */
213
+ async function exportIssues(client, repo, selector) {
214
+ return readIssues(client, repo, selector).catch((err) => {
215
+ throw explainSecondaryLimit(err);
216
+ });
217
+ }
218
+ async function readIssues(client, repo, selector) {
219
+ const [owner = "", name = ""] = repo.split("/", 2);
220
+ let raw;
221
+ if (selector.keys) raw = await mapLimit(selector.keys, EXPORT_CONCURRENCY, (k) => client.issues.getIssue(repo, parseNumber(k)));
222
+ else if (selector.milestone) {
223
+ const milestone = await findMilestone(client, repo, selector.milestone);
224
+ if (!milestone) throw new Error(`Milestone "${selector.milestone}" not found in ${repo}.`);
225
+ raw = await listAll(client, repo, { milestone: String(milestone.number) });
226
+ } else if (selector.all) raw = await listAll(client, repo, {});
227
+ else throw new Error("export needs keys, a milestone or all");
228
+ const since = selector.since ? Date.parse(selector.since) : void 0;
229
+ const issues = raw.filter((i) => !i.pull_request && !(selector.openOnly && i.state === "closed") && (since === void 0 || Date.parse(i.updated_at) >= since));
230
+ const records = [];
231
+ for (const issue of issues) {
232
+ const comments = await client.issues.listComments(repo, issue.number);
233
+ const links = (await client.graphql.query(LINK_QUERY, {
234
+ owner,
235
+ name,
236
+ number: issue.number
237
+ }).catch(() => void 0))?.repository.issue;
238
+ const { labels, priority } = splitLabels(issue.labels.map((l) => l.name));
239
+ const body = issue.body?.replace(MARKER, "").trimEnd();
240
+ const migratedFrom = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
241
+ records.push({
242
+ key: `#${issue.number}`,
243
+ url: issue.html_url,
244
+ title: issue.title,
245
+ ...body ? { body } : {},
246
+ statusCategory: categoryOf(issue),
247
+ closed: issue.state === "closed",
248
+ ...priority ? { priority } : {},
249
+ labels: labels.filter((l) => !l.toLowerCase().startsWith("status:")),
250
+ ...issue.assignee ? { assignee: {
251
+ id: issue.assignee.login,
252
+ displayName: issue.assignee.name ?? issue.assignee.login,
253
+ ...issue.assignee.email ? { emailAddress: issue.assignee.email } : {}
254
+ } } : {},
255
+ ...issue.milestone ? { milestone: issue.milestone.title } : {},
256
+ ...links?.parent ? { parent: `#${links.parent.number}` } : {},
257
+ blockedBy: (links?.blockedBy.nodes ?? []).map((n) => `#${n.number}`),
258
+ comments: comments.map((c) => ({
259
+ ...c.user ? { author: c.user.login } : {},
260
+ body: c.body,
261
+ createdAt: c.created_at
262
+ })),
263
+ createdAt: issue.created_at ?? issue.updated_at,
264
+ updatedAt: issue.updated_at,
265
+ ...migratedFrom ? { migratedFrom } : {}
266
+ });
267
+ }
268
+ return records;
269
+ }
270
+ /** Makes the records as issues, skipping any whose source address an earlier run already recorded. */
271
+ async function importIssues(client, repo, records, options = {}) {
272
+ const existing = /* @__PURE__ */ new Map();
273
+ for (const issue of await listAll(client, repo, {})) {
274
+ const url = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
275
+ if (url) existing.set(url, issue.number);
276
+ }
277
+ const results = [];
278
+ for (const record of records) {
279
+ const found = existing.get(record.url);
280
+ if (found !== void 0) {
281
+ results.push({
282
+ source: record.key,
283
+ key: `#${found}`,
284
+ created: false,
285
+ dropped: []
286
+ });
287
+ continue;
288
+ }
289
+ const dropped = droppedFor(record);
290
+ if (options.dryRun) {
291
+ results.push({
292
+ source: record.key,
293
+ created: true,
294
+ dropped
295
+ });
296
+ continue;
297
+ }
298
+ const number = await createFromRecord(client, repo, record, options);
299
+ results.push({
300
+ source: record.key,
301
+ key: `#${number}`,
302
+ created: true,
303
+ dropped
304
+ });
305
+ }
306
+ return results;
307
+ }
308
+ /** What GitHub cannot hold of this record, for the report. */
309
+ function droppedFor(record) {
310
+ const dropped = ["createdAt (GitHub sets it; the original date is in the text)"];
311
+ if (record.assignee) dropped.push("assignee (not mapped)");
312
+ if (record.parent) dropped.push("parent (not set on GitHub)");
313
+ if (record.blockedBy.length > 0) dropped.push("blockedBy (not set on GitHub)");
314
+ return dropped;
315
+ }
316
+ /** The labels a record becomes on GitHub: its own, plus `priority: <level>` (GitHub's priority is a label). */
317
+ function labelsFor(record) {
318
+ return [...record.labels, ...record.priority && record.priority !== "none" ? [`priority: ${record.priority}`] : []];
319
+ }
320
+ /** The text a comment gets when it is copied: GitHub cannot post as another author or backdate. */
321
+ function renderComment(comment) {
322
+ return `${comment.author ? `**${comment.author}**` : "Someone"} commented on ${comment.createdAt}:\n\n${comment.body}`;
323
+ }
324
+ /** Makes one issue from a record, with its comments, and closes it when the record is closed; returns its number. */
325
+ async function createFromRecord(client, repo, record, options) {
326
+ const milestoneName = options.milestone ?? record.milestone;
327
+ const milestone = milestoneName ? await ensureMilestone(client, repo, milestoneName) : void 0;
328
+ const labels = labelsFor(record);
329
+ const created = await client.issues.createIssue(repo, {
330
+ title: record.title,
331
+ body: withProvenance(record),
332
+ ...labels.length > 0 ? { labels } : {},
333
+ ...milestone !== void 0 ? { milestone } : {}
334
+ });
335
+ for (const comment of record.comments) await client.issues.createComment(repo, created.number, renderComment(comment));
336
+ if (record.closed) await client.issues.updateIssue(repo, created.number, {
337
+ state: "closed",
338
+ state_reason: "completed"
339
+ });
340
+ return created.number;
341
+ }
342
+ /** The text of a migrated issue: the record's body, then where it came from and the marker a second run looks for. */
343
+ function withProvenance(record) {
344
+ return `${record.body ? `${record.body}\n\n` : ""}---\n_Migrated from [${record.key}](${record.url}); created ${record.createdAt}._\n<!-- holocron:migrated-from ${record.url} -->`;
345
+ }
346
+ function parseNumber(key) {
347
+ const n = key.trim().replace(/^.*#/, "");
348
+ if (!/^\d+$/.test(n)) throw new Error(`Invalid GitHub issue key "${key}" — expected #N or N.`);
349
+ return parseInt(n, 10);
350
+ }
351
+ async function listAll(client, repo, extra) {
352
+ const all = [];
353
+ for (let page = 1;; page++) {
354
+ const batch = await client.issues.listIssues(repo, {
355
+ state: "all",
356
+ per_page: 100,
357
+ page,
358
+ ...extra
359
+ });
360
+ all.push(...batch);
361
+ if (batch.length < 100) return all;
362
+ }
363
+ }
364
+ async function findMilestone(client, repo, ref) {
365
+ return (await client.issues.listMilestones(repo, { state: "all" })).find((m) => String(m.number) === ref || m.title.toLowerCase() === ref.toLowerCase());
366
+ }
367
+ async function ensureMilestone(client, repo, title) {
368
+ return (await findMilestone(client, repo, title))?.number ?? (await client.issues.createMilestone(repo, title)).number;
369
+ }
370
+ // src/capabilities/issues-sync.ts
371
+ const COMMENT_HEADER = /^(?:\*\*.*?\*\*|Someone) commented on (\S+?):\n/;
372
+ /** Whether GitHub is asking to be left alone: a 429, or a 403 that says it is a rate limit. */
373
+ function isRateLimited(err) {
374
+ return err instanceof ProviderApiError && (err.status === 429 || err.status === 403 && /rate limit/i.test(`${err.message} ${String(err.details)}`));
375
+ }
376
+ const normalize = (text) => text.replace(/\r\n/g, "\n").trim();
377
+ const sorted = (names) => names.map((n) => n.toLowerCase()).sort().join("\n");
378
+ /** Makes the records missing from the repo and updates the ones an earlier run made. See the file comment. */
379
+ async function syncIssues(client, repo, records, options = {}) {
380
+ const existing = /* @__PURE__ */ new Map();
381
+ for (const issue of await listAll(client, repo, {})) {
382
+ const url = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
383
+ if (url) existing.set(url, issue);
384
+ }
385
+ const results = [];
386
+ for (const record of records) try {
387
+ const found = existing.get(record.url);
388
+ results.push(found ? await update(client, repo, found, record, options) : await create(client, repo, record, options));
389
+ } catch (err) {
390
+ if (isRateLimited(err)) return results;
391
+ throw err;
392
+ }
393
+ return results;
394
+ }
395
+ async function create(client, repo, record, options) {
396
+ const dropped = droppedFor(record);
397
+ if (options.dryRun) return {
398
+ source: record.key,
399
+ created: true,
400
+ updated: false,
401
+ changes: [],
402
+ dropped
403
+ };
404
+ const number = await createFromRecord(client, repo, record, options);
405
+ return {
406
+ source: record.key,
407
+ key: `#${number}`,
408
+ created: true,
409
+ updated: false,
410
+ changes: [],
411
+ dropped
412
+ };
413
+ }
414
+ async function update(client, repo, issue, record, options) {
415
+ const patch = {};
416
+ const changes = [];
417
+ if (issue.title !== record.title) {
418
+ patch.title = record.title;
419
+ changes.push("title");
420
+ }
421
+ const body = withProvenance(record);
422
+ if (normalize(issue.body) !== normalize(body)) {
423
+ patch.body = body;
424
+ changes.push("description");
425
+ }
426
+ if (issue.state === "closed" !== record.closed) {
427
+ patch.state = record.closed ? "closed" : "open";
428
+ if (record.closed) patch.state_reason = "completed";
429
+ changes.push("state");
430
+ }
431
+ const current = issue.labels.map((l) => l.name);
432
+ const finalLabels = [...labelsFor(record), ...current.filter((n) => n.toLowerCase().startsWith("status:"))];
433
+ if (sorted(finalLabels) !== sorted(current)) {
434
+ patch.labels = finalLabels;
435
+ changes.push("labels");
436
+ }
437
+ const comments = await client.issues.listComments(repo, issue.number);
438
+ const seen = new Set(comments.map((c) => COMMENT_HEADER.exec(c.body)?.[1]));
439
+ const missing = record.comments.filter((c) => !seen.has(c.createdAt));
440
+ if (missing.length > 0) changes.push("comments");
441
+ if (!options.dryRun) {
442
+ if (Object.keys(patch).length > 0) await client.issues.updateIssue(repo, issue.number, patch);
443
+ for (const comment of missing) await client.issues.createComment(repo, issue.number, renderComment(comment));
444
+ }
445
+ return {
446
+ source: record.key,
447
+ key: `#${issue.number}`,
448
+ created: false,
449
+ updated: changes.length > 0,
450
+ changes,
451
+ dropped: droppedFor(record)
452
+ };
453
+ }
454
+ // src/capabilities/issues.ts
455
+ /** The GitHub implementation of the `issues` capability, backed by GitHub Issues and status labels. */
124
456
  var GitHubIssues = class {
125
457
  client;
458
+ /** Capability key, always `"issues"`. */
126
459
  key = "issues";
460
+ /** Provider name, always `"github"`. */
127
461
  providerName = "github";
128
462
  owner;
129
463
  repoName;
@@ -145,6 +479,7 @@ var GitHubIssues = class {
145
479
  ...raw.email ? { emailAddress: raw.email } : {}
146
480
  };
147
481
  }
482
+ /** Searches the repo's issues, newest update first, leaving out pull requests. */
148
483
  async search(filter) {
149
484
  const params = {
150
485
  state: filter.openOnly ? "open" : "all",
@@ -164,11 +499,13 @@ var GitHubIssues = class {
164
499
  assignee: params.assignee
165
500
  })).filter((i) => !i.pull_request).map((i) => this.mapIssue(i));
166
501
  }
502
+ /** Fetches one issue by its key. */
167
503
  async get(key) {
168
504
  const number = parseIssueNumber(key, this.owner, this.repoName);
169
505
  const raw = await this.client.issues.getIssue(this.repo, number);
170
506
  return this.mapIssue(raw);
171
507
  }
508
+ /** Creates an issue and returns its key as `#<number>`; the milestone is resolved from its title. */
172
509
  async create(input) {
173
510
  const body = { title: input.summary };
174
511
  if (input.body) body.body = input.body;
@@ -216,10 +553,12 @@ var GitHubIssues = class {
216
553
  via: `label set to ${targetLabel}`
217
554
  };
218
555
  }
556
+ /** Adds a comment to the issue with the given key. */
219
557
  async comment(key, body) {
220
558
  const number = parseIssueNumber(key, this.owner, this.repoName);
221
559
  await this.client.issues.createComment(this.repo, number, body);
222
560
  }
561
+ /** Checks the authenticated user, the repo and the label-backed lifecycle slots, and reports what resolves. */
223
562
  async doctor() {
224
563
  const me = await this.getMyself();
225
564
  const repo = await this.client.repos.getRepo(this.repo);
@@ -288,6 +627,18 @@ var GitHubIssues = class {
288
627
  lifecycle
289
628
  };
290
629
  }
630
+ /** Reads issues with their comments, priority label, parent and blockers, for `holocron migrate`. */
631
+ export(selector) {
632
+ return exportIssues(this.client, this.repo, selector);
633
+ }
634
+ /** Makes the records as issues; one already made by an earlier run is skipped. */
635
+ import(records, options) {
636
+ return importIssues(this.client, this.repo, records, options);
637
+ }
638
+ /** Like `import`, and it also updates what an earlier import or sync made, for `holocron sync issues`. */
639
+ sync(records, options) {
640
+ return syncIssues(this.client, this.repo, records, options);
641
+ }
291
642
  async resolveMilestone(ref) {
292
643
  if (/^\d+$/.test(ref)) return parseInt(ref, 10);
293
644
  const match = (await this.client.issues.listMilestones(this.repo, { state: "all" })).find((m) => m.title.toLowerCase() === ref.toLowerCase());
@@ -337,8 +688,584 @@ function parseIssueNumber(key, owner, repoName) {
337
688
  if (!/^\d+$/.test(num)) throw new Error(`Invalid GitHub issue key "${key}" — expected #N or N.`);
338
689
  return parseInt(num, 10);
339
690
  }
340
- //#endregion
341
- //#region src/sodium.ts
691
+ // src/capabilities/projects.ts
692
+ /** The name of the single select field that holds an item's status. */
693
+ const STATUS_FIELD = "Status";
694
+ /** The name of the field `move` carries over besides the status. */
695
+ const PRIORITY_FIELD = "Priority";
696
+ const P_LEVELS = {
697
+ p0: "urgent",
698
+ p1: "high",
699
+ p2: "medium",
700
+ p3: "low"
701
+ };
702
+ /** The neutral priority a `Priority` option stands for, by its name; undefined for a name that is not one of them. */
703
+ function priorityOf(value) {
704
+ const name = value?.trim().toLowerCase();
705
+ if (name === "urgent" || name === "high" || name === "medium" || name === "low") return name;
706
+ return name ? P_LEVELS[name] : void 0;
707
+ }
708
+ const PROJECT_FIELDS = "id number title closed url";
709
+ const BOARD_QUERY = `query($id: ID!) { node(id: $id) { ... on ProjectV2 {
710
+ ${PROJECT_FIELDS}
711
+ fields(first: 100) { nodes {
712
+ ... on ProjectV2FieldCommon { id name dataType }
713
+ ... on ProjectV2SingleSelectField { options { id name color description } }
714
+ } }
715
+ views(first: 50) { nodes { id name layout filter groupByFields(first: 5) { nodes { ... on ProjectV2FieldCommon { name } } } } }
716
+ workflows(first: 50) { nodes { id name enabled } }
717
+ } } }`;
718
+ const ITEMS_QUERY = `query($id: ID!, $after: String) { node(id: $id) { ... on ProjectV2 {
719
+ items(first: 100, after: $after) {
720
+ pageInfo { hasNextPage endCursor }
721
+ nodes {
722
+ id
723
+ fieldValues(first: 30) { nodes { ... on ProjectV2ItemFieldSingleSelectValue { name field { ... on ProjectV2FieldCommon { name } } } } }
724
+ content {
725
+ __typename
726
+ ... on Issue { id number title state repository { nameWithOwner } blockedBy(first: 50) { nodes { number state repository { nameWithOwner } } } }
727
+ ... on PullRequest { id number title state repository { nameWithOwner } }
728
+ }
729
+ }
730
+ }
731
+ } } }`;
732
+ const LIST_QUERY = `query($owner: String!, $after: String) { organization(login: $owner) { id projectsV2(first: 100, after: $after) {
733
+ pageInfo { hasNextPage endCursor }
734
+ nodes { ${PROJECT_FIELDS} }
735
+ } } }`;
736
+ const OWNER_QUERY = "query($owner: String!) { organization(login: $owner) { id } }";
737
+ const SET_VALUE = `mutation($project: ID!, $item: ID!, $field: ID!, $option: String!) {
738
+ updateProjectV2ItemFieldValue(input: { projectId: $project, itemId: $item, fieldId: $field, value: { singleSelectOptionId: $option } }) { projectV2Item { id } }
739
+ }`;
740
+ const UPDATE_OPTIONS = `mutation($field: ID!, $options: [ProjectV2SingleSelectFieldOptionInput!]!) {
741
+ updateProjectV2Field(input: { fieldId: $field, singleSelectOptions: $options }) { projectV2Field { ... on ProjectV2SingleSelectField { id } } }
742
+ }`;
743
+ const DATA_TYPES = {
744
+ single_select: "SINGLE_SELECT",
745
+ text: "TEXT",
746
+ number: "NUMBER",
747
+ date: "DATE",
748
+ iteration: "ITERATION"
749
+ };
750
+ function fieldTypeOf(dataType) {
751
+ return Object.keys(DATA_TYPES).find((t) => DATA_TYPES[t] === dataType);
752
+ }
753
+ function toSummary(n) {
754
+ return {
755
+ id: n.id,
756
+ number: n.number,
757
+ name: n.title,
758
+ url: n.url,
759
+ closed: n.closed
760
+ };
761
+ }
762
+ function toOptionInput(o) {
763
+ return {
764
+ ...o.id ? { id: o.id } : {},
765
+ name: o.name,
766
+ color: (o.color ?? "GRAY").toUpperCase(),
767
+ description: o.description ?? ""
768
+ };
769
+ }
770
+ /** The GitHub implementation of the `projects` capability, backed by Projects v2. */
771
+ var GitHubProjects = class {
772
+ graphql;
773
+ /** Capability key, always `"projects"`. */
774
+ key = "projects";
775
+ /** Provider name, always `"github"`. */
776
+ providerName = "github";
777
+ repo;
778
+ constructor(graphql, opts) {
779
+ this.graphql = graphql;
780
+ this.repo = opts.repo;
781
+ }
782
+ /** Every board of the organization, open and closed. */
783
+ async list(owner) {
784
+ const boards = [];
785
+ let after = null;
786
+ for (;;) {
787
+ const page = (await this.graphql.query(LIST_QUERY, {
788
+ owner,
789
+ after
790
+ })).organization.projectsV2;
791
+ boards.push(...page.nodes.map(toSummary));
792
+ if (!page.pageInfo.hasNextPage) return boards;
793
+ after = page.pageInfo.endCursor;
794
+ }
795
+ }
796
+ /** The open board with exactly this name. */
797
+ async find(owner, name) {
798
+ return (await this.list(owner)).find((b) => !b.closed && b.name === name);
799
+ }
800
+ /**
801
+ * Makes a board. With `template.source` naming an open board it is copied (fields, options, views and automation
802
+ * rules, no items); otherwise the board is created and brought in line with the template.
803
+ */
804
+ async create(owner, name, template) {
805
+ const ownerId = await this.ownerId(owner);
806
+ const source = template.source ? await this.find(owner, template.source) : void 0;
807
+ if (source) return toSummary((await this.graphql.query(`mutation($project: ID!, $owner: ID!, $title: String!) {
808
+ copyProjectV2(input: { projectId: $project, ownerId: $owner, title: $title, includeDraftIssues: false }) { projectV2 { ${PROJECT_FIELDS} } }
809
+ }`, {
810
+ project: source.id,
811
+ owner: ownerId,
812
+ title: name
813
+ })).copyProjectV2.projectV2);
814
+ const board = toSummary((await this.graphql.query(`mutation($owner: ID!, $title: String!) {
815
+ createProjectV2(input: { ownerId: $owner, title: $title }) { projectV2 { ${PROJECT_FIELDS} } }
816
+ }`, {
817
+ owner: ownerId,
818
+ title: name
819
+ })).createProjectV2.projectV2);
820
+ await this.ensure(owner, board, template);
821
+ return board;
822
+ }
823
+ /** Closes the board; `updateProjectV2` with `closed: true` is the only way, and reversible. */
824
+ async close(_owner, board) {
825
+ await this.graphql.query(`mutation($project: ID!) { updateProjectV2(input: { projectId: $project, closed: true }) { projectV2 { id } } }`, { project: board.id });
826
+ }
827
+ /** The live board: statuses, other fields, views and automation rules. */
828
+ async read(_owner, board) {
829
+ const raw = await this.readRaw(board.id);
830
+ const status = raw.fields.find((f) => f.name === STATUS_FIELD);
831
+ const fields = [];
832
+ for (const f of raw.fields) {
833
+ const type = fieldTypeOf(f.dataType);
834
+ if (!type || f.name === STATUS_FIELD) continue;
835
+ fields.push({
836
+ name: f.name,
837
+ type,
838
+ ...f.options ? { options: f.options.map((o) => o.name) } : {}
839
+ });
840
+ }
841
+ const views = [];
842
+ for (const v of raw.views) {
843
+ const layout = v.layout === "BOARD_LAYOUT" ? "board" : v.layout === "TABLE_LAYOUT" ? "table" : void 0;
844
+ if (!layout) continue;
845
+ views.push({
846
+ name: v.name,
847
+ layout,
848
+ ...v.filter ? { filter: v.filter } : {},
849
+ ...v.groupBy[0] ? { groupBy: v.groupBy[0] } : {}
850
+ });
851
+ }
852
+ return {
853
+ board: raw.summary,
854
+ statuses: (status?.options ?? []).map((o) => o.name),
855
+ fields,
856
+ views,
857
+ rules: raw.rules.map(({ name, enabled }) => ({
858
+ name,
859
+ enabled
860
+ }))
861
+ };
862
+ }
863
+ /**
864
+ * Brings the board in line with the template. Never deletes a field, option or view, and never sends an option
865
+ * list without ids. Stops (throws) when the status field cannot be read.
866
+ */
867
+ async ensure(_owner, board, template) {
868
+ const raw = await this.readRaw(board.id);
869
+ const status = raw.fields.find((f) => f.name === STATUS_FIELD && f.options);
870
+ if (!status) throw new Error(`cannot read the "${STATUS_FIELD}" field of board "${board.name}"; stopped before any write so no item loses its status`);
871
+ const changes = [];
872
+ const todos = [];
873
+ const statusChanges = await this.ensureOptions(board, status, template.statuses.map((s) => ({
874
+ name: s.name,
875
+ color: s.color,
876
+ description: s.description
877
+ })));
878
+ changes.push(...statusChanges.map((c) => `status ${c}`));
879
+ for (const want of template.fields) {
880
+ const have = raw.fields.find((f) => f.name === want.name);
881
+ if (!have) {
882
+ await this.createField(board.id, want);
883
+ changes.push(`field ${want.name} created`);
884
+ continue;
885
+ }
886
+ if (fieldTypeOf(have.dataType) !== want.type) {
887
+ todos.push(`field "${want.name}" is ${have.dataType} but the template says ${want.type}; change it by hand`);
888
+ continue;
889
+ }
890
+ if (want.type === "single_select" && have.options && want.options) {
891
+ const diff = await this.ensureOptions(board, have, want.options.map((name) => ({ name })));
892
+ changes.push(...diff.map((c) => `field ${want.name} option ${c}`));
893
+ }
894
+ }
895
+ for (const want of template.views) {
896
+ const have = raw.views.find((v) => v.name === want.name);
897
+ const layout = want.layout === "board" ? "BOARD_LAYOUT" : "TABLE_LAYOUT";
898
+ let viewId = have?.id;
899
+ if (!viewId) {
900
+ viewId = await this.createView(board.id, want.name, layout);
901
+ changes.push(`view ${want.name} created`);
902
+ } else if (have && have.layout !== layout) {
903
+ await this.updateView(viewId, { layout });
904
+ changes.push(`view ${want.name} layout set to ${want.layout}`);
905
+ }
906
+ if (want.filter !== void 0 && want.filter !== (have?.filter ?? "")) {
907
+ await this.updateView(viewId, { filter: want.filter });
908
+ changes.push(`view ${want.name} filter set`);
909
+ }
910
+ if (want.groupBy && have?.groupBy[0] !== want.groupBy) todos.push(`group view "${want.name}" by ${want.groupBy}; the API cannot set a view's grouping`);
911
+ }
912
+ for (const rule of template.rules ?? []) {
913
+ const have = raw.rules.find((r) => r.name === rule);
914
+ if (!have) todos.push(`create the automation rule "${rule}"; the API cannot create one`);
915
+ else if (!have.enabled) todos.push(`turn on the automation rule "${rule}"; the API cannot switch one`);
916
+ }
917
+ return {
918
+ created: false,
919
+ changes,
920
+ todos
921
+ };
922
+ }
923
+ /**
924
+ * Makes a single select field hold the wanted options in order, every existing one sent with its id. Options the
925
+ * template does not mention stay, after the wanted ones. Returns what changed (`Blocked added`, `order set`).
926
+ */
927
+ async ensureOptions(board, field, wanted) {
928
+ /* v8 ignore next -- every caller passes a field it found with options; the fallback only satisfies the type */
929
+ const existing = field.options ?? [];
930
+ const next = [];
931
+ const changes = [];
932
+ for (const w of wanted) {
933
+ const have = existing.find((o) => o.name === w.name);
934
+ if (have) {
935
+ next.push({
936
+ id: have.id,
937
+ name: have.name,
938
+ color: (w.color ?? have.color).toUpperCase(),
939
+ description: w.description ?? have.description
940
+ });
941
+ if (next[next.length - 1].color !== have.color || next[next.length - 1].description !== have.description) changes.push(`${have.name} updated`);
942
+ } else {
943
+ next.push({
944
+ name: w.name,
945
+ color: (w.color ?? "GRAY").toUpperCase(),
946
+ description: w.description ?? ""
947
+ });
948
+ changes.push(`${w.name} added`);
949
+ }
950
+ }
951
+ for (const have of existing) if (!next.some((n) => n.id === have.id)) next.push({ ...have });
952
+ const sameOrder = next.length === existing.length && next.every((n, i) => n.id === existing[i]?.id);
953
+ if (changes.length === 0 && sameOrder) return [];
954
+ if (sameOrder === false && !changes.some((c) => c.endsWith("added"))) changes.push("order set");
955
+ const before = await this.fetchItems(board.id);
956
+ const snapshot = /* @__PURE__ */ new Map();
957
+ for (const item of before) {
958
+ const value = item.values[field.name];
959
+ if (value) snapshot.set(item.id, value);
960
+ }
961
+ await this.graphql.query(UPDATE_OPTIONS, {
962
+ field: field.id,
963
+ options: next.map(toOptionInput)
964
+ });
965
+ const afterField = (await this.readRaw(board.id)).fields.find((f) => f.id === field.id);
966
+ const afterItems = await this.fetchItems(board.id);
967
+ const afterValues = new Map(afterItems.map((i) => [i.id, i.values[field.name]]));
968
+ const lost = [...snapshot].filter(([itemId]) => !afterValues.get(itemId));
969
+ if (lost.length > 0) {
970
+ let restored = 0;
971
+ for (const [itemId, name] of lost) {
972
+ const option = afterField?.options?.find((o) => o.name === name);
973
+ if (!option) continue;
974
+ await this.graphql.query(SET_VALUE, {
975
+ project: board.id,
976
+ item: itemId,
977
+ field: field.id,
978
+ option: option.id
979
+ });
980
+ restored++;
981
+ }
982
+ throw new Error(`updating "${field.name}" on board "${board.name}" blanked ${lost.length} item value(s); wrote ${restored} back by option name`);
983
+ }
984
+ return changes;
985
+ }
986
+ async createField(projectId, want) {
987
+ await this.graphql.query(`mutation($project: ID!, $name: String!, $type: ProjectV2CustomFieldType!, $options: [ProjectV2SingleSelectFieldOptionInput!]) {
988
+ createProjectV2Field(input: { projectId: $project, name: $name, dataType: $type, singleSelectOptions: $options }) { projectV2Field { ... on ProjectV2SingleSelectField { id } } }
989
+ }`, {
990
+ project: projectId,
991
+ name: want.name,
992
+ type: DATA_TYPES[want.type],
993
+ options: want.type === "single_select" ? (want.options ?? []).map((name) => toOptionInput({ name })) : void 0
994
+ });
995
+ }
996
+ async createView(projectId, name, layout) {
997
+ return (await this.graphql.query(`mutation($project: ID!, $name: String!, $layout: ProjectV2ViewLayout!) {
998
+ createProjectV2View(input: { projectId: $project, name: $name, layout: $layout }) { projectV2View { id } }
999
+ }`, {
1000
+ project: projectId,
1001
+ name,
1002
+ layout
1003
+ })).createProjectV2View.projectV2View.id;
1004
+ }
1005
+ async updateView(viewId, change) {
1006
+ await this.graphql.query(`mutation($view: ID!, $layout: ProjectV2ViewLayout, $filter: String) {
1007
+ updateProjectV2View(input: { viewId: $view, layout: $layout, filter: $filter }) { projectV2View { id } }
1008
+ }`, {
1009
+ view: viewId,
1010
+ layout: change.layout,
1011
+ filter: change.filter
1012
+ });
1013
+ }
1014
+ /** The board's issues and pull requests with their status, whether they are open and their open blockers. */
1015
+ async items(_owner, board, template) {
1016
+ const categories = new Map(template.statuses.map((s) => [s.name, s.category]));
1017
+ return (await this.fetchItems(board.id)).map((i) => {
1018
+ const status = i.values[STATUS_FIELD];
1019
+ const category = status ? categories.get(status) : void 0;
1020
+ const priority = priorityOf(i.values[PRIORITY_FIELD]);
1021
+ return {
1022
+ key: this.keyOf(i.repo, i.number),
1023
+ title: i.title,
1024
+ open: i.open,
1025
+ ...status ? { status } : {},
1026
+ ...category ? { category } : {},
1027
+ blockedBy: i.blockers.map((b) => this.keyOf(b.repo, b.number)),
1028
+ ...priority ? { priority } : {}
1029
+ };
1030
+ });
1031
+ }
1032
+ /** Puts an item in a status; `transitioned` is false when it already is there. */
1033
+ async setStatus(_owner, board, key, status) {
1034
+ const ref = this.parseKey(key);
1035
+ const field = (await this.readRaw(board.id)).fields.find((f) => f.name === STATUS_FIELD && f.options);
1036
+ const option = field?.options?.find((o) => o.name === status);
1037
+ if (!field || !option) throw new Error(`board "${board.name}" has no status "${status}"`);
1038
+ const item = (await this.fetchItems(board.id)).find((i) => i.repo === ref.repo && i.number === ref.number);
1039
+ if (!item) throw new Error(`${key} is not on board "${board.name}"`);
1040
+ if (item.values[STATUS_FIELD] === status) return {
1041
+ transitioned: false,
1042
+ status
1043
+ };
1044
+ await this.graphql.query(SET_VALUE, {
1045
+ project: board.id,
1046
+ item: item.id,
1047
+ field: field.id,
1048
+ option: option.id
1049
+ });
1050
+ return {
1051
+ transitioned: true,
1052
+ status,
1053
+ via: "project field set"
1054
+ };
1055
+ }
1056
+ /**
1057
+ * Puts the open items of `from` on `to` with their status and priority, only where the target has no value;
1058
+ * closed and merged ones stay, and are set to the template's done status when theirs is not a done one.
1059
+ */
1060
+ async move(_owner, from, to, template) {
1061
+ const report = {
1062
+ moved: [],
1063
+ kept: [],
1064
+ left: []
1065
+ };
1066
+ const [source, target, fromRaw, toRaw] = await Promise.all([
1067
+ this.fetchItems(from.id),
1068
+ this.fetchItems(to.id),
1069
+ this.readRaw(from.id),
1070
+ this.readRaw(to.id)
1071
+ ]);
1072
+ const done = template.statuses.find((s) => s.category === "done")?.name;
1073
+ const doneNames = new Set(template.statuses.filter((s) => s.category === "done").map((s) => s.name));
1074
+ const carried = [STATUS_FIELD, PRIORITY_FIELD];
1075
+ for (const item of source) {
1076
+ const key = this.keyOf(item.repo, item.number);
1077
+ if (!item.open) {
1078
+ const current = item.values[STATUS_FIELD];
1079
+ if (done && (!current || !doneNames.has(current))) await this.setOption(from.id, fromRaw, item.id, STATUS_FIELD, done);
1080
+ report.left.push(key);
1081
+ continue;
1082
+ }
1083
+ let targetItem = target.find((t) => t.contentId === item.contentId);
1084
+ if (targetItem) report.kept.push(key);
1085
+ else {
1086
+ const data = await this.graphql.query(`mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`, {
1087
+ project: to.id,
1088
+ content: item.contentId
1089
+ });
1090
+ targetItem = {
1091
+ ...item,
1092
+ id: data.addProjectV2ItemById.item.id,
1093
+ values: {}
1094
+ };
1095
+ report.moved.push(key);
1096
+ }
1097
+ for (const name of carried) {
1098
+ const value = item.values[name];
1099
+ if (value && !targetItem.values[name]) await this.setOption(to.id, toRaw, targetItem.id, name, value);
1100
+ }
1101
+ }
1102
+ return report;
1103
+ }
1104
+ /**
1105
+ * Puts issues on the board (`addProjectV2ItemById`, the content id the issue's node id) and sets Status and Priority
1106
+ * through the single select update, only where the item has no value yet. A status or priority with no option on
1107
+ * the board is reported in `dropped`; no option is ever created, so no value is cleared.
1108
+ */
1109
+ async addItems(_owner, board, items, template) {
1110
+ const raw = await this.readRaw(board.id);
1111
+ const onBoard = await this.fetchItems(board.id);
1112
+ const statusField = raw.fields.find((f) => f.name === STATUS_FIELD && f.options);
1113
+ const priorityField = raw.fields.find((f) => f.name === PRIORITY_FIELD && f.options);
1114
+ const results = [];
1115
+ for (const input of items) {
1116
+ const ref = this.parseKey(input.key);
1117
+ let current = onBoard.find((i) => i.repo === ref.repo && i.number === ref.number);
1118
+ const added = !current;
1119
+ if (!current) current = {
1120
+ id: (await this.graphql.query(`mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`, {
1121
+ project: board.id,
1122
+ content: await this.nodeId(ref)
1123
+ })).addProjectV2ItemById.item.id,
1124
+ contentId: "",
1125
+ repo: ref.repo,
1126
+ number: ref.number,
1127
+ title: "",
1128
+ open: true,
1129
+ values: {},
1130
+ blockers: []
1131
+ };
1132
+ const dropped = [];
1133
+ if (input.status !== void 0 || input.category !== void 0) {
1134
+ const name = this.statusFor(input, template, statusField?.options);
1135
+ if (!name) dropped.push(`status ${input.status ?? input.category} (no matching option on the board)`);
1136
+ else if (!current.values[STATUS_FIELD]) await this.setOption(board.id, raw, current.id, STATUS_FIELD, name);
1137
+ }
1138
+ if (input.priority !== void 0 && input.priority !== "none") {
1139
+ const option = priorityField?.options?.find((o) => priorityOf(o.name) === input.priority);
1140
+ if (!option) dropped.push(`priority ${input.priority} (no matching option on the board)`);
1141
+ else if (!current.values[PRIORITY_FIELD]) await this.setOption(board.id, raw, current.id, PRIORITY_FIELD, option.name);
1142
+ }
1143
+ results.push({
1144
+ key: input.key,
1145
+ added,
1146
+ dropped
1147
+ });
1148
+ }
1149
+ return results;
1150
+ }
1151
+ /** The board's own status for an input: the option named like its status, else the template's status of its category. */
1152
+ statusFor(input, template, options) {
1153
+ const has = (name) => options?.find((o) => o.name.toLowerCase() === name.toLowerCase())?.name;
1154
+ const named = input.status === void 0 ? void 0 : has(input.status);
1155
+ if (named) return named;
1156
+ const byCategory = template.statuses.find((s) => s.category === input.category);
1157
+ return byCategory ? has(byCategory.name) : void 0;
1158
+ }
1159
+ /** The node id of an issue, which `addProjectV2ItemById` takes as the content id. */
1160
+ async nodeId(ref) {
1161
+ const [owner, name] = ref.repo.split("/");
1162
+ const id = (await this.graphql.query(`query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { id } } }`, {
1163
+ owner,
1164
+ name,
1165
+ number: ref.number
1166
+ })).repository?.issue?.id;
1167
+ if (!id) throw new Error(`issue ${ref.repo}#${ref.number} not found`);
1168
+ return id;
1169
+ }
1170
+ /** A `holocron doctor` smoke check: how many boards the token sees in the configured repository's organization. */
1171
+ async whoami() {
1172
+ try {
1173
+ return {
1174
+ ok: true,
1175
+ boards: (await this.list(this.repo.split("/")[0] ?? "")).length
1176
+ };
1177
+ } catch {
1178
+ return {
1179
+ ok: false,
1180
+ boards: 0
1181
+ };
1182
+ }
1183
+ }
1184
+ /** Sets a single select value by option name; a field or option the board lacks is skipped. */
1185
+ async setOption(projectId, raw, itemId, fieldName, optionName) {
1186
+ const field = raw.fields.find((f) => f.name === fieldName && f.options);
1187
+ const option = field?.options?.find((o) => o.name === optionName);
1188
+ if (!field || !option) return;
1189
+ await this.graphql.query(SET_VALUE, {
1190
+ project: projectId,
1191
+ item: itemId,
1192
+ field: field.id,
1193
+ option: option.id
1194
+ });
1195
+ }
1196
+ async ownerId(owner) {
1197
+ return (await this.graphql.query(OWNER_QUERY, { owner })).organization.id;
1198
+ }
1199
+ async readRaw(id) {
1200
+ const n = (await this.graphql.query(BOARD_QUERY, { id })).node;
1201
+ if (!n) throw new Error(`board ${id} not found`);
1202
+ return {
1203
+ summary: toSummary(n),
1204
+ fields: n.fields.nodes.filter((f) => f.id).map((f) => ({
1205
+ id: f.id,
1206
+ name: f.name,
1207
+ dataType: f.dataType,
1208
+ ...f.options ? { options: f.options } : {}
1209
+ })),
1210
+ views: n.views.nodes.map((v) => ({
1211
+ id: v.id,
1212
+ name: v.name,
1213
+ layout: v.layout,
1214
+ filter: v.filter,
1215
+ groupBy: (v.groupByFields?.nodes ?? []).map((g) => g.name)
1216
+ })),
1217
+ rules: n.workflows.nodes.map((w) => ({
1218
+ id: w.id,
1219
+ name: w.name,
1220
+ enabled: w.enabled
1221
+ }))
1222
+ };
1223
+ }
1224
+ async fetchItems(id) {
1225
+ const items = [];
1226
+ let after = null;
1227
+ for (;;) {
1228
+ const page = (await this.graphql.query(ITEMS_QUERY, {
1229
+ id,
1230
+ after
1231
+ })).node.items;
1232
+ for (const n of page.nodes) {
1233
+ const c = n.content;
1234
+ if (!c || !c.repository) continue;
1235
+ const values = {};
1236
+ for (const v of n.fieldValues.nodes) if (v.name && v.field?.name) values[v.field.name] = v.name;
1237
+ items.push({
1238
+ id: n.id,
1239
+ contentId: c.id,
1240
+ repo: c.repository.nameWithOwner,
1241
+ number: c.number,
1242
+ title: c.title,
1243
+ open: c.state === "OPEN",
1244
+ values,
1245
+ blockers: (c.blockedBy?.nodes ?? []).filter((b) => b.state === "OPEN").map((b) => ({
1246
+ repo: b.repository.nameWithOwner,
1247
+ number: b.number
1248
+ }))
1249
+ });
1250
+ }
1251
+ if (!page.pageInfo.hasNextPage) return items;
1252
+ after = page.pageInfo.endCursor;
1253
+ }
1254
+ }
1255
+ keyOf(repo, number) {
1256
+ return repo === this.repo ? `#${number}` : `${repo}#${number}`;
1257
+ }
1258
+ parseKey(key) {
1259
+ const m = /^(?:([^#\s]+))?#?(\d+)$/.exec(key.trim());
1260
+ const hasRepo = key.includes("#") && m?.[1];
1261
+ if (!m) throw new Error(`not an issue key: ${key}`);
1262
+ return {
1263
+ repo: hasRepo ? m[1] : this.repo,
1264
+ number: Number(m[2])
1265
+ };
1266
+ }
1267
+ };
1268
+ // src/sodium.ts
342
1269
  /**
343
1270
  * libsodium sealed-box encryption for GitHub Actions secrets.
344
1271
  *
@@ -369,32 +1296,46 @@ async function encryptSecret(publicKeyBase64, value) {
369
1296
  const ciphertext = sodium.crypto_box_seal(plaintext, publicKey);
370
1297
  return sodium.to_base64(ciphertext, sodium.base64_variants.ORIGINAL);
371
1298
  }
372
- //#endregion
373
- //#region src/capabilities/secrets.ts
1299
+ // src/capabilities/secrets.ts
1300
+ /** The GitHub implementation of the `secrets` capability, covering repository, environment and organization secrets. */
374
1301
  var GitHubSecrets = class {
375
1302
  client;
376
1303
  opts;
1304
+ orgClient;
1305
+ /** Capability key, always `"secrets"`. */
377
1306
  key = "secrets";
1307
+ /** Provider name, always `"github"`. */
378
1308
  providerName = "github";
379
- constructor(client, opts) {
1309
+ /**
1310
+ * `client` handles repo and environment scopes; `orgClient`, when given, handles
1311
+ * the organization scope. They differ when a dedicated org-only token exists:
1312
+ * it can write org secrets but not repo ones, and `github.admin` is the reverse.
1313
+ */
1314
+ constructor(client, opts, orgClient) {
380
1315
  this.client = client;
381
1316
  this.opts = opts;
1317
+ this.orgClient = orgClient;
1318
+ }
1319
+ clientFor(scope) {
1320
+ return scope.kind === "organization" ? this.orgClient ?? this.client : this.client;
382
1321
  }
383
1322
  async listSecrets(scope) {
384
- return this.client.secrets.listSecrets(this.opts.repo, toGHScope(scope));
1323
+ return this.clientFor(scope).secrets.listSecrets(this.opts.repo, toGHScope(scope));
385
1324
  }
386
1325
  async setSecret(scope, name, value) {
387
1326
  const ghScope = toGHScope(scope);
388
- const pk = await this.client.secrets.getPublicKey(this.opts.repo, ghScope);
1327
+ const client = this.clientFor(scope);
1328
+ const pk = await client.secrets.getPublicKey(this.opts.repo, ghScope);
389
1329
  const body = {
390
1330
  encrypted_value: await encryptSecret(pk.key, value),
391
1331
  key_id: pk.key_id
392
1332
  };
393
1333
  if (scope.kind === "organization") body.visibility = "all";
394
- await this.client.secrets.putSecret(this.opts.repo, ghScope, name, body);
1334
+ await client.secrets.putSecret(this.opts.repo, ghScope, name, body);
395
1335
  }
1336
+ /** Deletes the named secret in the given scope. */
396
1337
  async deleteSecret(scope, name) {
397
- await this.client.secrets.deleteSecret(this.opts.repo, toGHScope(scope), name);
1338
+ await this.clientFor(scope).secrets.deleteSecret(this.opts.repo, toGHScope(scope), name);
398
1339
  }
399
1340
  };
400
1341
  function toGHScope(scope) {
@@ -404,8 +1345,46 @@ function toGHScope(scope) {
404
1345
  };
405
1346
  return scope;
406
1347
  }
407
- //#endregion
408
- //#region src/capabilities/labels.ts
1348
+ // src/capabilities/files.ts
1349
+ /** Reads one file; `null` when it does not exist. `version` is the blob sha `writeFile` needs to replace exactly this one. */
1350
+ /** A fine-grained token only reaches the repositories and permissions it was given; say which one is missing. */
1351
+ function noAccess(repo, action, cause) {
1352
+ return new Error(`the token cannot ${action} files in ${repo} (403): give the user-sync token (HOLOCRON_USER_SYNC_TOKEN, or holocron auth set github.user-sync) access to that repository with Contents: ${action === "read" ? "read" : "read and write"}`, { cause });
1353
+ }
1354
+ async function readRepoFile(client, repo, path) {
1355
+ try {
1356
+ const file = await client.git.getContents(repo, path);
1357
+ if (file.encoding !== "base64") throw new Error(`${repo}/${path}: unexpected encoding \`${file.encoding}\``);
1358
+ return {
1359
+ content: Buffer.from(file.content, "base64").toString("utf-8"),
1360
+ version: file.sha
1361
+ };
1362
+ } catch (err) {
1363
+ if (err instanceof ProviderApiError && err.status === 403) throw noAccess(repo, "read", err);
1364
+ if (!(err instanceof ProviderApiError && err.status === 404)) throw err;
1365
+ }
1366
+ try {
1367
+ await client.repos.getRepo(repo);
1368
+ } catch (err) {
1369
+ if (err instanceof ProviderApiError && err.status === 404) throw new Error(`${repo} was not found: it does not exist, or the token cannot see it`, { cause: err });
1370
+ throw err;
1371
+ }
1372
+ return null;
1373
+ }
1374
+ /** Creates or replaces one file in a commit; GitHub refuses (409) a `version` that has since changed. */
1375
+ async function writeRepoFile(client, repo, path, content, opts) {
1376
+ try {
1377
+ await client.git.putContents(repo, path, {
1378
+ message: opts.message,
1379
+ content,
1380
+ ...opts.version ? { sha: opts.version } : {}
1381
+ });
1382
+ } catch (err) {
1383
+ if (err instanceof ProviderApiError && err.status === 403) throw noAccess(repo, "write", err);
1384
+ throw err;
1385
+ }
1386
+ }
1387
+ // src/capabilities/labels.ts
409
1388
  /**
410
1389
  * Idempotently synchronise a repo's labels to the canonical set.
411
1390
  *
@@ -443,14 +1422,202 @@ async function syncLabels(client, repo, canonical, stale) {
443
1422
  }
444
1423
  return `${created} created, ${updated} updated, ${deleted} deleted`;
445
1424
  }
446
- //#endregion
447
- //#region src/capabilities/properties.ts
448
- async function syncProperties(client, repo, values) {
449
- await client.properties.setProperties(repo, values);
1425
+ // src/capabilities/property-fix-hints.ts
1426
+ /** GitHub's wording when a custom property value is not one the organization's definition allows. */
1427
+ const NOT_ALLOWED = /Value '([^']+)' is not allowed for property '([^']+)'/g;
1428
+ /**
1429
+ * What to do about each value GitHub says an organization custom property does not allow, one sentence per property,
1430
+ * read from GitHub's own message so it works even when the organization's definitions cannot be read. The values
1431
+ * belong to the organization's definition, not to the repository, so the fix is to add them there: a repository cannot
1432
+ * make its own value allowed. Empty when GitHub's message names no such value.
1433
+ */
1434
+ function propertyFixHints(githubMessage) {
1435
+ const byProperty = /* @__PURE__ */ new Map();
1436
+ for (const [, value, property] of githubMessage.matchAll(NOT_ALLOWED)) {
1437
+ const values = byProperty.get(property) ?? [];
1438
+ if (!values.includes(value)) values.push(value);
1439
+ byProperty.set(property, values);
1440
+ }
1441
+ return [...byProperty].map(([property, values]) => `add ${values.map((v) => `"${v}"`).join(", ")} to the allowed values of the organization custom property ${property} (the organization's Settings, Custom properties), then run repo setup again`);
1442
+ }
1443
+ // src/capabilities/rejected-properties.ts
1444
+ /** The values `repo setup` sends for `true_false` properties; anything else is rejected. */
1445
+ const BOOLEANS = /* @__PURE__ */ new Set(["true", "false"]);
1446
+ /**
1447
+ * What is wrong with `values` when compared with the organization's property definitions, one sentence per
1448
+ * problem, in the order the properties are given: a property the organization does not define, a value a
1449
+ * `single_select` or `multi_select` property does not allow, or a `true_false` property that is not `true` or
1450
+ * `false`. A `string` or `url` property has nothing to check here. Empty when every value fits its definition.
1451
+ */
1452
+ function rejectedProperties(values, schema) {
1453
+ const byName = new Map(schema.map((property) => [property.property_name, property]));
1454
+ const problems = [];
1455
+ for (const [name, value] of Object.entries(values)) {
1456
+ const definition = byName.get(name);
1457
+ if (!definition) {
1458
+ problems.push(`${name} is not a custom property of the organization`);
1459
+ continue;
1460
+ }
1461
+ const sent = Array.isArray(value) ? value : [value];
1462
+ if (definition.value_type === "true_false") {
1463
+ for (const item of sent.filter((item) => !BOOLEANS.has(item))) problems.push(`${name} is "${item}", but it takes only true or false`);
1464
+ continue;
1465
+ }
1466
+ const allowed = definition.allowed_values ?? [];
1467
+ if (definition.value_type !== "single_select" && definition.value_type !== "multi_select") continue;
1468
+ for (const item of sent.filter((item) => !allowed.includes(item))) problems.push(`${name} has "${item}", which is not one of its allowed values (${allowed.join(", ")})`);
1469
+ }
1470
+ return problems;
1471
+ }
1472
+ // src/capabilities/properties.ts
1473
+ /** GitHub's own message from a 422 body (`{"message": ..., "errors": [...]}`), or the start of the body when it is not JSON. */
1474
+ function githubMessage(details) {
1475
+ const raw = String(details ?? "").trim();
1476
+ try {
1477
+ const body = JSON.parse(raw);
1478
+ const errors = Array.isArray(body.errors) ? body.errors.map((e) => JSON.stringify(e)).join(", ") : "";
1479
+ const message = typeof body.message === "string" ? body.message : raw;
1480
+ return errors ? `${message}: ${errors}` : message;
1481
+ } catch {
1482
+ return raw.slice(0, 300);
1483
+ }
1484
+ }
1485
+ /** The organization's property definitions, or `undefined` when they cannot be read (permission, an older client). */
1486
+ async function orgSchema(client, repo) {
1487
+ try {
1488
+ return await client.properties.orgSchema(repo.split("/")[0]);
1489
+ } catch {
1490
+ return;
1491
+ }
1492
+ }
1493
+ /**
1494
+ * The values `values` holds that the organization's property definitions do not allow, one sentence each, or
1495
+ * `undefined` when the definitions cannot be read (the token lacks the organization's custom properties permission, or
1496
+ * the organization defines none). `client` should be the organization-scoped one when there is one, since reading the
1497
+ * definitions is an organization permission a repository token often lacks. Read-only.
1498
+ */
1499
+ async function checkPropertyValues(client, repo, values) {
1500
+ const schema = await orgSchema(client, repo);
1501
+ return schema ? rejectedProperties(values, schema) : void 0;
1502
+ }
1503
+ /**
1504
+ * Sets the repo's custom properties. When GitHub answers 422 the error says which value it refused and what to do
1505
+ * about it: the values are compared with the organization's property definitions (read-only, with `schemaClient`, the
1506
+ * organization-scoped client when there is one), GitHub's own message is added, and each value GitHub says a property
1507
+ * does not allow gets the fix, which does not need the definitions to be readable. One refused value fails the whole
1508
+ * request, so none of the properties is set.
1509
+ */
1510
+ async function syncProperties(client, repo, values, schemaClient = client) {
1511
+ try {
1512
+ await client.properties.setProperties(repo, values);
1513
+ } catch (err) {
1514
+ if (!(err instanceof ProviderApiError$1) || err.status !== 422) throw err;
1515
+ const problems = await checkPropertyValues(schemaClient, repo, values) ?? [];
1516
+ const said = githubMessage(err.details);
1517
+ const fixes = propertyFixHints(said);
1518
+ throw new Error(`GitHub refused the custom properties (422), so none was set: ${problems.length > 0 ? problems.join("; ") : "no value differs from the organization's definitions, or they could not be read"}. GitHub said: ${said}${fixes.length > 0 ? `. To fix it: ${fixes.join("; ")}` : ""}`, { cause: err });
1519
+ }
450
1520
  return `${Object.keys(values).length} properties set`;
451
1521
  }
452
- //#endregion
453
- //#region src/capabilities/teams.ts
1522
+ /** The values the organization's property `name` allows; `undefined` when it cannot be read, is not defined or takes any value. */
1523
+ async function getOrgPropertyValues(client, repo, name) {
1524
+ return ((await orgSchema(client, repo))?.find((p) => p.property_name === name))?.allowed_values ?? void 0;
1525
+ }
1526
+ /**
1527
+ * Adds the missing `values` to the organization's property `name` and returns them. GitHub replaces the whole
1528
+ * definition on a write, so the current one is read and sent back with the allowed values extended, in their order,
1529
+ * and nothing removed. A write is made only when something is missing.
1530
+ */
1531
+ async function addOrgPropertyValues(client, repo, name, values) {
1532
+ const org = repo.split("/")[0];
1533
+ const current = (await client.properties.orgSchema(org)).find((p) => p.property_name === name);
1534
+ if (!current) throw new Error(`the organization ${org} has no custom property "${name}"; create it first`);
1535
+ if (!current.allowed_values) throw new Error(`the custom property "${name}" takes any value; it has nothing to extend`);
1536
+ const have = new Set(current.allowed_values);
1537
+ const added = [...new Set(values)].filter((v) => !have.has(v));
1538
+ if (added.length === 0) return [];
1539
+ await client.properties.setOrgProperty(org, {
1540
+ ...current,
1541
+ allowed_values: [...current.allowed_values, ...added]
1542
+ });
1543
+ return added;
1544
+ }
1545
+ // src/capabilities/read-repo.ts
1546
+ /** The settings `repo setup` writes, which `GET /repos/{repo}` reports under the same names. */
1547
+ const SETTING_KEYS = [
1548
+ "allow_squash_merge",
1549
+ "allow_merge_commit",
1550
+ "allow_rebase_merge",
1551
+ "allow_auto_merge",
1552
+ "allow_update_branch",
1553
+ "delete_branch_on_merge",
1554
+ "has_issues",
1555
+ "has_discussions",
1556
+ "has_projects",
1557
+ "has_wiki"
1558
+ ];
1559
+ /** The repository's description, homepage, default branch, topics and settings, from one read. */
1560
+ async function readRepoInfo(client, repo) {
1561
+ const data = await client.repos.getRepo(repo);
1562
+ const settings = { default_branch: data.default_branch };
1563
+ for (const key of SETTING_KEYS) {
1564
+ const value = data[key];
1565
+ if (value !== void 0) settings[key] = value;
1566
+ }
1567
+ return {
1568
+ description: data.description ?? null,
1569
+ homepage: data.homepage ?? null,
1570
+ defaultBranch: data.default_branch,
1571
+ topics: data.topics ?? [],
1572
+ settings
1573
+ };
1574
+ }
1575
+ /** A ruleset reduced to what `repo setup` writes: its enforcement, rule types and required status checks. */
1576
+ function toRulesetDetail(data) {
1577
+ const rules = data.rules ?? [];
1578
+ const checks = rules.find((r) => r.type === "required_status_checks")?.parameters?.required_status_checks;
1579
+ return {
1580
+ name: data.name,
1581
+ enforcement: data.enforcement,
1582
+ ruleTypes: rules.map((r) => r.type),
1583
+ requiredChecks: Array.isArray(checks) ? checks.map((c) => String(c.context)) : []
1584
+ };
1585
+ }
1586
+ /** The value, or `undefined` when GitHub refuses the read (permission, plan, feature absent). Other errors still throw. */
1587
+ async function readable(read) {
1588
+ try {
1589
+ return await read();
1590
+ } catch (err) {
1591
+ if (err instanceof ProviderApiError$1) return void 0;
1592
+ throw err;
1593
+ }
1594
+ }
1595
+ /** Which security features are on. One GitHub refuses to report is left out, not reported as off. */
1596
+ async function readSecurity(client, repo) {
1597
+ const [data, alerts, fixes, reporting, codeScanning] = await Promise.all([
1598
+ readable(() => client.repos.getRepo(repo)),
1599
+ readable(() => client.security.vulnerabilityAlertsEnabled(repo)),
1600
+ readable(() => client.security.automatedSecurityFixesEnabled(repo)),
1601
+ readable(() => client.security.privateVulnerabilityReportingEnabled(repo)),
1602
+ readable(() => client.security.codeScanningDefaultSetupState(repo))
1603
+ ]);
1604
+ const analysis = data?.security_and_analysis;
1605
+ const on = (feature) => {
1606
+ const status = analysis?.[feature]?.status;
1607
+ return status === void 0 ? void 0 : status === "enabled";
1608
+ };
1609
+ const found = {
1610
+ vulnerabilityAlerts: alerts,
1611
+ automatedSecurityFixes: fixes,
1612
+ secretScanning: on("secret_scanning"),
1613
+ secretScanningPushProtection: on("secret_scanning_push_protection"),
1614
+ privateVulnerabilityReporting: reporting,
1615
+ codeScanningDefaultSetup: codeScanning === void 0 ? void 0 : codeScanning === "configured"
1616
+ };
1617
+ return Object.fromEntries(Object.entries(found).filter(([, v]) => v !== void 0));
1618
+ }
1619
+ // src/capabilities/teams.ts
1620
+ /** Turns a team entry into slug and permission form; a bare slug gets `push`. */
454
1621
  function normalizeTeamEntry(entry) {
455
1622
  if (typeof entry === "string") return {
456
1623
  slug: entry,
@@ -458,6 +1625,7 @@ function normalizeTeamEntry(entry) {
458
1625
  };
459
1626
  return entry;
460
1627
  }
1628
+ /** Grants each team access to the repo and reports the outcome; throws when every team fails. */
461
1629
  async function syncTeams(client, repo, teams) {
462
1630
  const [org = "", name = ""] = repo.split("/", 2);
463
1631
  const normalized = teams.map(normalizeTeamEntry);
@@ -470,17 +1638,132 @@ async function syncTeams(client, repo, teams) {
470
1638
  }
471
1639
  return `${succeeded} team${succeeded === 1 ? "" : "s"} synced`;
472
1640
  }
473
- //#endregion
474
- //#region src/capabilities/topics.ts
1641
+ // src/capabilities/topics.ts
475
1642
  async function syncTopics(client, repo, topics) {
476
1643
  await client.topics.setTopics(repo, topics);
477
1644
  return `${topics.length} topics set`;
478
1645
  }
479
- //#endregion
480
- //#region src/capabilities/source.ts
1646
+ // src/capabilities/variables.ts
1647
+ /** GitHub's rule for a variable name: letters, digits and underscores, not starting with a digit or `GITHUB_`. */
1648
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
1649
+ /** Longest name GitHub accepts. */
1650
+ const MAX_NAME = 256;
1651
+ function assertNames(names) {
1652
+ for (const name of names) if (!NAME.test(name) || name.length > MAX_NAME || name.toUpperCase().startsWith("GITHUB_")) throw new Error(`invalid variable name ${JSON.stringify(name)}: use letters, digits and underscores (at most ${MAX_NAME}), not starting with a digit or GITHUB_`);
1653
+ }
1654
+ /** GitHub treats variable names as case-insensitive, so every comparison goes through this. */
1655
+ const key = (name) => name.toUpperCase();
1656
+ /**
1657
+ * Bring one scope's variables in line with the declaration: create what is missing, update what differs, leave what
1658
+ * already matches. Variables that exist but are not declared are left alone, or deleted with `prune`, except an
1659
+ * organization variable limited to selected repositories, which this client cannot manage and so is never deleted.
1660
+ * Returns a one-line summary, naming the ones left so drift is visible. In a dry run it only describes the changes.
1661
+ */
1662
+ async function reconcile(client, repo, scope, wanted, opts) {
1663
+ assertNames(wanted.map((w) => w.name));
1664
+ const existing = new Map((await client.variables.listVariables(repo, scope)).map((v) => [key(v.name), v]));
1665
+ const counts = {
1666
+ created: 0,
1667
+ updated: 0,
1668
+ unchanged: 0,
1669
+ deleted: 0
1670
+ };
1671
+ for (const want of wanted) {
1672
+ const have = existing.get(key(want.name));
1673
+ const body = {
1674
+ name: want.name,
1675
+ value: want.value
1676
+ };
1677
+ if (want.visibility) body["visibility"] = want.visibility;
1678
+ if (!have) {
1679
+ if (opts.dryRun) {
1680
+ counts.created++;
1681
+ continue;
1682
+ }
1683
+ try {
1684
+ await client.variables.createVariable(repo, scope, body);
1685
+ counts.created++;
1686
+ continue;
1687
+ } catch (err) {
1688
+ if (!(err instanceof ProviderApiError && (err.status === 409 || err.status === 422))) throw err;
1689
+ }
1690
+ } else if (have.value === want.value && (!want.visibility || have.visibility === want.visibility)) {
1691
+ counts.unchanged++;
1692
+ continue;
1693
+ }
1694
+ if (!opts.dryRun) await client.variables.updateVariable(repo, scope, have?.name ?? want.name, body);
1695
+ counts.updated++;
1696
+ }
1697
+ const declared = new Set(wanted.map((w) => key(w.name)));
1698
+ const undeclared = [...existing.entries()].filter(([k]) => !declared.has(k)).map(([, v]) => v);
1699
+ const unmanaged = undeclared.filter((v) => v.visibility === "selected");
1700
+ if (opts.prune) for (const v of undeclared.filter((u) => u.visibility !== "selected")) {
1701
+ if (!opts.dryRun) await client.variables.deleteVariable(repo, scope, v.name);
1702
+ counts.deleted++;
1703
+ }
1704
+ const parts = opts.dryRun ? [
1705
+ `would create ${counts.created}`,
1706
+ `would update ${counts.updated}`,
1707
+ `${counts.unchanged} unchanged`
1708
+ ] : [
1709
+ `${counts.created} created`,
1710
+ `${counts.updated} updated`,
1711
+ `${counts.unchanged} unchanged`
1712
+ ];
1713
+ if (counts.deleted > 0) parts.push(`${counts.deleted} ${opts.dryRun ? "would be deleted" : "deleted"}`);
1714
+ const left = opts.prune ? unmanaged : undeclared;
1715
+ if (left.length > 0) {
1716
+ const why = opts.prune ? "limited to selected repositories, not managed" : "not declared, left alone";
1717
+ parts.push(`${left.length} ${why}: ${left.map((v) => v.name).join(", ")}`);
1718
+ }
1719
+ return parts.join(", ");
1720
+ }
1721
+ /** Reconcile a repository's Actions variables. */
1722
+ function syncVariables(client, repo, variables, opts = {}) {
1723
+ return reconcile(client, repo, { kind: "repo" }, Object.entries(variables).map(([name, value]) => ({
1724
+ name,
1725
+ value
1726
+ })), {
1727
+ prune: opts.prune === true,
1728
+ dryRun: opts.dryRun === true
1729
+ });
1730
+ }
1731
+ /** Reconcile an organization's Actions variables. `repo` is only the coordinate the client is bound to. */
1732
+ function syncOrgVariables(client, repo, org, variables, opts = {}) {
1733
+ const wanted = Object.entries(variables).map(([name, v]) => ({
1734
+ name,
1735
+ value: v.value,
1736
+ visibility: v.visibility
1737
+ }));
1738
+ return reconcile(client, repo, {
1739
+ kind: "organization",
1740
+ org
1741
+ }, wanted, {
1742
+ prune: opts.prune === true,
1743
+ dryRun: opts.dryRun === true
1744
+ });
1745
+ }
1746
+ // src/capabilities/source.ts
1747
+ function toPullRequest(raw) {
1748
+ return {
1749
+ number: raw.number,
1750
+ title: raw.title,
1751
+ state: raw.state,
1752
+ merged: raw.merged_at !== null,
1753
+ branch: raw.head.ref,
1754
+ headSha: raw.head.sha,
1755
+ url: raw.html_url
1756
+ };
1757
+ }
1758
+ /**
1759
+ * The GitHub implementation of the `source` capability: repo settings, rulesets, branch protection, security
1760
+ * features and local workflow files.
1761
+ */
481
1762
  var GitHubSource = class {
482
1763
  client;
1764
+ /** Capability key, always `"source"`. */
483
1765
  key = "source";
1766
+ /** Provider name, always `"github"`. */
484
1767
  providerName = "github";
485
1768
  owner;
486
1769
  name;
@@ -488,6 +1771,7 @@ var GitHubSource = class {
488
1771
  repoRoot;
489
1772
  workflowDir;
490
1773
  orgClient;
1774
+ userSyncClient;
491
1775
  baseUrl;
492
1776
  fetchImpl;
493
1777
  constructor(client, opts) {
@@ -496,15 +1780,20 @@ var GitHubSource = class {
496
1780
  this.owner = owner;
497
1781
  this.name = name;
498
1782
  this.repo = opts.repo;
499
- this.repoRoot = opts.repoRoot;
500
- this.workflowDir = join(opts.repoRoot, ".github", "workflows");
1783
+ this.repoRoot = findRootSync(opts.repoRoot, ".git", {
1784
+ fallback: "start",
1785
+ realpath: true
1786
+ });
1787
+ this.workflowDir = join(this.repoRoot, ".github", "workflows");
501
1788
  this.orgClient = opts.orgClient;
1789
+ this.userSyncClient = opts.userSyncClient;
502
1790
  this.baseUrl = opts.baseUrl;
503
1791
  this.fetchImpl = opts.fetch;
504
1792
  }
505
1793
  async whoami() {
506
1794
  return { login: (await this.client.user.getCurrentUser()).login };
507
1795
  }
1796
+ /** Returns the repo's owner, name and default branch. */
508
1797
  async getRepo() {
509
1798
  const data = await this.client.repos.getRepo(this.repo);
510
1799
  return {
@@ -513,27 +1802,34 @@ var GitHubSource = class {
513
1802
  defaultBranch: data.default_branch
514
1803
  };
515
1804
  }
1805
+ /** Lists the repo's rulesets. */
516
1806
  async listRulesets() {
517
1807
  return this.client.rulesets.listRulesets(this.repo);
518
1808
  }
1809
+ /** Creates a ruleset from the given payload. */
519
1810
  async createRuleset(payload) {
520
1811
  return this.client.rulesets.createRuleset(this.repo, payload);
521
1812
  }
1813
+ /** Updates the ruleset with the given id from the payload. */
522
1814
  async updateRuleset(id, payload) {
523
1815
  return this.client.rulesets.updateRuleset(this.repo, id, payload);
524
1816
  }
1817
+ /** Updates the repo's settings. */
525
1818
  async updateRepoSettings(settings) {
526
1819
  await this.client.repos.updateRepo(this.repo, settings);
527
1820
  }
528
1821
  async protectBranch(branch, payload) {
529
1822
  await this.client.branches.protectBranch(this.repo, branch, payload);
530
1823
  }
1824
+ /** Enables Dependabot vulnerability alerts. */
531
1825
  async enableVulnerabilityAlerts() {
532
1826
  await this.client.security.enableVulnerabilityAlerts(this.repo);
533
1827
  }
1828
+ /** Enables Dependabot automated security fixes. */
534
1829
  async enableAutomatedSecurityFixes() {
535
1830
  await this.client.security.enableAutomatedSecurityFixes(this.repo);
536
1831
  }
1832
+ /** Enables secret scanning. */
537
1833
  async enableSecretScanning() {
538
1834
  await this.client.security.enableSecretScanning(this.repo);
539
1835
  }
@@ -546,9 +1842,11 @@ var GitHubSource = class {
546
1842
  async enableDependencyGraph() {
547
1843
  await this.client.security.enableDependencyGraph(this.repo);
548
1844
  }
1845
+ /** Enables private vulnerability reporting. */
549
1846
  async enablePrivateVulnerabilityReporting() {
550
1847
  await this.client.security.enablePrivateVulnerabilityReporting(this.repo);
551
1848
  }
1849
+ /** Lists the `.yml` and `.yaml` files in `.github/workflows`, sorted by name; empty when the folder is missing. */
552
1850
  async listWorkflowFiles() {
553
1851
  try {
554
1852
  return (await readdir(this.workflowDir)).filter((e) => e.endsWith(".yml") || e.endsWith(".yaml")).sort();
@@ -557,6 +1855,7 @@ var GitHubSource = class {
557
1855
  throw err;
558
1856
  }
559
1857
  }
1858
+ /** Reads a workflow file's text, or `null` when it does not exist. */
560
1859
  async readWorkflowFile(name) {
561
1860
  try {
562
1861
  return await readFile(join(this.workflowDir, name), "utf8");
@@ -565,10 +1864,12 @@ var GitHubSource = class {
565
1864
  throw err;
566
1865
  }
567
1866
  }
1867
+ /** Writes a workflow file, creating `.github/workflows` first when needed. */
568
1868
  async writeWorkflowFile(name, contents) {
569
1869
  await ensureDir(this.workflowDir);
570
1870
  await writeFile(join(this.workflowDir, name), contents, "utf8");
571
1871
  }
1872
+ /** Removes a workflow file; a file that is already gone is not an error. */
572
1873
  async removeWorkflowFile(name) {
573
1874
  try {
574
1875
  await rm(join(this.workflowDir, name));
@@ -586,14 +1887,83 @@ var GitHubSource = class {
586
1887
  return syncLabels(this.client, this.repo, canonical, stale);
587
1888
  }
588
1889
  async syncProperties(values) {
589
- return syncProperties(this.client, this.repo, values);
1890
+ return syncProperties(this.client, this.repo, values, this.orgClient ?? this.client);
1891
+ }
1892
+ async getOrgPropertyValues(name) {
1893
+ return getOrgPropertyValues(this.orgClient ?? this.client, this.repo, name);
1894
+ }
1895
+ async addOrgPropertyValues(name, values) {
1896
+ return addOrgPropertyValues(this.orgClient ?? this.client, this.repo, name, values);
1897
+ }
1898
+ async checkPropertyValues(values) {
1899
+ return checkPropertyValues(this.orgClient ?? this.client, this.repo, values);
590
1900
  }
591
1901
  async syncTeams(teams) {
592
1902
  return syncTeams(this.orgClient ?? this.client, this.repo, teams);
593
1903
  }
1904
+ async teamMembers(teamSlug, org = this.owner) {
1905
+ return (await (this.orgClient ?? this.client).teams.members(org, teamSlug)).map((m) => ({
1906
+ id: String(m.id),
1907
+ login: m.login
1908
+ }));
1909
+ }
1910
+ async readFile(path, repo = this.repo) {
1911
+ return readRepoFile(this.userSyncClient ?? this.orgClient ?? this.client, repo, path);
1912
+ }
1913
+ async writeFile(path, content, opts) {
1914
+ return writeRepoFile(this.userSyncClient ?? this.orgClient ?? this.client, opts.repo ?? this.repo, path, content, opts);
1915
+ }
594
1916
  async syncTopics(topics) {
595
1917
  return syncTopics(this.client, this.repo, topics);
596
1918
  }
1919
+ async syncVariables(variables, opts) {
1920
+ return syncVariables(this.client, this.repo, variables, opts);
1921
+ }
1922
+ async syncOrgVariables(org, variables, opts) {
1923
+ if (!this.orgClient) throw new Error("organization variables need the org token: set HOLOCRON_ORG_TOKEN or run `holocron auth set github.org <token>`");
1924
+ return syncOrgVariables(this.orgClient, this.repo, org, variables, opts);
1925
+ }
1926
+ async listVariables() {
1927
+ const found = await this.client.variables.listVariables(this.repo, { kind: "repo" });
1928
+ return Object.fromEntries(found.map((v) => [v.name, v.value]));
1929
+ }
1930
+ async listOrgVariables(org) {
1931
+ if (!this.orgClient) throw new MissingTokenError("organization variables need the org token: set HOLOCRON_ORG_TOKEN or run `holocron auth set github.org <token>`");
1932
+ const found = await this.orgClient.variables.listVariables(this.repo, {
1933
+ kind: "organization",
1934
+ org
1935
+ });
1936
+ return Object.fromEntries(found.map((v) => [v.name, {
1937
+ value: v.value,
1938
+ visibility: v.visibility ?? "all"
1939
+ }]));
1940
+ }
1941
+ async getRepoInfo() {
1942
+ return readRepoInfo(this.client, this.repo);
1943
+ }
1944
+ async getProperties() {
1945
+ const found = await this.client.properties.getValues(this.repo);
1946
+ return Object.fromEntries(found.flatMap((p) => p.value === null ? [] : [[p.property_name, p.value]]));
1947
+ }
1948
+ async listLabels() {
1949
+ return (await this.client.labels.listLabels(this.repo)).map((l) => ({
1950
+ name: l.name,
1951
+ color: l.color,
1952
+ description: l.description ?? ""
1953
+ }));
1954
+ }
1955
+ async listTeamAccess() {
1956
+ return (await (this.orgClient ?? this.client).teams.listForRepo(this.repo)).map((t) => ({
1957
+ slug: t.slug,
1958
+ permission: t.permission
1959
+ }));
1960
+ }
1961
+ async getRulesetDetail(id) {
1962
+ return toRulesetDetail(await this.client.rulesets.getRuleset(this.repo, id));
1963
+ }
1964
+ async getSecurity() {
1965
+ return readSecurity(this.client, this.repo);
1966
+ }
597
1967
  async syncDescription(description) {
598
1968
  await this.client.repos.updateRepo(this.repo, { description });
599
1969
  return "description updated";
@@ -603,15 +1973,27 @@ var GitHubSource = class {
603
1973
  return "homepage updated";
604
1974
  }
605
1975
  async getPullRequest(number, repo) {
606
- const raw = await this.client.pulls.getPullRequest(repo ?? this.repo, number);
607
- return {
608
- number: raw.number,
609
- title: raw.title,
610
- state: raw.state,
611
- merged: raw.merged_at !== null,
612
- branch: raw.head.ref,
613
- url: raw.html_url
614
- };
1976
+ return toPullRequest(await this.client.pulls.getPullRequest(repo ?? this.repo, number));
1977
+ }
1978
+ async listPullRequests(state, repo) {
1979
+ return (await this.client.pulls.listPullRequests(repo ?? this.repo, state)).map(toPullRequest);
1980
+ }
1981
+ async listBranches(repo) {
1982
+ return (await this.client.branches.listBranches(repo ?? this.repo)).map((b) => ({
1983
+ name: b.name,
1984
+ sha: b.commit.sha
1985
+ }));
1986
+ }
1987
+ async deleteBranch(name, repo) {
1988
+ try {
1989
+ await this.client.branches.removeBranch(repo ?? this.repo, name);
1990
+ } catch (err) {
1991
+ if (err instanceof ProviderApiError && err.status === 422 && String(err.details).includes("does not exist")) return;
1992
+ throw err;
1993
+ }
1994
+ }
1995
+ async listPullRequestCommits(number, repo) {
1996
+ return (await this.client.pulls.listCommits(repo ?? this.repo, number)).map((commit) => commit.sha);
615
1997
  }
616
1998
  async configurePages(config, token) {
617
1999
  const pagesClient = createGitHubClient$1({
@@ -650,18 +2032,8 @@ async function ensureDir(path) {
650
2032
  throw err;
651
2033
  }
652
2034
  }
653
- //#endregion
654
- //#region src/verify-token.ts
655
- /**
656
- * `verifyToken` — plugin-level export used by `holocron auth set` +
657
- * `holocron auth check`. Hits `GET /user` and translates the response
658
- * into the normalized `VerifyTokenResult` shape.
659
- *
660
- * Kept as a standalone function (not a capability method) so the auth
661
- * command can call it without initializing the full plugin — plugin
662
- * construction requires an already-resolved token, which is exactly
663
- * what we don't have yet at bootstrap time.
664
- */
2035
+ // src/verify-token.ts
2036
+ /** Checks a token against `GET /user` and returns who it belongs to, or why it failed. */
665
2037
  async function verifyToken(token, opts = {}) {
666
2038
  const client = createGitHubClient({
667
2039
  token,
@@ -669,49 +2041,61 @@ async function verifyToken(token, opts = {}) {
669
2041
  fetch: opts.fetch
670
2042
  });
671
2043
  try {
672
- const me = await client.user.getCurrentUser();
2044
+ const { user: me, expiresAt } = await client.user.getCurrentUserWithExpiry();
673
2045
  return {
674
2046
  ok: true,
675
- subject: `user @ ${me.login ?? me.email ?? "unknown"}`
2047
+ subject: `user @ ${me.login ?? me.email ?? "unknown"}`,
2048
+ ...expiresAt ? { expiresAt } : {}
676
2049
  };
677
2050
  } catch (err) {
678
2051
  return {
679
2052
  ok: false,
680
- message: err instanceof Error ? err.message : String(err)
2053
+ message: errorMessage(err)
681
2054
  };
682
2055
  }
683
2056
  }
684
- //#endregion
685
- //#region src/index.ts
686
- function source(ctx, orgClient) {
2057
+ // src/index.ts
2058
+ /** Builds the `source` capability; the optional clients cover org-level and user-sync access. */
2059
+ function source(ctx, orgClient, userSyncClient) {
687
2060
  return new GitHubSource(ctx.client, {
688
2061
  repo: ctx.repo,
689
2062
  repoRoot: ctx.repoRoot,
690
2063
  orgClient,
2064
+ userSyncClient,
691
2065
  baseUrl: ctx.options.baseUrl,
692
2066
  fetch: ctx.options.fetch
693
2067
  });
694
2068
  }
695
- function secrets(ctx) {
696
- return new GitHubSecrets(ctx.client, { repo: ctx.repo });
2069
+ /** Builds the `secrets` capability; the optional client handles organization secrets. */
2070
+ function secrets(ctx, orgClient) {
2071
+ return new GitHubSecrets(ctx.client, { repo: ctx.repo }, orgClient);
697
2072
  }
2073
+ /** Builds the `environments` capability. */
698
2074
  function environments(ctx) {
699
2075
  return new GitHubEnvironments(ctx.client, { repo: ctx.repo });
700
2076
  }
2077
+ /** Builds the `ci` capability. */
701
2078
  function ci(ctx) {
702
2079
  return new GitHubCi(ctx.client, { repo: ctx.repo });
703
2080
  }
2081
+ /** Builds the `issues` capability, passing the lifecycle labels when configured. */
704
2082
  function issues(ctx) {
705
2083
  const opts = { repo: ctx.repo };
706
2084
  if (ctx.options.labels !== void 0) opts.labels = ctx.options.labels;
707
2085
  return new GitHubIssues(ctx.client, opts);
708
2086
  }
2087
+ /** Builds the `projects` capability: GitHub Projects v2 over GraphQL, with items keyed relative to the configured repo. */
2088
+ function projects(ctx) {
2089
+ return new GitHubProjects(ctx.client.graphql, { repo: ctx.repo });
2090
+ }
2091
+ /** Creates the plugin, resolving a token per capability when it is first used. */
709
2092
  function createPlugin(options) {
710
2093
  function makeCtx(resolver) {
2094
+ const token = resolver(options);
711
2095
  return {
712
2096
  options,
713
2097
  client: createGitHubClient$1({
714
- token: resolver(options),
2098
+ token,
715
2099
  baseUrl: options.baseUrl,
716
2100
  fetch: options.fetch
717
2101
  }),
@@ -719,10 +2103,45 @@ function createPlugin(options) {
719
2103
  repoRoot: options.repoRoot ?? process.cwd()
720
2104
  };
721
2105
  }
2106
+ /** A token, or undefined when that feature token is simply not configured. */
2107
+ function tryResolve(resolver) {
2108
+ try {
2109
+ return resolver(options);
2110
+ } catch (err) {
2111
+ if (err instanceof AuthError) return void 0;
2112
+ throw err;
2113
+ }
2114
+ }
2115
+ /**
2116
+ * Organization secrets need an org-resource-owner token (`github.secrets`);
2117
+ * repo and environment secrets need `github.admin`. Each scope prefers its own
2118
+ * token and falls back to the other, so a setup with only one of them keeps
2119
+ * working, and an explicit `--token` serves both. With neither configured this
2120
+ * fails exactly as the admin-token capabilities do.
2121
+ */
2122
+ function makeSecrets() {
2123
+ const secretsToken = tryResolve(resolveSecretsToken);
2124
+ const adminToken = tryResolve(resolveAdminToken);
2125
+ if (!secretsToken && !adminToken) resolveAdminToken(options);
2126
+ const clientFor = (token) => createGitHubClient$1({
2127
+ token,
2128
+ baseUrl: options.baseUrl,
2129
+ fetch: options.fetch
2130
+ });
2131
+ const repoClient = clientFor(adminToken ?? secretsToken);
2132
+ const orgClient = clientFor(secretsToken ?? adminToken);
2133
+ return secrets({
2134
+ options,
2135
+ client: repoClient,
2136
+ repo: options.repo,
2137
+ repoRoot: options.repoRoot ?? process.cwd()
2138
+ }, orgClient);
2139
+ }
722
2140
  function makeOrgClient() {
723
2141
  try {
2142
+ const token = resolveOrgToken(options);
724
2143
  return createGitHubClient$1({
725
- token: resolveOrgToken(options),
2144
+ token,
726
2145
  baseUrl: options.baseUrl,
727
2146
  fetch: options.fetch
728
2147
  });
@@ -730,14 +2149,34 @@ function createPlugin(options) {
730
2149
  return;
731
2150
  }
732
2151
  }
2152
+ /** The token for the user-sync files; undefined when it is not configured, and the org token is used instead. */
2153
+ function makeUserSyncClient() {
2154
+ const token = tryResolve(resolveUserSyncToken);
2155
+ return token ? createGitHubClient$1({
2156
+ token,
2157
+ baseUrl: options.baseUrl,
2158
+ fetch: options.fetch
2159
+ }) : void 0;
2160
+ }
733
2161
  return {
734
2162
  name: "@theholocron/holocron-plugin-github",
2163
+ probes: { connection: connectionProbe({
2164
+ provider: "GitHub",
2165
+ url: options.baseUrl ?? "https://api.github.com",
2166
+ fetch: options.fetch,
2167
+ token: () => resolveReadToken(options),
2168
+ verify: (token) => verifyToken(token, {
2169
+ baseUrl: options.baseUrl,
2170
+ fetch: options.fetch
2171
+ })
2172
+ }) },
735
2173
  capabilities: {
736
- source: () => source(makeCtx(resolveAdminToken), makeOrgClient()),
2174
+ source: () => source(makeCtx(resolveAdminToken), makeOrgClient(), makeUserSyncClient()),
737
2175
  ci: () => ci(makeCtx(resolveReadToken)),
738
- secrets: () => secrets(makeCtx(resolveAdminToken)),
2176
+ secrets: () => makeSecrets(),
739
2177
  environments: () => environments(makeCtx(resolveAdminToken)),
740
- issues: () => issues(makeCtx(resolveIssuesToken))
2178
+ issues: () => issues(makeCtx(resolveIssuesToken)),
2179
+ projects: () => projects(makeCtx(resolveOrgToken))
741
2180
  }
742
2181
  };
743
2182
  }
@@ -746,5 +2185,16 @@ function createPlugin(options) {
746
2185
  * is supplied or the supplied token is rejected.
747
2186
  */
748
2187
  const AUTH_HINT = "generate fine-grained Personal Access Tokens at https://github.com/settings/tokens (one per feature — see docs/tokens.md for required scopes per operation), then run: holocron auth set github.<feature> <PAT>";
749
- //#endregion
750
- export { AUTH_HINT, AuthError, GitHubCi, GitHubEnvironments, GitHubIssues, GitHubSecrets, GitHubSource, ci, createFeatureResolver, createGitHubClient, createPlugin, encryptSecret, environments, issues, normalizeTeamEntry, resolveAdminToken, resolveDeployToken, resolveIssuesToken, resolveOrgToken, resolveReadToken, resolveReleaseToken, resolveSyncToken, secrets, source, syncLabels, syncTeams, verifyToken };
2188
+ /** Every token this plugin takes, for `holocron doctor tokens`. */
2189
+ const tokens = [
2190
+ resolveReadToken,
2191
+ resolveIssuesToken,
2192
+ resolveSyncToken,
2193
+ resolveReleaseToken,
2194
+ resolveAdminToken,
2195
+ resolveSecretsToken,
2196
+ resolveDeployToken,
2197
+ resolveUserSyncToken,
2198
+ resolveOrgToken
2199
+ ].map((resolver) => resolver.token);
2200
+ export { AUTH_HINT, AuthError, GitHubCi, GitHubEnvironments, GitHubIssues, GitHubProjects, GitHubSecrets, GitHubSource, ci, createFeatureResolver, createGitHubClient, createPlugin, encryptSecret, environments, issues, normalizeTeamEntry, projects, resolveAdminToken, resolveDeployToken, resolveIssuesToken, resolveOrgToken, resolveReadToken, resolveReleaseToken, resolveSecretsToken, resolveSyncToken, resolveUserSyncToken, secrets, source, syncLabels, syncTeams, tokens, verifyToken };