Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: messages deepCopy mutates src arguments #1975

Merged
merged 1 commit into from
Sep 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion packages/shared/src/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,15 @@ export function deepCopy(src: any, des: any): void {
while (stack.length) {
const { src, des } = stack.pop()!

// using `Object.keys` which skips prototype properties
Object.keys(src).forEach(key => {
if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) {
// if src[key] is an object/array, set des[key]
// to empty object/array to prevent setting by reference
if (isObject(src[key]) && !isObject(des[key])) {
des[key] = Array.isArray(src[key]) ? [] : {}
}

if (isNotObjectOrIsArray(des[key]) || isNotObjectOrIsArray(src[key])) {
// replace with src[key] when:
// src[key] or des[key] is not an object, or
// src[key] or des[key] is an array
Expand Down
50 changes: 50 additions & 0 deletions packages/shared/test/messages.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { deepCopy } from '../src/index'

test('deepCopy merges without mutating src argument', () => {
const msg1 = {
hello: 'Greetings',
about: {
title: 'About us'
},
overwritten: 'Original text',
fruit: [{ name: 'Apple' }]
}
const copy1 = structuredClone(msg1)

const msg2 = {
bye: 'Goodbye',
about: {
content: 'Some text'
},
overwritten: 'New text',
fruit: [{ name: 'Strawberry' }],
// @ts-ignore
car: ({ plural }) => plural(['car', 'cars'])
}

const merged = {}

deepCopy(msg1, merged)
deepCopy(msg2, merged)

expect(merged).toMatchInlineSnapshot(`
{
"about": {
"content": "Some text",
"title": "About us",
},
"bye": "Goodbye",
"car": [Function],
"fruit": [
{
"name": "Strawberry",
},
],
"hello": "Greetings",
"overwritten": "New text",
}
`)

// should not mutate source object
expect(msg1).toStrictEqual(copy1)
})