immer.cjs.development.js 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var _ref;
  4. // Should be no imports here!
  5. // Some things that should be evaluated before all else...
  6. // We only want to know if non-polyfilled symbols are available
  7. var hasSymbol = typeof Symbol !== "undefined" && typeof
  8. /*#__PURE__*/
  9. Symbol("x") === "symbol";
  10. var hasMap = typeof Map !== "undefined";
  11. var hasSet = typeof Set !== "undefined";
  12. var hasProxies = typeof Proxy !== "undefined" && typeof Proxy.revocable !== "undefined" && typeof Reflect !== "undefined";
  13. /**
  14. * The sentinel value returned by producers to replace the draft with undefined.
  15. */
  16. var NOTHING = hasSymbol ?
  17. /*#__PURE__*/
  18. Symbol.for("immer-nothing") : (_ref = {}, _ref["immer-nothing"] = true, _ref);
  19. /**
  20. * To let Immer treat your class instances as plain immutable objects
  21. * (albeit with a custom prototype), you must define either an instance property
  22. * or a static property on each of your custom classes.
  23. *
  24. * Otherwise, your class instance will never be drafted, which means it won't be
  25. * safe to mutate in a produce callback.
  26. */
  27. var DRAFTABLE = hasSymbol ?
  28. /*#__PURE__*/
  29. Symbol.for("immer-draftable") : "__$immer_draftable";
  30. var DRAFT_STATE = hasSymbol ?
  31. /*#__PURE__*/
  32. Symbol.for("immer-state") : "__$immer_state"; // Even a polyfilled Symbol might provide Symbol.iterator
  33. var iteratorSymbol = typeof Symbol != "undefined" && Symbol.iterator || "@@iterator";
  34. var errors = {
  35. 0: "Illegal state",
  36. 1: "Immer drafts cannot have computed properties",
  37. 2: "This object has been frozen and should not be mutated",
  38. 3: function _(data) {
  39. return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + data;
  40. },
  41. 4: "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",
  42. 5: "Immer forbids circular references",
  43. 6: "The first or second argument to `produce` must be a function",
  44. 7: "The third argument to `produce` must be a function or undefined",
  45. 8: "First argument to `createDraft` must be a plain object, an array, or an immerable object",
  46. 9: "First argument to `finishDraft` must be a draft returned by `createDraft`",
  47. 10: "The given draft is already finalized",
  48. 11: "Object.defineProperty() cannot be used on an Immer draft",
  49. 12: "Object.setPrototypeOf() cannot be used on an Immer draft",
  50. 13: "Immer only supports deleting array indices",
  51. 14: "Immer only supports setting array indices and the 'length' property",
  52. 15: function _(path) {
  53. return "Cannot apply patch, path doesn't resolve: " + path;
  54. },
  55. 16: 'Sets cannot have "replace" patches.',
  56. 17: function _(op) {
  57. return "Unsupported patch operation: " + op;
  58. },
  59. 18: function _(plugin) {
  60. return "The plugin for '" + plugin + "' has not been loaded into Immer. To enable the plugin, import and call `enable" + plugin + "()` when initializing your application.";
  61. },
  62. 20: "Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available",
  63. 21: function _(thing) {
  64. return "produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '" + thing + "'";
  65. },
  66. 22: function _(thing) {
  67. return "'current' expects a draft, got: " + thing;
  68. },
  69. 23: function _(thing) {
  70. return "'original' expects a draft, got: " + thing;
  71. },
  72. 24: "Patching reserved attributes like __proto__, prototype and constructor is not allowed"
  73. };
  74. function die(error) {
  75. for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  76. args[_key - 1] = arguments[_key];
  77. }
  78. {
  79. var e = errors[error];
  80. var msg = !e ? "unknown error nr: " + error : typeof e === "function" ? e.apply(null, args) : e;
  81. throw new Error("[Immer] " + msg);
  82. }
  83. }
  84. /** Returns true if the given value is an Immer draft */
  85. /*#__PURE__*/
  86. function isDraft(value) {
  87. return !!value && !!value[DRAFT_STATE];
  88. }
  89. /** Returns true if the given value can be drafted by Immer */
  90. /*#__PURE__*/
  91. function isDraftable(value) {
  92. var _value$constructor;
  93. if (!value) return false;
  94. return isPlainObject(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!((_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor[DRAFTABLE]) || isMap(value) || isSet(value);
  95. }
  96. var objectCtorString =
  97. /*#__PURE__*/
  98. Object.prototype.constructor.toString();
  99. /*#__PURE__*/
  100. function isPlainObject(value) {
  101. if (!value || typeof value !== "object") return false;
  102. var proto = Object.getPrototypeOf(value);
  103. if (proto === null) {
  104. return true;
  105. }
  106. var Ctor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor;
  107. if (Ctor === Object) return true;
  108. return typeof Ctor == "function" && Function.toString.call(Ctor) === objectCtorString;
  109. }
  110. function original(value) {
  111. if (!isDraft(value)) die(23, value);
  112. return value[DRAFT_STATE].base_;
  113. }
  114. /*#__PURE__*/
  115. var ownKeys = typeof Reflect !== "undefined" && Reflect.ownKeys ? Reflect.ownKeys : typeof Object.getOwnPropertySymbols !== "undefined" ? function (obj) {
  116. return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj));
  117. } :
  118. /* istanbul ignore next */
  119. Object.getOwnPropertyNames;
  120. var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(target) {
  121. // Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274
  122. var res = {};
  123. ownKeys(target).forEach(function (key) {
  124. res[key] = Object.getOwnPropertyDescriptor(target, key);
  125. });
  126. return res;
  127. };
  128. function each(obj, iter, enumerableOnly) {
  129. if (enumerableOnly === void 0) {
  130. enumerableOnly = false;
  131. }
  132. if (getArchtype(obj) === 0
  133. /* Object */
  134. ) {
  135. (enumerableOnly ? Object.keys : ownKeys)(obj).forEach(function (key) {
  136. if (!enumerableOnly || typeof key !== "symbol") iter(key, obj[key], obj);
  137. });
  138. } else {
  139. obj.forEach(function (entry, index) {
  140. return iter(index, entry, obj);
  141. });
  142. }
  143. }
  144. /*#__PURE__*/
  145. function getArchtype(thing) {
  146. /* istanbul ignore next */
  147. var state = thing[DRAFT_STATE];
  148. return state ? state.type_ > 3 ? state.type_ - 4 // cause Object and Array map back from 4 and 5
  149. : state.type_ // others are the same
  150. : Array.isArray(thing) ? 1
  151. /* Array */
  152. : isMap(thing) ? 2
  153. /* Map */
  154. : isSet(thing) ? 3
  155. /* Set */
  156. : 0
  157. /* Object */
  158. ;
  159. }
  160. /*#__PURE__*/
  161. function has(thing, prop) {
  162. return getArchtype(thing) === 2
  163. /* Map */
  164. ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);
  165. }
  166. /*#__PURE__*/
  167. function get(thing, prop) {
  168. // @ts-ignore
  169. return getArchtype(thing) === 2
  170. /* Map */
  171. ? thing.get(prop) : thing[prop];
  172. }
  173. /*#__PURE__*/
  174. function set(thing, propOrOldValue, value) {
  175. var t = getArchtype(thing);
  176. if (t === 2
  177. /* Map */
  178. ) thing.set(propOrOldValue, value);else if (t === 3
  179. /* Set */
  180. ) {
  181. thing.add(value);
  182. } else thing[propOrOldValue] = value;
  183. }
  184. /*#__PURE__*/
  185. function is(x, y) {
  186. // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js
  187. if (x === y) {
  188. return x !== 0 || 1 / x === 1 / y;
  189. } else {
  190. return x !== x && y !== y;
  191. }
  192. }
  193. /*#__PURE__*/
  194. function isMap(target) {
  195. return hasMap && target instanceof Map;
  196. }
  197. /*#__PURE__*/
  198. function isSet(target) {
  199. return hasSet && target instanceof Set;
  200. }
  201. /*#__PURE__*/
  202. function latest(state) {
  203. return state.copy_ || state.base_;
  204. }
  205. /*#__PURE__*/
  206. function shallowCopy(base) {
  207. if (Array.isArray(base)) return Array.prototype.slice.call(base);
  208. var descriptors = getOwnPropertyDescriptors(base);
  209. delete descriptors[DRAFT_STATE];
  210. var keys = ownKeys(descriptors);
  211. for (var i = 0; i < keys.length; i++) {
  212. var key = keys[i];
  213. var desc = descriptors[key];
  214. if (desc.writable === false) {
  215. desc.writable = true;
  216. desc.configurable = true;
  217. } // like object.assign, we will read any _own_, get/set accessors. This helps in dealing
  218. // with libraries that trap values, like mobx or vue
  219. // unlike object.assign, non-enumerables will be copied as well
  220. if (desc.get || desc.set) descriptors[key] = {
  221. configurable: true,
  222. writable: true,
  223. enumerable: desc.enumerable,
  224. value: base[key]
  225. };
  226. }
  227. return Object.create(Object.getPrototypeOf(base), descriptors);
  228. }
  229. function freeze(obj, deep) {
  230. if (deep === void 0) {
  231. deep = false;
  232. }
  233. if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj;
  234. if (getArchtype(obj) > 1
  235. /* Map or Set */
  236. ) {
  237. obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections;
  238. }
  239. Object.freeze(obj);
  240. if (deep) each(obj, function (key, value) {
  241. return freeze(value, true);
  242. }, true);
  243. return obj;
  244. }
  245. function dontMutateFrozenCollections() {
  246. die(2);
  247. }
  248. function isFrozen(obj) {
  249. if (obj == null || typeof obj !== "object") return true; // See #600, IE dies on non-objects in Object.isFrozen
  250. return Object.isFrozen(obj);
  251. }
  252. /** Plugin utilities */
  253. var plugins = {};
  254. function getPlugin(pluginKey) {
  255. var plugin = plugins[pluginKey];
  256. if (!plugin) {
  257. die(18, pluginKey);
  258. } // @ts-ignore
  259. return plugin;
  260. }
  261. function loadPlugin(pluginKey, implementation) {
  262. if (!plugins[pluginKey]) plugins[pluginKey] = implementation;
  263. }
  264. var currentScope;
  265. function getCurrentScope() {
  266. if ( !currentScope) die(0);
  267. return currentScope;
  268. }
  269. function createScope(parent_, immer_) {
  270. return {
  271. drafts_: [],
  272. parent_: parent_,
  273. immer_: immer_,
  274. // Whenever the modified draft contains a draft from another scope, we
  275. // need to prevent auto-freezing so the unowned draft can be finalized.
  276. canAutoFreeze_: true,
  277. unfinalizedDrafts_: 0
  278. };
  279. }
  280. function usePatchesInScope(scope, patchListener) {
  281. if (patchListener) {
  282. getPlugin("Patches"); // assert we have the plugin
  283. scope.patches_ = [];
  284. scope.inversePatches_ = [];
  285. scope.patchListener_ = patchListener;
  286. }
  287. }
  288. function revokeScope(scope) {
  289. leaveScope(scope);
  290. scope.drafts_.forEach(revokeDraft); // @ts-ignore
  291. scope.drafts_ = null;
  292. }
  293. function leaveScope(scope) {
  294. if (scope === currentScope) {
  295. currentScope = scope.parent_;
  296. }
  297. }
  298. function enterScope(immer) {
  299. return currentScope = createScope(currentScope, immer);
  300. }
  301. function revokeDraft(draft) {
  302. var state = draft[DRAFT_STATE];
  303. if (state.type_ === 0
  304. /* ProxyObject */
  305. || state.type_ === 1
  306. /* ProxyArray */
  307. ) state.revoke_();else state.revoked_ = true;
  308. }
  309. function processResult(result, scope) {
  310. scope.unfinalizedDrafts_ = scope.drafts_.length;
  311. var baseDraft = scope.drafts_[0];
  312. var isReplaced = result !== undefined && result !== baseDraft;
  313. if (!scope.immer_.useProxies_) getPlugin("ES5").willFinalizeES5_(scope, result, isReplaced);
  314. if (isReplaced) {
  315. if (baseDraft[DRAFT_STATE].modified_) {
  316. revokeScope(scope);
  317. die(4);
  318. }
  319. if (isDraftable(result)) {
  320. // Finalize the result in case it contains (or is) a subset of the draft.
  321. result = finalize(scope, result);
  322. if (!scope.parent_) maybeFreeze(scope, result);
  323. }
  324. if (scope.patches_) {
  325. getPlugin("Patches").generateReplacementPatches_(baseDraft[DRAFT_STATE].base_, result, scope.patches_, scope.inversePatches_);
  326. }
  327. } else {
  328. // Finalize the base draft.
  329. result = finalize(scope, baseDraft, []);
  330. }
  331. revokeScope(scope);
  332. if (scope.patches_) {
  333. scope.patchListener_(scope.patches_, scope.inversePatches_);
  334. }
  335. return result !== NOTHING ? result : undefined;
  336. }
  337. function finalize(rootScope, value, path) {
  338. // Don't recurse in tho recursive data structures
  339. if (isFrozen(value)) return value;
  340. var state = value[DRAFT_STATE]; // A plain object, might need freezing, might contain drafts
  341. if (!state) {
  342. each(value, function (key, childValue) {
  343. return finalizeProperty(rootScope, state, value, key, childValue, path);
  344. }, true // See #590, don't recurse into non-enumerable of non drafted objects
  345. );
  346. return value;
  347. } // Never finalize drafts owned by another scope.
  348. if (state.scope_ !== rootScope) return value; // Unmodified draft, return the (frozen) original
  349. if (!state.modified_) {
  350. maybeFreeze(rootScope, state.base_, true);
  351. return state.base_;
  352. } // Not finalized yet, let's do that now
  353. if (!state.finalized_) {
  354. state.finalized_ = true;
  355. state.scope_.unfinalizedDrafts_--;
  356. var result = // For ES5, create a good copy from the draft first, with added keys and without deleted keys.
  357. state.type_ === 4
  358. /* ES5Object */
  359. || state.type_ === 5
  360. /* ES5Array */
  361. ? state.copy_ = shallowCopy(state.draft_) : state.copy_; // Finalize all children of the copy
  362. // For sets we clone before iterating, otherwise we can get in endless loop due to modifying during iteration, see #628
  363. // To preserve insertion order in all cases we then clear the set
  364. // And we let finalizeProperty know it needs to re-add non-draft children back to the target
  365. var resultEach = result;
  366. var isSet = false;
  367. if (state.type_ === 3
  368. /* Set */
  369. ) {
  370. resultEach = new Set(result);
  371. result.clear();
  372. isSet = true;
  373. }
  374. each(resultEach, function (key, childValue) {
  375. return finalizeProperty(rootScope, state, result, key, childValue, path, isSet);
  376. }); // everything inside is frozen, we can freeze here
  377. maybeFreeze(rootScope, result, false); // first time finalizing, let's create those patches
  378. if (path && rootScope.patches_) {
  379. getPlugin("Patches").generatePatches_(state, path, rootScope.patches_, rootScope.inversePatches_);
  380. }
  381. }
  382. return state.copy_;
  383. }
  384. function finalizeProperty(rootScope, parentState, targetObject, prop, childValue, rootPath, targetIsSet) {
  385. if ( childValue === targetObject) die(5);
  386. if (isDraft(childValue)) {
  387. var path = rootPath && parentState && parentState.type_ !== 3
  388. /* Set */
  389. && // Set objects are atomic since they have no keys.
  390. !has(parentState.assigned_, prop) // Skip deep patches for assigned keys.
  391. ? rootPath.concat(prop) : undefined; // Drafts owned by `scope` are finalized here.
  392. var res = finalize(rootScope, childValue, path);
  393. set(targetObject, prop, res); // Drafts from another scope must prevented to be frozen
  394. // if we got a draft back from finalize, we're in a nested produce and shouldn't freeze
  395. if (isDraft(res)) {
  396. rootScope.canAutoFreeze_ = false;
  397. } else return;
  398. } else if (targetIsSet) {
  399. targetObject.add(childValue);
  400. } // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.
  401. if (isDraftable(childValue) && !isFrozen(childValue)) {
  402. if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
  403. // optimization: if an object is not a draft, and we don't have to
  404. // deepfreeze everything, and we are sure that no drafts are left in the remaining object
  405. // cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.
  406. // This benefits especially adding large data tree's without further processing.
  407. // See add-data.js perf test
  408. return;
  409. }
  410. finalize(rootScope, childValue); // immer deep freezes plain objects, so if there is no parent state, we freeze as well
  411. if (!parentState || !parentState.scope_.parent_) maybeFreeze(rootScope, childValue);
  412. }
  413. }
  414. function maybeFreeze(scope, value, deep) {
  415. if (deep === void 0) {
  416. deep = false;
  417. }
  418. // we never freeze for a non-root scope; as it would prevent pruning for drafts inside wrapping objects
  419. if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {
  420. freeze(value, deep);
  421. }
  422. }
  423. /**
  424. * Returns a new draft of the `base` object.
  425. *
  426. * The second argument is the parent draft-state (used internally).
  427. */
  428. function createProxyProxy(base, parent) {
  429. var isArray = Array.isArray(base);
  430. var state = {
  431. type_: isArray ? 1
  432. /* ProxyArray */
  433. : 0
  434. /* ProxyObject */
  435. ,
  436. // Track which produce call this is associated with.
  437. scope_: parent ? parent.scope_ : getCurrentScope(),
  438. // True for both shallow and deep changes.
  439. modified_: false,
  440. // Used during finalization.
  441. finalized_: false,
  442. // Track which properties have been assigned (true) or deleted (false).
  443. assigned_: {},
  444. // The parent draft state.
  445. parent_: parent,
  446. // The base state.
  447. base_: base,
  448. // The base proxy.
  449. draft_: null,
  450. // The base copy with any updated values.
  451. copy_: null,
  452. // Called by the `produce` function.
  453. revoke_: null,
  454. isManual_: false
  455. }; // the traps must target something, a bit like the 'real' base.
  456. // but also, we need to be able to determine from the target what the relevant state is
  457. // (to avoid creating traps per instance to capture the state in closure,
  458. // and to avoid creating weird hidden properties as well)
  459. // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)
  460. // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb
  461. var target = state;
  462. var traps = objectTraps;
  463. if (isArray) {
  464. target = [state];
  465. traps = arrayTraps;
  466. }
  467. var _Proxy$revocable = Proxy.revocable(target, traps),
  468. revoke = _Proxy$revocable.revoke,
  469. proxy = _Proxy$revocable.proxy;
  470. state.draft_ = proxy;
  471. state.revoke_ = revoke;
  472. return proxy;
  473. }
  474. /**
  475. * Object drafts
  476. */
  477. var objectTraps = {
  478. get: function get(state, prop) {
  479. if (prop === DRAFT_STATE) return state;
  480. var source = latest(state);
  481. if (!has(source, prop)) {
  482. // non-existing or non-own property...
  483. return readPropFromProto(state, source, prop);
  484. }
  485. var value = source[prop];
  486. if (state.finalized_ || !isDraftable(value)) {
  487. return value;
  488. } // Check for existing draft in modified state.
  489. // Assigned values are never drafted. This catches any drafts we created, too.
  490. if (value === peek(state.base_, prop)) {
  491. prepareCopy(state);
  492. return state.copy_[prop] = createProxy(state.scope_.immer_, value, state);
  493. }
  494. return value;
  495. },
  496. has: function has(state, prop) {
  497. return prop in latest(state);
  498. },
  499. ownKeys: function ownKeys(state) {
  500. return Reflect.ownKeys(latest(state));
  501. },
  502. set: function set(state, prop
  503. /* strictly not, but helps TS */
  504. , value) {
  505. var desc = getDescriptorFromProto(latest(state), prop);
  506. if (desc === null || desc === void 0 ? void 0 : desc.set) {
  507. // special case: if this write is captured by a setter, we have
  508. // to trigger it with the correct context
  509. desc.set.call(state.draft_, value);
  510. return true;
  511. }
  512. if (!state.modified_) {
  513. // the last check is because we need to be able to distinguish setting a non-existing to undefined (which is a change)
  514. // from setting an existing property with value undefined to undefined (which is not a change)
  515. var current = peek(latest(state), prop); // special case, if we assigning the original value to a draft, we can ignore the assignment
  516. var currentState = current === null || current === void 0 ? void 0 : current[DRAFT_STATE];
  517. if (currentState && currentState.base_ === value) {
  518. state.copy_[prop] = value;
  519. state.assigned_[prop] = false;
  520. return true;
  521. }
  522. if (is(value, current) && (value !== undefined || has(state.base_, prop))) return true;
  523. prepareCopy(state);
  524. markChanged(state);
  525. }
  526. if (state.copy_[prop] === value && ( // special case: handle new props with value 'undefined'
  527. value !== undefined || prop in state.copy_) || // special case: NaN
  528. Number.isNaN(value) && Number.isNaN(state.copy_[prop])) return true; // @ts-ignore
  529. state.copy_[prop] = value;
  530. state.assigned_[prop] = true;
  531. return true;
  532. },
  533. deleteProperty: function deleteProperty(state, prop) {
  534. // The `undefined` check is a fast path for pre-existing keys.
  535. if (peek(state.base_, prop) !== undefined || prop in state.base_) {
  536. state.assigned_[prop] = false;
  537. prepareCopy(state);
  538. markChanged(state);
  539. } else {
  540. // if an originally not assigned property was deleted
  541. delete state.assigned_[prop];
  542. } // @ts-ignore
  543. if (state.copy_) delete state.copy_[prop];
  544. return true;
  545. },
  546. // Note: We never coerce `desc.value` into an Immer draft, because we can't make
  547. // the same guarantee in ES5 mode.
  548. getOwnPropertyDescriptor: function getOwnPropertyDescriptor(state, prop) {
  549. var owner = latest(state);
  550. var desc = Reflect.getOwnPropertyDescriptor(owner, prop);
  551. if (!desc) return desc;
  552. return {
  553. writable: true,
  554. configurable: state.type_ !== 1
  555. /* ProxyArray */
  556. || prop !== "length",
  557. enumerable: desc.enumerable,
  558. value: owner[prop]
  559. };
  560. },
  561. defineProperty: function defineProperty() {
  562. die(11);
  563. },
  564. getPrototypeOf: function getPrototypeOf(state) {
  565. return Object.getPrototypeOf(state.base_);
  566. },
  567. setPrototypeOf: function setPrototypeOf() {
  568. die(12);
  569. }
  570. };
  571. /**
  572. * Array drafts
  573. */
  574. var arrayTraps = {};
  575. each(objectTraps, function (key, fn) {
  576. // @ts-ignore
  577. arrayTraps[key] = function () {
  578. arguments[0] = arguments[0][0];
  579. return fn.apply(this, arguments);
  580. };
  581. });
  582. arrayTraps.deleteProperty = function (state, prop) {
  583. if ( isNaN(parseInt(prop))) die(13); // @ts-ignore
  584. return arrayTraps.set.call(this, state, prop, undefined);
  585. };
  586. arrayTraps.set = function (state, prop, value) {
  587. if ( prop !== "length" && isNaN(parseInt(prop))) die(14);
  588. return objectTraps.set.call(this, state[0], prop, value, state[0]);
  589. }; // Access a property without creating an Immer draft.
  590. function peek(draft, prop) {
  591. var state = draft[DRAFT_STATE];
  592. var source = state ? latest(state) : draft;
  593. return source[prop];
  594. }
  595. function readPropFromProto(state, source, prop) {
  596. var _desc$get;
  597. var desc = getDescriptorFromProto(source, prop);
  598. return desc ? "value" in desc ? desc.value : // This is a very special case, if the prop is a getter defined by the
  599. // prototype, we should invoke it with the draft as context!
  600. (_desc$get = desc.get) === null || _desc$get === void 0 ? void 0 : _desc$get.call(state.draft_) : undefined;
  601. }
  602. function getDescriptorFromProto(source, prop) {
  603. // 'in' checks proto!
  604. if (!(prop in source)) return undefined;
  605. var proto = Object.getPrototypeOf(source);
  606. while (proto) {
  607. var desc = Object.getOwnPropertyDescriptor(proto, prop);
  608. if (desc) return desc;
  609. proto = Object.getPrototypeOf(proto);
  610. }
  611. return undefined;
  612. }
  613. function markChanged(state) {
  614. if (!state.modified_) {
  615. state.modified_ = true;
  616. if (state.parent_) {
  617. markChanged(state.parent_);
  618. }
  619. }
  620. }
  621. function prepareCopy(state) {
  622. if (!state.copy_) {
  623. state.copy_ = shallowCopy(state.base_);
  624. }
  625. }
  626. var Immer =
  627. /*#__PURE__*/
  628. function () {
  629. function Immer(config) {
  630. var _this = this;
  631. this.useProxies_ = hasProxies;
  632. this.autoFreeze_ = true;
  633. /**
  634. * The `produce` function takes a value and a "recipe function" (whose
  635. * return value often depends on the base state). The recipe function is
  636. * free to mutate its first argument however it wants. All mutations are
  637. * only ever applied to a __copy__ of the base state.
  638. *
  639. * Pass only a function to create a "curried producer" which relieves you
  640. * from passing the recipe function every time.
  641. *
  642. * Only plain objects and arrays are made mutable. All other objects are
  643. * considered uncopyable.
  644. *
  645. * Note: This function is __bound__ to its `Immer` instance.
  646. *
  647. * @param {any} base - the initial state
  648. * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified
  649. * @param {Function} patchListener - optional function that will be called with all the patches produced here
  650. * @returns {any} a new state, or the initial state if nothing was modified
  651. */
  652. this.produce = function (base, recipe, patchListener) {
  653. // curried invocation
  654. if (typeof base === "function" && typeof recipe !== "function") {
  655. var defaultBase = recipe;
  656. recipe = base;
  657. var self = _this;
  658. return function curriedProduce(base) {
  659. var _this2 = this;
  660. if (base === void 0) {
  661. base = defaultBase;
  662. }
  663. for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  664. args[_key - 1] = arguments[_key];
  665. }
  666. return self.produce(base, function (draft) {
  667. var _recipe;
  668. return (_recipe = recipe).call.apply(_recipe, [_this2, draft].concat(args));
  669. }); // prettier-ignore
  670. };
  671. }
  672. if (typeof recipe !== "function") die(6);
  673. if (patchListener !== undefined && typeof patchListener !== "function") die(7);
  674. var result; // Only plain objects, arrays, and "immerable classes" are drafted.
  675. if (isDraftable(base)) {
  676. var scope = enterScope(_this);
  677. var proxy = createProxy(_this, base, undefined);
  678. var hasError = true;
  679. try {
  680. result = recipe(proxy);
  681. hasError = false;
  682. } finally {
  683. // finally instead of catch + rethrow better preserves original stack
  684. if (hasError) revokeScope(scope);else leaveScope(scope);
  685. }
  686. if (typeof Promise !== "undefined" && result instanceof Promise) {
  687. return result.then(function (result) {
  688. usePatchesInScope(scope, patchListener);
  689. return processResult(result, scope);
  690. }, function (error) {
  691. revokeScope(scope);
  692. throw error;
  693. });
  694. }
  695. usePatchesInScope(scope, patchListener);
  696. return processResult(result, scope);
  697. } else if (!base || typeof base !== "object") {
  698. result = recipe(base);
  699. if (result === undefined) result = base;
  700. if (result === NOTHING) result = undefined;
  701. if (_this.autoFreeze_) freeze(result, true);
  702. if (patchListener) {
  703. var p = [];
  704. var ip = [];
  705. getPlugin("Patches").generateReplacementPatches_(base, result, p, ip);
  706. patchListener(p, ip);
  707. }
  708. return result;
  709. } else die(21, base);
  710. };
  711. this.produceWithPatches = function (base, recipe) {
  712. // curried invocation
  713. if (typeof base === "function") {
  714. return function (state) {
  715. for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  716. args[_key2 - 1] = arguments[_key2];
  717. }
  718. return _this.produceWithPatches(state, function (draft) {
  719. return base.apply(void 0, [draft].concat(args));
  720. });
  721. };
  722. }
  723. var patches, inversePatches;
  724. var result = _this.produce(base, recipe, function (p, ip) {
  725. patches = p;
  726. inversePatches = ip;
  727. });
  728. if (typeof Promise !== "undefined" && result instanceof Promise) {
  729. return result.then(function (nextState) {
  730. return [nextState, patches, inversePatches];
  731. });
  732. }
  733. return [result, patches, inversePatches];
  734. };
  735. if (typeof (config === null || config === void 0 ? void 0 : config.useProxies) === "boolean") this.setUseProxies(config.useProxies);
  736. if (typeof (config === null || config === void 0 ? void 0 : config.autoFreeze) === "boolean") this.setAutoFreeze(config.autoFreeze);
  737. }
  738. var _proto = Immer.prototype;
  739. _proto.createDraft = function createDraft(base) {
  740. if (!isDraftable(base)) die(8);
  741. if (isDraft(base)) base = current(base);
  742. var scope = enterScope(this);
  743. var proxy = createProxy(this, base, undefined);
  744. proxy[DRAFT_STATE].isManual_ = true;
  745. leaveScope(scope);
  746. return proxy;
  747. };
  748. _proto.finishDraft = function finishDraft(draft, patchListener) {
  749. var state = draft && draft[DRAFT_STATE];
  750. {
  751. if (!state || !state.isManual_) die(9);
  752. if (state.finalized_) die(10);
  753. }
  754. var scope = state.scope_;
  755. usePatchesInScope(scope, patchListener);
  756. return processResult(undefined, scope);
  757. }
  758. /**
  759. * Pass true to automatically freeze all copies created by Immer.
  760. *
  761. * By default, auto-freezing is enabled.
  762. */
  763. ;
  764. _proto.setAutoFreeze = function setAutoFreeze(value) {
  765. this.autoFreeze_ = value;
  766. }
  767. /**
  768. * Pass true to use the ES2015 `Proxy` class when creating drafts, which is
  769. * always faster than using ES5 proxies.
  770. *
  771. * By default, feature detection is used, so calling this is rarely necessary.
  772. */
  773. ;
  774. _proto.setUseProxies = function setUseProxies(value) {
  775. if (value && !hasProxies) {
  776. die(20);
  777. }
  778. this.useProxies_ = value;
  779. };
  780. _proto.applyPatches = function applyPatches(base, patches) {
  781. // If a patch replaces the entire state, take that replacement as base
  782. // before applying patches
  783. var i;
  784. for (i = patches.length - 1; i >= 0; i--) {
  785. var patch = patches[i];
  786. if (patch.path.length === 0 && patch.op === "replace") {
  787. base = patch.value;
  788. break;
  789. }
  790. } // If there was a patch that replaced the entire state, start from the
  791. // patch after that.
  792. if (i > -1) {
  793. patches = patches.slice(i + 1);
  794. }
  795. var applyPatchesImpl = getPlugin("Patches").applyPatches_;
  796. if (isDraft(base)) {
  797. // N.B: never hits if some patch a replacement, patches are never drafts
  798. return applyPatchesImpl(base, patches);
  799. } // Otherwise, produce a copy of the base state.
  800. return this.produce(base, function (draft) {
  801. return applyPatchesImpl(draft, patches);
  802. });
  803. };
  804. return Immer;
  805. }();
  806. function createProxy(immer, value, parent) {
  807. // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft
  808. var draft = isMap(value) ? getPlugin("MapSet").proxyMap_(value, parent) : isSet(value) ? getPlugin("MapSet").proxySet_(value, parent) : immer.useProxies_ ? createProxyProxy(value, parent) : getPlugin("ES5").createES5Proxy_(value, parent);
  809. var scope = parent ? parent.scope_ : getCurrentScope();
  810. scope.drafts_.push(draft);
  811. return draft;
  812. }
  813. function current(value) {
  814. if (!isDraft(value)) die(22, value);
  815. return currentImpl(value);
  816. }
  817. function currentImpl(value) {
  818. if (!isDraftable(value)) return value;
  819. var state = value[DRAFT_STATE];
  820. var copy;
  821. var archType = getArchtype(value);
  822. if (state) {
  823. if (!state.modified_ && (state.type_ < 4 || !getPlugin("ES5").hasChanges_(state))) return state.base_; // Optimization: avoid generating new drafts during copying
  824. state.finalized_ = true;
  825. copy = copyHelper(value, archType);
  826. state.finalized_ = false;
  827. } else {
  828. copy = copyHelper(value, archType);
  829. }
  830. each(copy, function (key, childValue) {
  831. if (state && get(state.base_, key) === childValue) return; // no need to copy or search in something that didn't change
  832. set(copy, key, currentImpl(childValue));
  833. }); // In the future, we might consider freezing here, based on the current settings
  834. return archType === 3
  835. /* Set */
  836. ? new Set(copy) : copy;
  837. }
  838. function copyHelper(value, archType) {
  839. // creates a shallow copy, even if it is a map or set
  840. switch (archType) {
  841. case 2
  842. /* Map */
  843. :
  844. return new Map(value);
  845. case 3
  846. /* Set */
  847. :
  848. // Set will be cloned as array temporarily, so that we can replace individual items
  849. return Array.from(value);
  850. }
  851. return shallowCopy(value);
  852. }
  853. function enableES5() {
  854. function willFinalizeES5_(scope, result, isReplaced) {
  855. if (!isReplaced) {
  856. if (scope.patches_) {
  857. markChangesRecursively(scope.drafts_[0]);
  858. } // This is faster when we don't care about which attributes changed.
  859. markChangesSweep(scope.drafts_);
  860. } // When a child draft is returned, look for changes.
  861. else if (isDraft(result) && result[DRAFT_STATE].scope_ === scope) {
  862. markChangesSweep(scope.drafts_);
  863. }
  864. }
  865. function createES5Draft(isArray, base) {
  866. if (isArray) {
  867. var draft = new Array(base.length);
  868. for (var i = 0; i < base.length; i++) {
  869. Object.defineProperty(draft, "" + i, proxyProperty(i, true));
  870. }
  871. return draft;
  872. } else {
  873. var _descriptors = getOwnPropertyDescriptors(base);
  874. delete _descriptors[DRAFT_STATE];
  875. var keys = ownKeys(_descriptors);
  876. for (var _i = 0; _i < keys.length; _i++) {
  877. var key = keys[_i];
  878. _descriptors[key] = proxyProperty(key, isArray || !!_descriptors[key].enumerable);
  879. }
  880. return Object.create(Object.getPrototypeOf(base), _descriptors);
  881. }
  882. }
  883. function createES5Proxy_(base, parent) {
  884. var isArray = Array.isArray(base);
  885. var draft = createES5Draft(isArray, base);
  886. var state = {
  887. type_: isArray ? 5
  888. /* ES5Array */
  889. : 4
  890. /* ES5Object */
  891. ,
  892. scope_: parent ? parent.scope_ : getCurrentScope(),
  893. modified_: false,
  894. finalized_: false,
  895. assigned_: {},
  896. parent_: parent,
  897. // base is the object we are drafting
  898. base_: base,
  899. // draft is the draft object itself, that traps all reads and reads from either the base (if unmodified) or copy (if modified)
  900. draft_: draft,
  901. copy_: null,
  902. revoked_: false,
  903. isManual_: false
  904. };
  905. Object.defineProperty(draft, DRAFT_STATE, {
  906. value: state,
  907. // enumerable: false <- the default
  908. writable: true
  909. });
  910. return draft;
  911. } // property descriptors are recycled to make sure we don't create a get and set closure per property,
  912. // but share them all instead
  913. var descriptors = {};
  914. function proxyProperty(prop, enumerable) {
  915. var desc = descriptors[prop];
  916. if (desc) {
  917. desc.enumerable = enumerable;
  918. } else {
  919. descriptors[prop] = desc = {
  920. configurable: true,
  921. enumerable: enumerable,
  922. get: function get() {
  923. var state = this[DRAFT_STATE];
  924. assertUnrevoked(state); // @ts-ignore
  925. return objectTraps.get(state, prop);
  926. },
  927. set: function set(value) {
  928. var state = this[DRAFT_STATE];
  929. assertUnrevoked(state); // @ts-ignore
  930. objectTraps.set(state, prop, value);
  931. }
  932. };
  933. }
  934. return desc;
  935. } // This looks expensive, but only proxies are visited, and only objects without known changes are scanned.
  936. function markChangesSweep(drafts) {
  937. // The natural order of drafts in the `scope` array is based on when they
  938. // were accessed. By processing drafts in reverse natural order, we have a
  939. // better chance of processing leaf nodes first. When a leaf node is known to
  940. // have changed, we can avoid any traversal of its ancestor nodes.
  941. for (var i = drafts.length - 1; i >= 0; i--) {
  942. var state = drafts[i][DRAFT_STATE];
  943. if (!state.modified_) {
  944. switch (state.type_) {
  945. case 5
  946. /* ES5Array */
  947. :
  948. if (hasArrayChanges(state)) markChanged(state);
  949. break;
  950. case 4
  951. /* ES5Object */
  952. :
  953. if (hasObjectChanges(state)) markChanged(state);
  954. break;
  955. }
  956. }
  957. }
  958. }
  959. function markChangesRecursively(object) {
  960. if (!object || typeof object !== "object") return;
  961. var state = object[DRAFT_STATE];
  962. if (!state) return;
  963. var base_ = state.base_,
  964. draft_ = state.draft_,
  965. assigned_ = state.assigned_,
  966. type_ = state.type_;
  967. if (type_ === 4
  968. /* ES5Object */
  969. ) {
  970. // Look for added keys.
  971. // probably there is a faster way to detect changes, as sweep + recurse seems to do some
  972. // unnecessary work.
  973. // also: probably we can store the information we detect here, to speed up tree finalization!
  974. each(draft_, function (key) {
  975. if (key === DRAFT_STATE) return; // The `undefined` check is a fast path for pre-existing keys.
  976. if (base_[key] === undefined && !has(base_, key)) {
  977. assigned_[key] = true;
  978. markChanged(state);
  979. } else if (!assigned_[key]) {
  980. // Only untouched properties trigger recursion.
  981. markChangesRecursively(draft_[key]);
  982. }
  983. }); // Look for removed keys.
  984. each(base_, function (key) {
  985. // The `undefined` check is a fast path for pre-existing keys.
  986. if (draft_[key] === undefined && !has(draft_, key)) {
  987. assigned_[key] = false;
  988. markChanged(state);
  989. }
  990. });
  991. } else if (type_ === 5
  992. /* ES5Array */
  993. ) {
  994. if (hasArrayChanges(state)) {
  995. markChanged(state);
  996. assigned_.length = true;
  997. }
  998. if (draft_.length < base_.length) {
  999. for (var i = draft_.length; i < base_.length; i++) {
  1000. assigned_[i] = false;
  1001. }
  1002. } else {
  1003. for (var _i2 = base_.length; _i2 < draft_.length; _i2++) {
  1004. assigned_[_i2] = true;
  1005. }
  1006. } // Minimum count is enough, the other parts has been processed.
  1007. var min = Math.min(draft_.length, base_.length);
  1008. for (var _i3 = 0; _i3 < min; _i3++) {
  1009. // Only untouched indices trigger recursion.
  1010. if (!draft_.hasOwnProperty(_i3)) {
  1011. assigned_[_i3] = true;
  1012. }
  1013. if (assigned_[_i3] === undefined) markChangesRecursively(draft_[_i3]);
  1014. }
  1015. }
  1016. }
  1017. function hasObjectChanges(state) {
  1018. var base_ = state.base_,
  1019. draft_ = state.draft_; // Search for added keys and changed keys. Start at the back, because
  1020. // non-numeric keys are ordered by time of definition on the object.
  1021. var keys = ownKeys(draft_);
  1022. for (var i = keys.length - 1; i >= 0; i--) {
  1023. var key = keys[i];
  1024. if (key === DRAFT_STATE) continue;
  1025. var baseValue = base_[key]; // The `undefined` check is a fast path for pre-existing keys.
  1026. if (baseValue === undefined && !has(base_, key)) {
  1027. return true;
  1028. } // Once a base key is deleted, future changes go undetected, because its
  1029. // descriptor is erased. This branch detects any missed changes.
  1030. else {
  1031. var value = draft_[key];
  1032. var _state = value && value[DRAFT_STATE];
  1033. if (_state ? _state.base_ !== baseValue : !is(value, baseValue)) {
  1034. return true;
  1035. }
  1036. }
  1037. } // At this point, no keys were added or changed.
  1038. // Compare key count to determine if keys were deleted.
  1039. var baseIsDraft = !!base_[DRAFT_STATE];
  1040. return keys.length !== ownKeys(base_).length + (baseIsDraft ? 0 : 1); // + 1 to correct for DRAFT_STATE
  1041. }
  1042. function hasArrayChanges(state) {
  1043. var draft_ = state.draft_;
  1044. if (draft_.length !== state.base_.length) return true; // See #116
  1045. // If we first shorten the length, our array interceptors will be removed.
  1046. // If after that new items are added, result in the same original length,
  1047. // those last items will have no intercepting property.
  1048. // So if there is no own descriptor on the last position, we know that items were removed and added
  1049. // N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check
  1050. // the last one
  1051. // last descriptor can be not a trap, if the array was extended
  1052. var descriptor = Object.getOwnPropertyDescriptor(draft_, draft_.length - 1); // descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)
  1053. if (descriptor && !descriptor.get) return true; // if we miss a property, it has been deleted, so array probobaly changed
  1054. for (var i = 0; i < draft_.length; i++) {
  1055. if (!draft_.hasOwnProperty(i)) return true;
  1056. } // For all other cases, we don't have to compare, as they would have been picked up by the index setters
  1057. return false;
  1058. }
  1059. function hasChanges_(state) {
  1060. return state.type_ === 4
  1061. /* ES5Object */
  1062. ? hasObjectChanges(state) : hasArrayChanges(state);
  1063. }
  1064. function assertUnrevoked(state
  1065. /*ES5State | MapState | SetState*/
  1066. ) {
  1067. if (state.revoked_) die(3, JSON.stringify(latest(state)));
  1068. }
  1069. loadPlugin("ES5", {
  1070. createES5Proxy_: createES5Proxy_,
  1071. willFinalizeES5_: willFinalizeES5_,
  1072. hasChanges_: hasChanges_
  1073. });
  1074. }
  1075. function enablePatches() {
  1076. var REPLACE = "replace";
  1077. var ADD = "add";
  1078. var REMOVE = "remove";
  1079. function generatePatches_(state, basePath, patches, inversePatches) {
  1080. switch (state.type_) {
  1081. case 0
  1082. /* ProxyObject */
  1083. :
  1084. case 4
  1085. /* ES5Object */
  1086. :
  1087. case 2
  1088. /* Map */
  1089. :
  1090. return generatePatchesFromAssigned(state, basePath, patches, inversePatches);
  1091. case 5
  1092. /* ES5Array */
  1093. :
  1094. case 1
  1095. /* ProxyArray */
  1096. :
  1097. return generateArrayPatches(state, basePath, patches, inversePatches);
  1098. case 3
  1099. /* Set */
  1100. :
  1101. return generateSetPatches(state, basePath, patches, inversePatches);
  1102. }
  1103. }
  1104. function generateArrayPatches(state, basePath, patches, inversePatches) {
  1105. var base_ = state.base_,
  1106. assigned_ = state.assigned_;
  1107. var copy_ = state.copy_; // Reduce complexity by ensuring `base` is never longer.
  1108. if (copy_.length < base_.length) {
  1109. var _ref = [copy_, base_];
  1110. base_ = _ref[0];
  1111. copy_ = _ref[1];
  1112. var _ref2 = [inversePatches, patches];
  1113. patches = _ref2[0];
  1114. inversePatches = _ref2[1];
  1115. } // Process replaced indices.
  1116. for (var i = 0; i < base_.length; i++) {
  1117. if (assigned_[i] && copy_[i] !== base_[i]) {
  1118. var path = basePath.concat([i]);
  1119. patches.push({
  1120. op: REPLACE,
  1121. path: path,
  1122. // Need to maybe clone it, as it can in fact be the original value
  1123. // due to the base/copy inversion at the start of this function
  1124. value: clonePatchValueIfNeeded(copy_[i])
  1125. });
  1126. inversePatches.push({
  1127. op: REPLACE,
  1128. path: path,
  1129. value: clonePatchValueIfNeeded(base_[i])
  1130. });
  1131. }
  1132. } // Process added indices.
  1133. for (var _i = base_.length; _i < copy_.length; _i++) {
  1134. var _path = basePath.concat([_i]);
  1135. patches.push({
  1136. op: ADD,
  1137. path: _path,
  1138. // Need to maybe clone it, as it can in fact be the original value
  1139. // due to the base/copy inversion at the start of this function
  1140. value: clonePatchValueIfNeeded(copy_[_i])
  1141. });
  1142. }
  1143. if (base_.length < copy_.length) {
  1144. inversePatches.push({
  1145. op: REPLACE,
  1146. path: basePath.concat(["length"]),
  1147. value: base_.length
  1148. });
  1149. }
  1150. } // This is used for both Map objects and normal objects.
  1151. function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {
  1152. var base_ = state.base_,
  1153. copy_ = state.copy_;
  1154. each(state.assigned_, function (key, assignedValue) {
  1155. var origValue = get(base_, key);
  1156. var value = get(copy_, key);
  1157. var op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD;
  1158. if (origValue === value && op === REPLACE) return;
  1159. var path = basePath.concat(key);
  1160. patches.push(op === REMOVE ? {
  1161. op: op,
  1162. path: path
  1163. } : {
  1164. op: op,
  1165. path: path,
  1166. value: value
  1167. });
  1168. inversePatches.push(op === ADD ? {
  1169. op: REMOVE,
  1170. path: path
  1171. } : op === REMOVE ? {
  1172. op: ADD,
  1173. path: path,
  1174. value: clonePatchValueIfNeeded(origValue)
  1175. } : {
  1176. op: REPLACE,
  1177. path: path,
  1178. value: clonePatchValueIfNeeded(origValue)
  1179. });
  1180. });
  1181. }
  1182. function generateSetPatches(state, basePath, patches, inversePatches) {
  1183. var base_ = state.base_,
  1184. copy_ = state.copy_;
  1185. var i = 0;
  1186. base_.forEach(function (value) {
  1187. if (!copy_.has(value)) {
  1188. var path = basePath.concat([i]);
  1189. patches.push({
  1190. op: REMOVE,
  1191. path: path,
  1192. value: value
  1193. });
  1194. inversePatches.unshift({
  1195. op: ADD,
  1196. path: path,
  1197. value: value
  1198. });
  1199. }
  1200. i++;
  1201. });
  1202. i = 0;
  1203. copy_.forEach(function (value) {
  1204. if (!base_.has(value)) {
  1205. var path = basePath.concat([i]);
  1206. patches.push({
  1207. op: ADD,
  1208. path: path,
  1209. value: value
  1210. });
  1211. inversePatches.unshift({
  1212. op: REMOVE,
  1213. path: path,
  1214. value: value
  1215. });
  1216. }
  1217. i++;
  1218. });
  1219. }
  1220. function generateReplacementPatches_(baseValue, replacement, patches, inversePatches) {
  1221. patches.push({
  1222. op: REPLACE,
  1223. path: [],
  1224. value: replacement === NOTHING ? undefined : replacement
  1225. });
  1226. inversePatches.push({
  1227. op: REPLACE,
  1228. path: [],
  1229. value: baseValue
  1230. });
  1231. }
  1232. function applyPatches_(draft, patches) {
  1233. patches.forEach(function (patch) {
  1234. var path = patch.path,
  1235. op = patch.op;
  1236. var base = draft;
  1237. for (var i = 0; i < path.length - 1; i++) {
  1238. var parentType = getArchtype(base);
  1239. var p = path[i];
  1240. if (typeof p !== "string" && typeof p !== "number") {
  1241. p = "" + p;
  1242. } // See #738, avoid prototype pollution
  1243. if ((parentType === 0
  1244. /* Object */
  1245. || parentType === 1
  1246. /* Array */
  1247. ) && (p === "__proto__" || p === "constructor")) die(24);
  1248. if (typeof base === "function" && p === "prototype") die(24);
  1249. base = get(base, p);
  1250. if (typeof base !== "object") die(15, path.join("/"));
  1251. }
  1252. var type = getArchtype(base);
  1253. var value = deepClonePatchValue(patch.value); // used to clone patch to ensure original patch is not modified, see #411
  1254. var key = path[path.length - 1];
  1255. switch (op) {
  1256. case REPLACE:
  1257. switch (type) {
  1258. case 2
  1259. /* Map */
  1260. :
  1261. return base.set(key, value);
  1262. /* istanbul ignore next */
  1263. case 3
  1264. /* Set */
  1265. :
  1266. die(16);
  1267. default:
  1268. // if value is an object, then it's assigned by reference
  1269. // in the following add or remove ops, the value field inside the patch will also be modifyed
  1270. // so we use value from the cloned patch
  1271. // @ts-ignore
  1272. return base[key] = value;
  1273. }
  1274. case ADD:
  1275. switch (type) {
  1276. case 1
  1277. /* Array */
  1278. :
  1279. return key === "-" ? base.push(value) : base.splice(key, 0, value);
  1280. case 2
  1281. /* Map */
  1282. :
  1283. return base.set(key, value);
  1284. case 3
  1285. /* Set */
  1286. :
  1287. return base.add(value);
  1288. default:
  1289. return base[key] = value;
  1290. }
  1291. case REMOVE:
  1292. switch (type) {
  1293. case 1
  1294. /* Array */
  1295. :
  1296. return base.splice(key, 1);
  1297. case 2
  1298. /* Map */
  1299. :
  1300. return base.delete(key);
  1301. case 3
  1302. /* Set */
  1303. :
  1304. return base.delete(patch.value);
  1305. default:
  1306. return delete base[key];
  1307. }
  1308. default:
  1309. die(17, op);
  1310. }
  1311. });
  1312. return draft;
  1313. }
  1314. function deepClonePatchValue(obj) {
  1315. if (!isDraftable(obj)) return obj;
  1316. if (Array.isArray(obj)) return obj.map(deepClonePatchValue);
  1317. if (isMap(obj)) return new Map(Array.from(obj.entries()).map(function (_ref3) {
  1318. var k = _ref3[0],
  1319. v = _ref3[1];
  1320. return [k, deepClonePatchValue(v)];
  1321. }));
  1322. if (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue));
  1323. var cloned = Object.create(Object.getPrototypeOf(obj));
  1324. for (var key in obj) {
  1325. cloned[key] = deepClonePatchValue(obj[key]);
  1326. }
  1327. if (has(obj, DRAFTABLE)) cloned[DRAFTABLE] = obj[DRAFTABLE];
  1328. return cloned;
  1329. }
  1330. function clonePatchValueIfNeeded(obj) {
  1331. if (isDraft(obj)) {
  1332. return deepClonePatchValue(obj);
  1333. } else return obj;
  1334. }
  1335. loadPlugin("Patches", {
  1336. applyPatches_: applyPatches_,
  1337. generatePatches_: generatePatches_,
  1338. generateReplacementPatches_: generateReplacementPatches_
  1339. });
  1340. }
  1341. // types only!
  1342. function enableMapSet() {
  1343. /* istanbul ignore next */
  1344. var _extendStatics = function extendStatics(d, b) {
  1345. _extendStatics = Object.setPrototypeOf || {
  1346. __proto__: []
  1347. } instanceof Array && function (d, b) {
  1348. d.__proto__ = b;
  1349. } || function (d, b) {
  1350. for (var p in b) {
  1351. if (b.hasOwnProperty(p)) d[p] = b[p];
  1352. }
  1353. };
  1354. return _extendStatics(d, b);
  1355. }; // Ugly hack to resolve #502 and inherit built in Map / Set
  1356. function __extends(d, b) {
  1357. _extendStatics(d, b);
  1358. function __() {
  1359. this.constructor = d;
  1360. }
  1361. d.prototype = ( // @ts-ignore
  1362. __.prototype = b.prototype, new __());
  1363. }
  1364. var DraftMap = function (_super) {
  1365. __extends(DraftMap, _super); // Create class manually, cause #502
  1366. function DraftMap(target, parent) {
  1367. this[DRAFT_STATE] = {
  1368. type_: 2
  1369. /* Map */
  1370. ,
  1371. parent_: parent,
  1372. scope_: parent ? parent.scope_ : getCurrentScope(),
  1373. modified_: false,
  1374. finalized_: false,
  1375. copy_: undefined,
  1376. assigned_: undefined,
  1377. base_: target,
  1378. draft_: this,
  1379. isManual_: false,
  1380. revoked_: false
  1381. };
  1382. return this;
  1383. }
  1384. var p = DraftMap.prototype;
  1385. Object.defineProperty(p, "size", {
  1386. get: function get() {
  1387. return latest(this[DRAFT_STATE]).size;
  1388. } // enumerable: false,
  1389. // configurable: true
  1390. });
  1391. p.has = function (key) {
  1392. return latest(this[DRAFT_STATE]).has(key);
  1393. };
  1394. p.set = function (key, value) {
  1395. var state = this[DRAFT_STATE];
  1396. assertUnrevoked(state);
  1397. if (!latest(state).has(key) || latest(state).get(key) !== value) {
  1398. prepareMapCopy(state);
  1399. markChanged(state);
  1400. state.assigned_.set(key, true);
  1401. state.copy_.set(key, value);
  1402. state.assigned_.set(key, true);
  1403. }
  1404. return this;
  1405. };
  1406. p.delete = function (key) {
  1407. if (!this.has(key)) {
  1408. return false;
  1409. }
  1410. var state = this[DRAFT_STATE];
  1411. assertUnrevoked(state);
  1412. prepareMapCopy(state);
  1413. markChanged(state);
  1414. if (state.base_.has(key)) {
  1415. state.assigned_.set(key, false);
  1416. } else {
  1417. state.assigned_.delete(key);
  1418. }
  1419. state.copy_.delete(key);
  1420. return true;
  1421. };
  1422. p.clear = function () {
  1423. var state = this[DRAFT_STATE];
  1424. assertUnrevoked(state);
  1425. if (latest(state).size) {
  1426. prepareMapCopy(state);
  1427. markChanged(state);
  1428. state.assigned_ = new Map();
  1429. each(state.base_, function (key) {
  1430. state.assigned_.set(key, false);
  1431. });
  1432. state.copy_.clear();
  1433. }
  1434. };
  1435. p.forEach = function (cb, thisArg) {
  1436. var _this = this;
  1437. var state = this[DRAFT_STATE];
  1438. latest(state).forEach(function (_value, key, _map) {
  1439. cb.call(thisArg, _this.get(key), key, _this);
  1440. });
  1441. };
  1442. p.get = function (key) {
  1443. var state = this[DRAFT_STATE];
  1444. assertUnrevoked(state);
  1445. var value = latest(state).get(key);
  1446. if (state.finalized_ || !isDraftable(value)) {
  1447. return value;
  1448. }
  1449. if (value !== state.base_.get(key)) {
  1450. return value; // either already drafted or reassigned
  1451. } // despite what it looks, this creates a draft only once, see above condition
  1452. var draft = createProxy(state.scope_.immer_, value, state);
  1453. prepareMapCopy(state);
  1454. state.copy_.set(key, draft);
  1455. return draft;
  1456. };
  1457. p.keys = function () {
  1458. return latest(this[DRAFT_STATE]).keys();
  1459. };
  1460. p.values = function () {
  1461. var _this2 = this,
  1462. _ref;
  1463. var iterator = this.keys();
  1464. return _ref = {}, _ref[iteratorSymbol] = function () {
  1465. return _this2.values();
  1466. }, _ref.next = function next() {
  1467. var r = iterator.next();
  1468. /* istanbul ignore next */
  1469. if (r.done) return r;
  1470. var value = _this2.get(r.value);
  1471. return {
  1472. done: false,
  1473. value: value
  1474. };
  1475. }, _ref;
  1476. };
  1477. p.entries = function () {
  1478. var _this3 = this,
  1479. _ref2;
  1480. var iterator = this.keys();
  1481. return _ref2 = {}, _ref2[iteratorSymbol] = function () {
  1482. return _this3.entries();
  1483. }, _ref2.next = function next() {
  1484. var r = iterator.next();
  1485. /* istanbul ignore next */
  1486. if (r.done) return r;
  1487. var value = _this3.get(r.value);
  1488. return {
  1489. done: false,
  1490. value: [r.value, value]
  1491. };
  1492. }, _ref2;
  1493. };
  1494. p[iteratorSymbol] = function () {
  1495. return this.entries();
  1496. };
  1497. return DraftMap;
  1498. }(Map);
  1499. function proxyMap_(target, parent) {
  1500. // @ts-ignore
  1501. return new DraftMap(target, parent);
  1502. }
  1503. function prepareMapCopy(state) {
  1504. if (!state.copy_) {
  1505. state.assigned_ = new Map();
  1506. state.copy_ = new Map(state.base_);
  1507. }
  1508. }
  1509. var DraftSet = function (_super) {
  1510. __extends(DraftSet, _super); // Create class manually, cause #502
  1511. function DraftSet(target, parent) {
  1512. this[DRAFT_STATE] = {
  1513. type_: 3
  1514. /* Set */
  1515. ,
  1516. parent_: parent,
  1517. scope_: parent ? parent.scope_ : getCurrentScope(),
  1518. modified_: false,
  1519. finalized_: false,
  1520. copy_: undefined,
  1521. base_: target,
  1522. draft_: this,
  1523. drafts_: new Map(),
  1524. revoked_: false,
  1525. isManual_: false
  1526. };
  1527. return this;
  1528. }
  1529. var p = DraftSet.prototype;
  1530. Object.defineProperty(p, "size", {
  1531. get: function get() {
  1532. return latest(this[DRAFT_STATE]).size;
  1533. } // enumerable: true,
  1534. });
  1535. p.has = function (value) {
  1536. var state = this[DRAFT_STATE];
  1537. assertUnrevoked(state); // bit of trickery here, to be able to recognize both the value, and the draft of its value
  1538. if (!state.copy_) {
  1539. return state.base_.has(value);
  1540. }
  1541. if (state.copy_.has(value)) return true;
  1542. if (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value))) return true;
  1543. return false;
  1544. };
  1545. p.add = function (value) {
  1546. var state = this[DRAFT_STATE];
  1547. assertUnrevoked(state);
  1548. if (!this.has(value)) {
  1549. prepareSetCopy(state);
  1550. markChanged(state);
  1551. state.copy_.add(value);
  1552. }
  1553. return this;
  1554. };
  1555. p.delete = function (value) {
  1556. if (!this.has(value)) {
  1557. return false;
  1558. }
  1559. var state = this[DRAFT_STATE];
  1560. assertUnrevoked(state);
  1561. prepareSetCopy(state);
  1562. markChanged(state);
  1563. return state.copy_.delete(value) || (state.drafts_.has(value) ? state.copy_.delete(state.drafts_.get(value)) :
  1564. /* istanbul ignore next */
  1565. false);
  1566. };
  1567. p.clear = function () {
  1568. var state = this[DRAFT_STATE];
  1569. assertUnrevoked(state);
  1570. if (latest(state).size) {
  1571. prepareSetCopy(state);
  1572. markChanged(state);
  1573. state.copy_.clear();
  1574. }
  1575. };
  1576. p.values = function () {
  1577. var state = this[DRAFT_STATE];
  1578. assertUnrevoked(state);
  1579. prepareSetCopy(state);
  1580. return state.copy_.values();
  1581. };
  1582. p.entries = function entries() {
  1583. var state = this[DRAFT_STATE];
  1584. assertUnrevoked(state);
  1585. prepareSetCopy(state);
  1586. return state.copy_.entries();
  1587. };
  1588. p.keys = function () {
  1589. return this.values();
  1590. };
  1591. p[iteratorSymbol] = function () {
  1592. return this.values();
  1593. };
  1594. p.forEach = function forEach(cb, thisArg) {
  1595. var iterator = this.values();
  1596. var result = iterator.next();
  1597. while (!result.done) {
  1598. cb.call(thisArg, result.value, result.value, this);
  1599. result = iterator.next();
  1600. }
  1601. };
  1602. return DraftSet;
  1603. }(Set);
  1604. function proxySet_(target, parent) {
  1605. // @ts-ignore
  1606. return new DraftSet(target, parent);
  1607. }
  1608. function prepareSetCopy(state) {
  1609. if (!state.copy_) {
  1610. // create drafts for all entries to preserve insertion order
  1611. state.copy_ = new Set();
  1612. state.base_.forEach(function (value) {
  1613. if (isDraftable(value)) {
  1614. var draft = createProxy(state.scope_.immer_, value, state);
  1615. state.drafts_.set(value, draft);
  1616. state.copy_.add(draft);
  1617. } else {
  1618. state.copy_.add(value);
  1619. }
  1620. });
  1621. }
  1622. }
  1623. function assertUnrevoked(state
  1624. /*ES5State | MapState | SetState*/
  1625. ) {
  1626. if (state.revoked_) die(3, JSON.stringify(latest(state)));
  1627. }
  1628. loadPlugin("MapSet", {
  1629. proxyMap_: proxyMap_,
  1630. proxySet_: proxySet_
  1631. });
  1632. }
  1633. function enableAllPlugins() {
  1634. enableES5();
  1635. enableMapSet();
  1636. enablePatches();
  1637. }
  1638. var immer =
  1639. /*#__PURE__*/
  1640. new Immer();
  1641. /**
  1642. * The `produce` function takes a value and a "recipe function" (whose
  1643. * return value often depends on the base state). The recipe function is
  1644. * free to mutate its first argument however it wants. All mutations are
  1645. * only ever applied to a __copy__ of the base state.
  1646. *
  1647. * Pass only a function to create a "curried producer" which relieves you
  1648. * from passing the recipe function every time.
  1649. *
  1650. * Only plain objects and arrays are made mutable. All other objects are
  1651. * considered uncopyable.
  1652. *
  1653. * Note: This function is __bound__ to its `Immer` instance.
  1654. *
  1655. * @param {any} base - the initial state
  1656. * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified
  1657. * @param {Function} patchListener - optional function that will be called with all the patches produced here
  1658. * @returns {any} a new state, or the initial state if nothing was modified
  1659. */
  1660. var produce = immer.produce;
  1661. /**
  1662. * Like `produce`, but `produceWithPatches` always returns a tuple
  1663. * [nextState, patches, inversePatches] (instead of just the next state)
  1664. */
  1665. var produceWithPatches =
  1666. /*#__PURE__*/
  1667. immer.produceWithPatches.bind(immer);
  1668. /**
  1669. * Pass true to automatically freeze all copies created by Immer.
  1670. *
  1671. * Always freeze by default, even in production mode
  1672. */
  1673. var setAutoFreeze =
  1674. /*#__PURE__*/
  1675. immer.setAutoFreeze.bind(immer);
  1676. /**
  1677. * Pass true to use the ES2015 `Proxy` class when creating drafts, which is
  1678. * always faster than using ES5 proxies.
  1679. *
  1680. * By default, feature detection is used, so calling this is rarely necessary.
  1681. */
  1682. var setUseProxies =
  1683. /*#__PURE__*/
  1684. immer.setUseProxies.bind(immer);
  1685. /**
  1686. * Apply an array of Immer patches to the first argument.
  1687. *
  1688. * This function is a producer, which means copy-on-write is in effect.
  1689. */
  1690. var applyPatches =
  1691. /*#__PURE__*/
  1692. immer.applyPatches.bind(immer);
  1693. /**
  1694. * Create an Immer draft from the given base state, which may be a draft itself.
  1695. * The draft can be modified until you finalize it with the `finishDraft` function.
  1696. */
  1697. var createDraft =
  1698. /*#__PURE__*/
  1699. immer.createDraft.bind(immer);
  1700. /**
  1701. * Finalize an Immer draft from a `createDraft` call, returning the base state
  1702. * (if no changes were made) or a modified copy. The draft must *not* be
  1703. * mutated afterwards.
  1704. *
  1705. * Pass a function as the 2nd argument to generate Immer patches based on the
  1706. * changes that were made.
  1707. */
  1708. var finishDraft =
  1709. /*#__PURE__*/
  1710. immer.finishDraft.bind(immer);
  1711. /**
  1712. * This function is actually a no-op, but can be used to cast an immutable type
  1713. * to an draft type and make TypeScript happy
  1714. *
  1715. * @param value
  1716. */
  1717. function castDraft(value) {
  1718. return value;
  1719. }
  1720. /**
  1721. * This function is actually a no-op, but can be used to cast a mutable type
  1722. * to an immutable type and make TypeScript happy
  1723. * @param value
  1724. */
  1725. function castImmutable(value) {
  1726. return value;
  1727. }
  1728. exports.Immer = Immer;
  1729. exports.applyPatches = applyPatches;
  1730. exports.castDraft = castDraft;
  1731. exports.castImmutable = castImmutable;
  1732. exports.createDraft = createDraft;
  1733. exports.current = current;
  1734. exports.default = produce;
  1735. exports.enableAllPlugins = enableAllPlugins;
  1736. exports.enableES5 = enableES5;
  1737. exports.enableMapSet = enableMapSet;
  1738. exports.enablePatches = enablePatches;
  1739. exports.finishDraft = finishDraft;
  1740. exports.freeze = freeze;
  1741. exports.immerable = DRAFTABLE;
  1742. exports.isDraft = isDraft;
  1743. exports.isDraftable = isDraftable;
  1744. exports.nothing = NOTHING;
  1745. exports.original = original;
  1746. exports.produce = produce;
  1747. exports.produceWithPatches = produceWithPatches;
  1748. exports.setAutoFreeze = setAutoFreeze;
  1749. exports.setUseProxies = setUseProxies;
  1750. //# sourceMappingURL=immer.cjs.development.js.map