@theholocron/holocron-plugin-github 5.0.0-alpha.52 → 5.0.0-alpha.520

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