1- import { Draft , Options , Patches , DraftType , Operation } from './interface' ;
1+ import { Operation , DraftType } from './interface' ;
2+ import type {
3+ Draft ,
4+ Patches ,
5+ ApplyMutableOptions ,
6+ ApplyOptions ,
7+ ApplyResult ,
8+ } from './interface' ;
29import { deepClone , get , getType , isDraft , unescapePath } from './utils' ;
310import { create } from './create' ;
411
@@ -23,14 +30,11 @@ import { create } from './create';
2330 * expect(state).toEqual(apply(baseState, patches));
2431 * ```
2532 */
26- export function apply < T extends object , F extends boolean = false > (
27- state : T ,
28- patches : Patches ,
29- applyOptions ?: Pick <
30- Options < boolean , F > ,
31- Exclude < keyof Options < boolean , F > , 'enablePatches' >
32- >
33- ) {
33+ export function apply <
34+ T extends object ,
35+ F extends boolean = false ,
36+ A extends ApplyOptions < F > = ApplyOptions < F > ,
37+ > ( state : T , patches : Patches , applyOptions ?: A ) : ApplyResult < T , F , A > {
3438 let i : number ;
3539 for ( i = patches . length - 1 ; i >= 0 ; i -= 1 ) {
3640 const { value, op, path } = patches [ i ] ;
@@ -45,7 +49,7 @@ export function apply<T extends object, F extends boolean = false>(
4549 if ( i > - 1 ) {
4650 patches = patches . slice ( i + 1 ) ;
4751 }
48- const mutate = ( draft : Draft < T > ) => {
52+ const mutate = ( draft : Draft < T > | T ) => {
4953 patches . forEach ( ( patch ) => {
5054 const { path : _path , op } = patch ;
5155 const path = unescapePath ( _path ) ;
@@ -119,15 +123,28 @@ export function apply<T extends object, F extends boolean = false>(
119123 }
120124 } ) ;
121125 } ;
126+ if ( ( applyOptions as ApplyMutableOptions ) ?. mutable ) {
127+ if ( __DEV__ ) {
128+ if (
129+ Object . keys ( applyOptions ! ) . filter ( ( key ) => key !== 'mutable' ) . length
130+ ) {
131+ console . warn (
132+ 'The "mutable" option is not allowed to be used with other options.'
133+ ) ;
134+ }
135+ }
136+ mutate ( state ) ;
137+ return undefined as ApplyResult < T , F , A > ;
138+ }
122139 if ( isDraft ( state ) ) {
123140 if ( applyOptions !== undefined ) {
124141 throw new Error ( `Cannot apply patches with options to a draft.` ) ;
125142 }
126143 mutate ( state as Draft < T > ) ;
127- return state ;
144+ return state as ApplyResult < T , F , A > ;
128145 }
129146 return create < T , F > ( state , mutate , {
130147 ...applyOptions ,
131148 enablePatches : false ,
132- } ) ;
149+ } ) as any ;
133150}
0 commit comments