@aspruyt/xfg 8.0.0 → 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 (41) hide show
  1. package/dist/cli/secrets-command.js +12 -2
  2. package/dist/cli/settings-factories.d.ts +2 -1
  3. package/dist/cli/settings-factories.js +7 -1
  4. package/dist/cli/settings-report-builder.d.ts +6 -1
  5. package/dist/cli/settings-report-builder.js +7 -1
  6. package/dist/cli/settings-runner.js +24 -15
  7. package/dist/cli/types.d.ts +4 -2
  8. package/dist/config/index.d.ts +1 -1
  9. package/dist/config/merge.d.ts +9 -5
  10. package/dist/config/merge.js +148 -67
  11. package/dist/config/normalizer.js +87 -18
  12. package/dist/config/types.d.ts +28 -0
  13. package/dist/config/validator.js +17 -3
  14. package/dist/config/validators/ruleset-validator.js +6 -5
  15. package/dist/config/validators/shared.js +123 -0
  16. package/dist/output/settings-report.d.ts +6 -1
  17. package/dist/output/settings-report.js +31 -9
  18. package/dist/settings/environments/diff.d.ts +22 -0
  19. package/dist/settings/environments/diff.js +78 -0
  20. package/dist/settings/environments/formatter.d.ts +17 -0
  21. package/dist/settings/environments/formatter.js +62 -0
  22. package/dist/settings/environments/github-environments-strategy.d.ts +23 -0
  23. package/dist/settings/environments/github-environments-strategy.js +54 -0
  24. package/dist/settings/environments/index.d.ts +5 -0
  25. package/dist/settings/environments/index.js +3 -0
  26. package/dist/settings/environments/processor.d.ts +21 -0
  27. package/dist/settings/environments/processor.js +100 -0
  28. package/dist/settings/environments/types.d.ts +38 -0
  29. package/dist/settings/environments/types.js +1 -0
  30. package/dist/settings/index.d.ts +1 -0
  31. package/dist/settings/index.js +1 -0
  32. package/dist/settings/secrets/diff.d.ts +2 -0
  33. package/dist/settings/secrets/formatter.d.ts +4 -0
  34. package/dist/settings/secrets/formatter.js +17 -4
  35. package/dist/settings/secrets/index.d.ts +2 -2
  36. package/dist/settings/secrets/index.js +1 -1
  37. package/dist/settings/secrets/processor.d.ts +16 -2
  38. package/dist/settings/secrets/processor.js +132 -28
  39. package/dist/shared/sequential.d.ts +2 -0
  40. package/dist/shared/sequential.js +4 -0
  41. package/package.json +2 -2
@@ -1,12 +1,13 @@
1
1
  import { mkdirSync } from "node:fs";
2
2
  import { loadRawConfig, normalizeConfig, validateSecretsConfig, validateNormalizedConfig, } from "../config/index.js";
3
3
  import { SecretsProcessor, GitHubSecretsStrategy, SodiumEncryptor, } from "../settings/secrets/index.js";
4
+ import { GitHubEnvironmentsStrategy } from "../settings/environments/index.js";
5
+ import { GitHubRepoMetadataProvider, parseGitUrl, getRepoDisplayName, } from "../repo/index.js";
4
6
  import { EnvResolver } from "../shared/env-resolver.js";
5
7
  import { ProcessExecutor } from "../shared/command-executor.js";
6
8
  import { createTokenManagerFromEnv } from "../vcs/index.js";
7
9
  import { createGitHubHostPolicyFromEnv } from "../shared/github-host-policy.js";
8
10
  import { GitHubTokenProvider, } from "../shared/gh-token-utils.js";
9
- import { parseGitUrl, getRepoDisplayName } from "../repo/index.js";
10
11
  import { Logger } from "../shared/logger.js";
11
12
  import { toErrorMessage } from "../shared/type-guards.js";
12
13
  import { buildSettingsReport, } from "./settings-report-builder.js";
@@ -19,7 +20,13 @@ function createDefaultProcessor(cwd, retries, tokenProvider) {
19
20
  cwd,
20
21
  retries,
21
22
  });
22
- return new SecretsProcessor(strategy, encryptor, envResolver, tokenProvider);
23
+ return new SecretsProcessor(strategy, encryptor, envResolver, tokenProvider, {
24
+ strategy: new GitHubEnvironmentsStrategy(executor, { cwd, retries }),
25
+ metadataProvider: new GitHubRepoMetadataProvider(executor, {
26
+ cwd,
27
+ retries,
28
+ }),
29
+ });
23
30
  }
