All files / collections / deep_merge.ts

100.00% Branches 34/34
100.00% Lines 99/99
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
 
 
 
x22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x22
 
 
 
 
 
 
 
 
x22
x22
x22
 
x319
x319
 
x333
 
 
 
 
 
 
 
 
x333
x333
x333
x333
 
 
 
 
x333
 
x333
x333
x333
x333
 
 
x333
 
x1839
x1840
x1840
 
 
 
x3344
 
x1839
x2985
 
x2985
x2985
 
x2198
 
x1839
x1839
x1839
x1875
x1875
x1875
 
x1875
x1875
 
 
x2162
x2162
 
x333
x333
 
x58
x58
x58
x58
x58
x58
x58
x58
x58
 
 
x58
x72
x72
 
x58
 
x107
x116
x120
x120
 
x121
x121
 
 
x107
x125
x128
x128
x128
x128
x128
 
x129
x129
 
 
x107
x112
x116
x116
x116
x116
x116
 
x113
x113
x107
 
x93
x58
 
 
 
 
 
 
x22
x22
 
x73
x73
 
x63
x63
 
x63
x63
 
x421
x421
 
x421
x421
 
x644
x644
x644
x644
x644
 
x644
 
x644
x644
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
































































































































































































































































































































































































































































































































































































// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

import { filterInPlace } from "./_utils.ts";

/**
 * Merges the two given records, recursively merging any nested records with the
 * second collection overriding the first in case of conflict.
 *
 * For arrays, maps and sets, a merging strategy can be specified to either
 * `replace` values, or `merge` them instead.
 *
 * @typeParam T Type of the first record
 *
 * @param record First record to merge.
 * @param other Second record to merge.
 * @param options Merging options.
 *
 * @returns A new record with the merged values.
 *
 * @example Merge objects
 * ```ts
 * import { deepMerge } from "@std/collections/deep-merge";
 * import { assertEquals } from "@std/assert";
 *
 * const a = { foo: true };
 * const b = { foo: { bar: true } };
 *
 * const result = deepMerge(a, b);
 *
 * const expected = { foo: { bar: true } };
 *
 * assertEquals(result, expected);
 * ```
 *
 * @example Merge arrays
 * ```ts
 * import { deepMerge } from "@std/collections/deep-merge";
 * import { assertEquals } from "@std/assert";
 *
 * const a = { foo: [1, 2] };
 * const b = { foo: [3, 4] };
 *
 * const result = deepMerge(a, b);
 *
 * const expected = { foo: [1, 2, 3, 4] };
 *
 * assertEquals(result, expected);
 * ```
 *
 * @example Merge maps
 * ```ts
 * import { deepMerge } from "@std/collections/deep-merge";
 * import { assertEquals } from "@std/assert";
 *
 * const a = { foo: new Map([["a", 1]]) };
 * const b = { foo: new Map([["b", 2]]) };
 *
 * const result = deepMerge(a, b);
 *
 * const expected = { foo: new Map([["a", 1], ["b", 2]]) };
 *
 * assertEquals(result, expected);
 * ```
 *
 * @example Merge sets
 * ```ts
 * import { deepMerge } from "@std/collections/deep-merge";
 * import { assertEquals } from "@std/assert";
 *
 * const a = { foo: new Set([1]) };
 * const b = { foo: new Set([2]) };
 *
 * const result = deepMerge(a, b);
 *
 * const expected = { foo: new Set([1, 2]) };
 *
 * assertEquals(result, expected);
 * ```
 *
 * @example Merge with custom options
 * ```ts
 * import { deepMerge } from "@std/collections/deep-merge";
 * import { assertEquals } from "@std/assert";
 *
 * const a = { foo: [1, 2] };
 * const b = { foo: [3, 4] };
 *
 * const result = deepMerge(a, b, { arrays: "replace" });
 *
 * const expected = { foo: [3, 4] };
 *
 * assertEquals(result, expected);
 * ```
 */
export function deepMerge<
  T extends Record<PropertyKey, unknown>,
