Introduce `class_only` strict mode setting
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by Michel Weststrate · parent 7f1b3b9 · Browse files · 4 files·+108 added−64 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+108 added−64 removed
- tests:+68 added−31 removed
- other:+40 added−33 removed
Provenance
- Commit
85a8f7b- Tree
b4a47c9- Author
Michel Weststrate <mweststrate@fb.com>- Committer
Michel Weststrate <mweststrate@fb.com>- Parent
7f1b3b9
4 files changed+108 added−64 removed
modified:__tests__/not-strict-copy.ts+68 added-31 removed
11234567345891011121378910111415161718192021222324252627282930131415161718192031222324323334352627282930363738394041424344454647484950515253545556575859606162636465666768697071723233343536377374import {produce, setUseStrictShallowCopy} from "../src/immer"import { immerable, produce, setUseStrictShallowCopy, setAutoFreeze} from "../src/immer"
describe("setUseStrictShallowCopy(true)", () => { test("keep descriptors", () => { setUseStrictShallowCopy(true)describe.each([true, false, "class_only" as const])( "setUseStrictShallowCopy(true)", (strictMode: boolean | "class_only") => { test("keep descriptors, mode: " + strictMode, () => { setUseStrictShallowCopy(strictMode)
const base: Record<string, unknown> = {} Object.defineProperty(base, "foo", { value: "foo", writable: false, configurable: false const base: Record<string, unknown> = {} Object.defineProperty(base, "foo", { value: "foo", writable: false, configurable: false }) const copy = produce(base, (draft: any) => { draft.bar = "bar" }) if (strictMode === true) { expect(Object.getOwnPropertyDescriptor(copy, "foo")).toStrictEqual( Object.getOwnPropertyDescriptor(base, "foo") ) } else { expect(Object.getOwnPropertyDescriptor(copy, "foo")).toBeUndefined() } }) const copy = produce(base, (draft: any) => { draft.bar = "bar" }) expect(Object.getOwnPropertyDescriptor(copy, "foo")).toStrictEqual( Object.getOwnPropertyDescriptor(base, "foo") ) })})
describe("setUseStrictShallowCopy(false)", () => { test("ignore descriptors", () => { setUseStrictShallowCopy(false) test("keep non-enumerable class descriptors, mode: " + strictMode, () => { setUseStrictShallowCopy(strictMode) setAutoFreeze(false)
const base: Record<string, unknown> = {} Object.defineProperty(base, "foo", { value: "foo", writable: false, configurable: false class X { [immerable] = true foo = "foo" bar!: string constructor() { Object.defineProperty(this, "bar", { get() { return this.foo + "bar" }, configurable: false, enumerable: false }) }
get baz() { return this.foo + "baz" } }
const copy = produce(new X(), (draft: any) => { draft.foo = "FOO" })
const strict = strictMode === true || strictMode === "class_only"
// descriptors on the prototype are unaffected, so this is still a getter expect(copy.baz).toBe("FOObaz") // descriptors on the instance are found, even when non-enumerable, and read during copy // so new values won't be reflected expect(copy.bar).toBe(strict ? "foobar" : undefined)
copy.foo = "fluff" // not updated, the own prop became a value expect(copy.bar).toBe(strict ? "foobar" : undefined) // updated, it is still a getter expect(copy.baz).toBe("fluffbaz") }) const copy = produce(base, (draft: any) => { draft.bar = "bar" }) expect(Object.getOwnPropertyDescriptor(copy, "foo")).toBeUndefined() })}) })modified:src/core/immerClass.ts+6 added-3 removed
31 unmodified lines32 }33 34 export class Immer implements ProducersFns {35 autoFreeze_: boolean = true36- useStrictShallowCopy_: boolean = false36+ useStrictShallowCopy_: boolean | "class_only" = false37 38- constructor(config?: {autoFreeze?: boolean; useStrictShallowCopy?: boolean}) {38+ constructor(config?: {39+ autoFreeze?: boolean40+ useStrictShallowCopy?: boolean | "class_only"41+ }) {42 if (typeof config?.autoFreeze === "boolean")43 this.setAutoFreeze(config!.autoFreeze)44 if (typeof config?.useStrictShallowCopy === "boolean")45 this.setUseStrictShallowCopy(config!.useStrictShallowCopy)119 unmodified lines165 * Pass true to enable strict shallow copy.166 *167 * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.168 */166- setUseStrictShallowCopy(value: boolean) {169+ setUseStrictShallowCopy(value: boolean | "class_only") {170 this.useStrictShallowCopy_ = value171 }172 173 applyPatches<T extends Objectish>(base: T, patches: Patch[]): T {43 unmodified linesmodified:src/utils/common.ts+30 added-26 removed
138 unmodified lines139 return state.copy_ || state.base_140 }141 142 /*#__PURE__*/143-export function shallowCopy(base: any, strict: boolean) {143+export function shallowCopy(base: any, strict: boolean | "class_only") {144 if (isMap(base)) {145 return new Map(base)146 }147 if (isSet(base)) {148 return new Set(base)149 }150 if (Array.isArray(base)) return Array.prototype.slice.call(base)151 152- if (!strict) {152+ const isPlain = isPlainObject(base)153+154+ if (strict === true || (strict === "class_only" && !isPlain)) {155+ // Perform a strict copy156+ const descriptors = Object.getOwnPropertyDescriptors(base)157+ delete descriptors[DRAFT_STATE as any]158+ let keys = Reflect.ownKeys(descriptors)159+ for (let i = 0; i < keys.length; i++) {160+ const key: any = keys[i]161+ const desc = descriptors[key]162+ if (desc.writable === false) {163+ desc.writable = true164+ desc.configurable = true165+ }166+ // like object.assign, we will read any _own_, get/set accessors. This helps in dealing167+ // with libraries that trap values, like mobx or vue168+ // unlike object.assign, non-enumerables will be copied as well169+ if (desc.get || desc.set)170+ descriptors[key] = {171+ configurable: true,172+ writable: true, // could live with !!desc.set as well here...173+ enumerable: desc.enumerable,174+ value: base[key]175+ }176+ }177+ return Object.create(getPrototypeOf(base), descriptors)178+ } else {179+ // perform a sloppy copy180 const proto = getPrototypeOf(base)154- if (proto !== null && isPlainObject(base)) {181+ if (proto !== null && isPlain) {182 return {...base} // assumption: better inner class optimization than the assign below183 }184 const obj = Object.create(proto)185 return Object.assign(obj, base)186 }160-161- const descriptors = Object.getOwnPropertyDescriptors(base)162- delete descriptors[DRAFT_STATE as any]163- let keys = Reflect.ownKeys(descriptors)164- for (let i = 0; i < keys.length; i++) {165- const key: any = keys[i]166- const desc = descriptors[key]167- if (desc.writable === false) {168- desc.writable = true169- desc.configurable = true170- }171- // like object.assign, we will read any _own_, get/set accessors. This helps in dealing172- // with libraries that trap values, like mobx or vue173- // unlike object.assign, non-enumerables will be copied as well174- if (desc.get || desc.set)175- descriptors[key] = {176- configurable: true,177- writable: true, // could live with !!desc.set as well here...178- enumerable: desc.enumerable,179- value: base[key]180- }181- }182- return Object.create(getPrototypeOf(base), descriptors)187 }188 189 /**190 * Freezes draftable objects. Returns the original object.26 unmodified linesmodified:website/docs/complex-objects.md+4 added-4 removed
5 unmodified lines678910111011121344 unmodified lines58596061646263666465666768697071727374755 unmodified lines<center><div data-ea-publisher="immerjs" data-ea-type="image" className="horizontal bordered"></div></center>
By default, Immer does not strictly handle Plain object's non-eumerable properties such as getters/setters for performance reason. If you want this behavior to be strict, you can opt-in with `useStrictShallowCopy(true)`.
Plain objects (objects without a prototype), arrays, `Map`s and `Set`s are always drafted by Immer. Every other object must use the `immerable` symbol to mark itself as compatible with Immer. When one of these objects is mutated within a producer, its prototype is preserved between copies.
```jsimport {immerable} from "immer"44 unmodified lines
The semantics on how classes are drafted are as follows:
1. A draft of a class is a fresh object but with the same prototype as the original object.1. When creating a draft, Immer will copy all _own_ properties from the base to the draft.This includes non-enumerable and symbolic properties.1. When creating a draft, Immer will copy all _own_ properties from the base to the draft.This includes (in strict mode) non-enumerable and symbolic properties.1. _Own_ getters will be invoked during the copy process, just like `Object.assign` would.1. Inherited getters and methods will remain as is and be inherited by the draft.1. Inherited getters and methods will remain as is and be inherited by the draft, as they are stored on the prototype which is untouched.1. Immer will not invoke constructor functions.1. The final instance will be constructed with the same mechanism as the draft was created.1. Only getters that have a setter as well will be writable in the draft, as otherwise the value can't be copied back.
Because Immer will dereference own getters of objects into normal properties, it is possible to use objects that use getter/setter traps on their fields, like MobX and Vue do.
Note that, by default, Immer does not strictly handle object's non-enumerable properties such as getters/setters for performance reason. If you want this behavior to be strict, you can opt-in with `useStrictShallowCopy(config)`. Use `true` to always copy strict, or `"class_only"` to only copy class instances strictly but use the faster loose copying for plain objects. The default is `false`. (Remember, regardless of strict mode, own getters / setters are always copied _by value_. There is currently no config to copy descriptors as-is. Feature request / PR welcome).
Immer does not support exotic / engine native objects such as DOM Nodes or Buffers, nor is subclassing Map, Set or arrays supported and the `immerable` symbol can't be used on them.
So when working for example with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.