@aspruyt/xfg 7.5.2 → 8.1.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.
Files changed (74) hide show
  1. package/dist/ai/client-factory.js +15 -3
  2. package/dist/cli/repo-sync-runner.d.ts +2 -0
  3. package/dist/cli/repo-sync-runner.js +18 -9
  4. package/dist/cli/secrets-command.js +16 -4
  5. package/dist/cli/settings-factories.d.ts +2 -1
  6. package/dist/cli/settings-factories.js +7 -1
  7. package/dist/cli/settings-report-builder.d.ts +6 -1
  8. package/dist/cli/settings-report-builder.js +7 -1
  9. package/dist/cli/settings-runner.js +24 -15
  10. package/dist/cli/sync-command.js +5 -1
  11. package/dist/cli/types.d.ts +4 -2
  12. package/dist/config/env.js +8 -0
  13. package/dist/config/file-reference-resolver.js +16 -13
  14. package/dist/config/index.d.ts +1 -1
  15. package/dist/config/merge.d.ts +9 -5
  16. package/dist/config/merge.js +148 -67
  17. package/dist/config/normalizer.js +87 -18
  18. package/dist/config/types.d.ts +28 -0
  19. package/dist/config/validator.js +25 -3
  20. package/dist/config/validators/ai-validator.js +2 -0
  21. package/dist/config/validators/file-validator.js +4 -1
  22. package/dist/config/validators/group-validator.js +3 -0
  23. package/dist/config/validators/ruleset-validator.js +6 -5
  24. package/dist/config/validators/shared.js +123 -0
  25. package/dist/output/settings-report.d.ts +6 -1
  26. package/dist/output/settings-report.js +31 -9
  27. package/dist/repo/detector.js +15 -24
  28. package/dist/settings/environments/diff.d.ts +22 -0
  29. package/dist/settings/environments/diff.js +78 -0
  30. package/dist/settings/environments/formatter.d.ts +17 -0
  31. package/dist/settings/environments/formatter.js +62 -0
  32. package/dist/settings/environments/github-environments-strategy.d.ts +23 -0
  33. package/dist/settings/environments/github-environments-strategy.js +54 -0
  34. package/dist/settings/environments/index.d.ts +5 -0
  35. package/dist/settings/environments/index.js +3 -0
  36. package/dist/settings/environments/processor.d.ts +21 -0
  37. package/dist/settings/environments/processor.js +100 -0
  38. package/dist/settings/environments/types.d.ts +38 -0
  39. package/dist/settings/environments/types.js +1 -0
  40. package/dist/settings/index.d.ts +1 -0
  41. package/dist/settings/index.js +1 -0
  42. package/dist/settings/secrets/diff.d.ts +2 -0
  43. package/dist/settings/secrets/formatter.d.ts +4 -0
  44. package/dist/settings/secrets/formatter.js +17 -4
  45. package/dist/settings/secrets/index.d.ts +2 -2
  46. package/dist/settings/secrets/index.js +1 -1
  47. package/dist/settings/secrets/processor.d.ts +16 -2
  48. package/dist/settings/secrets/processor.js +132 -28
  49. package/dist/shared/credential-env.d.ts +10 -0
  50. package/dist/shared/credential-env.js +50 -0
  51. package/dist/shared/gh-token-utils.d.ts +7 -1
  52. package/dist/shared/gh-token-utils.js +14 -1
  53. package/dist/shared/github-host-policy.d.ts +22 -0
  54. package/dist/shared/github-host-policy.js +61 -0
  55. package/dist/shared/path-safety.d.ts +12 -0
  56. package/dist/shared/path-safety.js +51 -0
  57. package/dist/shared/retry-utils.js +9 -13
  58. package/dist/shared/sequential.d.ts +2 -0
  59. package/dist/shared/sequential.js +4 -0
  60. package/dist/sync/auth-options-builder.d.ts +3 -1
  61. package/dist/sync/auth-options-builder.js +4 -1
  62. package/dist/sync/manifest.js +7 -2
  63. package/dist/sync/render-writer.js +7 -1
  64. package/dist/sync/repository-processor.d.ts +2 -0
  65. package/dist/sync/repository-processor.js +1 -1
  66. package/dist/vcs/ado-pr-strategy.js +3 -2
  67. package/dist/vcs/commit-strategy-selector.d.ts +3 -2
  68. package/dist/vcs/commit-strategy-selector.js +5 -4
  69. package/dist/vcs/git-ops.d.ts +3 -3
  70. package/dist/vcs/git-ops.js +29 -8
  71. package/dist/vcs/github-app-token-manager.d.ts +4 -1
  72. package/dist/vcs/github-app-token-manager.js +24 -4
  73. package/dist/vcs/github-pr-strategy.js +3 -2
  74. package/package.json +3 -2
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * Deep merge utilities for JSON configuration objects.
3
- * Supports per-field array merge strategies via $arrayMerge + $values directives.
3
+ * Supports per-field array merge strategies via $arrayMerge + $values (+ $matchBy) directives.
4
4
  */
