@aspruyt/xfg 8.6.0 → 9.0.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.
@@ -0,0 +1,21 @@
1
+ export declare const ARRAY_MERGE_STRATEGIES: readonly ["replace", "append", "prepend", "merge"];
2
+ export type ArrayMergeStrategy = (typeof ARRAY_MERGE_STRATEGIES)[number];
3
+ export declare const DIRECTIVE_KEYS: ReadonlySet<string>;
4
+ interface ArrayMergeDirective {
5
+ $arrayMerge: ArrayMergeStrategy;
6
+ $values: unknown[];
7
+ $matchBy?: string;
8
+ }
9
+ export declare function isArrayMergeStrategy(value: unknown): value is ArrayMergeStrategy;
10
+ /** Why `items` cannot be matched on `matchBy`, or undefined when they can. */
11
+ export declare function keyedItemsProblem(items: unknown[], matchBy: string): string | undefined;
12
+ /** Accepts exactly what merge.ts resolves, so validation and merge agree. */
13
+ export declare function isArrayMergeDirective(value: unknown): value is ArrayMergeDirective;
14
+ /**
15
+ * Adds to `message` why a directive that is otherwise well formed was refused,
16
+ * so a `$matchBy` that cannot match its `$values` is not reported as "not a directive".
17
+ */
18
+ export declare function explainNotArray(message: string, value: unknown): string;
19
+ /** An array as it is, a valid directive's `$values`, or null for anything else. */
20
+ export declare function arrayValues(value: unknown): unknown[] | null;
21
+ export {};
@@ -0,0 +1,88 @@
1
+ import { isPlainObject } from "../shared/type-guards.js";
2
+ export const ARRAY_MERGE_STRATEGIES = [
3
+ "replace",
4
+ "append",
5
+ "prepend",
6
+ "merge",
7
+ ];
8
+ // Only these are stripped; other $-prefixed keys ($schema, $id, $ref) are content
9
+ export const DIRECTIVE_KEYS = new Set([
10
+ "$arrayMerge",
11
+ "$values",
12
+ "$matchBy",
13
+ ]);
14
+ export function isArrayMergeStrategy(value) {
15
+ return (typeof value === "string" &&
16
+ ARRAY_MERGE_STRATEGIES.includes(value));
17
+ }
18
+ /** Why `items` cannot be matched on `matchBy`, or undefined when they can. */
19
+ export function keyedItemsProblem(items, matchBy) {
20
+ const firstIndexByValue = new Map();
21
+ for (let i = 0; i < items.length; i++) {
22
+ const item = items[i];
23
+ if (!isPlainObject(item) || !Object.hasOwn(item, matchBy)) {
24
+ return `item ${i} has no $matchBy key '${matchBy}'`;
25
+ }
26
+ const value = item[matchBy];
27
+ // Map compares objects by reference, so only primitives can match
28
+ if (value !== null &&
29
+ !["string", "number", "boolean"].includes(typeof value)) {
30
+ return `item ${i} $matchBy ${matchBy} must be a string, number, boolean or null`;
31
+ }
32
+ const first = firstIndexByValue.get(value);
33
+ if (first !== undefined) {
34
+ return `items ${first} and ${i} share $matchBy ${matchBy} '${String(value)}'`;
35
+ }
36
+ firstIndexByValue.set(value, i);
37
+ }
38
+ return undefined;
39
+ }
40
+ function hasDirectiveShape(value) {
41
+ if (!isPlainObject(value))
42
+ return false;
43
+ const keys = Object.keys(value);
44
+ return (keys.length > 0 &&
45
+ keys.every((key) => DIRECTIVE_KEYS.has(key)) &&
46
+ isArrayMergeStrategy(value.$arrayMerge) &&
47
+ Array.isArray(value.$values));
48
+ }
49
+ /** The `$matchBy` of a merge directive when it is a usable name, else undefined. */
50
+ function matchByName(value) {
51
+ const matchBy = value.$matchBy;
52
+ return value.$arrayMerge === "merge" &&
53
+ typeof matchBy === "string" &&
54
+ matchBy !== ""
55
+ ? matchBy
56
+ : undefined;
57
+ }
58
+ /** Accepts exactly what merge.ts resolves, so validation and merge agree. */
59
+ export function isArrayMergeDirective(value) {
60
+ if (!hasDirectiveShape(value))
61
+ return false;
62
+ if (!("$matchBy" in value))
63
+ return true;
64
+ const matchBy = matchByName(value);
65
+ return (matchBy !== undefined &&
66
+ keyedItemsProblem(value.$values, matchBy) === undefined);
67
+ }
68
+ /**
69
+ * Adds to `message` why a directive that is otherwise well formed was refused,
70
+ * so a `$matchBy` that cannot match its `$values` is not reported as "not a directive".
71
+ */
72
+ export function explainNotArray(message, value) {
73
+ if (!hasDirectiveShape(value))
74
+ return message;
75
+ const matchBy = matchByName(value);
76
+ const problem = matchBy === undefined
77
+ ? undefined
78
+ : keyedItemsProblem(value.$values, matchBy);
79
+ return problem === undefined ? message : `${message}: $values ${problem}`;
80
+ }
81
+ /** An array as it is, a valid directive's `$values`, or null for anything else. */
82
+ export function arrayValues(value) {
83
+ if (Array.isArray(value))
84
+ return value;
85
+ if (isArrayMergeDirective(value))
86
+ return value.$values;
87
+ return null;
88
+ }
@@ -0,0 +1,2 @@
1
+ /** First repeat wins; arrays holding objects are left alone, since lookalike objects can differ. */
2
+ export declare function dropRepeatedItems<T>(value: T): T;
@@ -0,0 +1,19 @@
1
+ import { isPlainObject } from "../shared/type-guards.js";
2
+ function isPrimitiveItem(item) {
3
+ return (typeof item === "string" ||
4
+ typeof item === "number" ||
5
+ typeof item === "boolean");
6
+ }
7
+ /** First repeat wins; arrays holding objects are left alone, since lookalike objects can differ. */
8
+ export function dropRepeatedItems(value) {
9
+ if (Array.isArray(value)) {
10
+ const items = value.every(isPrimitiveItem)
11
+ ? [...new Set(value)]
12
+ : value.map(dropRepeatedItems);
13
+ return items;
14
+ }
15
+ if (isPlainObject(value)) {
16
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, dropRepeatedItems(item)]));
17
+ }
18
+ return value;
19
+ }
@@ -1,12 +1,17 @@
1
+ import { type ArrayMergeStrategy } from "./array-directive.js";
1
2
  /** Order matters: the first key present in every item of both arrays wins. */
