reactivity.cjs.js 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var shared = require('@vue/shared');
  4. function warn(msg, ...args) {
  5. console.warn(`[Vue warn] ${msg}`, ...args);
  6. }
  7. let activeEffectScope;
  8. const effectScopeStack = [];
  9. class EffectScope {
  10. constructor(detached = false) {
  11. this.active = true;
  12. this.effects = [];
  13. this.cleanups = [];
  14. if (!detached && activeEffectScope) {
  15. this.parent = activeEffectScope;
  16. this.index =
  17. (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(this) - 1;
  18. }
  19. }
  20. run(fn) {
  21. if (this.active) {
  22. try {
  23. this.on();
  24. return fn();
  25. }
  26. finally {
  27. this.off();
  28. }
  29. }
  30. else {
  31. warn(`cannot run an inactive effect scope.`);
  32. }
  33. }
  34. on() {
  35. if (this.active) {
  36. effectScopeStack.push(this);
  37. activeEffectScope = this;
  38. }
  39. }
  40. off() {
  41. if (this.active) {
  42. effectScopeStack.pop();
  43. activeEffectScope = effectScopeStack[effectScopeStack.length - 1];
  44. }
  45. }
  46. stop(fromParent) {
  47. if (this.active) {
  48. this.effects.forEach(e => e.stop());
  49. this.cleanups.forEach(cleanup => cleanup());
  50. if (this.scopes) {
  51. this.scopes.forEach(e => e.stop(true));
  52. }
  53. // nested scope, dereference from parent to avoid memory leaks
  54. if (this.parent && !fromParent) {
  55. // optimized O(1) removal
  56. const last = this.parent.scopes.pop();
  57. if (last && last !== this) {
  58. this.parent.scopes[this.index] = last;
  59. last.index = this.index;
  60. }
  61. }
  62. this.active = false;
  63. }
  64. }
  65. }
  66. function effectScope(detached) {
  67. return new EffectScope(detached);
  68. }
  69. function recordEffectScope(effect, scope) {
  70. scope = scope || activeEffectScope;
  71. if (scope && scope.active) {
  72. scope.effects.push(effect);
  73. }
  74. }
  75. function getCurrentScope() {
  76. return activeEffectScope;
  77. }
  78. function onScopeDispose(fn) {
  79. if (activeEffectScope) {
  80. activeEffectScope.cleanups.push(fn);
  81. }
  82. else {
  83. warn(`onScopeDispose() is called when there is no active effect scope` +
  84. ` to be associated with.`);
  85. }
  86. }
  87. const createDep = (effects) => {
  88. const dep = new Set(effects);
  89. dep.w = 0;
  90. dep.n = 0;
  91. return dep;
  92. };
  93. const wasTracked = (dep) => (dep.w & trackOpBit) > 0;
  94. const newTracked = (dep) => (dep.n & trackOpBit) > 0;
  95. const initDepMarkers = ({ deps }) => {
  96. if (deps.length) {
  97. for (let i = 0; i < deps.length; i++) {
  98. deps[i].w |= trackOpBit; // set was tracked
  99. }
  100. }
  101. };
  102. const finalizeDepMarkers = (effect) => {
  103. const { deps } = effect;
  104. if (deps.length) {
  105. let ptr = 0;
  106. for (let i = 0; i < deps.length; i++) {
  107. const dep = deps[i];
  108. if (wasTracked(dep) && !newTracked(dep)) {
  109. dep.delete(effect);
  110. }
  111. else {
  112. deps[ptr++] = dep;
  113. }
  114. // clear bits
  115. dep.w &= ~trackOpBit;
  116. dep.n &= ~trackOpBit;
  117. }
  118. deps.length = ptr;
  119. }
  120. };
  121. const targetMap = new WeakMap();
  122. // The number of effects currently being tracked recursively.
  123. let effectTrackDepth = 0;
  124. let trackOpBit = 1;
  125. /**
  126. * The bitwise track markers support at most 30 levels of recursion.
  127. * This value is chosen to enable modern JS engines to use a SMI on all platforms.
  128. * When recursion depth is greater, fall back to using a full cleanup.
  129. */
  130. const maxMarkerBits = 30;
  131. const effectStack = [];
  132. let activeEffect;
  133. const ITERATE_KEY = Symbol('iterate' );
  134. const MAP_KEY_ITERATE_KEY = Symbol('Map key iterate' );
  135. class ReactiveEffect {
  136. constructor(fn, scheduler = null, scope) {
  137. this.fn = fn;
  138. this.scheduler = scheduler;
  139. this.active = true;
  140. this.deps = [];
  141. recordEffectScope(this, scope);
  142. }
  143. run() {
  144. if (!this.active) {
  145. return this.fn();
  146. }
  147. if (!effectStack.includes(this)) {
  148. try {
  149. effectStack.push((activeEffect = this));
  150. enableTracking();
  151. trackOpBit = 1 << ++effectTrackDepth;
  152. if (effectTrackDepth <= maxMarkerBits) {
  153. initDepMarkers(this);
  154. }
  155. else {
  156. cleanupEffect(this);
  157. }
  158. return this.fn();
  159. }
  160. finally {
  161. if (effectTrackDepth <= maxMarkerBits) {
  162. finalizeDepMarkers(this);
  163. }
  164. trackOpBit = 1 << --effectTrackDepth;
  165. resetTracking();
  166. effectStack.pop();
  167. const n = effectStack.length;
  168. activeEffect = n > 0 ? effectStack[n - 1] : undefined;
  169. }
  170. }
  171. }
  172. stop() {
  173. if (this.active) {
  174. cleanupEffect(this);
  175. if (this.onStop) {
  176. this.onStop();
  177. }
  178. this.active = false;
  179. }
  180. }
  181. }
  182. function cleanupEffect(effect) {
  183. const { deps } = effect;
  184. if (deps.length) {
  185. for (let i = 0; i < deps.length; i++) {
  186. deps[i].delete(effect);
  187. }
  188. deps.length = 0;
  189. }
  190. }
  191. function effect(fn, options) {
  192. if (fn.effect) {
  193. fn = fn.effect.fn;
  194. }
  195. const _effect = new ReactiveEffect(fn);
  196. if (options) {
  197. shared.extend(_effect, options);
  198. if (options.scope)
  199. recordEffectScope(_effect, options.scope);
  200. }
  201. if (!options || !options.lazy) {
  202. _effect.run();
  203. }
  204. const runner = _effect.run.bind(_effect);
  205. runner.effect = _effect;
  206. return runner;
  207. }
  208. function stop(runner) {
  209. runner.effect.stop();
  210. }
  211. let shouldTrack = true;
  212. const trackStack = [];
  213. function pauseTracking() {
  214. trackStack.push(shouldTrack);
  215. shouldTrack = false;
  216. }
  217. function enableTracking() {
  218. trackStack.push(shouldTrack);
  219. shouldTrack = true;
  220. }
  221. function resetTracking() {
  222. const last = trackStack.pop();
  223. shouldTrack = last === undefined ? true : last;
  224. }
  225. function track(target, type, key) {
  226. if (!isTracking()) {
  227. return;
  228. }
  229. let depsMap = targetMap.get(target);
  230. if (!depsMap) {
  231. targetMap.set(target, (depsMap = new Map()));
  232. }
  233. let dep = depsMap.get(key);
  234. if (!dep) {
  235. depsMap.set(key, (dep = createDep()));
  236. }
  237. const eventInfo = { effect: activeEffect, target, type, key }
  238. ;
  239. trackEffects(dep, eventInfo);
  240. }
  241. function isTracking() {
  242. return shouldTrack && activeEffect !== undefined;
  243. }
  244. function trackEffects(dep, debuggerEventExtraInfo) {
  245. let shouldTrack = false;
  246. if (effectTrackDepth <= maxMarkerBits) {
  247. if (!newTracked(dep)) {
  248. dep.n |= trackOpBit; // set newly tracked
  249. shouldTrack = !wasTracked(dep);
  250. }
  251. }
  252. else {
  253. // Full cleanup mode.
  254. shouldTrack = !dep.has(activeEffect);
  255. }
  256. if (shouldTrack) {
  257. dep.add(activeEffect);
  258. activeEffect.deps.push(dep);
  259. if (activeEffect.onTrack) {
  260. activeEffect.onTrack(Object.assign({
  261. effect: activeEffect
  262. }, debuggerEventExtraInfo));
  263. }
  264. }
  265. }
  266. function trigger(target, type, key, newValue, oldValue, oldTarget) {
  267. const depsMap = targetMap.get(target);
  268. if (!depsMap) {
  269. // never been tracked
  270. return;
  271. }
  272. let deps = [];
  273. if (type === "clear" /* CLEAR */) {
  274. // collection being cleared
  275. // trigger all effects for target
  276. deps = [...depsMap.values()];
  277. }
  278. else if (key === 'length' && shared.isArray(target)) {
  279. depsMap.forEach((dep, key) => {
  280. if (key === 'length' || key >= newValue) {
  281. deps.push(dep);
  282. }
  283. });
  284. }
  285. else {
  286. // schedule runs for SET | ADD | DELETE
  287. if (key !== void 0) {
  288. deps.push(depsMap.get(key));
  289. }
  290. // also run for iteration key on ADD | DELETE | Map.SET
  291. switch (type) {
  292. case "add" /* ADD */:
  293. if (!shared.isArray(target)) {
  294. deps.push(depsMap.get(ITERATE_KEY));
  295. if (shared.isMap(target)) {
  296. deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
  297. }
  298. }
  299. else if (shared.isIntegerKey(key)) {
  300. // new index added to array -> length changes
  301. deps.push(depsMap.get('length'));
  302. }
  303. break;
  304. case "delete" /* DELETE */:
  305. if (!shared.isArray(target)) {
  306. deps.push(depsMap.get(ITERATE_KEY));
  307. if (shared.isMap(target)) {
  308. deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
  309. }
  310. }
  311. break;
  312. case "set" /* SET */:
  313. if (shared.isMap(target)) {
  314. deps.push(depsMap.get(ITERATE_KEY));
  315. }
  316. break;
  317. }
  318. }
  319. const eventInfo = { target, type, key, newValue, oldValue, oldTarget }
  320. ;
  321. if (deps.length === 1) {
  322. if (deps[0]) {
  323. {
  324. triggerEffects(deps[0], eventInfo);
  325. }
  326. }
  327. }
  328. else {
  329. const effects = [];
  330. for (const dep of deps) {
  331. if (dep) {
  332. effects.push(...dep);
  333. }
  334. }
  335. {
  336. triggerEffects(createDep(effects), eventInfo);
  337. }
  338. }
  339. }
  340. function triggerEffects(dep, debuggerEventExtraInfo) {
  341. // spread into array for stabilization
  342. for (const effect of shared.isArray(dep) ? dep : [...dep]) {
  343. if (effect !== activeEffect || effect.allowRecurse) {
  344. if (effect.onTrigger) {
  345. effect.onTrigger(shared.extend({ effect }, debuggerEventExtraInfo));
  346. }
  347. if (effect.scheduler) {
  348. effect.scheduler();
  349. }
  350. else {
  351. effect.run();
  352. }
  353. }
  354. }
  355. }
  356. const isNonTrackableKeys = /*#__PURE__*/ shared.makeMap(`__proto__,__v_isRef,__isVue`);
  357. const builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol)
  358. .map(key => Symbol[key])
  359. .filter(shared.isSymbol));
  360. const get = /*#__PURE__*/ createGetter();
  361. const shallowGet = /*#__PURE__*/ createGetter(false, true);
  362. const readonlyGet = /*#__PURE__*/ createGetter(true);
  363. const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
  364. const arrayInstrumentations = /*#__PURE__*/ createArrayInstrumentations();
  365. function createArrayInstrumentations() {
  366. const instrumentations = {};
  367. ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
  368. instrumentations[key] = function (...args) {
  369. const arr = toRaw(this);
  370. for (let i = 0, l = this.length; i < l; i++) {
  371. track(arr, "get" /* GET */, i + '');
  372. }
  373. // we run the method using the original args first (which may be reactive)
  374. const res = arr[key](...args);
  375. if (res === -1 || res === false) {
  376. // if that didn't work, run it again using raw values.
  377. return arr[key](...args.map(toRaw));
  378. }
  379. else {
  380. return res;
  381. }
  382. };
  383. });
  384. ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
  385. instrumentations[key] = function (...args) {
  386. pauseTracking();
  387. const res = toRaw(this)[key].apply(this, args);
  388. resetTracking();
  389. return res;
  390. };
  391. });
  392. return instrumentations;
  393. }
  394. function createGetter(isReadonly = false, shallow = false) {
  395. return function get(target, key, receiver) {
  396. if (key === "__v_isReactive" /* IS_REACTIVE */) {
  397. return !isReadonly;
  398. }
  399. else if (key === "__v_isReadonly" /* IS_READONLY */) {
  400. return isReadonly;
  401. }
  402. else if (key === "__v_raw" /* RAW */ &&
  403. receiver ===
  404. (isReadonly
  405. ? shallow
  406. ? shallowReadonlyMap
  407. : readonlyMap
  408. : shallow
  409. ? shallowReactiveMap
  410. : reactiveMap).get(target)) {
  411. return target;
  412. }
  413. const targetIsArray = shared.isArray(target);
  414. if (!isReadonly && targetIsArray && shared.hasOwn(arrayInstrumentations, key)) {
  415. return Reflect.get(arrayInstrumentations, key, receiver);
  416. }
  417. const res = Reflect.get(target, key, receiver);
  418. if (shared.isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
  419. return res;
  420. }
  421. if (!isReadonly) {
  422. track(target, "get" /* GET */, key);
  423. }
  424. if (shallow) {
  425. return res;
  426. }
  427. if (isRef(res)) {
  428. // ref unwrapping - does not apply for Array + integer key.
  429. const shouldUnwrap = !targetIsArray || !shared.isIntegerKey(key);
  430. return shouldUnwrap ? res.value : res;
  431. }
  432. if (shared.isObject(res)) {
  433. // Convert returned value into a proxy as well. we do the isObject check
  434. // here to avoid invalid value warning. Also need to lazy access readonly
  435. // and reactive here to avoid circular dependency.
  436. return isReadonly ? readonly(res) : reactive(res);
  437. }
  438. return res;
  439. };
  440. }
  441. const set = /*#__PURE__*/ createSetter();
  442. const shallowSet = /*#__PURE__*/ createSetter(true);
  443. function createSetter(shallow = false) {
  444. return function set(target, key, value, receiver) {
  445. let oldValue = target[key];
  446. if (!shallow && !isReadonly(value)) {
  447. value = toRaw(value);
  448. oldValue = toRaw(oldValue);
  449. if (!shared.isArray(target) && isRef(oldValue) && !isRef(value)) {
  450. oldValue.value = value;
  451. return true;
  452. }
  453. }
  454. const hadKey = shared.isArray(target) && shared.isIntegerKey(key)
  455. ? Number(key) < target.length
  456. : shared.hasOwn(target, key);
  457. const result = Reflect.set(target, key, value, receiver);
  458. // don't trigger if target is something up in the prototype chain of original
  459. if (target === toRaw(receiver)) {
  460. if (!hadKey) {
  461. trigger(target, "add" /* ADD */, key, value);
  462. }
  463. else if (shared.hasChanged(value, oldValue)) {
  464. trigger(target, "set" /* SET */, key, value, oldValue);
  465. }
  466. }
  467. return result;
  468. };
  469. }
  470. function deleteProperty(target, key) {
  471. const hadKey = shared.hasOwn(target, key);
  472. const oldValue = target[key];
  473. const result = Reflect.deleteProperty(target, key);
  474. if (result && hadKey) {
  475. trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
  476. }
  477. return result;
  478. }
  479. function has(target, key) {
  480. const result = Reflect.has(target, key);
  481. if (!shared.isSymbol(key) || !builtInSymbols.has(key)) {
  482. track(target, "has" /* HAS */, key);
  483. }
  484. return result;
  485. }
  486. function ownKeys(target) {
  487. track(target, "iterate" /* ITERATE */, shared.isArray(target) ? 'length' : ITERATE_KEY);
  488. return Reflect.ownKeys(target);
  489. }
  490. const mutableHandlers = {
  491. get,
  492. set,
  493. deleteProperty,
  494. has,
  495. ownKeys
  496. };
  497. const readonlyHandlers = {
  498. get: readonlyGet,
  499. set(target, key) {
  500. {
  501. console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
  502. }
  503. return true;
  504. },
  505. deleteProperty(target, key) {
  506. {
  507. console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
  508. }
  509. return true;
  510. }
  511. };
  512. const shallowReactiveHandlers = /*#__PURE__*/ shared.extend({}, mutableHandlers, {
  513. get: shallowGet,
  514. set: shallowSet
  515. });
  516. // Props handlers are special in the sense that it should not unwrap top-level
  517. // refs (in order to allow refs to be explicitly passed down), but should
  518. // retain the reactivity of the normal readonly object.
  519. const shallowReadonlyHandlers = /*#__PURE__*/ shared.extend({}, readonlyHandlers, {
  520. get: shallowReadonlyGet
  521. });
  522. const toShallow = (value) => value;
  523. const getProto = (v) => Reflect.getPrototypeOf(v);
  524. function get$1(target, key, isReadonly = false, isShallow = false) {
  525. // #1772: readonly(reactive(Map)) should return readonly + reactive version
  526. // of the value
  527. target = target["__v_raw" /* RAW */];
  528. const rawTarget = toRaw(target);
  529. const rawKey = toRaw(key);
  530. if (key !== rawKey) {
  531. !isReadonly && track(rawTarget, "get" /* GET */, key);
  532. }
  533. !isReadonly && track(rawTarget, "get" /* GET */, rawKey);
  534. const { has } = getProto(rawTarget);
  535. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
  536. if (has.call(rawTarget, key)) {
  537. return wrap(target.get(key));
  538. }
  539. else if (has.call(rawTarget, rawKey)) {
  540. return wrap(target.get(rawKey));
  541. }
  542. else if (target !== rawTarget) {
  543. // #3602 readonly(reactive(Map))
  544. // ensure that the nested reactive `Map` can do tracking for itself
  545. target.get(key);
  546. }
  547. }
  548. function has$1(key, isReadonly = false) {
  549. const target = this["__v_raw" /* RAW */];
  550. const rawTarget = toRaw(target);
  551. const rawKey = toRaw(key);
  552. if (key !== rawKey) {
  553. !isReadonly && track(rawTarget, "has" /* HAS */, key);
  554. }
  555. !isReadonly && track(rawTarget, "has" /* HAS */, rawKey);
  556. return key === rawKey
  557. ? target.has(key)
  558. : target.has(key) || target.has(rawKey);
  559. }
  560. function size(target, isReadonly = false) {
  561. target = target["__v_raw" /* RAW */];
  562. !isReadonly && track(toRaw(target), "iterate" /* ITERATE */, ITERATE_KEY);
  563. return Reflect.get(target, 'size', target);
  564. }
  565. function add(value) {
  566. value = toRaw(value);
  567. const target = toRaw(this);
  568. const proto = getProto(target);
  569. const hadKey = proto.has.call(target, value);
  570. if (!hadKey) {
  571. target.add(value);
  572. trigger(target, "add" /* ADD */, value, value);
  573. }
  574. return this;
  575. }
  576. function set$1(key, value) {
  577. value = toRaw(value);
  578. const target = toRaw(this);
  579. const { has, get } = getProto(target);
  580. let hadKey = has.call(target, key);
  581. if (!hadKey) {
  582. key = toRaw(key);
  583. hadKey = has.call(target, key);
  584. }
  585. else {
  586. checkIdentityKeys(target, has, key);
  587. }
  588. const oldValue = get.call(target, key);
  589. target.set(key, value);
  590. if (!hadKey) {
  591. trigger(target, "add" /* ADD */, key, value);
  592. }
  593. else if (shared.hasChanged(value, oldValue)) {
  594. trigger(target, "set" /* SET */, key, value, oldValue);
  595. }
  596. return this;
  597. }
  598. function deleteEntry(key) {
  599. const target = toRaw(this);
  600. const { has, get } = getProto(target);
  601. let hadKey = has.call(target, key);
  602. if (!hadKey) {
  603. key = toRaw(key);
  604. hadKey = has.call(target, key);
  605. }
  606. else {
  607. checkIdentityKeys(target, has, key);
  608. }
  609. const oldValue = get ? get.call(target, key) : undefined;
  610. // forward the operation before queueing reactions
  611. const result = target.delete(key);
  612. if (hadKey) {
  613. trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
  614. }
  615. return result;
  616. }
  617. function clear() {
  618. const target = toRaw(this);
  619. const hadItems = target.size !== 0;
  620. const oldTarget = shared.isMap(target)
  621. ? new Map(target)
  622. : new Set(target)
  623. ;
  624. // forward the operation before queueing reactions
  625. const result = target.clear();
  626. if (hadItems) {
  627. trigger(target, "clear" /* CLEAR */, undefined, undefined, oldTarget);
  628. }
  629. return result;
  630. }
  631. function createForEach(isReadonly, isShallow) {
  632. return function forEach(callback, thisArg) {
  633. const observed = this;
  634. const target = observed["__v_raw" /* RAW */];
  635. const rawTarget = toRaw(target);
  636. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
  637. !isReadonly && track(rawTarget, "iterate" /* ITERATE */, ITERATE_KEY);
  638. return target.forEach((value, key) => {
  639. // important: make sure the callback is
  640. // 1. invoked with the reactive map as `this` and 3rd arg
  641. // 2. the value received should be a corresponding reactive/readonly.
  642. return callback.call(thisArg, wrap(value), wrap(key), observed);
  643. });
  644. };
  645. }
  646. function createIterableMethod(method, isReadonly, isShallow) {
  647. return function (...args) {
  648. const target = this["__v_raw" /* RAW */];
  649. const rawTarget = toRaw(target);
  650. const targetIsMap = shared.isMap(rawTarget);
  651. const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
  652. const isKeyOnly = method === 'keys' && targetIsMap;
  653. const innerIterator = target[method](...args);
  654. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
  655. !isReadonly &&
  656. track(rawTarget, "iterate" /* ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
  657. // return a wrapped iterator which returns observed versions of the
  658. // values emitted from the real iterator
  659. return {
  660. // iterator protocol
  661. next() {
  662. const { value, done } = innerIterator.next();
  663. return done
  664. ? { value, done }
  665. : {
  666. value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
  667. done
  668. };
  669. },
  670. // iterable protocol
  671. [Symbol.iterator]() {
  672. return this;
  673. }
  674. };
  675. };
  676. }
  677. function createReadonlyMethod(type) {
  678. return function (...args) {
  679. {
  680. const key = args[0] ? `on key "${args[0]}" ` : ``;
  681. console.warn(`${shared.capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
  682. }
  683. return type === "delete" /* DELETE */ ? false : this;
  684. };
  685. }
  686. function createInstrumentations() {
  687. const mutableInstrumentations = {
  688. get(key) {
  689. return get$1(this, key);
  690. },
  691. get size() {
  692. return size(this);
  693. },
  694. has: has$1,
  695. add,
  696. set: set$1,
  697. delete: deleteEntry,
  698. clear,
  699. forEach: createForEach(false, false)
  700. };
  701. const shallowInstrumentations = {
  702. get(key) {
  703. return get$1(this, key, false, true);
  704. },
  705. get size() {
  706. return size(this);
  707. },
  708. has: has$1,
  709. add,
  710. set: set$1,
  711. delete: deleteEntry,
  712. clear,
  713. forEach: createForEach(false, true)
  714. };
  715. const readonlyInstrumentations = {
  716. get(key) {
  717. return get$1(this, key, true);
  718. },
  719. get size() {
  720. return size(this, true);
  721. },
  722. has(key) {
  723. return has$1.call(this, key, true);
  724. },
  725. add: createReadonlyMethod("add" /* ADD */),
  726. set: createReadonlyMethod("set" /* SET */),
  727. delete: createReadonlyMethod("delete" /* DELETE */),
  728. clear: createReadonlyMethod("clear" /* CLEAR */),
  729. forEach: createForEach(true, false)
  730. };
  731. const shallowReadonlyInstrumentations = {
  732. get(key) {
  733. return get$1(this, key, true, true);
  734. },
  735. get size() {
  736. return size(this, true);
  737. },
  738. has(key) {
  739. return has$1.call(this, key, true);
  740. },
  741. add: createReadonlyMethod("add" /* ADD */),
  742. set: createReadonlyMethod("set" /* SET */),
  743. delete: createReadonlyMethod("delete" /* DELETE */),
  744. clear: createReadonlyMethod("clear" /* CLEAR */),
  745. forEach: createForEach(true, true)
  746. };
  747. const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
  748. iteratorMethods.forEach(method => {
  749. mutableInstrumentations[method] = createIterableMethod(method, false, false);
  750. readonlyInstrumentations[method] = createIterableMethod(method, true, false);
  751. shallowInstrumentations[method] = createIterableMethod(method, false, true);
  752. shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true);
  753. });
  754. return [
  755. mutableInstrumentations,
  756. readonlyInstrumentations,
  757. shallowInstrumentations,
  758. shallowReadonlyInstrumentations
  759. ];
  760. }
  761. const [mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations] = /* #__PURE__*/ createInstrumentations();
  762. function createInstrumentationGetter(isReadonly, shallow) {
  763. const instrumentations = shallow
  764. ? isReadonly
  765. ? shallowReadonlyInstrumentations
  766. : shallowInstrumentations
  767. : isReadonly
  768. ? readonlyInstrumentations
  769. : mutableInstrumentations;
  770. return (target, key, receiver) => {
  771. if (key === "__v_isReactive" /* IS_REACTIVE */) {
  772. return !isReadonly;
  773. }
  774. else if (key === "__v_isReadonly" /* IS_READONLY */) {
  775. return isReadonly;
  776. }
  777. else if (key === "__v_raw" /* RAW */) {
  778. return target;
  779. }
  780. return Reflect.get(shared.hasOwn(instrumentations, key) && key in target
  781. ? instrumentations
  782. : target, key, receiver);
  783. };
  784. }
  785. const mutableCollectionHandlers = {
  786. get: /*#__PURE__*/ createInstrumentationGetter(false, false)
  787. };
  788. const shallowCollectionHandlers = {
  789. get: /*#__PURE__*/ createInstrumentationGetter(false, true)
  790. };
  791. const readonlyCollectionHandlers = {
  792. get: /*#__PURE__*/ createInstrumentationGetter(true, false)
  793. };
  794. const shallowReadonlyCollectionHandlers = {
  795. get: /*#__PURE__*/ createInstrumentationGetter(true, true)
  796. };
  797. function checkIdentityKeys(target, has, key) {
  798. const rawKey = toRaw(key);
  799. if (rawKey !== key && has.call(target, rawKey)) {
  800. const type = shared.toRawType(target);
  801. console.warn(`Reactive ${type} contains both the raw and reactive ` +
  802. `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
  803. `which can lead to inconsistencies. ` +
  804. `Avoid differentiating between the raw and reactive versions ` +
  805. `of an object and only use the reactive version if possible.`);
  806. }
  807. }
  808. const reactiveMap = new WeakMap();
  809. const shallowReactiveMap = new WeakMap();
  810. const readonlyMap = new WeakMap();
  811. const shallowReadonlyMap = new WeakMap();
  812. function targetTypeMap(rawType) {
  813. switch (rawType) {
  814. case 'Object':
  815. case 'Array':
  816. return 1 /* COMMON */;
  817. case 'Map':
  818. case 'Set':
  819. case 'WeakMap':
  820. case 'WeakSet':
  821. return 2 /* COLLECTION */;
  822. default:
  823. return 0 /* INVALID */;
  824. }
  825. }
  826. function getTargetType(value) {
  827. return value["__v_skip" /* SKIP */] || !Object.isExtensible(value)
  828. ? 0 /* INVALID */
  829. : targetTypeMap(shared.toRawType(value));
  830. }
  831. function reactive(target) {
  832. // if trying to observe a readonly proxy, return the readonly version.
  833. if (target && target["__v_isReadonly" /* IS_READONLY */]) {
  834. return target;
  835. }
  836. return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
  837. }
  838. /**
  839. * Return a shallowly-reactive copy of the original object, where only the root
  840. * level properties are reactive. It also does not auto-unwrap refs (even at the
  841. * root level).
  842. */
  843. function shallowReactive(target) {
  844. return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
  845. }
  846. /**
  847. * Creates a readonly copy of the original object. Note the returned copy is not
  848. * made reactive, but `readonly` can be called on an already reactive object.
  849. */
  850. function readonly(target) {
  851. return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
  852. }
  853. /**
  854. * Returns a reactive-copy of the original object, where only the root level
  855. * properties are readonly, and does NOT unwrap refs nor recursively convert
  856. * returned properties.
  857. * This is used for creating the props proxy object for stateful components.
  858. */
  859. function shallowReadonly(target) {
  860. return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap);
  861. }
  862. function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) {
  863. if (!shared.isObject(target)) {
  864. {
  865. console.warn(`value cannot be made reactive: ${String(target)}`);
  866. }
  867. return target;
  868. }
  869. // target is already a Proxy, return it.
  870. // exception: calling readonly() on a reactive object
  871. if (target["__v_raw" /* RAW */] &&
  872. !(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) {
  873. return target;
  874. }
  875. // target already has corresponding Proxy
  876. const existingProxy = proxyMap.get(target);
  877. if (existingProxy) {
  878. return existingProxy;
  879. }
  880. // only a whitelist of value types can be observed.
  881. const targetType = getTargetType(target);
  882. if (targetType === 0 /* INVALID */) {
  883. return target;
  884. }
  885. const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers);
  886. proxyMap.set(target, proxy);
  887. return proxy;
  888. }
  889. function isReactive(value) {
  890. if (isReadonly(value)) {
  891. return isReactive(value["__v_raw" /* RAW */]);
  892. }
  893. return !!(value && value["__v_isReactive" /* IS_REACTIVE */]);
  894. }
  895. function isReadonly(value) {
  896. return !!(value && value["__v_isReadonly" /* IS_READONLY */]);
  897. }
  898. function isProxy(value) {
  899. return isReactive(value) || isReadonly(value);
  900. }
  901. function toRaw(observed) {
  902. const raw = observed && observed["__v_raw" /* RAW */];
  903. return raw ? toRaw(raw) : observed;
  904. }
  905. function markRaw(value) {
  906. shared.def(value, "__v_skip" /* SKIP */, true);
  907. return value;
  908. }
  909. const toReactive = (value) => shared.isObject(value) ? reactive(value) : value;
  910. const toReadonly = (value) => shared.isObject(value) ? readonly(value) : value;
  911. function trackRefValue(ref) {
  912. if (isTracking()) {
  913. ref = toRaw(ref);
  914. if (!ref.dep) {
  915. ref.dep = createDep();
  916. }
  917. {
  918. trackEffects(ref.dep, {
  919. target: ref,
  920. type: "get" /* GET */,
  921. key: 'value'
  922. });
  923. }
  924. }
  925. }
  926. function triggerRefValue(ref, newVal) {
  927. ref = toRaw(ref);
  928. if (ref.dep) {
  929. {
  930. triggerEffects(ref.dep, {
  931. target: ref,
  932. type: "set" /* SET */,
  933. key: 'value',
  934. newValue: newVal
  935. });
  936. }
  937. }
  938. }
  939. function isRef(r) {
  940. return Boolean(r && r.__v_isRef === true);
  941. }
  942. function ref(value) {
  943. return createRef(value, false);
  944. }
  945. function shallowRef(value) {
  946. return createRef(value, true);
  947. }
  948. function createRef(rawValue, shallow) {
  949. if (isRef(rawValue)) {
  950. return rawValue;
  951. }
  952. return new RefImpl(rawValue, shallow);
  953. }
  954. class RefImpl {
  955. constructor(value, _shallow) {
  956. this._shallow = _shallow;
  957. this.dep = undefined;
  958. this.__v_isRef = true;
  959. this._rawValue = _shallow ? value : toRaw(value);
  960. this._value = _shallow ? value : toReactive(value);
  961. }
  962. get value() {
  963. trackRefValue(this);
  964. return this._value;
  965. }
  966. set value(newVal) {
  967. newVal = this._shallow ? newVal : toRaw(newVal);
  968. if (shared.hasChanged(newVal, this._rawValue)) {
  969. this._rawValue = newVal;
  970. this._value = this._shallow ? newVal : toReactive(newVal);
  971. triggerRefValue(this, newVal);
  972. }
  973. }
  974. }
  975. function triggerRef(ref) {
  976. triggerRefValue(ref, ref.value );
  977. }
  978. function unref(ref) {
  979. return isRef(ref) ? ref.value : ref;
  980. }
  981. const shallowUnwrapHandlers = {
  982. get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
  983. set: (target, key, value, receiver) => {
  984. const oldValue = target[key];
  985. if (isRef(oldValue) && !isRef(value)) {
  986. oldValue.value = value;
  987. return true;
  988. }
  989. else {
  990. return Reflect.set(target, key, value, receiver);
  991. }
  992. }
  993. };
  994. function proxyRefs(objectWithRefs) {
  995. return isReactive(objectWithRefs)
  996. ? objectWithRefs
  997. : new Proxy(objectWithRefs, shallowUnwrapHandlers);
  998. }
  999. class CustomRefImpl {
  1000. constructor(factory) {
  1001. this.dep = undefined;
  1002. this.__v_isRef = true;
  1003. const { get, set } = factory(() => trackRefValue(this), () => triggerRefValue(this));
  1004. this._get = get;
  1005. this._set = set;
  1006. }
  1007. get value() {
  1008. return this._get();
  1009. }
  1010. set value(newVal) {
  1011. this._set(newVal);
  1012. }
  1013. }
  1014. function customRef(factory) {
  1015. return new CustomRefImpl(factory);
  1016. }
  1017. function toRefs(object) {
  1018. if (!isProxy(object)) {
  1019. console.warn(`toRefs() expects a reactive object but received a plain one.`);
  1020. }
  1021. const ret = shared.isArray(object) ? new Array(object.length) : {};
  1022. for (const key in object) {
  1023. ret[key] = toRef(object, key);
  1024. }
  1025. return ret;
  1026. }
  1027. class ObjectRefImpl {
  1028. constructor(_object, _key, _defaultValue) {
  1029. this._object = _object;
  1030. this._key = _key;
  1031. this._defaultValue = _defaultValue;
  1032. this.__v_isRef = true;
  1033. }
  1034. get value() {
  1035. const val = this._object[this._key];
  1036. return val === undefined ? this._defaultValue : val;
  1037. }
  1038. set value(newVal) {
  1039. this._object[this._key] = newVal;
  1040. }
  1041. }
  1042. function toRef(object, key, defaultValue) {
  1043. const val = object[key];
  1044. return isRef(val)
  1045. ? val
  1046. : new ObjectRefImpl(object, key, defaultValue);
  1047. }
  1048. class ComputedRefImpl {
  1049. constructor(getter, _setter, isReadonly) {
  1050. this._setter = _setter;
  1051. this.dep = undefined;
  1052. this._dirty = true;
  1053. this.__v_isRef = true;
  1054. this.effect = new ReactiveEffect(getter, () => {
  1055. if (!this._dirty) {
  1056. this._dirty = true;
  1057. triggerRefValue(this);
  1058. }
  1059. });
  1060. this["__v_isReadonly" /* IS_READONLY */] = isReadonly;
  1061. }
  1062. get value() {
  1063. // the computed ref may get wrapped by other proxies e.g. readonly() #3376
  1064. const self = toRaw(this);
  1065. trackRefValue(self);
  1066. if (self._dirty) {
  1067. self._dirty = false;
  1068. self._value = self.effect.run();
  1069. }
  1070. return self._value;
  1071. }
  1072. set value(newValue) {
  1073. this._setter(newValue);
  1074. }
  1075. }
  1076. function computed(getterOrOptions, debugOptions) {
  1077. let getter;
  1078. let setter;
  1079. const onlyGetter = shared.isFunction(getterOrOptions);
  1080. if (onlyGetter) {
  1081. getter = getterOrOptions;
  1082. setter = () => {
  1083. console.warn('Write operation failed: computed value is readonly');
  1084. }
  1085. ;
  1086. }
  1087. else {
  1088. getter = getterOrOptions.get;
  1089. setter = getterOrOptions.set;
  1090. }
  1091. const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter);
  1092. if (debugOptions) {
  1093. cRef.effect.onTrack = debugOptions.onTrack;
  1094. cRef.effect.onTrigger = debugOptions.onTrigger;
  1095. }
  1096. return cRef;
  1097. }
  1098. var _a;
  1099. const tick = Promise.resolve();
  1100. const queue = [];
  1101. let queued = false;
  1102. const scheduler = (fn) => {
  1103. queue.push(fn);
  1104. if (!queued) {
  1105. queued = true;
  1106. tick.then(flush);
  1107. }
  1108. };
  1109. const flush = () => {
  1110. for (let i = 0; i < queue.length; i++) {
  1111. queue[i]();
  1112. }
  1113. queue.length = 0;
  1114. queued = false;
  1115. };
  1116. class DeferredComputedRefImpl {
  1117. constructor(getter) {
  1118. this.dep = undefined;
  1119. this._dirty = true;
  1120. this.__v_isRef = true;
  1121. this[_a] = true;
  1122. let compareTarget;
  1123. let hasCompareTarget = false;
  1124. let scheduled = false;
  1125. this.effect = new ReactiveEffect(getter, (computedTrigger) => {
  1126. if (this.dep) {
  1127. if (computedTrigger) {
  1128. compareTarget = this._value;
  1129. hasCompareTarget = true;
  1130. }
  1131. else if (!scheduled) {
  1132. const valueToCompare = hasCompareTarget ? compareTarget : this._value;
  1133. scheduled = true;
  1134. hasCompareTarget = false;
  1135. scheduler(() => {
  1136. if (this.effect.active && this._get() !== valueToCompare) {
  1137. triggerRefValue(this);
  1138. }
  1139. scheduled = false;
  1140. });
  1141. }
  1142. // chained upstream computeds are notified synchronously to ensure
  1143. // value invalidation in case of sync access; normal effects are
  1144. // deferred to be triggered in scheduler.
  1145. for (const e of this.dep) {
  1146. if (e.computed) {
  1147. e.scheduler(true /* computedTrigger */);
  1148. }
  1149. }
  1150. }
  1151. this._dirty = true;
  1152. });
  1153. this.effect.computed = true;
  1154. }
  1155. _get() {
  1156. if (this._dirty) {
  1157. this._dirty = false;
  1158. return (this._value = this.effect.run());
  1159. }
  1160. return this._value;
  1161. }
  1162. get value() {
  1163. trackRefValue(this);
  1164. // the computed ref may get wrapped by other proxies e.g. readonly() #3376
  1165. return toRaw(this)._get();
  1166. }
  1167. }
  1168. _a = "__v_isReadonly" /* IS_READONLY */;
  1169. function deferredComputed(getter) {
  1170. return new DeferredComputedRefImpl(getter);
  1171. }
  1172. exports.EffectScope = EffectScope;
  1173. exports.ITERATE_KEY = ITERATE_KEY;
  1174. exports.ReactiveEffect = ReactiveEffect;
  1175. exports.computed = computed;
  1176. exports.customRef = customRef;
  1177. exports.deferredComputed = deferredComputed;
  1178. exports.effect = effect;
  1179. exports.effectScope = effectScope;
  1180. exports.enableTracking = enableTracking;
  1181. exports.getCurrentScope = getCurrentScope;
  1182. exports.isProxy = isProxy;
  1183. exports.isReactive = isReactive;
  1184. exports.isReadonly = isReadonly;
  1185. exports.isRef = isRef;
  1186. exports.markRaw = markRaw;
  1187. exports.onScopeDispose = onScopeDispose;
  1188. exports.pauseTracking = pauseTracking;
  1189. exports.proxyRefs = proxyRefs;
  1190. exports.reactive = reactive;
  1191. exports.readonly = readonly;
  1192. exports.ref = ref;
  1193. exports.resetTracking = resetTracking;
  1194. exports.shallowReactive = shallowReactive;
  1195. exports.shallowReadonly = shallowReadonly;
  1196. exports.shallowRef = shallowRef;
  1197. exports.stop = stop;
  1198. exports.toRaw = toRaw;
  1199. exports.toRef = toRef;
  1200. exports.toRefs = toRefs;
  1201. exports.track = track;
  1202. exports.trigger = trigger;
  1203. exports.triggerRef = triggerRef;
  1204. exports.unref = unref;