@aspruyt/xfg 8.4.0 → 8.5.1

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.
@@ -150,6 +150,7 @@ export class AiChangeDescriber {
150
150
  a.options.provider,
151
151
  a.options.model,
152
152
  a.options.baseUrl,
153
+ a.options.baseUrlEnv,
153
154
  a.system,
154
155
  a.user,
155
156
  ]
@@ -1,2 +1,2 @@
1
1
  import type { AiProviderOptions, FetchFn, IAiClient } from "./types.js";
2
- export declare function createAiClient(options: AiProviderOptions, env: Record<string, string | undefined>, fetch: FetchFn, path?: string): IAiClient;
2
+ export declare function createAiClient(configured: AiProviderOptions, env: Record<string, string | undefined>, fetch: FetchFn, path?: string): IAiClient;
@@ -1,5 +1,5 @@
1
1
  import { ValidationError } from "../shared/errors.js";
2
- import { assertAiHeadersEnvAllowed, assertAiKeyEnvAllowed, defaultAiKeyEnv, isDefaultAiBaseUrl, } from "../shared/credential-env.js";
2
+ import { assertAiBaseUrlEnvAllowed, assertAiHeadersEnvAllowed, assertAiKeyEnvAllowed, defaultAiKeyEnv, isDefaultAiBaseUrl, } from "../shared/credential-env.js";
3
3
  import { AnthropicClient, DEFAULT_ANTHROPIC_MODEL, } from "./anthropic-client.js";
4
4
  import { DEFAULT_OPENAI_BASE_URL, OpenAICompatibleClient, } from "./openai-compatible-client.js";
5
5
  /** The default key env only applies to the provider's own API. */
@@ -25,6 +25,59 @@ function readApiKey(env, keyEnv) {
25
25
  }
26
26
  return value;
27
27
  }
