All files / assert / object_match.ts

98.68% Branches 75/76
100.00% Functions 6/6
97.04% Lines 131/135
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
 
 
x1199
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x1199
 
x154
x154
x154
 
x154
 
 
x154
 
 
x154
x154
 
x154
 
 
 
x1088
x1088
x1088
 
x903
x903
x903
x903
x903
x903
x903
x903
 
x303
x303
x303
 
x303
 
x405
x405
 
x403
x403
x405
x5
x5
x5
 
x5
x5
 
 
x398
x398
x398
x398
x899
 
x405
 
 
x3
x3
x3
 
x405
 
x899
x6
x6
x6
 
x899
x6
x6
x6
 
x887
 
 
x899
x47
x47
x47
 
 
x899
 
x88
x12
x12
x12
x12
x12
x12
x12
x12
x6
x6
x6
x12
 
 
 
x12
x12
 
 
x88
x4
x4
x4
 
x72
x72
x72
x72
 
x72
x72
 
x752
x752
 
x395
x405
 
x303
 
x85
x85
 
x83
 
x83
x83
 
x85
x151
x151
 
 
x151
x8
x8
x8
 
 
 
 
 
 
 
x151
x38
x38
x38
 
 
x151
 
x28
x4
x4
x4
x4
x4
x2
x2
 
x2
x4
 
x4
x4
x4
 
 
x28
x2
x2
x2
 
x22
x22
x22
 
x77
x77
 
x151
x85
x303

















































































































































































I












































// Copyright 2018-2026 the Deno authors. MIT license.
// This module is browser compatible.
import { assertEquals } from "./equals.ts";

/**
 * Make an assertion that `expected` object is a subset of `actual` object,
 * deeply. If not, then throw a diff of the objects, with mismatching
 * properties highlighted.
 *
 * @example Usage
 * ```ts ignore
 * import { assertObjectMatch } from "@std/assert";
 *
 * assertObjectMatch({ foo: "bar" }, { foo: "bar" }); // Doesn't throw
 * assertObjectMatch({ foo: "bar" }, { foo: "baz" }); // Throws
 * assertObjectMatch({ foo: 1, bar: 2 }, { foo: 1 }); // Doesn't throw
 * assertObjectMatch({ foo: 1 }, { foo: 1, bar: 2 }); // Throws
 * ```
 *
 * @example Usage with nested objects
 * ```ts ignore
 * import { assertObjectMatch } from "@std/assert";
 *
 * assertObjectMatch({ foo: { bar: 3, baz: 4 } }, { foo: { bar: 3 } }); // Doesn't throw
 * assertObjectMatch({ foo: { bar: 3 } }, { foo: { bar: 3, baz: 4 } }); // Throws
 * ```
 *
 * @param actual The actual value to be matched.
 * @param expected The expected value to match.
 * @param msg The optional message to display if the assertion fails.
 */
export function assertObjectMatch(
  // deno-lint-ignore no-explicit-any
  actual: Record<PropertyKey, any>,
  expected: Record<PropertyKey, unknown>,
  msg?: string,
): void {
  return assertEquals(
    // get the intersection of "actual" and "expected"
    // side effect: all the instances' constructor field is "Object" now.
    filter(actual, expected),
    // set (nested) instances' constructor field to be "Object" without changing expected value.
    // see https://github.com/denoland/std/pull/1419
    filter(expected, expected),
    msg,
  );
}

type Loose = Record<PropertyKey, unknown>;

function isObject(val: unknown): boolean {
  return typeof val === "object" && val !== null;
}

function defineProperty(target: object, key: PropertyKey, value: unknown) {
  return Object.defineProperty(target, key, {
    value,
    configurable: true,
    enumerable: true,
    writable: true,
  });
}