>(
  record: Partial<Readonly<T>>,
  other: Partial<Readonly<T>>,
  options?: Readonly<DeepMergeOptions>,
): T;
/**
 * Merges the two given records, recursively merging any nested records with the
 * second collection overriding the first in case of conflict.
 *
 * For arrays, maps and sets, a merging strategy can be specified to either
 * `replace` values, or `merge` them instead.
 *
 * @typeParam T Type of the first record
 * @typeParam U Type of the second record
 * @typeParam Options Merging options
 *
 * @param record First record to merge.
 * @param other Second record to merge.
 * @param options Merging options.
 *
 * @returns A new record with the merged values.
 *
 * @example Merge objects
 * ```ts
 * import { deepMerge } from "@std/collections/deep-merge";
 * import { assertEquals } from "@std/assert";
 *
 * const a = { foo: true };
 * const b = { foo: { bar: true } };
 *
 * const result = deepMerge(a, b);
 *
 * const expected = { foo: { bar: true } };
 *
 * assertEquals(result, expected);
 * ```
 *
 * @example Merge arrays
 * ```ts
 * import { deepMerge } from "@std/collections/deep-merge";
 * import { assertEquals } from "@std/assert";
 *
 * const a = { foo: [1, 2] };
 * const b = { foo: [3, 4] };
 *
 * const result = deepMerge(a, b);
 *
 * const expected = { foo: [1, 2, 3, 4] };
 *
 * assertEquals(result, expected);
 * ```
 *
 * @example Merge maps
 * ```ts
 * import { deepMerge } from "@std/collections/deep-merge";
 * import { assertEquals } from "@std/assert";
 *
 * const a = { foo: new Map([["a", 1]]) };
 * const b = { foo: new Map([["b", 2]]) };
 *
 * const result = deepMerge(a, b);
 *
 * const expected = { foo: new Map([["a", 1], ["b", 2]]) };
 *
 * assertEquals(result, expected);
 * ```
 *
 * @example Merge sets
 * ```ts
 * import { deepMerge } from "@std/collections/deep-merge";
 * import { assertEquals } from "@std/assert";
 *
 * const a = { foo: new Set([1]) };
 * const b = { foo: new Set([2]) };
 *
 * const result = deepMerge(a, b);
 *
 * const expected = { foo: new Set([1, 2]) };
 *
 * assertEquals(result, expected);
 * ```
 *
 * @example Merge with custom options
 * ```ts
 * import { deepMerge } from "@std/collections/deep-merge";
 * import { assertEquals } from "@std/assert";
 *
 * const a = { foo: [1, 2] };
 * const b = { foo: [3, 4] };
 *
 * const result = deepMerge(a, b, { arrays: "replace" });
 *
 * const expected = { foo: [3, 4] };
 *
 * assertEquals(result, expected);
 * ```
 */
export function deepMerge<
  T extends Record<PropertyKey, unknown>,
  U extends Record<PropertyKey, unknown>,
  Options extends DeepMergeOptions,
>(
  record: Readonly<T>,
  other: Readonly<U>,
  options?: Readonly<Options>,
): DeepMerge<T, U, Options>;
export function deepMerge<
  T extends Record<PropertyKey, unknown>,
  U extends Record<PropertyKey, unknown>,
  Options extends DeepMergeOptions = {
    arrays: "merge";
    sets: "merge";
    maps: "merge";
  },
>(
  record: Readonly<T>,
  other: Readonly<U>,
  options?: Readonly<Options>,
): DeepMerge<T, U, Options> {
  return deepMergeInternal(record, other, new Set(), options);
}

function deepMergeInternal<
  T extends Record<PropertyKey, unknown>,
  U extends Record<PropertyKey, unknown>,
  Options extends DeepMergeOptions = {
    arrays: "merge";
    sets: "merge";
    maps: "merge";
  },
>(
  record: Readonly<T>,
  other: Readonly<U>,
  seen: Set<NonNullable<unknown>>,
  options?: Readonly<Options>,
) {
  // Extract options
  // Clone left operand to avoid performing mutations in-place
  type Result = DeepMerge<T, U, Options>;
  const result: Partial<Result> = {};

  const keys = new Set([
    ...getKeys(record),
    ...getKeys(other),
  ]) as Set<keyof Result>;

  // Iterate through each key of other object and use correct merging strategy
  for (const key of keys) {
    // Skip to prevent Object.prototype.__proto__ accessor property calls on non-Deno platforms
    if (key === "__proto__") {
      continue;
    }

    type ResultMember = Result[typeof key];

    const a = record[key] as ResultMember;

    if (!Object.hasOwn(other, key)) {
      result[key] = a;

      continue;
    }

    const b = other[key] as ResultMember;

    if (
      isNonNullObject(a) && isNonNullObject(b) && !seen.has(a) && !seen.has(b)
    ) {
      seen.add(a);
      seen.add(b);
      result[key] = mergeObjects(a, b, seen, options) as ResultMember;

      continue;
    }

    // Override value
    result[key] = b;
  }

  return result as Result;
}

