immer.cjs.development.js 57 KB

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