@theholocron/holocron-plugin-github 5.0.0-alpha.51 → 5.0.0-alpha.511

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, areaLabelsForFiles, areaLabelsForTitle, connectionProbe, createFeatureResolver, pickByCreation, readKeysLimited, reportProgress, tokenExpectations } 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,750 @@ var GitHubEnvironments = class {
119
151
  }));
120
152
  }
121
153
  };
122
- //#endregion
123
- //#region src/capabilities/issues.ts
154
+ // src/capabilities/issue-field-setter.ts
155
+ /**
156
+ * Sets and clears one organization issue field (Priority, Effort, Start date, Target date) on an issue, for the
157
+ * `issues` capability's `create` and `update` and for `createPrioritySetter()`.
158
+ *
159
+ * The field list is read once per setter. A value is added with `POST`, which leaves the issue's other field values
160
+ * alone (`PUT` replaces all of them, and a multi-select value cannot be sent back with certainty); a value that differs
161
+ * is removed first. A missing field, a missing option or a refusal from GitHub (401, 403, 404, 422) comes back as a
162
+ * `note` for the caller's `dropped` list; a rate limit and every other failure are thrown. Spec
163
+ * `tech-github-issue-priority-field`, #2253, and `tool-work-commands`, #2429.
164
+ *
165
+ * Not verified against the live API: that Effort, Start date and Target date are written the way Priority is.
166
+ */
167
+ /** Whether GitHub refused for a reason about access or setup, which a run reports and goes on from. */
168
+ function fieldRefusal(err) {
169
+ if (!(err instanceof ProviderApiError)) return void 0;
170
+ if (err.status === void 0 || ![
171
+ 401,
172
+ 403,
173
+ 404,
174
+ 422
175
+ ].includes(err.status)) return void 0;
176
+ if (/rate limit/i.test(`${err.message} ${String(err.details)}`)) return void 0;
177
+ return `GitHub refused: ${err.status}`;
178
+ }
179
+ const DATA_TYPE = {
180
+ select: "single_select",
181
+ date: "date"
182
+ };
183
+ /** Makes the setter for the issues of `repo` (`owner/name`); the organization's field list is read on first use and kept. */
184
+ function createFieldSetter(client, repo) {
185
+ const org = repo.split("/")[0];
186
+ let fields;
187
+ const listFields = () => fields ??= client.issueFields.list(org).then((list) => list, (err) => {
188
+ const why = fieldRefusal(err);
189
+ if (why === void 0) throw err;
190
+ return why;
191
+ });
192
+ const label = (target) => `${target.name.toLowerCase()} field`;
193
+ const find = async (target) => {
194
+ const list = await listFields();
195
+ if (typeof list === "string") return { note: `${label(target)} (${list})` };
196
+ const field = list.find((f) => f.name.toLowerCase() === target.name.toLowerCase() && f.data_type === DATA_TYPE[target.type]);
197
+ return field ? { field } : { note: `${label(target)} (${org} has no ${target.name} issue field)` };
198
+ };
199
+ const currentOf = async (number, field, target, flags) => {
200
+ if (flags.isNew) return void 0;
201
+ const found = (await client.issueFields.values(repo, number)).find((v) => v.issue_field_id === field.id);
202
+ if (!found) return void 0;
203
+ return target.type === "date" ? String(found.value).slice(0, 10) : found.single_select_option?.name ?? String(found.value);
204
+ };
205
+ return {
206
+ async set(number, target, flags = {}) {
207
+ if (!target.value) return { changed: false };
208
+ const found = await find(target);
209
+ if ("note" in found) return {
210
+ changed: false,
211
+ note: found.note
212
+ };
213
+ const { field } = found;
214
+ let value = target.value;
215
+ if (target.type === "select") {
216
+ const option = field.options?.find((o) => o.name.toLowerCase() === value.toLowerCase());
217
+ if (!option) return {
218
+ changed: false,
219
+ note: `${label(target)} (no "${value}" option)`
220
+ };
221
+ value = option.name;
222
+ }
223
+ try {
224
+ const current = await currentOf(number, field, target, flags);
225
+ if (current?.toLowerCase() === value.toLowerCase()) return { changed: false };
226
+ if (flags.dryRun) return { changed: true };
227
+ if (current !== void 0) await client.issueFields.deleteValue(repo, number, field.id);
228
+ await client.issueFields.addValues(repo, number, [{
229
+ field_id: field.id,
230
+ value
231
+ }]);
232
+ return { changed: true };
233
+ } catch (err) {
234
+ const why = fieldRefusal(err);
235
+ if (why === void 0) throw err;
236
+ return {
237
+ changed: false,
238
+ note: `${label(target)} (${why})`
239
+ };
240
+ }
241
+ },
242
+ async clear(number, target, flags = {}) {
243
+ if (flags.isNew) return { changed: false };
244
+ const found = await find(target);
245
+ if ("note" in found) return {
246
+ changed: false,
247
+ note: found.note
248
+ };
249
+ try {
250
+ if (await currentOf(number, found.field, target, flags) === void 0) return { changed: false };
251
+ if (flags.dryRun) return { changed: true };
252
+ await client.issueFields.deleteValue(repo, number, found.field.id);
253
+ return { changed: true };
254
+ } catch (err) {
255
+ const why = fieldRefusal(err);
256
+ if (why === void 0) throw err;
257
+ return {
258
+ changed: false,
259
+ note: `${label(target)} (${why})`
260
+ };
261
+ }
262
+ }
263
+ };
264
+ }
265
+ // src/capabilities/issue-kind.ts
266
+ /** The Type name of each kind. */
267
+ const KIND_TYPE_NAMES = {
268
+ bug: "Bug",
269
+ feature: "Feature",
270
+ task: "Task"
271
+ };
272
+ /** The kind each label names where there is no Type. */
273
+ const LABEL_KINDS = {
274
+ bug: "bug",
275
+ enhancement: "feature",
276
+ chore: "task"
277
+ };
278
+ const TYPE_KINDS = new Map(Object.entries(KIND_TYPE_NAMES).map(([kind, name]) => [name.toLowerCase(), kind]));
279
+ /** The kind of an issue: its Type, else the one kind its labels name (two different ones name none). */
280
+ function kindOfIssue(issue) {
281
+ const typed = TYPE_KINDS.get(issue.type?.name?.toLowerCase() ?? "");
282
+ if (typed) return typed;
283
+ const named = new Set(issue.labels.flatMap((l) => LABEL_KINDS[l.name.toLowerCase()] ?? []));
284
+ return named.size === 1 ? [...named][0] : void 0;
285
+ }
286
+ /** Whether the issue's Type is already the kind's. */
287
+ function hasKindType(issue, kind) {
288
+ return issue.type?.name?.toLowerCase() === KIND_TYPE_NAMES[kind].toLowerCase();
289
+ }
290
+ /** Sets the Type of issue `number`; a refusal is returned as a `dropped` line, anything else (a rate limit) is thrown. */
291
+ async function writeKind(client, repo, number, kind) {
292
+ const name = KIND_TYPE_NAMES[kind];
293
+ try {
294
+ await client.issues.updateIssue(repo, number, { type: name });
295
+ return;
296
+ } catch (err) {
297
+ const why = fieldRefusal(err);
298
+ if (why === void 0) throw err;
299
+ return `kind ${name} (${why})`;
300
+ }
301
+ }
302
+ // src/capabilities/issue-priority.ts
303
+ /** The Priority field's option for each level. */
304
+ const PRIORITY_OPTION_NAMES = {
305
+ urgent: "Urgent",
306
+ high: "High",
307
+ medium: "Medium",
308
+ low: "Low"
309
+ };
310
+ /** Makes the Priority setter for the issues of `repo` (`owner/name`). */
311
+ function createPrioritySetter(client, repo) {
312
+ const fields = createFieldSetter(client, repo);
313
+ return { set: (number, level, flags = {}) => !level || level === "none" ? Promise.resolve({ changed: false }) : fields.set(number, {
314
+ name: "Priority",
315
+ type: "select",
316
+ value: PRIORITY_OPTION_NAMES[level]
317
+ }, flags) };
318
+ }
319
+ // src/capabilities/issues-migration.ts
320
+ /**
321
+ * Export and import of GitHub issues for `holocron migrate`.
322
+ *
323
+ * GitHub holds less than a planning tool, so what does not fit is named in each result's `dropped` list rather than
324
+ * lost quietly:
325
+ * - priority is a label (`priority: high`), because on GitHub it lives in a project field, not on the issue;
326
+ * - an import cannot backdate an issue or a comment, and cannot post as someone else, so the original date and
327
+ * author go in the text;
328
+ * - an import does not set parent or blocked-by links (they need GraphQL node ids of issues made in the same run);
329
+ * - an assignee is not mapped (a Linear user is not a GitHub login).
330
+ * - the organization's `Priority` issue field is set from the priority (`issue-priority.ts`), beside the label.
331
+ * A migrated issue ends with `<!-- holocron:migrated-from <url> -->`, which is how a second run finds it.
332
+ */
333
+ const MARKER = /<!-- holocron:migrated-from (\S+) -->/;
334
+ const PRIORITY_LABEL = /^priority\s*[:/-]\s*(urgent|high|medium|low)$/i;
335
+ const LINK_QUERY = `query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) {
336
+ issue(number: $number) { parent { number } blockedBy(first: 50) { nodes { number } } } } }`;
337
+ /** Splits `priority: high` labels from the rest. */
338
+ function splitLabels(names) {
339
+ let priority;
340
+ const labels = [];
341
+ for (const name of names) {
342
+ const match = PRIORITY_LABEL.exec(name);
343
+ if (match) priority = match[1].toLowerCase();
344
+ else labels.push(name);
345
+ }
346
+ return {
347
+ labels,
348
+ ...priority ? { priority } : {}
349
+ };
350
+ }
351
+ function categoryOf(issue) {
352
+ if (issue.state === "closed") return "done";
353
+ const names = issue.labels.map((l) => l.name.toLowerCase());
354
+ if (names.some((n) => n === "status:in-review" || n === "status: in review")) return "in-review";
355
+ if (names.some((n) => n === "status:in-progress" || n === "status: in progress")) return "in-progress";
356
+ return "open";
357
+ }
358
+ /** How many issues an export fetches at once. GitHub's secondary rate limit punishes bursts of requests, not volume. */
359
+ const EXPORT_CONCURRENCY = 4;
360
+ /** Runs `fn` over `items`, at most `limit` at a time, and returns the results in the order of `items`. */
361
+ async function mapLimit(items, limit, fn) {
362
+ const results = new Array(items.length);
363
+ let next = 0;
364
+ const worker = async () => {
365
+ while (next < items.length) {
366
+ const at = next++;
367
+ results[at] = await fn(items[at]);
368
+ }
369
+ };
370
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
371
+ return results;
372
+ }
373
+ /** GitHub's own answer to a burst of requests (403 or 429 naming the secondary limit) becomes a message that says what to do. */
374
+ function explainSecondaryLimit(err) {
375
+ 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.");
376
+ return err;
377
+ }
378
+ /**
379
+ * Reads the issues `selector` names, with their comments, priority label, parent and blockers.
380
+ *
381
+ * With `limit`, only that many survivors of the other filters are read, from the `order` end of the creation order. A
382
+ * list of keys is sorted by issue number (which rises with creation in one repository) before anything is fetched, then
383
+ * fetched a few at a time until enough are kept; a listing already carries `created_at`, so it is cut before the
384
+ * per-issue comment and link requests. `info.matched` receives how many the selection matched before the cut.
385
+ */
386
+ async function exportIssues(client, repo, selector, info = {}) {
387
+ return readIssues(client, repo, selector, info).catch((err) => {
388
+ throw explainSecondaryLimit(err);
389
+ });
390
+ }
391
+ async function readIssues(client, repo, selector, info) {
392
+ const [owner = "", name = ""] = repo.split("/", 2);
393
+ const since = selector.since ? Date.parse(selector.since) : void 0;
394
+ const survives = (i) => !i.pull_request && !(selector.openOnly && i.state === "closed") && (since === void 0 || Date.parse(i.updated_at) >= since);
395
+ const { limit, order = "oldest" } = selector;
396
+ let issues;
397
+ if (selector.keys) {
398
+ const fetch = (k) => client.issues.getIssue(repo, parseNumber(k));
399
+ info.matched = selector.keys.length;
400
+ issues = limit === void 0 ? (await mapLimit(selector.keys, EXPORT_CONCURRENCY, fetch)).filter(survives) : await readKeysLimited({
401
+ keys: selector.keys,
402
+ order,
403
+ limit,
404
+ concurrency: EXPORT_CONCURRENCY,
405
+ fetch,
406
+ keep: survives
407
+ });
408
+ } else {
409
+ let raw;
410
+ if (selector.milestone) {
411
+ const milestone = await findMilestone(client, repo, selector.milestone);
412
+ if (!milestone) throw new Error(`Milestone "${selector.milestone}" not found in ${repo}.`);
413
+ raw = await listAll(client, repo, { milestone: String(milestone.number) });
414
+ } else if (selector.all) raw = await listAll(client, repo, {});
415
+ else throw new Error("export needs keys, a milestone or all");
416
+ issues = raw.filter(survives);
417
+ info.matched = issues.length;
418
+ if (limit !== void 0) issues = pickByCreation(issues, (i) => i.created_at ?? i.updated_at, order, limit);
419
+ }
420
+ const records = [];
421
+ for (const issue of issues) {
422
+ reportProgress(info.onProgress, records.length, issues.length);
423
+ const comments = await client.issues.listComments(repo, issue.number);
424
+ const links = (await client.graphql.query(LINK_QUERY, {
425
+ owner,
426
+ name,
427
+ number: issue.number
428
+ }).catch(() => void 0))?.repository.issue;
429
+ const { labels, priority } = splitLabels(issue.labels.map((l) => l.name));
430
+ const body = issue.body?.replace(MARKER, "").trimEnd();
431
+ const migratedFrom = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
432
+ const kind = kindOfIssue(issue);
433
+ records.push({
434
+ key: `#${issue.number}`,
435
+ url: issue.html_url,
436
+ title: issue.title,
437
+ ...body ? { body } : {},
438
+ statusCategory: categoryOf(issue),
439
+ closed: issue.state === "closed",
440
+ ...priority ? { priority } : {},
441
+ labels: labels.filter((l) => !l.toLowerCase().startsWith("status:")),
442
+ ...kind ? { kind } : {},
443
+ ...issue.assignee ? { assignee: {
444
+ id: issue.assignee.login,
445
+ displayName: issue.assignee.name ?? issue.assignee.login,
446
+ ...issue.assignee.email ? { emailAddress: issue.assignee.email } : {}
447
+ } } : {},
448
+ ...issue.milestone ? { milestone: issue.milestone.title } : {},
449
+ ...links?.parent ? { parent: `#${links.parent.number}` } : {},
450
+ blockedBy: (links?.blockedBy.nodes ?? []).map((n) => `#${n.number}`),
451
+ comments: comments.map((c) => ({
452
+ ...c.user ? { author: c.user.login } : {},
453
+ body: c.body,
454
+ createdAt: c.created_at
455
+ })),
456
+ createdAt: issue.created_at ?? issue.updated_at,
457
+ updatedAt: issue.updated_at,
458
+ ...migratedFrom ? { migratedFrom } : {}
459
+ });
460
+ }
461
+ reportProgress(info.onProgress, records.length, issues.length);
462
+ return records;
463
+ }
464
+ /** Makes the records as issues, skipping any whose source address an earlier run already recorded. */
465
+ async function importIssues(client, repo, records, options = {}) {
466
+ const existing = /* @__PURE__ */ new Map();
467
+ for (const issue of await listAll(client, repo, {})) {
468
+ const url = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
469
+ if (url) existing.set(url, issue.number);
470
+ }
471
+ const priority = createPrioritySetter(client, repo);
472
+ const results = [];
473
+ const tick = () => reportProgress(options.onProgress, results.length, records.length);
474
+ for (const record of records) {
475
+ const found = existing.get(record.url);
476
+ if (found !== void 0) {
477
+ results.push({
478
+ source: record.key,
479
+ key: `#${found}`,
480
+ created: false,
481
+ dropped: []
482
+ });
483
+ tick();
484
+ continue;
485
+ }
486
+ const dropped = droppedFor(record);
487
+ if (options.dryRun) {
488
+ results.push({
489
+ source: record.key,
490
+ created: true,
491
+ dropped
492
+ });
493
+ tick();
494
+ continue;
495
+ }
496
+ const number = await createFromRecord(client, repo, record, options);
497
+ const field = await priority.set(number, record.priority, { isNew: true });
498
+ if (field.note) dropped.push(field.note);
499
+ const kindNote = record.kind ? await writeKind(client, repo, number, record.kind) : void 0;
500
+ if (kindNote) dropped.push(kindNote);
501
+ results.push({
502
+ source: record.key,
503
+ key: `#${number}`,
504
+ created: true,
505
+ dropped
506
+ });
507
+ tick();
508
+ }
509
+ return results;
510
+ }
511
+ /** What GitHub cannot hold of this record, for the report. */
512
+ function droppedFor(record) {
513
+ const dropped = ["createdAt (GitHub sets it; the original date is in the text)"];
514
+ if (record.assignee && !record.assignee.login) dropped.push("assignee (not mapped)");
515
+ if (record.parent) dropped.push("parent (not set on GitHub)");
516
+ if (record.blockedBy.length > 0) dropped.push("blockedBy (not set on GitHub)");
517
+ return dropped;
518
+ }
519
+ /** The labels a record becomes on GitHub: its own, plus `priority: <level>` (GitHub's priority is a label). */
520
+ function labelsFor(record) {
521
+ return [...record.labels, ...record.priority && record.priority !== "none" ? [`priority: ${record.priority}`] : []];
522
+ }
523
+ /** The text a comment gets when it is copied: GitHub cannot post as another author or backdate. */
524
+ function renderComment(comment) {
525
+ return `${comment.author ? `**${comment.author}**` : "Someone"} commented on ${comment.createdAt}:\n\n${comment.body}`;
526
+ }
527
+ /** Makes one issue from a record, with its comments, and closes it when the record is closed; returns its number. */
528
+ async function createFromRecord(client, repo, record, options) {
529
+ const milestoneName = options.milestone ?? record.milestone;
530
+ const milestone = milestoneName ? await ensureMilestone(client, repo, milestoneName) : void 0;
531
+ const labels = labelsFor(record);
532
+ const created = await client.issues.createIssue(repo, {
533
+ title: record.title,
534
+ body: withProvenance(record),
535
+ ...labels.length > 0 ? { labels } : {},
536
+ ...milestone !== void 0 ? { milestone } : {},
537
+ ...record.assignee?.login ? { assignees: [record.assignee.login] } : {}
538
+ });
539
+ for (const comment of record.comments) await client.issues.createComment(repo, created.number, renderComment(comment));
540
+ if (record.closed) await client.issues.updateIssue(repo, created.number, {
541
+ state: "closed",
542
+ state_reason: "completed"
543
+ });
544
+ return created.number;
545
+ }
546
+ /** The text of a migrated issue: the record's body, then where it came from and the marker a second run looks for. */
547
+ function withProvenance(record) {
548
+ return `${record.body ? `${record.body}\n\n` : ""}---\n_Migrated from [${record.key}](${record.url}); created ${record.createdAt}._\n<!-- holocron:migrated-from ${record.url} -->`;
549
+ }
550
+ function parseNumber(key) {
551
+ const n = key.trim().replace(/^.*#/, "");
552
+ if (!/^\d+$/.test(n)) throw new Error(`Invalid GitHub issue key "${key}" — expected #N or N.`);
553
+ return parseInt(n, 10);
554
+ }
555
+ async function listAll(client, repo, extra) {
556
+ const all = [];
557
+ for (let page = 1;; page++) {
558
+ const batch = await client.issues.listIssues(repo, {
559
+ state: "all",
560
+ per_page: 100,
561
+ page,
562
+ ...extra
563
+ });
564
+ all.push(...batch);
565
+ if (batch.length < 100) return all;
566
+ }
567
+ }
568
+ async function findMilestone(client, repo, ref) {
569
+ return (await client.issues.listMilestones(repo, { state: "all" })).find((m) => String(m.number) === ref || m.title.toLowerCase() === ref.toLowerCase());
570
+ }
571
+ async function ensureMilestone(client, repo, title) {
572
+ return (await findMilestone(client, repo, title))?.number ?? (await client.issues.createMilestone(repo, title)).number;
573
+ }
574
+ // src/capabilities/issues-sync.ts
575
+ const COMMENT_HEADER = /^(?:\*\*.*?\*\*|Someone) commented on (\S+?):\n/;
576
+ /** Whether GitHub is asking to be left alone: a 429, or a 403 that says it is a rate limit. */
577
+ function isRateLimited(err) {
578
+ return err instanceof ProviderApiError && (err.status === 429 || err.status === 403 && /rate limit/i.test(`${err.message} ${String(err.details)}`));
579
+ }
580
+ const normalize = (text) => text.replace(/\r\n/g, "\n").trim();
581
+ const sorted = (names) => names.map((n) => n.toLowerCase()).sort().join("\n");
582
+ /** Makes the records missing from the repo and updates the ones an earlier run made. See the file comment. */
583
+ async function syncIssues(client, repo, records, options = {}) {
584
+ const existing = /* @__PURE__ */ new Map();
585
+ for (const issue of await listAll(client, repo, {})) {
586
+ const url = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
587
+ if (url) existing.set(url, issue);
588
+ }
589
+ const priority = createPrioritySetter(client, repo);
590
+ const results = [];
591
+ for (const record of records) try {
592
+ const found = existing.get(record.url);
593
+ results.push(found ? await update(client, repo, found, record, options, priority) : await create(client, repo, record, options, priority));
594
+ reportProgress(options.onProgress, results.length, records.length);
595
+ } catch (err) {
596
+ if (isRateLimited(err)) return results;
597
+ throw err;
598
+ }
599
+ return results;
600
+ }
601
+ async function create(client, repo, record, options, priority) {
602
+ const dropped = droppedFor(record);
603
+ if (options.dryRun) return {
604
+ source: record.key,
605
+ created: true,
606
+ updated: false,
607
+ changes: [],
608
+ dropped
609
+ };
610
+ const number = await createFromRecord(client, repo, record, options);
611
+ const field = await priority.set(number, record.priority, { isNew: true });
612
+ if (field.note) dropped.push(field.note);
613
+ const kindNote = record.kind ? await writeKind(client, repo, number, record.kind) : void 0;
614
+ if (kindNote) dropped.push(kindNote);
615
+ return {
616
+ source: record.key,
617
+ key: `#${number}`,
618
+ created: true,
619
+ updated: false,
620
+ changes: [],
621
+ dropped
622
+ };
623
+ }
624
+ async function update(client, repo, issue, record, options, priority) {
625
+ const patch = {};
626
+ const changes = [];
627
+ if (issue.title !== record.title) {
628
+ patch.title = record.title;
629
+ changes.push("title");
630
+ }
631
+ const body = withProvenance(record);
632
+ if (normalize(issue.body) !== normalize(body)) {
633
+ patch.body = body;
634
+ changes.push("description");
635
+ }
636
+ if (issue.state === "closed" !== record.closed) {
637
+ patch.state = record.closed ? "closed" : "open";
638
+ if (record.closed) patch.state_reason = "completed";
639
+ changes.push("state");
640
+ }
641
+ const current = issue.labels.map((l) => l.name);
642
+ const finalLabels = [...labelsFor(record), ...current.filter((n) => n.toLowerCase().startsWith("status:"))];
643
+ if (sorted(finalLabels) !== sorted(current)) {
644
+ patch.labels = finalLabels;
645
+ changes.push("labels");
646
+ }
647
+ const login = record.assignee?.login;
648
+ if (login && issue.assignee?.login.toLowerCase() !== login.toLowerCase()) {
649
+ patch.assignees = [login];
650
+ changes.push("assignee");
651
+ }
652
+ const field = await priority.set(issue.number, record.priority, { dryRun: options.dryRun });
653
+ if (field.changed) changes.push("priority field");
654
+ const kindWrong = record.kind !== void 0 && !hasKindType(issue, record.kind);
655
+ if (kindWrong) changes.push("kind");
656
+ const kindNote = kindWrong && !options.dryRun ? await writeKind(client, repo, issue.number, record.kind) : void 0;
657
+ const comments = await client.issues.listComments(repo, issue.number);
658
+ const seen = new Set(comments.map((c) => COMMENT_HEADER.exec(c.body)?.[1]));
659
+ const missing = record.comments.filter((c) => !seen.has(c.createdAt));
660
+ if (missing.length > 0) changes.push("comments");
661
+ if (!options.dryRun) {
662
+ if (Object.keys(patch).length > 0) await client.issues.updateIssue(repo, issue.number, patch);
663
+ for (const comment of missing) await client.issues.createComment(repo, issue.number, renderComment(comment));
664
+ }
665
+ return {
666
+ source: record.key,
667
+ key: `#${issue.number}`,
668
+ created: false,
669
+ updated: changes.length > 0,
670
+ changes,
671
+ dropped: [
672
+ ...droppedFor(record),
673
+ ...field.note ? [field.note] : [],
674
+ ...kindNote ? [kindNote] : []
675
+ ]
676
+ };
677
+ }
678
+ // src/capabilities/issues-update.ts
679
+ const KIND_NAMES = {
680
+ bug: "Bug",
681
+ feature: "Feature",
682
+ task: "Task"
683
+ };
684
+ const EFFORT_NAMES = {
685
+ high: "High",
686
+ medium: "Medium",
687
+ low: "Low"
688
+ };
689
+ /** Runs one step; a refusal or a bad key is a `dropped` line, anything else (a rate limit) is thrown. */
690
+ async function guarded(what, out, step) {
691
+ try {
692
+ await step();
693
+ } catch (err) {
694
+ const why = fieldRefusal(err);
695
+ if (why !== void 0) out.dropped.push(`${what} (${why})`);
696
+ else if (!(err instanceof ProviderApiError)) out.dropped.push(`${what} (${err.message})`);
697
+ else throw err;
698
+ }
699
+ }
700
+ const CLEAR_FIELD = {
701
+ priority: {
702
+ name: "Priority",
703
+ type: "select"
704
+ },
705
+ effort: {
706
+ name: "Effort",
707
+ type: "select"
708
+ },
709
+ startDate: {
710
+ name: "Start date",
711
+ type: "date"
712
+ },
713
+ targetDate: {
714
+ name: "Target date",
715
+ type: "date"
716
+ }
717
+ };
718
+ /**
719
+ * Writes the {@link IssueFields} of an issue, and clears and unblocks as `clear` and `unblock` ask. `issue` is the issue
720
+ * as it is now (its numeric id and Type); `isNew` says it was just made, so nothing is read to compare.
721
+ */
722
+ async function applyIssueFields(ctx, issue, input, isNew) {
723
+ const { client, repo } = ctx;
724
+ const fields = ctx.fields ??= createFieldSetter(client, repo);
725
+ const out = {
726
+ changed: [],
727
+ dropped: []
728
+ };
729
+ const flags = { isNew };
730
+ const clear = new Set(input.clear ?? []);
731
+ if (input.kind) {
732
+ const name = KIND_NAMES[input.kind];
733
+ if (issue.type?.name?.toLowerCase() !== name.toLowerCase()) await guarded(`kind ${name}`, out, async () => {
734
+ await client.issues.updateIssue(repo, issue.number, { type: name });
735
+ out.changed.push(`kind: ${name}`);
736
+ });
737
+ } else if (clear.has("kind") && issue.type) await guarded("kind", out, async () => {
738
+ await client.issues.updateIssue(repo, issue.number, { type: null });
739
+ out.changed.push("kind cleared");
740
+ });
741
+ const values = [
742
+ [
743
+ "priority",
744
+ "Priority",
745
+ "select",
746
+ input.priority && input.priority !== "none" ? PRIORITY_OPTION_NAMES[input.priority] : void 0
747
+ ],
748
+ [
749
+ "effort",
750
+ "Effort",
751
+ "select",
752
+ input.effort ? EFFORT_NAMES[input.effort] : void 0
753
+ ],
754
+ [
755
+ "startDate",
756
+ "Start date",
757
+ "date",
758
+ input.startDate
759
+ ],
760
+ [
761
+ "targetDate",
762
+ "Target date",
763
+ "date",
764
+ input.targetDate
765
+ ]
766
+ ];
767
+ for (const [label, name, type, value] of values) {
768
+ if (!value) continue;
769
+ const result = await fields.set(issue.number, {
770
+ name,
771
+ type,
772
+ value
773
+ }, flags);
774
+ if (result.note) out.dropped.push(result.note);
775
+ else if (result.changed) out.changed.push(`${label}: ${value}`);
776
+ }
777
+ for (const key of clear) {
778
+ const target = CLEAR_FIELD[key];
779
+ if (!target) continue;
780
+ const result = await fields.clear(issue.number, target, flags);
781
+ if (result.note) out.dropped.push(result.note);
782
+ else if (result.changed) out.changed.push(`${key} cleared`);
783
+ }
784
+ if (input.parent) {
785
+ const parentKey = input.parent;
786
+ await guarded(`parent ${parentKey}`, out, async () => {
787
+ const parentNumber = ctx.parseKey(parentKey);
788
+ const current = isNew ? null : await client.issues.getParent(repo, issue.number);
789
+ if (current?.number === parentNumber) return;
790
+ await client.issues.addSubIssue(repo, parentNumber, issue.id, current !== null);
791
+ out.changed.push(`parent: ${parentKey}`);
792
+ });
793
+ } else if (clear.has("parent") && !isNew) await guarded("parent", out, async () => {
794
+ const current = await client.issues.getParent(repo, issue.number);
795
+ if (!current) return;
796
+ await client.issues.removeSubIssue(repo, current.number, issue.id);
797
+ out.changed.push("parent cleared");
798
+ });
799
+ const adds = input.blockedBy ?? [];
800
+ const removes = input.unblock ?? [];
801
+ if (adds.length > 0 || removes.length > 0) {
802
+ let blockers;
803
+ const current = async () => blockers ??= isNew ? [] : await client.issues.listBlockedBy(repo, issue.number);
804
+ for (const key of adds) await guarded(`blocked by ${key}`, out, async () => {
805
+ const number = ctx.parseKey(key);
806
+ if ((await current()).some((b) => b.number === number)) return;
807
+ const blocker = await client.issues.getIssue(repo, number);
808
+ await client.issues.addBlockedBy(repo, issue.number, blocker.id);
809
+ out.changed.push(`blocked by: ${key}`);
810
+ });
811
+ for (const key of removes) await guarded(`unblock ${key}`, out, async () => {
812
+ const number = ctx.parseKey(key);
813
+ const blocker = (await current()).find((b) => b.number === number);
814
+ if (!blocker) return;
815
+ await client.issues.removeBlockedBy(repo, issue.number, blocker.id);
816
+ out.changed.push(`unblocked: ${key}`);
817
+ });
818
+ }
819
+ return out;
820
+ }
821
+ const sameSet = (a, b) => a.length === b.length && a.every((x) => b.includes(x));
822
+ /** Changes an issue to match the patch; whatever is already as asked is not written. */
823
+ async function updateGitHubIssue(ctx, key, patch) {
824
+ const { client, repo } = ctx;
825
+ const number = ctx.parseKey(key);
826
+ const issue = await client.issues.getIssue(repo, number);
827
+ const changed = [];
828
+ const clear = new Set(patch.clear ?? []);
829
+ const body = {};
830
+ if (patch.title !== void 0 && patch.title !== issue.title) {
831
+ body.title = patch.title;
832
+ changed.push("title");
833
+ }
834
+ if (patch.body !== void 0 && patch.body !== (issue.body ?? "")) {
835
+ body.body = patch.body;
836
+ changed.push("body");
837
+ }
838
+ if (patch.state && patch.state !== issue.state) {
839
+ body.state = patch.state;
840
+ if (patch.state === "closed") body.state_reason = patch.stateReason ?? "completed";
841
+ changed.push(`state: ${patch.state}`);
842
+ }
843
+ const have = (issue.assignees ?? (issue.assignee ? [issue.assignee] : [])).map((a) => a.login);
844
+ if (patch.assignees?.length) {
845
+ const isMe = (a) => /^@?me$/i.test(a);
846
+ const me = patch.assignees.some(isMe) ? await ctx.myLogin() : void 0;
847
+ const want = [...new Set(patch.assignees.map((a) => isMe(a) && me ? me : a.replace(/^@/, "")))];
848
+ if (!sameSet(want.map((a) => a.toLowerCase()), have.map((a) => a.toLowerCase()))) {
849
+ body.assignees = want;
850
+ changed.push(`assignees: ${want.join(", ")}`);
851
+ }
852
+ } else if (clear.has("assignees") && have.length > 0) {
853
+ body.assignees = [];
854
+ changed.push("assignees cleared");
855
+ }
856
+ if (patch.milestone) {
857
+ const milestone = await ctx.resolveMilestone(patch.milestone);
858
+ if (issue.milestone?.number !== milestone) {
859
+ body.milestone = milestone;
860
+ changed.push(`milestone: ${patch.milestone}`);
861
+ }
862
+ } else if (clear.has("milestone") && issue.milestone) {
863
+ body.milestone = null;
864
+ changed.push("milestone cleared");
865
+ }
866
+ if (Object.keys(body).length > 0) await client.issues.updateIssue(repo, number, body);
867
+ const labels = new Set(issue.labels.map((l) => l.name.toLowerCase()));
868
+ const add = [...new Set(patch.addLabels ?? [])].filter((l) => !labels.has(l.toLowerCase()));
869
+ if (add.length > 0) {
870
+ await client.issues.addLabels(repo, number, add);
871
+ changed.push(`labels added: ${add.join(", ")}`);
872
+ }
873
+ for (const label of new Set(patch.removeLabels ?? [])) {
874
+ if (!labels.has(label.toLowerCase())) continue;
875
+ const exact = issue.labels.find((l) => l.name.toLowerCase() === label.toLowerCase()).name;
876
+ await client.issues.removeLabel(repo, number, exact);
877
+ changed.push(`label removed: ${exact}`);
878
+ }
879
+ const fields = await applyIssueFields(ctx, issue, patch, false);
880
+ const all = [...changed, ...fields.changed];
881
+ return {
882
+ key: `#${number}`,
883
+ changed: all,
884
+ ...fields.dropped.length > 0 ? { dropped: fields.dropped } : {}
885
+ };
886
+ }
887
+ // src/capabilities/issues.ts
888
+ /** Issues read per request when `search` has a `text`; GitHub's largest page. */
889
+ const TEXT_PAGE_SIZE = 100;
890
+ /** Pages `search` reads for a `text` before it stops (the 2000 most recently updated issues). */
891
+ const TEXT_MAX_PAGES = 20;
892
+ /** The GitHub implementation of the `issues` capability, backed by GitHub Issues and status labels. */
124
893
  var GitHubIssues = class {
125
894
  client;
895
+ /** Capability key, always `"issues"`. */
126
896
  key = "issues";
897
+ /** Provider name, always `"github"`. */
127
898
  providerName = "github";
128
899
  owner;
129
900
  repoName;
@@ -145,7 +916,18 @@ var GitHubIssues = class {
145
916
  ...raw.email ? { emailAddress: raw.email } : {}
146
917
  };
147
918
  }
919
+ /**
920
+ * Searches the repo's issues, newest update first, leaving out pull requests.
921
+ *
922
+ * With `filter.text`, the issues are paged (newest update first, 100 a page, at most 20 pages) and compared
923
+ * client-side, without regard to case, until `limit` matches are found or the issues run out. GitHub's issue
924
+ * search (`GET /search/issues`) is deliberately not used: it indexes the words of a body, so punctuation and an
925
+ * HTML comment such as `<!-- holocron:idea notes/a.md -->` cannot be relied on to match, it is limited to 30
926
+ * requests a minute and it is eventually consistent (an issue made a moment ago may be missing). Paging has none
927
+ * of those limits, at the cost of reading up to 20 pages of a very large repository.
928
+ */
148
929
  async search(filter) {
930
+ if (filter.text) return this.searchText(filter, filter.text);
149
931
  const params = {
150
932
  state: filter.openOnly ? "open" : "all",
151
933
  sort: "updated",
@@ -164,17 +946,71 @@ var GitHubIssues = class {
164
946
  assignee: params.assignee
165
947
  })).filter((i) => !i.pull_request).map((i) => this.mapIssue(i));
166
948
  }