function mergeObjects(
  left: Readonly<NonNullable<Record<string, unknown>>>,
  right: Readonly<NonNullable<Record<string, unknown>>>,
  seen: Set<NonNullable<unknown>>,
  options: Readonly<DeepMergeOptions> = {
    arrays: "merge",
    sets: "merge",
    maps: "merge",
  },
): Readonly<NonNullable<Record<string, unknown> | Iterable<unknown>>> {
  // Recursively merge mergeable objects
  if (isMergeable(left) && isMergeable(right)) {
    return deepMergeInternal(left, right, seen, options);
  }

  if (isIterable(left) && isIterable(right)) {
    // Handle arrays
    if ((Array.isArray(left)) && (Array.isArray(right))) {
      if (options.arrays === "merge") {
        return left.concat(right);
      }

      return right;
    }

    // Handle maps
    if ((left instanceof Map) && (right instanceof Map)) {
      if (options.maps === "merge") {
        return new Map([
          ...left,
          ...right,
        ]);
      }

      return right;
    }

    // Handle sets
    if ((left instanceof Set) && (right instanceof Set)) {
      if (options.sets === "merge") {
        return new Set([
          ...left,
          ...right,
        ]);
      }

      return right;
    }
  }

  return right;
}

/**
 * Test whether a value is mergeable or not
 * Builtins that look like objects, null and user defined classes
 * are not considered mergeable (it means that reference will be copied)
 */
function isMergeable(
  value: NonNullable<unknown>,
): value is Record<PropertyKey, unknown> {
  return Object.getPrototypeOf(value) === Object.prototype;
}

function isIterable(
  value: NonNullable<unknown>,
): value is Iterable<unknown> {
  return typeof (value as Iterable<unknown>)[Symbol.iterator] === "function";
}

function isNonNullObject(
  value: unknown,
): value is NonNullable<Record<string, unknown>> {
  return value !== null && typeof value === "object";
}

function getKeys<T extends Record<string, unknown>>(record: T): Array<keyof T> {
  const result = Object.getOwnPropertySymbols(record) as Array<keyof T>;
  filterInPlace(
    result,
    (key) => Object.prototype.propertyIsEnumerable.call(record, key),
  );
  result.push(...(Object.keys(record) as Array<keyof T>));

  return result;
}

/** Merging strategy */
export type MergingStrategy = "replace" | "merge";

/** Options for {@linkcode deepMerge}. */
export type DeepMergeOptions = {
  /**
   * Merging strategy for arrays
   *
   * @default {"merge"}
   */
  arrays?: MergingStrategy;
  /**
   * Merging strategy for maps.
   *
   * @default {"merge"}
   */
  maps?: MergingStrategy;
  /**
   * Merging strategy for sets.
   *
   * @default {"merge"}
   */
  sets?: MergingStrategy;
};

/**
 * How does recursive typing works ?
 *
 * Deep merging process is handled through `DeepMerge<T, U, Options>` type.
 * If both T and U are Records, we recursively merge them,
 * else we treat them as primitives.
 *
 * Merging process is handled through `Merge<T, U>` type, in which
 * we remove all maps, sets, arrays and records so we can handle them
 * separately depending on merging strategy:
 *
 *    Merge<
 *      {foo: string},
 *      {bar: string, baz: Set<unknown>},
 *    > // "foo" and "bar" will be handled with `MergeRightOmitComplexes`
 *      // "baz" will be handled with `MergeAll*` type
 *
 * `MergeRightOmitComplexes<T, U>` will do the above: all T's
 * exclusive keys will be kept, though common ones with U will have their
 * typing overridden instead:
 *
 *    MergeRightOmitComplexes<
 *      {foo: string, baz: number},
 *      {foo: boolean, bar: string}
 *    > // {baz: number, foo: boolean, bar: string}
 *      // "baz" was kept from T
 *      // "foo" was overridden by U's typing
 *      // "bar" was added from U
 *
 * For Maps, Arrays, Sets and Records, we use `MergeAll*<T, U>` utility
 * types. They will extract relevant data structure from both T and U
 * (providing that both have same data data structure, except for typing).
 *
 * From these, `*ValueType<T>` will extract values (and keys) types to be
 * able to create a new data structure with an union typing from both
 * data structure of T and U:
 *
 *    MergeAllSets<
 *      {foo: Set<number>},
 *      {foo: Set<string>}
 *    > // `SetValueType` will extract "number" for T
 *      // `SetValueType` will extract "string" for U
 *      // `MergeAllSets` will infer type as Set<number|string>
 *      // Process is similar for Maps, Arrays, and Sets
 *
 * `DeepMerge<T, U, Options>` is taking a third argument to be handle to
 * infer final typing depending on merging strategy:
 *
 *    & (Options extends { sets: "replace" } ? PartialByType<U, Set<unknown>>
 *      : MergeAllSets<T, U>)
 *
 * In the above line, if "Options" have its merging strategy for Sets set to
 * "replace", instead of performing merging of Sets type, it will take the
 * typing from right operand (U) instead, effectively replacing the typing.
 *
 * An additional note, we use `ExpandRecursively<T>` utility type to expand
 * the resulting typing and hide all the typing logic of deep merging so it is
 * more user friendly.
 */