24
31
  function hostQualifiedName(repoInfo) {
25
32
  const name = getRepoDisplayName(repoInfo);
@@ -87,6 +94,9 @@ export async function runSecretsSync(options, deps = {}) {
87
94
  continue;
88
95
  }
89
96
  anySecretsConfigured = true;
97
+ for (const warning of result.warnings ?? []) {
98
+ logger.warn(warning);
99
+ }
90
100
  if (result.skipped) {
91
101
  logger.skip(i + 1, displayName, result.message);
92
102
  continue;
@@ -1,9 +1,10 @@
1
1
  import type { ProcessExecutor } from "../shared/command-executor.js";
2
- import type { RulesetProcessorFactory, RepoSettingsProcessorFactory, LabelsProcessorFactory, CodeScanningProcessorFactory, VariablesProcessorFactory, CollaboratorsProcessorFactory, SettingsProcessorFactories } from "./types.js";
2
+ import type { RulesetProcessorFactory, RepoSettingsProcessorFactory, LabelsProcessorFactory, CodeScanningProcessorFactory, VariablesProcessorFactory, CollaboratorsProcessorFactory, EnvironmentsProcessorFactory, SettingsProcessorFactories } from "./types.js";
3
3
  export declare function createDefaultRulesetProcessorFactory(executor: ProcessExecutor): RulesetProcessorFactory;
4
4
  export declare function createDefaultRepoSettingsProcessorFactory(executor: ProcessExecutor): RepoSettingsProcessorFactory;
5
5
  export declare function createDefaultLabelsProcessorFactory(executor: ProcessExecutor): LabelsProcessorFactory;
6
6
  export declare function createDefaultCodeScanningProcessorFactory(executor: ProcessExecutor): CodeScanningProcessorFactory;
7
7
  export declare function createDefaultVariablesProcessorFactory(executor: ProcessExecutor): VariablesProcessorFactory;
8
8
  export declare function createDefaultCollaboratorsProcessorFactory(executor: ProcessExecutor): CollaboratorsProcessorFactory;
9
+ export declare function createDefaultEnvironmentsProcessorFactory(executor: ProcessExecutor): EnvironmentsProcessorFactory;
9
10
  export declare function createDefaultFactories(executor: ProcessExecutor, overrides?: Partial<SettingsProcessorFactories>): SettingsProcessorFactories;
@@ -1,4 +1,4 @@
1
- import { RulesetProcessor, RepoSettingsProcessor, LabelsProcessor, CodeScanningProcessor, VariablesProcessor, CollaboratorsProcessor, GitHubRulesetStrategy, GitHubRepoSettingsStrategy, GitHubLabelsStrategy, GitHubCodeScanningStrategy, GitHubVariablesStrategy, GitHubCollaboratorsStrategy, } from "../settings/index.js";
1
+ import { RulesetProcessor, RepoSettingsProcessor, LabelsProcessor, CodeScanningProcessor, VariablesProcessor, CollaboratorsProcessor, EnvironmentsProcessor, GitHubRulesetStrategy, GitHubRepoSettingsStrategy, GitHubLabelsStrategy, GitHubCodeScanningStrategy, GitHubVariablesStrategy, GitHubCollaboratorsStrategy, GitHubEnvironmentsStrategy, } from "../settings/index.js";
2
2
  import { GitHubRepoMetadataProvider } from "../repo/index.js";
3
3
  export function createDefaultRulesetProcessorFactory(executor) {
4
4
  const cwd = process.cwd();
@@ -24,6 +24,10 @@ export function createDefaultCollaboratorsProcessorFactory(executor) {
24
24
  const cwd = process.cwd();
25
25
  return () => new CollaboratorsProcessor(new GitHubCollaboratorsStrategy(executor, { cwd }), new GitHubRepoMetadataProvider(executor, { cwd }));
26
26
  }
27
+ export function createDefaultEnvironmentsProcessorFactory(executor) {
28
+ const cwd = process.cwd();
29
+ return () => new EnvironmentsProcessor(new GitHubEnvironmentsStrategy(executor, { cwd }), new GitHubRepoMetadataProvider(executor, { cwd }));
30
+ }
27
31
  export function createDefaultFactories(executor, overrides) {
28
32
  return {
29
33
  rulesets: overrides?.rulesets ?? createDefaultRulesetProcessorFactory(executor),
@@ -34,5 +38,7 @@ export function createDefaultFactories(executor, overrides) {
34
38
  variables: overrides?.variables ?? createDefaultVariablesProcessorFactory(executor),
35
39
  collaborators: overrides?.collaborators ??
36
40
  createDefaultCollaboratorsProcessorFactory(executor),
41
+ environments: overrides?.environments ??
42
+ createDefaultEnvironmentsProcessorFactory(executor),
37
43
  };
38
44
  }
@@ -1,5 +1,5 @@
1
1
  import type { SettingsReport } from "../output/index.js";
2
- import { type RepoSettingsPlanEntry, type RulesetPlanEntry, type LabelsPlanEntry, type CodeScanningPlanEntry, type VariablesPlanEntry, type CollaboratorsPlanEntry, type SecretsPlanEntry } from "../settings/index.js";
2
+ import { type RepoSettingsPlanEntry, type RulesetPlanEntry, type LabelsPlanEntry, type CodeScanningPlanEntry, type VariablesPlanEntry, type CollaboratorsPlanEntry, type SecretsPlanEntry, type EnvironmentsPlanEntry } from "../settings/index.js";
3
3
  export interface ProcessorResults {
4
4
  repoName: string;
5
5
  settingsResult?: {
@@ -37,6 +37,11 @@ export interface ProcessorResults {
37
37
  entries?: SecretsPlanEntry[];
38
38
  };
39
39
  };
40
+ environmentsResult?: {
41
+ planOutput?: {
42
+ entries?: EnvironmentsPlanEntry[];
43
+ };
44
+ };
40
45
  error?: string;
41
46
  }
42
47
  export declare function buildSettingsReport(results: ProcessorResults[]): SettingsReport;
@@ -8,6 +8,7 @@ export function buildSettingsReport(results) {
8
8
  variables: { create: 0, update: 0, delete: 0 },
9
9
  secrets: { create: 0, update: 0, delete: 0 },
10
10
  collaborators: { create: 0, update: 0, delete: 0 },
11
+ environments: { create: 0, update: 0 },
11
12
  };
12
13
  for (const result of results) {
13
14
  const repoChanges = {
@@ -18,6 +19,7 @@ export function buildSettingsReport(results) {
18
19
  variables: [],
19
20
  secrets: [],
20
21
  collaborators: [],
22
+ environments: [],
21
23
  };
22
24
  if (result.settingsResult?.planOutput?.entries) {
23
25
  for (const entry of result.settingsResult.planOutput.entries) {
@@ -99,7 +101,7 @@ export function buildSettingsReport(results) {
99
101
  }
100
102
  if (result.secretsResult?.planOutput?.entries) {
101
103
  for (const entry of result.secretsResult.planOutput.entries) {
102
- repoChanges.secrets.push({ name: entry.name, action: entry.action });
104
+ repoChanges.secrets.push({ ...entry });
103
105
  }
104
106
  const counts = countActions(repoChanges.secrets);
105
107
  totals.secrets.create += counts.create;
@@ -119,6 +121,10 @@ export function buildSettingsReport(results) {
119
121
  totals.collaborators.create += counts.create;
120
122
  totals.collaborators.delete += counts.delete;
121
123
  }
124
+ for (const entry of result.environmentsResult?.planOutput?.entries ?? []) {
125
+ repoChanges.environments.push(entry);
126
+ totals.environments[entry.action]++;
127
+ }
122
128
  if (result.error) {
123
129
  repoChanges.error = result.error;
124
130
  }
@@ -1,25 +1,27 @@
1
1
  import { isGitHubRepo } from "../repo/index.js";
2
2
  import { toErrorMessage } from "../shared/type-guards.js";
3
+ function logWarnings(logger, warnings) {
4
+ for (const warning of warnings ?? []) {
5
+ logger.warn(warning);
6
+ }
7
+ }
8
+ function logPlanLines(logger, header, lines) {
9
+ logger.info("");
10
+ logger.info(header);
11
+ for (const line of lines) {
12
+ logger.info(line);
13
+ }
14
+ }
3
15
  function logSettingsResult(logger, result, label, repoNumber, repoName, settingsCollector) {
4
- if (result.planOutput?.lines?.length) {
5
- logger.info("");
6
- logger.info(`${repoName} - ${label}:`);
7
- for (const line of result.planOutput.lines) {
8
- logger.info(line);
9
- }
10
- if (result.warnings?.length) {
11
- for (const warning of result.warnings) {
12
- logger.warn(warning);
13
- }
14
- }
16
+ const planLines = result.planOutput?.lines;
17
+ if (planLines?.length) {
18
+ logPlanLines(logger, `${repoName} - ${label}:`, planLines);
15
19
  }
16
20
  else if (!result.skipped && result.success) {
17
21
  logger.success(repoNumber, repoName, `${label}: ${result.message}`);
18
22
  }
19
- else if (result.skipped) {
20
- for (const warning of result.warnings ?? []) {
21
- logger.warn(warning);
22
- }
23
+ if (planLines?.length || result.skipped || result.success) {
24
+ logWarnings(logger, result.warnings);
23
25
  }
24
26
  if (!result.success && !result.skipped) {
25
27
  logger.error(repoNumber, repoName, `${label}: ${result.message}`);
@@ -84,6 +86,13 @@ function buildSettingsDescriptors(ctx) {
84
86
  e.collaboratorsResult = r;
85
87
  }),
86
88
  },
89
+ {
90
+ key: "environments",
91
+ label: "Environments",
92
+ run: () => runAndStoreResult(factories.environments, repoConfig, repoInfo, sharedOpts, repoName, settingsCollector, (e, r) => {
93
+ e.environmentsResult = r;
94
+ }),
95
+ },
87
96
  ];
88
97
  }
89
98
  export async function applyRepoSettings(ctx) {
@@ -1,7 +1,7 @@
1
1
  import type { MergeMode, MergeStrategy, RepoConfig } from "../config/index.js";
2
2
  import type { IRepoLifecycleManager } from "../lifecycle/index.js";
3
3
  import type { IRepositoryProcessor, FileChangeDetail } from "../sync/index.js";
4
- import type { ISettingsProcessor, IRulesetProcessor, IRepoSettingsProcessor, ILabelsProcessor, ICodeScanningProcessor, IVariablesProcessor, ICollaboratorsProcessor, BaseProcessorResult } from "../settings/index.js";
4
+ import type { ISettingsProcessor, IRulesetProcessor, IRepoSettingsProcessor, ILabelsProcessor, ICodeScanningProcessor, IVariablesProcessor, ICollaboratorsProcessor, IEnvironmentsProcessor, BaseProcessorResult } from "../settings/index.js";
5
5
  import type { RepoInfo } from "../repo/index.js";
6
6
  import type { ResultsCollector } from "./results-collector.js";
7
7
  import type { Logger } from "../shared/logger.js";
@@ -13,7 +13,8 @@ export type LabelsProcessorFactory = SettingsProcessorFactory<ILabelsProcessor>;
13
13
  export type CodeScanningProcessorFactory = SettingsProcessorFactory<ICodeScanningProcessor>;
14
14
  export type VariablesProcessorFactory = SettingsProcessorFactory<IVariablesProcessor>;
15
15
  export type CollaboratorsProcessorFactory = SettingsProcessorFactory<ICollaboratorsProcessor>;
16
- export type SettingsKind = "rulesets" | "labels" | "repo" | "codeScanning" | "variables" | "collaborators";
16
+ export type EnvironmentsProcessorFactory = SettingsProcessorFactory<IEnvironmentsProcessor>;
17
+ export type SettingsKind = "rulesets" | "labels" | "repo" | "codeScanning" | "variables" | "collaborators" | "environments";
17
18
  export interface SettingsProcessorFactories {
18
19
  rulesets: RulesetProcessorFactory;
19
20
  labels: LabelsProcessorFactory;
@@ -21,6 +22,7 @@ export interface SettingsProcessorFactories {
21
22
  codeScanning: CodeScanningProcessorFactory;
22
23
  variables: VariablesProcessorFactory;
23
24
  collaborators: CollaboratorsProcessorFactory;
25
+ environments: EnvironmentsProcessorFactory;
24
26
  }
25
27
  /**
26
28
  * Dependencies for the sync command (dependency injection).
@@ -1,4 +1,4 @@
1
- export type { PRMergeOptions, RepoPROptions, AiConfig, AiProvider, ResolvedAiConfig, MergeMode, MergeStrategy, BypassActor, BypassMode, StatusCheckConfig, CodeScanningTool, PullRequestRuleParameters, RulesetRule, Ruleset, GitHubRepoSettings, RepoVisibility, SquashMergeCommitTitle, SquashMergeCommitMessage, MergeCommitTitle, MergeCommitMessage, Label, CodeScanningSettings, CodeScanningState, CodeScanningQuerySuite, CodeScanningLanguage, RepoSettings, RawFileConfig, RawRepoFileOverride, RawGroupConfig, SecretConfig, CollaboratorsConfig, RawCollaboratorsConfig, SecretsConfig, RawRootSettings, RawRepoSettings, RawRepoConfig, RawConfig, RawConditionalGroupWhen, RawConditionalGroupConfig, RepoConfig, Config, FileContent, ContentValue, } from "./types.js";
1
+ export type { PRMergeOptions, RepoPROptions, AiConfig, AiProvider, ResolvedAiConfig, MergeMode, MergeStrategy, BypassActor, BypassMode, StatusCheckConfig, CodeScanningTool, PullRequestRuleParameters, RulesetRule, Ruleset, GitHubRepoSettings, RepoVisibility, SquashMergeCommitTitle, SquashMergeCommitMessage, MergeCommitTitle, MergeCommitMessage, Label, CodeScanningSettings, CodeScanningState, CodeScanningQuerySuite, CodeScanningLanguage, DeploymentBranchPatternType, DeploymentBranchPattern, DeploymentBranchPolicy, EnvironmentConfig, RawEnvironmentConfig, RepoSettings, RawFileConfig, RawRepoFileOverride, RawGroupConfig, SecretConfig, CollaboratorsConfig, RawCollaboratorsConfig, SecretsConfig, RawRootSettings, RawRepoSettings, RawRepoConfig, RawConfig, RawConditionalGroupWhen, RawConditionalGroupConfig, RepoConfig, Config, FileContent, ContentValue, } from "./types.js";
2
2
  export { RULESET_COMPARABLE_FIELDS } from "./types.js";
3
3
  export { loadRawConfig, loadConfig, normalizeConfig } from "./loader.js";
4
4
  export { convertContentToString } from "./formatter.js";
@@ -1,6 +1,6 @@
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
  /**
6
6
  * Candidate keys for matching array items by identity rather than index.
@@ -15,6 +15,8 @@ export declare function findMatchKey(base: unknown[], overlay: unknown[]): strin
15
15
  export type ArrayMergeStrategy = "replace" | "append" | "prepend" | "merge";
16
16
  export interface MergeContext {
17
17
  defaultArrayStrategy: ArrayMergeStrategy;
18
+ /** Prefixes merge errors, e.g. the file name being merged. */
19
+ location?: string;
18
20
  }
19
21
  /**
20
22
  * Deep merge two objects with configurable array handling.
@@ -25,16 +27,18 @@ export interface MergeContext {
25
27
  */
26
28
  export declare function deepMerge(base: Record<string, unknown>, overlay: Record<string, unknown>, ctx: MergeContext): Record<string, unknown>;
27
29
  /**
28
- * Strip xfg merge directive keys ($arrayMerge, $values) from an object.
30
+ * Strip xfg merge directive keys ($arrayMerge, $values, $matchBy) from an object.
29
31
  * Works recursively on nested objects and arrays.
30
32
  * Standard $-prefixed keys ($schema, $id, $ref, etc.) are preserved.
31
33
  *
32
- * When an unresolved directive object is found (only contains $arrayMerge + $values),
34
+ * When an unresolved directive object is found (only directive keys),
33
35
  * it is replaced with the $values array. This handles the case where a directive
34
36
  * had no base array to merge with.
37
+ *
38
+ * @param location - Prefixes errors, e.g. the file name being stripped
35
39
  */
36
- export declare function stripMergeDirectives(obj: Record<string, unknown>): Record<string, unknown>;
37
- export declare function createMergeContext(defaultStrategy?: ArrayMergeStrategy): MergeContext;
40
+ export declare function stripMergeDirectives(obj: Record<string, unknown>, location?: string): Record<string, unknown>;
41
+ export declare function createMergeContext(defaultStrategy?: ArrayMergeStrategy, location?: string): MergeContext;
38
42
  export declare function isTextContent(content: unknown): content is string | string[];
39
43
  /**
40
44
  * Merge two text content values.
@@ -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
  }