2
3
  export declare const MATCH_KEY_CANDIDATES: readonly ["type", "actorId", "actor_id"];
3
4
  export declare function findMatchKey(base: unknown[], overlay: unknown[]): string | undefined;
4
- export type ArrayMergeStrategy = "replace" | "append" | "prepend" | "merge";
5
5
  export interface MergeContext {
6
6
  defaultArrayStrategy: ArrayMergeStrategy;
7
7
  /** Prefixes merge errors, e.g. the file name being merged. */
8
8
  location?: string;
9
9
  }
10
+ /** `inherit` is stripped so it never lands in the merged block as content. */
11
+ export declare function applyInherit(base: Record<string, unknown> | false | undefined, overlay: Record<string, unknown>): {
12
+ base: Record<string, unknown>;
13
+ overlay: Record<string, unknown>;
14
+ };
10
15
  export declare function deepMerge(base: Record<string, unknown>, overlay: Record<string, unknown>, ctx: MergeContext): Record<string, unknown>;
11
16
  /**
12
17
  * A valid directive-only object that is the value of a key had no base array
@@ -1,5 +1,6 @@
1
1
  import { isPlainObject } from "../shared/type-guards.js";
2
2
  import { ValidationError } from "../shared/errors.js";
3
+ import { ARRAY_MERGE_STRATEGIES, DIRECTIVE_KEYS, isArrayMergeStrategy, keyedItemsProblem, } from "./array-directive.js";
3
4
  /** Order matters: the first key present in every item of both arrays wins. */
4
5
  export const MATCH_KEY_CANDIDATES = ["type", "actorId", "actor_id"];
5
6
  export function findMatchKey(base, overlay) {
@@ -14,8 +15,6 @@ export function findMatchKey(base, overlay) {
14
15
  }
15
16
  return undefined;
16
17
  }
17
- // Only these are stripped; other $-prefixed keys ($schema, $id, $ref) are content
18
- const XFG_DIRECTIVES = new Set(["$arrayMerge", "$values", "$matchBy"]);
19
18
  function childPath(path, key) {
20
19
  return path ? `${path}.${key}` : key;
21
20
  }
@@ -46,7 +45,7 @@ function readMatchBy(directive, ctx, path) {
46
45
  }
47
46
  function isDirectiveOnly(value) {
48
47
  const keys = Object.keys(value);
49
- return keys.length > 0 && keys.every((k) => XFG_DIRECTIVES.has(k));
48
+ return keys.length > 0 && keys.every((k) => DIRECTIVE_KEYS.has(k));
50
49
  }
51
50
  /** An object of only directive keys must be a complete directive, or it would resolve to nothing. */