/** Force intellisense to expand the typing to hide merging typings */
export type ExpandRecursively<T> = T extends Record<PropertyKey, unknown>
  ? T extends infer O ? { [K in keyof O]: ExpandRecursively<O[K]> } : never
  : T;

/** Filter of keys matching a given type */
export type PartialByType<T, U> = {
  [K in keyof T as T[K] extends U ? K : never]: T[K];
};

/** Get set values type */
export type SetValueType<T> = T extends Set<infer V> ? V : never;

/** Merge all sets types definitions from keys present in both objects */
export type MergeAllSets<
  T,
  U,
  X = PartialByType<T, Set<unknown>>,
  Y = PartialByType<U, Set<unknown>>,
  Z = {
    [K in keyof X & keyof Y]: Set<SetValueType<X[K]> | SetValueType<Y[K]>>;
  },
> = Z;

/** Get array values type */
export type ArrayValueType<T> = T extends Array<infer V> ? V : never;

/** Merge all sets types definitions from keys present in both objects */
export type MergeAllArrays<
  T,
  U,
  X = PartialByType<T, Array<unknown>>,
  Y = PartialByType<U, Array<unknown>>,
  Z = {
    [K in keyof X & keyof Y]: Array<
      ArrayValueType<X[K]> | ArrayValueType<Y[K]>
    >;
  },
> = Z;

/** Get map values types */
export type MapKeyType<T> = T extends Map<infer K, unknown> ? K : never;

/** Get map values types */
export type MapValueType<T> = T extends Map<unknown, infer V> ? V : never;

/** Merge all sets types definitions from keys present in both objects */
export type MergeAllMaps<
  T,
  U,
  X = PartialByType<T, Map<unknown, unknown>>,
  Y = PartialByType<U, Map<unknown, unknown>>,
  Z = {
    [K in keyof X & keyof Y]: Map<
      MapKeyType<X[K]> | MapKeyType<Y[K]>,
      MapValueType<X[K]> | MapValueType<Y[K]>
    >;
  },
> = Z;

/** Merge all records types definitions from keys present in both objects */
export type MergeAllRecords<
  T,
  U,
  Options,
  X = PartialByType<T, Record<PropertyKey, unknown>>,
  Y = PartialByType<U, Record<PropertyKey, unknown>>,
  Z = {
    [K in keyof X & keyof Y]: DeepMerge<X[K], Y[K], Options>;
  },
> = Z;

/** Exclude map, sets and array from type */
export type OmitComplexes<T> = Omit<
  T,
  keyof PartialByType<
    T,
    | Map<unknown, unknown>
    | Set<unknown>
    | Array<unknown>
    | Record<PropertyKey, unknown>
  >
>;

/** Object with keys in either T or U but not in both */
export type ObjectXorKeys<
  T,
  U,
  X = Omit<T, keyof U> & Omit<U, keyof T>,
  Y = { [K in keyof X]: X[K] },
> = Y;

/** Merge two objects, with left precedence */
export type MergeRightOmitComplexes<
  T,
  U,
  X = ObjectXorKeys<T, U> & OmitComplexes<{ [K in keyof U]: U[K] }>,
> = X;

/** Merge two objects */
export type Merge<
  T,
  U,
  Options,
  X =
    & MergeRightOmitComplexes<T, U>
    & MergeAllRecords<T, U, Options>
    & (Options extends { sets: "replace" } ? PartialByType<U, Set<unknown>>
      : MergeAllSets<T, U>)
    & (Options extends { arrays: "replace" } ? PartialByType<U, Array<unknown>>
      : MergeAllArrays<T, U>)
    & (Options extends { maps: "replace" }
      ? PartialByType<U, Map<unknown, unknown>>
      : MergeAllMaps<T, U>),
> = ExpandRecursively<X>;

/** Merge deeply two objects */
export type DeepMerge<
  T,
  U,
  Options = Record<string, MergingStrategy>,
> =
  // Handle objects
  [T, U] extends [Record<PropertyKey, unknown>, Record<PropertyKey, unknown>]
    ? Merge<T, U, Options>
    // Handle primitives
    : T | U;