@aspruyt/xfg 7.1.0 → 7.2.0

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.
@@ -1,11 +1,15 @@
1
1
  import chalk from "chalk";
2
2
  import { writeGitHubStepSummary } from "./github-summary.js";
3
3
  import { formatScalarValue } from "../shared/string-utils.js";
4
- /**
5
- * Shared recursive renderer for ruleset config objects.
6
- * The formatLine callback controls indentation style and coloring:
7
- * formatLine(depth, text) → formatted line string
8
- */
4
+ import { formatActionCountEntry, } from "../shared/count-format.js";
5
+ export function hasRepoSettingsChanges(repo) {
6
+ return (repo.settings.length > 0 ||
7
+ repo.rulesets.length > 0 ||
8
+ repo.labels.length > 0 ||
9
+ (repo.variables ?? []).length > 0 ||
10
+ (repo.secrets ?? []).length > 0 ||
11
+ !!repo.error);
12
+ }
9
13
  function renderRulesetConfig(config, startDepth, formatLine) {
10
14
  const lines = [];
11
15
  function renderObject(obj, depth) {
@@ -54,49 +58,22 @@ function renderRulesetConfig(config, startDepth, formatLine) {
54
58
  }
55
59
  return lines;
56
60
  }
57
- /**
58
- * Formats a summary entry like "3 files (1 to create, 2 to update)".
59
- * Returns null if total is 0.
60
- */
61
- export function formatCountEntry(noun, pluralNoun, counts) {
62
- const total = counts.reduce((sum, c) => sum + c.value, 0);
63
- if (total === 0)
64
- return null;
65
- const word = total === 1 ? noun : pluralNoun;
66
- const actions = counts
67
- .filter((c) => c.value > 0)
68
- .map((c) => `${c.value} ${c.label}`);
69
- return `${total} ${word} (${actions.join(", ")})`;
61
+ const SETTINGS_CATEGORIES = [
62
+ { noun: "setting", plural: "settings", totals: (t) => t.settings },
63
+ { noun: "ruleset", plural: "rulesets", totals: (t) => t.rulesets },
64
+ { noun: "label", plural: "labels", totals: (t) => t.labels },
65
+ { noun: "variable", plural: "variables", totals: (t) => t.variables },
66
+ { noun: "secret", plural: "secrets", totals: (t) => t.secrets },
67
+ ];
68
+ export function formatSettingsCountEntries(totals, dryRun) {
69
+ return SETTINGS_CATEGORIES.flatMap(({ noun, plural, totals: pick }) => {
70
+ const t = pick(totals);
71
+ const entry = t && formatActionCountEntry(noun, plural, t, dryRun);
72
+ return entry ? [entry] : [];
73
+ });
70
74
  }
71
75
  function formatSettingsSummary(totals) {
72
- const parts = [];
73
- const settingsEntry = formatCountEntry("setting", "settings", [
74
- { label: "to create", value: totals.settings.create },
75
- { label: "to update", value: totals.settings.update },
76
- ]);
77
- if (settingsEntry)
78
- parts.push(settingsEntry);
79
- const rulesetsEntry = formatCountEntry("ruleset", "rulesets", [
80
- { label: "to create", value: totals.rulesets.create },
81
- { label: "to update", value: totals.rulesets.update },
82
- { label: "to delete", value: totals.rulesets.delete },
83
- ]);
84
- if (rulesetsEntry)
85
- parts.push(rulesetsEntry);
86
- const labelsEntry = formatCountEntry("label", "labels", [
87
- { label: "to create", value: totals.labels.create },
88
- { label: "to update", value: totals.labels.update },
89
- { label: "to delete", value: totals.labels.delete },
90
- ]);
91
- if (labelsEntry)
92
- parts.push(labelsEntry);
93
- const variablesEntry = formatCountEntry("variable", "variables", [
94
- { label: "to create", value: totals.variables?.create ?? 0 },
95
- { label: "to update", value: totals.variables?.update ?? 0 },
96
- { label: "to delete", value: totals.variables?.delete ?? 0 },
97
- ]);
98
- if (variablesEntry)
99
- parts.push(variablesEntry);
76
+ const parts = formatSettingsCountEntries(totals, true);
100
77
  if (parts.length === 0) {
101
78
  return "No changes";
102
79
  }
@@ -116,22 +93,16 @@ function colorizeDiffLine(line) {
116
93
  export function formatSettingsReportCLI(report) {
117
94
  const lines = [];
118
95
  for (const repo of report.repos) {
119
- if (repo.settings.length === 0 &&
120
- repo.rulesets.length === 0 &&
121
- repo.labels.length === 0 &&
122
- (repo.variables ?? []).length === 0 &&
123
- !repo.error) {
96
+ if (!hasRepoSettingsChanges(repo))
124
97
  continue;
125
- }
126
98
  lines.push(chalk.yellow(`~ ${repo.repoName}`));
127
99
  const diffLines = [];
128
100
  renderRepoSettingsDiffLines(repo, diffLines);
129
101
  for (const diffLine of diffLines) {
130
102
  lines.push(colorizeDiffLine(diffLine));
131
103
  }
132
- lines.push(""); // Blank line between repos
104
+ lines.push("");
133
105
  }
134
- // Summary
135
106
  lines.push(formatSettingsSummary(report.totals));
136
107
  return lines;
137
108
  }
@@ -146,10 +117,6 @@ function formatValuePlain(val) {
146
117
  function formatRulesetConfigPlain(config) {
147
118
  return renderRulesetConfig(config, 1, (depth, text) => `+${" ".repeat(depth)}${text.substring(1)}`);
148
119
  }
149
- /**
150
- * Renders a single repo's settings/rulesets/labels changes as plain-text diff lines.
151
- * Shared between formatSettingsReportMarkdown and unified-summary's renderSettingsLines.
152
- */
153
120
  export function renderRepoSettingsDiffLines(repo, diffLines) {
154
121
  const startLength = diffLines.length;
155
122
  for (const setting of repo.settings) {
@@ -163,13 +130,11 @@ export function renderRepoSettingsDiffLines(repo, diffLines) {
163
130
  diffLines.push(`! ${setting.name}: ${formatValuePlain(setting.oldValue)} → ${formatValuePlain(setting.newValue)}`);
164
131
  }
165
132
  }
166
- // Blank line before rulesets if there was content above
167
133
  if (repo.rulesets.length > 0 && diffLines.length > startLength) {
168
134
  diffLines.push("");
169
135
  }
170
136
  for (let i = 0; i < repo.rulesets.length; i++) {
171
137
  const ruleset = repo.rulesets[i];
172
- // Blank line between rulesets
173
138
  if (i > 0)
174
139
  diffLines.push("");
175
140
  if (ruleset.action === "create") {
@@ -201,7 +166,6 @@ export function renderRepoSettingsDiffLines(repo, diffLines) {
201
166
  diffLines.push(`- ruleset "${ruleset.name}"`);
202
167
  }
203
168
  }
204
- // Blank line before labels if there was content above
205
169
  if (repo.labels.length > 0 && diffLines.length > startLength) {
206
170
  diffLines.push("");
207
171
  }
@@ -239,7 +203,6 @@ export function renderRepoSettingsDiffLines(repo, diffLines) {
239
203
  diffLines.push(`- label "${label.name}"`);
240
204
  }
241
205
  }
242
- // Blank line before variables if there was content above
243
206
  if ((repo.variables ?? []).length > 0 && diffLines.length > startLength) {
244
207
  diffLines.push("");
245
208
  }
@@ -254,31 +217,38 @@ export function renderRepoSettingsDiffLines(repo, diffLines) {
254
217
  diffLines.push(`- variable "${variable.name}"`);
255
218
  }
256
219
  }
220
+ if ((repo.secrets ?? []).length > 0 && diffLines.length > startLength) {
221
+ diffLines.push("");
222
+ }
223
+ // Names only: secret values are write-only and must never reach output.
224
+ for (const secret of repo.secrets ?? []) {
225
+ if (secret.action === "create") {
226
+ diffLines.push(`+ secret "${secret.name}"`);
227
+ }
228
+ else if (secret.action === "update") {
229
+ diffLines.push(`! secret "${secret.name}" (update, value write-only)`);
230
+ }
231
+ else {
232
+ diffLines.push(`- secret "${secret.name}"`);
233
+ }
234
+ }
257
235
  if (repo.error) {
258
236
  diffLines.push(`- Error: ${repo.error}`);
259
237
  }
260
238
  }
261
239
  export function formatSettingsReportMarkdown(report, dryRun) {
262
240
  const lines = [];
263
- // Title
264
241
  const title = dryRun ? "## xfg Plan" : "## xfg Apply";
265
242
  lines.push(title);
266
243
  lines.push("");
267
- // Dry-run warning
268
244
  if (dryRun) {
269
245
  lines.push("> [!WARNING]");
270
246
  lines.push("> This was a dry run — no changes were applied");
271
247
  lines.push("");
272
248
  }
273
- // Per-repo sections: heading + diff block
274
249
  for (const repo of report.repos) {
275
- if (repo.settings.length === 0 &&
276
- repo.rulesets.length === 0 &&
277
- repo.labels.length === 0 &&
278
- (repo.variables ?? []).length === 0 &&
279
- !repo.error) {
250
+ if (!hasRepoSettingsChanges(repo))
280
251
  continue;
281
- }
282
252
  lines.push(`### ${repo.repoName}`);
283
253
  lines.push("");
284
254
  const diffLines = [];
@@ -290,7 +260,6 @@ export function formatSettingsReportMarkdown(report, dryRun) {
290
260
  lines.push("");
291
261
  }
292
262
  }
293
- // Summary
294
263
  lines.push(`**${formatSettingsSummary(report.totals)}**`);
295
264
  return lines.join("\n");
296
265
  }
@@ -1,6 +1,6 @@
1
1
  import chalk from "chalk";
2
2
  import { writeGitHubStepSummary } from "./github-summary.js";
3
- import { formatCountEntry } from "./settings-report.js";
3
+ import { formatCountEntry } from "../shared/count-format.js";
4
4
  import { formatDiffLine } from "../shared/diff-format.js";
5
5
  function formatSyncSummary(totals) {
6
6
  const entry = formatCountEntry("file", "files", [
@@ -16,9 +16,7 @@ export function formatSyncReportCLI(report) {
16
16
  if (repo.files.length === 0 && !repo.error) {
17
17
  continue;
18
18
  }
19
- // Repo header
20
19
  lines.push(chalk.yellow(`~ ${repo.repoName}`));
21
- // Files
22
20
  for (const file of repo.files) {
23
21
  if (file.action === "create") {
24
22
  lines.push(chalk.green(` + ${file.path}`));
@@ -29,36 +27,30 @@ export function formatSyncReportCLI(report) {
29
27
  else if (file.action === "delete") {
30
28
  lines.push(chalk.red(` - ${file.path}`));
31
29
  }
32
- // Content diff for structured data files
33
30
  if (file.diffLines) {
34
31
  for (const diffLine of file.diffLines) {
35
32
  lines.push(` ${formatDiffLine(diffLine)}`);
36
33
  }
37
34
  }
38
35
  }
39
- // Error
40
36
  if (repo.error) {
41
37
  lines.push(chalk.red(` Error: ${repo.error}`));
42
38
  }
43
- lines.push(""); // Blank line between repos
39
+ lines.push("");
44
40
  }
45
- // Summary
46
41
  lines.push(formatSyncSummary(report.totals));
47
42
  return lines;
48
43
  }
49
44
  export function formatSyncReportMarkdown(report, dryRun) {
50
45
  const lines = [];
51
- // Title
52
46
  const title = dryRun ? "## xfg Plan" : "## xfg Apply";
53
47
  lines.push(title);
54
48
  lines.push("");
55
- // Dry-run warning
56
49
  if (dryRun) {
57
50
  lines.push("> [!WARNING]");
58
51
  lines.push("> This was a dry run — no changes were applied");
59
52
  lines.push("");
60
53
  }
61
- // Per-repo sections: heading + diff block
62
54
  for (const repo of report.repos) {
63
55
  if (repo.files.length === 0 && !repo.error) {
64
56
  continue;
@@ -73,7 +65,6 @@ export function formatSyncReportMarkdown(report, dryRun) {
73
65
  lines.push("");
74
66
  }
75
67
  }
76
- // Summary
77
68
  lines.push(`**${formatSyncSummary(report.totals)}**`);
78
69
  return lines.join("\n");
79
70
  }
@@ -4,4 +4,4 @@ export { RepoSettingsProcessor, type IRepoSettingsProcessor, type RepoSettingsPl
4
4
  export { type LabelsPlanEntry, LabelsProcessor, type ILabelsProcessor, GitHubLabelsStrategy, } from "./labels/index.js";
5
5
  export { type CodeScanningPlanEntry, CodeScanningProcessor, type ICodeScanningProcessor, GitHubCodeScanningStrategy, } from "./code-scanning/index.js";
6
6
  export { type VariablesPlanEntry, VariablesProcessor, type IVariablesProcessor, GitHubVariablesStrategy, } from "./variables/index.js";
7
- export { SecretsProcessor, type ISecretsProcessor, type SecretsProcessorOptions, type SecretsProcessorResult, GitHubSecretsStrategy, SodiumEncryptor, type ISecretEncryptor, } from "./secrets/index.js";
7
+ export { SecretsProcessor, type SecretsPlanEntry, type ISecretsProcessor, type SecretsProcessorOptions, type SecretsProcessorResult, GitHubSecretsStrategy, SodiumEncryptor, type ISecretEncryptor, } from "./secrets/index.js";
@@ -1,14 +1,8 @@
1
- // Base processor
2
1
  export { countActions, isActiveAction, } from "./base-processor.js";
3
- // Rulesets
4
2
  export { RulesetProcessor, GitHubRulesetStrategy, } from "./rulesets/index.js";
5
- // Repo settings
6
3
  export { RepoSettingsProcessor, GitHubRepoSettingsStrategy, } from "./repo-settings/index.js";
7
- // Labels
8
4
  export { LabelsProcessor, GitHubLabelsStrategy, } from "./labels/index.js";
9
- // Code scanning
10
5
  export { CodeScanningProcessor, GitHubCodeScanningStrategy, } from "./code-scanning/index.js";
11
- // Variables
12
6
  export { VariablesProcessor, GitHubVariablesStrategy, } from "./variables/index.js";
13
7
  // Secrets — not wired into `xfg sync`; driven by `xfg secrets sync` only.
14
8
  export { SecretsProcessor, GitHubSecretsStrategy, SodiumEncryptor, } from "./secrets/index.js";
@@ -0,0 +1,11 @@
1
+ import type { SecretChange } from "./diff.js";
2
+ import { type ActiveAction } from "../base-processor.js";
3
+ export interface SecretsPlanEntry {
4
+ name: string;
5
+ action: ActiveAction;
6
+ }
7
+ export interface SecretsPlanResult {
8
+ lines: string[];
9
+ entries: SecretsPlanEntry[];
10
+ }
11
+ export declare function formatSecretsPlan(changes: SecretChange[], dryRun: boolean): SecretsPlanResult;
@@ -0,0 +1,36 @@
1
+ import chalk from "chalk";
2
+ import { countActions, isActiveAction, } from "../base-processor.js";
3
+ import { formatActionCountEntry } from "../../shared/count-format.js";
4
+ const ACTION_ORDER = {
5
+ create: 0,
6
+ update: 1,
7
+ delete: 2,
8
+ };
9
+ // Names only: this formatter must never receive or print a secret value.
10
+ function formatEntry(entry) {
11
+ switch (entry.action) {
12
+ case "create":
13
+ return chalk.green(` + secret "${entry.name}"`);
14
+ case "update":
15
+ return chalk.yellow(` ~ secret "${entry.name}" (update, value write-only)`);
16
+ case "delete":
17
+ return chalk.red(` - secret "${entry.name}"`);
18
+ }
19
+ }
20
+ export function formatSecretsPlan(changes, dryRun) {
21
+ const entries = changes
22
+ .filter(isActiveAction)
23
+ .map((c) => ({ name: c.name, action: c.action }))
24
+ .sort((a, b) => ACTION_ORDER[a.action] - ACTION_ORDER[b.action]);
25
+ const summary = formatActionCountEntry("secret", "secrets", countActions(entries), dryRun);
26
+ if (!summary) {
27
+ return { lines: [], entries };
28
+ }
29
+ return {
30
+ lines: [
31
+ ...entries.map(formatEntry),
32
+ ` ${dryRun ? "Plan" : "Applied"}: ${summary}`,
33
+ ],
34
+ entries,
35
+ };
36
+ }
@@ -1,5 +1,6 @@
1
1
  export { SecretsProcessor } from "./processor.js";
2
2
  export type { ISecretsProcessor, SecretsProcessorOptions, SecretsProcessorResult, } from "./processor.js";
3
+ export { formatSecretsPlan, type SecretsPlanEntry, type SecretsPlanResult, } from "./formatter.js";
3
4
  export { diffSecrets, type SecretAction, type SecretChange } from "./diff.js";
4
5
  export { GitHubSecretsStrategy } from "./github-secrets-strategy.js";
5
6
  export { SodiumEncryptor, type ISecretEncryptor } from "./encryption.js";
@@ -1,4 +1,5 @@
1
1
  export { SecretsProcessor } from "./processor.js";
2
+ export { formatSecretsPlan, } from "./formatter.js";
2
3
  export { diffSecrets } from "./diff.js";
3
4
  export { GitHubSecretsStrategy } from "./github-secrets-strategy.js";
4
5
  export { SodiumEncryptor } from "./encryption.js";
@@ -3,6 +3,8 @@ import type { RepoConfig } from "../../config/index.js";
3
3
  import type { ISecretsStrategy } from "./types.js";
4
4
  import type { ISecretEncryptor } from "./encryption.js";
5
5
  import type { IEnvResolver } from "../../shared/env-resolver.js";
6
+ import { type IGitHubTokenProvider } from "../../shared/gh-token-utils.js";
7
+ import { type SecretsPlanResult } from "./formatter.js";
6
8
  import { type BaseProcessorOptions, type BaseProcessorResult, type ISettingsProcessor, type ChangeCounts } from "../base-processor.js";
7
9
  export type ISecretsProcessor = ISettingsProcessor<SecretsProcessorOptions, SecretsProcessorResult>;
8
10
  export interface SecretsProcessorOptions extends BaseProcessorOptions {
@@ -10,6 +12,7 @@ export interface SecretsProcessorOptions extends BaseProcessorOptions {
10
12
  }
11
13
  export interface SecretsProcessorResult extends BaseProcessorResult {
12
14
  changes?: ChangeCounts;
15
+ planOutput?: SecretsPlanResult;
13
16
  /** Set when the skip is "nothing configured here" rather than "not a GitHub repo". */
14
17
  noSecretsConfigured?: boolean;
15
18
  }
@@ -17,7 +20,8 @@ export declare class SecretsProcessor implements ISecretsProcessor {
17
20
  private readonly strategy;
18
21
  private readonly encryptor;
19
22
  private readonly envResolver;
20
- constructor(strategy: ISecretsStrategy, encryptor: ISecretEncryptor, envResolver: IEnvResolver);
23
+ private readonly tokenProvider?;
24
+ constructor(strategy: ISecretsStrategy, encryptor: ISecretEncryptor, envResolver: IEnvResolver, tokenProvider?: IGitHubTokenProvider | undefined);
21
25
  process(repoConfig: RepoConfig, repoInfo: RepoInfo, options: SecretsProcessorOptions): Promise<SecretsProcessorResult>;
22
26
  private applySettings;
23
27
  }
@@ -1,5 +1,8 @@
1
+ import { noAppInstallationMessage, } from "../../shared/gh-token-utils.js";
1
2
  import { diffSecrets } from "./diff.js";
2
- import { withGitHubGuards, countActions, buildDryRunResult, buildApplyResult, } from "../base-processor.js";
3
+ import { formatSecretsPlan } from "./formatter.js";
4
+ import { toErrorMessage } from "../../shared/type-guards.js";
5
+ import { withGitHubGuards, countActions, isActiveAction, buildDryRunResult, buildApplyResult, } from "../base-processor.js";
3
6
  function secretEntriesOf(repoConfig) {
4
7
  const { deleteOrphaned: _d, ...entries } = (repoConfig.settings?.secrets ??
5
8
  {});
@@ -14,10 +17,12 @@ export class SecretsProcessor {
14
17
  strategy;
15
18
  encryptor;
16
19
  envResolver;
17
- constructor(strategy, encryptor, envResolver) {
20
+ tokenProvider;
21
+ constructor(strategy, encryptor, envResolver, tokenProvider) {
18
22
  this.strategy = strategy;
19
23
  this.encryptor = encryptor;
20
24
  this.envResolver = envResolver;
25
+ this.tokenProvider = tokenProvider;
21
26
  }
22
27
  async process(repoConfig, repoInfo, options) {
23
28
  const result = await withGitHubGuards(repoConfig, repoInfo, options, {
@@ -31,17 +36,32 @@ export class SecretsProcessor {
31
36
  return result;
32
37
  }
33
38
  async applySettings(githubRepo, repoConfig, options, effectiveToken, repoName) {
39
+ let token = effectiveToken;
40
+ if (this.tokenProvider) {
41
+ const resolved = await this.tokenProvider.getToken(githubRepo, repoName);
42
+ if (resolved.skipped) {
43
+ // A missed rotation must fail the run, not pass as a skip.
44
+ return {
45
+ success: false,
46
+ repoName,
47
+ message: `Failed: ${noAppInstallationMessage(githubRepo.owner)}`,
48
+ };
49
+ }
50
+ token = resolved.token;
51
+ }
34
52
  const { dryRun, noDelete } = options;
35
53
  const secrets = (repoConfig.settings?.secrets ?? {});
36
54
  const configDeleteOrphaned = secrets.deleteOrphaned === true;
37
55
  const deleteOrphaned = configDeleteOrphaned && !(noDelete ?? false);
38
56
  const secretEntries = secretEntriesOf(repoConfig).filter((entry) => typeof entry[1] !== "boolean");
39
- const strategyOptions = { token: effectiveToken, host: githubRepo.host };
57
+ const strategyOptions = { token, host: githubRepo.host };
40
58
  const currentSecrets = await this.strategy.list(githubRepo, strategyOptions);
41
59
  const changes = diffSecrets(currentSecrets, secretEntries.map(([name]) => name), deleteOrphaned);
42
60
  const changeCounts = countActions(changes);
43
61
  if (dryRun) {
44
- return buildDryRunResult(repoName, changeCounts);
62
+ return buildDryRunResult(repoName, changeCounts, {
63
+ planOutput: formatSecretsPlan(changes, true),
64
+ });
45
65
  }
46
66
  const resolvedValues = secretEntries.length > 0
47
67
  ? this.envResolver.resolveAll(secretEntries.map(([name, config]) => ({
@@ -49,27 +69,34 @@ export class SecretsProcessor {
49
69
  envVar: config.env,
50
70
  })))
51
71
  : new Map();
52
- let appliedCount = 0;
53
72
  const publicKey = secretEntries.length > 0
54
73
  ? await this.strategy.getPublicKey(githubRepo, strategyOptions)
55
74
  : undefined;
56
- for (const change of changes) {
57
- switch (change.action) {
58
- case "create":
59
- case "update": {
75
+ const applied = [];
76
+ try {
77
+ for (const change of changes.filter(isActiveAction)) {
78
+ if (change.action === "delete") {
79
+ await this.strategy.delete(githubRepo, change.name, strategyOptions);
80
+ }
81
+ else {
60
82
  const encrypted = await this.encryptor.encrypt(resolvedValues.get(change.name), publicKey.key);
61
83
  await this.strategy.upsert(githubRepo, change.name, encrypted, publicKey.key_id, strategyOptions);
62
- appliedCount++;
63
- break;
64
84
  }
65
- case "delete":
66
- await this.strategy.delete(githubRepo, change.name, strategyOptions);
67
- appliedCount++;
68
- break;
69
- case "unchanged":
70
- break;
85
+ applied.push(change);
71
86
  }
72
87
  }
73
- return buildApplyResult(repoName, changeCounts, appliedCount);
88
+ catch (error) {
89
+ // Report what already landed: the writes are not rolled back.
90
+ return {
91
+ success: false,
92
+ repoName,
93
+ message: `Failed: ${toErrorMessage(error)}`,
94
+ changes: countActions(applied),
95
+ planOutput: formatSecretsPlan(applied, false),
96
+ };
97
+ }
98
+ return buildApplyResult(repoName, changeCounts, applied.length, {
99
+ planOutput: formatSecretsPlan(changes, false),
100
+ });
74
101
  }
75
102
  }
@@ -0,0 +1,10 @@
1
+ export declare function formatCountEntry(noun: string, pluralNoun: string, counts: {
2
+ label: string;
3
+ value: number;
4
+ }[]): string | null;
5
+ export interface ActionTotals {
6
+ create: number;
7
+ update: number;
8
+ delete?: number;
9
+ }
10
+ export declare function formatActionCountEntry(noun: string, pluralNoun: string, totals: ActionTotals, dryRun: boolean): string | null;
@@ -0,0 +1,17 @@
1
+ export function formatCountEntry(noun, pluralNoun, counts) {
2
+ const total = counts.reduce((sum, c) => sum + c.value, 0);
3
+ if (total === 0)
4
+ return null;
5
+ const word = total === 1 ? noun : pluralNoun;
6
+ const actions = counts
7
+ .filter((c) => c.value > 0)
8
+ .map((c) => `${c.value} ${c.label}`);
9
+ return `${total} ${word} (${actions.join(", ")})`;
10
+ }
11
+ export function formatActionCountEntry(noun, pluralNoun, totals, dryRun) {
12
+ return formatCountEntry(noun, pluralNoun, [
13
+ { label: dryRun ? "to create" : "created", value: totals.create },
14
+ { label: dryRun ? "to update" : "updated", value: totals.update },
15
+ { label: dryRun ? "to delete" : "deleted", value: totals.delete ?? 0 },
16
+ ]);
17
+ }
@@ -1,8 +1,16 @@
1
1
  import type { DebugWarnLog } from "./logger.js";
2
2
  import type { GitHubApiTarget } from "./gh-api-utils.js";
3
- interface ITokenManager {
3
+ export interface ITokenManager {
4
4
  getTokenForRepo(repoInfo: GitHubApiTarget): Promise<string | null>;
5
5
  }
6
+ export interface GitHubTokenResult {
7
+ token: string | undefined;
8
+ skipped: boolean;
9
+ }
10
+ /** Resolves the token for one GitHub repo; skipped=true means the owner has no App installation. */
11
+ export interface IGitHubTokenProvider {
12
+ getToken(repoInfo: GitHubApiTarget, context: string): Promise<GitHubTokenResult>;
13
+ }
6
14
  export interface ResolveGitHubTokenOptions {
7
15
  repoInfo: GitHubApiTarget;
8
16
  tokenManager: ITokenManager | null;
@@ -15,12 +23,16 @@ export interface ResolveGitHubTokenOptions {
15
23
  * Returns { token, skipped } where skipped=true means no App installation found
16
24
  * for this owner (token will be undefined). Both sync and settings paths use this.
17
25
  */
18
- export declare function resolveGitHubToken(options: ResolveGitHubTokenOptions): Promise<{
19
- token: string | undefined;
20
- skipped: boolean;
21
- }>;
26
+ export declare function resolveGitHubToken(options: ResolveGitHubTokenOptions): Promise<GitHubTokenResult>;
27
+ export declare function noAppInstallationMessage(owner: string): string;
28
+ export declare class GitHubTokenProvider implements IGitHubTokenProvider {
29
+ private readonly tokenManager;
30
+ private readonly envToken?;
31
+ private readonly log?;
32
+ constructor(tokenManager: ITokenManager | null, envToken?: string | undefined, log?: DebugWarnLog | undefined);
33
+ getToken(repoInfo: GitHubApiTarget, context: string): Promise<GitHubTokenResult>;
34
+ }
22
35
  /**
23
36
  * Check if an error message indicates an HTTP 404 response from the GitHub API.
24
37
  */
25
38
  export declare function isHttp404Error(error: unknown): boolean;
26
- export {};
@@ -16,7 +16,7 @@ export async function resolveGitHubToken(options) {
16
16
  catch (error) {
17
17
  const errorMsg = `GitHub App token resolution failed for ${context}: ${toErrorMessage(error)}`;
18
18
  if (envToken) {
19
- log?.debug(`${errorMsg}; falling back to GH_TOKEN`);
19
+ log?.warn(`${errorMsg}; falling back to the environment token`);
20
20
  }
21
21
  else {
22
22
  log?.warn(`${errorMsg}; no fallback token available`);
@@ -24,6 +24,28 @@ export async function resolveGitHubToken(options) {
24
24
  return { token: envToken, skipped: false };
25
25
  }
26
26
  }
27
+ export function noAppInstallationMessage(owner) {
28
+ return `No GitHub App installation found for ${owner}`;
29
+ }
30
+ export class GitHubTokenProvider {
31
+ tokenManager;
32
+ envToken;
33
+ log;
34
+ constructor(tokenManager, envToken, log) {
35
+ this.tokenManager = tokenManager;
36
+ this.envToken = envToken;
37
+ this.log = log;
38
+ }
39
+ getToken(repoInfo, context) {
40
+ return resolveGitHubToken({
41
+ repoInfo,
42
+ tokenManager: this.tokenManager,
43
+ context,
44
+ log: this.log,
45
+ envToken: this.envToken,
46
+ });
47
+ }
48
+ }
27
49
  /**
28
50
  * Check if an error message indicates an HTTP 404 response from the GitHub API.
29
51
  */
@@ -1,5 +1,5 @@
1
1
  import { isGitHubRepo } from "../repo/index.js";
2
- import { resolveGitHubToken } from "../shared/gh-token-utils.js";
2
+ import { noAppInstallationMessage, resolveGitHubToken, } from "../shared/gh-token-utils.js";
3
3
  export class AuthOptionsBuilder {
4
4
  tokenManager;
5
5
  log;
@@ -32,7 +32,7 @@ export class AuthOptionsBuilder {
32
32
  skipResult: {
33
33
  success: true,
34
34
  repoName,
35
- message: `No GitHub App installation found for ${repoInfo.owner}`,
35
+ message: noAppInstallationMessage(repoInfo.owner),
36
36
  skipped: true,
37
37
  },
38
38
  };
@@ -10,6 +10,7 @@ interface GitHubAppCredentials {
10
10
  * Creates a GitHubAppTokenManager from credentials, or null if not provided.
11
11
  */
12
12
  export declare function createTokenManager(credentials?: GitHubAppCredentials): GitHubAppTokenManager | null;
13
+ export declare function createTokenManagerFromEnv(env: NodeJS.ProcessEnv): GitHubAppTokenManager | null;
13
14
  /**
14
15
  * Returns FileModeFixupCommitStrategy (decorating GraphQLCommitStrategy) for
15
16
  * GitHub repos with App credentials (verified commits + executable file mode
@@ -12,6 +12,11 @@ export function createTokenManager(credentials) {
12
12
  }
13
13
  return new GitHubAppTokenManager(credentials.clientId, credentials.privateKey);
14
14
  }
15
+ export function createTokenManagerFromEnv(env) {
16
+ const clientId = env.XFG_GITHUB_CLIENT_ID;
17
+ const privateKey = env.XFG_GITHUB_APP_PRIVATE_KEY;
18
+ return createTokenManager(clientId && privateKey ? { clientId, privateKey } : undefined);
19
+ }
15
20
  /**
16
21
  * Returns FileModeFixupCommitStrategy (decorating GraphQLCommitStrategy) for
17
22
  * GitHub repos with App credentials (verified commits + executable file mode