5
5
  import { isPlainObject } from "../shared/type-guards.js";
6
+ import { ValidationError } from "../shared/errors.js";
6
7
  /**
7
8
  * Candidate keys for matching array items by identity rather than index.
8
9
  * Order matters — first key found across all items wins.
@@ -29,10 +30,59 @@ export function findMatchKey(base, overlay) {
29
30
  * Only these are stripped during merge — standard $-prefixed keys
30
31
  * like $schema, $id, $ref, $generated are preserved.
31
32
  */
32
- const XFG_DIRECTIVES = new Set(["$arrayMerge", "$values"]);
33
- function mergeByKey(base, overlay, matchKey, ctx) {
33
+ const XFG_DIRECTIVES = new Set(["$arrayMerge", "$values", "$matchBy"]);
34
+ function childPath(path, key) {
35
+ return path ? `${path}.${key}` : key;
36
+ }
37
+ function mergeError(ctx, path, message) {
38
+ const prefix = ctx.location ? `${ctx.location}: ` : "";
39
+ return new ValidationError(`${prefix}${path}: ${message}`);
40
+ }
41
+ /**
42
+ * Returns the directive's $matchBy key, or undefined when it has none.
43
+ * Throws unless $matchBy is a non-empty string paired with $arrayMerge: merge.
44
+ */
45
+ function readMatchBy(directive, ctx, path) {
46
+ if (!("$matchBy" in directive))
47
+ return undefined;
48
+ const matchBy = directive.$matchBy;
49
+ if (typeof matchBy !== "string" || matchBy === "") {
50
+ throw mergeError(ctx, path, "$matchBy must be a non-empty string");
51
+ }
52
+ const strategy = directive.$arrayMerge;
53
+ if (strategy !== "merge") {
54
+ let got = "none";
55
+ if (typeof strategy === "string")
56
+ got = `'${strategy}'`;
57
+ else if (strategy !== undefined)
58
+ got = JSON.stringify(strategy);
59
+ throw mergeError(ctx, path, `$matchBy requires $arrayMerge: merge, got ${got}`);
60
+ }
61
+ return matchBy;
62
+ }
63
+ function assertKeyedItems(items, matchBy, label, ctx, path) {
64
+ const firstIndexByValue = new Map();
65
+ for (let i = 0; i < items.length; i++) {
66
+ const item = items[i];
67
+ if (!isPlainObject(item) || !Object.hasOwn(item, matchBy)) {
68
+ throw mergeError(ctx, path, `${label} item ${i} has no $matchBy key '${matchBy}'`);
69
+ }
70
+ const value = item[matchBy];
71
+ // Map compares objects by reference, so only primitives can match
72
+ if (value !== null &&
73
+ !["string", "number", "boolean"].includes(typeof value)) {
74
+ throw mergeError(ctx, path, `${label} item ${i} $matchBy ${matchBy} must be a string, number, boolean or null`);
75
+ }
76
+ const first = firstIndexByValue.get(value);
77
+ if (first !== undefined) {
78
+ throw mergeError(ctx, path, `${label} items ${first} and ${i} share $matchBy ${matchBy} '${String(value)}'`);
79
+ }
80
+ firstIndexByValue.set(value, i);
81
+ }
82
+ }
83
+ function mergeByKey(base, overlay, matchKey, ctx, path) {
34
84
  const baseByKey = new Map();
35
- // findMatchKey guarantees every item in both arrays is a plain object with matchKey
85
+ // Callers guarantee every item in both arrays is a plain object with matchKey
36
86
  for (let i = 0; i < base.length; i++) {
37
87
  const item = base[i];
38
88
  const keyValue = item[matchKey];
@@ -47,7 +97,7 @@ function mergeByKey(base, overlay, matchKey, ctx) {
47
97
  const baseEntry = baseByKey.get(keyValue);
48
98
  if (baseEntry) {
49
99
  baseByKey.set(keyValue, {
50
- item: deepMerge(baseEntry.item, item, ctx),
100
+ item: mergeObjects(baseEntry.item, item, ctx, `${path}[${baseEntry.index}]`),
51
101
  index: baseEntry.index,
52
102
  });
53
103
  }
@@ -76,33 +126,30 @@ const arrayMergeStrategies = new Map([
76
126
  ["prepend", (base, overlay) => [...overlay, ...base]],
77
127
  [
78
128
  "merge",
79
- (base, overlay, ctx) => {
129
+ (base, overlay, ctx, path) => {
80
130
  const matchKey = findMatchKey(base, overlay);
81
131
  if (!matchKey) {
82
132
  return [...base, ...overlay];
83
133
  }
84
- return mergeByKey(base, overlay, matchKey, ctx);
134
+ return mergeByKey(base, overlay, matchKey, ctx, path);
85
135
  },
86
136
  ],
87
137
  ]);
88
138
  /**
89
139
  * Checks if a value is an unresolved $arrayMerge directive object
90
- * (only contains $arrayMerge + $values keys, with a valid strategy and array values).
140
+ * (only directive keys, with a valid strategy and array values).
91
141
  */
92
142
  function isUnresolvedDirective(value) {
93
143
  if (!isPlainObject(value))
94
144
  return false;
95
- const keys = Object.keys(value);
96
- return (keys.length === 2 &&
97
- keys.every((k) => XFG_DIRECTIVES.has(k)) &&
98
- typeof value.$arrayMerge === "string" &&
99
- arrayMergeStrategies.has(value.$arrayMerge) &&
145
+ return (Object.keys(value).every((k) => XFG_DIRECTIVES.has(k)) &&
146
+ isArrayMergeStrategy(value.$arrayMerge) &&
100
147
  Array.isArray(value.$values));
101
148
  }
102
- function mergeArrays(base, overlay, strategy, ctx) {
149
+ function mergeArrays(base, overlay, strategy, ctx, path) {
103
150
  const handler = arrayMergeStrategies.get(strategy);
104
151
  if (handler) {
105
- return handler(base, overlay, ctx);
152
+ return handler(base, overlay, ctx, path);
106
153
  }
107
154
  return overlay;
108
155
  }
@@ -114,72 +161,109 @@ function mergeArrays(base, overlay, strategy, ctx) {
114
161
  * @param ctx - Merge context with array strategies
115
162
  */
116
163
  export function deepMerge(base, overlay, ctx) {
164
+ return mergeObjects(base, overlay, ctx, "");
165
+ }
166
+ function mergeObjects(base, overlay, ctx, path) {
117
167
  const result = { ...base };
118
168
  for (const [key, overlayValue] of Object.entries(overlay)) {
119
- // Skip directive keys in output
120
169
  if (XFG_DIRECTIVES.has(key))
121
170
  continue;
122
- const baseValue = base[key];
123
- // If base is an unresolved directive (from a previous layer with no base array),
124
- // resolve it to its $values array before proceeding with merge logic.
125
- const resolvedBase = isUnresolvedDirective(baseValue)
126
- ? baseValue.$values
127
- : baseValue;
128
- // Per-field $arrayMerge + $values directive
129
- if (isPlainObject(overlayValue) && "$arrayMerge" in overlayValue) {
130
- const strategy = overlayValue.$arrayMerge;
131
- const values = overlayValue.$values;
132
- if ((strategy === "replace" ||
133
- strategy === "append" ||
134
- strategy === "prepend" ||
135
- strategy === "merge") &&
136
- Array.isArray(values) &&
137
- Array.isArray(resolvedBase)) {
138
- result[key] = mergeArrays(resolvedBase, values, strategy, ctx);
139
- continue;
140
- }
141
- }
142
- // Both are arrays — use default strategy
143
- if (Array.isArray(resolvedBase) && Array.isArray(overlayValue)) {
144
- result[key] = mergeArrays(resolvedBase, overlayValue, ctx.defaultArrayStrategy, ctx);
145
- continue;
146
- }
147
- // Both are plain objects — recurse
148
- if (isPlainObject(resolvedBase) && isPlainObject(overlayValue)) {
149
- result[key] = deepMerge(resolvedBase, overlayValue, ctx);
150
- continue;
151
- }
152
- // Otherwise, overlay wins (including null values)
153
- result[key] = overlayValue;
171
+ result[key] = mergeValue(base[key], overlayValue, ctx, childPath(path, key));
154
172
  }
155
173
  return result;
156
174
  }
175
+ function mergeValue(baseValue, overlayValue, ctx, path) {
176
+ // A directive left unresolved by an earlier layer with no base array acts as its $values
177
+ const resolvedBase = isUnresolvedDirective(baseValue)
178
+ ? resolveBaseDirective(baseValue, ctx, path)
179
+ : baseValue;
180
+ if (isArrayDirective(overlayValue)) {
181
+ const merged = applyArrayDirective(resolvedBase, overlayValue, ctx, path);
182
+ if (merged !== undefined)
183
+ return merged;
184
+ }
185
+ if (Array.isArray(resolvedBase) && Array.isArray(overlayValue)) {
186
+ return mergeArrays(resolvedBase, overlayValue, ctx.defaultArrayStrategy, ctx, path);
187
+ }
188
+ if (isPlainObject(resolvedBase) && isPlainObject(overlayValue)) {
189
+ return mergeObjects(resolvedBase, overlayValue, ctx, path);
190
+ }
191
+ return overlayValue;
192
+ }
193
+ function resolveBaseDirective(directive, ctx, path) {
194
+ const matchBy = readMatchBy(directive, ctx, path);
195
+ if (matchBy !== undefined) {
196
+ assertKeyedItems(directive.$values, matchBy, "base", ctx, path);
197
+ }
198
+ return directive.$values;
199
+ }
200
+ function isArrayDirective(value) {
201
+ return (isPlainObject(value) && ("$arrayMerge" in value || "$matchBy" in value));
202
+ }
203
+ function isArrayMergeStrategy(value) {
204
+ return (typeof value === "string" &&
205
+ arrayMergeStrategies.has(value));
206
+ }
207
+ /**
208
+ * Applies an overlay directive to the base array.
209
+ * Returns undefined when it doesn't apply, so the caller falls back to a plain merge.
210
+ */
211
+ function applyArrayDirective(base, directive, ctx, path) {
212
+ const strategy = directive.$arrayMerge;
213
+ const values = directive.$values;
214
+ const matchBy = readMatchBy(directive, ctx, path);
215
+ if (matchBy !== undefined && Array.isArray(values)) {
216
+ assertKeyedItems(values, matchBy, "overlay", ctx, path);
217
+ }
218
+ if (!isArrayMergeStrategy(strategy) ||
219
+ !Array.isArray(values) ||
220
+ !Array.isArray(base)) {
221
+ return undefined;
222
+ }
223
+ if (matchBy === undefined) {
224
+ return mergeArrays(base, values, strategy, ctx, path);
225
+ }
226
+ assertKeyedItems(base, matchBy, "base", ctx, path);
227
+ return mergeByKey(base, values, matchBy, ctx, path);
228
+ }
157
229
  /**
158
- * Strip xfg merge directive keys ($arrayMerge, $values) from an object.
230
+ * Strip xfg merge directive keys ($arrayMerge, $values, $matchBy) from an object.
159
231
  * Works recursively on nested objects and arrays.
160
232
  * Standard $-prefixed keys ($schema, $id, $ref, etc.) are preserved.
161
233
  *
162
- * When an unresolved directive object is found (only contains $arrayMerge + $values),
234
+ * When an unresolved directive object is found (only directive keys),
163
235
  * it is replaced with the $values array. This handles the case where a directive
164
236
  * had no base array to merge with.
237
+ *
238
+ * @param location - Prefixes errors, e.g. the file name being stripped
165
239
  */
166
- export function stripMergeDirectives(obj) {
240
+ export function stripMergeDirectives(obj, location) {
241
+ return stripObject(obj, { location }, "");
242
+ }
243
+ function stripItems(items, errCtx, path) {
244
+ return items.map((item, i) => isPlainObject(item) ? stripObject(item, errCtx, `${path}[${i}]`) : item);
245
+ }
246
+ function stripObject(obj, errCtx, path) {
167
247
  const result = {};
168
248
  for (const [key, value] of Object.entries(obj)) {
169
- // Skip xfg directive keys only
170
249
  if (XFG_DIRECTIVES.has(key))
171
250
  continue;
172
- if (isPlainObject(value)) {
173
- if (isUnresolvedDirective(value)) {
174
- // Resolve to the $values array, stripping directives from items
175
- result[key] = value.$values.map((item) => isPlainObject(item) ? stripMergeDirectives(item) : item);
176
- }
177
- else {
178
- result[key] = stripMergeDirectives(value);
251
+ const keyPath = childPath(path, key);
252
+ // Validate before branching: an invalid $matchBy is not a directive and would be stripped silently
253
+ const matchBy = isPlainObject(value)
254
+ ? readMatchBy(value, errCtx, keyPath)
255
+ : undefined;
256
+ if (isUnresolvedDirective(value)) {
257
+ if (matchBy !== undefined) {
258
+ assertKeyedItems(value.$values, matchBy, "overlay", errCtx, keyPath);
179
259
  }
260
+ result[key] = stripItems(value.$values, errCtx, keyPath);
261
+ }
262
+ else if (isPlainObject(value)) {
263
+ result[key] = stripObject(value, errCtx, keyPath);
180
264
  }
181
265
  else if (Array.isArray(value)) {
182
- result[key] = value.map((item) => isPlainObject(item) ? stripMergeDirectives(item) : item);
266
+ result[key] = stripItems(value, errCtx, keyPath);
183
267
  }
184
268
  else {
185
269
  result[key] = value;
@@ -187,10 +271,10 @@ export function stripMergeDirectives(obj) {
187
271
  }
188
272
  return result;
189
273
  }
190
- export function createMergeContext(defaultStrategy = "replace") {
191
- return {
192
- defaultArrayStrategy: defaultStrategy,
193
- };
274
+ export function createMergeContext(defaultStrategy = "replace", location) {
275
+ return location === undefined
276
+ ? { defaultArrayStrategy: defaultStrategy }
277
+ : { defaultArrayStrategy: defaultStrategy, location };
194
278
  }
195
279
  // =============================================================================
196
280
  // Text Content Utilities
@@ -207,11 +291,9 @@ export function isTextContent(content) {
207
291
  * For mixed types: overlay replaces base.
208
292
  */
209
293
  export function mergeTextContent(base, overlay, strategy = "replace") {
210
- // If overlay is a string, it always replaces
211
294
  if (typeof overlay === "string") {
212
295
  return overlay;
213
296
  }
214
- // If base is also an array, apply merge strategy
215
297
  if (Array.isArray(base)) {
216
298
  switch (strategy) {
217
299
  case "append":
@@ -224,6 +306,5 @@ export function mergeTextContent(base, overlay, strategy = "replace") {
224
306
  return overlay;
225
307
  }
226
308
  }
227
- // Base is string, overlay is array - overlay replaces
228
309
  return overlay;
229
310
  }
@@ -5,11 +5,11 @@ import { expandRepoGroups } from "./extends-resolver.js";
5
5
  * Clone content, stripping merge directives from object content.
6
6
  * Text content is cloned as-is since it has no merge directives.
7
7
  */
8
- function cloneContent(content) {
8
+ function cloneContent(content, fileName) {
9
9
  if (isTextContent(content)) {
10
10
  return structuredClone(content);
11
11
  }
12
- return stripMergeDirectives(structuredClone(content));
12
+ return stripMergeDirectives(structuredClone(content), fileName);
13
13
  }
14
14
  /**
15
15
  * Resolve the final content for a file by applying override/inherit/merge rules.
@@ -17,32 +17,34 @@ function cloneContent(content) {
17
17
  * Returns null when the file should be empty (e.g. override with no content,
18
18
  * or root file with no content and no repo override).
19
19
  */
20
- function resolveFileContent(rootContent, repoOverride, mergeStrategy) {
20
+ function resolveFileContent(fileName, rootContent, repoOverride, mergeStrategy) {
21
21
  if (repoOverride?.override) {
22
22
  return repoOverride.content !== undefined
23
- ? cloneContent(repoOverride.content)
23
+ ? cloneContent(repoOverride.content, fileName)
24
24
  : null;
25
25
  }
26
26
  if (rootContent === undefined) {
27
- return repoOverride?.content ? cloneContent(repoOverride.content) : null;
27
+ return repoOverride?.content
28
+ ? cloneContent(repoOverride.content, fileName)
29
+ : null;
28
30
  }
29
31
  if (!repoOverride?.content) {
30
32
  return structuredClone(rootContent);
31
33
  }
32
- return mergeContentPair(rootContent, repoOverride.content, mergeStrategy);
34
+ return mergeContentPair(fileName, rootContent, repoOverride.content, mergeStrategy);
33
35
  }
34
36
  /**
35
37
  * Merge two content values using the appropriate strategy.
36
38
  * Handles text+text, object+object, and type mismatch cases.
37
39
  */
38
- function mergeContentPair(base, overlay, strategy) {
40
+ function mergeContentPair(fileName, base, overlay, strategy) {
39
41
  if (isTextContent(base) && isTextContent(overlay)) {
40
42
  return mergeTextContent(base, overlay, strategy);
41
43
  }
42
44
  if (!isTextContent(base) && !isTextContent(overlay)) {
43
- const ctx = createMergeContext(strategy);
45
+ const ctx = createMergeContext(strategy, fileName);
44
46
  const merged = deepMerge(structuredClone(base), overlay, ctx);
45
- return stripMergeDirectives(merged);
47
+ return stripMergeDirectives(merged, fileName);
46
48
  }
47
49
  return overlay;
48
50
  }
@@ -93,10 +95,13 @@ function normalizeAiOption(prOptions) {
93
95
  return { ...rest, ai: { ...ai, provider: ai.provider ?? "anthropic" } };
94
96
  return Object.keys(rest).length > 0 ? rest : undefined;
95
97
  }
98
+ function rulesetLocation(name) {
99
+ return `ruleset '${name}'`;
100
+ }
96
101
  /**
97
102
  * Deep merges two rulesets: per-repo values override root values.
98
103
  */
99
- function mergeRuleset(root, perRepo) {
104
+ function mergeRuleset(name, root, perRepo) {
100
105
  if (!root)
101
106
  return structuredClone(perRepo ?? {});
102
107
  if (!perRepo)
@@ -104,7 +109,7 @@ function mergeRuleset(root, perRepo) {
104
109
  // Deep merge using the existing merge utility with replace strategy.
105
110
  // deepMerge operates on Record<string, unknown> — the cast is safe because
106
111
  // merging two Ruleset-shaped objects preserves the Ruleset structure.
107
- const ctx = createMergeContext("replace");
112
+ const ctx = createMergeContext("replace", rulesetLocation(name));
108
113
  return deepMerge(structuredClone(root), perRepo, ctx);
109
114
  }
110
115
  function mergeLabels(rootLabels, repoLabels) {
@@ -218,6 +223,63 @@ function dropCollaboratorsIfEmpty(merged) {
218
223
  return undefined;
219
224
  return merged;
220
225
  }
226
+ /**
227
+ * Merges one environment layer over another: a set `deploymentBranchPolicy`
228
+ * replaces the inherited one whole, and secrets merge like repo secrets.
229
+ */
230
+ function mergeEnvironmentLayer(base, overlay) {
231
+ const inherited = base === false ? undefined : base;
232
+ const result = {};
233
+ const policy = overlay.deploymentBranchPolicy ?? inherited?.deploymentBranchPolicy;
234
+ if (policy !== undefined) {
235
+ result.deploymentBranchPolicy = structuredClone(policy);
236
+ }
237
+ if (inherited?.secrets || overlay.secrets) {
238
+ result.secrets = mergeEntryMapLayer(inherited?.secrets, overlay.secrets);
239
+ }
240
+ return result;
241
+ }
242
+ function finalizeEnvironment(env) {
243
+ const result = {};
244
+ if (env.deploymentBranchPolicy) {
245
+ result.deploymentBranchPolicy = structuredClone(env.deploymentBranchPolicy);
246
+ }
247
+ const secrets = Object.entries(env.secrets ?? {}).filter(([, value]) => value !== false);
248
+ if (secrets.length > 0) {
249
+ result.secrets = Object.fromEntries(secrets);
250
+ }
251
+ return result;
252
+ }
253
+ // Matches the entries mergeNamedEntries acts on; anything else is ignored there.
254
+ function isMergeableEntry(entry) {
255
+ return entry === false || (typeof entry === "object" && entry !== null);
256
+ }
257
+ // GitHub environment names are case-insensitive; base entries take the overlay's spelling so they merge.
258
+ function mergeEnvironmentEntries(base, overlay) {
259
+ const overlayNames = new Map();
260
+ for (const [name, entry] of Object.entries(overlay)) {
261
+ if (name !== "inherit" && isMergeableEntry(entry)) {
262
+ overlayNames.set(name.toLowerCase(), name);
263
+ }
264
+ }
265
+ const rekeyed = {};
266
+ for (const [name, env] of Object.entries(base ?? {})) {
267
+ rekeyed[overlayNames.get(name.toLowerCase()) ?? name] = env;
268
+ }
269
+ return mergeNamedEntries(rekeyed, overlay, mergeEnvironmentLayer);
270
+ }
271
+ function mergeEnvironments(root, perRepo) {
272
+ if (!root && !perRepo)
273
+ return undefined;
274
+ const merged = mergeEnvironmentEntries(root, perRepo ?? {});
275
+ const result = {};
276
+ for (const [name, env] of Object.entries(merged)) {
277
+ if (env === false)
278
+ continue;
279
+ result[name] = finalizeEnvironment(env);
280
+ }
281
+ return Object.keys(result).length > 0 ? result : undefined;
282
+ }
221
283
  /**
222
284
  * Merges settings: per-repo settings deep merge with root settings.
223
285
  * Returns undefined if no settings are defined.
@@ -244,8 +306,8 @@ export function mergeSettings(root, perRepo) {
244
306
  if (!inheritRulesets && !repoRuleset && rootRuleset) {
245
307
  continue;
246
308
  }
247
- const merged = mergeRuleset(rootRuleset, repoRuleset);
248
- result.rulesets[name] = stripMergeDirectives(merged);
309
+ const merged = mergeRuleset(name, rootRuleset, repoRuleset);
310
+ result.rulesets[name] = stripMergeDirectives(merged, rulesetLocation(name));
249
311
  }
250
312
  if (Object.keys(result.rulesets).length === 0) {
251
313
  delete result.rulesets;
@@ -312,6 +374,10 @@ export function mergeSettings(root, perRepo) {
312
374
  result.collaborators = merged;
313
375
  }
314
376
  }
377
+ const mergedEnvironments = mergeEnvironments(root?.environments, perRepo?.environments);
378
+ if (mergedEnvironments) {
379
+ result.environments = mergedEnvironments;
380
+ }
315
381
  return Object.keys(result).length > 0 ? result : undefined;
316
382
  }
317
383
  /**
@@ -340,7 +406,7 @@ function applyFileLayer(accumulated, layerFiles) {
340
406
  mergedContent = overlay.content ?? existing.content;
341
407
  }
342
408
  else {
343
- mergedContent = mergeContentPair(existing.content, overlay.content, existing.mergeStrategy ?? "replace");
409
+ mergedContent = mergeContentPair(fileName, existing.content, overlay.content, existing.mergeStrategy ?? "replace");
344
410
  }
345
411
  const { override: _override, ...restFileConfig } = fileConfig;
346
412
  accumulated[fileName] = {
@@ -400,7 +466,7 @@ function mergeNamedEntries(base, overlay, merge) {
400
466
  }
401
467
  else if (typeof entry === "object" && entry !== null) {
402
468
  const existing = result[name];
403
- result[name] = merge(existing, entry);
469
+ result[name] = merge(existing, entry, name);
404
470
  }
405
471
  }
406
472
  return result;
@@ -418,8 +484,8 @@ function mergeRawSettings(base, overlay) {
418
484
  return structuredClone(base);
419
485
  const result = base ? structuredClone(base) : {};
420
486
  if (overlay.rulesets) {
421
- result.rulesets = mergeNamedEntries(result.rulesets, overlay.rulesets, (existing, entry) => existing && typeof existing === "object"
422
- ? mergeRuleset(existing, entry)
487
+ result.rulesets = mergeNamedEntries(result.rulesets, overlay.rulesets, (existing, entry, name) => existing && typeof existing === "object"
488
+ ? mergeRuleset(name, existing, entry)
423
489
  : structuredClone(entry));
424
490
  }
425
491
  if (overlay.repo !== undefined) {
@@ -456,6 +522,9 @@ function mergeRawSettings(base, overlay) {
456
522
  if (overlay.collaborators) {
457
523
  result.collaborators = mergeCollaboratorsLayer(result.collaborators, overlay.collaborators);
458
524
  }
525
+ if (overlay.environments) {
526
+ result.environments = mergeEnvironmentEntries(result.environments, overlay.environments);
527
+ }
459
528
  if (overlay.deleteOrphaned !== undefined) {
460
529
  result.deleteOrphaned = overlay.deleteOrphaned;
461
530
  }
@@ -524,7 +593,7 @@ function resolveFileEntry(fileName, fileConfig, repoOverride, inheritFiles, glob
524
593
  if (!inheritFiles && !repoOverride)
525
594
  return null;
526
595
  const fileStrategy = fileConfig.mergeStrategy ?? "replace";
527
- let mergedContent = resolveFileContent(fileConfig.content, repoOverride, fileStrategy);
596
+ let mergedContent = resolveFileContent(fileName, fileConfig.content, repoOverride, fileStrategy);
528
597
  if (mergedContent !== null) {
529
598
  mergedContent = interpolateContent(mergedContent, { strict: true, env });
530
599
  }
@@ -291,6 +291,28 @@ export interface SecretConfig {
291
291
  export type SecretsConfig = Record<string, SecretConfig | boolean> & {
292
292
  deleteOrphaned?: boolean;
293
293
  };
294
+ export type DeploymentBranchPatternType = "branch" | "tag";
295
+ export interface DeploymentBranchPattern {
296
+ type: DeploymentBranchPatternType;
297
+ /** fnmatch-style name pattern, e.g. `main` or `v*.*.*` */
298
+ name: string;
299
+ }
300
+ /** Exactly one of `protectedBranches: true` or a non-empty `custom` list. */
301
+ export interface DeploymentBranchPolicy {
302
+ protectedBranches?: boolean;
303
+ custom?: DeploymentBranchPattern[];
304
+ }
305
+ export interface EnvironmentConfig {
306
+ /** Omitted: any branch can deploy */
307
+ deploymentBranchPolicy?: DeploymentBranchPolicy;
308
+ /** Environment secrets keyed by name; only `xfg secrets sync` writes them */
309
+ secrets?: Record<string, SecretConfig>;
310
+ }
311
+ export interface RawEnvironmentConfig {
312
+ /** `false` clears an inherited policy so any branch can deploy */
313
+ deploymentBranchPolicy?: DeploymentBranchPolicy | false;
314
+ secrets?: Record<string, SecretConfig | false>;
315
+ }
294
316
  export interface CollaboratorsConfig {
295
317
  /** GitHub usernames granted write access (personal repos only) */
296
318
  users?: string[];
@@ -319,6 +341,8 @@ export interface RepoSettings {
319
341
  };
320
342
  /** Direct collaborators on personal (user-owned) repos */
321
343
  collaborators?: CollaboratorsConfig;
344
+ /** GitHub deployment environments keyed by name */
345
+ environments?: Record<string, EnvironmentConfig>;
322
346
  deleteOrphaned?: boolean;
323
347
  }
324
348
  export type ContentValue = Record<string, unknown> | string | string[];
@@ -384,6 +408,7 @@ export interface RawRootSettings {
384
408
  };
385
409
  secrets?: SecretsConfig;
386
410
  collaborators?: CollaboratorsConfig;
411
+ environments?: Record<string, RawEnvironmentConfig | false>;
387
412
  deleteOrphaned?: boolean;
388
413
  }
389
414
  export interface RawRepoSettings {
@@ -403,6 +428,9 @@ export interface RawRepoSettings {
403
428
  inherit?: boolean;
404
429
  };
405
430
  collaborators?: RawCollaboratorsConfig;
431
+ environments?: Record<string, RawEnvironmentConfig | false> & {
432
+ inherit?: boolean;
433
+ };
406
434
  deleteOrphaned?: boolean;
407
435
  }
408
436
  export interface RawRepoConfig {
@@ -1,6 +1,8 @@
1
1
  import { validateFileName } from "./validators/file-validator.js";
2
2
  import { isPlainObject } from "../shared/type-guards.js";
3
3
  import { ValidationError } from "../shared/errors.js";
4
+ import { isValidHostname } from "../shared/github-host-policy.js";
5
+ import { isCredentialEnvName } from "../shared/credential-env.js";
4
6
  import { validateBranchName } from "../shared/branch-validation.js";
5
7
  import { validateAiOption } from "./validators/ai-validator.js";
6
8
  import { validateFileConfigFields, validateSettings, } from "./validators/shared.js";
@@ -73,6 +75,10 @@ function validateRootSettings(config) {
73
75
  "inherit" in config.settings.collaborators) {
74
76
  throw new ValidationError("'inherit' is not allowed in root-level collaborators (nothing to inherit from)");
75
77
  }
78
+ if (config.settings.environments &&
79
+ "inherit" in config.settings.environments) {
80
+ throw new ValidationError("'inherit' is not allowed in root-level environments (nothing to inherit from)");
81
+ }
76
82
  }
77
83
  function validateGithubHosts(config) {
78
84
  if (config.githubHosts === undefined)
@@ -91,6 +97,9 @@ function validateGithubHosts(config) {
91
97
  if (host.includes("/")) {
92
98
  throw new ValidationError(`githubHosts entries must be hostnames only, not paths. Got: ${host}`);
93
99
  }
100
+ if (!isValidHostname(host)) {
101
+ throw new ValidationError(`githubHosts entries must be hostnames (no userinfo, port, whitespace or trailing dot). Got: ${host}`);
102
+ }
94
103
  }
95
104
  }
96
105
  function validatePrOptions(config) {
@@ -295,6 +304,11 @@ export function hasActionableSettings(settings) {
295
304
  settings.collaborators.deleteOrphaned === true)) {
296
305
  return true;
297
306
  }
307
+ // An environment holding only secrets still needs `xfg sync` to create it.
308
+ if (settings.environments &&
309
+ Object.entries(settings.environments).some(([name, env]) => name !== "inherit" && isPlainObject(env))) {
310
+ return true;
311
+ }
298
312
  // Secrets are deliberately absent: `xfg sync` must never process them.
299
313
  // A secrets-only config leaves `xfg sync` with nothing to do.
300
314
  return false;
@@ -320,6 +334,9 @@ function validateSecretEntry(name, config) {
320
334
  if (!config.env || typeof config.env !== "string") {
321
335
  throw new ValidationError(`Secret '${name}' requires an 'env' field (string) specifying the environment variable source.`);
322
336
  }
337
+ if (isCredentialEnvName(config.env)) {
338
+ throw new ValidationError(`Secret '${name}' cannot use '${config.env}' as its source: it is a credential xfg uses for authentication.`);
339
+ }
323
340
  }
324
341
  function validateSecretsLayer(secrets) {
325
342
  const { deleteOrphaned, inherit } = secrets;
@@ -350,8 +367,13 @@ function validateSecretsLayer(secrets) {
350
367
  }
351
368
  export function validateSecretsConfig(config) {
352
369
  for (const settings of collectAllSettings(config)) {
353
- if (!settings?.secrets)
354
- continue;
355
- validateSecretsLayer(settings.secrets);
370
+ if (settings?.secrets) {
371
+ validateSecretsLayer(settings.secrets);
372
+ }
373
+ for (const [name, env] of Object.entries(settings?.environments ?? {})) {
374
+ if (name === "inherit" || !isPlainObject(env) || !env.secrets)
375
+ continue;
376
+ validateSecretsLayer(env.secrets);
377
+ }
356
378
  }
357
379
  }
@@ -1,5 +1,6 @@
1
1
  import { isPlainObject } from "../../shared/type-guards.js";
2
2
  import { ValidationError } from "../../shared/errors.js";
3
+ import { assertAiKeyEnvAllowed } from "../../shared/credential-env.js";
3
4
  const VALID_PROVIDERS = ["anthropic", "openai"];
4
5
  const STRING_FIELDS = ["model", "baseUrl", "apiKeyEnv", "prompt"];
5
6
  const KNOWN_KEYS = new Set([
@@ -28,6 +29,7 @@ export function validateAiOption(ai) {
28
29
  throw new ValidationError(`prOptions.ai.${field} must be a non-empty string`);
29
30
  }
30
31
  }
32
+ assertAiKeyEnvAllowed(provider ?? "anthropic", ai.apiKeyEnv, ai.baseUrl);
31
33
  if (provider === "openai" && ai.model === undefined) {
32
34
  throw new ValidationError("prOptions.ai.model is required when provider is 'openai'");
33
35
  }