@theholocron/holocron-plugin-github 5.0.0-alpha.25 → 5.0.0-alpha.250

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/README.md CHANGED
@@ -45,7 +45,7 @@ holocron auth set github.release ghp_xxx # semantic-release
45
45
  holocron auth set github.admin ghp_xxx # setup, secrets, environments
46
46
  ```
47
47
 
48
- See [docs/tokens.md](../../docs/tokens.md) for full scope requirements and CI setup.
48
+ See the [token reference](https://docs.theholocron.dev/holocron/tokens/) for full scope requirements and CI setup.
49
49
 
50
50
  ## Config
51
51
 
package/dist/index.d.mts CHANGED
@@ -1,19 +1,18 @@
1
+ import { Auth, AuthError, Ci, CiRun, CiRunFilter, Environment, Environments, Issue, IssueSearchFilter, Issues, LabelDef, LifecycleResult, LifecycleSlot, PagesConfig, PullRequest, RepoRef, RepoSettings, ResolveTokenInput, Ruleset, SecretScope, Secrets, Source, SourceFile, SourceTeamMember, TeamEntry, TeamEntry as TeamEntry$1, TeamPermission, TrackerDoctorReport, TrackerUser, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess, createFeatureResolver } from "@theholocron/cli";
1
2
  import { GitHubClient, GitHubClientOptions, createGitHubClient } from "@theholocron/github-client";
2
- import { Auth, AuthError, Ci, CiRun, CiRunFilter, Environment, Environments, Issue, IssueSearchFilter, Issues, LabelDef, LifecycleResult, LifecycleSlot, PagesConfig, PullRequest, RepoRef, RepoSettings, ResolveTokenInput, Ruleset, SecretScope, Secrets, Source, TeamEntry, TeamEntry as TeamEntry$1, TeamPermission, TrackerDoctorReport, TrackerUser, createFeatureResolver } from "@theholocron/cli";
3
- //#region src/auth.d.ts
4
- declare const resolveReadToken: (input?: ResolveTokenInput) => string;
5
- declare const resolveIssuesToken: (input?: ResolveTokenInput) => string;
6
- declare const resolveSyncToken: (input?: ResolveTokenInput) => string;
7
- declare const resolveReleaseToken: (input?: ResolveTokenInput) => string;
8
- declare const resolveAdminToken: (input?: ResolveTokenInput) => string;
9
- declare const resolveDeployToken: (input?: ResolveTokenInput) => string;
10
- declare const resolveOrgToken: (input?: ResolveTokenInput) => string;
11
- //#endregion
12
- //#region src/capabilities/ci.d.ts
3
+ export declare const resolveReadToken: (input?: ResolveTokenInput) => string;
4
+ export declare const resolveIssuesToken: (input?: ResolveTokenInput) => string;
5
+ export declare const resolveSyncToken: (input?: ResolveTokenInput) => string;
6
+ export declare const resolveReleaseToken: (input?: ResolveTokenInput) => string;
7
+ export declare const resolveAdminToken: (input?: ResolveTokenInput) => string;
8
+ export declare const resolveSecretsToken: (input?: ResolveTokenInput) => string;
9
+ export declare const resolveDeployToken: (input?: ResolveTokenInput) => string;
10
+ export declare const resolveUserSyncToken: (input?: ResolveTokenInput) => string;
11
+ export declare const resolveOrgToken: (input?: ResolveTokenInput) => string;
13
12
  interface CiOptions {
14
13
  repo: string;
15
14
  }
16
- declare class GitHubCi implements Ci {
15
+ export declare class GitHubCi implements Ci {
17
16
  private readonly client;
18
17
  private readonly opts;
19
18
  readonly key: "ci";
@@ -24,12 +23,10 @@ declare class GitHubCi implements Ci {
24
23
  private mapRun;
25
24
  private mapConclusion;
26
25
  }
27
- //#endregion
28
- //#region src/capabilities/environments.d.ts
29
26
  interface EnvironmentsOptions {
30
27
  repo: string;
31
28
  }
32
- declare class GitHubEnvironments implements Environments {
29
+ export declare class GitHubEnvironments implements Environments {
33
30
  private readonly client;
34
31
  private readonly opts;
35
32
  readonly key: "environments";
@@ -40,8 +37,6 @@ declare class GitHubEnvironments implements Environments {
40
37
  deleteEnvironment(name: string): Promise<void>;
41
38
  private flattenReviewers;
42
39
  }
43
- //#endregion
44
- //#region src/capabilities/issues.d.ts
45
40
  interface IssuesOptions {
46
41
  repo: string;
47
42
  /**
@@ -55,7 +50,7 @@ interface IssuesOptions {
55
50
  inReview: string;
56
51
  };
57
52
  }
58
- declare class GitHubIssues implements Issues {
53
+ export declare class GitHubIssues implements Issues {
59
54
  private readonly client;
60
55
  readonly key: "issues";
61
56
  readonly providerName = "github";
@@ -82,8 +77,6 @@ declare class GitHubIssues implements Issues {
82
77
  private removeStatusLabels;
83
78
  private mapIssue;
84
79
  }
85
- //#endregion
86
- //#region src/capabilities/labels.d.ts
87
80
  interface CanonicalLabel {
88
81
  readonly name: string;
89
82
  readonly color: string;
@@ -97,34 +90,39 @@ interface CanonicalLabel {
97
90
  * - DELETEs labels listed in `stale`.
98
91
  * - Leaves unrecognised labels that aren't in `stale` untouched.
99
92
  */
100
- declare function syncLabels(client: GitHubClient, repo: string, canonical: ReadonlyArray<CanonicalLabel>, stale: ReadonlyArray<string>): Promise<string>;
101
- //#endregion
102
- //#region src/capabilities/secrets.d.ts
93
+ export declare function syncLabels(client: GitHubClient, repo: string, canonical: ReadonlyArray<CanonicalLabel>, stale: ReadonlyArray<string>): Promise<string>;
103
94
  interface SecretsOptions {
104
95
  repo: string;
105
96
  }
106
- declare class GitHubSecrets implements Secrets {
97
+ export declare class GitHubSecrets implements Secrets {
107
98
  private readonly client;
108
99
  private readonly opts;
100
+ private readonly orgClient?;
109
101
  readonly key: "secrets";
110
102
  readonly providerName = "github";
111
- constructor(client: GitHubClient, opts: SecretsOptions);
103
+ /**
104
+ * `client` handles repo and environment scopes; `orgClient`, when given, handles
105
+ * the organization scope. They differ when a dedicated org-only token exists:
106
+ * it can write org secrets but not repo ones, and `github.admin` is the reverse.
107
+ */
108
+ constructor(client: GitHubClient, opts: SecretsOptions, orgClient?: GitHubClient | undefined);
109
+ private clientFor;
112
110
  listSecrets(scope: SecretScope): Promise<string[]>;
113
111
  setSecret(scope: SecretScope, name: string, value: string): Promise<void>;
114
112
  deleteSecret(scope: SecretScope, name: string): Promise<void>;
115
113
  }
116
- //#endregion
117
- //#region src/capabilities/source.d.ts
118
114
  interface SourceOptions {
119
115
  repo: string;
120
116
  repoRoot: string;
121
117
  /** Secondary client authenticated with HOLOCRON_ORG_TOKEN for org-scoped operations (teams, custom properties). */
122
118
  orgClient?: GitHubClient;
119
+ /** Client for the files that link GitHub accounts to other services (HOLOCRON_USER_SYNC_TOKEN); falls back to the org client. */
120
+ userSyncClient?: GitHubClient;
123
121
  /** Forwarded to a secondary client created for Pages calls (HOLOCRON_DEPLOY_TOKEN). */
124
122
  baseUrl?: string;
125
123
  fetch?: typeof fetch;
126
124
  }
127
- declare class GitHubSource implements Source {
125
+ export declare class GitHubSource implements Source {
128
126
  private readonly client;
129
127
  readonly key: "source";
130
128
  readonly providerName = "github";
@@ -134,6 +132,7 @@ declare class GitHubSource implements Source {
134
132
  private readonly repoRoot;
135
133
  private readonly workflowDir;
136
134
  private readonly orgClient?;
135
+ private readonly userSyncClient?;
137
136
  private readonly baseUrl?;
138
137
  private readonly fetchImpl?;
139
138
  constructor(client: GitHubClient, opts: SourceOptions);
@@ -161,56 +160,47 @@ declare class GitHubSource implements Source {
161
160
  syncLabels(canonical: ReadonlyArray<LabelDef>, stale: ReadonlyArray<string>): Promise<string>;
162
161
  syncProperties(values: Record<string, string | string[]>): Promise<string>;
163
162
  syncTeams(teams: TeamEntry$1[]): Promise<string>;
163
+ teamMembers(teamSlug: string, org?: string): Promise<SourceTeamMember[]>;
164
+ readFile(path: string, repo?: string): Promise<SourceFile | null>;
165
+ writeFile(path: string, content: string, opts: {
166
+ message: string;
167
+ version?: string;
168
+ repo?: string;
169
+ }): Promise<void>;
164
170
  syncTopics(topics: string[]): Promise<string>;
171
+ syncVariables(variables: Record<string, string>, opts?: {
172
+ prune?: boolean;
173
+ dryRun?: boolean;
174
+ }): Promise<string>;
175
+ syncOrgVariables(org: string, variables: Record<string, {
176
+ value: string;
177
+ visibility: "all" | "private";
178
+ }>, opts?: {
179
+ prune?: boolean;
180
+ dryRun?: boolean;
181
+ }): Promise<string>;
165
182
  syncDescription(description: string): Promise<string>;
166
183
  syncHomepage(homepage: string): Promise<string>;
167
184
  getPullRequest(number: number, repo?: string): Promise<PullRequest>;
168
185
  configurePages(config: PagesConfig, token: string): Promise<void>;
169
186
  }
170
- //#endregion
171
- //#region src/capabilities/teams.d.ts
172
187
  interface NormalizedTeamEntry {
173
188
  slug: string;
174
189
  permission: TeamPermission;
175
190
  }
176
- declare function normalizeTeamEntry(entry: TeamEntry): NormalizedTeamEntry;
177
- declare function syncTeams(client: GitHubClient, repo: string, teams: TeamEntry[]): Promise<string>;
178
- //#endregion
179
- //#region src/sodium.d.ts
191
+ export declare function normalizeTeamEntry(entry: TeamEntry): NormalizedTeamEntry;
192
+ export declare function syncTeams(client: GitHubClient, repo: string, teams: TeamEntry[]): Promise<string>;
180
193
  /**
181
194
  * Encrypt `value` for the given GitHub-provided base64 public key.
182
195
  * Returns the base64 ciphertext to send as `encrypted_value`.
183
196
  */
184
- declare function encryptSecret(publicKeyBase64: string, value: string): Promise<string>;
185
- //#endregion
186
- //#region src/verify-token.d.ts
187
- /**
188
- * `verifyToken` — plugin-level export used by `holocron auth set` +
189
- * `holocron auth check`. Hits `GET /user` and translates the response
190
- * into the normalized `VerifyTokenResult` shape.
191
- *
192
- * Kept as a standalone function (not a capability method) so the auth
193
- * command can call it without initializing the full plugin — plugin
194
- * construction requires an already-resolved token, which is exactly
195
- * what we don't have yet at bootstrap time.
196
- */
197
- interface VerifyTokenSuccess {
198
- ok: true;
199
- subject: string;
200
- }
201
- interface VerifyTokenFailure {
202
- ok: false;
203
- message: string;
204
- }
205
- type VerifyTokenResult = VerifyTokenSuccess | VerifyTokenFailure;
197
+ export declare function encryptSecret(publicKeyBase64: string, value: string): Promise<string>;
206
198
  interface VerifyTokenOptions {
207
199
  baseUrl?: string;
208
200
  fetch?: typeof fetch;
209
201
  }
210
- declare function verifyToken(token: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult>;
211
- //#endregion
212
- //#region src/index.d.ts
213
- interface GitHubPluginOptions extends ResolveTokenInput {
202
+ export declare function verifyToken(token: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult$1>;
203
+ export interface GitHubPluginOptions extends ResolveTokenInput {
214
204
  /** "owner/name" — e.g., "theholocron/holocron". Required. */
215
205
  repo: string;
216
206
  /** Absolute path to the working repo root. Used by `source`'s
@@ -226,19 +216,22 @@ interface GitHubPluginOptions extends ResolveTokenInput {
226
216
  /** Override `fetch` for tests. Defaults to global `fetch`. */
227
217
  fetch?: typeof fetch;
228
218
  }
229
- interface PluginContext {
219
+ export interface PluginContext {
230
220
  options: GitHubPluginOptions;
231
221
  client: GitHubClient;
232
222
  repo: string;
233
223
  repoRoot: string;
234
224
  }
235
- declare function source(ctx: PluginContext, orgClient?: GitHubClient): Source;
236
- declare function secrets(ctx: PluginContext): Secrets;
237
- declare function environments(ctx: PluginContext): Environments;
238
- declare function ci(ctx: PluginContext): Ci;
239
- declare function issues(ctx: PluginContext): Issues;
240
- declare function createPlugin(options: GitHubPluginOptions): {
225
+ export declare function source(ctx: PluginContext, orgClient?: GitHubClient, userSyncClient?: GitHubClient): Source;
226
+ export declare function secrets(ctx: PluginContext, orgClient?: GitHubClient): Secrets;
227
+ export declare function environments(ctx: PluginContext): Environments;
228
+ export declare function ci(ctx: PluginContext): Ci;
229
+ export declare function issues(ctx: PluginContext): Issues;
230
+ export declare function createPlugin(options: GitHubPluginOptions): {
241
231
  name: string;
232
+ probes: {
233
+ connection: import("@theholocron/cli").Probe;
234
+ };
242
235
  capabilities: {
243
236
  source: () => Source;
244
237
  ci: () => Ci;
@@ -251,6 +244,5 @@ declare function createPlugin(options: GitHubPluginOptions): {
251
244
  * One-line hint printed by `holocron auth set github` when no token
252
245
  * is supplied or the supplied token is rejected.
253
246
  */
254
- declare const AUTH_HINT: string;
255
- //#endregion
256
- export { AUTH_HINT, type Auth, AuthError, type CanonicalLabel, GitHubCi, type GitHubClientOptions, GitHubEnvironments, GitHubIssues, GitHubPluginOptions, GitHubSecrets, GitHubSource, type NormalizedTeamEntry, PluginContext, type ResolveTokenInput, type TeamEntry, type TeamPermission, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, ci, createFeatureResolver, createGitHubClient, createPlugin, encryptSecret, environments, issues, normalizeTeamEntry, resolveAdminToken, resolveDeployToken, resolveIssuesToken, resolveOrgToken, resolveReadToken, resolveReleaseToken, resolveSyncToken, secrets, source, syncLabels, syncTeams, verifyToken };
247
+ export declare const AUTH_HINT: string;
248
+ export { type Auth, AuthError, type CanonicalLabel, type GitHubClientOptions, type NormalizedTeamEntry, type ResolveTokenInput, type TeamEntry, type TeamPermission, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, createFeatureResolver, createGitHubClient };
package/dist/index.mjs CHANGED
@@ -1,9 +1,11 @@
1
1
  import { createRequire } from "node:module";
2
+ import { AuthError, ProviderApiError, connectionProbe, createFeatureResolver } from "@theholocron/cli";
2
3
  import { createGitHubClient, createGitHubClient as createGitHubClient$1 } from "@theholocron/github-client";
3
- import { AuthError, createFeatureResolver } from "@theholocron/cli";
4
4
  import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
5
5
  import { dirname, join } from "node:path";
6
- //#region src/auth.ts
6
+ import { findRootSync } from "@theholocron/fs-utils";
7
+ import { errorMessage } from "@theholocron/misc-utils";
8
+ // src/auth.ts
7
9
  const resolveReadToken = createFeatureResolver({
8
10
  envName: "HOLOCRON_READ_TOKEN",
9
11
  keyringKey: "github.read"
@@ -24,16 +26,23 @@ const resolveAdminToken = createFeatureResolver({
24
26
  envName: "HOLOCRON_ADMIN_TOKEN",
25
27
  keyringKey: "github.admin"
26
28
  });
29
+ const resolveSecretsToken = createFeatureResolver({
30
+ envName: "HOLOCRON_SECRETS_TOKEN",
31
+ keyringKey: "github.secrets"
32
+ });
27
33
  const resolveDeployToken = createFeatureResolver({
28
34
  envName: "HOLOCRON_DEPLOY_TOKEN",
29
35
  keyringKey: "github.deploy"
30
36
  });
37
+ const resolveUserSyncToken = createFeatureResolver({
38
+ envName: "HOLOCRON_USER_SYNC_TOKEN",
39
+ keyringKey: "github.user-sync"
40
+ });
31
41
  const resolveOrgToken = createFeatureResolver({
32
42
  envName: "HOLOCRON_ORG_TOKEN",
33
43
  keyringKey: "github.org"
34
44
  });
35
- //#endregion
36
- //#region src/capabilities/ci.ts
45
+ // src/capabilities/ci.ts
37
46
  var GitHubCi = class {
38
47
  client;
39
48
  opts;
@@ -77,8 +86,7 @@ var GitHubCi = class {
77
86
  }
78
87
  }
79
88
  };
80
- //#endregion
81
- //#region src/capabilities/environments.ts
89
+ // src/capabilities/environments.ts
82
90
  var GitHubEnvironments = class {
83
91
  client;
84
92
  opts;
@@ -119,8 +127,7 @@ var GitHubEnvironments = class {
119
127
  }));
120
128
  }
121
129
  };
122
- //#endregion
123
- //#region src/capabilities/issues.ts
130
+ // src/capabilities/issues.ts
124
131
  var GitHubIssues = class {
125
132
  client;
126
133
  key = "issues";
@@ -337,8 +344,7 @@ function parseIssueNumber(key, owner, repoName) {
337
344
  if (!/^\d+$/.test(num)) throw new Error(`Invalid GitHub issue key "${key}" — expected #N or N.`);