949
+ async searchText(filter, text) {
950
+ const needle = text.toLowerCase();
951
+ const limit = filter.limit ?? 50;
952
+ const assignee = filter.assignee === "currentUser" ? (await this.getMyself()).id : filter.assignee || void 0;
953
+ const found = [];
954
+ for (let page = 1; page <= TEXT_MAX_PAGES; page++) {
955
+ const raw = await this.client.issues.listIssues(this.repo, {
956
+ state: filter.openOnly ? "open" : "all",
957
+ sort: "updated",
958
+ direction: "desc",
959
+ per_page: TEXT_PAGE_SIZE,
960
+ page,
961
+ filter: "all",
962
+ ...assignee ? { assignee } : {}
963
+ });
964
+ for (const issue of raw) {
965
+ if (issue.pull_request) continue;
966
+ if (`${issue.title}\n${issue.body ?? ""}`.toLowerCase().includes(needle)) {
967
+ found.push(this.mapIssue(issue));
968
+ if (found.length >= limit) return found;
969
+ }
970
+ }
971
+ if (raw.length < TEXT_PAGE_SIZE) break;
972
+ }
973
+ return found;
974
+ }
975
+ /** Fetches one issue by its key. */
167
976
  async get(key) {
168
977
  const number = parseIssueNumber(key, this.owner, this.repoName);
169
978
  const raw = await this.client.issues.getIssue(this.repo, number);
170
979
  return this.mapIssue(raw);
171
980
  }
981
+ /**
982
+ * Creates an issue and returns its key as `#<number>`; the milestone is resolved from its title. Type, Priority,
983
+ * Effort, the dates, the parent and the blockers are set after the issue exists; what GitHub refuses of them comes
984
+ * back in `dropped`, never as a failure, because the issue is made by then and its key must not be lost.
985
+ */
172
986
  async create(input) {
173
987
  const body = { title: input.summary };
988
+ if (input.assignees?.length) {
989
+ const isMe = (a) => /^@?me$/i.test(a);
990
+ const me = input.assignees.some(isMe) ? (await this.getMyself()).id : void 0;
991
+ body.assignees = [...new Set(input.assignees.map((a) => isMe(a) && me ? me : a.replace(/^@/, "")))];
992
+ }
174
993
  if (input.body) body.body = input.body;
175
994
  if (input.labels?.length) body.labels = input.labels;
176
995
  if (input.milestone) body.milestone = await this.resolveMilestone(input.milestone);
177
- return { key: `#${(await this.client.issues.createIssue(this.repo, body)).number}` };
996
+ const raw = await this.client.issues.createIssue(this.repo, body);
997
+ const key = `#${raw.number}`;
998
+ const fields = await applyIssueFields(this.fieldContext(), raw, input, true).catch((err) => ({
999
+ changed: [],
1000
+ dropped: [`fields (not set: ${err.message})`]
1001
+ }));
1002
+ return {
1003
+ key,
1004
+ ...fields.dropped.length > 0 ? { dropped: fields.dropped } : {}
1005
+ };
1006
+ }
1007
+ /** Changes an issue; see {@link updateGitHubIssue}. */
1008
+ update(key, patch) {
1009
+ return updateGitHubIssue({
1010
+ ...this.fieldContext(),
1011
+ myLogin: async () => (await this.getMyself()).id,
1012
+ resolveMilestone: (ref) => this.resolveMilestone(ref)
1013
+ }, key, patch);
178
1014
  }
179
1015
  async transition(key, slot) {
180
1016
  const number = parseIssueNumber(key, this.owner, this.repoName);
@@ -216,10 +1052,12 @@ var GitHubIssues = class {
216
1052
  via: `label set to ${targetLabel}`
217
1053
  };
218
1054
  }
1055
+ /** Adds a comment to the issue with the given key. */
219
1056
  async comment(key, body) {
220
1057
  const number = parseIssueNumber(key, this.owner, this.repoName);
221
1058
  await this.client.issues.createComment(this.repo, number, body);
222
1059
  }
1060
+ /** Checks the authenticated user, the repo and the label-backed lifecycle slots, and reports what resolves. */
223
1061
  async doctor() {
224
1062
  const me = await this.getMyself();
225
1063
  const repo = await this.client.repos.getRepo(this.repo);
@@ -288,6 +1126,29 @@ var GitHubIssues = class {
288
1126
  lifecycle
289
1127
  };
290
1128
  }