function filter(a: Loose, b: Loose): Loose {
  const seen = new WeakMap<Loose | unknown[], Loose | unknown[]>();
  return filterObject(a, b);

  function filterObject(a: Loose, b: Loose): Loose {
    // Prevent infinite loop with circular references with same filter
    const memo = seen.get(a);
    if (memo && (memo === b)) return a;

    try {
      seen.set(a, b);
    } catch (err) {
      if (err instanceof TypeError) {
        throw new TypeError(
          `Cannot assertObjectMatch ${a === null ? null : `type ${typeof a}`}`,
        );
      }
    }

    // Filter keys and symbols which are present in both actual and expected
    const filtered = {} as Loose;
    const keysA = Reflect.ownKeys(a);
    const keysB = Reflect.ownKeys(b);
    const entries = keysA.filter((key) => keysB.includes(key))
      .map((key) => [key, a[key as string]]) as Array<[string, unknown]>;

    if (keysA.length && keysB.length && !entries.length) {
      // If both objects are not empty but don't have the same keys or symbols,
      // returns the entries in object a.
      for (const key of keysA) defineProperty(filtered, key, a[key]);
      return filtered;
    }

    for (const [key, value] of entries) {
      // On regexp references, keep value as it to avoid losing pattern and flags
      if (value instanceof RegExp) {
        defineProperty(filtered, key, value);
        continue;
      }
      // On date references, keep value as it to avoid losing the timestamp
      if (value instanceof Date) {
        defineProperty(filtered, key, value);
        continue;
      }

      const subset = (b as Loose)[key];

      // On array references, build a filtered array and filter nested objects inside
      if (Array.isArray(value) && Array.isArray(subset)) {
        defineProperty(filtered, key, filterArray(value, subset));
        continue;
      }

      // On nested objects references, build a filtered object recursively
      if (isObject(value) && isObject(subset)) {
        // When both operands are maps, build a filtered map with common keys and filter nested objects inside
        if ((value instanceof Map) && (subset instanceof Map)) {
          defineProperty(
            filtered,
            key,
            new Map(
              [...value].filter(([k]) => subset.has(k)).map(
                ([k, v]) => {
                  const v2 = subset.get(k);
                  if (isObject(v) && isObject(v2)) {
                    return [k, filterObject(v as Loose, v2 as Loose)];
                  }
                  return [k, v];
                },
              ),
            ),
          );
          continue;
        }

        // When both operands are set, build a filtered set with common values
        if ((value instanceof Set) && (subset instanceof Set)) {
          defineProperty(filtered, key, value.intersection(subset));
          continue;
        }

        defineProperty(
          filtered,
          key,
          filterObject(value as Loose, subset as Loose),
        );
        continue;
      }

      defineProperty(filtered, key, value);
    }

    return filtered;
  }

  function filterArray(a: unknown[], b: unknown[]): unknown[] {
    // Prevent infinite loop with circular references with same filter
    const memo = seen.get(a);
    if (memo && (memo === b)) return a;

    seen.set(a, b);

    const filtered: unknown[] = [];
    const count = Math.min(a.length, b.length);

    for (let i = 0; i < count; ++i) {
      const value = a[i];
      const subset = b[i];

      // On regexp references, keep value as it to avoid losing pattern and flags
      if (value instanceof RegExp) {
        filtered.push(value);
        continue;
      }
      // On date references, keep value as it to avoid losing the timestamp
      if (value instanceof Date) {
        filtered.push(value);
        continue;
      }

      // On array references, build a filtered array and filter nested objects inside
      if (Array.isArray(value) && Array.isArray(subset)) {
        filtered.push(filterArray(value, subset));
        continue;
      }

      // On nested objects references, build a filtered object recursively
      if (isObject(value) && isObject(subset)) {
        // When both operands are maps, build a filtered map with common keys and filter nested objects inside
        if ((value instanceof Map) && (subset instanceof Map)) {
          const map = new Map(
            [...value].filter(([k]) => subset.has(k))
              .map(([k, v]) => {
                const v2 = subset.get(k);
                if (isObject(v) && isObject(v2)) {
                  return [k, filterObject(v as Loose, v2 as Loose)];
                }

                return [k, v];
              }),
          );
          filtered.push(map);
          continue;
        }

        // When both operands are set, build a filtered set with common values
        if ((value instanceof Set) && (subset instanceof Set)) {
          filtered.push(value.intersection(subset));
          continue;
        }

        filtered.push(filterObject(value as Loose, subset as Loose));
        continue;
      }

      filtered.push(value);
    }

    return filtered;
  }
}