feature: Always freeze by default (#702)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
BREAKING CHANGE: always freeze by default, even in production mode. Use `setAutoFreeze(process.env.NODE_ENV !== 'production')` for the old behavior. See https://github.com/immerjs/immer/issues/687#issuecomment-728881754 for the rationale. Fixes #649, #681, #687
authored by Michel Weststrate · committed by GitHub · parent 6c62eec · Browse files · 11 files·+44 added−28 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+44 added−28 removed
- tests:+20 added−1 removed
- other:+24 added−27 removed
Provenance
- Commit
a406c8f- Tree
fa12b4c- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
6c62eec
11 files changed+44 added−28 removed
modified:__tests__/frozen.js+20 added-1 removed
1 "use strict"2 import produce, {3 setUseProxies,4 setAutoFreeze,5- enableAllPlugins5+ enableAllPlugins,6+ freeze7 } from "../src/immer"8 9 enableAllPlugins()10 235 unmodified lines246 expect(state2.ref[symbol].x).toBe(2)247 })248 })249 }250+251+test("freeze - shallow", () => {252+ const obj1 = {hello: {world: true}}253+ const res = freeze(obj1)254+255+ expect(res).toBe(obj1)256+ expect(Object.isFrozen(res)).toBe(true)257+ expect(Object.isFrozen(res.hello)).toBe(false)258+})259+260+test("freeze - deep", () => {261+ const obj1 = {hello: {world: true}}262+ const res = freeze(obj1, true)263+264+ expect(res).toBe(obj1)265+ expect(Object.isFrozen(res)).toBe(true)266+ expect(Object.isFrozen(res.hello)).toBe(true)267+})modified:docs/api.md+2 added-1 removed
19 unmodified lines2021222324252627282 unmodified lines3132333434353637383913 unmodified lines19 unmodified lines| `enableES5()` | Enables support for older JavaScript engines, such as Internet Explorer and React Native | [Installation](installation#pick-your-immer-version) || `enableMapSet()` | Enables support for `Map` and `Set` collections. | [Installation](installation#pick-your-immer-version) || `enablePatches()` | Enables support for JSON patches. | [Installation](installation#pick-your-immer-version) || `finishDraft` | Given an draft created using `createDraft`, seals the draft and produces and returns the next immutable state that captures all the changes | [Async](async.md) || `freeze(obj, deep?)` | Freezes draftable objects. Returns the original object. By default freezes shallowly, but if the second argument is `true` it will freeze recursively. || `Immer` | constructor that can be used to create a second "immer" instance (exposing all APIs listed in this instance), that doesn't share its settings with global instance. || `immerable` | Symbol that can be added to a constructor or prototype, to indicate that Immer should treat the class as something that can be safely drafted | [Classes](complex-objects.md) || `Immutable<T>` | Exposed TypeScript type to convert mutable types to immutable types | || `isDraft` | Returns true if the given object is a draft object | |2 unmodified lines| `original` | Given a draft object (doesn't have to be a tree root), returns the original object at the same path in the original state tree, if present | [Original](original.md) || `Patch` | Exposed TypeScript type, describes the shape of an (inverse) patch object | [Patches](patches.md) || `produce` | The core API of Immer, also exposed as the `default` export | [Produce](produce.md) || `produceWithPatches` | Works the same as `produce`, but instead of just returning the produced object, it returns a tuple, consisting of `[result, patches, inversePatches]`. | [Patches](patches.md) || `setAutoFreeze` | Enables / disables automatic freezing of the trees produces. By default enabled in development builds | [Freezing](freezing.md) || `setAutoFreeze` | Enables / disables automatic freezing of the trees produces. By default enabled. | [Freezing](freezing.md) || `setUseProxies` | Can be used to disable or force the use of `Proxy` objects. Useful when filing bug reports. | |
## Importing immer
13 unmodified linesmodified:docs/freezing.md+3 added-1 removed
14 unmodified lines15161718191920212223242514 unmodified lines </div> <a style="font-style:italic;padding:5px;margin:5px;" href="https://egghead.io/lessons/javascript-produces-immutable-data-and-avoid-unnecessary-creation-of-new-data-trees-with-immer">Hosted on egghead.io</a></details>
Immer automatically freezes any state trees that are modified using `produce`. This protects against accidental modifications of the state tree outside of a producer. This comes with a performance impact, so it is recommended to disable this option in production. By default, it is turned on during local development and turned off in production. Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.Immer automatically freezes any state trees that are modified using `produce`. This protects against accidental modifications of the state tree outside of a producer. In most cases this provides the most optimal behavior, but `setAutoFreeze(true / false)` can be used to explicitly turn this feature on or off.
Immer will never freeze (the contents of) non-enumerable, non-own or symbolic properties, unless their content was drafted.
_⚠️ Immer freezes everything recursively, for large data objects that won't be changed in the future this might be over-kill, in that case it can be more efficient to shallowly pre-freeze data using the `freeze` utility.⚠️_
_⚠️ If auto freezing is enabled, recipes are not entirely side-effect free: Any plain object or array that ends up in the produced result, will be frozen, even when these objects were not frozen before the start of the producer! ⚠️_modified:docs/performance.md+1 added-1 removed
42 unmodified lines434445464747484950518 unmodified lines42 unmodified lines## Performance tips
### Pre-freeze data
When adding a large data set to the state tree in an Immer producer (for example data received from a JSON endpoint), it is worth to call `Object.freeze(json)` on the root of the data to be added first. This will allow Immer to add the new data to the tree faster, as it will skip freezing it, or searching the tree for any changes (drafts) that might be made.When adding a large data set to the state tree in an Immer producer (for example data received from a JSON endpoint), it is worth to call `freeze(json)` on the root of the data to be added first. This will allow Immer to add the new data to the tree faster, as it will skip _recursively_ freezing it, or searching the new data for any changes (drafts) that might be made.
### You can always opt-out
Realize that immer is opt-in everywhere, so it is perfectly fine to manually write super performance critical reducers, and use immer for all the normal ones. Even from within a producer you opt-out from Immer for certain parts of your logic by using utilies `original` or `current` and perform some of your operations on plain JavaScript objects.8 unmodified linesmodified:src/core/immerClass.ts+1 added-2 removed
15 unmodified lines16 createProxyProxy,17 getPlugin,18 die,19 hasProxies,20- isMinified,20 enterScope,21 revokeScope,22 leaveScope,23 usePatchesInScope,10 unmodified lines34 35 export class Immer implements ProducersFns {36 useProxies_: boolean = hasProxies37 39- autoFreeze_: boolean = __DEV__ ? true /* istanbul ignore next */ : !isMinified38+ autoFreeze_: boolean = true39 40 constructor(config?: {useProxies?: boolean; autoFreeze?: boolean}) {41 if (typeof config?.useProxies === "boolean")42 this.setUseProxies(config!.useProxies)185 unmodified linesmodified:src/types/index.js.flow+2 added
107 unmodified lines108 declare export function enableES5(): void109 declare export function enableMapSet(): void110 declare export function enablePatches(): void111 declare export function enableAllPlugins(): void112+113+declare export function freeze<T>(obj: T, freeze?: boolean): Tmodified:src/utils/common.ts+11 added-2 removed
177 unmodified lines178 }179 return Object.create(Object.getPrototypeOf(base), descriptors)180 }181 182+/**183+ * Freezes draftable objects. Returns the original object.184+ * By default freezes shallowly, but if the second argument is `true` it will freeze recursively.185+ *186+ * @param obj187+ * @param deep188+ */189+export function freeze<T>(obj: T, deep?: boolean): T182-export function freeze(obj: any, deep: boolean): void {183- if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return190+export function freeze<T>(obj: any, deep: boolean = false): T {191+ if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj192 if (getArchtype(obj) > 1 /* Map or Set */) {193 obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any194 }195 Object.freeze(obj)196 if (deep) each(obj, (key, value) => freeze(value, true), true)197+ return obj198 }199 200 function dontMutateFrozenCollections() {201 die(2)7 unmodified linesmodified:src/utils/env.ts-4 removed
10 unmodified lines11121314151617181516171829 unmodified lines10 unmodified lines typeof Proxy !== "undefined" && typeof Proxy.revocable !== "undefined" && typeof Reflect !== "undefined"
/* istanbul ignore next */function mini() {}export const isMinified = mini.name !== "mini"
/** * The sentinel value returned by producers to replace the draft with undefined. */export const NOTHING: Nothing = hasSymbol29 unmodified linesmodified:src/immer.ts+2 added-1 removed
14 unmodified lines15 current,16 isDraft,17 isDraftable,18 NOTHING as nothing,19- DRAFTABLE as immerable19+ DRAFTABLE as immerable,20+ freeze21 } from "./internal"22 23 const immer = new Immer()24 93 unmodified linesmodified:website/static/css/custom.css-13 removed
20 unmodified lines21 22 a:hover {23 text-decoration: underline;24 }25-26-/* BLM */27-.slidingNav::before {28- content: "Black Lives Matter";29- position: fixed;30- left: 0;31- width: 100vw;32- top: 13px;33- text-align: center;34- pointer-events: none;35- text-transform: uppercase;36- font-weight: bold;37-}modified:.travis.yml+2 added-2 removed
1 language: node_js2 node_js:3- # - "10.18.1"4- - "node"3+ - "10.18.1"4+ # - "node"5 env:6 - NODE_ENV=TEST7 cache:8 yarn: true16 unmodified lines