338
345
  return parseInt(num, 10);
339
346
  }
340
- //#endregion
341
- //#region src/sodium.ts
347
+ // src/sodium.ts
342
348
  /**
343
349
  * libsodium sealed-box encryption for GitHub Actions secrets.
344
350
  *
@@ -369,32 +375,42 @@ async function encryptSecret(publicKeyBase64, value) {
369
375
  const ciphertext = sodium.crypto_box_seal(plaintext, publicKey);
370
376
  return sodium.to_base64(ciphertext, sodium.base64_variants.ORIGINAL);
371
377
  }
372
- //#endregion
373
- //#region src/capabilities/secrets.ts
378
+ // src/capabilities/secrets.ts
374
379
  var GitHubSecrets = class {
375
380
  client;
376
381
  opts;
382
+ orgClient;
377
383
  key = "secrets";
378
384
  providerName = "github";
379
- constructor(client, opts) {
385
+ /**
386
+ * `client` handles repo and environment scopes; `orgClient`, when given, handles
387
+ * the organization scope. They differ when a dedicated org-only token exists:
388
+ * it can write org secrets but not repo ones, and `github.admin` is the reverse.
389
+ */
390
+ constructor(client, opts, orgClient) {
380
391
  this.client = client;
381
392
  this.opts = opts;
393
+ this.orgClient = orgClient;
394
+ }
395
+ clientFor(scope) {
396
+ return scope.kind === "organization" ? this.orgClient ?? this.client : this.client;
382
397
  }
