UNPKG

530 kBJavaScriptView Raw
1/**
2 * Make a map and return a function for checking if a key
3 * is in that map.
4 * IMPORTANT: all calls of this function must be prefixed with
5 * \/\*#\_\_PURE\_\_\*\/
6 * So that rollup can tree-shake them if necessary.
7 */
8function makeMap(str, expectsLowerCase) {
9 const map = Object.create(null);
10 const list = str.split(',');
11 for (let i = 0; i < list.length; i++) {
12 map[list[i]] = true;
13 }
14 return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val];
15}
16
17/**
18 * dev only flag -> name mapping
19 */
20const PatchFlagNames = {
21 [1 /* TEXT */]: `TEXT`,
22 [2 /* CLASS */]: `CLASS`,
23 [4 /* STYLE */]: `STYLE`,
24 [8 /* PROPS */]: `PROPS`,
25 [16 /* FULL_PROPS */]: `FULL_PROPS`,
26 [32 /* HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
27 [64 /* STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
28 [128 /* KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
29 [256 /* UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
30 [512 /* NEED_PATCH */]: `NEED_PATCH`,
31 [1024 /* DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
32 [2048 /* DEV_ROOT_FRAGMENT */]: `DEV_ROOT_FRAGMENT`,
33 [-1 /* HOISTED */]: `HOISTED`,
34 [-2 /* BAIL */]: `BAIL`
35};
36
37/**
38 * Dev only
39 */
40const slotFlagsText = {
41 [1 /* STABLE */]: 'STABLE',
42 [2 /* DYNAMIC */]: 'DYNAMIC',
43 [3 /* FORWARDED */]: 'FORWARDED'
44};
45
46const GLOBALS_WHITE_LISTED = 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' +
47 'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' +
48 'Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt';
49const isGloballyWhitelisted = /*#__PURE__*/ makeMap(GLOBALS_WHITE_LISTED);
50
51const range = 2;
52function generateCodeFrame(source, start = 0, end = source.length) {
53 const lines = source.split(/\r?\n/);
54 let count = 0;
55 const res = [];
56 for (let i = 0; i < lines.length; i++) {
57 count += lines[i].length + 1;
58 if (count >= start) {
59 for (let j = i - range; j <= i + range || end > count; j++) {
60 if (j < 0 || j >= lines.length)
61 continue;
62 const line = j + 1;
63 res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
64 const lineLength = lines[j].length;
65 if (j === i) {
66 // push underline
67 const pad = start - (count - lineLength) + 1;
68 const length = Math.max(1, end > count ? lineLength - pad : end - start);
69 res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
70 }
71 else if (j > i) {
72 if (end > count) {
73 const length = Math.max(Math.min(end - count, lineLength), 1);
74 res.push(` | ` + '^'.repeat(length));
75 }
76 count += lineLength + 1;
77 }
78 }
79 break;
80 }
81 }
82 return res.join('\n');
83}
84
85/**
86 * On the client we only need to offer special cases for boolean attributes that
87 * have different names from their corresponding dom properties:
88 * - itemscope -> N/A
89 * - allowfullscreen -> allowFullscreen
90 * - formnovalidate -> formNoValidate
91 * - ismap -> isMap
92 * - nomodule -> noModule
93 * - novalidate -> noValidate
94 * - readonly -> readOnly
95 */
96const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
97const isSpecialBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs);
98
99function normalizeStyle(value) {
100 if (isArray(value)) {
101 const res = {};
102 for (let i = 0; i < value.length; i++) {
103 const item = value[i];
104 const normalized = normalizeStyle(isString(item) ? parseStringStyle(item) : item);
105 if (normalized) {
106 for (const key in normalized) {
107 res[key] = normalized[key];
108 }
109 }
110 }
111 return res;
112 }
113 else if (isObject(value)) {
114 return value;
115 }
116}
117const listDelimiterRE = /;(?![^(]*\))/g;
118const propertyDelimiterRE = /:(.+)/;
119function parseStringStyle(cssText) {
120 const ret = {};
121 cssText.split(listDelimiterRE).forEach(item => {
122 if (item) {
123 const tmp = item.split(propertyDelimiterRE);
124 tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
125 }
126 });
127 return ret;
128}
129function normalizeClass(value) {
130 let res = '';
131 if (isString(value)) {
132 res = value;
133 }
134 else if (isArray(value)) {
135 for (let i = 0; i < value.length; i++) {
136 const normalized = normalizeClass(value[i]);
137 if (normalized) {
138 res += normalized + ' ';
139 }
140 }
141 }
142 else if (isObject(value)) {
143 for (const name in value) {
144 if (value[name]) {
145 res += name + ' ';
146 }
147 }
148 }
149 return res.trim();
150}
151
152// These tag configs are shared between compiler-dom and runtime-dom, so they
153// https://developer.mozilla.org/en-US/docs/Web/HTML/Element
154const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
155 'header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,' +
156 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
157 'data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,' +
158 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
159 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
160 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
161 'option,output,progress,select,textarea,details,dialog,menu,' +
162 'summary,template,blockquote,iframe,tfoot';
163// https://developer.mozilla.org/en-US/docs/Web/SVG/Element
164const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
165 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
166 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
167 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
168 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
169 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
170 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
171 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
172 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
173 'text,textPath,title,tspan,unknown,use,view';
174const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
175const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
176const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
177const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
178
179function looseCompareArrays(a, b) {
180 if (a.length !== b.length)
181 return false;
182 let equal = true;
183 for (let i = 0; equal && i < a.length; i++) {
184 equal = looseEqual(a[i], b[i]);
185 }
186 return equal;
187}
188function looseEqual(a, b) {
189 if (a === b)
190 return true;
191 let aValidType = isDate(a);
192 let bValidType = isDate(b);
193 if (aValidType || bValidType) {
194 return aValidType && bValidType ? a.getTime() === b.getTime() : false;
195 }
196 aValidType = isArray(a);
197 bValidType = isArray(b);
198 if (aValidType || bValidType) {
199 return aValidType && bValidType ? looseCompareArrays(a, b) : false;
200 }
201 aValidType = isObject(a);
202 bValidType = isObject(b);
203 if (aValidType || bValidType) {
204 /* istanbul ignore if: this if will probably never be called */
205 if (!aValidType || !bValidType) {
206 return false;
207 }
208 const aKeysCount = Object.keys(a).length;
209 const bKeysCount = Object.keys(b).length;
210 if (aKeysCount !== bKeysCount) {
211 return false;
212 }
213 for (const key in a) {
214 const aHasKey = a.hasOwnProperty(key);
215 const bHasKey = b.hasOwnProperty(key);
216 if ((aHasKey && !bHasKey) ||
217 (!aHasKey && bHasKey) ||
218 !looseEqual(a[key], b[key])) {
219 return false;
220 }
221 }
222 }
223 return String(a) === String(b);
224}
225function looseIndexOf(arr, val) {
226 return arr.findIndex(item => looseEqual(item, val));
227}
228
229/**
230 * For converting {{ interpolation }} values to displayed strings.
231 * @private
232 */
233const toDisplayString = (val) => {
234 return val == null
235 ? ''
236 : isObject(val)
237 ? JSON.stringify(val, replacer, 2)
238 : String(val);
239};
240const replacer = (_key, val) => {
241 if (isMap(val)) {
242 return {
243 [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
244 entries[`${key} =>`] = val;
245 return entries;
246 }, {})
247 };
248 }
249 else if (isSet(val)) {
250 return {
251 [`Set(${val.size})`]: [...val.values()]
252 };
253 }
254 else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
255 return String(val);
256 }
257 return val;
258};
259
260const EMPTY_OBJ = Object.freeze({})
261 ;
262const EMPTY_ARR = Object.freeze([]) ;
263const NOOP = () => { };
264/**
265 * Always return false.
266 */
267const NO = () => false;
268const onRE = /^on[^a-z]/;
269const isOn = (key) => onRE.test(key);
270const isModelListener = (key) => key.startsWith('onUpdate:');
271const extend = Object.assign;
272const remove = (arr, el) => {
273 const i = arr.indexOf(el);
274 if (i > -1) {
275 arr.splice(i, 1);
276 }
277};
278const hasOwnProperty = Object.prototype.hasOwnProperty;
279const hasOwn = (val, key) => hasOwnProperty.call(val, key);
280const isArray = Array.isArray;
281const isMap = (val) => toTypeString(val) === '[object Map]';
282const isSet = (val) => toTypeString(val) === '[object Set]';
283const isDate = (val) => val instanceof Date;
284const isFunction = (val) => typeof val === 'function';
285const isString = (val) => typeof val === 'string';
286const isSymbol = (val) => typeof val === 'symbol';
287const isObject = (val) => val !== null && typeof val === 'object';
288const isPromise = (val) => {
289 return isObject(val) && isFunction(val.then) && isFunction(val.catch);
290};
291const objectToString = Object.prototype.toString;
292const toTypeString = (value) => objectToString.call(value);
293const toRawType = (value) => {
294 // extract "RawType" from strings like "[object RawType]"
295 return toTypeString(value).slice(8, -1);
296};
297const isPlainObject = (val) => toTypeString(val) === '[object Object]';
298const isIntegerKey = (key) => isString(key) &&
299 key !== 'NaN' &&
300 key[0] !== '-' &&
301 '' + parseInt(key, 10) === key;
302const isReservedProp = /*#__PURE__*/ makeMap(
303// the leading comma is intentional so empty string "" is also included
304',key,ref,' +
305 'onVnodeBeforeMount,onVnodeMounted,' +
306 'onVnodeBeforeUpdate,onVnodeUpdated,' +
307 'onVnodeBeforeUnmount,onVnodeUnmounted');
308const cacheStringFunction = (fn) => {
309 const cache = Object.create(null);
310 return ((str) => {
311 const hit = cache[str];
312 return hit || (cache[str] = fn(str));
313 });
314};
315const camelizeRE = /-(\w)/g;
316/**
317 * @private
318 */
319const camelize = cacheStringFunction((str) => {
320 return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
321});
322const hyphenateRE = /\B([A-Z])/g;
323/**
324 * @private
325 */
326const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
327/**
328 * @private
329 */
330const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
331/**
332 * @private
333 */
334const toHandlerKey = cacheStringFunction((str) => (str ? `on${capitalize(str)}` : ``));
335// compare whether a value has changed, accounting for NaN.
336const hasChanged = (value, oldValue) => value !== oldValue && (value === value || oldValue === oldValue);
337const invokeArrayFns = (fns, arg) => {
338 for (let i = 0; i < fns.length; i++) {
339 fns[i](arg);
340 }
341};
342const def = (obj, key, value) => {
343 Object.defineProperty(obj, key, {
344 configurable: true,
345 enumerable: false,
346 value
347 });
348};
349const toNumber = (val) => {
350 const n = parseFloat(val);
351 return isNaN(n) ? val : n;
352};
353let _globalThis;
354const getGlobalThis = () => {
355 return (_globalThis ||
356 (_globalThis =
357 typeof globalThis !== 'undefined'
358 ? globalThis
359 : typeof self !== 'undefined'
360 ? self
361 : typeof window !== 'undefined'
362 ? window
363 : typeof global !== 'undefined'
364 ? global
365 : {}));
366};
367
368const targetMap = new WeakMap();
369const effectStack = [];
370let activeEffect;
371const ITERATE_KEY = Symbol('iterate' );
372const MAP_KEY_ITERATE_KEY = Symbol('Map key iterate' );
373function isEffect(fn) {
374 return fn && fn._isEffect === true;
375}
376function effect(fn, options = EMPTY_OBJ) {
377 if (isEffect(fn)) {
378 fn = fn.raw;
379 }
380 const effect = createReactiveEffect(fn, options);
381 if (!options.lazy) {
382 effect();
383 }
384 return effect;
385}
386function stop(effect) {
387 if (effect.active) {
388 cleanup(effect);
389 if (effect.options.onStop) {
390 effect.options.onStop();
391 }
392 effect.active = false;
393 }
394}
395let uid = 0;
396function createReactiveEffect(fn, options) {
397 const effect = function reactiveEffect() {
398 if (!effect.active) {
399 return options.scheduler ? undefined : fn();
400 }
401 if (!effectStack.includes(effect)) {
402 cleanup(effect);
403 try {
404 enableTracking();
405 effectStack.push(effect);
406 activeEffect = effect;
407 return fn();
408 }
409 finally {
410 effectStack.pop();
411 resetTracking();
412 activeEffect = effectStack[effectStack.length - 1];
413 }
414 }
415 };
416 effect.id = uid++;
417 effect.allowRecurse = !!options.allowRecurse;
418 effect._isEffect = true;
419 effect.active = true;
420 effect.raw = fn;
421 effect.deps = [];
422 effect.options = options;
423 return effect;
424}
425function cleanup(effect) {
426 const { deps } = effect;
427 if (deps.length) {
428 for (let i = 0; i < deps.length; i++) {
429 deps[i].delete(effect);
430 }
431 deps.length = 0;
432 }
433}
434let shouldTrack = true;
435const trackStack = [];
436function pauseTracking() {
437 trackStack.push(shouldTrack);
438 shouldTrack = false;
439}
440function enableTracking() {
441 trackStack.push(shouldTrack);
442 shouldTrack = true;
443}
444function resetTracking() {
445 const last = trackStack.pop();
446 shouldTrack = last === undefined ? true : last;
447}
448function track(target, type, key) {
449 if (!shouldTrack || activeEffect === undefined) {
450 return;
451 }
452 let depsMap = targetMap.get(target);
453 if (!depsMap) {
454 targetMap.set(target, (depsMap = new Map()));
455 }
456 let dep = depsMap.get(key);
457 if (!dep) {
458 depsMap.set(key, (dep = new Set()));
459 }
460 if (!dep.has(activeEffect)) {
461 dep.add(activeEffect);
462 activeEffect.deps.push(dep);
463 if (activeEffect.options.onTrack) {
464 activeEffect.options.onTrack({
465 effect: activeEffect,
466 target,
467 type,
468 key
469 });
470 }
471 }
472}
473function trigger(target, type, key, newValue, oldValue, oldTarget) {
474 const depsMap = targetMap.get(target);
475 if (!depsMap) {
476 // never been tracked
477 return;
478 }
479 const effects = new Set();
480 const add = (effectsToAdd) => {
481 if (effectsToAdd) {
482 effectsToAdd.forEach(effect => {
483 if (effect !== activeEffect || effect.allowRecurse) {
484 effects.add(effect);
485 }
486 });
487 }
488 };
489 if (type === "clear" /* CLEAR */) {
490 // collection being cleared
491 // trigger all effects for target
492 depsMap.forEach(add);
493 }
494 else if (key === 'length' && isArray(target)) {
495 depsMap.forEach((dep, key) => {
496 if (key === 'length' || key >= newValue) {
497 add(dep);
498 }
499 });
500 }
501 else {
502 // schedule runs for SET | ADD | DELETE
503 if (key !== void 0) {
504 add(depsMap.get(key));
505 }
506 // also run for iteration key on ADD | DELETE | Map.SET
507 switch (type) {
508 case "add" /* ADD */:
509 if (!isArray(target)) {
510 add(depsMap.get(ITERATE_KEY));
511 if (isMap(target)) {
512 add(depsMap.get(MAP_KEY_ITERATE_KEY));
513 }
514 }
515 else if (isIntegerKey(key)) {
516 // new index added to array -> length changes
517 add(depsMap.get('length'));
518 }
519 break;
520 case "delete" /* DELETE */:
521 if (!isArray(target)) {
522 add(depsMap.get(ITERATE_KEY));
523 if (isMap(target)) {
524 add(depsMap.get(MAP_KEY_ITERATE_KEY));
525 }
526 }
527 break;
528 case "set" /* SET */:
529 if (isMap(target)) {
530 add(depsMap.get(ITERATE_KEY));
531 }
532 break;
533 }
534 }
535 const run = (effect) => {
536 if (effect.options.onTrigger) {
537 effect.options.onTrigger({
538 effect,
539 target,
540 key,
541 type,
542 newValue,
543 oldValue,
544 oldTarget
545 });
546 }
547 if (effect.options.scheduler) {
548 effect.options.scheduler(effect);
549 }
550 else {
551 effect();
552 }
553 };
554 effects.forEach(run);
555}
556
557const isNonTrackableKeys = /*#__PURE__*/ makeMap(`__proto__,__v_isRef,__isVue`);
558const builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol)
559 .map(key => Symbol[key])
560 .filter(isSymbol));
561const get = /*#__PURE__*/ createGetter();
562const shallowGet = /*#__PURE__*/ createGetter(false, true);
563const readonlyGet = /*#__PURE__*/ createGetter(true);
564const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
565const arrayInstrumentations = {};
566['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
567 const method = Array.prototype[key];
568 arrayInstrumentations[key] = function (...args) {
569 const arr = toRaw(this);
570 for (let i = 0, l = this.length; i < l; i++) {
571 track(arr, "get" /* GET */, i + '');
572 }
573 // we run the method using the original args first (which may be reactive)
574 const res = method.apply(arr, args);
575 if (res === -1 || res === false) {
576 // if that didn't work, run it again using raw values.
577 return method.apply(arr, args.map(toRaw));
578 }
579 else {
580 return res;
581 }
582 };
583});
584['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
585 const method = Array.prototype[key];
586 arrayInstrumentations[key] = function (...args) {
587 pauseTracking();
588 const res = method.apply(this, args);
589 resetTracking();
590 return res;
591 };
592});
593function createGetter(isReadonly = false, shallow = false) {
594 return function get(target, key, receiver) {
595 if (key === "__v_isReactive" /* IS_REACTIVE */) {
596 return !isReadonly;
597 }
598 else if (key === "__v_isReadonly" /* IS_READONLY */) {
599 return isReadonly;
600 }
601 else if (key === "__v_raw" /* RAW */ &&
602 receiver ===
603 (isReadonly
604 ? shallow
605 ? shallowReadonlyMap
606 : readonlyMap
607 : shallow
608 ? shallowReactiveMap
609 : reactiveMap).get(target)) {
610 return target;
611 }
612 const targetIsArray = isArray(target);
613 if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) {
614 return Reflect.get(arrayInstrumentations, key, receiver);
615 }
616 const res = Reflect.get(target, key, receiver);
617 if (isSymbol(key)
618 ? builtInSymbols.has(key)
619 : isNonTrackableKeys(key)) {
620 return res;
621 }
622 if (!isReadonly) {
623 track(target, "get" /* GET */, key);
624 }
625 if (shallow) {
626 return res;
627 }
628 if (isRef(res)) {
629 // ref unwrapping - does not apply for Array + integer key.
630 const shouldUnwrap = !targetIsArray || !isIntegerKey(key);
631 return shouldUnwrap ? res.value : res;
632 }
633 if (isObject(res)) {
634 // Convert returned value into a proxy as well. we do the isObject check
635 // here to avoid invalid value warning. Also need to lazy access readonly
636 // and reactive here to avoid circular dependency.
637 return isReadonly ? readonly(res) : reactive(res);
638 }
639 return res;
640 };
641}
642const set = /*#__PURE__*/ createSetter();
643const shallowSet = /*#__PURE__*/ createSetter(true);
644function createSetter(shallow = false) {
645 return function set(target, key, value, receiver) {
646 let oldValue = target[key];
647 if (!shallow) {
648 value = toRaw(value);
649 oldValue = toRaw(oldValue);
650 if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
651 oldValue.value = value;
652 return true;
653 }
654 }
655 const hadKey = isArray(target) && isIntegerKey(key)
656 ? Number(key) < target.length
657 : hasOwn(target, key);
658 const result = Reflect.set(target, key, value, receiver);
659 // don't trigger if target is something up in the prototype chain of original
660 if (target === toRaw(receiver)) {
661 if (!hadKey) {
662 trigger(target, "add" /* ADD */, key, value);
663 }
664 else if (hasChanged(value, oldValue)) {
665 trigger(target, "set" /* SET */, key, value, oldValue);
666 }
667 }
668 return result;
669 };
670}
671function deleteProperty(target, key) {
672 const hadKey = hasOwn(target, key);
673 const oldValue = target[key];
674 const result = Reflect.deleteProperty(target, key);
675 if (result && hadKey) {
676 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
677 }
678 return result;
679}
680function has(target, key) {
681 const result = Reflect.has(target, key);
682 if (!isSymbol(key) || !builtInSymbols.has(key)) {
683 track(target, "has" /* HAS */, key);
684 }
685 return result;
686}
687function ownKeys(target) {
688 track(target, "iterate" /* ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
689 return Reflect.ownKeys(target);
690}
691const mutableHandlers = {
692 get,
693 set,
694 deleteProperty,
695 has,
696 ownKeys
697};
698const readonlyHandlers = {
699 get: readonlyGet,
700 set(target, key) {
701 {
702 console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
703 }
704 return true;
705 },
706 deleteProperty(target, key) {
707 {
708 console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
709 }
710 return true;
711 }
712};
713const shallowReactiveHandlers = extend({}, mutableHandlers, {
714 get: shallowGet,
715 set: shallowSet
716});
717// Props handlers are special in the sense that it should not unwrap top-level
718// refs (in order to allow refs to be explicitly passed down), but should
719// retain the reactivity of the normal readonly object.
720const shallowReadonlyHandlers = extend({}, readonlyHandlers, {
721 get: shallowReadonlyGet
722});
723
724const toReactive = (value) => isObject(value) ? reactive(value) : value;
725const toReadonly = (value) => isObject(value) ? readonly(value) : value;
726const toShallow = (value) => value;
727const getProto = (v) => Reflect.getPrototypeOf(v);
728function get$1(target, key, isReadonly = false, isShallow = false) {
729 // #1772: readonly(reactive(Map)) should return readonly + reactive version
730 // of the value
731 target = target["__v_raw" /* RAW */];
732 const rawTarget = toRaw(target);
733 const rawKey = toRaw(key);
734 if (key !== rawKey) {
735 !isReadonly && track(rawTarget, "get" /* GET */, key);
736 }
737 !isReadonly && track(rawTarget, "get" /* GET */, rawKey);
738 const { has } = getProto(rawTarget);
739 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
740 if (has.call(rawTarget, key)) {
741 return wrap(target.get(key));
742 }
743 else if (has.call(rawTarget, rawKey)) {
744 return wrap(target.get(rawKey));
745 }
746}
747function has$1(key, isReadonly = false) {
748 const target = this["__v_raw" /* RAW */];
749 const rawTarget = toRaw(target);
750 const rawKey = toRaw(key);
751 if (key !== rawKey) {
752 !isReadonly && track(rawTarget, "has" /* HAS */, key);
753 }
754 !isReadonly && track(rawTarget, "has" /* HAS */, rawKey);
755 return key === rawKey
756 ? target.has(key)
757 : target.has(key) || target.has(rawKey);
758}
759function size(target, isReadonly = false) {
760 target = target["__v_raw" /* RAW */];
761 !isReadonly && track(toRaw(target), "iterate" /* ITERATE */, ITERATE_KEY);
762 return Reflect.get(target, 'size', target);
763}
764function add(value) {
765 value = toRaw(value);
766 const target = toRaw(this);
767 const proto = getProto(target);
768 const hadKey = proto.has.call(target, value);
769 if (!hadKey) {
770 target.add(value);
771 trigger(target, "add" /* ADD */, value, value);
772 }
773 return this;
774}
775function set$1(key, value) {
776 value = toRaw(value);
777 const target = toRaw(this);
778 const { has, get } = getProto(target);
779 let hadKey = has.call(target, key);
780 if (!hadKey) {
781 key = toRaw(key);
782 hadKey = has.call(target, key);
783 }
784 else {
785 checkIdentityKeys(target, has, key);
786 }
787 const oldValue = get.call(target, key);
788 target.set(key, value);
789 if (!hadKey) {
790 trigger(target, "add" /* ADD */, key, value);
791 }
792 else if (hasChanged(value, oldValue)) {
793 trigger(target, "set" /* SET */, key, value, oldValue);
794 }
795 return this;
796}
797function deleteEntry(key) {
798 const target = toRaw(this);
799 const { has, get } = getProto(target);
800 let hadKey = has.call(target, key);
801 if (!hadKey) {
802 key = toRaw(key);
803 hadKey = has.call(target, key);
804 }
805 else {
806 checkIdentityKeys(target, has, key);
807 }
808 const oldValue = get ? get.call(target, key) : undefined;
809 // forward the operation before queueing reactions
810 const result = target.delete(key);
811 if (hadKey) {
812 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
813 }
814 return result;
815}
816function clear() {
817 const target = toRaw(this);
818 const hadItems = target.size !== 0;
819 const oldTarget = isMap(target)
820 ? new Map(target)
821 : new Set(target)
822 ;
823 // forward the operation before queueing reactions
824 const result = target.clear();
825 if (hadItems) {
826 trigger(target, "clear" /* CLEAR */, undefined, undefined, oldTarget);
827 }
828 return result;
829}
830function createForEach(isReadonly, isShallow) {
831 return function forEach(callback, thisArg) {
832 const observed = this;
833 const target = observed["__v_raw" /* RAW */];
834 const rawTarget = toRaw(target);
835 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
836 !isReadonly && track(rawTarget, "iterate" /* ITERATE */, ITERATE_KEY);
837 return target.forEach((value, key) => {
838 // important: make sure the callback is
839 // 1. invoked with the reactive map as `this` and 3rd arg
840 // 2. the value received should be a corresponding reactive/readonly.
841 return callback.call(thisArg, wrap(value), wrap(key), observed);
842 });
843 };
844}
845function createIterableMethod(method, isReadonly, isShallow) {
846 return function (...args) {
847 const target = this["__v_raw" /* RAW */];
848 const rawTarget = toRaw(target);
849 const targetIsMap = isMap(rawTarget);
850 const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
851 const isKeyOnly = method === 'keys' && targetIsMap;
852 const innerIterator = target[method](...args);
853 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
854 !isReadonly &&
855 track(rawTarget, "iterate" /* ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
856 // return a wrapped iterator which returns observed versions of the
857 // values emitted from the real iterator
858 return {
859 // iterator protocol
860 next() {
861 const { value, done } = innerIterator.next();
862 return done
863 ? { value, done }
864 : {
865 value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
866 done
867 };
868 },
869 // iterable protocol
870 [Symbol.iterator]() {
871 return this;
872 }
873 };
874 };
875}
876function createReadonlyMethod(type) {
877 return function (...args) {
878 {
879 const key = args[0] ? `on key "${args[0]}" ` : ``;
880 console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
881 }
882 return type === "delete" /* DELETE */ ? false : this;
883 };
884}
885const mutableInstrumentations = {
886 get(key) {
887 return get$1(this, key);
888 },
889 get size() {
890 return size(this);
891 },
892 has: has$1,
893 add,
894 set: set$1,
895 delete: deleteEntry,
896 clear,
897 forEach: createForEach(false, false)
898};
899const shallowInstrumentations = {
900 get(key) {
901 return get$1(this, key, false, true);
902 },
903 get size() {
904 return size(this);
905 },
906 has: has$1,
907 add,
908 set: set$1,
909 delete: deleteEntry,
910 clear,
911 forEach: createForEach(false, true)
912};
913const readonlyInstrumentations = {
914 get(key) {
915 return get$1(this, key, true);
916 },
917 get size() {
918 return size(this, true);
919 },
920 has(key) {
921 return has$1.call(this, key, true);
922 },
923 add: createReadonlyMethod("add" /* ADD */),
924 set: createReadonlyMethod("set" /* SET */),
925 delete: createReadonlyMethod("delete" /* DELETE */),
926 clear: createReadonlyMethod("clear" /* CLEAR */),
927 forEach: createForEach(true, false)
928};
929const shallowReadonlyInstrumentations = {
930 get(key) {
931 return get$1(this, key, true, true);
932 },
933 get size() {
934 return size(this, true);
935 },
936 has(key) {
937 return has$1.call(this, key, true);
938 },
939 add: createReadonlyMethod("add" /* ADD */),
940 set: createReadonlyMethod("set" /* SET */),
941 delete: createReadonlyMethod("delete" /* DELETE */),
942 clear: createReadonlyMethod("clear" /* CLEAR */),
943 forEach: createForEach(true, true)
944};
945const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
946iteratorMethods.forEach(method => {
947 mutableInstrumentations[method] = createIterableMethod(method, false, false);
948 readonlyInstrumentations[method] = createIterableMethod(method, true, false);
949 shallowInstrumentations[method] = createIterableMethod(method, false, true);
950 shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true);
951});
952function createInstrumentationGetter(isReadonly, shallow) {
953 const instrumentations = shallow
954 ? isReadonly
955 ? shallowReadonlyInstrumentations
956 : shallowInstrumentations
957 : isReadonly
958 ? readonlyInstrumentations
959 : mutableInstrumentations;
960 return (target, key, receiver) => {
961 if (key === "__v_isReactive" /* IS_REACTIVE */) {
962 return !isReadonly;
963 }
964 else if (key === "__v_isReadonly" /* IS_READONLY */) {
965 return isReadonly;
966 }
967 else if (key === "__v_raw" /* RAW */) {
968 return target;
969 }
970 return Reflect.get(hasOwn(instrumentations, key) && key in target
971 ? instrumentations
972 : target, key, receiver);
973 };
974}
975const mutableCollectionHandlers = {
976 get: createInstrumentationGetter(false, false)
977};
978const shallowCollectionHandlers = {
979 get: createInstrumentationGetter(false, true)
980};
981const readonlyCollectionHandlers = {
982 get: createInstrumentationGetter(true, false)
983};
984const shallowReadonlyCollectionHandlers = {
985 get: createInstrumentationGetter(true, true)
986};
987function checkIdentityKeys(target, has, key) {
988 const rawKey = toRaw(key);
989 if (rawKey !== key && has.call(target, rawKey)) {
990 const type = toRawType(target);
991 console.warn(`Reactive ${type} contains both the raw and reactive ` +
992 `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
993 `which can lead to inconsistencies. ` +
994 `Avoid differentiating between the raw and reactive versions ` +
995 `of an object and only use the reactive version if possible.`);
996 }
997}
998
999const reactiveMap = new WeakMap();
1000const shallowReactiveMap = new WeakMap();
1001const readonlyMap = new WeakMap();
1002const shallowReadonlyMap = new WeakMap();
1003function targetTypeMap(rawType) {
1004 switch (rawType) {
1005 case 'Object':
1006 case 'Array':
1007 return 1 /* COMMON */;
1008 case 'Map':
1009 case 'Set':
1010 case 'WeakMap':
1011 case 'WeakSet':
1012 return 2 /* COLLECTION */;
1013 default:
1014 return 0 /* INVALID */;
1015 }
1016}
1017function getTargetType(value) {
1018 return value["__v_skip" /* SKIP */] || !Object.isExtensible(value)
1019 ? 0 /* INVALID */
1020 : targetTypeMap(toRawType(value));
1021}
1022function reactive(target) {
1023 // if trying to observe a readonly proxy, return the readonly version.
1024 if (target && target["__v_isReadonly" /* IS_READONLY */]) {
1025 return target;
1026 }
1027 return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
1028}
1029/**
1030 * Return a shallowly-reactive copy of the original object, where only the root
1031 * level properties are reactive. It also does not auto-unwrap refs (even at the
1032 * root level).
1033 */
1034function shallowReactive(target) {
1035 return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
1036}
1037/**
1038 * Creates a readonly copy of the original object. Note the returned copy is not
1039 * made reactive, but `readonly` can be called on an already reactive object.
1040 */
1041function readonly(target) {
1042 return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
1043}
1044/**
1045 * Returns a reactive-copy of the original object, where only the root level
1046 * properties are readonly, and does NOT unwrap refs nor recursively convert
1047 * returned properties.
1048 * This is used for creating the props proxy object for stateful components.
1049 */
1050function shallowReadonly(target) {
1051 return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap);
1052}
1053function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) {
1054 if (!isObject(target)) {
1055 {
1056 console.warn(`value cannot be made reactive: ${String(target)}`);
1057 }
1058 return target;
1059 }
1060 // target is already a Proxy, return it.
1061 // exception: calling readonly() on a reactive object
1062 if (target["__v_raw" /* RAW */] &&
1063 !(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) {
1064 return target;
1065 }
1066 // target already has corresponding Proxy
1067 const existingProxy = proxyMap.get(target);
1068 if (existingProxy) {
1069 return existingProxy;
1070 }
1071 // only a whitelist of value types can be observed.
1072 const targetType = getTargetType(target);
1073 if (targetType === 0 /* INVALID */) {
1074 return target;
1075 }
1076 const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers);
1077 proxyMap.set(target, proxy);
1078 return proxy;
1079}
1080function isReactive(value) {
1081 if (isReadonly(value)) {
1082 return isReactive(value["__v_raw" /* RAW */]);
1083 }
1084 return !!(value && value["__v_isReactive" /* IS_REACTIVE */]);
1085}
1086function isReadonly(value) {
1087 return !!(value && value["__v_isReadonly" /* IS_READONLY */]);
1088}
1089function isProxy(value) {
1090 return isReactive(value) || isReadonly(value);
1091}
1092function toRaw(observed) {
1093 return ((observed && toRaw(observed["__v_raw" /* RAW */])) || observed);
1094}
1095function markRaw(value) {
1096 def(value, "__v_skip" /* SKIP */, true);
1097 return value;
1098}
1099
1100const convert = (val) => isObject(val) ? reactive(val) : val;
1101function isRef(r) {
1102 return Boolean(r && r.__v_isRef === true);
1103}
1104function ref(value) {
1105 return createRef(value);
1106}
1107function shallowRef(value) {
1108 return createRef(value, true);
1109}
1110class RefImpl {
1111 constructor(_rawValue, _shallow = false) {
1112 this._rawValue = _rawValue;
1113 this._shallow = _shallow;
1114 this.__v_isRef = true;
1115 this._value = _shallow ? _rawValue : convert(_rawValue);
1116 }
1117 get value() {
1118 track(toRaw(this), "get" /* GET */, 'value');
1119 return this._value;
1120 }
1121 set value(newVal) {
1122 if (hasChanged(toRaw(newVal), this._rawValue)) {
1123 this._rawValue = newVal;
1124 this._value = this._shallow ? newVal : convert(newVal);
1125 trigger(toRaw(this), "set" /* SET */, 'value', newVal);
1126 }
1127 }
1128}
1129function createRef(rawValue, shallow = false) {
1130 if (isRef(rawValue)) {
1131 return rawValue;
1132 }
1133 return new RefImpl(rawValue, shallow);
1134}
1135function triggerRef(ref) {
1136 trigger(toRaw(ref), "set" /* SET */, 'value', ref.value );
1137}
1138function unref(ref) {
1139 return isRef(ref) ? ref.value : ref;
1140}
1141const shallowUnwrapHandlers = {
1142 get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
1143 set: (target, key, value, receiver) => {
1144 const oldValue = target[key];
1145 if (isRef(oldValue) && !isRef(value)) {
1146 oldValue.value = value;
1147 return true;
1148 }
1149 else {
1150 return Reflect.set(target, key, value, receiver);
1151 }
1152 }
1153};
1154function proxyRefs(objectWithRefs) {
1155 return isReactive(objectWithRefs)
1156 ? objectWithRefs
1157 : new Proxy(objectWithRefs, shallowUnwrapHandlers);
1158}
1159class CustomRefImpl {
1160 constructor(factory) {
1161 this.__v_isRef = true;
1162 const { get, set } = factory(() => track(this, "get" /* GET */, 'value'), () => trigger(this, "set" /* SET */, 'value'));
1163 this._get = get;
1164 this._set = set;
1165 }
1166 get value() {
1167 return this._get();
1168 }
1169 set value(newVal) {
1170 this._set(newVal);
1171 }
1172}
1173function customRef(factory) {
1174 return new CustomRefImpl(factory);
1175}
1176function toRefs(object) {
1177 if (!isProxy(object)) {
1178 console.warn(`toRefs() expects a reactive object but received a plain one.`);
1179 }
1180 const ret = isArray(object) ? new Array(object.length) : {};
1181 for (const key in object) {
1182 ret[key] = toRef(object, key);
1183 }
1184 return ret;
1185}
1186class ObjectRefImpl {
1187 constructor(_object, _key) {
1188 this._object = _object;
1189 this._key = _key;
1190 this.__v_isRef = true;
1191 }
1192 get value() {
1193 return this._object[this._key];
1194 }
1195 set value(newVal) {
1196 this._object[this._key] = newVal;
1197 }
1198}
1199function toRef(object, key) {
1200 return isRef(object[key])
1201 ? object[key]
1202 : new ObjectRefImpl(object, key);
1203}
1204
1205class ComputedRefImpl {
1206 constructor(getter, _setter, isReadonly) {
1207 this._setter = _setter;
1208 this._dirty = true;
1209 this.__v_isRef = true;
1210 this.effect = effect(getter, {
1211 lazy: true,
1212 scheduler: () => {
1213 if (!this._dirty) {
1214 this._dirty = true;
1215 trigger(toRaw(this), "set" /* SET */, 'value');
1216 }
1217 }
1218 });
1219 this["__v_isReadonly" /* IS_READONLY */] = isReadonly;
1220 }
1221 get value() {
1222 // the computed ref may get wrapped by other proxies e.g. readonly() #3376
1223 const self = toRaw(this);
1224 if (self._dirty) {
1225 self._value = this.effect();
1226 self._dirty = false;
1227 }
1228 track(self, "get" /* GET */, 'value');
1229 return self._value;
1230 }
1231 set value(newValue) {
1232 this._setter(newValue);
1233 }
1234}
1235function computed(getterOrOptions) {
1236 let getter;
1237 let setter;
1238 if (isFunction(getterOrOptions)) {
1239 getter = getterOrOptions;
1240 setter = () => {
1241 console.warn('Write operation failed: computed value is readonly');
1242 }
1243 ;
1244 }
1245 else {
1246 getter = getterOrOptions.get;
1247 setter = getterOrOptions.set;
1248 }
1249 return new ComputedRefImpl(getter, setter, isFunction(getterOrOptions) || !getterOrOptions.set);
1250}
1251
1252const stack = [];
1253function pushWarningContext(vnode) {
1254 stack.push(vnode);
1255}
1256function popWarningContext() {
1257 stack.pop();
1258}
1259function warn(msg, ...args) {
1260 // avoid props formatting or warn handler tracking deps that might be mutated
1261 // during patch, leading to infinite recursion.
1262 pauseTracking();
1263 const instance = stack.length ? stack[stack.length - 1].component : null;
1264 const appWarnHandler = instance && instance.appContext.config.warnHandler;
1265 const trace = getComponentTrace();
1266 if (appWarnHandler) {
1267 callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [
1268 msg + args.join(''),
1269 instance && instance.proxy,
1270 trace
1271 .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
1272 .join('\n'),
1273 trace
1274 ]);
1275 }
1276 else {
1277 const warnArgs = [`[Vue warn]: ${msg}`, ...args];
1278 /* istanbul ignore if */
1279 if (trace.length &&
1280 // avoid spamming console during tests
1281 !false) {
1282 warnArgs.push(`\n`, ...formatTrace(trace));
1283 }
1284 console.warn(...warnArgs);
1285 }
1286 resetTracking();
1287}
1288function getComponentTrace() {
1289 let currentVNode = stack[stack.length - 1];
1290 if (!currentVNode) {
1291 return [];
1292 }
1293 // we can't just use the stack because it will be incomplete during updates
1294 // that did not start from the root. Re-construct the parent chain using
1295 // instance parent pointers.
1296 const normalizedStack = [];
1297 while (currentVNode) {
1298 const last = normalizedStack[0];
1299 if (last && last.vnode === currentVNode) {
1300 last.recurseCount++;
1301 }
1302 else {
1303 normalizedStack.push({
1304 vnode: currentVNode,
1305 recurseCount: 0
1306 });
1307 }
1308 const parentInstance = currentVNode.component && currentVNode.component.parent;
1309 currentVNode = parentInstance && parentInstance.vnode;
1310 }
1311 return normalizedStack;
1312}
1313/* istanbul ignore next */
1314function formatTrace(trace) {
1315 const logs = [];
1316 trace.forEach((entry, i) => {
1317 logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
1318 });
1319 return logs;
1320}
1321function formatTraceEntry({ vnode, recurseCount }) {
1322 const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
1323 const isRoot = vnode.component ? vnode.component.parent == null : false;
1324 const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
1325 const close = `>` + postfix;
1326 return vnode.props
1327 ? [open, ...formatProps(vnode.props), close]
1328 : [open + close];
1329}
1330/* istanbul ignore next */
1331function formatProps(props) {
1332 const res = [];
1333 const keys = Object.keys(props);
1334 keys.slice(0, 3).forEach(key => {
1335 res.push(...formatProp(key, props[key]));
1336 });
1337 if (keys.length > 3) {
1338 res.push(` ...`);
1339 }
1340 return res;
1341}
1342/* istanbul ignore next */
1343function formatProp(key, value, raw) {
1344 if (isString(value)) {
1345 value = JSON.stringify(value);
1346 return raw ? value : [`${key}=${value}`];
1347 }
1348 else if (typeof value === 'number' ||
1349 typeof value === 'boolean' ||
1350 value == null) {
1351 return raw ? value : [`${key}=${value}`];
1352 }
1353 else if (isRef(value)) {
1354 value = formatProp(key, toRaw(value.value), true);
1355 return raw ? value : [`${key}=Ref<`, value, `>`];
1356 }
1357 else if (isFunction(value)) {
1358 return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
1359 }
1360 else {
1361 value = toRaw(value);
1362 return raw ? value : [`${key}=`, value];
1363 }
1364}
1365
1366const ErrorTypeStrings = {
1367 ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',
1368 ["c" /* CREATED */]: 'created hook',
1369 ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',
1370 ["m" /* MOUNTED */]: 'mounted hook',
1371 ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',
1372 ["u" /* UPDATED */]: 'updated',
1373 ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',
1374 ["um" /* UNMOUNTED */]: 'unmounted hook',
1375 ["a" /* ACTIVATED */]: 'activated hook',
1376 ["da" /* DEACTIVATED */]: 'deactivated hook',
1377 ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',
1378 ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',
1379 ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',
1380 [0 /* SETUP_FUNCTION */]: 'setup function',
1381 [1 /* RENDER_FUNCTION */]: 'render function',
1382 [2 /* WATCH_GETTER */]: 'watcher getter',
1383 [3 /* WATCH_CALLBACK */]: 'watcher callback',
1384 [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',
1385 [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',
1386 [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',
1387 [7 /* VNODE_HOOK */]: 'vnode hook',
1388 [8 /* DIRECTIVE_HOOK */]: 'directive hook',
1389 [9 /* TRANSITION_HOOK */]: 'transition hook',
1390 [10 /* APP_ERROR_HANDLER */]: 'app errorHandler',
1391 [11 /* APP_WARN_HANDLER */]: 'app warnHandler',
1392 [12 /* FUNCTION_REF */]: 'ref function',
1393 [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader',
1394 [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
1395 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next'
1396};
1397function callWithErrorHandling(fn, instance, type, args) {
1398 let res;
1399 try {
1400 res = args ? fn(...args) : fn();
1401 }
1402 catch (err) {
1403 handleError(err, instance, type);
1404 }
1405 return res;
1406}
1407function callWithAsyncErrorHandling(fn, instance, type, args) {
1408 if (isFunction(fn)) {
1409 const res = callWithErrorHandling(fn, instance, type, args);
1410 if (res && isPromise(res)) {
1411 res.catch(err => {
1412 handleError(err, instance, type);
1413 });
1414 }
1415 return res;
1416 }
1417 const values = [];
1418 for (let i = 0; i < fn.length; i++) {
1419 values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
1420 }
1421 return values;
1422}
1423function handleError(err, instance, type, throwInDev = true) {
1424 const contextVNode = instance ? instance.vnode : null;
1425 if (instance) {
1426 let cur = instance.parent;
1427 // the exposed instance is the render proxy to keep it consistent with 2.x
1428 const exposedInstance = instance.proxy;
1429 // in production the hook receives only the error code
1430 const errorInfo = ErrorTypeStrings[type] ;
1431 while (cur) {
1432 const errorCapturedHooks = cur.ec;
1433 if (errorCapturedHooks) {
1434 for (let i = 0; i < errorCapturedHooks.length; i++) {
1435 if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
1436 return;
1437 }
1438 }
1439 }
1440 cur = cur.parent;
1441 }
1442 // app-level handling
1443 const appErrorHandler = instance.appContext.config.errorHandler;
1444 if (appErrorHandler) {
1445 callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
1446 return;
1447 }
1448 }
1449 logError(err, type, contextVNode, throwInDev);
1450}
1451function logError(err, type, contextVNode, throwInDev = true) {
1452 {
1453 const info = ErrorTypeStrings[type];
1454 if (contextVNode) {
1455 pushWarningContext(contextVNode);
1456 }
1457 warn(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
1458 if (contextVNode) {
1459 popWarningContext();
1460 }
1461 // crash in dev by default so it's more noticeable
1462 if (throwInDev) {
1463 throw err;
1464 }
1465 else {
1466 console.error(err);
1467 }
1468 }
1469}
1470
1471let isFlushing = false;
1472let isFlushPending = false;
1473const queue = [];
1474let flushIndex = 0;
1475const pendingPreFlushCbs = [];
1476let activePreFlushCbs = null;
1477let preFlushIndex = 0;
1478const pendingPostFlushCbs = [];
1479let activePostFlushCbs = null;
1480let postFlushIndex = 0;
1481const resolvedPromise = Promise.resolve();
1482let currentFlushPromise = null;
1483let currentPreFlushParentJob = null;
1484const RECURSION_LIMIT = 100;
1485function nextTick(fn) {
1486 const p = currentFlushPromise || resolvedPromise;
1487 return fn ? p.then(this ? fn.bind(this) : fn) : p;
1488}
1489// #2768
1490// Use binary-search to find a suitable position in the queue,
1491// so that the queue maintains the increasing order of job's id,
1492// which can prevent the job from being skipped and also can avoid repeated patching.
1493function findInsertionIndex(job) {
1494 // the start index should be `flushIndex + 1`
1495 let start = flushIndex + 1;
1496 let end = queue.length;
1497 const jobId = getId(job);
1498 while (start < end) {
1499 const middle = (start + end) >>> 1;
1500 const middleJobId = getId(queue[middle]);
1501 middleJobId < jobId ? (start = middle + 1) : (end = middle);
1502 }
1503 return start;
1504}
1505function queueJob(job) {
1506 // the dedupe search uses the startIndex argument of Array.includes()
1507 // by default the search index includes the current job that is being run
1508 // so it cannot recursively trigger itself again.
1509 // if the job is a watch() callback, the search will start with a +1 index to
1510 // allow it recursively trigger itself - it is the user's responsibility to
1511 // ensure it doesn't end up in an infinite loop.
1512 if ((!queue.length ||
1513 !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) &&
1514 job !== currentPreFlushParentJob) {
1515 const pos = findInsertionIndex(job);
1516 if (pos > -1) {
1517 queue.splice(pos, 0, job);
1518 }
1519 else {
1520 queue.push(job);
1521 }
1522 queueFlush();
1523 }
1524}
1525function queueFlush() {
1526 if (!isFlushing && !isFlushPending) {
1527 isFlushPending = true;
1528 currentFlushPromise = resolvedPromise.then(flushJobs);
1529 }
1530}
1531function invalidateJob(job) {
1532 const i = queue.indexOf(job);
1533 if (i > flushIndex) {
1534 queue.splice(i, 1);
1535 }
1536}
1537function queueCb(cb, activeQueue, pendingQueue, index) {
1538 if (!isArray(cb)) {
1539 if (!activeQueue ||
1540 !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) {
1541 pendingQueue.push(cb);
1542 }
1543 }
1544 else {
1545 // if cb is an array, it is a component lifecycle hook which can only be
1546 // triggered by a job, which is already deduped in the main queue, so
1547 // we can skip duplicate check here to improve perf
1548 pendingQueue.push(...cb);
1549 }
1550 queueFlush();
1551}
1552function queuePreFlushCb(cb) {
1553 queueCb(cb, activePreFlushCbs, pendingPreFlushCbs, preFlushIndex);
1554}
1555function queuePostFlushCb(cb) {
1556 queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex);
1557}
1558function flushPreFlushCbs(seen, parentJob = null) {
1559 if (pendingPreFlushCbs.length) {
1560 currentPreFlushParentJob = parentJob;
1561 activePreFlushCbs = [...new Set(pendingPreFlushCbs)];
1562 pendingPreFlushCbs.length = 0;
1563 {
1564 seen = seen || new Map();
1565 }
1566 for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) {
1567 {
1568 checkRecursiveUpdates(seen, activePreFlushCbs[preFlushIndex]);
1569 }
1570 activePreFlushCbs[preFlushIndex]();
1571 }
1572 activePreFlushCbs = null;
1573 preFlushIndex = 0;
1574 currentPreFlushParentJob = null;
1575 // recursively flush until it drains
1576 flushPreFlushCbs(seen, parentJob);
1577 }
1578}
1579function flushPostFlushCbs(seen) {
1580 if (pendingPostFlushCbs.length) {
1581 const deduped = [...new Set(pendingPostFlushCbs)];
1582 pendingPostFlushCbs.length = 0;
1583 // #1947 already has active queue, nested flushPostFlushCbs call
1584 if (activePostFlushCbs) {
1585 activePostFlushCbs.push(...deduped);
1586 return;
1587 }
1588 activePostFlushCbs = deduped;
1589 {
1590 seen = seen || new Map();
1591 }
1592 activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
1593 for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
1594 {
1595 checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex]);
1596 }
1597 activePostFlushCbs[postFlushIndex]();
1598 }
1599 activePostFlushCbs = null;
1600 postFlushIndex = 0;
1601 }
1602}
1603const getId = (job) => job.id == null ? Infinity : job.id;
1604function flushJobs(seen) {
1605 isFlushPending = false;
1606 isFlushing = true;
1607 {
1608 seen = seen || new Map();
1609 }
1610 flushPreFlushCbs(seen);
1611 // Sort queue before flush.
1612 // This ensures that:
1613 // 1. Components are updated from parent to child. (because parent is always
1614 // created before the child so its render effect will have smaller
1615 // priority number)
1616 // 2. If a component is unmounted during a parent component's update,
1617 // its update can be skipped.
1618 queue.sort((a, b) => getId(a) - getId(b));
1619 try {
1620 for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
1621 const job = queue[flushIndex];
1622 if (job) {
1623 if (true) {
1624 checkRecursiveUpdates(seen, job);
1625 }
1626 callWithErrorHandling(job, null, 14 /* SCHEDULER */);
1627 }
1628 }
1629 }
1630 finally {
1631 flushIndex = 0;
1632 queue.length = 0;
1633 flushPostFlushCbs(seen);
1634 isFlushing = false;
1635 currentFlushPromise = null;
1636 // some postFlushCb queued jobs!
1637 // keep flushing until it drains.
1638 if (queue.length || pendingPostFlushCbs.length) {
1639 flushJobs(seen);
1640 }
1641 }
1642}
1643function checkRecursiveUpdates(seen, fn) {
1644 if (!seen.has(fn)) {
1645 seen.set(fn, 1);
1646 }
1647 else {
1648 const count = seen.get(fn);
1649 if (count > RECURSION_LIMIT) {
1650 throw new Error(`Maximum recursive updates exceeded. ` +
1651 `This means you have a reactive effect that is mutating its own ` +
1652 `dependencies and thus recursively triggering itself. Possible sources ` +
1653 `include component template, render function, updated hook or ` +
1654 `watcher source function.`);
1655 }
1656 else {
1657 seen.set(fn, count + 1);
1658 }
1659 }
1660}
1661
1662/* eslint-disable no-restricted-globals */
1663let isHmrUpdating = false;
1664const hmrDirtyComponents = new Set();
1665// Expose the HMR runtime on the global object
1666// This makes it entirely tree-shakable without polluting the exports and makes
1667// it easier to be used in toolings like vue-loader
1668// Note: for a component to be eligible for HMR it also needs the __hmrId option
1669// to be set so that its instances can be registered / removed.
1670{
1671 const globalObject = typeof global !== 'undefined'
1672 ? global
1673 : typeof self !== 'undefined'
1674 ? self
1675 : typeof window !== 'undefined'
1676 ? window
1677 : {};
1678 globalObject.__VUE_HMR_RUNTIME__ = {
1679 createRecord: tryWrap(createRecord),
1680 rerender: tryWrap(rerender),
1681 reload: tryWrap(reload)
1682 };
1683}
1684const map = new Map();
1685function registerHMR(instance) {
1686 const id = instance.type.__hmrId;
1687 let record = map.get(id);
1688 if (!record) {
1689 createRecord(id, instance.type);
1690 record = map.get(id);
1691 }
1692 record.instances.add(instance);
1693}
1694function unregisterHMR(instance) {
1695 map.get(instance.type.__hmrId).instances.delete(instance);
1696}
1697function createRecord(id, component) {
1698 if (!component) {
1699 warn(`HMR API usage is out of date.\n` +
1700 `Please upgrade vue-loader/vite/rollup-plugin-vue or other relevant ` +
1701 `dependency that handles Vue SFC compilation.`);
1702 component = {};
1703 }
1704 if (map.has(id)) {
1705 return false;
1706 }
1707 map.set(id, {
1708 component: isClassComponent(component) ? component.__vccOpts : component,
1709 instances: new Set()
1710 });
1711 return true;
1712}
1713function rerender(id, newRender) {
1714 const record = map.get(id);
1715 if (!record)
1716 return;
1717 if (newRender)
1718 record.component.render = newRender;
1719 // Array.from creates a snapshot which avoids the set being mutated during
1720 // updates
1721 Array.from(record.instances).forEach(instance => {
1722 if (newRender) {
1723 instance.render = newRender;
1724 }
1725 instance.renderCache = [];
1726 // this flag forces child components with slot content to update
1727 isHmrUpdating = true;
1728 instance.update();
1729 isHmrUpdating = false;
1730 });
1731}
1732function reload(id, newComp) {
1733 const record = map.get(id);
1734 if (!record)
1735 return;
1736 // Array.from creates a snapshot which avoids the set being mutated during
1737 // updates
1738 const { component, instances } = record;
1739 if (!hmrDirtyComponents.has(component)) {
1740 // 1. Update existing comp definition to match new one
1741 newComp = isClassComponent(newComp) ? newComp.__vccOpts : newComp;
1742 extend(component, newComp);
1743 for (const key in component) {
1744 if (!(key in newComp)) {
1745 delete component[key];
1746 }
1747 }
1748 // 2. Mark component dirty. This forces the renderer to replace the component
1749 // on patch.
1750 hmrDirtyComponents.add(component);
1751 // 3. Make sure to unmark the component after the reload.
1752 queuePostFlushCb(() => {
1753 hmrDirtyComponents.delete(component);
1754 });
1755 }
1756 Array.from(instances).forEach(instance => {
1757 if (instance.parent) {
1758 // 4. Force the parent instance to re-render. This will cause all updated
1759 // components to be unmounted and re-mounted. Queue the update so that we
1760 // don't end up forcing the same parent to re-render multiple times.
1761 queueJob(instance.parent.update);
1762 }
1763 else if (instance.appContext.reload) {
1764 // root instance mounted via createApp() has a reload method
1765 instance.appContext.reload();
1766 }
1767 else if (typeof window !== 'undefined') {
1768 // root instance inside tree created via raw render(). Force reload.
1769 window.location.reload();
1770 }
1771 else {
1772 console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
1773 }
1774 });
1775}
1776function tryWrap(fn) {
1777 return (id, arg) => {
1778 try {
1779 return fn(id, arg);
1780 }
1781 catch (e) {
1782 console.error(e);
1783 console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
1784 `Full reload required.`);
1785 }
1786 };
1787}
1788
1789let devtools;
1790function setDevtoolsHook(hook) {
1791 devtools = hook;
1792}
1793function devtoolsInitApp(app, version) {
1794 // TODO queue if devtools is undefined
1795 if (!devtools)
1796 return;
1797 devtools.emit("app:init" /* APP_INIT */, app, version, {
1798 Fragment,
1799 Text,
1800 Comment,
1801 Static
1802 });
1803}
1804function devtoolsUnmountApp(app) {
1805 if (!devtools)
1806 return;
1807 devtools.emit("app:unmount" /* APP_UNMOUNT */, app);
1808}
1809const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* COMPONENT_ADDED */);
1810const devtoolsComponentUpdated = /*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */);
1811const devtoolsComponentRemoved = /*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* COMPONENT_REMOVED */);
1812function createDevtoolsComponentHook(hook) {
1813 return (component) => {
1814 if (!devtools)
1815 return;
1816 devtools.emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component);
1817 };
1818}
1819function devtoolsComponentEmit(component, event, params) {
1820 if (!devtools)
1821 return;
1822 devtools.emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params);
1823}
1824
1825function emit(instance, event, ...rawArgs) {
1826 const props = instance.vnode.props || EMPTY_OBJ;
1827 {
1828 const { emitsOptions, propsOptions: [propsOptions] } = instance;
1829 if (emitsOptions) {
1830 if (!(event in emitsOptions)) {
1831 if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
1832 warn(`Component emitted event "${event}" but it is neither declared in ` +
1833 `the emits option nor as an "${toHandlerKey(event)}" prop.`);
1834 }
1835 }
1836 else {
1837 const validator = emitsOptions[event];
1838 if (isFunction(validator)) {
1839 const isValid = validator(...rawArgs);
1840 if (!isValid) {
1841 warn(`Invalid event arguments: event validation failed for event "${event}".`);
1842 }
1843 }
1844 }
1845 }
1846 }
1847 let args = rawArgs;
1848 const isModelListener = event.startsWith('update:');
1849 // for v-model update:xxx events, apply modifiers on args
1850 const modelArg = isModelListener && event.slice(7);
1851 if (modelArg && modelArg in props) {
1852 const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
1853 const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
1854 if (trim) {
1855 args = rawArgs.map(a => a.trim());
1856 }
1857 else if (number) {
1858 args = rawArgs.map(toNumber);
1859 }
1860 }
1861 {
1862 devtoolsComponentEmit(instance, event, args);
1863 }
1864 {
1865 const lowerCaseEvent = event.toLowerCase();
1866 if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
1867 warn(`Event "${lowerCaseEvent}" is emitted in component ` +
1868 `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
1869 `Note that HTML attributes are case-insensitive and you cannot use ` +
1870 `v-on to listen to camelCase events when using in-DOM templates. ` +
1871 `You should probably use "${hyphenate(event)}" instead of "${event}".`);
1872 }
1873 }
1874 // convert handler name to camelCase. See issue #2249
1875 let handlerName = toHandlerKey(camelize(event));
1876 let handler = props[handlerName];
1877 // for v-model update:xxx events, also trigger kebab-case equivalent
1878 // for props passed via kebab-case
1879 if (!handler && isModelListener) {
1880 handlerName = toHandlerKey(hyphenate(event));
1881 handler = props[handlerName];
1882 }
1883 if (handler) {
1884 callWithAsyncErrorHandling(handler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
1885 }
1886 const onceHandler = props[handlerName + `Once`];
1887 if (onceHandler) {
1888 if (!instance.emitted) {
1889 (instance.emitted = {})[handlerName] = true;
1890 }
1891 else if (instance.emitted[handlerName]) {
1892 return;
1893 }
1894 callWithAsyncErrorHandling(onceHandler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
1895 }
1896}
1897function normalizeEmitsOptions(comp, appContext, asMixin = false) {
1898 if (!appContext.deopt && comp.__emits !== undefined) {
1899 return comp.__emits;
1900 }
1901 const raw = comp.emits;
1902 let normalized = {};
1903 // apply mixin/extends props
1904 let hasExtends = false;
1905 if (!isFunction(comp)) {
1906 const extendEmits = (raw) => {
1907 const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true);
1908 if (normalizedFromExtend) {
1909 hasExtends = true;
1910 extend(normalized, normalizedFromExtend);
1911 }
1912 };
1913 if (!asMixin && appContext.mixins.length) {
1914 appContext.mixins.forEach(extendEmits);
1915 }
1916 if (comp.extends) {
1917 extendEmits(comp.extends);
1918 }
1919 if (comp.mixins) {
1920 comp.mixins.forEach(extendEmits);
1921 }
1922 }
1923 if (!raw && !hasExtends) {
1924 return (comp.__emits = null);
1925 }
1926 if (isArray(raw)) {
1927 raw.forEach(key => (normalized[key] = null));
1928 }
1929 else {
1930 extend(normalized, raw);
1931 }
1932 return (comp.__emits = normalized);
1933}
1934// Check if an incoming prop key is a declared emit event listener.
1935// e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
1936// both considered matched listeners.
1937function isEmitListener(options, key) {
1938 if (!options || !isOn(key)) {
1939 return false;
1940 }
1941 key = key.slice(2).replace(/Once$/, '');
1942 return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||
1943 hasOwn(options, hyphenate(key)) ||
1944 hasOwn(options, key));
1945}
1946
1947let isRenderingCompiledSlot = 0;
1948const setCompiledSlotRendering = (n) => (isRenderingCompiledSlot += n);
1949/**
1950 * Compiler runtime helper for rendering `<slot/>`
1951 * @private
1952 */
1953function renderSlot(slots, name, props = {},
1954// this is not a user-facing function, so the fallback is always generated by
1955// the compiler and guaranteed to be a function returning an array
1956fallback, noSlotted) {
1957 let slot = slots[name];
1958 if (slot && slot.length > 1) {
1959 warn(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
1960 `function. You need to mark this component with $dynamic-slots in the ` +
1961 `parent template.`);
1962 slot = () => [];
1963 }
1964 // a compiled slot disables block tracking by default to avoid manual
1965 // invocation interfering with template-based block tracking, but in
1966 // `renderSlot` we can be sure that it's template-based so we can force
1967 // enable it.
1968 isRenderingCompiledSlot++;
1969 openBlock();
1970 const validSlotContent = slot && ensureValidVNode(slot(props));
1971 const rendered = createBlock(Fragment, { key: props.key || `_${name}` }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 /* STABLE */
1972 ? 64 /* STABLE_FRAGMENT */
1973 : -2 /* BAIL */);
1974 if (!noSlotted && rendered.scopeId) {
1975 rendered.slotScopeIds = [rendered.scopeId + '-s'];
1976 }
1977 isRenderingCompiledSlot--;
1978 return rendered;
1979}
1980function ensureValidVNode(vnodes) {
1981 return vnodes.some(child => {
1982 if (!isVNode(child))
1983 return true;
1984 if (child.type === Comment)
1985 return false;
1986 if (child.type === Fragment &&
1987 !ensureValidVNode(child.children))
1988 return false;
1989 return true;
1990 })
1991 ? vnodes
1992 : null;
1993}
1994
1995/**
1996 * mark the current rendering instance for asset resolution (e.g.
1997 * resolveComponent, resolveDirective) during render
1998 */
1999let currentRenderingInstance = null;
2000let currentScopeId = null;
2001/**
2002 * Note: rendering calls maybe nested. The function returns the parent rendering
2003 * instance if present, which should be restored after the render is done:
2004 *
2005 * ```js
2006 * const prev = setCurrentRenderingInstance(i)
2007 * // ...render
2008 * setCurrentRenderingInstance(prev)
2009 * ```
2010 */
2011function setCurrentRenderingInstance(instance) {
2012 const prev = currentRenderingInstance;
2013 currentRenderingInstance = instance;
2014 currentScopeId = (instance && instance.type.__scopeId) || null;
2015 return prev;
2016}
2017/**
2018 * Set scope id when creating hoisted vnodes.
2019 * @private compiler helper
2020 */
2021function pushScopeId(id) {
2022 currentScopeId = id;
2023}
2024/**
2025 * Technically we no longer need this after 3.0.8 but we need to keep the same
2026 * API for backwards compat w/ code generated by compilers.
2027 * @private
2028 */
2029function popScopeId() {
2030 currentScopeId = null;
2031}
2032/**
2033 * Only for backwards compat
2034 * @private
2035 */
2036const withScopeId = (_id) => withCtx;
2037/**
2038 * Wrap a slot function to memoize current rendering instance
2039 * @private compiler helper
2040 */
2041function withCtx(fn, ctx = currentRenderingInstance) {
2042 if (!ctx)
2043 return fn;
2044 const renderFnWithContext = (...args) => {
2045 // If a user calls a compiled slot inside a template expression (#1745), it
2046 // can mess up block tracking, so by default we need to push a null block to
2047 // avoid that. This isn't necessary if rendering a compiled `<slot>`.
2048 if (!isRenderingCompiledSlot) {
2049 openBlock(true /* null block that disables tracking */);
2050 }
2051 const prevInstance = setCurrentRenderingInstance(ctx);
2052 const res = fn(...args);
2053 setCurrentRenderingInstance(prevInstance);
2054 if (!isRenderingCompiledSlot) {
2055 closeBlock();
2056 }
2057 return res;
2058 };
2059 // mark this as a compiled slot function.
2060 // this is used in vnode.ts -> normalizeChildren() to set the slot
2061 // rendering flag.
2062 renderFnWithContext._c = true;
2063 return renderFnWithContext;
2064}
2065
2066/**
2067 * dev only flag to track whether $attrs was used during render.
2068 * If $attrs was used during render then the warning for failed attrs
2069 * fallthrough can be suppressed.
2070 */
2071let accessedAttrs = false;
2072function markAttrsAccessed() {
2073 accessedAttrs = true;
2074}
2075function renderComponentRoot(instance) {
2076 const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx } = instance;
2077 let result;
2078 const prev = setCurrentRenderingInstance(instance);
2079 {
2080 accessedAttrs = false;
2081 }
2082 try {
2083 let fallthroughAttrs;
2084 if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
2085 // withProxy is a proxy with a different `has` trap only for
2086 // runtime-compiled render functions using `with` block.
2087 const proxyToUse = withProxy || proxy;
2088 result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
2089 fallthroughAttrs = attrs;
2090 }
2091 else {
2092 // functional
2093 const render = Component;
2094 // in dev, mark attrs accessed if optional props (attrs === props)
2095 if (true && attrs === props) {
2096 markAttrsAccessed();
2097 }
2098 result = normalizeVNode(render.length > 1
2099 ? render(props, true
2100 ? {
2101 get attrs() {
2102 markAttrsAccessed();
2103 return attrs;
2104 },
2105 slots,
2106 emit
2107 }
2108 : { attrs, slots, emit })
2109 : render(props, null /* we know it doesn't need it */));
2110 fallthroughAttrs = Component.props
2111 ? attrs
2112 : getFunctionalFallthrough(attrs);
2113 }
2114 // attr merging
2115 // in dev mode, comments are preserved, and it's possible for a template
2116 // to have comments along side the root element which makes it a fragment
2117 let root = result;
2118 let setRoot = undefined;
2119 if (true &&
2120 result.patchFlag > 0 &&
2121 result.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
2122 ;
2123 [root, setRoot] = getChildRoot(result);
2124 }
2125 if (Component.inheritAttrs !== false && fallthroughAttrs) {
2126 const keys = Object.keys(fallthroughAttrs);
2127 const { shapeFlag } = root;
2128 if (keys.length) {
2129 if (shapeFlag & 1 /* ELEMENT */ ||
2130 shapeFlag & 6 /* COMPONENT */) {
2131 if (propsOptions && keys.some(isModelListener)) {
2132 // If a v-model listener (onUpdate:xxx) has a corresponding declared
2133 // prop, it indicates this component expects to handle v-model and
2134 // it should not fallthrough.
2135 // related: #1543, #1643, #1989
2136 fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
2137 }
2138 root = cloneVNode(root, fallthroughAttrs);
2139 }
2140 else if (true && !accessedAttrs && root.type !== Comment) {
2141 const allAttrs = Object.keys(attrs);
2142 const eventAttrs = [];
2143 const extraAttrs = [];
2144 for (let i = 0, l = allAttrs.length; i < l; i++) {
2145 const key = allAttrs[i];
2146 if (isOn(key)) {
2147 // ignore v-model handlers when they fail to fallthrough
2148 if (!isModelListener(key)) {
2149 // remove `on`, lowercase first letter to reflect event casing
2150 // accurately
2151 eventAttrs.push(key[2].toLowerCase() + key.slice(3));
2152 }
2153 }
2154 else {
2155 extraAttrs.push(key);
2156 }
2157 }
2158 if (extraAttrs.length) {
2159 warn(`Extraneous non-props attributes (` +
2160 `${extraAttrs.join(', ')}) ` +
2161 `were passed to component but could not be automatically inherited ` +
2162 `because component renders fragment or text root nodes.`);
2163 }
2164 if (eventAttrs.length) {
2165 warn(`Extraneous non-emits event listeners (` +
2166 `${eventAttrs.join(', ')}) ` +
2167 `were passed to component but could not be automatically inherited ` +
2168 `because component renders fragment or text root nodes. ` +
2169 `If the listener is intended to be a component custom event listener only, ` +
2170 `declare it using the "emits" option.`);
2171 }
2172 }
2173 }
2174 }
2175 // inherit directives
2176 if (vnode.dirs) {
2177 if (true && !isElementRoot(root)) {
2178 warn(`Runtime directive used on component with non-element root node. ` +
2179 `The directives will not function as intended.`);
2180 }
2181 root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
2182 }
2183 // inherit transition data
2184 if (vnode.transition) {
2185 if (true && !isElementRoot(root)) {
2186 warn(`Component inside <Transition> renders non-element root node ` +
2187 `that cannot be animated.`);
2188 }
2189 root.transition = vnode.transition;
2190 }
2191 if (true && setRoot) {
2192 setRoot(root);
2193 }
2194 else {
2195 result = root;
2196 }
2197 }
2198 catch (err) {
2199 blockStack.length = 0;
2200 handleError(err, instance, 1 /* RENDER_FUNCTION */);
2201 result = createVNode(Comment);
2202 }
2203 setCurrentRenderingInstance(prev);
2204 return result;
2205}
2206/**
2207 * dev only
2208 * In dev mode, template root level comments are rendered, which turns the
2209 * template into a fragment root, but we need to locate the single element
2210 * root for attrs and scope id processing.
2211 */
2212const getChildRoot = (vnode) => {
2213 const rawChildren = vnode.children;
2214 const dynamicChildren = vnode.dynamicChildren;
2215 const childRoot = filterSingleRoot(rawChildren);
2216 if (!childRoot) {
2217 return [vnode, undefined];
2218 }
2219 const index = rawChildren.indexOf(childRoot);
2220 const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
2221 const setRoot = (updatedRoot) => {
2222 rawChildren[index] = updatedRoot;
2223 if (dynamicChildren) {
2224 if (dynamicIndex > -1) {
2225 dynamicChildren[dynamicIndex] = updatedRoot;
2226 }
2227 else if (updatedRoot.patchFlag > 0) {
2228 vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
2229 }
2230 }
2231 };
2232 return [normalizeVNode(childRoot), setRoot];
2233};
2234function filterSingleRoot(children) {
2235 let singleRoot;
2236 for (let i = 0; i < children.length; i++) {
2237 const child = children[i];
2238 if (isVNode(child)) {
2239 // ignore user comment
2240 if (child.type !== Comment || child.children === 'v-if') {
2241 if (singleRoot) {
2242 // has more than 1 non-comment child, return now
2243 return;
2244 }
2245 else {
2246 singleRoot = child;
2247 }
2248 }
2249 }
2250 else {
2251 return;
2252 }
2253 }
2254 return singleRoot;
2255}
2256const getFunctionalFallthrough = (attrs) => {
2257 let res;
2258 for (const key in attrs) {
2259 if (key === 'class' || key === 'style' || isOn(key)) {
2260 (res || (res = {}))[key] = attrs[key];
2261 }
2262 }
2263 return res;
2264};
2265const filterModelListeners = (attrs, props) => {
2266 const res = {};
2267 for (const key in attrs) {
2268 if (!isModelListener(key) || !(key.slice(9) in props)) {
2269 res[key] = attrs[key];
2270 }
2271 }
2272 return res;
2273};
2274const isElementRoot = (vnode) => {
2275 return (vnode.shapeFlag & 6 /* COMPONENT */ ||
2276 vnode.shapeFlag & 1 /* ELEMENT */ ||
2277 vnode.type === Comment // potential v-if branch switch
2278 );
2279};
2280function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
2281 const { props: prevProps, children: prevChildren, component } = prevVNode;
2282 const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
2283 const emits = component.emitsOptions;
2284 // Parent component's render function was hot-updated. Since this may have
2285 // caused the child component's slots content to have changed, we need to
2286 // force the child to update as well.
2287 if ((prevChildren || nextChildren) && isHmrUpdating) {
2288 return true;
2289 }
2290 // force child update for runtime directive or transition on component vnode.
2291 if (nextVNode.dirs || nextVNode.transition) {
2292 return true;
2293 }
2294 if (optimized && patchFlag >= 0) {
2295 if (patchFlag & 1024 /* DYNAMIC_SLOTS */) {
2296 // slot content that references values that might have changed,
2297 // e.g. in a v-for
2298 return true;
2299 }
2300 if (patchFlag & 16 /* FULL_PROPS */) {
2301 if (!prevProps) {
2302 return !!nextProps;
2303 }
2304 // presence of this flag indicates props are always non-null
2305 return hasPropsChanged(prevProps, nextProps, emits);
2306 }
2307 else if (patchFlag & 8 /* PROPS */) {
2308 const dynamicProps = nextVNode.dynamicProps;
2309 for (let i = 0; i < dynamicProps.length; i++) {
2310 const key = dynamicProps[i];
2311 if (nextProps[key] !== prevProps[key] &&
2312 !isEmitListener(emits, key)) {
2313 return true;
2314 }
2315 }
2316 }
2317 }
2318 else {
2319 // this path is only taken by manually written render functions
2320 // so presence of any children leads to a forced update
2321 if (prevChildren || nextChildren) {
2322 if (!nextChildren || !nextChildren.$stable) {
2323 return true;
2324 }
2325 }
2326 if (prevProps === nextProps) {
2327 return false;
2328 }
2329 if (!prevProps) {
2330 return !!nextProps;
2331 }
2332 if (!nextProps) {
2333 return true;
2334 }
2335 return hasPropsChanged(prevProps, nextProps, emits);
2336 }
2337 return false;
2338}
2339function hasPropsChanged(prevProps, nextProps, emitsOptions) {
2340 const nextKeys = Object.keys(nextProps);
2341 if (nextKeys.length !== Object.keys(prevProps).length) {
2342 return true;
2343 }
2344 for (let i = 0; i < nextKeys.length; i++) {
2345 const key = nextKeys[i];
2346 if (nextProps[key] !== prevProps[key] &&
2347 !isEmitListener(emitsOptions, key)) {
2348 return true;
2349 }
2350 }
2351 return false;
2352}
2353function updateHOCHostEl({ vnode, parent }, el // HostNode
2354) {
2355 while (parent && parent.subTree === vnode) {
2356 (vnode = parent.vnode).el = el;
2357 parent = parent.parent;
2358 }
2359}
2360
2361const isSuspense = (type) => type.__isSuspense;
2362// Suspense exposes a component-like API, and is treated like a component
2363// in the compiler, but internally it's a special built-in type that hooks
2364// directly into the renderer.
2365const SuspenseImpl = {
2366 name: 'Suspense',
2367 // In order to make Suspense tree-shakable, we need to avoid importing it
2368 // directly in the renderer. The renderer checks for the __isSuspense flag
2369 // on a vnode's type and calls the `process` method, passing in renderer
2370 // internals.
2371 __isSuspense: true,
2372 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized,
2373 // platform-specific impl passed from renderer
2374 rendererInternals) {
2375 if (n1 == null) {
2376 mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals);
2377 }
2378 else {
2379 patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, rendererInternals);
2380 }
2381 },
2382 hydrate: hydrateSuspense,
2383 create: createSuspenseBoundary
2384};
2385// Force-casted public typing for h and TSX props inference
2386const Suspense = (SuspenseImpl
2387 );
2388function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals) {
2389 const { p: patch, o: { createElement } } = rendererInternals;
2390 const hiddenContainer = createElement('div');
2391 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals));
2392 // start mounting the content subtree in an off-dom container
2393 patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds);
2394 // now check if we have encountered any async deps
2395 if (suspense.deps > 0) {
2396 // has async
2397 // mount the fallback tree
2398 patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2399 isSVG, slotScopeIds);
2400 setActiveBranch(suspense, vnode.ssFallback);
2401 }
2402 else {
2403 // Suspense has no async deps. Just resolve.
2404 suspense.resolve();
2405 }
2406}
2407function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) {
2408 const suspense = (n2.suspense = n1.suspense);
2409 suspense.vnode = n2;
2410 n2.el = n1.el;
2411 const newBranch = n2.ssContent;
2412 const newFallback = n2.ssFallback;
2413 const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
2414 if (pendingBranch) {
2415 suspense.pendingBranch = newBranch;
2416 if (isSameVNodeType(newBranch, pendingBranch)) {
2417 // same root type but content may have changed.
2418 patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2419 if (suspense.deps <= 0) {
2420 suspense.resolve();
2421 }
2422 else if (isInFallback) {
2423 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2424 isSVG, slotScopeIds, optimized);
2425 setActiveBranch(suspense, newFallback);
2426 }
2427 }
2428 else {
2429 // toggled before pending tree is resolved
2430 suspense.pendingId++;
2431 if (isHydrating) {
2432 // if toggled before hydration is finished, the current DOM tree is
2433 // no longer valid. set it as the active branch so it will be unmounted
2434 // when resolved
2435 suspense.isHydrating = false;
2436 suspense.activeBranch = pendingBranch;
2437 }
2438 else {
2439 unmount(pendingBranch, parentComponent, suspense);
2440 }
2441 // increment pending ID. this is used to invalidate async callbacks
2442 // reset suspense state
2443 suspense.deps = 0;
2444 // discard effects from pending branch
2445 suspense.effects.length = 0;
2446 // discard previous container
2447 suspense.hiddenContainer = createElement('div');
2448 if (isInFallback) {
2449 // already in fallback state
2450 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2451 if (suspense.deps <= 0) {
2452 suspense.resolve();
2453 }
2454 else {
2455 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2456 isSVG, slotScopeIds, optimized);
2457 setActiveBranch(suspense, newFallback);
2458 }
2459 }
2460 else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2461 // toggled "back" to current active branch
2462 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2463 // force resolve
2464 suspense.resolve(true);
2465 }
2466 else {
2467 // switched to a 3rd branch
2468 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2469 if (suspense.deps <= 0) {
2470 suspense.resolve();
2471 }
2472 }
2473 }
2474 }
2475 else {
2476 if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2477 // root did not change, just normal patch
2478 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2479 setActiveBranch(suspense, newBranch);
2480 }
2481 else {
2482 // root node toggled
2483 // invoke @pending event
2484 const onPending = n2.props && n2.props.onPending;
2485 if (isFunction(onPending)) {
2486 onPending();
2487 }
2488 // mount pending branch in off-dom container
2489 suspense.pendingBranch = newBranch;
2490 suspense.pendingId++;
2491 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2492 if (suspense.deps <= 0) {
2493 // incoming branch has no async deps, resolve now.
2494 suspense.resolve();
2495 }
2496 else {
2497 const { timeout, pendingId } = suspense;
2498 if (timeout > 0) {
2499 setTimeout(() => {
2500 if (suspense.pendingId === pendingId) {
2501 suspense.fallback(newFallback);
2502 }
2503 }, timeout);
2504 }
2505 else if (timeout === 0) {
2506 suspense.fallback(newFallback);
2507 }
2508 }
2509 }
2510 }
2511}
2512let hasWarned = false;
2513function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals, isHydrating = false) {
2514 /* istanbul ignore if */
2515 if (!hasWarned) {
2516 hasWarned = true;
2517 // @ts-ignore `console.info` cannot be null error
2518 console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
2519 }
2520 const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
2521 const timeout = toNumber(vnode.props && vnode.props.timeout);
2522 const suspense = {
2523 vnode,
2524 parent,
2525 parentComponent,
2526 isSVG,
2527 container,
2528 hiddenContainer,
2529 anchor,
2530 deps: 0,
2531 pendingId: 0,
2532 timeout: typeof timeout === 'number' ? timeout : -1,
2533 activeBranch: null,
2534 pendingBranch: null,
2535 isInFallback: true,
2536 isHydrating,
2537 isUnmounted: false,
2538 effects: [],
2539 resolve(resume = false) {
2540 {
2541 if (!resume && !suspense.pendingBranch) {
2542 throw new Error(`suspense.resolve() is called without a pending branch.`);
2543 }
2544 if (suspense.isUnmounted) {
2545 throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
2546 }
2547 }
2548 const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
2549 if (suspense.isHydrating) {
2550 suspense.isHydrating = false;
2551 }
2552 else if (!resume) {
2553 const delayEnter = activeBranch &&
2554 pendingBranch.transition &&
2555 pendingBranch.transition.mode === 'out-in';
2556 if (delayEnter) {
2557 activeBranch.transition.afterLeave = () => {
2558 if (pendingId === suspense.pendingId) {
2559 move(pendingBranch, container, anchor, 0 /* ENTER */);
2560 }
2561 };
2562 }
2563 // this is initial anchor on mount
2564 let { anchor } = suspense;
2565 // unmount current active tree
2566 if (activeBranch) {
2567 // if the fallback tree was mounted, it may have been moved
2568 // as part of a parent suspense. get the latest anchor for insertion
2569 anchor = next(activeBranch);
2570 unmount(activeBranch, parentComponent, suspense, true);
2571 }
2572 if (!delayEnter) {
2573 // move content from off-dom container to actual container
2574 move(pendingBranch, container, anchor, 0 /* ENTER */);
2575 }
2576 }
2577 setActiveBranch(suspense, pendingBranch);
2578 suspense.pendingBranch = null;
2579 suspense.isInFallback = false;
2580 // flush buffered effects
2581 // check if there is a pending parent suspense
2582 let parent = suspense.parent;
2583 let hasUnresolvedAncestor = false;
2584 while (parent) {
2585 if (parent.pendingBranch) {
2586 // found a pending parent suspense, merge buffered post jobs
2587 // into that parent
2588 parent.effects.push(...effects);
2589 hasUnresolvedAncestor = true;
2590 break;
2591 }
2592 parent = parent.parent;
2593 }
2594 // no pending parent suspense, flush all jobs
2595 if (!hasUnresolvedAncestor) {
2596 queuePostFlushCb(effects);
2597 }
2598 suspense.effects = [];
2599 // invoke @resolve event
2600 const onResolve = vnode.props && vnode.props.onResolve;
2601 if (isFunction(onResolve)) {
2602 onResolve();
2603 }
2604 },
2605 fallback(fallbackVNode) {
2606 if (!suspense.pendingBranch) {
2607 return;
2608 }
2609 const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
2610 // invoke @fallback event
2611 const onFallback = vnode.props && vnode.props.onFallback;
2612 if (isFunction(onFallback)) {
2613 onFallback();
2614 }
2615 const anchor = next(activeBranch);
2616 const mountFallback = () => {
2617 if (!suspense.isInFallback) {
2618 return;
2619 }
2620 // mount the fallback tree
2621 patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2622 isSVG, slotScopeIds, optimized);
2623 setActiveBranch(suspense, fallbackVNode);
2624 };
2625 const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
2626 if (delayEnter) {
2627 activeBranch.transition.afterLeave = mountFallback;
2628 }
2629 // unmount current active branch
2630 unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
2631 true // shouldRemove
2632 );
2633 suspense.isInFallback = true;
2634 if (!delayEnter) {
2635 mountFallback();
2636 }
2637 },
2638 move(container, anchor, type) {
2639 suspense.activeBranch &&
2640 move(suspense.activeBranch, container, anchor, type);
2641 suspense.container = container;
2642 },
2643 next() {
2644 return suspense.activeBranch && next(suspense.activeBranch);
2645 },
2646 registerDep(instance, setupRenderEffect) {
2647 const isInPendingSuspense = !!suspense.pendingBranch;
2648 if (isInPendingSuspense) {
2649 suspense.deps++;
2650 }
2651 const hydratedEl = instance.vnode.el;
2652 instance
2653 .asyncDep.catch(err => {
2654 handleError(err, instance, 0 /* SETUP_FUNCTION */);
2655 })
2656 .then(asyncSetupResult => {
2657 // retry when the setup() promise resolves.
2658 // component may have been unmounted before resolve.
2659 if (instance.isUnmounted ||
2660 suspense.isUnmounted ||
2661 suspense.pendingId !== instance.suspenseId) {
2662 return;
2663 }
2664 // retry from this component
2665 instance.asyncResolved = true;
2666 const { vnode } = instance;
2667 {
2668 pushWarningContext(vnode);
2669 }
2670 handleSetupResult(instance, asyncSetupResult, false);
2671 if (hydratedEl) {
2672 // vnode may have been replaced if an update happened before the
2673 // async dep is resolved.
2674 vnode.el = hydratedEl;
2675 }
2676 const placeholder = !hydratedEl && instance.subTree.el;
2677 setupRenderEffect(instance, vnode,
2678 // component may have been moved before resolve.
2679 // if this is not a hydration, instance.subTree will be the comment
2680 // placeholder.
2681 parentNode(hydratedEl || instance.subTree.el),
2682 // anchor will not be used if this is hydration, so only need to
2683 // consider the comment placeholder case.
2684 hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
2685 if (placeholder) {
2686 remove(placeholder);
2687 }
2688 updateHOCHostEl(instance, vnode.el);
2689 {
2690 popWarningContext();
2691 }
2692 // only decrease deps count if suspense is not already resolved
2693 if (isInPendingSuspense && --suspense.deps === 0) {
2694 suspense.resolve();
2695 }
2696 });
2697 },
2698 unmount(parentSuspense, doRemove) {
2699 suspense.isUnmounted = true;
2700 if (suspense.activeBranch) {
2701 unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
2702 }
2703 if (suspense.pendingBranch) {
2704 unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
2705 }
2706 }
2707 };
2708 return suspense;
2709}
2710function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals, hydrateNode) {
2711 /* eslint-disable no-restricted-globals */
2712 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, slotScopeIds, optimized, rendererInternals, true /* hydrating */));
2713 // there are two possible scenarios for server-rendered suspense:
2714 // - success: ssr content should be fully resolved
2715 // - failure: ssr content should be the fallback branch.
2716 // however, on the client we don't really know if it has failed or not
2717 // attempt to hydrate the DOM assuming it has succeeded, but we still
2718 // need to construct a suspense boundary first
2719 const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, slotScopeIds, optimized);
2720 if (suspense.deps === 0) {
2721 suspense.resolve();
2722 }
2723 return result;
2724 /* eslint-enable no-restricted-globals */
2725}
2726function normalizeSuspenseChildren(vnode) {
2727 const { shapeFlag, children } = vnode;
2728 let content;
2729 let fallback;
2730 if (shapeFlag & 32 /* SLOTS_CHILDREN */) {
2731 content = normalizeSuspenseSlot(children.default);
2732 fallback = normalizeSuspenseSlot(children.fallback);
2733 }
2734 else {
2735 content = normalizeSuspenseSlot(children);
2736 fallback = normalizeVNode(null);
2737 }
2738 return {
2739 content,
2740 fallback
2741 };
2742}
2743function normalizeSuspenseSlot(s) {
2744 if (isFunction(s)) {
2745 s = s();
2746 }
2747 if (isArray(s)) {
2748 const singleChild = filterSingleRoot(s);
2749 if (!singleChild) {
2750 warn(`<Suspense> slots expect a single root node.`);
2751 }
2752 s = singleChild;
2753 }
2754 return normalizeVNode(s);
2755}
2756function queueEffectWithSuspense(fn, suspense) {
2757 if (suspense && suspense.pendingBranch) {
2758 if (isArray(fn)) {
2759 suspense.effects.push(...fn);
2760 }
2761 else {
2762 suspense.effects.push(fn);
2763 }
2764 }
2765 else {
2766 queuePostFlushCb(fn);
2767 }
2768}
2769function setActiveBranch(suspense, branch) {
2770 suspense.activeBranch = branch;
2771 const { vnode, parentComponent } = suspense;
2772 const el = (vnode.el = branch.el);
2773 // in case suspense is the root node of a component,
2774 // recursively update the HOC el
2775 if (parentComponent && parentComponent.subTree === vnode) {
2776 parentComponent.vnode.el = el;
2777 updateHOCHostEl(parentComponent, el);
2778 }
2779}
2780
2781function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
2782isSSR = false) {
2783 const props = {};
2784 const attrs = {};
2785 def(attrs, InternalObjectKey, 1);
2786 instance.propsDefaults = Object.create(null);
2787 setFullProps(instance, rawProps, props, attrs);
2788 // validation
2789 {
2790 validateProps(rawProps || {}, props, instance);
2791 }
2792 if (isStateful) {
2793 // stateful
2794 instance.props = isSSR ? props : shallowReactive(props);
2795 }
2796 else {
2797 if (!instance.type.props) {
2798 // functional w/ optional props, props === attrs
2799 instance.props = attrs;
2800 }
2801 else {
2802 // functional w/ declared props
2803 instance.props = props;
2804 }
2805 }
2806 instance.attrs = attrs;
2807}
2808function updateProps(instance, rawProps, rawPrevProps, optimized) {
2809 const { props, attrs, vnode: { patchFlag } } = instance;
2810 const rawCurrentProps = toRaw(props);
2811 const [options] = instance.propsOptions;
2812 if (
2813 // always force full diff in dev
2814 // - #1942 if hmr is enabled with sfc component
2815 // - vite#872 non-sfc component used by sfc component
2816 !((instance.type.__hmrId ||
2817 (instance.parent && instance.parent.type.__hmrId))) &&
2818 (optimized || patchFlag > 0) &&
2819 !(patchFlag & 16 /* FULL_PROPS */)) {
2820 if (patchFlag & 8 /* PROPS */) {
2821 // Compiler-generated props & no keys change, just set the updated
2822 // the props.
2823 const propsToUpdate = instance.vnode.dynamicProps;
2824 for (let i = 0; i < propsToUpdate.length; i++) {
2825 const key = propsToUpdate[i];
2826 // PROPS flag guarantees rawProps to be non-null
2827 const value = rawProps[key];
2828 if (options) {
2829 // attr / props separation was done on init and will be consistent
2830 // in this code path, so just check if attrs have it.
2831 if (hasOwn(attrs, key)) {
2832 attrs[key] = value;
2833 }
2834 else {
2835 const camelizedKey = camelize(key);
2836 props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance);
2837 }
2838 }
2839 else {
2840 attrs[key] = value;
2841 }
2842 }
2843 }
2844 }
2845 else {
2846 // full props update.
2847 setFullProps(instance, rawProps, props, attrs);
2848 // in case of dynamic props, check if we need to delete keys from
2849 // the props object
2850 let kebabKey;
2851 for (const key in rawCurrentProps) {
2852 if (!rawProps ||
2853 // for camelCase
2854 (!hasOwn(rawProps, key) &&
2855 // it's possible the original props was passed in as kebab-case
2856 // and converted to camelCase (#955)
2857 ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
2858 if (options) {
2859 if (rawPrevProps &&
2860 // for camelCase
2861 (rawPrevProps[key] !== undefined ||
2862 // for kebab-case
2863 rawPrevProps[kebabKey] !== undefined)) {
2864 props[key] = resolvePropValue(options, rawProps || EMPTY_OBJ, key, undefined, instance);
2865 }
2866 }
2867 else {
2868 delete props[key];
2869 }
2870 }
2871 }
2872 // in the case of functional component w/o props declaration, props and
2873 // attrs point to the same object so it should already have been updated.
2874 if (attrs !== rawCurrentProps) {
2875 for (const key in attrs) {
2876 if (!rawProps || !hasOwn(rawProps, key)) {
2877 delete attrs[key];
2878 }
2879 }
2880 }
2881 }
2882 // trigger updates for $attrs in case it's used in component slots
2883 trigger(instance, "set" /* SET */, '$attrs');
2884 {
2885 validateProps(rawProps || {}, props, instance);
2886 }
2887}
2888function setFullProps(instance, rawProps, props, attrs) {
2889 const [options, needCastKeys] = instance.propsOptions;
2890 if (rawProps) {
2891 for (const key in rawProps) {
2892 const value = rawProps[key];
2893 // key, ref are reserved and never passed down
2894 if (isReservedProp(key)) {
2895 continue;
2896 }
2897 // prop option names are camelized during normalization, so to support
2898 // kebab -> camel conversion here we need to camelize the key.
2899 let camelKey;
2900 if (options && hasOwn(options, (camelKey = camelize(key)))) {
2901 props[camelKey] = value;
2902 }
2903 else if (!isEmitListener(instance.emitsOptions, key)) {
2904 // Any non-declared (either as a prop or an emitted event) props are put
2905 // into a separate `attrs` object for spreading. Make sure to preserve
2906 // original key casing
2907 attrs[key] = value;
2908 }
2909 }
2910 }
2911 if (needCastKeys) {
2912 const rawCurrentProps = toRaw(props);
2913 for (let i = 0; i < needCastKeys.length; i++) {
2914 const key = needCastKeys[i];
2915 props[key] = resolvePropValue(options, rawCurrentProps, key, rawCurrentProps[key], instance);
2916 }
2917 }
2918}
2919function resolvePropValue(options, props, key, value, instance) {
2920 const opt = options[key];
2921 if (opt != null) {
2922 const hasDefault = hasOwn(opt, 'default');
2923 // default values
2924 if (hasDefault && value === undefined) {
2925 const defaultValue = opt.default;
2926 if (opt.type !== Function && isFunction(defaultValue)) {
2927 const { propsDefaults } = instance;
2928 if (key in propsDefaults) {
2929 value = propsDefaults[key];
2930 }
2931 else {
2932 setCurrentInstance(instance);
2933 value = propsDefaults[key] = defaultValue(props);
2934 setCurrentInstance(null);
2935 }
2936 }
2937 else {
2938 value = defaultValue;
2939 }
2940 }
2941 // boolean casting
2942 if (opt[0 /* shouldCast */]) {
2943 if (!hasOwn(props, key) && !hasDefault) {
2944 value = false;
2945 }
2946 else if (opt[1 /* shouldCastTrue */] &&
2947 (value === '' || value === hyphenate(key))) {
2948 value = true;
2949 }
2950 }
2951 }
2952 return value;
2953}
2954function normalizePropsOptions(comp, appContext, asMixin = false) {
2955 if (!appContext.deopt && comp.__props) {
2956 return comp.__props;
2957 }
2958 const raw = comp.props;
2959 const normalized = {};
2960 const needCastKeys = [];
2961 // apply mixin/extends props
2962 let hasExtends = false;
2963 if (!isFunction(comp)) {
2964 const extendProps = (raw) => {
2965 hasExtends = true;
2966 const [props, keys] = normalizePropsOptions(raw, appContext, true);
2967 extend(normalized, props);
2968 if (keys)
2969 needCastKeys.push(...keys);
2970 };
2971 if (!asMixin && appContext.mixins.length) {
2972 appContext.mixins.forEach(extendProps);
2973 }
2974 if (comp.extends) {
2975 extendProps(comp.extends);
2976 }
2977 if (comp.mixins) {
2978 comp.mixins.forEach(extendProps);
2979 }
2980 }
2981 if (!raw && !hasExtends) {
2982 return (comp.__props = EMPTY_ARR);
2983 }
2984 if (isArray(raw)) {
2985 for (let i = 0; i < raw.length; i++) {
2986 if (!isString(raw[i])) {
2987 warn(`props must be strings when using array syntax.`, raw[i]);
2988 }
2989 const normalizedKey = camelize(raw[i]);
2990 if (validatePropName(normalizedKey)) {
2991 normalized[normalizedKey] = EMPTY_OBJ;
2992 }
2993 }
2994 }
2995 else if (raw) {
2996 if (!isObject(raw)) {
2997 warn(`invalid props options`, raw);
2998 }
2999 for (const key in raw) {
3000 const normalizedKey = camelize(key);
3001 if (validatePropName(normalizedKey)) {
3002 const opt = raw[key];
3003 const prop = (normalized[normalizedKey] =
3004 isArray(opt) || isFunction(opt) ? { type: opt } : opt);
3005 if (prop) {
3006 const booleanIndex = getTypeIndex(Boolean, prop.type);
3007 const stringIndex = getTypeIndex(String, prop.type);
3008 prop[0 /* shouldCast */] = booleanIndex > -1;
3009 prop[1 /* shouldCastTrue */] =
3010 stringIndex < 0 || booleanIndex < stringIndex;
3011 // if the prop needs boolean casting or default value
3012 if (booleanIndex > -1 || hasOwn(prop, 'default')) {
3013 needCastKeys.push(normalizedKey);
3014 }
3015 }
3016 }
3017 }
3018 }
3019 return (comp.__props = [normalized, needCastKeys]);
3020}
3021function validatePropName(key) {
3022 if (key[0] !== '$') {
3023 return true;
3024 }
3025 else {
3026 warn(`Invalid prop name: "${key}" is a reserved property.`);
3027 }
3028 return false;
3029}
3030// use function string name to check type constructors
3031// so that it works across vms / iframes.
3032function getType(ctor) {
3033 const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
3034 return match ? match[1] : '';
3035}
3036function isSameType(a, b) {
3037 return getType(a) === getType(b);
3038}
3039function getTypeIndex(type, expectedTypes) {
3040 if (isArray(expectedTypes)) {
3041 return expectedTypes.findIndex(t => isSameType(t, type));
3042 }
3043 else if (isFunction(expectedTypes)) {
3044 return isSameType(expectedTypes, type) ? 0 : -1;
3045 }
3046 return -1;
3047}
3048/**
3049 * dev only
3050 */
3051function validateProps(rawProps, props, instance) {
3052 const resolvedValues = toRaw(props);
3053 const options = instance.propsOptions[0];
3054 for (const key in options) {
3055 let opt = options[key];
3056 if (opt == null)
3057 continue;
3058 validateProp(key, resolvedValues[key], opt, !hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key)));
3059 }
3060}
3061/**
3062 * dev only
3063 */
3064function validateProp(name, value, prop, isAbsent) {
3065 const { type, required, validator } = prop;
3066 // required!
3067 if (required && isAbsent) {
3068 warn('Missing required prop: "' + name + '"');
3069 return;
3070 }
3071 // missing but optional
3072 if (value == null && !prop.required) {
3073 return;
3074 }
3075 // type check
3076 if (type != null && type !== true) {
3077 let isValid = false;
3078 const types = isArray(type) ? type : [type];
3079 const expectedTypes = [];
3080 // value is valid as long as one of the specified types match
3081 for (let i = 0; i < types.length && !isValid; i++) {
3082 const { valid, expectedType } = assertType(value, types[i]);
3083 expectedTypes.push(expectedType || '');
3084 isValid = valid;
3085 }
3086 if (!isValid) {
3087 warn(getInvalidTypeMessage(name, value, expectedTypes));
3088 return;
3089 }
3090 }
3091 // custom validator
3092 if (validator && !validator(value)) {
3093 warn('Invalid prop: custom validator check failed for prop "' + name + '".');
3094 }
3095}
3096const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol,BigInt');
3097/**
3098 * dev only
3099 */
3100function assertType(value, type) {
3101 let valid;
3102 const expectedType = getType(type);
3103 if (isSimpleType(expectedType)) {
3104 const t = typeof value;
3105 valid = t === expectedType.toLowerCase();
3106 // for primitive wrapper objects
3107 if (!valid && t === 'object') {
3108 valid = value instanceof type;
3109 }
3110 }
3111 else if (expectedType === 'Object') {
3112 valid = isObject(value);
3113 }
3114 else if (expectedType === 'Array') {
3115 valid = isArray(value);
3116 }
3117 else {
3118 valid = value instanceof type;
3119 }
3120 return {
3121 valid,
3122 expectedType
3123 };
3124}
3125/**
3126 * dev only
3127 */
3128function getInvalidTypeMessage(name, value, expectedTypes) {
3129 let message = `Invalid prop: type check failed for prop "${name}".` +
3130 ` Expected ${expectedTypes.map(capitalize).join(', ')}`;
3131 const expectedType = expectedTypes[0];
3132 const receivedType = toRawType(value);
3133 const expectedValue = styleValue(value, expectedType);
3134 const receivedValue = styleValue(value, receivedType);
3135 // check if we need to specify expected value
3136 if (expectedTypes.length === 1 &&
3137 isExplicable(expectedType) &&
3138 !isBoolean(expectedType, receivedType)) {
3139 message += ` with value ${expectedValue}`;
3140 }
3141 message += `, got ${receivedType} `;
3142 // check if we need to specify received value
3143 if (isExplicable(receivedType)) {
3144 message += `with value ${receivedValue}.`;
3145 }
3146 return message;
3147}
3148/**
3149 * dev only
3150 */
3151function styleValue(value, type) {
3152 if (type === 'String') {
3153 return `"${value}"`;
3154 }
3155 else if (type === 'Number') {
3156 return `${Number(value)}`;
3157 }
3158 else {
3159 return `${value}`;
3160 }
3161}
3162/**
3163 * dev only
3164 */
3165function isExplicable(type) {
3166 const explicitTypes = ['string', 'number', 'boolean'];
3167 return explicitTypes.some(elem => type.toLowerCase() === elem);
3168}
3169/**
3170 * dev only
3171 */
3172function isBoolean(...args) {
3173 return args.some(elem => elem.toLowerCase() === 'boolean');
3174}
3175
3176function injectHook(type, hook, target = currentInstance, prepend = false) {
3177 if (target) {
3178 const hooks = target[type] || (target[type] = []);
3179 // cache the error handling wrapper for injected hooks so the same hook
3180 // can be properly deduped by the scheduler. "__weh" stands for "with error
3181 // handling".
3182 const wrappedHook = hook.__weh ||
3183 (hook.__weh = (...args) => {
3184 if (target.isUnmounted) {
3185 return;
3186 }
3187 // disable tracking inside all lifecycle hooks
3188 // since they can potentially be called inside effects.
3189 pauseTracking();
3190 // Set currentInstance during hook invocation.
3191 // This assumes the hook does not synchronously trigger other hooks, which
3192 // can only be false when the user does something really funky.
3193 setCurrentInstance(target);
3194 const res = callWithAsyncErrorHandling(hook, target, type, args);
3195 setCurrentInstance(null);
3196 resetTracking();
3197 return res;
3198 });
3199 if (prepend) {
3200 hooks.unshift(wrappedHook);
3201 }
3202 else {
3203 hooks.push(wrappedHook);
3204 }
3205 return wrappedHook;
3206 }
3207 else {
3208 const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
3209 warn(`${apiName} is called when there is no active component instance to be ` +
3210 `associated with. ` +
3211 `Lifecycle injection APIs can only be used during execution of setup().` +
3212 (` If you are using async setup(), make sure to register lifecycle ` +
3213 `hooks before the first await statement.`
3214 ));
3215 }
3216}
3217const createHook = (lifecycle) => (hook, target = currentInstance) =>
3218// post-create lifecycle registrations are noops during SSR
3219!isInSSRComponentSetup && injectHook(lifecycle, hook, target);
3220const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */);
3221const onMounted = createHook("m" /* MOUNTED */);
3222const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */);
3223const onUpdated = createHook("u" /* UPDATED */);
3224const onBeforeUnmount = createHook("bum" /* BEFORE_UNMOUNT */);
3225const onUnmounted = createHook("um" /* UNMOUNTED */);
3226const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */);
3227const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */);
3228const onErrorCaptured = (hook, target = currentInstance) => {
3229 injectHook("ec" /* ERROR_CAPTURED */, hook, target);
3230};
3231
3232// Simple effect.
3233function watchEffect(effect, options) {
3234 return doWatch(effect, null, options);
3235}
3236// initial value for watchers to trigger on undefined initial values
3237const INITIAL_WATCHER_VALUE = {};
3238// implementation
3239function watch(source, cb, options) {
3240 if (!isFunction(cb)) {
3241 warn(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
3242 `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
3243 `supports \`watch(source, cb, options?) signature.`);
3244 }
3245 return doWatch(source, cb, options);
3246}
3247function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ, instance = currentInstance) {
3248 if (!cb) {
3249 if (immediate !== undefined) {
3250 warn(`watch() "immediate" option is only respected when using the ` +
3251 `watch(source, callback, options?) signature.`);
3252 }
3253 if (deep !== undefined) {
3254 warn(`watch() "deep" option is only respected when using the ` +
3255 `watch(source, callback, options?) signature.`);
3256 }
3257 }
3258 const warnInvalidSource = (s) => {
3259 warn(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
3260 `a reactive object, or an array of these types.`);
3261 };
3262 let getter;
3263 let forceTrigger = false;
3264 if (isRef(source)) {
3265 getter = () => source.value;
3266 forceTrigger = !!source._shallow;
3267 }
3268 else if (isReactive(source)) {
3269 getter = () => source;
3270 deep = true;
3271 }
3272 else if (isArray(source)) {
3273 getter = () => source.map(s => {
3274 if (isRef(s)) {
3275 return s.value;
3276 }
3277 else if (isReactive(s)) {
3278 return traverse(s);
3279 }
3280 else if (isFunction(s)) {
3281 return callWithErrorHandling(s, instance, 2 /* WATCH_GETTER */, [
3282 instance && instance.proxy
3283 ]);
3284 }
3285 else {
3286 warnInvalidSource(s);
3287 }
3288 });
3289 }
3290 else if (isFunction(source)) {
3291 if (cb) {
3292 // getter with cb
3293 getter = () => callWithErrorHandling(source, instance, 2 /* WATCH_GETTER */, [
3294 instance && instance.proxy
3295 ]);
3296 }
3297 else {
3298 // no cb -> simple effect
3299 getter = () => {
3300 if (instance && instance.isUnmounted) {
3301 return;
3302 }
3303 if (cleanup) {
3304 cleanup();
3305 }
3306 return callWithAsyncErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onInvalidate]);
3307 };
3308 }
3309 }
3310 else {
3311 getter = NOOP;
3312 warnInvalidSource(source);
3313 }
3314 if (cb && deep) {
3315 const baseGetter = getter;
3316 getter = () => traverse(baseGetter());
3317 }
3318 let cleanup;
3319 let onInvalidate = (fn) => {
3320 cleanup = runner.options.onStop = () => {
3321 callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */);
3322 };
3323 };
3324 let oldValue = isArray(source) ? [] : INITIAL_WATCHER_VALUE;
3325 const job = () => {
3326 if (!runner.active) {
3327 return;
3328 }
3329 if (cb) {
3330 // watch(source, cb)
3331 const newValue = runner();
3332 if (deep || forceTrigger || hasChanged(newValue, oldValue)) {
3333 // cleanup before running cb again
3334 if (cleanup) {
3335 cleanup();
3336 }
3337 callWithAsyncErrorHandling(cb, instance, 3 /* WATCH_CALLBACK */, [
3338 newValue,
3339 // pass undefined as the old value when it's changed for the first time
3340 oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
3341 onInvalidate
3342 ]);
3343 oldValue = newValue;
3344 }
3345 }
3346 else {
3347 // watchEffect
3348 runner();
3349 }
3350 };
3351 // important: mark the job as a watcher callback so that scheduler knows
3352 // it is allowed to self-trigger (#1727)
3353 job.allowRecurse = !!cb;
3354 let scheduler;
3355 if (flush === 'sync') {
3356 scheduler = job;
3357 }
3358 else if (flush === 'post') {
3359 scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
3360 }
3361 else {
3362 // default: 'pre'
3363 scheduler = () => {
3364 if (!instance || instance.isMounted) {
3365 queuePreFlushCb(job);
3366 }
3367 else {
3368 // with 'pre' option, the first call must happen before
3369 // the component is mounted so it is called synchronously.
3370 job();
3371 }
3372 };
3373 }
3374 const runner = effect(getter, {
3375 lazy: true,
3376 onTrack,
3377 onTrigger,
3378 scheduler
3379 });
3380 recordInstanceBoundEffect(runner, instance);
3381 // initial run
3382 if (cb) {
3383 if (immediate) {
3384 job();
3385 }
3386 else {
3387 oldValue = runner();
3388 }
3389 }
3390 else if (flush === 'post') {
3391 queuePostRenderEffect(runner, instance && instance.suspense);
3392 }
3393 else {
3394 runner();
3395 }
3396 return () => {
3397 stop(runner);
3398 if (instance) {
3399 remove(instance.effects, runner);
3400 }
3401 };
3402}
3403// this.$watch
3404function instanceWatch(source, cb, options) {
3405 const publicThis = this.proxy;
3406 const getter = isString(source)
3407 ? () => publicThis[source]
3408 : source.bind(publicThis);
3409 return doWatch(getter, cb.bind(publicThis), options, this);
3410}
3411function traverse(value, seen = new Set()) {
3412 if (!isObject(value) || seen.has(value)) {
3413 return value;
3414 }
3415 seen.add(value);
3416 if (isRef(value)) {
3417 traverse(value.value, seen);
3418 }
3419 else if (isArray(value)) {
3420 for (let i = 0; i < value.length; i++) {
3421 traverse(value[i], seen);
3422 }
3423 }
3424 else if (isSet(value) || isMap(value)) {
3425 value.forEach((v) => {
3426 traverse(v, seen);
3427 });
3428 }
3429 else {
3430 for (const key in value) {
3431 traverse(value[key], seen);
3432 }
3433 }
3434 return value;
3435}
3436
3437function useTransitionState() {
3438 const state = {
3439 isMounted: false,
3440 isLeaving: false,
3441 isUnmounting: false,
3442 leavingVNodes: new Map()
3443 };
3444 onMounted(() => {
3445 state.isMounted = true;
3446 });
3447 onBeforeUnmount(() => {
3448 state.isUnmounting = true;
3449 });
3450 return state;
3451}
3452const TransitionHookValidator = [Function, Array];
3453const BaseTransitionImpl = {
3454 name: `BaseTransition`,
3455 props: {
3456 mode: String,
3457 appear: Boolean,
3458 persisted: Boolean,
3459 // enter
3460 onBeforeEnter: TransitionHookValidator,
3461 onEnter: TransitionHookValidator,
3462 onAfterEnter: TransitionHookValidator,
3463 onEnterCancelled: TransitionHookValidator,
3464 // leave
3465 onBeforeLeave: TransitionHookValidator,
3466 onLeave: TransitionHookValidator,
3467 onAfterLeave: TransitionHookValidator,
3468 onLeaveCancelled: TransitionHookValidator,
3469 // appear
3470 onBeforeAppear: TransitionHookValidator,
3471 onAppear: TransitionHookValidator,
3472 onAfterAppear: TransitionHookValidator,
3473 onAppearCancelled: TransitionHookValidator
3474 },
3475 setup(props, { slots }) {
3476 const instance = getCurrentInstance();
3477 const state = useTransitionState();
3478 let prevTransitionKey;
3479 return () => {
3480 const children = slots.default && getTransitionRawChildren(slots.default(), true);
3481 if (!children || !children.length) {
3482 return;
3483 }
3484 // warn multiple elements
3485 if (children.length > 1) {
3486 warn('<transition> can only be used on a single element or component. Use ' +
3487 '<transition-group> for lists.');
3488 }
3489 // there's no need to track reactivity for these props so use the raw
3490 // props for a bit better perf
3491 const rawProps = toRaw(props);
3492 const { mode } = rawProps;
3493 // check mode
3494 if (mode && !['in-out', 'out-in', 'default'].includes(mode)) {
3495 warn(`invalid <transition> mode: ${mode}`);
3496 }
3497 // at this point children has a guaranteed length of 1.
3498 const child = children[0];
3499 if (state.isLeaving) {
3500 return emptyPlaceholder(child);
3501 }
3502 // in the case of <transition><keep-alive/></transition>, we need to
3503 // compare the type of the kept-alive children.
3504 const innerChild = getKeepAliveChild(child);
3505 if (!innerChild) {
3506 return emptyPlaceholder(child);
3507 }
3508 const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
3509 setTransitionHooks(innerChild, enterHooks);
3510 const oldChild = instance.subTree;
3511 const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
3512 let transitionKeyChanged = false;
3513 const { getTransitionKey } = innerChild.type;
3514 if (getTransitionKey) {
3515 const key = getTransitionKey();
3516 if (prevTransitionKey === undefined) {
3517 prevTransitionKey = key;
3518 }
3519 else if (key !== prevTransitionKey) {
3520 prevTransitionKey = key;
3521 transitionKeyChanged = true;
3522 }
3523 }
3524 // handle mode
3525 if (oldInnerChild &&
3526 oldInnerChild.type !== Comment &&
3527 (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
3528 const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
3529 // update old tree's hooks in case of dynamic transition
3530 setTransitionHooks(oldInnerChild, leavingHooks);
3531 // switching between different views
3532 if (mode === 'out-in') {
3533 state.isLeaving = true;
3534 // return placeholder node and queue update when leave finishes
3535 leavingHooks.afterLeave = () => {
3536 state.isLeaving = false;
3537 instance.update();
3538 };
3539 return emptyPlaceholder(child);
3540 }
3541 else if (mode === 'in-out' && innerChild.type !== Comment) {
3542 leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
3543 const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
3544 leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
3545 // early removal callback
3546 el._leaveCb = () => {
3547 earlyRemove();
3548 el._leaveCb = undefined;
3549 delete enterHooks.delayedLeave;
3550 };
3551 enterHooks.delayedLeave = delayedLeave;
3552 };
3553 }
3554 }
3555 return child;
3556 };
3557 }
3558};
3559// export the public type for h/tsx inference
3560// also to avoid inline import() in generated d.ts files
3561const BaseTransition = BaseTransitionImpl;
3562function getLeavingNodesForType(state, vnode) {
3563 const { leavingVNodes } = state;
3564 let leavingVNodesCache = leavingVNodes.get(vnode.type);
3565 if (!leavingVNodesCache) {
3566 leavingVNodesCache = Object.create(null);
3567 leavingVNodes.set(vnode.type, leavingVNodesCache);
3568 }
3569 return leavingVNodesCache;
3570}
3571// The transition hooks are attached to the vnode as vnode.transition
3572// and will be called at appropriate timing in the renderer.
3573function resolveTransitionHooks(vnode, props, state, instance) {
3574 const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
3575 const key = String(vnode.key);
3576 const leavingVNodesCache = getLeavingNodesForType(state, vnode);
3577 const callHook = (hook, args) => {
3578 hook &&
3579 callWithAsyncErrorHandling(hook, instance, 9 /* TRANSITION_HOOK */, args);
3580 };
3581 const hooks = {
3582 mode,
3583 persisted,
3584 beforeEnter(el) {
3585 let hook = onBeforeEnter;
3586 if (!state.isMounted) {
3587 if (appear) {
3588 hook = onBeforeAppear || onBeforeEnter;
3589 }
3590 else {
3591 return;
3592 }
3593 }
3594 // for same element (v-show)
3595 if (el._leaveCb) {
3596 el._leaveCb(true /* cancelled */);
3597 }
3598 // for toggled element with same key (v-if)
3599 const leavingVNode = leavingVNodesCache[key];
3600 if (leavingVNode &&
3601 isSameVNodeType(vnode, leavingVNode) &&
3602 leavingVNode.el._leaveCb) {
3603 // force early removal (not cancelled)
3604 leavingVNode.el._leaveCb();
3605 }
3606 callHook(hook, [el]);
3607 },
3608 enter(el) {
3609 let hook = onEnter;
3610 let afterHook = onAfterEnter;
3611 let cancelHook = onEnterCancelled;
3612 if (!state.isMounted) {
3613 if (appear) {
3614 hook = onAppear || onEnter;
3615 afterHook = onAfterAppear || onAfterEnter;
3616 cancelHook = onAppearCancelled || onEnterCancelled;
3617 }
3618 else {
3619 return;
3620 }
3621 }
3622 let called = false;
3623 const done = (el._enterCb = (cancelled) => {
3624 if (called)
3625 return;
3626 called = true;
3627 if (cancelled) {
3628 callHook(cancelHook, [el]);
3629 }
3630 else {
3631 callHook(afterHook, [el]);
3632 }
3633 if (hooks.delayedLeave) {
3634 hooks.delayedLeave();
3635 }
3636 el._enterCb = undefined;
3637 });
3638 if (hook) {
3639 hook(el, done);
3640 if (hook.length <= 1) {
3641 done();
3642 }
3643 }
3644 else {
3645 done();
3646 }
3647 },
3648 leave(el, remove) {
3649 const key = String(vnode.key);
3650 if (el._enterCb) {
3651 el._enterCb(true /* cancelled */);
3652 }
3653 if (state.isUnmounting) {
3654 return remove();
3655 }
3656 callHook(onBeforeLeave, [el]);
3657 let called = false;
3658 const done = (el._leaveCb = (cancelled) => {
3659 if (called)
3660 return;
3661 called = true;
3662 remove();
3663 if (cancelled) {
3664 callHook(onLeaveCancelled, [el]);
3665 }
3666 else {
3667 callHook(onAfterLeave, [el]);
3668 }
3669 el._leaveCb = undefined;
3670 if (leavingVNodesCache[key] === vnode) {
3671 delete leavingVNodesCache[key];
3672 }
3673 });
3674 leavingVNodesCache[key] = vnode;
3675 if (onLeave) {
3676 onLeave(el, done);
3677 if (onLeave.length <= 1) {
3678 done();
3679 }
3680 }
3681 else {
3682 done();
3683 }
3684 },
3685 clone(vnode) {
3686 return resolveTransitionHooks(vnode, props, state, instance);
3687 }
3688 };
3689 return hooks;
3690}
3691// the placeholder really only handles one special case: KeepAlive
3692// in the case of a KeepAlive in a leave phase we need to return a KeepAlive
3693// placeholder with empty content to avoid the KeepAlive instance from being
3694// unmounted.
3695function emptyPlaceholder(vnode) {
3696 if (isKeepAlive(vnode)) {
3697 vnode = cloneVNode(vnode);
3698 vnode.children = null;
3699 return vnode;
3700 }
3701}
3702function getKeepAliveChild(vnode) {
3703 return isKeepAlive(vnode)
3704 ? vnode.children
3705 ? vnode.children[0]
3706 : undefined
3707 : vnode;
3708}
3709function setTransitionHooks(vnode, hooks) {
3710 if (vnode.shapeFlag & 6 /* COMPONENT */ && vnode.component) {
3711 setTransitionHooks(vnode.component.subTree, hooks);
3712 }
3713 else if (vnode.shapeFlag & 128 /* SUSPENSE */) {
3714 vnode.ssContent.transition = hooks.clone(vnode.ssContent);
3715 vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
3716 }
3717 else {
3718 vnode.transition = hooks;
3719 }
3720}
3721function getTransitionRawChildren(children, keepComment = false) {
3722 let ret = [];
3723 let keyedFragmentCount = 0;
3724 for (let i = 0; i < children.length; i++) {
3725 const child = children[i];
3726 // handle fragment children case, e.g. v-for
3727 if (child.type === Fragment) {
3728 if (child.patchFlag & 128 /* KEYED_FRAGMENT */)
3729 keyedFragmentCount++;
3730 ret = ret.concat(getTransitionRawChildren(child.children, keepComment));
3731 }
3732 // comment placeholders should be skipped, e.g. v-if
3733 else if (keepComment || child.type !== Comment) {
3734 ret.push(child);
3735 }
3736 }
3737 // #1126 if a transition children list contains multiple sub fragments, these
3738 // fragments will be merged into a flat children array. Since each v-for
3739 // fragment may contain different static bindings inside, we need to de-op
3740 // these children to force full diffs to ensure correct behavior.
3741 if (keyedFragmentCount > 1) {
3742 for (let i = 0; i < ret.length; i++) {
3743 ret[i].patchFlag = -2 /* BAIL */;
3744 }
3745 }
3746 return ret;
3747}
3748
3749const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
3750const KeepAliveImpl = {
3751 name: `KeepAlive`,
3752 // Marker for special handling inside the renderer. We are not using a ===
3753 // check directly on KeepAlive in the renderer, because importing it directly
3754 // would prevent it from being tree-shaken.
3755 __isKeepAlive: true,
3756 props: {
3757 include: [String, RegExp, Array],
3758 exclude: [String, RegExp, Array],
3759 max: [String, Number]
3760 },
3761 setup(props, { slots }) {
3762 const instance = getCurrentInstance();
3763 // KeepAlive communicates with the instantiated renderer via the
3764 // ctx where the renderer passes in its internals,
3765 // and the KeepAlive instance exposes activate/deactivate implementations.
3766 // The whole point of this is to avoid importing KeepAlive directly in the
3767 // renderer to facilitate tree-shaking.
3768 const sharedContext = instance.ctx;
3769 // if the internal renderer is not registered, it indicates that this is server-side rendering,
3770 // for KeepAlive, we just need to render its children
3771 if (!sharedContext.renderer) {
3772 return slots.default;
3773 }
3774 const cache = new Map();
3775 const keys = new Set();
3776 let current = null;
3777 const parentSuspense = instance.suspense;
3778 const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
3779 const storageContainer = createElement('div');
3780 sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
3781 const instance = vnode.component;
3782 move(vnode, container, anchor, 0 /* ENTER */, parentSuspense);
3783 // in case props have changed
3784 patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, vnode.slotScopeIds, optimized);
3785 queuePostRenderEffect(() => {
3786 instance.isDeactivated = false;
3787 if (instance.a) {
3788 invokeArrayFns(instance.a);
3789 }
3790 const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
3791 if (vnodeHook) {
3792 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3793 }
3794 }, parentSuspense);
3795 };
3796 sharedContext.deactivate = (vnode) => {
3797 const instance = vnode.component;
3798 move(vnode, storageContainer, null, 1 /* LEAVE */, parentSuspense);
3799 queuePostRenderEffect(() => {
3800 if (instance.da) {
3801 invokeArrayFns(instance.da);
3802 }
3803 const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
3804 if (vnodeHook) {
3805 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3806 }
3807 instance.isDeactivated = true;
3808 }, parentSuspense);
3809 };
3810 function unmount(vnode) {
3811 // reset the shapeFlag so it can be properly unmounted
3812 resetShapeFlag(vnode);
3813 _unmount(vnode, instance, parentSuspense);
3814 }
3815 function pruneCache(filter) {
3816 cache.forEach((vnode, key) => {
3817 const name = getComponentName(vnode.type);
3818 if (name && (!filter || !filter(name))) {
3819 pruneCacheEntry(key);
3820 }
3821 });
3822 }
3823 function pruneCacheEntry(key) {
3824 const cached = cache.get(key);
3825 if (!current || cached.type !== current.type) {
3826 unmount(cached);
3827 }
3828 else if (current) {
3829 // current active instance should no longer be kept-alive.
3830 // we can't unmount it now but it might be later, so reset its flag now.
3831 resetShapeFlag(current);
3832 }
3833 cache.delete(key);
3834 keys.delete(key);
3835 }
3836 // prune cache on include/exclude prop change
3837 watch(() => [props.include, props.exclude], ([include, exclude]) => {
3838 include && pruneCache(name => matches(include, name));
3839 exclude && pruneCache(name => !matches(exclude, name));
3840 },
3841 // prune post-render after `current` has been updated
3842 { flush: 'post', deep: true });
3843 // cache sub tree after render
3844 let pendingCacheKey = null;
3845 const cacheSubtree = () => {
3846 // fix #1621, the pendingCacheKey could be 0
3847 if (pendingCacheKey != null) {
3848 cache.set(pendingCacheKey, getInnerChild(instance.subTree));
3849 }
3850 };
3851 onMounted(cacheSubtree);
3852 onUpdated(cacheSubtree);
3853 onBeforeUnmount(() => {
3854 cache.forEach(cached => {
3855 const { subTree, suspense } = instance;
3856 const vnode = getInnerChild(subTree);
3857 if (cached.type === vnode.type) {
3858 // current instance will be unmounted as part of keep-alive's unmount
3859 resetShapeFlag(vnode);
3860 // but invoke its deactivated hook here
3861 const da = vnode.component.da;
3862 da && queuePostRenderEffect(da, suspense);
3863 return;
3864 }
3865 unmount(cached);
3866 });
3867 });
3868 return () => {
3869 pendingCacheKey = null;
3870 if (!slots.default) {
3871 return null;
3872 }
3873 const children = slots.default();
3874 const rawVNode = children[0];
3875 if (children.length > 1) {
3876 {
3877 warn(`KeepAlive should contain exactly one component child.`);
3878 }
3879 current = null;
3880 return children;
3881 }
3882 else if (!isVNode(rawVNode) ||
3883 (!(rawVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) &&
3884 !(rawVNode.shapeFlag & 128 /* SUSPENSE */))) {
3885 current = null;
3886 return rawVNode;
3887 }
3888 let vnode = getInnerChild(rawVNode);
3889 const comp = vnode.type;
3890 const name = getComponentName(comp);
3891 const { include, exclude, max } = props;
3892 if ((include && (!name || !matches(include, name))) ||
3893 (exclude && name && matches(exclude, name))) {
3894 current = vnode;
3895 return rawVNode;
3896 }
3897 const key = vnode.key == null ? comp : vnode.key;
3898 const cachedVNode = cache.get(key);
3899 // clone vnode if it's reused because we are going to mutate it
3900 if (vnode.el) {
3901 vnode = cloneVNode(vnode);
3902 if (rawVNode.shapeFlag & 128 /* SUSPENSE */) {
3903 rawVNode.ssContent = vnode;
3904 }
3905 }
3906 // #1513 it's possible for the returned vnode to be cloned due to attr
3907 // fallthrough or scopeId, so the vnode here may not be the final vnode
3908 // that is mounted. Instead of caching it directly, we store the pending
3909 // key and cache `instance.subTree` (the normalized vnode) in
3910 // beforeMount/beforeUpdate hooks.
3911 pendingCacheKey = key;
3912 if (cachedVNode) {
3913 // copy over mounted state
3914 vnode.el = cachedVNode.el;
3915 vnode.component = cachedVNode.component;
3916 if (vnode.transition) {
3917 // recursively update transition hooks on subTree
3918 setTransitionHooks(vnode, vnode.transition);
3919 }
3920 // avoid vnode being mounted as fresh
3921 vnode.shapeFlag |= 512 /* COMPONENT_KEPT_ALIVE */;
3922 // make this key the freshest
3923 keys.delete(key);
3924 keys.add(key);
3925 }
3926 else {
3927 keys.add(key);
3928 // prune oldest entry
3929 if (max && keys.size > parseInt(max, 10)) {
3930 pruneCacheEntry(keys.values().next().value);
3931 }
3932 }
3933 // avoid vnode being unmounted
3934 vnode.shapeFlag |= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
3935 current = vnode;
3936 return rawVNode;
3937 };
3938 }
3939};
3940// export the public type for h/tsx inference
3941// also to avoid inline import() in generated d.ts files
3942const KeepAlive = KeepAliveImpl;
3943function matches(pattern, name) {
3944 if (isArray(pattern)) {
3945 return pattern.some((p) => matches(p, name));
3946 }
3947 else if (isString(pattern)) {
3948 return pattern.split(',').indexOf(name) > -1;
3949 }
3950 else if (pattern.test) {
3951 return pattern.test(name);
3952 }
3953 /* istanbul ignore next */
3954 return false;
3955}
3956function onActivated(hook, target) {
3957 registerKeepAliveHook(hook, "a" /* ACTIVATED */, target);
3958}
3959function onDeactivated(hook, target) {
3960 registerKeepAliveHook(hook, "da" /* DEACTIVATED */, target);
3961}
3962function registerKeepAliveHook(hook, type, target = currentInstance) {
3963 // cache the deactivate branch check wrapper for injected hooks so the same
3964 // hook can be properly deduped by the scheduler. "__wdc" stands for "with
3965 // deactivation check".
3966 const wrappedHook = hook.__wdc ||
3967 (hook.__wdc = () => {
3968 // only fire the hook if the target instance is NOT in a deactivated branch.
3969 let current = target;
3970 while (current) {
3971 if (current.isDeactivated) {
3972 return;
3973 }
3974 current = current.parent;
3975 }
3976 hook();
3977 });
3978 injectHook(type, wrappedHook, target);
3979 // In addition to registering it on the target instance, we walk up the parent
3980 // chain and register it on all ancestor instances that are keep-alive roots.
3981 // This avoids the need to walk the entire component tree when invoking these
3982 // hooks, and more importantly, avoids the need to track child components in
3983 // arrays.
3984 if (target) {
3985 let current = target.parent;
3986 while (current && current.parent) {
3987 if (isKeepAlive(current.parent.vnode)) {
3988 injectToKeepAliveRoot(wrappedHook, type, target, current);
3989 }
3990 current = current.parent;
3991 }
3992 }
3993}
3994function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
3995 // injectHook wraps the original for error handling, so make sure to remove
3996 // the wrapped version.
3997 const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
3998 onUnmounted(() => {
3999 remove(keepAliveRoot[type], injected);
4000 }, target);
4001}
4002function resetShapeFlag(vnode) {
4003 let shapeFlag = vnode.shapeFlag;
4004 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
4005 shapeFlag -= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
4006 }
4007 if (shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
4008 shapeFlag -= 512 /* COMPONENT_KEPT_ALIVE */;
4009 }
4010 vnode.shapeFlag = shapeFlag;
4011}
4012function getInnerChild(vnode) {
4013 return vnode.shapeFlag & 128 /* SUSPENSE */ ? vnode.ssContent : vnode;
4014}
4015
4016const isInternalKey = (key) => key[0] === '_' || key === '$stable';
4017const normalizeSlotValue = (value) => isArray(value)
4018 ? value.map(normalizeVNode)
4019 : [normalizeVNode(value)];
4020const normalizeSlot = (key, rawSlot, ctx) => withCtx((props) => {
4021 if (currentInstance) {
4022 warn(`Slot "${key}" invoked outside of the render function: ` +
4023 `this will not track dependencies used in the slot. ` +
4024 `Invoke the slot function inside the render function instead.`);
4025 }
4026 return normalizeSlotValue(rawSlot(props));
4027}, ctx);
4028const normalizeObjectSlots = (rawSlots, slots) => {
4029 const ctx = rawSlots._ctx;
4030 for (const key in rawSlots) {
4031 if (isInternalKey(key))
4032 continue;
4033 const value = rawSlots[key];
4034 if (isFunction(value)) {
4035 slots[key] = normalizeSlot(key, value, ctx);
4036 }
4037 else if (value != null) {
4038 {
4039 warn(`Non-function value encountered for slot "${key}". ` +
4040 `Prefer function slots for better performance.`);
4041 }
4042 const normalized = normalizeSlotValue(value);
4043 slots[key] = () => normalized;
4044 }
4045 }
4046};
4047const normalizeVNodeSlots = (instance, children) => {
4048 if (!isKeepAlive(instance.vnode)) {
4049 warn(`Non-function value encountered for default slot. ` +
4050 `Prefer function slots for better performance.`);
4051 }
4052 const normalized = normalizeSlotValue(children);
4053 instance.slots.default = () => normalized;
4054};
4055const initSlots = (instance, children) => {
4056 if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
4057 const type = children._;
4058 if (type) {
4059 instance.slots = children;
4060 // make compiler marker non-enumerable
4061 def(children, '_', type);
4062 }
4063 else {
4064 normalizeObjectSlots(children, (instance.slots = {}));
4065 }
4066 }
4067 else {
4068 instance.slots = {};
4069 if (children) {
4070 normalizeVNodeSlots(instance, children);
4071 }
4072 }
4073 def(instance.slots, InternalObjectKey, 1);
4074};
4075const updateSlots = (instance, children) => {
4076 const { vnode, slots } = instance;
4077 let needDeletionCheck = true;
4078 let deletionComparisonTarget = EMPTY_OBJ;
4079 if (vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
4080 const type = children._;
4081 if (type) {
4082 // compiled slots.
4083 if (isHmrUpdating) {
4084 // Parent was HMR updated so slot content may have changed.
4085 // force update slots and mark instance for hmr as well
4086 extend(slots, children);
4087 }
4088 else if (type === 1 /* STABLE */) {
4089 // compiled AND stable.
4090 // no need to update, and skip stale slots removal.
4091 needDeletionCheck = false;
4092 }
4093 else {
4094 // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
4095 // normalization.
4096 extend(slots, children);
4097 }
4098 }
4099 else {
4100 needDeletionCheck = !children.$stable;
4101 normalizeObjectSlots(children, slots);
4102 }
4103 deletionComparisonTarget = children;
4104 }
4105 else if (children) {
4106 // non slot object children (direct value) passed to a component
4107 normalizeVNodeSlots(instance, children);
4108 deletionComparisonTarget = { default: 1 };
4109 }
4110 // delete stale slots
4111 if (needDeletionCheck) {
4112 for (const key in slots) {
4113 if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
4114 delete slots[key];
4115 }
4116 }
4117 }
4118};
4119
4120/**
4121Runtime helper for applying directives to a vnode. Example usage:
4122
4123const comp = resolveComponent('comp')
4124const foo = resolveDirective('foo')
4125const bar = resolveDirective('bar')
4126
4127return withDirectives(h(comp), [
4128 [foo, this.x],
4129 [bar, this.y]
4130])
4131*/
4132const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text');
4133function validateDirectiveName(name) {
4134 if (isBuiltInDirective(name)) {
4135 warn('Do not use built-in directive ids as custom directive id: ' + name);
4136 }
4137}
4138/**
4139 * Adds directives to a VNode.
4140 */
4141function withDirectives(vnode, directives) {
4142 const internalInstance = currentRenderingInstance;
4143 if (internalInstance === null) {
4144 warn(`withDirectives can only be used inside render functions.`);
4145 return vnode;
4146 }
4147 const instance = internalInstance.proxy;
4148 const bindings = vnode.dirs || (vnode.dirs = []);
4149 for (let i = 0; i < directives.length; i++) {
4150 let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
4151 if (isFunction(dir)) {
4152 dir = {
4153 mounted: dir,
4154 updated: dir
4155 };
4156 }
4157 bindings.push({
4158 dir,
4159 instance,
4160 value,
4161 oldValue: void 0,
4162 arg,
4163 modifiers
4164 });
4165 }
4166 return vnode;
4167}
4168function invokeDirectiveHook(vnode, prevVNode, instance, name) {
4169 const bindings = vnode.dirs;
4170 const oldBindings = prevVNode && prevVNode.dirs;
4171 for (let i = 0; i < bindings.length; i++) {
4172 const binding = bindings[i];
4173 if (oldBindings) {
4174 binding.oldValue = oldBindings[i].value;
4175 }
4176 const hook = binding.dir[name];
4177 if (hook) {
4178 callWithAsyncErrorHandling(hook, instance, 8 /* DIRECTIVE_HOOK */, [
4179 vnode.el,
4180 binding,
4181 vnode,
4182 prevVNode
4183 ]);
4184 }
4185 }
4186}
4187
4188function createAppContext() {
4189 return {
4190 app: null,
4191 config: {
4192 isNativeTag: NO,
4193 performance: false,
4194 globalProperties: {},
4195 optionMergeStrategies: {},
4196 isCustomElement: NO,
4197 errorHandler: undefined,
4198 warnHandler: undefined
4199 },
4200 mixins: [],
4201 components: {},
4202 directives: {},
4203 provides: Object.create(null)
4204 };
4205}
4206let uid$1 = 0;
4207function createAppAPI(render, hydrate) {
4208 return function createApp(rootComponent, rootProps = null) {
4209 if (rootProps != null && !isObject(rootProps)) {
4210 warn(`root props passed to app.mount() must be an object.`);
4211 rootProps = null;
4212 }
4213 const context = createAppContext();
4214 const installedPlugins = new Set();
4215 let isMounted = false;
4216 const app = (context.app = {
4217 _uid: uid$1++,
4218 _component: rootComponent,
4219 _props: rootProps,
4220 _container: null,
4221 _context: context,
4222 version,
4223 get config() {
4224 return context.config;
4225 },
4226 set config(v) {
4227 {
4228 warn(`app.config cannot be replaced. Modify individual options instead.`);
4229 }
4230 },
4231 use(plugin, ...options) {
4232 if (installedPlugins.has(plugin)) {
4233 warn(`Plugin has already been applied to target app.`);
4234 }
4235 else if (plugin && isFunction(plugin.install)) {
4236 installedPlugins.add(plugin);
4237 plugin.install(app, ...options);
4238 }
4239 else if (isFunction(plugin)) {
4240 installedPlugins.add(plugin);
4241 plugin(app, ...options);
4242 }
4243 else {
4244 warn(`A plugin must either be a function or an object with an "install" ` +
4245 `function.`);
4246 }
4247 return app;
4248 },
4249 mixin(mixin) {
4250 {
4251 if (!context.mixins.includes(mixin)) {
4252 context.mixins.push(mixin);
4253 // global mixin with props/emits de-optimizes props/emits
4254 // normalization caching.
4255 if (mixin.props || mixin.emits) {
4256 context.deopt = true;
4257 }
4258 }
4259 else {
4260 warn('Mixin has already been applied to target app' +
4261 (mixin.name ? `: ${mixin.name}` : ''));
4262 }
4263 }
4264 return app;
4265 },
4266 component(name, component) {
4267 {
4268 validateComponentName(name, context.config);
4269 }
4270 if (!component) {
4271 return context.components[name];
4272 }
4273 if (context.components[name]) {
4274 warn(`Component "${name}" has already been registered in target app.`);
4275 }
4276 context.components[name] = component;
4277 return app;
4278 },
4279 directive(name, directive) {
4280 {
4281 validateDirectiveName(name);
4282 }
4283 if (!directive) {
4284 return context.directives[name];
4285 }
4286 if (context.directives[name]) {
4287 warn(`Directive "${name}" has already been registered in target app.`);
4288 }
4289 context.directives[name] = directive;
4290 return app;
4291 },
4292 mount(rootContainer, isHydrate, isSVG) {
4293 if (!isMounted) {
4294 const vnode = createVNode(rootComponent, rootProps);
4295 // store app context on the root VNode.
4296 // this will be set on the root instance on initial mount.
4297 vnode.appContext = context;
4298 // HMR root reload
4299 {
4300 context.reload = () => {
4301 render(cloneVNode(vnode), rootContainer, isSVG);
4302 };
4303 }
4304 if (isHydrate && hydrate) {
4305 hydrate(vnode, rootContainer);
4306 }
4307 else {
4308 render(vnode, rootContainer, isSVG);
4309 }
4310 isMounted = true;
4311 app._container = rootContainer;
4312 rootContainer.__vue_app__ = app;
4313 {
4314 devtoolsInitApp(app, version);
4315 }
4316 return vnode.component.proxy;
4317 }
4318 else {
4319 warn(`App has already been mounted.\n` +
4320 `If you want to remount the same app, move your app creation logic ` +
4321 `into a factory function and create fresh app instances for each ` +
4322 `mount - e.g. \`const createMyApp = () => createApp(App)\``);
4323 }
4324 },
4325 unmount() {
4326 if (isMounted) {
4327 render(null, app._container);
4328 {
4329 devtoolsUnmountApp(app);
4330 }
4331 delete app._container.__vue_app__;
4332 }
4333 else {
4334 warn(`Cannot unmount an app that is not mounted.`);
4335 }
4336 },
4337 provide(key, value) {
4338 if (key in context.provides) {
4339 warn(`App already provides property with key "${String(key)}". ` +
4340 `It will be overwritten with the new value.`);
4341 }
4342 // TypeScript doesn't allow symbols as index type
4343 // https://github.com/Microsoft/TypeScript/issues/24587
4344 context.provides[key] = value;
4345 return app;
4346 }
4347 });
4348 return app;
4349 };
4350}
4351
4352let hasMismatch = false;
4353const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
4354const isComment = (node) => node.nodeType === 8 /* COMMENT */;
4355// Note: hydration is DOM-specific
4356// But we have to place it in core due to tight coupling with core - splitting
4357// it out creates a ton of unnecessary complexity.
4358// Hydration also depends on some renderer internal logic which needs to be
4359// passed in via arguments.
4360function createHydrationFunctions(rendererInternals) {
4361 const { mt: mountComponent, p: patch, o: { patchProp, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
4362 const hydrate = (vnode, container) => {
4363 if (!container.hasChildNodes()) {
4364 warn(`Attempting to hydrate existing markup but container is empty. ` +
4365 `Performing full mount instead.`);
4366 patch(null, vnode, container);
4367 return;
4368 }
4369 hasMismatch = false;
4370 hydrateNode(container.firstChild, vnode, null, null, null);
4371 flushPostFlushCbs();
4372 if (hasMismatch && !false) {
4373 // this error should show up in production
4374 console.error(`Hydration completed but contains mismatches.`);
4375 }
4376 };
4377 const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => {
4378 const isFragmentStart = isComment(node) && node.data === '[';
4379 const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragmentStart);
4380 const { type, ref, shapeFlag } = vnode;
4381 const domType = node.nodeType;
4382 vnode.el = node;
4383 let nextNode = null;
4384 switch (type) {
4385 case Text:
4386 if (domType !== 3 /* TEXT */) {
4387 nextNode = onMismatch();
4388 }
4389 else {
4390 if (node.data !== vnode.children) {
4391 hasMismatch = true;
4392 warn(`Hydration text mismatch:` +
4393 `\n- Client: ${JSON.stringify(node.data)}` +
4394 `\n- Server: ${JSON.stringify(vnode.children)}`);
4395 node.data = vnode.children;
4396 }
4397 nextNode = nextSibling(node);
4398 }
4399 break;
4400 case Comment:
4401 if (domType !== 8 /* COMMENT */ || isFragmentStart) {
4402 nextNode = onMismatch();
4403 }
4404 else {
4405 nextNode = nextSibling(node);
4406 }
4407 break;
4408 case Static:
4409 if (domType !== 1 /* ELEMENT */) {
4410 nextNode = onMismatch();
4411 }
4412 else {
4413 // determine anchor, adopt content
4414 nextNode = node;
4415 // if the static vnode has its content stripped during build,
4416 // adopt it from the server-rendered HTML.
4417 const needToAdoptContent = !vnode.children.length;
4418 for (let i = 0; i < vnode.staticCount; i++) {
4419 if (needToAdoptContent)
4420 vnode.children += nextNode.outerHTML;
4421 if (i === vnode.staticCount - 1) {
4422 vnode.anchor = nextNode;
4423 }
4424 nextNode = nextSibling(nextNode);
4425 }
4426 return nextNode;
4427 }
4428 break;
4429 case Fragment:
4430 if (!isFragmentStart) {
4431 nextNode = onMismatch();
4432 }
4433 else {
4434 nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
4435 }
4436 break;
4437 default:
4438 if (shapeFlag & 1 /* ELEMENT */) {
4439 if (domType !== 1 /* ELEMENT */ ||
4440 vnode.type.toLowerCase() !==
4441 node.tagName.toLowerCase()) {
4442 nextNode = onMismatch();
4443 }
4444 else {
4445 nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
4446 }
4447 }
4448 else if (shapeFlag & 6 /* COMPONENT */) {
4449 // when setting up the render effect, if the initial vnode already
4450 // has .el set, the component will perform hydration instead of mount
4451 // on its sub-tree.
4452 vnode.slotScopeIds = slotScopeIds;
4453 const container = parentNode(node);
4454 const hydrateComponent = () => {
4455 mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
4456 };
4457 // async component
4458 const loadAsync = vnode.type.__asyncLoader;
4459 if (loadAsync) {
4460 loadAsync().then(hydrateComponent);
4461 }
4462 else {
4463 hydrateComponent();
4464 }
4465 // component may be async, so in the case of fragments we cannot rely
4466 // on component's rendered output to determine the end of the fragment
4467 // instead, we do a lookahead to find the end anchor node.
4468 nextNode = isFragmentStart
4469 ? locateClosingAsyncAnchor(node)
4470 : nextSibling(node);
4471 }
4472 else if (shapeFlag & 64 /* TELEPORT */) {
4473 if (domType !== 8 /* COMMENT */) {
4474 nextNode = onMismatch();
4475 }
4476 else {
4477 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, rendererInternals, hydrateChildren);
4478 }
4479 }
4480 else if (shapeFlag & 128 /* SUSPENSE */) {
4481 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), slotScopeIds, optimized, rendererInternals, hydrateNode);
4482 }
4483 else {
4484 warn('Invalid HostVNode type:', type, `(${typeof type})`);
4485 }
4486 }
4487 if (ref != null) {
4488 setRef(ref, null, parentSuspense, vnode);
4489 }
4490 return nextNode;
4491 };
4492 const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
4493 optimized = optimized || !!vnode.dynamicChildren;
4494 const { props, patchFlag, shapeFlag, dirs } = vnode;
4495 // skip props & children if this is hoisted static nodes
4496 if (patchFlag !== -1 /* HOISTED */) {
4497 if (dirs) {
4498 invokeDirectiveHook(vnode, null, parentComponent, 'created');
4499 }
4500 // props
4501 if (props) {
4502 if (!optimized ||
4503 (patchFlag & 16 /* FULL_PROPS */ ||
4504 patchFlag & 32 /* HYDRATE_EVENTS */)) {
4505 for (const key in props) {
4506 if (!isReservedProp(key) && isOn(key)) {
4507 patchProp(el, key, null, props[key]);
4508 }
4509 }
4510 }
4511 else if (props.onClick) {
4512 // Fast path for click listeners (which is most often) to avoid
4513 // iterating through props.
4514 patchProp(el, 'onClick', null, props.onClick);
4515 }
4516 }
4517 // vnode / directive hooks
4518 let vnodeHooks;
4519 if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
4520 invokeVNodeHook(vnodeHooks, parentComponent, vnode);
4521 }
4522 if (dirs) {
4523 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
4524 }
4525 if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
4526 queueEffectWithSuspense(() => {
4527 vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
4528 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
4529 }, parentSuspense);
4530 }
4531 // children
4532 if (shapeFlag & 16 /* ARRAY_CHILDREN */ &&
4533 // skip if element has innerHTML / textContent
4534 !(props && (props.innerHTML || props.textContent))) {
4535 let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, slotScopeIds, optimized);
4536 let hasWarned = false;
4537 while (next) {
4538 hasMismatch = true;
4539 if (!hasWarned) {
4540 warn(`Hydration children mismatch in <${vnode.type}>: ` +
4541 `server rendered element contains more child nodes than client vdom.`);
4542 hasWarned = true;
4543 }
4544 // The SSRed DOM contains more nodes than it should. Remove them.
4545 const cur = next;
4546 next = next.nextSibling;
4547 remove(cur);
4548 }
4549 }
4550 else if (shapeFlag & 8 /* TEXT_CHILDREN */) {
4551 if (el.textContent !== vnode.children) {
4552 hasMismatch = true;
4553 warn(`Hydration text content mismatch in <${vnode.type}>:\n` +
4554 `- Client: ${el.textContent}\n` +
4555 `- Server: ${vnode.children}`);
4556 el.textContent = vnode.children;
4557 }
4558 }
4559 }
4560 return el.nextSibling;
4561 };
4562 const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => {
4563 optimized = optimized || !!parentVNode.dynamicChildren;
4564 const children = parentVNode.children;
4565 const l = children.length;
4566 let hasWarned = false;
4567 for (let i = 0; i < l; i++) {
4568 const vnode = optimized
4569 ? children[i]
4570 : (children[i] = normalizeVNode(children[i]));
4571 if (node) {
4572 node = hydrateNode(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
4573 }
4574 else if (vnode.type === Text && !vnode.children) {
4575 continue;
4576 }
4577 else {
4578 hasMismatch = true;
4579 if (!hasWarned) {
4580 warn(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
4581 `server rendered element contains fewer child nodes than client vdom.`);
4582 hasWarned = true;
4583 }
4584 // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
4585 patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
4586 }
4587 }
4588 return node;
4589 };
4590 const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
4591 const { slotScopeIds: fragmentSlotScopeIds } = vnode;
4592 if (fragmentSlotScopeIds) {
4593 slotScopeIds = slotScopeIds
4594 ? slotScopeIds.concat(fragmentSlotScopeIds)
4595 : fragmentSlotScopeIds;
4596 }
4597 const container = parentNode(node);
4598 const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, slotScopeIds, optimized);
4599 if (next && isComment(next) && next.data === ']') {
4600 return nextSibling((vnode.anchor = next));
4601 }
4602 else {
4603 // fragment didn't hydrate successfully, since we didn't get a end anchor
4604 // back. This should have led to node/children mismatch warnings.
4605 hasMismatch = true;
4606 // since the anchor is missing, we need to create one and insert it
4607 insert((vnode.anchor = createComment(`]`)), container, next);
4608 return next;
4609 }
4610 };
4611 const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => {
4612 hasMismatch = true;
4613 warn(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* TEXT */
4614 ? `(text)`
4615 : isComment(node) && node.data === '['
4616 ? `(start of fragment)`
4617 : ``);
4618 vnode.el = null;
4619 if (isFragment) {
4620 // remove excessive fragment nodes
4621 const end = locateClosingAsyncAnchor(node);
4622 while (true) {
4623 const next = nextSibling(node);
4624 if (next && next !== end) {
4625 remove(next);
4626 }
4627 else {
4628 break;
4629 }
4630 }
4631 }
4632 const next = nextSibling(node);
4633 const container = parentNode(node);
4634 remove(node);
4635 patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
4636 return next;
4637 };
4638 const locateClosingAsyncAnchor = (node) => {
4639 let match = 0;
4640 while (node) {
4641 node = nextSibling(node);
4642 if (node && isComment(node)) {
4643 if (node.data === '[')
4644 match++;
4645 if (node.data === ']') {
4646 if (match === 0) {
4647 return nextSibling(node);
4648 }
4649 else {
4650 match--;
4651 }
4652 }
4653 }
4654 }
4655 return node;
4656 };
4657 return [hydrate, hydrateNode];
4658}
4659
4660let supported;
4661let perf;
4662function startMeasure(instance, type) {
4663 if (instance.appContext.config.performance && isSupported()) {
4664 perf.mark(`vue-${type}-${instance.uid}`);
4665 }
4666}
4667function endMeasure(instance, type) {
4668 if (instance.appContext.config.performance && isSupported()) {
4669 const startTag = `vue-${type}-${instance.uid}`;
4670 const endTag = startTag + `:end`;
4671 perf.mark(endTag);
4672 perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
4673 perf.clearMarks(startTag);
4674 perf.clearMarks(endTag);
4675 }
4676}
4677function isSupported() {
4678 if (supported !== undefined) {
4679 return supported;
4680 }
4681 /* eslint-disable no-restricted-globals */
4682 if (typeof window !== 'undefined' && window.performance) {
4683 supported = true;
4684 perf = window.performance;
4685 }
4686 else {
4687 supported = false;
4688 }
4689 /* eslint-enable no-restricted-globals */
4690 return supported;
4691}
4692
4693// implementation, close to no-op
4694function defineComponent(options) {
4695 return isFunction(options) ? { setup: options, name: options.name } : options;
4696}
4697
4698const isAsyncWrapper = (i) => !!i.type.__asyncLoader;
4699function defineAsyncComponent(source) {
4700 if (isFunction(source)) {
4701 source = { loader: source };
4702 }
4703 const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out
4704 suspensible = true, onError: userOnError } = source;
4705 let pendingRequest = null;
4706 let resolvedComp;
4707 let retries = 0;
4708 const retry = () => {
4709 retries++;
4710 pendingRequest = null;
4711 return load();
4712 };
4713 const load = () => {
4714 let thisRequest;
4715 return (pendingRequest ||
4716 (thisRequest = pendingRequest = loader()
4717 .catch(err => {
4718 err = err instanceof Error ? err : new Error(String(err));
4719 if (userOnError) {
4720 return new Promise((resolve, reject) => {
4721 const userRetry = () => resolve(retry());
4722 const userFail = () => reject(err);
4723 userOnError(err, userRetry, userFail, retries + 1);
4724 });
4725 }
4726 else {
4727 throw err;
4728 }
4729 })
4730 .then((comp) => {
4731 if (thisRequest !== pendingRequest && pendingRequest) {
4732 return pendingRequest;
4733 }
4734 if (!comp) {
4735 warn(`Async component loader resolved to undefined. ` +
4736 `If you are using retry(), make sure to return its return value.`);
4737 }
4738 // interop module default
4739 if (comp &&
4740 (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
4741 comp = comp.default;
4742 }
4743 if (comp && !isObject(comp) && !isFunction(comp)) {
4744 throw new Error(`Invalid async component load result: ${comp}`);
4745 }
4746 resolvedComp = comp;
4747 return comp;
4748 })));
4749 };
4750 return defineComponent({
4751 __asyncLoader: load,
4752 name: 'AsyncComponentWrapper',
4753 setup() {
4754 const instance = currentInstance;
4755 // already resolved
4756 if (resolvedComp) {
4757 return () => createInnerComp(resolvedComp, instance);
4758 }
4759 const onError = (err) => {
4760 pendingRequest = null;
4761 handleError(err, instance, 13 /* ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
4762 };
4763 // suspense-controlled or SSR.
4764 if ((suspensible && instance.suspense) ||
4765 (false )) {
4766 return load()
4767 .then(comp => {
4768 return () => createInnerComp(comp, instance);
4769 })
4770 .catch(err => {
4771 onError(err);
4772 return () => errorComponent
4773 ? createVNode(errorComponent, {
4774 error: err
4775 })
4776 : null;
4777 });
4778 }
4779 const loaded = ref(false);
4780 const error = ref();
4781 const delayed = ref(!!delay);
4782 if (delay) {
4783 setTimeout(() => {
4784 delayed.value = false;
4785 }, delay);
4786 }
4787 if (timeout != null) {
4788 setTimeout(() => {
4789 if (!loaded.value && !error.value) {
4790 const err = new Error(`Async component timed out after ${timeout}ms.`);
4791 onError(err);
4792 error.value = err;
4793 }
4794 }, timeout);
4795 }
4796 load()
4797 .then(() => {
4798 loaded.value = true;
4799 })
4800 .catch(err => {
4801 onError(err);
4802 error.value = err;
4803 });
4804 return () => {
4805 if (loaded.value && resolvedComp) {
4806 return createInnerComp(resolvedComp, instance);
4807 }
4808 else if (error.value && errorComponent) {
4809 return createVNode(errorComponent, {
4810 error: error.value
4811 });
4812 }
4813 else if (loadingComponent && !delayed.value) {
4814 return createVNode(loadingComponent);
4815 }
4816 };
4817 }
4818 });
4819}
4820function createInnerComp(comp, { vnode: { ref, props, children } }) {
4821 const vnode = createVNode(comp, props, children);
4822 // ensure inner component inherits the async wrapper's ref owner
4823 vnode.ref = ref;
4824 return vnode;
4825}
4826
4827function createDevEffectOptions(instance) {
4828 return {
4829 scheduler: queueJob,
4830 allowRecurse: true,
4831 onTrack: instance.rtc ? e => invokeArrayFns(instance.rtc, e) : void 0,
4832 onTrigger: instance.rtg ? e => invokeArrayFns(instance.rtg, e) : void 0
4833 };
4834}
4835const queuePostRenderEffect = queueEffectWithSuspense
4836 ;
4837const setRef = (rawRef, oldRawRef, parentSuspense, vnode) => {
4838 if (isArray(rawRef)) {
4839 rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode));
4840 return;
4841 }
4842 let value;
4843 if (!vnode) {
4844 // means unmount
4845 value = null;
4846 }
4847 else if (isAsyncWrapper(vnode)) {
4848 // when mounting async components, nothing needs to be done,
4849 // because the template ref is forwarded to inner component
4850 return;
4851 }
4852 else if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
4853 value = vnode.component.exposed || vnode.component.proxy;
4854 }
4855 else {
4856 value = vnode.el;
4857 }
4858 const { i: owner, r: ref } = rawRef;
4859 if (!owner) {
4860 warn(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
4861 `A vnode with ref must be created inside the render function.`);
4862 return;
4863 }
4864 const oldRef = oldRawRef && oldRawRef.r;
4865 const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
4866 const setupState = owner.setupState;
4867 // unset old ref
4868 if (oldRef != null && oldRef !== ref) {
4869 if (isString(oldRef)) {
4870 refs[oldRef] = null;
4871 if (hasOwn(setupState, oldRef)) {
4872 setupState[oldRef] = null;
4873 }
4874 }
4875 else if (isRef(oldRef)) {
4876 oldRef.value = null;
4877 }
4878 }
4879 if (isString(ref)) {
4880 const doSet = () => {
4881 refs[ref] = value;
4882 if (hasOwn(setupState, ref)) {
4883 setupState[ref] = value;
4884 }
4885 };
4886 // #1789: for non-null values, set them after render
4887 // null values means this is unmount and it should not overwrite another
4888 // ref with the same key
4889 if (value) {
4890 doSet.id = -1;
4891 queuePostRenderEffect(doSet, parentSuspense);
4892 }
4893 else {
4894 doSet();
4895 }
4896 }
4897 else if (isRef(ref)) {
4898 const doSet = () => {
4899 ref.value = value;
4900 };
4901 if (value) {
4902 doSet.id = -1;
4903 queuePostRenderEffect(doSet, parentSuspense);
4904 }
4905 else {
4906 doSet();
4907 }
4908 }
4909 else if (isFunction(ref)) {
4910 callWithErrorHandling(ref, owner, 12 /* FUNCTION_REF */, [value, refs]);
4911 }
4912 else {
4913 warn('Invalid template ref type:', value, `(${typeof value})`);
4914 }
4915};
4916/**
4917 * The createRenderer function accepts two generic arguments:
4918 * HostNode and HostElement, corresponding to Node and Element types in the
4919 * host environment. For example, for runtime-dom, HostNode would be the DOM
4920 * `Node` interface and HostElement would be the DOM `Element` interface.
4921 *
4922 * Custom renderers can pass in the platform specific types like this:
4923 *
4924 * ``` js
4925 * const { render, createApp } = createRenderer<Node, Element>({
4926 * patchProp,
4927 * ...nodeOps
4928 * })
4929 * ```
4930 */
4931function createRenderer(options) {
4932 return baseCreateRenderer(options);
4933}
4934// Separate API for creating hydration-enabled renderer.
4935// Hydration logic is only used when calling this function, making it
4936// tree-shakable.
4937function createHydrationRenderer(options) {
4938 return baseCreateRenderer(options, createHydrationFunctions);
4939}
4940// implementation
4941function baseCreateRenderer(options, createHydrationFns) {
4942 {
4943 const target = getGlobalThis();
4944 target.__VUE__ = true;
4945 setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__);
4946 }
4947 const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, forcePatchProp: hostForcePatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, setScopeId: hostSetScopeId = NOOP, cloneNode: hostCloneNode, insertStaticContent: hostInsertStaticContent } = options;
4948 // Note: functions inside this closure should use `const xxx = () => {}`
4949 // style in order to prevent being inlined by minifiers.
4950 const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, slotScopeIds = null, optimized = false) => {
4951 // patching & not same type, unmount old tree
4952 if (n1 && !isSameVNodeType(n1, n2)) {
4953 anchor = getNextHostNode(n1);
4954 unmount(n1, parentComponent, parentSuspense, true);
4955 n1 = null;
4956 }
4957 if (n2.patchFlag === -2 /* BAIL */) {
4958 optimized = false;
4959 n2.dynamicChildren = null;
4960 }
4961 const { type, ref, shapeFlag } = n2;
4962 switch (type) {
4963 case Text:
4964 processText(n1, n2, container, anchor);
4965 break;
4966 case Comment:
4967 processCommentNode(n1, n2, container, anchor);
4968 break;
4969 case Static:
4970 if (n1 == null) {
4971 mountStaticNode(n2, container, anchor, isSVG);
4972 }
4973 else {
4974 patchStaticNode(n1, n2, container, isSVG);
4975 }
4976 break;
4977 case Fragment:
4978 processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
4979 break;
4980 default:
4981 if (shapeFlag & 1 /* ELEMENT */) {
4982 processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
4983 }
4984 else if (shapeFlag & 6 /* COMPONENT */) {
4985 processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
4986 }
4987 else if (shapeFlag & 64 /* TELEPORT */) {
4988 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
4989 }
4990 else if (shapeFlag & 128 /* SUSPENSE */) {
4991 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
4992 }
4993 else {
4994 warn('Invalid VNode type:', type, `(${typeof type})`);
4995 }
4996 }
4997 // set ref
4998 if (ref != null && parentComponent) {
4999 setRef(ref, n1 && n1.ref, parentSuspense, n2);
5000 }
5001 };
5002 const processText = (n1, n2, container, anchor) => {
5003 if (n1 == null) {
5004 hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
5005 }
5006 else {
5007 const el = (n2.el = n1.el);
5008 if (n2.children !== n1.children) {
5009 hostSetText(el, n2.children);
5010 }
5011 }
5012 };
5013 const processCommentNode = (n1, n2, container, anchor) => {
5014 if (n1 == null) {
5015 hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
5016 }
5017 else {
5018 // there's no support for dynamic comments
5019 n2.el = n1.el;
5020 }
5021 };
5022 const mountStaticNode = (n2, container, anchor, isSVG) => {
5023 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
5024 };
5025 /**
5026 * Dev / HMR only
5027 */
5028 const patchStaticNode = (n1, n2, container, isSVG) => {
5029 // static nodes are only patched during dev for HMR
5030 if (n2.children !== n1.children) {
5031 const anchor = hostNextSibling(n1.anchor);
5032 // remove existing
5033 removeStaticNode(n1);
5034 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
5035 }
5036 else {
5037 n2.el = n1.el;
5038 n2.anchor = n1.anchor;
5039 }
5040 };
5041 const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
5042 let next;
5043 while (el && el !== anchor) {
5044 next = hostNextSibling(el);
5045 hostInsert(el, container, nextSibling);
5046 el = next;
5047 }
5048 hostInsert(anchor, container, nextSibling);
5049 };
5050 const removeStaticNode = ({ el, anchor }) => {
5051 let next;
5052 while (el && el !== anchor) {
5053 next = hostNextSibling(el);
5054 hostRemove(el);
5055 el = next;
5056 }
5057 hostRemove(anchor);
5058 };
5059 const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5060 isSVG = isSVG || n2.type === 'svg';
5061 if (n1 == null) {
5062 mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5063 }
5064 else {
5065 patchElement(n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5066 }
5067 };
5068 const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5069 let el;
5070 let vnodeHook;
5071 const { type, props, shapeFlag, transition, patchFlag, dirs } = vnode;
5072 {
5073 el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is, props);
5074 // mount children first, since some props may rely on child content
5075 // being already rendered, e.g. `<select value>`
5076 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
5077 hostSetElementText(el, vnode.children);
5078 }
5079 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
5080 mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', slotScopeIds, optimized || !!vnode.dynamicChildren);
5081 }
5082 if (dirs) {
5083 invokeDirectiveHook(vnode, null, parentComponent, 'created');
5084 }
5085 // props
5086 if (props) {
5087 for (const key in props) {
5088 if (!isReservedProp(key)) {
5089 hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
5090 }
5091 }
5092 if ((vnodeHook = props.onVnodeBeforeMount)) {
5093 invokeVNodeHook(vnodeHook, parentComponent, vnode);
5094 }
5095 }
5096 // scopeId
5097 setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
5098 }
5099 {
5100 Object.defineProperty(el, '__vnode', {
5101 value: vnode,
5102 enumerable: false
5103 });
5104 Object.defineProperty(el, '__vueParentComponent', {
5105 value: parentComponent,
5106 enumerable: false
5107 });
5108 }
5109 if (dirs) {
5110 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
5111 }
5112 // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
5113 // #1689 For inside suspense + suspense resolved case, just call it
5114 const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
5115 transition &&
5116 !transition.persisted;
5117 if (needCallTransitionHooks) {
5118 transition.beforeEnter(el);
5119 }
5120 hostInsert(el, container, anchor);
5121 if ((vnodeHook = props && props.onVnodeMounted) ||
5122 needCallTransitionHooks ||
5123 dirs) {
5124 queuePostRenderEffect(() => {
5125 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
5126 needCallTransitionHooks && transition.enter(el);
5127 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
5128 }, parentSuspense);
5129 }
5130 };
5131 const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => {
5132 if (scopeId) {
5133 hostSetScopeId(el, scopeId);
5134 }
5135 if (slotScopeIds) {
5136 for (let i = 0; i < slotScopeIds.length; i++) {
5137 hostSetScopeId(el, slotScopeIds[i]);
5138 }
5139 }
5140 if (parentComponent) {
5141 let subTree = parentComponent.subTree;
5142 if (subTree.patchFlag > 0 &&
5143 subTree.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
5144 subTree =
5145 filterSingleRoot(subTree.children) || subTree;
5146 }
5147 if (vnode === subTree) {
5148 const parentVNode = parentComponent.vnode;
5149 setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent);
5150 }
5151 }
5152 };
5153 const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, optimized, slotScopeIds, start = 0) => {
5154 for (let i = start; i < children.length; i++) {
5155 const child = (children[i] = optimized
5156 ? cloneIfMounted(children[i])
5157 : normalizeVNode(children[i]));
5158 patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, optimized, slotScopeIds);
5159 }
5160 };
5161 const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5162 const el = (n2.el = n1.el);
5163 let { patchFlag, dynamicChildren, dirs } = n2;
5164 // #1426 take the old vnode's patch flag into account since user may clone a
5165 // compiler-generated vnode, which de-opts to FULL_PROPS
5166 patchFlag |= n1.patchFlag & 16 /* FULL_PROPS */;
5167 const oldProps = n1.props || EMPTY_OBJ;
5168 const newProps = n2.props || EMPTY_OBJ;
5169 let vnodeHook;
5170 if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
5171 invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
5172 }
5173 if (dirs) {
5174 invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
5175 }
5176 if (isHmrUpdating) {
5177 // HMR updated, force full diff
5178 patchFlag = 0;
5179 optimized = false;
5180 dynamicChildren = null;
5181 }
5182 if (patchFlag > 0) {
5183 // the presence of a patchFlag means this element's render code was
5184 // generated by the compiler and can take the fast path.
5185 // in this path old node and new node are guaranteed to have the same shape
5186 // (i.e. at the exact same position in the source template)
5187 if (patchFlag & 16 /* FULL_PROPS */) {
5188 // element props contain dynamic keys, full diff needed
5189 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
5190 }
5191 else {
5192 // class
5193 // this flag is matched when the element has dynamic class bindings.
5194 if (patchFlag & 2 /* CLASS */) {
5195 if (oldProps.class !== newProps.class) {
5196 hostPatchProp(el, 'class', null, newProps.class, isSVG);
5197 }
5198 }
5199 // style
5200 // this flag is matched when the element has dynamic style bindings
5201 if (patchFlag & 4 /* STYLE */) {
5202 hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
5203 }
5204 // props
5205 // This flag is matched when the element has dynamic prop/attr bindings
5206 // other than class and style. The keys of dynamic prop/attrs are saved for
5207 // faster iteration.
5208 // Note dynamic keys like :[foo]="bar" will cause this optimization to
5209 // bail out and go through a full diff because we need to unset the old key
5210 if (patchFlag & 8 /* PROPS */) {
5211 // if the flag is present then dynamicProps must be non-null
5212 const propsToUpdate = n2.dynamicProps;
5213 for (let i = 0; i < propsToUpdate.length; i++) {
5214 const key = propsToUpdate[i];
5215 const prev = oldProps[key];
5216 const next = newProps[key];
5217 if (next !== prev ||
5218 (hostForcePatchProp && hostForcePatchProp(el, key))) {
5219 hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
5220 }
5221 }
5222 }
5223 }
5224 // text
5225 // This flag is matched when the element has only dynamic text children.
5226 if (patchFlag & 1 /* TEXT */) {
5227 if (n1.children !== n2.children) {
5228 hostSetElementText(el, n2.children);
5229 }
5230 }
5231 }
5232 else if (!optimized && dynamicChildren == null) {
5233 // unoptimized, full diff
5234 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
5235 }
5236 const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
5237 if (dynamicChildren) {
5238 patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds);
5239 if (parentComponent && parentComponent.type.__hmrId) {
5240 traverseStaticChildren(n1, n2);
5241 }
5242 }
5243 else if (!optimized) {
5244 // full diff
5245 patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds, false);
5246 }
5247 if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
5248 queuePostRenderEffect(() => {
5249 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
5250 dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
5251 }, parentSuspense);
5252 }
5253 };
5254 // The fast path for blocks.
5255 const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG, slotScopeIds) => {
5256 for (let i = 0; i < newChildren.length; i++) {
5257 const oldVNode = oldChildren[i];
5258 const newVNode = newChildren[i];
5259 // Determine the container (parent element) for the patch.
5260 const container =
5261 // - In the case of a Fragment, we need to provide the actual parent
5262 // of the Fragment itself so it can move its children.
5263 oldVNode.type === Fragment ||
5264 // - In the case of different nodes, there is going to be a replacement
5265 // which also requires the correct parent container
5266 !isSameVNodeType(oldVNode, newVNode) ||
5267 // - In the case of a component, it could contain anything.
5268 oldVNode.shapeFlag & 6 /* COMPONENT */ ||
5269 oldVNode.shapeFlag & 64 /* TELEPORT */
5270 ? hostParentNode(oldVNode.el)
5271 : // In other cases, the parent container is not actually used so we
5272 // just pass the block element here to avoid a DOM parentNode call.
5273 fallbackContainer;
5274 patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, true);
5275 }
5276 };
5277 const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
5278 if (oldProps !== newProps) {
5279 for (const key in newProps) {
5280 // empty string is not valid prop
5281 if (isReservedProp(key))
5282 continue;
5283 const next = newProps[key];
5284 const prev = oldProps[key];
5285 if (next !== prev ||
5286 (hostForcePatchProp && hostForcePatchProp(el, key))) {
5287 hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
5288 }
5289 }
5290 if (oldProps !== EMPTY_OBJ) {
5291 for (const key in oldProps) {
5292 if (!isReservedProp(key) && !(key in newProps)) {
5293 hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
5294 }
5295 }
5296 }
5297 }
5298 };
5299 const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5300 const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
5301 const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
5302 let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;
5303 if (patchFlag > 0) {
5304 optimized = true;
5305 }
5306 // check if this is a slot fragment with :slotted scope ids
5307 if (fragmentSlotScopeIds) {
5308 slotScopeIds = slotScopeIds
5309 ? slotScopeIds.concat(fragmentSlotScopeIds)
5310 : fragmentSlotScopeIds;
5311 }
5312 if (isHmrUpdating) {
5313 // HMR updated, force full diff
5314 patchFlag = 0;
5315 optimized = false;
5316 dynamicChildren = null;
5317 }
5318 if (n1 == null) {
5319 hostInsert(fragmentStartAnchor, container, anchor);
5320 hostInsert(fragmentEndAnchor, container, anchor);
5321 // a fragment can only have array children
5322 // since they are either generated by the compiler, or implicitly created
5323 // from arrays.
5324 mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5325 }
5326 else {
5327 if (patchFlag > 0 &&
5328 patchFlag & 64 /* STABLE_FRAGMENT */ &&
5329 dynamicChildren &&
5330 // #2715 the previous fragment could've been a BAILed one as a result
5331 // of renderSlot() with no valid children
5332 n1.dynamicChildren) {
5333 // a stable fragment (template root or <template v-for>) doesn't need to
5334 // patch children order, but it may contain dynamicChildren.
5335 patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG, slotScopeIds);
5336 if (parentComponent && parentComponent.type.__hmrId) {
5337 traverseStaticChildren(n1, n2);
5338 }
5339 else if (
5340 // #2080 if the stable fragment has a key, it's a <template v-for> that may
5341 // get moved around. Make sure all root level vnodes inherit el.
5342 // #2134 or if it's a component root, it may also get moved around
5343 // as the component is being moved.
5344 n2.key != null ||
5345 (parentComponent && n2 === parentComponent.subTree)) {
5346 traverseStaticChildren(n1, n2, true /* shallow */);
5347 }
5348 }
5349 else {
5350 // keyed / unkeyed, or manual fragments.
5351 // for keyed & unkeyed, since they are compiler generated from v-for,
5352 // each child is guaranteed to be a block so the fragment will never
5353 // have dynamicChildren.
5354 patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5355 }
5356 }
5357 };
5358 const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5359 n2.slotScopeIds = slotScopeIds;
5360 if (n1 == null) {
5361 if (n2.shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
5362 parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
5363 }
5364 else {
5365 mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
5366 }
5367 }
5368 else {
5369 updateComponent(n1, n2, optimized);
5370 }
5371 };
5372 const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
5373 const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
5374 if (instance.type.__hmrId) {
5375 registerHMR(instance);
5376 }
5377 {
5378 pushWarningContext(initialVNode);
5379 startMeasure(instance, `mount`);
5380 }
5381 // inject renderer internals for keepAlive
5382 if (isKeepAlive(initialVNode)) {
5383 instance.ctx.renderer = internals;
5384 }
5385 // resolve props and slots for setup context
5386 {
5387 startMeasure(instance, `init`);
5388 }
5389 setupComponent(instance);
5390 {
5391 endMeasure(instance, `init`);
5392 }
5393 // setup() is async. This component relies on async logic to be resolved
5394 // before proceeding
5395 if (instance.asyncDep) {
5396 parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
5397 // Give it a placeholder if this is not hydration
5398 // TODO handle self-defined fallback
5399 if (!initialVNode.el) {
5400 const placeholder = (instance.subTree = createVNode(Comment));
5401 processCommentNode(null, placeholder, container, anchor);
5402 }
5403 return;
5404 }
5405 setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
5406 {
5407 popWarningContext();
5408 endMeasure(instance, `mount`);
5409 }
5410 };
5411 const updateComponent = (n1, n2, optimized) => {
5412 const instance = (n2.component = n1.component);
5413 if (shouldUpdateComponent(n1, n2, optimized)) {
5414 if (instance.asyncDep &&
5415 !instance.asyncResolved) {
5416 // async & still pending - just update props and slots
5417 // since the component's reactive effect for render isn't set-up yet
5418 {
5419 pushWarningContext(n2);
5420 }
5421 updateComponentPreRender(instance, n2, optimized);
5422 {
5423 popWarningContext();
5424 }
5425 return;
5426 }
5427 else {
5428 // normal update
5429 instance.next = n2;
5430 // in case the child component is also queued, remove it to avoid
5431 // double updating the same child component in the same flush.
5432 invalidateJob(instance.update);
5433 // instance.update is the reactive effect runner.
5434 instance.update();
5435 }
5436 }
5437 else {
5438 // no update needed. just copy over properties
5439 n2.component = n1.component;
5440 n2.el = n1.el;
5441 instance.vnode = n2;
5442 }
5443 };
5444 const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
5445 // create reactive effect for rendering
5446 instance.update = effect(function componentEffect() {
5447 if (!instance.isMounted) {
5448 let vnodeHook;
5449 const { el, props } = initialVNode;
5450 const { bm, m, parent } = instance;
5451 // beforeMount hook
5452 if (bm) {
5453 invokeArrayFns(bm);
5454 }
5455 // onVnodeBeforeMount
5456 if ((vnodeHook = props && props.onVnodeBeforeMount)) {
5457 invokeVNodeHook(vnodeHook, parent, initialVNode);
5458 }
5459 // render
5460 {
5461 startMeasure(instance, `render`);
5462 }
5463 const subTree = (instance.subTree = renderComponentRoot(instance));
5464 {
5465 endMeasure(instance, `render`);
5466 }
5467 if (el && hydrateNode) {
5468 {
5469 startMeasure(instance, `hydrate`);
5470 }
5471 // vnode has adopted host node - perform hydration instead of mount.
5472 hydrateNode(initialVNode.el, subTree, instance, parentSuspense, null);
5473 {
5474 endMeasure(instance, `hydrate`);
5475 }
5476 }
5477 else {
5478 {
5479 startMeasure(instance, `patch`);
5480 }
5481 patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
5482 {
5483 endMeasure(instance, `patch`);
5484 }
5485 initialVNode.el = subTree.el;
5486 }
5487 // mounted hook
5488 if (m) {
5489 queuePostRenderEffect(m, parentSuspense);
5490 }
5491 // onVnodeMounted
5492 if ((vnodeHook = props && props.onVnodeMounted)) {
5493 const scopedInitialVNode = initialVNode;
5494 queuePostRenderEffect(() => {
5495 invokeVNodeHook(vnodeHook, parent, scopedInitialVNode);
5496 }, parentSuspense);
5497 }
5498 // activated hook for keep-alive roots.
5499 // #1742 activated hook must be accessed after first render
5500 // since the hook may be injected by a child keep-alive
5501 const { a } = instance;
5502 if (a &&
5503 initialVNode.shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
5504 queuePostRenderEffect(a, parentSuspense);
5505 }
5506 instance.isMounted = true;
5507 {
5508 devtoolsComponentAdded(instance);
5509 }
5510 // #2458: deference mount-only object parameters to prevent memleaks
5511 initialVNode = container = anchor = null;
5512 }
5513 else {
5514 // updateComponent
5515 // This is triggered by mutation of component's own state (next: null)
5516 // OR parent calling processComponent (next: VNode)
5517 let { next, bu, u, parent, vnode } = instance;
5518 let originNext = next;
5519 let vnodeHook;
5520 {
5521 pushWarningContext(next || instance.vnode);
5522 }
5523 if (next) {
5524 next.el = vnode.el;
5525 updateComponentPreRender(instance, next, optimized);
5526 }
5527 else {
5528 next = vnode;
5529 }
5530 // beforeUpdate hook
5531 if (bu) {
5532 invokeArrayFns(bu);
5533 }
5534 // onVnodeBeforeUpdate
5535 if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
5536 invokeVNodeHook(vnodeHook, parent, next, vnode);
5537 }
5538 // render
5539 {
5540 startMeasure(instance, `render`);
5541 }
5542 const nextTree = renderComponentRoot(instance);
5543 {
5544 endMeasure(instance, `render`);
5545 }
5546 const prevTree = instance.subTree;
5547 instance.subTree = nextTree;
5548 {
5549 startMeasure(instance, `patch`);
5550 }
5551 patch(prevTree, nextTree,
5552 // parent may have changed if it's in a teleport
5553 hostParentNode(prevTree.el),
5554 // anchor may have changed if it's in a fragment
5555 getNextHostNode(prevTree), instance, parentSuspense, isSVG);
5556 {
5557 endMeasure(instance, `patch`);
5558 }
5559 next.el = nextTree.el;
5560 if (originNext === null) {
5561 // self-triggered update. In case of HOC, update parent component
5562 // vnode el. HOC is indicated by parent instance's subTree pointing
5563 // to child component's vnode
5564 updateHOCHostEl(instance, nextTree.el);
5565 }
5566 // updated hook
5567 if (u) {
5568 queuePostRenderEffect(u, parentSuspense);
5569 }
5570 // onVnodeUpdated
5571 if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
5572 queuePostRenderEffect(() => {
5573 invokeVNodeHook(vnodeHook, parent, next, vnode);
5574 }, parentSuspense);
5575 }
5576 {
5577 devtoolsComponentUpdated(instance);
5578 }
5579 {
5580 popWarningContext();
5581 }
5582 }
5583 }, createDevEffectOptions(instance) );
5584 };
5585 const updateComponentPreRender = (instance, nextVNode, optimized) => {
5586 nextVNode.component = instance;
5587 const prevProps = instance.vnode.props;
5588 instance.vnode = nextVNode;
5589 instance.next = null;
5590 updateProps(instance, nextVNode.props, prevProps, optimized);
5591 updateSlots(instance, nextVNode.children);
5592 pauseTracking();
5593 // props update may have triggered pre-flush watchers.
5594 // flush them before the render update.
5595 flushPreFlushCbs(undefined, instance.update);
5596 resetTracking();
5597 };
5598 const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized = false) => {
5599 const c1 = n1 && n1.children;
5600 const prevShapeFlag = n1 ? n1.shapeFlag : 0;
5601 const c2 = n2.children;
5602 const { patchFlag, shapeFlag } = n2;
5603 // fast path
5604 if (patchFlag > 0) {
5605 if (patchFlag & 128 /* KEYED_FRAGMENT */) {
5606 // this could be either fully-keyed or mixed (some keyed some not)
5607 // presence of patchFlag means children are guaranteed to be arrays
5608 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5609 return;
5610 }
5611 else if (patchFlag & 256 /* UNKEYED_FRAGMENT */) {
5612 // unkeyed
5613 patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5614 return;
5615 }
5616 }
5617 // children has 3 possibilities: text, array or no children.
5618 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
5619 // text children fast path
5620 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
5621 unmountChildren(c1, parentComponent, parentSuspense);
5622 }
5623 if (c2 !== c1) {
5624 hostSetElementText(container, c2);
5625 }
5626 }
5627 else {
5628 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
5629 // prev children was array
5630 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
5631 // two arrays, cannot assume anything, do full diff
5632 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5633 }
5634 else {
5635 // no new children, just unmount old
5636 unmountChildren(c1, parentComponent, parentSuspense, true);
5637 }
5638 }
5639 else {
5640 // prev children was text OR null
5641 // new children is array OR null
5642 if (prevShapeFlag & 8 /* TEXT_CHILDREN */) {
5643 hostSetElementText(container, '');
5644 }
5645 // mount new if array
5646 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
5647 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5648 }
5649 }
5650 }
5651 };
5652 const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5653 c1 = c1 || EMPTY_ARR;
5654 c2 = c2 || EMPTY_ARR;
5655 const oldLength = c1.length;
5656 const newLength = c2.length;
5657 const commonLength = Math.min(oldLength, newLength);
5658 let i;
5659 for (i = 0; i < commonLength; i++) {
5660 const nextChild = (c2[i] = optimized
5661 ? cloneIfMounted(c2[i])
5662 : normalizeVNode(c2[i]));
5663 patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5664 }
5665 if (oldLength > newLength) {
5666 // remove old
5667 unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
5668 }
5669 else {
5670 // mount new
5671 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, commonLength);
5672 }
5673 };
5674 // can be all-keyed or mixed
5675 const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5676 let i = 0;
5677 const l2 = c2.length;
5678 let e1 = c1.length - 1; // prev ending index
5679 let e2 = l2 - 1; // next ending index
5680 // 1. sync from start
5681 // (a b) c
5682 // (a b) d e
5683 while (i <= e1 && i <= e2) {
5684 const n1 = c1[i];
5685 const n2 = (c2[i] = optimized
5686 ? cloneIfMounted(c2[i])
5687 : normalizeVNode(c2[i]));
5688 if (isSameVNodeType(n1, n2)) {
5689 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5690 }
5691 else {
5692 break;
5693 }
5694 i++;
5695 }
5696 // 2. sync from end
5697 // a (b c)
5698 // d e (b c)
5699 while (i <= e1 && i <= e2) {
5700 const n1 = c1[e1];
5701 const n2 = (c2[e2] = optimized
5702 ? cloneIfMounted(c2[e2])
5703 : normalizeVNode(c2[e2]));
5704 if (isSameVNodeType(n1, n2)) {
5705 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5706 }
5707 else {
5708 break;
5709 }
5710 e1--;
5711 e2--;
5712 }
5713 // 3. common sequence + mount
5714 // (a b)
5715 // (a b) c
5716 // i = 2, e1 = 1, e2 = 2
5717 // (a b)
5718 // c (a b)
5719 // i = 0, e1 = -1, e2 = 0
5720 if (i > e1) {
5721 if (i <= e2) {
5722 const nextPos = e2 + 1;
5723 const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
5724 while (i <= e2) {
5725 patch(null, (c2[i] = optimized
5726 ? cloneIfMounted(c2[i])
5727 : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5728 i++;
5729 }
5730 }
5731 }
5732 // 4. common sequence + unmount
5733 // (a b) c
5734 // (a b)
5735 // i = 2, e1 = 2, e2 = 1
5736 // a (b c)
5737 // (b c)
5738 // i = 0, e1 = 0, e2 = -1
5739 else if (i > e2) {
5740 while (i <= e1) {
5741 unmount(c1[i], parentComponent, parentSuspense, true);
5742 i++;
5743 }
5744 }
5745 // 5. unknown sequence
5746 // [i ... e1 + 1]: a b [c d e] f g
5747 // [i ... e2 + 1]: a b [e d c h] f g
5748 // i = 2, e1 = 4, e2 = 5
5749 else {
5750 const s1 = i; // prev starting index
5751 const s2 = i; // next starting index
5752 // 5.1 build key:index map for newChildren
5753 const keyToNewIndexMap = new Map();
5754 for (i = s2; i <= e2; i++) {
5755 const nextChild = (c2[i] = optimized
5756 ? cloneIfMounted(c2[i])
5757 : normalizeVNode(c2[i]));
5758 if (nextChild.key != null) {
5759 if (keyToNewIndexMap.has(nextChild.key)) {
5760 warn(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
5761 }
5762 keyToNewIndexMap.set(nextChild.key, i);
5763 }
5764 }
5765 // 5.2 loop through old children left to be patched and try to patch
5766 // matching nodes & remove nodes that are no longer present
5767 let j;
5768 let patched = 0;
5769 const toBePatched = e2 - s2 + 1;
5770 let moved = false;
5771 // used to track whether any node has moved
5772 let maxNewIndexSoFar = 0;
5773 // works as Map<newIndex, oldIndex>
5774 // Note that oldIndex is offset by +1
5775 // and oldIndex = 0 is a special value indicating the new node has
5776 // no corresponding old node.
5777 // used for determining longest stable subsequence
5778 const newIndexToOldIndexMap = new Array(toBePatched);
5779 for (i = 0; i < toBePatched; i++)
5780 newIndexToOldIndexMap[i] = 0;
5781 for (i = s1; i <= e1; i++) {
5782 const prevChild = c1[i];
5783 if (patched >= toBePatched) {
5784 // all new children have been patched so this can only be a removal
5785 unmount(prevChild, parentComponent, parentSuspense, true);
5786 continue;
5787 }
5788 let newIndex;
5789 if (prevChild.key != null) {
5790 newIndex = keyToNewIndexMap.get(prevChild.key);
5791 }
5792 else {
5793 // key-less node, try to locate a key-less node of the same type
5794 for (j = s2; j <= e2; j++) {
5795 if (newIndexToOldIndexMap[j - s2] === 0 &&
5796 isSameVNodeType(prevChild, c2[j])) {
5797 newIndex = j;
5798 break;
5799 }
5800 }
5801 }
5802 if (newIndex === undefined) {
5803 unmount(prevChild, parentComponent, parentSuspense, true);
5804 }
5805 else {
5806 newIndexToOldIndexMap[newIndex - s2] = i + 1;
5807 if (newIndex >= maxNewIndexSoFar) {
5808 maxNewIndexSoFar = newIndex;
5809 }
5810 else {
5811 moved = true;
5812 }
5813 patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5814 patched++;
5815 }
5816 }
5817 // 5.3 move and mount
5818 // generate longest stable subsequence only when nodes have moved
5819 const increasingNewIndexSequence = moved
5820 ? getSequence(newIndexToOldIndexMap)
5821 : EMPTY_ARR;
5822 j = increasingNewIndexSequence.length - 1;
5823 // looping backwards so that we can use last patched node as anchor
5824 for (i = toBePatched - 1; i >= 0; i--) {
5825 const nextIndex = s2 + i;
5826 const nextChild = c2[nextIndex];
5827 const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
5828 if (newIndexToOldIndexMap[i] === 0) {
5829 // mount new
5830 patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5831 }
5832 else if (moved) {
5833 // move if:
5834 // There is no stable subsequence (e.g. a reverse)
5835 // OR current node is not among the stable sequence
5836 if (j < 0 || i !== increasingNewIndexSequence[j]) {
5837 move(nextChild, container, anchor, 2 /* REORDER */);
5838 }
5839 else {
5840 j--;
5841 }
5842 }
5843 }
5844 }
5845 };
5846 const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
5847 const { el, type, transition, children, shapeFlag } = vnode;
5848 if (shapeFlag & 6 /* COMPONENT */) {
5849 move(vnode.component.subTree, container, anchor, moveType);
5850 return;
5851 }
5852 if (shapeFlag & 128 /* SUSPENSE */) {
5853 vnode.suspense.move(container, anchor, moveType);
5854 return;
5855 }
5856 if (shapeFlag & 64 /* TELEPORT */) {
5857 type.move(vnode, container, anchor, internals);
5858 return;
5859 }
5860 if (type === Fragment) {
5861 hostInsert(el, container, anchor);
5862 for (let i = 0; i < children.length; i++) {
5863 move(children[i], container, anchor, moveType);
5864 }
5865 hostInsert(vnode.anchor, container, anchor);
5866 return;
5867 }
5868 if (type === Static) {
5869 moveStaticNode(vnode, container, anchor);
5870 return;
5871 }
5872 // single nodes
5873 const needTransition = moveType !== 2 /* REORDER */ &&
5874 shapeFlag & 1 /* ELEMENT */ &&
5875 transition;
5876 if (needTransition) {
5877 if (moveType === 0 /* ENTER */) {
5878 transition.beforeEnter(el);
5879 hostInsert(el, container, anchor);
5880 queuePostRenderEffect(() => transition.enter(el), parentSuspense);
5881 }
5882 else {
5883 const { leave, delayLeave, afterLeave } = transition;
5884 const remove = () => hostInsert(el, container, anchor);
5885 const performLeave = () => {
5886 leave(el, () => {
5887 remove();
5888 afterLeave && afterLeave();
5889 });
5890 };
5891 if (delayLeave) {
5892 delayLeave(el, remove, performLeave);
5893 }
5894 else {
5895 performLeave();
5896 }
5897 }
5898 }
5899 else {
5900 hostInsert(el, container, anchor);
5901 }
5902 };
5903 const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
5904 const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
5905 // unset ref
5906 if (ref != null) {
5907 setRef(ref, null, parentSuspense, null);
5908 }
5909 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
5910 parentComponent.ctx.deactivate(vnode);
5911 return;
5912 }
5913 const shouldInvokeDirs = shapeFlag & 1 /* ELEMENT */ && dirs;
5914 let vnodeHook;
5915 if ((vnodeHook = props && props.onVnodeBeforeUnmount)) {
5916 invokeVNodeHook(vnodeHook, parentComponent, vnode);
5917 }
5918 if (shapeFlag & 6 /* COMPONENT */) {
5919 unmountComponent(vnode.component, parentSuspense, doRemove);
5920 }
5921 else {
5922 if (shapeFlag & 128 /* SUSPENSE */) {
5923 vnode.suspense.unmount(parentSuspense, doRemove);
5924 return;
5925 }
5926 if (shouldInvokeDirs) {
5927 invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
5928 }
5929 if (shapeFlag & 64 /* TELEPORT */) {
5930 vnode.type.remove(vnode, parentComponent, parentSuspense, optimized, internals, doRemove);
5931 }
5932 else if (dynamicChildren &&
5933 // #1153: fast path should not be taken for non-stable (v-for) fragments
5934 (type !== Fragment ||
5935 (patchFlag > 0 && patchFlag & 64 /* STABLE_FRAGMENT */))) {
5936 // fast path for block nodes: only need to unmount dynamic children.
5937 unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
5938 }
5939 else if ((type === Fragment &&
5940 (patchFlag & 128 /* KEYED_FRAGMENT */ ||
5941 patchFlag & 256 /* UNKEYED_FRAGMENT */)) ||
5942 (!optimized && shapeFlag & 16 /* ARRAY_CHILDREN */)) {
5943 unmountChildren(children, parentComponent, parentSuspense);
5944 }
5945 if (doRemove) {
5946 remove(vnode);
5947 }
5948 }
5949 if ((vnodeHook = props && props.onVnodeUnmounted) || shouldInvokeDirs) {
5950 queuePostRenderEffect(() => {
5951 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
5952 shouldInvokeDirs &&
5953 invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
5954 }, parentSuspense);
5955 }
5956 };
5957 const remove = vnode => {
5958 const { type, el, anchor, transition } = vnode;
5959 if (type === Fragment) {
5960 removeFragment(el, anchor);
5961 return;
5962 }
5963 if (type === Static) {
5964 removeStaticNode(vnode);
5965 return;
5966 }
5967 const performRemove = () => {
5968 hostRemove(el);
5969 if (transition && !transition.persisted && transition.afterLeave) {
5970 transition.afterLeave();
5971 }
5972 };
5973 if (vnode.shapeFlag & 1 /* ELEMENT */ &&
5974 transition &&
5975 !transition.persisted) {
5976 const { leave, delayLeave } = transition;
5977 const performLeave = () => leave(el, performRemove);
5978 if (delayLeave) {
5979 delayLeave(vnode.el, performRemove, performLeave);
5980 }
5981 else {
5982 performLeave();
5983 }
5984 }
5985 else {
5986 performRemove();
5987 }
5988 };
5989 const removeFragment = (cur, end) => {
5990 // For fragments, directly remove all contained DOM nodes.
5991 // (fragment child nodes cannot have transition)
5992 let next;
5993 while (cur !== end) {
5994 next = hostNextSibling(cur);
5995 hostRemove(cur);
5996 cur = next;
5997 }
5998 hostRemove(end);
5999 };
6000 const unmountComponent = (instance, parentSuspense, doRemove) => {
6001 if (instance.type.__hmrId) {
6002 unregisterHMR(instance);
6003 }
6004 const { bum, effects, update, subTree, um } = instance;
6005 // beforeUnmount hook
6006 if (bum) {
6007 invokeArrayFns(bum);
6008 }
6009 if (effects) {
6010 for (let i = 0; i < effects.length; i++) {
6011 stop(effects[i]);
6012 }
6013 }
6014 // update may be null if a component is unmounted before its async
6015 // setup has resolved.
6016 if (update) {
6017 stop(update);
6018 unmount(subTree, instance, parentSuspense, doRemove);
6019 }
6020 // unmounted hook
6021 if (um) {
6022 queuePostRenderEffect(um, parentSuspense);
6023 }
6024 queuePostRenderEffect(() => {
6025 instance.isUnmounted = true;
6026 }, parentSuspense);
6027 // A component with async dep inside a pending suspense is unmounted before
6028 // its async dep resolves. This should remove the dep from the suspense, and
6029 // cause the suspense to resolve immediately if that was the last dep.
6030 if (parentSuspense &&
6031 parentSuspense.pendingBranch &&
6032 !parentSuspense.isUnmounted &&
6033 instance.asyncDep &&
6034 !instance.asyncResolved &&
6035 instance.suspenseId === parentSuspense.pendingId) {
6036 parentSuspense.deps--;
6037 if (parentSuspense.deps === 0) {
6038 parentSuspense.resolve();
6039 }
6040 }
6041 {
6042 devtoolsComponentRemoved(instance);
6043 }
6044 };
6045 const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
6046 for (let i = start; i < children.length; i++) {
6047 unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
6048 }
6049 };
6050 const getNextHostNode = vnode => {
6051 if (vnode.shapeFlag & 6 /* COMPONENT */) {
6052 return getNextHostNode(vnode.component.subTree);
6053 }
6054 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
6055 return vnode.suspense.next();
6056 }
6057 return hostNextSibling((vnode.anchor || vnode.el));
6058 };
6059 const render = (vnode, container, isSVG) => {
6060 if (vnode == null) {
6061 if (container._vnode) {
6062 unmount(container._vnode, null, null, true);
6063 }
6064 }
6065 else {
6066 patch(container._vnode || null, vnode, container, null, null, null, isSVG);
6067 }
6068 flushPostFlushCbs();
6069 container._vnode = vnode;
6070 };
6071 const internals = {
6072 p: patch,
6073 um: unmount,
6074 m: move,
6075 r: remove,
6076 mt: mountComponent,
6077 mc: mountChildren,
6078 pc: patchChildren,
6079 pbc: patchBlockChildren,
6080 n: getNextHostNode,
6081 o: options
6082 };
6083 let hydrate;
6084 let hydrateNode;
6085 if (createHydrationFns) {
6086 [hydrate, hydrateNode] = createHydrationFns(internals);
6087 }
6088 return {
6089 render,
6090 hydrate,
6091 createApp: createAppAPI(render, hydrate)
6092 };
6093}
6094function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
6095 callWithAsyncErrorHandling(hook, instance, 7 /* VNODE_HOOK */, [
6096 vnode,
6097 prevVNode
6098 ]);
6099}
6100/**
6101 * #1156
6102 * When a component is HMR-enabled, we need to make sure that all static nodes
6103 * inside a block also inherit the DOM element from the previous tree so that
6104 * HMR updates (which are full updates) can retrieve the element for patching.
6105 *
6106 * #2080
6107 * Inside keyed `template` fragment static children, if a fragment is moved,
6108 * the children will always moved so that need inherit el form previous nodes
6109 * to ensure correct moved position.
6110 */
6111function traverseStaticChildren(n1, n2, shallow = false) {
6112 const ch1 = n1.children;
6113 const ch2 = n2.children;
6114 if (isArray(ch1) && isArray(ch2)) {
6115 for (let i = 0; i < ch1.length; i++) {
6116 // this is only called in the optimized path so array children are
6117 // guaranteed to be vnodes
6118 const c1 = ch1[i];
6119 let c2 = ch2[i];
6120 if (c2.shapeFlag & 1 /* ELEMENT */ && !c2.dynamicChildren) {
6121 if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* HYDRATE_EVENTS */) {
6122 c2 = ch2[i] = cloneIfMounted(ch2[i]);
6123 c2.el = c1.el;
6124 }
6125 if (!shallow)
6126 traverseStaticChildren(c1, c2);
6127 }
6128 // also inherit for comment nodes, but not placeholders (e.g. v-if which
6129 // would have received .el during block patch)
6130 if (c2.type === Comment && !c2.el) {
6131 c2.el = c1.el;
6132 }
6133 }
6134 }
6135}
6136// https://en.wikipedia.org/wiki/Longest_increasing_subsequence
6137function getSequence(arr) {
6138 const p = arr.slice();
6139 const result = [0];
6140 let i, j, u, v, c;
6141 const len = arr.length;
6142 for (i = 0; i < len; i++) {
6143 const arrI = arr[i];
6144 if (arrI !== 0) {
6145 j = result[result.length - 1];
6146 if (arr[j] < arrI) {
6147 p[i] = j;
6148 result.push(i);
6149 continue;
6150 }
6151 u = 0;
6152 v = result.length - 1;
6153 while (u < v) {
6154 c = ((u + v) / 2) | 0;
6155 if (arr[result[c]] < arrI) {
6156 u = c + 1;
6157 }
6158 else {
6159 v = c;
6160 }
6161 }
6162 if (arrI < arr[result[u]]) {
6163 if (u > 0) {
6164 p[i] = result[u - 1];
6165 }
6166 result[u] = i;
6167 }
6168 }
6169 }
6170 u = result.length;
6171 v = result[u - 1];
6172 while (u-- > 0) {
6173 result[u] = v;
6174 v = p[v];
6175 }
6176 return result;
6177}
6178
6179const isTeleport = (type) => type.__isTeleport;
6180const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
6181const isTargetSVG = (target) => typeof SVGElement !== 'undefined' && target instanceof SVGElement;
6182const resolveTarget = (props, select) => {
6183 const targetSelector = props && props.to;
6184 if (isString(targetSelector)) {
6185 if (!select) {
6186 warn(`Current renderer does not support string target for Teleports. ` +
6187 `(missing querySelector renderer option)`);
6188 return null;
6189 }
6190 else {
6191 const target = select(targetSelector);
6192 if (!target) {
6193 warn(`Failed to locate Teleport target with selector "${targetSelector}". ` +
6194 `Note the target element must exist before the component is mounted - ` +
6195 `i.e. the target cannot be rendered by the component itself, and ` +
6196 `ideally should be outside of the entire Vue component tree.`);
6197 }
6198 return target;
6199 }
6200 }
6201 else {
6202 if (!targetSelector && !isTeleportDisabled(props)) {
6203 warn(`Invalid Teleport target: ${targetSelector}`);
6204 }
6205 return targetSelector;
6206 }
6207};
6208const TeleportImpl = {
6209 __isTeleport: true,
6210 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals) {
6211 const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
6212 const disabled = isTeleportDisabled(n2.props);
6213 const { shapeFlag, children } = n2;
6214 // #3302
6215 // HMR updated, force full diff
6216 if (isHmrUpdating) {
6217 optimized = false;
6218 n2.dynamicChildren = null;
6219 }
6220 if (n1 == null) {
6221 // insert anchors in the main view
6222 const placeholder = (n2.el = createComment('teleport start')
6223 );
6224 const mainAnchor = (n2.anchor = createComment('teleport end')
6225 );
6226 insert(placeholder, container, anchor);
6227 insert(mainAnchor, container, anchor);
6228 const target = (n2.target = resolveTarget(n2.props, querySelector));
6229 const targetAnchor = (n2.targetAnchor = createText(''));
6230 if (target) {
6231 insert(targetAnchor, target);
6232 // #2652 we could be teleporting from a non-SVG tree into an SVG tree
6233 isSVG = isSVG || isTargetSVG(target);
6234 }
6235 else if (!disabled) {
6236 warn('Invalid Teleport target on mount:', target, `(${typeof target})`);
6237 }
6238 const mount = (container, anchor) => {
6239 // Teleport *always* has Array children. This is enforced in both the
6240 // compiler and vnode children normalization.
6241 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6242 mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6243 }
6244 };
6245 if (disabled) {
6246 mount(container, mainAnchor);
6247 }
6248 else if (target) {
6249 mount(target, targetAnchor);
6250 }
6251 }
6252 else {
6253 // update content
6254 n2.el = n1.el;
6255 const mainAnchor = (n2.anchor = n1.anchor);
6256 const target = (n2.target = n1.target);
6257 const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
6258 const wasDisabled = isTeleportDisabled(n1.props);
6259 const currentContainer = wasDisabled ? container : target;
6260 const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
6261 isSVG = isSVG || isTargetSVG(target);
6262 if (n2.dynamicChildren) {
6263 // fast path when the teleport happens to be a block root
6264 patchBlockChildren(n1.dynamicChildren, n2.dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG, slotScopeIds);
6265 // even in block tree mode we need to make sure all root-level nodes
6266 // in the teleport inherit previous DOM references so that they can
6267 // be moved in future patches.
6268 traverseStaticChildren(n1, n2, true);
6269 }
6270 else if (!optimized) {
6271 patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, false);
6272 }
6273 if (disabled) {
6274 if (!wasDisabled) {
6275 // enabled -> disabled
6276 // move into main container
6277 moveTeleport(n2, container, mainAnchor, internals, 1 /* TOGGLE */);
6278 }
6279 }
6280 else {
6281 // target changed
6282 if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
6283 const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
6284 if (nextTarget) {
6285 moveTeleport(n2, nextTarget, null, internals, 0 /* TARGET_CHANGE */);
6286 }
6287 else {
6288 warn('Invalid Teleport target on update:', target, `(${typeof target})`);
6289 }
6290 }
6291 else if (wasDisabled) {
6292 // disabled -> enabled
6293 // move into teleport target
6294 moveTeleport(n2, target, targetAnchor, internals, 1 /* TOGGLE */);
6295 }
6296 }
6297 }
6298 },
6299 remove(vnode, parentComponent, parentSuspense, optimized, { um: unmount, o: { remove: hostRemove } }, doRemove) {
6300 const { shapeFlag, children, anchor, targetAnchor, target, props } = vnode;
6301 if (target) {
6302 hostRemove(targetAnchor);
6303 }
6304 // an unmounted teleport should always remove its children if not disabled
6305 if (doRemove || !isTeleportDisabled(props)) {
6306 hostRemove(anchor);
6307 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6308 for (let i = 0; i < children.length; i++) {
6309 unmount(children[i], parentComponent, parentSuspense, true, optimized);
6310 }
6311 }
6312 }
6313 },
6314 move: moveTeleport,
6315 hydrate: hydrateTeleport
6316};
6317function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* REORDER */) {
6318 // move target anchor if this is a target change.
6319 if (moveType === 0 /* TARGET_CHANGE */) {
6320 insert(vnode.targetAnchor, container, parentAnchor);
6321 }
6322 const { el, anchor, shapeFlag, children, props } = vnode;
6323 const isReorder = moveType === 2 /* REORDER */;
6324 // move main view anchor if this is a re-order.
6325 if (isReorder) {
6326 insert(el, container, parentAnchor);
6327 }
6328 // if this is a re-order and teleport is enabled (content is in target)
6329 // do not move children. So the opposite is: only move children if this
6330 // is not a reorder, or the teleport is disabled
6331 if (!isReorder || isTeleportDisabled(props)) {
6332 // Teleport has either Array children or no children.
6333 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6334 for (let i = 0; i < children.length; i++) {
6335 move(children[i], container, parentAnchor, 2 /* REORDER */);
6336 }
6337 }
6338 }
6339 // move main view anchor if this is a re-order.
6340 if (isReorder) {
6341 insert(anchor, container, parentAnchor);
6342 }
6343}
6344function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
6345 const target = (vnode.target = resolveTarget(vnode.props, querySelector));
6346 if (target) {
6347 // if multiple teleports rendered to the same target element, we need to
6348 // pick up from where the last teleport finished instead of the first node
6349 const targetNode = target._lpa || target.firstChild;
6350 if (vnode.shapeFlag & 16 /* ARRAY_CHILDREN */) {
6351 if (isTeleportDisabled(vnode.props)) {
6352 vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, slotScopeIds, optimized);
6353 vnode.targetAnchor = targetNode;
6354 }
6355 else {
6356 vnode.anchor = nextSibling(node);
6357 vnode.targetAnchor = hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, slotScopeIds, optimized);
6358 }
6359 target._lpa =
6360 vnode.targetAnchor && nextSibling(vnode.targetAnchor);
6361 }
6362 }
6363 return vnode.anchor && nextSibling(vnode.anchor);
6364}
6365// Force-casted public typing for h and TSX props inference
6366const Teleport = TeleportImpl;
6367
6368const COMPONENTS = 'components';
6369const DIRECTIVES = 'directives';
6370/**
6371 * @private
6372 */
6373function resolveComponent(name, maybeSelfReference) {
6374 return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name;
6375}
6376const NULL_DYNAMIC_COMPONENT = Symbol();
6377/**
6378 * @private
6379 */
6380function resolveDynamicComponent(component) {
6381 if (isString(component)) {
6382 return resolveAsset(COMPONENTS, component, false) || component;
6383 }
6384 else {
6385 // invalid types will fallthrough to createVNode and raise warning
6386 return (component || NULL_DYNAMIC_COMPONENT);
6387 }
6388}
6389/**
6390 * @private
6391 */
6392function resolveDirective(name) {
6393 return resolveAsset(DIRECTIVES, name);
6394}
6395// implementation
6396function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {
6397 const instance = currentRenderingInstance || currentInstance;
6398 if (instance) {
6399 const Component = instance.type;
6400 // explicit self name has highest priority
6401 if (type === COMPONENTS) {
6402 const selfName = getComponentName(Component);
6403 if (selfName &&
6404 (selfName === name ||
6405 selfName === camelize(name) ||
6406 selfName === capitalize(camelize(name)))) {
6407 return Component;
6408 }
6409 }
6410 const res =
6411 // local registration
6412 // check instance[type] first for components with mixin or extends.
6413 resolve(instance[type] || Component[type], name) ||
6414 // global registration
6415 resolve(instance.appContext[type], name);
6416 if (!res && maybeSelfReference) {
6417 // fallback to implicit self-reference
6418 return Component;
6419 }
6420 if (warnMissing && !res) {
6421 warn(`Failed to resolve ${type.slice(0, -1)}: ${name}`);
6422 }
6423 return res;
6424 }
6425 else {
6426 warn(`resolve${capitalize(type.slice(0, -1))} ` +
6427 `can only be used in render() or setup().`);
6428 }
6429}
6430function resolve(registry, name) {
6431 return (registry &&
6432 (registry[name] ||
6433 registry[camelize(name)] ||
6434 registry[capitalize(camelize(name))]));
6435}
6436
6437const Fragment = Symbol('Fragment' );
6438const Text = Symbol('Text' );
6439const Comment = Symbol('Comment' );
6440const Static = Symbol('Static' );
6441// Since v-if and v-for are the two possible ways node structure can dynamically
6442// change, once we consider v-if branches and each v-for fragment a block, we
6443// can divide a template into nested blocks, and within each block the node
6444// structure would be stable. This allows us to skip most children diffing
6445// and only worry about the dynamic nodes (indicated by patch flags).
6446const blockStack = [];
6447let currentBlock = null;
6448/**
6449 * Open a block.
6450 * This must be called before `createBlock`. It cannot be part of `createBlock`
6451 * because the children of the block are evaluated before `createBlock` itself
6452 * is called. The generated code typically looks like this:
6453 *
6454 * ```js
6455 * function render() {
6456 * return (openBlock(),createBlock('div', null, [...]))
6457 * }
6458 * ```
6459 * disableTracking is true when creating a v-for fragment block, since a v-for
6460 * fragment always diffs its children.
6461 *
6462 * @private
6463 */
6464function openBlock(disableTracking = false) {
6465 blockStack.push((currentBlock = disableTracking ? null : []));
6466}
6467function closeBlock() {
6468 blockStack.pop();
6469 currentBlock = blockStack[blockStack.length - 1] || null;
6470}
6471// Whether we should be tracking dynamic child nodes inside a block.
6472// Only tracks when this value is > 0
6473// We are not using a simple boolean because this value may need to be
6474// incremented/decremented by nested usage of v-once (see below)
6475let shouldTrack$1 = 1;
6476/**
6477 * Block tracking sometimes needs to be disabled, for example during the
6478 * creation of a tree that needs to be cached by v-once. The compiler generates
6479 * code like this:
6480 *
6481 * ``` js
6482 * _cache[1] || (
6483 * setBlockTracking(-1),
6484 * _cache[1] = createVNode(...),
6485 * setBlockTracking(1),
6486 * _cache[1]
6487 * )
6488 * ```
6489 *
6490 * @private
6491 */
6492function setBlockTracking(value) {
6493 shouldTrack$1 += value;
6494}
6495/**
6496 * Create a block root vnode. Takes the same exact arguments as `createVNode`.
6497 * A block root keeps track of dynamic nodes within the block in the
6498 * `dynamicChildren` array.
6499 *
6500 * @private
6501 */
6502function createBlock(type, props, children, patchFlag, dynamicProps) {
6503 const vnode = createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */);
6504 // save current block children on the block vnode
6505 vnode.dynamicChildren = currentBlock || EMPTY_ARR;
6506 // close block
6507 closeBlock();
6508 // a block is always going to be patched, so track it as a child of its
6509 // parent block
6510 if (shouldTrack$1 > 0 && currentBlock) {
6511 currentBlock.push(vnode);
6512 }
6513 return vnode;
6514}
6515function isVNode(value) {
6516 return value ? value.__v_isVNode === true : false;
6517}
6518function isSameVNodeType(n1, n2) {
6519 if (n2.shapeFlag & 6 /* COMPONENT */ &&
6520 hmrDirtyComponents.has(n2.type)) {
6521 // HMR only: if the component has been hot-updated, force a reload.
6522 return false;
6523 }
6524 return n1.type === n2.type && n1.key === n2.key;
6525}
6526let vnodeArgsTransformer;
6527/**
6528 * Internal API for registering an arguments transform for createVNode
6529 * used for creating stubs in the test-utils
6530 * It is *internal* but needs to be exposed for test-utils to pick up proper
6531 * typings
6532 */
6533function transformVNodeArgs(transformer) {
6534 vnodeArgsTransformer = transformer;
6535}
6536const createVNodeWithArgsTransform = (...args) => {
6537 return _createVNode(...(vnodeArgsTransformer
6538 ? vnodeArgsTransformer(args, currentRenderingInstance)
6539 : args));
6540};
6541const InternalObjectKey = `__vInternal`;
6542const normalizeKey = ({ key }) => key != null ? key : null;
6543const normalizeRef = ({ ref }) => {
6544 return (ref != null
6545 ? isString(ref) || isRef(ref) || isFunction(ref)
6546 ? { i: currentRenderingInstance, r: ref }
6547 : ref
6548 : null);
6549};
6550const createVNode = (createVNodeWithArgsTransform
6551 );
6552function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
6553 if (!type || type === NULL_DYNAMIC_COMPONENT) {
6554 if (!type) {
6555 warn(`Invalid vnode type when creating vnode: ${type}.`);
6556 }
6557 type = Comment;
6558 }
6559 if (isVNode(type)) {
6560 // createVNode receiving an existing vnode. This happens in cases like
6561 // <component :is="vnode"/>
6562 // #2078 make sure to merge refs during the clone instead of overwriting it
6563 const cloned = cloneVNode(type, props, true /* mergeRef: true */);
6564 if (children) {
6565 normalizeChildren(cloned, children);
6566 }
6567 return cloned;
6568 }
6569 // class component normalization.
6570 if (isClassComponent(type)) {
6571 type = type.__vccOpts;
6572 }
6573 // class & style normalization.
6574 if (props) {
6575 // for reactive or proxy objects, we need to clone it to enable mutation.
6576 if (isProxy(props) || InternalObjectKey in props) {
6577 props = extend({}, props);
6578 }
6579 let { class: klass, style } = props;
6580 if (klass && !isString(klass)) {
6581 props.class = normalizeClass(klass);
6582 }
6583 if (isObject(style)) {
6584 // reactive state objects need to be cloned since they are likely to be
6585 // mutated
6586 if (isProxy(style) && !isArray(style)) {
6587 style = extend({}, style);
6588 }
6589 props.style = normalizeStyle(style);
6590 }
6591 }
6592 // encode the vnode type information into a bitmap
6593 const shapeFlag = isString(type)
6594 ? 1 /* ELEMENT */
6595 : isSuspense(type)
6596 ? 128 /* SUSPENSE */
6597 : isTeleport(type)
6598 ? 64 /* TELEPORT */
6599 : isObject(type)
6600 ? 4 /* STATEFUL_COMPONENT */
6601 : isFunction(type)
6602 ? 2 /* FUNCTIONAL_COMPONENT */
6603 : 0;
6604 if (shapeFlag & 4 /* STATEFUL_COMPONENT */ && isProxy(type)) {
6605 type = toRaw(type);
6606 warn(`Vue received a Component which was made a reactive object. This can ` +
6607 `lead to unnecessary performance overhead, and should be avoided by ` +
6608 `marking the component with \`markRaw\` or using \`shallowRef\` ` +
6609 `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
6610 }
6611 const vnode = {
6612 __v_isVNode: true,
6613 ["__v_skip" /* SKIP */]: true,
6614 type,
6615 props,
6616 key: props && normalizeKey(props),
6617 ref: props && normalizeRef(props),
6618 scopeId: currentScopeId,
6619 slotScopeIds: null,
6620 children: null,
6621 component: null,
6622 suspense: null,
6623 ssContent: null,
6624 ssFallback: null,
6625 dirs: null,
6626 transition: null,
6627 el: null,
6628 anchor: null,
6629 target: null,
6630 targetAnchor: null,
6631 staticCount: 0,
6632 shapeFlag,
6633 patchFlag,
6634 dynamicProps,
6635 dynamicChildren: null,
6636 appContext: null
6637 };
6638 // validate key
6639 if (vnode.key !== vnode.key) {
6640 warn(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
6641 }
6642 normalizeChildren(vnode, children);
6643 // normalize suspense children
6644 if (shapeFlag & 128 /* SUSPENSE */) {
6645 const { content, fallback } = normalizeSuspenseChildren(vnode);
6646 vnode.ssContent = content;
6647 vnode.ssFallback = fallback;
6648 }
6649 if (shouldTrack$1 > 0 &&
6650 // avoid a block node from tracking itself
6651 !isBlockNode &&
6652 // has current parent block
6653 currentBlock &&
6654 // presence of a patch flag indicates this node needs patching on updates.
6655 // component nodes also should always be patched, because even if the
6656 // component doesn't need to update, it needs to persist the instance on to
6657 // the next vnode so that it can be properly unmounted later.
6658 (patchFlag > 0 || shapeFlag & 6 /* COMPONENT */) &&
6659 // the EVENTS flag is only for hydration and if it is the only flag, the
6660 // vnode should not be considered dynamic due to handler caching.
6661 patchFlag !== 32 /* HYDRATE_EVENTS */) {
6662 currentBlock.push(vnode);
6663 }
6664 return vnode;
6665}
6666function cloneVNode(vnode, extraProps, mergeRef = false) {
6667 // This is intentionally NOT using spread or extend to avoid the runtime
6668 // key enumeration cost.
6669 const { props, ref, patchFlag, children } = vnode;
6670 const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
6671 return {
6672 __v_isVNode: true,
6673 ["__v_skip" /* SKIP */]: true,
6674 type: vnode.type,
6675 props: mergedProps,
6676 key: mergedProps && normalizeKey(mergedProps),
6677 ref: extraProps && extraProps.ref
6678 ? // #2078 in the case of <component :is="vnode" ref="extra"/>
6679 // if the vnode itself already has a ref, cloneVNode will need to merge
6680 // the refs so the single vnode can be set on multiple refs
6681 mergeRef && ref
6682 ? isArray(ref)
6683 ? ref.concat(normalizeRef(extraProps))
6684 : [ref, normalizeRef(extraProps)]
6685 : normalizeRef(extraProps)
6686 : ref,
6687 scopeId: vnode.scopeId,
6688 slotScopeIds: vnode.slotScopeIds,
6689 children: patchFlag === -1 /* HOISTED */ && isArray(children)
6690 ? children.map(deepCloneVNode)
6691 : children,
6692 target: vnode.target,
6693 targetAnchor: vnode.targetAnchor,
6694 staticCount: vnode.staticCount,
6695 shapeFlag: vnode.shapeFlag,
6696 // if the vnode is cloned with extra props, we can no longer assume its
6697 // existing patch flag to be reliable and need to add the FULL_PROPS flag.
6698 // note: perserve flag for fragments since they use the flag for children
6699 // fast paths only.
6700 patchFlag: extraProps && vnode.type !== Fragment
6701 ? patchFlag === -1 // hoisted node
6702 ? 16 /* FULL_PROPS */
6703 : patchFlag | 16 /* FULL_PROPS */
6704 : patchFlag,
6705 dynamicProps: vnode.dynamicProps,
6706 dynamicChildren: vnode.dynamicChildren,
6707 appContext: vnode.appContext,
6708 dirs: vnode.dirs,
6709 transition: vnode.transition,
6710 // These should technically only be non-null on mounted VNodes. However,
6711 // they *should* be copied for kept-alive vnodes. So we just always copy
6712 // them since them being non-null during a mount doesn't affect the logic as
6713 // they will simply be overwritten.
6714 component: vnode.component,
6715 suspense: vnode.suspense,
6716 ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
6717 ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
6718 el: vnode.el,
6719 anchor: vnode.anchor
6720 };
6721}
6722/**
6723 * Dev only, for HMR of hoisted vnodes reused in v-for
6724 * https://github.com/vitejs/vite/issues/2022
6725 */
6726function deepCloneVNode(vnode) {
6727 const cloned = cloneVNode(vnode);
6728 if (isArray(vnode.children)) {
6729 cloned.children = vnode.children.map(deepCloneVNode);
6730 }
6731 return cloned;
6732}
6733/**
6734 * @private
6735 */
6736function createTextVNode(text = ' ', flag = 0) {
6737 return createVNode(Text, null, text, flag);
6738}
6739/**
6740 * @private
6741 */
6742function createStaticVNode(content, numberOfNodes) {
6743 // A static vnode can contain multiple stringified elements, and the number
6744 // of elements is necessary for hydration.
6745 const vnode = createVNode(Static, null, content);
6746 vnode.staticCount = numberOfNodes;
6747 return vnode;
6748}
6749/**
6750 * @private
6751 */
6752function createCommentVNode(text = '',
6753// when used as the v-else branch, the comment node must be created as a
6754// block to ensure correct updates.
6755asBlock = false) {
6756 return asBlock
6757 ? (openBlock(), createBlock(Comment, null, text))
6758 : createVNode(Comment, null, text);
6759}
6760function normalizeVNode(child) {
6761 if (child == null || typeof child === 'boolean') {
6762 // empty placeholder
6763 return createVNode(Comment);
6764 }
6765 else if (isArray(child)) {
6766 // fragment
6767 return createVNode(Fragment, null, child);
6768 }
6769 else if (typeof child === 'object') {
6770 // already vnode, this should be the most common since compiled templates
6771 // always produce all-vnode children arrays
6772 return child.el === null ? child : cloneVNode(child);
6773 }
6774 else {
6775 // strings and numbers
6776 return createVNode(Text, null, String(child));
6777 }
6778}
6779// optimized normalization for template-compiled render fns
6780function cloneIfMounted(child) {
6781 return child.el === null ? child : cloneVNode(child);
6782}
6783function normalizeChildren(vnode, children) {
6784 let type = 0;
6785 const { shapeFlag } = vnode;
6786 if (children == null) {
6787 children = null;
6788 }
6789 else if (isArray(children)) {
6790 type = 16 /* ARRAY_CHILDREN */;
6791 }
6792 else if (typeof children === 'object') {
6793 if (shapeFlag & 1 /* ELEMENT */ || shapeFlag & 64 /* TELEPORT */) {
6794 // Normalize slot to plain children for plain element and Teleport
6795 const slot = children.default;
6796 if (slot) {
6797 // _c marker is added by withCtx() indicating this is a compiled slot
6798 slot._c && setCompiledSlotRendering(1);
6799 normalizeChildren(vnode, slot());
6800 slot._c && setCompiledSlotRendering(-1);
6801 }
6802 return;
6803 }
6804 else {
6805 type = 32 /* SLOTS_CHILDREN */;
6806 const slotFlag = children._;
6807 if (!slotFlag && !(InternalObjectKey in children)) {
6808 children._ctx = currentRenderingInstance;
6809 }
6810 else if (slotFlag === 3 /* FORWARDED */ && currentRenderingInstance) {
6811 // a child component receives forwarded slots from the parent.
6812 // its slot type is determined by its parent's slot type.
6813 if (currentRenderingInstance.vnode.patchFlag & 1024 /* DYNAMIC_SLOTS */) {
6814 children._ = 2 /* DYNAMIC */;
6815 vnode.patchFlag |= 1024 /* DYNAMIC_SLOTS */;
6816 }
6817 else {
6818 children._ = 1 /* STABLE */;
6819 }
6820 }
6821 }
6822 }
6823 else if (isFunction(children)) {
6824 children = { default: children, _ctx: currentRenderingInstance };
6825 type = 32 /* SLOTS_CHILDREN */;
6826 }
6827 else {
6828 children = String(children);
6829 // force teleport children to array so it can be moved around
6830 if (shapeFlag & 64 /* TELEPORT */) {
6831 type = 16 /* ARRAY_CHILDREN */;
6832 children = [createTextVNode(children)];
6833 }
6834 else {
6835 type = 8 /* TEXT_CHILDREN */;
6836 }
6837 }
6838 vnode.children = children;
6839 vnode.shapeFlag |= type;
6840}
6841function mergeProps(...args) {
6842 const ret = extend({}, args[0]);
6843 for (let i = 1; i < args.length; i++) {
6844 const toMerge = args[i];
6845 for (const key in toMerge) {
6846 if (key === 'class') {
6847 if (ret.class !== toMerge.class) {
6848 ret.class = normalizeClass([ret.class, toMerge.class]);
6849 }
6850 }
6851 else if (key === 'style') {
6852 ret.style = normalizeStyle([ret.style, toMerge.style]);
6853 }
6854 else if (isOn(key)) {
6855 const existing = ret[key];
6856 const incoming = toMerge[key];
6857 if (existing !== incoming) {
6858 ret[key] = existing
6859 ? [].concat(existing, toMerge[key])
6860 : incoming;
6861 }
6862 }
6863 else if (key !== '') {
6864 ret[key] = toMerge[key];
6865 }
6866 }
6867 }
6868 return ret;
6869}
6870
6871function provide(key, value) {
6872 if (!currentInstance) {
6873 {
6874 warn(`provide() can only be used inside setup().`);
6875 }
6876 }
6877 else {
6878 let provides = currentInstance.provides;
6879 // by default an instance inherits its parent's provides object
6880 // but when it needs to provide values of its own, it creates its
6881 // own provides object using parent provides object as prototype.
6882 // this way in `inject` we can simply look up injections from direct
6883 // parent and let the prototype chain do the work.
6884 const parentProvides = currentInstance.parent && currentInstance.parent.provides;
6885 if (parentProvides === provides) {
6886 provides = currentInstance.provides = Object.create(parentProvides);
6887 }
6888 // TS doesn't allow symbol as index type
6889 provides[key] = value;
6890 }
6891}
6892function inject(key, defaultValue, treatDefaultAsFactory = false) {
6893 // fallback to `currentRenderingInstance` so that this can be called in
6894 // a functional component
6895 const instance = currentInstance || currentRenderingInstance;
6896 if (instance) {
6897 // #2400
6898 // to support `app.use` plugins,
6899 // fallback to appContext's `provides` if the intance is at root
6900 const provides = instance.parent == null
6901 ? instance.vnode.appContext && instance.vnode.appContext.provides
6902 : instance.parent.provides;
6903 if (provides && key in provides) {
6904 // TS doesn't allow symbol as index type
6905 return provides[key];
6906 }
6907 else if (arguments.length > 1) {
6908 return treatDefaultAsFactory && isFunction(defaultValue)
6909 ? defaultValue()
6910 : defaultValue;
6911 }
6912 else {
6913 warn(`injection "${String(key)}" not found.`);
6914 }
6915 }
6916 else {
6917 warn(`inject() can only be used inside setup() or functional components.`);
6918 }
6919}
6920
6921function createDuplicateChecker() {
6922 const cache = Object.create(null);
6923 return (type, key) => {
6924 if (cache[key]) {
6925 warn(`${type} property "${key}" is already defined in ${cache[key]}.`);
6926 }
6927 else {
6928 cache[key] = type;
6929 }
6930 };
6931}
6932let shouldCacheAccess = true;
6933function applyOptions(instance, options, deferredData = [], deferredWatch = [], deferredProvide = [], asMixin = false) {
6934 const {
6935 // composition
6936 mixins, extends: extendsOptions,
6937 // state
6938 data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
6939 // assets
6940 components, directives,
6941 // lifecycle
6942 beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured,
6943 // public API
6944 expose } = options;
6945 const publicThis = instance.proxy;
6946 const ctx = instance.ctx;
6947 const globalMixins = instance.appContext.mixins;
6948 if (asMixin && render && instance.render === NOOP) {
6949 instance.render = render;
6950 }
6951 // applyOptions is called non-as-mixin once per instance
6952 if (!asMixin) {
6953 shouldCacheAccess = false;
6954 callSyncHook('beforeCreate', "bc" /* BEFORE_CREATE */, options, instance, globalMixins);
6955 shouldCacheAccess = true;
6956 // global mixins are applied first
6957 applyMixins(instance, globalMixins, deferredData, deferredWatch, deferredProvide);
6958 }
6959 // extending a base component...
6960 if (extendsOptions) {
6961 applyOptions(instance, extendsOptions, deferredData, deferredWatch, deferredProvide, true);
6962 }
6963 // local mixins
6964 if (mixins) {
6965 applyMixins(instance, mixins, deferredData, deferredWatch, deferredProvide);
6966 }
6967 const checkDuplicateProperties = createDuplicateChecker() ;
6968 {
6969 const [propsOptions] = instance.propsOptions;
6970 if (propsOptions) {
6971 for (const key in propsOptions) {
6972 checkDuplicateProperties("Props" /* PROPS */, key);
6973 }
6974 }
6975 }
6976 // options initialization order (to be consistent with Vue 2):
6977 // - props (already done outside of this function)
6978 // - inject
6979 // - methods
6980 // - data (deferred since it relies on `this` access)
6981 // - computed
6982 // - watch (deferred since it relies on `this` access)
6983 if (injectOptions) {
6984 if (isArray(injectOptions)) {
6985 for (let i = 0; i < injectOptions.length; i++) {
6986 const key = injectOptions[i];
6987 ctx[key] = inject(key);
6988 {
6989 checkDuplicateProperties("Inject" /* INJECT */, key);
6990 }
6991 }
6992 }
6993 else {
6994 for (const key in injectOptions) {
6995 const opt = injectOptions[key];
6996 if (isObject(opt)) {
6997 ctx[key] = inject(opt.from || key, opt.default, true /* treat default function as factory */);
6998 }
6999 else {
7000 ctx[key] = inject(opt);
7001 }
7002 {
7003 checkDuplicateProperties("Inject" /* INJECT */, key);
7004 }
7005 }
7006 }
7007 }
7008 if (methods) {
7009 for (const key in methods) {
7010 const methodHandler = methods[key];
7011 if (isFunction(methodHandler)) {
7012 // In dev mode, we use the `createRenderContext` function to define methods to the proxy target,
7013 // and those are read-only but reconfigurable, so it needs to be redefined here
7014 {
7015 Object.defineProperty(ctx, key, {
7016 value: methodHandler.bind(publicThis),
7017 configurable: true,
7018 enumerable: true,
7019 writable: true
7020 });
7021 }
7022 {
7023 checkDuplicateProperties("Methods" /* METHODS */, key);
7024 }
7025 }
7026 else {
7027 warn(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
7028 `Did you reference the function correctly?`);
7029 }
7030 }
7031 }
7032 if (!asMixin) {
7033 if (deferredData.length) {
7034 deferredData.forEach(dataFn => resolveData(instance, dataFn, publicThis));
7035 }
7036 if (dataOptions) {
7037 // @ts-ignore dataOptions is not fully type safe
7038 resolveData(instance, dataOptions, publicThis);
7039 }
7040 {
7041 const rawData = toRaw(instance.data);
7042 for (const key in rawData) {
7043 checkDuplicateProperties("Data" /* DATA */, key);
7044 // expose data on ctx during dev
7045 if (key[0] !== '$' && key[0] !== '_') {
7046 Object.defineProperty(ctx, key, {
7047 configurable: true,
7048 enumerable: true,
7049 get: () => rawData[key],
7050 set: NOOP
7051 });
7052 }
7053 }
7054 }
7055 }
7056 else if (dataOptions) {
7057 deferredData.push(dataOptions);
7058 }
7059 if (computedOptions) {
7060 for (const key in computedOptions) {
7061 const opt = computedOptions[key];
7062 const get = isFunction(opt)
7063 ? opt.bind(publicThis, publicThis)
7064 : isFunction(opt.get)
7065 ? opt.get.bind(publicThis, publicThis)
7066 : NOOP;
7067 if (get === NOOP) {
7068 warn(`Computed property "${key}" has no getter.`);
7069 }
7070 const set = !isFunction(opt) && isFunction(opt.set)
7071 ? opt.set.bind(publicThis)
7072 : () => {
7073 warn(`Write operation failed: computed property "${key}" is readonly.`);
7074 }
7075 ;
7076 const c = computed$1({
7077 get,
7078 set
7079 });
7080 Object.defineProperty(ctx, key, {
7081 enumerable: true,
7082 configurable: true,
7083 get: () => c.value,
7084 set: v => (c.value = v)
7085 });
7086 {
7087 checkDuplicateProperties("Computed" /* COMPUTED */, key);
7088 }
7089 }
7090 }
7091 if (watchOptions) {
7092 deferredWatch.push(watchOptions);
7093 }
7094 if (!asMixin && deferredWatch.length) {
7095 deferredWatch.forEach(watchOptions => {
7096 for (const key in watchOptions) {
7097 createWatcher(watchOptions[key], ctx, publicThis, key);
7098 }
7099 });
7100 }
7101 if (provideOptions) {
7102 deferredProvide.push(provideOptions);
7103 }
7104 if (!asMixin && deferredProvide.length) {
7105 deferredProvide.forEach(provideOptions => {
7106 const provides = isFunction(provideOptions)
7107 ? provideOptions.call(publicThis)
7108 : provideOptions;
7109 Reflect.ownKeys(provides).forEach(key => {
7110 provide(key, provides[key]);
7111 });
7112 });
7113 }
7114 // asset options.
7115 // To reduce memory usage, only components with mixins or extends will have
7116 // resolved asset registry attached to instance.
7117 if (asMixin) {
7118 if (components) {
7119 extend(instance.components ||
7120 (instance.components = extend({}, instance.type.components)), components);
7121 }
7122 if (directives) {
7123 extend(instance.directives ||
7124 (instance.directives = extend({}, instance.type.directives)), directives);
7125 }
7126 }
7127 // lifecycle options
7128 if (!asMixin) {
7129 callSyncHook('created', "c" /* CREATED */, options, instance, globalMixins);
7130 }
7131 if (beforeMount) {
7132 onBeforeMount(beforeMount.bind(publicThis));
7133 }
7134 if (mounted) {
7135 onMounted(mounted.bind(publicThis));
7136 }
7137 if (beforeUpdate) {
7138 onBeforeUpdate(beforeUpdate.bind(publicThis));
7139 }
7140 if (updated) {
7141 onUpdated(updated.bind(publicThis));
7142 }
7143 if (activated) {
7144 onActivated(activated.bind(publicThis));
7145 }
7146 if (deactivated) {
7147 onDeactivated(deactivated.bind(publicThis));
7148 }
7149 if (errorCaptured) {
7150 onErrorCaptured(errorCaptured.bind(publicThis));
7151 }
7152 if (renderTracked) {
7153 onRenderTracked(renderTracked.bind(publicThis));
7154 }
7155 if (renderTriggered) {
7156 onRenderTriggered(renderTriggered.bind(publicThis));
7157 }
7158 if (beforeDestroy) {
7159 warn(`\`beforeDestroy\` has been renamed to \`beforeUnmount\`.`);
7160 }
7161 if (beforeUnmount) {
7162 onBeforeUnmount(beforeUnmount.bind(publicThis));
7163 }
7164 if (destroyed) {
7165 warn(`\`destroyed\` has been renamed to \`unmounted\`.`);
7166 }
7167 if (unmounted) {
7168 onUnmounted(unmounted.bind(publicThis));
7169 }
7170 if (isArray(expose)) {
7171 if (!asMixin) {
7172 if (expose.length) {
7173 const exposed = instance.exposed || (instance.exposed = proxyRefs({}));
7174 expose.forEach(key => {
7175 exposed[key] = toRef(publicThis, key);
7176 });
7177 }
7178 else if (!instance.exposed) {
7179 instance.exposed = EMPTY_OBJ;
7180 }
7181 }
7182 else {
7183 warn(`The \`expose\` option is ignored when used in mixins.`);
7184 }
7185 }
7186}
7187function callSyncHook(name, type, options, instance, globalMixins) {
7188 for (let i = 0; i < globalMixins.length; i++) {
7189 callHookWithMixinAndExtends(name, type, globalMixins[i], instance);
7190 }
7191 callHookWithMixinAndExtends(name, type, options, instance);
7192}
7193function callHookWithMixinAndExtends(name, type, options, instance) {
7194 const { extends: base, mixins } = options;
7195 const selfHook = options[name];
7196 if (base) {
7197 callHookWithMixinAndExtends(name, type, base, instance);
7198 }
7199 if (mixins) {
7200 for (let i = 0; i < mixins.length; i++) {
7201 callHookWithMixinAndExtends(name, type, mixins[i], instance);
7202 }
7203 }
7204 if (selfHook) {
7205 callWithAsyncErrorHandling(selfHook.bind(instance.proxy), instance, type);
7206 }
7207}
7208function applyMixins(instance, mixins, deferredData, deferredWatch, deferredProvide) {
7209 for (let i = 0; i < mixins.length; i++) {
7210 applyOptions(instance, mixins[i], deferredData, deferredWatch, deferredProvide, true);
7211 }
7212}
7213function resolveData(instance, dataFn, publicThis) {
7214 if (!isFunction(dataFn)) {
7215 warn(`The data option must be a function. ` +
7216 `Plain object usage is no longer supported.`);
7217 }
7218 shouldCacheAccess = false;
7219 const data = dataFn.call(publicThis, publicThis);
7220 shouldCacheAccess = true;
7221 if (isPromise(data)) {
7222 warn(`data() returned a Promise - note data() cannot be async; If you ` +
7223 `intend to perform data fetching before component renders, use ` +
7224 `async setup() + <Suspense>.`);
7225 }
7226 if (!isObject(data)) {
7227 warn(`data() should return an object.`);
7228 }
7229 else if (instance.data === EMPTY_OBJ) {
7230 instance.data = reactive(data);
7231 }
7232 else {
7233 // existing data: this is a mixin or extends.
7234 extend(instance.data, data);
7235 }
7236}
7237function createWatcher(raw, ctx, publicThis, key) {
7238 const getter = key.includes('.')
7239 ? createPathGetter(publicThis, key)
7240 : () => publicThis[key];
7241 if (isString(raw)) {
7242 const handler = ctx[raw];
7243 if (isFunction(handler)) {
7244 watch(getter, handler);
7245 }
7246 else {
7247 warn(`Invalid watch handler specified by key "${raw}"`, handler);
7248 }
7249 }
7250 else if (isFunction(raw)) {
7251 watch(getter, raw.bind(publicThis));
7252 }
7253 else if (isObject(raw)) {
7254 if (isArray(raw)) {
7255 raw.forEach(r => createWatcher(r, ctx, publicThis, key));
7256 }
7257 else {
7258 const handler = isFunction(raw.handler)
7259 ? raw.handler.bind(publicThis)
7260 : ctx[raw.handler];
7261 if (isFunction(handler)) {
7262 watch(getter, handler, raw);
7263 }
7264 else {
7265 warn(`Invalid watch handler specified by key "${raw.handler}"`, handler);
7266 }
7267 }
7268 }
7269 else {
7270 warn(`Invalid watch option: "${key}"`, raw);
7271 }
7272}
7273function createPathGetter(ctx, path) {
7274 const segments = path.split('.');
7275 return () => {
7276 let cur = ctx;
7277 for (let i = 0; i < segments.length && cur; i++) {
7278 cur = cur[segments[i]];
7279 }
7280 return cur;
7281 };
7282}
7283function resolveMergedOptions(instance) {
7284 const raw = instance.type;
7285 const { __merged, mixins, extends: extendsOptions } = raw;
7286 if (__merged)
7287 return __merged;
7288 const globalMixins = instance.appContext.mixins;
7289 if (!globalMixins.length && !mixins && !extendsOptions)
7290 return raw;
7291 const options = {};
7292 globalMixins.forEach(m => mergeOptions(options, m, instance));
7293 mergeOptions(options, raw, instance);
7294 return (raw.__merged = options);
7295}
7296function mergeOptions(to, from, instance) {
7297 const strats = instance.appContext.config.optionMergeStrategies;
7298 const { mixins, extends: extendsOptions } = from;
7299 extendsOptions && mergeOptions(to, extendsOptions, instance);
7300 mixins &&
7301 mixins.forEach((m) => mergeOptions(to, m, instance));
7302 for (const key in from) {
7303 if (strats && hasOwn(strats, key)) {
7304 to[key] = strats[key](to[key], from[key], instance.proxy, key);
7305 }
7306 else {
7307 to[key] = from[key];
7308 }
7309 }
7310}
7311
7312/**
7313 * #2437 In Vue 3, functional components do not have a public instance proxy but
7314 * they exist in the internal parent chain. For code that relies on traversing
7315 * public $parent chains, skip functional ones and go to the parent instead.
7316 */
7317const getPublicInstance = (i) => {
7318 if (!i)
7319 return null;
7320 if (isStatefulComponent(i))
7321 return i.exposed ? i.exposed : i.proxy;
7322 return getPublicInstance(i.parent);
7323};
7324const publicPropertiesMap = extend(Object.create(null), {
7325 $: i => i,
7326 $el: i => i.vnode.el,
7327 $data: i => i.data,
7328 $props: i => (shallowReadonly(i.props) ),
7329 $attrs: i => (shallowReadonly(i.attrs) ),
7330 $slots: i => (shallowReadonly(i.slots) ),
7331 $refs: i => (shallowReadonly(i.refs) ),
7332 $parent: i => getPublicInstance(i.parent),
7333 $root: i => getPublicInstance(i.root),
7334 $emit: i => i.emit,
7335 $options: i => (resolveMergedOptions(i) ),
7336 $forceUpdate: i => () => queueJob(i.update),
7337 $nextTick: i => nextTick.bind(i.proxy),
7338 $watch: i => (instanceWatch.bind(i) )
7339});
7340const PublicInstanceProxyHandlers = {
7341 get({ _: instance }, key) {
7342 const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
7343 // let @vue/reactivity know it should never observe Vue public instances.
7344 if (key === "__v_skip" /* SKIP */) {
7345 return true;
7346 }
7347 // for internal formatters to know that this is a Vue instance
7348 if (key === '__isVue') {
7349 return true;
7350 }
7351 // data / props / ctx
7352 // This getter gets called for every property access on the render context
7353 // during render and is a major hotspot. The most expensive part of this
7354 // is the multiple hasOwn() calls. It's much faster to do a simple property
7355 // access on a plain object, so we use an accessCache object (with null
7356 // prototype) to memoize what access type a key corresponds to.
7357 let normalizedProps;
7358 if (key[0] !== '$') {
7359 const n = accessCache[key];
7360 if (n !== undefined) {
7361 switch (n) {
7362 case 0 /* SETUP */:
7363 return setupState[key];
7364 case 1 /* DATA */:
7365 return data[key];
7366 case 3 /* CONTEXT */:
7367 return ctx[key];
7368 case 2 /* PROPS */:
7369 return props[key];
7370 // default: just fallthrough
7371 }
7372 }
7373 else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
7374 accessCache[key] = 0 /* SETUP */;
7375 return setupState[key];
7376 }
7377 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
7378 accessCache[key] = 1 /* DATA */;
7379 return data[key];
7380 }
7381 else if (
7382 // only cache other properties when instance has declared (thus stable)
7383 // props
7384 (normalizedProps = instance.propsOptions[0]) &&
7385 hasOwn(normalizedProps, key)) {
7386 accessCache[key] = 2 /* PROPS */;
7387 return props[key];
7388 }
7389 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
7390 accessCache[key] = 3 /* CONTEXT */;
7391 return ctx[key];
7392 }
7393 else if (shouldCacheAccess) {
7394 accessCache[key] = 4 /* OTHER */;
7395 }
7396 }
7397 const publicGetter = publicPropertiesMap[key];
7398 let cssModule, globalProperties;
7399 // public $xxx properties
7400 if (publicGetter) {
7401 if (key === '$attrs') {
7402 track(instance, "get" /* GET */, key);
7403 markAttrsAccessed();
7404 }
7405 return publicGetter(instance);
7406 }
7407 else if (
7408 // css module (injected by vue-loader)
7409 (cssModule = type.__cssModules) &&
7410 (cssModule = cssModule[key])) {
7411 return cssModule;
7412 }
7413 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
7414 // user may set custom properties to `this` that start with `$`
7415 accessCache[key] = 3 /* CONTEXT */;
7416 return ctx[key];
7417 }
7418 else if (
7419 // global properties
7420 ((globalProperties = appContext.config.globalProperties),
7421 hasOwn(globalProperties, key))) {
7422 return globalProperties[key];
7423 }
7424 else if (currentRenderingInstance &&
7425 (!isString(key) ||
7426 // #1091 avoid internal isRef/isVNode checks on component instance leading
7427 // to infinite warning loop
7428 key.indexOf('__v') !== 0)) {
7429 if (data !== EMPTY_OBJ &&
7430 (key[0] === '$' || key[0] === '_') &&
7431 hasOwn(data, key)) {
7432 warn(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
7433 `character ("$" or "_") and is not proxied on the render context.`);
7434 }
7435 else if (instance === currentRenderingInstance) {
7436 warn(`Property ${JSON.stringify(key)} was accessed during render ` +
7437 `but is not defined on instance.`);
7438 }
7439 }
7440 },
7441 set({ _: instance }, key, value) {
7442 const { data, setupState, ctx } = instance;
7443 if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
7444 setupState[key] = value;
7445 }
7446 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
7447 data[key] = value;
7448 }
7449 else if (hasOwn(instance.props, key)) {
7450 warn(`Attempting to mutate prop "${key}". Props are readonly.`, instance);
7451 return false;
7452 }
7453 if (key[0] === '$' && key.slice(1) in instance) {
7454 warn(`Attempting to mutate public property "${key}". ` +
7455 `Properties starting with $ are reserved and readonly.`, instance);
7456 return false;
7457 }
7458 else {
7459 if (key in instance.appContext.config.globalProperties) {
7460 Object.defineProperty(ctx, key, {
7461 enumerable: true,
7462 configurable: true,
7463 value
7464 });
7465 }
7466 else {
7467 ctx[key] = value;
7468 }
7469 }
7470 return true;
7471 },
7472 has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
7473 let normalizedProps;
7474 return (accessCache[key] !== undefined ||
7475 (data !== EMPTY_OBJ && hasOwn(data, key)) ||
7476 (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
7477 ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
7478 hasOwn(ctx, key) ||
7479 hasOwn(publicPropertiesMap, key) ||
7480 hasOwn(appContext.config.globalProperties, key));
7481 }
7482};
7483{
7484 PublicInstanceProxyHandlers.ownKeys = (target) => {
7485 warn(`Avoid app logic that relies on enumerating keys on a component instance. ` +
7486 `The keys will be empty in production mode to avoid performance overhead.`);
7487 return Reflect.ownKeys(target);
7488 };
7489}
7490const RuntimeCompiledPublicInstanceProxyHandlers = extend({}, PublicInstanceProxyHandlers, {
7491 get(target, key) {
7492 // fast path for unscopables when using `with` block
7493 if (key === Symbol.unscopables) {
7494 return;
7495 }
7496 return PublicInstanceProxyHandlers.get(target, key, target);
7497 },
7498 has(_, key) {
7499 const has = key[0] !== '_' && !isGloballyWhitelisted(key);
7500 if (!has && PublicInstanceProxyHandlers.has(_, key)) {
7501 warn(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
7502 }
7503 return has;
7504 }
7505});
7506// In dev mode, the proxy target exposes the same properties as seen on `this`
7507// for easier console inspection. In prod mode it will be an empty object so
7508// these properties definitions can be skipped.
7509function createRenderContext(instance) {
7510 const target = {};
7511 // expose internal instance for proxy handlers
7512 Object.defineProperty(target, `_`, {
7513 configurable: true,
7514 enumerable: false,
7515 get: () => instance
7516 });
7517 // expose public properties
7518 Object.keys(publicPropertiesMap).forEach(key => {
7519 Object.defineProperty(target, key, {
7520 configurable: true,
7521 enumerable: false,
7522 get: () => publicPropertiesMap[key](instance),
7523 // intercepted by the proxy so no need for implementation,
7524 // but needed to prevent set errors
7525 set: NOOP
7526 });
7527 });
7528 // expose global properties
7529 const { globalProperties } = instance.appContext.config;
7530 Object.keys(globalProperties).forEach(key => {
7531 Object.defineProperty(target, key, {
7532 configurable: true,
7533 enumerable: false,
7534 get: () => globalProperties[key],
7535 set: NOOP
7536 });
7537 });
7538 return target;
7539}
7540// dev only
7541function exposePropsOnRenderContext(instance) {
7542 const { ctx, propsOptions: [propsOptions] } = instance;
7543 if (propsOptions) {
7544 Object.keys(propsOptions).forEach(key => {
7545 Object.defineProperty(ctx, key, {
7546 enumerable: true,
7547 configurable: true,
7548 get: () => instance.props[key],
7549 set: NOOP
7550 });
7551 });
7552 }
7553}
7554// dev only
7555function exposeSetupStateOnRenderContext(instance) {
7556 const { ctx, setupState } = instance;
7557 Object.keys(toRaw(setupState)).forEach(key => {
7558 if (key[0] === '$' || key[0] === '_') {
7559 warn(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
7560 `which are reserved prefixes for Vue internals.`);
7561 return;
7562 }
7563 Object.defineProperty(ctx, key, {
7564 enumerable: true,
7565 configurable: true,
7566 get: () => setupState[key],
7567 set: NOOP
7568 });
7569 });
7570}
7571
7572const emptyAppContext = createAppContext();
7573let uid$2 = 0;
7574function createComponentInstance(vnode, parent, suspense) {
7575 const type = vnode.type;
7576 // inherit parent app context - or - if root, adopt from root vnode
7577 const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
7578 const instance = {
7579 uid: uid$2++,
7580 vnode,
7581 type,
7582 parent,
7583 appContext,
7584 root: null,
7585 next: null,
7586 subTree: null,
7587 update: null,
7588 render: null,
7589 proxy: null,
7590 exposed: null,
7591 withProxy: null,
7592 effects: null,
7593 provides: parent ? parent.provides : Object.create(appContext.provides),
7594 accessCache: null,
7595 renderCache: [],
7596 // local resovled assets
7597 components: null,
7598 directives: null,
7599 // resolved props and emits options
7600 propsOptions: normalizePropsOptions(type, appContext),
7601 emitsOptions: normalizeEmitsOptions(type, appContext),
7602 // emit
7603 emit: null,
7604 emitted: null,
7605 // props default value
7606 propsDefaults: EMPTY_OBJ,
7607 // state
7608 ctx: EMPTY_OBJ,
7609 data: EMPTY_OBJ,
7610 props: EMPTY_OBJ,
7611 attrs: EMPTY_OBJ,
7612 slots: EMPTY_OBJ,
7613 refs: EMPTY_OBJ,
7614 setupState: EMPTY_OBJ,
7615 setupContext: null,
7616 // suspense related
7617 suspense,
7618 suspenseId: suspense ? suspense.pendingId : 0,
7619 asyncDep: null,
7620 asyncResolved: false,
7621 // lifecycle hooks
7622 // not using enums here because it results in computed properties
7623 isMounted: false,
7624 isUnmounted: false,
7625 isDeactivated: false,
7626 bc: null,
7627 c: null,
7628 bm: null,
7629 m: null,
7630 bu: null,
7631 u: null,
7632 um: null,
7633 bum: null,
7634 da: null,
7635 a: null,
7636 rtg: null,
7637 rtc: null,
7638 ec: null
7639 };
7640 {
7641 instance.ctx = createRenderContext(instance);
7642 }
7643 instance.root = parent ? parent.root : instance;
7644 instance.emit = emit.bind(null, instance);
7645 return instance;
7646}
7647let currentInstance = null;
7648const getCurrentInstance = () => currentInstance || currentRenderingInstance;
7649const setCurrentInstance = (instance) => {
7650 currentInstance = instance;
7651};
7652const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
7653function validateComponentName(name, config) {
7654 const appIsNativeTag = config.isNativeTag || NO;
7655 if (isBuiltInTag(name) || appIsNativeTag(name)) {
7656 warn('Do not use built-in or reserved HTML elements as component id: ' + name);
7657 }
7658}
7659function isStatefulComponent(instance) {
7660 return instance.vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */;
7661}
7662let isInSSRComponentSetup = false;
7663function setupComponent(instance, isSSR = false) {
7664 isInSSRComponentSetup = isSSR;
7665 const { props, children } = instance.vnode;
7666 const isStateful = isStatefulComponent(instance);
7667 initProps(instance, props, isStateful, isSSR);
7668 initSlots(instance, children);
7669 const setupResult = isStateful
7670 ? setupStatefulComponent(instance, isSSR)
7671 : undefined;
7672 isInSSRComponentSetup = false;
7673 return setupResult;
7674}
7675function setupStatefulComponent(instance, isSSR) {
7676 const Component = instance.type;
7677 {
7678 if (Component.name) {
7679 validateComponentName(Component.name, instance.appContext.config);
7680 }
7681 if (Component.components) {
7682 const names = Object.keys(Component.components);
7683 for (let i = 0; i < names.length; i++) {
7684 validateComponentName(names[i], instance.appContext.config);
7685 }
7686 }
7687 if (Component.directives) {
7688 const names = Object.keys(Component.directives);
7689 for (let i = 0; i < names.length; i++) {
7690 validateDirectiveName(names[i]);
7691 }
7692 }
7693 }
7694 // 0. create render proxy property access cache
7695 instance.accessCache = Object.create(null);
7696 // 1. create public instance / render proxy
7697 // also mark it raw so it's never observed
7698 instance.proxy = new Proxy(instance.ctx, PublicInstanceProxyHandlers);
7699 {
7700 exposePropsOnRenderContext(instance);
7701 }
7702 // 2. call setup()
7703 const { setup } = Component;
7704 if (setup) {
7705 const setupContext = (instance.setupContext =
7706 setup.length > 1 ? createSetupContext(instance) : null);
7707 currentInstance = instance;
7708 pauseTracking();
7709 const setupResult = callWithErrorHandling(setup, instance, 0 /* SETUP_FUNCTION */, [shallowReadonly(instance.props) , setupContext]);
7710 resetTracking();
7711 currentInstance = null;
7712 if (isPromise(setupResult)) {
7713 if (isSSR) {
7714 // return the promise so server-renderer can wait on it
7715 return setupResult
7716 .then((resolvedResult) => {
7717 handleSetupResult(instance, resolvedResult, isSSR);
7718 })
7719 .catch(e => {
7720 handleError(e, instance, 0 /* SETUP_FUNCTION */);
7721 });
7722 }
7723 else {
7724 // async setup returned Promise.
7725 // bail here and wait for re-entry.
7726 instance.asyncDep = setupResult;
7727 }
7728 }
7729 else {
7730 handleSetupResult(instance, setupResult, isSSR);
7731 }
7732 }
7733 else {
7734 finishComponentSetup(instance, isSSR);
7735 }
7736}
7737function handleSetupResult(instance, setupResult, isSSR) {
7738 if (isFunction(setupResult)) {
7739 // setup returned an inline render function
7740 {
7741 instance.render = setupResult;
7742 }
7743 }
7744 else if (isObject(setupResult)) {
7745 if (isVNode(setupResult)) {
7746 warn(`setup() should not return VNodes directly - ` +
7747 `return a render function instead.`);
7748 }
7749 // setup returned bindings.
7750 // assuming a render function compiled from template is present.
7751 {
7752 instance.devtoolsRawSetupState = setupResult;
7753 }
7754 instance.setupState = proxyRefs(setupResult);
7755 {
7756 exposeSetupStateOnRenderContext(instance);
7757 }
7758 }
7759 else if (setupResult !== undefined) {
7760 warn(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
7761 }
7762 finishComponentSetup(instance, isSSR);
7763}
7764let compile;
7765// dev only
7766const isRuntimeOnly = () => !compile;
7767/**
7768 * For runtime-dom to register the compiler.
7769 * Note the exported method uses any to avoid d.ts relying on the compiler types.
7770 */
7771function registerRuntimeCompiler(_compile) {
7772 compile = _compile;
7773}
7774function finishComponentSetup(instance, isSSR) {
7775 const Component = instance.type;
7776 // template / render function normalization
7777 if (!instance.render) {
7778 // could be set from setup()
7779 if (compile && Component.template && !Component.render) {
7780 {
7781 startMeasure(instance, `compile`);
7782 }
7783 Component.render = compile(Component.template, {
7784 isCustomElement: instance.appContext.config.isCustomElement,
7785 delimiters: Component.delimiters
7786 });
7787 {
7788 endMeasure(instance, `compile`);
7789 }
7790 }
7791 instance.render = (Component.render || NOOP);
7792 // for runtime-compiled render functions using `with` blocks, the render
7793 // proxy used needs a different `has` handler which is more performant and
7794 // also only allows a whitelist of globals to fallthrough.
7795 if (instance.render._rc) {
7796 instance.withProxy = new Proxy(instance.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
7797 }
7798 }
7799 // support for 2.x options
7800 {
7801 currentInstance = instance;
7802 pauseTracking();
7803 applyOptions(instance, Component);
7804 resetTracking();
7805 currentInstance = null;
7806 }
7807 // warn missing template/render
7808 // the runtime compilation of template in SSR is done by server-render
7809 if (!Component.render && instance.render === NOOP && !isSSR) {
7810 /* istanbul ignore if */
7811 if (!compile && Component.template) {
7812 warn(`Component provided template option but ` +
7813 `runtime compilation is not supported in this build of Vue.` +
7814 (` Use "vue.esm-browser.js" instead.`
7815 ) /* should not happen */);
7816 }
7817 else {
7818 warn(`Component is missing template or render function.`);
7819 }
7820 }
7821}
7822const attrHandlers = {
7823 get: (target, key) => {
7824 {
7825 markAttrsAccessed();
7826 }
7827 return target[key];
7828 },
7829 set: () => {
7830 warn(`setupContext.attrs is readonly.`);
7831 return false;
7832 },
7833 deleteProperty: () => {
7834 warn(`setupContext.attrs is readonly.`);
7835 return false;
7836 }
7837};
7838function createSetupContext(instance) {
7839 const expose = exposed => {
7840 if (instance.exposed) {
7841 warn(`expose() should be called only once per setup().`);
7842 }
7843 instance.exposed = proxyRefs(exposed);
7844 };
7845 {
7846 // We use getters in dev in case libs like test-utils overwrite instance
7847 // properties (overwrites should not be done in prod)
7848 return Object.freeze({
7849 get attrs() {
7850 return new Proxy(instance.attrs, attrHandlers);
7851 },
7852 get slots() {
7853 return shallowReadonly(instance.slots);
7854 },
7855 get emit() {
7856 return (event, ...args) => instance.emit(event, ...args);
7857 },
7858 expose
7859 });
7860 }
7861}
7862// record effects created during a component's setup() so that they can be
7863// stopped when the component unmounts
7864function recordInstanceBoundEffect(effect, instance = currentInstance) {
7865 if (instance) {
7866 (instance.effects || (instance.effects = [])).push(effect);
7867 }
7868}
7869const classifyRE = /(?:^|[-_])(\w)/g;
7870const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
7871function getComponentName(Component) {
7872 return isFunction(Component)
7873 ? Component.displayName || Component.name
7874 : Component.name;
7875}
7876/* istanbul ignore next */
7877function formatComponentName(instance, Component, isRoot = false) {
7878 let name = getComponentName(Component);
7879 if (!name && Component.__file) {
7880 const match = Component.__file.match(/([^/\\]+)\.\w+$/);
7881 if (match) {
7882 name = match[1];
7883 }
7884 }
7885 if (!name && instance && instance.parent) {
7886 // try to infer the name based on reverse resolution
7887 const inferFromRegistry = (registry) => {
7888 for (const key in registry) {
7889 if (registry[key] === Component) {
7890 return key;
7891 }
7892 }
7893 };
7894 name =
7895 inferFromRegistry(instance.components ||
7896 instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
7897 }
7898 return name ? classify(name) : isRoot ? `App` : `Anonymous`;
7899}
7900function isClassComponent(value) {
7901 return isFunction(value) && '__vccOpts' in value;
7902}
7903
7904function computed$1(getterOrOptions) {
7905 const c = computed(getterOrOptions);
7906 recordInstanceBoundEffect(c.effect);
7907 return c;
7908}
7909
7910// implementation
7911function defineProps() {
7912 {
7913 warn(`defineProps() is a compiler-hint helper that is only usable inside ` +
7914 `<script setup> of a single file component. Its arguments should be ` +
7915 `compiled away and passing it at runtime has no effect.`);
7916 }
7917 return null;
7918}
7919// implementation
7920function defineEmit() {
7921 {
7922 warn(`defineEmit() is a compiler-hint helper that is only usable inside ` +
7923 `<script setup> of a single file component. Its arguments should be ` +
7924 `compiled away and passing it at runtime has no effect.`);
7925 }
7926 return null;
7927}
7928function useContext() {
7929 const i = getCurrentInstance();
7930 if (!i) {
7931 warn(`useContext() called without active instance.`);
7932 }
7933 return i.setupContext || (i.setupContext = createSetupContext(i));
7934}
7935
7936// Actual implementation
7937function h(type, propsOrChildren, children) {
7938 const l = arguments.length;
7939 if (l === 2) {
7940 if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
7941 // single vnode without props
7942 if (isVNode(propsOrChildren)) {
7943 return createVNode(type, null, [propsOrChildren]);
7944 }
7945 // props without children
7946 return createVNode(type, propsOrChildren);
7947 }
7948 else {
7949 // omit props
7950 return createVNode(type, null, propsOrChildren);
7951 }
7952 }
7953 else {
7954 if (l > 3) {
7955 children = Array.prototype.slice.call(arguments, 2);
7956 }
7957 else if (l === 3 && isVNode(children)) {
7958 children = [children];
7959 }
7960 return createVNode(type, propsOrChildren, children);
7961 }
7962}
7963
7964const ssrContextKey = Symbol(`ssrContext` );
7965const useSSRContext = () => {
7966 {
7967 const ctx = inject(ssrContextKey);
7968 if (!ctx) {
7969 warn(`Server rendering context not provided. Make sure to only call ` +
7970 `useSSRContext() conditionally in the server build.`);
7971 }
7972 return ctx;
7973 }
7974};
7975
7976function initCustomFormatter() {
7977 /* eslint-disable no-restricted-globals */
7978 if (typeof window === 'undefined') {
7979 return;
7980 }
7981 const vueStyle = { style: 'color:#3ba776' };
7982 const numberStyle = { style: 'color:#0b1bc9' };
7983 const stringStyle = { style: 'color:#b62e24' };
7984 const keywordStyle = { style: 'color:#9d288c' };
7985 // custom formatter for Chrome
7986 // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
7987 const formatter = {
7988 header(obj) {
7989 // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
7990 if (!isObject(obj)) {
7991 return null;
7992 }
7993 if (obj.__isVue) {
7994 return ['div', vueStyle, `VueInstance`];
7995 }
7996 else if (isRef(obj)) {
7997 return [
7998 'div',
7999 {},
8000 ['span', vueStyle, genRefFlag(obj)],
8001 '<',
8002 formatValue(obj.value),
8003 `>`
8004 ];
8005 }
8006 else if (isReactive(obj)) {
8007 return [
8008 'div',
8009 {},
8010 ['span', vueStyle, 'Reactive'],
8011 '<',
8012 formatValue(obj),
8013 `>${isReadonly(obj) ? ` (readonly)` : ``}`
8014 ];
8015 }
8016 else if (isReadonly(obj)) {
8017 return [
8018 'div',
8019 {},
8020 ['span', vueStyle, 'Readonly'],
8021 '<',
8022 formatValue(obj),
8023 '>'
8024 ];
8025 }
8026 return null;
8027 },
8028 hasBody(obj) {
8029 return obj && obj.__isVue;
8030 },
8031 body(obj) {
8032 if (obj && obj.__isVue) {
8033 return [
8034 'div',
8035 {},
8036 ...formatInstance(obj.$)
8037 ];
8038 }
8039 }
8040 };
8041 function formatInstance(instance) {
8042 const blocks = [];
8043 if (instance.type.props && instance.props) {
8044 blocks.push(createInstanceBlock('props', toRaw(instance.props)));
8045 }
8046 if (instance.setupState !== EMPTY_OBJ) {
8047 blocks.push(createInstanceBlock('setup', instance.setupState));
8048 }
8049 if (instance.data !== EMPTY_OBJ) {
8050 blocks.push(createInstanceBlock('data', toRaw(instance.data)));
8051 }
8052 const computed = extractKeys(instance, 'computed');
8053 if (computed) {
8054 blocks.push(createInstanceBlock('computed', computed));
8055 }
8056 const injected = extractKeys(instance, 'inject');
8057 if (injected) {
8058 blocks.push(createInstanceBlock('injected', injected));
8059 }
8060 blocks.push([
8061 'div',
8062 {},
8063 [
8064 'span',
8065 {
8066 style: keywordStyle.style + ';opacity:0.66'
8067 },
8068 '$ (internal): '
8069 ],
8070 ['object', { object: instance }]
8071 ]);
8072 return blocks;
8073 }
8074 function createInstanceBlock(type, target) {
8075 target = extend({}, target);
8076 if (!Object.keys(target).length) {
8077 return ['span', {}];
8078 }
8079 return [
8080 'div',
8081 { style: 'line-height:1.25em;margin-bottom:0.6em' },
8082 [
8083 'div',
8084 {
8085 style: 'color:#476582'
8086 },
8087 type
8088 ],
8089 [
8090 'div',
8091 {
8092 style: 'padding-left:1.25em'
8093 },
8094 ...Object.keys(target).map(key => {
8095 return [
8096 'div',
8097 {},
8098 ['span', keywordStyle, key + ': '],
8099 formatValue(target[key], false)
8100 ];
8101 })
8102 ]
8103 ];
8104 }
8105 function formatValue(v, asRaw = true) {
8106 if (typeof v === 'number') {
8107 return ['span', numberStyle, v];
8108 }
8109 else if (typeof v === 'string') {
8110 return ['span', stringStyle, JSON.stringify(v)];
8111 }
8112 else if (typeof v === 'boolean') {
8113 return ['span', keywordStyle, v];
8114 }
8115 else if (isObject(v)) {
8116 return ['object', { object: asRaw ? toRaw(v) : v }];
8117 }
8118 else {
8119 return ['span', stringStyle, String(v)];
8120 }
8121 }
8122 function extractKeys(instance, type) {
8123 const Comp = instance.type;
8124 if (isFunction(Comp)) {
8125 return;
8126 }
8127 const extracted = {};
8128 for (const key in instance.ctx) {
8129 if (isKeyOfType(Comp, key, type)) {
8130 extracted[key] = instance.ctx[key];
8131 }
8132 }
8133 return extracted;
8134 }
8135 function isKeyOfType(Comp, key, type) {
8136 const opts = Comp[type];
8137 if ((isArray(opts) && opts.includes(key)) ||
8138 (isObject(opts) && key in opts)) {
8139 return true;
8140 }
8141 if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
8142 return true;
8143 }
8144 if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
8145 return true;
8146 }
8147 }
8148 function genRefFlag(v) {
8149 if (v._shallow) {
8150 return `ShallowRef`;
8151 }
8152 if (v.effect) {
8153 return `ComputedRef`;
8154 }
8155 return `Ref`;
8156 }
8157 if (window.devtoolsFormatters) {
8158 window.devtoolsFormatters.push(formatter);
8159 }
8160 else {
8161 window.devtoolsFormatters = [formatter];
8162 }
8163}
8164
8165/**
8166 * Actual implementation
8167 */
8168function renderList(source, renderItem) {
8169 let ret;
8170 if (isArray(source) || isString(source)) {
8171 ret = new Array(source.length);
8172 for (let i = 0, l = source.length; i < l; i++) {
8173 ret[i] = renderItem(source[i], i);
8174 }
8175 }
8176 else if (typeof source === 'number') {
8177 if (!Number.isInteger(source)) {
8178 warn(`The v-for range expect an integer value but got ${source}.`);
8179 return [];
8180 }
8181 ret = new Array(source);
8182 for (let i = 0; i < source; i++) {
8183 ret[i] = renderItem(i + 1, i);
8184 }
8185 }
8186 else if (isObject(source)) {
8187 if (source[Symbol.iterator]) {
8188 ret = Array.from(source, renderItem);
8189 }
8190 else {
8191 const keys = Object.keys(source);
8192 ret = new Array(keys.length);
8193 for (let i = 0, l = keys.length; i < l; i++) {
8194 const key = keys[i];
8195 ret[i] = renderItem(source[key], key, i);
8196 }
8197 }
8198 }
8199 else {
8200 ret = [];
8201 }
8202 return ret;
8203}
8204
8205/**
8206 * For prefixing keys in v-on="obj" with "on"
8207 * @private
8208 */
8209function toHandlers(obj) {
8210 const ret = {};
8211 if (!isObject(obj)) {
8212 warn(`v-on with no argument expects an object value.`);
8213 return ret;
8214 }
8215 for (const key in obj) {
8216 ret[toHandlerKey(key)] = obj[key];
8217 }
8218 return ret;
8219}
8220
8221/**
8222 * Compiler runtime helper for creating dynamic slots object
8223 * @private
8224 */
8225function createSlots(slots, dynamicSlots) {
8226 for (let i = 0; i < dynamicSlots.length; i++) {
8227 const slot = dynamicSlots[i];
8228 // array of dynamic slot generated by <template v-for="..." #[...]>
8229 if (isArray(slot)) {
8230 for (let j = 0; j < slot.length; j++) {
8231 slots[slot[j].name] = slot[j].fn;
8232 }
8233 }
8234 else if (slot) {
8235 // conditional single slot generated by <template v-if="..." #foo>
8236 slots[slot.name] = slot.fn;
8237 }
8238 }
8239 return slots;
8240}
8241
8242// Core API ------------------------------------------------------------------
8243const version = "3.0.10";
8244/**
8245 * SSR utils for \@vue/server-renderer. Only exposed in cjs builds.
8246 * @internal
8247 */
8248const ssrUtils = (null);
8249
8250const svgNS = 'http://www.w3.org/2000/svg';
8251const doc = (typeof document !== 'undefined' ? document : null);
8252let tempContainer;
8253let tempSVGContainer;
8254const nodeOps = {
8255 insert: (child, parent, anchor) => {
8256 parent.insertBefore(child, anchor || null);
8257 },
8258 remove: child => {
8259 const parent = child.parentNode;
8260 if (parent) {
8261 parent.removeChild(child);
8262 }
8263 },
8264 createElement: (tag, isSVG, is, props) => {
8265 const el = isSVG
8266 ? doc.createElementNS(svgNS, tag)
8267 : doc.createElement(tag, is ? { is } : undefined);
8268 if (tag === 'select' && props && props.multiple != null) {
8269 el.setAttribute('multiple', props.multiple);
8270 }
8271 return el;
8272 },
8273 createText: text => doc.createTextNode(text),
8274 createComment: text => doc.createComment(text),
8275 setText: (node, text) => {
8276 node.nodeValue = text;
8277 },
8278 setElementText: (el, text) => {
8279 el.textContent = text;
8280 },
8281 parentNode: node => node.parentNode,
8282 nextSibling: node => node.nextSibling,
8283 querySelector: selector => doc.querySelector(selector),
8284 setScopeId(el, id) {
8285 el.setAttribute(id, '');
8286 },
8287 cloneNode(el) {
8288 const cloned = el.cloneNode(true);
8289 // #3072
8290 // - in `patchDOMProp`, we store the actual value in the `el._value` property.
8291 // - normally, elements using `:value` bindings will not be hoisted, but if
8292 // the bound value is a constant, e.g. `:value="true"` - they do get
8293 // hoisted.
8294 // - in production, hoisted nodes are cloned when subsequent inserts, but
8295 // cloneNode() does not copy the custom property we attached.
8296 // - This may need to account for other custom DOM properties we attach to
8297 // elements in addition to `_value` in the future.
8298 if (`_value` in el) {
8299 cloned._value = el._value;
8300 }
8301 return cloned;
8302 },
8303 // __UNSAFE__
8304 // Reason: innerHTML.
8305 // Static content here can only come from compiled templates.
8306 // As long as the user only uses trusted templates, this is safe.
8307 insertStaticContent(content, parent, anchor, isSVG) {
8308 const temp = isSVG
8309 ? tempSVGContainer ||
8310 (tempSVGContainer = doc.createElementNS(svgNS, 'svg'))
8311 : tempContainer || (tempContainer = doc.createElement('div'));
8312 temp.innerHTML = content;
8313 const first = temp.firstChild;
8314 let node = first;
8315 let last = node;
8316 while (node) {
8317 last = node;
8318 nodeOps.insert(node, parent, anchor);
8319 node = temp.firstChild;
8320 }
8321 return [first, last];
8322 }
8323};
8324
8325// compiler should normalize class + :class bindings on the same element
8326// into a single binding ['staticClass', dynamic]
8327function patchClass(el, value, isSVG) {
8328 if (value == null) {
8329 value = '';
8330 }
8331 if (isSVG) {
8332 el.setAttribute('class', value);
8333 }
8334 else {
8335 // directly setting className should be faster than setAttribute in theory
8336 // if this is an element during a transition, take the temporary transition
8337 // classes into account.
8338 const transitionClasses = el._vtc;
8339 if (transitionClasses) {
8340 value = (value
8341 ? [value, ...transitionClasses]
8342 : [...transitionClasses]).join(' ');
8343 }
8344 el.className = value;
8345 }
8346}
8347
8348function patchStyle(el, prev, next) {
8349 const style = el.style;
8350 if (!next) {
8351 el.removeAttribute('style');
8352 }
8353 else if (isString(next)) {
8354 if (prev !== next) {
8355 const current = style.display;
8356 style.cssText = next;
8357 // indicates that the `display` of the element is controlled by `v-show`,
8358 // so we always keep the current `display` value regardless of the `style` value,
8359 // thus handing over control to `v-show`.
8360 if ('_vod' in el) {
8361 style.display = current;
8362 }
8363 }
8364 }
8365 else {
8366 for (const key in next) {
8367 setStyle(style, key, next[key]);
8368 }
8369 if (prev && !isString(prev)) {
8370 for (const key in prev) {
8371 if (next[key] == null) {
8372 setStyle(style, key, '');
8373 }
8374 }
8375 }
8376 }
8377}
8378const importantRE = /\s*!important$/;
8379function setStyle(style, name, val) {
8380 if (isArray(val)) {
8381 val.forEach(v => setStyle(style, name, v));
8382 }
8383 else {
8384 if (name.startsWith('--')) {
8385 // custom property definition
8386 style.setProperty(name, val);
8387 }
8388 else {
8389 const prefixed = autoPrefix(style, name);
8390 if (importantRE.test(val)) {
8391 // !important
8392 style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
8393 }
8394 else {
8395 style[prefixed] = val;
8396 }
8397 }
8398 }
8399}
8400const prefixes = ['Webkit', 'Moz', 'ms'];
8401const prefixCache = {};
8402function autoPrefix(style, rawName) {
8403 const cached = prefixCache[rawName];
8404 if (cached) {
8405 return cached;
8406 }
8407 let name = camelize(rawName);
8408 if (name !== 'filter' && name in style) {
8409 return (prefixCache[rawName] = name);
8410 }
8411 name = capitalize(name);
8412 for (let i = 0; i < prefixes.length; i++) {
8413 const prefixed = prefixes[i] + name;
8414 if (prefixed in style) {
8415 return (prefixCache[rawName] = prefixed);
8416 }
8417 }
8418 return rawName;
8419}
8420
8421const xlinkNS = 'http://www.w3.org/1999/xlink';
8422function patchAttr(el, key, value, isSVG) {
8423 if (isSVG && key.startsWith('xlink:')) {
8424 if (value == null) {
8425 el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
8426 }
8427 else {
8428 el.setAttributeNS(xlinkNS, key, value);
8429 }
8430 }
8431 else {
8432 // note we are only checking boolean attributes that don't have a
8433 // corresponding dom prop of the same name here.
8434 const isBoolean = isSpecialBooleanAttr(key);
8435 if (value == null || (isBoolean && value === false)) {
8436 el.removeAttribute(key);
8437 }
8438 else {
8439 el.setAttribute(key, isBoolean ? '' : value);
8440 }
8441 }
8442}
8443
8444// __UNSAFE__
8445// functions. The user is responsible for using them with only trusted content.
8446function patchDOMProp(el, key, value,
8447// the following args are passed only due to potential innerHTML/textContent
8448// overriding existing VNodes, in which case the old tree must be properly
8449// unmounted.
8450prevChildren, parentComponent, parentSuspense, unmountChildren) {
8451 if (key === 'innerHTML' || key === 'textContent') {
8452 if (prevChildren) {
8453 unmountChildren(prevChildren, parentComponent, parentSuspense);
8454 }
8455 el[key] = value == null ? '' : value;
8456 return;
8457 }
8458 if (key === 'value' && el.tagName !== 'PROGRESS') {
8459 // store value as _value as well since
8460 // non-string values will be stringified.
8461 el._value = value;
8462 const newValue = value == null ? '' : value;
8463 if (el.value !== newValue) {
8464 el.value = newValue;
8465 }
8466 return;
8467 }
8468 if (value === '' || value == null) {
8469 const type = typeof el[key];
8470 if (value === '' && type === 'boolean') {
8471 // e.g. <select multiple> compiles to { multiple: '' }
8472 el[key] = true;
8473 return;
8474 }
8475 else if (value == null && type === 'string') {
8476 // e.g. <div :id="null">
8477 el[key] = '';
8478 el.removeAttribute(key);
8479 return;
8480 }
8481 else if (type === 'number') {
8482 // e.g. <img :width="null">
8483 el[key] = 0;
8484 el.removeAttribute(key);
8485 return;
8486 }
8487 }
8488 // some properties perform value validation and throw
8489 try {
8490 el[key] = value;
8491 }
8492 catch (e) {
8493 {
8494 warn(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
8495 `value ${value} is invalid.`, e);
8496 }
8497 }
8498}
8499
8500// Async edge case fix requires storing an event listener's attach timestamp.
8501let _getNow = Date.now;
8502let skipTimestampCheck = false;
8503if (typeof window !== 'undefined') {
8504 // Determine what event timestamp the browser is using. Annoyingly, the
8505 // timestamp can either be hi-res (relative to page load) or low-res
8506 // (relative to UNIX epoch), so in order to compare time we have to use the
8507 // same timestamp type when saving the flush timestamp.
8508 if (_getNow() > document.createEvent('Event').timeStamp) {
8509 // if the low-res timestamp which is bigger than the event timestamp
8510 // (which is evaluated AFTER) it means the event is using a hi-res timestamp,
8511 // and we need to use the hi-res version for event listeners as well.
8512 _getNow = () => performance.now();
8513 }
8514 // #3485: Firefox <= 53 has incorrect Event.timeStamp implementation
8515 // and does not fire microtasks in between event propagation, so safe to exclude.
8516 const ffMatch = navigator.userAgent.match(/firefox\/(\d+)/i);
8517 skipTimestampCheck = !!(ffMatch && Number(ffMatch[1]) <= 53);
8518}
8519// To avoid the overhead of repeatedly calling performance.now(), we cache
8520// and use the same timestamp for all event listeners attached in the same tick.
8521let cachedNow = 0;
8522const p = Promise.resolve();
8523const reset = () => {
8524 cachedNow = 0;
8525};
8526const getNow = () => cachedNow || (p.then(reset), (cachedNow = _getNow()));
8527function addEventListener(el, event, handler, options) {
8528 el.addEventListener(event, handler, options);
8529}
8530function removeEventListener(el, event, handler, options) {
8531 el.removeEventListener(event, handler, options);
8532}
8533function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
8534 // vei = vue event invokers
8535 const invokers = el._vei || (el._vei = {});
8536 const existingInvoker = invokers[rawName];
8537 if (nextValue && existingInvoker) {
8538 // patch
8539 existingInvoker.value = nextValue;
8540 }
8541 else {
8542 const [name, options] = parseName(rawName);
8543 if (nextValue) {
8544 // add
8545 const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
8546 addEventListener(el, name, invoker, options);
8547 }
8548 else if (existingInvoker) {
8549 // remove
8550 removeEventListener(el, name, existingInvoker, options);
8551 invokers[rawName] = undefined;
8552 }
8553 }
8554}
8555const optionsModifierRE = /(?:Once|Passive|Capture)$/;
8556function parseName(name) {
8557 let options;
8558 if (optionsModifierRE.test(name)) {
8559 options = {};
8560 let m;
8561 while ((m = name.match(optionsModifierRE))) {
8562 name = name.slice(0, name.length - m[0].length);
8563 options[m[0].toLowerCase()] = true;
8564 }
8565 }
8566 return [hyphenate(name.slice(2)), options];
8567}
8568function createInvoker(initialValue, instance) {
8569 const invoker = (e) => {
8570 // async edge case #6566: inner click event triggers patch, event handler
8571 // attached to outer element during patch, and triggered again. This
8572 // happens because browsers fire microtask ticks between event propagation.
8573 // the solution is simple: we save the timestamp when a handler is attached,
8574 // and the handler would only fire if the event passed to it was fired
8575 // AFTER it was attached.
8576 const timeStamp = e.timeStamp || _getNow();
8577 if (skipTimestampCheck || timeStamp >= invoker.attached - 1) {
8578 callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* NATIVE_EVENT_HANDLER */, [e]);
8579 }
8580 };
8581 invoker.value = initialValue;
8582 invoker.attached = getNow();
8583 return invoker;
8584}
8585function patchStopImmediatePropagation(e, value) {
8586 if (isArray(value)) {
8587 const originalStop = e.stopImmediatePropagation;
8588 e.stopImmediatePropagation = () => {
8589 originalStop.call(e);
8590 e._stopped = true;
8591 };
8592 return value.map(fn => (e) => !e._stopped && fn(e));
8593 }
8594 else {
8595 return value;
8596 }
8597}
8598
8599const nativeOnRE = /^on[a-z]/;
8600const forcePatchProp = (_, key) => key === 'value';
8601const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
8602 switch (key) {
8603 // special
8604 case 'class':
8605 patchClass(el, nextValue, isSVG);
8606 break;
8607 case 'style':
8608 patchStyle(el, prevValue, nextValue);
8609 break;
8610 default:
8611 if (isOn(key)) {
8612 // ignore v-model listeners
8613 if (!isModelListener(key)) {
8614 patchEvent(el, key, prevValue, nextValue, parentComponent);
8615 }
8616 }
8617 else if (shouldSetAsProp(el, key, nextValue, isSVG)) {
8618 patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
8619 }
8620 else {
8621 // special case for <input v-model type="checkbox"> with
8622 // :true-value & :false-value
8623 // store value as dom properties since non-string values will be
8624 // stringified.
8625 if (key === 'true-value') {
8626 el._trueValue = nextValue;
8627 }
8628 else if (key === 'false-value') {
8629 el._falseValue = nextValue;
8630 }
8631 patchAttr(el, key, nextValue, isSVG);
8632 }
8633 break;
8634 }
8635};
8636function shouldSetAsProp(el, key, value, isSVG) {
8637 if (isSVG) {
8638 // most keys must be set as attribute on svg elements to work
8639 // ...except innerHTML
8640 if (key === 'innerHTML') {
8641 return true;
8642 }
8643 // or native onclick with function values
8644 if (key in el && nativeOnRE.test(key) && isFunction(value)) {
8645 return true;
8646 }
8647 return false;
8648 }
8649 // spellcheck and draggable are numerated attrs, however their
8650 // corresponding DOM properties are actually booleans - this leads to
8651 // setting it with a string "false" value leading it to be coerced to
8652 // `true`, so we need to always treat them as attributes.
8653 // Note that `contentEditable` doesn't have this problem: its DOM
8654 // property is also enumerated string values.
8655 if (key === 'spellcheck' || key === 'draggable') {
8656 return false;
8657 }
8658 // #1787, #2840 form property on form elements is readonly and must be set as
8659 // attribute.
8660 if (key === 'form') {
8661 return false;
8662 }
8663 // #1526 <input list> must be set as attribute
8664 if (key === 'list' && el.tagName === 'INPUT') {
8665 return false;
8666 }
8667 // #2766 <textarea type> must be set as attribute
8668 if (key === 'type' && el.tagName === 'TEXTAREA') {
8669 return false;
8670 }
8671 // native onclick with string value, must be set as attribute
8672 if (nativeOnRE.test(key) && isString(value)) {
8673 return false;
8674 }
8675 return key in el;
8676}
8677
8678function useCssModule(name = '$style') {
8679 /* istanbul ignore else */
8680 {
8681 const instance = getCurrentInstance();
8682 if (!instance) {
8683 warn(`useCssModule must be called inside setup()`);
8684 return EMPTY_OBJ;
8685 }
8686 const modules = instance.type.__cssModules;
8687 if (!modules) {
8688 warn(`Current instance does not have CSS modules injected.`);
8689 return EMPTY_OBJ;
8690 }
8691 const mod = modules[name];
8692 if (!mod) {
8693 warn(`Current instance does not have CSS module named "${name}".`);
8694 return EMPTY_OBJ;
8695 }
8696 return mod;
8697 }
8698}
8699
8700/**
8701 * Runtime helper for SFC's CSS variable injection feature.
8702 * @private
8703 */
8704function useCssVars(getter) {
8705 const instance = getCurrentInstance();
8706 /* istanbul ignore next */
8707 if (!instance) {
8708 warn(`useCssVars is called without current active component instance.`);
8709 return;
8710 }
8711 const setVars = () => setVarsOnVNode(instance.subTree, getter(instance.proxy));
8712 onMounted(() => watchEffect(setVars, { flush: 'post' }));
8713 onUpdated(setVars);
8714}
8715function setVarsOnVNode(vnode, vars) {
8716 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
8717 const suspense = vnode.suspense;
8718 vnode = suspense.activeBranch;
8719 if (suspense.pendingBranch && !suspense.isHydrating) {
8720 suspense.effects.push(() => {
8721 setVarsOnVNode(suspense.activeBranch, vars);
8722 });
8723 }
8724 }
8725 // drill down HOCs until it's a non-component vnode
8726 while (vnode.component) {
8727 vnode = vnode.component.subTree;
8728 }
8729 if (vnode.shapeFlag & 1 /* ELEMENT */ && vnode.el) {
8730 const style = vnode.el.style;
8731 for (const key in vars) {
8732 style.setProperty(`--${key}`, vars[key]);
8733 }
8734 }
8735 else if (vnode.type === Fragment) {
8736 vnode.children.forEach(c => setVarsOnVNode(c, vars));
8737 }
8738}
8739
8740const TRANSITION = 'transition';
8741const ANIMATION = 'animation';
8742// DOM Transition is a higher-order-component based on the platform-agnostic
8743// base Transition component, with DOM-specific logic.
8744const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
8745Transition.displayName = 'Transition';
8746const DOMTransitionPropsValidators = {
8747 name: String,
8748 type: String,
8749 css: {
8750 type: Boolean,
8751 default: true
8752 },
8753 duration: [String, Number, Object],
8754 enterFromClass: String,
8755 enterActiveClass: String,
8756 enterToClass: String,
8757 appearFromClass: String,
8758 appearActiveClass: String,
8759 appearToClass: String,
8760 leaveFromClass: String,
8761 leaveActiveClass: String,
8762 leaveToClass: String
8763};
8764const TransitionPropsValidators = (Transition.props = /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
8765function resolveTransitionProps(rawProps) {
8766 let { name = 'v', type, css = true, duration, enterFromClass = `${name}-enter-from`, enterActiveClass = `${name}-enter-active`, enterToClass = `${name}-enter-to`, appearFromClass = enterFromClass, appearActiveClass = enterActiveClass, appearToClass = enterToClass, leaveFromClass = `${name}-leave-from`, leaveActiveClass = `${name}-leave-active`, leaveToClass = `${name}-leave-to` } = rawProps;
8767 const baseProps = {};
8768 for (const key in rawProps) {
8769 if (!(key in DOMTransitionPropsValidators)) {
8770 baseProps[key] = rawProps[key];
8771 }
8772 }
8773 if (!css) {
8774 return baseProps;
8775 }
8776 const durations = normalizeDuration(duration);
8777 const enterDuration = durations && durations[0];
8778 const leaveDuration = durations && durations[1];
8779 const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
8780 const finishEnter = (el, isAppear, done) => {
8781 removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
8782 removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
8783 done && done();
8784 };
8785 const finishLeave = (el, done) => {
8786 removeTransitionClass(el, leaveToClass);
8787 removeTransitionClass(el, leaveActiveClass);
8788 done && done();
8789 };
8790 const makeEnterHook = (isAppear) => {
8791 return (el, done) => {
8792 const hook = isAppear ? onAppear : onEnter;
8793 const resolve = () => finishEnter(el, isAppear, done);
8794 hook && hook(el, resolve);
8795 nextFrame(() => {
8796 removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
8797 addTransitionClass(el, isAppear ? appearToClass : enterToClass);
8798 if (!(hook && hook.length > 1)) {
8799 whenTransitionEnds(el, type, enterDuration, resolve);
8800 }
8801 });
8802 };
8803 };
8804 return extend(baseProps, {
8805 onBeforeEnter(el) {
8806 onBeforeEnter && onBeforeEnter(el);
8807 addTransitionClass(el, enterFromClass);
8808 addTransitionClass(el, enterActiveClass);
8809 },
8810 onBeforeAppear(el) {
8811 onBeforeAppear && onBeforeAppear(el);
8812 addTransitionClass(el, appearFromClass);
8813 addTransitionClass(el, appearActiveClass);
8814 },
8815 onEnter: makeEnterHook(false),
8816 onAppear: makeEnterHook(true),
8817 onLeave(el, done) {
8818 const resolve = () => finishLeave(el, done);
8819 addTransitionClass(el, leaveFromClass);
8820 // force reflow so *-leave-from classes immediately take effect (#2593)
8821 forceReflow();
8822 addTransitionClass(el, leaveActiveClass);
8823 nextFrame(() => {
8824 removeTransitionClass(el, leaveFromClass);
8825 addTransitionClass(el, leaveToClass);
8826 if (!(onLeave && onLeave.length > 1)) {
8827 whenTransitionEnds(el, type, leaveDuration, resolve);
8828 }
8829 });
8830 onLeave && onLeave(el, resolve);
8831 },
8832 onEnterCancelled(el) {
8833 finishEnter(el, false);
8834 onEnterCancelled && onEnterCancelled(el);
8835 },
8836 onAppearCancelled(el) {
8837 finishEnter(el, true);
8838 onAppearCancelled && onAppearCancelled(el);
8839 },
8840 onLeaveCancelled(el) {
8841 finishLeave(el);
8842 onLeaveCancelled && onLeaveCancelled(el);
8843 }
8844 });
8845}
8846function normalizeDuration(duration) {
8847 if (duration == null) {
8848 return null;
8849 }
8850 else if (isObject(duration)) {
8851 return [NumberOf(duration.enter), NumberOf(duration.leave)];
8852 }
8853 else {
8854 const n = NumberOf(duration);
8855 return [n, n];
8856 }
8857}
8858function NumberOf(val) {
8859 const res = toNumber(val);
8860 validateDuration(res);
8861 return res;
8862}
8863function validateDuration(val) {
8864 if (typeof val !== 'number') {
8865 warn(`<transition> explicit duration is not a valid number - ` +
8866 `got ${JSON.stringify(val)}.`);
8867 }
8868 else if (isNaN(val)) {
8869 warn(`<transition> explicit duration is NaN - ` +
8870 'the duration expression might be incorrect.');
8871 }
8872}
8873function addTransitionClass(el, cls) {
8874 cls.split(/\s+/).forEach(c => c && el.classList.add(c));
8875 (el._vtc ||
8876 (el._vtc = new Set())).add(cls);
8877}
8878function removeTransitionClass(el, cls) {
8879 cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
8880 const { _vtc } = el;
8881 if (_vtc) {
8882 _vtc.delete(cls);
8883 if (!_vtc.size) {
8884 el._vtc = undefined;
8885 }
8886 }
8887}
8888function nextFrame(cb) {
8889 requestAnimationFrame(() => {
8890 requestAnimationFrame(cb);
8891 });
8892}
8893let endId = 0;
8894function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
8895 const id = (el._endId = ++endId);
8896 const resolveIfNotStale = () => {
8897 if (id === el._endId) {
8898 resolve();
8899 }
8900 };
8901 if (explicitTimeout) {
8902 return setTimeout(resolveIfNotStale, explicitTimeout);
8903 }
8904 const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
8905 if (!type) {
8906 return resolve();
8907 }
8908 const endEvent = type + 'end';
8909 let ended = 0;
8910 const end = () => {
8911 el.removeEventListener(endEvent, onEnd);
8912 resolveIfNotStale();
8913 };
8914 const onEnd = (e) => {
8915 if (e.target === el && ++ended >= propCount) {
8916 end();
8917 }
8918 };
8919 setTimeout(() => {
8920 if (ended < propCount) {
8921 end();
8922 }
8923 }, timeout + 1);
8924 el.addEventListener(endEvent, onEnd);
8925}
8926function getTransitionInfo(el, expectedType) {
8927 const styles = window.getComputedStyle(el);
8928 // JSDOM may return undefined for transition properties
8929 const getStyleProperties = (key) => (styles[key] || '').split(', ');
8930 const transitionDelays = getStyleProperties(TRANSITION + 'Delay');
8931 const transitionDurations = getStyleProperties(TRANSITION + 'Duration');
8932 const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
8933 const animationDelays = getStyleProperties(ANIMATION + 'Delay');
8934 const animationDurations = getStyleProperties(ANIMATION + 'Duration');
8935 const animationTimeout = getTimeout(animationDelays, animationDurations);
8936 let type = null;
8937 let timeout = 0;
8938 let propCount = 0;
8939 /* istanbul ignore if */
8940 if (expectedType === TRANSITION) {
8941 if (transitionTimeout > 0) {
8942 type = TRANSITION;
8943 timeout = transitionTimeout;
8944 propCount = transitionDurations.length;
8945 }
8946 }
8947 else if (expectedType === ANIMATION) {
8948 if (animationTimeout > 0) {
8949 type = ANIMATION;
8950 timeout = animationTimeout;
8951 propCount = animationDurations.length;
8952 }
8953 }
8954 else {
8955 timeout = Math.max(transitionTimeout, animationTimeout);
8956 type =
8957 timeout > 0
8958 ? transitionTimeout > animationTimeout
8959 ? TRANSITION
8960 : ANIMATION
8961 : null;
8962 propCount = type
8963 ? type === TRANSITION
8964 ? transitionDurations.length
8965 : animationDurations.length
8966 : 0;
8967 }
8968 const hasTransform = type === TRANSITION &&
8969 /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']);
8970 return {
8971 type,
8972 timeout,
8973 propCount,
8974 hasTransform
8975 };
8976}
8977function getTimeout(delays, durations) {
8978 while (delays.length < durations.length) {
8979 delays = delays.concat(delays);
8980 }
8981 return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
8982}
8983// Old versions of Chromium (below 61.0.3163.100) formats floating pointer
8984// numbers in a locale-dependent way, using a comma instead of a dot.
8985// If comma is not replaced with a dot, the input will be rounded down
8986// (i.e. acting as a floor function) causing unexpected behaviors
8987function toMs(s) {
8988 return Number(s.slice(0, -1).replace(',', '.')) * 1000;
8989}
8990// synchronously force layout to put elements into a certain state
8991function forceReflow() {
8992 return document.body.offsetHeight;
8993}
8994
8995const positionMap = new WeakMap();
8996const newPositionMap = new WeakMap();
8997const TransitionGroupImpl = {
8998 name: 'TransitionGroup',
8999 props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
9000 tag: String,
9001 moveClass: String
9002 }),
9003 setup(props, { slots }) {
9004 const instance = getCurrentInstance();
9005 const state = useTransitionState();
9006 let prevChildren;
9007 let children;
9008 onUpdated(() => {
9009 // children is guaranteed to exist after initial render
9010 if (!prevChildren.length) {
9011 return;
9012 }
9013 const moveClass = props.moveClass || `${props.name || 'v'}-move`;
9014 if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
9015 return;
9016 }
9017 // we divide the work into three loops to avoid mixing DOM reads and writes
9018 // in each iteration - which helps prevent layout thrashing.
9019 prevChildren.forEach(callPendingCbs);
9020 prevChildren.forEach(recordPosition);
9021 const movedChildren = prevChildren.filter(applyTranslation);
9022 // force reflow to put everything in position
9023 forceReflow();
9024 movedChildren.forEach(c => {
9025 const el = c.el;
9026 const style = el.style;
9027 addTransitionClass(el, moveClass);
9028 style.transform = style.webkitTransform = style.transitionDuration = '';
9029 const cb = (el._moveCb = (e) => {
9030 if (e && e.target !== el) {
9031 return;
9032 }
9033 if (!e || /transform$/.test(e.propertyName)) {
9034 el.removeEventListener('transitionend', cb);
9035 el._moveCb = null;
9036 removeTransitionClass(el, moveClass);
9037 }
9038 });
9039 el.addEventListener('transitionend', cb);
9040 });
9041 });
9042 return () => {
9043 const rawProps = toRaw(props);
9044 const cssTransitionProps = resolveTransitionProps(rawProps);
9045 const tag = rawProps.tag || Fragment;
9046 prevChildren = children;
9047 children = slots.default ? getTransitionRawChildren(slots.default()) : [];
9048 for (let i = 0; i < children.length; i++) {
9049 const child = children[i];
9050 if (child.key != null) {
9051 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
9052 }
9053 else {
9054 warn(`<TransitionGroup> children must be keyed.`);
9055 }
9056 }
9057 if (prevChildren) {
9058 for (let i = 0; i < prevChildren.length; i++) {
9059 const child = prevChildren[i];
9060 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
9061 positionMap.set(child, child.el.getBoundingClientRect());
9062 }
9063 }
9064 return createVNode(tag, null, children);
9065 };
9066 }
9067};
9068const TransitionGroup = TransitionGroupImpl;
9069function callPendingCbs(c) {
9070 const el = c.el;
9071 if (el._moveCb) {
9072 el._moveCb();
9073 }
9074 if (el._enterCb) {
9075 el._enterCb();
9076 }
9077}
9078function recordPosition(c) {
9079 newPositionMap.set(c, c.el.getBoundingClientRect());
9080}
9081function applyTranslation(c) {
9082 const oldPos = positionMap.get(c);
9083 const newPos = newPositionMap.get(c);
9084 const dx = oldPos.left - newPos.left;
9085 const dy = oldPos.top - newPos.top;
9086 if (dx || dy) {
9087 const s = c.el.style;
9088 s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
9089 s.transitionDuration = '0s';
9090 return c;
9091 }
9092}
9093function hasCSSTransform(el, root, moveClass) {
9094 // Detect whether an element with the move class applied has
9095 // CSS transitions. Since the element may be inside an entering
9096 // transition at this very moment, we make a clone of it and remove
9097 // all other transition classes applied to ensure only the move class
9098 // is applied.
9099 const clone = el.cloneNode();
9100 if (el._vtc) {
9101 el._vtc.forEach(cls => {
9102 cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
9103 });
9104 }
9105 moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
9106 clone.style.display = 'none';
9107 const container = (root.nodeType === 1
9108 ? root
9109 : root.parentNode);
9110 container.appendChild(clone);
9111 const { hasTransform } = getTransitionInfo(clone);
9112 container.removeChild(clone);
9113 return hasTransform;
9114}
9115
9116const getModelAssigner = (vnode) => {
9117 const fn = vnode.props['onUpdate:modelValue'];
9118 return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
9119};
9120function onCompositionStart(e) {
9121 e.target.composing = true;
9122}
9123function onCompositionEnd(e) {
9124 const target = e.target;
9125 if (target.composing) {
9126 target.composing = false;
9127 trigger$1(target, 'input');
9128 }
9129}
9130function trigger$1(el, type) {
9131 const e = document.createEvent('HTMLEvents');
9132 e.initEvent(type, true, true);
9133 el.dispatchEvent(e);
9134}
9135// We are exporting the v-model runtime directly as vnode hooks so that it can
9136// be tree-shaken in case v-model is never used.
9137const vModelText = {
9138 created(el, { modifiers: { lazy, trim, number } }, vnode) {
9139 el._assign = getModelAssigner(vnode);
9140 const castToNumber = number || el.type === 'number';
9141 addEventListener(el, lazy ? 'change' : 'input', e => {
9142 if (e.target.composing)
9143 return;
9144 let domValue = el.value;
9145 if (trim) {
9146 domValue = domValue.trim();
9147 }
9148 else if (castToNumber) {
9149 domValue = toNumber(domValue);
9150 }
9151 el._assign(domValue);
9152 });
9153 if (trim) {
9154 addEventListener(el, 'change', () => {
9155 el.value = el.value.trim();
9156 });
9157 }
9158 if (!lazy) {
9159 addEventListener(el, 'compositionstart', onCompositionStart);
9160 addEventListener(el, 'compositionend', onCompositionEnd);
9161 // Safari < 10.2 & UIWebView doesn't fire compositionend when
9162 // switching focus before confirming composition choice
9163 // this also fixes the issue where some browsers e.g. iOS Chrome
9164 // fires "change" instead of "input" on autocomplete.
9165 addEventListener(el, 'change', onCompositionEnd);
9166 }
9167 },
9168 // set value on mounted so it's after min/max for type="range"
9169 mounted(el, { value }) {
9170 el.value = value == null ? '' : value;
9171 },
9172 beforeUpdate(el, { value, modifiers: { trim, number } }, vnode) {
9173 el._assign = getModelAssigner(vnode);
9174 // avoid clearing unresolved text. #2302
9175 if (el.composing)
9176 return;
9177 if (document.activeElement === el) {
9178 if (trim && el.value.trim() === value) {
9179 return;
9180 }
9181 if ((number || el.type === 'number') && toNumber(el.value) === value) {
9182 return;
9183 }
9184 }
9185 const newValue = value == null ? '' : value;
9186 if (el.value !== newValue) {
9187 el.value = newValue;
9188 }
9189 }
9190};
9191const vModelCheckbox = {
9192 created(el, _, vnode) {
9193 el._assign = getModelAssigner(vnode);
9194 addEventListener(el, 'change', () => {
9195 const modelValue = el._modelValue;
9196 const elementValue = getValue(el);
9197 const checked = el.checked;
9198 const assign = el._assign;
9199 if (isArray(modelValue)) {
9200 const index = looseIndexOf(modelValue, elementValue);
9201 const found = index !== -1;
9202 if (checked && !found) {
9203 assign(modelValue.concat(elementValue));
9204 }
9205 else if (!checked && found) {
9206 const filtered = [...modelValue];
9207 filtered.splice(index, 1);
9208 assign(filtered);
9209 }
9210 }
9211 else if (isSet(modelValue)) {
9212 const cloned = new Set(modelValue);
9213 if (checked) {
9214 cloned.add(elementValue);
9215 }
9216 else {
9217 cloned.delete(elementValue);
9218 }
9219 assign(cloned);
9220 }
9221 else {
9222 assign(getCheckboxValue(el, checked));
9223 }
9224 });
9225 },
9226 // set initial checked on mount to wait for true-value/false-value
9227 mounted: setChecked,
9228 beforeUpdate(el, binding, vnode) {
9229 el._assign = getModelAssigner(vnode);
9230 setChecked(el, binding, vnode);
9231 }
9232};
9233function setChecked(el, { value, oldValue }, vnode) {
9234 el._modelValue = value;
9235 if (isArray(value)) {
9236 el.checked = looseIndexOf(value, vnode.props.value) > -1;
9237 }
9238 else if (isSet(value)) {
9239 el.checked = value.has(vnode.props.value);
9240 }
9241 else if (value !== oldValue) {
9242 el.checked = looseEqual(value, getCheckboxValue(el, true));
9243 }
9244}
9245const vModelRadio = {
9246 created(el, { value }, vnode) {
9247 el.checked = looseEqual(value, vnode.props.value);
9248 el._assign = getModelAssigner(vnode);
9249 addEventListener(el, 'change', () => {
9250 el._assign(getValue(el));
9251 });
9252 },
9253 beforeUpdate(el, { value, oldValue }, vnode) {
9254 el._assign = getModelAssigner(vnode);
9255 if (value !== oldValue) {
9256 el.checked = looseEqual(value, vnode.props.value);
9257 }
9258 }
9259};
9260const vModelSelect = {
9261 created(el, { value, modifiers: { number } }, vnode) {
9262 const isSetModel = isSet(value);
9263 addEventListener(el, 'change', () => {
9264 const selectedVal = Array.prototype.filter
9265 .call(el.options, (o) => o.selected)
9266 .map((o) => number ? toNumber(getValue(o)) : getValue(o));
9267 el._assign(el.multiple
9268 ? isSetModel
9269 ? new Set(selectedVal)
9270 : selectedVal
9271 : selectedVal[0]);
9272 });
9273 el._assign = getModelAssigner(vnode);
9274 },
9275 // set value in mounted & updated because <select> relies on its children
9276 // <option>s.
9277 mounted(el, { value }) {
9278 setSelected(el, value);
9279 },
9280 beforeUpdate(el, _binding, vnode) {
9281 el._assign = getModelAssigner(vnode);
9282 },
9283 updated(el, { value }) {
9284 setSelected(el, value);
9285 }
9286};
9287function setSelected(el, value) {
9288 const isMultiple = el.multiple;
9289 if (isMultiple && !isArray(value) && !isSet(value)) {
9290 warn(`<select multiple v-model> expects an Array or Set value for its binding, ` +
9291 `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
9292 return;
9293 }
9294 for (let i = 0, l = el.options.length; i < l; i++) {
9295 const option = el.options[i];
9296 const optionValue = getValue(option);
9297 if (isMultiple) {
9298 if (isArray(value)) {
9299 option.selected = looseIndexOf(value, optionValue) > -1;
9300 }
9301 else {
9302 option.selected = value.has(optionValue);
9303 }
9304 }
9305 else {
9306 if (looseEqual(getValue(option), value)) {
9307 el.selectedIndex = i;
9308 return;
9309 }
9310 }
9311 }
9312 if (!isMultiple) {
9313 el.selectedIndex = -1;
9314 }
9315}
9316// retrieve raw value set via :value bindings
9317function getValue(el) {
9318 return '_value' in el ? el._value : el.value;
9319}
9320// retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
9321function getCheckboxValue(el, checked) {
9322 const key = checked ? '_trueValue' : '_falseValue';
9323 return key in el ? el[key] : checked;
9324}
9325const vModelDynamic = {
9326 created(el, binding, vnode) {
9327 callModelHook(el, binding, vnode, null, 'created');
9328 },
9329 mounted(el, binding, vnode) {
9330 callModelHook(el, binding, vnode, null, 'mounted');
9331 },
9332 beforeUpdate(el, binding, vnode, prevVNode) {
9333 callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
9334 },
9335 updated(el, binding, vnode, prevVNode) {
9336 callModelHook(el, binding, vnode, prevVNode, 'updated');
9337 }
9338};
9339function callModelHook(el, binding, vnode, prevVNode, hook) {
9340 let modelToUse;
9341 switch (el.tagName) {
9342 case 'SELECT':
9343 modelToUse = vModelSelect;
9344 break;
9345 case 'TEXTAREA':
9346 modelToUse = vModelText;
9347 break;
9348 default:
9349 switch (vnode.props && vnode.props.type) {
9350 case 'checkbox':
9351 modelToUse = vModelCheckbox;
9352 break;
9353 case 'radio':
9354 modelToUse = vModelRadio;
9355 break;
9356 default:
9357 modelToUse = vModelText;
9358 }
9359 }
9360 const fn = modelToUse[hook];
9361 fn && fn(el, binding, vnode, prevVNode);
9362}
9363
9364const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
9365const modifierGuards = {
9366 stop: e => e.stopPropagation(),
9367 prevent: e => e.preventDefault(),
9368 self: e => e.target !== e.currentTarget,
9369 ctrl: e => !e.ctrlKey,
9370 shift: e => !e.shiftKey,
9371 alt: e => !e.altKey,
9372 meta: e => !e.metaKey,
9373 left: e => 'button' in e && e.button !== 0,
9374 middle: e => 'button' in e && e.button !== 1,
9375 right: e => 'button' in e && e.button !== 2,
9376 exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
9377};
9378/**
9379 * @private
9380 */
9381const withModifiers = (fn, modifiers) => {
9382 return (event, ...args) => {
9383 for (let i = 0; i < modifiers.length; i++) {
9384 const guard = modifierGuards[modifiers[i]];
9385 if (guard && guard(event, modifiers))
9386 return;
9387 }
9388 return fn(event, ...args);
9389 };
9390};
9391// Kept for 2.x compat.
9392// Note: IE11 compat for `spacebar` and `del` is removed for now.
9393const keyNames = {
9394 esc: 'escape',
9395 space: ' ',
9396 up: 'arrow-up',
9397 left: 'arrow-left',
9398 right: 'arrow-right',
9399 down: 'arrow-down',
9400 delete: 'backspace'
9401};
9402/**
9403 * @private
9404 */
9405const withKeys = (fn, modifiers) => {
9406 return (event) => {
9407 if (!('key' in event))
9408 return;
9409 const eventKey = hyphenate(event.key);
9410 if (
9411 // None of the provided key modifiers match the current event key
9412 !modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
9413 return;
9414 }
9415 return fn(event);
9416 };
9417};
9418
9419const vShow = {
9420 beforeMount(el, { value }, { transition }) {
9421 el._vod = el.style.display === 'none' ? '' : el.style.display;
9422 if (transition && value) {
9423 transition.beforeEnter(el);
9424 }
9425 else {
9426 setDisplay(el, value);
9427 }
9428 },
9429 mounted(el, { value }, { transition }) {
9430 if (transition && value) {
9431 transition.enter(el);
9432 }
9433 },
9434 updated(el, { value, oldValue }, { transition }) {
9435 if (!value === !oldValue)
9436 return;
9437 if (transition) {
9438 if (value) {
9439 transition.beforeEnter(el);
9440 setDisplay(el, true);
9441 transition.enter(el);
9442 }
9443 else {
9444 transition.leave(el, () => {
9445 setDisplay(el, false);
9446 });
9447 }
9448 }
9449 else {
9450 setDisplay(el, value);
9451 }
9452 },
9453 beforeUnmount(el, { value }) {
9454 setDisplay(el, value);
9455 }
9456};
9457function setDisplay(el, value) {
9458 el.style.display = value ? el._vod : 'none';
9459}
9460
9461const rendererOptions = extend({ patchProp, forcePatchProp }, nodeOps);
9462// lazy create the renderer - this makes core renderer logic tree-shakable
9463// in case the user only imports reactivity utilities from Vue.
9464let renderer;
9465let enabledHydration = false;
9466function ensureRenderer() {
9467 return renderer || (renderer = createRenderer(rendererOptions));
9468}
9469function ensureHydrationRenderer() {
9470 renderer = enabledHydration
9471 ? renderer
9472 : createHydrationRenderer(rendererOptions);
9473 enabledHydration = true;
9474 return renderer;
9475}
9476// use explicit type casts here to avoid import() calls in rolled-up d.ts
9477const render = ((...args) => {
9478 ensureRenderer().render(...args);
9479});
9480const hydrate = ((...args) => {
9481 ensureHydrationRenderer().hydrate(...args);
9482});
9483const createApp = ((...args) => {
9484 const app = ensureRenderer().createApp(...args);
9485 {
9486 injectNativeTagCheck(app);
9487 injectCustomElementCheck(app);
9488 }
9489 const { mount } = app;
9490 app.mount = (containerOrSelector) => {
9491 const container = normalizeContainer(containerOrSelector);
9492 if (!container)
9493 return;
9494 const component = app._component;
9495 if (!isFunction(component) && !component.render && !component.template) {
9496 component.template = container.innerHTML;
9497 }
9498 // clear content before mounting
9499 container.innerHTML = '';
9500 const proxy = mount(container, false, container instanceof SVGElement);
9501 if (container instanceof Element) {
9502 container.removeAttribute('v-cloak');
9503 container.setAttribute('data-v-app', '');
9504 }
9505 return proxy;
9506 };
9507 return app;
9508});
9509const createSSRApp = ((...args) => {
9510 const app = ensureHydrationRenderer().createApp(...args);
9511 {
9512 injectNativeTagCheck(app);
9513 injectCustomElementCheck(app);
9514 }
9515 const { mount } = app;
9516 app.mount = (containerOrSelector) => {
9517 const container = normalizeContainer(containerOrSelector);
9518 if (container) {
9519 return mount(container, true, container instanceof SVGElement);
9520 }
9521 };
9522 return app;
9523});
9524function injectNativeTagCheck(app) {
9525 // Inject `isNativeTag`
9526 // this is used for component name validation (dev only)
9527 Object.defineProperty(app.config, 'isNativeTag', {
9528 value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
9529 writable: false
9530 });
9531}
9532// dev only
9533function injectCustomElementCheck(app) {
9534 if (isRuntimeOnly()) {
9535 const value = app.config.isCustomElement;
9536 Object.defineProperty(app.config, 'isCustomElement', {
9537 get() {
9538 return value;
9539 },
9540 set() {
9541 warn(`The \`isCustomElement\` config option is only respected when using the runtime compiler.` +
9542 `If you are using the runtime-only build, \`isCustomElement\` must be passed to \`@vue/compiler-dom\` in the build setup instead` +
9543 `- for example, via the \`compilerOptions\` option in vue-loader: https://vue-loader.vuejs.org/options.html#compileroptions.`);
9544 }
9545 });
9546 }
9547}
9548function normalizeContainer(container) {
9549 if (isString(container)) {
9550 const res = document.querySelector(container);
9551 if (!res) {
9552 warn(`Failed to mount app: mount target selector "${container}" returned null.`);
9553 }
9554 return res;
9555 }
9556 if (container instanceof window.ShadowRoot &&
9557 container.mode === 'closed') {
9558 warn(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`);
9559 }
9560 return container;
9561}
9562
9563var runtimeDom = /*#__PURE__*/Object.freeze({
9564 __proto__: null,
9565 render: render,
9566 hydrate: hydrate,
9567 createApp: createApp,
9568 createSSRApp: createSSRApp,
9569 useCssModule: useCssModule,
9570 useCssVars: useCssVars,
9571 Transition: Transition,
9572 TransitionGroup: TransitionGroup,
9573 vModelText: vModelText,
9574 vModelCheckbox: vModelCheckbox,
9575 vModelRadio: vModelRadio,
9576 vModelSelect: vModelSelect,
9577 vModelDynamic: vModelDynamic,
9578 withModifiers: withModifiers,
9579 withKeys: withKeys,
9580 vShow: vShow,
9581 reactive: reactive,
9582 ref: ref,
9583 readonly: readonly,
9584 unref: unref,
9585 proxyRefs: proxyRefs,
9586 isRef: isRef,
9587 toRef: toRef,
9588 toRefs: toRefs,
9589 isProxy: isProxy,
9590 isReactive: isReactive,
9591 isReadonly: isReadonly,
9592 customRef: customRef,
9593 triggerRef: triggerRef,
9594 shallowRef: shallowRef,
9595 shallowReactive: shallowReactive,
9596 shallowReadonly: shallowReadonly,
9597 markRaw: markRaw,
9598 toRaw: toRaw,
9599 computed: computed$1,
9600 watch: watch,
9601 watchEffect: watchEffect,
9602 onBeforeMount: onBeforeMount,
9603 onMounted: onMounted,
9604 onBeforeUpdate: onBeforeUpdate,
9605 onUpdated: onUpdated,
9606 onBeforeUnmount: onBeforeUnmount,
9607 onUnmounted: onUnmounted,
9608 onActivated: onActivated,
9609 onDeactivated: onDeactivated,
9610 onRenderTracked: onRenderTracked,
9611 onRenderTriggered: onRenderTriggered,
9612 onErrorCaptured: onErrorCaptured,
9613 provide: provide,
9614 inject: inject,
9615 nextTick: nextTick,
9616 defineComponent: defineComponent,
9617 defineAsyncComponent: defineAsyncComponent,
9618 defineProps: defineProps,
9619 defineEmit: defineEmit,
9620 useContext: useContext,
9621 getCurrentInstance: getCurrentInstance,
9622 h: h,
9623 createVNode: createVNode,
9624 cloneVNode: cloneVNode,
9625 mergeProps: mergeProps,
9626 isVNode: isVNode,
9627 Fragment: Fragment,
9628 Text: Text,
9629 Comment: Comment,
9630 Static: Static,
9631 Teleport: Teleport,
9632 Suspense: Suspense,
9633 KeepAlive: KeepAlive,
9634 BaseTransition: BaseTransition,
9635 withDirectives: withDirectives,
9636 useSSRContext: useSSRContext,
9637 ssrContextKey: ssrContextKey,
9638 createRenderer: createRenderer,
9639 createHydrationRenderer: createHydrationRenderer,
9640 queuePostFlushCb: queuePostFlushCb,
9641 warn: warn,
9642 handleError: handleError,
9643 callWithErrorHandling: callWithErrorHandling,
9644 callWithAsyncErrorHandling: callWithAsyncErrorHandling,
9645 resolveComponent: resolveComponent,
9646 resolveDirective: resolveDirective,
9647 resolveDynamicComponent: resolveDynamicComponent,
9648 registerRuntimeCompiler: registerRuntimeCompiler,
9649 isRuntimeOnly: isRuntimeOnly,
9650 useTransitionState: useTransitionState,
9651 resolveTransitionHooks: resolveTransitionHooks,
9652 setTransitionHooks: setTransitionHooks,
9653 getTransitionRawChildren: getTransitionRawChildren,
9654 initCustomFormatter: initCustomFormatter,
9655 get devtools () { return devtools; },
9656 setDevtoolsHook: setDevtoolsHook,
9657 withCtx: withCtx,
9658 pushScopeId: pushScopeId,
9659 popScopeId: popScopeId,
9660 withScopeId: withScopeId,
9661 renderList: renderList,
9662 toHandlers: toHandlers,
9663 renderSlot: renderSlot,
9664 createSlots: createSlots,
9665 openBlock: openBlock,
9666 createBlock: createBlock,
9667 setBlockTracking: setBlockTracking,
9668 createTextVNode: createTextVNode,
9669 createCommentVNode: createCommentVNode,
9670 createStaticVNode: createStaticVNode,
9671 toDisplayString: toDisplayString,
9672 camelize: camelize,
9673 capitalize: capitalize,
9674 toHandlerKey: toHandlerKey,
9675 transformVNodeArgs: transformVNodeArgs,
9676 version: version,
9677 ssrUtils: ssrUtils
9678});
9679
9680function initDev() {
9681 {
9682 {
9683 console.info(`You are running a development build of Vue.\n` +
9684 `Make sure to use the production build (*.prod.js) when deploying for production.`);
9685 }
9686 initCustomFormatter();
9687 }
9688}
9689
9690function defaultOnError(error) {
9691 throw error;
9692}
9693function createCompilerError(code, loc, messages, additionalMessage) {
9694 const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
9695 ;
9696 const error = new SyntaxError(String(msg));
9697 error.code = code;
9698 error.loc = loc;
9699 return error;
9700}
9701const errorMessages = {
9702 // parse errors
9703 [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
9704 [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
9705 [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
9706 [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
9707 [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
9708 [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
9709 [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
9710 [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
9711 [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
9712 [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
9713 [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
9714 [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
9715 [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
9716 [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
9717 [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
9718 [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
9719 [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
9720 [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
9721 [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
9722 [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
9723 [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
9724 [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
9725 // Vue-specific parse errors
9726 [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
9727 [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
9728 [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
9729 [26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
9730 'Note that dynamic directive argument cannot contain spaces.',
9731 // transform errors
9732 [27 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
9733 [28 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
9734 [29 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if.`,
9735 [30 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
9736 [31 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
9737 [32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
9738 [33 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
9739 [34 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
9740 [35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
9741 [36 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
9742 `When there are multiple named slots, all slots should use <template> ` +
9743 `syntax to avoid scope ambiguity.`,
9744 [37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
9745 [38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
9746 `default slot. These children will be ignored.`,
9747 [39 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
9748 [40 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
9749 [41 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
9750 [42 /* X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
9751 [43 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
9752 [44 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
9753 // generic errors
9754 [45 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
9755 [46 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
9756 [47 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
9757 [48 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`
9758};
9759
9760const FRAGMENT = Symbol(`Fragment` );
9761const TELEPORT = Symbol(`Teleport` );
9762const SUSPENSE = Symbol(`Suspense` );
9763const KEEP_ALIVE = Symbol(`KeepAlive` );
9764const BASE_TRANSITION = Symbol(`BaseTransition` );
9765const OPEN_BLOCK = Symbol(`openBlock` );
9766const CREATE_BLOCK = Symbol(`createBlock` );
9767const CREATE_VNODE = Symbol(`createVNode` );
9768const CREATE_COMMENT = Symbol(`createCommentVNode` );
9769const CREATE_TEXT = Symbol(`createTextVNode` );
9770const CREATE_STATIC = Symbol(`createStaticVNode` );
9771const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
9772const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
9773const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
9774const WITH_DIRECTIVES = Symbol(`withDirectives` );
9775const RENDER_LIST = Symbol(`renderList` );
9776const RENDER_SLOT = Symbol(`renderSlot` );
9777const CREATE_SLOTS = Symbol(`createSlots` );
9778const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
9779const MERGE_PROPS = Symbol(`mergeProps` );
9780const TO_HANDLERS = Symbol(`toHandlers` );
9781const CAMELIZE = Symbol(`camelize` );
9782const CAPITALIZE = Symbol(`capitalize` );
9783const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
9784const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
9785const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
9786const POP_SCOPE_ID = Symbol(`popScopeId` );
9787const WITH_SCOPE_ID = Symbol(`withScopeId` );
9788const WITH_CTX = Symbol(`withCtx` );
9789const UNREF = Symbol(`unref` );
9790const IS_REF = Symbol(`isRef` );
9791// Name mapping for runtime helpers that need to be imported from 'vue' in
9792// generated code. Make sure these are correctly exported in the runtime!
9793// Using `any` here because TS doesn't allow symbols as index type.
9794const helperNameMap = {
9795 [FRAGMENT]: `Fragment`,
9796 [TELEPORT]: `Teleport`,
9797 [SUSPENSE]: `Suspense`,
9798 [KEEP_ALIVE]: `KeepAlive`,
9799 [BASE_TRANSITION]: `BaseTransition`,
9800 [OPEN_BLOCK]: `openBlock`,
9801 [CREATE_BLOCK]: `createBlock`,
9802 [CREATE_VNODE]: `createVNode`,
9803 [CREATE_COMMENT]: `createCommentVNode`,
9804 [CREATE_TEXT]: `createTextVNode`,
9805 [CREATE_STATIC]: `createStaticVNode`,
9806 [RESOLVE_COMPONENT]: `resolveComponent`,
9807 [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
9808 [RESOLVE_DIRECTIVE]: `resolveDirective`,
9809 [WITH_DIRECTIVES]: `withDirectives`,
9810 [RENDER_LIST]: `renderList`,
9811 [RENDER_SLOT]: `renderSlot`,
9812 [CREATE_SLOTS]: `createSlots`,
9813 [TO_DISPLAY_STRING]: `toDisplayString`,
9814 [MERGE_PROPS]: `mergeProps`,
9815 [TO_HANDLERS]: `toHandlers`,
9816 [CAMELIZE]: `camelize`,
9817 [CAPITALIZE]: `capitalize`,
9818 [TO_HANDLER_KEY]: `toHandlerKey`,
9819 [SET_BLOCK_TRACKING]: `setBlockTracking`,
9820 [PUSH_SCOPE_ID]: `pushScopeId`,
9821 [POP_SCOPE_ID]: `popScopeId`,
9822 [WITH_SCOPE_ID]: `withScopeId`,
9823 [WITH_CTX]: `withCtx`,
9824 [UNREF]: `unref`,
9825 [IS_REF]: `isRef`
9826};
9827function registerRuntimeHelpers(helpers) {
9828 Object.getOwnPropertySymbols(helpers).forEach(s => {
9829 helperNameMap[s] = helpers[s];
9830 });
9831}
9832
9833// AST Utilities ---------------------------------------------------------------
9834// Some expressions, e.g. sequence and conditional expressions, are never
9835// associated with template nodes, so their source locations are just a stub.
9836// Container types like CompoundExpression also don't need a real location.
9837const locStub = {
9838 source: '',
9839 start: { line: 1, column: 1, offset: 0 },
9840 end: { line: 1, column: 1, offset: 0 }
9841};
9842function createRoot(children, loc = locStub) {
9843 return {
9844 type: 0 /* ROOT */,
9845 children,
9846 helpers: [],
9847 components: [],
9848 directives: [],
9849 hoists: [],
9850 imports: [],
9851 cached: 0,
9852 temps: 0,
9853 codegenNode: undefined,
9854 loc
9855 };
9856}
9857function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, loc = locStub) {
9858 if (context) {
9859 if (isBlock) {
9860 context.helper(OPEN_BLOCK);
9861 context.helper(CREATE_BLOCK);
9862 }
9863 else {
9864 context.helper(CREATE_VNODE);
9865 }
9866 if (directives) {
9867 context.helper(WITH_DIRECTIVES);
9868 }
9869 }
9870 return {
9871 type: 13 /* VNODE_CALL */,
9872 tag,
9873 props,
9874 children,
9875 patchFlag,
9876 dynamicProps,
9877 directives,
9878 isBlock,
9879 disableTracking,
9880 loc
9881 };
9882}
9883function createArrayExpression(elements, loc = locStub) {
9884 return {
9885 type: 17 /* JS_ARRAY_EXPRESSION */,
9886 loc,
9887 elements
9888 };
9889}
9890function createObjectExpression(properties, loc = locStub) {
9891 return {
9892 type: 15 /* JS_OBJECT_EXPRESSION */,
9893 loc,
9894 properties
9895 };
9896}
9897function createObjectProperty(key, value) {
9898 return {
9899 type: 16 /* JS_PROPERTY */,
9900 loc: locStub,
9901 key: isString(key) ? createSimpleExpression(key, true) : key,
9902 value
9903 };
9904}
9905function createSimpleExpression(content, isStatic, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
9906 return {
9907 type: 4 /* SIMPLE_EXPRESSION */,
9908 loc,
9909 content,
9910 isStatic,
9911 constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
9912 };
9913}
9914function createCompoundExpression(children, loc = locStub) {
9915 return {
9916 type: 8 /* COMPOUND_EXPRESSION */,
9917 loc,
9918 children
9919 };
9920}
9921function createCallExpression(callee, args = [], loc = locStub) {
9922 return {
9923 type: 14 /* JS_CALL_EXPRESSION */,
9924 loc,
9925 callee,
9926 arguments: args
9927 };
9928}
9929function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
9930 return {
9931 type: 18 /* JS_FUNCTION_EXPRESSION */,
9932 params,
9933 returns,
9934 newline,
9935 isSlot,
9936 loc
9937 };
9938}
9939function createConditionalExpression(test, consequent, alternate, newline = true) {
9940 return {
9941 type: 19 /* JS_CONDITIONAL_EXPRESSION */,
9942 test,
9943 consequent,
9944 alternate,
9945 newline,
9946 loc: locStub
9947 };
9948}
9949function createCacheExpression(index, value, isVNode = false) {
9950 return {
9951 type: 20 /* JS_CACHE_EXPRESSION */,
9952 index,
9953 value,
9954 isVNode,
9955 loc: locStub
9956 };
9957}
9958
9959const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
9960const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
9961function isCoreComponent(tag) {
9962 if (isBuiltInType(tag, 'Teleport')) {
9963 return TELEPORT;
9964 }
9965 else if (isBuiltInType(tag, 'Suspense')) {
9966 return SUSPENSE;
9967 }
9968 else if (isBuiltInType(tag, 'KeepAlive')) {
9969 return KEEP_ALIVE;
9970 }
9971 else if (isBuiltInType(tag, 'BaseTransition')) {
9972 return BASE_TRANSITION;
9973 }
9974}
9975const nonIdentifierRE = /^\d|[^\$\w]/;
9976const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
9977const memberExpRE = /^[A-Za-z_$\xA0-\uFFFF][\w$\xA0-\uFFFF]*(?:\s*\.\s*[A-Za-z_$\xA0-\uFFFF][\w$\xA0-\uFFFF]*|\[[^\]]+\])*$/;
9978const isMemberExpression = (path) => {
9979 if (!path)
9980 return false;
9981 return memberExpRE.test(path.trim());
9982};
9983function getInnerRange(loc, offset, length) {
9984 const source = loc.source.substr(offset, length);
9985 const newLoc = {
9986 source,
9987 start: advancePositionWithClone(loc.start, loc.source, offset),
9988 end: loc.end
9989 };
9990 if (length != null) {
9991 newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
9992 }
9993 return newLoc;
9994}
9995function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
9996 return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
9997}
9998// advance by mutation without cloning (for performance reasons), since this
9999// gets called a lot in the parser
10000function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
10001 let linesCount = 0;
10002 let lastNewLinePos = -1;
10003 for (let i = 0; i < numberOfCharacters; i++) {
10004 if (source.charCodeAt(i) === 10 /* newline char code */) {
10005 linesCount++;
10006 lastNewLinePos = i;
10007 }
10008 }
10009 pos.offset += numberOfCharacters;
10010 pos.line += linesCount;
10011 pos.column =
10012 lastNewLinePos === -1
10013 ? pos.column + numberOfCharacters
10014 : numberOfCharacters - lastNewLinePos;
10015 return pos;
10016}
10017function assert(condition, msg) {
10018 /* istanbul ignore if */
10019 if (!condition) {
10020 throw new Error(msg || `unexpected compiler condition`);
10021 }
10022}
10023function findDir(node, name, allowEmpty = false) {
10024 for (let i = 0; i < node.props.length; i++) {
10025 const p = node.props[i];
10026 if (p.type === 7 /* DIRECTIVE */ &&
10027 (allowEmpty || p.exp) &&
10028 (isString(name) ? p.name === name : name.test(p.name))) {
10029 return p;
10030 }
10031 }
10032}
10033function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
10034 for (let i = 0; i < node.props.length; i++) {
10035 const p = node.props[i];
10036 if (p.type === 6 /* ATTRIBUTE */) {
10037 if (dynamicOnly)
10038 continue;
10039 if (p.name === name && (p.value || allowEmpty)) {
10040 return p;
10041 }
10042 }
10043 else if (p.name === 'bind' &&
10044 (p.exp || allowEmpty) &&
10045 isBindKey(p.arg, name)) {
10046 return p;
10047 }
10048 }
10049}
10050function isBindKey(arg, name) {
10051 return !!(arg && isStaticExp(arg) && arg.content === name);
10052}
10053function hasDynamicKeyVBind(node) {
10054 return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
10055 p.name === 'bind' &&
10056 (!p.arg || // v-bind="obj"
10057 p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
10058 !p.arg.isStatic) // v-bind:[foo]
10059 );
10060}
10061function isText(node) {
10062 return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
10063}
10064function isVSlot(p) {
10065 return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
10066}
10067function isTemplateNode(node) {
10068 return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
10069}
10070function isSlotOutlet(node) {
10071 return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
10072}
10073function injectProp(node, prop, context) {
10074 let propsWithInjection;
10075 const props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
10076 if (props == null || isString(props)) {
10077 propsWithInjection = createObjectExpression([prop]);
10078 }
10079 else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
10080 // merged props... add ours
10081 // only inject key to object literal if it's the first argument so that
10082 // if doesn't override user provided keys
10083 const first = props.arguments[0];
10084 if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
10085 first.properties.unshift(prop);
10086 }
10087 else {
10088 if (props.callee === TO_HANDLERS) {
10089 // #2366
10090 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
10091 createObjectExpression([prop]),
10092 props
10093 ]);
10094 }
10095 else {
10096 props.arguments.unshift(createObjectExpression([prop]));
10097 }
10098 }
10099 !propsWithInjection && (propsWithInjection = props);
10100 }
10101 else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
10102 let alreadyExists = false;
10103 // check existing key to avoid overriding user provided keys
10104 if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
10105 const propKeyName = prop.key.content;
10106 alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
10107 p.key.content === propKeyName);
10108 }
10109 if (!alreadyExists) {
10110 props.properties.unshift(prop);
10111 }
10112 propsWithInjection = props;
10113 }
10114 else {
10115 // single v-bind with expression, return a merged replacement
10116 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
10117 createObjectExpression([prop]),
10118 props
10119 ]);
10120 }
10121 if (node.type === 13 /* VNODE_CALL */) {
10122 node.props = propsWithInjection;
10123 }
10124 else {
10125 node.arguments[2] = propsWithInjection;
10126 }
10127}
10128function toValidAssetId(name, type) {
10129 return `_${type}_${name.replace(/[^\w]/g, '_')}`;
10130}
10131
10132// The default decoder only provides escapes for characters reserved as part of
10133// the template syntax, and is only used if the custom renderer did not provide
10134// a platform-specific decoder.
10135const decodeRE = /&(gt|lt|amp|apos|quot);/g;
10136const decodeMap = {
10137 gt: '>',
10138 lt: '<',
10139 amp: '&',
10140 apos: "'",
10141 quot: '"'
10142};
10143const defaultParserOptions = {
10144 delimiters: [`{{`, `}}`],
10145 getNamespace: () => 0 /* HTML */,
10146 getTextMode: () => 0 /* DATA */,
10147 isVoidTag: NO,
10148 isPreTag: NO,
10149 isCustomElement: NO,
10150 decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
10151 onError: defaultOnError,
10152 comments: false
10153};
10154function baseParse(content, options = {}) {
10155 const context = createParserContext(content, options);
10156 const start = getCursor(context);
10157 return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
10158}
10159function createParserContext(content, rawOptions) {
10160 const options = extend({}, defaultParserOptions);
10161 for (const key in rawOptions) {
10162 // @ts-ignore
10163 options[key] = rawOptions[key] || defaultParserOptions[key];
10164 }
10165 return {
10166 options,
10167 column: 1,
10168 line: 1,
10169 offset: 0,
10170 originalSource: content,
10171 source: content,
10172 inPre: false,
10173 inVPre: false
10174 };
10175}
10176function parseChildren(context, mode, ancestors) {
10177 const parent = last(ancestors);
10178 const ns = parent ? parent.ns : 0 /* HTML */;
10179 const nodes = [];
10180 while (!isEnd(context, mode, ancestors)) {
10181 const s = context.source;
10182 let node = undefined;
10183 if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
10184 if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
10185 // '{{'
10186 node = parseInterpolation(context, mode);
10187 }
10188 else if (mode === 0 /* DATA */ && s[0] === '<') {
10189 // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
10190 if (s.length === 1) {
10191 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
10192 }
10193 else if (s[1] === '!') {
10194 // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
10195 if (startsWith(s, '<!--')) {
10196 node = parseComment(context);
10197 }
10198 else if (startsWith(s, '<!DOCTYPE')) {
10199 // Ignore DOCTYPE by a limitation.
10200 node = parseBogusComment(context);
10201 }
10202 else if (startsWith(s, '<![CDATA[')) {
10203 if (ns !== 0 /* HTML */) {
10204 node = parseCDATA(context, ancestors);
10205 }
10206 else {
10207 emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
10208 node = parseBogusComment(context);
10209 }
10210 }
10211 else {
10212 emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
10213 node = parseBogusComment(context);
10214 }
10215 }
10216 else if (s[1] === '/') {
10217 // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
10218 if (s.length === 2) {
10219 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
10220 }
10221 else if (s[2] === '>') {
10222 emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
10223 advanceBy(context, 3);
10224 continue;
10225 }
10226 else if (/[a-z]/i.test(s[2])) {
10227 emitError(context, 23 /* X_INVALID_END_TAG */);
10228 parseTag(context, 1 /* End */, parent);
10229 continue;
10230 }
10231 else {
10232 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
10233 node = parseBogusComment(context);
10234 }
10235 }
10236 else if (/[a-z]/i.test(s[1])) {
10237 node = parseElement(context, ancestors);
10238 }
10239 else if (s[1] === '?') {
10240 emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
10241 node = parseBogusComment(context);
10242 }
10243 else {
10244 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
10245 }
10246 }
10247 }
10248 if (!node) {
10249 node = parseText(context, mode);
10250 }
10251 if (isArray(node)) {
10252 for (let i = 0; i < node.length; i++) {
10253 pushNode(nodes, node[i]);
10254 }
10255 }
10256 else {
10257 pushNode(nodes, node);
10258 }
10259 }
10260 // Whitespace management for more efficient output
10261 // (same as v2 whitespace: 'condense')
10262 let removedWhitespace = false;
10263 if (mode !== 2 /* RAWTEXT */ && mode !== 1 /* RCDATA */) {
10264 for (let i = 0; i < nodes.length; i++) {
10265 const node = nodes[i];
10266 if (!context.inPre && node.type === 2 /* TEXT */) {
10267 if (!/[^\t\r\n\f ]/.test(node.content)) {
10268 const prev = nodes[i - 1];
10269 const next = nodes[i + 1];
10270 // If:
10271 // - the whitespace is the first or last node, or:
10272 // - the whitespace is adjacent to a comment, or:
10273 // - the whitespace is between two elements AND contains newline
10274 // Then the whitespace is ignored.
10275 if (!prev ||
10276 !next ||
10277 prev.type === 3 /* COMMENT */ ||
10278 next.type === 3 /* COMMENT */ ||
10279 (prev.type === 1 /* ELEMENT */ &&
10280 next.type === 1 /* ELEMENT */ &&
10281 /[\r\n]/.test(node.content))) {
10282 removedWhitespace = true;
10283 nodes[i] = null;
10284 }
10285 else {
10286 // Otherwise, condensed consecutive whitespace inside the text
10287 // down to a single space
10288 node.content = ' ';
10289 }
10290 }
10291 else {
10292 node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
10293 }
10294 }
10295 }
10296 if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
10297 // remove leading newline per html spec
10298 // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
10299 const first = nodes[0];
10300 if (first && first.type === 2 /* TEXT */) {
10301 first.content = first.content.replace(/^\r?\n/, '');
10302 }
10303 }
10304 }
10305 return removedWhitespace ? nodes.filter(Boolean) : nodes;
10306}
10307function pushNode(nodes, node) {
10308 if (node.type === 2 /* TEXT */) {
10309 const prev = last(nodes);
10310 // Merge if both this and the previous node are text and those are
10311 // consecutive. This happens for cases like "a < b".
10312 if (prev &&
10313 prev.type === 2 /* TEXT */ &&
10314 prev.loc.end.offset === node.loc.start.offset) {
10315 prev.content += node.content;
10316 prev.loc.end = node.loc.end;
10317 prev.loc.source += node.loc.source;
10318 return;
10319 }
10320 }
10321 nodes.push(node);
10322}
10323function parseCDATA(context, ancestors) {
10324 advanceBy(context, 9);
10325 const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
10326 if (context.source.length === 0) {
10327 emitError(context, 6 /* EOF_IN_CDATA */);
10328 }
10329 else {
10330 advanceBy(context, 3);
10331 }
10332 return nodes;
10333}
10334function parseComment(context) {
10335 const start = getCursor(context);
10336 let content;
10337 // Regular comment.
10338 const match = /--(\!)?>/.exec(context.source);
10339 if (!match) {
10340 content = context.source.slice(4);
10341 advanceBy(context, context.source.length);
10342 emitError(context, 7 /* EOF_IN_COMMENT */);
10343 }
10344 else {
10345 if (match.index <= 3) {
10346 emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
10347 }
10348 if (match[1]) {
10349 emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
10350 }
10351 content = context.source.slice(4, match.index);
10352 // Advancing with reporting nested comments.
10353 const s = context.source.slice(0, match.index);
10354 let prevIndex = 1, nestedIndex = 0;
10355 while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
10356 advanceBy(context, nestedIndex - prevIndex + 1);
10357 if (nestedIndex + 4 < s.length) {
10358 emitError(context, 16 /* NESTED_COMMENT */);
10359 }
10360 prevIndex = nestedIndex + 1;
10361 }
10362 advanceBy(context, match.index + match[0].length - prevIndex + 1);
10363 }
10364 return {
10365 type: 3 /* COMMENT */,
10366 content,
10367 loc: getSelection(context, start)
10368 };
10369}
10370function parseBogusComment(context) {
10371 const start = getCursor(context);
10372 const contentStart = context.source[1] === '?' ? 1 : 2;
10373 let content;
10374 const closeIndex = context.source.indexOf('>');
10375 if (closeIndex === -1) {
10376 content = context.source.slice(contentStart);
10377 advanceBy(context, context.source.length);
10378 }
10379 else {
10380 content = context.source.slice(contentStart, closeIndex);
10381 advanceBy(context, closeIndex + 1);
10382 }
10383 return {
10384 type: 3 /* COMMENT */,
10385 content,
10386 loc: getSelection(context, start)
10387 };
10388}
10389function parseElement(context, ancestors) {
10390 // Start tag.
10391 const wasInPre = context.inPre;
10392 const wasInVPre = context.inVPre;
10393 const parent = last(ancestors);
10394 const element = parseTag(context, 0 /* Start */, parent);
10395 const isPreBoundary = context.inPre && !wasInPre;
10396 const isVPreBoundary = context.inVPre && !wasInVPre;
10397 if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
10398 return element;
10399 }
10400 // Children.
10401 ancestors.push(element);
10402 const mode = context.options.getTextMode(element, parent);
10403 const children = parseChildren(context, mode, ancestors);
10404 ancestors.pop();
10405 element.children = children;
10406 // End tag.
10407 if (startsWithEndTagOpen(context.source, element.tag)) {
10408 parseTag(context, 1 /* End */, parent);
10409 }
10410 else {
10411 emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
10412 if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
10413 const first = children[0];
10414 if (first && startsWith(first.loc.source, '<!--')) {
10415 emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
10416 }
10417 }
10418 }
10419 element.loc = getSelection(context, element.loc.start);
10420 if (isPreBoundary) {
10421 context.inPre = false;
10422 }
10423 if (isVPreBoundary) {
10424 context.inVPre = false;
10425 }
10426 return element;
10427}
10428const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
10429/**
10430 * Parse a tag (E.g. `<div id=a>`) with that type (start tag or end tag).
10431 */
10432function parseTag(context, type, parent) {
10433 // Tag open.
10434 const start = getCursor(context);
10435 const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
10436 const tag = match[1];
10437 const ns = context.options.getNamespace(tag, parent);
10438 advanceBy(context, match[0].length);
10439 advanceSpaces(context);
10440 // save current state in case we need to re-parse attributes with v-pre
10441 const cursor = getCursor(context);
10442 const currentSource = context.source;
10443 // Attributes.
10444 let props = parseAttributes(context, type);
10445 // check <pre> tag
10446 if (context.options.isPreTag(tag)) {
10447 context.inPre = true;
10448 }
10449 // check v-pre
10450 if (!context.inVPre &&
10451 props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
10452 context.inVPre = true;
10453 // reset context
10454 extend(context, cursor);
10455 context.source = currentSource;
10456 // re-parse attrs and filter out v-pre itself
10457 props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
10458 }
10459 // Tag close.
10460 let isSelfClosing = false;
10461 if (context.source.length === 0) {
10462 emitError(context, 9 /* EOF_IN_TAG */);
10463 }
10464 else {
10465 isSelfClosing = startsWith(context.source, '/>');
10466 if (type === 1 /* End */ && isSelfClosing) {
10467 emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
10468 }
10469 advanceBy(context, isSelfClosing ? 2 : 1);
10470 }
10471 let tagType = 0 /* ELEMENT */;
10472 const options = context.options;
10473 if (!context.inVPre && !options.isCustomElement(tag)) {
10474 const hasVIs = props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'is');
10475 if (options.isNativeTag && !hasVIs) {
10476 if (!options.isNativeTag(tag))
10477 tagType = 1 /* COMPONENT */;
10478 }
10479 else if (hasVIs ||
10480 isCoreComponent(tag) ||
10481 (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
10482 /^[A-Z]/.test(tag) ||
10483 tag === 'component') {
10484 tagType = 1 /* COMPONENT */;
10485 }
10486 if (tag === 'slot') {
10487 tagType = 2 /* SLOT */;
10488 }
10489 else if (tag === 'template' &&
10490 props.some(p => {
10491 return (p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name));
10492 })) {
10493 tagType = 3 /* TEMPLATE */;
10494 }
10495 }
10496 return {
10497 type: 1 /* ELEMENT */,
10498 ns,
10499 tag,
10500 tagType,
10501 props,
10502 isSelfClosing,
10503 children: [],
10504 loc: getSelection(context, start),
10505 codegenNode: undefined // to be created during transform phase
10506 };
10507}
10508function parseAttributes(context, type) {
10509 const props = [];
10510 const attributeNames = new Set();
10511 while (context.source.length > 0 &&
10512 !startsWith(context.source, '>') &&
10513 !startsWith(context.source, '/>')) {
10514 if (startsWith(context.source, '/')) {
10515 emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
10516 advanceBy(context, 1);
10517 advanceSpaces(context);
10518 continue;
10519 }
10520 if (type === 1 /* End */) {
10521 emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
10522 }
10523 const attr = parseAttribute(context, attributeNames);
10524 if (type === 0 /* Start */) {
10525 props.push(attr);
10526 }
10527 if (/^[^\t\r\n\f />]/.test(context.source)) {
10528 emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
10529 }
10530 advanceSpaces(context);
10531 }
10532 return props;
10533}
10534function parseAttribute(context, nameSet) {
10535 // Name.
10536 const start = getCursor(context);
10537 const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
10538 const name = match[0];
10539 if (nameSet.has(name)) {
10540 emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
10541 }
10542 nameSet.add(name);
10543 if (name[0] === '=') {
10544 emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
10545 }
10546 {
10547 const pattern = /["'<]/g;
10548 let m;
10549 while ((m = pattern.exec(name))) {
10550 emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
10551 }
10552 }
10553 advanceBy(context, name.length);
10554 // Value
10555 let value = undefined;
10556 if (/^[\t\r\n\f ]*=/.test(context.source)) {
10557 advanceSpaces(context);
10558 advanceBy(context, 1);
10559 advanceSpaces(context);
10560 value = parseAttributeValue(context);
10561 if (!value) {
10562 emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
10563 }
10564 }
10565 const loc = getSelection(context, start);
10566 if (!context.inVPre && /^(v-|:|@|#)/.test(name)) {
10567 const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
10568 const dirName = match[1] ||
10569 (startsWith(name, ':') ? 'bind' : startsWith(name, '@') ? 'on' : 'slot');
10570 let arg;
10571 if (match[2]) {
10572 const isSlot = dirName === 'slot';
10573 const startOffset = name.lastIndexOf(match[2]);
10574 const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
10575 let content = match[2];
10576 let isStatic = true;
10577 if (content.startsWith('[')) {
10578 isStatic = false;
10579 if (!content.endsWith(']')) {
10580 emitError(context, 26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
10581 }
10582 content = content.substr(1, content.length - 2);
10583 }
10584 else if (isSlot) {
10585 // #1241 special case for v-slot: vuetify relies extensively on slot
10586 // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
10587 // supports such usage so we are keeping it consistent with 2.x.
10588 content += match[3] || '';
10589 }
10590 arg = {
10591 type: 4 /* SIMPLE_EXPRESSION */,
10592 content,
10593 isStatic,
10594 constType: isStatic
10595 ? 3 /* CAN_STRINGIFY */
10596 : 0 /* NOT_CONSTANT */,
10597 loc
10598 };
10599 }
10600 if (value && value.isQuoted) {
10601 const valueLoc = value.loc;
10602 valueLoc.start.offset++;
10603 valueLoc.start.column++;
10604 valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
10605 valueLoc.source = valueLoc.source.slice(1, -1);
10606 }
10607 return {
10608 type: 7 /* DIRECTIVE */,
10609 name: dirName,
10610 exp: value && {
10611 type: 4 /* SIMPLE_EXPRESSION */,
10612 content: value.content,
10613 isStatic: false,
10614 // Treat as non-constant by default. This can be potentially set to
10615 // other values by `transformExpression` to make it eligible for hoisting.
10616 constType: 0 /* NOT_CONSTANT */,
10617 loc: value.loc
10618 },
10619 arg,
10620 modifiers: match[3] ? match[3].substr(1).split('.') : [],
10621 loc
10622 };
10623 }
10624 return {
10625 type: 6 /* ATTRIBUTE */,
10626 name,
10627 value: value && {
10628 type: 2 /* TEXT */,
10629 content: value.content,
10630 loc: value.loc
10631 },
10632 loc
10633 };
10634}
10635function parseAttributeValue(context) {
10636 const start = getCursor(context);
10637 let content;
10638 const quote = context.source[0];
10639 const isQuoted = quote === `"` || quote === `'`;
10640 if (isQuoted) {
10641 // Quoted value.
10642 advanceBy(context, 1);
10643 const endIndex = context.source.indexOf(quote);
10644 if (endIndex === -1) {
10645 content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
10646 }
10647 else {
10648 content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
10649 advanceBy(context, 1);
10650 }
10651 }
10652 else {
10653 // Unquoted
10654 const match = /^[^\t\r\n\f >]+/.exec(context.source);
10655 if (!match) {
10656 return undefined;
10657 }
10658 const unexpectedChars = /["'<=`]/g;
10659 let m;
10660 while ((m = unexpectedChars.exec(match[0]))) {
10661 emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
10662 }
10663 content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
10664 }
10665 return { content, isQuoted, loc: getSelection(context, start) };
10666}
10667function parseInterpolation(context, mode) {
10668 const [open, close] = context.options.delimiters;
10669 const closeIndex = context.source.indexOf(close, open.length);
10670 if (closeIndex === -1) {
10671 emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
10672 return undefined;
10673 }
10674 const start = getCursor(context);
10675 advanceBy(context, open.length);
10676 const innerStart = getCursor(context);
10677 const innerEnd = getCursor(context);
10678 const rawContentLength = closeIndex - open.length;
10679 const rawContent = context.source.slice(0, rawContentLength);
10680 const preTrimContent = parseTextData(context, rawContentLength, mode);
10681 const content = preTrimContent.trim();
10682 const startOffset = preTrimContent.indexOf(content);
10683 if (startOffset > 0) {
10684 advancePositionWithMutation(innerStart, rawContent, startOffset);
10685 }
10686 const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
10687 advancePositionWithMutation(innerEnd, rawContent, endOffset);
10688 advanceBy(context, close.length);
10689 return {
10690 type: 5 /* INTERPOLATION */,
10691 content: {
10692 type: 4 /* SIMPLE_EXPRESSION */,
10693 isStatic: false,
10694 // Set `isConstant` to false by default and will decide in transformExpression
10695 constType: 0 /* NOT_CONSTANT */,
10696 content,
10697 loc: getSelection(context, innerStart, innerEnd)
10698 },
10699 loc: getSelection(context, start)
10700 };
10701}
10702function parseText(context, mode) {
10703 const endTokens = ['<', context.options.delimiters[0]];
10704 if (mode === 3 /* CDATA */) {
10705 endTokens.push(']]>');
10706 }
10707 let endIndex = context.source.length;
10708 for (let i = 0; i < endTokens.length; i++) {
10709 const index = context.source.indexOf(endTokens[i], 1);
10710 if (index !== -1 && endIndex > index) {
10711 endIndex = index;
10712 }
10713 }
10714 const start = getCursor(context);
10715 const content = parseTextData(context, endIndex, mode);
10716 return {
10717 type: 2 /* TEXT */,
10718 content,
10719 loc: getSelection(context, start)
10720 };
10721}
10722/**
10723 * Get text data with a given length from the current location.
10724 * This translates HTML entities in the text data.
10725 */
10726function parseTextData(context, length, mode) {
10727 const rawText = context.source.slice(0, length);
10728 advanceBy(context, length);
10729 if (mode === 2 /* RAWTEXT */ ||
10730 mode === 3 /* CDATA */ ||
10731 rawText.indexOf('&') === -1) {
10732 return rawText;
10733 }
10734 else {
10735 // DATA or RCDATA containing "&"". Entity decoding required.
10736 return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
10737 }
10738}
10739function getCursor(context) {
10740 const { column, line, offset } = context;
10741 return { column, line, offset };
10742}
10743function getSelection(context, start, end) {
10744 end = end || getCursor(context);
10745 return {
10746 start,
10747 end,
10748 source: context.originalSource.slice(start.offset, end.offset)
10749 };
10750}
10751function last(xs) {
10752 return xs[xs.length - 1];
10753}
10754function startsWith(source, searchString) {
10755 return source.startsWith(searchString);
10756}
10757function advanceBy(context, numberOfCharacters) {
10758 const { source } = context;
10759 advancePositionWithMutation(context, source, numberOfCharacters);
10760 context.source = source.slice(numberOfCharacters);
10761}
10762function advanceSpaces(context) {
10763 const match = /^[\t\r\n\f ]+/.exec(context.source);
10764 if (match) {
10765 advanceBy(context, match[0].length);
10766 }
10767}
10768function getNewPosition(context, start, numberOfCharacters) {
10769 return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
10770}
10771function emitError(context, code, offset, loc = getCursor(context)) {
10772 if (offset) {
10773 loc.offset += offset;
10774 loc.column += offset;
10775 }
10776 context.options.onError(createCompilerError(code, {
10777 start: loc,
10778 end: loc,
10779 source: ''
10780 }));
10781}
10782function isEnd(context, mode, ancestors) {
10783 const s = context.source;
10784 switch (mode) {
10785 case 0 /* DATA */:
10786 if (startsWith(s, '</')) {
10787 // TODO: probably bad performance
10788 for (let i = ancestors.length - 1; i >= 0; --i) {
10789 if (startsWithEndTagOpen(s, ancestors[i].tag)) {
10790 return true;
10791 }
10792 }
10793 }
10794 break;
10795 case 1 /* RCDATA */:
10796 case 2 /* RAWTEXT */: {
10797 const parent = last(ancestors);
10798 if (parent && startsWithEndTagOpen(s, parent.tag)) {
10799 return true;
10800 }
10801 break;
10802 }
10803 case 3 /* CDATA */:
10804 if (startsWith(s, ']]>')) {
10805 return true;
10806 }
10807 break;
10808 }
10809 return !s;
10810}
10811function startsWithEndTagOpen(source, tag) {
10812 return (startsWith(source, '</') &&
10813 source.substr(2, tag.length).toLowerCase() === tag.toLowerCase() &&
10814 /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
10815}
10816
10817function hoistStatic(root, context) {
10818 walk(root, context,
10819 // Root node is unfortunately non-hoistable due to potential parent
10820 // fallthrough attributes.
10821 isSingleElementRoot(root, root.children[0]));
10822}
10823function isSingleElementRoot(root, child) {
10824 const { children } = root;
10825 return (children.length === 1 &&
10826 child.type === 1 /* ELEMENT */ &&
10827 !isSlotOutlet(child));
10828}
10829function walk(node, context, doNotHoistNode = false) {
10830 let hasHoistedNode = false;
10831 // Some transforms, e.g. transformAssetUrls from @vue/compiler-sfc, replaces
10832 // static bindings with expressions. These expressions are guaranteed to be
10833 // constant so they are still eligible for hoisting, but they are only
10834 // available at runtime and therefore cannot be evaluated ahead of time.
10835 // This is only a concern for pre-stringification (via transformHoist by
10836 // @vue/compiler-dom), but doing it here allows us to perform only one full
10837 // walk of the AST and allow `stringifyStatic` to stop walking as soon as its
10838 // stringficiation threshold is met.
10839 let canStringify = true;
10840 const { children } = node;
10841 for (let i = 0; i < children.length; i++) {
10842 const child = children[i];
10843 // only plain elements & text calls are eligible for hoisting.
10844 if (child.type === 1 /* ELEMENT */ &&
10845 child.tagType === 0 /* ELEMENT */) {
10846 const constantType = doNotHoistNode
10847 ? 0 /* NOT_CONSTANT */
10848 : getConstantType(child, context);
10849 if (constantType > 0 /* NOT_CONSTANT */) {
10850 if (constantType < 3 /* CAN_STRINGIFY */) {
10851 canStringify = false;
10852 }
10853 if (constantType >= 2 /* CAN_HOIST */) {
10854 child.codegenNode.patchFlag =
10855 -1 /* HOISTED */ + (` /* HOISTED */` );
10856 child.codegenNode = context.hoist(child.codegenNode);
10857 hasHoistedNode = true;
10858 continue;
10859 }
10860 }
10861 else {
10862 // node may contain dynamic children, but its props may be eligible for
10863 // hoisting.
10864 const codegenNode = child.codegenNode;
10865 if (codegenNode.type === 13 /* VNODE_CALL */) {
10866 const flag = getPatchFlag(codegenNode);
10867 if ((!flag ||
10868 flag === 512 /* NEED_PATCH */ ||
10869 flag === 1 /* TEXT */) &&
10870 getGeneratedPropsConstantType(child, context) >=
10871 2 /* CAN_HOIST */) {
10872 const props = getNodeProps(child);
10873 if (props) {
10874 codegenNode.props = context.hoist(props);
10875 }
10876 }
10877 }
10878 }
10879 }
10880 else if (child.type === 12 /* TEXT_CALL */) {
10881 const contentType = getConstantType(child.content, context);
10882 if (contentType > 0) {
10883 if (contentType < 3 /* CAN_STRINGIFY */) {
10884 canStringify = false;
10885 }
10886 if (contentType >= 2 /* CAN_HOIST */) {
10887 child.codegenNode = context.hoist(child.codegenNode);
10888 hasHoistedNode = true;
10889 }
10890 }
10891 }
10892 // walk further
10893 if (child.type === 1 /* ELEMENT */) {
10894 const isComponent = child.tagType === 1 /* COMPONENT */;
10895 if (isComponent) {
10896 context.scopes.vSlot++;
10897 }
10898 walk(child, context);
10899 if (isComponent) {
10900 context.scopes.vSlot--;
10901 }
10902 }
10903 else if (child.type === 11 /* FOR */) {
10904 // Do not hoist v-for single child because it has to be a block
10905 walk(child, context, child.children.length === 1);
10906 }
10907 else if (child.type === 9 /* IF */) {
10908 for (let i = 0; i < child.branches.length; i++) {
10909 // Do not hoist v-if single child because it has to be a block
10910 walk(child.branches[i], context, child.branches[i].children.length === 1);
10911 }
10912 }
10913 }
10914 if (canStringify && hasHoistedNode && context.transformHoist) {
10915 context.transformHoist(children, context, node);
10916 }
10917}
10918function getConstantType(node, context) {
10919 const { constantCache } = context;
10920 switch (node.type) {
10921 case 1 /* ELEMENT */:
10922 if (node.tagType !== 0 /* ELEMENT */) {
10923 return 0 /* NOT_CONSTANT */;
10924 }
10925 const cached = constantCache.get(node);
10926 if (cached !== undefined) {
10927 return cached;
10928 }
10929 const codegenNode = node.codegenNode;
10930 if (codegenNode.type !== 13 /* VNODE_CALL */) {
10931 return 0 /* NOT_CONSTANT */;
10932 }
10933 const flag = getPatchFlag(codegenNode);
10934 if (!flag) {
10935 let returnType = 3 /* CAN_STRINGIFY */;
10936 // Element itself has no patch flag. However we still need to check:
10937 // 1. Even for a node with no patch flag, it is possible for it to contain
10938 // non-hoistable expressions that refers to scope variables, e.g. compiler
10939 // injected keys or cached event handlers. Therefore we need to always
10940 // check the codegenNode's props to be sure.
10941 const generatedPropsType = getGeneratedPropsConstantType(node, context);
10942 if (generatedPropsType === 0 /* NOT_CONSTANT */) {
10943 constantCache.set(node, 0 /* NOT_CONSTANT */);
10944 return 0 /* NOT_CONSTANT */;
10945 }
10946 if (generatedPropsType < returnType) {
10947 returnType = generatedPropsType;
10948 }
10949 // 2. its children.
10950 for (let i = 0; i < node.children.length; i++) {
10951 const childType = getConstantType(node.children[i], context);
10952 if (childType === 0 /* NOT_CONSTANT */) {
10953 constantCache.set(node, 0 /* NOT_CONSTANT */);
10954 return 0 /* NOT_CONSTANT */;
10955 }
10956 if (childType < returnType) {
10957 returnType = childType;
10958 }
10959 }
10960 // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
10961 // type, check if any of the props can cause the type to be lowered
10962 // we can skip can_patch because it's guaranteed by the absence of a
10963 // patchFlag.
10964 if (returnType > 1 /* CAN_SKIP_PATCH */) {
10965 for (let i = 0; i < node.props.length; i++) {
10966 const p = node.props[i];
10967 if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
10968 const expType = getConstantType(p.exp, context);
10969 if (expType === 0 /* NOT_CONSTANT */) {
10970 constantCache.set(node, 0 /* NOT_CONSTANT */);
10971 return 0 /* NOT_CONSTANT */;
10972 }
10973 if (expType < returnType) {
10974 returnType = expType;
10975 }
10976 }
10977 }
10978 }
10979 // only svg/foreignObject could be block here, however if they are
10980 // static then they don't need to be blocks since there will be no
10981 // nested updates.
10982 if (codegenNode.isBlock) {
10983 context.removeHelper(OPEN_BLOCK);
10984 context.removeHelper(CREATE_BLOCK);
10985 codegenNode.isBlock = false;
10986 context.helper(CREATE_VNODE);
10987 }
10988 constantCache.set(node, returnType);
10989 return returnType;
10990 }
10991 else {
10992 constantCache.set(node, 0 /* NOT_CONSTANT */);
10993 return 0 /* NOT_CONSTANT */;
10994 }
10995 case 2 /* TEXT */:
10996 case 3 /* COMMENT */:
10997 return 3 /* CAN_STRINGIFY */;
10998 case 9 /* IF */:
10999 case 11 /* FOR */:
11000 case 10 /* IF_BRANCH */:
11001 return 0 /* NOT_CONSTANT */;
11002 case 5 /* INTERPOLATION */:
11003 case 12 /* TEXT_CALL */:
11004 return getConstantType(node.content, context);
11005 case 4 /* SIMPLE_EXPRESSION */:
11006 return node.constType;
11007 case 8 /* COMPOUND_EXPRESSION */:
11008 let returnType = 3 /* CAN_STRINGIFY */;
11009 for (let i = 0; i < node.children.length; i++) {
11010 const child = node.children[i];
11011 if (isString(child) || isSymbol(child)) {
11012 continue;
11013 }
11014 const childType = getConstantType(child, context);
11015 if (childType === 0 /* NOT_CONSTANT */) {
11016 return 0 /* NOT_CONSTANT */;
11017 }
11018 else if (childType < returnType) {
11019 returnType = childType;
11020 }
11021 }
11022 return returnType;
11023 default:
11024 return 0 /* NOT_CONSTANT */;
11025 }
11026}
11027function getGeneratedPropsConstantType(node, context) {
11028 let returnType = 3 /* CAN_STRINGIFY */;
11029 const props = getNodeProps(node);
11030 if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
11031 const { properties } = props;
11032 for (let i = 0; i < properties.length; i++) {
11033 const { key, value } = properties[i];
11034 const keyType = getConstantType(key, context);
11035 if (keyType === 0 /* NOT_CONSTANT */) {
11036 return keyType;
11037 }
11038 if (keyType < returnType) {
11039 returnType = keyType;
11040 }
11041 if (value.type !== 4 /* SIMPLE_EXPRESSION */) {
11042 return 0 /* NOT_CONSTANT */;
11043 }
11044 const valueType = getConstantType(value, context);
11045 if (valueType === 0 /* NOT_CONSTANT */) {
11046 return valueType;
11047 }
11048 if (valueType < returnType) {
11049 returnType = valueType;
11050 }
11051 }
11052 }
11053 return returnType;
11054}
11055function getNodeProps(node) {
11056 const codegenNode = node.codegenNode;
11057 if (codegenNode.type === 13 /* VNODE_CALL */) {
11058 return codegenNode.props;
11059 }
11060}
11061function getPatchFlag(node) {
11062 const flag = node.patchFlag;
11063 return flag ? parseInt(flag, 10) : undefined;
11064}
11065
11066function createTransformContext(root, { filename = '', prefixIdentifiers = false, hoistStatic = false, cacheHandlers = false, nodeTransforms = [], directiveTransforms = {}, transformHoist = null, isBuiltInComponent = NOOP, isCustomElement = NOOP, expressionPlugins = [], scopeId = null, slotted = true, ssr = false, ssrCssVars = ``, bindingMetadata = EMPTY_OBJ, inline = false, isTS = false, onError = defaultOnError }) {
11067 const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
11068 const context = {
11069 // options
11070 selfName: nameMatch && capitalize(camelize(nameMatch[1])),
11071 prefixIdentifiers,
11072 hoistStatic,
11073 cacheHandlers,
11074 nodeTransforms,
11075 directiveTransforms,
11076 transformHoist,
11077 isBuiltInComponent,
11078 isCustomElement,
11079 expressionPlugins,
11080 scopeId,
11081 slotted,
11082 ssr,
11083 ssrCssVars,
11084 bindingMetadata,
11085 inline,
11086 isTS,
11087 onError,
11088 // state
11089 root,
11090 helpers: new Map(),
11091 components: new Set(),
11092 directives: new Set(),
11093 hoists: [],
11094 imports: [],
11095 constantCache: new Map(),
11096 temps: 0,
11097 cached: 0,
11098 identifiers: Object.create(null),
11099 scopes: {
11100 vFor: 0,
11101 vSlot: 0,
11102 vPre: 0,
11103 vOnce: 0
11104 },
11105 parent: null,
11106 currentNode: root,
11107 childIndex: 0,
11108 // methods
11109 helper(name) {
11110 const count = context.helpers.get(name) || 0;
11111 context.helpers.set(name, count + 1);
11112 return name;
11113 },
11114 removeHelper(name) {
11115 const count = context.helpers.get(name);
11116 if (count) {
11117 const currentCount = count - 1;
11118 if (!currentCount) {
11119 context.helpers.delete(name);
11120 }
11121 else {
11122 context.helpers.set(name, currentCount);
11123 }
11124 }
11125 },
11126 helperString(name) {
11127 return `_${helperNameMap[context.helper(name)]}`;
11128 },
11129 replaceNode(node) {
11130 /* istanbul ignore if */
11131 {
11132 if (!context.currentNode) {
11133 throw new Error(`Node being replaced is already removed.`);
11134 }
11135 if (!context.parent) {
11136 throw new Error(`Cannot replace root node.`);
11137 }
11138 }
11139 context.parent.children[context.childIndex] = context.currentNode = node;
11140 },
11141 removeNode(node) {
11142 if (!context.parent) {
11143 throw new Error(`Cannot remove root node.`);
11144 }
11145 const list = context.parent.children;
11146 const removalIndex = node
11147 ? list.indexOf(node)
11148 : context.currentNode
11149 ? context.childIndex
11150 : -1;
11151 /* istanbul ignore if */
11152 if (removalIndex < 0) {
11153 throw new Error(`node being removed is not a child of current parent`);
11154 }
11155 if (!node || node === context.currentNode) {
11156 // current node removed
11157 context.currentNode = null;
11158 context.onNodeRemoved();
11159 }
11160 else {
11161 // sibling node removed
11162 if (context.childIndex > removalIndex) {
11163 context.childIndex--;
11164 context.onNodeRemoved();
11165 }
11166 }
11167 context.parent.children.splice(removalIndex, 1);
11168 },
11169 onNodeRemoved: () => { },
11170 addIdentifiers(exp) {
11171 },
11172 removeIdentifiers(exp) {
11173 },
11174 hoist(exp) {
11175 context.hoists.push(exp);
11176 const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
11177 identifier.hoisted = exp;
11178 return identifier;
11179 },
11180 cache(exp, isVNode = false) {
11181 return createCacheExpression(++context.cached, exp, isVNode);
11182 }
11183 };
11184 return context;
11185}
11186function transform(root, options) {
11187 const context = createTransformContext(root, options);
11188 traverseNode(root, context);
11189 if (options.hoistStatic) {
11190 hoistStatic(root, context);
11191 }
11192 if (!options.ssr) {
11193 createRootCodegen(root, context);
11194 }
11195 // finalize meta information
11196 root.helpers = [...context.helpers.keys()];
11197 root.components = [...context.components];
11198 root.directives = [...context.directives];
11199 root.imports = context.imports;
11200 root.hoists = context.hoists;
11201 root.temps = context.temps;
11202 root.cached = context.cached;
11203}
11204function createRootCodegen(root, context) {
11205 const { helper, removeHelper } = context;
11206 const { children } = root;
11207 if (children.length === 1) {
11208 const child = children[0];
11209 // if the single child is an element, turn it into a block.
11210 if (isSingleElementRoot(root, child) && child.codegenNode) {
11211 // single element root is never hoisted so codegenNode will never be
11212 // SimpleExpressionNode
11213 const codegenNode = child.codegenNode;
11214 if (codegenNode.type === 13 /* VNODE_CALL */) {
11215 if (!codegenNode.isBlock) {
11216 removeHelper(CREATE_VNODE);
11217 codegenNode.isBlock = true;
11218 helper(OPEN_BLOCK);
11219 helper(CREATE_BLOCK);
11220 }
11221 }
11222 root.codegenNode = codegenNode;
11223 }
11224 else {
11225 // - single <slot/>, IfNode, ForNode: already blocks.
11226 // - single text node: always patched.
11227 // root codegen falls through via genNode()
11228 root.codegenNode = child;
11229 }
11230 }
11231 else if (children.length > 1) {
11232 // root has multiple nodes - return a fragment block.
11233 let patchFlag = 64 /* STABLE_FRAGMENT */;
11234 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
11235 // check if the fragment actually contains a single valid child with
11236 // the rest being comments
11237 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
11238 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
11239 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
11240 }
11241 root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true);
11242 }
11243 else ;
11244}
11245function traverseChildren(parent, context) {
11246 let i = 0;
11247 const nodeRemoved = () => {
11248 i--;
11249 };
11250 for (; i < parent.children.length; i++) {
11251 const child = parent.children[i];
11252 if (isString(child))
11253 continue;
11254 context.parent = parent;
11255 context.childIndex = i;
11256 context.onNodeRemoved = nodeRemoved;
11257 traverseNode(child, context);
11258 }
11259}
11260function traverseNode(node, context) {
11261 context.currentNode = node;
11262 // apply transform plugins
11263 const { nodeTransforms } = context;
11264 const exitFns = [];
11265 for (let i = 0; i < nodeTransforms.length; i++) {
11266 const onExit = nodeTransforms[i](node, context);
11267 if (onExit) {
11268 if (isArray(onExit)) {
11269 exitFns.push(...onExit);
11270 }
11271 else {
11272 exitFns.push(onExit);
11273 }
11274 }
11275 if (!context.currentNode) {
11276 // node was removed
11277 return;
11278 }
11279 else {
11280 // node may have been replaced
11281 node = context.currentNode;
11282 }
11283 }
11284 switch (node.type) {
11285 case 3 /* COMMENT */:
11286 if (!context.ssr) {
11287 // inject import for the Comment symbol, which is needed for creating
11288 // comment nodes with `createVNode`
11289 context.helper(CREATE_COMMENT);
11290 }
11291 break;
11292 case 5 /* INTERPOLATION */:
11293 // no need to traverse, but we need to inject toString helper
11294 if (!context.ssr) {
11295 context.helper(TO_DISPLAY_STRING);
11296 }
11297 break;
11298 // for container types, further traverse downwards
11299 case 9 /* IF */:
11300 for (let i = 0; i < node.branches.length; i++) {
11301 traverseNode(node.branches[i], context);
11302 }
11303 break;
11304 case 10 /* IF_BRANCH */:
11305 case 11 /* FOR */:
11306 case 1 /* ELEMENT */:
11307 case 0 /* ROOT */:
11308 traverseChildren(node, context);
11309 break;
11310 }
11311 // exit transforms
11312 context.currentNode = node;
11313 let i = exitFns.length;
11314 while (i--) {
11315 exitFns[i]();
11316 }
11317}
11318function createStructuralDirectiveTransform(name, fn) {
11319 const matches = isString(name)
11320 ? (n) => n === name
11321 : (n) => name.test(n);
11322 return (node, context) => {
11323 if (node.type === 1 /* ELEMENT */) {
11324 const { props } = node;
11325 // structural directive transforms are not concerned with slots
11326 // as they are handled separately in vSlot.ts
11327 if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
11328 return;
11329 }
11330 const exitFns = [];
11331 for (let i = 0; i < props.length; i++) {
11332 const prop = props[i];
11333 if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
11334 // structural directives are removed to avoid infinite recursion
11335 // also we remove them *before* applying so that it can further
11336 // traverse itself in case it moves the node around
11337 props.splice(i, 1);
11338 i--;
11339 const onExit = fn(node, prop, context);
11340 if (onExit)
11341 exitFns.push(onExit);
11342 }
11343 }
11344 return exitFns;
11345 }
11346 };
11347}
11348
11349const PURE_ANNOTATION = `/*#__PURE__*/`;
11350function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssr = false }) {
11351 const context = {
11352 mode,
11353 prefixIdentifiers,
11354 sourceMap,
11355 filename,
11356 scopeId,
11357 optimizeImports,
11358 runtimeGlobalName,
11359 runtimeModuleName,
11360 ssr,
11361 source: ast.loc.source,
11362 code: ``,
11363 column: 1,
11364 line: 1,
11365 offset: 0,
11366 indentLevel: 0,
11367 pure: false,
11368 map: undefined,
11369 helper(key) {
11370 return `_${helperNameMap[key]}`;
11371 },
11372 push(code, node) {
11373 context.code += code;
11374 },
11375 indent() {
11376 newline(++context.indentLevel);
11377 },
11378 deindent(withoutNewLine = false) {
11379 if (withoutNewLine) {
11380 --context.indentLevel;
11381 }
11382 else {
11383 newline(--context.indentLevel);
11384 }
11385 },
11386 newline() {
11387 newline(context.indentLevel);
11388 }
11389 };
11390 function newline(n) {
11391 context.push('\n' + ` `.repeat(n));
11392 }
11393 return context;
11394}
11395function generate(ast, options = {}) {
11396 const context = createCodegenContext(ast, options);
11397 if (options.onContextCreated)
11398 options.onContextCreated(context);
11399 const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
11400 const hasHelpers = ast.helpers.length > 0;
11401 const useWithBlock = !prefixIdentifiers && mode !== 'module';
11402 // preambles
11403 // in setup() inline mode, the preamble is generated in a sub context
11404 // and returned separately.
11405 const preambleContext = context;
11406 {
11407 genFunctionPreamble(ast, preambleContext);
11408 }
11409 // enter render function
11410 const functionName = ssr ? `ssrRender` : `render`;
11411 const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
11412 const signature = args.join(', ');
11413 {
11414 push(`function ${functionName}(${signature}) {`);
11415 }
11416 indent();
11417 if (useWithBlock) {
11418 push(`with (_ctx) {`);
11419 indent();
11420 // function mode const declarations should be inside with block
11421 // also they should be renamed to avoid collision with user properties
11422 if (hasHelpers) {
11423 push(`const { ${ast.helpers
11424 .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
11425 .join(', ')} } = _Vue`);
11426 push(`\n`);
11427 newline();
11428 }
11429 }
11430 // generate asset resolution statements
11431 if (ast.components.length) {
11432 genAssets(ast.components, 'component', context);
11433 if (ast.directives.length || ast.temps > 0) {
11434 newline();
11435 }
11436 }
11437 if (ast.directives.length) {
11438 genAssets(ast.directives, 'directive', context);
11439 if (ast.temps > 0) {
11440 newline();
11441 }
11442 }
11443 if (ast.temps > 0) {
11444 push(`let `);
11445 for (let i = 0; i < ast.temps; i++) {
11446 push(`${i > 0 ? `, ` : ``}_temp${i}`);
11447 }
11448 }
11449 if (ast.components.length || ast.directives.length || ast.temps) {
11450 push(`\n`);
11451 newline();
11452 }
11453 // generate the VNode tree expression
11454 if (!ssr) {
11455 push(`return `);
11456 }
11457 if (ast.codegenNode) {
11458 genNode(ast.codegenNode, context);
11459 }
11460 else {
11461 push(`null`);
11462 }
11463 if (useWithBlock) {
11464 deindent();
11465 push(`}`);
11466 }
11467 deindent();
11468 push(`}`);
11469 return {
11470 ast,
11471 code: context.code,
11472 preamble: ``,
11473 // SourceMapGenerator does have toJSON() method but it's not in the types
11474 map: context.map ? context.map.toJSON() : undefined
11475 };
11476}
11477function genFunctionPreamble(ast, context) {
11478 const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName } = context;
11479 const VueBinding = runtimeGlobalName;
11480 const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
11481 // Generate const declaration for helpers
11482 // In prefix mode, we place the const declaration at top so it's done
11483 // only once; But if we not prefixing, we place the declaration inside the
11484 // with block so it doesn't incur the `in` check cost for every helper access.
11485 if (ast.helpers.length > 0) {
11486 {
11487 // "with" mode.
11488 // save Vue in a separate variable to avoid collision
11489 push(`const _Vue = ${VueBinding}\n`);
11490 // in "with" mode, helpers are declared inside the with block to avoid
11491 // has check cost, but hoists are lifted out of the function - we need
11492 // to provide the helper here.
11493 if (ast.hoists.length) {
11494 const staticHelpers = [
11495 CREATE_VNODE,
11496 CREATE_COMMENT,
11497 CREATE_TEXT,
11498 CREATE_STATIC
11499 ]
11500 .filter(helper => ast.helpers.includes(helper))
11501 .map(aliasHelper)
11502 .join(', ');
11503 push(`const { ${staticHelpers} } = _Vue\n`);
11504 }
11505 }
11506 }
11507 genHoists(ast.hoists, context);
11508 newline();
11509 push(`return `);
11510}
11511function genAssets(assets, type, { helper, push, newline }) {
11512 const resolver = helper(type === 'component' ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE);
11513 for (let i = 0; i < assets.length; i++) {
11514 let id = assets[i];
11515 // potential component implicit self-reference inferred from SFC filename
11516 const maybeSelfReference = id.endsWith('__self');
11517 if (maybeSelfReference) {
11518 id = id.slice(0, -6);
11519 }
11520 push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})`);
11521 if (i < assets.length - 1) {
11522 newline();
11523 }
11524 }
11525}
11526function genHoists(hoists, context) {
11527 if (!hoists.length) {
11528 return;
11529 }
11530 context.pure = true;
11531 const { push, newline, helper, scopeId, mode } = context;
11532 newline();
11533 hoists.forEach((exp, i) => {
11534 if (exp) {
11535 push(`const _hoisted_${i + 1} = `);
11536 genNode(exp, context);
11537 newline();
11538 }
11539 });
11540 context.pure = false;
11541}
11542function isText$1(n) {
11543 return (isString(n) ||
11544 n.type === 4 /* SIMPLE_EXPRESSION */ ||
11545 n.type === 2 /* TEXT */ ||
11546 n.type === 5 /* INTERPOLATION */ ||
11547 n.type === 8 /* COMPOUND_EXPRESSION */);
11548}
11549function genNodeListAsArray(nodes, context) {
11550 const multilines = nodes.length > 3 ||
11551 (nodes.some(n => isArray(n) || !isText$1(n)));
11552 context.push(`[`);
11553 multilines && context.indent();
11554 genNodeList(nodes, context, multilines);
11555 multilines && context.deindent();
11556 context.push(`]`);
11557}
11558function genNodeList(nodes, context, multilines = false, comma = true) {
11559 const { push, newline } = context;
11560 for (let i = 0; i < nodes.length; i++) {
11561 const node = nodes[i];
11562 if (isString(node)) {
11563 push(node);
11564 }
11565 else if (isArray(node)) {
11566 genNodeListAsArray(node, context);
11567 }
11568 else {
11569 genNode(node, context);
11570 }
11571 if (i < nodes.length - 1) {
11572 if (multilines) {
11573 comma && push(',');
11574 newline();
11575 }
11576 else {
11577 comma && push(', ');
11578 }
11579 }
11580 }
11581}
11582function genNode(node, context) {
11583 if (isString(node)) {
11584 context.push(node);
11585 return;
11586 }
11587 if (isSymbol(node)) {
11588 context.push(context.helper(node));
11589 return;
11590 }
11591 switch (node.type) {
11592 case 1 /* ELEMENT */:
11593 case 9 /* IF */:
11594 case 11 /* FOR */:
11595 assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
11596 `Apply appropriate transforms first.`);
11597 genNode(node.codegenNode, context);
11598 break;
11599 case 2 /* TEXT */:
11600 genText(node, context);
11601 break;
11602 case 4 /* SIMPLE_EXPRESSION */:
11603 genExpression(node, context);
11604 break;
11605 case 5 /* INTERPOLATION */:
11606 genInterpolation(node, context);
11607 break;
11608 case 12 /* TEXT_CALL */:
11609 genNode(node.codegenNode, context);
11610 break;
11611 case 8 /* COMPOUND_EXPRESSION */:
11612 genCompoundExpression(node, context);
11613 break;
11614 case 3 /* COMMENT */:
11615 genComment(node, context);
11616 break;
11617 case 13 /* VNODE_CALL */:
11618 genVNodeCall(node, context);
11619 break;
11620 case 14 /* JS_CALL_EXPRESSION */:
11621 genCallExpression(node, context);
11622 break;
11623 case 15 /* JS_OBJECT_EXPRESSION */:
11624 genObjectExpression(node, context);
11625 break;
11626 case 17 /* JS_ARRAY_EXPRESSION */:
11627 genArrayExpression(node, context);
11628 break;
11629 case 18 /* JS_FUNCTION_EXPRESSION */:
11630 genFunctionExpression(node, context);
11631 break;
11632 case 19 /* JS_CONDITIONAL_EXPRESSION */:
11633 genConditionalExpression(node, context);
11634 break;
11635 case 20 /* JS_CACHE_EXPRESSION */:
11636 genCacheExpression(node, context);
11637 break;
11638 // SSR only types
11639 case 21 /* JS_BLOCK_STATEMENT */:
11640 break;
11641 case 22 /* JS_TEMPLATE_LITERAL */:
11642 break;
11643 case 23 /* JS_IF_STATEMENT */:
11644 break;
11645 case 24 /* JS_ASSIGNMENT_EXPRESSION */:
11646 break;
11647 case 25 /* JS_SEQUENCE_EXPRESSION */:
11648 break;
11649 case 26 /* JS_RETURN_STATEMENT */:
11650 break;
11651 /* istanbul ignore next */
11652 case 10 /* IF_BRANCH */:
11653 // noop
11654 break;
11655 default:
11656 {
11657 assert(false, `unhandled codegen node type: ${node.type}`);
11658 // make sure we exhaust all possible types
11659 const exhaustiveCheck = node;
11660 return exhaustiveCheck;
11661 }
11662 }
11663}
11664function genText(node, context) {
11665 context.push(JSON.stringify(node.content), node);
11666}
11667function genExpression(node, context) {
11668 const { content, isStatic } = node;
11669 context.push(isStatic ? JSON.stringify(content) : content, node);
11670}
11671function genInterpolation(node, context) {
11672 const { push, helper, pure } = context;
11673 if (pure)
11674 push(PURE_ANNOTATION);
11675 push(`${helper(TO_DISPLAY_STRING)}(`);
11676 genNode(node.content, context);
11677 push(`)`);
11678}
11679function genCompoundExpression(node, context) {
11680 for (let i = 0; i < node.children.length; i++) {
11681 const child = node.children[i];
11682 if (isString(child)) {
11683 context.push(child);
11684 }
11685 else {
11686 genNode(child, context);
11687 }
11688 }
11689}
11690function genExpressionAsPropertyKey(node, context) {
11691 const { push } = context;
11692 if (node.type === 8 /* COMPOUND_EXPRESSION */) {
11693 push(`[`);
11694 genCompoundExpression(node, context);
11695 push(`]`);
11696 }
11697 else if (node.isStatic) {
11698 // only quote keys if necessary
11699 const text = isSimpleIdentifier(node.content)
11700 ? node.content
11701 : JSON.stringify(node.content);
11702 push(text, node);
11703 }
11704 else {
11705 push(`[${node.content}]`, node);
11706 }
11707}
11708function genComment(node, context) {
11709 {
11710 const { push, helper, pure } = context;
11711 if (pure) {
11712 push(PURE_ANNOTATION);
11713 }
11714 push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
11715 }
11716}
11717function genVNodeCall(node, context) {
11718 const { push, helper, pure } = context;
11719 const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking } = node;
11720 if (directives) {
11721 push(helper(WITH_DIRECTIVES) + `(`);
11722 }
11723 if (isBlock) {
11724 push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
11725 }
11726 if (pure) {
11727 push(PURE_ANNOTATION);
11728 }
11729 push(helper(isBlock ? CREATE_BLOCK : CREATE_VNODE) + `(`, node);
11730 genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
11731 push(`)`);
11732 if (isBlock) {
11733 push(`)`);
11734 }
11735 if (directives) {
11736 push(`, `);
11737 genNode(directives, context);
11738 push(`)`);
11739 }
11740}
11741function genNullableArgs(args) {
11742 let i = args.length;
11743 while (i--) {
11744 if (args[i] != null)
11745 break;
11746 }
11747 return args.slice(0, i + 1).map(arg => arg || `null`);
11748}
11749// JavaScript
11750function genCallExpression(node, context) {
11751 const { push, helper, pure } = context;
11752 const callee = isString(node.callee) ? node.callee : helper(node.callee);
11753 if (pure) {
11754 push(PURE_ANNOTATION);
11755 }
11756 push(callee + `(`, node);
11757 genNodeList(node.arguments, context);
11758 push(`)`);
11759}
11760function genObjectExpression(node, context) {
11761 const { push, indent, deindent, newline } = context;
11762 const { properties } = node;
11763 if (!properties.length) {
11764 push(`{}`, node);
11765 return;
11766 }
11767 const multilines = properties.length > 1 ||
11768 (properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
11769 push(multilines ? `{` : `{ `);
11770 multilines && indent();
11771 for (let i = 0; i < properties.length; i++) {
11772 const { key, value } = properties[i];
11773 // key
11774 genExpressionAsPropertyKey(key, context);
11775 push(`: `);
11776 // value
11777 genNode(value, context);
11778 if (i < properties.length - 1) {
11779 // will only reach this if it's multilines
11780 push(`,`);
11781 newline();
11782 }
11783 }
11784 multilines && deindent();
11785 push(multilines ? `}` : ` }`);
11786}
11787function genArrayExpression(node, context) {
11788 genNodeListAsArray(node.elements, context);
11789}
11790function genFunctionExpression(node, context) {
11791 const { push, indent, deindent, scopeId, mode } = context;
11792 const { params, returns, body, newline, isSlot } = node;
11793 if (isSlot) {
11794 // wrap slot functions with owner context
11795 push(`_${helperNameMap[WITH_CTX]}(`);
11796 }
11797 push(`(`, node);
11798 if (isArray(params)) {
11799 genNodeList(params, context);
11800 }
11801 else if (params) {
11802 genNode(params, context);
11803 }
11804 push(`) => `);
11805 if (newline || body) {
11806 push(`{`);
11807 indent();
11808 }
11809 if (returns) {
11810 if (newline) {
11811 push(`return `);
11812 }
11813 if (isArray(returns)) {
11814 genNodeListAsArray(returns, context);
11815 }
11816 else {
11817 genNode(returns, context);
11818 }
11819 }
11820 else if (body) {
11821 genNode(body, context);
11822 }
11823 if (newline || body) {
11824 deindent();
11825 push(`}`);
11826 }
11827 if (isSlot) {
11828 push(`)`);
11829 }
11830}
11831function genConditionalExpression(node, context) {
11832 const { test, consequent, alternate, newline: needNewline } = node;
11833 const { push, indent, deindent, newline } = context;
11834 if (test.type === 4 /* SIMPLE_EXPRESSION */) {
11835 const needsParens = !isSimpleIdentifier(test.content);
11836 needsParens && push(`(`);
11837 genExpression(test, context);
11838 needsParens && push(`)`);
11839 }
11840 else {
11841 push(`(`);
11842 genNode(test, context);
11843 push(`)`);
11844 }
11845 needNewline && indent();
11846 context.indentLevel++;
11847 needNewline || push(` `);
11848 push(`? `);
11849 genNode(consequent, context);
11850 context.indentLevel--;
11851 needNewline && newline();
11852 needNewline || push(` `);
11853 push(`: `);
11854 const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
11855 if (!isNested) {
11856 context.indentLevel++;
11857 }
11858 genNode(alternate, context);
11859 if (!isNested) {
11860 context.indentLevel--;
11861 }
11862 needNewline && deindent(true /* without newline */);
11863}
11864function genCacheExpression(node, context) {
11865 const { push, helper, indent, deindent, newline } = context;
11866 push(`_cache[${node.index}] || (`);
11867 if (node.isVNode) {
11868 indent();
11869 push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
11870 newline();
11871 }
11872 push(`_cache[${node.index}] = `);
11873 genNode(node.value, context);
11874 if (node.isVNode) {
11875 push(`,`);
11876 newline();
11877 push(`${helper(SET_BLOCK_TRACKING)}(1),`);
11878 newline();
11879 push(`_cache[${node.index}]`);
11880 deindent();
11881 }
11882 push(`)`);
11883}
11884
11885// these keywords should not appear inside expressions, but operators like
11886// typeof, instanceof and in are allowed
11887const prohibitedKeywordRE = new RegExp('\\b' +
11888 ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
11889 'super,throw,while,yield,delete,export,import,return,switch,default,' +
11890 'extends,finally,continue,debugger,function,arguments,typeof,void')
11891 .split(',')
11892 .join('\\b|\\b') +
11893 '\\b');
11894// strip strings in expressions
11895const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
11896/**
11897 * Validate a non-prefixed expression.
11898 * This is only called when using the in-browser runtime compiler since it
11899 * doesn't prefix expressions.
11900 */
11901function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
11902 const exp = node.content;
11903 // empty expressions are validated per-directive since some directives
11904 // do allow empty expressions.
11905 if (!exp.trim()) {
11906 return;
11907 }
11908 try {
11909 new Function(asRawStatements
11910 ? ` ${exp} `
11911 : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
11912 }
11913 catch (e) {
11914 let message = e.message;
11915 const keywordMatch = exp
11916 .replace(stripStringRE, '')
11917 .match(prohibitedKeywordRE);
11918 if (keywordMatch) {
11919 message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
11920 }
11921 context.onError(createCompilerError(43 /* X_INVALID_EXPRESSION */, node.loc, undefined, message));
11922 }
11923}
11924
11925const transformExpression = (node, context) => {
11926 if (node.type === 5 /* INTERPOLATION */) {
11927 node.content = processExpression(node.content, context);
11928 }
11929 else if (node.type === 1 /* ELEMENT */) {
11930 // handle directives on element
11931 for (let i = 0; i < node.props.length; i++) {
11932 const dir = node.props[i];
11933 // do not process for v-on & v-for since they are special handled
11934 if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
11935 const exp = dir.exp;
11936 const arg = dir.arg;
11937 // do not process exp if this is v-on:arg - we need special handling
11938 // for wrapping inline statements.
11939 if (exp &&
11940 exp.type === 4 /* SIMPLE_EXPRESSION */ &&
11941 !(dir.name === 'on' && arg)) {
11942 dir.exp = processExpression(exp, context,
11943 // slot args must be processed as function params
11944 dir.name === 'slot');
11945 }
11946 if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
11947 dir.arg = processExpression(arg, context);
11948 }
11949 }
11950 }
11951 }
11952};
11953// Important: since this function uses Node.js only dependencies, it should
11954// always be used with a leading !true check so that it can be
11955// tree-shaken from the browser build.
11956function processExpression(node, context,
11957// some expressions like v-slot props & v-for aliases should be parsed as
11958// function params
11959asParams = false,
11960// v-on handler values may contain multiple statements
11961asRawStatements = false) {
11962 {
11963 {
11964 // simple in-browser validation (same logic in 2.x)
11965 validateBrowserExpression(node, context, asParams, asRawStatements);
11966 }
11967 return node;
11968 }
11969}
11970
11971const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
11972 return processIf(node, dir, context, (ifNode, branch, isRoot) => {
11973 // #1587: We need to dynamically increment the key based on the current
11974 // node's sibling nodes, since chained v-if/else branches are
11975 // rendered at the same depth
11976 const siblings = context.parent.children;
11977 let i = siblings.indexOf(ifNode);
11978 let key = 0;
11979 while (i-- >= 0) {
11980 const sibling = siblings[i];
11981 if (sibling && sibling.type === 9 /* IF */) {
11982 key += sibling.branches.length;
11983 }
11984 }
11985 // Exit callback. Complete the codegenNode when all children have been
11986 // transformed.
11987 return () => {
11988 if (isRoot) {
11989 ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
11990 }
11991 else {
11992 // attach this branch's codegen node to the v-if root.
11993 const parentCondition = getParentCondition(ifNode.codegenNode);
11994 parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
11995 }
11996 };
11997 });
11998});
11999// target-agnostic transform used for both Client and SSR
12000function processIf(node, dir, context, processCodegen) {
12001 if (dir.name !== 'else' &&
12002 (!dir.exp || !dir.exp.content.trim())) {
12003 const loc = dir.exp ? dir.exp.loc : node.loc;
12004 context.onError(createCompilerError(27 /* X_V_IF_NO_EXPRESSION */, dir.loc));
12005 dir.exp = createSimpleExpression(`true`, false, loc);
12006 }
12007 if (dir.exp) {
12008 validateBrowserExpression(dir.exp, context);
12009 }
12010 if (dir.name === 'if') {
12011 const branch = createIfBranch(node, dir);
12012 const ifNode = {
12013 type: 9 /* IF */,
12014 loc: node.loc,
12015 branches: [branch]
12016 };
12017 context.replaceNode(ifNode);
12018 if (processCodegen) {
12019 return processCodegen(ifNode, branch, true);
12020 }
12021 }
12022 else {
12023 // locate the adjacent v-if
12024 const siblings = context.parent.children;
12025 const comments = [];
12026 let i = siblings.indexOf(node);
12027 while (i-- >= -1) {
12028 const sibling = siblings[i];
12029 if (sibling && sibling.type === 3 /* COMMENT */) {
12030 context.removeNode(sibling);
12031 comments.unshift(sibling);
12032 continue;
12033 }
12034 if (sibling &&
12035 sibling.type === 2 /* TEXT */ &&
12036 !sibling.content.trim().length) {
12037 context.removeNode(sibling);
12038 continue;
12039 }
12040 if (sibling && sibling.type === 9 /* IF */) {
12041 // move the node to the if node's branches
12042 context.removeNode();
12043 const branch = createIfBranch(node, dir);
12044 if (comments.length) {
12045 branch.children = [...comments, ...branch.children];
12046 }
12047 // check if user is forcing same key on different branches
12048 {
12049 const key = branch.userKey;
12050 if (key) {
12051 sibling.branches.forEach(({ userKey }) => {
12052 if (isSameKey(userKey, key)) {
12053 context.onError(createCompilerError(28 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
12054 }
12055 });
12056 }
12057 }
12058 sibling.branches.push(branch);
12059 const onExit = processCodegen && processCodegen(sibling, branch, false);
12060 // since the branch was removed, it will not be traversed.
12061 // make sure to traverse here.
12062 traverseNode(branch, context);
12063 // call on exit
12064 if (onExit)
12065 onExit();
12066 // make sure to reset currentNode after traversal to indicate this
12067 // node has been removed.
12068 context.currentNode = null;
12069 }
12070 else {
12071 context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
12072 }
12073 break;
12074 }
12075 }
12076}
12077function createIfBranch(node, dir) {
12078 return {
12079 type: 10 /* IF_BRANCH */,
12080 loc: node.loc,
12081 condition: dir.name === 'else' ? undefined : dir.exp,
12082 children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
12083 ? node.children
12084 : [node],
12085 userKey: findProp(node, `key`)
12086 };
12087}
12088function createCodegenNodeForBranch(branch, keyIndex, context) {
12089 if (branch.condition) {
12090 return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
12091 // make sure to pass in asBlock: true so that the comment node call
12092 // closes the current block.
12093 createCallExpression(context.helper(CREATE_COMMENT), [
12094 '"v-if"' ,
12095 'true'
12096 ]));
12097 }
12098 else {
12099 return createChildrenCodegenNode(branch, keyIndex, context);
12100 }
12101}
12102function createChildrenCodegenNode(branch, keyIndex, context) {
12103 const { helper, removeHelper } = context;
12104 const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
12105 const { children } = branch;
12106 const firstChild = children[0];
12107 const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
12108 if (needFragmentWrapper) {
12109 if (children.length === 1 && firstChild.type === 11 /* FOR */) {
12110 // optimize away nested fragments when child is a ForNode
12111 const vnodeCall = firstChild.codegenNode;
12112 injectProp(vnodeCall, keyProperty, context);
12113 return vnodeCall;
12114 }
12115 else {
12116 let patchFlag = 64 /* STABLE_FRAGMENT */;
12117 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
12118 // check if the fragment actually contains a single valid child with
12119 // the rest being comments
12120 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
12121 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
12122 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
12123 }
12124 return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, branch.loc);
12125 }
12126 }
12127 else {
12128 const vnodeCall = firstChild
12129 .codegenNode;
12130 // Change createVNode to createBlock.
12131 if (vnodeCall.type === 13 /* VNODE_CALL */ && !vnodeCall.isBlock) {
12132 removeHelper(CREATE_VNODE);
12133 vnodeCall.isBlock = true;
12134 helper(OPEN_BLOCK);
12135 helper(CREATE_BLOCK);
12136 }
12137 // inject branch key
12138 injectProp(vnodeCall, keyProperty, context);
12139 return vnodeCall;
12140 }
12141}
12142function isSameKey(a, b) {
12143 if (!a || a.type !== b.type) {
12144 return false;
12145 }
12146 if (a.type === 6 /* ATTRIBUTE */) {
12147 if (a.value.content !== b.value.content) {
12148 return false;
12149 }
12150 }
12151 else {
12152 // directive
12153 const exp = a.exp;
12154 const branchExp = b.exp;
12155 if (exp.type !== branchExp.type) {
12156 return false;
12157 }
12158 if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
12159 (exp.isStatic !== branchExp.isStatic ||
12160 exp.content !== branchExp.content)) {
12161 return false;
12162 }
12163 }
12164 return true;
12165}
12166function getParentCondition(node) {
12167 while (true) {
12168 if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
12169 if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
12170 node = node.alternate;
12171 }
12172 else {
12173 return node;
12174 }
12175 }
12176 else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
12177 node = node.value;
12178 }
12179 }
12180}
12181
12182const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
12183 const { helper, removeHelper } = context;
12184 return processFor(node, dir, context, forNode => {
12185 // create the loop render function expression now, and add the
12186 // iterator on exit after all children have been traversed
12187 const renderExp = createCallExpression(helper(RENDER_LIST), [
12188 forNode.source
12189 ]);
12190 const keyProp = findProp(node, `key`);
12191 const keyProperty = keyProp
12192 ? createObjectProperty(`key`, keyProp.type === 6 /* ATTRIBUTE */
12193 ? createSimpleExpression(keyProp.value.content, true)
12194 : keyProp.exp)
12195 : null;
12196 const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
12197 forNode.source.constType > 0 /* NOT_CONSTANT */;
12198 const fragmentFlag = isStableFragment
12199 ? 64 /* STABLE_FRAGMENT */
12200 : keyProp
12201 ? 128 /* KEYED_FRAGMENT */
12202 : 256 /* UNKEYED_FRAGMENT */;
12203 forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
12204 (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, node.loc);
12205 return () => {
12206 // finish the codegen now that all children have been traversed
12207 let childBlock;
12208 const isTemplate = isTemplateNode(node);
12209 const { children } = forNode;
12210 // check <template v-for> key placement
12211 if (isTemplate) {
12212 node.children.some(c => {
12213 if (c.type === 1 /* ELEMENT */) {
12214 const key = findProp(c, 'key');
12215 if (key) {
12216 context.onError(createCompilerError(32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
12217 return true;
12218 }
12219 }
12220 });
12221 }
12222 const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
12223 const slotOutlet = isSlotOutlet(node)
12224 ? node
12225 : isTemplate &&
12226 node.children.length === 1 &&
12227 isSlotOutlet(node.children[0])
12228 ? node.children[0] // api-extractor somehow fails to infer this
12229 : null;
12230 if (slotOutlet) {
12231 // <slot v-for="..."> or <template v-for="..."><slot/></template>
12232 childBlock = slotOutlet.codegenNode;
12233 if (isTemplate && keyProperty) {
12234 // <template v-for="..." :key="..."><slot/></template>
12235 // we need to inject the key to the renderSlot() call.
12236 // the props for renderSlot is passed as the 3rd argument.
12237 injectProp(childBlock, keyProperty, context);
12238 }
12239 }
12240 else if (needFragmentWrapper) {
12241 // <template v-for="..."> with text or multi-elements
12242 // should generate a fragment block for each loop
12243 childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
12244 (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
12245 ), undefined, undefined, true);
12246 }
12247 else {
12248 // Normal element v-for. Directly use the child's codegenNode
12249 // but mark it as a block.
12250 childBlock = children[0]
12251 .codegenNode;
12252 if (isTemplate && keyProperty) {
12253 injectProp(childBlock, keyProperty, context);
12254 }
12255 if (childBlock.isBlock !== !isStableFragment) {
12256 if (childBlock.isBlock) {
12257 // switch from block to vnode
12258 removeHelper(OPEN_BLOCK);
12259 removeHelper(CREATE_BLOCK);
12260 }
12261 else {
12262 // switch from vnode to block
12263 removeHelper(CREATE_VNODE);
12264 }
12265 }
12266 childBlock.isBlock = !isStableFragment;
12267 if (childBlock.isBlock) {
12268 helper(OPEN_BLOCK);
12269 helper(CREATE_BLOCK);
12270 }
12271 else {
12272 helper(CREATE_VNODE);
12273 }
12274 }
12275 renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
12276 };
12277 });
12278});
12279// target-agnostic transform used for both Client and SSR
12280function processFor(node, dir, context, processCodegen) {
12281 if (!dir.exp) {
12282 context.onError(createCompilerError(30 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
12283 return;
12284 }
12285 const parseResult = parseForExpression(
12286 // can only be simple expression because vFor transform is applied
12287 // before expression transform.
12288 dir.exp, context);
12289 if (!parseResult) {
12290 context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
12291 return;
12292 }
12293 const { addIdentifiers, removeIdentifiers, scopes } = context;
12294 const { source, value, key, index } = parseResult;
12295 const forNode = {
12296 type: 11 /* FOR */,
12297 loc: dir.loc,
12298 source,
12299 valueAlias: value,
12300 keyAlias: key,
12301 objectIndexAlias: index,
12302 parseResult,
12303 children: isTemplateNode(node) ? node.children : [node]
12304 };
12305 context.replaceNode(forNode);
12306 // bookkeeping
12307 scopes.vFor++;
12308 const onExit = processCodegen && processCodegen(forNode);
12309 return () => {
12310 scopes.vFor--;
12311 if (onExit)
12312 onExit();
12313 };
12314}
12315const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
12316// This regex doesn't cover the case if key or index aliases have destructuring,
12317// but those do not make sense in the first place, so this works in practice.
12318const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
12319const stripParensRE = /^\(|\)$/g;
12320function parseForExpression(input, context) {
12321 const loc = input.loc;
12322 const exp = input.content;
12323 const inMatch = exp.match(forAliasRE);
12324 if (!inMatch)
12325 return;
12326 const [, LHS, RHS] = inMatch;
12327 const result = {
12328 source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
12329 value: undefined,
12330 key: undefined,
12331 index: undefined
12332 };
12333 {
12334 validateBrowserExpression(result.source, context);
12335 }
12336 let valueContent = LHS.trim()
12337 .replace(stripParensRE, '')
12338 .trim();
12339 const trimmedOffset = LHS.indexOf(valueContent);
12340 const iteratorMatch = valueContent.match(forIteratorRE);
12341 if (iteratorMatch) {
12342 valueContent = valueContent.replace(forIteratorRE, '').trim();
12343 const keyContent = iteratorMatch[1].trim();
12344 let keyOffset;
12345 if (keyContent) {
12346 keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
12347 result.key = createAliasExpression(loc, keyContent, keyOffset);
12348 {
12349 validateBrowserExpression(result.key, context, true);
12350 }
12351 }
12352 if (iteratorMatch[2]) {
12353 const indexContent = iteratorMatch[2].trim();
12354 if (indexContent) {
12355 result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
12356 ? keyOffset + keyContent.length
12357 : trimmedOffset + valueContent.length));
12358 {
12359 validateBrowserExpression(result.index, context, true);
12360 }
12361 }
12362 }
12363 }
12364 if (valueContent) {
12365 result.value = createAliasExpression(loc, valueContent, trimmedOffset);
12366 {
12367 validateBrowserExpression(result.value, context, true);
12368 }
12369 }
12370 return result;
12371}
12372function createAliasExpression(range, content, offset) {
12373 return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
12374}
12375function createForLoopParams({ value, key, index }) {
12376 const params = [];
12377 if (value) {
12378 params.push(value);
12379 }
12380 if (key) {
12381 if (!value) {
12382 params.push(createSimpleExpression(`_`, false));
12383 }
12384 params.push(key);
12385 }
12386 if (index) {
12387 if (!key) {
12388 if (!value) {
12389 params.push(createSimpleExpression(`_`, false));
12390 }
12391 params.push(createSimpleExpression(`__`, false));
12392 }
12393 params.push(index);
12394 }
12395 return params;
12396}
12397
12398const defaultFallback = createSimpleExpression(`undefined`, false);
12399// A NodeTransform that:
12400// 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
12401// by transformExpression. This is only applied in non-browser builds with
12402// { prefixIdentifiers: true }.
12403// 2. Track v-slot depths so that we know a slot is inside another slot.
12404// Note the exit callback is executed before buildSlots() on the same node,
12405// so only nested slots see positive numbers.
12406const trackSlotScopes = (node, context) => {
12407 if (node.type === 1 /* ELEMENT */ &&
12408 (node.tagType === 1 /* COMPONENT */ ||
12409 node.tagType === 3 /* TEMPLATE */)) {
12410 // We are only checking non-empty v-slot here
12411 // since we only care about slots that introduce scope variables.
12412 const vSlot = findDir(node, 'slot');
12413 if (vSlot) {
12414 vSlot.exp;
12415 context.scopes.vSlot++;
12416 return () => {
12417 context.scopes.vSlot--;
12418 };
12419 }
12420 }
12421};
12422const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
12423// Instead of being a DirectiveTransform, v-slot processing is called during
12424// transformElement to build the slots object for a component.
12425function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
12426 context.helper(WITH_CTX);
12427 const { children, loc } = node;
12428 const slotsProperties = [];
12429 const dynamicSlots = [];
12430 const buildDefaultSlotProperty = (props, children) => createObjectProperty(`default`, buildSlotFn(props, children, loc));
12431 // If the slot is inside a v-for or another v-slot, force it to be dynamic
12432 // since it likely uses a scope variable.
12433 let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
12434 // 1. Check for slot with slotProps on component itself.
12435 // <Comp v-slot="{ prop }"/>
12436 const onComponentSlot = findDir(node, 'slot', true);
12437 if (onComponentSlot) {
12438 const { arg, exp } = onComponentSlot;
12439 if (arg && !isStaticExp(arg)) {
12440 hasDynamicSlots = true;
12441 }
12442 slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
12443 }
12444 // 2. Iterate through children and check for template slots
12445 // <template v-slot:foo="{ prop }">
12446 let hasTemplateSlots = false;
12447 let hasNamedDefaultSlot = false;
12448 const implicitDefaultChildren = [];
12449 const seenSlotNames = new Set();
12450 for (let i = 0; i < children.length; i++) {
12451 const slotElement = children[i];
12452 let slotDir;
12453 if (!isTemplateNode(slotElement) ||
12454 !(slotDir = findDir(slotElement, 'slot', true))) {
12455 // not a <template v-slot>, skip.
12456 if (slotElement.type !== 3 /* COMMENT */) {
12457 implicitDefaultChildren.push(slotElement);
12458 }
12459 continue;
12460 }
12461 if (onComponentSlot) {
12462 // already has on-component slot - this is incorrect usage.
12463 context.onError(createCompilerError(36 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
12464 break;
12465 }
12466 hasTemplateSlots = true;
12467 const { children: slotChildren, loc: slotLoc } = slotElement;
12468 const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
12469 // check if name is dynamic.
12470 let staticSlotName;
12471 if (isStaticExp(slotName)) {
12472 staticSlotName = slotName ? slotName.content : `default`;
12473 }
12474 else {
12475 hasDynamicSlots = true;
12476 }
12477 const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
12478 // check if this slot is conditional (v-if/v-for)
12479 let vIf;
12480 let vElse;
12481 let vFor;
12482 if ((vIf = findDir(slotElement, 'if'))) {
12483 hasDynamicSlots = true;
12484 dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
12485 }
12486 else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
12487 // find adjacent v-if
12488 let j = i;
12489 let prev;
12490 while (j--) {
12491 prev = children[j];
12492 if (prev.type !== 3 /* COMMENT */) {
12493 break;
12494 }
12495 }
12496 if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
12497 // remove node
12498 children.splice(i, 1);
12499 i--;
12500 // attach this slot to previous conditional
12501 let conditional = dynamicSlots[dynamicSlots.length - 1];
12502 while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
12503 conditional = conditional.alternate;
12504 }
12505 conditional.alternate = vElse.exp
12506 ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
12507 : buildDynamicSlot(slotName, slotFunction);
12508 }
12509 else {
12510 context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
12511 }
12512 }
12513 else if ((vFor = findDir(slotElement, 'for'))) {
12514 hasDynamicSlots = true;
12515 const parseResult = vFor.parseResult ||
12516 parseForExpression(vFor.exp, context);
12517 if (parseResult) {
12518 // Render the dynamic slots as an array and add it to the createSlot()
12519 // args. The runtime knows how to handle it appropriately.
12520 dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
12521 parseResult.source,
12522 createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
12523 ]));
12524 }
12525 else {
12526 context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
12527 }
12528 }
12529 else {
12530 // check duplicate static names
12531 if (staticSlotName) {
12532 if (seenSlotNames.has(staticSlotName)) {
12533 context.onError(createCompilerError(37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
12534 continue;
12535 }
12536 seenSlotNames.add(staticSlotName);
12537 if (staticSlotName === 'default') {
12538 hasNamedDefaultSlot = true;
12539 }
12540 }
12541 slotsProperties.push(createObjectProperty(slotName, slotFunction));
12542 }
12543 }
12544 if (!onComponentSlot) {
12545 if (!hasTemplateSlots) {
12546 // implicit default slot (on component)
12547 slotsProperties.push(buildDefaultSlotProperty(undefined, children));
12548 }
12549 else if (implicitDefaultChildren.length) {
12550 // implicit default slot (mixed with named slots)
12551 if (hasNamedDefaultSlot) {
12552 context.onError(createCompilerError(38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
12553 }
12554 else {
12555 slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
12556 }
12557 }
12558 }
12559 const slotFlag = hasDynamicSlots
12560 ? 2 /* DYNAMIC */
12561 : hasForwardedSlots(node.children)
12562 ? 3 /* FORWARDED */
12563 : 1 /* STABLE */;
12564 let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
12565 // 2 = compiled but dynamic = can skip normalization, but must run diff
12566 // 1 = compiled and static = can skip normalization AND diff as optimized
12567 createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
12568 if (dynamicSlots.length) {
12569 slots = createCallExpression(context.helper(CREATE_SLOTS), [
12570 slots,
12571 createArrayExpression(dynamicSlots)
12572 ]);
12573 }
12574 return {
12575 slots,
12576 hasDynamicSlots
12577 };
12578}
12579function buildDynamicSlot(name, fn) {
12580 return createObjectExpression([
12581 createObjectProperty(`name`, name),
12582 createObjectProperty(`fn`, fn)
12583 ]);
12584}
12585function hasForwardedSlots(children) {
12586 for (let i = 0; i < children.length; i++) {
12587 const child = children[i];
12588 switch (child.type) {
12589 case 1 /* ELEMENT */:
12590 if (child.tagType === 2 /* SLOT */ ||
12591 (child.tagType === 0 /* ELEMENT */ &&
12592 hasForwardedSlots(child.children))) {
12593 return true;
12594 }
12595 break;
12596 case 9 /* IF */:
12597 if (hasForwardedSlots(child.branches))
12598 return true;
12599 break;
12600 case 10 /* IF_BRANCH */:
12601 case 11 /* FOR */:
12602 if (hasForwardedSlots(child.children))
12603 return true;
12604 break;
12605 }
12606 }
12607 return false;
12608}
12609
12610// some directive transforms (e.g. v-model) may return a symbol for runtime
12611// import, which should be used instead of a resolveDirective call.
12612const directiveImportMap = new WeakMap();
12613// generate a JavaScript AST for this element's codegen
12614const transformElement = (node, context) => {
12615 // perform the work on exit, after all child expressions have been
12616 // processed and merged.
12617 return function postTransformElement() {
12618 node = context.currentNode;
12619 if (!(node.type === 1 /* ELEMENT */ &&
12620 (node.tagType === 0 /* ELEMENT */ ||
12621 node.tagType === 1 /* COMPONENT */))) {
12622 return;
12623 }
12624 const { tag, props } = node;
12625 const isComponent = node.tagType === 1 /* COMPONENT */;
12626 // The goal of the transform is to create a codegenNode implementing the
12627 // VNodeCall interface.
12628 const vnodeTag = isComponent
12629 ? resolveComponentType(node, context)
12630 : `"${tag}"`;
12631 const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
12632 let vnodeProps;
12633 let vnodeChildren;
12634 let vnodePatchFlag;
12635 let patchFlag = 0;
12636 let vnodeDynamicProps;
12637 let dynamicPropNames;
12638 let vnodeDirectives;
12639 let shouldUseBlock =
12640 // dynamic component may resolve to plain elements
12641 isDynamicComponent ||
12642 vnodeTag === TELEPORT ||
12643 vnodeTag === SUSPENSE ||
12644 (!isComponent &&
12645 // <svg> and <foreignObject> must be forced into blocks so that block
12646 // updates inside get proper isSVG flag at runtime. (#639, #643)
12647 // This is technically web-specific, but splitting the logic out of core
12648 // leads to too much unnecessary complexity.
12649 (tag === 'svg' ||
12650 tag === 'foreignObject' ||
12651 // #938: elements with dynamic keys should be forced into blocks
12652 findProp(node, 'key', true)));
12653 // props
12654 if (props.length > 0) {
12655 const propsBuildResult = buildProps(node, context);
12656 vnodeProps = propsBuildResult.props;
12657 patchFlag = propsBuildResult.patchFlag;
12658 dynamicPropNames = propsBuildResult.dynamicPropNames;
12659 const directives = propsBuildResult.directives;
12660 vnodeDirectives =
12661 directives && directives.length
12662 ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
12663 : undefined;
12664 }
12665 // children
12666 if (node.children.length > 0) {
12667 if (vnodeTag === KEEP_ALIVE) {
12668 // Although a built-in component, we compile KeepAlive with raw children
12669 // instead of slot functions so that it can be used inside Transition
12670 // or other Transition-wrapping HOCs.
12671 // To ensure correct updates with block optimizations, we need to:
12672 // 1. Force keep-alive into a block. This avoids its children being
12673 // collected by a parent block.
12674 shouldUseBlock = true;
12675 // 2. Force keep-alive to always be updated, since it uses raw children.
12676 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
12677 if (node.children.length > 1) {
12678 context.onError(createCompilerError(44 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
12679 start: node.children[0].loc.start,
12680 end: node.children[node.children.length - 1].loc.end,
12681 source: ''
12682 }));
12683 }
12684 }
12685 const shouldBuildAsSlots = isComponent &&
12686 // Teleport is not a real component and has dedicated runtime handling
12687 vnodeTag !== TELEPORT &&
12688 // explained above.
12689 vnodeTag !== KEEP_ALIVE;
12690 if (shouldBuildAsSlots) {
12691 const { slots, hasDynamicSlots } = buildSlots(node, context);
12692 vnodeChildren = slots;
12693 if (hasDynamicSlots) {
12694 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
12695 }
12696 }
12697 else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
12698 const child = node.children[0];
12699 const type = child.type;
12700 // check for dynamic text children
12701 const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
12702 type === 8 /* COMPOUND_EXPRESSION */;
12703 if (hasDynamicTextChild &&
12704 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
12705 patchFlag |= 1 /* TEXT */;
12706 }
12707 // pass directly if the only child is a text node
12708 // (plain / interpolation / expression)
12709 if (hasDynamicTextChild || type === 2 /* TEXT */) {
12710 vnodeChildren = child;
12711 }
12712 else {
12713 vnodeChildren = node.children;
12714 }
12715 }
12716 else {
12717 vnodeChildren = node.children;
12718 }
12719 }
12720 // patchFlag & dynamicPropNames
12721 if (patchFlag !== 0) {
12722 {
12723 if (patchFlag < 0) {
12724 // special flags (negative and mutually exclusive)
12725 vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
12726 }
12727 else {
12728 // bitwise flags
12729 const flagNames = Object.keys(PatchFlagNames)
12730 .map(Number)
12731 .filter(n => n > 0 && patchFlag & n)
12732 .map(n => PatchFlagNames[n])
12733 .join(`, `);
12734 vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
12735 }
12736 }
12737 if (dynamicPropNames && dynamicPropNames.length) {
12738 vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
12739 }
12740 }
12741 node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, node.loc);
12742 };
12743};
12744function resolveComponentType(node, context, ssr = false) {
12745 const { tag } = node;
12746 // 1. dynamic component
12747 const isProp = isComponentTag(tag)
12748 ? findProp(node, 'is')
12749 : findDir(node, 'is');
12750 if (isProp) {
12751 const exp = isProp.type === 6 /* ATTRIBUTE */
12752 ? isProp.value && createSimpleExpression(isProp.value.content, true)
12753 : isProp.exp;
12754 if (exp) {
12755 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
12756 exp
12757 ]);
12758 }
12759 }
12760 // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
12761 const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
12762 if (builtIn) {
12763 // built-ins are simply fallthroughs / have special handling during ssr
12764 // so we don't need to import their runtime equivalents
12765 if (!ssr)
12766 context.helper(builtIn);
12767 return builtIn;
12768 }
12769 // 5. user component (resolve)
12770 context.helper(RESOLVE_COMPONENT);
12771 context.components.add(tag);
12772 return toValidAssetId(tag, `component`);
12773}
12774function buildProps(node, context, props = node.props, ssr = false) {
12775 const { tag, loc: elementLoc } = node;
12776 const isComponent = node.tagType === 1 /* COMPONENT */;
12777 let properties = [];
12778 const mergeArgs = [];
12779 const runtimeDirectives = [];
12780 // patchFlag analysis
12781 let patchFlag = 0;
12782 let hasRef = false;
12783 let hasClassBinding = false;
12784 let hasStyleBinding = false;
12785 let hasHydrationEventBinding = false;
12786 let hasDynamicKeys = false;
12787 let hasVnodeHook = false;
12788 const dynamicPropNames = [];
12789 const analyzePatchFlag = ({ key, value }) => {
12790 if (isStaticExp(key)) {
12791 const name = key.content;
12792 const isEventHandler = isOn(name);
12793 if (!isComponent &&
12794 isEventHandler &&
12795 // omit the flag for click handlers because hydration gives click
12796 // dedicated fast path.
12797 name.toLowerCase() !== 'onclick' &&
12798 // omit v-model handlers
12799 name !== 'onUpdate:modelValue' &&
12800 // omit onVnodeXXX hooks
12801 !isReservedProp(name)) {
12802 hasHydrationEventBinding = true;
12803 }
12804 if (isEventHandler && isReservedProp(name)) {
12805 hasVnodeHook = true;
12806 }
12807 if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
12808 ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
12809 value.type === 8 /* COMPOUND_EXPRESSION */) &&
12810 getConstantType(value, context) > 0)) {
12811 // skip if the prop is a cached handler or has constant value
12812 return;
12813 }
12814 if (name === 'ref') {
12815 hasRef = true;
12816 }
12817 else if (name === 'class' && !isComponent) {
12818 hasClassBinding = true;
12819 }
12820 else if (name === 'style' && !isComponent) {
12821 hasStyleBinding = true;
12822 }
12823 else if (name !== 'key' && !dynamicPropNames.includes(name)) {
12824 dynamicPropNames.push(name);
12825 }
12826 }
12827 else {
12828 hasDynamicKeys = true;
12829 }
12830 };
12831 for (let i = 0; i < props.length; i++) {
12832 // static attribute
12833 const prop = props[i];
12834 if (prop.type === 6 /* ATTRIBUTE */) {
12835 const { loc, name, value } = prop;
12836 let isStatic = true;
12837 if (name === 'ref') {
12838 hasRef = true;
12839 }
12840 // skip :is on <component>
12841 if (name === 'is' && isComponentTag(tag)) {
12842 continue;
12843 }
12844 properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
12845 }
12846 else {
12847 // directives
12848 const { name, arg, exp, loc } = prop;
12849 const isBind = name === 'bind';
12850 const isOn = name === 'on';
12851 // skip v-slot - it is handled by its dedicated transform.
12852 if (name === 'slot') {
12853 if (!isComponent) {
12854 context.onError(createCompilerError(39 /* X_V_SLOT_MISPLACED */, loc));
12855 }
12856 continue;
12857 }
12858 // skip v-once - it is handled by its dedicated transform.
12859 if (name === 'once') {
12860 continue;
12861 }
12862 // skip v-is and :is on <component>
12863 if (name === 'is' ||
12864 (isBind && isComponentTag(tag) && isBindKey(arg, 'is'))) {
12865 continue;
12866 }
12867 // skip v-on in SSR compilation
12868 if (isOn && ssr) {
12869 continue;
12870 }
12871 // special case for v-bind and v-on with no argument
12872 if (!arg && (isBind || isOn)) {
12873 hasDynamicKeys = true;
12874 if (exp) {
12875 if (properties.length) {
12876 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
12877 properties = [];
12878 }
12879 if (isBind) {
12880 mergeArgs.push(exp);
12881 }
12882 else {
12883 // v-on="obj" -> toHandlers(obj)
12884 mergeArgs.push({
12885 type: 14 /* JS_CALL_EXPRESSION */,
12886 loc,
12887 callee: context.helper(TO_HANDLERS),
12888 arguments: [exp]
12889 });
12890 }
12891 }
12892 else {
12893 context.onError(createCompilerError(isBind
12894 ? 33 /* X_V_BIND_NO_EXPRESSION */
12895 : 34 /* X_V_ON_NO_EXPRESSION */, loc));
12896 }
12897 continue;
12898 }
12899 const directiveTransform = context.directiveTransforms[name];
12900 if (directiveTransform) {
12901 // has built-in directive transform.
12902 const { props, needRuntime } = directiveTransform(prop, node, context);
12903 !ssr && props.forEach(analyzePatchFlag);
12904 properties.push(...props);
12905 if (needRuntime) {
12906 runtimeDirectives.push(prop);
12907 if (isSymbol(needRuntime)) {
12908 directiveImportMap.set(prop, needRuntime);
12909 }
12910 }
12911 }
12912 else {
12913 // no built-in transform, this is a user custom directive.
12914 runtimeDirectives.push(prop);
12915 }
12916 }
12917 }
12918 let propsExpression = undefined;
12919 // has v-bind="object" or v-on="object", wrap with mergeProps
12920 if (mergeArgs.length) {
12921 if (properties.length) {
12922 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
12923 }
12924 if (mergeArgs.length > 1) {
12925 propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
12926 }
12927 else {
12928 // single v-bind with nothing else - no need for a mergeProps call
12929 propsExpression = mergeArgs[0];
12930 }
12931 }
12932 else if (properties.length) {
12933 propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
12934 }
12935 // patchFlag analysis
12936 if (hasDynamicKeys) {
12937 patchFlag |= 16 /* FULL_PROPS */;
12938 }
12939 else {
12940 if (hasClassBinding) {
12941 patchFlag |= 2 /* CLASS */;
12942 }
12943 if (hasStyleBinding) {
12944 patchFlag |= 4 /* STYLE */;
12945 }
12946 if (dynamicPropNames.length) {
12947 patchFlag |= 8 /* PROPS */;
12948 }
12949 if (hasHydrationEventBinding) {
12950 patchFlag |= 32 /* HYDRATE_EVENTS */;
12951 }
12952 }
12953 if ((patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
12954 (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
12955 patchFlag |= 512 /* NEED_PATCH */;
12956 }
12957 return {
12958 props: propsExpression,
12959 directives: runtimeDirectives,
12960 patchFlag,
12961 dynamicPropNames
12962 };
12963}
12964// Dedupe props in an object literal.
12965// Literal duplicated attributes would have been warned during the parse phase,
12966// however, it's possible to encounter duplicated `onXXX` handlers with different
12967// modifiers. We also need to merge static and dynamic class / style attributes.
12968// - onXXX handlers / style: merge into array
12969// - class: merge into single expression with concatenation
12970function dedupeProperties(properties) {
12971 const knownProps = new Map();
12972 const deduped = [];
12973 for (let i = 0; i < properties.length; i++) {
12974 const prop = properties[i];
12975 // dynamic keys are always allowed
12976 if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
12977 deduped.push(prop);
12978 continue;
12979 }
12980 const name = prop.key.content;
12981 const existing = knownProps.get(name);
12982 if (existing) {
12983 if (name === 'style' || name === 'class' || name.startsWith('on')) {
12984 mergeAsArray(existing, prop);
12985 }
12986 // unexpected duplicate, should have emitted error during parse
12987 }
12988 else {
12989 knownProps.set(name, prop);
12990 deduped.push(prop);
12991 }
12992 }
12993 return deduped;
12994}
12995function mergeAsArray(existing, incoming) {
12996 if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
12997 existing.value.elements.push(incoming.value);
12998 }
12999 else {
13000 existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
13001 }
13002}
13003function buildDirectiveArgs(dir, context) {
13004 const dirArgs = [];
13005 const runtime = directiveImportMap.get(dir);
13006 if (runtime) {
13007 // built-in directive with runtime
13008 dirArgs.push(context.helperString(runtime));
13009 }
13010 else {
13011 {
13012 // inject statement for resolving directive
13013 context.helper(RESOLVE_DIRECTIVE);
13014 context.directives.add(dir.name);
13015 dirArgs.push(toValidAssetId(dir.name, `directive`));
13016 }
13017 }
13018 const { loc } = dir;
13019 if (dir.exp)
13020 dirArgs.push(dir.exp);
13021 if (dir.arg) {
13022 if (!dir.exp) {
13023 dirArgs.push(`void 0`);
13024 }
13025 dirArgs.push(dir.arg);
13026 }
13027 if (Object.keys(dir.modifiers).length) {
13028 if (!dir.arg) {
13029 if (!dir.exp) {
13030 dirArgs.push(`void 0`);
13031 }
13032 dirArgs.push(`void 0`);
13033 }
13034 const trueExpression = createSimpleExpression(`true`, false, loc);
13035 dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
13036 }
13037 return createArrayExpression(dirArgs, dir.loc);
13038}
13039function stringifyDynamicPropNames(props) {
13040 let propsNamesString = `[`;
13041 for (let i = 0, l = props.length; i < l; i++) {
13042 propsNamesString += JSON.stringify(props[i]);
13043 if (i < l - 1)
13044 propsNamesString += ', ';
13045 }
13046 return propsNamesString + `]`;
13047}
13048function isComponentTag(tag) {
13049 return tag[0].toLowerCase() + tag.slice(1) === 'component';
13050}
13051
13052const transformSlotOutlet = (node, context) => {
13053 if (isSlotOutlet(node)) {
13054 const { children, loc } = node;
13055 const { slotName, slotProps } = processSlotOutlet(node, context);
13056 const slotArgs = [
13057 context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
13058 slotName
13059 ];
13060 if (slotProps) {
13061 slotArgs.push(slotProps);
13062 }
13063 if (children.length) {
13064 if (!slotProps) {
13065 slotArgs.push(`{}`);
13066 }
13067 slotArgs.push(createFunctionExpression([], children, false, false, loc));
13068 }
13069 if (context.scopeId && !context.slotted) {
13070 if (!slotProps) {
13071 slotArgs.push(`{}`);
13072 }
13073 if (!children.length) {
13074 slotArgs.push(`undefined`);
13075 }
13076 slotArgs.push(`true`);
13077 }
13078 node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
13079 }
13080};
13081function processSlotOutlet(node, context) {
13082 let slotName = `"default"`;
13083 let slotProps = undefined;
13084 const nonNameProps = [];
13085 for (let i = 0; i < node.props.length; i++) {
13086 const p = node.props[i];
13087 if (p.type === 6 /* ATTRIBUTE */) {
13088 if (p.value) {
13089 if (p.name === 'name') {
13090 slotName = JSON.stringify(p.value.content);
13091 }
13092 else {
13093 p.name = camelize(p.name);
13094 nonNameProps.push(p);
13095 }
13096 }
13097 }
13098 else {
13099 if (p.name === 'bind' && isBindKey(p.arg, 'name')) {
13100 if (p.exp)
13101 slotName = p.exp;
13102 }
13103 else {
13104 if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
13105 p.arg.content = camelize(p.arg.content);
13106 }
13107 nonNameProps.push(p);
13108 }
13109 }
13110 }
13111 if (nonNameProps.length > 0) {
13112 const { props, directives } = buildProps(node, context, nonNameProps);
13113 slotProps = props;
13114 if (directives.length) {
13115 context.onError(createCompilerError(35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
13116 }
13117 }
13118 return {
13119 slotName,
13120 slotProps
13121 };
13122}
13123
13124const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^\s*function(?:\s+[\w$]+)?\s*\(/;
13125const transformOn = (dir, node, context, augmentor) => {
13126 const { loc, modifiers, arg } = dir;
13127 if (!dir.exp && !modifiers.length) {
13128 context.onError(createCompilerError(34 /* X_V_ON_NO_EXPRESSION */, loc));
13129 }
13130 let eventName;
13131 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
13132 if (arg.isStatic) {
13133 const rawName = arg.content;
13134 // for all event listeners, auto convert it to camelCase. See issue #2249
13135 eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
13136 }
13137 else {
13138 // #2388
13139 eventName = createCompoundExpression([
13140 `${context.helperString(TO_HANDLER_KEY)}(`,
13141 arg,
13142 `)`
13143 ]);
13144 }
13145 }
13146 else {
13147 // already a compound expression.
13148 eventName = arg;
13149 eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
13150 eventName.children.push(`)`);
13151 }
13152 // handler processing
13153 let exp = dir.exp;
13154 if (exp && !exp.content.trim()) {
13155 exp = undefined;
13156 }
13157 let shouldCache = context.cacheHandlers && !exp;
13158 if (exp) {
13159 const isMemberExp = isMemberExpression(exp.content);
13160 const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
13161 const hasMultipleStatements = exp.content.includes(`;`);
13162 {
13163 validateBrowserExpression(exp, context, false, hasMultipleStatements);
13164 }
13165 if (isInlineStatement || (shouldCache && isMemberExp)) {
13166 // wrap inline statement in a function expression
13167 exp = createCompoundExpression([
13168 `${isInlineStatement
13169 ? `$event`
13170 : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
13171 exp,
13172 hasMultipleStatements ? `}` : `)`
13173 ]);
13174 }
13175 }
13176 let ret = {
13177 props: [
13178 createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
13179 ]
13180 };
13181 // apply extended compiler augmentor
13182 if (augmentor) {
13183 ret = augmentor(ret);
13184 }
13185 if (shouldCache) {
13186 // cache handlers so that it's always the same handler being passed down.
13187 // this avoids unnecessary re-renders when users use inline handlers on
13188 // components.
13189 ret.props[0].value = context.cache(ret.props[0].value);
13190 }
13191 return ret;
13192};
13193
13194// v-bind without arg is handled directly in ./transformElements.ts due to it affecting
13195// codegen for the entire props object. This transform here is only for v-bind
13196// *with* args.
13197const transformBind = (dir, node, context) => {
13198 const { exp, modifiers, loc } = dir;
13199 const arg = dir.arg;
13200 if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
13201 arg.children.unshift(`(`);
13202 arg.children.push(`) || ""`);
13203 }
13204 else if (!arg.isStatic) {
13205 arg.content = `${arg.content} || ""`;
13206 }
13207 // .prop is no longer necessary due to new patch behavior
13208 // .sync is replaced by v-model:arg
13209 if (modifiers.includes('camel')) {
13210 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
13211 if (arg.isStatic) {
13212 arg.content = camelize(arg.content);
13213 }
13214 else {
13215 arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
13216 }
13217 }
13218 else {
13219 arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
13220 arg.children.push(`)`);
13221 }
13222 }
13223 if (!exp ||
13224 (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
13225 context.onError(createCompilerError(33 /* X_V_BIND_NO_EXPRESSION */, loc));
13226 return {
13227 props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
13228 };
13229 }
13230 return {
13231 props: [createObjectProperty(arg, exp)]
13232 };
13233};
13234
13235// Merge adjacent text nodes and expressions into a single expression
13236// e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
13237const transformText = (node, context) => {
13238 if (node.type === 0 /* ROOT */ ||
13239 node.type === 1 /* ELEMENT */ ||
13240 node.type === 11 /* FOR */ ||
13241 node.type === 10 /* IF_BRANCH */) {
13242 // perform the transform on node exit so that all expressions have already
13243 // been processed.
13244 return () => {
13245 const children = node.children;
13246 let currentContainer = undefined;
13247 let hasText = false;
13248 for (let i = 0; i < children.length; i++) {
13249 const child = children[i];
13250 if (isText(child)) {
13251 hasText = true;
13252 for (let j = i + 1; j < children.length; j++) {
13253 const next = children[j];
13254 if (isText(next)) {
13255 if (!currentContainer) {
13256 currentContainer = children[i] = {
13257 type: 8 /* COMPOUND_EXPRESSION */,
13258 loc: child.loc,
13259 children: [child]
13260 };
13261 }
13262 // merge adjacent text node into current
13263 currentContainer.children.push(` + `, next);
13264 children.splice(j, 1);
13265 j--;
13266 }
13267 else {
13268 currentContainer = undefined;
13269 break;
13270 }
13271 }
13272 }
13273 }
13274 if (!hasText ||
13275 // if this is a plain element with a single text child, leave it
13276 // as-is since the runtime has dedicated fast path for this by directly
13277 // setting textContent of the element.
13278 // for component root it's always normalized anyway.
13279 (children.length === 1 &&
13280 (node.type === 0 /* ROOT */ ||
13281 (node.type === 1 /* ELEMENT */ &&
13282 node.tagType === 0 /* ELEMENT */)))) {
13283 return;
13284 }
13285 // pre-convert text nodes into createTextVNode(text) calls to avoid
13286 // runtime normalization.
13287 for (let i = 0; i < children.length; i++) {
13288 const child = children[i];
13289 if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
13290 const callArgs = [];
13291 // createTextVNode defaults to single whitespace, so if it is a
13292 // single space the code could be an empty call to save bytes.
13293 if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
13294 callArgs.push(child);
13295 }
13296 // mark dynamic text with flag so it gets patched inside a block
13297 if (!context.ssr &&
13298 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
13299 callArgs.push(1 /* TEXT */ +
13300 (` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
13301 }
13302 children[i] = {
13303 type: 12 /* TEXT_CALL */,
13304 content: child,
13305 loc: child.loc,
13306 codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
13307 };
13308 }
13309 }
13310 };
13311 }
13312};
13313
13314const seen = new WeakSet();
13315const transformOnce = (node, context) => {
13316 if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
13317 if (seen.has(node)) {
13318 return;
13319 }
13320 seen.add(node);
13321 context.helper(SET_BLOCK_TRACKING);
13322 return () => {
13323 const cur = context.currentNode;
13324 if (cur.codegenNode) {
13325 cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
13326 }
13327 };
13328 }
13329};
13330
13331const transformModel = (dir, node, context) => {
13332 const { exp, arg } = dir;
13333 if (!exp) {
13334 context.onError(createCompilerError(40 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
13335 return createTransformProps();
13336 }
13337 const rawExp = exp.loc.source;
13338 const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
13339 // im SFC <script setup> inline mode, the exp may have been transformed into
13340 // _unref(exp)
13341 context.bindingMetadata[rawExp];
13342 const maybeRef = !true /* SETUP_CONST */;
13343 if (!isMemberExpression(expString) && !maybeRef) {
13344 context.onError(createCompilerError(41 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
13345 return createTransformProps();
13346 }
13347 const propName = arg ? arg : createSimpleExpression('modelValue', true);
13348 const eventName = arg
13349 ? isStaticExp(arg)
13350 ? `onUpdate:${arg.content}`
13351 : createCompoundExpression(['"onUpdate:" + ', arg])
13352 : `onUpdate:modelValue`;
13353 let assignmentExp;
13354 const eventArg = context.isTS ? `($event: any)` : `$event`;
13355 {
13356 assignmentExp = createCompoundExpression([
13357 `${eventArg} => (`,
13358 exp,
13359 ` = $event)`
13360 ]);
13361 }
13362 const props = [
13363 // modelValue: foo
13364 createObjectProperty(propName, dir.exp),
13365 // "onUpdate:modelValue": $event => (foo = $event)
13366 createObjectProperty(eventName, assignmentExp)
13367 ];
13368 // modelModifiers: { foo: true, "bar-baz": true }
13369 if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
13370 const modifiers = dir.modifiers
13371 .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
13372 .join(`, `);
13373 const modifiersKey = arg
13374 ? isStaticExp(arg)
13375 ? `${arg.content}Modifiers`
13376 : createCompoundExpression([arg, ' + "Modifiers"'])
13377 : `modelModifiers`;
13378 props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
13379 }
13380 return createTransformProps(props);
13381};
13382function createTransformProps(props = []) {
13383 return { props };
13384}
13385
13386function getBaseTransformPreset(prefixIdentifiers) {
13387 return [
13388 [
13389 transformOnce,
13390 transformIf,
13391 transformFor,
13392 ...([transformExpression]
13393 ),
13394 transformSlotOutlet,
13395 transformElement,
13396 trackSlotScopes,
13397 transformText
13398 ],
13399 {
13400 on: transformOn,
13401 bind: transformBind,
13402 model: transformModel
13403 }
13404 ];
13405}
13406// we name it `baseCompile` so that higher order compilers like
13407// @vue/compiler-dom can export `compile` while re-exporting everything else.
13408function baseCompile(template, options = {}) {
13409 const onError = options.onError || defaultOnError;
13410 const isModuleMode = options.mode === 'module';
13411 /* istanbul ignore if */
13412 {
13413 if (options.prefixIdentifiers === true) {
13414 onError(createCompilerError(45 /* X_PREFIX_ID_NOT_SUPPORTED */));
13415 }
13416 else if (isModuleMode) {
13417 onError(createCompilerError(46 /* X_MODULE_MODE_NOT_SUPPORTED */));
13418 }
13419 }
13420 const prefixIdentifiers = !true ;
13421 if (options.cacheHandlers) {
13422 onError(createCompilerError(47 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
13423 }
13424 if (options.scopeId && !isModuleMode) {
13425 onError(createCompilerError(48 /* X_SCOPE_ID_NOT_SUPPORTED */));
13426 }
13427 const ast = isString(template) ? baseParse(template, options) : template;
13428 const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
13429 transform(ast, extend({}, options, {
13430 prefixIdentifiers,
13431 nodeTransforms: [
13432 ...nodeTransforms,
13433 ...(options.nodeTransforms || []) // user transforms
13434 ],
13435 directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
13436 )
13437 }));
13438 return generate(ast, extend({}, options, {
13439 prefixIdentifiers
13440 }));
13441}
13442
13443const noopDirectiveTransform = () => ({ props: [] });
13444
13445const V_MODEL_RADIO = Symbol(`vModelRadio` );
13446const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
13447const V_MODEL_TEXT = Symbol(`vModelText` );
13448const V_MODEL_SELECT = Symbol(`vModelSelect` );
13449const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
13450const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
13451const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
13452const V_SHOW = Symbol(`vShow` );
13453const TRANSITION$1 = Symbol(`Transition` );
13454const TRANSITION_GROUP = Symbol(`TransitionGroup` );
13455registerRuntimeHelpers({
13456 [V_MODEL_RADIO]: `vModelRadio`,
13457 [V_MODEL_CHECKBOX]: `vModelCheckbox`,
13458 [V_MODEL_TEXT]: `vModelText`,
13459 [V_MODEL_SELECT]: `vModelSelect`,
13460 [V_MODEL_DYNAMIC]: `vModelDynamic`,
13461 [V_ON_WITH_MODIFIERS]: `withModifiers`,
13462 [V_ON_WITH_KEYS]: `withKeys`,
13463 [V_SHOW]: `vShow`,
13464 [TRANSITION$1]: `Transition`,
13465 [TRANSITION_GROUP]: `TransitionGroup`
13466});
13467
13468/* eslint-disable no-restricted-globals */
13469let decoder;
13470function decodeHtmlBrowser(raw) {
13471 (decoder || (decoder = document.createElement('div'))).innerHTML = raw;
13472 return decoder.textContent;
13473}
13474
13475const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
13476const parserOptions = {
13477 isVoidTag,
13478 isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
13479 isPreTag: tag => tag === 'pre',
13480 decodeEntities: decodeHtmlBrowser ,
13481 isBuiltInComponent: (tag) => {
13482 if (isBuiltInType(tag, `Transition`)) {
13483 return TRANSITION$1;
13484 }
13485 else if (isBuiltInType(tag, `TransitionGroup`)) {
13486 return TRANSITION_GROUP;
13487 }
13488 },
13489 // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
13490 getNamespace(tag, parent) {
13491 let ns = parent ? parent.ns : 0 /* HTML */;
13492 if (parent && ns === 2 /* MATH_ML */) {
13493 if (parent.tag === 'annotation-xml') {
13494 if (tag === 'svg') {
13495 return 1 /* SVG */;
13496 }
13497 if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
13498 a.name === 'encoding' &&
13499 a.value != null &&
13500 (a.value.content === 'text/html' ||
13501 a.value.content === 'application/xhtml+xml'))) {
13502 ns = 0 /* HTML */;
13503 }
13504 }
13505 else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
13506 tag !== 'mglyph' &&
13507 tag !== 'malignmark') {
13508 ns = 0 /* HTML */;
13509 }
13510 }
13511 else if (parent && ns === 1 /* SVG */) {
13512 if (parent.tag === 'foreignObject' ||
13513 parent.tag === 'desc' ||
13514 parent.tag === 'title') {
13515 ns = 0 /* HTML */;
13516 }
13517 }
13518 if (ns === 0 /* HTML */) {
13519 if (tag === 'svg') {
13520 return 1 /* SVG */;
13521 }
13522 if (tag === 'math') {
13523 return 2 /* MATH_ML */;
13524 }
13525 }
13526 return ns;
13527 },
13528 // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
13529 getTextMode({ tag, ns }) {
13530 if (ns === 0 /* HTML */) {
13531 if (tag === 'textarea' || tag === 'title') {
13532 return 1 /* RCDATA */;
13533 }
13534 if (isRawTextContainer(tag)) {
13535 return 2 /* RAWTEXT */;
13536 }
13537 }
13538 return 0 /* DATA */;
13539 }
13540};
13541
13542// Parse inline CSS strings for static style attributes into an object.
13543// This is a NodeTransform since it works on the static `style` attribute and
13544// converts it into a dynamic equivalent:
13545// style="color: red" -> :style='{ "color": "red" }'
13546// It is then processed by `transformElement` and included in the generated
13547// props.
13548const transformStyle = node => {
13549 if (node.type === 1 /* ELEMENT */) {
13550 node.props.forEach((p, i) => {
13551 if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
13552 // replace p with an expression node
13553 node.props[i] = {
13554 type: 7 /* DIRECTIVE */,
13555 name: `bind`,
13556 arg: createSimpleExpression(`style`, true, p.loc),
13557 exp: parseInlineCSS(p.value.content, p.loc),
13558 modifiers: [],
13559 loc: p.loc
13560 };
13561 }
13562 });
13563 }
13564};
13565const parseInlineCSS = (cssText, loc) => {
13566 const normalized = parseStringStyle(cssText);
13567 return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
13568};
13569
13570function createDOMCompilerError(code, loc) {
13571 return createCompilerError(code, loc, DOMErrorMessages );
13572}
13573const DOMErrorMessages = {
13574 [49 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
13575 [50 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
13576 [51 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
13577 [52 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
13578 [53 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
13579 [54 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
13580 [55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
13581 [56 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
13582 [57 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
13583 [58 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
13584 [59 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
13585};
13586
13587const transformVHtml = (dir, node, context) => {
13588 const { exp, loc } = dir;
13589 if (!exp) {
13590 context.onError(createDOMCompilerError(49 /* X_V_HTML_NO_EXPRESSION */, loc));
13591 }
13592 if (node.children.length) {
13593 context.onError(createDOMCompilerError(50 /* X_V_HTML_WITH_CHILDREN */, loc));
13594 node.children.length = 0;
13595 }
13596 return {
13597 props: [
13598 createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
13599 ]
13600 };
13601};
13602
13603const transformVText = (dir, node, context) => {
13604 const { exp, loc } = dir;
13605 if (!exp) {
13606 context.onError(createDOMCompilerError(51 /* X_V_TEXT_NO_EXPRESSION */, loc));
13607 }
13608 if (node.children.length) {
13609 context.onError(createDOMCompilerError(52 /* X_V_TEXT_WITH_CHILDREN */, loc));
13610 node.children.length = 0;
13611 }
13612 return {
13613 props: [
13614 createObjectProperty(createSimpleExpression(`textContent`, true), exp
13615 ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
13616 : createSimpleExpression('', true))
13617 ]
13618 };
13619};
13620
13621const transformModel$1 = (dir, node, context) => {
13622 const baseResult = transformModel(dir, node, context);
13623 // base transform has errors OR component v-model (only need props)
13624 if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
13625 return baseResult;
13626 }
13627 if (dir.arg) {
13628 context.onError(createDOMCompilerError(54 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
13629 }
13630 function checkDuplicatedValue() {
13631 const value = findProp(node, 'value');
13632 if (value) {
13633 context.onError(createDOMCompilerError(56 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
13634 }
13635 }
13636 const { tag } = node;
13637 const isCustomElement = context.isCustomElement(tag);
13638 if (tag === 'input' ||
13639 tag === 'textarea' ||
13640 tag === 'select' ||
13641 isCustomElement) {
13642 let directiveToUse = V_MODEL_TEXT;
13643 let isInvalidType = false;
13644 if (tag === 'input' || isCustomElement) {
13645 const type = findProp(node, `type`);
13646 if (type) {
13647 if (type.type === 7 /* DIRECTIVE */) {
13648 // :type="foo"
13649 directiveToUse = V_MODEL_DYNAMIC;
13650 }
13651 else if (type.value) {
13652 switch (type.value.content) {
13653 case 'radio':
13654 directiveToUse = V_MODEL_RADIO;
13655 break;
13656 case 'checkbox':
13657 directiveToUse = V_MODEL_CHECKBOX;
13658 break;
13659 case 'file':
13660 isInvalidType = true;
13661 context.onError(createDOMCompilerError(55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
13662 break;
13663 default:
13664 // text type
13665 checkDuplicatedValue();
13666 break;
13667 }
13668 }
13669 }
13670 else if (hasDynamicKeyVBind(node)) {
13671 // element has bindings with dynamic keys, which can possibly contain
13672 // "type".
13673 directiveToUse = V_MODEL_DYNAMIC;
13674 }
13675 else {
13676 // text type
13677 checkDuplicatedValue();
13678 }
13679 }
13680 else if (tag === 'select') {
13681 directiveToUse = V_MODEL_SELECT;
13682 }
13683 else {
13684 // textarea
13685 checkDuplicatedValue();
13686 }
13687 // inject runtime directive
13688 // by returning the helper symbol via needRuntime
13689 // the import will replaced a resolveDirective call.
13690 if (!isInvalidType) {
13691 baseResult.needRuntime = context.helper(directiveToUse);
13692 }
13693 }
13694 else {
13695 context.onError(createDOMCompilerError(53 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
13696 }
13697 // native vmodel doesn't need the `modelValue` props since they are also
13698 // passed to the runtime as `binding.value`. removing it reduces code size.
13699 baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
13700 p.key.content === 'modelValue'));
13701 return baseResult;
13702};
13703
13704const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
13705const isNonKeyModifier = /*#__PURE__*/ makeMap(
13706// event propagation management
13707`stop,prevent,self,` +
13708 // system modifiers + exact
13709 `ctrl,shift,alt,meta,exact,` +
13710 // mouse
13711 `middle`);
13712// left & right could be mouse or key modifiers based on event type
13713const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
13714const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
13715const resolveModifiers = (key, modifiers) => {
13716 const keyModifiers = [];
13717 const nonKeyModifiers = [];
13718 const eventOptionModifiers = [];
13719 for (let i = 0; i < modifiers.length; i++) {
13720 const modifier = modifiers[i];
13721 if (isEventOptionModifier(modifier)) {
13722 // eventOptionModifiers: modifiers for addEventListener() options,
13723 // e.g. .passive & .capture
13724 eventOptionModifiers.push(modifier);
13725 }
13726 else {
13727 // runtimeModifiers: modifiers that needs runtime guards
13728 if (maybeKeyModifier(modifier)) {
13729 if (isStaticExp(key)) {
13730 if (isKeyboardEvent(key.content)) {
13731 keyModifiers.push(modifier);
13732 }
13733 else {
13734 nonKeyModifiers.push(modifier);
13735 }
13736 }
13737 else {
13738 keyModifiers.push(modifier);
13739 nonKeyModifiers.push(modifier);
13740 }
13741 }
13742 else {
13743 if (isNonKeyModifier(modifier)) {
13744 nonKeyModifiers.push(modifier);
13745 }
13746 else {
13747 keyModifiers.push(modifier);
13748 }
13749 }
13750 }
13751 }
13752 return {
13753 keyModifiers,
13754 nonKeyModifiers,
13755 eventOptionModifiers
13756 };
13757};
13758const transformClick = (key, event) => {
13759 const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
13760 return isStaticClick
13761 ? createSimpleExpression(event, true)
13762 : key.type !== 4 /* SIMPLE_EXPRESSION */
13763 ? createCompoundExpression([
13764 `(`,
13765 key,
13766 `) === "onClick" ? "${event}" : (`,
13767 key,
13768 `)`
13769 ])
13770 : key;
13771};
13772const transformOn$1 = (dir, node, context) => {
13773 return transformOn(dir, node, context, baseResult => {
13774 const { modifiers } = dir;
13775 if (!modifiers.length)
13776 return baseResult;
13777 let { key, value: handlerExp } = baseResult.props[0];
13778 const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers);
13779 // normalize click.right and click.middle since they don't actually fire
13780 if (nonKeyModifiers.includes('right')) {
13781 key = transformClick(key, `onContextmenu`);
13782 }
13783 if (nonKeyModifiers.includes('middle')) {
13784 key = transformClick(key, `onMouseup`);
13785 }
13786 if (nonKeyModifiers.length) {
13787 handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
13788 handlerExp,
13789 JSON.stringify(nonKeyModifiers)
13790 ]);
13791 }
13792 if (keyModifiers.length &&
13793 // if event name is dynamic, always wrap with keys guard
13794 (!isStaticExp(key) || isKeyboardEvent(key.content))) {
13795 handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
13796 handlerExp,
13797 JSON.stringify(keyModifiers)
13798 ]);
13799 }
13800 if (eventOptionModifiers.length) {
13801 const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
13802 key = isStaticExp(key)
13803 ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
13804 : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
13805 }
13806 return {
13807 props: [createObjectProperty(key, handlerExp)]
13808 };
13809 });
13810};
13811
13812const transformShow = (dir, node, context) => {
13813 const { exp, loc } = dir;
13814 if (!exp) {
13815 context.onError(createDOMCompilerError(57 /* X_V_SHOW_NO_EXPRESSION */, loc));
13816 }
13817 return {
13818 props: [],
13819 needRuntime: context.helper(V_SHOW)
13820 };
13821};
13822
13823const warnTransitionChildren = (node, context) => {
13824 if (node.type === 1 /* ELEMENT */ &&
13825 node.tagType === 1 /* COMPONENT */) {
13826 const component = context.isBuiltInComponent(node.tag);
13827 if (component === TRANSITION$1) {
13828 return () => {
13829 if (node.children.length && hasMultipleChildren(node)) {
13830 context.onError(createDOMCompilerError(58 /* X_TRANSITION_INVALID_CHILDREN */, {
13831 start: node.children[0].loc.start,
13832 end: node.children[node.children.length - 1].loc.end,
13833 source: ''
13834 }));
13835 }
13836 };
13837 }
13838 }
13839};
13840function hasMultipleChildren(node) {
13841 // #1352 filter out potential comment nodes.
13842 const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */));
13843 const child = children[0];
13844 return (children.length !== 1 ||
13845 child.type === 11 /* FOR */ ||
13846 (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
13847}
13848
13849const ignoreSideEffectTags = (node, context) => {
13850 if (node.type === 1 /* ELEMENT */ &&
13851 node.tagType === 0 /* ELEMENT */ &&
13852 (node.tag === 'script' || node.tag === 'style')) {
13853 context.onError(createDOMCompilerError(59 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
13854 context.removeNode();
13855 }
13856};
13857
13858const DOMNodeTransforms = [
13859 transformStyle,
13860 ...([warnTransitionChildren] )
13861];
13862const DOMDirectiveTransforms = {
13863 cloak: noopDirectiveTransform,
13864 html: transformVHtml,
13865 text: transformVText,
13866 model: transformModel$1,
13867 on: transformOn$1,
13868 show: transformShow
13869};
13870function compile$1(template, options = {}) {
13871 return baseCompile(template, extend({}, parserOptions, options, {
13872 nodeTransforms: [
13873 // ignore <script> and <tag>
13874 // this is not put inside DOMNodeTransforms because that list is used
13875 // by compiler-ssr to generate vnode fallback branches
13876 ignoreSideEffectTags,
13877 ...DOMNodeTransforms,
13878 ...(options.nodeTransforms || [])
13879 ],
13880 directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
13881 transformHoist: null
13882 }));
13883}
13884
13885// This entry is the "full-build" that includes both the runtime
13886{
13887 initDev();
13888}
13889const compileCache = Object.create(null);
13890function compileToFunction(template, options) {
13891 if (!isString(template)) {
13892 if (template.nodeType) {
13893 template = template.innerHTML;
13894 }
13895 else {
13896 warn(`invalid template option: `, template);
13897 return NOOP;
13898 }
13899 }
13900 const key = template;
13901 const cached = compileCache[key];
13902 if (cached) {
13903 return cached;
13904 }
13905 if (template[0] === '#') {
13906 const el = document.querySelector(template);
13907 if (!el) {
13908 warn(`Template element not found or is empty: ${template}`);
13909 }
13910 // __UNSAFE__
13911 // Reason: potential execution of JS expressions in in-DOM template.
13912 // The user must make sure the in-DOM template is trusted. If it's rendered
13913 // by the server, the template should not contain any user data.
13914 template = el ? el.innerHTML : ``;
13915 }
13916 const { code } = compile$1(template, extend({
13917 hoistStatic: true,
13918 onError(err) {
13919 {
13920 const message = `Template compilation error: ${err.message}`;
13921 const codeFrame = err.loc &&
13922 generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
13923 warn(codeFrame ? `${message}\n${codeFrame}` : message);
13924 }
13925 }
13926 }, options));
13927 // The wildcard import results in a huge object with every export
13928 // with keys that cannot be mangled, and can be quite heavy size-wise.
13929 // In the global build we know `Vue` is available globally so we can avoid
13930 // the wildcard object.
13931 const render = (new Function('Vue', code)(runtimeDom));
13932 render._rc = true;
13933 return (compileCache[key] = render);
13934}
13935registerRuntimeCompiler(compileToFunction);
13936
13937export { BaseTransition, Comment, Fragment, KeepAlive, Static, Suspense, Teleport, Text, Transition, TransitionGroup, callWithAsyncErrorHandling, callWithErrorHandling, camelize, capitalize, cloneVNode, compileToFunction as compile, computed$1 as computed, createApp, createBlock, createCommentVNode, createHydrationRenderer, createRenderer, createSSRApp, createSlots, createStaticVNode, createTextVNode, createVNode, customRef, defineAsyncComponent, defineComponent, defineEmit, defineProps, devtools, getCurrentInstance, getTransitionRawChildren, h, handleError, hydrate, initCustomFormatter, inject, isProxy, isReactive, isReadonly, isRef, isRuntimeOnly, isVNode, markRaw, mergeProps, nextTick, onActivated, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onErrorCaptured, onMounted, onRenderTracked, onRenderTriggered, onUnmounted, onUpdated, openBlock, popScopeId, provide, proxyRefs, pushScopeId, queuePostFlushCb, reactive, readonly, ref, registerRuntimeCompiler, render, renderList, renderSlot, resolveComponent, resolveDirective, resolveDynamicComponent, resolveTransitionHooks, setBlockTracking, setDevtoolsHook, setTransitionHooks, shallowReactive, shallowReadonly, shallowRef, ssrContextKey, ssrUtils, toDisplayString, toHandlerKey, toHandlers, toRaw, toRef, toRefs, transformVNodeArgs, triggerRef, unref, useContext, useCssModule, useCssVars, useSSRContext, useTransitionState, vModelCheckbox, vModelDynamic, vModelRadio, vModelSelect, vModelText, vShow, version, warn, watch, watchEffect, withCtx, withDirectives, withKeys, withModifiers, withScopeId };