immer.umd.development.js 59 KB

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