52
51
  function readDirective(value, ctx, path) {
@@ -56,8 +55,7 @@ function readDirective(value, ctx, path) {
56
55
  if (!isDirectiveOnly(value))
57
56
  return matchBy;
58
57
  if (!isArrayMergeStrategy(value.$arrayMerge)) {
59
- const strategies = [...arrayMergeStrategies.keys()].join(", ");
60
- throw mergeError(ctx, path, `$arrayMerge must be one of ${strategies}, got ${describeValue(value.$arrayMerge)}`);
58
+ throw mergeError(ctx, path, `$arrayMerge must be one of ${ARRAY_MERGE_STRATEGIES.join(", ")}, got ${describeValue(value.$arrayMerge)}`);
61
59
  }
62
60
  if (!Array.isArray(value.$values)) {
63
61
  throw mergeError(ctx, path, `$values must be an array, got ${describeValue(value.$values)}`);
@@ -71,24 +69,9 @@ function assertNotDirective(value, ctx, path, position) {
71
69
  }
72
70
  }
73
71
  function assertKeyedItems(items, matchBy, label, ctx, path) {
74
- const firstIndexByValue = new Map();
75
- for (let i = 0; i < items.length; i++) {
76
- const item = items[i];
77
- if (!isPlainObject(item) || !Object.hasOwn(item, matchBy)) {
78
- throw mergeError(ctx, path, `${label} item ${i} has no $matchBy key '${matchBy}'`);
79
- }
80
- const value = item[matchBy];
81
- // Map compares objects by reference, so only primitives can match
82
- if (value !== null &&
83
- !["string", "number", "boolean"].includes(typeof value)) {
84
- throw mergeError(ctx, path, `${label} item ${i} $matchBy ${matchBy} must be a string, number, boolean or null`);
85
- }
86
- const first = firstIndexByValue.get(value);
87
- if (first !== undefined) {
88
- throw mergeError(ctx, path, `${label} items ${first} and ${i} share $matchBy ${matchBy} '${String(value)}'`);
89
- }
90
- firstIndexByValue.set(value, i);
91
- }
72
+ const problem = keyedItemsProblem(items, matchBy);
73
+ if (problem !== undefined)
74
+ throw mergeError(ctx, path, `${label} ${problem}`);
92
75
  }
93
76
  function mergeByKey(base, overlay, matchKey, ctx, path) {
94
77
  const baseByKey = new Map();
@@ -159,6 +142,11 @@ function mergeArrays(base, overlay, strategy, ctx, path) {
159
142
  }
160
143
  return overlay;
161
144
  }
145
+ /** `inherit` is stripped so it never lands in the merged block as content. */
146
+ export function applyInherit(base, overlay) {
147
+ const { inherit, ...rest } = overlay;
148
+ return { base: inherit === false || !base ? {} : base, overlay: rest };
149
+ }
162
150
  export function deepMerge(base, overlay, ctx) {
163
151
  assertNotDirective(base, ctx, "", "the content root");
164
152
  assertNotDirective(overlay, ctx, "", "the content root");
@@ -167,7 +155,7 @@ export function deepMerge(base, overlay, ctx) {
167
155
  function mergeObjects(base, overlay, ctx, path) {
168
156
  const result = { ...base };
169
157
  for (const [key, overlayValue] of Object.entries(overlay)) {
170
- if (XFG_DIRECTIVES.has(key))
158
+ if (DIRECTIVE_KEYS.has(key))
171
159
  continue;
172
160
  result[key] = mergeValue(base[key], overlayValue, ctx, childPath(path, key));
173
161
  }
@@ -205,10 +193,6 @@ function resolveBase(base, ctx, path) {
205
193
  function isArrayDirective(value) {
206
194
  return (isPlainObject(value) && ("$arrayMerge" in value || "$matchBy" in value));
207
195
  }
208
- function isArrayMergeStrategy(value) {
209
- return (typeof value === "string" &&
210
- arrayMergeStrategies.has(value));
211
- }
212
196
  /** Returns undefined when the directive doesn't apply, so the caller falls back to a plain merge. */
213
197
  function applyArrayDirective(base, directive, matchBy, ctx, path) {
214
198
  const strategy = directive.$arrayMerge;
@@ -249,7 +233,7 @@ function stripItems(items, errCtx, path) {
249
233
  function stripObject(obj, errCtx, path) {
250
234
  const result = {};
251
235
  for (const [key, value] of Object.entries(obj)) {
252
- if (XFG_DIRECTIVES.has(key))
236
+ if (DIRECTIVE_KEYS.has(key))
253
237
  continue;
254
238
  const keyPath = childPath(path, key);
255
239
  // Validate before branching: an invalid directive is not resolved and would be stripped silently