383
398
  async listSecrets(scope) {
384
- return this.client.secrets.listSecrets(this.opts.repo, toGHScope(scope));
399
+ return this.clientFor(scope).secrets.listSecrets(this.opts.repo, toGHScope(scope));
385
400
  }
386
401
  async setSecret(scope, name, value) {
387
402
  const ghScope = toGHScope(scope);
388
- const pk = await this.client.secrets.getPublicKey(this.opts.repo, ghScope);
403
+ const client = this.clientFor(scope);
404
+ const pk = await client.secrets.getPublicKey(this.opts.repo, ghScope);
389
405
  const body = {
390
406
  encrypted_value: await encryptSecret(pk.key, value),
391
407
  key_id: pk.key_id
392
408
  };
393
409
  if (scope.kind === "organization") body.visibility = "all";
394
- await this.client.secrets.putSecret(this.opts.repo, ghScope, name, body);
410
+ await client.secrets.putSecret(this.opts.repo, ghScope, name, body);
395
411
  }
396
412
  async deleteSecret(scope, name) {
397
- await this.client.secrets.deleteSecret(this.opts.repo, toGHScope(scope), name);
413
+ await this.clientFor(scope).secrets.deleteSecret(this.opts.repo, toGHScope(scope), name);
398
414
  }
399
415
  };