1129
+ /** Reads issues with their comments, priority label, parent and blockers, for `holocron migrate`. */
1130
+ export(selector, info) {
1131
+ return exportIssues(this.client, this.repo, selector, info);
1132
+ }
1133
+ /** Makes the records as issues; one already made by an earlier run is skipped. */
1134
+ import(records, options) {
1135
+ return importIssues(this.client, this.repo, records, options);
1136
+ }
1137
+ /** Like `import`, and it also updates what an earlier import or sync made, for `holocron sync issues`. */
1138
+ sync(records, options) {
1139
+ return syncIssues(this.client, this.repo, records, options);
1140
+ }
1141
+ fieldSetter;
1142
+ /** What the field writers need; the setter is shared so the organization's field list is read once. */
1143
+ fieldContext() {
1144
+ this.fieldSetter ??= createFieldSetter(this.client, this.repo);
1145
+ return {
1146
+ client: this.client,
1147
+ repo: this.repo,
1148
+ parseKey: (k) => parseIssueNumber(k, this.owner, this.repoName),
1149
+ fields: this.fieldSetter
1150
+ };
1151
+ }
291
1152
  async resolveMilestone(ref) {
292
1153
  if (/^\d+$/.test(ref)) return parseInt(ref, 10);
293
1154
  const match = (await this.client.issues.listMilestones(this.repo, { state: "all" })).find((m) => m.title.toLowerCase() === ref.toLowerCase());
@@ -337,150 +1198,1393 @@ function parseIssueNumber(key, owner, repoName) {
337
1198
  if (!/^\d+$/.test(num)) throw new Error(`Invalid GitHub issue key "${key}" — expected #N or N.`);
338
1199
  return parseInt(num, 10);
339
1200
  }
340
- //#endregion
341
- //#region src/sodium.ts
342
1201
  /**
343
- * libsodium sealed-box encryption for GitHub Actions secrets.
344
- *
345
- * GitHub stores Actions / Codespaces / Dependabot secrets encrypted
346
- * with a curve25519 public key (returned by the `/actions/secrets/public-key`
347
- * endpoint). Callers fetch that key, encrypt the plaintext value with
348
- * `crypto_box_seal`, then PUT the base64-encoded ciphertext + `key_id`.
349
- *
350
- * Reference: https://docs.github.com/en/rest/actions/secrets#create-or-update-a-repository-secret
351
- *
352
- * **Why createRequire?** `libsodium-wrappers@0.7.x` ships a broken
353
- * ESM bundle — the `dist/modules-esm/libsodium-wrappers.mjs` entry
354
- * imports a sibling `libsodium.mjs` that isn't included in the npm
355
- * tarball. Native `import` against the package therefore fails.
356
- * `createRequire` routes through Node's CJS resolver, which honors
357
- * the `"require"` condition in the package's exports map and loads
358
- * the self-contained CJS bundle instead. Same API, working module.
1202
+ * One issue's closing pull requests and the aggregate check on each one's newest commit. It is its own small query,
1203
+ * never part of the board's items query: nested under `items(first: 100)` it multiplies past GitHub's resource limit.
359
1204
  */
360
- const sodium = createRequire(import.meta.url)("libsodium-wrappers");
1205
+ const CLOSING_QUERY = `query($id: ID!) { node(id: $id) { ... on Issue {
1206
+ closedByPullRequestsReferences(first: 5, includeClosedPrs: true) { nodes {
1207
+ number state isDraft repository { nameWithOwner }
1208
+ commits(last: 1) { nodes { commit { checkSuites(first: 30) { nodes {
1209
+ checkRuns(first: 5, filterBy: { checkName: "ci / Required checks" }) { nodes { databaseId status conclusion startedAt } }
1210
+ } } } } }
1211
+ } }
1212
+ } } }`;
1213
+ const FAILED$1 = /* @__PURE__ */ new Set([
1214
+ "FAILURE",
1215
+ "TIMED_OUT",
1216
+ "STARTUP_FAILURE",
1217
+ "ACTION_REQUIRED",
1218
+ "STALE"
1219
+ ]);
361
1220
  /**
362
- * Encrypt `value` for the given GitHub-provided base64 public key.
363
- * Returns the base64 ciphertext to send as `encrypted_value`.
1221
+ * The state of the aggregate check from the runs of that name on one commit. Only the newest run counts (latest
1222
+ * `startedAt`, then id), so a cancelled first batch or a re-run that went green does not hold the verdict red. A run
1223
+ * that is not finished, or that was cancelled, is `pending`; one with no verdict (neutral, skipped) or none posted is `none`.
364
1224
  */
365
- async function encryptSecret(publicKeyBase64, value) {
366
- await sodium.ready;
367
- const publicKey = sodium.from_base64(publicKeyBase64, sodium.base64_variants.ORIGINAL);
368
- const plaintext = sodium.from_string(value);
369
- const ciphertext = sodium.crypto_box_seal(plaintext, publicKey);
370
- return sodium.to_base64(ciphertext, sodium.base64_variants.ORIGINAL);
1225
+ function aggregateChecks(runs) {
1226
+ const newest = [...runs].sort((a, b) => (b.startedAt ?? "").localeCompare(a.startedAt ?? "") || b.databaseId - a.databaseId)[0];
1227
+ if (!newest) return "none";
1228
+ if (newest.status !== "COMPLETED") return "pending";
1229
+ if (newest.conclusion === "SUCCESS") return "success";
1230
+ if (newest.conclusion && FAILED$1.has(newest.conclusion)) return "failure";
1231
+ if (newest.conclusion === "CANCELLED") return "pending";
1232
+ return "none";
371
1233
  }
372
- //#endregion
373
- //#region src/capabilities/secrets.ts
374
- var GitHubSecrets = class {
375
- client;
376
- opts;
377
- key = "secrets";
378
- providerName = "github";
379
- constructor(client, opts) {
380
- this.client = client;
381
- this.opts = opts;
382
- }
383
- async listSecrets(scope) {
384
- return this.client.secrets.listSecrets(this.opts.repo, toGHScope(scope));
385
- }
386
- async setSecret(scope, name, value) {
387
- const ghScope = toGHScope(scope);
388
- const pk = await this.client.secrets.getPublicKey(this.opts.repo, ghScope);
389
- const body = {
390
- encrypted_value: await encryptSecret(pk.key, value),
391
- key_id: pk.key_id
1234
+ /** The neutral pull requests an issue is closed by; only an open one has its checks read, the others are `none`. */
1235
+ function toBoardPullRequests(nodes, keyOf) {
1236
+ return nodes.map((pr) => {
1237
+ const state = pr.state === "OPEN" ? "open" : pr.state === "MERGED" ? "merged" : "closed";
1238
+ const runs = (pr.commits?.nodes ?? []).flatMap((c) => c.commit.checkSuites.nodes.flatMap((suite) => suite.checkRuns.nodes));
1239
+ return {
1240
+ key: keyOf(pr.repository.nameWithOwner, pr.number),
1241
+ state,
1242
+ draft: pr.isDraft,
1243
+ checks: state === "open" ? aggregateChecks(runs) : "none"
392
1244
  };
393
- if (scope.kind === "organization") body.visibility = "all";
394
- await this.client.secrets.putSecret(this.opts.repo, ghScope, name, body);
395
- }
396
- async deleteSecret(scope, name) {
397
- await this.client.secrets.deleteSecret(this.opts.repo, toGHScope(scope), name);
398
- }
399
- };
400
- function toGHScope(scope) {
401
- if (scope.kind === "organization") return {
402
- kind: "organization",
403
- org: scope.name
404
- };
405
- return scope;
1245
+ });
406
1246
  }
407
- //#endregion
408
- //#region src/capabilities/labels.ts
409
1247
  /**
410
- * Idempotently synchronise a repo's labels to the canonical set.
411
- *
412
- * - Creates labels that are missing.
413
- * - PATCHes labels whose color or description has drifted.
414
- * - DELETEs labels listed in `stale`.
415
- * - Leaves unrecognised labels that aren't in `stale` untouched.
1248
+ * Reads the closing pull requests of each issue (by node id) with one small query per issue, a few at a time. A query
1249
+ * that fails is that issue's `problem` and nothing else: the others are read, and the caller leaves the failed one's
1250
+ * pull-request rules unapplied.
416
1251
  */
417
- async function syncLabels(client, repo, canonical, stale) {
418
- const existing = await client.labels.listLabels(repo);
419
- const existingMap = new Map(existing.map((l) => [l.name.toLowerCase(), l]));
420
- let created = 0;
421
- let updated = 0;
422
- let deleted = 0;
423
- for (const label of canonical) {
424
- const current = existingMap.get(label.name);
425
- if (!current) {
426
- await client.labels.createLabel(repo, {
427
- name: label.name,
428
- color: label.color,
429
- description: label.description
430
- });
431
- created++;
432
- } else if (current.color !== label.color || (current.description ?? "") !== label.description) {
433
- await client.labels.updateLabel(repo, label.name, {
434
- color: label.color,
435
- description: label.description
436
- });
437
- updated++;
1252
+ async function readClosingPullRequests(graphql, contentIds, keyOf) {
1253
+ const results = /* @__PURE__ */ new Map();
1254
+ let next = 0;
1255
+ const worker = async () => {
1256
+ for (let i = next++; i < contentIds.length; i = next++) {
1257
+ const id = contentIds[i];
1258
+ try {
1259
+ const nodes = (await graphql.query(CLOSING_QUERY, { id })).node?.closedByPullRequestsReferences?.nodes;
1260
+ results.set(id, nodes ? { pullRequests: toBoardPullRequests(nodes, keyOf) } : { problem: "GitHub returned no pull request list" });
1261
+ } catch (err) {
1262
+ results.set(id, { problem: err instanceof Error ? err.message : String(err) });
1263
+ }
1264
+ }
1265
+ };
1266
+ await Promise.all(Array.from({ length: Math.min(4, contentIds.length) }, worker));
1267
+ return results;
1268
+ }
1269
+ // src/capabilities/projects.ts
1270
+ /** The name of the single select field that holds an item's status. */
1271
+ const STATUS_FIELD = "Status";
1272
+ /** The name of the field `move` carries over besides the status. */
1273
+ const PRIORITY_FIELD = "Priority";
1274
+ const P_LEVELS = {
1275
+ p0: "urgent",
1276
+ p1: "high",
1277
+ p2: "medium",
1278
+ p3: "low"
1279
+ };
1280
+ /** The neutral priority a `Priority` option stands for, by its name; undefined for a name that is not one of them. */
1281
+ function priorityOf(value) {
1282
+ const name = value?.trim().toLowerCase();
1283
+ if (name === "urgent" || name === "high" || name === "medium" || name === "low") return name;
1284
+ return name ? P_LEVELS[name] : void 0;
1285
+ }
1286
+ const PROJECT_FIELDS = "id number title closed url";
1287
+ const BOARD_QUERY = `query($id: ID!) { node(id: $id) { ... on ProjectV2 {
1288
+ ${PROJECT_FIELDS}
1289
+ fields(first: 100) { nodes {
1290
+ ... on ProjectV2FieldCommon { id name dataType }
1291
+ ... on ProjectV2SingleSelectField { options { id name color description } }
1292
+ } }
1293
+ views(first: 50) { nodes { id name layout filter groupByFields(first: 5) { nodes { ... on ProjectV2FieldCommon { name } } } } }
1294
+ workflows(first: 50) { nodes { id name enabled } }
1295
+ } } }`;
1296
+ const ITEMS_QUERY = `query($id: ID!, $after: String) { node(id: $id) { ... on ProjectV2 {
1297
+ items(first: 100, after: $after) {
1298
+ pageInfo { hasNextPage endCursor }
1299
+ nodes {
1300
+ id
1301
+ fieldValues(first: 30) { nodes { ... on ProjectV2ItemFieldSingleSelectValue { name field { ... on ProjectV2FieldCommon { name } } } } }
1302
+ content {
1303
+ __typename
1304
+ ... on Issue { id number title state repository { nameWithOwner } blockedBy(first: 50) { nodes { number state repository { nameWithOwner } } } }
1305
+ ... on PullRequest { id number title state repository { nameWithOwner } }
1306
+ }
438
1307
  }
439
1308
  }
440
- for (const staleName of stale) if (existingMap.has(staleName)) {
441
- await client.labels.deleteLabel(repo, staleName);
442
- deleted++;
443
- }
444
- return `${created} created, ${updated} updated, ${deleted} deleted`;
1309
+ } } }`;
1310
+ const LIST_QUERY = `query($owner: String!, $after: String) { organization(login: $owner) { id projectsV2(first: 100, after: $after) {
1311
+ pageInfo { hasNextPage endCursor }
1312
+ nodes { ${PROJECT_FIELDS} }
1313
+ } } }`;
1314
+ const OWNER_QUERY = "query($owner: String!) { organization(login: $owner) { id } }";
1315
+ const SET_VALUE = `mutation($project: ID!, $item: ID!, $field: ID!, $option: String!) {
1316
+ updateProjectV2ItemFieldValue(input: { projectId: $project, itemId: $item, fieldId: $field, value: { singleSelectOptionId: $option } }) { projectV2Item { id } }
1317
+ }`;
1318
+ const UPDATE_OPTIONS = `mutation($field: ID!, $options: [ProjectV2SingleSelectFieldOptionInput!]!) {
1319
+ updateProjectV2Field(input: { fieldId: $field, singleSelectOptions: $options }) { projectV2Field { ... on ProjectV2SingleSelectField { id } } }
1320
+ }`;
1321
+ const DATA_TYPES = {
1322
+ single_select: "SINGLE_SELECT",
1323
+ text: "TEXT",
1324
+ number: "NUMBER",
1325
+ date: "DATE",
1326
+ iteration: "ITERATION"
1327
+ };
1328
+ function fieldTypeOf(dataType) {
1329
+ return Object.keys(DATA_TYPES).find((t) => DATA_TYPES[t] === dataType);
445
1330
  }
446
- //#endregion
447
- //#region src/capabilities/properties.ts
448
- async function syncProperties(client, repo, values) {
449
- await client.properties.setProperties(repo, values);
450
- return `${Object.keys(values).length} properties set`;
1331
+ function toSummary(n) {
1332
+ return {
1333
+ id: n.id,
1334
+ number: n.number,
1335
+ name: n.title,
1336
+ url: n.url,
1337
+ closed: n.closed
1338
+ };
451
1339
  }
452
- //#endregion
453
- //#region src/capabilities/teams.ts
454
- function normalizeTeamEntry(entry) {
455
- if (typeof entry === "string") return {
456
- slug: entry,
457
- permission: "push"
1340
+ function toOptionInput(o) {
1341
+ return {
1342
+ ...o.id ? { id: o.id } : {},
1343
+ name: o.name,
1344
+ color: (o.color ?? "GRAY").toUpperCase(),
1345
+ description: o.description ?? ""
458
1346
  };
459
- return entry;
460
1347
  }
461
- async function syncTeams(client, repo, teams) {
462
- const [org = "", name = ""] = repo.split("/", 2);
463
- const normalized = teams.map(normalizeTeamEntry);
464
- const results = await Promise.allSettled(normalized.map(({ slug, permission }) => client.teams.addRepo(org, slug, org, name, permission)));
465
- const succeeded = results.filter((r) => r.status === "fulfilled").length;
466
- const failedSlugs = normalized.filter((_, i) => results[i]?.status === "rejected").map(({ slug }) => slug);
467
- if (failedSlugs.length > 0) {
468
- if (succeeded === 0) throw new Error(`all teams failed: ${failedSlugs.join(", ")}`);
469
- return `${succeeded} synced, failed: ${failedSlugs.join(", ")}`;
1348
+ /** The GitHub implementation of the `projects` capability, backed by Projects v2. */
1349
+ var GitHubProjects = class {
1350
+ graphql;
1351
+ /** Capability key, always `"projects"`. */
1352
+ key = "projects";
1353
+ /** Provider name, always `"github"`. */
1354
+ providerName = "github";
1355
+ repo;
1356
+ constructor(graphql, opts) {
1357
+ this.graphql = graphql;
1358
+ this.repo = opts.repo;
1359
+ }
1360
+ /** Every board of the organization, open and closed. */
1361
+ async list(owner) {
1362
+ const boards = [];
1363
+ let after = null;
1364
+ for (;;) {
1365
+ const page = (await this.graphql.query(LIST_QUERY, {
1366
+ owner,
1367
+ after
1368
+ })).organization.projectsV2;
1369
+ boards.push(...page.nodes.map(toSummary));
1370
+ if (!page.pageInfo.hasNextPage) return boards;
1371
+ after = page.pageInfo.endCursor;
1372
+ }
1373
+ }
1374
+ /** The open board with exactly this name. */
1375
+ async find(owner, name) {
1376
+ return (await this.list(owner)).find((b) => !b.closed && b.name === name);
1377
+ }
1378
+ /**
1379
+ * Makes a board. With `template.source` naming an open board it is copied (fields, options, views and automation
1380
+ * rules, no items); otherwise the board is created and brought in line with the template.
1381
+ */
1382
+ async create(owner, name, template) {
1383
+ const ownerId = await this.ownerId(owner);
1384
+ const source = template.source ? await this.find(owner, template.source) : void 0;
1385
+ if (source) return toSummary((await this.graphql.query(`mutation($project: ID!, $owner: ID!, $title: String!) {
1386
+ copyProjectV2(input: { projectId: $project, ownerId: $owner, title: $title, includeDraftIssues: false }) { projectV2 { ${PROJECT_FIELDS} } }
1387
+ }`, {
1388
+ project: source.id,
1389
+ owner: ownerId,
1390
+ title: name
1391
+ })).copyProjectV2.projectV2);
1392
+ const board = toSummary((await this.graphql.query(`mutation($owner: ID!, $title: String!) {
1393
+ createProjectV2(input: { ownerId: $owner, title: $title }) { projectV2 { ${PROJECT_FIELDS} } }
1394
+ }`, {
1395
+ owner: ownerId,
1396
+ title: name
1397
+ })).createProjectV2.projectV2);
1398
+ await this.ensure(owner, board, template);
1399
+ return board;
1400
+ }
1401
+ /** Closes the board; `updateProjectV2` with `closed: true` is the only way, and reversible. */
1402
+ async close(_owner, board) {
1403
+ await this.graphql.query(`mutation($project: ID!) { updateProjectV2(input: { projectId: $project, closed: true }) { projectV2 { id } } }`, { project: board.id });
1404
+ }
1405
+ /** The live board: statuses, other fields, views and automation rules. */
1406
+ async read(_owner, board) {
1407
+ const raw = await this.readRaw(board.id);
1408
+ const status = raw.fields.find((f) => f.name === STATUS_FIELD);
1409
+ const fields = [];
1410
+ for (const f of raw.fields) {
1411
+ const type = fieldTypeOf(f.dataType);
1412
+ if (!type || f.name === STATUS_FIELD) continue;
1413
+ fields.push({
1414
+ name: f.name,
1415
+ type,
1416
+ ...f.options ? { options: f.options.map((o) => o.name) } : {}
1417
+ });
1418
+ }
1419
+ const views = [];
1420
+ for (const v of raw.views) {
1421
+ const layout = v.layout === "BOARD_LAYOUT" ? "board" : v.layout === "TABLE_LAYOUT" ? "table" : void 0;
1422
+ if (!layout) continue;
1423
+ views.push({
1424
+ name: v.name,
1425
+ layout,
1426
+ ...v.filter ? { filter: v.filter } : {},
1427
+ ...v.groupBy[0] ? { groupBy: v.groupBy[0] } : {}
1428
+ });
1429
+ }
1430
+ return {
1431
+ board: raw.summary,
1432
+ statuses: (status?.options ?? []).map((o) => o.name),
1433
+ fields,
1434
+ views,
1435
+ rules: raw.rules.map(({ name, enabled }) => ({
1436
+ name,
1437
+ enabled
1438
+ }))
1439
+ };
1440
+ }
1441
+ /**
1442
+ * Brings the board in line with the template. Never deletes a field, option or view, and never sends an option
1443
+ * list without ids. Stops (throws) when the status field cannot be read.
1444
+ */
1445
+ async ensure(_owner, board, template) {
1446
+ const raw = await this.readRaw(board.id);
1447
+ const status = raw.fields.find((f) => f.name === STATUS_FIELD && f.options);
1448
+ 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`);
1449
+ const changes = [];
1450
+ const todos = [];
1451
+ const statusChanges = await this.ensureOptions(board, status, template.statuses.map((s) => ({
1452
+ name: s.name,
1453
+ color: s.color,
1454
+ description: s.description
1455
+ })));
1456
+ changes.push(...statusChanges.map((c) => `status ${c}`));
1457
+ for (const want of template.fields) {
1458
+ const have = raw.fields.find((f) => f.name === want.name);
1459
+ if (!have) {
1460
+ await this.createField(board.id, want);
1461
+ changes.push(`field ${want.name} created`);
1462
+ continue;
1463
+ }
1464
+ if (fieldTypeOf(have.dataType) !== want.type) {
1465
+ todos.push(`field "${want.name}" is ${have.dataType} but the template says ${want.type}; change it by hand`);
1466
+ continue;
1467
+ }
1468
+ if (want.type === "single_select" && have.options && want.options) {
1469
+ const diff = await this.ensureOptions(board, have, want.options.map((name) => ({ name })));
1470
+ changes.push(...diff.map((c) => `field ${want.name} option ${c}`));
1471
+ }
1472
+ }
1473
+ for (const want of template.views) {
1474
+ const have = raw.views.find((v) => v.name === want.name);
1475
+ const layout = want.layout === "board" ? "BOARD_LAYOUT" : "TABLE_LAYOUT";
1476
+ let viewId = have?.id;
1477
+ if (!viewId) {
1478
+ viewId = await this.createView(board.id, want.name, layout);
1479
+ changes.push(`view ${want.name} created`);
1480
+ } else if (have && have.layout !== layout) {
1481
+ await this.updateView(viewId, { layout });
1482
+ changes.push(`view ${want.name} layout set to ${want.layout}`);
1483
+ }
1484
+ if (want.filter !== void 0 && want.filter !== (have?.filter ?? "")) {
1485
+ await this.updateView(viewId, { filter: want.filter });
1486
+ changes.push(`view ${want.name} filter set`);
1487
+ }
1488
+ 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`);
1489
+ }
1490
+ for (const rule of template.rules ?? []) {
1491
+ const have = raw.rules.find((r) => r.name === rule);
1492
+ if (!have) todos.push(`create the automation rule "${rule}"; the API cannot create one`);
1493
+ else if (!have.enabled) todos.push(`turn on the automation rule "${rule}"; the API cannot switch one`);
1494
+ }
1495
+ return {
1496
+ created: false,
1497
+ changes,
1498
+ todos
1499
+ };
1500
+ }
1501
+ /**
1502
+ * Makes a single select field hold the wanted options in order, every existing one sent with its id. Options the
1503
+ * template does not mention stay, after the wanted ones. Returns what changed (`Blocked added`, `order set`).
1504
+ */
1505
+ async ensureOptions(board, field, wanted) {
1506
+ /* v8 ignore next -- every caller passes a field it found with options; the fallback only satisfies the type */
1507
+ const existing = field.options ?? [];
1508
+ const next = [];
1509
+ const changes = [];
1510
+ for (const w of wanted) {
1511
+ const have = existing.find((o) => o.name === w.name);
1512
+ if (have) {
1513
+ next.push({
1514
+ id: have.id,
1515
+ name: have.name,
1516
+ color: (w.color ?? have.color).toUpperCase(),
1517
+ description: w.description ?? have.description
1518
+ });
1519
+ if (next[next.length - 1].color !== have.color || next[next.length - 1].description !== have.description) changes.push(`${have.name} updated`);
1520
+ } else {
1521
+ next.push({
1522
+ name: w.name,
1523
+ color: (w.color ?? "GRAY").toUpperCase(),
1524
+ description: w.description ?? ""
1525
+ });
1526
+ changes.push(`${w.name} added`);
1527
+ }
1528
+ }
1529
+ for (const have of existing) if (!next.some((n) => n.id === have.id)) next.push({ ...have });
1530
+ const sameOrder = next.length === existing.length && next.every((n, i) => n.id === existing[i]?.id);
1531
+ if (changes.length === 0 && sameOrder) return [];
1532
+ if (sameOrder === false && !changes.some((c) => c.endsWith("added"))) changes.push("order set");
1533
+ const before = await this.fetchItems(board.id);
1534
+ const snapshot = /* @__PURE__ */ new Map();
1535
+ for (const item of before) {
1536
+ const value = item.values[field.name];
1537
+ if (value) snapshot.set(item.id, value);
1538
+ }
1539
+ await this.graphql.query(UPDATE_OPTIONS, {
1540
+ field: field.id,
1541
+ options: next.map(toOptionInput)
1542
+ });
1543
+ const afterField = (await this.readRaw(board.id)).fields.find((f) => f.id === field.id);
1544
+ const afterItems = await this.fetchItems(board.id);
1545
+ const afterValues = new Map(afterItems.map((i) => [i.id, i.values[field.name]]));
1546
+ const lost = [...snapshot].filter(([itemId]) => !afterValues.get(itemId));
1547
+ if (lost.length > 0) {
1548
+ let restored = 0;
1549
+ for (const [itemId, name] of lost) {
1550
+ const option = afterField?.options?.find((o) => o.name === name);
1551
+ if (!option) continue;
1552
+ await this.graphql.query(SET_VALUE, {
1553
+ project: board.id,
1554
+ item: itemId,
1555
+ field: field.id,
1556
+ option: option.id
1557
+ });
1558
+ restored++;
1559
+ }
1560
+ throw new Error(`updating "${field.name}" on board "${board.name}" blanked ${lost.length} item value(s); wrote ${restored} back by option name`);
1561
+ }
1562
+ return changes;
1563
+ }
1564
+ async createField(projectId, want) {
1565
+ await this.graphql.query(`mutation($project: ID!, $name: String!, $type: ProjectV2CustomFieldType!, $options: [ProjectV2SingleSelectFieldOptionInput!]) {
1566
+ createProjectV2Field(input: { projectId: $project, name: $name, dataType: $type, singleSelectOptions: $options }) { projectV2Field { ... on ProjectV2SingleSelectField { id } } }
1567
+ }`, {
1568
+ project: projectId,
1569
+ name: want.name,
1570
+ type: DATA_TYPES[want.type],
1571
+ options: want.type === "single_select" ? (want.options ?? []).map((name) => toOptionInput({ name })) : void 0
1572
+ });
1573
+ }
1574
+ async createView(projectId, name, layout) {
1575
+ return (await this.graphql.query(`mutation($project: ID!, $name: String!, $layout: ProjectV2ViewLayout!) {
1576
+ createProjectV2View(input: { projectId: $project, name: $name, layout: $layout }) { projectV2View { id } }
1577
+ }`, {
1578
+ project: projectId,
1579
+ name,
1580
+ layout
1581
+ })).createProjectV2View.projectV2View.id;
1582
+ }
1583
+ async updateView(viewId, change) {
1584
+ await this.graphql.query(`mutation($view: ID!, $layout: ProjectV2ViewLayout, $filter: String) {
1585
+ updateProjectV2View(input: { viewId: $view, layout: $layout, filter: $filter }) { projectV2View { id } }
1586
+ }`, {
1587
+ view: viewId,
1588
+ layout: change.layout,
1589
+ filter: change.filter
1590
+ });
1591
+ }
1592
+ /**
1593
+ * The board's issues and pull requests with their status, whether they are open and their open blockers. A second step
1594
+ * then reads, one small query per issue, the pull requests that close each open issue a rule could still move (it has a
1595
+ * status that is not `done` or `blocked` and no open blocker), each with the aggregate `ci / Required checks` state of
1596
+ * its head commit. An issue whose read fails keeps no `pullRequests` and carries `pullRequestsProblem` instead.
1597
+ */
1598
+ async items(_owner, board, template) {
1599
+ const categories = new Map(template.statuses.map((s) => [s.name, s.category]));
1600
+ const raw = await this.fetchItems(board.id);
1601
+ const wanted = raw.filter((i) => {
1602
+ const status = i.values[STATUS_FIELD];
1603
+ const category = status ? categories.get(status) : void 0;
1604
+ return i.issue && i.open && status !== void 0 && i.blockers.length === 0 && category !== "done" && category !== "blocked";
1605
+ });
1606
+ const closing = await readClosingPullRequests(this.graphql, wanted.map((i) => i.contentId), (r, n) => this.keyOf(r, n));
1607
+ return raw.map((i) => {
1608
+ const read = closing.get(i.contentId);
1609
+ const status = i.values[STATUS_FIELD];
1610
+ const category = status ? categories.get(status) : void 0;
1611
+ const priority = priorityOf(i.values[PRIORITY_FIELD]);
1612
+ return {
1613
+ key: this.keyOf(i.repo, i.number),
1614
+ title: i.title,
1615
+ open: i.open,
1616
+ ...status ? { status } : {},
1617
+ ...category ? { category } : {},
1618
+ blockedBy: i.blockers.map((b) => this.keyOf(b.repo, b.number)),
1619
+ ...priority ? { priority } : {},
1620
+ ...read && "pullRequests" in read ? { pullRequests: read.pullRequests } : {},
1621
+ ...read && "problem" in read ? { pullRequestsProblem: read.problem } : {}
1622
+ };
1623
+ });
1624
+ }
1625
+ /** Puts an item in a status; `transitioned` is false when it already is there. */
1626
+ async setStatus(_owner, board, key, status) {
1627
+ const ref = this.parseKey(key);
1628
+ const field = (await this.readRaw(board.id)).fields.find((f) => f.name === STATUS_FIELD && f.options);
1629
+ const option = field?.options?.find((o) => o.name === status);
1630
+ if (!field || !option) throw new Error(`board "${board.name}" has no status "${status}"`);
1631
+ const item = (await this.fetchItems(board.id)).find((i) => i.repo === ref.repo && i.number === ref.number);
1632
+ if (!item) throw new Error(`${key} is not on board "${board.name}"`);
1633
+ if (item.values[STATUS_FIELD] === status) return {
1634
+ transitioned: false,
1635
+ status
1636
+ };
1637
+ await this.graphql.query(SET_VALUE, {
1638
+ project: board.id,
1639
+ item: item.id,
1640
+ field: field.id,
1641
+ option: option.id
1642
+ });
1643
+ return {
1644
+ transitioned: true,
1645
+ status,
1646
+ via: "project field set"
1647
+ };
1648
+ }
1649
+ /**
1650
+ * Puts the open items of `from` on `to` with their status and priority, only where the target has no value;
1651
+ * closed and merged ones stay, and are set to the template's done status when theirs is not a done one.
1652
+ */
1653
+ async move(_owner, from, to, template) {
1654
+ const report = {
1655
+ moved: [],
1656
+ kept: [],
1657
+ left: []
1658
+ };
1659
+ const [source, target, fromRaw, toRaw] = await Promise.all([
1660
+ this.fetchItems(from.id),
1661
+ this.fetchItems(to.id),
1662
+ this.readRaw(from.id),
1663
+ this.readRaw(to.id)
1664
+ ]);
1665
+ const done = template.statuses.find((s) => s.category === "done")?.name;
1666
+ const doneNames = new Set(template.statuses.filter((s) => s.category === "done").map((s) => s.name));
1667
+ const carried = [STATUS_FIELD, PRIORITY_FIELD];
1668
+ for (const item of source) {
1669
+ const key = this.keyOf(item.repo, item.number);
1670
+ if (!item.open) {
1671
+ const current = item.values[STATUS_FIELD];
1672
+ if (done && (!current || !doneNames.has(current))) await this.setOption(from.id, fromRaw, item.id, STATUS_FIELD, done);
1673
+ report.left.push(key);
1674
+ continue;
1675
+ }
1676
+ let targetItem = target.find((t) => t.contentId === item.contentId);
1677
+ if (targetItem) report.kept.push(key);
1678
+ else {
1679
+ const data = await this.graphql.query(`mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`, {
1680
+ project: to.id,
1681
+ content: item.contentId
1682
+ });
1683
+ targetItem = {
1684
+ ...item,
1685
+ id: data.addProjectV2ItemById.item.id,
1686
+ values: {}
1687
+ };
1688
+ report.moved.push(key);
1689
+ }
1690
+ for (const name of carried) {
1691
+ const value = item.values[name];
1692
+ if (value && !targetItem.values[name]) await this.setOption(to.id, toRaw, targetItem.id, name, value);
1693
+ }
1694
+ }
1695
+ return report;
1696
+ }
1697
+ /**
1698
+ * Puts issues on the board (`addProjectV2ItemById`, the content id the issue's node id) and sets Status and Priority
1699
+ * through the single select update, only where the item has no value yet. A status or priority with no option on
1700
+ * the board is reported in `dropped`; no option is ever created, so no value is cleared.
1701
+ */
1702
+ async addItems(_owner, board, items, template) {
1703
+ const raw = await this.readRaw(board.id);
1704
+ const onBoard = await this.fetchItems(board.id);
1705
+ const statusField = raw.fields.find((f) => f.name === STATUS_FIELD && f.options);
1706
+ const priorityField = raw.fields.find((f) => f.name === PRIORITY_FIELD && f.options);
1707
+ const results = [];
1708
+ for (const input of items) {
1709
+ const ref = this.parseKey(input.key);
1710
+ let current = onBoard.find((i) => i.repo === ref.repo && i.number === ref.number);
1711
+ const added = !current;
1712
+ if (!current) current = {
1713
+ id: (await this.graphql.query(`mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`, {
1714
+ project: board.id,
1715
+ content: await this.nodeId(ref)
1716
+ })).addProjectV2ItemById.item.id,
1717
+ contentId: "",
1718
+ repo: ref.repo,
1719
+ number: ref.number,
1720
+ title: "",
1721
+ open: true,
1722
+ issue: false,
1723
+ values: {},
1724
+ blockers: []
1725
+ };
1726
+ const dropped = [];
1727
+ if (input.status !== void 0 || input.category !== void 0) {
1728
+ const name = this.statusFor(input, template, statusField?.options);
1729
+ if (!name) dropped.push(`status ${input.status ?? input.category} (no matching option on the board)`);
1730
+ else if (!current.values[STATUS_FIELD]) await this.setOption(board.id, raw, current.id, STATUS_FIELD, name);
1731
+ }
1732
+ if (input.priority !== void 0 && input.priority !== "none") {
1733
+ const option = priorityField?.options?.find((o) => priorityOf(o.name) === input.priority);
1734
+ if (!option) dropped.push(`priority ${input.priority} (no matching option on the board)`);
1735
+ else if (!current.values[PRIORITY_FIELD]) await this.setOption(board.id, raw, current.id, PRIORITY_FIELD, option.name);
1736
+ }
1737
+ results.push({
1738
+ key: input.key,
1739
+ added,
1740
+ dropped
1741
+ });
1742
+ }
1743
+ return results;
1744
+ }
1745
+ /** The board's own status for an input: the option named like its status, else the template's status of its category. */
1746
+ statusFor(input, template, options) {
1747
+ const has = (name) => options?.find((o) => o.name.toLowerCase() === name.toLowerCase())?.name;
1748
+ const named = input.status === void 0 ? void 0 : has(input.status);
1749
+ if (named) return named;
1750
+ const byCategory = template.statuses.find((s) => s.category === input.category);
1751
+ return byCategory ? has(byCategory.name) : void 0;
1752
+ }
1753
+ /** The node id of an issue, which `addProjectV2ItemById` takes as the content id. */
1754
+ async nodeId(ref) {
1755
+ const [owner, name] = ref.repo.split("/");
1756
+ const id = (await this.graphql.query(`query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { id } } }`, {
1757
+ owner,
1758
+ name,
1759
+ number: ref.number
1760
+ })).repository?.issue?.id;
1761
+ if (!id) throw new Error(`issue ${ref.repo}#${ref.number} not found`);
1762
+ return id;
1763
+ }
1764
+ /** A `holocron doctor` smoke check: how many boards the token sees in the configured repository's organization. */
1765
+ async whoami() {
1766
+ try {
1767
+ return {
1768
+ ok: true,
1769
+ boards: (await this.list(this.repo.split("/")[0] ?? "")).length
1770
+ };
1771
+ } catch {
1772
+ return {
1773
+ ok: false,
1774
+ boards: 0
1775
+ };
1776
+ }
1777
+ }
1778
+ /** Sets a single select value by option name; a field or option the board lacks is skipped. */
1779
+ async setOption(projectId, raw, itemId, fieldName, optionName) {
1780
+ const field = raw.fields.find((f) => f.name === fieldName && f.options);
1781
+ const option = field?.options?.find((o) => o.name === optionName);
1782
+ if (!field || !option) return;
1783
+ await this.graphql.query(SET_VALUE, {
1784
+ project: projectId,
1785
+ item: itemId,
1786
+ field: field.id,
1787
+ option: option.id
1788
+ });
1789
+ }
1790
+ async ownerId(owner) {
1791
+ return (await this.graphql.query(OWNER_QUERY, { owner })).organization.id;
1792
+ }
1793
+ async readRaw(id) {
1794
+ const n = (await this.graphql.query(BOARD_QUERY, { id })).node;
1795
+ if (!n) throw new Error(`board ${id} not found`);
1796
+ return {
1797
+ summary: toSummary(n),
1798
+ fields: n.fields.nodes.filter((f) => f.id).map((f) => ({
1799
+ id: f.id,
1800
+ name: f.name,
1801
+ dataType: f.dataType,
1802
+ ...f.options ? { options: f.options } : {}
1803
+ })),
1804
+ views: n.views.nodes.map((v) => ({
1805
+ id: v.id,
1806
+ name: v.name,
1807
+ layout: v.layout,
1808
+ filter: v.filter,
1809
+ groupBy: (v.groupByFields?.nodes ?? []).map((g) => g.name)
1810
+ })),
1811
+ rules: n.workflows.nodes.map((w) => ({
1812
+ id: w.id,
1813
+ name: w.name,
1814
+ enabled: w.enabled
1815
+ }))
1816
+ };
1817
+ }
1818
+ async fetchItems(id) {
1819
+ const items = [];
1820
+ let after = null;
1821
+ for (;;) {
1822
+ const page = (await this.graphql.query(ITEMS_QUERY, {
1823
+ id,
1824
+ after
1825
+ })).node.items;
1826
+ for (const n of page.nodes) {
1827
+ const c = n.content;
1828
+ if (!c || !c.repository) continue;
1829
+ const values = {};
1830
+ for (const v of n.fieldValues.nodes) if (v.name && v.field?.name) values[v.field.name] = v.name;
1831
+ items.push({
1832
+ id: n.id,
1833
+ contentId: c.id,
1834
+ repo: c.repository.nameWithOwner,
1835
+ number: c.number,
1836
+ title: c.title,
1837
+ open: c.state === "OPEN",
1838
+ issue: c.__typename === "Issue",
1839
+ values,
1840
+ blockers: (c.blockedBy?.nodes ?? []).filter((b) => b.state === "OPEN").map((b) => ({
1841
+ repo: b.repository.nameWithOwner,
1842
+ number: b.number
1843
+ }))
1844
+ });
1845
+ }
1846
+ if (!page.pageInfo.hasNextPage) return items;
1847
+ after = page.pageInfo.endCursor;
1848
+ }
1849
+ }
1850
+ keyOf(repo, number) {
1851
+ return repo === this.repo ? `#${number}` : `${repo}#${number}`;
1852
+ }
1853
+ parseKey(key) {
1854
+ const m = /^(?:([^#\s]+))?#?(\d+)$/.exec(key.trim());
1855
+ const hasRepo = key.includes("#") && m?.[1];
1856
+ if (!m) throw new Error(`not an issue key: ${key}`);
1857
+ return {
1858
+ repo: hasRepo ? m[1] : this.repo,
1859
+ number: Number(m[2])
1860
+ };
1861
+ }
1862
+ };
1863
+ // src/sodium.ts
1864
+ /**
1865
+ * libsodium sealed-box encryption for GitHub Actions secrets.
1866
+ *
1867
+ * GitHub stores Actions / Codespaces / Dependabot secrets encrypted
1868
+ * with a curve25519 public key (returned by the `/actions/secrets/public-key`
1869
+ * endpoint). Callers fetch that key, encrypt the plaintext value with
1870
+ * `crypto_box_seal`, then PUT the base64-encoded ciphertext + `key_id`.
1871
+ *
1872
+ * Reference: https://docs.github.com/en/rest/actions/secrets#create-or-update-a-repository-secret
1873
+ *
1874
+ * **Why createRequire?** `libsodium-wrappers@0.7.x` ships a broken
1875
+ * ESM bundle — the `dist/modules-esm/libsodium-wrappers.mjs` entry
1876
+ * imports a sibling `libsodium.mjs` that isn't included in the npm
1877
+ * tarball. Native `import` against the package therefore fails.
1878
+ * `createRequire` routes through Node's CJS resolver, which honors
1879
+ * the `"require"` condition in the package's exports map and loads
1880
+ * the self-contained CJS bundle instead. Same API, working module.
1881
+ */
1882
+ const sodium = createRequire(import.meta.url)("libsodium-wrappers");
1883
+ /**
1884
+ * Encrypt `value` for the given GitHub-provided base64 public key.
1885
+ * Returns the base64 ciphertext to send as `encrypted_value`.
1886
+ */
1887
+ async function encryptSecret(publicKeyBase64, value) {
1888
+ await sodium.ready;
1889
+ const publicKey = sodium.from_base64(publicKeyBase64, sodium.base64_variants.ORIGINAL);
1890
+ const plaintext = sodium.from_string(value);
1891
+ const ciphertext = sodium.crypto_box_seal(plaintext, publicKey);
1892
+ return sodium.to_base64(ciphertext, sodium.base64_variants.ORIGINAL);
1893
+ }
1894
+ // src/capabilities/secrets.ts
1895
+ /** The GitHub implementation of the `secrets` capability, covering repository, environment and organization secrets. */
1896
+ var GitHubSecrets = class {
1897
+ client;
1898
+ opts;
1899
+ orgClient;
1900
+ /** Capability key, always `"secrets"`. */
1901
+ key = "secrets";
1902
+ /** Provider name, always `"github"`. */
1903
+ providerName = "github";
1904
+ /**
1905
+ * `client` handles repo and environment scopes; `orgClient`, when given, handles
1906
+ * the organization scope. They differ when a dedicated org-only token exists:
1907
+ * it can write org secrets but not repo ones, and `github.admin` is the reverse.
1908
+ */
1909
+ constructor(client, opts, orgClient) {
1910
+ this.client = client;
1911
+ this.opts = opts;
1912
+ this.orgClient = orgClient;
1913
+ }
1914
+ /** Repository name to numeric id, so one run asks GitHub once per repository however many secrets name it. */
1915
+ repoIds = /* @__PURE__ */ new Map();
1916
+ clientFor(scope) {
1917
+ return scope.kind === "organization" ? this.orgClient ?? this.client : this.client;
1918
+ }
1919
+ async listSecrets(scope) {
1920
+ return this.clientFor(scope).secrets.listSecrets(this.opts.repo, toGHScope(scope));
1921
+ }
1922
+ async setSecret(scope, name, value) {
1923
+ const ghScope = toGHScope(scope);
1924
+ const client = this.clientFor(scope);
1925
+ const readers = scope.kind === "organization" ? await this.readers(scope) : {};
1926
+ const pk = await client.secrets.getPublicKey(this.opts.repo, ghScope);
1927
+ const body = {
1928
+ encrypted_value: await encryptSecret(pk.key, value),
1929
+ key_id: pk.key_id
1930
+ };
1931
+ Object.assign(body, readers);
1932
+ await client.secrets.putSecret(this.opts.repo, ghScope, name, body);
1933
+ }
1934
+ /**
1935
+ * Who can read each organization secret, by name (never a value): `selected` ones come with the names of their
1936
+ * repositories. Any other scope has no visibility and gives `{}`.
1937
+ */
1938
+ async listSecretAccess(scope) {
1939
+ if (scope.kind !== "organization") return {};
1940
+ const client = this.clientFor(scope);
1941
+ const found = {};
1942
+ for (const info of await client.secrets.listOrgSecretInfo(scope.name)) found[info.name] = info.visibility === "selected" ? {
1943
+ visibility: "selected",
1944
+ repos: await client.secrets.listSelectedRepositories(scope.name, info.name)
1945
+ } : { visibility: info.visibility };
1946
+ return found;
1947
+ }
1948
+ /** The `visibility` (and repository ids) of an organization write. No `visibility` keeps the older default, `all`. */
1949
+ async readers(scope) {
1950
+ const visibility = scope.visibility ?? "all";
1951
+ if (visibility !== "selected") return { visibility };
1952
+ if (!scope.repos?.length) throw new Error(`organization secret with visibility "selected" needs a non-empty repos list`);
1953
+ const ids = [];
1954
+ for (const name of scope.repos) ids.push(await this.repoId(scope.name, name));
1955
+ return {
1956
+ visibility,
1957
+ selected_repository_ids: ids
1958
+ };
1959
+ }
1960
+ repoId(org, name) {
1961
+ const full = `${org}/${name}`;
1962
+ let id = this.repoIds.get(full);
1963
+ if (!id) {
1964
+ id = this.client.repos.getRepo(full).then((repo) => repo.id, (err) => {
1965
+ throw new Error(`could not resolve repository ${full}: ${err instanceof Error ? err.message : String(err)}`);
1966
+ });
1967
+ this.repoIds.set(full, id);
1968
+ }
1969
+ return id;
1970
+ }
1971
+ /** Deletes the named secret in the given scope. */
1972
+ async deleteSecret(scope, name) {
1973
+ await this.clientFor(scope).secrets.deleteSecret(this.opts.repo, toGHScope(scope), name);
1974
+ }
1975
+ };
1976
+ function toGHScope(scope) {
1977
+ if (scope.kind === "organization") return {
1978
+ kind: "organization",
1979
+ org: scope.name
1980
+ };
1981
+ return scope;
1982
+ }
1983
+ // src/capabilities/files.ts
1984
+ /** Reads one file; `null` when it does not exist. `version` is the blob sha `writeFile` needs to replace exactly this one. */
1985
+ /** A fine-grained token only reaches the repositories and permissions it was given; say which one is missing. */
1986
+ function noAccess(repo, action, cause) {
1987
+ return new Error(`the token cannot ${action} files in ${repo} (403): give the user-sync token (HOLOCRON_USER_SYNC_TOKEN, or holocron new token github.user-sync) access to that repository with Contents: ${action === "read" ? "read" : "read and write"}`, { cause });
1988
+ }
1989
+ async function readRepoFile(client, repo, path) {
1990
+ try {
1991
+ const file = await client.git.getContents(repo, path);
1992
+ if (file.encoding !== "base64") throw new Error(`${repo}/${path}: unexpected encoding \`${file.encoding}\``);
1993
+ return {
1994
+ content: Buffer.from(file.content, "base64").toString("utf-8"),
1995
+ version: file.sha
1996
+ };
1997
+ } catch (err) {
1998
+ if (err instanceof ProviderApiError && err.status === 403) throw noAccess(repo, "read", err);
1999
+ if (!(err instanceof ProviderApiError && err.status === 404)) throw err;
2000
+ }
2001
+ try {
2002
+ await client.repos.getRepo(repo);
2003
+ } catch (err) {
2004
+ 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 });
2005
+ throw err;
2006
+ }
2007
+ return null;
2008
+ }
2009
+ /** Creates or replaces one file in a commit; GitHub refuses (409) a `version` that has since changed. */
2010
+ async function writeRepoFile(client, repo, path, content, opts) {
2011
+ try {
2012
+ await client.git.putContents(repo, path, {
2013
+ message: opts.message,
2014
+ content,
2015
+ ...opts.version ? { sha: opts.version } : {}
2016
+ });
2017
+ } catch (err) {
2018
+ if (err instanceof ProviderApiError && err.status === 403) throw noAccess(repo, "write", err);
2019
+ throw err;
2020
+ }
2021
+ }
2022
+ // src/capabilities/labels.ts
2023
+ /**
2024
+ * Idempotently synchronise a repo's labels to the canonical set.
2025
+ *
2026
+ * - Creates labels that are missing.
2027
+ * - PATCHes labels whose color or description has drifted.
2028
+ * - DELETEs labels listed in `stale`.
2029
+ * - Leaves unrecognised labels that aren't in `stale` untouched.
2030
+ */
2031
+ async function syncLabels(client, repo, canonical, stale) {
2032
+ const existing = await client.labels.listLabels(repo);
2033
+ const existingMap = new Map(existing.map((l) => [l.name.toLowerCase(), l]));
2034
+ let created = 0;
2035
+ let updated = 0;
2036
+ let deleted = 0;
2037
+ for (const label of canonical) {
2038
+ const current = existingMap.get(label.name);
2039
+ if (!current) {
2040
+ await client.labels.createLabel(repo, {
2041
+ name: label.name,
2042
+ color: label.color,
2043
+ description: label.description
2044
+ });
2045
+ created++;
2046
+ } else if (current.color !== label.color || (current.description ?? "") !== label.description) {
2047
+ await client.labels.updateLabel(repo, label.name, {
2048
+ color: label.color,
2049
+ description: label.description
2050
+ });
2051
+ updated++;
2052
+ }
2053
+ }
2054
+ for (const staleName of stale) if (existingMap.has(staleName)) {
2055
+ await client.labels.deleteLabel(repo, staleName);
2056
+ deleted++;
2057
+ }
2058
+ return `${created} created, ${updated} updated, ${deleted} deleted`;
2059
+ }
2060
+ /**
2061
+ * Make the labels a repo lacks and change nothing else: an existing label (found without regard to case) keeps its
2062
+ * colour and description, and nothing is deleted. Used for the `area:<name>` family, which is not in the canonical set.
2063
+ */
2064
+ async function ensureLabels(client, repo, labels) {
2065
+ const existing = await client.labels.listLabels(repo);
2066
+ const have = new Set(existing.map((l) => l.name.toLowerCase()));
2067
+ let created = 0;
2068
+ for (const label of labels) {
2069
+ if (have.has(label.name.toLowerCase())) continue;
2070
+ await client.labels.createLabel(repo, {
2071
+ name: label.name,
2072
+ color: label.color,
2073
+ description: label.description
2074
+ });
2075
+ created++;
2076
+ }
2077
+ return `${created} created, ${labels.length - created} already there`;
2078
+ }
2079
+ // src/capabilities/property-fix-hints.ts
2080
+ /** GitHub's wording when a custom property value is not one the organization's definition allows. */
2081
+ const NOT_ALLOWED = /Value '([^']+)' is not allowed for property '([^']+)'/g;
2082
+ /**
2083
+ * What to do about each value GitHub says an organization custom property does not allow, one sentence per property,
2084
+ * read from GitHub's own message so it works even when the organization's definitions cannot be read. The values
2085
+ * belong to the organization's definition, not to the repository, so the fix is to add them there: a repository cannot
2086
+ * make its own value allowed. Empty when GitHub's message names no such value.
2087
+ */
2088
+ function propertyFixHints(githubMessage) {
2089
+ const byProperty = /* @__PURE__ */ new Map();
2090
+ for (const [, value, property] of githubMessage.matchAll(NOT_ALLOWED)) {
2091
+ const values = byProperty.get(property) ?? [];
2092
+ if (!values.includes(value)) values.push(value);
2093
+ byProperty.set(property, values);
2094
+ }
2095
+ 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 setup again`);
2096
+ }
2097
+ // src/capabilities/rejected-properties.ts
2098
+ /** The values `setup` sends for `true_false` properties; anything else is rejected. */
2099
+ const BOOLEANS = /* @__PURE__ */ new Set(["true", "false"]);
2100
+ /**
2101
+ * What is wrong with `values` when compared with the organization's property definitions, one sentence per
2102
+ * problem, in the order the properties are given: a property the organization does not define, a value a
2103
+ * `single_select` or `multi_select` property does not allow, or a `true_false` property that is not `true` or
2104
+ * `false`. A `string` or `url` property has nothing to check here. Empty when every value fits its definition.
2105
+ */
2106
+ function rejectedProperties(values, schema) {
2107
+ const byName = new Map(schema.map((property) => [property.property_name, property]));
2108
+ const problems = [];
2109
+ for (const [name, value] of Object.entries(values)) {
2110
+ const definition = byName.get(name);
2111
+ if (!definition) {
2112
+ problems.push(`${name} is not a custom property of the organization`);
2113
+ continue;
2114
+ }
2115
+ const sent = Array.isArray(value) ? value : [value];
2116
+ if (definition.value_type === "true_false") {
2117
+ for (const item of sent.filter((item) => !BOOLEANS.has(item))) problems.push(`${name} is "${item}", but it takes only true or false`);
2118
+ continue;
2119
+ }
2120
+ const allowed = definition.allowed_values ?? [];
2121
+ if (definition.value_type !== "single_select" && definition.value_type !== "multi_select") continue;
2122
+ 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(", ")})`);
2123
+ }
2124
+ return problems;
2125
+ }
2126
+ // src/capabilities/properties.ts
2127
+ /** GitHub's own message from a 422 body (`{"message": ..., "errors": [...]}`), or the start of the body when it is not JSON. */
2128
+ function githubMessage(details) {
2129
+ const raw = String(details ?? "").trim();
2130
+ try {
2131
+ const body = JSON.parse(raw);
2132
+ const errors = Array.isArray(body.errors) ? body.errors.map((e) => JSON.stringify(e)).join(", ") : "";
2133
+ const message = typeof body.message === "string" ? body.message : raw;
2134
+ return errors ? `${message}: ${errors}` : message;
2135
+ } catch {
2136
+ return raw.slice(0, 300);
2137
+ }
2138
+ }
2139
+ /** The organization's property definitions, or `undefined` when they cannot be read (permission, an older client). */
2140
+ async function orgSchema(client, repo) {
2141
+ try {
2142
+ return await client.properties.orgSchema(repo.split("/")[0]);
2143
+ } catch {
2144
+ return;
2145
+ }
2146
+ }
2147
+ /**
2148
+ * The values `values` holds that the organization's property definitions do not allow, one sentence each, or
2149
+ * `undefined` when the definitions cannot be read (the token lacks the organization's custom properties permission, or
2150
+ * the organization defines none). `client` should be the organization-scoped one when there is one, since reading the
2151
+ * definitions is an organization permission a repository token often lacks. Read-only.
2152
+ */
2153
+ async function checkPropertyValues(client, repo, values) {
2154
+ const schema = await orgSchema(client, repo);
2155
+ return schema ? rejectedProperties(values, schema) : void 0;
2156
+ }
2157
+ /**
2158
+ * Sets the repo's custom properties. When GitHub answers 422 the error says which value it refused and what to do
2159
+ * about it: the values are compared with the organization's property definitions (read-only, with `schemaClient`, the
2160
+ * organization-scoped client when there is one), GitHub's own message is added, and each value GitHub says a property
2161
+ * does not allow gets the fix, which does not need the definitions to be readable. One refused value fails the whole
2162
+ * request, so none of the properties is set.
2163
+ */
2164
+ async function syncProperties(client, repo, values, schemaClient = client) {
2165
+ try {
2166
+ await client.properties.setProperties(repo, values);
2167
+ } catch (err) {
2168
+ if (!(err instanceof ProviderApiError$1) || err.status !== 422) throw err;
2169
+ const problems = await checkPropertyValues(schemaClient, repo, values) ?? [];
2170
+ const said = githubMessage(err.details);
2171
+ const fixes = propertyFixHints(said);
2172
+ 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 });
2173
+ }
2174
+ return `${Object.keys(values).length} properties set`;
2175
+ }
2176
+ /** The values the organization's property `name` allows; `undefined` when it cannot be read, is not defined or takes any value. */
2177
+ async function getOrgPropertyValues(client, repo, name) {
2178
+ return ((await orgSchema(client, repo))?.find((p) => p.property_name === name))?.allowed_values ?? void 0;
2179
+ }
2180
+ /**
2181
+ * Adds the missing `values` to the organization's property `name` and returns them. GitHub replaces the whole
2182
+ * definition on a write, so the current one is read and sent back with the allowed values extended, in their order,
2183
+ * and nothing removed. A write is made only when something is missing.
2184
+ */
2185
+ async function addOrgPropertyValues(client, repo, name, values, viaOrgToken = true) {
2186
+ const org = repo.split("/")[0];
2187
+ const current = (await client.properties.orgSchema(org)).find((p) => p.property_name === name);
2188
+ if (!current) throw new Error(`the organization ${org} has no custom property "${name}"; create it first`);
2189
+ if (!current.allowed_values) throw new Error(`the custom property "${name}" takes any value; it has nothing to extend`);
2190
+ const have = new Set(current.allowed_values);
2191
+ const added = [...new Set(values)].filter((v) => !have.has(v));
2192
+ if (added.length === 0) return [];
2193
+ try {
2194
+ await client.properties.setOrgProperty(org, {
2195
+ ...current,
2196
+ allowed_values: [...current.allowed_values, ...added]
2197
+ });
2198
+ } catch (err) {
2199
+ if (!(err instanceof ProviderApiError$1) || err.status !== 403 && err.status !== 401) throw err;
2200
+ const token = viaOrgToken ? "the organization token (HOLOCRON_ORG_TOKEN, or the token passed with --token)" : "the admin token, because no organization token was found (set HOLOCRON_ORG_TOKEN or pass --token)";
2201
+ throw new Error(`GitHub refused to change the "${name}" definition (${err.status}): it needs the organization permission Custom properties: Read and write (admin) on ${org}, and this ran with ${token}`, { cause: err });
2202
+ }
2203
+ return added;
2204
+ }
2205
+ // src/capabilities/pull-request-checks.ts
2206
+ /** The check run the aggregate `ci` workflow posts on a pull request's head commit. */
2207
+ const AGGREGATE_CHECK = "ci / Required checks";
2208
+ const FAILED = /* @__PURE__ */ new Set([
2209
+ "failure",
2210
+ "timed_out",
2211
+ "startup_failure",
2212
+ "action_required",
2213
+ "stale"
2214
+ ]);
2215
+ const newestFirst = (a, b) => (b.started_at ?? "").localeCompare(a.started_at ?? "") || b.id - a.id;
2216
+ /** The aggregate's verdict from its runs: only the newest counts; a cancelled or unfinished run is `pending`. */
2217
+ function aggregateState(runs) {
2218
+ const newest = [...runs].sort(newestFirst)[0];
2219
+ if (!newest) return "none";
2220
+ if (newest.status !== "completed") return "pending";
2221
+ if (newest.conclusion === "success") return "success";
2222
+ if (newest.conclusion && FAILED.has(newest.conclusion)) return "failure";
2223
+ if (newest.conclusion === "cancelled") return "pending";
2224
+ return "none";
2225
+ }
2226
+ /**
2227
+ * The aggregate check of a pull request's newest commit and the checks that failed on it, read now (never cached, so a
2228
+ * caller that polls sees each change). The newest run of each name counts, so a job that failed and was re-run to green
2229
+ * is not listed.
2230
+ */
2231
+ async function readPullRequestChecks(client, repo, number) {
2232
+ const sha = (await client.pulls.getPullRequest(repo, number)).head.sha;
2233
+ const runs = await client.checks.listCheckRunsForRef(repo, sha);
2234
+ const newest = /* @__PURE__ */ new Map();
2235
+ for (const run of [...runs].sort(newestFirst)) if (!newest.has(run.name)) newest.set(run.name, run);
2236
+ return {
2237
+ state: aggregateState(runs.filter((r) => r.name === AGGREGATE_CHECK)),
2238
+ sha,
2239
+ failing: [...newest.values()].filter((r) => r.status === "completed" && r.conclusion !== null && FAILED.has(r.conclusion)).map((r) => ({
2240
+ name: r.name,
2241
+ url: r.details_url ?? r.html_url
2242
+ }))
2243
+ };
2244
+ }
2245
+ // src/capabilities/pull-requests.ts
2246
+ /** The GitHub pull request as the neutral {@link PullRequest}. */
2247
+ function toPullRequest(raw) {
2248
+ return {
2249
+ number: raw.number,
2250
+ title: raw.title,
2251
+ state: raw.state,
2252
+ merged: raw.merged_at !== null,
2253
+ branch: raw.head.ref,
2254
+ headSha: raw.head.sha,
2255
+ url: raw.html_url
2256
+ };
2257
+ }
2258
+ /** Whether a body already holds a closing or referencing line for the issue (any keyword, any case). */
2259
+ function names(body, issue) {
2260
+ const escaped = issue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2261
+ return new RegExp(`\\b(closes?|fix(es)?|resolves?|refs?)\\s+${escaped}(?![\\w-])`, "i").test(body);
2262
+ }
2263
+ /**
2264
+ * The body with the link line the issue's closing reference needs. GitHub reads `Closes #12` itself, so the link is
2265
+ * text, not a call; a body that already names the issue is left alone.
2266
+ */
2267
+ function withLink(body, link) {
2268
+ if (!link) return body;
2269
+ const issue = link.issue.trim();
2270
+ const ref = /^\d+$/.test(issue) ? `#${issue}` : issue;
2271
+ const text = body ?? "";
2272
+ if (names(text, ref)) return body;
2273
+ const line = `${link.keyword ?? "Refs"} ${ref}`;
2274
+ return text.trim() === "" ? line : `${text.replace(/\s+$/, "")}\n\n${line}`;
2275
+ }
2276
+ /** Puts the pull request (by node id) on each board of the organization found by title; a board not found or refused is returned by name. */
2277
+ async function addToBoards(client, repo, nodeId, titles) {
2278
+ const dropped = [];
2279
+ const owner = repo.slice(0, repo.indexOf("/"));
2280
+ let boards;
2281
+ try {
2282
+ boards = (await client.graphql.query(`query($owner: String!) { organization(login: $owner) { projectsV2(first: 100) { nodes { id title closed } } } }`, { owner })).organization;
2283
+ } catch {
2284
+ return titles.map((t) => `project ${t}`);
2285
+ }
2286
+ for (const title of titles) {
2287
+ const board = boards?.projectsV2.nodes.find((b) => b.title === title && !b.closed);
2288
+ if (!board) {
2289
+ dropped.push(`project ${title}`);
2290
+ continue;
2291
+ }
2292
+ try {
2293
+ await client.graphql.query(`mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`, {
2294
+ project: board.id,
2295
+ content: nodeId
2296
+ });
2297
+ } catch {
2298
+ dropped.push(`project ${title}`);
2299
+ }
2300
+ }
2301
+ return dropped;
2302
+ }
2303
+ /**
2304
+ * Puts the fields an issue and its pull request share on the pull request (GitHub serves a pull request through
2305
+ * the issues API for these): labels and assignees are added to what is there, a milestone is found by title and
2306
+ * boards by title. What cannot be applied comes back by name; nothing is created or cleared.
2307
+ */
2308
+ async function applyFields(client, repo, pr, fields) {
2309
+ const dropped = [];
2310
+ const { number } = pr;
2311
+ if (fields.labels?.length) await client.issues.addLabels(repo, number, fields.labels);
2312
+ for (const label of fields.removeLabels ?? []) try {
2313
+ await client.issues.removeLabel(repo, number, label);
2314
+ } catch {}
2315
+ const patch = {};
2316
+ if (fields.assignees?.length) {
2317
+ const have = ((await client.issues.getIssue(repo, number)).assignees ?? []).map((a) => a.login);
2318
+ const want = fields.assignees.map((a) => a.replace(/^@/, ""));
2319
+ const next = [.../* @__PURE__ */ new Set([...have, ...want])];
2320
+ if (next.length !== have.length) patch.assignees = next;
2321
+ }
2322
+ if (fields.milestone) {
2323
+ const found = (await client.issues.listMilestones(repo, { state: "open" })).find((m) => m.title === fields.milestone);
2324
+ if (found) patch.milestone = found.number;
2325
+ else dropped.push(`milestone ${fields.milestone}`);
2326
+ }
2327
+ if (Object.keys(patch).length) await client.issues.updateIssue(repo, number, patch);
2328
+ if (fields.projects?.length) {
2329
+ if (pr.node_id) dropped.push(...await addToBoards(client, repo, pr.node_id, fields.projects));
2330
+ else dropped.push(...fields.projects.map((t) => `project ${t}`));
2331
+ }
2332
+ return dropped;
2333
+ }
2334
+ /** Opens a draft pull request, or returns the open one for the same head, and applies the mirrored fields. */
2335
+ async function createPullRequest(client, repo, input) {
2336
+ const existing = (await client.pulls.listOpenByHead(repo, input.head))[0];
2337
+ const created = !existing;
2338
+ const raw = existing ?? await client.pulls.createPullRequest(repo, {
2339
+ title: input.title,
2340
+ head: input.head,
2341
+ base: input.base,
2342
+ body: withLink(input.body, input.link),
2343
+ draft: input.draft ?? true
2344
+ });
2345
+ const dropped = await applyFields(client, repo, raw, input);
2346
+ return {
2347
+ pullRequest: toPullRequest(raw),
2348
+ created,
2349
+ draft: raw.draft ?? false,
2350
+ dropped
2351
+ };
2352
+ }
2353
+ /** Changes a pull request's own fields, then the mirrored ones. A patch that names none of the own fields makes no PATCH. */
2354
+ async function updatePullRequest(client, repo, number, patch) {
2355
+ const own = {};
2356
+ if (patch.title !== void 0) own.title = patch.title;
2357
+ if (patch.body !== void 0) own.body = patch.body;
2358
+ if (patch.base !== void 0) own.base = patch.base;
2359
+ if (patch.state !== void 0) own.state = patch.state;
2360
+ const raw = Object.keys(own).length ? await client.pulls.updatePullRequest(repo, number, own) : await client.pulls.getPullRequest(repo, number);
2361
+ const dropped = await applyFields(client, repo, raw, patch);
2362
+ return {
2363
+ pullRequest: toPullRequest(raw),
2364
+ created: false,
2365
+ draft: raw.draft ?? false,
2366
+ dropped
2367
+ };
2368
+ }
2369
+ /** Takes a draft out of draft; `false` when it was not a draft or is not open. */
2370
+ async function markReady(client, repo, number) {
2371
+ const raw = await client.pulls.getPullRequest(repo, number);
2372
+ if (!raw.draft || raw.state !== "open") return false;
2373
+ if (!raw.node_id) throw new Error(`pull request ${repo}#${number} has no node id to mark ready`);
2374
+ await client.pulls.markReadyForReview(raw.node_id);
2375
+ return true;
2376
+ }
2377
+ // src/capabilities/read-repo.ts
2378
+ /** The settings `setup` writes, which `GET /repos/{repo}` reports under the same names. */
2379
+ const SETTING_KEYS = [
2380
+ "allow_squash_merge",
2381
+ "allow_merge_commit",
2382
+ "allow_rebase_merge",
2383
+ "allow_auto_merge",
2384
+ "allow_update_branch",
2385
+ "delete_branch_on_merge",
2386
+ "has_issues",
2387
+ "has_discussions",
2388
+ "has_projects",
2389
+ "has_wiki"
2390
+ ];
2391
+ /** The repository's description, homepage, default branch, topics and settings, from one read. */
2392
+ async function readRepoInfo(client, repo) {
2393
+ const data = await client.repos.getRepo(repo);
2394
+ const settings = { default_branch: data.default_branch };
2395
+ for (const key of SETTING_KEYS) {
2396
+ const value = data[key];
2397
+ if (value !== void 0) settings[key] = value;
2398
+ }
2399
+ return {
2400
+ description: data.description ?? null,
2401
+ homepage: data.homepage ?? null,
2402
+ defaultBranch: data.default_branch,
2403
+ topics: data.topics ?? [],
2404
+ settings
2405
+ };
2406
+ }
2407
+ /** A ruleset reduced to what `setup` writes: its enforcement, rule types and required status checks. */
2408
+ function toRulesetDetail(data) {
2409
+ const rules = data.rules ?? [];
2410
+ const checks = rules.find((r) => r.type === "required_status_checks")?.parameters?.required_status_checks;
2411
+ return {
2412
+ name: data.name,
2413
+ enforcement: data.enforcement,
2414
+ ruleTypes: rules.map((r) => r.type),
2415
+ requiredChecks: Array.isArray(checks) ? checks.map((c) => String(c.context)) : []
2416
+ };
2417
+ }
2418
+ /** The value, or `undefined` when GitHub refuses the read (permission, plan, feature absent). Other errors still throw. */
2419
+ async function readable(read) {
2420
+ try {
2421
+ return await read();
2422
+ } catch (err) {
2423
+ if (err instanceof ProviderApiError$1) return void 0;
2424
+ throw err;
2425
+ }
2426
+ }
2427
+ /** Which security features are on. One GitHub refuses to report is left out, not reported as off. */
2428
+ async function readSecurity(client, repo) {
2429
+ const [data, alerts, fixes, reporting, codeScanning] = await Promise.all([
2430
+ readable(() => client.repos.getRepo(repo)),
2431
+ readable(() => client.security.vulnerabilityAlertsEnabled(repo)),
2432
+ readable(() => client.security.automatedSecurityFixesEnabled(repo)),
2433
+ readable(() => client.security.privateVulnerabilityReportingEnabled(repo)),
2434
+ readable(() => client.security.codeScanningDefaultSetupState(repo))
2435
+ ]);
2436
+ const analysis = data?.security_and_analysis;
2437
+ const on = (feature) => {
2438
+ const status = analysis?.[feature]?.status;
2439
+ return status === void 0 ? void 0 : status === "enabled";
2440
+ };
2441
+ const found = {
2442
+ vulnerabilityAlerts: alerts,
2443
+ automatedSecurityFixes: fixes,
2444
+ secretScanning: on("secret_scanning"),
2445
+ secretScanningPushProtection: on("secret_scanning_push_protection"),
2446
+ privateVulnerabilityReporting: reporting,
2447
+ codeScanningDefaultSetup: codeScanning === void 0 ? void 0 : codeScanning === "configured"
2448
+ };
2449
+ return Object.fromEntries(Object.entries(found).filter(([, v]) => v !== void 0));
2450
+ }
2451
+ // src/capabilities/teams.ts
2452
+ /** Turns a team entry into slug and permission form; a bare slug gets `push`. */
2453
+ function normalizeTeamEntry(entry) {
2454
+ if (typeof entry === "string") return {
2455
+ slug: entry,
2456
+ permission: "push"
2457
+ };
2458
+ return entry;
2459
+ }
2460
+ /** Grants each team access to the repo and reports the outcome; throws when every team fails. */
2461
+ async function syncTeams(client, repo, teams) {
2462
+ const [org = "", name = ""] = repo.split("/", 2);
2463
+ const normalized = teams.map(normalizeTeamEntry);
2464
+ const results = await Promise.allSettled(normalized.map(({ slug, permission }) => client.teams.addRepo(org, slug, org, name, permission)));
2465
+ const succeeded = results.filter((r) => r.status === "fulfilled").length;
2466
+ const failedSlugs = normalized.filter((_, i) => results[i]?.status === "rejected").map(({ slug }) => slug);
2467
+ if (failedSlugs.length > 0) {
2468
+ if (succeeded === 0) throw new Error(`all teams failed: ${failedSlugs.join(", ")}`);
2469
+ return `${succeeded} synced, failed: ${failedSlugs.join(", ")}`;
470
2470
  }
471
2471
  return `${succeeded} team${succeeded === 1 ? "" : "s"} synced`;
472
2472
  }
473
- //#endregion
474
- //#region src/capabilities/topics.ts
475
- async function syncTopics(client, repo, topics) {
476
- await client.topics.setTopics(repo, topics);
477
- return `${topics.length} topics set`;
2473
+ // src/capabilities/topics.ts
2474
+ async function syncTopics(client, repo, topics) {
2475
+ await client.topics.setTopics(repo, topics);
2476
+ return `${topics.length} topics set`;
2477
+ }
2478
+ // src/capabilities/variables.ts
2479
+ /** GitHub's rule for a variable name: letters, digits and underscores, not starting with a digit or `GITHUB_`. */
2480
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
2481
+ /** Longest name GitHub accepts. */
2482
+ const MAX_NAME = 256;
2483
+ function assertNames(names) {
2484
+ 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_`);
2485
+ }
2486
+ /** GitHub treats variable names as case-insensitive, so every comparison goes through this. */
2487
+ const key = (name) => name.toUpperCase();
2488
+ /**
2489
+ * Bring one scope's variables in line with the declaration: create what is missing, update what differs, leave what
2490
+ * already matches. Variables that exist but are not declared are left alone, or deleted with `prune`, except an
2491
+ * organization variable limited to selected repositories, which this client cannot manage and so is never deleted.
2492
+ * Returns a one-line summary, naming the ones left so drift is visible. In a dry run it only describes the changes.
2493
+ */
2494
+ async function reconcile(client, repo, scope, wanted, opts) {
2495
+ assertNames(wanted.map((w) => w.name));
2496
+ const existing = new Map((await client.variables.listVariables(repo, scope)).map((v) => [key(v.name), v]));
2497
+ const counts = {
2498
+ created: 0,
2499
+ updated: 0,
2500
+ unchanged: 0,
2501
+ deleted: 0
2502
+ };
2503
+ for (const want of wanted) {
2504
+ const have = existing.get(key(want.name));
2505
+ const body = {
2506
+ name: want.name,
2507
+ value: want.value
2508
+ };
2509
+ if (want.visibility) body["visibility"] = want.visibility;
2510
+ if (!have) {
2511
+ if (opts.dryRun) {
2512
+ counts.created++;
2513
+ continue;
2514
+ }
2515
+ try {
2516
+ await client.variables.createVariable(repo, scope, body);
2517
+ counts.created++;
2518
+ continue;
2519
+ } catch (err) {
2520
+ if (!(err instanceof ProviderApiError && (err.status === 409 || err.status === 422))) throw err;
2521
+ }
2522
+ } else if (have.value === want.value && (!want.visibility || have.visibility === want.visibility)) {
2523
+ counts.unchanged++;
2524
+ continue;
2525
+ }
2526
+ if (!opts.dryRun) await client.variables.updateVariable(repo, scope, have?.name ?? want.name, body);
2527
+ counts.updated++;
2528
+ }
2529
+ const declared = new Set(wanted.map((w) => key(w.name)));
2530
+ const undeclared = [...existing.entries()].filter(([k]) => !declared.has(k)).map(([, v]) => v);
2531
+ const unmanaged = undeclared.filter((v) => v.visibility === "selected");
2532
+ if (opts.prune) for (const v of undeclared.filter((u) => u.visibility !== "selected")) {
2533
+ if (!opts.dryRun) await client.variables.deleteVariable(repo, scope, v.name);
2534
+ counts.deleted++;
2535
+ }
2536
+ const parts = opts.dryRun ? [
2537
+ `would create ${counts.created}`,
2538
+ `would update ${counts.updated}`,
2539
+ `${counts.unchanged} unchanged`
2540
+ ] : [
2541
+ `${counts.created} created`,
2542
+ `${counts.updated} updated`,
2543
+ `${counts.unchanged} unchanged`
2544
+ ];
2545
+ if (counts.deleted > 0) parts.push(`${counts.deleted} ${opts.dryRun ? "would be deleted" : "deleted"}`);
2546
+ const left = opts.prune ? unmanaged : undeclared;
2547
+ if (left.length > 0) {
2548
+ const why = opts.prune ? "limited to selected repositories, not managed" : "not declared, left alone";
2549
+ parts.push(`${left.length} ${why}: ${left.map((v) => v.name).join(", ")}`);
2550
+ }
2551
+ return parts.join(", ");
2552
+ }
2553
+ /** Reconcile a repository's Actions variables. */
2554
+ function syncVariables(client, repo, variables, opts = {}) {
2555
+ return reconcile(client, repo, { kind: "repo" }, Object.entries(variables).map(([name, value]) => ({
2556
+ name,
2557
+ value
2558
+ })), {
2559
+ prune: opts.prune === true,
2560
+ dryRun: opts.dryRun === true
2561
+ });
2562
+ }
2563
+ /** Reconcile an organization's Actions variables. `repo` is only the coordinate the client is bound to. */
2564
+ function syncOrgVariables(client, repo, org, variables, opts = {}) {
2565
+ const wanted = Object.entries(variables).map(([name, v]) => ({
2566
+ name,
2567
+ value: v.value,
2568
+ visibility: v.visibility
2569
+ }));
2570
+ return reconcile(client, repo, {
2571
+ kind: "organization",
2572
+ org
2573
+ }, wanted, {
2574
+ prune: opts.prune === true,
2575
+ dryRun: opts.dryRun === true
2576
+ });
478
2577
  }
479
- //#endregion
480
- //#region src/capabilities/source.ts
2578
+ // src/capabilities/source.ts
2579
+ /**
2580
+ * The GitHub implementation of the `source` capability: repo settings, rulesets, branch protection, security
2581
+ * features and local workflow files.
2582
+ */
481
2583
  var GitHubSource = class {
482
2584
  client;
2585
+ /** Capability key, always `"source"`. */
483
2586
  key = "source";
2587
+ /** Provider name, always `"github"`. */
484
2588
  providerName = "github";
485
2589
  owner;
486
2590
  name;
@@ -488,6 +2592,7 @@ var GitHubSource = class {
488
2592
  repoRoot;
489
2593
  workflowDir;
490
2594
  orgClient;
2595
+ userSyncClient;
491
2596
  baseUrl;
492
2597
  fetchImpl;
493
2598
  constructor(client, opts) {
@@ -496,15 +2601,20 @@ var GitHubSource = class {
496
2601
  this.owner = owner;
497
2602
  this.name = name;
498
2603
  this.repo = opts.repo;
499
- this.repoRoot = opts.repoRoot;
500
- this.workflowDir = join(opts.repoRoot, ".github", "workflows");
2604
+ this.repoRoot = findRootSync(opts.repoRoot, ".git", {
2605
+ fallback: "start",
2606
+ realpath: true
2607
+ });
2608
+ this.workflowDir = join(this.repoRoot, ".github", "workflows");
501
2609
  this.orgClient = opts.orgClient;
2610
+ this.userSyncClient = opts.userSyncClient;
502
2611
  this.baseUrl = opts.baseUrl;
503
2612
  this.fetchImpl = opts.fetch;
504
2613
  }
505
2614
  async whoami() {
506
2615
  return { login: (await this.client.user.getCurrentUser()).login };
507
2616
  }
2617
+ /** Returns the repo's owner, name and default branch. */
508
2618
  async getRepo() {
509
2619
  const data = await this.client.repos.getRepo(this.repo);
510
2620
  return {
@@ -513,27 +2623,34 @@ var GitHubSource = class {
513
2623
  defaultBranch: data.default_branch
514
2624
  };
515
2625
  }
2626
+ /** Lists the repo's rulesets. */
516
2627
  async listRulesets() {
517
2628
  return this.client.rulesets.listRulesets(this.repo);
518
2629
  }
2630
+ /** Creates a ruleset from the given payload. */
519
2631
  async createRuleset(payload) {
520
2632
  return this.client.rulesets.createRuleset(this.repo, payload);
521
2633
  }
2634
+ /** Updates the ruleset with the given id from the payload. */
522
2635
  async updateRuleset(id, payload) {
523
2636
  return this.client.rulesets.updateRuleset(this.repo, id, payload);
524
2637
  }
2638
+ /** Updates the repo's settings. */
525
2639
  async updateRepoSettings(settings) {
526
2640
  await this.client.repos.updateRepo(this.repo, settings);
527
2641
  }
528
2642
  async protectBranch(branch, payload) {
529
2643
  await this.client.branches.protectBranch(this.repo, branch, payload);
530
2644
  }
2645
+ /** Enables Dependabot vulnerability alerts. */
531
2646
  async enableVulnerabilityAlerts() {
532
2647
  await this.client.security.enableVulnerabilityAlerts(this.repo);
533
2648
  }
2649
+ /** Enables Dependabot automated security fixes. */
534
2650
  async enableAutomatedSecurityFixes() {
535
2651
  await this.client.security.enableAutomatedSecurityFixes(this.repo);
536
2652
  }
2653
+ /** Enables secret scanning. */
537
2654
  async enableSecretScanning() {
538
2655
  await this.client.security.enableSecretScanning(this.repo);
539
2656
  }
@@ -546,9 +2663,11 @@ var GitHubSource = class {
546
2663
  async enableDependencyGraph() {
547
2664
  await this.client.security.enableDependencyGraph(this.repo);
548
2665
  }
2666
+ /** Enables private vulnerability reporting. */
549
2667
  async enablePrivateVulnerabilityReporting() {
550
2668
  await this.client.security.enablePrivateVulnerabilityReporting(this.repo);
551
2669
  }
2670
+ /** Lists the `.yml` and `.yaml` files in `.github/workflows`, sorted by name; empty when the folder is missing. */
552
2671
  async listWorkflowFiles() {
553
2672
  try {
554
2673
  return (await readdir(this.workflowDir)).filter((e) => e.endsWith(".yml") || e.endsWith(".yaml")).sort();
@@ -557,6 +2676,7 @@ var GitHubSource = class {
557
2676
  throw err;
558
2677
  }
559
2678
  }
2679
+ /** Reads a workflow file's text, or `null` when it does not exist. */
560
2680
  async readWorkflowFile(name) {
561
2681
  try {
562
2682
  return await readFile(join(this.workflowDir, name), "utf8");
@@ -565,10 +2685,12 @@ var GitHubSource = class {
565
2685
  throw err;
566
2686
  }
567
2687
  }
2688
+ /** Writes a workflow file, creating `.github/workflows` first when needed. */
568
2689
  async writeWorkflowFile(name, contents) {
569
2690
  await ensureDir(this.workflowDir);
570
2691
  await writeFile(join(this.workflowDir, name), contents, "utf8");
571
2692
  }
2693
+ /** Removes a workflow file; a file that is already gone is not an error. */
572
2694
  async removeWorkflowFile(name) {
573
2695
  try {
574
2696
  await rm(join(this.workflowDir, name));
@@ -585,15 +2707,87 @@ var GitHubSource = class {
585
2707
  async syncLabels(canonical, stale) {
586
2708
  return syncLabels(this.client, this.repo, canonical, stale);
587
2709
  }
2710
+ async ensureLabels(labels) {
2711
+ return ensureLabels(this.client, this.repo, labels);
2712
+ }
588
2713
  async syncProperties(values) {
589
- return syncProperties(this.client, this.repo, values);
2714
+ return syncProperties(this.client, this.repo, values, this.orgClient ?? this.client);
2715
+ }
2716
+ async getOrgPropertyValues(name) {
2717
+ return getOrgPropertyValues(this.orgClient ?? this.client, this.repo, name);
2718
+ }
2719
+ async addOrgPropertyValues(name, values) {
2720
+ return addOrgPropertyValues(this.orgClient ?? this.client, this.repo, name, values, this.orgClient !== void 0);
2721
+ }
2722
+ async checkPropertyValues(values) {
2723
+ return checkPropertyValues(this.orgClient ?? this.client, this.repo, values);
590
2724
  }
591
2725
  async syncTeams(teams) {
592
2726
  return syncTeams(this.orgClient ?? this.client, this.repo, teams);
593
2727
  }
2728
+ async teamMembers(teamSlug, org = this.owner) {
2729
+ return (await (this.orgClient ?? this.client).teams.members(org, teamSlug)).map((m) => ({
2730
+ id: String(m.id),
2731
+ login: m.login
2732
+ }));
2733
+ }
2734
+ async readFile(path, repo = this.repo) {
2735
+ return readRepoFile(this.userSyncClient ?? this.orgClient ?? this.client, repo, path);
2736
+ }
2737
+ async writeFile(path, content, opts) {
2738
+ return writeRepoFile(this.userSyncClient ?? this.orgClient ?? this.client, opts.repo ?? this.repo, path, content, opts);
2739
+ }
594
2740
  async syncTopics(topics) {
595
2741
  return syncTopics(this.client, this.repo, topics);
596
2742
  }
2743
+ async syncVariables(variables, opts) {
2744
+ return syncVariables(this.client, this.repo, variables, opts);
2745
+ }
2746
+ async syncOrgVariables(org, variables, opts) {
2747
+ if (!this.orgClient) throw new Error("organization variables need the org token: set HOLOCRON_ORG_TOKEN or run `holocron new token github.org <token>`");
2748
+ return syncOrgVariables(this.orgClient, this.repo, org, variables, opts);
2749
+ }
2750
+ async listVariables() {
2751
+ const found = await this.client.variables.listVariables(this.repo, { kind: "repo" });
2752
+ return Object.fromEntries(found.map((v) => [v.name, v.value]));
2753
+ }
2754
+ async listOrgVariables(org) {
2755
+ if (!this.orgClient) throw new MissingTokenError("organization variables need the org token: set HOLOCRON_ORG_TOKEN or run `holocron new token github.org <token>`");
2756
+ const found = await this.orgClient.variables.listVariables(this.repo, {
2757
+ kind: "organization",
2758
+ org
2759
+ });
2760
+ return Object.fromEntries(found.map((v) => [v.name, {
2761
+ value: v.value,
2762
+ visibility: v.visibility ?? "all"
2763
+ }]));
2764
+ }
2765
+ async getRepoInfo() {
2766
+ return readRepoInfo(this.client, this.repo);
2767
+ }
2768
+ async getProperties() {
2769
+ const found = await this.client.properties.getValues(this.repo);
2770
+ return Object.fromEntries(found.flatMap((p) => p.value === null ? [] : [[p.property_name, p.value]]));
2771
+ }
2772
+ async listLabels() {
2773
+ return (await this.client.labels.listLabels(this.repo)).map((l) => ({
2774
+ name: l.name,
2775
+ color: l.color,
2776
+ description: l.description ?? ""
2777
+ }));
2778
+ }
2779
+ async listTeamAccess() {
2780
+ return (await (this.orgClient ?? this.client).teams.listForRepo(this.repo)).map((t) => ({
2781
+ slug: t.slug,
2782
+ permission: t.permission
2783
+ }));
2784
+ }
2785
+ async getRulesetDetail(id) {
2786
+ return toRulesetDetail(await this.client.rulesets.getRuleset(this.repo, id));
2787
+ }
2788
+ async getSecurity() {
2789
+ return readSecurity(this.client, this.repo);
2790
+ }
597
2791
  async syncDescription(description) {
598
2792
  await this.client.repos.updateRepo(this.repo, { description });
599
2793
  return "description updated";
@@ -603,15 +2797,43 @@ var GitHubSource = class {
603
2797
  return "homepage updated";
604
2798
  }
605
2799
  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
- };
2800
+ return toPullRequest(await this.client.pulls.getPullRequest(repo ?? this.repo, number));
2801
+ }
2802
+ async listPullRequests(state, repo) {
2803
+ return (await this.client.pulls.listPullRequests(repo ?? this.repo, state)).map(toPullRequest);
2804
+ }
2805
+ async listBranches(repo) {
2806
+ return (await this.client.branches.listBranches(repo ?? this.repo)).map((b) => ({
2807
+ name: b.name,
2808
+ sha: b.commit.sha
2809
+ }));
2810
+ }
2811
+ async deleteBranch(name, repo) {
2812
+ try {
2813
+ await this.client.branches.removeBranch(repo ?? this.repo, name);
2814
+ } catch (err) {
2815
+ if (err instanceof ProviderApiError && err.status === 422 && String(err.details).includes("does not exist")) return;
2816
+ throw err;
2817
+ }
2818
+ }
2819
+ async listPullRequestCommits(number, repo) {
2820
+ return (await this.client.pulls.listCommits(repo ?? this.repo, number)).map((commit) => commit.sha);
2821
+ }
2822
+ async listPullRequestFiles(number, repo) {
2823
+ const files = await this.client.pulls.listFiles(repo ?? this.repo, number);
2824
+ return [...new Set(files.flatMap((f) => f.previous_filename ? [f.filename, f.previous_filename] : [f.filename]))];
2825
+ }
2826
+ async createPullRequest(input, repo) {
2827
+ return createPullRequest(this.client, repo ?? this.repo, input);
2828
+ }
2829
+ async updatePullRequest(number, patch, repo) {
2830
+ return updatePullRequest(this.client, repo ?? this.repo, number, patch);
2831
+ }
2832
+ async markReady(number, repo) {
2833
+ return markReady(this.client, repo ?? this.repo, number);
2834
+ }
2835
+ async getPullRequestChecks(number, repo) {
2836
+ return readPullRequestChecks(this.client, repo ?? this.repo, number);
615
2837
  }
616
2838
  async configurePages(config, token) {
617
2839
  const pagesClient = createGitHubClient$1({
@@ -650,18 +2872,1136 @@ async function ensureDir(path) {
650
2872
  throw err;
651
2873
  }
652
2874
  }
653
- //#endregion
654
- //#region src/verify-token.ts
2875
+ // src/probes/issue-types/github-api.ts
2876
+ const PAGE = 100;
2877
+ const PROJECTS_OF = `query($ids: [ID!]!) { nodes(ids: $ids) { ... on Issue { id projectItems(first: 20) { nodes { project { id } } } } } }`;
2878
+ const ADD_ITEM = `mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`;
2879
+ const ISSUE_TYPES = `query($org: String!) { organization(login: $org) { issueTypes(first: 50) { nodes { name } } } }`;
2880
+ function toItem(issue) {
2881
+ return {
2882
+ number: issue.number,
2883
+ title: issue.title,
2884
+ state: issue.state,
2885
+ labels: issue.labels.map((l) => l.name),
2886
+ type: issue.type?.name ?? null,
2887
+ milestone: issue.milestone ?? null,
2888
+ nodeId: issue.node_id ?? "",
2889
+ isPullRequest: issue.pull_request !== void 0,
2890
+ createdAt: issue.created_at ?? ""
2891
+ };
2892
+ }
2893
+ /**
2894
+ * The backfill's reads and writes over the GitHub client. `client` reads and writes issues (the `github.issues` token);
2895
+ * `orgClient` reads and writes the organization's projects (the `github.org` token). Each method is the one call, or the
2896
+ * fixed few, its name says, so the probe's logic is tested against a fake of {@link BackfillApi} and this stays thin.
2897
+ */
2898
+ function createBackfillApi(client, orgClient, repo) {
2899
+ const org = repo.split("/")[0];
2900
+ const projects = new GitHubProjects(orgClient.graphql, { repo });
2901
+ let fieldList;
2902
+ const fields = async () => fieldList ??= client.issueFields.list(org);
2903
+ return {
2904
+ async list(page) {
2905
+ return (await client.issues.listIssues(repo, {
2906
+ state: "all",
2907
+ sort: "created",
2908
+ direction: "asc",
2909
+ per_page: PAGE,
2910
+ page
2911
+ })).map(toItem);
2912
+ },
2913
+ async get(number) {
2914
+ return toItem(await client.issues.getIssue(repo, number));
2915
+ },
2916
+ async parent(number) {
2917
+ const parent = await client.issues.getParent(repo, number);
2918
+ return parent ? {
2919
+ number: parent.number,
2920
+ milestone: parent.milestone?.number ?? null
2921
+ } : null;
2922
+ },
2923
+ async labelNames() {
2924
+ return new Set((await client.labels.listLabels(repo)).map((l) => l.name.toLowerCase()));
2925
+ },
2926
+ async milestoneNumber(title) {
2927
+ return (await client.issues.listMilestones(repo, { state: "all" })).find((m) => m.title.toLowerCase() === title.toLowerCase())?.number;
2928
+ },
2929
+ async projectId(title) {
2930
+ return (await projects.find(org, title))?.id;
2931
+ },
2932
+ async projectsOf(nodeIds) {
2933
+ const data = await orgClient.graphql.query(PROJECTS_OF, { ids: nodeIds });
2934
+ const out = /* @__PURE__ */ new Map();
2935
+ for (const node of data.nodes) if (node?.id) out.set(node.id, (node.projectItems?.nodes ?? []).map((i) => i.project.id));
2936
+ return out;
2937
+ },
2938
+ async fieldNames() {
2939
+ try {
2940
+ return new Set((await fields()).map((f) => f.name.toLowerCase()));
2941
+ } catch (err) {
2942
+ const why = fieldRefusal(err);
2943
+ if (why === void 0) throw err;
2944
+ return why;
2945
+ }
2946
+ },
2947
+ async fieldValues(number) {
2948
+ const byId = new Map((await fields()).map((f) => [f.id, f.name.toLowerCase()]));
2949
+ const values = await client.issueFields.values(repo, number);
2950
+ return new Set(values.map((v) => v.issue_field_name?.toLowerCase() ?? byId.get(v.issue_field_id) ?? ""));
2951
+ },
2952
+ async files(number) {
2953
+ return (await client.pulls.listFiles(repo, number)).map((f) => f.filename);
2954
+ },
2955
+ async typeNames() {
2956
+ const data = await orgClient.graphql.query(ISSUE_TYPES, { org });
2957
+ return new Set((data.organization?.issueTypes?.nodes ?? []).map((t) => t.name));
2958
+ },
2959
+ async readFile(path) {
2960
+ return (await readRepoFile(client, repo, path))?.content ?? null;
2961
+ },
2962
+ async setType(number, type) {
2963
+ await client.issues.updateIssue(repo, number, { type });
2964
+ },
2965
+ async addLabels(number, labels) {
2966
+ await client.issues.addLabels(repo, number, labels);
2967
+ },
2968
+ async setMilestone(number, milestone) {
2969
+ await client.issues.updateIssue(repo, number, { milestone });
2970
+ },
2971
+ async addToProject(projectId, nodeId) {
2972
+ await orgClient.graphql.query(ADD_ITEM, {
2973
+ project: projectId,
2974
+ content: nodeId
2975
+ });
2976
+ }
2977
+ };
2978
+ }
2979
+ // src/probes/issue-types/gather.ts
2980
+ /** Whether a day (`YYYY-MM-DD`) is before the start of the window. */
2981
+ const before = (item, since) => since !== void 0 && item.createdAt.slice(0, 10) < since;
2982
+ /** The issues named by `--issues`, past the cursor, at most `limit` of them. */
2983
+ async function named(api, options, isRateLimited) {
2984
+ const numbers = [...new Set(options.issues)].sort((a, b) => a - b).filter((n) => n > options.after);
2985
+ const out = {
2986
+ items: [],
2987
+ more: numbers.length > options.limit,
2988
+ rateLimited: false,
2989
+ pullRequestsSkipped: 0
2990
+ };
2991
+ for (const number of numbers.slice(0, options.limit)) try {
2992
+ const item = await api.get(number);
2993
+ if (item.isPullRequest && !options.pullRequests) out.pullRequestsSkipped++;
2994
+ else out.items.push(item);
2995
+ } catch (err) {
2996
+ if (!isRateLimited(err)) throw err;
2997
+ return {
2998
+ ...out,
2999
+ more: true,
3000
+ rateLimited: true
3001
+ };
3002
+ }
3003
+ return out;
3004
+ }
3005
+ /**
3006
+ * The items one run looks at: with `--issues` those numbers, otherwise every issue of the repository oldest first, a
3007
+ * page at a time, past the `--after` cursor and on or after `--since`, until `--limit` are kept. Issue numbers rise with
3008
+ * creation, so the last number read is a cursor the next run can resume from. A rate limit ends the read with what it has.
3009
+ */
3010
+ async function gather(api, options, isRateLimited) {
3011
+ if (options.issues) return named(api, options, isRateLimited);
3012
+ const out = {
3013
+ items: [],
3014
+ more: false,
3015
+ rateLimited: false,
3016
+ pullRequestsSkipped: 0
3017
+ };
3018
+ try {
3019
+ for (let page = 1;; page++) {
3020
+ const batch = await api.list(page);
3021
+ if (batch.length === 0) return out;
3022
+ for (const item of batch) {
3023
+ if (item.number <= options.after || before(item, options.since)) continue;
3024
+ if (item.isPullRequest && !options.pullRequests) {
3025
+ out.pullRequestsSkipped++;
3026
+ continue;
3027
+ }
3028
+ if (out.items.length >= options.limit) return {
3029
+ ...out,
3030
+ more: true
3031
+ };
3032
+ out.items.push(item);
3033
+ }
3034
+ }
3035
+ } catch (err) {
3036
+ if (!isRateLimited(err)) throw err;
3037
+ return {
3038
+ ...out,
3039
+ more: true,
3040
+ rateLimited: true
3041
+ };
3042
+ }
3043
+ }
3044
+ // src/probes/issue-types/kinds.ts
3045
+ /** The kind labels and the Type each one means (spec `tech-github-area-labels`, decision 3). */
3046
+ const DEFAULT_MAIN_KINDS = {
3047
+ bug: "Bug",
3048
+ enhancement: "Feature",
3049
+ chore: "Task"
3050
+ };
3051
+ /** The other kind labels, which mean Task only when none of the main ones is on the issue (issue #2494). */
3052
+ const DEFAULT_FALLBACK_KINDS = Object.fromEntries([
3053
+ "ci",
3054
+ "documentation",
3055
+ "refactor",
3056
+ "test",
3057
+ "performance",
3058
+ "dependencies"
3059
+ ].map((label) => [label, "Task"]));
3060
+ const lowered = (table) => Object.fromEntries(Object.entries(table).map(([label, type]) => [label.toLowerCase(), type]));
3061
+ /** The tables a run uses: what `repo.labels` sets, else the defaults, table by table. */
3062
+ function resolveKinds(config) {
3063
+ return {
3064
+ main: config.kinds ? lowered(config.kinds) : DEFAULT_MAIN_KINDS,
3065
+ fallback: config.fallbackKinds ? lowered(config.fallbackKinds) : DEFAULT_FALLBACK_KINDS
3066
+ };
3067
+ }
3068
+ /** The Types the tables name that `known` (the organization's Types) lacks, each with the labels that use it. */
3069
+ function unknownTypes(kinds, known) {
3070
+ const byType = /* @__PURE__ */ new Map();
3071
+ for (const [label, type] of [...Object.entries(kinds.main), ...Object.entries(kinds.fallback)]) if (!known.has(type)) byType.set(type, [...byType.get(type) ?? [], label]);
3072
+ return [...byType].map(([type, labels]) => ({
3073
+ type,
3074
+ labels
3075
+ }));
3076
+ }
3077
+ // src/probes/issue-types/plan-type.ts
3078
+ /** The labels of an issue that `table` knows, each once (lower case), in the issue's order. */
3079
+ const matching = (labels, table) => [...new Set(labels.map((l) => l.toLowerCase()).filter((l) => Object.hasOwn(table, l)))];
3080
+ /**
3081
+ * The Type an issue gets from its kind labels. One that has a Type keeps it, whatever its labels say. Otherwise the main
3082
+ * table decides (`bug`, `enhancement`, `chore` by default), and only an issue with none of those looks at the fallback
3083
+ * table (`ci`, `documentation`, `refactor`, `test`, `performance`, `dependencies`, all Task by default; #2494). Labels
3084
+ * that point to one Type set it, however many they are; labels that point to two different Types are `ambiguous` and left
3085
+ * for a person (the spec's rule: the probe never picks between two kinds); one with no label in either table has no source.
3086
+ */
3087
+ function planType(item, kinds) {
3088
+ if (item.type) return { skip: "typed" };
3089
+ for (const table of [kinds.main, kinds.fallback]) {
3090
+ const found = matching(item.labels, table);
3091
+ if (found.length === 0) continue;
3092
+ if (new Set(found.map((l) => table[l])).size > 1) return {
3093
+ skip: "ambiguous",
3094
+ labels: found
3095
+ };
3096
+ return { set: table[found[0]] };
3097
+ }
3098
+ return { skip: "no-kind-label" };
3099
+ }
3100
+ // src/probes/issue-types/report.ts
3101
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
3102
+ const GROUPS = [
3103
+ ["project", "a project"],
3104
+ ["milestone", "a milestone"],
3105
+ ["priority", "a Priority"],
3106
+ ["effort", "an Effort"]
3107
+ ];
3108
+ /** The command the maintainer runs to continue, from the cursor. */
3109
+ function resumeCommand(options, cursor) {
3110
+ const flags = ["--after", String(cursor)];
3111
+ if (options.issues) flags.push("--issues", options.issues.join(","));
3112
+ if (options.since) flags.push("--since", options.since);
3113
+ flags.push("--limit", String(options.limit));
3114
+ if (options.repo) flags.push("--repo", options.repo);
3115
+ if (options.milestone) flags.push("--milestone", options.milestone);
3116
+ if (options.project) flags.push("--project", options.project);
3117
+ if (options.pullRequests) flags.push("--pull-requests");
3118
+ return `holocron probe github issue-types -- ${flags.join(" ")}`;
3119
+ }
3120
+ /** Prints the counts, what was left for a person, the lists of what is still missing and how to go on. */
3121
+ function reportBackfill(ctx, input) {
3122
+ const { tally, options, dryRun, more, rateLimited, fields } = input;
3123
+ const verb = dryRun ? "would be set" : "set";
3124
+ ctx.say({
3125
+ status: "heading",
3126
+ label: "Backfill"
3127
+ });
3128
+ const passed = tally.pullRequestsSkipped;
3129
+ ctx.say({
3130
+ status: "info",
3131
+ label: "summary",
3132
+ detail: `read ${plural(tally.examined, "item")}` + (tally.pullRequestsRead > 0 ? ` (${plural(tally.pullRequestsRead, "pull request")})` : "") + `; ${dryRun ? "would change" : "changed"} ${tally.changed}; passed over ${plural(passed, "pull request")}${passed > 0 ? " (give --pull-requests to include them)" : ""}; ${plural(tally.failed, "failure")}` + (more ? `; ${rateLimited ? "stopped by GitHub's rate limit" : `stopped at the limit of ${options.limit}`}, more remain` : "; the window is finished")
3133
+ });
3134
+ const types = Object.entries(tally.typeSet).map(([name, n]) => `${name} ${n}`).join(", ");
3135
+ ctx.say({
3136
+ status: "info",
3137
+ label: "Type",
3138
+ detail: `${types || "none"} ${verb}; ${tally.typed} already typed, ${tally.noKind} with no label that maps to a Type, ${tally.ambiguous.length} with two kind labels`
3139
+ });
3140
+ for (const a of tally.ambiguous) ctx.say({
3141
+ status: "info",
3142
+ label: `#${a.number}`,
3143
+ detail: `has ${a.labels.join(" and ")}: left for a person to choose`
3144
+ });
3145
+ ctx.say({
3146
+ status: "info",
3147
+ label: "area labels",
3148
+ detail: `added to ${plural(tally.areaLabelsAdded, "item")}`
3149
+ });
3150
+ for (const label of tally.missingAreaLabels) ctx.say({
3151
+ status: "info",
3152
+ label,
3153
+ detail: "wanted but the repository has no such label: run `holocron setup` first"
3154
+ });
3155
+ ctx.say({
3156
+ status: "info",
3157
+ label: "milestone",
3158
+ detail: `${verb} on ${tally.milestoneSet.parent + tally.milestoneSet.explicit} (${tally.milestoneSet.parent} from a parent, ${tally.milestoneSet.explicit} from --milestone)`
3159
+ });
3160
+ ctx.say({
3161
+ status: "info",
3162
+ label: "project",
3163
+ detail: `${plural(tally.projectSet, "issue")} ${dryRun ? "would be added" : "added"} from --project`
3164
+ });
3165
+ ctx.say({
3166
+ status: "heading",
3167
+ label: `Still lacking, among the ${plural(tally.examined, "item")} read${dryRun ? ", after the changes above" : ""}`
3168
+ });
3169
+ if (tally.skippedFields !== void 0) ctx.say({
3170
+ status: "fail",
3171
+ label: "Priority, Effort",
3172
+ detail: `NOT checked, so the lists below are incomplete: the token (github.issues) was refused reading the organization issue fields (${tally.skippedFields})`
3173
+ });
3174
+ for (const [group, noun] of GROUPS) {
3175
+ if (!(group === "project" || group === "milestone" || fields.includes(group))) continue;
3176
+ const items = tally.lacking[group];
3177
+ ctx.say({
3178
+ status: "info",
3179
+ label: `without ${noun}`,
3180
+ detail: `${items.length} of ${plural(tally.examined, "item")} read`
3181
+ });
3182
+ for (const item of items) ctx.say({
3183
+ status: "info",
3184
+ label: `#${item.number}`,
3185
+ detail: `${item.state}: ${item.title}`
3186
+ });
3187
+ }
3188
+ if (more && tally.last !== void 0) ctx.say({
3189
+ status: "info",
3190
+ label: "resume",
3191
+ detail: `${rateLimited ? "GitHub's rate limit stopped the run" : "the limit was reached"}; to continue: ${resumeCommand(options, tally.last)}`
3192
+ });
3193
+ else if (more) ctx.say({
3194
+ status: "info",
3195
+ label: "resume",
3196
+ detail: "GitHub's rate limit stopped the run before it finished one item; run it again later"
3197
+ });
3198
+ else ctx.say({
3199
+ status: "info",
3200
+ label: "resume",
3201
+ detail: "the window is finished"
3202
+ });
3203
+ }
3204
+ // src/probes/issue-types/backfill.ts
3205
+ /** The numbers the report is made of. */
3206
+ const emptyTally = () => ({
3207
+ examined: 0,
3208
+ pullRequestsSkipped: 0,
3209
+ typeSet: {},
3210
+ typed: 0,
3211
+ noKind: 0,
3212
+ ambiguous: [],
3213
+ areaLabelsAdded: 0,
3214
+ missingAreaLabels: /* @__PURE__ */ new Set(),
3215
+ milestoneSet: {
3216
+ parent: 0,
3217
+ explicit: 0
3218
+ },
3219
+ projectSet: 0,
3220
+ lacking: {
3221
+ project: [],
3222
+ milestone: [],
3223
+ priority: [],
3224
+ effort: []
3225
+ },
3226
+ failed: 0,
3227
+ changed: 0,
3228
+ pullRequestsRead: 0,
3229
+ last: void 0,
3230
+ skippedFields: void 0
3231
+ });
3232
+ /** How many changes the tally holds, to tell whether one item added any. */
3233
+ const changes = (t) => Object.values(t.typeSet).reduce((a, b) => a + b, 0) + t.areaLabelsAdded + t.milestoneSet.parent + t.milestoneSet.explicit + t.projectSet;
3234
+ /** How an issue is named in a row. */
3235
+ const labelOf = (item) => `#${item.number}`;
3236
+ /** Reads what the run needs before it starts: labels, the named milestone and project, the organization's issue fields. Says why and returns nothing when a name does not exist. */
3237
+ async function prepare(run, tally) {
3238
+ const { api, ctx, options } = run;
3239
+ const known = await api.typeNames();
3240
+ const unknown = unknownTypes(run.kinds, known);
3241
+ for (const { type, labels } of unknown) ctx.say({
3242
+ status: "fail",
3243
+ label: "Type",
3244
+ detail: `${type} (for ${labels.join(", ")}) is not an issue Type of this organization; its Types are ${[...known].join(", ") || "none"}`
3245
+ });
3246
+ if (unknown.length > 0) return void 0;
3247
+ const setup = {
3248
+ labelNames: await api.labelNames(),
3249
+ fields: []
3250
+ };
3251
+ if (options.milestone !== void 0) {
3252
+ setup.milestone = await api.milestoneNumber(options.milestone);
3253
+ if (setup.milestone === void 0) {
3254
+ ctx.say({
3255
+ status: "fail",
3256
+ label: "milestone",
3257
+ detail: `${options.milestone} is not a milestone of this repository`
3258
+ });
3259
+ return;
3260
+ }
3261
+ }
3262
+ if (options.project !== void 0) {
3263
+ setup.projectId = await api.projectId(options.project);
3264
+ if (setup.projectId === void 0) {
3265
+ ctx.say({
3266
+ status: "fail",
3267
+ label: "project",
3268
+ detail: `${options.project} is not a project of this organization`
3269
+ });
3270
+ return;
3271
+ }
3272
+ }
3273
+ const names = await api.fieldNames();
3274
+ if (typeof names === "string") tally.skippedFields = names;
3275
+ else setup.fields = ["priority", "effort"].filter((f) => names.has(f));
3276
+ return setup;
3277
+ }
3278
+ /** Does one issue or pull request; throws for a rate limit or a failed request, which the caller tells apart. */
3279
+ async function handle(run, setup, tally, item, projects) {
3280
+ const { api, ctx, areas, options } = run;
3281
+ const n = item.number;
3282
+ const wanted = item.isPullRequest ? areaLabelsForFiles(await api.files(n), areas.areas) : areaLabelsForTitle(item.title, areas.scopes);
3283
+ const have = new Set(item.labels.map((l) => l.toLowerCase()));
3284
+ const add = [];
3285
+ for (const label of wanted) {
3286
+ if (have.has(label.toLowerCase())) continue;
3287
+ if (setup.labelNames.has(label.toLowerCase())) add.push(label);
3288
+ else tally.missingAreaLabels.add(label);
3289
+ }
3290
+ if (add.length > 0) {
3291
+ await ctx.write(`add ${add.join(", ")} to ${labelOf(item)}`, () => api.addLabels(n, add));
3292
+ tally.areaLabelsAdded++;
3293
+ }
3294
+ if (item.isPullRequest) return;
3295
+ const type = planType(item, run.kinds);
3296
+ if ("set" in type) {
3297
+ await ctx.write(`set Type ${type.set} on ${labelOf(item)}`, () => api.setType(n, type.set));
3298
+ tally.typeSet[type.set] = (tally.typeSet[type.set] ?? 0) + 1;
3299
+ } else if (type.skip === "typed") tally.typed++;
3300
+ else if (type.skip === "no-kind-label") tally.noKind++;
3301
+ else tally.ambiguous.push({
3302
+ number: n,
3303
+ labels: type.labels
3304
+ });
3305
+ let milestone = item.milestone !== null;
3306
+ if (!milestone) {
3307
+ const parent = await api.parent(n);
3308
+ const fromParent = parent?.milestone;
3309
+ const target = fromParent ?? setup.milestone;
3310
+ if (target !== void 0) {
3311
+ const source = typeof fromParent === "number" ? "parent" : "explicit";
3312
+ const why = source === "parent" ? `from its parent #${parent?.number}` : `from --milestone ${options.milestone}`;
3313
+ await ctx.write(`set milestone on ${labelOf(item)} ${why}`, () => api.setMilestone(n, target));
3314
+ tally.milestoneSet[source]++;
3315
+ milestone = true;
3316
+ }
3317
+ }
3318
+ if (!milestone) tally.lacking.milestone.push(item);
3319
+ let onProject = projects.length > 0;
3320
+ if (!onProject && setup.projectId !== void 0) {
3321
+ const id = setup.projectId;
3322
+ await ctx.write(`add ${labelOf(item)} to project ${options.project}`, () => api.addToProject(id, item.nodeId));
3323
+ tally.projectSet++;
3324
+ onProject = true;
3325
+ }
3326
+ if (!onProject) tally.lacking.project.push(item);
3327
+ if (setup.fields.length > 0) {
3328
+ const values = await api.fieldValues(n);
3329
+ for (const field of setup.fields) if (!values.has(field)) tally.lacking[field].push(item);
3330
+ }
3331
+ }
3332
+ /**
3333
+ * The backfill of `holocron probe github issue-types` (spec `tech-github-area-labels`, rollout item 5): reads a window of
3334
+ * issues, and for each adds what it can derive and nothing else.
3335
+ *
3336
+ * - **Type** from the kind labels (`bug`, `enhancement`, `chore`, else Task for `ci`, `documentation`, `refactor`, `test`,
3337
+ * `performance`, `dependencies`); one that has a Type keeps it, one with two kind labels
3338
+ * is listed and left.
3339
+ * - **Area labels** from the title's scope, or, for a pull request with `--pull-requests`, from its changed files; only
3340
+ * added, and only when the label exists (`holocron setup` makes them).
3341
+ * - **Milestone** from the issue's parent, else `--milestone` for an issue in the window named by `--issues` or `--since`.
3342
+ * - **Project** from `--project` for such an issue that is on no project.
3343
+ *
3344
+ * Nothing is overwritten and no label is removed. Priority and Effort are never set, only listed when missing. Every
3345
+ * change goes through `ctx.write`, so `--dry-run` says `would ...` and writes nothing. A rate limit ends the run with the
3346
+ * cursor to resume from; any other failure is a row for that issue and the run goes on.
3347
+ */
3348
+ async function runBackfill(run) {
3349
+ const { ctx, api, options } = run;
3350
+ const tally = emptyTally();
3351
+ const setup = await prepare(run, tally);
3352
+ if (!setup) return;
3353
+ const read = await gather(api, options, run.isRateLimited);
3354
+ tally.pullRequestsSkipped = read.pullRequestsSkipped;
3355
+ const projects = /* @__PURE__ */ new Map();
3356
+ const ids = read.items.filter((i) => !i.isPullRequest).map((i) => i.nodeId);
3357
+ try {
3358
+ for (let at = 0; at < ids.length; at += 100) for (const [id, found] of await api.projectsOf(ids.slice(at, at + 100))) projects.set(id, found);
3359
+ } catch (err) {
3360
+ if (!run.isRateLimited(err)) throw err;
3361
+ read.rateLimited = true;
3362
+ read.more = true;
3363
+ read.items.length = 0;
3364
+ }
3365
+ let stopped = read.rateLimited;
3366
+ for (const item of read.items) {
3367
+ const before = changes(tally);
3368
+ try {
3369
+ await handle(run, setup, tally, item, projects.get(item.nodeId) ?? []);
3370
+ if (changes(tally) > before) tally.changed++;
3371
+ } catch (err) {
3372
+ if (run.isRateLimited(err)) {
3373
+ stopped = true;
3374
+ break;
3375
+ }
3376
+ ctx.say({
3377
+ status: "fail",
3378
+ label: labelOf(item),
3379
+ detail: errorMessage(err)
3380
+ });
3381
+ tally.failed++;
3382
+ }
3383
+ tally.examined++;
3384
+ if (item.isPullRequest) tally.pullRequestsRead++;
3385
+ tally.last = item.number;
3386
+ }
3387
+ reportBackfill(ctx, {
3388
+ tally,
3389
+ options,
3390
+ dryRun: ctx.dryRun,
3391
+ more: read.more || stopped,
3392
+ rateLimited: stopped,
3393
+ fields: setup.fields
3394
+ });
3395
+ }
3396
+ const VALUED = [
3397
+ "--issues",
3398
+ "--since",
3399
+ "--after",
3400
+ "--limit",
3401
+ "--milestone",
3402
+ "--project",
3403
+ "--repo"
3404
+ ];
3405
+ const INTEGER = /^\d+$/;
3406
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
3407
+ const MAX_RANGE = 1e3;
3408
+ const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
3409
+ /** `12,15,20-23` to `[12, 15, 20, 21, 22, 23]`, or `undefined` for text that is not such a list. */
3410
+ function numbersOf(text) {
3411
+ const out = [];
3412
+ for (const part of text.split(",")) {
3413
+ const [from, to, ...rest] = part.trim().split("-");
3414
+ if (rest.length > 0 || !INTEGER.test(from)) return void 0;
3415
+ const end = to === void 0 ? Number(from) : INTEGER.test(to) ? Number(to) : -1;
3416
+ if (end < Number(from) || end - Number(from) > MAX_RANGE) return void 0;
3417
+ for (let n = Number(from); n <= end; n++) out.push(n);
3418
+ }
3419
+ return out;
3420
+ }
3421
+ /** The words after `issue-types`, read into options, or the one thing wrong with them. */
3422
+ function parseArgs(args) {
3423
+ const options = {
3424
+ after: 0,
3425
+ limit: 100,
3426
+ pullRequests: false,
3427
+ repos: []
3428
+ };
3429
+ for (let i = 0; i < args.length; i++) {
3430
+ const flag = args[i];
3431
+ if (flag === "--pull-requests") {
3432
+ options.pullRequests = true;
3433
+ continue;
3434
+ }
3435
+ if (!VALUED.includes(flag)) return {
3436
+ ok: false,
3437
+ message: `unknown argument ${flag}`
3438
+ };
3439
+ const value = args[++i];
3440
+ if (value === void 0 || value.startsWith("--")) return {
3441
+ ok: false,
3442
+ message: `${flag} needs a value`
3443
+ };
3444
+ if (flag === "--issues") {
3445
+ const issues = numbersOf(value);
3446
+ if (!issues) return {
3447
+ ok: false,
3448
+ message: `--issues takes numbers and ranges such as 12,15,20-25, not ${value}`
3449
+ };
3450
+ options.issues = issues;
3451
+ } else if (flag === "--since") {
3452
+ if (!DAY.test(value)) return {
3453
+ ok: false,
3454
+ message: `--since takes a day as YYYY-MM-DD, not ${value}`
3455
+ };
3456
+ options.since = value;
3457
+ } else if (flag === "--after") {
3458
+ if (!INTEGER.test(value)) return {
3459
+ ok: false,
3460
+ message: `--after takes a whole number, not ${value}`
3461
+ };
3462
+ options.after = Number(value);
3463
+ } else if (flag === "--limit") {
3464
+ if (!INTEGER.test(value) || Number(value) < 1) return {
3465
+ ok: false,
3466
+ message: `--limit takes a whole number of at least 1, not ${value}`
3467
+ };
3468
+ options.limit = Number(value);
3469
+ } else if (flag === "--repo") {
3470
+ if (!REPOSITORY.test(value)) return {
3471
+ ok: false,
3472
+ message: `--repo takes owner/name, not ${value}`
3473
+ };
3474
+ if (!options.repos.includes(value)) options.repos.push(value);
3475
+ } else if (flag === "--milestone") options.milestone = value;
3476
+ else options.project = value;
3477
+ }
3478
+ if ((options.milestone || options.project) && !options.issues && !options.since) return {
3479
+ ok: false,
3480
+ message: "--milestone and --project need a window to apply to: name it with --issues or --since"
3481
+ };
3482
+ if (options.repos.length > 1 && (options.issues || options.after > 0)) return {
3483
+ ok: false,
3484
+ message: "--issues and --after are numbers of one repository, so they cannot go with more than one --repo"
3485
+ };
3486
+ return {
3487
+ ok: true,
3488
+ options
3489
+ };
3490
+ }
3491
+ // src/probes/issue-types/repo-areas.ts
3492
+ /** Where a repository without a `package.json` declares `repo.labels` (the `repo` area file, spec `tech-holocron-directory`). */
3493
+ const AREA_FILE_JSON = ".holocron/repo.json";
3494
+ const AREA_FILE_TS = ".holocron/repo.ts";
3495
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3496
+ /** `repo.labels.areas` and `scopes` as the mapping reads them, or `undefined` for a shape it cannot use. */
3497
+ function areaMap(labels) {
3498
+ if (!isRecord(labels) || !isRecord(labels.areas) || Object.keys(labels.areas).length === 0) return void 0;
3499
+ const areas = labels.areas;
3500
+ if (!Object.values(areas).every((p) => Array.isArray(p) && p.every((x) => typeof x === "string"))) return void 0;
3501
+ const scopes = isRecord(labels.scopes) ? labels.scopes : {};
3502
+ if (!Object.values(scopes).every((a) => typeof a === "string")) return void 0;
3503
+ return {
3504
+ areas,
3505
+ scopes
3506
+ };
3507
+ }
3508
+ const none = (detail) => ({
3509
+ areas: {},
3510
+ row: {
3511
+ status: "info",
3512
+ label: "area labels",
3513
+ detail
3514
+ }
3515
+ });
3516
+ /**
3517
+ * The area labels another repository declares (spec `tech-backfill-config-mapping`), read from its own
3518
+ * `.holocron/repo.json`. A `.holocron/repo.ts` is TypeScript, which only Sentinel's remote config reader evaluates and a
3519
+ * plugin cannot reach, so that repository gets a skipped row and no area step; so does one with no declaration. Never
3520
+ * throws for a missing or unusable file: the Type step of the repository still runs.
3521
+ */
3522
+ async function readRepoAreas(api) {
3523
+ const json = await api.readFile(AREA_FILE_JSON);
3524
+ if (json !== null) {
3525
+ let parsed;
3526
+ try {
3527
+ parsed = JSON.parse(json);
3528
+ } catch (err) {
3529
+ return {
3530
+ areas: {},
3531
+ row: {
3532
+ status: "fail",
3533
+ label: "area labels",
3534
+ detail: `${AREA_FILE_JSON} is not JSON (${errorMessage(err)})`
3535
+ }
3536
+ };
3537
+ }
3538
+ const found = areaMap(isRecord(parsed) ? parsed.labels : void 0);
3539
+ return found ? {
3540
+ areas: found,
3541
+ row: {
3542
+ status: "info",
3543
+ label: "area labels",
3544
+ detail: `read from ${AREA_FILE_JSON}`
3545
+ }
3546
+ } : none(`skipped: ${AREA_FILE_JSON} declares no usable \`labels.areas\`, so no area labels are added`);
3547
+ }
3548
+ if (await api.readFile(AREA_FILE_TS) !== null) return none(`skipped: its areas are in ${AREA_FILE_TS}, which is TypeScript the probe cannot evaluate (only Sentinel's config reader does); no area labels are added`);
3549
+ return none(`skipped: it has no ${AREA_FILE_JSON} or ${AREA_FILE_TS}, so no area labels are added`);
3550
+ }
3551
+ // src/probes/issue-types/issue-types.ts
3552
+ /**
3553
+ * `holocron probe github issue-types`: the one-time backfill of spec `tech-github-area-labels` (rollout item 5), a writer
3554
+ * the maintainer runs. It sets the Type of an issue from its kind labels, adds `area:<name>` labels, fills a milestone
3555
+ * and a project where a source exists, and ends with the list of every issue it read that still lacks a project, a
3556
+ * milestone, a Priority or an Effort. See `backfill.ts` for the rules. Run it with `--dry-run` first.
3557
+ *
3558
+ * The kind labels and the repositories come from `repo.labels` (`kinds`, `fallbackKinds`, `repos`) and `--repo`, and a
3559
+ * repository other than this one has its area labels read from its own `.holocron/repo.json` (spec
3560
+ * `tech-backfill-config-mapping`).
3561
+ *
3562
+ * Not verified against the live API: writing an issue's Type, adding an issue to a project, reading the organization's
3563
+ * issue Types, and the endpoints that read an issue's field values and parent.
3564
+ */
3565
+ function issueTypesProbe(ctx) {
3566
+ return {
3567
+ summary: "Backfill issues: set Type from the kind labels, add area labels, fill milestone and project where a source exists, and list what still lacks a project, milestone, Priority or Effort. Never overwrites a value. Run with --dry-run first.",
3568
+ writes: true,
3569
+ async run(probe) {
3570
+ const parsed = parseArgs(probe.args ?? []);
3571
+ if (!parsed.ok) {
3572
+ probe.say({
3573
+ status: "fail",
3574
+ label: "arguments",
3575
+ detail: parsed.message
3576
+ });
3577
+ return;
3578
+ }
3579
+ const named = parsed.options.repos;
3580
+ const repos = named.length > 0 ? named : ctx.config.repos?.length ? ctx.config.repos : [ctx.repo];
3581
+ const kinds = resolveKinds(ctx.config);
3582
+ for (const repo of repos) {
3583
+ if (repos.length > 1) probe.say({
3584
+ status: "heading",
3585
+ label: repo
3586
+ });
3587
+ try {
3588
+ const api = ctx.makeApi(repo);
3589
+ let areas = ctx.config;
3590
+ if (repo.toLowerCase() !== ctx.repo.toLowerCase()) {
3591
+ const found = await readRepoAreas(api);
3592
+ probe.say(found.row);
3593
+ areas = found.areas;
3594
+ }
3595
+ await runBackfill({
3596
+ ctx: probe,
3597
+ api,
3598
+ options: {
3599
+ ...parsed.options,
3600
+ repo: named.length > 0 || repos.length > 1 ? repo : void 0
3601
+ },
3602
+ areas,
3603
+ kinds,
3604
+ isRateLimited
3605
+ });
3606
+ } catch (err) {
3607
+ probe.say({
3608
+ status: "fail",
3609
+ label: "issue-types",
3610
+ detail: errorMessage(err)
3611
+ });
3612
+ }
3613
+ }
3614
+ }
3615
+ };
3616
+ }
3617
+ // src/probes/token/expectations.ts
3618
+ /** The same rules in every layer that runs the workflow: a laptop (`local` inherits `dev`) and CI. */
3619
+ function everywhere(rules) {
3620
+ return { permissions: {
3621
+ local: rules,
3622
+ dev: rules,
3623
+ ci: rules
3624
+ } };
3625
+ }
3626
+ /**
3627
+ * What each GitHub token is meant to carry, by its `envName`, the same as the GitHub tokens table in
3628
+ * `docs/src/content/docs/tokens.mdx`. This is the plugin's `tokens` declaration, read through `tokenExpectations()`;
3629
+ * change it and that table together.
3630
+ *
3631
+ * Every token CI uses (the `sync-repo`, `sync-secrets`, `reconcile-projects` and `check-tokens` workflows read all of
3632
+ * them) is declared with the same permissions in `local`, `dev` and `ci`, so the probe checks that a `ci` token is no
3633
+ * broader than its `dev` one rather than assuming a split the workflows do not allow. The release token is held by CI
3634
+ * only, so it has no `local` or `dev` entry. A narrow token must not reach administration or secrets; the admin token
3635
+ * must not reach organization secrets (that is `HOLOCRON_SECRETS_TOKEN`'s alone).
3636
+ */
3637
+ const EXPECTED = {
3638
+ HOLOCRON_READ_TOKEN: everywhere({
3639
+ contents: "required",
3640
+ actions: "required",
3641
+ administration: "absent",
3642
+ secrets: "absent",
3643
+ environments: "absent"
3644
+ }),
3645
+ HOLOCRON_ISSUES_TOKEN: everywhere({
3646
+ issues: "required",
3647
+ administration: "absent",
3648
+ secrets: "absent",
3649
+ environments: "absent"
3650
+ }),
3651
+ HOLOCRON_SYNC_TOKEN: everywhere({
3652
+ actions: "required",
3653
+ contents: "required",
3654
+ "pull-requests": "required",
3655
+ administration: "absent",
3656
+ secrets: "absent"
3657
+ }),
3658
+ HOLOCRON_RELEASE_TOKEN: { permissions: { ci: {
3659
+ contents: "required",
3660
+ issues: "required",
3661
+ "pull-requests": "required",
3662
+ administration: "absent",
3663
+ secrets: "absent"
3664
+ } } },
3665
+ HOLOCRON_ADMIN_TOKEN: everywhere({
3666
+ administration: "required",
3667
+ secrets: "required",
3668
+ environments: "required",
3669
+ issues: "required",
3670
+ "custom-properties": "required",
3671
+ "actions-variables": "required",
3672
+ "org-secrets": "absent"
3673
+ }),
3674
+ HOLOCRON_SECRETS_TOKEN: everywhere({
3675
+ "org-secrets": "required",
3676
+ administration: "absent"
3677
+ }),
3678
+ HOLOCRON_DEPLOY_TOKEN: everywhere({
3679
+ pages: "required",
3680
+ administration: "required",
3681
+ secrets: "absent",
3682
+ "org-secrets": "absent"
3683
+ }),
3684
+ HOLOCRON_USER_SYNC_TOKEN: everywhere({
3685
+ "user-sync-contents": "required",
3686
+ administration: "absent",
3687
+ secrets: "absent"
3688
+ }),
3689
+ HOLOCRON_ORG_TOKEN: everywhere({
3690
+ administration: "required",
3691
+ "org-members": "required",
3692
+ "org-variables": "required",
3693
+ "org-secrets": "absent"
3694
+ })
3695
+ };
3696
+ // src/tokens.ts
3697
+ /** Adds what a layer's token must and must not be able to do (`EXPECTED`, by `envName`) to a token. */
3698
+ function declared(token) {
3699
+ return {
3700
+ ...token,
3701
+ expect: EXPECTED[token.envName]
3702
+ };
3703
+ }
3704
+ /**
3705
+ * Every token this plugin takes, for `holocron doctor tokens`, with what each layer's token must and must not be able
3706
+ * to do. The release token is `optional`: only CI's release workflow reads it (from the org secret), so a development
3707
+ * environment has no reason to hold it.
3708
+ */
3709
+ const tokens = [
3710
+ declared(resolveReadToken.token),
3711
+ declared(resolveIssuesToken.token),
3712
+ declared(resolveSyncToken.token),
3713
+ declared({
3714
+ ...resolveReleaseToken.token,
3715
+ optional: true
3716
+ }),
3717
+ declared(resolveAdminToken.token),
3718
+ declared(resolveSecretsToken.token),
3719
+ declared(resolveDeployToken.token),
3720
+ declared(resolveUserSyncToken.token),
3721
+ declared(resolveOrgToken.token)
3722
+ ];
3723
+ // src/probes/token/parse-token-args.ts
3724
+ /** Reads the words after the probe name: `--layer <word>` and `--token-name <VAR>`, in either spelling. */
3725
+ function parseTokenArgs(args) {
3726
+ let layer;
3727
+ let tokenName;
3728
+ for (let i = 0; i < args.length; i++) {
3729
+ const arg = args[i];
3730
+ if (arg === "--layer") layer = args[++i];
3731
+ else if (arg.startsWith("--layer=")) layer = arg.slice(8);
3732
+ else if (arg === "--token-name") tokenName = args[++i];
3733
+ else if (arg.startsWith("--token-name=")) tokenName = arg.slice(13);
3734
+ }
3735
+ return {
3736
+ ...layer ? { layer } : {},
3737
+ ...tokenName ? { tokenName } : {}
3738
+ };
3739
+ }
3740
+ // src/probes/token/permissions.ts
3741
+ /**
3742
+ * Every permission the GitHub plugin's tokens are declared against, by the name the declaration uses, with one read
3743
+ * that needs it. A read proves the token can see the area, not that it can write to it: GitHub exposes no list of a
3744
+ * fine-grained token's permissions, so the write half of `read/write` is taken from the permission table in
3745
+ * `docs/src/content/docs/tokens.mdx`. On a public repository the `contents`, `actions`, `issues`, `pull-requests` and `environments`
3746
+ * reads succeed for any token, so only the other permissions can prove a permission absent. Names with more than one
3747
+ * word are hyphenated, not underscored: `holocron probe docs tokens` strips `_` (Markdown emphasis) from a table cell
3748
+ * before it compares the id with the declaration.
3749
+ */
3750
+ const PERMISSIONS = {
3751
+ contents: {
3752
+ label: "Contents",
3753
+ path: "/repos/{r}/contents",
3754
+ publicRead: true
3755
+ },
3756
+ actions: {
3757
+ label: "Actions",
3758
+ path: "/repos/{r}/actions/runs?per_page=1",
3759
+ publicRead: true
3760
+ },
3761
+ issues: {
3762
+ label: "Issues",
3763
+ path: "/repos/{r}/issues?per_page=1",
3764
+ publicRead: true
3765
+ },
3766
+ "pull-requests": {
3767
+ label: "Pull requests",
3768
+ path: "/repos/{r}/pulls?per_page=1",
3769
+ publicRead: true
3770
+ },
3771
+ administration: {
3772
+ label: "Administration",
3773
+ path: "/repos/{r}/actions/permissions"
3774
+ },
3775
+ secrets: {
3776
+ label: "Secrets",
3777
+ path: "/repos/{r}/actions/secrets?per_page=1"
3778
+ },
3779
+ environments: {
3780
+ label: "Environments",
3781
+ path: "/repos/{r}/environments?per_page=1",
3782
+ publicRead: true
3783
+ },
3784
+ "actions-variables": {
3785
+ label: "Variables",
3786
+ path: "/repos/{r}/actions/variables?per_page=1"
3787
+ },
3788
+ "custom-properties": {
3789
+ label: "Custom properties",
3790
+ path: "/repos/{r}/properties/values"
3791
+ },
3792
+ pages: {
3793
+ label: "Pages",
3794
+ path: "/repos/{r}/pages"
3795
+ },
3796
+ "org-members": {
3797
+ label: "Organization: Members",
3798
+ path: "/orgs/{o}/members?per_page=1"
3799
+ },
3800
+ "org-variables": {
3801
+ label: "Organization: Variables",
3802
+ path: "/orgs/{o}/actions/variables?per_page=1"
3803
+ },
3804
+ "org-secrets": {
3805
+ label: "Organization: Secrets",
3806
+ path: "/orgs/{o}/actions/secrets?per_page=1"
3807
+ },
3808
+ "issue-fields": {
3809
+ label: "Organization: Issue fields",
3810
+ path: "/orgs/{o}/issue-fields"
3811
+ },
3812
+ "issue-types": {
3813
+ label: "Organization: Issue types",
3814
+ path: "/orgs/{o}/issue-types"
3815
+ },
3816
+ "user-sync-contents": {
3817
+ label: "Contents (.github-private)",
3818
+ path: "/repos/{o}/.github-private/contents"
3819
+ }
3820
+ };
3821
+ // src/probes/token/token.ts
3822
+ /** The token checked when none is named: the one the plugin reads with by default. */
3823
+ const DEFAULT_TOKEN = "HOLOCRON_READ_TOKEN";
3824
+ /** Does one GET with the token; the response headers are returned for the caller that wants them. */
3825
+ async function get(ctx, token, path) {
3826
+ return ctx.fetch(`${ctx.baseUrl}${path}`, { headers: {
3827
+ authorization: `Bearer ${token}`,
3828
+ accept: "application/vnd.github+json",
3829
+ "x-github-api-version": "2022-11-28",
3830
+ "user-agent": "holocron-probe"
3831
+ } });
3832
+ }
3833
+ /**
3834
+ * One read for one permission. GitHub answers a token without the permission with a 403, or a 404 for something it will
3835
+ * not admit exists, so both are `none`; a 2xx is `has`. Any other status, or a request that did not go through, is an
3836
+ * `error`, which is a failure whatever the layer expects.
3837
+ */
3838
+ async function reach(ctx, token, permission) {
3839
+ const [owner = ""] = ctx.repo.split("/");
3840
+ const path = PERMISSIONS[permission].path.replaceAll("{r}", ctx.repo).replaceAll("{o}", owner);
3841
+ try {
3842
+ const res = await get(ctx, token, path);
3843
+ if (res.ok) return {
3844
+ kind: "has",
3845
+ detail: `read ${path.split("?")[0]}`
3846
+ };
3847
+ if (res.status === 403 || res.status === 404) return {
3848
+ kind: "none",
3849
+ detail: `no access (${res.status})`
3850
+ };
3851
+ return {
3852
+ kind: "error",
3853
+ detail: `${res.status} ${res.statusText}`.trim()
3854
+ };
3855
+ } catch (err) {
3856
+ return {
3857
+ kind: "error",
3858
+ detail: errorMessage(err)
3859
+ };
3860
+ }
3861
+ }
3862
+ /**
3863
+ * One row for what was tried. With no rule it only describes (`ok` for access, `info` for none). Under a layer's rule it
3864
+ * judges: a required permission the token lacks fails, and one the layer must not have fails when the token has it; a
3865
+ * permission that is rightly absent is a bare `ok`.
3866
+ */
3867
+ function rowFor({ label, permission, outcome }, rule) {
3868
+ if (outcome.kind === "error") return {
3869
+ status: "fail",
3870
+ label,
3871
+ detail: outcome.detail
3872
+ };
3873
+ const has = outcome.kind === "has";
3874
+ if (rule === "required") return {
3875
+ status: has ? "ok" : "fail",
3876
+ label,
3877
+ detail: outcome.detail
3878
+ };
3879
+ if (rule === "absent" && has && PERMISSIONS[permission].publicRead) return {
3880
+ status: "info",
3881
+ label,
3882
+ detail: `${outcome.detail}, which any token can on a public repository: not proof either way`
3883
+ };
3884
+ if (rule === "absent") return has ? {
3885
+ status: "fail",
3886
+ label,
3887
+ detail: outcome.detail
3888
+ } : {
3889
+ status: "ok",
3890
+ label
3891
+ };
3892
+ return {
3893
+ status: has ? "ok" : "info",
3894
+ label,
3895
+ detail: outcome.detail
3896
+ };
3897
+ }
655
3898
  /**
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.
3899
+ * The `token` probe: `holocron probe github token` tries each permission Holocron uses with one of the plugin's nine
3900
+ * tokens and reports which ones the token reaches. It only reads (one GET per permission), so it changes nothing, and a
3901
+ * read proves the token can see an area, not that it can write there.
659
3902
  *
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.
3903
+ * GitHub lists scopes only for a classic token (the `X-OAuth-Scopes` header on any response), so a classic token's scopes
3904
+ * are shown. A fine-grained token has no list, so the permissions are found by trying them; the first row says which kind
3905
+ * was read. With `--environment <layer>` the CLI runs the probe once for each token the Environment holds and hands it
3906
+ * `--token-name <envName>` (and the token itself as `cliToken`); by hand, `--token-name` picks which token the plugin
3907
+ * resolves (default `HOLOCRON_READ_TOKEN`).
3908
+ *
3909
+ * With no layer the token is only described. When the CLI passes `--layer` (because `--environment` named `ci`, `dev` or
3910
+ * `local`), the results are judged against what that token is meant to carry in that layer (the plugin's `tokens`
3911
+ * declaration, read with `tokenExpectations()`) and shown in two groups, what it should have and what it should not,
3912
+ * where a missing or extra permission fails.
664
3913
  */
3914
+ function tokenProbe(ctx) {
3915
+ return {
3916
+ summary: "Try each GitHub permission Holocron uses (contents, actions, issues, administration, secrets, ...) with one of the plugin's tokens and report which it reaches; for a ci or dev Environment, check it against what that layer should carry. Read-only.",
3917
+ writes: false,
3918
+ acceptsToken: true,
3919
+ async run(probe) {
3920
+ const { layer, tokenName } = parseTokenArgs(probe.args ?? []);
3921
+ const envName = tokenName ?? DEFAULT_TOKEN;
3922
+ const token = ctx.resolve(envName);
3923
+ if (token === void 0) {
3924
+ probe.say({
3925
+ status: "fail",
3926
+ label: envName,
3927
+ detail: `not a GitHub token; use one of: ${ctx.tokenNames.join(", ")}`
3928
+ });
3929
+ return;
3930
+ }
3931
+ probe.secret(token);
3932
+ let identity;
3933
+ try {
3934
+ identity = await get(ctx, token, "/user");
3935
+ } catch (err) {
3936
+ probe.say({
3937
+ status: "fail",
3938
+ label: "token",
3939
+ detail: errorMessage(err)
3940
+ });
3941
+ return;
3942
+ }
3943
+ if (identity.status === 401) {
3944
+ probe.say({
3945
+ status: "fail",
3946
+ label: "token",
3947
+ detail: "rejected by GitHub (401): expired, revoked or not a token"
3948
+ });
3949
+ return;
3950
+ }
3951
+ const scopes = identity.headers.get("x-oauth-scopes");
3952
+ probe.say({
3953
+ status: "ok",
3954
+ label: "token",
3955
+ detail: scopes === null ? "fine-grained (GitHub lists no permissions for one, so each is tried with a read)" : `classic (scopes: ${scopes === "" ? "none" : scopes}); each permission is also tried with a read`
3956
+ });
3957
+ const declared = layer ? tokenExpectations(tokens, {
3958
+ layer,
3959
+ envName
3960
+ })[0] : void 0;
3961
+ if (layer && !declared) probe.say({
3962
+ status: "info",
3963
+ label: layer,
3964
+ detail: "no expectations are declared for this token there, so it is only described"
3965
+ });
3966
+ const rules = declared?.rules ?? {};
3967
+ const names = declared ? Object.keys(rules) : Object.keys(PERMISSIONS);
3968
+ const tried = [];
3969
+ for (const permission of names) tried.push({
3970
+ label: PERMISSIONS[permission].label,
3971
+ permission,
3972
+ outcome: await reach(ctx, token, permission)
3973
+ });
3974
+ if (!declared) {
3975
+ for (const t of tried) probe.say(rowFor(t, void 0));
3976
+ return;
3977
+ }
3978
+ for (const [heading, rule] of [["Should have", "required"], ["Should not have", "absent"]]) {
3979
+ const inGroup = tried.filter((t) => rules[t.permission] === rule);
3980
+ if (inGroup.length === 0) continue;
3981
+ probe.say({
3982
+ status: "heading",
3983
+ label: heading
3984
+ });
3985
+ for (const t of inGroup) probe.say(rowFor(t, rule));
3986
+ }
3987
+ }
3988
+ };
3989
+ }
3990
+ // src/token-resolvers.ts
3991
+ /** Each token's resolver by its environment variable (`HOLOCRON_ADMIN_TOKEN`), which is what `--token-name` carries. */
3992
+ const TOKEN_RESOLVERS = {
3993
+ HOLOCRON_READ_TOKEN: resolveReadToken,
3994
+ HOLOCRON_ISSUES_TOKEN: resolveIssuesToken,
3995
+ HOLOCRON_SYNC_TOKEN: resolveSyncToken,
3996
+ HOLOCRON_RELEASE_TOKEN: resolveReleaseToken,
3997
+ HOLOCRON_ADMIN_TOKEN: resolveAdminToken,
3998
+ HOLOCRON_SECRETS_TOKEN: resolveSecretsToken,
3999
+ HOLOCRON_DEPLOY_TOKEN: resolveDeployToken,
4000
+ HOLOCRON_USER_SYNC_TOKEN: resolveUserSyncToken,
4001
+ HOLOCRON_ORG_TOKEN: resolveOrgToken
4002
+ };
4003
+ // src/verify-token.ts
4004
+ /** Checks a token against `GET /user` and returns who it belongs to, or why it failed. */
665
4005
  async function verifyToken(token, opts = {}) {
666
4006
  const client = createGitHubClient({
667
4007
  token,
@@ -669,49 +4009,61 @@ async function verifyToken(token, opts = {}) {
669
4009
  fetch: opts.fetch
670
4010
  });
671
4011
  try {
672
- const me = await client.user.getCurrentUser();
4012
+ const { user: me, expiresAt } = await client.user.getCurrentUserWithExpiry();
673
4013
  return {
674
4014
  ok: true,
675
- subject: `user @ ${me.login ?? me.email ?? "unknown"}`
4015
+ subject: `user @ ${me.login ?? me.email ?? "unknown"}`,
4016
+ ...expiresAt ? { expiresAt } : {}
676
4017
  };
677
4018
  } catch (err) {
678
4019
  return {
679
4020
  ok: false,
680
- message: err instanceof Error ? err.message : String(err)
4021
+ message: errorMessage(err)
681
4022
  };
682
4023
  }
683
4024
  }
684
- //#endregion
685
- //#region src/index.ts
686
- function source(ctx, orgClient) {
4025
+ // src/index.ts
4026
+ /** Builds the `source` capability; the optional clients cover org-level and user-sync access. */
4027
+ function source(ctx, orgClient, userSyncClient) {
687
4028
  return new GitHubSource(ctx.client, {
688
4029
  repo: ctx.repo,
689
4030
  repoRoot: ctx.repoRoot,
690
4031
  orgClient,
4032
+ userSyncClient,
691
4033
  baseUrl: ctx.options.baseUrl,
692
4034
  fetch: ctx.options.fetch
693
4035
  });
694
4036
  }
695
- function secrets(ctx) {
696
- return new GitHubSecrets(ctx.client, { repo: ctx.repo });
4037
+ /** Builds the `secrets` capability; the optional client handles organization secrets. */
4038
+ function secrets(ctx, orgClient) {
4039
+ return new GitHubSecrets(ctx.client, { repo: ctx.repo }, orgClient);
697
4040
  }
4041
+ /** Builds the `environments` capability. */
698
4042
  function environments(ctx) {
699
4043
  return new GitHubEnvironments(ctx.client, { repo: ctx.repo });
700
4044
  }
4045
+ /** Builds the `ci` capability. */
701
4046
  function ci(ctx) {
702
4047
  return new GitHubCi(ctx.client, { repo: ctx.repo });
703
4048
  }
4049
+ /** Builds the `issues` capability, passing the lifecycle labels when configured. */
704
4050
  function issues(ctx) {
705
4051
  const opts = { repo: ctx.repo };
706
4052
  if (ctx.options.labels !== void 0) opts.labels = ctx.options.labels;
707
4053
  return new GitHubIssues(ctx.client, opts);
708
4054
  }
4055
+ /** Builds the `projects` capability: GitHub Projects v2 over GraphQL, with items keyed relative to the configured repo. */
4056
+ function projects(ctx) {
4057
+ return new GitHubProjects(ctx.client.graphql, { repo: ctx.repo });
4058
+ }
4059
+ /** Creates the plugin, resolving a token per capability when it is first used. */
709
4060
  function createPlugin(options) {
710
4061
  function makeCtx(resolver) {
4062
+ const token = resolver(options);
711
4063
  return {
712
4064
  options,
713
4065
  client: createGitHubClient$1({
714
- token: resolver(options),
4066
+ token,
715
4067
  baseUrl: options.baseUrl,
716
4068
  fetch: options.fetch
717
4069
  }),
@@ -719,10 +4071,45 @@ function createPlugin(options) {
719
4071
  repoRoot: options.repoRoot ?? process.cwd()
720
4072
  };
721
4073
  }
4074
+ /** A token, or undefined when that feature token is simply not configured. */
4075
+ function tryResolve(resolver) {
4076
+ try {
4077
+ return resolver(options);
4078
+ } catch (err) {
4079
+ if (err instanceof AuthError) return void 0;
4080
+ throw err;
4081
+ }
4082
+ }
4083
+ /**
4084
+ * Organization secrets need an org-resource-owner token (`github.secrets`);
4085
+ * repo and environment secrets need `github.admin`. Each scope prefers its own
4086
+ * token and falls back to the other, so a setup with only one of them keeps
4087
+ * working, and an explicit `--token` serves both. With neither configured this
4088
+ * fails exactly as the admin-token capabilities do.
4089
+ */
4090
+ function makeSecrets() {
4091
+ const secretsToken = tryResolve(resolveSecretsToken);
4092
+ const adminToken = tryResolve(resolveAdminToken);
4093
+ if (!secretsToken && !adminToken) resolveAdminToken(options);
4094
+ const clientFor = (token) => createGitHubClient$1({
4095
+ token,
4096
+ baseUrl: options.baseUrl,
4097
+ fetch: options.fetch
4098
+ });
4099
+ const repoClient = clientFor(adminToken ?? secretsToken);
4100
+ const orgClient = clientFor(secretsToken ?? adminToken);
4101
+ return secrets({
4102
+ options,
4103
+ client: repoClient,
4104
+ repo: options.repo,
4105
+ repoRoot: options.repoRoot ?? process.cwd()
4106
+ }, orgClient);
4107
+ }
722
4108
  function makeOrgClient() {
723
4109
  try {
4110
+ const token = resolveOrgToken(options);
724
4111
  return createGitHubClient$1({
725
- token: resolveOrgToken(options),
4112
+ token,
726
4113
  baseUrl: options.baseUrl,
727
4114
  fetch: options.fetch
728
4115
  });
@@ -730,21 +4117,54 @@ function createPlugin(options) {
730
4117
  return;
731
4118
  }
732
4119
  }
4120
+ /** The token for the user-sync files; undefined when it is not configured, and the org token is used instead. */
4121
+ function makeUserSyncClient() {
4122
+ const token = tryResolve(resolveUserSyncToken);
4123
+ return token ? createGitHubClient$1({
4124
+ token,
4125
+ baseUrl: options.baseUrl,
4126
+ fetch: options.fetch
4127
+ }) : void 0;
4128
+ }
733
4129
  return {
734
4130
  name: "@theholocron/holocron-plugin-github",
4131
+ probes: {
4132
+ token: tokenProbe({
4133
+ repo: options.repo,
4134
+ baseUrl: (options.baseUrl ?? "https://api.github.com").replace(/\/$/, ""),
4135
+ fetch: options.fetch ?? fetch,
4136
+ resolve: (envName) => TOKEN_RESOLVERS[envName]?.(options),
4137
+ tokenNames: Object.keys(TOKEN_RESOLVERS)
4138
+ }),
4139
+ "issue-types": issueTypesProbe({
4140
+ makeApi: (repo) => createBackfillApi(makeCtx(resolveIssuesToken).client, makeCtx(resolveOrgToken).client, repo),
4141
+ repo: options.repo,
4142
+ config: options.areaLabels ?? {}
4143
+ }),
4144
+ connection: connectionProbe({
4145
+ provider: "GitHub",
4146
+ url: options.baseUrl ?? "https://api.github.com",
4147
+ fetch: options.fetch,
4148
+ token: () => resolveReadToken(options),
4149
+ verify: (token) => verifyToken(token, {
4150
+ baseUrl: options.baseUrl,
4151
+ fetch: options.fetch
4152
+ })
4153
+ })
4154
+ },
735
4155
  capabilities: {
736
- source: () => source(makeCtx(resolveAdminToken), makeOrgClient()),
4156
+ source: () => source(makeCtx(resolveAdminToken), makeOrgClient(), makeUserSyncClient()),
737
4157
  ci: () => ci(makeCtx(resolveReadToken)),
738
- secrets: () => secrets(makeCtx(resolveAdminToken)),
4158
+ secrets: () => makeSecrets(),
739
4159
  environments: () => environments(makeCtx(resolveAdminToken)),
740
- issues: () => issues(makeCtx(resolveIssuesToken))
4160
+ issues: () => issues(makeCtx(resolveIssuesToken)),
4161
+ projects: () => projects(makeCtx(resolveOrgToken))
741
4162
  }
742
4163
  };
743
4164
  }
744
4165
  /**
745
- * One-line hint printed by `holocron auth set github` when no token
4166
+ * One-line hint printed by `holocron new token github` when no token
746
4167
  * is supplied or the supplied token is rejected.
747
4168
  */
748
- 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 };
4169
+ 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 new token github.<feature> <PAT>";
4170
+ 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 };