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

Throw when accessing non-draftables in strict mode #715

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

Gelio
Copy link
Contributor

@Gelio Gelio commented Dec 3, 2020

This MR attempts to implement the idea from #686

It adds a strictMode (false by default, enabled by setStrictMode or passing strictMode in Immer constructor) that makes it so that accessing non-draftable properties will throw an error, unless the access is made in an unsafe callback.

Fixes #686

Example

class Foo {}

setStrictMode(true)

produce({ instance: new Foo() }, draft => {
  unsafe(() => {
    draft.instance.abc = 1; // works fine in unsafe
  });

  console.log(draft.instance); // will throw, because access not wrapped in unsafe
});

See the tests for more examples

Limitations

I tried to make it as compliant with existing functionalities as possible. I was not able to make it fully ES5-compliant. There are a few tests that fail when strict mode is enabled in base.js tests.

I do not have enough expertise to fully fix them. Suggestions are welcome

Gelio added 3 commits December 3, 2020 23:10
In strict mode, accessing a non-draftable property will throw
One can use the unsafe function to perform such operations

Fixes immerjs#686
@codesandbox-ci
Copy link

codesandbox-ci bot commented Dec 3, 2020

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Latest deployment of this branch, based on commit c60c592:

Sandbox Source
Immer sandbox Configuration

@mweststrate
Copy link
Collaborator

Really awesome! Thanks for doing this :). Looks really promising, just up front a notif that it will probably take me a while to review 😅

@Gelio
Copy link
Contributor Author

Gelio commented Dec 7, 2020

@mweststrate I'm glad you like it! Take your time to review it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Idea: forbid grabbing non draftables in strict mode
2 participants