@theholocron/holocron-plugin-github 5.0.0-alpha.58 → 5.0.0-alpha.580

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