immer.umd.development.js 61 KB

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