immer.cjs.development.js 59 KB

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