Skip to content

Commit

Permalink
fix: Make applyPatches to accept readonly Patch[] (#1094)
Browse files Browse the repository at this point in the history
* Demonstrate possible regression

* Make `Patch[]` arrays `readonly` on the outer bounds

* Limit the change to `applyPatches`

---------

Co-authored-by: Minh Nguyen <2852660+NMinhNguyen@users.noreply.github.com>
  • Loading branch information
Andarist and NMinhNguyen committed Apr 27, 2024
1 parent 073d634 commit 4da2e0d
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 4 deletions.
17 changes: 16 additions & 1 deletion __tests__/produce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import {
Immutable,
Immer,
enableMapSet,
enablePatches
enablePatches,
produceWithPatches
} from "../src/immer"

enableMapSet()
Expand Down Expand Up @@ -162,6 +163,20 @@ it("can apply patches", () => {
expect(applyPatches({}, patches)).toEqual({x: 4})
})

it("can apply readonly patches", () => {
const [, patches]: readonly [
{
x: number
},
readonly Patch[],
readonly Patch[]
] = produceWithPatches({x: 3}, d => {
d.x++
})

expect(applyPatches({}, patches)).toEqual({x: 4})
})

describe("curried producer", () => {
it("supports rest parameters", () => {
type State = {readonly a: 1}
Expand Down
2 changes: 1 addition & 1 deletion src/core/immerClass.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ export class Immer implements ProducersFns {
this.useStrictShallowCopy_ = value
}

applyPatches<T extends Objectish>(base: T, patches: Patch[]): T {
applyPatches<T extends Objectish>(base: T, patches: readonly Patch[]): T {
// If a patch replaces the entire state, take that replacement as base
// before applying patches
let i: number
Expand Down
2 changes: 1 addition & 1 deletion src/plugins/patches.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ export function enablePatches() {
})
}

function applyPatches_<T>(draft: T, patches: Patch[]): T {
function applyPatches_<T>(draft: T, patches: readonly Patch[]): T {
patches.forEach(patch => {
const {path, op} = patch

Expand Down
2 changes: 1 addition & 1 deletion src/utils/plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const plugins: {
patches: Patch[],
inversePatches: Patch[]
): void
applyPatches_<T>(draft: T, patches: Patch[]): T
applyPatches_<T>(draft: T, patches: readonly Patch[]): T
}
MapSet?: {
proxyMap_<T extends AnyMap>(target: T, parent?: ImmerState): T
Expand Down

0 comments on commit 4da2e0d

Please sign in to comment.