@aspruyt/xfg 8.1.0 → 8.1.2

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.
@@ -31,9 +31,9 @@ export declare function deepMerge(base: Record<string, unknown>, overlay: Record
31
31
  * Works recursively on nested objects and arrays.
32
32
  * Standard $-prefixed keys ($schema, $id, $ref, etc.) are preserved.
33
33
  *
34
- * When an unresolved directive object is found (only directive keys),
35
- * it is replaced with the $values array. This handles the case where a directive
36
- * had no base array to merge with.
34
+ * A valid directive-only object that is the value of a key had no base array
35
+ * to merge with, and is replaced with its $values array. A directive-only object
36
+ * that is invalid, an array item, or the root is a ValidationError.
37
37
  *
38
38
  * @param location - Prefixes errors, e.g. the file name being stripped
39
39
  */
@@ -36,7 +36,15 @@ function childPath(path, key) {
36
36
  }
37
37
  function mergeError(ctx, path, message) {
38
38
  const prefix = ctx.location ? `${ctx.location}: ` : "";
39
- return new ValidationError(`${prefix}${path}: ${message}`);
39
+ const pathPrefix = path ? `${path}: ` : "";
40
+ return new ValidationError(`${prefix}${pathPrefix}${message}`);
41
+ }
42
+ function describeValue(value) {
43
+ if (value === undefined)
44
+ return "none";
45
+ if (typeof value === "string")
46
+ return `'${value}'`;
47
+ return JSON.stringify(value);
40
48
  }
41
49
  /**
42
50
  * Returns the directive's $matchBy key, or undefined when it has none.
@@ -51,15 +59,39 @@ function readMatchBy(directive, ctx, path) {
51
59
  }
52
60
  const strategy = directive.$arrayMerge;
53
61
  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}`);
62
+ throw mergeError(ctx, path, `$matchBy requires $arrayMerge: merge, got ${describeValue(strategy)}`);
63
+ }
64
+ return matchBy;
65
+ }
66
+ function isDirectiveOnly(value) {
67
+ const keys = Object.keys(value);
68
+ return keys.length > 0 && keys.every((k) => XFG_DIRECTIVES.has(k));
69
+ }
70
+ /**
71
+ * Validates a value's directive keys and returns its $matchBy.
72
+ * An object of only directive keys must be a complete directive, or it would resolve to nothing.
73
+ */
74
+ function readDirective(value, ctx, path) {
75
+ if (!isPlainObject(value))
76
+ return undefined;
77
+ const matchBy = readMatchBy(value, ctx, path);
78
+ if (!isDirectiveOnly(value))
79
+ return matchBy;
80
+ if (!isArrayMergeStrategy(value.$arrayMerge)) {
81
+ const strategies = [...arrayMergeStrategies.keys()].join(", ");
82
+ throw mergeError(ctx, path, `$arrayMerge must be one of ${strategies}, got ${describeValue(value.$arrayMerge)}`);
83
+ }
84
+ if (!Array.isArray(value.$values)) {
85
+ throw mergeError(ctx, path, `$values must be an array, got ${describeValue(value.$values)}`);
60
86
  }
61
87
  return matchBy;
62
88
  }
89
+ /** Rejects directive-only objects; mixed-key objects keep their directive keys stripped silently. */
90
+ function assertNotDirective(value, ctx, path, position) {
91
+ if (isPlainObject(value) && isDirectiveOnly(value)) {
92
+ throw mergeError(ctx, path, `a directive must be the value of a key whose base is an array, not ${position}`);
93
+ }
94
+ }
63
95
  function assertKeyedItems(items, matchBy, label, ctx, path) {
64
96
  const firstIndexByValue = new Map();
65
97
  for (let i = 0; i < items.length; i++) {
@@ -142,7 +174,7 @@ const arrayMergeStrategies = new Map([
142
174
  function isUnresolvedDirective(value) {
143
175
  if (!isPlainObject(value))
144
176
  return false;
145
- return (Object.keys(value).every((k) => XFG_DIRECTIVES.has(k)) &&
177
+ return (isDirectiveOnly(value) &&
146
178
  isArrayMergeStrategy(value.$arrayMerge) &&
147
179
  Array.isArray(value.$values));
148
180
  }
@@ -161,6 +193,8 @@ function mergeArrays(base, overlay, strategy, ctx, path) {
161
193
  * @param ctx - Merge context with array strategies
162
194
  */
163
195
  export function deepMerge(base, overlay, ctx) {
196
+ assertNotDirective(base, ctx, "", "the content root");
197
+ assertNotDirective(overlay, ctx, "", "the content root");
164
198
  return mergeObjects(base, overlay, ctx, "");
165
199
  }
166
200
  function mergeObjects(base, overlay, ctx, path) {
@@ -173,12 +207,10 @@ function mergeObjects(base, overlay, ctx, path) {
173
207
  return result;
174
208
  }
175
209
  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;
210
+ const resolvedBase = resolveBase(baseValue, ctx, path);
211
+ const overlayMatchBy = readDirective(overlayValue, ctx, path);
180
212
  if (isArrayDirective(overlayValue)) {
181
- const merged = applyArrayDirective(resolvedBase, overlayValue, ctx, path);
213
+ const merged = applyArrayDirective(resolvedBase, overlayValue, overlayMatchBy, ctx, path);
182
214
  if (merged !== undefined)
183
215
  return merged;
184
216
  }
@@ -190,12 +222,18 @@ function mergeValue(baseValue, overlayValue, ctx, path) {
190
222
  }
191
223
  return overlayValue;
192
224
  }
193
- function resolveBaseDirective(directive, ctx, path) {
194
- const matchBy = readMatchBy(directive, ctx, path);
225
+ /**
226
+ * A directive left unresolved by an earlier layer with no base array acts as its $values.
227
+ * Any other base is returned as-is once its directive keys are valid.
228
+ */
229
+ function resolveBase(base, ctx, path) {
230
+ const matchBy = readDirective(base, ctx, path);
231
+ if (!isUnresolvedDirective(base))
232
+ return base;
195
233
  if (matchBy !== undefined) {
196
- assertKeyedItems(directive.$values, matchBy, "base", ctx, path);
234
+ assertKeyedItems(base.$values, matchBy, "base", ctx, path);
197
235
  }
198
- return directive.$values;
236
+ return base.$values;
199
237
  }
200
238
  function isArrayDirective(value) {
201
239
  return (isPlainObject(value) && ("$arrayMerge" in value || "$matchBy" in value));
@@ -208,10 +246,9 @@ function isArrayMergeStrategy(value) {
208
246
  * Applies an overlay directive to the base array.
209
247
  * Returns undefined when it doesn't apply, so the caller falls back to a plain merge.
210
248
  */
211
- function applyArrayDirective(base, directive, ctx, path) {
249
+ function applyArrayDirective(base, directive, matchBy, ctx, path) {
212
250
  const strategy = directive.$arrayMerge;
213
251
  const values = directive.$values;
214
- const matchBy = readMatchBy(directive, ctx, path);
215
252
  if (matchBy !== undefined && Array.isArray(values)) {
216
253
  assertKeyedItems(values, matchBy, "overlay", ctx, path);
217
254
  }
@@ -231,17 +268,25 @@ function applyArrayDirective(base, directive, ctx, path) {
231
268
  * Works recursively on nested objects and arrays.
232
269
  * Standard $-prefixed keys ($schema, $id, $ref, etc.) are preserved.
233
270
  *
234
- * When an unresolved directive object is found (only directive keys),
235
- * it is replaced with the $values array. This handles the case where a directive
236
- * had no base array to merge with.
271
+ * A valid directive-only object that is the value of a key had no base array
272
+ * to merge with, and is replaced with its $values array. A directive-only object
273
+ * that is invalid, an array item, or the root is a ValidationError.
237
274
  *
238
275
  * @param location - Prefixes errors, e.g. the file name being stripped
239
276
  */
240
277
  export function stripMergeDirectives(obj, location) {
241
- return stripObject(obj, { location }, "");
278
+ const errCtx = { location };
279
+ assertNotDirective(obj, errCtx, "", "the content root");
280
+ return stripObject(obj, errCtx, "");
242
281
  }
243
282
  function stripItems(items, errCtx, path) {
244
- return items.map((item, i) => isPlainObject(item) ? stripObject(item, errCtx, `${path}[${i}]`) : item);
283
+ return items.map((item, i) => {
284
+ if (!isPlainObject(item))
285
+ return item;
286
+ const itemPath = `${path}[${i}]`;
287
+ assertNotDirective(item, errCtx, itemPath, "an array item");
288
+ return stripObject(item, errCtx, itemPath);
289
+ });
245
290
  }
246
291
  function stripObject(obj, errCtx, path) {
247
292
  const result = {};
@@ -249,13 +294,11 @@ function stripObject(obj, errCtx, path) {
249
294
  if (XFG_DIRECTIVES.has(key))
250
295
  continue;
251
296
  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;
297
+ // Validate before branching: an invalid directive is not resolved and would be stripped silently
298
+ const matchBy = readDirective(value, errCtx, keyPath);
256
299
  if (isUnresolvedDirective(value)) {
257
300
  if (matchBy !== undefined) {
258
- assertKeyedItems(value.$values, matchBy, "overlay", errCtx, keyPath);
301
+ assertKeyedItems(value.$values, matchBy, "$values", errCtx, keyPath);
259
302
  }
260
303
  result[key] = stripItems(value.$values, errCtx, keyPath);
261
304
  }
@@ -29,7 +29,7 @@ function resolveFileContent(fileName, rootContent, repoOverride, mergeStrategy)
29
29
  : null;
30
30
  }
31
31
  if (!repoOverride?.content) {
32
- return structuredClone(rootContent);
32
+ return cloneContent(rootContent, fileName);
33
33
  }
34
34
  return mergeContentPair(fileName, rootContent, repoOverride.content, mergeStrategy);
35
35
  }
@@ -46,7 +46,7 @@ function mergeContentPair(fileName, base, overlay, strategy) {
46
46
  const merged = deepMerge(structuredClone(base), overlay, ctx);
47
47
  return stripMergeDirectives(merged, fileName);
48
48
  }
49
- return overlay;
49
+ return cloneContent(overlay, fileName);
50
50
  }
51
51
  /**
52
52
  * Checks whether an object's `inherit` property is not explicitly set to false.
@@ -30,7 +30,7 @@ export declare class GitHubLifecycleProvider implements IRepoLifecycleProvider {
30
30
  */
31
31
  private isOrganization;
32
32
  private assertGitHub;
33
- private assertTokenCanCreateRepo;
33
+ private execRepoCreatingCommand;
34
34
  private buildGhApiPrefix;
35
35
  exists(params: LifecycleExistsParams): Promise<boolean>;
36
36
  create(params: LifecycleCreateParams): Promise<void>;
@@ -11,14 +11,17 @@ const REPO_NOT_FOUND_PATTERNS = [
11
11
  "Not Found",
12
12
  "404",
13
13
  ];
14
+ function errorText(error) {
15
+ return (toErrorMessage(error) +
16
+ ((error instanceof Error
17
+ ? error.stderr
18
+ : undefined) ?? ""));
19
+ }
14
20
  /**
15
21
  * Check if an error indicates repo not found (vs network/auth error).
16
22
  */
17
23
  function isRepoNotFoundError(error) {
18
- const message = toErrorMessage(error) +
19
- ((error instanceof Error
20
- ? error.stderr
21
- : undefined) ?? "");
24
+ const message = errorText(error);
22
25
  return REPO_NOT_FOUND_PATTERNS.some((pattern) => message.includes(pattern));
23
26
  }
24
27
  /**
@@ -41,13 +44,32 @@ const POST_CREATE_PERMANENT_PATTERNS = [
41
44
  * Interval between fork readiness checks (2 seconds).
42
45
  */
43
46
  const FORK_POLL_INTERVAL_MS = 2_000;
47
+ const CREATE_REPO_APP_PERMISSIONS = "Repository creation: Read and write";
48
+ const FORK_REPO_APP_PERMISSIONS = "Repository creation: Read and write, Administration: Read and write and Contents: Read, and be installed on the target account with access to all repositories and on the upstream account with access to the upstream repository";
49
+ const APP_PERMISSION_DENIED_PATTERNS = [
50
+ /\bHTTP\s*403\b/,
51
+ /not\s*accessible\s*by\s*integration/i,
52
+ ];
53
+ const GITHUB_RATE_LIMIT_PATTERNS = [
54
+ /API rate limit/i,
55
+ /secondary rate limit/i,
56
+ /abuse detection/i,
57
+ /too many requests/i,
58
+ /\b429\b/,
59
+ ];
44
60
  function isInstallationToken(token) {
45
61
  return token?.startsWith("ghs_") ?? false;
46
62
  }
47
- function personalAccountInstallationTokenError(repoInfo) {
48
- return new LifecycleError(`An installation token (GitHub App or Actions GITHUB_TOKEN) cannot create repositories for personal account '${repoInfo.owner}'. ` +
49
- `Create ${repoInfo.owner}/${repoInfo.repo} first, or run lifecycle with a personal access token. ` +
50
- `Installation tokens can only create repositories in organizations.`);
63
+ // GitHub reports a missing App permission on POST /user/repos as "403 Rate Limit Exceeded".
64
+ function isAppPermissionDenied(error) {
65
+ const text = errorText(error);
66
+ return (APP_PERMISSION_DENIED_PATTERNS.some((p) => p.test(text)) &&
67
+ !GITHUB_RATE_LIMIT_PATTERNS.some((p) => p.test(text)));
68
+ }
69
+ function appPermissionDeniedError(action, requiredPermissions, error) {
70
+ return new LifecycleError(`GitHub refused the App installation token while ${action}: ${toErrorMessage(error)}. ` +
71
+ `The GitHub App needs ${requiredPermissions}. ` +
72
+ `After changing App permissions, approve them on the installation.`, { cause: error });
51
73
  }
52
74
  function buildRepoCreateArgs(args, settings) {
53
75
  if (settings?.visibility === "public") {
@@ -121,21 +143,22 @@ export class GitHubLifecycleProvider {
121
143
  assertGitHub(repoInfo) {
122
144
  assertGitHubRepo(repoInfo, "GitHubLifecycleProvider");
123
145
  }
124
- // GitHub refuses installation tokens on POST /user/repos with a misleading
125
- // "403 Rate Limit Exceeded", which withRetry treats as transient.
126
- async assertTokenCanCreateRepo(repoInfo, token) {
127
- if (!isInstallationToken(token))
128
- return;
129
- let isOrg;
146
+ async execRepoCreatingCommand(args, token, permission, retryOptions = {}) {
147
+ const appPermissionDenied = (error) => isInstallationToken(token) && isAppPermissionDenied(error);
148
+ const tokenEnv = buildTokenEnv(token);
130
149
  try {
131
- isOrg = await this.isOrganization(repoInfo.owner, repoInfo, token);
150
+ return await withRetry(() => this.executor.exec("gh", args, this.cwd, { env: tokenEnv }), {
151
+ retries: this.retries,
152
+ ...retryOptions,
153
+ abortOn: appPermissionDenied,
154
+ });
132
155
  }
133
156
  catch (error) {
134
- this.log?.debug(`Skipping installation token owner check for '${repoInfo.owner}': ${toErrorMessage(error)}`);
135
- return;
157
+ if (appPermissionDenied(error)) {
158
+ throw appPermissionDeniedError(permission.action, permission.required, error);
159
+ }
160
+ throw error;
136
161
  }
137
- if (!isOrg)
138
- throw personalAccountInstallationTokenError(repoInfo);
139
162
  }
140
163
  buildGhApiPrefix(repoInfo, token) {
141
164
  const tokenEnv = buildTokenEnv(token);
@@ -167,19 +190,15 @@ export class GitHubLifecycleProvider {
167
190
  async create(params) {
168
191
  const { repo: repoInfo, settings, token } = params;
169
192
  this.assertGitHub(repoInfo);
170
- await this.assertTokenCanCreateRepo(repoInfo, token);
171
- const tokenEnv = buildTokenEnv(token);
172
- const args = [
173
- "repo",
174
- "create",
175
- `${repoInfo.owner}/${repoInfo.repo}`,
176
- ];
193
+ const repoSlug = `${repoInfo.owner}/${repoInfo.repo}`;
194
+ const args = ["repo", "create", repoSlug];
177
195
  buildRepoCreateArgs(args, settings);
178
196
  // Add --add-readme to establish the default branch via an initial commit.
179
197
  // This avoids empty repos where HEAD doesn't resolve.
180
198
  args.push("--add-readme");
181
- await withRetry(() => this.executor.exec("gh", args, this.cwd, { env: tokenEnv }), {
182
- retries: this.retries,
199
+ await this.execRepoCreatingCommand(args, token, {
200
+ action: `creating ${repoSlug}`,
201
+ required: CREATE_REPO_APP_PERMISSIONS,
183
202
  });
184
203
  if (settings?.defaultBranch) {
185
204
  const { tokenEnv: branchTokenEnv, baseArgs, apiPath, } = this.buildGhApiPrefix(repoInfo, token);
@@ -208,17 +227,14 @@ export class GitHubLifecycleProvider {
208
227
  `The upstream and target owners must be different.`);
209
228
  }
210
229
  const isOrg = await this.isOrganization(target.owner, target, token);
211
- if (!isOrg && isInstallationToken(token)) {
212
- throw personalAccountInstallationTokenError(target);
213
- }
214
- const tokenEnv = buildTokenEnv(token);
215
230
  const forkArgs = ["repo", "fork", `${upstream.owner}/${upstream.repo}`];
216
231
  if (isOrg) {
217
232
  forkArgs.push("--org", target.owner);
218
233
  }
219
234
  forkArgs.push("--fork-name", target.repo, "--clone=false");
220
- await withRetry(() => this.executor.exec("gh", forkArgs, this.cwd, { env: tokenEnv }), {
221
- retries: this.retries,
235
+ await this.execRepoCreatingCommand(forkArgs, token, {
236
+ action: `forking ${upstream.owner}/${upstream.repo} to ${target.owner}/${target.repo}`,
237
+ required: FORK_REPO_APP_PERMISSIONS,
222
238
  });
223
239
  // GitHub forks are async - wait for the fork to be ready for git operations
224
240
  await this.waitForForkReady(target, {
@@ -280,7 +296,6 @@ export class GitHubLifecycleProvider {
280
296
  async receiveMigration(params) {
281
297
  const { repo: repoInfo, sourceDir, settings, token } = params;
282
298
  this.assertGitHub(repoInfo);
283
- await this.assertTokenCanCreateRepo(repoInfo, token);
284
299
  await this.removeOriginRemote(sourceDir);
285
300
  await this.cleanNonStandardRefs(sourceDir);
286
301
  await this.renameMirrorDefaultBranch(sourceDir, settings?.defaultBranch);
@@ -335,8 +350,10 @@ export class GitHubLifecycleProvider {
335
350
  const createArgs = ["repo", "create", repoSlug];
336
351
  buildRepoCreateArgs(createArgs, settings);
337
352
  try {
338
- await withRetry(() => this.executor.exec("gh", createArgs, this.cwd, { env: tokenEnv }), {
339
- retries: this.retries,
353
+ await this.execRepoCreatingCommand(createArgs, token, {
354
+ action: `creating ${repoSlug}`,
355
+ required: CREATE_REPO_APP_PERMISSIONS,
356
+ }, {
340
357
  permanentErrorPatterns: POST_CREATE_PERMANENT_PATTERNS,
341
358
  log: this.log
342
359
  ? { info: (m) => this.log.info(m) }
@@ -14,7 +14,7 @@ export declare const DEFAULT_PERMANENT_ERROR_PATTERNS: RegExp[];
14
14
  * Rate limit errors need longer backoff (60s+) compared to network errors (1-4s).
15
15
  */
16
16
  export declare function isRateLimitError(error: unknown): boolean;
17
- interface RetryOptions {
17
+ export interface RetryOptions {
18
18
  /** Maximum number of retries (default: 3) */
19
19
  retries?: number;
20
20
  /** Callback when a retry attempt fails */
@@ -23,6 +23,8 @@ interface RetryOptions {
23
23
  permanentErrorPatterns?: RegExp[];
24
24
  /** Custom transient error patterns (defaults to DEFAULT_TRANSIENT_ERROR_PATTERNS) */
25
25
  transientErrorPatterns?: RegExp[];
26
+ /** Errors this returns true for fail at once, even if they match a transient pattern */
27
+ abortOn?: (error: Error) => boolean;
26
28
  /** Logger for retry messages (defaults to no logging) */
27
29
  log?: {
28
30
  info(msg: string): void;
@@ -48,4 +50,3 @@ export declare function isTransientError(error: unknown, patterns?: RegExp[]): b
48
50
  * @throws The original error for permanent failures (pRetry unwraps AbortError before propagating), or the last transient error after all retries exhausted
49
51
  */
50
52
  export declare function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
51
- export {};
@@ -152,8 +152,9 @@ export async function withRetry(fn, options) {
152
152
  }
153
153
  catch (error) {
154
154
  if (error instanceof Error &&
155
- !isTransientError(error, options?.transientErrorPatterns) &&
156
- isPermanentError(error, permanentPatterns)) {
155
+ (options?.abortOn?.(error) ||
156
+ (!isTransientError(error, options?.transientErrorPatterns) &&
157
+ isPermanentError(error, permanentPatterns)))) {
157
158
  throw new AbortError(error);
158
159
  }
159
160
  throw error;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aspruyt/xfg",
3
- "version": "8.1.0",
3
+ "version": "8.1.2",
4
4
  "description": "Manage files, settings, and repositories across GitHub, Azure DevOps, and GitLab — declaratively, from a single YAML config",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",