28
+ function resolveBaseUrl(options, env, path) {
29
+ assertAiBaseUrlEnvAllowed(options.baseUrlEnv, options.baseUrl, path);
30
+ if (options.baseUrlEnv === undefined)
31
+ return options.baseUrl;
32
+ const value = readEnv(env, options.baseUrlEnv);
33
+ if (!value) {
34
+ throw new ValidationError(`${options.baseUrlEnv} is not set (required for ${path}.baseUrlEnv)`);
35
+ }
36
+ if (!isHttpUrl(value)) {
37
+ throw new ValidationError(`${options.baseUrlEnv} does not hold an http(s) URL (used for ${path}.baseUrlEnv)`);
38
+ }
39
+ return value;
40
+ }
41
+ // Userinfo is refused because undici rejects it and echoes the whole URL in its error.
42
+ function isHttpUrl(value) {
43
+ try {
44
+ const { protocol, username, password } = new URL(value);
45
+ if (username || password)
46
+ return false;
47
+ return protocol === "https:" || protocol === "http:";
48
+ }
49
+ catch {
50
+ return false;
51
+ }
52
+ }
53
+ function escapeRegExp(value) {
54
+ return value.replace(/[.*+?^${}()|[\]\\]/g, String.raw `\$&`);
55
+ }
56
+ /** Replaces the resolved host in error text with the env var name that supplied it. */
57
+ class HostRedactingClient {
58
+ inner;
59
+ envName;
60
+ pattern;
61
+ constructor(inner, baseUrl, envName) {
62
+ this.inner = inner;
63
+ this.envName = envName;
64
+ const { host, hostname } = new URL(baseUrl);
65
+ const hosts = [...new Set([host, hostname])].sort((a, b) => b.length - a.length);
66
+ this.pattern = new RegExp(hosts.map(escapeRegExp).join("|"), "gi");
67
+ }
68
+ async complete(system, user, schema) {
69
+ try {
70
+ return await this.inner.complete(system, user, schema);
71
+ }
72
+ catch (error) {
73
+ if (!(error instanceof Error))
74
+ throw error;
75
+ const redacted = new Error(error.message.replace(this.pattern, () => this.envName));
76
+ // Keep fields such as retryAfter that withRetry reads.
77
+ throw Object.assign(redacted, { ...error });
78
+ }
79
+ }
80
+ }
28
81
  function resolveHeaders(options, env, path) {
29
82
  const headers = {};
30
83
  for (const [name, envName] of Object.entries(options.headersEnv ?? {})) {
@@ -39,7 +92,7 @@ function resolveHeaders(options, env, path) {
39
92
  }
40
93
  return headers;
41
94
  }
42
- export function createAiClient(options, env, fetch, path = "prOptions.ai") {
95
+ function buildClient(options, env, fetch, path) {
43
96
  assertAiKeyEnvAllowed(options.provider, options.apiKeyEnv, options.baseUrl, path);
44
97
  assertAiHeadersEnvAllowed(options.headersEnv, path);
45
98
  const keyEnv = keyEnvFor(options);
@@ -75,3 +128,14 @@ export function createAiClient(options, env, fetch, path = "prOptions.ai") {
75
128
  fetch,
76
129
  });
77
130
  }
131
+ export function createAiClient(configured, env, fetch, path = "prOptions.ai") {
132
+ const options = {
133
+ ...configured,
134
+ baseUrl: resolveBaseUrl(configured, env, path),
135
+ };
136
+ const client = buildClient(options, env, fetch, path);
137
+ if (options.baseUrlEnv === undefined || options.baseUrl === undefined) {
138
+ return client;
139
+ }
140
+ return new HostRedactingClient(client, options.baseUrl, options.baseUrlEnv);
141
+ }
@@ -6,6 +6,8 @@ export interface AiProviderConfig {
6
6
  provider?: AiProvider;
7
7
  model?: string;
8
8
  baseUrl?: string;
9
+ /** Name of the env var that holds the base URL; exclusive with `baseUrl` */
10
+ baseUrlEnv?: string;
9
11
  apiKeyEnv?: string;
10
12
  /** Extra request headers: header name to the env var that holds its value */
11
13
  headersEnv?: Record<string, string>;
@@ -1,12 +1,13 @@
1
1
  import { isPlainObject } from "../../shared/type-guards.js";
2
2
  import { ValidationError } from "../../shared/errors.js";
3
- import { assertAiHeadersEnvAllowed, assertAiKeyEnvAllowed, } from "../../shared/credential-env.js";
3
+ import { assertAiBaseUrlEnvAllowed, assertAiHeadersEnvAllowed, assertAiKeyEnvAllowed, } from "../../shared/credential-env.js";
4
4
  const VALID_PROVIDERS = ["anthropic", "openai"];
5
5
  const STRING_FIELDS = ["model", "baseUrl", "apiKeyEnv", "prompt"];
6
6
  const PROVIDER_KEYS = [
7
7
  "provider",
8
8
  "maxDiffChars",
9
9
  "headersEnv",
10
+ "baseUrlEnv",
10
11
  ...STRING_FIELDS,
11
12
  ];
12
13
  const PRIMARY_KEYS = new Set([...PROVIDER_KEYS, "fallback"]);
@@ -41,7 +42,10 @@ function validateProvider(ai, path, knownKeys) {
41
42
  throw new ValidationError(`${path}.${field} must be a non-empty string`);
42
43
  }
43
44
  }
44
- assertAiKeyEnvAllowed(provider ?? "anthropic", ai.apiKeyEnv, ai.baseUrl, path);
45
+ assertAiBaseUrlEnvAllowed(ai.baseUrlEnv, ai.baseUrl, path);
46
+ assertAiKeyEnvAllowed(provider ?? "anthropic", ai.apiKeyEnv, ai.baseUrl, path,
47
+ // A URL read from the env is unknown here, so it never counts as the provider's own API.
48
+ ai.baseUrlEnv !== undefined);
45
49
  assertAiHeadersEnvAllowed(ai.headersEnv, path);
46
50
  if (provider === "openai" && ai.model === undefined) {
47
51
  throw new ValidationError(`${path}.model is required when provider is 'openai'`);
@@ -23,12 +23,16 @@ export interface LabelChange {
23
23
  * An explicit empty string "" means "set to empty."
24
24
  * GitHub API returns null for labels without descriptions — treat null and
25
25
  * undefined as equivalent when comparing (neither triggers an update).
26
+ * A `new_name` entry whose source is missing is treated as an already-applied
27
+ * rename: the target is compared (or created) in its place and never deleted.
28
+ * A rename target that is itself a `new_name` entry (a chain) is rejected, as
29
+ * is a rename onto a label that already exists.
26
30
  *
27
31
  * @param current - Current labels from GitHub API
28
32
  * @param desired - Desired labels from config (name -> label)
29
33
  * @param deleteOrphaned - If true, delete current labels not in desired config
30
34
  * @param noDelete - If true, skip delete operations
31
35
  * @returns Array of changes to apply
32
- * @throws ValidationError if rename collisions are detected
36
+ * @throws ValidationError if rename collisions or chains are detected
33
37
  */
34
38
  export declare function diffLabels(current: GitHubLabel[], desired: Record<string, Label>, deleteOrphaned: boolean, noDelete: boolean): LabelChange[];
@@ -9,22 +9,24 @@ import { ValidationError } from "../../shared/errors.js";
9
9
  * An explicit empty string "" means "set to empty."
10
10
  * GitHub API returns null for labels without descriptions — treat null and
11
11
  * undefined as equivalent when comparing (neither triggers an update).
12
+ * A `new_name` entry whose source is missing is treated as an already-applied
13
+ * rename: the target is compared (or created) in its place and never deleted.
14
+ * A rename target that is itself a `new_name` entry (a chain) is rejected, as
15
+ * is a rename onto a label that already exists.
12
16
  *
13
17
  * @param current - Current labels from GitHub API
14
18
  * @param desired - Desired labels from config (name -> label)
15
19
  * @param deleteOrphaned - If true, delete current labels not in desired config
16
20
  * @param noDelete - If true, skip delete operations
17
21
  * @returns Array of changes to apply
18
- * @throws ValidationError if rename collisions are detected
22
+ * @throws ValidationError if rename collisions or chains are detected
19
23
  */
20
24
  export function diffLabels(current, desired, deleteOrphaned, noDelete) {
21
25
  const changes = [];
22
- // Build case-insensitive lookup of current labels
23
26
  const currentByName = new Map();
24
27
  for (const label of current) {
25
28
  currentByName.set(label.name.toLowerCase(), label);
26
29
  }
27
- // Collect rename targets for collision detection
28
30
  const renameTargets = new Map(); // lowercase target -> source name
29
31
  for (const [name, label] of Object.entries(desired)) {
30
32
  if (label.new_name) {
@@ -35,54 +37,66 @@ export function diffLabels(current, desired, deleteOrphaned, noDelete) {
35
37
  renameTargets.set(targetLower, name);
36
38
  }
37
39
  }
38
- // Determine which labels will be deleted (for collision checking)
39
- const desiredLower = new Set(Object.keys(desired).map((n) => n.toLowerCase()));
40
- const deletedNames = new Set();
41
- if (deleteOrphaned && !noDelete) {
42
- for (const nameLower of currentByName.keys()) {
43
- if (!desiredLower.has(nameLower)) {
44
- deletedNames.add(nameLower);
45
- }
40
+ for (const [name, label] of Object.entries(desired)) {
41
+ if (!label.new_name)
42
+ continue;
43
+ const targetLower = label.new_name.toLowerCase();
44
+ if (targetLower === name.toLowerCase())
45
+ continue;
46
+ const chained = Object.entries(desired).find(([n, l]) => n.toLowerCase() === targetLower && l.new_name);
47
+ if (chained) {
48
+ throw new ValidationError(`Rename chain: '${name}' renames to '${label.new_name}', which is itself renamed to '${chained[1].new_name}'. Chained renames are not supported; run them separately`);
46
49
  }
47
50
  }
48
- // Check rename targets for collisions with existing labels.
49
- // Note: Chain renames (A->B and B->C) are allowed when the target label is
50
- // itself being renamed away. This is safe because the apply ordering
51
- // (deletes -> updates -> creates) ensures both renames execute in the same batch.
52
- // This deviates from the original design plan which called for flagging chains
53
- // as errors, but the permissive behavior is correct and more user-friendly.
51
+ // A rename whose source is gone was already applied: its target is the managed label
52
+ const renamedTargets = new Set();
53
+ for (const [name, label] of Object.entries(desired)) {
54
+ if (label.new_name && !currentByName.has(name.toLowerCase())) {
55
+ renamedTargets.add(label.new_name.toLowerCase());
56
+ }
57
+ }
58
+ const desiredLower = new Set([
59
+ ...Object.keys(desired).map((n) => n.toLowerCase()),
60
+ ...renamedTargets,
61
+ ]);
54
62
  for (const [name, label] of Object.entries(desired)) {
55
63
  if (!label.new_name)
56
64
  continue;
57
65
  const targetLower = label.new_name.toLowerCase();
58
66
  const nameLower = name.toLowerCase();
59
- // Check if target collides with an existing label that is NOT:
60
- // 1. The source label itself
61
- // 2. Being deleted in this diff
62
- // 3. Being renamed away in this diff
63
- if (currentByName.has(targetLower) &&
64
- targetLower !== nameLower &&
65
- !deletedNames.has(targetLower)) {
66
- const collidingDesired = Object.entries(desired).find(([n]) => n.toLowerCase() === targetLower);
67
- if (!collidingDesired || !collidingDesired[1].new_name) {
68
- throw new ValidationError(`Rename collision: '${name}' would rename to '${label.new_name}', but that label already exists`);
69
- }
67
+ if (!currentByName.has(nameLower))
68
+ continue;
69
+ // Never resolve a collision by deleting the target: deleting a label strips it from every PR
70
+ if (currentByName.has(targetLower) && targetLower !== nameLower) {
71
+ throw new ValidationError(`Rename collision: '${name}' would rename to '${label.new_name}', but that label already exists`);
70
72
  }
71
73
  }
72
- // Check each desired label
73
74
  for (const [name, desiredLabel] of Object.entries(desired)) {
74
75
  const nameLower = name.toLowerCase();
75
- const currentLabel = currentByName.get(nameLower);
76
+ let currentLabel = currentByName.get(nameLower);
77
+ let labelName = name;
78
+ let labelConfig = desiredLabel;
79
+ if (!currentLabel && desiredLabel.new_name) {
80
+ const targetLower = desiredLabel.new_name.toLowerCase();
81
+ // The target's own entry, if any, already covers this label
82
+ if (Object.keys(desired).some((n) => n.toLowerCase() === targetLower)) {
83
+ continue;
84
+ }
85
+ const { new_name: targetName, ...config } = desiredLabel;
86
+ labelName = targetName;
87
+ labelConfig = config;
88
+ currentLabel = currentByName.get(targetLower);
89
+ }
76
90
  if (!currentLabel) {
77
91
  changes.push({
78
92
  action: "create",
79
- name,
80
- desired: desiredLabel,
93
+ name: labelName,
94
+ desired: labelConfig,
81
95
  });
82
96
  }
83
97
  else {
84
98
  const propChanges = [];
85
- const desiredColor = normalizeColor(desiredLabel.color);
99
+ const desiredColor = normalizeColor(labelConfig.color);
86
100
  const currentColor = currentLabel.color.toLowerCase();
87
101
  if (desiredColor !== currentColor) {
88
102
  propChanges.push({
@@ -91,46 +105,44 @@ export function diffLabels(current, desired, deleteOrphaned, noDelete) {
91
105
  newValue: desiredColor,
92
106
  });
93
107
  }
94
- // Description: undefined = don't compare, explicit value = compare
95
- if (desiredLabel.description !== undefined) {
108
+ if (labelConfig.description !== undefined) {
96
109
  const currentDesc = currentLabel.description ?? "";
97
- if (desiredLabel.description !== currentDesc) {
110
+ if (labelConfig.description !== currentDesc) {
98
111
  propChanges.push({
99
112
  property: "description",
100
113
  oldValue: currentLabel.description ?? undefined,
101
- newValue: desiredLabel.description,
114
+ newValue: labelConfig.description,
102
115
  });
103
116
  }
104
117
  }
105
- // new_name always triggers an update
106
- if (desiredLabel.new_name) {
118
+ if (labelConfig.new_name &&
119
+ labelConfig.new_name !== currentLabel.name) {
107
120
  propChanges.push({
108
121
  property: "new_name",
109
- oldValue: name,
110
- newValue: desiredLabel.new_name,
122
+ oldValue: currentLabel.name,
123
+ newValue: labelConfig.new_name,
111
124
  });
112
125
  }
113
126
  if (propChanges.length > 0) {
114
127
  changes.push({
115
128
  action: "update",
116
- name,
117
- newName: desiredLabel.new_name,
129
+ name: currentLabel.name,
130
+ newName: labelConfig.new_name,
118
131
  current: currentLabel,
119
- desired: desiredLabel,
132
+ desired: labelConfig,
120
133
  propertyChanges: propChanges,
121
134
  });
122
135
  }
123
136
  else {
124
137
  changes.push({
125
138
  action: "unchanged",
126
- name,
139
+ name: labelName,
127
140
  current: currentLabel,
128
- desired: desiredLabel,
141
+ desired: labelConfig,
129
142
  });
130
143
  }
131
144
  }
132
145
  }
133
- // Desired-state orphan detection: delete ALL current not in desired
134
146
  if (deleteOrphaned && !noDelete) {
135
147
  for (const [nameLower, currentLabel] of currentByName) {
136
148
  if (!desiredLower.has(nameLower)) {
@@ -142,7 +154,6 @@ export function diffLabels(current, desired, deleteOrphaned, noDelete) {
142
154
  }
143
155
  }
144
156
  }
145
- // Sort: delete first, then update, then create, then unchanged
146
157
  const actionOrder = {
147
158
  delete: 0,
148
159
  update: 1,
@@ -7,9 +7,15 @@ export declare function isDefaultAiBaseUrl(provider: string, baseUrl: string | u
7
7
  * A credential name may only feed `prOptions.ai` when it is the provider's
8
8
  * own key going to the provider's own API.
9
9
  */
10
- export declare function assertAiKeyEnvAllowed(provider: string, apiKeyEnv: string | undefined, baseUrl: string | undefined, path?: string): void;
10
+ export declare function assertAiKeyEnvAllowed(provider: string, apiKeyEnv: string | undefined, baseUrl: string | undefined, path?: string, baseUrlFromEnv?: boolean): void;
11
11
  /**
12
12
  * `headersEnv` maps header names to env var names. A value is never accepted
13
13
  * inline, and the env var may not be a credential xfg uses elsewhere.
14
14
  */
15
15
  export declare function assertAiHeadersEnvAllowed(headersEnv: unknown, path?: string): void;
16
+ /**
17
+ * `baseUrlEnv` names the env var that holds the base URL. A URL is never
18
+ * accepted inline, the two forms are exclusive, and the env var may not be a
19
+ * credential xfg uses elsewhere.
20
+ */
21
+ export declare function assertAiBaseUrlEnvAllowed(baseUrlEnv: unknown, baseUrl: unknown, path?: string): void;
@@ -40,11 +40,11 @@ export function isDefaultAiBaseUrl(provider, baseUrl) {
40
40
  * A credential name may only feed `prOptions.ai` when it is the provider's
41
41
  * own key going to the provider's own API.
42
42
  */
43
- export function assertAiKeyEnvAllowed(provider, apiKeyEnv, baseUrl, path = "prOptions.ai") {
43
+ export function assertAiKeyEnvAllowed(provider, apiKeyEnv, baseUrl, path = "prOptions.ai", baseUrlFromEnv = false) {
44
44
  if (apiKeyEnv === undefined || !isCredentialEnvName(apiKeyEnv))
45
45
  return;
46
46
  const ownKey = apiKeyEnv.toUpperCase() === defaultAiKeyEnv(provider);
47
- if (ownKey && isDefaultAiBaseUrl(provider, baseUrl))
47
+ if (ownKey && !baseUrlFromEnv && isDefaultAiBaseUrl(provider, baseUrl))
48
48
  return;
49
49
  throw new ValidationError(`${path}.apiKeyEnv '${apiKeyEnv}' is a credential xfg uses elsewhere; ` +
50
50
  `export the key under a dedicated name for this provider and baseUrl.`);
@@ -91,3 +91,22 @@ export function assertAiHeadersEnvAllowed(headersEnv, path = "prOptions.ai") {
91
91
  }
92
92
  }
93
93
  }
94
+ /**
95
+ * `baseUrlEnv` names the env var that holds the base URL. A URL is never
96
+ * accepted inline, the two forms are exclusive, and the env var may not be a
97
+ * credential xfg uses elsewhere.
98
+ */
99
+ export function assertAiBaseUrlEnvAllowed(baseUrlEnv, baseUrl, path = "prOptions.ai") {
100
+ if (baseUrlEnv === undefined)
101
+ return;
102
+ if (baseUrl !== undefined) {
103
+ throw new ValidationError(`${path}: baseUrl and baseUrlEnv are mutually exclusive`);
104
+ }
105
+ if (typeof baseUrlEnv !== "string" || !ENV_NAME.test(baseUrlEnv)) {
106
+ throw new ValidationError(`${path}.baseUrlEnv must be an env var name, not a value`);
107
+ }
108
+ if (isCredentialEnvName(baseUrlEnv)) {
109
+ throw new ValidationError(`${path}.baseUrlEnv '${baseUrlEnv}' is a credential xfg uses elsewhere; ` +
110
+ `export the URL under a dedicated name.`);
111
+ }
112
+ }
@@ -97,6 +97,15 @@ export class SyncWorkflow {
97
97
  };
98
98
  }
99
99
  if (isDirectMode) {
100
+ if (runCtx.dryRun) {
101
+ return {
102
+ success: true,
103
+ repoName,
104
+ message: `[DRY RUN] Would push directly to ${session.baseBranch}`,
105
+ diffStats: workResult.diffStats,
106
+ fileChanges: workResult.fileChangeDetails,
107
+ };
108
+ }
100
109
  this.log.info(`Changes pushed directly to ${session.baseBranch}`);
101
110
  return {
102
111
  success: true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aspruyt/xfg",
3
- "version": "8.4.0",
3
+ "version": "8.5.1",
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",