400
416
  function toGHScope(scope) {
@@ -404,8 +420,46 @@ function toGHScope(scope) {
404
420
  };
405
421
  return scope;
406
422
  }
407
- //#endregion
408
- //#region src/capabilities/labels.ts
423
+ // src/capabilities/files.ts
424
+ /** Reads one file; `null` when it does not exist. `version` is the blob sha `writeFile` needs to replace exactly this one. */
425
+ /** A fine-grained token only reaches the repositories and permissions it was given; say which one is missing. */
426
+ function noAccess(repo, action, cause) {
427
+ return new Error(`the token cannot ${action} files in ${repo} (403): give the user-sync token (HOLOCRON_USER_SYNC_TOKEN, or holocron auth set github.user-sync) access to that repository with Contents: ${action === "read" ? "read" : "read and write"}`, { cause });
428
+ }
429
+ async function readRepoFile(client, repo, path) {
430
+ try {
431
+ const file = await client.git.getContents(repo, path);
432
+ if (file.encoding !== "base64") throw new Error(`${repo}/${path}: unexpected encoding \`${file.encoding}\``);
433
+ return {
434
+ content: Buffer.from(file.content, "base64").toString("utf-8"),
435
+ version: file.sha
436
+ };
437
+ } catch (err) {
438
+ if (err instanceof ProviderApiError && err.status === 403) throw noAccess(repo, "read", err);
439
+ if (!(err instanceof ProviderApiError && err.status === 404)) throw err;
440
+ }
441
+ try {
442
+ await client.repos.getRepo(repo);
443
+ } catch (err) {
444
+ 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 });
445
+ throw err;
446
+ }
447
+ return null;
448
+ }
449
+ /** Creates or replaces one file in a commit; GitHub refuses (409) a `version` that has since changed. */
450
+ async function writeRepoFile(client, repo, path, content, opts) {
451
+ try {
452
+ await client.git.putContents(repo, path, {
453
+ message: opts.message,
454
+ content,
455
+ ...opts.version ? { sha: opts.version } : {}
456
+ });
457
+ } catch (err) {
458
+ if (err instanceof ProviderApiError && err.status === 403) throw noAccess(repo, "write", err);
459
+ throw err;
460
+ }
461
+ }
462
+ // src/capabilities/labels.ts
409
463
  /**
410
464
  * Idempotently synchronise a repo's labels to the canonical set.
411
465
  *
@@ -443,14 +497,12 @@ async function syncLabels(client, repo, canonical, stale) {
443
497
  }
444
498
  return `${created} created, ${updated} updated, ${deleted} deleted`;
445
499
  }
446
- //#endregion
447
- //#region src/capabilities/properties.ts
500
+ // src/capabilities/properties.ts
448
501
  async function syncProperties(client, repo, values) {
449
502
  await client.properties.setProperties(repo, values);
450
503
  return `${Object.keys(values).length} properties set`;
451
504
  }
452
- //#endregion
453
- //#region src/capabilities/teams.ts
505
+ // src/capabilities/teams.ts
454
506
  function normalizeTeamEntry(entry) {
455
507
  if (typeof entry === "string") return {
456
508
  slug: entry,
@@ -470,14 +522,112 @@ async function syncTeams(client, repo, teams) {
470
522
  }
471
523
  return `${succeeded} team${succeeded === 1 ? "" : "s"} synced`;
472
524
  }
473
- //#endregion
474
- //#region src/capabilities/topics.ts
525
+ // src/capabilities/topics.ts
475
526
  async function syncTopics(client, repo, topics) {
476
527
  await client.topics.setTopics(repo, topics);
477
528
  return `${topics.length} topics set`;
478
529
  }
479
- //#endregion
480
- //#region src/capabilities/source.ts
530
+ // src/capabilities/variables.ts
531
+ /** GitHub's rule for a variable name: letters, digits and underscores, not starting with a digit or `GITHUB_`. */
532
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
533
+ /** Longest name GitHub accepts. */
534
+ const MAX_NAME = 256;
535
+ function assertNames(names) {
536
+ 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_`);
537
+ }
538
+ /** GitHub treats variable names as case-insensitive, so every comparison goes through this. */
539
+ const key = (name) => name.toUpperCase();
540
+ /**
541
+ * Bring one scope's variables in line with the declaration: create what is missing, update what differs, leave what
542
+ * already matches. Variables that exist but are not declared are left alone, or deleted with `prune`, except an
543
+ * organization variable limited to selected repositories, which this client cannot manage and so is never deleted.
544
+ * Returns a one-line summary, naming the ones left so drift is visible. In a dry run it only describes the changes.
545
+ */
546
+ async function reconcile(client, repo, scope, wanted, opts) {
547
+ assertNames(wanted.map((w) => w.name));
548
+ const existing = new Map((await client.variables.listVariables(repo, scope)).map((v) => [key(v.name), v]));
549
+ const counts = {
550
+ created: 0,
551
+ updated: 0,
552
+ unchanged: 0,
553
+ deleted: 0
554
+ };
555
+ for (const want of wanted) {
556
+ const have = existing.get(key(want.name));
557
+ const body = {
558
+ name: want.name,
559
+ value: want.value
560
+ };
561
+ if (want.visibility) body["visibility"] = want.visibility;
562
+ if (!have) {
563
+ if (opts.dryRun) {
564
+ counts.created++;
565
+ continue;
566
+ }
567
+ try {
568
+ await client.variables.createVariable(repo, scope, body);
569
+ counts.created++;
570
+ continue;
571
+ } catch (err) {
572
+ if (!(err instanceof ProviderApiError && (err.status === 409 || err.status === 422))) throw err;
573
+ }
574
+ } else if (have.value === want.value && (!want.visibility || have.visibility === want.visibility)) {
575
+ counts.unchanged++;
576
+ continue;
577
+ }
578
+ if (!opts.dryRun) await client.variables.updateVariable(repo, scope, have?.name ?? want.name, body);
579
+ counts.updated++;
580
+ }
581
+ const declared = new Set(wanted.map((w) => key(w.name)));
582
+ const undeclared = [...existing.entries()].filter(([k]) => !declared.has(k)).map(([, v]) => v);
583
+ const unmanaged = undeclared.filter((v) => v.visibility === "selected");
584
+ if (opts.prune) for (const v of undeclared.filter((u) => u.visibility !== "selected")) {
585
+ if (!opts.dryRun) await client.variables.deleteVariable(repo, scope, v.name);
586
+ counts.deleted++;
587
+ }
588
+ const parts = opts.dryRun ? [
589
+ `would create ${counts.created}`,
590
+ `would update ${counts.updated}`,
591
+ `${counts.unchanged} unchanged`
592
+ ] : [
593
+ `${counts.created} created`,
594
+ `${counts.updated} updated`,
595
+ `${counts.unchanged} unchanged`
596
+ ];
597
+ if (counts.deleted > 0) parts.push(`${counts.deleted} ${opts.dryRun ? "would be deleted" : "deleted"}`);
598
+ const left = opts.prune ? unmanaged : undeclared;
599
+ if (left.length > 0) {
600
+ const why = opts.prune ? "limited to selected repositories, not managed" : "not declared, left alone";
601
+ parts.push(`${left.length} ${why}: ${left.map((v) => v.name).join(", ")}`);
602
+ }
603
+ return parts.join(", ");
604
+ }
605
+ /** Reconcile a repository's Actions variables. */
606
+ function syncVariables(client, repo, variables, opts = {}) {
607
+ return reconcile(client, repo, { kind: "repo" }, Object.entries(variables).map(([name, value]) => ({
608
+ name,
609
+ value
610
+ })), {
611
+ prune: opts.prune === true,
612
+ dryRun: opts.dryRun === true
613
+ });
614
+ }
615
+ /** Reconcile an organization's Actions variables. `repo` is only the coordinate the client is bound to. */
616
+ function syncOrgVariables(client, repo, org, variables, opts = {}) {
617
+ const wanted = Object.entries(variables).map(([name, v]) => ({
618
+ name,
619
+ value: v.value,
620
+ visibility: v.visibility
621
+ }));
622
+ return reconcile(client, repo, {
623
+ kind: "organization",
624
+ org
625
+ }, wanted, {
626
+ prune: opts.prune === true,
627
+ dryRun: opts.dryRun === true
628
+ });
629
+ }
630
+ // src/capabilities/source.ts
481
631
  var GitHubSource = class {
482
632
  client;
483
633
  key = "source";
@@ -488,6 +638,7 @@ var GitHubSource = class {
488
638
  repoRoot;
489
639
  workflowDir;
490
640
  orgClient;
641
+ userSyncClient;
491
642
  baseUrl;
492
643
  fetchImpl;
493
644
  constructor(client, opts) {
@@ -496,9 +647,13 @@ var GitHubSource = class {
496
647
  this.owner = owner;
497
648
  this.name = name;
498
649
  this.repo = opts.repo;
499
- this.repoRoot = opts.repoRoot;
500
- this.workflowDir = join(opts.repoRoot, ".github", "workflows");
650
+ this.repoRoot = findRootSync(opts.repoRoot, ".git", {
651
+ fallback: "start",
652
+ realpath: true
653
+ });
654
+ this.workflowDir = join(this.repoRoot, ".github", "workflows");
501
655
  this.orgClient = opts.orgClient;
656
+ this.userSyncClient = opts.userSyncClient;
502
657
  this.baseUrl = opts.baseUrl;
503
658
  this.fetchImpl = opts.fetch;
504
659
  }
@@ -591,9 +746,28 @@ var GitHubSource = class {
591
746
  async syncTeams(teams) {
592
747
  return syncTeams(this.orgClient ?? this.client, this.repo, teams);
593
748
  }
749
+ async teamMembers(teamSlug, org = this.owner) {
750
+ return (await (this.orgClient ?? this.client).teams.members(org, teamSlug)).map((m) => ({
751
+ id: String(m.id),
752
+ login: m.login
753
+ }));
754
+ }
755
+ async readFile(path, repo = this.repo) {
756
+ return readRepoFile(this.userSyncClient ?? this.orgClient ?? this.client, repo, path);
757
+ }
758
+ async writeFile(path, content, opts) {
759
+ return writeRepoFile(this.userSyncClient ?? this.orgClient ?? this.client, opts.repo ?? this.repo, path, content, opts);
760
+ }
594
761
  async syncTopics(topics) {
595
762
  return syncTopics(this.client, this.repo, topics);
596
763
  }
764
+ async syncVariables(variables, opts) {
765
+ return syncVariables(this.client, this.repo, variables, opts);
766
+ }
767
+ async syncOrgVariables(org, variables, opts) {
768
+ if (!this.orgClient) throw new Error("organization variables need the org token: set HOLOCRON_ORG_TOKEN or run `holocron auth set github.org <token>`");
769
+ return syncOrgVariables(this.orgClient, this.repo, org, variables, opts);
770
+ }
597
771
  async syncDescription(description) {
598
772
  await this.client.repos.updateRepo(this.repo, { description });
599
773
  return "description updated";
@@ -650,18 +824,7 @@ async function ensureDir(path) {
650
824
  throw err;
651
825
  }
652
826
  }
653
- //#endregion
654
- //#region src/verify-token.ts
655
- /**
656
- * `verifyToken` — plugin-level export used by `holocron auth set` +
657
- * `holocron auth check`. Hits `GET /user` and translates the response
658
- * into the normalized `VerifyTokenResult` shape.
659
- *
660
- * Kept as a standalone function (not a capability method) so the auth
661
- * command can call it without initializing the full plugin — plugin
662
- * construction requires an already-resolved token, which is exactly
663
- * what we don't have yet at bootstrap time.
664
- */
827
+ // src/verify-token.ts
665
828
  async function verifyToken(token, opts = {}) {
666
829
  const client = createGitHubClient({
667
830
  token,
@@ -677,23 +840,23 @@ async function verifyToken(token, opts = {}) {
677
840
  } catch (err) {
678
841
  return {
679
842
  ok: false,
680
- message: err instanceof Error ? err.message : String(err)
843
+ message: errorMessage(err)
681
844
  };
682
845
  }
683
846
  }
684
- //#endregion
685
- //#region src/index.ts
686
- function source(ctx, orgClient) {
847
+ // src/index.ts
848
+ function source(ctx, orgClient, userSyncClient) {
687
849
  return new GitHubSource(ctx.client, {
688
850
  repo: ctx.repo,
689
851
  repoRoot: ctx.repoRoot,
690
852
  orgClient,
853
+ userSyncClient,
691
854
  baseUrl: ctx.options.baseUrl,
692
855
  fetch: ctx.options.fetch
693
856
  });
694
857
  }
695
- function secrets(ctx) {
696
- return new GitHubSecrets(ctx.client, { repo: ctx.repo });
858
+ function secrets(ctx, orgClient) {
859
+ return new GitHubSecrets(ctx.client, { repo: ctx.repo }, orgClient);
697
860
  }
698
861
  function environments(ctx) {
699
862
  return new GitHubEnvironments(ctx.client, { repo: ctx.repo });
@@ -708,10 +871,11 @@ function issues(ctx) {
708
871
  }
709
872
  function createPlugin(options) {
710
873
  function makeCtx(resolver) {
874
+ const token = resolver(options);
711
875
  return {
712
876
  options,
713
877
  client: createGitHubClient$1({
714
- token: resolver(options),
878
+ token,
715
879
  baseUrl: options.baseUrl,
716
880
  fetch: options.fetch
717
881
  }),
@@ -719,10 +883,45 @@ function createPlugin(options) {
719
883
  repoRoot: options.repoRoot ?? process.cwd()
720
884
  };
721
885
  }
886
+ /** A token, or undefined when that feature token is simply not configured. */
887
+ function tryResolve(resolver) {
888
+ try {
889
+ return resolver(options);
890
+ } catch (err) {
891
+ if (err instanceof AuthError) return void 0;
892
+ throw err;
893
+ }
894
+ }
895
+ /**
896
+ * Organization secrets need an org-resource-owner token (`github.secrets`);
897
+ * repo and environment secrets need `github.admin`. Each scope prefers its own
898
+ * token and falls back to the other, so a setup with only one of them keeps
899
+ * working, and an explicit `--token` serves both. With neither configured this
900
+ * fails exactly as the admin-token capabilities do.
901
+ */
902
+ function makeSecrets() {
903
+ const secretsToken = tryResolve(resolveSecretsToken);
904
+ const adminToken = tryResolve(resolveAdminToken);
905
+ if (!secretsToken && !adminToken) resolveAdminToken(options);
906
+ const clientFor = (token) => createGitHubClient$1({
907
+ token,
908
+ baseUrl: options.baseUrl,
909
+ fetch: options.fetch
910
+ });
911
+ const repoClient = clientFor(adminToken ?? secretsToken);
912
+ const orgClient = clientFor(secretsToken ?? adminToken);
913
+ return secrets({
914
+ options,
915
+ client: repoClient,
916
+ repo: options.repo,
917
+ repoRoot: options.repoRoot ?? process.cwd()
918
+ }, orgClient);
919
+ }
722
920
  function makeOrgClient() {
723
921
  try {
922
+ const token = resolveOrgToken(options);
724
923
  return createGitHubClient$1({
725
- token: resolveOrgToken(options),
924
+ token,
726
925
  baseUrl: options.baseUrl,
727
926
  fetch: options.fetch
728
927
  });
@@ -730,12 +929,31 @@ function createPlugin(options) {
730
929
  return;
731
930
  }
732
931
  }
932
+ /** The token for the user-sync files; undefined when it is not configured, and the org token is used instead. */
933
+ function makeUserSyncClient() {
934
+ const token = tryResolve(resolveUserSyncToken);
935
+ return token ? createGitHubClient$1({
936
+ token,
937
+ baseUrl: options.baseUrl,
938
+ fetch: options.fetch
939
+ }) : void 0;
940
+ }
733
941
  return {
734
942
  name: "@theholocron/holocron-plugin-github",
943
+ probes: { connection: connectionProbe({
944
+ provider: "GitHub",
945
+ url: options.baseUrl ?? "https://api.github.com",
946
+ fetch: options.fetch,
947
+ token: () => resolveReadToken(options),
948
+ verify: (token) => verifyToken(token, {
949
+ baseUrl: options.baseUrl,
950
+ fetch: options.fetch
951
+ })
952
+ }) },
735
953
  capabilities: {
736
- source: () => source(makeCtx(resolveAdminToken), makeOrgClient()),
954
+ source: () => source(makeCtx(resolveAdminToken), makeOrgClient(), makeUserSyncClient()),
737
955
  ci: () => ci(makeCtx(resolveReadToken)),
738
- secrets: () => secrets(makeCtx(resolveAdminToken)),
956
+ secrets: () => makeSecrets(),
739
957
  environments: () => environments(makeCtx(resolveAdminToken)),
740
958
  issues: () => issues(makeCtx(resolveIssuesToken))
741
959
  }
@@ -746,5 +964,4 @@ function createPlugin(options) {
746
964
  * is supplied or the supplied token is rejected.
747
965
  */
748
966
  const AUTH_HINT = "generate fine-grained Personal Access Tokens at https://github.com/settings/tokens (one per feature — see docs/tokens.md for required scopes per operation), then run: holocron auth set github.<feature> <PAT>";
749
- //#endregion
750
- export { AUTH_HINT, AuthError, GitHubCi, GitHubEnvironments, GitHubIssues, GitHubSecrets, GitHubSource, ci, createFeatureResolver, createGitHubClient, createPlugin, encryptSecret, environments, issues, normalizeTeamEntry, resolveAdminToken, resolveDeployToken, resolveIssuesToken, resolveOrgToken, resolveReadToken, resolveReleaseToken, resolveSyncToken, secrets, source, syncLabels, syncTeams, verifyToken };
967
+ export { AUTH_HINT, AuthError, GitHubCi, GitHubEnvironments, GitHubIssues, GitHubSecrets, GitHubSource, ci, createFeatureResolver, createGitHubClient, createPlugin, encryptSecret, environments, issues, normalizeTeamEntry, resolveAdminToken, resolveDeployToken, resolveIssuesToken, resolveOrgToken, resolveReadToken, resolveReleaseToken, resolveSecretsToken, resolveSyncToken, resolveUserSyncToken, secrets, source, syncLabels, syncTeams, verifyToken };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-github",
3
- "version": "5.0.0-alpha.25",
3
+ "version": "5.0.0-alpha.250",
4
4
  "description": "Holocron plugin for GitHub. Implements source, ci, secrets, environments, and issues capabilities against the GitHub REST API.",
5
5
  "keywords": [
6
6
  "ci",
@@ -9,12 +9,12 @@
9
9
  "plugin",
10
10
  "source"
11
11
  ],
12
- "homepage": "https://github.com/theholocron/holocron/tree/main/packages/holocron-plugin-github#readme",
12
+ "homepage": "https://github.com/theholocron/holocron/tree/main/plugins/holocron-plugin-github#readme",
13
13
  "bugs": "https://github.com/theholocron/holocron/issues",
14
14
  "repository": {
15
15
  "type": "git",
16
16
  "url": "git+https://github.com/theholocron/holocron.git",
17
- "directory": "packages/holocron-plugin-github"
17
+ "directory": "plugins/holocron-plugin-github"
18
18
  },
19
19
  "license": "MIT",
20
20
  "author": "Newton Koumantzelis",
@@ -34,27 +34,31 @@
34
34
  "libsodium-wrappers": "^0.8.4"
35
35
  },
36
36
  "devDependencies": {
37
- "@theholocron/eslint-config": "^8.0.0",
38
- "@theholocron/github-client": "^1.22.0",
39
- "@theholocron/http-client": "^1.22.0",
40
- "@theholocron/tsconfig": "^8.0.0",
41
- "@theholocron/tsdown-config": "^8.0.0",
42
- "@theholocron/vitest-config": "^8.0.0",
37
+ "@theholocron/eslint-config": "^8.8.2",
38
+ "@theholocron/fs-utils": "^1.16.0",
39
+ "@theholocron/github-client": "^1.51.0",
40
+ "@theholocron/http-client": "^1.57.0",
41
+ "@theholocron/misc-utils": "^1.16.0",
42
+ "@theholocron/tsconfig": "^8.8.2",
43
+ "@theholocron/tsdown-config": "^8.8.2",
44
+ "@theholocron/vitest-config": "^8.8.2",
43
45
  "@types/node": "^26",
44
- "@vitest/coverage-v8": "^4.1.11",
46
+ "@vitest/coverage-v8": "^5.0.5",
45
47
  "@vitest/eslint-plugin": "^1.6.27",
46
48
  "eslint": "^10.8.1",
47
49
  "eslint-plugin-n": "^18.3.0",
48
50
  "globals": "^17.11.0",
49
- "tsdown": "^0.22.14",
50
- "tsx": "4.23.12",
51
+ "tsdown": "^0.23.3",
52
+ "tsx": "4.23.15",
51
53
  "typescript": "^5.9.3",
52
- "vitest": "^4.1.11",
53
- "@theholocron/cli": "5.0.0-alpha.25"
54
+ "vitest": "^5.0.5",
55
+ "@theholocron/cli": "5.0.0-alpha.250"
54
56
  },
55
57
  "peerDependencies": {
56
- "@theholocron/github-client": "^1.22.0",
57
- "@theholocron/cli": "5.0.0-alpha.25"
58
+ "@theholocron/fs-utils": "^1.16.0",
59
+ "@theholocron/github-client": "^1.51.0",
60
+ "@theholocron/misc-utils": "^1.16.0",
61
+ "@theholocron/cli": "5.0.0-alpha.250"
58
62
  },
59
63
  "engines": {
60
64
  "node": ">=22"