UNPKG

606 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 // Split the content into individual lines but capture the newline sequence
54 // that separated each line. This is important because the actual sequence is
55 // needed to properly take into account the full line length for offset
56 // comparison
57 let lines = source.split(/(\r?\n)/);
58 // Separate the lines and newline sequences into separate arrays for easier referencing
59 const newlineSequences = lines.filter((_, idx) => idx % 2 === 1);
60 lines = lines.filter((_, idx) => idx % 2 === 0);
61 let count = 0;
62 const res = [];
63 for (let i = 0; i < lines.length; i++) {
64 count +=
65 lines[i].length +
66 ((newlineSequences[i] && newlineSequences[i].length) || 0);
67 if (count >= start) {
68 for (let j = i - range; j <= i + range || end > count; j++) {
69 if (j < 0 || j >= lines.length)
70 continue;
71 const line = j + 1;
72 res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
73 const lineLength = lines[j].length;
74 const newLineSeqLength = (newlineSequences[j] && newlineSequences[j].length) || 0;
75 if (j === i) {
76 // push underline
77 const pad = start - (count - (lineLength + newLineSeqLength));
78 const length = Math.max(1, end > count ? lineLength - pad : end - start);
79 res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
80 }
81 else if (j > i) {
82 if (end > count) {
83 const length = Math.max(Math.min(end - count, lineLength), 1);
84 res.push(` | ` + '^'.repeat(length));
85 }
86 count += lineLength + newLineSeqLength;
87 }
88 }
89 break;
90 }
91 }
92 return res.join('\n');
93}
94
95/**
96 * On the client we only need to offer special cases for boolean attributes that
97 * have different names from their corresponding dom properties:
98 * - itemscope -> N/A
99 * - allowfullscreen -> allowFullscreen
100 * - formnovalidate -> formNoValidate
101 * - ismap -> isMap
102 * - nomodule -> noModule
103 * - novalidate -> noValidate
104 * - readonly -> readOnly
105 */
106const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
107const isSpecialBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs);
108/**
109 * Boolean attributes should be included if the value is truthy or ''.
110 * e.g. `<select multiple>` compiles to `{ multiple: '' }`
111 */
112function includeBooleanAttr(value) {
113 return !!value || value === '';
114}
115
116function normalizeStyle(value) {
117 if (isArray(value)) {
118 const res = {};
119 for (let i = 0; i < value.length; i++) {
120 const item = value[i];
121 const normalized = isString(item)
122 ? parseStringStyle(item)
123 : normalizeStyle(item);
124 if (normalized) {
125 for (const key in normalized) {
126 res[key] = normalized[key];
127 }
128 }
129 }
130 return res;
131 }
132 else if (isString(value)) {
133 return value;
134 }
135 else if (isObject(value)) {
136 return value;
137 }
138}
139const listDelimiterRE = /;(?![^(]*\))/g;
140const propertyDelimiterRE = /:(.+)/;
141function parseStringStyle(cssText) {
142 const ret = {};
143 cssText.split(listDelimiterRE).forEach(item => {
144 if (item) {
145 const tmp = item.split(propertyDelimiterRE);
146 tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
147 }
148 });
149 return ret;
150}
151function normalizeClass(value) {
152 let res = '';
153 if (isString(value)) {
154 res = value;
155 }
156 else if (isArray(value)) {
157 for (let i = 0; i < value.length; i++) {
158 const normalized = normalizeClass(value[i]);
159 if (normalized) {
160 res += normalized + ' ';
161 }
162 }
163 }
164 else if (isObject(value)) {
165 for (const name in value) {
166 if (value[name]) {
167 res += name + ' ';
168 }
169 }
170 }
171 return res.trim();
172}
173function normalizeProps(props) {
174 if (!props)
175 return null;
176 let { class: klass, style } = props;
177 if (klass && !isString(klass)) {
178 props.class = normalizeClass(klass);
179 }
180 if (style) {
181 props.style = normalizeStyle(style);
182 }
183 return props;
184}
185
186// These tag configs are shared between compiler-dom and runtime-dom, so they
187// https://developer.mozilla.org/en-US/docs/Web/HTML/Element
188const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
189 'header,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,' +
190 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
191 'data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,' +
192 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
193 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
194 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
195 'option,output,progress,select,textarea,details,dialog,menu,' +
196 'summary,template,blockquote,iframe,tfoot';
197// https://developer.mozilla.org/en-US/docs/Web/SVG/Element
198const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
199 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
200 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
201 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
202 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
203 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
204 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
205 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
206 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
207 'text,textPath,title,tspan,unknown,use,view';
208const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
209/**
210 * Compiler only.
211 * Do NOT use in runtime code paths unless behind `true` flag.
212 */
213const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
214/**
215 * Compiler only.
216 * Do NOT use in runtime code paths unless behind `true` flag.
217 */
218const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
219/**
220 * Compiler only.
221 * Do NOT use in runtime code paths unless behind `true` flag.
222 */
223const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
224
225function looseCompareArrays(a, b) {
226 if (a.length !== b.length)
227 return false;
228 let equal = true;
229 for (let i = 0; equal && i < a.length; i++) {
230 equal = looseEqual(a[i], b[i]);
231 }
232 return equal;
233}
234function looseEqual(a, b) {
235 if (a === b)
236 return true;
237 let aValidType = isDate(a);
238 let bValidType = isDate(b);
239 if (aValidType || bValidType) {
240 return aValidType && bValidType ? a.getTime() === b.getTime() : false;
241 }
242 aValidType = isArray(a);
243 bValidType = isArray(b);
244 if (aValidType || bValidType) {
245 return aValidType && bValidType ? looseCompareArrays(a, b) : false;
246 }
247 aValidType = isObject(a);
248 bValidType = isObject(b);
249 if (aValidType || bValidType) {
250 /* istanbul ignore if: this if will probably never be called */
251 if (!aValidType || !bValidType) {
252 return false;
253 }
254 const aKeysCount = Object.keys(a).length;
255 const bKeysCount = Object.keys(b).length;
256 if (aKeysCount !== bKeysCount) {
257 return false;
258 }
259 for (const key in a) {
260 const aHasKey = a.hasOwnProperty(key);
261 const bHasKey = b.hasOwnProperty(key);
262 if ((aHasKey && !bHasKey) ||
263 (!aHasKey && bHasKey) ||
264 !looseEqual(a[key], b[key])) {
265 return false;
266 }
267 }
268 }
269 return String(a) === String(b);
270}
271function looseIndexOf(arr, val) {
272 return arr.findIndex(item => looseEqual(item, val));
273}
274
275/**
276 * For converting {{ interpolation }} values to displayed strings.
277 * @private
278 */
279const toDisplayString = (val) => {
280 return isString(val)
281 ? val
282 : val == null
283 ? ''
284 : isArray(val) ||
285 (isObject(val) &&
286 (val.toString === objectToString || !isFunction(val.toString)))
287 ? JSON.stringify(val, replacer, 2)
288 : String(val);
289};
290const replacer = (_key, val) => {
291 // can't use isRef here since @vue/shared has no deps
292 if (val && val.__v_isRef) {
293 return replacer(_key, val.value);
294 }
295 else if (isMap(val)) {
296 return {
297 [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
298 entries[`${key} =>`] = val;
299 return entries;
300 }, {})
301 };
302 }
303 else if (isSet(val)) {
304 return {
305 [`Set(${val.size})`]: [...val.values()]
306 };
307 }
308 else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
309 return String(val);
310 }
311 return val;
312};
313
314const EMPTY_OBJ = Object.freeze({})
315 ;
316const EMPTY_ARR = Object.freeze([]) ;
317const NOOP = () => { };
318/**
319 * Always return false.
320 */
321const NO = () => false;
322const onRE = /^on[^a-z]/;
323const isOn = (key) => onRE.test(key);
324const isModelListener = (key) => key.startsWith('onUpdate:');
325const extend = Object.assign;
326const remove = (arr, el) => {
327 const i = arr.indexOf(el);
328 if (i > -1) {
329 arr.splice(i, 1);
330 }
331};
332const hasOwnProperty = Object.prototype.hasOwnProperty;
333const hasOwn = (val, key) => hasOwnProperty.call(val, key);
334const isArray = Array.isArray;
335const isMap = (val) => toTypeString(val) === '[object Map]';
336const isSet = (val) => toTypeString(val) === '[object Set]';
337const isDate = (val) => val instanceof Date;
338const isFunction = (val) => typeof val === 'function';
339const isString = (val) => typeof val === 'string';
340const isSymbol = (val) => typeof val === 'symbol';
341const isObject = (val) => val !== null && typeof val === 'object';
342const isPromise = (val) => {
343 return isObject(val) && isFunction(val.then) && isFunction(val.catch);
344};
345const objectToString = Object.prototype.toString;
346const toTypeString = (value) => objectToString.call(value);
347const toRawType = (value) => {
348 // extract "RawType" from strings like "[object RawType]"
349 return toTypeString(value).slice(8, -1);
350};
351const isPlainObject = (val) => toTypeString(val) === '[object Object]';
352const isIntegerKey = (key) => isString(key) &&
353 key !== 'NaN' &&
354 key[0] !== '-' &&
355 '' + parseInt(key, 10) === key;
356const isReservedProp = /*#__PURE__*/ makeMap(
357// the leading comma is intentional so empty string "" is also included
358',key,ref,ref_for,ref_key,' +
359 'onVnodeBeforeMount,onVnodeMounted,' +
360 'onVnodeBeforeUpdate,onVnodeUpdated,' +
361 'onVnodeBeforeUnmount,onVnodeUnmounted');
362const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo');
363const cacheStringFunction = (fn) => {
364 const cache = Object.create(null);
365 return ((str) => {
366 const hit = cache[str];
367 return hit || (cache[str] = fn(str));
368 });
369};
370const camelizeRE = /-(\w)/g;
371/**
372 * @private
373 */
374const camelize = cacheStringFunction((str) => {
375 return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
376});
377const hyphenateRE = /\B([A-Z])/g;
378/**
379 * @private
380 */
381const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
382/**
383 * @private
384 */
385const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
386/**
387 * @private
388 */
389const toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``);
390// compare whether a value has changed, accounting for NaN.
391const hasChanged = (value, oldValue) => !Object.is(value, oldValue);
392const invokeArrayFns = (fns, arg) => {
393 for (let i = 0; i < fns.length; i++) {
394 fns[i](arg);
395 }
396};
397const def = (obj, key, value) => {
398 Object.defineProperty(obj, key, {
399 configurable: true,
400 enumerable: false,
401 value
402 });
403};
404const toNumber = (val) => {
405 const n = parseFloat(val);
406 return isNaN(n) ? val : n;
407};
408let _globalThis;
409const getGlobalThis = () => {
410 return (_globalThis ||
411 (_globalThis =
412 typeof globalThis !== 'undefined'
413 ? globalThis
414 : typeof self !== 'undefined'
415 ? self
416 : typeof window !== 'undefined'
417 ? window
418 : typeof global !== 'undefined'
419 ? global
420 : {}));
421};
422
423function warn(msg, ...args) {
424 console.warn(`[Vue warn] ${msg}`, ...args);
425}
426
427let activeEffectScope;
428class EffectScope {
429 constructor(detached = false) {
430 /**
431 * @internal
432 */
433 this.active = true;
434 /**
435 * @internal
436 */
437 this.effects = [];
438 /**
439 * @internal
440 */
441 this.cleanups = [];
442 if (!detached && activeEffectScope) {
443 this.parent = activeEffectScope;
444 this.index =
445 (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(this) - 1;
446 }
447 }
448 run(fn) {
449 if (this.active) {
450 const currentEffectScope = activeEffectScope;
451 try {
452 activeEffectScope = this;
453 return fn();
454 }
455 finally {
456 activeEffectScope = currentEffectScope;
457 }
458 }
459 else {
460 warn(`cannot run an inactive effect scope.`);
461 }
462 }
463 /**
464 * This should only be called on non-detached scopes
465 * @internal
466 */
467 on() {
468 activeEffectScope = this;
469 }
470 /**
471 * This should only be called on non-detached scopes
472 * @internal
473 */
474 off() {
475 activeEffectScope = this.parent;
476 }
477 stop(fromParent) {
478 if (this.active) {
479 let i, l;
480 for (i = 0, l = this.effects.length; i < l; i++) {
481 this.effects[i].stop();
482 }
483 for (i = 0, l = this.cleanups.length; i < l; i++) {
484 this.cleanups[i]();
485 }
486 if (this.scopes) {
487 for (i = 0, l = this.scopes.length; i < l; i++) {
488 this.scopes[i].stop(true);
489 }
490 }
491 // nested scope, dereference from parent to avoid memory leaks
492 if (this.parent && !fromParent) {
493 // optimized O(1) removal
494 const last = this.parent.scopes.pop();
495 if (last && last !== this) {
496 this.parent.scopes[this.index] = last;
497 last.index = this.index;
498 }
499 }
500 this.active = false;
501 }
502 }
503}
504function effectScope(detached) {
505 return new EffectScope(detached);
506}
507function recordEffectScope(effect, scope = activeEffectScope) {
508 if (scope && scope.active) {
509 scope.effects.push(effect);
510 }
511}
512function getCurrentScope() {
513 return activeEffectScope;
514}
515function onScopeDispose(fn) {
516 if (activeEffectScope) {
517 activeEffectScope.cleanups.push(fn);
518 }
519 else {
520 warn(`onScopeDispose() is called when there is no active effect scope` +
521 ` to be associated with.`);
522 }
523}
524
525const createDep = (effects) => {
526 const dep = new Set(effects);
527 dep.w = 0;
528 dep.n = 0;
529 return dep;
530};
531const wasTracked = (dep) => (dep.w & trackOpBit) > 0;
532const newTracked = (dep) => (dep.n & trackOpBit) > 0;
533const initDepMarkers = ({ deps }) => {
534 if (deps.length) {
535 for (let i = 0; i < deps.length; i++) {
536 deps[i].w |= trackOpBit; // set was tracked
537 }
538 }
539};
540const finalizeDepMarkers = (effect) => {
541 const { deps } = effect;
542 if (deps.length) {
543 let ptr = 0;
544 for (let i = 0; i < deps.length; i++) {
545 const dep = deps[i];
546 if (wasTracked(dep) && !newTracked(dep)) {
547 dep.delete(effect);
548 }
549 else {
550 deps[ptr++] = dep;
551 }
552 // clear bits
553 dep.w &= ~trackOpBit;
554 dep.n &= ~trackOpBit;
555 }
556 deps.length = ptr;
557 }
558};
559
560const targetMap = new WeakMap();
561// The number of effects currently being tracked recursively.
562let effectTrackDepth = 0;
563let trackOpBit = 1;
564/**
565 * The bitwise track markers support at most 30 levels of recursion.
566 * This value is chosen to enable modern JS engines to use a SMI on all platforms.
567 * When recursion depth is greater, fall back to using a full cleanup.
568 */
569const maxMarkerBits = 30;
570let activeEffect;
571const ITERATE_KEY = Symbol('iterate' );
572const MAP_KEY_ITERATE_KEY = Symbol('Map key iterate' );
573class ReactiveEffect {
574 constructor(fn, scheduler = null, scope) {
575 this.fn = fn;
576 this.scheduler = scheduler;
577 this.active = true;
578 this.deps = [];
579 this.parent = undefined;
580 recordEffectScope(this, scope);
581 }
582 run() {
583 if (!this.active) {
584 return this.fn();
585 }
586 let parent = activeEffect;
587 let lastShouldTrack = shouldTrack;
588 while (parent) {
589 if (parent === this) {
590 return;
591 }
592 parent = parent.parent;
593 }
594 try {
595 this.parent = activeEffect;
596 activeEffect = this;
597 shouldTrack = true;
598 trackOpBit = 1 << ++effectTrackDepth;
599 if (effectTrackDepth <= maxMarkerBits) {
600 initDepMarkers(this);
601 }
602 else {
603 cleanupEffect(this);
604 }
605 return this.fn();
606 }
607 finally {
608 if (effectTrackDepth <= maxMarkerBits) {
609 finalizeDepMarkers(this);
610 }
611 trackOpBit = 1 << --effectTrackDepth;
612 activeEffect = this.parent;
613 shouldTrack = lastShouldTrack;
614 this.parent = undefined;
615 if (this.deferStop) {
616 this.stop();
617 }
618 }
619 }
620 stop() {
621 // stopped while running itself - defer the cleanup
622 if (activeEffect === this) {
623 this.deferStop = true;
624 }
625 else if (this.active) {
626 cleanupEffect(this);
627 if (this.onStop) {
628 this.onStop();
629 }
630 this.active = false;
631 }
632 }
633}
634function cleanupEffect(effect) {
635 const { deps } = effect;
636 if (deps.length) {
637 for (let i = 0; i < deps.length; i++) {
638 deps[i].delete(effect);
639 }
640 deps.length = 0;
641 }
642}
643function effect(fn, options) {
644 if (fn.effect) {
645 fn = fn.effect.fn;
646 }
647 const _effect = new ReactiveEffect(fn);
648 if (options) {
649 extend(_effect, options);
650 if (options.scope)
651 recordEffectScope(_effect, options.scope);
652 }
653 if (!options || !options.lazy) {
654 _effect.run();
655 }
656 const runner = _effect.run.bind(_effect);
657 runner.effect = _effect;
658 return runner;
659}
660function stop(runner) {
661 runner.effect.stop();
662}
663let shouldTrack = true;
664const trackStack = [];
665function pauseTracking() {
666 trackStack.push(shouldTrack);
667 shouldTrack = false;
668}
669function resetTracking() {
670 const last = trackStack.pop();
671 shouldTrack = last === undefined ? true : last;
672}
673function track(target, type, key) {
674 if (shouldTrack && activeEffect) {
675 let depsMap = targetMap.get(target);
676 if (!depsMap) {
677 targetMap.set(target, (depsMap = new Map()));
678 }
679 let dep = depsMap.get(key);
680 if (!dep) {
681 depsMap.set(key, (dep = createDep()));
682 }
683 const eventInfo = { effect: activeEffect, target, type, key }
684 ;
685 trackEffects(dep, eventInfo);
686 }
687}
688function trackEffects(dep, debuggerEventExtraInfo) {
689 let shouldTrack = false;
690 if (effectTrackDepth <= maxMarkerBits) {
691 if (!newTracked(dep)) {
692 dep.n |= trackOpBit; // set newly tracked
693 shouldTrack = !wasTracked(dep);
694 }
695 }
696 else {
697 // Full cleanup mode.
698 shouldTrack = !dep.has(activeEffect);
699 }
700 if (shouldTrack) {
701 dep.add(activeEffect);
702 activeEffect.deps.push(dep);
703 if (activeEffect.onTrack) {
704 activeEffect.onTrack(Object.assign({ effect: activeEffect }, debuggerEventExtraInfo));
705 }
706 }
707}
708function trigger(target, type, key, newValue, oldValue, oldTarget) {
709 const depsMap = targetMap.get(target);
710 if (!depsMap) {
711 // never been tracked
712 return;
713 }
714 let deps = [];
715 if (type === "clear" /* CLEAR */) {
716 // collection being cleared
717 // trigger all effects for target
718 deps = [...depsMap.values()];
719 }
720 else if (key === 'length' && isArray(target)) {
721 depsMap.forEach((dep, key) => {
722 if (key === 'length' || key >= newValue) {
723 deps.push(dep);
724 }
725 });
726 }
727 else {
728 // schedule runs for SET | ADD | DELETE
729 if (key !== void 0) {
730 deps.push(depsMap.get(key));
731 }
732 // also run for iteration key on ADD | DELETE | Map.SET
733 switch (type) {
734 case "add" /* ADD */:
735 if (!isArray(target)) {
736 deps.push(depsMap.get(ITERATE_KEY));
737 if (isMap(target)) {
738 deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
739 }
740 }
741 else if (isIntegerKey(key)) {
742 // new index added to array -> length changes
743 deps.push(depsMap.get('length'));
744 }
745 break;
746 case "delete" /* DELETE */:
747 if (!isArray(target)) {
748 deps.push(depsMap.get(ITERATE_KEY));
749 if (isMap(target)) {
750 deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
751 }
752 }
753 break;
754 case "set" /* SET */:
755 if (isMap(target)) {
756 deps.push(depsMap.get(ITERATE_KEY));
757 }
758 break;
759 }
760 }
761 const eventInfo = { target, type, key, newValue, oldValue, oldTarget }
762 ;
763 if (deps.length === 1) {
764 if (deps[0]) {
765 {
766 triggerEffects(deps[0], eventInfo);
767 }
768 }
769 }
770 else {
771 const effects = [];
772 for (const dep of deps) {
773 if (dep) {
774 effects.push(...dep);
775 }
776 }
777 {
778 triggerEffects(createDep(effects), eventInfo);
779 }
780 }
781}
782function triggerEffects(dep, debuggerEventExtraInfo) {
783 // spread into array for stabilization
784 for (const effect of isArray(dep) ? dep : [...dep]) {
785 if (effect !== activeEffect || effect.allowRecurse) {
786 if (effect.onTrigger) {
787 effect.onTrigger(extend({ effect }, debuggerEventExtraInfo));
788 }
789 if (effect.scheduler) {
790 effect.scheduler();
791 }
792 else {
793 effect.run();
794 }
795 }
796 }
797}
798
799const isNonTrackableKeys = /*#__PURE__*/ makeMap(`__proto__,__v_isRef,__isVue`);
800const builtInSymbols = new Set(
801/*#__PURE__*/
802Object.getOwnPropertyNames(Symbol)
803 .map(key => Symbol[key])
804 .filter(isSymbol));
805const get = /*#__PURE__*/ createGetter();
806const shallowGet = /*#__PURE__*/ createGetter(false, true);
807const readonlyGet = /*#__PURE__*/ createGetter(true);
808const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
809const arrayInstrumentations = /*#__PURE__*/ createArrayInstrumentations();
810function createArrayInstrumentations() {
811 const instrumentations = {};
812 ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
813 instrumentations[key] = function (...args) {
814 const arr = toRaw(this);
815 for (let i = 0, l = this.length; i < l; i++) {
816 track(arr, "get" /* GET */, i + '');
817 }
818 // we run the method using the original args first (which may be reactive)
819 const res = arr[key](...args);
820 if (res === -1 || res === false) {
821 // if that didn't work, run it again using raw values.
822 return arr[key](...args.map(toRaw));
823 }
824 else {
825 return res;
826 }
827 };
828 });
829 ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
830 instrumentations[key] = function (...args) {
831 pauseTracking();
832 const res = toRaw(this)[key].apply(this, args);
833 resetTracking();
834 return res;
835 };
836 });
837 return instrumentations;
838}
839function createGetter(isReadonly = false, shallow = false) {
840 return function get(target, key, receiver) {
841 if (key === "__v_isReactive" /* IS_REACTIVE */) {
842 return !isReadonly;
843 }
844 else if (key === "__v_isReadonly" /* IS_READONLY */) {
845 return isReadonly;
846 }
847 else if (key === "__v_isShallow" /* IS_SHALLOW */) {
848 return shallow;
849 }
850 else if (key === "__v_raw" /* RAW */ &&
851 receiver ===
852 (isReadonly
853 ? shallow
854 ? shallowReadonlyMap
855 : readonlyMap
856 : shallow
857 ? shallowReactiveMap
858 : reactiveMap).get(target)) {
859 return target;
860 }
861 const targetIsArray = isArray(target);
862 if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) {
863 return Reflect.get(arrayInstrumentations, key, receiver);
864 }
865 const res = Reflect.get(target, key, receiver);
866 if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
867 return res;
868 }
869 if (!isReadonly) {
870 track(target, "get" /* GET */, key);
871 }
872 if (shallow) {
873 return res;
874 }
875 if (isRef(res)) {
876 // ref unwrapping - does not apply for Array + integer key.
877 const shouldUnwrap = !targetIsArray || !isIntegerKey(key);
878 return shouldUnwrap ? res.value : res;
879 }
880 if (isObject(res)) {
881 // Convert returned value into a proxy as well. we do the isObject check
882 // here to avoid invalid value warning. Also need to lazy access readonly
883 // and reactive here to avoid circular dependency.
884 return isReadonly ? readonly(res) : reactive(res);
885 }
886 return res;
887 };
888}
889const set = /*#__PURE__*/ createSetter();
890const shallowSet = /*#__PURE__*/ createSetter(true);
891function createSetter(shallow = false) {
892 return function set(target, key, value, receiver) {
893 let oldValue = target[key];
894 if (isReadonly(oldValue) && isRef(oldValue) && !isRef(value)) {
895 return false;
896 }
897 if (!shallow && !isReadonly(value)) {
898 if (!isShallow(value)) {
899 value = toRaw(value);
900 oldValue = toRaw(oldValue);
901 }
902 if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
903 oldValue.value = value;
904 return true;
905 }
906 }
907 const hadKey = isArray(target) && isIntegerKey(key)
908 ? Number(key) < target.length
909 : hasOwn(target, key);
910 const result = Reflect.set(target, key, value, receiver);
911 // don't trigger if target is something up in the prototype chain of original
912 if (target === toRaw(receiver)) {
913 if (!hadKey) {
914 trigger(target, "add" /* ADD */, key, value);
915 }
916 else if (hasChanged(value, oldValue)) {
917 trigger(target, "set" /* SET */, key, value, oldValue);
918 }
919 }
920 return result;
921 };
922}
923function deleteProperty(target, key) {
924 const hadKey = hasOwn(target, key);
925 const oldValue = target[key];
926 const result = Reflect.deleteProperty(target, key);
927 if (result && hadKey) {
928 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
929 }
930 return result;
931}
932function has(target, key) {
933 const result = Reflect.has(target, key);
934 if (!isSymbol(key) || !builtInSymbols.has(key)) {
935 track(target, "has" /* HAS */, key);
936 }
937 return result;
938}
939function ownKeys(target) {
940 track(target, "iterate" /* ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
941 return Reflect.ownKeys(target);
942}
943const mutableHandlers = {
944 get,
945 set,
946 deleteProperty,
947 has,
948 ownKeys
949};
950const readonlyHandlers = {
951 get: readonlyGet,
952 set(target, key) {
953 {
954 warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
955 }
956 return true;
957 },
958 deleteProperty(target, key) {
959 {
960 warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
961 }
962 return true;
963 }
964};
965const shallowReactiveHandlers = /*#__PURE__*/ extend({}, mutableHandlers, {
966 get: shallowGet,
967 set: shallowSet
968});
969// Props handlers are special in the sense that it should not unwrap top-level
970// refs (in order to allow refs to be explicitly passed down), but should
971// retain the reactivity of the normal readonly object.
972const shallowReadonlyHandlers = /*#__PURE__*/ extend({}, readonlyHandlers, {
973 get: shallowReadonlyGet
974});
975
976const toShallow = (value) => value;
977const getProto = (v) => Reflect.getPrototypeOf(v);
978function get$1(target, key, isReadonly = false, isShallow = false) {
979 // #1772: readonly(reactive(Map)) should return readonly + reactive version
980 // of the value
981 target = target["__v_raw" /* RAW */];
982 const rawTarget = toRaw(target);
983 const rawKey = toRaw(key);
984 if (key !== rawKey) {
985 !isReadonly && track(rawTarget, "get" /* GET */, key);
986 }
987 !isReadonly && track(rawTarget, "get" /* GET */, rawKey);
988 const { has } = getProto(rawTarget);
989 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
990 if (has.call(rawTarget, key)) {
991 return wrap(target.get(key));
992 }
993 else if (has.call(rawTarget, rawKey)) {
994 return wrap(target.get(rawKey));
995 }
996 else if (target !== rawTarget) {
997 // #3602 readonly(reactive(Map))
998 // ensure that the nested reactive `Map` can do tracking for itself
999 target.get(key);
1000 }
1001}
1002function has$1(key, isReadonly = false) {
1003 const target = this["__v_raw" /* RAW */];
1004 const rawTarget = toRaw(target);
1005 const rawKey = toRaw(key);
1006 if (key !== rawKey) {
1007 !isReadonly && track(rawTarget, "has" /* HAS */, key);
1008 }
1009 !isReadonly && track(rawTarget, "has" /* HAS */, rawKey);
1010 return key === rawKey
1011 ? target.has(key)
1012 : target.has(key) || target.has(rawKey);
1013}
1014function size(target, isReadonly = false) {
1015 target = target["__v_raw" /* RAW */];
1016 !isReadonly && track(toRaw(target), "iterate" /* ITERATE */, ITERATE_KEY);
1017 return Reflect.get(target, 'size', target);
1018}
1019function add(value) {
1020 value = toRaw(value);
1021 const target = toRaw(this);
1022 const proto = getProto(target);
1023 const hadKey = proto.has.call(target, value);
1024 if (!hadKey) {
1025 target.add(value);
1026 trigger(target, "add" /* ADD */, value, value);
1027 }
1028 return this;
1029}
1030function set$1(key, value) {
1031 value = toRaw(value);
1032 const target = toRaw(this);
1033 const { has, get } = getProto(target);
1034 let hadKey = has.call(target, key);
1035 if (!hadKey) {
1036 key = toRaw(key);
1037 hadKey = has.call(target, key);
1038 }
1039 else {
1040 checkIdentityKeys(target, has, key);
1041 }
1042 const oldValue = get.call(target, key);
1043 target.set(key, value);
1044 if (!hadKey) {
1045 trigger(target, "add" /* ADD */, key, value);
1046 }
1047 else if (hasChanged(value, oldValue)) {
1048 trigger(target, "set" /* SET */, key, value, oldValue);
1049 }
1050 return this;
1051}
1052function deleteEntry(key) {
1053 const target = toRaw(this);
1054 const { has, get } = getProto(target);
1055 let hadKey = has.call(target, key);
1056 if (!hadKey) {
1057 key = toRaw(key);
1058 hadKey = has.call(target, key);
1059 }
1060 else {
1061 checkIdentityKeys(target, has, key);
1062 }
1063 const oldValue = get ? get.call(target, key) : undefined;
1064 // forward the operation before queueing reactions
1065 const result = target.delete(key);
1066 if (hadKey) {
1067 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
1068 }
1069 return result;
1070}
1071function clear() {
1072 const target = toRaw(this);
1073 const hadItems = target.size !== 0;
1074 const oldTarget = isMap(target)
1075 ? new Map(target)
1076 : new Set(target)
1077 ;
1078 // forward the operation before queueing reactions
1079 const result = target.clear();
1080 if (hadItems) {
1081 trigger(target, "clear" /* CLEAR */, undefined, undefined, oldTarget);
1082 }
1083 return result;
1084}
1085function createForEach(isReadonly, isShallow) {
1086 return function forEach(callback, thisArg) {
1087 const observed = this;
1088 const target = observed["__v_raw" /* RAW */];
1089 const rawTarget = toRaw(target);
1090 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
1091 !isReadonly && track(rawTarget, "iterate" /* ITERATE */, ITERATE_KEY);
1092 return target.forEach((value, key) => {
1093 // important: make sure the callback is
1094 // 1. invoked with the reactive map as `this` and 3rd arg
1095 // 2. the value received should be a corresponding reactive/readonly.
1096 return callback.call(thisArg, wrap(value), wrap(key), observed);
1097 });
1098 };
1099}
1100function createIterableMethod(method, isReadonly, isShallow) {
1101 return function (...args) {
1102 const target = this["__v_raw" /* RAW */];
1103 const rawTarget = toRaw(target);
1104 const targetIsMap = isMap(rawTarget);
1105 const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
1106 const isKeyOnly = method === 'keys' && targetIsMap;
1107 const innerIterator = target[method](...args);
1108 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
1109 !isReadonly &&
1110 track(rawTarget, "iterate" /* ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
1111 // return a wrapped iterator which returns observed versions of the
1112 // values emitted from the real iterator
1113 return {
1114 // iterator protocol
1115 next() {
1116 const { value, done } = innerIterator.next();
1117 return done
1118 ? { value, done }
1119 : {
1120 value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
1121 done
1122 };
1123 },
1124 // iterable protocol
1125 [Symbol.iterator]() {
1126 return this;
1127 }
1128 };
1129 };
1130}
1131function createReadonlyMethod(type) {
1132 return function (...args) {
1133 {
1134 const key = args[0] ? `on key "${args[0]}" ` : ``;
1135 console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
1136 }
1137 return type === "delete" /* DELETE */ ? false : this;
1138 };
1139}
1140function createInstrumentations() {
1141 const mutableInstrumentations = {
1142 get(key) {
1143 return get$1(this, key);
1144 },
1145 get size() {
1146 return size(this);
1147 },
1148 has: has$1,
1149 add,
1150 set: set$1,
1151 delete: deleteEntry,
1152 clear,
1153 forEach: createForEach(false, false)
1154 };
1155 const shallowInstrumentations = {
1156 get(key) {
1157 return get$1(this, key, false, true);
1158 },
1159 get size() {
1160 return size(this);
1161 },
1162 has: has$1,
1163 add,
1164 set: set$1,
1165 delete: deleteEntry,
1166 clear,
1167 forEach: createForEach(false, true)
1168 };
1169 const readonlyInstrumentations = {
1170 get(key) {
1171 return get$1(this, key, true);
1172 },
1173 get size() {
1174 return size(this, true);
1175 },
1176 has(key) {
1177 return has$1.call(this, key, true);
1178 },
1179 add: createReadonlyMethod("add" /* ADD */),
1180 set: createReadonlyMethod("set" /* SET */),
1181 delete: createReadonlyMethod("delete" /* DELETE */),
1182 clear: createReadonlyMethod("clear" /* CLEAR */),
1183 forEach: createForEach(true, false)
1184 };
1185 const shallowReadonlyInstrumentations = {
1186 get(key) {
1187 return get$1(this, key, true, true);
1188 },
1189 get size() {
1190 return size(this, true);
1191 },
1192 has(key) {
1193 return has$1.call(this, key, true);
1194 },
1195 add: createReadonlyMethod("add" /* ADD */),
1196 set: createReadonlyMethod("set" /* SET */),
1197 delete: createReadonlyMethod("delete" /* DELETE */),
1198 clear: createReadonlyMethod("clear" /* CLEAR */),
1199 forEach: createForEach(true, true)
1200 };
1201 const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
1202 iteratorMethods.forEach(method => {
1203 mutableInstrumentations[method] = createIterableMethod(method, false, false);
1204 readonlyInstrumentations[method] = createIterableMethod(method, true, false);
1205 shallowInstrumentations[method] = createIterableMethod(method, false, true);
1206 shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true);
1207 });
1208 return [
1209 mutableInstrumentations,
1210 readonlyInstrumentations,
1211 shallowInstrumentations,
1212 shallowReadonlyInstrumentations
1213 ];
1214}
1215const [mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations] = /* #__PURE__*/ createInstrumentations();
1216function createInstrumentationGetter(isReadonly, shallow) {
1217 const instrumentations = shallow
1218 ? isReadonly
1219 ? shallowReadonlyInstrumentations
1220 : shallowInstrumentations
1221 : isReadonly
1222 ? readonlyInstrumentations
1223 : mutableInstrumentations;
1224 return (target, key, receiver) => {
1225 if (key === "__v_isReactive" /* IS_REACTIVE */) {
1226 return !isReadonly;
1227 }
1228 else if (key === "__v_isReadonly" /* IS_READONLY */) {
1229 return isReadonly;
1230 }
1231 else if (key === "__v_raw" /* RAW */) {
1232 return target;
1233 }
1234 return Reflect.get(hasOwn(instrumentations, key) && key in target
1235 ? instrumentations
1236 : target, key, receiver);
1237 };
1238}
1239const mutableCollectionHandlers = {
1240 get: /*#__PURE__*/ createInstrumentationGetter(false, false)
1241};
1242const shallowCollectionHandlers = {
1243 get: /*#__PURE__*/ createInstrumentationGetter(false, true)
1244};
1245const readonlyCollectionHandlers = {
1246 get: /*#__PURE__*/ createInstrumentationGetter(true, false)
1247};
1248const shallowReadonlyCollectionHandlers = {
1249 get: /*#__PURE__*/ createInstrumentationGetter(true, true)
1250};
1251function checkIdentityKeys(target, has, key) {
1252 const rawKey = toRaw(key);
1253 if (rawKey !== key && has.call(target, rawKey)) {
1254 const type = toRawType(target);
1255 console.warn(`Reactive ${type} contains both the raw and reactive ` +
1256 `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
1257 `which can lead to inconsistencies. ` +
1258 `Avoid differentiating between the raw and reactive versions ` +
1259 `of an object and only use the reactive version if possible.`);
1260 }
1261}
1262
1263const reactiveMap = new WeakMap();
1264const shallowReactiveMap = new WeakMap();
1265const readonlyMap = new WeakMap();
1266const shallowReadonlyMap = new WeakMap();
1267function targetTypeMap(rawType) {
1268 switch (rawType) {
1269 case 'Object':
1270 case 'Array':
1271 return 1 /* COMMON */;
1272 case 'Map':
1273 case 'Set':
1274 case 'WeakMap':
1275 case 'WeakSet':
1276 return 2 /* COLLECTION */;
1277 default:
1278 return 0 /* INVALID */;
1279 }
1280}
1281function getTargetType(value) {
1282 return value["__v_skip" /* SKIP */] || !Object.isExtensible(value)
1283 ? 0 /* INVALID */
1284 : targetTypeMap(toRawType(value));
1285}
1286function reactive(target) {
1287 // if trying to observe a readonly proxy, return the readonly version.
1288 if (isReadonly(target)) {
1289 return target;
1290 }
1291 return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
1292}
1293/**
1294 * Return a shallowly-reactive copy of the original object, where only the root
1295 * level properties are reactive. It also does not auto-unwrap refs (even at the
1296 * root level).
1297 */
1298function shallowReactive(target) {
1299 return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
1300}
1301/**
1302 * Creates a readonly copy of the original object. Note the returned copy is not
1303 * made reactive, but `readonly` can be called on an already reactive object.
1304 */
1305function readonly(target) {
1306 return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
1307}
1308/**
1309 * Returns a reactive-copy of the original object, where only the root level
1310 * properties are readonly, and does NOT unwrap refs nor recursively convert
1311 * returned properties.
1312 * This is used for creating the props proxy object for stateful components.
1313 */
1314function shallowReadonly(target) {
1315 return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap);
1316}
1317function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) {
1318 if (!isObject(target)) {
1319 {
1320 console.warn(`value cannot be made reactive: ${String(target)}`);
1321 }
1322 return target;
1323 }
1324 // target is already a Proxy, return it.
1325 // exception: calling readonly() on a reactive object
1326 if (target["__v_raw" /* RAW */] &&
1327 !(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) {
1328 return target;
1329 }
1330 // target already has corresponding Proxy
1331 const existingProxy = proxyMap.get(target);
1332 if (existingProxy) {
1333 return existingProxy;
1334 }
1335 // only a whitelist of value types can be observed.
1336 const targetType = getTargetType(target);
1337 if (targetType === 0 /* INVALID */) {
1338 return target;
1339 }
1340 const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers);
1341 proxyMap.set(target, proxy);
1342 return proxy;
1343}
1344function isReactive(value) {
1345 if (isReadonly(value)) {
1346 return isReactive(value["__v_raw" /* RAW */]);
1347 }
1348 return !!(value && value["__v_isReactive" /* IS_REACTIVE */]);
1349}
1350function isReadonly(value) {
1351 return !!(value && value["__v_isReadonly" /* IS_READONLY */]);
1352}
1353function isShallow(value) {
1354 return !!(value && value["__v_isShallow" /* IS_SHALLOW */]);
1355}
1356function isProxy(value) {
1357 return isReactive(value) || isReadonly(value);
1358}
1359function toRaw(observed) {
1360 const raw = observed && observed["__v_raw" /* RAW */];
1361 return raw ? toRaw(raw) : observed;
1362}
1363function markRaw(value) {
1364 def(value, "__v_skip" /* SKIP */, true);
1365 return value;
1366}
1367const toReactive = (value) => isObject(value) ? reactive(value) : value;
1368const toReadonly = (value) => isObject(value) ? readonly(value) : value;
1369
1370function trackRefValue(ref) {
1371 if (shouldTrack && activeEffect) {
1372 ref = toRaw(ref);
1373 {
1374 trackEffects(ref.dep || (ref.dep = createDep()), {
1375 target: ref,
1376 type: "get" /* GET */,
1377 key: 'value'
1378 });
1379 }
1380 }
1381}
1382function triggerRefValue(ref, newVal) {
1383 ref = toRaw(ref);
1384 if (ref.dep) {
1385 {
1386 triggerEffects(ref.dep, {
1387 target: ref,
1388 type: "set" /* SET */,
1389 key: 'value',
1390 newValue: newVal
1391 });
1392 }
1393 }
1394}
1395function isRef(r) {
1396 return !!(r && r.__v_isRef === true);
1397}
1398function ref(value) {
1399 return createRef(value, false);
1400}
1401function shallowRef(value) {
1402 return createRef(value, true);
1403}
1404function createRef(rawValue, shallow) {
1405 if (isRef(rawValue)) {
1406 return rawValue;
1407 }
1408 return new RefImpl(rawValue, shallow);
1409}
1410class RefImpl {
1411 constructor(value, __v_isShallow) {
1412 this.__v_isShallow = __v_isShallow;
1413 this.dep = undefined;
1414 this.__v_isRef = true;
1415 this._rawValue = __v_isShallow ? value : toRaw(value);
1416 this._value = __v_isShallow ? value : toReactive(value);
1417 }
1418 get value() {
1419 trackRefValue(this);
1420 return this._value;
1421 }
1422 set value(newVal) {
1423 newVal = this.__v_isShallow ? newVal : toRaw(newVal);
1424 if (hasChanged(newVal, this._rawValue)) {
1425 this._rawValue = newVal;
1426 this._value = this.__v_isShallow ? newVal : toReactive(newVal);
1427 triggerRefValue(this, newVal);
1428 }
1429 }
1430}
1431function triggerRef(ref) {
1432 triggerRefValue(ref, ref.value );
1433}
1434function unref(ref) {
1435 return isRef(ref) ? ref.value : ref;
1436}
1437const shallowUnwrapHandlers = {
1438 get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
1439 set: (target, key, value, receiver) => {
1440 const oldValue = target[key];
1441 if (isRef(oldValue) && !isRef(value)) {
1442 oldValue.value = value;
1443 return true;
1444 }
1445 else {
1446 return Reflect.set(target, key, value, receiver);
1447 }
1448 }
1449};
1450function proxyRefs(objectWithRefs) {
1451 return isReactive(objectWithRefs)
1452 ? objectWithRefs
1453 : new Proxy(objectWithRefs, shallowUnwrapHandlers);
1454}
1455class CustomRefImpl {
1456 constructor(factory) {
1457 this.dep = undefined;
1458 this.__v_isRef = true;
1459 const { get, set } = factory(() => trackRefValue(this), () => triggerRefValue(this));
1460 this._get = get;
1461 this._set = set;
1462 }
1463 get value() {
1464 return this._get();
1465 }
1466 set value(newVal) {
1467 this._set(newVal);
1468 }
1469}
1470function customRef(factory) {
1471 return new CustomRefImpl(factory);
1472}
1473function toRefs(object) {
1474 if (!isProxy(object)) {
1475 console.warn(`toRefs() expects a reactive object but received a plain one.`);
1476 }
1477 const ret = isArray(object) ? new Array(object.length) : {};
1478 for (const key in object) {
1479 ret[key] = toRef(object, key);
1480 }
1481 return ret;
1482}
1483class ObjectRefImpl {
1484 constructor(_object, _key, _defaultValue) {
1485 this._object = _object;
1486 this._key = _key;
1487 this._defaultValue = _defaultValue;
1488 this.__v_isRef = true;
1489 }
1490 get value() {
1491 const val = this._object[this._key];
1492 return val === undefined ? this._defaultValue : val;
1493 }
1494 set value(newVal) {
1495 this._object[this._key] = newVal;
1496 }
1497}
1498function toRef(object, key, defaultValue) {
1499 const val = object[key];
1500 return isRef(val)
1501 ? val
1502 : new ObjectRefImpl(object, key, defaultValue);
1503}
1504
1505class ComputedRefImpl {
1506 constructor(getter, _setter, isReadonly, isSSR) {
1507 this._setter = _setter;
1508 this.dep = undefined;
1509 this.__v_isRef = true;
1510 this._dirty = true;
1511 this.effect = new ReactiveEffect(getter, () => {
1512 if (!this._dirty) {
1513 this._dirty = true;
1514 triggerRefValue(this);
1515 }
1516 });
1517 this.effect.computed = this;
1518 this.effect.active = this._cacheable = !isSSR;
1519 this["__v_isReadonly" /* IS_READONLY */] = isReadonly;
1520 }
1521 get value() {
1522 // the computed ref may get wrapped by other proxies e.g. readonly() #3376
1523 const self = toRaw(this);
1524 trackRefValue(self);
1525 if (self._dirty || !self._cacheable) {
1526 self._dirty = false;
1527 self._value = self.effect.run();
1528 }
1529 return self._value;
1530 }
1531 set value(newValue) {
1532 this._setter(newValue);
1533 }
1534}
1535function computed(getterOrOptions, debugOptions, isSSR = false) {
1536 let getter;
1537 let setter;
1538 const onlyGetter = isFunction(getterOrOptions);
1539 if (onlyGetter) {
1540 getter = getterOrOptions;
1541 setter = () => {
1542 console.warn('Write operation failed: computed value is readonly');
1543 }
1544 ;
1545 }
1546 else {
1547 getter = getterOrOptions.get;
1548 setter = getterOrOptions.set;
1549 }
1550 const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR);
1551 if (debugOptions && !isSSR) {
1552 cRef.effect.onTrack = debugOptions.onTrack;
1553 cRef.effect.onTrigger = debugOptions.onTrigger;
1554 }
1555 return cRef;
1556}
1557
1558const stack = [];
1559function pushWarningContext(vnode) {
1560 stack.push(vnode);
1561}
1562function popWarningContext() {
1563 stack.pop();
1564}
1565function warn$1(msg, ...args) {
1566 // avoid props formatting or warn handler tracking deps that might be mutated
1567 // during patch, leading to infinite recursion.
1568 pauseTracking();
1569 const instance = stack.length ? stack[stack.length - 1].component : null;
1570 const appWarnHandler = instance && instance.appContext.config.warnHandler;
1571 const trace = getComponentTrace();
1572 if (appWarnHandler) {
1573 callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [
1574 msg + args.join(''),
1575 instance && instance.proxy,
1576 trace
1577 .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
1578 .join('\n'),
1579 trace
1580 ]);
1581 }
1582 else {
1583 const warnArgs = [`[Vue warn]: ${msg}`, ...args];
1584 /* istanbul ignore if */
1585 if (trace.length &&
1586 // avoid spamming console during tests
1587 !false) {
1588 warnArgs.push(`\n`, ...formatTrace(trace));
1589 }
1590 console.warn(...warnArgs);
1591 }
1592 resetTracking();
1593}
1594function getComponentTrace() {
1595 let currentVNode = stack[stack.length - 1];
1596 if (!currentVNode) {
1597 return [];
1598 }
1599 // we can't just use the stack because it will be incomplete during updates
1600 // that did not start from the root. Re-construct the parent chain using
1601 // instance parent pointers.
1602 const normalizedStack = [];
1603 while (currentVNode) {
1604 const last = normalizedStack[0];
1605 if (last && last.vnode === currentVNode) {
1606 last.recurseCount++;
1607 }
1608 else {
1609 normalizedStack.push({
1610 vnode: currentVNode,
1611 recurseCount: 0
1612 });
1613 }
1614 const parentInstance = currentVNode.component && currentVNode.component.parent;
1615 currentVNode = parentInstance && parentInstance.vnode;
1616 }
1617 return normalizedStack;
1618}
1619/* istanbul ignore next */
1620function formatTrace(trace) {
1621 const logs = [];
1622 trace.forEach((entry, i) => {
1623 logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
1624 });
1625 return logs;
1626}
1627function formatTraceEntry({ vnode, recurseCount }) {
1628 const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
1629 const isRoot = vnode.component ? vnode.component.parent == null : false;
1630 const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
1631 const close = `>` + postfix;
1632 return vnode.props
1633 ? [open, ...formatProps(vnode.props), close]
1634 : [open + close];
1635}
1636/* istanbul ignore next */
1637function formatProps(props) {
1638 const res = [];
1639 const keys = Object.keys(props);
1640 keys.slice(0, 3).forEach(key => {
1641 res.push(...formatProp(key, props[key]));
1642 });
1643 if (keys.length > 3) {
1644 res.push(` ...`);
1645 }
1646 return res;
1647}
1648/* istanbul ignore next */
1649function formatProp(key, value, raw) {
1650 if (isString(value)) {
1651 value = JSON.stringify(value);
1652 return raw ? value : [`${key}=${value}`];
1653 }
1654 else if (typeof value === 'number' ||
1655 typeof value === 'boolean' ||
1656 value == null) {
1657 return raw ? value : [`${key}=${value}`];
1658 }
1659 else if (isRef(value)) {
1660 value = formatProp(key, toRaw(value.value), true);
1661 return raw ? value : [`${key}=Ref<`, value, `>`];
1662 }
1663 else if (isFunction(value)) {
1664 return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
1665 }
1666 else {
1667 value = toRaw(value);
1668 return raw ? value : [`${key}=`, value];
1669 }
1670}
1671
1672const ErrorTypeStrings = {
1673 ["sp" /* SERVER_PREFETCH */]: 'serverPrefetch hook',
1674 ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',
1675 ["c" /* CREATED */]: 'created hook',
1676 ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',
1677 ["m" /* MOUNTED */]: 'mounted hook',
1678 ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',
1679 ["u" /* UPDATED */]: 'updated',
1680 ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',
1681 ["um" /* UNMOUNTED */]: 'unmounted hook',
1682 ["a" /* ACTIVATED */]: 'activated hook',
1683 ["da" /* DEACTIVATED */]: 'deactivated hook',
1684 ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',
1685 ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',
1686 ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',
1687 [0 /* SETUP_FUNCTION */]: 'setup function',
1688 [1 /* RENDER_FUNCTION */]: 'render function',
1689 [2 /* WATCH_GETTER */]: 'watcher getter',
1690 [3 /* WATCH_CALLBACK */]: 'watcher callback',
1691 [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',
1692 [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',
1693 [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',
1694 [7 /* VNODE_HOOK */]: 'vnode hook',
1695 [8 /* DIRECTIVE_HOOK */]: 'directive hook',
1696 [9 /* TRANSITION_HOOK */]: 'transition hook',
1697 [10 /* APP_ERROR_HANDLER */]: 'app errorHandler',
1698 [11 /* APP_WARN_HANDLER */]: 'app warnHandler',
1699 [12 /* FUNCTION_REF */]: 'ref function',
1700 [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader',
1701 [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
1702 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/core'
1703};
1704function callWithErrorHandling(fn, instance, type, args) {
1705 let res;
1706 try {
1707 res = args ? fn(...args) : fn();
1708 }
1709 catch (err) {
1710 handleError(err, instance, type);
1711 }
1712 return res;
1713}
1714function callWithAsyncErrorHandling(fn, instance, type, args) {
1715 if (isFunction(fn)) {
1716 const res = callWithErrorHandling(fn, instance, type, args);
1717 if (res && isPromise(res)) {
1718 res.catch(err => {
1719 handleError(err, instance, type);
1720 });
1721 }
1722 return res;
1723 }
1724 const values = [];
1725 for (let i = 0; i < fn.length; i++) {
1726 values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
1727 }
1728 return values;
1729}
1730function handleError(err, instance, type, throwInDev = true) {
1731 const contextVNode = instance ? instance.vnode : null;
1732 if (instance) {
1733 let cur = instance.parent;
1734 // the exposed instance is the render proxy to keep it consistent with 2.x
1735 const exposedInstance = instance.proxy;
1736 // in production the hook receives only the error code
1737 const errorInfo = ErrorTypeStrings[type] ;
1738 while (cur) {
1739 const errorCapturedHooks = cur.ec;
1740 if (errorCapturedHooks) {
1741 for (let i = 0; i < errorCapturedHooks.length; i++) {
1742 if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
1743 return;
1744 }
1745 }
1746 }
1747 cur = cur.parent;
1748 }
1749 // app-level handling
1750 const appErrorHandler = instance.appContext.config.errorHandler;
1751 if (appErrorHandler) {
1752 callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
1753 return;
1754 }
1755 }
1756 logError(err, type, contextVNode, throwInDev);
1757}
1758function logError(err, type, contextVNode, throwInDev = true) {
1759 {
1760 const info = ErrorTypeStrings[type];
1761 if (contextVNode) {
1762 pushWarningContext(contextVNode);
1763 }
1764 warn$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
1765 if (contextVNode) {
1766 popWarningContext();
1767 }
1768 // crash in dev by default so it's more noticeable
1769 if (throwInDev) {
1770 throw err;
1771 }
1772 else {
1773 console.error(err);
1774 }
1775 }
1776}
1777
1778let isFlushing = false;
1779let isFlushPending = false;
1780const queue = [];
1781let flushIndex = 0;
1782const pendingPreFlushCbs = [];
1783let activePreFlushCbs = null;
1784let preFlushIndex = 0;
1785const pendingPostFlushCbs = [];
1786let activePostFlushCbs = null;
1787let postFlushIndex = 0;
1788const resolvedPromise = /*#__PURE__*/ Promise.resolve();
1789let currentFlushPromise = null;
1790let currentPreFlushParentJob = null;
1791const RECURSION_LIMIT = 100;
1792function nextTick(fn) {
1793 const p = currentFlushPromise || resolvedPromise;
1794 return fn ? p.then(this ? fn.bind(this) : fn) : p;
1795}
1796// #2768
1797// Use binary-search to find a suitable position in the queue,
1798// so that the queue maintains the increasing order of job's id,
1799// which can prevent the job from being skipped and also can avoid repeated patching.
1800function findInsertionIndex(id) {
1801 // the start index should be `flushIndex + 1`
1802 let start = flushIndex + 1;
1803 let end = queue.length;
1804 while (start < end) {
1805 const middle = (start + end) >>> 1;
1806 const middleJobId = getId(queue[middle]);
1807 middleJobId < id ? (start = middle + 1) : (end = middle);
1808 }
1809 return start;
1810}
1811function queueJob(job) {
1812 // the dedupe search uses the startIndex argument of Array.includes()
1813 // by default the search index includes the current job that is being run
1814 // so it cannot recursively trigger itself again.
1815 // if the job is a watch() callback, the search will start with a +1 index to
1816 // allow it recursively trigger itself - it is the user's responsibility to
1817 // ensure it doesn't end up in an infinite loop.
1818 if ((!queue.length ||
1819 !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) &&
1820 job !== currentPreFlushParentJob) {
1821 if (job.id == null) {
1822 queue.push(job);
1823 }
1824 else {
1825 queue.splice(findInsertionIndex(job.id), 0, job);
1826 }
1827 queueFlush();
1828 }
1829}
1830function queueFlush() {
1831 if (!isFlushing && !isFlushPending) {
1832 isFlushPending = true;
1833 currentFlushPromise = resolvedPromise.then(flushJobs);
1834 }
1835}
1836function invalidateJob(job) {
1837 const i = queue.indexOf(job);
1838 if (i > flushIndex) {
1839 queue.splice(i, 1);
1840 }
1841}
1842function queueCb(cb, activeQueue, pendingQueue, index) {
1843 if (!isArray(cb)) {
1844 if (!activeQueue ||
1845 !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) {
1846 pendingQueue.push(cb);
1847 }
1848 }
1849 else {
1850 // if cb is an array, it is a component lifecycle hook which can only be
1851 // triggered by a job, which is already deduped in the main queue, so
1852 // we can skip duplicate check here to improve perf
1853 pendingQueue.push(...cb);
1854 }
1855 queueFlush();
1856}
1857function queuePreFlushCb(cb) {
1858 queueCb(cb, activePreFlushCbs, pendingPreFlushCbs, preFlushIndex);
1859}
1860function queuePostFlushCb(cb) {
1861 queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex);
1862}
1863function flushPreFlushCbs(seen, parentJob = null) {
1864 if (pendingPreFlushCbs.length) {
1865 currentPreFlushParentJob = parentJob;
1866 activePreFlushCbs = [...new Set(pendingPreFlushCbs)];
1867 pendingPreFlushCbs.length = 0;
1868 {
1869 seen = seen || new Map();
1870 }
1871 for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) {
1872 if (checkRecursiveUpdates(seen, activePreFlushCbs[preFlushIndex])) {
1873 continue;
1874 }
1875 activePreFlushCbs[preFlushIndex]();
1876 }
1877 activePreFlushCbs = null;
1878 preFlushIndex = 0;
1879 currentPreFlushParentJob = null;
1880 // recursively flush until it drains
1881 flushPreFlushCbs(seen, parentJob);
1882 }
1883}
1884function flushPostFlushCbs(seen) {
1885 if (pendingPostFlushCbs.length) {
1886 const deduped = [...new Set(pendingPostFlushCbs)];
1887 pendingPostFlushCbs.length = 0;
1888 // #1947 already has active queue, nested flushPostFlushCbs call
1889 if (activePostFlushCbs) {
1890 activePostFlushCbs.push(...deduped);
1891 return;
1892 }
1893 activePostFlushCbs = deduped;
1894 {
1895 seen = seen || new Map();
1896 }
1897 activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
1898 for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
1899 if (checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) {
1900 continue;
1901 }
1902 activePostFlushCbs[postFlushIndex]();
1903 }
1904 activePostFlushCbs = null;
1905 postFlushIndex = 0;
1906 }
1907}
1908const getId = (job) => job.id == null ? Infinity : job.id;
1909function flushJobs(seen) {
1910 isFlushPending = false;
1911 isFlushing = true;
1912 {
1913 seen = seen || new Map();
1914 }
1915 flushPreFlushCbs(seen);
1916 // Sort queue before flush.
1917 // This ensures that:
1918 // 1. Components are updated from parent to child. (because parent is always
1919 // created before the child so its render effect will have smaller
1920 // priority number)
1921 // 2. If a component is unmounted during a parent component's update,
1922 // its update can be skipped.
1923 queue.sort((a, b) => getId(a) - getId(b));
1924 // conditional usage of checkRecursiveUpdate must be determined out of
1925 // try ... catch block since Rollup by default de-optimizes treeshaking
1926 // inside try-catch. This can leave all warning code unshaked. Although
1927 // they would get eventually shaken by a minifier like terser, some minifiers
1928 // would fail to do that (e.g. https://github.com/evanw/esbuild/issues/1610)
1929 const check = (job) => checkRecursiveUpdates(seen, job)
1930 ;
1931 try {
1932 for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
1933 const job = queue[flushIndex];
1934 if (job && job.active !== false) {
1935 if (true && check(job)) {
1936 continue;
1937 }
1938 // console.log(`running:`, job.id)
1939 callWithErrorHandling(job, null, 14 /* SCHEDULER */);
1940 }
1941 }
1942 }
1943 finally {
1944 flushIndex = 0;
1945 queue.length = 0;
1946 flushPostFlushCbs(seen);
1947 isFlushing = false;
1948 currentFlushPromise = null;
1949 // some postFlushCb queued jobs!
1950 // keep flushing until it drains.
1951 if (queue.length ||
1952 pendingPreFlushCbs.length ||
1953 pendingPostFlushCbs.length) {
1954 flushJobs(seen);
1955 }
1956 }
1957}
1958function checkRecursiveUpdates(seen, fn) {
1959 if (!seen.has(fn)) {
1960 seen.set(fn, 1);
1961 }
1962 else {
1963 const count = seen.get(fn);
1964 if (count > RECURSION_LIMIT) {
1965 const instance = fn.ownerInstance;
1966 const componentName = instance && getComponentName(instance.type);
1967 warn$1(`Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. ` +
1968 `This means you have a reactive effect that is mutating its own ` +
1969 `dependencies and thus recursively triggering itself. Possible sources ` +
1970 `include component template, render function, updated hook or ` +
1971 `watcher source function.`);
1972 return true;
1973 }
1974 else {
1975 seen.set(fn, count + 1);
1976 }
1977 }
1978}
1979
1980/* eslint-disable no-restricted-globals */
1981let isHmrUpdating = false;
1982const hmrDirtyComponents = new Set();
1983// Expose the HMR runtime on the global object
1984// This makes it entirely tree-shakable without polluting the exports and makes
1985// it easier to be used in toolings like vue-loader
1986// Note: for a component to be eligible for HMR it also needs the __hmrId option
1987// to be set so that its instances can be registered / removed.
1988{
1989 getGlobalThis().__VUE_HMR_RUNTIME__ = {
1990 createRecord: tryWrap(createRecord),
1991 rerender: tryWrap(rerender),
1992 reload: tryWrap(reload)
1993 };
1994}
1995const map = new Map();
1996function registerHMR(instance) {
1997 const id = instance.type.__hmrId;
1998 let record = map.get(id);
1999 if (!record) {
2000 createRecord(id, instance.type);
2001 record = map.get(id);
2002 }
2003 record.instances.add(instance);
2004}
2005function unregisterHMR(instance) {
2006 map.get(instance.type.__hmrId).instances.delete(instance);
2007}
2008function createRecord(id, initialDef) {
2009 if (map.has(id)) {
2010 return false;
2011 }
2012 map.set(id, {
2013 initialDef: normalizeClassComponent(initialDef),
2014 instances: new Set()
2015 });
2016 return true;
2017}
2018function normalizeClassComponent(component) {
2019 return isClassComponent(component) ? component.__vccOpts : component;
2020}
2021function rerender(id, newRender) {
2022 const record = map.get(id);
2023 if (!record) {
2024 return;
2025 }
2026 // update initial record (for not-yet-rendered component)
2027 record.initialDef.render = newRender;
2028 [...record.instances].forEach(instance => {
2029 if (newRender) {
2030 instance.render = newRender;
2031 normalizeClassComponent(instance.type).render = newRender;
2032 }
2033 instance.renderCache = [];
2034 // this flag forces child components with slot content to update
2035 isHmrUpdating = true;
2036 instance.update();
2037 isHmrUpdating = false;
2038 });
2039}
2040function reload(id, newComp) {
2041 const record = map.get(id);
2042 if (!record)
2043 return;
2044 newComp = normalizeClassComponent(newComp);
2045 // update initial def (for not-yet-rendered components)
2046 updateComponentDef(record.initialDef, newComp);
2047 // create a snapshot which avoids the set being mutated during updates
2048 const instances = [...record.instances];
2049 for (const instance of instances) {
2050 const oldComp = normalizeClassComponent(instance.type);
2051 if (!hmrDirtyComponents.has(oldComp)) {
2052 // 1. Update existing comp definition to match new one
2053 if (oldComp !== record.initialDef) {
2054 updateComponentDef(oldComp, newComp);
2055 }
2056 // 2. mark definition dirty. This forces the renderer to replace the
2057 // component on patch.
2058 hmrDirtyComponents.add(oldComp);
2059 }
2060 // 3. invalidate options resolution cache
2061 instance.appContext.optionsCache.delete(instance.type);
2062 // 4. actually update
2063 if (instance.ceReload) {
2064 // custom element
2065 hmrDirtyComponents.add(oldComp);
2066 instance.ceReload(newComp.styles);
2067 hmrDirtyComponents.delete(oldComp);
2068 }
2069 else if (instance.parent) {
2070 // 4. Force the parent instance to re-render. This will cause all updated
2071 // components to be unmounted and re-mounted. Queue the update so that we
2072 // don't end up forcing the same parent to re-render multiple times.
2073 queueJob(instance.parent.update);
2074 // instance is the inner component of an async custom element
2075 // invoke to reset styles
2076 if (instance.parent.type.__asyncLoader &&
2077 instance.parent.ceReload) {
2078 instance.parent.ceReload(newComp.styles);
2079 }
2080 }
2081 else if (instance.appContext.reload) {
2082 // root instance mounted via createApp() has a reload method
2083 instance.appContext.reload();
2084 }
2085 else if (typeof window !== 'undefined') {
2086 // root instance inside tree created via raw render(). Force reload.
2087 window.location.reload();
2088 }
2089 else {
2090 console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
2091 }
2092 }
2093 // 5. make sure to cleanup dirty hmr components after update
2094 queuePostFlushCb(() => {
2095 for (const instance of instances) {
2096 hmrDirtyComponents.delete(normalizeClassComponent(instance.type));
2097 }
2098 });
2099}
2100function updateComponentDef(oldComp, newComp) {
2101 extend(oldComp, newComp);
2102 for (const key in oldComp) {
2103 if (key !== '__file' && !(key in newComp)) {
2104 delete oldComp[key];
2105 }
2106 }
2107}
2108function tryWrap(fn) {
2109 return (id, arg) => {
2110 try {
2111 return fn(id, arg);
2112 }
2113 catch (e) {
2114 console.error(e);
2115 console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
2116 `Full reload required.`);
2117 }
2118 };
2119}
2120
2121let devtools;
2122let buffer = [];
2123let devtoolsNotInstalled = false;
2124function emit(event, ...args) {
2125 if (devtools) {
2126 devtools.emit(event, ...args);
2127 }
2128 else if (!devtoolsNotInstalled) {
2129 buffer.push({ event, args });
2130 }
2131}
2132function setDevtoolsHook(hook, target) {
2133 var _a, _b;
2134 devtools = hook;
2135 if (devtools) {
2136 devtools.enabled = true;
2137 buffer.forEach(({ event, args }) => devtools.emit(event, ...args));
2138 buffer = [];
2139 }
2140 else if (
2141 // handle late devtools injection - only do this if we are in an actual
2142 // browser environment to avoid the timer handle stalling test runner exit
2143 // (#4815)
2144 // eslint-disable-next-line no-restricted-globals
2145 typeof window !== 'undefined' &&
2146 // some envs mock window but not fully
2147 window.HTMLElement &&
2148 // also exclude jsdom
2149 !((_b = (_a = window.navigator) === null || _a === void 0 ? void 0 : _a.userAgent) === null || _b === void 0 ? void 0 : _b.includes('jsdom'))) {
2150 const replay = (target.__VUE_DEVTOOLS_HOOK_REPLAY__ =
2151 target.__VUE_DEVTOOLS_HOOK_REPLAY__ || []);
2152 replay.push((newHook) => {
2153 setDevtoolsHook(newHook, target);
2154 });
2155 // clear buffer after 3s - the user probably doesn't have devtools installed
2156 // at all, and keeping the buffer will cause memory leaks (#4738)
2157 setTimeout(() => {
2158 if (!devtools) {
2159 target.__VUE_DEVTOOLS_HOOK_REPLAY__ = null;
2160 devtoolsNotInstalled = true;
2161 buffer = [];
2162 }
2163 }, 3000);
2164 }
2165 else {
2166 // non-browser env, assume not installed
2167 devtoolsNotInstalled = true;
2168 buffer = [];
2169 }
2170}
2171function devtoolsInitApp(app, version) {
2172 emit("app:init" /* APP_INIT */, app, version, {
2173 Fragment,
2174 Text,
2175 Comment,
2176 Static
2177 });
2178}
2179function devtoolsUnmountApp(app) {
2180 emit("app:unmount" /* APP_UNMOUNT */, app);
2181}
2182const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* COMPONENT_ADDED */);
2183const devtoolsComponentUpdated =
2184/*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */);
2185const devtoolsComponentRemoved =
2186/*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* COMPONENT_REMOVED */);
2187function createDevtoolsComponentHook(hook) {
2188 return (component) => {
2189 emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component);
2190 };
2191}
2192const devtoolsPerfStart = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:start" /* PERFORMANCE_START */);
2193const devtoolsPerfEnd = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:end" /* PERFORMANCE_END */);
2194function createDevtoolsPerformanceHook(hook) {
2195 return (component, type, time) => {
2196 emit(hook, component.appContext.app, component.uid, component, type, time);
2197 };
2198}
2199function devtoolsComponentEmit(component, event, params) {
2200 emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params);
2201}
2202
2203function emit$1(instance, event, ...rawArgs) {
2204 if (instance.isUnmounted)
2205 return;
2206 const props = instance.vnode.props || EMPTY_OBJ;
2207 {
2208 const { emitsOptions, propsOptions: [propsOptions] } = instance;
2209 if (emitsOptions) {
2210 if (!(event in emitsOptions) &&
2211 !(false )) {
2212 if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
2213 warn$1(`Component emitted event "${event}" but it is neither declared in ` +
2214 `the emits option nor as an "${toHandlerKey(event)}" prop.`);
2215 }
2216 }
2217 else {
2218 const validator = emitsOptions[event];
2219 if (isFunction(validator)) {
2220 const isValid = validator(...rawArgs);
2221 if (!isValid) {
2222 warn$1(`Invalid event arguments: event validation failed for event "${event}".`);
2223 }
2224 }
2225 }
2226 }
2227 }
2228 let args = rawArgs;
2229 const isModelListener = event.startsWith('update:');
2230 // for v-model update:xxx events, apply modifiers on args
2231 const modelArg = isModelListener && event.slice(7);
2232 if (modelArg && modelArg in props) {
2233 const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
2234 const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
2235 if (trim) {
2236 args = rawArgs.map(a => a.trim());
2237 }
2238 else if (number) {
2239 args = rawArgs.map(toNumber);
2240 }
2241 }
2242 {
2243 devtoolsComponentEmit(instance, event, args);
2244 }
2245 {
2246 const lowerCaseEvent = event.toLowerCase();
2247 if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
2248 warn$1(`Event "${lowerCaseEvent}" is emitted in component ` +
2249 `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
2250 `Note that HTML attributes are case-insensitive and you cannot use ` +
2251 `v-on to listen to camelCase events when using in-DOM templates. ` +
2252 `You should probably use "${hyphenate(event)}" instead of "${event}".`);
2253 }
2254 }
2255 let handlerName;
2256 let handler = props[(handlerName = toHandlerKey(event))] ||
2257 // also try camelCase event handler (#2249)
2258 props[(handlerName = toHandlerKey(camelize(event)))];
2259 // for v-model update:xxx events, also trigger kebab-case equivalent
2260 // for props passed via kebab-case
2261 if (!handler && isModelListener) {
2262 handler = props[(handlerName = toHandlerKey(hyphenate(event)))];
2263 }
2264 if (handler) {
2265 callWithAsyncErrorHandling(handler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
2266 }
2267 const onceHandler = props[handlerName + `Once`];
2268 if (onceHandler) {
2269 if (!instance.emitted) {
2270 instance.emitted = {};
2271 }
2272 else if (instance.emitted[handlerName]) {
2273 return;
2274 }
2275 instance.emitted[handlerName] = true;
2276 callWithAsyncErrorHandling(onceHandler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
2277 }
2278}
2279function normalizeEmitsOptions(comp, appContext, asMixin = false) {
2280 const cache = appContext.emitsCache;
2281 const cached = cache.get(comp);
2282 if (cached !== undefined) {
2283 return cached;
2284 }
2285 const raw = comp.emits;
2286 let normalized = {};
2287 // apply mixin/extends props
2288 let hasExtends = false;
2289 if (!isFunction(comp)) {
2290 const extendEmits = (raw) => {
2291 const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true);
2292 if (normalizedFromExtend) {
2293 hasExtends = true;
2294 extend(normalized, normalizedFromExtend);
2295 }
2296 };
2297 if (!asMixin && appContext.mixins.length) {
2298 appContext.mixins.forEach(extendEmits);
2299 }
2300 if (comp.extends) {
2301 extendEmits(comp.extends);
2302 }
2303 if (comp.mixins) {
2304 comp.mixins.forEach(extendEmits);
2305 }
2306 }
2307 if (!raw && !hasExtends) {
2308 cache.set(comp, null);
2309 return null;
2310 }
2311 if (isArray(raw)) {
2312 raw.forEach(key => (normalized[key] = null));
2313 }
2314 else {
2315 extend(normalized, raw);
2316 }
2317 cache.set(comp, normalized);
2318 return normalized;
2319}
2320// Check if an incoming prop key is a declared emit event listener.
2321// e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
2322// both considered matched listeners.
2323function isEmitListener(options, key) {
2324 if (!options || !isOn(key)) {
2325 return false;
2326 }
2327 key = key.slice(2).replace(/Once$/, '');
2328 return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||
2329 hasOwn(options, hyphenate(key)) ||
2330 hasOwn(options, key));
2331}
2332
2333/**
2334 * mark the current rendering instance for asset resolution (e.g.
2335 * resolveComponent, resolveDirective) during render
2336 */
2337let currentRenderingInstance = null;
2338let currentScopeId = null;
2339/**
2340 * Note: rendering calls maybe nested. The function returns the parent rendering
2341 * instance if present, which should be restored after the render is done:
2342 *
2343 * ```js
2344 * const prev = setCurrentRenderingInstance(i)
2345 * // ...render
2346 * setCurrentRenderingInstance(prev)
2347 * ```
2348 */
2349function setCurrentRenderingInstance(instance) {
2350 const prev = currentRenderingInstance;
2351 currentRenderingInstance = instance;
2352 currentScopeId = (instance && instance.type.__scopeId) || null;
2353 return prev;
2354}
2355/**
2356 * Set scope id when creating hoisted vnodes.
2357 * @private compiler helper
2358 */
2359function pushScopeId(id) {
2360 currentScopeId = id;
2361}
2362/**
2363 * Technically we no longer need this after 3.0.8 but we need to keep the same
2364 * API for backwards compat w/ code generated by compilers.
2365 * @private
2366 */
2367function popScopeId() {
2368 currentScopeId = null;
2369}
2370/**
2371 * Only for backwards compat
2372 * @private
2373 */
2374const withScopeId = (_id) => withCtx;
2375/**
2376 * Wrap a slot function to memoize current rendering instance
2377 * @private compiler helper
2378 */
2379function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot // false only
2380) {
2381 if (!ctx)
2382 return fn;
2383 // already normalized
2384 if (fn._n) {
2385 return fn;
2386 }
2387 const renderFnWithContext = (...args) => {
2388 // If a user calls a compiled slot inside a template expression (#1745), it
2389 // can mess up block tracking, so by default we disable block tracking and
2390 // force bail out when invoking a compiled slot (indicated by the ._d flag).
2391 // This isn't necessary if rendering a compiled `<slot>`, so we flip the
2392 // ._d flag off when invoking the wrapped fn inside `renderSlot`.
2393 if (renderFnWithContext._d) {
2394 setBlockTracking(-1);
2395 }
2396 const prevInstance = setCurrentRenderingInstance(ctx);
2397 const res = fn(...args);
2398 setCurrentRenderingInstance(prevInstance);
2399 if (renderFnWithContext._d) {
2400 setBlockTracking(1);
2401 }
2402 {
2403 devtoolsComponentUpdated(ctx);
2404 }
2405 return res;
2406 };
2407 // mark normalized to avoid duplicated wrapping
2408 renderFnWithContext._n = true;
2409 // mark this as compiled by default
2410 // this is used in vnode.ts -> normalizeChildren() to set the slot
2411 // rendering flag.
2412 renderFnWithContext._c = true;
2413 // disable block tracking by default
2414 renderFnWithContext._d = true;
2415 return renderFnWithContext;
2416}
2417
2418/**
2419 * dev only flag to track whether $attrs was used during render.
2420 * If $attrs was used during render then the warning for failed attrs
2421 * fallthrough can be suppressed.
2422 */
2423let accessedAttrs = false;
2424function markAttrsAccessed() {
2425 accessedAttrs = true;
2426}
2427function renderComponentRoot(instance) {
2428 const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx, inheritAttrs } = instance;
2429 let result;
2430 let fallthroughAttrs;
2431 const prev = setCurrentRenderingInstance(instance);
2432 {
2433 accessedAttrs = false;
2434 }
2435 try {
2436 if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
2437 // withProxy is a proxy with a different `has` trap only for
2438 // runtime-compiled render functions using `with` block.
2439 const proxyToUse = withProxy || proxy;
2440 result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
2441 fallthroughAttrs = attrs;
2442 }
2443 else {
2444 // functional
2445 const render = Component;
2446 // in dev, mark attrs accessed if optional props (attrs === props)
2447 if (true && attrs === props) {
2448 markAttrsAccessed();
2449 }
2450 result = normalizeVNode(render.length > 1
2451 ? render(props, true
2452 ? {
2453 get attrs() {
2454 markAttrsAccessed();
2455 return attrs;
2456 },
2457 slots,
2458 emit
2459 }
2460 : { attrs, slots, emit })
2461 : render(props, null /* we know it doesn't need it */));
2462 fallthroughAttrs = Component.props
2463 ? attrs
2464 : getFunctionalFallthrough(attrs);
2465 }
2466 }
2467 catch (err) {
2468 blockStack.length = 0;
2469 handleError(err, instance, 1 /* RENDER_FUNCTION */);
2470 result = createVNode(Comment);
2471 }
2472 // attr merging
2473 // in dev mode, comments are preserved, and it's possible for a template
2474 // to have comments along side the root element which makes it a fragment
2475 let root = result;
2476 let setRoot = undefined;
2477 if (result.patchFlag > 0 &&
2478 result.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
2479 [root, setRoot] = getChildRoot(result);
2480 }
2481 if (fallthroughAttrs && inheritAttrs !== false) {
2482 const keys = Object.keys(fallthroughAttrs);
2483 const { shapeFlag } = root;
2484 if (keys.length) {
2485 if (shapeFlag & (1 /* ELEMENT */ | 6 /* COMPONENT */)) {
2486 if (propsOptions && keys.some(isModelListener)) {
2487 // If a v-model listener (onUpdate:xxx) has a corresponding declared
2488 // prop, it indicates this component expects to handle v-model and
2489 // it should not fallthrough.
2490 // related: #1543, #1643, #1989
2491 fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
2492 }
2493 root = cloneVNode(root, fallthroughAttrs);
2494 }
2495 else if (!accessedAttrs && root.type !== Comment) {
2496 const allAttrs = Object.keys(attrs);
2497 const eventAttrs = [];
2498 const extraAttrs = [];
2499 for (let i = 0, l = allAttrs.length; i < l; i++) {
2500 const key = allAttrs[i];
2501 if (isOn(key)) {
2502 // ignore v-model handlers when they fail to fallthrough
2503 if (!isModelListener(key)) {
2504 // remove `on`, lowercase first letter to reflect event casing
2505 // accurately
2506 eventAttrs.push(key[2].toLowerCase() + key.slice(3));
2507 }
2508 }
2509 else {
2510 extraAttrs.push(key);
2511 }
2512 }
2513 if (extraAttrs.length) {
2514 warn$1(`Extraneous non-props attributes (` +
2515 `${extraAttrs.join(', ')}) ` +
2516 `were passed to component but could not be automatically inherited ` +
2517 `because component renders fragment or text root nodes.`);
2518 }
2519 if (eventAttrs.length) {
2520 warn$1(`Extraneous non-emits event listeners (` +
2521 `${eventAttrs.join(', ')}) ` +
2522 `were passed to component but could not be automatically inherited ` +
2523 `because component renders fragment or text root nodes. ` +
2524 `If the listener is intended to be a component custom event listener only, ` +
2525 `declare it using the "emits" option.`);
2526 }
2527 }
2528 }
2529 }
2530 // inherit directives
2531 if (vnode.dirs) {
2532 if (!isElementRoot(root)) {
2533 warn$1(`Runtime directive used on component with non-element root node. ` +
2534 `The directives will not function as intended.`);
2535 }
2536 root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
2537 }
2538 // inherit transition data
2539 if (vnode.transition) {
2540 if (!isElementRoot(root)) {
2541 warn$1(`Component inside <Transition> renders non-element root node ` +
2542 `that cannot be animated.`);
2543 }
2544 root.transition = vnode.transition;
2545 }
2546 if (setRoot) {
2547 setRoot(root);
2548 }
2549 else {
2550 result = root;
2551 }
2552 setCurrentRenderingInstance(prev);
2553 return result;
2554}
2555/**
2556 * dev only
2557 * In dev mode, template root level comments are rendered, which turns the
2558 * template into a fragment root, but we need to locate the single element
2559 * root for attrs and scope id processing.
2560 */
2561const getChildRoot = (vnode) => {
2562 const rawChildren = vnode.children;
2563 const dynamicChildren = vnode.dynamicChildren;
2564 const childRoot = filterSingleRoot(rawChildren);
2565 if (!childRoot) {
2566 return [vnode, undefined];
2567 }
2568 const index = rawChildren.indexOf(childRoot);
2569 const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
2570 const setRoot = (updatedRoot) => {
2571 rawChildren[index] = updatedRoot;
2572 if (dynamicChildren) {
2573 if (dynamicIndex > -1) {
2574 dynamicChildren[dynamicIndex] = updatedRoot;
2575 }
2576 else if (updatedRoot.patchFlag > 0) {
2577 vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
2578 }
2579 }
2580 };
2581 return [normalizeVNode(childRoot), setRoot];
2582};
2583function filterSingleRoot(children) {
2584 let singleRoot;
2585 for (let i = 0; i < children.length; i++) {
2586 const child = children[i];
2587 if (isVNode(child)) {
2588 // ignore user comment
2589 if (child.type !== Comment || child.children === 'v-if') {
2590 if (singleRoot) {
2591 // has more than 1 non-comment child, return now
2592 return;
2593 }
2594 else {
2595 singleRoot = child;
2596 }
2597 }
2598 }
2599 else {
2600 return;
2601 }
2602 }
2603 return singleRoot;
2604}
2605const getFunctionalFallthrough = (attrs) => {
2606 let res;
2607 for (const key in attrs) {
2608 if (key === 'class' || key === 'style' || isOn(key)) {
2609 (res || (res = {}))[key] = attrs[key];
2610 }
2611 }
2612 return res;
2613};
2614const filterModelListeners = (attrs, props) => {
2615 const res = {};
2616 for (const key in attrs) {
2617 if (!isModelListener(key) || !(key.slice(9) in props)) {
2618 res[key] = attrs[key];
2619 }
2620 }
2621 return res;
2622};
2623const isElementRoot = (vnode) => {
2624 return (vnode.shapeFlag & (6 /* COMPONENT */ | 1 /* ELEMENT */) ||
2625 vnode.type === Comment // potential v-if branch switch
2626 );
2627};
2628function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
2629 const { props: prevProps, children: prevChildren, component } = prevVNode;
2630 const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
2631 const emits = component.emitsOptions;
2632 // Parent component's render function was hot-updated. Since this may have
2633 // caused the child component's slots content to have changed, we need to
2634 // force the child to update as well.
2635 if ((prevChildren || nextChildren) && isHmrUpdating) {
2636 return true;
2637 }
2638 // force child update for runtime directive or transition on component vnode.
2639 if (nextVNode.dirs || nextVNode.transition) {
2640 return true;
2641 }
2642 if (optimized && patchFlag >= 0) {
2643 if (patchFlag & 1024 /* DYNAMIC_SLOTS */) {
2644 // slot content that references values that might have changed,
2645 // e.g. in a v-for
2646 return true;
2647 }
2648 if (patchFlag & 16 /* FULL_PROPS */) {
2649 if (!prevProps) {
2650 return !!nextProps;
2651 }
2652 // presence of this flag indicates props are always non-null
2653 return hasPropsChanged(prevProps, nextProps, emits);
2654 }
2655 else if (patchFlag & 8 /* PROPS */) {
2656 const dynamicProps = nextVNode.dynamicProps;
2657 for (let i = 0; i < dynamicProps.length; i++) {
2658 const key = dynamicProps[i];
2659 if (nextProps[key] !== prevProps[key] &&
2660 !isEmitListener(emits, key)) {
2661 return true;
2662 }
2663 }
2664 }
2665 }
2666 else {
2667 // this path is only taken by manually written render functions
2668 // so presence of any children leads to a forced update
2669 if (prevChildren || nextChildren) {
2670 if (!nextChildren || !nextChildren.$stable) {
2671 return true;
2672 }
2673 }
2674 if (prevProps === nextProps) {
2675 return false;
2676 }
2677 if (!prevProps) {
2678 return !!nextProps;
2679 }
2680 if (!nextProps) {
2681 return true;
2682 }
2683 return hasPropsChanged(prevProps, nextProps, emits);
2684 }
2685 return false;
2686}
2687function hasPropsChanged(prevProps, nextProps, emitsOptions) {
2688 const nextKeys = Object.keys(nextProps);
2689 if (nextKeys.length !== Object.keys(prevProps).length) {
2690 return true;
2691 }
2692 for (let i = 0; i < nextKeys.length; i++) {
2693 const key = nextKeys[i];
2694 if (nextProps[key] !== prevProps[key] &&
2695 !isEmitListener(emitsOptions, key)) {
2696 return true;
2697 }
2698 }
2699 return false;
2700}
2701function updateHOCHostEl({ vnode, parent }, el // HostNode
2702) {
2703 while (parent && parent.subTree === vnode) {
2704 (vnode = parent.vnode).el = el;
2705 parent = parent.parent;
2706 }
2707}
2708
2709const isSuspense = (type) => type.__isSuspense;
2710// Suspense exposes a component-like API, and is treated like a component
2711// in the compiler, but internally it's a special built-in type that hooks
2712// directly into the renderer.
2713const SuspenseImpl = {
2714 name: 'Suspense',
2715 // In order to make Suspense tree-shakable, we need to avoid importing it
2716 // directly in the renderer. The renderer checks for the __isSuspense flag
2717 // on a vnode's type and calls the `process` method, passing in renderer
2718 // internals.
2719 __isSuspense: true,
2720 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized,
2721 // platform-specific impl passed from renderer
2722 rendererInternals) {
2723 if (n1 == null) {
2724 mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals);
2725 }
2726 else {
2727 patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, rendererInternals);
2728 }
2729 },
2730 hydrate: hydrateSuspense,
2731 create: createSuspenseBoundary,
2732 normalize: normalizeSuspenseChildren
2733};
2734// Force-casted public typing for h and TSX props inference
2735const Suspense = (SuspenseImpl );
2736function triggerEvent(vnode, name) {
2737 const eventListener = vnode.props && vnode.props[name];
2738 if (isFunction(eventListener)) {
2739 eventListener();
2740 }
2741}
2742function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals) {
2743 const { p: patch, o: { createElement } } = rendererInternals;
2744 const hiddenContainer = createElement('div');
2745 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals));
2746 // start mounting the content subtree in an off-dom container
2747 patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds);
2748 // now check if we have encountered any async deps
2749 if (suspense.deps > 0) {
2750 // has async
2751 // invoke @fallback event
2752 triggerEvent(vnode, 'onPending');
2753 triggerEvent(vnode, 'onFallback');
2754 // mount the fallback tree
2755 patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2756 isSVG, slotScopeIds);
2757 setActiveBranch(suspense, vnode.ssFallback);
2758 }
2759 else {
2760 // Suspense has no async deps. Just resolve.
2761 suspense.resolve();
2762 }
2763}
2764function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) {
2765 const suspense = (n2.suspense = n1.suspense);
2766 suspense.vnode = n2;
2767 n2.el = n1.el;
2768 const newBranch = n2.ssContent;
2769 const newFallback = n2.ssFallback;
2770 const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
2771 if (pendingBranch) {
2772 suspense.pendingBranch = newBranch;
2773 if (isSameVNodeType(newBranch, pendingBranch)) {
2774 // same root type but content may have changed.
2775 patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2776 if (suspense.deps <= 0) {
2777 suspense.resolve();
2778 }
2779 else if (isInFallback) {
2780 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2781 isSVG, slotScopeIds, optimized);
2782 setActiveBranch(suspense, newFallback);
2783 }
2784 }
2785 else {
2786 // toggled before pending tree is resolved
2787 suspense.pendingId++;
2788 if (isHydrating) {
2789 // if toggled before hydration is finished, the current DOM tree is
2790 // no longer valid. set it as the active branch so it will be unmounted
2791 // when resolved
2792 suspense.isHydrating = false;
2793 suspense.activeBranch = pendingBranch;
2794 }
2795 else {
2796 unmount(pendingBranch, parentComponent, suspense);
2797 }
2798 // increment pending ID. this is used to invalidate async callbacks
2799 // reset suspense state
2800 suspense.deps = 0;
2801 // discard effects from pending branch
2802 suspense.effects.length = 0;
2803 // discard previous container
2804 suspense.hiddenContainer = createElement('div');
2805 if (isInFallback) {
2806 // already in fallback state
2807 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2808 if (suspense.deps <= 0) {
2809 suspense.resolve();
2810 }
2811 else {
2812 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2813 isSVG, slotScopeIds, optimized);
2814 setActiveBranch(suspense, newFallback);
2815 }
2816 }
2817 else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2818 // toggled "back" to current active branch
2819 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2820 // force resolve
2821 suspense.resolve(true);
2822 }
2823 else {
2824 // switched to a 3rd branch
2825 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2826 if (suspense.deps <= 0) {
2827 suspense.resolve();
2828 }
2829 }
2830 }
2831 }
2832 else {
2833 if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2834 // root did not change, just normal patch
2835 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2836 setActiveBranch(suspense, newBranch);
2837 }
2838 else {
2839 // root node toggled
2840 // invoke @pending event
2841 triggerEvent(n2, 'onPending');
2842 // mount pending branch in off-dom container
2843 suspense.pendingBranch = newBranch;
2844 suspense.pendingId++;
2845 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2846 if (suspense.deps <= 0) {
2847 // incoming branch has no async deps, resolve now.
2848 suspense.resolve();
2849 }
2850 else {
2851 const { timeout, pendingId } = suspense;
2852 if (timeout > 0) {
2853 setTimeout(() => {
2854 if (suspense.pendingId === pendingId) {
2855 suspense.fallback(newFallback);
2856 }
2857 }, timeout);
2858 }
2859 else if (timeout === 0) {
2860 suspense.fallback(newFallback);
2861 }
2862 }
2863 }
2864 }
2865}
2866let hasWarned = false;
2867function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals, isHydrating = false) {
2868 /* istanbul ignore if */
2869 if (!hasWarned) {
2870 hasWarned = true;
2871 // @ts-ignore `console.info` cannot be null error
2872 console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
2873 }
2874 const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
2875 const timeout = toNumber(vnode.props && vnode.props.timeout);
2876 const suspense = {
2877 vnode,
2878 parent,
2879 parentComponent,
2880 isSVG,
2881 container,
2882 hiddenContainer,
2883 anchor,
2884 deps: 0,
2885 pendingId: 0,
2886 timeout: typeof timeout === 'number' ? timeout : -1,
2887 activeBranch: null,
2888 pendingBranch: null,
2889 isInFallback: true,
2890 isHydrating,
2891 isUnmounted: false,
2892 effects: [],
2893 resolve(resume = false) {
2894 {
2895 if (!resume && !suspense.pendingBranch) {
2896 throw new Error(`suspense.resolve() is called without a pending branch.`);
2897 }
2898 if (suspense.isUnmounted) {
2899 throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
2900 }
2901 }
2902 const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
2903 if (suspense.isHydrating) {
2904 suspense.isHydrating = false;
2905 }
2906 else if (!resume) {
2907 const delayEnter = activeBranch &&
2908 pendingBranch.transition &&
2909 pendingBranch.transition.mode === 'out-in';
2910 if (delayEnter) {
2911 activeBranch.transition.afterLeave = () => {
2912 if (pendingId === suspense.pendingId) {
2913 move(pendingBranch, container, anchor, 0 /* ENTER */);
2914 }
2915 };
2916 }
2917 // this is initial anchor on mount
2918 let { anchor } = suspense;
2919 // unmount current active tree
2920 if (activeBranch) {
2921 // if the fallback tree was mounted, it may have been moved
2922 // as part of a parent suspense. get the latest anchor for insertion
2923 anchor = next(activeBranch);
2924 unmount(activeBranch, parentComponent, suspense, true);
2925 }
2926 if (!delayEnter) {
2927 // move content from off-dom container to actual container
2928 move(pendingBranch, container, anchor, 0 /* ENTER */);
2929 }
2930 }
2931 setActiveBranch(suspense, pendingBranch);
2932 suspense.pendingBranch = null;
2933 suspense.isInFallback = false;
2934 // flush buffered effects
2935 // check if there is a pending parent suspense
2936 let parent = suspense.parent;
2937 let hasUnresolvedAncestor = false;
2938 while (parent) {
2939 if (parent.pendingBranch) {
2940 // found a pending parent suspense, merge buffered post jobs
2941 // into that parent
2942 parent.effects.push(...effects);
2943 hasUnresolvedAncestor = true;
2944 break;
2945 }
2946 parent = parent.parent;
2947 }
2948 // no pending parent suspense, flush all jobs
2949 if (!hasUnresolvedAncestor) {
2950 queuePostFlushCb(effects);
2951 }
2952 suspense.effects = [];
2953 // invoke @resolve event
2954 triggerEvent(vnode, 'onResolve');
2955 },
2956 fallback(fallbackVNode) {
2957 if (!suspense.pendingBranch) {
2958 return;
2959 }
2960 const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
2961 // invoke @fallback event
2962 triggerEvent(vnode, 'onFallback');
2963 const anchor = next(activeBranch);
2964 const mountFallback = () => {
2965 if (!suspense.isInFallback) {
2966 return;
2967 }
2968 // mount the fallback tree
2969 patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2970 isSVG, slotScopeIds, optimized);
2971 setActiveBranch(suspense, fallbackVNode);
2972 };
2973 const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
2974 if (delayEnter) {
2975 activeBranch.transition.afterLeave = mountFallback;
2976 }
2977 suspense.isInFallback = true;
2978 // unmount current active branch
2979 unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
2980 true // shouldRemove
2981 );
2982 if (!delayEnter) {
2983 mountFallback();
2984 }
2985 },
2986 move(container, anchor, type) {
2987 suspense.activeBranch &&
2988 move(suspense.activeBranch, container, anchor, type);
2989 suspense.container = container;
2990 },
2991 next() {
2992 return suspense.activeBranch && next(suspense.activeBranch);
2993 },
2994 registerDep(instance, setupRenderEffect) {
2995 const isInPendingSuspense = !!suspense.pendingBranch;
2996 if (isInPendingSuspense) {
2997 suspense.deps++;
2998 }
2999 const hydratedEl = instance.vnode.el;
3000 instance
3001 .asyncDep.catch(err => {
3002 handleError(err, instance, 0 /* SETUP_FUNCTION */);
3003 })
3004 .then(asyncSetupResult => {
3005 // retry when the setup() promise resolves.
3006 // component may have been unmounted before resolve.
3007 if (instance.isUnmounted ||
3008 suspense.isUnmounted ||
3009 suspense.pendingId !== instance.suspenseId) {
3010 return;
3011 }
3012 // retry from this component
3013 instance.asyncResolved = true;
3014 const { vnode } = instance;
3015 {
3016 pushWarningContext(vnode);
3017 }
3018 handleSetupResult(instance, asyncSetupResult, false);
3019 if (hydratedEl) {
3020 // vnode may have been replaced if an update happened before the
3021 // async dep is resolved.
3022 vnode.el = hydratedEl;
3023 }
3024 const placeholder = !hydratedEl && instance.subTree.el;
3025 setupRenderEffect(instance, vnode,
3026 // component may have been moved before resolve.
3027 // if this is not a hydration, instance.subTree will be the comment
3028 // placeholder.
3029 parentNode(hydratedEl || instance.subTree.el),
3030 // anchor will not be used if this is hydration, so only need to
3031 // consider the comment placeholder case.
3032 hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
3033 if (placeholder) {
3034 remove(placeholder);
3035 }
3036 updateHOCHostEl(instance, vnode.el);
3037 {
3038 popWarningContext();
3039 }
3040 // only decrease deps count if suspense is not already resolved
3041 if (isInPendingSuspense && --suspense.deps === 0) {
3042 suspense.resolve();
3043 }
3044 });
3045 },
3046 unmount(parentSuspense, doRemove) {
3047 suspense.isUnmounted = true;
3048 if (suspense.activeBranch) {
3049 unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
3050 }
3051 if (suspense.pendingBranch) {
3052 unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
3053 }
3054 }
3055 };
3056 return suspense;
3057}
3058function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals, hydrateNode) {
3059 /* eslint-disable no-restricted-globals */
3060 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, slotScopeIds, optimized, rendererInternals, true /* hydrating */));
3061 // there are two possible scenarios for server-rendered suspense:
3062 // - success: ssr content should be fully resolved
3063 // - failure: ssr content should be the fallback branch.
3064 // however, on the client we don't really know if it has failed or not
3065 // attempt to hydrate the DOM assuming it has succeeded, but we still
3066 // need to construct a suspense boundary first
3067 const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, slotScopeIds, optimized);
3068 if (suspense.deps === 0) {
3069 suspense.resolve();
3070 }
3071 return result;
3072 /* eslint-enable no-restricted-globals */
3073}
3074function normalizeSuspenseChildren(vnode) {
3075 const { shapeFlag, children } = vnode;
3076 const isSlotChildren = shapeFlag & 32 /* SLOTS_CHILDREN */;
3077 vnode.ssContent = normalizeSuspenseSlot(isSlotChildren ? children.default : children);
3078 vnode.ssFallback = isSlotChildren
3079 ? normalizeSuspenseSlot(children.fallback)
3080 : createVNode(Comment);
3081}
3082function normalizeSuspenseSlot(s) {
3083 let block;
3084 if (isFunction(s)) {
3085 const trackBlock = isBlockTreeEnabled && s._c;
3086 if (trackBlock) {
3087 // disableTracking: false
3088 // allow block tracking for compiled slots
3089 // (see ./componentRenderContext.ts)
3090 s._d = false;
3091 openBlock();
3092 }
3093 s = s();
3094 if (trackBlock) {
3095 s._d = true;
3096 block = currentBlock;
3097 closeBlock();
3098 }
3099 }
3100 if (isArray(s)) {
3101 const singleChild = filterSingleRoot(s);
3102 if (!singleChild) {
3103 warn$1(`<Suspense> slots expect a single root node.`);
3104 }
3105 s = singleChild;
3106 }
3107 s = normalizeVNode(s);
3108 if (block && !s.dynamicChildren) {
3109 s.dynamicChildren = block.filter(c => c !== s);
3110 }
3111 return s;
3112}
3113function queueEffectWithSuspense(fn, suspense) {
3114 if (suspense && suspense.pendingBranch) {
3115 if (isArray(fn)) {
3116 suspense.effects.push(...fn);
3117 }
3118 else {
3119 suspense.effects.push(fn);
3120 }
3121 }
3122 else {
3123 queuePostFlushCb(fn);
3124 }
3125}
3126function setActiveBranch(suspense, branch) {
3127 suspense.activeBranch = branch;
3128 const { vnode, parentComponent } = suspense;
3129 const el = (vnode.el = branch.el);
3130 // in case suspense is the root node of a component,
3131 // recursively update the HOC el
3132 if (parentComponent && parentComponent.subTree === vnode) {
3133 parentComponent.vnode.el = el;
3134 updateHOCHostEl(parentComponent, el);
3135 }
3136}
3137
3138function provide(key, value) {
3139 if (!currentInstance) {
3140 {
3141 warn$1(`provide() can only be used inside setup().`);
3142 }
3143 }
3144 else {
3145 let provides = currentInstance.provides;
3146 // by default an instance inherits its parent's provides object
3147 // but when it needs to provide values of its own, it creates its
3148 // own provides object using parent provides object as prototype.
3149 // this way in `inject` we can simply look up injections from direct
3150 // parent and let the prototype chain do the work.
3151 const parentProvides = currentInstance.parent && currentInstance.parent.provides;
3152 if (parentProvides === provides) {
3153 provides = currentInstance.provides = Object.create(parentProvides);
3154 }
3155 // TS doesn't allow symbol as index type
3156 provides[key] = value;
3157 }
3158}
3159function inject(key, defaultValue, treatDefaultAsFactory = false) {
3160 // fallback to `currentRenderingInstance` so that this can be called in
3161 // a functional component
3162 const instance = currentInstance || currentRenderingInstance;
3163 if (instance) {
3164 // #2400
3165 // to support `app.use` plugins,
3166 // fallback to appContext's `provides` if the instance is at root
3167 const provides = instance.parent == null
3168 ? instance.vnode.appContext && instance.vnode.appContext.provides
3169 : instance.parent.provides;
3170 if (provides && key in provides) {
3171 // TS doesn't allow symbol as index type
3172 return provides[key];
3173 }
3174 else if (arguments.length > 1) {
3175 return treatDefaultAsFactory && isFunction(defaultValue)
3176 ? defaultValue.call(instance.proxy)
3177 : defaultValue;
3178 }
3179 else {
3180 warn$1(`injection "${String(key)}" not found.`);
3181 }
3182 }
3183 else {
3184 warn$1(`inject() can only be used inside setup() or functional components.`);
3185 }
3186}
3187
3188// Simple effect.
3189function watchEffect(effect, options) {
3190 return doWatch(effect, null, options);
3191}
3192function watchPostEffect(effect, options) {
3193 return doWatch(effect, null, (Object.assign(Object.assign({}, options), { flush: 'post' }) ));
3194}
3195function watchSyncEffect(effect, options) {
3196 return doWatch(effect, null, (Object.assign(Object.assign({}, options), { flush: 'sync' }) ));
3197}
3198// initial value for watchers to trigger on undefined initial values
3199const INITIAL_WATCHER_VALUE = {};
3200// implementation
3201function watch(source, cb, options) {
3202 if (!isFunction(cb)) {
3203 warn$1(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
3204 `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
3205 `supports \`watch(source, cb, options?) signature.`);
3206 }
3207 return doWatch(source, cb, options);
3208}
3209function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ) {
3210 if (!cb) {
3211 if (immediate !== undefined) {
3212 warn$1(`watch() "immediate" option is only respected when using the ` +
3213 `watch(source, callback, options?) signature.`);
3214 }
3215 if (deep !== undefined) {
3216 warn$1(`watch() "deep" option is only respected when using the ` +
3217 `watch(source, callback, options?) signature.`);
3218 }
3219 }
3220 const warnInvalidSource = (s) => {
3221 warn$1(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
3222 `a reactive object, or an array of these types.`);
3223 };
3224 const instance = currentInstance;
3225 let getter;
3226 let forceTrigger = false;
3227 let isMultiSource = false;
3228 if (isRef(source)) {
3229 getter = () => source.value;
3230 forceTrigger = isShallow(source);
3231 }
3232 else if (isReactive(source)) {
3233 getter = () => source;
3234 deep = true;
3235 }
3236 else if (isArray(source)) {
3237 isMultiSource = true;
3238 forceTrigger = source.some(isReactive);
3239 getter = () => source.map(s => {
3240 if (isRef(s)) {
3241 return s.value;
3242 }
3243 else if (isReactive(s)) {
3244 return traverse(s);
3245 }
3246 else if (isFunction(s)) {
3247 return callWithErrorHandling(s, instance, 2 /* WATCH_GETTER */);
3248 }
3249 else {
3250 warnInvalidSource(s);
3251 }
3252 });
3253 }
3254 else if (isFunction(source)) {
3255 if (cb) {
3256 // getter with cb
3257 getter = () => callWithErrorHandling(source, instance, 2 /* WATCH_GETTER */);
3258 }
3259 else {
3260 // no cb -> simple effect
3261 getter = () => {
3262 if (instance && instance.isUnmounted) {
3263 return;
3264 }
3265 if (cleanup) {
3266 cleanup();
3267 }
3268 return callWithAsyncErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onCleanup]);
3269 };
3270 }
3271 }
3272 else {
3273 getter = NOOP;
3274 warnInvalidSource(source);
3275 }
3276 if (cb && deep) {
3277 const baseGetter = getter;
3278 getter = () => traverse(baseGetter());
3279 }
3280 let cleanup;
3281 let onCleanup = (fn) => {
3282 cleanup = effect.onStop = () => {
3283 callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */);
3284 };
3285 };
3286 let oldValue = isMultiSource ? [] : INITIAL_WATCHER_VALUE;
3287 const job = () => {
3288 if (!effect.active) {
3289 return;
3290 }
3291 if (cb) {
3292 // watch(source, cb)
3293 const newValue = effect.run();
3294 if (deep ||
3295 forceTrigger ||
3296 (isMultiSource
3297 ? newValue.some((v, i) => hasChanged(v, oldValue[i]))
3298 : hasChanged(newValue, oldValue)) ||
3299 (false )) {
3300 // cleanup before running cb again
3301 if (cleanup) {
3302 cleanup();
3303 }
3304 callWithAsyncErrorHandling(cb, instance, 3 /* WATCH_CALLBACK */, [
3305 newValue,
3306 // pass undefined as the old value when it's changed for the first time
3307 oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
3308 onCleanup
3309 ]);
3310 oldValue = newValue;
3311 }
3312 }
3313 else {
3314 // watchEffect
3315 effect.run();
3316 }
3317 };
3318 // important: mark the job as a watcher callback so that scheduler knows
3319 // it is allowed to self-trigger (#1727)
3320 job.allowRecurse = !!cb;
3321 let scheduler;
3322 if (flush === 'sync') {
3323 scheduler = job; // the scheduler function gets called directly
3324 }
3325 else if (flush === 'post') {
3326 scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
3327 }
3328 else {
3329 // default: 'pre'
3330 scheduler = () => {
3331 if (!instance || instance.isMounted) {
3332 queuePreFlushCb(job);
3333 }
3334 else {
3335 // with 'pre' option, the first call must happen before
3336 // the component is mounted so it is called synchronously.
3337 job();
3338 }
3339 };
3340 }
3341 const effect = new ReactiveEffect(getter, scheduler);
3342 {
3343 effect.onTrack = onTrack;
3344 effect.onTrigger = onTrigger;
3345 }
3346 // initial run
3347 if (cb) {
3348 if (immediate) {
3349 job();
3350 }
3351 else {
3352 oldValue = effect.run();
3353 }
3354 }
3355 else if (flush === 'post') {
3356 queuePostRenderEffect(effect.run.bind(effect), instance && instance.suspense);
3357 }
3358 else {
3359 effect.run();
3360 }
3361 return () => {
3362 effect.stop();
3363 if (instance && instance.scope) {
3364 remove(instance.scope.effects, effect);
3365 }
3366 };
3367}
3368// this.$watch
3369function instanceWatch(source, value, options) {
3370 const publicThis = this.proxy;
3371 const getter = isString(source)
3372 ? source.includes('.')
3373 ? createPathGetter(publicThis, source)
3374 : () => publicThis[source]
3375 : source.bind(publicThis, publicThis);
3376 let cb;
3377 if (isFunction(value)) {
3378 cb = value;
3379 }
3380 else {
3381 cb = value.handler;
3382 options = value;
3383 }
3384 const cur = currentInstance;
3385 setCurrentInstance(this);
3386 const res = doWatch(getter, cb.bind(publicThis), options);
3387 if (cur) {
3388 setCurrentInstance(cur);
3389 }
3390 else {
3391 unsetCurrentInstance();
3392 }
3393 return res;
3394}
3395function createPathGetter(ctx, path) {
3396 const segments = path.split('.');
3397 return () => {
3398 let cur = ctx;
3399 for (let i = 0; i < segments.length && cur; i++) {
3400 cur = cur[segments[i]];
3401 }
3402 return cur;
3403 };
3404}
3405function traverse(value, seen) {
3406 if (!isObject(value) || value["__v_skip" /* SKIP */]) {
3407 return value;
3408 }
3409 seen = seen || new Set();
3410 if (seen.has(value)) {
3411 return value;
3412 }
3413 seen.add(value);
3414 if (isRef(value)) {
3415 traverse(value.value, seen);
3416 }
3417 else if (isArray(value)) {
3418 for (let i = 0; i < value.length; i++) {
3419 traverse(value[i], seen);
3420 }
3421 }
3422 else if (isSet(value) || isMap(value)) {
3423 value.forEach((v) => {
3424 traverse(v, seen);
3425 });
3426 }
3427 else if (isPlainObject(value)) {
3428 for (const key in value) {
3429 traverse(value[key], seen);
3430 }
3431 }
3432 return value;
3433}
3434
3435function useTransitionState() {
3436 const state = {
3437 isMounted: false,
3438 isLeaving: false,
3439 isUnmounting: false,
3440 leavingVNodes: new Map()
3441 };
3442 onMounted(() => {
3443 state.isMounted = true;
3444 });
3445 onBeforeUnmount(() => {
3446 state.isUnmounting = true;
3447 });
3448 return state;
3449}
3450const TransitionHookValidator = [Function, Array];
3451const BaseTransitionImpl = {
3452 name: `BaseTransition`,
3453 props: {
3454 mode: String,
3455 appear: Boolean,
3456 persisted: Boolean,
3457 // enter
3458 onBeforeEnter: TransitionHookValidator,
3459 onEnter: TransitionHookValidator,
3460 onAfterEnter: TransitionHookValidator,
3461 onEnterCancelled: TransitionHookValidator,
3462 // leave
3463 onBeforeLeave: TransitionHookValidator,
3464 onLeave: TransitionHookValidator,
3465 onAfterLeave: TransitionHookValidator,
3466 onLeaveCancelled: TransitionHookValidator,
3467 // appear
3468 onBeforeAppear: TransitionHookValidator,
3469 onAppear: TransitionHookValidator,
3470 onAfterAppear: TransitionHookValidator,
3471 onAppearCancelled: TransitionHookValidator
3472 },
3473 setup(props, { slots }) {
3474 const instance = getCurrentInstance();
3475 const state = useTransitionState();
3476 let prevTransitionKey;
3477 return () => {
3478 const children = slots.default && getTransitionRawChildren(slots.default(), true);
3479 if (!children || !children.length) {
3480 return;
3481 }
3482 let child = children[0];
3483 if (children.length > 1) {
3484 let hasFound = false;
3485 // locate first non-comment child
3486 for (const c of children) {
3487 if (c.type !== Comment) {
3488 if (hasFound) {
3489 // warn more than one non-comment child
3490 warn$1('<transition> can only be used on a single element or component. ' +
3491 'Use <transition-group> for lists.');
3492 break;
3493 }
3494 child = c;
3495 hasFound = true;
3496 }
3497 }
3498 }
3499 // there's no need to track reactivity for these props so use the raw
3500 // props for a bit better perf
3501 const rawProps = toRaw(props);
3502 const { mode } = rawProps;
3503 // check mode
3504 if (mode &&
3505 mode !== 'in-out' &&
3506 mode !== 'out-in' &&
3507 mode !== 'default') {
3508 warn$1(`invalid <transition> mode: ${mode}`);
3509 }
3510 if (state.isLeaving) {
3511 return emptyPlaceholder(child);
3512 }
3513 // in the case of <transition><keep-alive/></transition>, we need to
3514 // compare the type of the kept-alive children.
3515 const innerChild = getKeepAliveChild(child);
3516 if (!innerChild) {
3517 return emptyPlaceholder(child);
3518 }
3519 const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
3520 setTransitionHooks(innerChild, enterHooks);
3521 const oldChild = instance.subTree;
3522 const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
3523 let transitionKeyChanged = false;
3524 const { getTransitionKey } = innerChild.type;
3525 if (getTransitionKey) {
3526 const key = getTransitionKey();
3527 if (prevTransitionKey === undefined) {
3528 prevTransitionKey = key;
3529 }
3530 else if (key !== prevTransitionKey) {
3531 prevTransitionKey = key;
3532 transitionKeyChanged = true;
3533 }
3534 }
3535 // handle mode
3536 if (oldInnerChild &&
3537 oldInnerChild.type !== Comment &&
3538 (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
3539 const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
3540 // update old tree's hooks in case of dynamic transition
3541 setTransitionHooks(oldInnerChild, leavingHooks);
3542 // switching between different views
3543 if (mode === 'out-in') {
3544 state.isLeaving = true;
3545 // return placeholder node and queue update when leave finishes
3546 leavingHooks.afterLeave = () => {
3547 state.isLeaving = false;
3548 instance.update();
3549 };
3550 return emptyPlaceholder(child);
3551 }
3552 else if (mode === 'in-out' && innerChild.type !== Comment) {
3553 leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
3554 const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
3555 leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
3556 // early removal callback
3557 el._leaveCb = () => {
3558 earlyRemove();
3559 el._leaveCb = undefined;
3560 delete enterHooks.delayedLeave;
3561 };
3562 enterHooks.delayedLeave = delayedLeave;
3563 };
3564 }
3565 }
3566 return child;
3567 };
3568 }
3569};
3570// export the public type for h/tsx inference
3571// also to avoid inline import() in generated d.ts files
3572const BaseTransition = BaseTransitionImpl;
3573function getLeavingNodesForType(state, vnode) {
3574 const { leavingVNodes } = state;
3575 let leavingVNodesCache = leavingVNodes.get(vnode.type);
3576 if (!leavingVNodesCache) {
3577 leavingVNodesCache = Object.create(null);
3578 leavingVNodes.set(vnode.type, leavingVNodesCache);
3579 }
3580 return leavingVNodesCache;
3581}
3582// The transition hooks are attached to the vnode as vnode.transition
3583// and will be called at appropriate timing in the renderer.
3584function resolveTransitionHooks(vnode, props, state, instance) {
3585 const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
3586 const key = String(vnode.key);
3587 const leavingVNodesCache = getLeavingNodesForType(state, vnode);
3588 const callHook = (hook, args) => {
3589 hook &&
3590 callWithAsyncErrorHandling(hook, instance, 9 /* TRANSITION_HOOK */, args);
3591 };
3592 const hooks = {
3593 mode,
3594 persisted,
3595 beforeEnter(el) {
3596 let hook = onBeforeEnter;
3597 if (!state.isMounted) {
3598 if (appear) {
3599 hook = onBeforeAppear || onBeforeEnter;
3600 }
3601 else {
3602 return;
3603 }
3604 }
3605 // for same element (v-show)
3606 if (el._leaveCb) {
3607 el._leaveCb(true /* cancelled */);
3608 }
3609 // for toggled element with same key (v-if)
3610 const leavingVNode = leavingVNodesCache[key];
3611 if (leavingVNode &&
3612 isSameVNodeType(vnode, leavingVNode) &&
3613 leavingVNode.el._leaveCb) {
3614 // force early removal (not cancelled)
3615 leavingVNode.el._leaveCb();
3616 }
3617 callHook(hook, [el]);
3618 },
3619 enter(el) {
3620 let hook = onEnter;
3621 let afterHook = onAfterEnter;
3622 let cancelHook = onEnterCancelled;
3623 if (!state.isMounted) {
3624 if (appear) {
3625 hook = onAppear || onEnter;
3626 afterHook = onAfterAppear || onAfterEnter;
3627 cancelHook = onAppearCancelled || onEnterCancelled;
3628 }
3629 else {
3630 return;
3631 }
3632 }
3633 let called = false;
3634 const done = (el._enterCb = (cancelled) => {
3635 if (called)
3636 return;
3637 called = true;
3638 if (cancelled) {
3639 callHook(cancelHook, [el]);
3640 }
3641 else {
3642 callHook(afterHook, [el]);
3643 }
3644 if (hooks.delayedLeave) {
3645 hooks.delayedLeave();
3646 }
3647 el._enterCb = undefined;
3648 });
3649 if (hook) {
3650 hook(el, done);
3651 if (hook.length <= 1) {
3652 done();
3653 }
3654 }
3655 else {
3656 done();
3657 }
3658 },
3659 leave(el, remove) {
3660 const key = String(vnode.key);
3661 if (el._enterCb) {
3662 el._enterCb(true /* cancelled */);
3663 }
3664 if (state.isUnmounting) {
3665 return remove();
3666 }
3667 callHook(onBeforeLeave, [el]);
3668 let called = false;
3669 const done = (el._leaveCb = (cancelled) => {
3670 if (called)
3671 return;
3672 called = true;
3673 remove();
3674 if (cancelled) {
3675 callHook(onLeaveCancelled, [el]);
3676 }
3677 else {
3678 callHook(onAfterLeave, [el]);
3679 }
3680 el._leaveCb = undefined;
3681 if (leavingVNodesCache[key] === vnode) {
3682 delete leavingVNodesCache[key];
3683 }
3684 });
3685 leavingVNodesCache[key] = vnode;
3686 if (onLeave) {
3687 onLeave(el, done);
3688 if (onLeave.length <= 1) {
3689 done();
3690 }
3691 }
3692 else {
3693 done();
3694 }
3695 },
3696 clone(vnode) {
3697 return resolveTransitionHooks(vnode, props, state, instance);
3698 }
3699 };
3700 return hooks;
3701}
3702// the placeholder really only handles one special case: KeepAlive
3703// in the case of a KeepAlive in a leave phase we need to return a KeepAlive
3704// placeholder with empty content to avoid the KeepAlive instance from being
3705// unmounted.
3706function emptyPlaceholder(vnode) {
3707 if (isKeepAlive(vnode)) {
3708 vnode = cloneVNode(vnode);
3709 vnode.children = null;
3710 return vnode;
3711 }
3712}
3713function getKeepAliveChild(vnode) {
3714 return isKeepAlive(vnode)
3715 ? vnode.children
3716 ? vnode.children[0]
3717 : undefined
3718 : vnode;
3719}
3720function setTransitionHooks(vnode, hooks) {
3721 if (vnode.shapeFlag & 6 /* COMPONENT */ && vnode.component) {
3722 setTransitionHooks(vnode.component.subTree, hooks);
3723 }
3724 else if (vnode.shapeFlag & 128 /* SUSPENSE */) {
3725 vnode.ssContent.transition = hooks.clone(vnode.ssContent);
3726 vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
3727 }
3728 else {
3729 vnode.transition = hooks;
3730 }
3731}
3732function getTransitionRawChildren(children, keepComment = false, parentKey) {
3733 let ret = [];
3734 let keyedFragmentCount = 0;
3735 for (let i = 0; i < children.length; i++) {
3736 let child = children[i];
3737 // #5360 inherit parent key in case of <template v-for>
3738 const key = parentKey == null
3739 ? child.key
3740 : String(parentKey) + String(child.key != null ? child.key : i);
3741 // handle fragment children case, e.g. v-for
3742 if (child.type === Fragment) {
3743 if (child.patchFlag & 128 /* KEYED_FRAGMENT */)
3744 keyedFragmentCount++;
3745 ret = ret.concat(getTransitionRawChildren(child.children, keepComment, key));
3746 }
3747 // comment placeholders should be skipped, e.g. v-if
3748 else if (keepComment || child.type !== Comment) {
3749 ret.push(key != null ? cloneVNode(child, { key }) : child);
3750 }
3751 }
3752 // #1126 if a transition children list contains multiple sub fragments, these
3753 // fragments will be merged into a flat children array. Since each v-for
3754 // fragment may contain different static bindings inside, we need to de-op
3755 // these children to force full diffs to ensure correct behavior.
3756 if (keyedFragmentCount > 1) {
3757 for (let i = 0; i < ret.length; i++) {
3758 ret[i].patchFlag = -2 /* BAIL */;
3759 }
3760 }
3761 return ret;
3762}
3763
3764// implementation, close to no-op
3765function defineComponent(options) {
3766 return isFunction(options) ? { setup: options, name: options.name } : options;
3767}
3768
3769const isAsyncWrapper = (i) => !!i.type.__asyncLoader;
3770function defineAsyncComponent(source) {
3771 if (isFunction(source)) {
3772 source = { loader: source };
3773 }
3774 const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out
3775 suspensible = true, onError: userOnError } = source;
3776 let pendingRequest = null;
3777 let resolvedComp;
3778 let retries = 0;
3779 const retry = () => {
3780 retries++;
3781 pendingRequest = null;
3782 return load();
3783 };
3784 const load = () => {
3785 let thisRequest;
3786 return (pendingRequest ||
3787 (thisRequest = pendingRequest =
3788 loader()
3789 .catch(err => {
3790 err = err instanceof Error ? err : new Error(String(err));
3791 if (userOnError) {
3792 return new Promise((resolve, reject) => {
3793 const userRetry = () => resolve(retry());
3794 const userFail = () => reject(err);
3795 userOnError(err, userRetry, userFail, retries + 1);
3796 });
3797 }
3798 else {
3799 throw err;
3800 }
3801 })
3802 .then((comp) => {
3803 if (thisRequest !== pendingRequest && pendingRequest) {
3804 return pendingRequest;
3805 }
3806 if (!comp) {
3807 warn$1(`Async component loader resolved to undefined. ` +
3808 `If you are using retry(), make sure to return its return value.`);
3809 }
3810 // interop module default
3811 if (comp &&
3812 (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
3813 comp = comp.default;
3814 }
3815 if (comp && !isObject(comp) && !isFunction(comp)) {
3816 throw new Error(`Invalid async component load result: ${comp}`);
3817 }
3818 resolvedComp = comp;
3819 return comp;
3820 })));
3821 };
3822 return defineComponent({
3823 name: 'AsyncComponentWrapper',
3824 __asyncLoader: load,
3825 get __asyncResolved() {
3826 return resolvedComp;
3827 },
3828 setup() {
3829 const instance = currentInstance;
3830 // already resolved
3831 if (resolvedComp) {
3832 return () => createInnerComp(resolvedComp, instance);
3833 }
3834 const onError = (err) => {
3835 pendingRequest = null;
3836 handleError(err, instance, 13 /* ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
3837 };
3838 // suspense-controlled or SSR.
3839 if ((suspensible && instance.suspense) ||
3840 (false )) {
3841 return load()
3842 .then(comp => {
3843 return () => createInnerComp(comp, instance);
3844 })
3845 .catch(err => {
3846 onError(err);
3847 return () => errorComponent
3848 ? createVNode(errorComponent, {
3849 error: err
3850 })
3851 : null;
3852 });
3853 }
3854 const loaded = ref(false);
3855 const error = ref();
3856 const delayed = ref(!!delay);
3857 if (delay) {
3858 setTimeout(() => {
3859 delayed.value = false;
3860 }, delay);
3861 }
3862 if (timeout != null) {
3863 setTimeout(() => {
3864 if (!loaded.value && !error.value) {
3865 const err = new Error(`Async component timed out after ${timeout}ms.`);
3866 onError(err);
3867 error.value = err;
3868 }
3869 }, timeout);
3870 }
3871 load()
3872 .then(() => {
3873 loaded.value = true;
3874 if (instance.parent && isKeepAlive(instance.parent.vnode)) {
3875 // parent is keep-alive, force update so the loaded component's
3876 // name is taken into account
3877 queueJob(instance.parent.update);
3878 }
3879 })
3880 .catch(err => {
3881 onError(err);
3882 error.value = err;
3883 });
3884 return () => {
3885 if (loaded.value && resolvedComp) {
3886 return createInnerComp(resolvedComp, instance);
3887 }
3888 else if (error.value && errorComponent) {
3889 return createVNode(errorComponent, {
3890 error: error.value
3891 });
3892 }
3893 else if (loadingComponent && !delayed.value) {
3894 return createVNode(loadingComponent);
3895 }
3896 };
3897 }
3898 });
3899}
3900function createInnerComp(comp, { vnode: { ref, props, children } }) {
3901 const vnode = createVNode(comp, props, children);
3902 // ensure inner component inherits the async wrapper's ref owner
3903 vnode.ref = ref;
3904 return vnode;
3905}
3906
3907const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
3908const KeepAliveImpl = {
3909 name: `KeepAlive`,
3910 // Marker for special handling inside the renderer. We are not using a ===
3911 // check directly on KeepAlive in the renderer, because importing it directly
3912 // would prevent it from being tree-shaken.
3913 __isKeepAlive: true,
3914 props: {
3915 include: [String, RegExp, Array],
3916 exclude: [String, RegExp, Array],
3917 max: [String, Number]
3918 },
3919 setup(props, { slots }) {
3920 const instance = getCurrentInstance();
3921 // KeepAlive communicates with the instantiated renderer via the
3922 // ctx where the renderer passes in its internals,
3923 // and the KeepAlive instance exposes activate/deactivate implementations.
3924 // The whole point of this is to avoid importing KeepAlive directly in the
3925 // renderer to facilitate tree-shaking.
3926 const sharedContext = instance.ctx;
3927 // if the internal renderer is not registered, it indicates that this is server-side rendering,
3928 // for KeepAlive, we just need to render its children
3929 if (!sharedContext.renderer) {
3930 return slots.default;
3931 }
3932 const cache = new Map();
3933 const keys = new Set();
3934 let current = null;
3935 {
3936 instance.__v_cache = cache;
3937 }
3938 const parentSuspense = instance.suspense;
3939 const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
3940 const storageContainer = createElement('div');
3941 sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
3942 const instance = vnode.component;
3943 move(vnode, container, anchor, 0 /* ENTER */, parentSuspense);
3944 // in case props have changed
3945 patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, vnode.slotScopeIds, optimized);
3946 queuePostRenderEffect(() => {
3947 instance.isDeactivated = false;
3948 if (instance.a) {
3949 invokeArrayFns(instance.a);
3950 }
3951 const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
3952 if (vnodeHook) {
3953 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3954 }
3955 }, parentSuspense);
3956 {
3957 // Update components tree
3958 devtoolsComponentAdded(instance);
3959 }
3960 };
3961 sharedContext.deactivate = (vnode) => {
3962 const instance = vnode.component;
3963 move(vnode, storageContainer, null, 1 /* LEAVE */, parentSuspense);
3964 queuePostRenderEffect(() => {
3965 if (instance.da) {
3966 invokeArrayFns(instance.da);
3967 }
3968 const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
3969 if (vnodeHook) {
3970 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3971 }
3972 instance.isDeactivated = true;
3973 }, parentSuspense);
3974 {
3975 // Update components tree
3976 devtoolsComponentAdded(instance);
3977 }
3978 };
3979 function unmount(vnode) {
3980 // reset the shapeFlag so it can be properly unmounted
3981 resetShapeFlag(vnode);
3982 _unmount(vnode, instance, parentSuspense, true);
3983 }
3984 function pruneCache(filter) {
3985 cache.forEach((vnode, key) => {
3986 const name = getComponentName(vnode.type);
3987 if (name && (!filter || !filter(name))) {
3988 pruneCacheEntry(key);
3989 }
3990 });
3991 }
3992 function pruneCacheEntry(key) {
3993 const cached = cache.get(key);
3994 if (!current || cached.type !== current.type) {
3995 unmount(cached);
3996 }
3997 else if (current) {
3998 // current active instance should no longer be kept-alive.
3999 // we can't unmount it now but it might be later, so reset its flag now.
4000 resetShapeFlag(current);
4001 }
4002 cache.delete(key);
4003 keys.delete(key);
4004 }
4005 // prune cache on include/exclude prop change
4006 watch(() => [props.include, props.exclude], ([include, exclude]) => {
4007 include && pruneCache(name => matches(include, name));
4008 exclude && pruneCache(name => !matches(exclude, name));
4009 },
4010 // prune post-render after `current` has been updated
4011 { flush: 'post', deep: true });
4012 // cache sub tree after render
4013 let pendingCacheKey = null;
4014 const cacheSubtree = () => {
4015 // fix #1621, the pendingCacheKey could be 0
4016 if (pendingCacheKey != null) {
4017 cache.set(pendingCacheKey, getInnerChild(instance.subTree));
4018 }
4019 };
4020 onMounted(cacheSubtree);
4021 onUpdated(cacheSubtree);
4022 onBeforeUnmount(() => {
4023 cache.forEach(cached => {
4024 const { subTree, suspense } = instance;
4025 const vnode = getInnerChild(subTree);
4026 if (cached.type === vnode.type) {
4027 // current instance will be unmounted as part of keep-alive's unmount
4028 resetShapeFlag(vnode);
4029 // but invoke its deactivated hook here
4030 const da = vnode.component.da;
4031 da && queuePostRenderEffect(da, suspense);
4032 return;
4033 }
4034 unmount(cached);
4035 });
4036 });
4037 return () => {
4038 pendingCacheKey = null;
4039 if (!slots.default) {
4040 return null;
4041 }
4042 const children = slots.default();
4043 const rawVNode = children[0];
4044 if (children.length > 1) {
4045 {
4046 warn$1(`KeepAlive should contain exactly one component child.`);
4047 }
4048 current = null;
4049 return children;
4050 }
4051 else if (!isVNode(rawVNode) ||
4052 (!(rawVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) &&
4053 !(rawVNode.shapeFlag & 128 /* SUSPENSE */))) {
4054 current = null;
4055 return rawVNode;
4056 }
4057 let vnode = getInnerChild(rawVNode);
4058 const comp = vnode.type;
4059 // for async components, name check should be based in its loaded
4060 // inner component if available
4061 const name = getComponentName(isAsyncWrapper(vnode)
4062 ? vnode.type.__asyncResolved || {}
4063 : comp);
4064 const { include, exclude, max } = props;
4065 if ((include && (!name || !matches(include, name))) ||
4066 (exclude && name && matches(exclude, name))) {
4067 current = vnode;
4068 return rawVNode;
4069 }
4070 const key = vnode.key == null ? comp : vnode.key;
4071 const cachedVNode = cache.get(key);
4072 // clone vnode if it's reused because we are going to mutate it
4073 if (vnode.el) {
4074 vnode = cloneVNode(vnode);
4075 if (rawVNode.shapeFlag & 128 /* SUSPENSE */) {
4076 rawVNode.ssContent = vnode;
4077 }
4078 }
4079 // #1513 it's possible for the returned vnode to be cloned due to attr
4080 // fallthrough or scopeId, so the vnode here may not be the final vnode
4081 // that is mounted. Instead of caching it directly, we store the pending
4082 // key and cache `instance.subTree` (the normalized vnode) in
4083 // beforeMount/beforeUpdate hooks.
4084 pendingCacheKey = key;
4085 if (cachedVNode) {
4086 // copy over mounted state
4087 vnode.el = cachedVNode.el;
4088 vnode.component = cachedVNode.component;
4089 if (vnode.transition) {
4090 // recursively update transition hooks on subTree
4091 setTransitionHooks(vnode, vnode.transition);
4092 }
4093 // avoid vnode being mounted as fresh
4094 vnode.shapeFlag |= 512 /* COMPONENT_KEPT_ALIVE */;
4095 // make this key the freshest
4096 keys.delete(key);
4097 keys.add(key);
4098 }
4099 else {
4100 keys.add(key);
4101 // prune oldest entry
4102 if (max && keys.size > parseInt(max, 10)) {
4103 pruneCacheEntry(keys.values().next().value);
4104 }
4105 }
4106 // avoid vnode being unmounted
4107 vnode.shapeFlag |= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
4108 current = vnode;
4109 return rawVNode;
4110 };
4111 }
4112};
4113// export the public type for h/tsx inference
4114// also to avoid inline import() in generated d.ts files
4115const KeepAlive = KeepAliveImpl;
4116function matches(pattern, name) {
4117 if (isArray(pattern)) {
4118 return pattern.some((p) => matches(p, name));
4119 }
4120 else if (isString(pattern)) {
4121 return pattern.split(',').includes(name);
4122 }
4123 else if (pattern.test) {
4124 return pattern.test(name);
4125 }
4126 /* istanbul ignore next */
4127 return false;
4128}
4129function onActivated(hook, target) {
4130 registerKeepAliveHook(hook, "a" /* ACTIVATED */, target);
4131}
4132function onDeactivated(hook, target) {
4133 registerKeepAliveHook(hook, "da" /* DEACTIVATED */, target);
4134}
4135function registerKeepAliveHook(hook, type, target = currentInstance) {
4136 // cache the deactivate branch check wrapper for injected hooks so the same
4137 // hook can be properly deduped by the scheduler. "__wdc" stands for "with
4138 // deactivation check".
4139 const wrappedHook = hook.__wdc ||
4140 (hook.__wdc = () => {
4141 // only fire the hook if the target instance is NOT in a deactivated branch.
4142 let current = target;
4143 while (current) {
4144 if (current.isDeactivated) {
4145 return;
4146 }
4147 current = current.parent;
4148 }
4149 return hook();
4150 });
4151 injectHook(type, wrappedHook, target);
4152 // In addition to registering it on the target instance, we walk up the parent
4153 // chain and register it on all ancestor instances that are keep-alive roots.
4154 // This avoids the need to walk the entire component tree when invoking these
4155 // hooks, and more importantly, avoids the need to track child components in
4156 // arrays.
4157 if (target) {
4158 let current = target.parent;
4159 while (current && current.parent) {
4160 if (isKeepAlive(current.parent.vnode)) {
4161 injectToKeepAliveRoot(wrappedHook, type, target, current);
4162 }
4163 current = current.parent;
4164 }
4165 }
4166}
4167function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
4168 // injectHook wraps the original for error handling, so make sure to remove
4169 // the wrapped version.
4170 const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
4171 onUnmounted(() => {
4172 remove(keepAliveRoot[type], injected);
4173 }, target);
4174}
4175function resetShapeFlag(vnode) {
4176 let shapeFlag = vnode.shapeFlag;
4177 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
4178 shapeFlag -= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
4179 }
4180 if (shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
4181 shapeFlag -= 512 /* COMPONENT_KEPT_ALIVE */;
4182 }
4183 vnode.shapeFlag = shapeFlag;
4184}
4185function getInnerChild(vnode) {
4186 return vnode.shapeFlag & 128 /* SUSPENSE */ ? vnode.ssContent : vnode;
4187}
4188
4189function injectHook(type, hook, target = currentInstance, prepend = false) {
4190 if (target) {
4191 const hooks = target[type] || (target[type] = []);
4192 // cache the error handling wrapper for injected hooks so the same hook
4193 // can be properly deduped by the scheduler. "__weh" stands for "with error
4194 // handling".
4195 const wrappedHook = hook.__weh ||
4196 (hook.__weh = (...args) => {
4197 if (target.isUnmounted) {
4198 return;
4199 }
4200 // disable tracking inside all lifecycle hooks
4201 // since they can potentially be called inside effects.
4202 pauseTracking();
4203 // Set currentInstance during hook invocation.
4204 // This assumes the hook does not synchronously trigger other hooks, which
4205 // can only be false when the user does something really funky.
4206 setCurrentInstance(target);
4207 const res = callWithAsyncErrorHandling(hook, target, type, args);
4208 unsetCurrentInstance();
4209 resetTracking();
4210 return res;
4211 });
4212 if (prepend) {
4213 hooks.unshift(wrappedHook);
4214 }
4215 else {
4216 hooks.push(wrappedHook);
4217 }
4218 return wrappedHook;
4219 }
4220 else {
4221 const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
4222 warn$1(`${apiName} is called when there is no active component instance to be ` +
4223 `associated with. ` +
4224 `Lifecycle injection APIs can only be used during execution of setup().` +
4225 (` If you are using async setup(), make sure to register lifecycle ` +
4226 `hooks before the first await statement.`
4227 ));
4228 }
4229}
4230const createHook = (lifecycle) => (hook, target = currentInstance) =>
4231// post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
4232(!isInSSRComponentSetup || lifecycle === "sp" /* SERVER_PREFETCH */) &&
4233 injectHook(lifecycle, hook, target);
4234const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */);
4235const onMounted = createHook("m" /* MOUNTED */);
4236const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */);
4237const onUpdated = createHook("u" /* UPDATED */);
4238const onBeforeUnmount = createHook("bum" /* BEFORE_UNMOUNT */);
4239const onUnmounted = createHook("um" /* UNMOUNTED */);
4240const onServerPrefetch = createHook("sp" /* SERVER_PREFETCH */);
4241const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */);
4242const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */);
4243function onErrorCaptured(hook, target = currentInstance) {
4244 injectHook("ec" /* ERROR_CAPTURED */, hook, target);
4245}
4246
4247function createDuplicateChecker() {
4248 const cache = Object.create(null);
4249 return (type, key) => {
4250 if (cache[key]) {
4251 warn$1(`${type} property "${key}" is already defined in ${cache[key]}.`);
4252 }
4253 else {
4254 cache[key] = type;
4255 }
4256 };
4257}
4258let shouldCacheAccess = true;
4259function applyOptions(instance) {
4260 const options = resolveMergedOptions(instance);
4261 const publicThis = instance.proxy;
4262 const ctx = instance.ctx;
4263 // do not cache property access on public proxy during state initialization
4264 shouldCacheAccess = false;
4265 // call beforeCreate first before accessing other options since
4266 // the hook may mutate resolved options (#2791)
4267 if (options.beforeCreate) {
4268 callHook(options.beforeCreate, instance, "bc" /* BEFORE_CREATE */);
4269 }
4270 const {
4271 // state
4272 data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
4273 // lifecycle
4274 created, beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured, serverPrefetch,
4275 // public API
4276 expose, inheritAttrs,
4277 // assets
4278 components, directives, filters } = options;
4279 const checkDuplicateProperties = createDuplicateChecker() ;
4280 {
4281 const [propsOptions] = instance.propsOptions;
4282 if (propsOptions) {
4283 for (const key in propsOptions) {
4284 checkDuplicateProperties("Props" /* PROPS */, key);
4285 }
4286 }
4287 }
4288 // options initialization order (to be consistent with Vue 2):
4289 // - props (already done outside of this function)
4290 // - inject
4291 // - methods
4292 // - data (deferred since it relies on `this` access)
4293 // - computed
4294 // - watch (deferred since it relies on `this` access)
4295 if (injectOptions) {
4296 resolveInjections(injectOptions, ctx, checkDuplicateProperties, instance.appContext.config.unwrapInjectedRef);
4297 }
4298 if (methods) {
4299 for (const key in methods) {
4300 const methodHandler = methods[key];
4301 if (isFunction(methodHandler)) {
4302 // In dev mode, we use the `createRenderContext` function to define
4303 // methods to the proxy target, and those are read-only but
4304 // reconfigurable, so it needs to be redefined here
4305 {
4306 Object.defineProperty(ctx, key, {
4307 value: methodHandler.bind(publicThis),
4308 configurable: true,
4309 enumerable: true,
4310 writable: true
4311 });
4312 }
4313 {
4314 checkDuplicateProperties("Methods" /* METHODS */, key);
4315 }
4316 }
4317 else {
4318 warn$1(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
4319 `Did you reference the function correctly?`);
4320 }
4321 }
4322 }
4323 if (dataOptions) {
4324 if (!isFunction(dataOptions)) {
4325 warn$1(`The data option must be a function. ` +
4326 `Plain object usage is no longer supported.`);
4327 }
4328 const data = dataOptions.call(publicThis, publicThis);
4329 if (isPromise(data)) {
4330 warn$1(`data() returned a Promise - note data() cannot be async; If you ` +
4331 `intend to perform data fetching before component renders, use ` +
4332 `async setup() + <Suspense>.`);
4333 }
4334 if (!isObject(data)) {
4335 warn$1(`data() should return an object.`);
4336 }
4337 else {
4338 instance.data = reactive(data);
4339 {
4340 for (const key in data) {
4341 checkDuplicateProperties("Data" /* DATA */, key);
4342 // expose data on ctx during dev
4343 if (key[0] !== '$' && key[0] !== '_') {
4344 Object.defineProperty(ctx, key, {
4345 configurable: true,
4346 enumerable: true,
4347 get: () => data[key],
4348 set: NOOP
4349 });
4350 }
4351 }
4352 }
4353 }
4354 }
4355 // state initialization complete at this point - start caching access
4356 shouldCacheAccess = true;
4357 if (computedOptions) {
4358 for (const key in computedOptions) {
4359 const opt = computedOptions[key];
4360 const get = isFunction(opt)
4361 ? opt.bind(publicThis, publicThis)
4362 : isFunction(opt.get)
4363 ? opt.get.bind(publicThis, publicThis)
4364 : NOOP;
4365 if (get === NOOP) {
4366 warn$1(`Computed property "${key}" has no getter.`);
4367 }
4368 const set = !isFunction(opt) && isFunction(opt.set)
4369 ? opt.set.bind(publicThis)
4370 : () => {
4371 warn$1(`Write operation failed: computed property "${key}" is readonly.`);
4372 }
4373 ;
4374 const c = computed$1({
4375 get,
4376 set
4377 });
4378 Object.defineProperty(ctx, key, {
4379 enumerable: true,
4380 configurable: true,
4381 get: () => c.value,
4382 set: v => (c.value = v)
4383 });
4384 {
4385 checkDuplicateProperties("Computed" /* COMPUTED */, key);
4386 }
4387 }
4388 }
4389 if (watchOptions) {
4390 for (const key in watchOptions) {
4391 createWatcher(watchOptions[key], ctx, publicThis, key);
4392 }
4393 }
4394 if (provideOptions) {
4395 const provides = isFunction(provideOptions)
4396 ? provideOptions.call(publicThis)
4397 : provideOptions;
4398 Reflect.ownKeys(provides).forEach(key => {
4399 provide(key, provides[key]);
4400 });
4401 }
4402 if (created) {
4403 callHook(created, instance, "c" /* CREATED */);
4404 }
4405 function registerLifecycleHook(register, hook) {
4406 if (isArray(hook)) {
4407 hook.forEach(_hook => register(_hook.bind(publicThis)));
4408 }
4409 else if (hook) {
4410 register(hook.bind(publicThis));
4411 }
4412 }
4413 registerLifecycleHook(onBeforeMount, beforeMount);
4414 registerLifecycleHook(onMounted, mounted);
4415 registerLifecycleHook(onBeforeUpdate, beforeUpdate);
4416 registerLifecycleHook(onUpdated, updated);
4417 registerLifecycleHook(onActivated, activated);
4418 registerLifecycleHook(onDeactivated, deactivated);
4419 registerLifecycleHook(onErrorCaptured, errorCaptured);
4420 registerLifecycleHook(onRenderTracked, renderTracked);
4421 registerLifecycleHook(onRenderTriggered, renderTriggered);
4422 registerLifecycleHook(onBeforeUnmount, beforeUnmount);
4423 registerLifecycleHook(onUnmounted, unmounted);
4424 registerLifecycleHook(onServerPrefetch, serverPrefetch);
4425 if (isArray(expose)) {
4426 if (expose.length) {
4427 const exposed = instance.exposed || (instance.exposed = {});
4428 expose.forEach(key => {
4429 Object.defineProperty(exposed, key, {
4430 get: () => publicThis[key],
4431 set: val => (publicThis[key] = val)
4432 });
4433 });
4434 }
4435 else if (!instance.exposed) {
4436 instance.exposed = {};
4437 }
4438 }
4439 // options that are handled when creating the instance but also need to be
4440 // applied from mixins
4441 if (render && instance.render === NOOP) {
4442 instance.render = render;
4443 }
4444 if (inheritAttrs != null) {
4445 instance.inheritAttrs = inheritAttrs;
4446 }
4447 // asset options.
4448 if (components)
4449 instance.components = components;
4450 if (directives)
4451 instance.directives = directives;
4452}
4453function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP, unwrapRef = false) {
4454 if (isArray(injectOptions)) {
4455 injectOptions = normalizeInject(injectOptions);
4456 }
4457 for (const key in injectOptions) {
4458 const opt = injectOptions[key];
4459 let injected;
4460 if (isObject(opt)) {
4461 if ('default' in opt) {
4462 injected = inject(opt.from || key, opt.default, true /* treat default function as factory */);
4463 }
4464 else {
4465 injected = inject(opt.from || key);
4466 }
4467 }
4468 else {
4469 injected = inject(opt);
4470 }
4471 if (isRef(injected)) {
4472 // TODO remove the check in 3.3
4473 if (unwrapRef) {
4474 Object.defineProperty(ctx, key, {
4475 enumerable: true,
4476 configurable: true,
4477 get: () => injected.value,
4478 set: v => (injected.value = v)
4479 });
4480 }
4481 else {
4482 {
4483 warn$1(`injected property "${key}" is a ref and will be auto-unwrapped ` +
4484 `and no longer needs \`.value\` in the next minor release. ` +
4485 `To opt-in to the new behavior now, ` +
4486 `set \`app.config.unwrapInjectedRef = true\` (this config is ` +
4487 `temporary and will not be needed in the future.)`);
4488 }
4489 ctx[key] = injected;
4490 }
4491 }
4492 else {
4493 ctx[key] = injected;
4494 }
4495 {
4496 checkDuplicateProperties("Inject" /* INJECT */, key);
4497 }
4498 }
4499}
4500function callHook(hook, instance, type) {
4501 callWithAsyncErrorHandling(isArray(hook)
4502 ? hook.map(h => h.bind(instance.proxy))
4503 : hook.bind(instance.proxy), instance, type);
4504}
4505function createWatcher(raw, ctx, publicThis, key) {
4506 const getter = key.includes('.')
4507 ? createPathGetter(publicThis, key)
4508 : () => publicThis[key];
4509 if (isString(raw)) {
4510 const handler = ctx[raw];
4511 if (isFunction(handler)) {
4512 watch(getter, handler);
4513 }
4514 else {
4515 warn$1(`Invalid watch handler specified by key "${raw}"`, handler);
4516 }
4517 }
4518 else if (isFunction(raw)) {
4519 watch(getter, raw.bind(publicThis));
4520 }
4521 else if (isObject(raw)) {
4522 if (isArray(raw)) {
4523 raw.forEach(r => createWatcher(r, ctx, publicThis, key));
4524 }
4525 else {
4526 const handler = isFunction(raw.handler)
4527 ? raw.handler.bind(publicThis)
4528 : ctx[raw.handler];
4529 if (isFunction(handler)) {
4530 watch(getter, handler, raw);
4531 }
4532 else {
4533 warn$1(`Invalid watch handler specified by key "${raw.handler}"`, handler);
4534 }
4535 }
4536 }
4537 else {
4538 warn$1(`Invalid watch option: "${key}"`, raw);
4539 }
4540}
4541/**
4542 * Resolve merged options and cache it on the component.
4543 * This is done only once per-component since the merging does not involve
4544 * instances.
4545 */
4546function resolveMergedOptions(instance) {
4547 const base = instance.type;
4548 const { mixins, extends: extendsOptions } = base;
4549 const { mixins: globalMixins, optionsCache: cache, config: { optionMergeStrategies } } = instance.appContext;
4550 const cached = cache.get(base);
4551 let resolved;
4552 if (cached) {
4553 resolved = cached;
4554 }
4555 else if (!globalMixins.length && !mixins && !extendsOptions) {
4556 {
4557 resolved = base;
4558 }
4559 }
4560 else {
4561 resolved = {};
4562 if (globalMixins.length) {
4563 globalMixins.forEach(m => mergeOptions(resolved, m, optionMergeStrategies, true));
4564 }
4565 mergeOptions(resolved, base, optionMergeStrategies);
4566 }
4567 cache.set(base, resolved);
4568 return resolved;
4569}
4570function mergeOptions(to, from, strats, asMixin = false) {
4571 const { mixins, extends: extendsOptions } = from;
4572 if (extendsOptions) {
4573 mergeOptions(to, extendsOptions, strats, true);
4574 }
4575 if (mixins) {
4576 mixins.forEach((m) => mergeOptions(to, m, strats, true));
4577 }
4578 for (const key in from) {
4579 if (asMixin && key === 'expose') {
4580 warn$1(`"expose" option is ignored when declared in mixins or extends. ` +
4581 `It should only be declared in the base component itself.`);
4582 }
4583 else {
4584 const strat = internalOptionMergeStrats[key] || (strats && strats[key]);
4585 to[key] = strat ? strat(to[key], from[key]) : from[key];
4586 }
4587 }
4588 return to;
4589}
4590const internalOptionMergeStrats = {
4591 data: mergeDataFn,
4592 props: mergeObjectOptions,
4593 emits: mergeObjectOptions,
4594 // objects
4595 methods: mergeObjectOptions,
4596 computed: mergeObjectOptions,
4597 // lifecycle
4598 beforeCreate: mergeAsArray,
4599 created: mergeAsArray,
4600 beforeMount: mergeAsArray,
4601 mounted: mergeAsArray,
4602 beforeUpdate: mergeAsArray,
4603 updated: mergeAsArray,
4604 beforeDestroy: mergeAsArray,
4605 beforeUnmount: mergeAsArray,
4606 destroyed: mergeAsArray,
4607 unmounted: mergeAsArray,
4608 activated: mergeAsArray,
4609 deactivated: mergeAsArray,
4610 errorCaptured: mergeAsArray,
4611 serverPrefetch: mergeAsArray,
4612 // assets
4613 components: mergeObjectOptions,
4614 directives: mergeObjectOptions,
4615 // watch
4616 watch: mergeWatchOptions,
4617 // provide / inject
4618 provide: mergeDataFn,
4619 inject: mergeInject
4620};
4621function mergeDataFn(to, from) {
4622 if (!from) {
4623 return to;
4624 }
4625 if (!to) {
4626 return from;
4627 }
4628 return function mergedDataFn() {
4629 return (extend)(isFunction(to) ? to.call(this, this) : to, isFunction(from) ? from.call(this, this) : from);
4630 };
4631}
4632function mergeInject(to, from) {
4633 return mergeObjectOptions(normalizeInject(to), normalizeInject(from));
4634}
4635function normalizeInject(raw) {
4636 if (isArray(raw)) {
4637 const res = {};
4638 for (let i = 0; i < raw.length; i++) {
4639 res[raw[i]] = raw[i];
4640 }
4641 return res;
4642 }
4643 return raw;
4644}
4645function mergeAsArray(to, from) {
4646 return to ? [...new Set([].concat(to, from))] : from;
4647}
4648function mergeObjectOptions(to, from) {
4649 return to ? extend(extend(Object.create(null), to), from) : from;
4650}
4651function mergeWatchOptions(to, from) {
4652 if (!to)
4653 return from;
4654 if (!from)
4655 return to;
4656 const merged = extend(Object.create(null), to);
4657 for (const key in from) {
4658 merged[key] = mergeAsArray(to[key], from[key]);
4659 }
4660 return merged;
4661}
4662
4663function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
4664isSSR = false) {
4665 const props = {};
4666 const attrs = {};
4667 def(attrs, InternalObjectKey, 1);
4668 instance.propsDefaults = Object.create(null);
4669 setFullProps(instance, rawProps, props, attrs);
4670 // ensure all declared prop keys are present
4671 for (const key in instance.propsOptions[0]) {
4672 if (!(key in props)) {
4673 props[key] = undefined;
4674 }
4675 }
4676 // validation
4677 {
4678 validateProps(rawProps || {}, props, instance);
4679 }
4680 if (isStateful) {
4681 // stateful
4682 instance.props = isSSR ? props : shallowReactive(props);
4683 }
4684 else {
4685 if (!instance.type.props) {
4686 // functional w/ optional props, props === attrs
4687 instance.props = attrs;
4688 }
4689 else {
4690 // functional w/ declared props
4691 instance.props = props;
4692 }
4693 }
4694 instance.attrs = attrs;
4695}
4696function updateProps(instance, rawProps, rawPrevProps, optimized) {
4697 const { props, attrs, vnode: { patchFlag } } = instance;
4698 const rawCurrentProps = toRaw(props);
4699 const [options] = instance.propsOptions;
4700 let hasAttrsChanged = false;
4701 if (
4702 // always force full diff in dev
4703 // - #1942 if hmr is enabled with sfc component
4704 // - vite#872 non-sfc component used by sfc component
4705 !((instance.type.__hmrId ||
4706 (instance.parent && instance.parent.type.__hmrId))) &&
4707 (optimized || patchFlag > 0) &&
4708 !(patchFlag & 16 /* FULL_PROPS */)) {
4709 if (patchFlag & 8 /* PROPS */) {
4710 // Compiler-generated props & no keys change, just set the updated
4711 // the props.
4712 const propsToUpdate = instance.vnode.dynamicProps;
4713 for (let i = 0; i < propsToUpdate.length; i++) {
4714 let key = propsToUpdate[i];
4715 // skip if the prop key is a declared emit event listener
4716 if (isEmitListener(instance.emitsOptions, key)) {
4717 continue;
4718 }
4719 // PROPS flag guarantees rawProps to be non-null
4720 const value = rawProps[key];
4721 if (options) {
4722 // attr / props separation was done on init and will be consistent
4723 // in this code path, so just check if attrs have it.
4724 if (hasOwn(attrs, key)) {
4725 if (value !== attrs[key]) {
4726 attrs[key] = value;
4727 hasAttrsChanged = true;
4728 }
4729 }
4730 else {
4731 const camelizedKey = camelize(key);
4732 props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance, false /* isAbsent */);
4733 }
4734 }
4735 else {
4736 if (value !== attrs[key]) {
4737 attrs[key] = value;
4738 hasAttrsChanged = true;
4739 }
4740 }
4741 }
4742 }
4743 }
4744 else {
4745 // full props update.
4746 if (setFullProps(instance, rawProps, props, attrs)) {
4747 hasAttrsChanged = true;
4748 }
4749 // in case of dynamic props, check if we need to delete keys from
4750 // the props object
4751 let kebabKey;
4752 for (const key in rawCurrentProps) {
4753 if (!rawProps ||
4754 // for camelCase
4755 (!hasOwn(rawProps, key) &&
4756 // it's possible the original props was passed in as kebab-case
4757 // and converted to camelCase (#955)
4758 ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
4759 if (options) {
4760 if (rawPrevProps &&
4761 // for camelCase
4762 (rawPrevProps[key] !== undefined ||
4763 // for kebab-case
4764 rawPrevProps[kebabKey] !== undefined)) {
4765 props[key] = resolvePropValue(options, rawCurrentProps, key, undefined, instance, true /* isAbsent */);
4766 }
4767 }
4768 else {
4769 delete props[key];
4770 }
4771 }
4772 }
4773 // in the case of functional component w/o props declaration, props and
4774 // attrs point to the same object so it should already have been updated.
4775 if (attrs !== rawCurrentProps) {
4776 for (const key in attrs) {
4777 if (!rawProps ||
4778 (!hasOwn(rawProps, key) &&
4779 (!false ))) {
4780 delete attrs[key];
4781 hasAttrsChanged = true;
4782 }
4783 }
4784 }
4785 }
4786 // trigger updates for $attrs in case it's used in component slots
4787 if (hasAttrsChanged) {
4788 trigger(instance, "set" /* SET */, '$attrs');
4789 }
4790 {
4791 validateProps(rawProps || {}, props, instance);
4792 }
4793}
4794function setFullProps(instance, rawProps, props, attrs) {
4795 const [options, needCastKeys] = instance.propsOptions;
4796 let hasAttrsChanged = false;
4797 let rawCastValues;
4798 if (rawProps) {
4799 for (let key in rawProps) {
4800 // key, ref are reserved and never passed down
4801 if (isReservedProp(key)) {
4802 continue;
4803 }
4804 const value = rawProps[key];
4805 // prop option names are camelized during normalization, so to support
4806 // kebab -> camel conversion here we need to camelize the key.
4807 let camelKey;
4808 if (options && hasOwn(options, (camelKey = camelize(key)))) {
4809 if (!needCastKeys || !needCastKeys.includes(camelKey)) {
4810 props[camelKey] = value;
4811 }
4812 else {
4813 (rawCastValues || (rawCastValues = {}))[camelKey] = value;
4814 }
4815 }
4816 else if (!isEmitListener(instance.emitsOptions, key)) {
4817 if (!(key in attrs) || value !== attrs[key]) {
4818 attrs[key] = value;
4819 hasAttrsChanged = true;
4820 }
4821 }
4822 }
4823 }
4824 if (needCastKeys) {
4825 const rawCurrentProps = toRaw(props);
4826 const castValues = rawCastValues || EMPTY_OBJ;
4827 for (let i = 0; i < needCastKeys.length; i++) {
4828 const key = needCastKeys[i];
4829 props[key] = resolvePropValue(options, rawCurrentProps, key, castValues[key], instance, !hasOwn(castValues, key));
4830 }
4831 }
4832 return hasAttrsChanged;
4833}
4834function resolvePropValue(options, props, key, value, instance, isAbsent) {
4835 const opt = options[key];
4836 if (opt != null) {
4837 const hasDefault = hasOwn(opt, 'default');
4838 // default values
4839 if (hasDefault && value === undefined) {
4840 const defaultValue = opt.default;
4841 if (opt.type !== Function && isFunction(defaultValue)) {
4842 const { propsDefaults } = instance;
4843 if (key in propsDefaults) {
4844 value = propsDefaults[key];
4845 }
4846 else {
4847 setCurrentInstance(instance);
4848 value = propsDefaults[key] = defaultValue.call(null, props);
4849 unsetCurrentInstance();
4850 }
4851 }
4852 else {
4853 value = defaultValue;
4854 }
4855 }
4856 // boolean casting
4857 if (opt[0 /* shouldCast */]) {
4858 if (isAbsent && !hasDefault) {
4859 value = false;
4860 }
4861 else if (opt[1 /* shouldCastTrue */] &&
4862 (value === '' || value === hyphenate(key))) {
4863 value = true;
4864 }
4865 }
4866 }
4867 return value;
4868}
4869function normalizePropsOptions(comp, appContext, asMixin = false) {
4870 const cache = appContext.propsCache;
4871 const cached = cache.get(comp);
4872 if (cached) {
4873 return cached;
4874 }
4875 const raw = comp.props;
4876 const normalized = {};
4877 const needCastKeys = [];
4878 // apply mixin/extends props
4879 let hasExtends = false;
4880 if (!isFunction(comp)) {
4881 const extendProps = (raw) => {
4882 hasExtends = true;
4883 const [props, keys] = normalizePropsOptions(raw, appContext, true);
4884 extend(normalized, props);
4885 if (keys)
4886 needCastKeys.push(...keys);
4887 };
4888 if (!asMixin && appContext.mixins.length) {
4889 appContext.mixins.forEach(extendProps);
4890 }
4891 if (comp.extends) {
4892 extendProps(comp.extends);
4893 }
4894 if (comp.mixins) {
4895 comp.mixins.forEach(extendProps);
4896 }
4897 }
4898 if (!raw && !hasExtends) {
4899 cache.set(comp, EMPTY_ARR);
4900 return EMPTY_ARR;
4901 }
4902 if (isArray(raw)) {
4903 for (let i = 0; i < raw.length; i++) {
4904 if (!isString(raw[i])) {
4905 warn$1(`props must be strings when using array syntax.`, raw[i]);
4906 }
4907 const normalizedKey = camelize(raw[i]);
4908 if (validatePropName(normalizedKey)) {
4909 normalized[normalizedKey] = EMPTY_OBJ;
4910 }
4911 }
4912 }
4913 else if (raw) {
4914 if (!isObject(raw)) {
4915 warn$1(`invalid props options`, raw);
4916 }
4917 for (const key in raw) {
4918 const normalizedKey = camelize(key);
4919 if (validatePropName(normalizedKey)) {
4920 const opt = raw[key];
4921 const prop = (normalized[normalizedKey] =
4922 isArray(opt) || isFunction(opt) ? { type: opt } : opt);
4923 if (prop) {
4924 const booleanIndex = getTypeIndex(Boolean, prop.type);
4925 const stringIndex = getTypeIndex(String, prop.type);
4926 prop[0 /* shouldCast */] = booleanIndex > -1;
4927 prop[1 /* shouldCastTrue */] =
4928 stringIndex < 0 || booleanIndex < stringIndex;
4929 // if the prop needs boolean casting or default value
4930 if (booleanIndex > -1 || hasOwn(prop, 'default')) {
4931 needCastKeys.push(normalizedKey);
4932 }
4933 }
4934 }
4935 }
4936 }
4937 const res = [normalized, needCastKeys];
4938 cache.set(comp, res);
4939 return res;
4940}
4941function validatePropName(key) {
4942 if (key[0] !== '$') {
4943 return true;
4944 }
4945 else {
4946 warn$1(`Invalid prop name: "${key}" is a reserved property.`);
4947 }
4948 return false;
4949}
4950// use function string name to check type constructors
4951// so that it works across vms / iframes.
4952function getType(ctor) {
4953 const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
4954 return match ? match[1] : ctor === null ? 'null' : '';
4955}
4956function isSameType(a, b) {
4957 return getType(a) === getType(b);
4958}
4959function getTypeIndex(type, expectedTypes) {
4960 if (isArray(expectedTypes)) {
4961 return expectedTypes.findIndex(t => isSameType(t, type));
4962 }
4963 else if (isFunction(expectedTypes)) {
4964 return isSameType(expectedTypes, type) ? 0 : -1;
4965 }
4966 return -1;
4967}
4968/**
4969 * dev only
4970 */
4971function validateProps(rawProps, props, instance) {
4972 const resolvedValues = toRaw(props);
4973 const options = instance.propsOptions[0];
4974 for (const key in options) {
4975 let opt = options[key];
4976 if (opt == null)
4977 continue;
4978 validateProp(key, resolvedValues[key], opt, !hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key)));
4979 }
4980}
4981/**
4982 * dev only
4983 */
4984function validateProp(name, value, prop, isAbsent) {
4985 const { type, required, validator } = prop;
4986 // required!
4987 if (required && isAbsent) {
4988 warn$1('Missing required prop: "' + name + '"');
4989 return;
4990 }
4991 // missing but optional
4992 if (value == null && !prop.required) {
4993 return;
4994 }
4995 // type check
4996 if (type != null && type !== true) {
4997 let isValid = false;
4998 const types = isArray(type) ? type : [type];
4999 const expectedTypes = [];
5000 // value is valid as long as one of the specified types match
5001 for (let i = 0; i < types.length && !isValid; i++) {
5002 const { valid, expectedType } = assertType(value, types[i]);
5003 expectedTypes.push(expectedType || '');
5004 isValid = valid;
5005 }
5006 if (!isValid) {
5007 warn$1(getInvalidTypeMessage(name, value, expectedTypes));
5008 return;
5009 }
5010 }
5011 // custom validator
5012 if (validator && !validator(value)) {
5013 warn$1('Invalid prop: custom validator check failed for prop "' + name + '".');
5014 }
5015}
5016const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol,BigInt');
5017/**
5018 * dev only
5019 */
5020function assertType(value, type) {
5021 let valid;
5022 const expectedType = getType(type);
5023 if (isSimpleType(expectedType)) {
5024 const t = typeof value;
5025 valid = t === expectedType.toLowerCase();
5026 // for primitive wrapper objects
5027 if (!valid && t === 'object') {
5028 valid = value instanceof type;
5029 }
5030 }
5031 else if (expectedType === 'Object') {
5032 valid = isObject(value);
5033 }
5034 else if (expectedType === 'Array') {
5035 valid = isArray(value);
5036 }
5037 else if (expectedType === 'null') {
5038 valid = value === null;
5039 }
5040 else {
5041 valid = value instanceof type;
5042 }
5043 return {
5044 valid,
5045 expectedType
5046 };
5047}
5048/**
5049 * dev only
5050 */
5051function getInvalidTypeMessage(name, value, expectedTypes) {
5052 let message = `Invalid prop: type check failed for prop "${name}".` +
5053 ` Expected ${expectedTypes.map(capitalize).join(' | ')}`;
5054 const expectedType = expectedTypes[0];
5055 const receivedType = toRawType(value);
5056 const expectedValue = styleValue(value, expectedType);
5057 const receivedValue = styleValue(value, receivedType);
5058 // check if we need to specify expected value
5059 if (expectedTypes.length === 1 &&
5060 isExplicable(expectedType) &&
5061 !isBoolean(expectedType, receivedType)) {
5062 message += ` with value ${expectedValue}`;
5063 }
5064 message += `, got ${receivedType} `;
5065 // check if we need to specify received value
5066 if (isExplicable(receivedType)) {
5067 message += `with value ${receivedValue}.`;
5068 }
5069 return message;
5070}
5071/**
5072 * dev only
5073 */
5074function styleValue(value, type) {
5075 if (type === 'String') {
5076 return `"${value}"`;
5077 }
5078 else if (type === 'Number') {
5079 return `${Number(value)}`;
5080 }
5081 else {
5082 return `${value}`;
5083 }
5084}
5085/**
5086 * dev only
5087 */
5088function isExplicable(type) {
5089 const explicitTypes = ['string', 'number', 'boolean'];
5090 return explicitTypes.some(elem => type.toLowerCase() === elem);
5091}
5092/**
5093 * dev only
5094 */
5095function isBoolean(...args) {
5096 return args.some(elem => elem.toLowerCase() === 'boolean');
5097}
5098
5099const isInternalKey = (key) => key[0] === '_' || key === '$stable';
5100const normalizeSlotValue = (value) => isArray(value)
5101 ? value.map(normalizeVNode)
5102 : [normalizeVNode(value)];
5103const normalizeSlot = (key, rawSlot, ctx) => {
5104 const normalized = withCtx((...args) => {
5105 if (currentInstance) {
5106 warn$1(`Slot "${key}" invoked outside of the render function: ` +
5107 `this will not track dependencies used in the slot. ` +
5108 `Invoke the slot function inside the render function instead.`);
5109 }
5110 return normalizeSlotValue(rawSlot(...args));
5111 }, ctx);
5112 normalized._c = false;
5113 return normalized;
5114};
5115const normalizeObjectSlots = (rawSlots, slots, instance) => {
5116 const ctx = rawSlots._ctx;
5117 for (const key in rawSlots) {
5118 if (isInternalKey(key))
5119 continue;
5120 const value = rawSlots[key];
5121 if (isFunction(value)) {
5122 slots[key] = normalizeSlot(key, value, ctx);
5123 }
5124 else if (value != null) {
5125 {
5126 warn$1(`Non-function value encountered for slot "${key}". ` +
5127 `Prefer function slots for better performance.`);
5128 }
5129 const normalized = normalizeSlotValue(value);
5130 slots[key] = () => normalized;
5131 }
5132 }
5133};
5134const normalizeVNodeSlots = (instance, children) => {
5135 if (!isKeepAlive(instance.vnode) &&
5136 !(false )) {
5137 warn$1(`Non-function value encountered for default slot. ` +
5138 `Prefer function slots for better performance.`);
5139 }
5140 const normalized = normalizeSlotValue(children);
5141 instance.slots.default = () => normalized;
5142};
5143const initSlots = (instance, children) => {
5144 if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
5145 const type = children._;
5146 if (type) {
5147 // users can get the shallow readonly version of the slots object through `this.$slots`,
5148 // we should avoid the proxy object polluting the slots of the internal instance
5149 instance.slots = toRaw(children);
5150 // make compiler marker non-enumerable
5151 def(children, '_', type);
5152 }
5153 else {
5154 normalizeObjectSlots(children, (instance.slots = {}));
5155 }
5156 }
5157 else {
5158 instance.slots = {};
5159 if (children) {
5160 normalizeVNodeSlots(instance, children);
5161 }
5162 }
5163 def(instance.slots, InternalObjectKey, 1);
5164};
5165const updateSlots = (instance, children, optimized) => {
5166 const { vnode, slots } = instance;
5167 let needDeletionCheck = true;
5168 let deletionComparisonTarget = EMPTY_OBJ;
5169 if (vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
5170 const type = children._;
5171 if (type) {
5172 // compiled slots.
5173 if (isHmrUpdating) {
5174 // Parent was HMR updated so slot content may have changed.
5175 // force update slots and mark instance for hmr as well
5176 extend(slots, children);
5177 }
5178 else if (optimized && type === 1 /* STABLE */) {
5179 // compiled AND stable.
5180 // no need to update, and skip stale slots removal.
5181 needDeletionCheck = false;
5182 }
5183 else {
5184 // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
5185 // normalization.
5186 extend(slots, children);
5187 // #2893
5188 // when rendering the optimized slots by manually written render function,
5189 // we need to delete the `slots._` flag if necessary to make subsequent updates reliable,
5190 // i.e. let the `renderSlot` create the bailed Fragment
5191 if (!optimized && type === 1 /* STABLE */) {
5192 delete slots._;
5193 }
5194 }
5195 }
5196 else {
5197 needDeletionCheck = !children.$stable;
5198 normalizeObjectSlots(children, slots);
5199 }
5200 deletionComparisonTarget = children;
5201 }
5202 else if (children) {
5203 // non slot object children (direct value) passed to a component
5204 normalizeVNodeSlots(instance, children);
5205 deletionComparisonTarget = { default: 1 };
5206 }
5207 // delete stale slots
5208 if (needDeletionCheck) {
5209 for (const key in slots) {
5210 if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
5211 delete slots[key];
5212 }
5213 }
5214 }
5215};
5216
5217/**
5218Runtime helper for applying directives to a vnode. Example usage:
5219
5220const comp = resolveComponent('comp')
5221const foo = resolveDirective('foo')
5222const bar = resolveDirective('bar')
5223
5224return withDirectives(h(comp), [
5225 [foo, this.x],
5226 [bar, this.y]
5227])
5228*/
5229function validateDirectiveName(name) {
5230 if (isBuiltInDirective(name)) {
5231 warn$1('Do not use built-in directive ids as custom directive id: ' + name);
5232 }
5233}
5234/**
5235 * Adds directives to a VNode.
5236 */
5237function withDirectives(vnode, directives) {
5238 const internalInstance = currentRenderingInstance;
5239 if (internalInstance === null) {
5240 warn$1(`withDirectives can only be used inside render functions.`);
5241 return vnode;
5242 }
5243 const instance = getExposeProxy(internalInstance) ||
5244 internalInstance.proxy;
5245 const bindings = vnode.dirs || (vnode.dirs = []);
5246 for (let i = 0; i < directives.length; i++) {
5247 let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
5248 if (isFunction(dir)) {
5249 dir = {
5250 mounted: dir,
5251 updated: dir
5252 };
5253 }
5254 if (dir.deep) {
5255 traverse(value);
5256 }
5257 bindings.push({
5258 dir,
5259 instance,
5260 value,
5261 oldValue: void 0,
5262 arg,
5263 modifiers
5264 });
5265 }
5266 return vnode;
5267}
5268function invokeDirectiveHook(vnode, prevVNode, instance, name) {
5269 const bindings = vnode.dirs;
5270 const oldBindings = prevVNode && prevVNode.dirs;
5271 for (let i = 0; i < bindings.length; i++) {
5272 const binding = bindings[i];
5273 if (oldBindings) {
5274 binding.oldValue = oldBindings[i].value;
5275 }
5276 let hook = binding.dir[name];
5277 if (hook) {
5278 // disable tracking inside all lifecycle hooks
5279 // since they can potentially be called inside effects.
5280 pauseTracking();
5281 callWithAsyncErrorHandling(hook, instance, 8 /* DIRECTIVE_HOOK */, [
5282 vnode.el,
5283 binding,
5284 vnode,
5285 prevVNode
5286 ]);
5287 resetTracking();
5288 }
5289 }
5290}
5291
5292function createAppContext() {
5293 return {
5294 app: null,
5295 config: {
5296 isNativeTag: NO,
5297 performance: false,
5298 globalProperties: {},
5299 optionMergeStrategies: {},
5300 errorHandler: undefined,
5301 warnHandler: undefined,
5302 compilerOptions: {}
5303 },
5304 mixins: [],
5305 components: {},
5306 directives: {},
5307 provides: Object.create(null),
5308 optionsCache: new WeakMap(),
5309 propsCache: new WeakMap(),
5310 emitsCache: new WeakMap()
5311 };
5312}
5313let uid = 0;
5314function createAppAPI(render, hydrate) {
5315 return function createApp(rootComponent, rootProps = null) {
5316 if (!isFunction(rootComponent)) {
5317 rootComponent = Object.assign({}, rootComponent);
5318 }
5319 if (rootProps != null && !isObject(rootProps)) {
5320 warn$1(`root props passed to app.mount() must be an object.`);
5321 rootProps = null;
5322 }
5323 const context = createAppContext();
5324 const installedPlugins = new Set();
5325 let isMounted = false;
5326 const app = (context.app = {
5327 _uid: uid++,
5328 _component: rootComponent,
5329 _props: rootProps,
5330 _container: null,
5331 _context: context,
5332 _instance: null,
5333 version,
5334 get config() {
5335 return context.config;
5336 },
5337 set config(v) {
5338 {
5339 warn$1(`app.config cannot be replaced. Modify individual options instead.`);
5340 }
5341 },
5342 use(plugin, ...options) {
5343 if (installedPlugins.has(plugin)) {
5344 warn$1(`Plugin has already been applied to target app.`);
5345 }
5346 else if (plugin && isFunction(plugin.install)) {
5347 installedPlugins.add(plugin);
5348 plugin.install(app, ...options);
5349 }
5350 else if (isFunction(plugin)) {
5351 installedPlugins.add(plugin);
5352 plugin(app, ...options);
5353 }
5354 else {
5355 warn$1(`A plugin must either be a function or an object with an "install" ` +
5356 `function.`);
5357 }
5358 return app;
5359 },
5360 mixin(mixin) {
5361 {
5362 if (!context.mixins.includes(mixin)) {
5363 context.mixins.push(mixin);
5364 }
5365 else {
5366 warn$1('Mixin has already been applied to target app' +
5367 (mixin.name ? `: ${mixin.name}` : ''));
5368 }
5369 }
5370 return app;
5371 },
5372 component(name, component) {
5373 {
5374 validateComponentName(name, context.config);
5375 }
5376 if (!component) {
5377 return context.components[name];
5378 }
5379 if (context.components[name]) {
5380 warn$1(`Component "${name}" has already been registered in target app.`);
5381 }
5382 context.components[name] = component;
5383 return app;
5384 },
5385 directive(name, directive) {
5386 {
5387 validateDirectiveName(name);
5388 }
5389 if (!directive) {
5390 return context.directives[name];
5391 }
5392 if (context.directives[name]) {
5393 warn$1(`Directive "${name}" has already been registered in target app.`);
5394 }
5395 context.directives[name] = directive;
5396 return app;
5397 },
5398 mount(rootContainer, isHydrate, isSVG) {
5399 if (!isMounted) {
5400 const vnode = createVNode(rootComponent, rootProps);
5401 // store app context on the root VNode.
5402 // this will be set on the root instance on initial mount.
5403 vnode.appContext = context;
5404 // HMR root reload
5405 {
5406 context.reload = () => {
5407 render(cloneVNode(vnode), rootContainer, isSVG);
5408 };
5409 }
5410 if (isHydrate && hydrate) {
5411 hydrate(vnode, rootContainer);
5412 }
5413 else {
5414 render(vnode, rootContainer, isSVG);
5415 }
5416 isMounted = true;
5417 app._container = rootContainer;
5418 rootContainer.__vue_app__ = app;
5419 {
5420 app._instance = vnode.component;
5421 devtoolsInitApp(app, version);
5422 }
5423 return getExposeProxy(vnode.component) || vnode.component.proxy;
5424 }
5425 else {
5426 warn$1(`App has already been mounted.\n` +
5427 `If you want to remount the same app, move your app creation logic ` +
5428 `into a factory function and create fresh app instances for each ` +
5429 `mount - e.g. \`const createMyApp = () => createApp(App)\``);
5430 }
5431 },
5432 unmount() {
5433 if (isMounted) {
5434 render(null, app._container);
5435 {
5436 app._instance = null;
5437 devtoolsUnmountApp(app);
5438 }
5439 delete app._container.__vue_app__;
5440 }
5441 else {
5442 warn$1(`Cannot unmount an app that is not mounted.`);
5443 }
5444 },
5445 provide(key, value) {
5446 if (key in context.provides) {
5447 warn$1(`App already provides property with key "${String(key)}". ` +
5448 `It will be overwritten with the new value.`);
5449 }
5450 // TypeScript doesn't allow symbols as index type
5451 // https://github.com/Microsoft/TypeScript/issues/24587
5452 context.provides[key] = value;
5453 return app;
5454 }
5455 });
5456 return app;
5457 };
5458}
5459
5460/**
5461 * Function for handling a template ref
5462 */
5463function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) {
5464 if (isArray(rawRef)) {
5465 rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode, isUnmount));
5466 return;
5467 }
5468 if (isAsyncWrapper(vnode) && !isUnmount) {
5469 // when mounting async components, nothing needs to be done,
5470 // because the template ref is forwarded to inner component
5471 return;
5472 }
5473 const refValue = vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */
5474 ? getExposeProxy(vnode.component) || vnode.component.proxy
5475 : vnode.el;
5476 const value = isUnmount ? null : refValue;
5477 const { i: owner, r: ref } = rawRef;
5478 if (!owner) {
5479 warn$1(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
5480 `A vnode with ref must be created inside the render function.`);
5481 return;
5482 }
5483 const oldRef = oldRawRef && oldRawRef.r;
5484 const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
5485 const setupState = owner.setupState;
5486 // dynamic ref changed. unset old ref
5487 if (oldRef != null && oldRef !== ref) {
5488 if (isString(oldRef)) {
5489 refs[oldRef] = null;
5490 if (hasOwn(setupState, oldRef)) {
5491 setupState[oldRef] = null;
5492 }
5493 }
5494 else if (isRef(oldRef)) {
5495 oldRef.value = null;
5496 }
5497 }
5498 if (isFunction(ref)) {
5499 callWithErrorHandling(ref, owner, 12 /* FUNCTION_REF */, [value, refs]);
5500 }
5501 else {
5502 const _isString = isString(ref);
5503 const _isRef = isRef(ref);
5504 if (_isString || _isRef) {
5505 const doSet = () => {
5506 if (rawRef.f) {
5507 const existing = _isString ? refs[ref] : ref.value;
5508 if (isUnmount) {
5509 isArray(existing) && remove(existing, refValue);
5510 }
5511 else {
5512 if (!isArray(existing)) {
5513 if (_isString) {
5514 refs[ref] = [refValue];
5515 if (hasOwn(setupState, ref)) {
5516 setupState[ref] = refs[ref];
5517 }
5518 }
5519 else {
5520 ref.value = [refValue];
5521 if (rawRef.k)
5522 refs[rawRef.k] = ref.value;
5523 }
5524 }
5525 else if (!existing.includes(refValue)) {
5526 existing.push(refValue);
5527 }
5528 }
5529 }
5530 else if (_isString) {
5531 refs[ref] = value;
5532 if (hasOwn(setupState, ref)) {
5533 setupState[ref] = value;
5534 }
5535 }
5536 else if (isRef(ref)) {
5537 ref.value = value;
5538 if (rawRef.k)
5539 refs[rawRef.k] = value;
5540 }
5541 else {
5542 warn$1('Invalid template ref type:', ref, `(${typeof ref})`);
5543 }
5544 };
5545 if (value) {
5546 doSet.id = -1;
5547 queuePostRenderEffect(doSet, parentSuspense);
5548 }
5549 else {
5550 doSet();
5551 }
5552 }
5553 else {
5554 warn$1('Invalid template ref type:', ref, `(${typeof ref})`);
5555 }
5556 }
5557}
5558
5559let hasMismatch = false;
5560const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
5561const isComment = (node) => node.nodeType === 8 /* COMMENT */;
5562// Note: hydration is DOM-specific
5563// But we have to place it in core due to tight coupling with core - splitting
5564// it out creates a ton of unnecessary complexity.
5565// Hydration also depends on some renderer internal logic which needs to be
5566// passed in via arguments.
5567function createHydrationFunctions(rendererInternals) {
5568 const { mt: mountComponent, p: patch, o: { patchProp, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
5569 const hydrate = (vnode, container) => {
5570 if (!container.hasChildNodes()) {
5571 warn$1(`Attempting to hydrate existing markup but container is empty. ` +
5572 `Performing full mount instead.`);
5573 patch(null, vnode, container);
5574 flushPostFlushCbs();
5575 return;
5576 }
5577 hasMismatch = false;
5578 hydrateNode(container.firstChild, vnode, null, null, null);
5579 flushPostFlushCbs();
5580 if (hasMismatch && !false) {
5581 // this error should show up in production
5582 console.error(`Hydration completed but contains mismatches.`);
5583 }
5584 };
5585 const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => {
5586 const isFragmentStart = isComment(node) && node.data === '[';
5587 const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragmentStart);
5588 const { type, ref, shapeFlag } = vnode;
5589 const domType = node.nodeType;
5590 vnode.el = node;
5591 let nextNode = null;
5592 switch (type) {
5593 case Text:
5594 if (domType !== 3 /* TEXT */) {
5595 nextNode = onMismatch();
5596 }
5597 else {
5598 if (node.data !== vnode.children) {
5599 hasMismatch = true;
5600 warn$1(`Hydration text mismatch:` +
5601 `\n- Client: ${JSON.stringify(node.data)}` +
5602 `\n- Server: ${JSON.stringify(vnode.children)}`);
5603 node.data = vnode.children;
5604 }
5605 nextNode = nextSibling(node);
5606 }
5607 break;
5608 case Comment:
5609 if (domType !== 8 /* COMMENT */ || isFragmentStart) {
5610 nextNode = onMismatch();
5611 }
5612 else {
5613 nextNode = nextSibling(node);
5614 }
5615 break;
5616 case Static:
5617 if (domType !== 1 /* ELEMENT */) {
5618 nextNode = onMismatch();
5619 }
5620 else {
5621 // determine anchor, adopt content
5622 nextNode = node;
5623 // if the static vnode has its content stripped during build,
5624 // adopt it from the server-rendered HTML.
5625 const needToAdoptContent = !vnode.children.length;
5626 for (let i = 0; i < vnode.staticCount; i++) {
5627 if (needToAdoptContent)
5628 vnode.children += nextNode.outerHTML;
5629 if (i === vnode.staticCount - 1) {
5630 vnode.anchor = nextNode;
5631 }
5632 nextNode = nextSibling(nextNode);
5633 }
5634 return nextNode;
5635 }
5636 break;
5637 case Fragment:
5638 if (!isFragmentStart) {
5639 nextNode = onMismatch();
5640 }
5641 else {
5642 nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5643 }
5644 break;
5645 default:
5646 if (shapeFlag & 1 /* ELEMENT */) {
5647 if (domType !== 1 /* ELEMENT */ ||
5648 vnode.type.toLowerCase() !==
5649 node.tagName.toLowerCase()) {
5650 nextNode = onMismatch();
5651 }
5652 else {
5653 nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5654 }
5655 }
5656 else if (shapeFlag & 6 /* COMPONENT */) {
5657 // when setting up the render effect, if the initial vnode already
5658 // has .el set, the component will perform hydration instead of mount
5659 // on its sub-tree.
5660 vnode.slotScopeIds = slotScopeIds;
5661 const container = parentNode(node);
5662 mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
5663 // component may be async, so in the case of fragments we cannot rely
5664 // on component's rendered output to determine the end of the fragment
5665 // instead, we do a lookahead to find the end anchor node.
5666 nextNode = isFragmentStart
5667 ? locateClosingAsyncAnchor(node)
5668 : nextSibling(node);
5669 // #3787
5670 // if component is async, it may get moved / unmounted before its
5671 // inner component is loaded, so we need to give it a placeholder
5672 // vnode that matches its adopted DOM.
5673 if (isAsyncWrapper(vnode)) {
5674 let subTree;
5675 if (isFragmentStart) {
5676 subTree = createVNode(Fragment);
5677 subTree.anchor = nextNode
5678 ? nextNode.previousSibling
5679 : container.lastChild;
5680 }
5681 else {
5682 subTree =
5683 node.nodeType === 3 ? createTextVNode('') : createVNode('div');
5684 }
5685 subTree.el = node;
5686 vnode.component.subTree = subTree;
5687 }
5688 }
5689 else if (shapeFlag & 64 /* TELEPORT */) {
5690 if (domType !== 8 /* COMMENT */) {
5691 nextNode = onMismatch();
5692 }
5693 else {
5694 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, rendererInternals, hydrateChildren);
5695 }
5696 }
5697 else if (shapeFlag & 128 /* SUSPENSE */) {
5698 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), slotScopeIds, optimized, rendererInternals, hydrateNode);
5699 }
5700 else {
5701 warn$1('Invalid HostVNode type:', type, `(${typeof type})`);
5702 }
5703 }
5704 if (ref != null) {
5705 setRef(ref, null, parentSuspense, vnode);
5706 }
5707 return nextNode;
5708 };
5709 const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5710 optimized = optimized || !!vnode.dynamicChildren;
5711 const { type, props, patchFlag, shapeFlag, dirs } = vnode;
5712 // #4006 for form elements with non-string v-model value bindings
5713 // e.g. <option :value="obj">, <input type="checkbox" :true-value="1">
5714 const forcePatchValue = (type === 'input' && dirs) || type === 'option';
5715 // skip props & children if this is hoisted static nodes
5716 // #5405 in dev, always hydrate children for HMR
5717 {
5718 if (dirs) {
5719 invokeDirectiveHook(vnode, null, parentComponent, 'created');
5720 }
5721 // props
5722 if (props) {
5723 if (forcePatchValue ||
5724 !optimized ||
5725 patchFlag & (16 /* FULL_PROPS */ | 32 /* HYDRATE_EVENTS */)) {
5726 for (const key in props) {
5727 if ((forcePatchValue && key.endsWith('value')) ||
5728 (isOn(key) && !isReservedProp(key))) {
5729 patchProp(el, key, null, props[key], false, undefined, parentComponent);
5730 }
5731 }
5732 }
5733 else if (props.onClick) {
5734 // Fast path for click listeners (which is most often) to avoid
5735 // iterating through props.
5736 patchProp(el, 'onClick', null, props.onClick, false, undefined, parentComponent);
5737 }
5738 }
5739 // vnode / directive hooks
5740 let vnodeHooks;
5741 if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
5742 invokeVNodeHook(vnodeHooks, parentComponent, vnode);
5743 }
5744 if (dirs) {
5745 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
5746 }
5747 if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
5748 queueEffectWithSuspense(() => {
5749 vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
5750 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
5751 }, parentSuspense);
5752 }
5753 // children
5754 if (shapeFlag & 16 /* ARRAY_CHILDREN */ &&
5755 // skip if element has innerHTML / textContent
5756 !(props && (props.innerHTML || props.textContent))) {
5757 let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, slotScopeIds, optimized);
5758 let hasWarned = false;
5759 while (next) {
5760 hasMismatch = true;
5761 if (!hasWarned) {
5762 warn$1(`Hydration children mismatch in <${vnode.type}>: ` +
5763 `server rendered element contains more child nodes than client vdom.`);
5764 hasWarned = true;
5765 }
5766 // The SSRed DOM contains more nodes than it should. Remove them.
5767 const cur = next;
5768 next = next.nextSibling;
5769 remove(cur);
5770 }
5771 }
5772 else if (shapeFlag & 8 /* TEXT_CHILDREN */) {
5773 if (el.textContent !== vnode.children) {
5774 hasMismatch = true;
5775 warn$1(`Hydration text content mismatch in <${vnode.type}>:\n` +
5776 `- Client: ${el.textContent}\n` +
5777 `- Server: ${vnode.children}`);
5778 el.textContent = vnode.children;
5779 }
5780 }
5781 }
5782 return el.nextSibling;
5783 };
5784 const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5785 optimized = optimized || !!parentVNode.dynamicChildren;
5786 const children = parentVNode.children;
5787 const l = children.length;
5788 let hasWarned = false;
5789 for (let i = 0; i < l; i++) {
5790 const vnode = optimized
5791 ? children[i]
5792 : (children[i] = normalizeVNode(children[i]));
5793 if (node) {
5794 node = hydrateNode(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5795 }
5796 else if (vnode.type === Text && !vnode.children) {
5797 continue;
5798 }
5799 else {
5800 hasMismatch = true;
5801 if (!hasWarned) {
5802 warn$1(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
5803 `server rendered element contains fewer child nodes than client vdom.`);
5804 hasWarned = true;
5805 }
5806 // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
5807 patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
5808 }
5809 }
5810 return node;
5811 };
5812 const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5813 const { slotScopeIds: fragmentSlotScopeIds } = vnode;
5814 if (fragmentSlotScopeIds) {
5815 slotScopeIds = slotScopeIds
5816 ? slotScopeIds.concat(fragmentSlotScopeIds)
5817 : fragmentSlotScopeIds;
5818 }
5819 const container = parentNode(node);
5820 const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, slotScopeIds, optimized);
5821 if (next && isComment(next) && next.data === ']') {
5822 return nextSibling((vnode.anchor = next));
5823 }
5824 else {
5825 // fragment didn't hydrate successfully, since we didn't get a end anchor
5826 // back. This should have led to node/children mismatch warnings.
5827 hasMismatch = true;
5828 // since the anchor is missing, we need to create one and insert it
5829 insert((vnode.anchor = createComment(`]`)), container, next);
5830 return next;
5831 }
5832 };
5833 const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => {
5834 hasMismatch = true;
5835 warn$1(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* TEXT */
5836 ? `(text)`
5837 : isComment(node) && node.data === '['
5838 ? `(start of fragment)`
5839 : ``);
5840 vnode.el = null;
5841 if (isFragment) {
5842 // remove excessive fragment nodes
5843 const end = locateClosingAsyncAnchor(node);
5844 while (true) {
5845 const next = nextSibling(node);
5846 if (next && next !== end) {
5847 remove(next);
5848 }
5849 else {
5850 break;
5851 }
5852 }
5853 }
5854 const next = nextSibling(node);
5855 const container = parentNode(node);
5856 remove(node);
5857 patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
5858 return next;
5859 };
5860 const locateClosingAsyncAnchor = (node) => {
5861 let match = 0;
5862 while (node) {
5863 node = nextSibling(node);
5864 if (node && isComment(node)) {
5865 if (node.data === '[')
5866 match++;
5867 if (node.data === ']') {
5868 if (match === 0) {
5869 return nextSibling(node);
5870 }
5871 else {
5872 match--;
5873 }
5874 }
5875 }
5876 }
5877 return node;
5878 };
5879 return [hydrate, hydrateNode];
5880}
5881
5882/* eslint-disable no-restricted-globals */
5883let supported;
5884let perf;
5885function startMeasure(instance, type) {
5886 if (instance.appContext.config.performance && isSupported()) {
5887 perf.mark(`vue-${type}-${instance.uid}`);
5888 }
5889 {
5890 devtoolsPerfStart(instance, type, isSupported() ? perf.now() : Date.now());
5891 }
5892}
5893function endMeasure(instance, type) {
5894 if (instance.appContext.config.performance && isSupported()) {
5895 const startTag = `vue-${type}-${instance.uid}`;
5896 const endTag = startTag + `:end`;
5897 perf.mark(endTag);
5898 perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
5899 perf.clearMarks(startTag);
5900 perf.clearMarks(endTag);
5901 }
5902 {
5903 devtoolsPerfEnd(instance, type, isSupported() ? perf.now() : Date.now());
5904 }
5905}
5906function isSupported() {
5907 if (supported !== undefined) {
5908 return supported;
5909 }
5910 if (typeof window !== 'undefined' && window.performance) {
5911 supported = true;
5912 perf = window.performance;
5913 }
5914 else {
5915 supported = false;
5916 }
5917 return supported;
5918}
5919
5920const queuePostRenderEffect = queueEffectWithSuspense
5921 ;
5922/**
5923 * The createRenderer function accepts two generic arguments:
5924 * HostNode and HostElement, corresponding to Node and Element types in the
5925 * host environment. For example, for runtime-dom, HostNode would be the DOM
5926 * `Node` interface and HostElement would be the DOM `Element` interface.
5927 *
5928 * Custom renderers can pass in the platform specific types like this:
5929 *
5930 * ``` js
5931 * const { render, createApp } = createRenderer<Node, Element>({
5932 * patchProp,
5933 * ...nodeOps
5934 * })
5935 * ```
5936 */
5937function createRenderer(options) {
5938 return baseCreateRenderer(options);
5939}
5940// Separate API for creating hydration-enabled renderer.
5941// Hydration logic is only used when calling this function, making it
5942// tree-shakable.
5943function createHydrationRenderer(options) {
5944 return baseCreateRenderer(options, createHydrationFunctions);
5945}
5946// implementation
5947function baseCreateRenderer(options, createHydrationFns) {
5948 const target = getGlobalThis();
5949 target.__VUE__ = true;
5950 {
5951 setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__, target);
5952 }
5953 const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, setScopeId: hostSetScopeId = NOOP, cloneNode: hostCloneNode, insertStaticContent: hostInsertStaticContent } = options;
5954 // Note: functions inside this closure should use `const xxx = () => {}`
5955 // style in order to prevent being inlined by minifiers.
5956 const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, slotScopeIds = null, optimized = isHmrUpdating ? false : !!n2.dynamicChildren) => {
5957 if (n1 === n2) {
5958 return;
5959 }
5960 // patching & not same type, unmount old tree
5961 if (n1 && !isSameVNodeType(n1, n2)) {
5962 anchor = getNextHostNode(n1);
5963 unmount(n1, parentComponent, parentSuspense, true);
5964 n1 = null;
5965 }
5966 if (n2.patchFlag === -2 /* BAIL */) {
5967 optimized = false;
5968 n2.dynamicChildren = null;
5969 }
5970 const { type, ref, shapeFlag } = n2;
5971 switch (type) {
5972 case Text:
5973 processText(n1, n2, container, anchor);
5974 break;
5975 case Comment:
5976 processCommentNode(n1, n2, container, anchor);
5977 break;
5978 case Static:
5979 if (n1 == null) {
5980 mountStaticNode(n2, container, anchor, isSVG);
5981 }
5982 else {
5983 patchStaticNode(n1, n2, container, isSVG);
5984 }
5985 break;
5986 case Fragment:
5987 processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5988 break;
5989 default:
5990 if (shapeFlag & 1 /* ELEMENT */) {
5991 processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5992 }
5993 else if (shapeFlag & 6 /* COMPONENT */) {
5994 processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5995 }
5996 else if (shapeFlag & 64 /* TELEPORT */) {
5997 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
5998 }
5999 else if (shapeFlag & 128 /* SUSPENSE */) {
6000 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
6001 }
6002 else {
6003 warn$1('Invalid VNode type:', type, `(${typeof type})`);
6004 }
6005 }
6006 // set ref
6007 if (ref != null && parentComponent) {
6008 setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2);
6009 }
6010 };
6011 const processText = (n1, n2, container, anchor) => {
6012 if (n1 == null) {
6013 hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
6014 }
6015 else {
6016 const el = (n2.el = n1.el);
6017 if (n2.children !== n1.children) {
6018 hostSetText(el, n2.children);
6019 }
6020 }
6021 };
6022 const processCommentNode = (n1, n2, container, anchor) => {
6023 if (n1 == null) {
6024 hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
6025 }
6026 else {
6027 // there's no support for dynamic comments
6028 n2.el = n1.el;
6029 }
6030 };
6031 const mountStaticNode = (n2, container, anchor, isSVG) => {
6032 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG, n2.el, n2.anchor);
6033 };
6034 /**
6035 * Dev / HMR only
6036 */
6037 const patchStaticNode = (n1, n2, container, isSVG) => {
6038 // static nodes are only patched during dev for HMR
6039 if (n2.children !== n1.children) {
6040 const anchor = hostNextSibling(n1.anchor);
6041 // remove existing
6042 removeStaticNode(n1);
6043 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
6044 }
6045 else {
6046 n2.el = n1.el;
6047 n2.anchor = n1.anchor;
6048 }
6049 };
6050 const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
6051 let next;
6052 while (el && el !== anchor) {
6053 next = hostNextSibling(el);
6054 hostInsert(el, container, nextSibling);
6055 el = next;
6056 }
6057 hostInsert(anchor, container, nextSibling);
6058 };
6059 const removeStaticNode = ({ el, anchor }) => {
6060 let next;
6061 while (el && el !== anchor) {
6062 next = hostNextSibling(el);
6063 hostRemove(el);
6064 el = next;
6065 }
6066 hostRemove(anchor);
6067 };
6068 const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6069 isSVG = isSVG || n2.type === 'svg';
6070 if (n1 == null) {
6071 mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6072 }
6073 else {
6074 patchElement(n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6075 }
6076 };
6077 const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6078 let el;
6079 let vnodeHook;
6080 const { type, props, shapeFlag, transition, patchFlag, dirs } = vnode;
6081 {
6082 el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is, props);
6083 // mount children first, since some props may rely on child content
6084 // being already rendered, e.g. `<select value>`
6085 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
6086 hostSetElementText(el, vnode.children);
6087 }
6088 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6089 mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', slotScopeIds, optimized);
6090 }
6091 if (dirs) {
6092 invokeDirectiveHook(vnode, null, parentComponent, 'created');
6093 }
6094 // props
6095 if (props) {
6096 for (const key in props) {
6097 if (key !== 'value' && !isReservedProp(key)) {
6098 hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6099 }
6100 }
6101 /**
6102 * Special case for setting value on DOM elements:
6103 * - it can be order-sensitive (e.g. should be set *after* min/max, #2325, #4024)
6104 * - it needs to be forced (#1471)
6105 * #2353 proposes adding another renderer option to configure this, but
6106 * the properties affects are so finite it is worth special casing it
6107 * here to reduce the complexity. (Special casing it also should not
6108 * affect non-DOM renderers)
6109 */
6110 if ('value' in props) {
6111 hostPatchProp(el, 'value', null, props.value);
6112 }
6113 if ((vnodeHook = props.onVnodeBeforeMount)) {
6114 invokeVNodeHook(vnodeHook, parentComponent, vnode);
6115 }
6116 }
6117 // scopeId
6118 setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
6119 }
6120 {
6121 Object.defineProperty(el, '__vnode', {
6122 value: vnode,
6123 enumerable: false
6124 });
6125 Object.defineProperty(el, '__vueParentComponent', {
6126 value: parentComponent,
6127 enumerable: false
6128 });
6129 }
6130 if (dirs) {
6131 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
6132 }
6133 // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
6134 // #1689 For inside suspense + suspense resolved case, just call it
6135 const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
6136 transition &&
6137 !transition.persisted;
6138 if (needCallTransitionHooks) {
6139 transition.beforeEnter(el);
6140 }
6141 hostInsert(el, container, anchor);
6142 if ((vnodeHook = props && props.onVnodeMounted) ||
6143 needCallTransitionHooks ||
6144 dirs) {
6145 queuePostRenderEffect(() => {
6146 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
6147 needCallTransitionHooks && transition.enter(el);
6148 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
6149 }, parentSuspense);
6150 }
6151 };
6152 const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => {
6153 if (scopeId) {
6154 hostSetScopeId(el, scopeId);
6155 }
6156 if (slotScopeIds) {
6157 for (let i = 0; i < slotScopeIds.length; i++) {
6158 hostSetScopeId(el, slotScopeIds[i]);
6159 }
6160 }
6161 if (parentComponent) {
6162 let subTree = parentComponent.subTree;
6163 if (subTree.patchFlag > 0 &&
6164 subTree.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
6165 subTree =
6166 filterSingleRoot(subTree.children) || subTree;
6167 }
6168 if (vnode === subTree) {
6169 const parentVNode = parentComponent.vnode;
6170 setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent);
6171 }
6172 }
6173 };
6174 const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, start = 0) => {
6175 for (let i = start; i < children.length; i++) {
6176 const child = (children[i] = optimized
6177 ? cloneIfMounted(children[i])
6178 : normalizeVNode(children[i]));
6179 patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6180 }
6181 };
6182 const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6183 const el = (n2.el = n1.el);
6184 let { patchFlag, dynamicChildren, dirs } = n2;
6185 // #1426 take the old vnode's patch flag into account since user may clone a
6186 // compiler-generated vnode, which de-opts to FULL_PROPS
6187 patchFlag |= n1.patchFlag & 16 /* FULL_PROPS */;
6188 const oldProps = n1.props || EMPTY_OBJ;
6189 const newProps = n2.props || EMPTY_OBJ;
6190 let vnodeHook;
6191 // disable recurse in beforeUpdate hooks
6192 parentComponent && toggleRecurse(parentComponent, false);
6193 if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
6194 invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
6195 }
6196 if (dirs) {
6197 invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
6198 }
6199 parentComponent && toggleRecurse(parentComponent, true);
6200 if (isHmrUpdating) {
6201 // HMR updated, force full diff
6202 patchFlag = 0;
6203 optimized = false;
6204 dynamicChildren = null;
6205 }
6206 const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
6207 if (dynamicChildren) {
6208 patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds);
6209 if (parentComponent && parentComponent.type.__hmrId) {
6210 traverseStaticChildren(n1, n2);
6211 }
6212 }
6213 else if (!optimized) {
6214 // full diff
6215 patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds, false);
6216 }
6217 if (patchFlag > 0) {
6218 // the presence of a patchFlag means this element's render code was
6219 // generated by the compiler and can take the fast path.
6220 // in this path old node and new node are guaranteed to have the same shape
6221 // (i.e. at the exact same position in the source template)
6222 if (patchFlag & 16 /* FULL_PROPS */) {
6223 // element props contain dynamic keys, full diff needed
6224 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
6225 }
6226 else {
6227 // class
6228 // this flag is matched when the element has dynamic class bindings.
6229 if (patchFlag & 2 /* CLASS */) {
6230 if (oldProps.class !== newProps.class) {
6231 hostPatchProp(el, 'class', null, newProps.class, isSVG);
6232 }
6233 }
6234 // style
6235 // this flag is matched when the element has dynamic style bindings
6236 if (patchFlag & 4 /* STYLE */) {
6237 hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
6238 }
6239 // props
6240 // This flag is matched when the element has dynamic prop/attr bindings
6241 // other than class and style. The keys of dynamic prop/attrs are saved for
6242 // faster iteration.
6243 // Note dynamic keys like :[foo]="bar" will cause this optimization to
6244 // bail out and go through a full diff because we need to unset the old key
6245 if (patchFlag & 8 /* PROPS */) {
6246 // if the flag is present then dynamicProps must be non-null
6247 const propsToUpdate = n2.dynamicProps;
6248 for (let i = 0; i < propsToUpdate.length; i++) {
6249 const key = propsToUpdate[i];
6250 const prev = oldProps[key];
6251 const next = newProps[key];
6252 // #1471 force patch value
6253 if (next !== prev || key === 'value') {
6254 hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
6255 }
6256 }
6257 }
6258 }
6259 // text
6260 // This flag is matched when the element has only dynamic text children.
6261 if (patchFlag & 1 /* TEXT */) {
6262 if (n1.children !== n2.children) {
6263 hostSetElementText(el, n2.children);
6264 }
6265 }
6266 }
6267 else if (!optimized && dynamicChildren == null) {
6268 // unoptimized, full diff
6269 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
6270 }
6271 if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
6272 queuePostRenderEffect(() => {
6273 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
6274 dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
6275 }, parentSuspense);
6276 }
6277 };
6278 // The fast path for blocks.
6279 const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG, slotScopeIds) => {
6280 for (let i = 0; i < newChildren.length; i++) {
6281 const oldVNode = oldChildren[i];
6282 const newVNode = newChildren[i];
6283 // Determine the container (parent element) for the patch.
6284 const container =
6285 // oldVNode may be an errored async setup() component inside Suspense
6286 // which will not have a mounted element
6287 oldVNode.el &&
6288 // - In the case of a Fragment, we need to provide the actual parent
6289 // of the Fragment itself so it can move its children.
6290 (oldVNode.type === Fragment ||
6291 // - In the case of different nodes, there is going to be a replacement
6292 // which also requires the correct parent container
6293 !isSameVNodeType(oldVNode, newVNode) ||
6294 // - In the case of a component, it could contain anything.
6295 oldVNode.shapeFlag & (6 /* COMPONENT */ | 64 /* TELEPORT */))
6296 ? hostParentNode(oldVNode.el)
6297 : // In other cases, the parent container is not actually used so we
6298 // just pass the block element here to avoid a DOM parentNode call.
6299 fallbackContainer;
6300 patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, true);
6301 }
6302 };
6303 const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
6304 if (oldProps !== newProps) {
6305 for (const key in newProps) {
6306 // empty string is not valid prop
6307 if (isReservedProp(key))
6308 continue;
6309 const next = newProps[key];
6310 const prev = oldProps[key];
6311 // defer patching value
6312 if (next !== prev && key !== 'value') {
6313 hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6314 }
6315 }
6316 if (oldProps !== EMPTY_OBJ) {
6317 for (const key in oldProps) {
6318 if (!isReservedProp(key) && !(key in newProps)) {
6319 hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6320 }
6321 }
6322 }
6323 if ('value' in newProps) {
6324 hostPatchProp(el, 'value', oldProps.value, newProps.value);
6325 }
6326 }
6327 };
6328 const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6329 const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
6330 const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
6331 let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;
6332 if (isHmrUpdating) {
6333 // HMR updated, force full diff
6334 patchFlag = 0;
6335 optimized = false;
6336 dynamicChildren = null;
6337 }
6338 // check if this is a slot fragment with :slotted scope ids
6339 if (fragmentSlotScopeIds) {
6340 slotScopeIds = slotScopeIds
6341 ? slotScopeIds.concat(fragmentSlotScopeIds)
6342 : fragmentSlotScopeIds;
6343 }
6344 if (n1 == null) {
6345 hostInsert(fragmentStartAnchor, container, anchor);
6346 hostInsert(fragmentEndAnchor, container, anchor);
6347 // a fragment can only have array children
6348 // since they are either generated by the compiler, or implicitly created
6349 // from arrays.
6350 mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6351 }
6352 else {
6353 if (patchFlag > 0 &&
6354 patchFlag & 64 /* STABLE_FRAGMENT */ &&
6355 dynamicChildren &&
6356 // #2715 the previous fragment could've been a BAILed one as a result
6357 // of renderSlot() with no valid children
6358 n1.dynamicChildren) {
6359 // a stable fragment (template root or <template v-for>) doesn't need to
6360 // patch children order, but it may contain dynamicChildren.
6361 patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG, slotScopeIds);
6362 if (parentComponent && parentComponent.type.__hmrId) {
6363 traverseStaticChildren(n1, n2);
6364 }
6365 else if (
6366 // #2080 if the stable fragment has a key, it's a <template v-for> that may
6367 // get moved around. Make sure all root level vnodes inherit el.
6368 // #2134 or if it's a component root, it may also get moved around
6369 // as the component is being moved.
6370 n2.key != null ||
6371 (parentComponent && n2 === parentComponent.subTree)) {
6372 traverseStaticChildren(n1, n2, true /* shallow */);
6373 }
6374 }
6375 else {
6376 // keyed / unkeyed, or manual fragments.
6377 // for keyed & unkeyed, since they are compiler generated from v-for,
6378 // each child is guaranteed to be a block so the fragment will never
6379 // have dynamicChildren.
6380 patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6381 }
6382 }
6383 };
6384 const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6385 n2.slotScopeIds = slotScopeIds;
6386 if (n1 == null) {
6387 if (n2.shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
6388 parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
6389 }
6390 else {
6391 mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
6392 }
6393 }
6394 else {
6395 updateComponent(n1, n2, optimized);
6396 }
6397 };
6398 const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
6399 const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
6400 if (instance.type.__hmrId) {
6401 registerHMR(instance);
6402 }
6403 {
6404 pushWarningContext(initialVNode);
6405 startMeasure(instance, `mount`);
6406 }
6407 // inject renderer internals for keepAlive
6408 if (isKeepAlive(initialVNode)) {
6409 instance.ctx.renderer = internals;
6410 }
6411 // resolve props and slots for setup context
6412 {
6413 {
6414 startMeasure(instance, `init`);
6415 }
6416 setupComponent(instance);
6417 {
6418 endMeasure(instance, `init`);
6419 }
6420 }
6421 // setup() is async. This component relies on async logic to be resolved
6422 // before proceeding
6423 if (instance.asyncDep) {
6424 parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
6425 // Give it a placeholder if this is not hydration
6426 // TODO handle self-defined fallback
6427 if (!initialVNode.el) {
6428 const placeholder = (instance.subTree = createVNode(Comment));
6429 processCommentNode(null, placeholder, container, anchor);
6430 }
6431 return;
6432 }
6433 setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
6434 {
6435 popWarningContext();
6436 endMeasure(instance, `mount`);
6437 }
6438 };
6439 const updateComponent = (n1, n2, optimized) => {
6440 const instance = (n2.component = n1.component);
6441 if (shouldUpdateComponent(n1, n2, optimized)) {
6442 if (instance.asyncDep &&
6443 !instance.asyncResolved) {
6444 // async & still pending - just update props and slots
6445 // since the component's reactive effect for render isn't set-up yet
6446 {
6447 pushWarningContext(n2);
6448 }
6449 updateComponentPreRender(instance, n2, optimized);
6450 {
6451 popWarningContext();
6452 }
6453 return;
6454 }
6455 else {
6456 // normal update
6457 instance.next = n2;
6458 // in case the child component is also queued, remove it to avoid
6459 // double updating the same child component in the same flush.
6460 invalidateJob(instance.update);
6461 // instance.update is the reactive effect.
6462 instance.update();
6463 }
6464 }
6465 else {
6466 // no update needed. just copy over properties
6467 n2.component = n1.component;
6468 n2.el = n1.el;
6469 instance.vnode = n2;
6470 }
6471 };
6472 const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
6473 const componentUpdateFn = () => {
6474 if (!instance.isMounted) {
6475 let vnodeHook;
6476 const { el, props } = initialVNode;
6477 const { bm, m, parent } = instance;
6478 const isAsyncWrapperVNode = isAsyncWrapper(initialVNode);
6479 toggleRecurse(instance, false);
6480 // beforeMount hook
6481 if (bm) {
6482 invokeArrayFns(bm);
6483 }
6484 // onVnodeBeforeMount
6485 if (!isAsyncWrapperVNode &&
6486 (vnodeHook = props && props.onVnodeBeforeMount)) {
6487 invokeVNodeHook(vnodeHook, parent, initialVNode);
6488 }
6489 toggleRecurse(instance, true);
6490 if (el && hydrateNode) {
6491 // vnode has adopted host node - perform hydration instead of mount.
6492 const hydrateSubTree = () => {
6493 {
6494 startMeasure(instance, `render`);
6495 }
6496 instance.subTree = renderComponentRoot(instance);
6497 {
6498 endMeasure(instance, `render`);
6499 }
6500 {
6501 startMeasure(instance, `hydrate`);
6502 }
6503 hydrateNode(el, instance.subTree, instance, parentSuspense, null);
6504 {
6505 endMeasure(instance, `hydrate`);
6506 }
6507 };
6508 if (isAsyncWrapperVNode) {
6509 initialVNode.type.__asyncLoader().then(
6510 // note: we are moving the render call into an async callback,
6511 // which means it won't track dependencies - but it's ok because
6512 // a server-rendered async wrapper is already in resolved state
6513 // and it will never need to change.
6514 () => !instance.isUnmounted && hydrateSubTree());
6515 }
6516 else {
6517 hydrateSubTree();
6518 }
6519 }
6520 else {
6521 {
6522 startMeasure(instance, `render`);
6523 }
6524 const subTree = (instance.subTree = renderComponentRoot(instance));
6525 {
6526 endMeasure(instance, `render`);
6527 }
6528 {
6529 startMeasure(instance, `patch`);
6530 }
6531 patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
6532 {
6533 endMeasure(instance, `patch`);
6534 }
6535 initialVNode.el = subTree.el;
6536 }
6537 // mounted hook
6538 if (m) {
6539 queuePostRenderEffect(m, parentSuspense);
6540 }
6541 // onVnodeMounted
6542 if (!isAsyncWrapperVNode &&
6543 (vnodeHook = props && props.onVnodeMounted)) {
6544 const scopedInitialVNode = initialVNode;
6545 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), parentSuspense);
6546 }
6547 // activated hook for keep-alive roots.
6548 // #1742 activated hook must be accessed after first render
6549 // since the hook may be injected by a child keep-alive
6550 if (initialVNode.shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
6551 instance.a && queuePostRenderEffect(instance.a, parentSuspense);
6552 }
6553 instance.isMounted = true;
6554 {
6555 devtoolsComponentAdded(instance);
6556 }
6557 // #2458: deference mount-only object parameters to prevent memleaks
6558 initialVNode = container = anchor = null;
6559 }
6560 else {
6561 // updateComponent
6562 // This is triggered by mutation of component's own state (next: null)
6563 // OR parent calling processComponent (next: VNode)
6564 let { next, bu, u, parent, vnode } = instance;
6565 let originNext = next;
6566 let vnodeHook;
6567 {
6568 pushWarningContext(next || instance.vnode);
6569 }
6570 // Disallow component effect recursion during pre-lifecycle hooks.
6571 toggleRecurse(instance, false);
6572 if (next) {
6573 next.el = vnode.el;
6574 updateComponentPreRender(instance, next, optimized);
6575 }
6576 else {
6577 next = vnode;
6578 }
6579 // beforeUpdate hook
6580 if (bu) {
6581 invokeArrayFns(bu);
6582 }
6583 // onVnodeBeforeUpdate
6584 if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
6585 invokeVNodeHook(vnodeHook, parent, next, vnode);
6586 }
6587 toggleRecurse(instance, true);
6588 // render
6589 {
6590 startMeasure(instance, `render`);
6591 }
6592 const nextTree = renderComponentRoot(instance);
6593 {
6594 endMeasure(instance, `render`);
6595 }
6596 const prevTree = instance.subTree;
6597 instance.subTree = nextTree;
6598 {
6599 startMeasure(instance, `patch`);
6600 }
6601 patch(prevTree, nextTree,
6602 // parent may have changed if it's in a teleport
6603 hostParentNode(prevTree.el),
6604 // anchor may have changed if it's in a fragment
6605 getNextHostNode(prevTree), instance, parentSuspense, isSVG);
6606 {
6607 endMeasure(instance, `patch`);
6608 }
6609 next.el = nextTree.el;
6610 if (originNext === null) {
6611 // self-triggered update. In case of HOC, update parent component
6612 // vnode el. HOC is indicated by parent instance's subTree pointing
6613 // to child component's vnode
6614 updateHOCHostEl(instance, nextTree.el);
6615 }
6616 // updated hook
6617 if (u) {
6618 queuePostRenderEffect(u, parentSuspense);
6619 }
6620 // onVnodeUpdated
6621 if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
6622 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, next, vnode), parentSuspense);
6623 }
6624 {
6625 devtoolsComponentUpdated(instance);
6626 }
6627 {
6628 popWarningContext();
6629 }
6630 }
6631 };
6632 // create reactive effect for rendering
6633 const effect = (instance.effect = new ReactiveEffect(componentUpdateFn, () => queueJob(instance.update), instance.scope // track it in component's effect scope
6634 ));
6635 const update = (instance.update = effect.run.bind(effect));
6636 update.id = instance.uid;
6637 // allowRecurse
6638 // #1801, #2043 component render effects should allow recursive updates
6639 toggleRecurse(instance, true);
6640 {
6641 effect.onTrack = instance.rtc
6642 ? e => invokeArrayFns(instance.rtc, e)
6643 : void 0;
6644 effect.onTrigger = instance.rtg
6645 ? e => invokeArrayFns(instance.rtg, e)
6646 : void 0;
6647 // @ts-ignore (for scheduler)
6648 update.ownerInstance = instance;
6649 }
6650 update();
6651 };
6652 const updateComponentPreRender = (instance, nextVNode, optimized) => {
6653 nextVNode.component = instance;
6654 const prevProps = instance.vnode.props;
6655 instance.vnode = nextVNode;
6656 instance.next = null;
6657 updateProps(instance, nextVNode.props, prevProps, optimized);
6658 updateSlots(instance, nextVNode.children, optimized);
6659 pauseTracking();
6660 // props update may have triggered pre-flush watchers.
6661 // flush them before the render update.
6662 flushPreFlushCbs(undefined, instance.update);
6663 resetTracking();
6664 };
6665 const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized = false) => {
6666 const c1 = n1 && n1.children;
6667 const prevShapeFlag = n1 ? n1.shapeFlag : 0;
6668 const c2 = n2.children;
6669 const { patchFlag, shapeFlag } = n2;
6670 // fast path
6671 if (patchFlag > 0) {
6672 if (patchFlag & 128 /* KEYED_FRAGMENT */) {
6673 // this could be either fully-keyed or mixed (some keyed some not)
6674 // presence of patchFlag means children are guaranteed to be arrays
6675 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6676 return;
6677 }
6678 else if (patchFlag & 256 /* UNKEYED_FRAGMENT */) {
6679 // unkeyed
6680 patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6681 return;
6682 }
6683 }
6684 // children has 3 possibilities: text, array or no children.
6685 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
6686 // text children fast path
6687 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
6688 unmountChildren(c1, parentComponent, parentSuspense);
6689 }
6690 if (c2 !== c1) {
6691 hostSetElementText(container, c2);
6692 }
6693 }
6694 else {
6695 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
6696 // prev children was array
6697 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6698 // two arrays, cannot assume anything, do full diff
6699 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6700 }
6701 else {
6702 // no new children, just unmount old
6703 unmountChildren(c1, parentComponent, parentSuspense, true);
6704 }
6705 }
6706 else {
6707 // prev children was text OR null
6708 // new children is array OR null
6709 if (prevShapeFlag & 8 /* TEXT_CHILDREN */) {
6710 hostSetElementText(container, '');
6711 }
6712 // mount new if array
6713 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6714 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6715 }
6716 }
6717 }
6718 };
6719 const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6720 c1 = c1 || EMPTY_ARR;
6721 c2 = c2 || EMPTY_ARR;
6722 const oldLength = c1.length;
6723 const newLength = c2.length;
6724 const commonLength = Math.min(oldLength, newLength);
6725 let i;
6726 for (i = 0; i < commonLength; i++) {
6727 const nextChild = (c2[i] = optimized
6728 ? cloneIfMounted(c2[i])
6729 : normalizeVNode(c2[i]));
6730 patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6731 }
6732 if (oldLength > newLength) {
6733 // remove old
6734 unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
6735 }
6736 else {
6737 // mount new
6738 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, commonLength);
6739 }
6740 };
6741 // can be all-keyed or mixed
6742 const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6743 let i = 0;
6744 const l2 = c2.length;
6745 let e1 = c1.length - 1; // prev ending index
6746 let e2 = l2 - 1; // next ending index
6747 // 1. sync from start
6748 // (a b) c
6749 // (a b) d e
6750 while (i <= e1 && i <= e2) {
6751 const n1 = c1[i];
6752 const n2 = (c2[i] = optimized
6753 ? cloneIfMounted(c2[i])
6754 : normalizeVNode(c2[i]));
6755 if (isSameVNodeType(n1, n2)) {
6756 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6757 }
6758 else {
6759 break;
6760 }
6761 i++;
6762 }
6763 // 2. sync from end
6764 // a (b c)
6765 // d e (b c)
6766 while (i <= e1 && i <= e2) {
6767 const n1 = c1[e1];
6768 const n2 = (c2[e2] = optimized
6769 ? cloneIfMounted(c2[e2])
6770 : normalizeVNode(c2[e2]));
6771 if (isSameVNodeType(n1, n2)) {
6772 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6773 }
6774 else {
6775 break;
6776 }
6777 e1--;
6778 e2--;
6779 }
6780 // 3. common sequence + mount
6781 // (a b)
6782 // (a b) c
6783 // i = 2, e1 = 1, e2 = 2
6784 // (a b)
6785 // c (a b)
6786 // i = 0, e1 = -1, e2 = 0
6787 if (i > e1) {
6788 if (i <= e2) {
6789 const nextPos = e2 + 1;
6790 const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
6791 while (i <= e2) {
6792 patch(null, (c2[i] = optimized
6793 ? cloneIfMounted(c2[i])
6794 : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6795 i++;
6796 }
6797 }
6798 }
6799 // 4. common sequence + unmount
6800 // (a b) c
6801 // (a b)
6802 // i = 2, e1 = 2, e2 = 1
6803 // a (b c)
6804 // (b c)
6805 // i = 0, e1 = 0, e2 = -1
6806 else if (i > e2) {
6807 while (i <= e1) {
6808 unmount(c1[i], parentComponent, parentSuspense, true);
6809 i++;
6810 }
6811 }
6812 // 5. unknown sequence
6813 // [i ... e1 + 1]: a b [c d e] f g
6814 // [i ... e2 + 1]: a b [e d c h] f g
6815 // i = 2, e1 = 4, e2 = 5
6816 else {
6817 const s1 = i; // prev starting index
6818 const s2 = i; // next starting index
6819 // 5.1 build key:index map for newChildren
6820 const keyToNewIndexMap = new Map();
6821 for (i = s2; i <= e2; i++) {
6822 const nextChild = (c2[i] = optimized
6823 ? cloneIfMounted(c2[i])
6824 : normalizeVNode(c2[i]));
6825 if (nextChild.key != null) {
6826 if (keyToNewIndexMap.has(nextChild.key)) {
6827 warn$1(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
6828 }
6829 keyToNewIndexMap.set(nextChild.key, i);
6830 }
6831 }
6832 // 5.2 loop through old children left to be patched and try to patch
6833 // matching nodes & remove nodes that are no longer present
6834 let j;
6835 let patched = 0;
6836 const toBePatched = e2 - s2 + 1;
6837 let moved = false;
6838 // used to track whether any node has moved
6839 let maxNewIndexSoFar = 0;
6840 // works as Map<newIndex, oldIndex>
6841 // Note that oldIndex is offset by +1
6842 // and oldIndex = 0 is a special value indicating the new node has
6843 // no corresponding old node.
6844 // used for determining longest stable subsequence
6845 const newIndexToOldIndexMap = new Array(toBePatched);
6846 for (i = 0; i < toBePatched; i++)
6847 newIndexToOldIndexMap[i] = 0;
6848 for (i = s1; i <= e1; i++) {
6849 const prevChild = c1[i];
6850 if (patched >= toBePatched) {
6851 // all new children have been patched so this can only be a removal
6852 unmount(prevChild, parentComponent, parentSuspense, true);
6853 continue;
6854 }
6855 let newIndex;
6856 if (prevChild.key != null) {
6857 newIndex = keyToNewIndexMap.get(prevChild.key);
6858 }
6859 else {
6860 // key-less node, try to locate a key-less node of the same type
6861 for (j = s2; j <= e2; j++) {
6862 if (newIndexToOldIndexMap[j - s2] === 0 &&
6863 isSameVNodeType(prevChild, c2[j])) {
6864 newIndex = j;
6865 break;
6866 }
6867 }
6868 }
6869 if (newIndex === undefined) {
6870 unmount(prevChild, parentComponent, parentSuspense, true);
6871 }
6872 else {
6873 newIndexToOldIndexMap[newIndex - s2] = i + 1;
6874 if (newIndex >= maxNewIndexSoFar) {
6875 maxNewIndexSoFar = newIndex;
6876 }
6877 else {
6878 moved = true;
6879 }
6880 patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6881 patched++;
6882 }
6883 }
6884 // 5.3 move and mount
6885 // generate longest stable subsequence only when nodes have moved
6886 const increasingNewIndexSequence = moved
6887 ? getSequence(newIndexToOldIndexMap)
6888 : EMPTY_ARR;
6889 j = increasingNewIndexSequence.length - 1;
6890 // looping backwards so that we can use last patched node as anchor
6891 for (i = toBePatched - 1; i >= 0; i--) {
6892 const nextIndex = s2 + i;
6893 const nextChild = c2[nextIndex];
6894 const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
6895 if (newIndexToOldIndexMap[i] === 0) {
6896 // mount new
6897 patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6898 }
6899 else if (moved) {
6900 // move if:
6901 // There is no stable subsequence (e.g. a reverse)
6902 // OR current node is not among the stable sequence
6903 if (j < 0 || i !== increasingNewIndexSequence[j]) {
6904 move(nextChild, container, anchor, 2 /* REORDER */);
6905 }
6906 else {
6907 j--;
6908 }
6909 }
6910 }
6911 }
6912 };
6913 const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
6914 const { el, type, transition, children, shapeFlag } = vnode;
6915 if (shapeFlag & 6 /* COMPONENT */) {
6916 move(vnode.component.subTree, container, anchor, moveType);
6917 return;
6918 }
6919 if (shapeFlag & 128 /* SUSPENSE */) {
6920 vnode.suspense.move(container, anchor, moveType);
6921 return;
6922 }
6923 if (shapeFlag & 64 /* TELEPORT */) {
6924 type.move(vnode, container, anchor, internals);
6925 return;
6926 }
6927 if (type === Fragment) {
6928 hostInsert(el, container, anchor);
6929 for (let i = 0; i < children.length; i++) {
6930 move(children[i], container, anchor, moveType);
6931 }
6932 hostInsert(vnode.anchor, container, anchor);
6933 return;
6934 }
6935 if (type === Static) {
6936 moveStaticNode(vnode, container, anchor);
6937 return;
6938 }
6939 // single nodes
6940 const needTransition = moveType !== 2 /* REORDER */ &&
6941 shapeFlag & 1 /* ELEMENT */ &&
6942 transition;
6943 if (needTransition) {
6944 if (moveType === 0 /* ENTER */) {
6945 transition.beforeEnter(el);
6946 hostInsert(el, container, anchor);
6947 queuePostRenderEffect(() => transition.enter(el), parentSuspense);
6948 }
6949 else {
6950 const { leave, delayLeave, afterLeave } = transition;
6951 const remove = () => hostInsert(el, container, anchor);
6952 const performLeave = () => {
6953 leave(el, () => {
6954 remove();
6955 afterLeave && afterLeave();
6956 });
6957 };
6958 if (delayLeave) {
6959 delayLeave(el, remove, performLeave);
6960 }
6961 else {
6962 performLeave();
6963 }
6964 }
6965 }
6966 else {
6967 hostInsert(el, container, anchor);
6968 }
6969 };
6970 const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
6971 const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
6972 // unset ref
6973 if (ref != null) {
6974 setRef(ref, null, parentSuspense, vnode, true);
6975 }
6976 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
6977 parentComponent.ctx.deactivate(vnode);
6978 return;
6979 }
6980 const shouldInvokeDirs = shapeFlag & 1 /* ELEMENT */ && dirs;
6981 const shouldInvokeVnodeHook = !isAsyncWrapper(vnode);
6982 let vnodeHook;
6983 if (shouldInvokeVnodeHook &&
6984 (vnodeHook = props && props.onVnodeBeforeUnmount)) {
6985 invokeVNodeHook(vnodeHook, parentComponent, vnode);
6986 }
6987 if (shapeFlag & 6 /* COMPONENT */) {
6988 unmountComponent(vnode.component, parentSuspense, doRemove);
6989 }
6990 else {
6991 if (shapeFlag & 128 /* SUSPENSE */) {
6992 vnode.suspense.unmount(parentSuspense, doRemove);
6993 return;
6994 }
6995 if (shouldInvokeDirs) {
6996 invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
6997 }
6998 if (shapeFlag & 64 /* TELEPORT */) {
6999 vnode.type.remove(vnode, parentComponent, parentSuspense, optimized, internals, doRemove);
7000 }
7001 else if (dynamicChildren &&
7002 // #1153: fast path should not be taken for non-stable (v-for) fragments
7003 (type !== Fragment ||
7004 (patchFlag > 0 && patchFlag & 64 /* STABLE_FRAGMENT */))) {
7005 // fast path for block nodes: only need to unmount dynamic children.
7006 unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
7007 }
7008 else if ((type === Fragment &&
7009 patchFlag &
7010 (128 /* KEYED_FRAGMENT */ | 256 /* UNKEYED_FRAGMENT */)) ||
7011 (!optimized && shapeFlag & 16 /* ARRAY_CHILDREN */)) {
7012 unmountChildren(children, parentComponent, parentSuspense);
7013 }
7014 if (doRemove) {
7015 remove(vnode);
7016 }
7017 }
7018 if ((shouldInvokeVnodeHook &&
7019 (vnodeHook = props && props.onVnodeUnmounted)) ||
7020 shouldInvokeDirs) {
7021 queuePostRenderEffect(() => {
7022 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
7023 shouldInvokeDirs &&
7024 invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
7025 }, parentSuspense);
7026 }
7027 };
7028 const remove = vnode => {
7029 const { type, el, anchor, transition } = vnode;
7030 if (type === Fragment) {
7031 if (vnode.patchFlag > 0 &&
7032 vnode.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */ &&
7033 transition &&
7034 !transition.persisted) {
7035 vnode.children.forEach(child => {
7036 if (child.type === Comment) {
7037 hostRemove(child.el);
7038 }
7039 else {
7040 remove(child);
7041 }
7042 });
7043 }
7044 else {
7045 removeFragment(el, anchor);
7046 }
7047 return;
7048 }
7049 if (type === Static) {
7050 removeStaticNode(vnode);
7051 return;
7052 }
7053 const performRemove = () => {
7054 hostRemove(el);
7055 if (transition && !transition.persisted && transition.afterLeave) {
7056 transition.afterLeave();
7057 }
7058 };
7059 if (vnode.shapeFlag & 1 /* ELEMENT */ &&
7060 transition &&
7061 !transition.persisted) {
7062 const { leave, delayLeave } = transition;
7063 const performLeave = () => leave(el, performRemove);
7064 if (delayLeave) {
7065 delayLeave(vnode.el, performRemove, performLeave);
7066 }
7067 else {
7068 performLeave();
7069 }
7070 }
7071 else {
7072 performRemove();
7073 }
7074 };
7075 const removeFragment = (cur, end) => {
7076 // For fragments, directly remove all contained DOM nodes.
7077 // (fragment child nodes cannot have transition)
7078 let next;
7079 while (cur !== end) {
7080 next = hostNextSibling(cur);
7081 hostRemove(cur);
7082 cur = next;
7083 }
7084 hostRemove(end);
7085 };
7086 const unmountComponent = (instance, parentSuspense, doRemove) => {
7087 if (instance.type.__hmrId) {
7088 unregisterHMR(instance);
7089 }
7090 const { bum, scope, update, subTree, um } = instance;
7091 // beforeUnmount hook
7092 if (bum) {
7093 invokeArrayFns(bum);
7094 }
7095 // stop effects in component scope
7096 scope.stop();
7097 // update may be null if a component is unmounted before its async
7098 // setup has resolved.
7099 if (update) {
7100 // so that scheduler will no longer invoke it
7101 update.active = false;
7102 unmount(subTree, instance, parentSuspense, doRemove);
7103 }
7104 // unmounted hook
7105 if (um) {
7106 queuePostRenderEffect(um, parentSuspense);
7107 }
7108 queuePostRenderEffect(() => {
7109 instance.isUnmounted = true;
7110 }, parentSuspense);
7111 // A component with async dep inside a pending suspense is unmounted before
7112 // its async dep resolves. This should remove the dep from the suspense, and
7113 // cause the suspense to resolve immediately if that was the last dep.
7114 if (parentSuspense &&
7115 parentSuspense.pendingBranch &&
7116 !parentSuspense.isUnmounted &&
7117 instance.asyncDep &&
7118 !instance.asyncResolved &&
7119 instance.suspenseId === parentSuspense.pendingId) {
7120 parentSuspense.deps--;
7121 if (parentSuspense.deps === 0) {
7122 parentSuspense.resolve();
7123 }
7124 }
7125 {
7126 devtoolsComponentRemoved(instance);
7127 }
7128 };
7129 const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
7130 for (let i = start; i < children.length; i++) {
7131 unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
7132 }
7133 };
7134 const getNextHostNode = vnode => {
7135 if (vnode.shapeFlag & 6 /* COMPONENT */) {
7136 return getNextHostNode(vnode.component.subTree);
7137 }
7138 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
7139 return vnode.suspense.next();
7140 }
7141 return hostNextSibling((vnode.anchor || vnode.el));
7142 };
7143 const render = (vnode, container, isSVG) => {
7144 if (vnode == null) {
7145 if (container._vnode) {
7146 unmount(container._vnode, null, null, true);
7147 }
7148 }
7149 else {
7150 patch(container._vnode || null, vnode, container, null, null, null, isSVG);
7151 }
7152 flushPostFlushCbs();
7153 container._vnode = vnode;
7154 };
7155 const internals = {
7156 p: patch,
7157 um: unmount,
7158 m: move,
7159 r: remove,
7160 mt: mountComponent,
7161 mc: mountChildren,
7162 pc: patchChildren,
7163 pbc: patchBlockChildren,
7164 n: getNextHostNode,
7165 o: options
7166 };
7167 let hydrate;
7168 let hydrateNode;
7169 if (createHydrationFns) {
7170 [hydrate, hydrateNode] = createHydrationFns(internals);
7171 }
7172 return {
7173 render,
7174 hydrate,
7175 createApp: createAppAPI(render, hydrate)
7176 };
7177}
7178function toggleRecurse({ effect, update }, allowed) {
7179 effect.allowRecurse = update.allowRecurse = allowed;
7180}
7181/**
7182 * #1156
7183 * When a component is HMR-enabled, we need to make sure that all static nodes
7184 * inside a block also inherit the DOM element from the previous tree so that
7185 * HMR updates (which are full updates) can retrieve the element for patching.
7186 *
7187 * #2080
7188 * Inside keyed `template` fragment static children, if a fragment is moved,
7189 * the children will always be moved. Therefore, in order to ensure correct move
7190 * position, el should be inherited from previous nodes.
7191 */
7192function traverseStaticChildren(n1, n2, shallow = false) {
7193 const ch1 = n1.children;
7194 const ch2 = n2.children;
7195 if (isArray(ch1) && isArray(ch2)) {
7196 for (let i = 0; i < ch1.length; i++) {
7197 // this is only called in the optimized path so array children are
7198 // guaranteed to be vnodes
7199 const c1 = ch1[i];
7200 let c2 = ch2[i];
7201 if (c2.shapeFlag & 1 /* ELEMENT */ && !c2.dynamicChildren) {
7202 if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* HYDRATE_EVENTS */) {
7203 c2 = ch2[i] = cloneIfMounted(ch2[i]);
7204 c2.el = c1.el;
7205 }
7206 if (!shallow)
7207 traverseStaticChildren(c1, c2);
7208 }
7209 // also inherit for comment nodes, but not placeholders (e.g. v-if which
7210 // would have received .el during block patch)
7211 if (c2.type === Comment && !c2.el) {
7212 c2.el = c1.el;
7213 }
7214 }
7215 }
7216}
7217// https://en.wikipedia.org/wiki/Longest_increasing_subsequence
7218function getSequence(arr) {
7219 const p = arr.slice();
7220 const result = [0];
7221 let i, j, u, v, c;
7222 const len = arr.length;
7223 for (i = 0; i < len; i++) {
7224 const arrI = arr[i];
7225 if (arrI !== 0) {
7226 j = result[result.length - 1];
7227 if (arr[j] < arrI) {
7228 p[i] = j;
7229 result.push(i);
7230 continue;
7231 }
7232 u = 0;
7233 v = result.length - 1;
7234 while (u < v) {
7235 c = (u + v) >> 1;
7236 if (arr[result[c]] < arrI) {
7237 u = c + 1;
7238 }
7239 else {
7240 v = c;
7241 }
7242 }
7243 if (arrI < arr[result[u]]) {
7244 if (u > 0) {
7245 p[i] = result[u - 1];
7246 }
7247 result[u] = i;
7248 }
7249 }
7250 }
7251 u = result.length;
7252 v = result[u - 1];
7253 while (u-- > 0) {
7254 result[u] = v;
7255 v = p[v];
7256 }
7257 return result;
7258}
7259
7260const isTeleport = (type) => type.__isTeleport;
7261const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
7262const isTargetSVG = (target) => typeof SVGElement !== 'undefined' && target instanceof SVGElement;
7263const resolveTarget = (props, select) => {
7264 const targetSelector = props && props.to;
7265 if (isString(targetSelector)) {
7266 if (!select) {
7267 warn$1(`Current renderer does not support string target for Teleports. ` +
7268 `(missing querySelector renderer option)`);
7269 return null;
7270 }
7271 else {
7272 const target = select(targetSelector);
7273 if (!target) {
7274 warn$1(`Failed to locate Teleport target with selector "${targetSelector}". ` +
7275 `Note the target element must exist before the component is mounted - ` +
7276 `i.e. the target cannot be rendered by the component itself, and ` +
7277 `ideally should be outside of the entire Vue component tree.`);
7278 }
7279 return target;
7280 }
7281 }
7282 else {
7283 if (!targetSelector && !isTeleportDisabled(props)) {
7284 warn$1(`Invalid Teleport target: ${targetSelector}`);
7285 }
7286 return targetSelector;
7287 }
7288};
7289const TeleportImpl = {
7290 __isTeleport: true,
7291 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals) {
7292 const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
7293 const disabled = isTeleportDisabled(n2.props);
7294 let { shapeFlag, children, dynamicChildren } = n2;
7295 // #3302
7296 // HMR updated, force full diff
7297 if (isHmrUpdating) {
7298 optimized = false;
7299 dynamicChildren = null;
7300 }
7301 if (n1 == null) {
7302 // insert anchors in the main view
7303 const placeholder = (n2.el = createComment('teleport start')
7304 );
7305 const mainAnchor = (n2.anchor = createComment('teleport end')
7306 );
7307 insert(placeholder, container, anchor);
7308 insert(mainAnchor, container, anchor);
7309 const target = (n2.target = resolveTarget(n2.props, querySelector));
7310 const targetAnchor = (n2.targetAnchor = createText(''));
7311 if (target) {
7312 insert(targetAnchor, target);
7313 // #2652 we could be teleporting from a non-SVG tree into an SVG tree
7314 isSVG = isSVG || isTargetSVG(target);
7315 }
7316 else if (!disabled) {
7317 warn$1('Invalid Teleport target on mount:', target, `(${typeof target})`);
7318 }
7319 const mount = (container, anchor) => {
7320 // Teleport *always* has Array children. This is enforced in both the
7321 // compiler and vnode children normalization.
7322 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7323 mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7324 }
7325 };
7326 if (disabled) {
7327 mount(container, mainAnchor);
7328 }
7329 else if (target) {
7330 mount(target, targetAnchor);
7331 }
7332 }
7333 else {
7334 // update content
7335 n2.el = n1.el;
7336 const mainAnchor = (n2.anchor = n1.anchor);
7337 const target = (n2.target = n1.target);
7338 const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
7339 const wasDisabled = isTeleportDisabled(n1.props);
7340 const currentContainer = wasDisabled ? container : target;
7341 const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
7342 isSVG = isSVG || isTargetSVG(target);
7343 if (dynamicChildren) {
7344 // fast path when the teleport happens to be a block root
7345 patchBlockChildren(n1.dynamicChildren, dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG, slotScopeIds);
7346 // even in block tree mode we need to make sure all root-level nodes
7347 // in the teleport inherit previous DOM references so that they can
7348 // be moved in future patches.
7349 traverseStaticChildren(n1, n2, true);
7350 }
7351 else if (!optimized) {
7352 patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, false);
7353 }
7354 if (disabled) {
7355 if (!wasDisabled) {
7356 // enabled -> disabled
7357 // move into main container
7358 moveTeleport(n2, container, mainAnchor, internals, 1 /* TOGGLE */);
7359 }
7360 }
7361 else {
7362 // target changed
7363 if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
7364 const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
7365 if (nextTarget) {
7366 moveTeleport(n2, nextTarget, null, internals, 0 /* TARGET_CHANGE */);
7367 }
7368 else {
7369 warn$1('Invalid Teleport target on update:', target, `(${typeof target})`);
7370 }
7371 }
7372 else if (wasDisabled) {
7373 // disabled -> enabled
7374 // move into teleport target
7375 moveTeleport(n2, target, targetAnchor, internals, 1 /* TOGGLE */);
7376 }
7377 }
7378 }
7379 },
7380 remove(vnode, parentComponent, parentSuspense, optimized, { um: unmount, o: { remove: hostRemove } }, doRemove) {
7381 const { shapeFlag, children, anchor, targetAnchor, target, props } = vnode;
7382 if (target) {
7383 hostRemove(targetAnchor);
7384 }
7385 // an unmounted teleport should always remove its children if not disabled
7386 if (doRemove || !isTeleportDisabled(props)) {
7387 hostRemove(anchor);
7388 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7389 for (let i = 0; i < children.length; i++) {
7390 const child = children[i];
7391 unmount(child, parentComponent, parentSuspense, true, !!child.dynamicChildren);
7392 }
7393 }
7394 }
7395 },
7396 move: moveTeleport,
7397 hydrate: hydrateTeleport
7398};
7399function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* REORDER */) {
7400 // move target anchor if this is a target change.
7401 if (moveType === 0 /* TARGET_CHANGE */) {
7402 insert(vnode.targetAnchor, container, parentAnchor);
7403 }
7404 const { el, anchor, shapeFlag, children, props } = vnode;
7405 const isReorder = moveType === 2 /* REORDER */;
7406 // move main view anchor if this is a re-order.
7407 if (isReorder) {
7408 insert(el, container, parentAnchor);
7409 }
7410 // if this is a re-order and teleport is enabled (content is in target)
7411 // do not move children. So the opposite is: only move children if this
7412 // is not a reorder, or the teleport is disabled
7413 if (!isReorder || isTeleportDisabled(props)) {
7414 // Teleport has either Array children or no children.
7415 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7416 for (let i = 0; i < children.length; i++) {
7417 move(children[i], container, parentAnchor, 2 /* REORDER */);
7418 }
7419 }
7420 }
7421 // move main view anchor if this is a re-order.
7422 if (isReorder) {
7423 insert(anchor, container, parentAnchor);
7424 }
7425}
7426function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
7427 const target = (vnode.target = resolveTarget(vnode.props, querySelector));
7428 if (target) {
7429 // if multiple teleports rendered to the same target element, we need to
7430 // pick up from where the last teleport finished instead of the first node
7431 const targetNode = target._lpa || target.firstChild;
7432 if (vnode.shapeFlag & 16 /* ARRAY_CHILDREN */) {
7433 if (isTeleportDisabled(vnode.props)) {
7434 vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, slotScopeIds, optimized);
7435 vnode.targetAnchor = targetNode;
7436 }
7437 else {
7438 vnode.anchor = nextSibling(node);
7439 vnode.targetAnchor = hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, slotScopeIds, optimized);
7440 }
7441 target._lpa =
7442 vnode.targetAnchor && nextSibling(vnode.targetAnchor);
7443 }
7444 }
7445 return vnode.anchor && nextSibling(vnode.anchor);
7446}
7447// Force-casted public typing for h and TSX props inference
7448const Teleport = TeleportImpl;
7449
7450const COMPONENTS = 'components';
7451const DIRECTIVES = 'directives';
7452/**
7453 * @private
7454 */
7455function resolveComponent(name, maybeSelfReference) {
7456 return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name;
7457}
7458const NULL_DYNAMIC_COMPONENT = Symbol();
7459/**
7460 * @private
7461 */
7462function resolveDynamicComponent(component) {
7463 if (isString(component)) {
7464 return resolveAsset(COMPONENTS, component, false) || component;
7465 }
7466 else {
7467 // invalid types will fallthrough to createVNode and raise warning
7468 return (component || NULL_DYNAMIC_COMPONENT);
7469 }
7470}
7471/**
7472 * @private
7473 */
7474function resolveDirective(name) {
7475 return resolveAsset(DIRECTIVES, name);
7476}
7477// implementation
7478function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {
7479 const instance = currentRenderingInstance || currentInstance;
7480 if (instance) {
7481 const Component = instance.type;
7482 // explicit self name has highest priority
7483 if (type === COMPONENTS) {
7484 const selfName = getComponentName(Component);
7485 if (selfName &&
7486 (selfName === name ||
7487 selfName === camelize(name) ||
7488 selfName === capitalize(camelize(name)))) {
7489 return Component;
7490 }
7491 }
7492 const res =
7493 // local registration
7494 // check instance[type] first which is resolved for options API
7495 resolve(instance[type] || Component[type], name) ||
7496 // global registration
7497 resolve(instance.appContext[type], name);
7498 if (!res && maybeSelfReference) {
7499 // fallback to implicit self-reference
7500 return Component;
7501 }
7502 if (warnMissing && !res) {
7503 const extra = type === COMPONENTS
7504 ? `\nIf this is a native custom element, make sure to exclude it from ` +
7505 `component resolution via compilerOptions.isCustomElement.`
7506 : ``;
7507 warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`);
7508 }
7509 return res;
7510 }
7511 else {
7512 warn$1(`resolve${capitalize(type.slice(0, -1))} ` +
7513 `can only be used in render() or setup().`);
7514 }
7515}
7516function resolve(registry, name) {
7517 return (registry &&
7518 (registry[name] ||
7519 registry[camelize(name)] ||
7520 registry[capitalize(camelize(name))]));
7521}
7522
7523const Fragment = Symbol('Fragment' );
7524const Text = Symbol('Text' );
7525const Comment = Symbol('Comment' );
7526const Static = Symbol('Static' );
7527// Since v-if and v-for are the two possible ways node structure can dynamically
7528// change, once we consider v-if branches and each v-for fragment a block, we
7529// can divide a template into nested blocks, and within each block the node
7530// structure would be stable. This allows us to skip most children diffing
7531// and only worry about the dynamic nodes (indicated by patch flags).
7532const blockStack = [];
7533let currentBlock = null;
7534/**
7535 * Open a block.
7536 * This must be called before `createBlock`. It cannot be part of `createBlock`
7537 * because the children of the block are evaluated before `createBlock` itself
7538 * is called. The generated code typically looks like this:
7539 *
7540 * ```js
7541 * function render() {
7542 * return (openBlock(),createBlock('div', null, [...]))
7543 * }
7544 * ```
7545 * disableTracking is true when creating a v-for fragment block, since a v-for
7546 * fragment always diffs its children.
7547 *
7548 * @private
7549 */
7550function openBlock(disableTracking = false) {
7551 blockStack.push((currentBlock = disableTracking ? null : []));
7552}
7553function closeBlock() {
7554 blockStack.pop();
7555 currentBlock = blockStack[blockStack.length - 1] || null;
7556}
7557// Whether we should be tracking dynamic child nodes inside a block.
7558// Only tracks when this value is > 0
7559// We are not using a simple boolean because this value may need to be
7560// incremented/decremented by nested usage of v-once (see below)
7561let isBlockTreeEnabled = 1;
7562/**
7563 * Block tracking sometimes needs to be disabled, for example during the
7564 * creation of a tree that needs to be cached by v-once. The compiler generates
7565 * code like this:
7566 *
7567 * ``` js
7568 * _cache[1] || (
7569 * setBlockTracking(-1),
7570 * _cache[1] = createVNode(...),
7571 * setBlockTracking(1),
7572 * _cache[1]
7573 * )
7574 * ```
7575 *
7576 * @private
7577 */
7578function setBlockTracking(value) {
7579 isBlockTreeEnabled += value;
7580}
7581function setupBlock(vnode) {
7582 // save current block children on the block vnode
7583 vnode.dynamicChildren =
7584 isBlockTreeEnabled > 0 ? currentBlock || EMPTY_ARR : null;
7585 // close block
7586 closeBlock();
7587 // a block is always going to be patched, so track it as a child of its
7588 // parent block
7589 if (isBlockTreeEnabled > 0 && currentBlock) {
7590 currentBlock.push(vnode);
7591 }
7592 return vnode;
7593}
7594/**
7595 * @private
7596 */
7597function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) {
7598 return setupBlock(createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, true /* isBlock */));
7599}
7600/**
7601 * Create a block root vnode. Takes the same exact arguments as `createVNode`.
7602 * A block root keeps track of dynamic nodes within the block in the
7603 * `dynamicChildren` array.
7604 *
7605 * @private
7606 */
7607function createBlock(type, props, children, patchFlag, dynamicProps) {
7608 return setupBlock(createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */));
7609}
7610function isVNode(value) {
7611 return value ? value.__v_isVNode === true : false;
7612}
7613function isSameVNodeType(n1, n2) {
7614 if (n2.shapeFlag & 6 /* COMPONENT */ &&
7615 hmrDirtyComponents.has(n2.type)) {
7616 // HMR only: if the component has been hot-updated, force a reload.
7617 return false;
7618 }
7619 return n1.type === n2.type && n1.key === n2.key;
7620}
7621let vnodeArgsTransformer;
7622/**
7623 * Internal API for registering an arguments transform for createVNode
7624 * used for creating stubs in the test-utils
7625 * It is *internal* but needs to be exposed for test-utils to pick up proper
7626 * typings
7627 */
7628function transformVNodeArgs(transformer) {
7629 vnodeArgsTransformer = transformer;
7630}
7631const createVNodeWithArgsTransform = (...args) => {
7632 return _createVNode(...(vnodeArgsTransformer
7633 ? vnodeArgsTransformer(args, currentRenderingInstance)
7634 : args));
7635};
7636const InternalObjectKey = `__vInternal`;
7637const normalizeKey = ({ key }) => key != null ? key : null;
7638const normalizeRef = ({ ref, ref_key, ref_for }) => {
7639 return (ref != null
7640 ? isString(ref) || isRef(ref) || isFunction(ref)
7641 ? { i: currentRenderingInstance, r: ref, k: ref_key, f: !!ref_for }
7642 : ref
7643 : null);
7644};
7645function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1 /* ELEMENT */, isBlockNode = false, needFullChildrenNormalization = false) {
7646 const vnode = {
7647 __v_isVNode: true,
7648 __v_skip: true,
7649 type,
7650 props,
7651 key: props && normalizeKey(props),
7652 ref: props && normalizeRef(props),
7653 scopeId: currentScopeId,
7654 slotScopeIds: null,
7655 children,
7656 component: null,
7657 suspense: null,
7658 ssContent: null,
7659 ssFallback: null,
7660 dirs: null,
7661 transition: null,
7662 el: null,
7663 anchor: null,
7664 target: null,
7665 targetAnchor: null,
7666 staticCount: 0,
7667 shapeFlag,
7668 patchFlag,
7669 dynamicProps,
7670 dynamicChildren: null,
7671 appContext: null
7672 };
7673 if (needFullChildrenNormalization) {
7674 normalizeChildren(vnode, children);
7675 // normalize suspense children
7676 if (shapeFlag & 128 /* SUSPENSE */) {
7677 type.normalize(vnode);
7678 }
7679 }
7680 else if (children) {
7681 // compiled element vnode - if children is passed, only possible types are
7682 // string or Array.
7683 vnode.shapeFlag |= isString(children)
7684 ? 8 /* TEXT_CHILDREN */
7685 : 16 /* ARRAY_CHILDREN */;
7686 }
7687 // validate key
7688 if (vnode.key !== vnode.key) {
7689 warn$1(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
7690 }
7691 // track vnode for block tree
7692 if (isBlockTreeEnabled > 0 &&
7693 // avoid a block node from tracking itself
7694 !isBlockNode &&
7695 // has current parent block
7696 currentBlock &&
7697 // presence of a patch flag indicates this node needs patching on updates.
7698 // component nodes also should always be patched, because even if the
7699 // component doesn't need to update, it needs to persist the instance on to
7700 // the next vnode so that it can be properly unmounted later.
7701 (vnode.patchFlag > 0 || shapeFlag & 6 /* COMPONENT */) &&
7702 // the EVENTS flag is only for hydration and if it is the only flag, the
7703 // vnode should not be considered dynamic due to handler caching.
7704 vnode.patchFlag !== 32 /* HYDRATE_EVENTS */) {
7705 currentBlock.push(vnode);
7706 }
7707 return vnode;
7708}
7709const createVNode = (createVNodeWithArgsTransform );
7710function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
7711 if (!type || type === NULL_DYNAMIC_COMPONENT) {
7712 if (!type) {
7713 warn$1(`Invalid vnode type when creating vnode: ${type}.`);
7714 }
7715 type = Comment;
7716 }
7717 if (isVNode(type)) {
7718 // createVNode receiving an existing vnode. This happens in cases like
7719 // <component :is="vnode"/>
7720 // #2078 make sure to merge refs during the clone instead of overwriting it
7721 const cloned = cloneVNode(type, props, true /* mergeRef: true */);
7722 if (children) {
7723 normalizeChildren(cloned, children);
7724 }
7725 return cloned;
7726 }
7727 // class component normalization.
7728 if (isClassComponent(type)) {
7729 type = type.__vccOpts;
7730 }
7731 // class & style normalization.
7732 if (props) {
7733 // for reactive or proxy objects, we need to clone it to enable mutation.
7734 props = guardReactiveProps(props);
7735 let { class: klass, style } = props;
7736 if (klass && !isString(klass)) {
7737 props.class = normalizeClass(klass);
7738 }
7739 if (isObject(style)) {
7740 // reactive state objects need to be cloned since they are likely to be
7741 // mutated
7742 if (isProxy(style) && !isArray(style)) {
7743 style = extend({}, style);
7744 }
7745 props.style = normalizeStyle(style);
7746 }
7747 }
7748 // encode the vnode type information into a bitmap
7749 const shapeFlag = isString(type)
7750 ? 1 /* ELEMENT */
7751 : isSuspense(type)
7752 ? 128 /* SUSPENSE */
7753 : isTeleport(type)
7754 ? 64 /* TELEPORT */
7755 : isObject(type)
7756 ? 4 /* STATEFUL_COMPONENT */
7757 : isFunction(type)
7758 ? 2 /* FUNCTIONAL_COMPONENT */
7759 : 0;
7760 if (shapeFlag & 4 /* STATEFUL_COMPONENT */ && isProxy(type)) {
7761 type = toRaw(type);
7762 warn$1(`Vue received a Component which was made a reactive object. This can ` +
7763 `lead to unnecessary performance overhead, and should be avoided by ` +
7764 `marking the component with \`markRaw\` or using \`shallowRef\` ` +
7765 `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
7766 }
7767 return createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, isBlockNode, true);
7768}
7769function guardReactiveProps(props) {
7770 if (!props)
7771 return null;
7772 return isProxy(props) || InternalObjectKey in props
7773 ? extend({}, props)
7774 : props;
7775}
7776function cloneVNode(vnode, extraProps, mergeRef = false) {
7777 // This is intentionally NOT using spread or extend to avoid the runtime
7778 // key enumeration cost.
7779 const { props, ref, patchFlag, children } = vnode;
7780 const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
7781 const cloned = {
7782 __v_isVNode: true,
7783 __v_skip: true,
7784 type: vnode.type,
7785 props: mergedProps,
7786 key: mergedProps && normalizeKey(mergedProps),
7787 ref: extraProps && extraProps.ref
7788 ? // #2078 in the case of <component :is="vnode" ref="extra"/>
7789 // if the vnode itself already has a ref, cloneVNode will need to merge
7790 // the refs so the single vnode can be set on multiple refs
7791 mergeRef && ref
7792 ? isArray(ref)
7793 ? ref.concat(normalizeRef(extraProps))
7794 : [ref, normalizeRef(extraProps)]
7795 : normalizeRef(extraProps)
7796 : ref,
7797 scopeId: vnode.scopeId,
7798 slotScopeIds: vnode.slotScopeIds,
7799 children: patchFlag === -1 /* HOISTED */ && isArray(children)
7800 ? children.map(deepCloneVNode)
7801 : children,
7802 target: vnode.target,
7803 targetAnchor: vnode.targetAnchor,
7804 staticCount: vnode.staticCount,
7805 shapeFlag: vnode.shapeFlag,
7806 // if the vnode is cloned with extra props, we can no longer assume its
7807 // existing patch flag to be reliable and need to add the FULL_PROPS flag.
7808 // note: preserve flag for fragments since they use the flag for children
7809 // fast paths only.
7810 patchFlag: extraProps && vnode.type !== Fragment
7811 ? patchFlag === -1 // hoisted node
7812 ? 16 /* FULL_PROPS */
7813 : patchFlag | 16 /* FULL_PROPS */
7814 : patchFlag,
7815 dynamicProps: vnode.dynamicProps,
7816 dynamicChildren: vnode.dynamicChildren,
7817 appContext: vnode.appContext,
7818 dirs: vnode.dirs,
7819 transition: vnode.transition,
7820 // These should technically only be non-null on mounted VNodes. However,
7821 // they *should* be copied for kept-alive vnodes. So we just always copy
7822 // them since them being non-null during a mount doesn't affect the logic as
7823 // they will simply be overwritten.
7824 component: vnode.component,
7825 suspense: vnode.suspense,
7826 ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
7827 ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
7828 el: vnode.el,
7829 anchor: vnode.anchor
7830 };
7831 return cloned;
7832}
7833/**
7834 * Dev only, for HMR of hoisted vnodes reused in v-for
7835 * https://github.com/vitejs/vite/issues/2022
7836 */
7837function deepCloneVNode(vnode) {
7838 const cloned = cloneVNode(vnode);
7839 if (isArray(vnode.children)) {
7840 cloned.children = vnode.children.map(deepCloneVNode);
7841 }
7842 return cloned;
7843}
7844/**
7845 * @private
7846 */
7847function createTextVNode(text = ' ', flag = 0) {
7848 return createVNode(Text, null, text, flag);
7849}
7850/**
7851 * @private
7852 */
7853function createStaticVNode(content, numberOfNodes) {
7854 // A static vnode can contain multiple stringified elements, and the number
7855 // of elements is necessary for hydration.
7856 const vnode = createVNode(Static, null, content);
7857 vnode.staticCount = numberOfNodes;
7858 return vnode;
7859}
7860/**
7861 * @private
7862 */
7863function createCommentVNode(text = '',
7864// when used as the v-else branch, the comment node must be created as a
7865// block to ensure correct updates.
7866asBlock = false) {
7867 return asBlock
7868 ? (openBlock(), createBlock(Comment, null, text))
7869 : createVNode(Comment, null, text);
7870}
7871function normalizeVNode(child) {
7872 if (child == null || typeof child === 'boolean') {
7873 // empty placeholder
7874 return createVNode(Comment);
7875 }
7876 else if (isArray(child)) {
7877 // fragment
7878 return createVNode(Fragment, null,
7879 // #3666, avoid reference pollution when reusing vnode
7880 child.slice());
7881 }
7882 else if (typeof child === 'object') {
7883 // already vnode, this should be the most common since compiled templates
7884 // always produce all-vnode children arrays
7885 return cloneIfMounted(child);
7886 }
7887 else {
7888 // strings and numbers
7889 return createVNode(Text, null, String(child));
7890 }
7891}
7892// optimized normalization for template-compiled render fns
7893function cloneIfMounted(child) {
7894 return child.el === null || child.memo ? child : cloneVNode(child);
7895}
7896function normalizeChildren(vnode, children) {
7897 let type = 0;
7898 const { shapeFlag } = vnode;
7899 if (children == null) {
7900 children = null;
7901 }
7902 else if (isArray(children)) {
7903 type = 16 /* ARRAY_CHILDREN */;
7904 }
7905 else if (typeof children === 'object') {
7906 if (shapeFlag & (1 /* ELEMENT */ | 64 /* TELEPORT */)) {
7907 // Normalize slot to plain children for plain element and Teleport
7908 const slot = children.default;
7909 if (slot) {
7910 // _c marker is added by withCtx() indicating this is a compiled slot
7911 slot._c && (slot._d = false);
7912 normalizeChildren(vnode, slot());
7913 slot._c && (slot._d = true);
7914 }
7915 return;
7916 }
7917 else {
7918 type = 32 /* SLOTS_CHILDREN */;
7919 const slotFlag = children._;
7920 if (!slotFlag && !(InternalObjectKey in children)) {
7921 children._ctx = currentRenderingInstance;
7922 }
7923 else if (slotFlag === 3 /* FORWARDED */ && currentRenderingInstance) {
7924 // a child component receives forwarded slots from the parent.
7925 // its slot type is determined by its parent's slot type.
7926 if (currentRenderingInstance.slots._ === 1 /* STABLE */) {
7927 children._ = 1 /* STABLE */;
7928 }
7929 else {
7930 children._ = 2 /* DYNAMIC */;
7931 vnode.patchFlag |= 1024 /* DYNAMIC_SLOTS */;
7932 }
7933 }
7934 }
7935 }
7936 else if (isFunction(children)) {
7937 children = { default: children, _ctx: currentRenderingInstance };
7938 type = 32 /* SLOTS_CHILDREN */;
7939 }
7940 else {
7941 children = String(children);
7942 // force teleport children to array so it can be moved around
7943 if (shapeFlag & 64 /* TELEPORT */) {
7944 type = 16 /* ARRAY_CHILDREN */;
7945 children = [createTextVNode(children)];
7946 }
7947 else {
7948 type = 8 /* TEXT_CHILDREN */;
7949 }
7950 }
7951 vnode.children = children;
7952 vnode.shapeFlag |= type;
7953}
7954function mergeProps(...args) {
7955 const ret = {};
7956 for (let i = 0; i < args.length; i++) {
7957 const toMerge = args[i];
7958 for (const key in toMerge) {
7959 if (key === 'class') {
7960 if (ret.class !== toMerge.class) {
7961 ret.class = normalizeClass([ret.class, toMerge.class]);
7962 }
7963 }
7964 else if (key === 'style') {
7965 ret.style = normalizeStyle([ret.style, toMerge.style]);
7966 }
7967 else if (isOn(key)) {
7968 const existing = ret[key];
7969 const incoming = toMerge[key];
7970 if (incoming &&
7971 existing !== incoming &&
7972 !(isArray(existing) && existing.includes(incoming))) {
7973 ret[key] = existing
7974 ? [].concat(existing, incoming)
7975 : incoming;
7976 }
7977 }
7978 else if (key !== '') {
7979 ret[key] = toMerge[key];
7980 }
7981 }
7982 }
7983 return ret;
7984}
7985function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
7986 callWithAsyncErrorHandling(hook, instance, 7 /* VNODE_HOOK */, [
7987 vnode,
7988 prevVNode
7989 ]);
7990}
7991
7992/**
7993 * Actual implementation
7994 */
7995function renderList(source, renderItem, cache, index) {
7996 let ret;
7997 const cached = (cache && cache[index]);
7998 if (isArray(source) || isString(source)) {
7999 ret = new Array(source.length);
8000 for (let i = 0, l = source.length; i < l; i++) {
8001 ret[i] = renderItem(source[i], i, undefined, cached && cached[i]);
8002 }
8003 }
8004 else if (typeof source === 'number') {
8005 if (!Number.isInteger(source)) {
8006 warn$1(`The v-for range expect an integer value but got ${source}.`);
8007 return [];
8008 }
8009 ret = new Array(source);
8010 for (let i = 0; i < source; i++) {
8011 ret[i] = renderItem(i + 1, i, undefined, cached && cached[i]);
8012 }
8013 }
8014 else if (isObject(source)) {
8015 if (source[Symbol.iterator]) {
8016 ret = Array.from(source, (item, i) => renderItem(item, i, undefined, cached && cached[i]));
8017 }
8018 else {
8019 const keys = Object.keys(source);
8020 ret = new Array(keys.length);
8021 for (let i = 0, l = keys.length; i < l; i++) {
8022 const key = keys[i];
8023 ret[i] = renderItem(source[key], key, i, cached && cached[i]);
8024 }
8025 }
8026 }
8027 else {
8028 ret = [];
8029 }
8030 if (cache) {
8031 cache[index] = ret;
8032 }
8033 return ret;
8034}
8035
8036/**
8037 * Compiler runtime helper for creating dynamic slots object
8038 * @private
8039 */
8040function createSlots(slots, dynamicSlots) {
8041 for (let i = 0; i < dynamicSlots.length; i++) {
8042 const slot = dynamicSlots[i];
8043 // array of dynamic slot generated by <template v-for="..." #[...]>
8044 if (isArray(slot)) {
8045 for (let j = 0; j < slot.length; j++) {
8046 slots[slot[j].name] = slot[j].fn;
8047 }
8048 }
8049 else if (slot) {
8050 // conditional single slot generated by <template v-if="..." #foo>
8051 slots[slot.name] = slot.fn;
8052 }
8053 }
8054 return slots;
8055}
8056
8057/**
8058 * Compiler runtime helper for rendering `<slot/>`
8059 * @private
8060 */
8061function renderSlot(slots, name, props = {},
8062// this is not a user-facing function, so the fallback is always generated by
8063// the compiler and guaranteed to be a function returning an array
8064fallback, noSlotted) {
8065 if (currentRenderingInstance.isCE ||
8066 (currentRenderingInstance.parent &&
8067 isAsyncWrapper(currentRenderingInstance.parent) &&
8068 currentRenderingInstance.parent.isCE)) {
8069 return createVNode('slot', name === 'default' ? null : { name }, fallback && fallback());
8070 }
8071 let slot = slots[name];
8072 if (slot && slot.length > 1) {
8073 warn$1(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
8074 `function. You need to mark this component with $dynamic-slots in the ` +
8075 `parent template.`);
8076 slot = () => [];
8077 }
8078 // a compiled slot disables block tracking by default to avoid manual
8079 // invocation interfering with template-based block tracking, but in
8080 // `renderSlot` we can be sure that it's template-based so we can force
8081 // enable it.
8082 if (slot && slot._c) {
8083 slot._d = false;
8084 }
8085 openBlock();
8086 const validSlotContent = slot && ensureValidVNode(slot(props));
8087 const rendered = createBlock(Fragment, { key: props.key || `_${name}` }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 /* STABLE */
8088 ? 64 /* STABLE_FRAGMENT */
8089 : -2 /* BAIL */);
8090 if (!noSlotted && rendered.scopeId) {
8091 rendered.slotScopeIds = [rendered.scopeId + '-s'];
8092 }
8093 if (slot && slot._c) {
8094 slot._d = true;
8095 }
8096 return rendered;
8097}
8098function ensureValidVNode(vnodes) {
8099 return vnodes.some(child => {
8100 if (!isVNode(child))
8101 return true;
8102 if (child.type === Comment)
8103 return false;
8104 if (child.type === Fragment &&
8105 !ensureValidVNode(child.children))
8106 return false;
8107 return true;
8108 })
8109 ? vnodes
8110 : null;
8111}
8112
8113/**
8114 * For prefixing keys in v-on="obj" with "on"
8115 * @private
8116 */
8117function toHandlers(obj) {
8118 const ret = {};
8119 if (!isObject(obj)) {
8120 warn$1(`v-on with no argument expects an object value.`);
8121 return ret;
8122 }
8123 for (const key in obj) {
8124 ret[toHandlerKey(key)] = obj[key];
8125 }
8126 return ret;
8127}
8128
8129/**
8130 * #2437 In Vue 3, functional components do not have a public instance proxy but
8131 * they exist in the internal parent chain. For code that relies on traversing
8132 * public $parent chains, skip functional ones and go to the parent instead.
8133 */
8134const getPublicInstance = (i) => {
8135 if (!i)
8136 return null;
8137 if (isStatefulComponent(i))
8138 return getExposeProxy(i) || i.proxy;
8139 return getPublicInstance(i.parent);
8140};
8141const publicPropertiesMap =
8142// Move PURE marker to new line to workaround compiler discarding it
8143// due to type annotation
8144/*#__PURE__*/ extend(Object.create(null), {
8145 $: i => i,
8146 $el: i => i.vnode.el,
8147 $data: i => i.data,
8148 $props: i => (shallowReadonly(i.props) ),
8149 $attrs: i => (shallowReadonly(i.attrs) ),
8150 $slots: i => (shallowReadonly(i.slots) ),
8151 $refs: i => (shallowReadonly(i.refs) ),
8152 $parent: i => getPublicInstance(i.parent),
8153 $root: i => getPublicInstance(i.root),
8154 $emit: i => i.emit,
8155 $options: i => (resolveMergedOptions(i) ),
8156 $forceUpdate: i => () => queueJob(i.update),
8157 $nextTick: i => nextTick.bind(i.proxy),
8158 $watch: i => (instanceWatch.bind(i) )
8159});
8160const PublicInstanceProxyHandlers = {
8161 get({ _: instance }, key) {
8162 const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
8163 // for internal formatters to know that this is a Vue instance
8164 if (key === '__isVue') {
8165 return true;
8166 }
8167 // prioritize <script setup> bindings during dev.
8168 // this allows even properties that start with _ or $ to be used - so that
8169 // it aligns with the production behavior where the render fn is inlined and
8170 // indeed has access to all declared variables.
8171 if (setupState !== EMPTY_OBJ &&
8172 setupState.__isScriptSetup &&
8173 hasOwn(setupState, key)) {
8174 return setupState[key];
8175 }
8176 // data / props / ctx
8177 // This getter gets called for every property access on the render context
8178 // during render and is a major hotspot. The most expensive part of this
8179 // is the multiple hasOwn() calls. It's much faster to do a simple property
8180 // access on a plain object, so we use an accessCache object (with null
8181 // prototype) to memoize what access type a key corresponds to.
8182 let normalizedProps;
8183 if (key[0] !== '$') {
8184 const n = accessCache[key];
8185 if (n !== undefined) {
8186 switch (n) {
8187 case 1 /* SETUP */:
8188 return setupState[key];
8189 case 2 /* DATA */:
8190 return data[key];
8191 case 4 /* CONTEXT */:
8192 return ctx[key];
8193 case 3 /* PROPS */:
8194 return props[key];
8195 // default: just fallthrough
8196 }
8197 }
8198 else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
8199 accessCache[key] = 1 /* SETUP */;
8200 return setupState[key];
8201 }
8202 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
8203 accessCache[key] = 2 /* DATA */;
8204 return data[key];
8205 }
8206 else if (
8207 // only cache other properties when instance has declared (thus stable)
8208 // props
8209 (normalizedProps = instance.propsOptions[0]) &&
8210 hasOwn(normalizedProps, key)) {
8211 accessCache[key] = 3 /* PROPS */;
8212 return props[key];
8213 }
8214 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
8215 accessCache[key] = 4 /* CONTEXT */;
8216 return ctx[key];
8217 }
8218 else if (shouldCacheAccess) {
8219 accessCache[key] = 0 /* OTHER */;
8220 }
8221 }
8222 const publicGetter = publicPropertiesMap[key];
8223 let cssModule, globalProperties;
8224 // public $xxx properties
8225 if (publicGetter) {
8226 if (key === '$attrs') {
8227 track(instance, "get" /* GET */, key);
8228 markAttrsAccessed();
8229 }
8230 return publicGetter(instance);
8231 }
8232 else if (
8233 // css module (injected by vue-loader)
8234 (cssModule = type.__cssModules) &&
8235 (cssModule = cssModule[key])) {
8236 return cssModule;
8237 }
8238 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
8239 // user may set custom properties to `this` that start with `$`
8240 accessCache[key] = 4 /* CONTEXT */;
8241 return ctx[key];
8242 }
8243 else if (
8244 // global properties
8245 ((globalProperties = appContext.config.globalProperties),
8246 hasOwn(globalProperties, key))) {
8247 {
8248 return globalProperties[key];
8249 }
8250 }
8251 else if (currentRenderingInstance &&
8252 (!isString(key) ||
8253 // #1091 avoid internal isRef/isVNode checks on component instance leading
8254 // to infinite warning loop
8255 key.indexOf('__v') !== 0)) {
8256 if (data !== EMPTY_OBJ &&
8257 (key[0] === '$' || key[0] === '_') &&
8258 hasOwn(data, key)) {
8259 warn$1(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
8260 `character ("$" or "_") and is not proxied on the render context.`);
8261 }
8262 else if (instance === currentRenderingInstance) {
8263 warn$1(`Property ${JSON.stringify(key)} was accessed during render ` +
8264 `but is not defined on instance.`);
8265 }
8266 }
8267 },
8268 set({ _: instance }, key, value) {
8269 const { data, setupState, ctx } = instance;
8270 if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
8271 setupState[key] = value;
8272 return true;
8273 }
8274 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
8275 data[key] = value;
8276 return true;
8277 }
8278 else if (hasOwn(instance.props, key)) {
8279 warn$1(`Attempting to mutate prop "${key}". Props are readonly.`, instance);
8280 return false;
8281 }
8282 if (key[0] === '$' && key.slice(1) in instance) {
8283 warn$1(`Attempting to mutate public property "${key}". ` +
8284 `Properties starting with $ are reserved and readonly.`, instance);
8285 return false;
8286 }
8287 else {
8288 if (key in instance.appContext.config.globalProperties) {
8289 Object.defineProperty(ctx, key, {
8290 enumerable: true,
8291 configurable: true,
8292 value
8293 });
8294 }
8295 else {
8296 ctx[key] = value;
8297 }
8298 }
8299 return true;
8300 },
8301 has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
8302 let normalizedProps;
8303 return (!!accessCache[key] ||
8304 (data !== EMPTY_OBJ && hasOwn(data, key)) ||
8305 (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
8306 ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
8307 hasOwn(ctx, key) ||
8308 hasOwn(publicPropertiesMap, key) ||
8309 hasOwn(appContext.config.globalProperties, key));
8310 },
8311 defineProperty(target, key, descriptor) {
8312 if (descriptor.get != null) {
8313 // invalidate key cache of a getter based property #5417
8314 target._.accessCache[key] = 0;
8315 }
8316 else if (hasOwn(descriptor, 'value')) {
8317 this.set(target, key, descriptor.value, null);
8318 }
8319 return Reflect.defineProperty(target, key, descriptor);
8320 }
8321};
8322{
8323 PublicInstanceProxyHandlers.ownKeys = (target) => {
8324 warn$1(`Avoid app logic that relies on enumerating keys on a component instance. ` +
8325 `The keys will be empty in production mode to avoid performance overhead.`);
8326 return Reflect.ownKeys(target);
8327 };
8328}
8329const RuntimeCompiledPublicInstanceProxyHandlers = /*#__PURE__*/ extend({}, PublicInstanceProxyHandlers, {
8330 get(target, key) {
8331 // fast path for unscopables when using `with` block
8332 if (key === Symbol.unscopables) {
8333 return;
8334 }
8335 return PublicInstanceProxyHandlers.get(target, key, target);
8336 },
8337 has(_, key) {
8338 const has = key[0] !== '_' && !isGloballyWhitelisted(key);
8339 if (!has && PublicInstanceProxyHandlers.has(_, key)) {
8340 warn$1(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
8341 }
8342 return has;
8343 }
8344});
8345// dev only
8346// In dev mode, the proxy target exposes the same properties as seen on `this`
8347// for easier console inspection. In prod mode it will be an empty object so
8348// these properties definitions can be skipped.
8349function createDevRenderContext(instance) {
8350 const target = {};
8351 // expose internal instance for proxy handlers
8352 Object.defineProperty(target, `_`, {
8353 configurable: true,
8354 enumerable: false,
8355 get: () => instance
8356 });
8357 // expose public properties
8358 Object.keys(publicPropertiesMap).forEach(key => {
8359 Object.defineProperty(target, key, {
8360 configurable: true,
8361 enumerable: false,
8362 get: () => publicPropertiesMap[key](instance),
8363 // intercepted by the proxy so no need for implementation,
8364 // but needed to prevent set errors
8365 set: NOOP
8366 });
8367 });
8368 return target;
8369}
8370// dev only
8371function exposePropsOnRenderContext(instance) {
8372 const { ctx, propsOptions: [propsOptions] } = instance;
8373 if (propsOptions) {
8374 Object.keys(propsOptions).forEach(key => {
8375 Object.defineProperty(ctx, key, {
8376 enumerable: true,
8377 configurable: true,
8378 get: () => instance.props[key],
8379 set: NOOP
8380 });
8381 });
8382 }
8383}
8384// dev only
8385function exposeSetupStateOnRenderContext(instance) {
8386 const { ctx, setupState } = instance;
8387 Object.keys(toRaw(setupState)).forEach(key => {
8388 if (!setupState.__isScriptSetup) {
8389 if (key[0] === '$' || key[0] === '_') {
8390 warn$1(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
8391 `which are reserved prefixes for Vue internals.`);
8392 return;
8393 }
8394 Object.defineProperty(ctx, key, {
8395 enumerable: true,
8396 configurable: true,
8397 get: () => setupState[key],
8398 set: NOOP
8399 });
8400 }
8401 });
8402}
8403
8404const emptyAppContext = createAppContext();
8405let uid$1 = 0;
8406function createComponentInstance(vnode, parent, suspense) {
8407 const type = vnode.type;
8408 // inherit parent app context - or - if root, adopt from root vnode
8409 const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
8410 const instance = {
8411 uid: uid$1++,
8412 vnode,
8413 type,
8414 parent,
8415 appContext,
8416 root: null,
8417 next: null,
8418 subTree: null,
8419 effect: null,
8420 update: null,
8421 scope: new EffectScope(true /* detached */),
8422 render: null,
8423 proxy: null,
8424 exposed: null,
8425 exposeProxy: null,
8426 withProxy: null,
8427 provides: parent ? parent.provides : Object.create(appContext.provides),
8428 accessCache: null,
8429 renderCache: [],
8430 // local resovled assets
8431 components: null,
8432 directives: null,
8433 // resolved props and emits options
8434 propsOptions: normalizePropsOptions(type, appContext),
8435 emitsOptions: normalizeEmitsOptions(type, appContext),
8436 // emit
8437 emit: null,
8438 emitted: null,
8439 // props default value
8440 propsDefaults: EMPTY_OBJ,
8441 // inheritAttrs
8442 inheritAttrs: type.inheritAttrs,
8443 // state
8444 ctx: EMPTY_OBJ,
8445 data: EMPTY_OBJ,
8446 props: EMPTY_OBJ,
8447 attrs: EMPTY_OBJ,
8448 slots: EMPTY_OBJ,
8449 refs: EMPTY_OBJ,
8450 setupState: EMPTY_OBJ,
8451 setupContext: null,
8452 // suspense related
8453 suspense,
8454 suspenseId: suspense ? suspense.pendingId : 0,
8455 asyncDep: null,
8456 asyncResolved: false,
8457 // lifecycle hooks
8458 // not using enums here because it results in computed properties
8459 isMounted: false,
8460 isUnmounted: false,
8461 isDeactivated: false,
8462 bc: null,
8463 c: null,
8464 bm: null,
8465 m: null,
8466 bu: null,
8467 u: null,
8468 um: null,
8469 bum: null,
8470 da: null,
8471 a: null,
8472 rtg: null,
8473 rtc: null,
8474 ec: null,
8475 sp: null
8476 };
8477 {
8478 instance.ctx = createDevRenderContext(instance);
8479 }
8480 instance.root = parent ? parent.root : instance;
8481 instance.emit = emit$1.bind(null, instance);
8482 // apply custom element special handling
8483 if (vnode.ce) {
8484 vnode.ce(instance);
8485 }
8486 return instance;
8487}
8488let currentInstance = null;
8489const getCurrentInstance = () => currentInstance || currentRenderingInstance;
8490const setCurrentInstance = (instance) => {
8491 currentInstance = instance;
8492 instance.scope.on();
8493};
8494const unsetCurrentInstance = () => {
8495 currentInstance && currentInstance.scope.off();
8496 currentInstance = null;
8497};
8498const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
8499function validateComponentName(name, config) {
8500 const appIsNativeTag = config.isNativeTag || NO;
8501 if (isBuiltInTag(name) || appIsNativeTag(name)) {
8502 warn$1('Do not use built-in or reserved HTML elements as component id: ' + name);
8503 }
8504}
8505function isStatefulComponent(instance) {
8506 return instance.vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */;
8507}
8508let isInSSRComponentSetup = false;
8509function setupComponent(instance, isSSR = false) {
8510 isInSSRComponentSetup = isSSR;
8511 const { props, children } = instance.vnode;
8512 const isStateful = isStatefulComponent(instance);
8513 initProps(instance, props, isStateful, isSSR);
8514 initSlots(instance, children);
8515 const setupResult = isStateful
8516 ? setupStatefulComponent(instance, isSSR)
8517 : undefined;
8518 isInSSRComponentSetup = false;
8519 return setupResult;
8520}
8521function setupStatefulComponent(instance, isSSR) {
8522 var _a;
8523 const Component = instance.type;
8524 {
8525 if (Component.name) {
8526 validateComponentName(Component.name, instance.appContext.config);
8527 }
8528 if (Component.components) {
8529 const names = Object.keys(Component.components);
8530 for (let i = 0; i < names.length; i++) {
8531 validateComponentName(names[i], instance.appContext.config);
8532 }
8533 }
8534 if (Component.directives) {
8535 const names = Object.keys(Component.directives);
8536 for (let i = 0; i < names.length; i++) {
8537 validateDirectiveName(names[i]);
8538 }
8539 }
8540 if (Component.compilerOptions && isRuntimeOnly()) {
8541 warn$1(`"compilerOptions" is only supported when using a build of Vue that ` +
8542 `includes the runtime compiler. Since you are using a runtime-only ` +
8543 `build, the options should be passed via your build tool config instead.`);
8544 }
8545 }
8546 // 0. create render proxy property access cache
8547 instance.accessCache = Object.create(null);
8548 // 1. create public instance / render proxy
8549 // also mark it raw so it's never observed
8550 instance.proxy = markRaw(new Proxy(instance.ctx, PublicInstanceProxyHandlers));
8551 {
8552 exposePropsOnRenderContext(instance);
8553 }
8554 // 2. call setup()
8555 const { setup } = Component;
8556 if (setup) {
8557 const setupContext = (instance.setupContext =
8558 setup.length > 1 ? createSetupContext(instance) : null);
8559 setCurrentInstance(instance);
8560 pauseTracking();
8561 const setupResult = callWithErrorHandling(setup, instance, 0 /* SETUP_FUNCTION */, [shallowReadonly(instance.props) , setupContext]);
8562 resetTracking();
8563 unsetCurrentInstance();
8564 if (isPromise(setupResult)) {
8565 setupResult.then(unsetCurrentInstance, unsetCurrentInstance);
8566 if (isSSR) {
8567 // return the promise so server-renderer can wait on it
8568 return setupResult
8569 .then((resolvedResult) => {
8570 handleSetupResult(instance, resolvedResult, isSSR);
8571 })
8572 .catch(e => {
8573 handleError(e, instance, 0 /* SETUP_FUNCTION */);
8574 });
8575 }
8576 else {
8577 // async setup returned Promise.
8578 // bail here and wait for re-entry.
8579 instance.asyncDep = setupResult;
8580 if (!instance.suspense) {
8581 const name = (_a = Component.name) !== null && _a !== void 0 ? _a : 'Anonymous';
8582 warn$1(`Component <${name}>: setup function returned a promise, but no ` +
8583 `<Suspense> boundary was found in the parent component tree. ` +
8584 `A component with async setup() must be nested in a <Suspense> ` +
8585 `in order to be rendered.`);
8586 }
8587 }
8588 }
8589 else {
8590 handleSetupResult(instance, setupResult, isSSR);
8591 }
8592 }
8593 else {
8594 finishComponentSetup(instance, isSSR);
8595 }
8596}
8597function handleSetupResult(instance, setupResult, isSSR) {
8598 if (isFunction(setupResult)) {
8599 // setup returned an inline render function
8600 {
8601 instance.render = setupResult;
8602 }
8603 }
8604 else if (isObject(setupResult)) {
8605 if (isVNode(setupResult)) {
8606 warn$1(`setup() should not return VNodes directly - ` +
8607 `return a render function instead.`);
8608 }
8609 // setup returned bindings.
8610 // assuming a render function compiled from template is present.
8611 {
8612 instance.devtoolsRawSetupState = setupResult;
8613 }
8614 instance.setupState = proxyRefs(setupResult);
8615 {
8616 exposeSetupStateOnRenderContext(instance);
8617 }
8618 }
8619 else if (setupResult !== undefined) {
8620 warn$1(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
8621 }
8622 finishComponentSetup(instance, isSSR);
8623}
8624let compile;
8625let installWithProxy;
8626/**
8627 * For runtime-dom to register the compiler.
8628 * Note the exported method uses any to avoid d.ts relying on the compiler types.
8629 */
8630function registerRuntimeCompiler(_compile) {
8631 compile = _compile;
8632 installWithProxy = i => {
8633 if (i.render._rc) {
8634 i.withProxy = new Proxy(i.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
8635 }
8636 };
8637}
8638// dev only
8639const isRuntimeOnly = () => !compile;
8640function finishComponentSetup(instance, isSSR, skipOptions) {
8641 const Component = instance.type;
8642 // template / render function normalization
8643 // could be already set when returned from setup()
8644 if (!instance.render) {
8645 // only do on-the-fly compile if not in SSR - SSR on-the-fly compilation
8646 // is done by server-renderer
8647 if (!isSSR && compile && !Component.render) {
8648 const template = Component.template;
8649 if (template) {
8650 {
8651 startMeasure(instance, `compile`);
8652 }
8653 const { isCustomElement, compilerOptions } = instance.appContext.config;
8654 const { delimiters, compilerOptions: componentCompilerOptions } = Component;
8655 const finalCompilerOptions = extend(extend({
8656 isCustomElement,
8657 delimiters
8658 }, compilerOptions), componentCompilerOptions);
8659 Component.render = compile(template, finalCompilerOptions);
8660 {
8661 endMeasure(instance, `compile`);
8662 }
8663 }
8664 }
8665 instance.render = (Component.render || NOOP);
8666 // for runtime-compiled render functions using `with` blocks, the render
8667 // proxy used needs a different `has` handler which is more performant and
8668 // also only allows a whitelist of globals to fallthrough.
8669 if (installWithProxy) {
8670 installWithProxy(instance);
8671 }
8672 }
8673 // support for 2.x options
8674 {
8675 setCurrentInstance(instance);
8676 pauseTracking();
8677 applyOptions(instance);
8678 resetTracking();
8679 unsetCurrentInstance();
8680 }
8681 // warn missing template/render
8682 // the runtime compilation of template in SSR is done by server-render
8683 if (!Component.render && instance.render === NOOP && !isSSR) {
8684 /* istanbul ignore if */
8685 if (!compile && Component.template) {
8686 warn$1(`Component provided template option but ` +
8687 `runtime compilation is not supported in this build of Vue.` +
8688 (` Use "vue.esm-browser.js" instead.`
8689 ) /* should not happen */);
8690 }
8691 else {
8692 warn$1(`Component is missing template or render function.`);
8693 }
8694 }
8695}
8696function createAttrsProxy(instance) {
8697 return new Proxy(instance.attrs, {
8698 get(target, key) {
8699 markAttrsAccessed();
8700 track(instance, "get" /* GET */, '$attrs');
8701 return target[key];
8702 },
8703 set() {
8704 warn$1(`setupContext.attrs is readonly.`);
8705 return false;
8706 },
8707 deleteProperty() {
8708 warn$1(`setupContext.attrs is readonly.`);
8709 return false;
8710 }
8711 }
8712 );
8713}
8714function createSetupContext(instance) {
8715 const expose = exposed => {
8716 if (instance.exposed) {
8717 warn$1(`expose() should be called only once per setup().`);
8718 }
8719 instance.exposed = exposed || {};
8720 };
8721 let attrs;
8722 {
8723 // We use getters in dev in case libs like test-utils overwrite instance
8724 // properties (overwrites should not be done in prod)
8725 return Object.freeze({
8726 get attrs() {
8727 return attrs || (attrs = createAttrsProxy(instance));
8728 },
8729 get slots() {
8730 return shallowReadonly(instance.slots);
8731 },
8732 get emit() {
8733 return (event, ...args) => instance.emit(event, ...args);
8734 },
8735 expose
8736 });
8737 }
8738}
8739function getExposeProxy(instance) {
8740 if (instance.exposed) {
8741 return (instance.exposeProxy ||
8742 (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), {
8743 get(target, key) {
8744 if (key in target) {
8745 return target[key];
8746 }
8747 else if (key in publicPropertiesMap) {
8748 return publicPropertiesMap[key](instance);
8749 }
8750 }
8751 })));
8752 }
8753}
8754const classifyRE = /(?:^|[-_])(\w)/g;
8755const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
8756function getComponentName(Component) {
8757 return isFunction(Component)
8758 ? Component.displayName || Component.name
8759 : Component.name;
8760}
8761/* istanbul ignore next */
8762function formatComponentName(instance, Component, isRoot = false) {
8763 let name = getComponentName(Component);
8764 if (!name && Component.__file) {
8765 const match = Component.__file.match(/([^/\\]+)\.\w+$/);
8766 if (match) {
8767 name = match[1];
8768 }
8769 }
8770 if (!name && instance && instance.parent) {
8771 // try to infer the name based on reverse resolution
8772 const inferFromRegistry = (registry) => {
8773 for (const key in registry) {
8774 if (registry[key] === Component) {
8775 return key;
8776 }
8777 }
8778 };
8779 name =
8780 inferFromRegistry(instance.components ||
8781 instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
8782 }
8783 return name ? classify(name) : isRoot ? `App` : `Anonymous`;
8784}
8785function isClassComponent(value) {
8786 return isFunction(value) && '__vccOpts' in value;
8787}
8788
8789const computed$1 = ((getterOrOptions, debugOptions) => {
8790 // @ts-ignore
8791 return computed(getterOrOptions, debugOptions, isInSSRComponentSetup);
8792});
8793
8794// dev only
8795const warnRuntimeUsage = (method) => warn$1(`${method}() is a compiler-hint helper that is only usable inside ` +
8796 `<script setup> of a single file component. Its arguments should be ` +
8797 `compiled away and passing it at runtime has no effect.`);
8798// implementation
8799function defineProps() {
8800 {
8801 warnRuntimeUsage(`defineProps`);
8802 }
8803 return null;
8804}
8805// implementation
8806function defineEmits() {
8807 {
8808 warnRuntimeUsage(`defineEmits`);
8809 }
8810 return null;
8811}
8812/**
8813 * Vue `<script setup>` compiler macro for declaring a component's exposed
8814 * instance properties when it is accessed by a parent component via template
8815 * refs.
8816 *
8817 * `<script setup>` components are closed by default - i.e. variables inside
8818 * the `<script setup>` scope is not exposed to parent unless explicitly exposed
8819 * via `defineExpose`.
8820 *
8821 * This is only usable inside `<script setup>`, is compiled away in the
8822 * output and should **not** be actually called at runtime.
8823 */
8824function defineExpose(exposed) {
8825 {
8826 warnRuntimeUsage(`defineExpose`);
8827 }
8828}
8829/**
8830 * Vue `<script setup>` compiler macro for providing props default values when
8831 * using type-based `defineProps` declaration.
8832 *
8833 * Example usage:
8834 * ```ts
8835 * withDefaults(defineProps<{
8836 * size?: number
8837 * labels?: string[]
8838 * }>(), {
8839 * size: 3,
8840 * labels: () => ['default label']
8841 * })
8842 * ```
8843 *
8844 * This is only usable inside `<script setup>`, is compiled away in the output
8845 * and should **not** be actually called at runtime.
8846 */
8847function withDefaults(props, defaults) {
8848 {
8849 warnRuntimeUsage(`withDefaults`);
8850 }
8851 return null;
8852}
8853function useSlots() {
8854 return getContext().slots;
8855}
8856function useAttrs() {
8857 return getContext().attrs;
8858}
8859function getContext() {
8860 const i = getCurrentInstance();
8861 if (!i) {
8862 warn$1(`useContext() called without active instance.`);
8863 }
8864 return i.setupContext || (i.setupContext = createSetupContext(i));
8865}
8866/**
8867 * Runtime helper for merging default declarations. Imported by compiled code
8868 * only.
8869 * @internal
8870 */
8871function mergeDefaults(raw, defaults) {
8872 const props = isArray(raw)
8873 ? raw.reduce((normalized, p) => ((normalized[p] = {}), normalized), {})
8874 : raw;
8875 for (const key in defaults) {
8876 const opt = props[key];
8877 if (opt) {
8878 if (isArray(opt) || isFunction(opt)) {
8879 props[key] = { type: opt, default: defaults[key] };
8880 }
8881 else {
8882 opt.default = defaults[key];
8883 }
8884 }
8885 else if (opt === null) {
8886 props[key] = { default: defaults[key] };
8887 }
8888 else {
8889 warn$1(`props default key "${key}" has no corresponding declaration.`);
8890 }
8891 }
8892 return props;
8893}
8894/**
8895 * Used to create a proxy for the rest element when destructuring props with
8896 * defineProps().
8897 * @internal
8898 */
8899function createPropsRestProxy(props, excludedKeys) {
8900 const ret = {};
8901 for (const key in props) {
8902 if (!excludedKeys.includes(key)) {
8903 Object.defineProperty(ret, key, {
8904 enumerable: true,
8905 get: () => props[key]
8906 });
8907 }
8908 }
8909 return ret;
8910}
8911/**
8912 * `<script setup>` helper for persisting the current instance context over
8913 * async/await flows.
8914 *
8915 * `@vue/compiler-sfc` converts the following:
8916 *
8917 * ```ts
8918 * const x = await foo()
8919 * ```
8920 *
8921 * into:
8922 *
8923 * ```ts
8924 * let __temp, __restore
8925 * const x = (([__temp, __restore] = withAsyncContext(() => foo())),__temp=await __temp,__restore(),__temp)
8926 * ```
8927 * @internal
8928 */
8929function withAsyncContext(getAwaitable) {
8930 const ctx = getCurrentInstance();
8931 if (!ctx) {
8932 warn$1(`withAsyncContext called without active current instance. ` +
8933 `This is likely a bug.`);
8934 }
8935 let awaitable = getAwaitable();
8936 unsetCurrentInstance();
8937 if (isPromise(awaitable)) {
8938 awaitable = awaitable.catch(e => {
8939 setCurrentInstance(ctx);
8940 throw e;
8941 });
8942 }
8943 return [awaitable, () => setCurrentInstance(ctx)];
8944}
8945
8946// Actual implementation
8947function h(type, propsOrChildren, children) {
8948 const l = arguments.length;
8949 if (l === 2) {
8950 if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
8951 // single vnode without props
8952 if (isVNode(propsOrChildren)) {
8953 return createVNode(type, null, [propsOrChildren]);
8954 }
8955 // props without children
8956 return createVNode(type, propsOrChildren);
8957 }
8958 else {
8959 // omit props
8960 return createVNode(type, null, propsOrChildren);
8961 }
8962 }
8963 else {
8964 if (l > 3) {
8965 children = Array.prototype.slice.call(arguments, 2);
8966 }
8967 else if (l === 3 && isVNode(children)) {
8968 children = [children];
8969 }
8970 return createVNode(type, propsOrChildren, children);
8971 }
8972}
8973
8974const ssrContextKey = Symbol(`ssrContext` );
8975const useSSRContext = () => {
8976 {
8977 const ctx = inject(ssrContextKey);
8978 if (!ctx) {
8979 warn$1(`Server rendering context not provided. Make sure to only call ` +
8980 `useSSRContext() conditionally in the server build.`);
8981 }
8982 return ctx;
8983 }
8984};
8985
8986function initCustomFormatter() {
8987 /* eslint-disable no-restricted-globals */
8988 if (typeof window === 'undefined') {
8989 return;
8990 }
8991 const vueStyle = { style: 'color:#3ba776' };
8992 const numberStyle = { style: 'color:#0b1bc9' };
8993 const stringStyle = { style: 'color:#b62e24' };
8994 const keywordStyle = { style: 'color:#9d288c' };
8995 // custom formatter for Chrome
8996 // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
8997 const formatter = {
8998 header(obj) {
8999 // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
9000 if (!isObject(obj)) {
9001 return null;
9002 }
9003 if (obj.__isVue) {
9004 return ['div', vueStyle, `VueInstance`];
9005 }
9006 else if (isRef(obj)) {
9007 return [
9008 'div',
9009 {},
9010 ['span', vueStyle, genRefFlag(obj)],
9011 '<',
9012 formatValue(obj.value),
9013 `>`
9014 ];
9015 }
9016 else if (isReactive(obj)) {
9017 return [
9018 'div',
9019 {},
9020 ['span', vueStyle, isShallow(obj) ? 'ShallowReactive' : 'Reactive'],
9021 '<',
9022 formatValue(obj),
9023 `>${isReadonly(obj) ? ` (readonly)` : ``}`
9024 ];
9025 }
9026 else if (isReadonly(obj)) {
9027 return [
9028 'div',
9029 {},
9030 ['span', vueStyle, isShallow(obj) ? 'ShallowReadonly' : 'Readonly'],
9031 '<',
9032 formatValue(obj),
9033 '>'
9034 ];
9035 }
9036 return null;
9037 },
9038 hasBody(obj) {
9039 return obj && obj.__isVue;
9040 },
9041 body(obj) {
9042 if (obj && obj.__isVue) {
9043 return [
9044 'div',
9045 {},
9046 ...formatInstance(obj.$)
9047 ];
9048 }
9049 }
9050 };
9051 function formatInstance(instance) {
9052 const blocks = [];
9053 if (instance.type.props && instance.props) {
9054 blocks.push(createInstanceBlock('props', toRaw(instance.props)));
9055 }
9056 if (instance.setupState !== EMPTY_OBJ) {
9057 blocks.push(createInstanceBlock('setup', instance.setupState));
9058 }
9059 if (instance.data !== EMPTY_OBJ) {
9060 blocks.push(createInstanceBlock('data', toRaw(instance.data)));
9061 }
9062 const computed = extractKeys(instance, 'computed');
9063 if (computed) {
9064 blocks.push(createInstanceBlock('computed', computed));
9065 }
9066 const injected = extractKeys(instance, 'inject');
9067 if (injected) {
9068 blocks.push(createInstanceBlock('injected', injected));
9069 }
9070 blocks.push([
9071 'div',
9072 {},
9073 [
9074 'span',
9075 {
9076 style: keywordStyle.style + ';opacity:0.66'
9077 },
9078 '$ (internal): '
9079 ],
9080 ['object', { object: instance }]
9081 ]);
9082 return blocks;
9083 }
9084 function createInstanceBlock(type, target) {
9085 target = extend({}, target);
9086 if (!Object.keys(target).length) {
9087 return ['span', {}];
9088 }
9089 return [
9090 'div',
9091 { style: 'line-height:1.25em;margin-bottom:0.6em' },
9092 [
9093 'div',
9094 {
9095 style: 'color:#476582'
9096 },
9097 type
9098 ],
9099 [
9100 'div',
9101 {
9102 style: 'padding-left:1.25em'
9103 },
9104 ...Object.keys(target).map(key => {
9105 return [
9106 'div',
9107 {},
9108 ['span', keywordStyle, key + ': '],
9109 formatValue(target[key], false)
9110 ];
9111 })
9112 ]
9113 ];
9114 }
9115 function formatValue(v, asRaw = true) {
9116 if (typeof v === 'number') {
9117 return ['span', numberStyle, v];
9118 }
9119 else if (typeof v === 'string') {
9120 return ['span', stringStyle, JSON.stringify(v)];
9121 }
9122 else if (typeof v === 'boolean') {
9123 return ['span', keywordStyle, v];
9124 }
9125 else if (isObject(v)) {
9126 return ['object', { object: asRaw ? toRaw(v) : v }];
9127 }
9128 else {
9129 return ['span', stringStyle, String(v)];
9130 }
9131 }
9132 function extractKeys(instance, type) {
9133 const Comp = instance.type;
9134 if (isFunction(Comp)) {
9135 return;
9136 }
9137 const extracted = {};
9138 for (const key in instance.ctx) {
9139 if (isKeyOfType(Comp, key, type)) {
9140 extracted[key] = instance.ctx[key];
9141 }
9142 }
9143 return extracted;
9144 }
9145 function isKeyOfType(Comp, key, type) {
9146 const opts = Comp[type];
9147 if ((isArray(opts) && opts.includes(key)) ||
9148 (isObject(opts) && key in opts)) {
9149 return true;
9150 }
9151 if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
9152 return true;
9153 }
9154 if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
9155 return true;
9156 }
9157 }
9158 function genRefFlag(v) {
9159 if (isShallow(v)) {
9160 return `ShallowRef`;
9161 }
9162 if (v.effect) {
9163 return `ComputedRef`;
9164 }
9165 return `Ref`;
9166 }
9167 if (window.devtoolsFormatters) {
9168 window.devtoolsFormatters.push(formatter);
9169 }
9170 else {
9171 window.devtoolsFormatters = [formatter];
9172 }
9173}
9174
9175function withMemo(memo, render, cache, index) {
9176 const cached = cache[index];
9177 if (cached && isMemoSame(cached, memo)) {
9178 return cached;
9179 }
9180 const ret = render();
9181 // shallow clone
9182 ret.memo = memo.slice();
9183 return (cache[index] = ret);
9184}
9185function isMemoSame(cached, memo) {
9186 const prev = cached.memo;
9187 if (prev.length != memo.length) {
9188 return false;
9189 }
9190 for (let i = 0; i < prev.length; i++) {
9191 if (prev[i] !== memo[i]) {
9192 return false;
9193 }
9194 }
9195 // make sure to let parent block track it when returning cached
9196 if (isBlockTreeEnabled > 0 && currentBlock) {
9197 currentBlock.push(cached);
9198 }
9199 return true;
9200}
9201
9202// Core API ------------------------------------------------------------------
9203const version = "3.2.33";
9204/**
9205 * SSR utils for \@vue/server-renderer. Only exposed in cjs builds.
9206 * @internal
9207 */
9208const ssrUtils = (null);
9209/**
9210 * @internal only exposed in compat builds
9211 */
9212const resolveFilter = null;
9213/**
9214 * @internal only exposed in compat builds.
9215 */
9216const compatUtils = (null);
9217
9218const svgNS = 'http://www.w3.org/2000/svg';
9219const doc = (typeof document !== 'undefined' ? document : null);
9220const templateContainer = doc && /*#__PURE__*/ doc.createElement('template');
9221const nodeOps = {
9222 insert: (child, parent, anchor) => {
9223 parent.insertBefore(child, anchor || null);
9224 },
9225 remove: child => {
9226 const parent = child.parentNode;
9227 if (parent) {
9228 parent.removeChild(child);
9229 }
9230 },
9231 createElement: (tag, isSVG, is, props) => {
9232 const el = isSVG
9233 ? doc.createElementNS(svgNS, tag)
9234 : doc.createElement(tag, is ? { is } : undefined);
9235 if (tag === 'select' && props && props.multiple != null) {
9236 el.setAttribute('multiple', props.multiple);
9237 }
9238 return el;
9239 },
9240 createText: text => doc.createTextNode(text),
9241 createComment: text => doc.createComment(text),
9242 setText: (node, text) => {
9243 node.nodeValue = text;
9244 },
9245 setElementText: (el, text) => {
9246 el.textContent = text;
9247 },
9248 parentNode: node => node.parentNode,
9249 nextSibling: node => node.nextSibling,
9250 querySelector: selector => doc.querySelector(selector),
9251 setScopeId(el, id) {
9252 el.setAttribute(id, '');
9253 },
9254 cloneNode(el) {
9255 const cloned = el.cloneNode(true);
9256 // #3072
9257 // - in `patchDOMProp`, we store the actual value in the `el._value` property.
9258 // - normally, elements using `:value` bindings will not be hoisted, but if
9259 // the bound value is a constant, e.g. `:value="true"` - they do get
9260 // hoisted.
9261 // - in production, hoisted nodes are cloned when subsequent inserts, but
9262 // cloneNode() does not copy the custom property we attached.
9263 // - This may need to account for other custom DOM properties we attach to
9264 // elements in addition to `_value` in the future.
9265 if (`_value` in el) {
9266 cloned._value = el._value;
9267 }
9268 return cloned;
9269 },
9270 // __UNSAFE__
9271 // Reason: innerHTML.
9272 // Static content here can only come from compiled templates.
9273 // As long as the user only uses trusted templates, this is safe.
9274 insertStaticContent(content, parent, anchor, isSVG, start, end) {
9275 // <parent> before | first ... last | anchor </parent>
9276 const before = anchor ? anchor.previousSibling : parent.lastChild;
9277 // #5308 can only take cached path if:
9278 // - has a single root node
9279 // - nextSibling info is still available
9280 if (start && (start === end || start.nextSibling)) {
9281 // cached
9282 while (true) {
9283 parent.insertBefore(start.cloneNode(true), anchor);
9284 if (start === end || !(start = start.nextSibling))
9285 break;
9286 }
9287 }
9288 else {
9289 // fresh insert
9290 templateContainer.innerHTML = isSVG ? `<svg>${content}</svg>` : content;
9291 const template = templateContainer.content;
9292 if (isSVG) {
9293 // remove outer svg wrapper
9294 const wrapper = template.firstChild;
9295 while (wrapper.firstChild) {
9296 template.appendChild(wrapper.firstChild);
9297 }
9298 template.removeChild(wrapper);
9299 }
9300 parent.insertBefore(template, anchor);
9301 }
9302 return [
9303 // first
9304 before ? before.nextSibling : parent.firstChild,
9305 // last
9306 anchor ? anchor.previousSibling : parent.lastChild
9307 ];
9308 }
9309};
9310
9311// compiler should normalize class + :class bindings on the same element
9312// into a single binding ['staticClass', dynamic]
9313function patchClass(el, value, isSVG) {
9314 // directly setting className should be faster than setAttribute in theory
9315 // if this is an element during a transition, take the temporary transition
9316 // classes into account.
9317 const transitionClasses = el._vtc;
9318 if (transitionClasses) {
9319 value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(' ');
9320 }
9321 if (value == null) {
9322 el.removeAttribute('class');
9323 }
9324 else if (isSVG) {
9325 el.setAttribute('class', value);
9326 }
9327 else {
9328 el.className = value;
9329 }
9330}
9331
9332function patchStyle(el, prev, next) {
9333 const style = el.style;
9334 const isCssString = isString(next);
9335 if (next && !isCssString) {
9336 for (const key in next) {
9337 setStyle(style, key, next[key]);
9338 }
9339 if (prev && !isString(prev)) {
9340 for (const key in prev) {
9341 if (next[key] == null) {
9342 setStyle(style, key, '');
9343 }
9344 }
9345 }
9346 }
9347 else {
9348 const currentDisplay = style.display;
9349 if (isCssString) {
9350 if (prev !== next) {
9351 style.cssText = next;
9352 }
9353 }
9354 else if (prev) {
9355 el.removeAttribute('style');
9356 }
9357 // indicates that the `display` of the element is controlled by `v-show`,
9358 // so we always keep the current `display` value regardless of the `style`
9359 // value, thus handing over control to `v-show`.
9360 if ('_vod' in el) {
9361 style.display = currentDisplay;
9362 }
9363 }
9364}
9365const importantRE = /\s*!important$/;
9366function setStyle(style, name, val) {
9367 if (isArray(val)) {
9368 val.forEach(v => setStyle(style, name, v));
9369 }
9370 else {
9371 if (val == null)
9372 val = '';
9373 if (name.startsWith('--')) {
9374 // custom property definition
9375 style.setProperty(name, val);
9376 }
9377 else {
9378 const prefixed = autoPrefix(style, name);
9379 if (importantRE.test(val)) {
9380 // !important
9381 style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
9382 }
9383 else {
9384 style[prefixed] = val;
9385 }
9386 }
9387 }
9388}
9389const prefixes = ['Webkit', 'Moz', 'ms'];
9390const prefixCache = {};
9391function autoPrefix(style, rawName) {
9392 const cached = prefixCache[rawName];
9393 if (cached) {
9394 return cached;
9395 }
9396 let name = camelize(rawName);
9397 if (name !== 'filter' && name in style) {
9398 return (prefixCache[rawName] = name);
9399 }
9400 name = capitalize(name);
9401 for (let i = 0; i < prefixes.length; i++) {
9402 const prefixed = prefixes[i] + name;
9403 if (prefixed in style) {
9404 return (prefixCache[rawName] = prefixed);
9405 }
9406 }
9407 return rawName;
9408}
9409
9410const xlinkNS = 'http://www.w3.org/1999/xlink';
9411function patchAttr(el, key, value, isSVG, instance) {
9412 if (isSVG && key.startsWith('xlink:')) {
9413 if (value == null) {
9414 el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
9415 }
9416 else {
9417 el.setAttributeNS(xlinkNS, key, value);
9418 }
9419 }
9420 else {
9421 // note we are only checking boolean attributes that don't have a
9422 // corresponding dom prop of the same name here.
9423 const isBoolean = isSpecialBooleanAttr(key);
9424 if (value == null || (isBoolean && !includeBooleanAttr(value))) {
9425 el.removeAttribute(key);
9426 }
9427 else {
9428 el.setAttribute(key, isBoolean ? '' : value);
9429 }
9430 }
9431}
9432
9433// __UNSAFE__
9434// functions. The user is responsible for using them with only trusted content.
9435function patchDOMProp(el, key, value,
9436// the following args are passed only due to potential innerHTML/textContent
9437// overriding existing VNodes, in which case the old tree must be properly
9438// unmounted.
9439prevChildren, parentComponent, parentSuspense, unmountChildren) {
9440 if (key === 'innerHTML' || key === 'textContent') {
9441 if (prevChildren) {
9442 unmountChildren(prevChildren, parentComponent, parentSuspense);
9443 }
9444 el[key] = value == null ? '' : value;
9445 return;
9446 }
9447 if (key === 'value' &&
9448 el.tagName !== 'PROGRESS' &&
9449 // custom elements may use _value internally
9450 !el.tagName.includes('-')) {
9451 // store value as _value as well since
9452 // non-string values will be stringified.
9453 el._value = value;
9454 const newValue = value == null ? '' : value;
9455 if (el.value !== newValue ||
9456 // #4956: always set for OPTION elements because its value falls back to
9457 // textContent if no value attribute is present. And setting .value for
9458 // OPTION has no side effect
9459 el.tagName === 'OPTION') {
9460 el.value = newValue;
9461 }
9462 if (value == null) {
9463 el.removeAttribute(key);
9464 }
9465 return;
9466 }
9467 let needRemove = false;
9468 if (value === '' || value == null) {
9469 const type = typeof el[key];
9470 if (type === 'boolean') {
9471 // e.g. <select multiple> compiles to { multiple: '' }
9472 value = includeBooleanAttr(value);
9473 }
9474 else if (value == null && type === 'string') {
9475 // e.g. <div :id="null">
9476 value = '';
9477 needRemove = true;
9478 }
9479 else if (type === 'number') {
9480 // e.g. <img :width="null">
9481 // the value of some IDL attr must be greater than 0, e.g. input.size = 0 -> error
9482 value = 0;
9483 needRemove = true;
9484 }
9485 }
9486 // some properties perform value validation and throw,
9487 // some properties has getter, no setter, will error in 'use strict'
9488 // eg. <select :type="null"></select> <select :willValidate="null"></select>
9489 try {
9490 el[key] = value;
9491 }
9492 catch (e) {
9493 {
9494 warn$1(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
9495 `value ${value} is invalid.`, e);
9496 }
9497 }
9498 needRemove && el.removeAttribute(key);
9499}
9500
9501// Async edge case fix requires storing an event listener's attach timestamp.
9502const [_getNow, skipTimestampCheck] = /*#__PURE__*/ (() => {
9503 let _getNow = Date.now;
9504 let skipTimestampCheck = false;
9505 if (typeof window !== 'undefined') {
9506 // Determine what event timestamp the browser is using. Annoyingly, the
9507 // timestamp can either be hi-res (relative to page load) or low-res
9508 // (relative to UNIX epoch), so in order to compare time we have to use the
9509 // same timestamp type when saving the flush timestamp.
9510 if (Date.now() > document.createEvent('Event').timeStamp) {
9511 // if the low-res timestamp which is bigger than the event timestamp
9512 // (which is evaluated AFTER) it means the event is using a hi-res timestamp,
9513 // and we need to use the hi-res version for event listeners as well.
9514 _getNow = () => performance.now();
9515 }
9516 // #3485: Firefox <= 53 has incorrect Event.timeStamp implementation
9517 // and does not fire microtasks in between event propagation, so safe to exclude.
9518 const ffMatch = navigator.userAgent.match(/firefox\/(\d+)/i);
9519 skipTimestampCheck = !!(ffMatch && Number(ffMatch[1]) <= 53);
9520 }
9521 return [_getNow, skipTimestampCheck];
9522})();
9523// To avoid the overhead of repeatedly calling performance.now(), we cache
9524// and use the same timestamp for all event listeners attached in the same tick.
9525let cachedNow = 0;
9526const p = /*#__PURE__*/ Promise.resolve();
9527const reset = () => {
9528 cachedNow = 0;
9529};
9530const getNow = () => cachedNow || (p.then(reset), (cachedNow = _getNow()));
9531function addEventListener(el, event, handler, options) {
9532 el.addEventListener(event, handler, options);
9533}
9534function removeEventListener(el, event, handler, options) {
9535 el.removeEventListener(event, handler, options);
9536}
9537function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
9538 // vei = vue event invokers
9539 const invokers = el._vei || (el._vei = {});
9540 const existingInvoker = invokers[rawName];
9541 if (nextValue && existingInvoker) {
9542 // patch
9543 existingInvoker.value = nextValue;
9544 }
9545 else {
9546 const [name, options] = parseName(rawName);
9547 if (nextValue) {
9548 // add
9549 const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
9550 addEventListener(el, name, invoker, options);
9551 }
9552 else if (existingInvoker) {
9553 // remove
9554 removeEventListener(el, name, existingInvoker, options);
9555 invokers[rawName] = undefined;
9556 }
9557 }
9558}
9559const optionsModifierRE = /(?:Once|Passive|Capture)$/;
9560function parseName(name) {
9561 let options;
9562 if (optionsModifierRE.test(name)) {
9563 options = {};
9564 let m;
9565 while ((m = name.match(optionsModifierRE))) {
9566 name = name.slice(0, name.length - m[0].length);
9567 options[m[0].toLowerCase()] = true;
9568 }
9569 }
9570 return [hyphenate(name.slice(2)), options];
9571}
9572function createInvoker(initialValue, instance) {
9573 const invoker = (e) => {
9574 // async edge case #6566: inner click event triggers patch, event handler
9575 // attached to outer element during patch, and triggered again. This
9576 // happens because browsers fire microtask ticks between event propagation.
9577 // the solution is simple: we save the timestamp when a handler is attached,
9578 // and the handler would only fire if the event passed to it was fired
9579 // AFTER it was attached.
9580 const timeStamp = e.timeStamp || _getNow();
9581 if (skipTimestampCheck || timeStamp >= invoker.attached - 1) {
9582 callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* NATIVE_EVENT_HANDLER */, [e]);
9583 }
9584 };
9585 invoker.value = initialValue;
9586 invoker.attached = getNow();
9587 return invoker;
9588}
9589function patchStopImmediatePropagation(e, value) {
9590 if (isArray(value)) {
9591 const originalStop = e.stopImmediatePropagation;
9592 e.stopImmediatePropagation = () => {
9593 originalStop.call(e);
9594 e._stopped = true;
9595 };
9596 return value.map(fn => (e) => !e._stopped && fn && fn(e));
9597 }
9598 else {
9599 return value;
9600 }
9601}
9602
9603const nativeOnRE = /^on[a-z]/;
9604const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
9605 if (key === 'class') {
9606 patchClass(el, nextValue, isSVG);
9607 }
9608 else if (key === 'style') {
9609 patchStyle(el, prevValue, nextValue);
9610 }
9611 else if (isOn(key)) {
9612 // ignore v-model listeners
9613 if (!isModelListener(key)) {
9614 patchEvent(el, key, prevValue, nextValue, parentComponent);
9615 }
9616 }
9617 else if (key[0] === '.'
9618 ? ((key = key.slice(1)), true)
9619 : key[0] === '^'
9620 ? ((key = key.slice(1)), false)
9621 : shouldSetAsProp(el, key, nextValue, isSVG)) {
9622 patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
9623 }
9624 else {
9625 // special case for <input v-model type="checkbox"> with
9626 // :true-value & :false-value
9627 // store value as dom properties since non-string values will be
9628 // stringified.
9629 if (key === 'true-value') {
9630 el._trueValue = nextValue;
9631 }
9632 else if (key === 'false-value') {
9633 el._falseValue = nextValue;
9634 }
9635 patchAttr(el, key, nextValue, isSVG);
9636 }
9637};
9638function shouldSetAsProp(el, key, value, isSVG) {
9639 if (isSVG) {
9640 // most keys must be set as attribute on svg elements to work
9641 // ...except innerHTML & textContent
9642 if (key === 'innerHTML' || key === 'textContent') {
9643 return true;
9644 }
9645 // or native onclick with function values
9646 if (key in el && nativeOnRE.test(key) && isFunction(value)) {
9647 return true;
9648 }
9649 return false;
9650 }
9651 // these are enumerated attrs, however their corresponding DOM properties
9652 // are actually booleans - this leads to setting it with a string "false"
9653 // value leading it to be coerced to `true`, so we need to always treat
9654 // them as attributes.
9655 // Note that `contentEditable` doesn't have this problem: its DOM
9656 // property is also enumerated string values.
9657 if (key === 'spellcheck' || key === 'draggable' || key === 'translate') {
9658 return false;
9659 }
9660 // #1787, #2840 form property on form elements is readonly and must be set as
9661 // attribute.
9662 if (key === 'form') {
9663 return false;
9664 }
9665 // #1526 <input list> must be set as attribute
9666 if (key === 'list' && el.tagName === 'INPUT') {
9667 return false;
9668 }
9669 // #2766 <textarea type> must be set as attribute
9670 if (key === 'type' && el.tagName === 'TEXTAREA') {
9671 return false;
9672 }
9673 // native onclick with string value, must be set as attribute
9674 if (nativeOnRE.test(key) && isString(value)) {
9675 return false;
9676 }
9677 return key in el;
9678}
9679
9680function defineCustomElement(options, hydate) {
9681 const Comp = defineComponent(options);
9682 class VueCustomElement extends VueElement {
9683 constructor(initialProps) {
9684 super(Comp, initialProps, hydate);
9685 }
9686 }
9687 VueCustomElement.def = Comp;
9688 return VueCustomElement;
9689}
9690const defineSSRCustomElement = ((options) => {
9691 // @ts-ignore
9692 return defineCustomElement(options, hydrate);
9693});
9694const BaseClass = (typeof HTMLElement !== 'undefined' ? HTMLElement : class {
9695});
9696class VueElement extends BaseClass {
9697 constructor(_def, _props = {}, hydrate) {
9698 super();
9699 this._def = _def;
9700 this._props = _props;
9701 /**
9702 * @internal
9703 */
9704 this._instance = null;
9705 this._connected = false;
9706 this._resolved = false;
9707 this._numberProps = null;
9708 if (this.shadowRoot && hydrate) {
9709 hydrate(this._createVNode(), this.shadowRoot);
9710 }
9711 else {
9712 if (this.shadowRoot) {
9713 warn$1(`Custom element has pre-rendered declarative shadow root but is not ` +
9714 `defined as hydratable. Use \`defineSSRCustomElement\`.`);
9715 }
9716 this.attachShadow({ mode: 'open' });
9717 }
9718 }
9719 connectedCallback() {
9720 this._connected = true;
9721 if (!this._instance) {
9722 this._resolveDef();
9723 }
9724 }
9725 disconnectedCallback() {
9726 this._connected = false;
9727 nextTick(() => {
9728 if (!this._connected) {
9729 render(null, this.shadowRoot);
9730 this._instance = null;
9731 }
9732 });
9733 }
9734 /**
9735 * resolve inner component definition (handle possible async component)
9736 */
9737 _resolveDef() {
9738 if (this._resolved) {
9739 return;
9740 }
9741 this._resolved = true;
9742 // set initial attrs
9743 for (let i = 0; i < this.attributes.length; i++) {
9744 this._setAttr(this.attributes[i].name);
9745 }
9746 // watch future attr changes
9747 new MutationObserver(mutations => {
9748 for (const m of mutations) {
9749 this._setAttr(m.attributeName);
9750 }
9751 }).observe(this, { attributes: true });
9752 const resolve = (def) => {
9753 const { props, styles } = def;
9754 const hasOptions = !isArray(props);
9755 const rawKeys = props ? (hasOptions ? Object.keys(props) : props) : [];
9756 // cast Number-type props set before resolve
9757 let numberProps;
9758 if (hasOptions) {
9759 for (const key in this._props) {
9760 const opt = props[key];
9761 if (opt === Number || (opt && opt.type === Number)) {
9762 this._props[key] = toNumber(this._props[key]);
9763 (numberProps || (numberProps = Object.create(null)))[key] = true;
9764 }
9765 }
9766 }
9767 this._numberProps = numberProps;
9768 // check if there are props set pre-upgrade or connect
9769 for (const key of Object.keys(this)) {
9770 if (key[0] !== '_') {
9771 this._setProp(key, this[key], true, false);
9772 }
9773 }
9774 // defining getter/setters on prototype
9775 for (const key of rawKeys.map(camelize)) {
9776 Object.defineProperty(this, key, {
9777 get() {
9778 return this._getProp(key);
9779 },
9780 set(val) {
9781 this._setProp(key, val);
9782 }
9783 });
9784 }
9785 // apply CSS
9786 this._applyStyles(styles);
9787 // initial render
9788 this._update();
9789 };
9790 const asyncDef = this._def.__asyncLoader;
9791 if (asyncDef) {
9792 asyncDef().then(resolve);
9793 }
9794 else {
9795 resolve(this._def);
9796 }
9797 }
9798 _setAttr(key) {
9799 let value = this.getAttribute(key);
9800 if (this._numberProps && this._numberProps[key]) {
9801 value = toNumber(value);
9802 }
9803 this._setProp(camelize(key), value, false);
9804 }
9805 /**
9806 * @internal
9807 */
9808 _getProp(key) {
9809 return this._props[key];
9810 }
9811 /**
9812 * @internal
9813 */
9814 _setProp(key, val, shouldReflect = true, shouldUpdate = true) {
9815 if (val !== this._props[key]) {
9816 this._props[key] = val;
9817 if (shouldUpdate && this._instance) {
9818 this._update();
9819 }
9820 // reflect
9821 if (shouldReflect) {
9822 if (val === true) {
9823 this.setAttribute(hyphenate(key), '');
9824 }
9825 else if (typeof val === 'string' || typeof val === 'number') {
9826 this.setAttribute(hyphenate(key), val + '');
9827 }
9828 else if (!val) {
9829 this.removeAttribute(hyphenate(key));
9830 }
9831 }
9832 }
9833 }
9834 _update() {
9835 render(this._createVNode(), this.shadowRoot);
9836 }
9837 _createVNode() {
9838 const vnode = createVNode(this._def, extend({}, this._props));
9839 if (!this._instance) {
9840 vnode.ce = instance => {
9841 this._instance = instance;
9842 instance.isCE = true;
9843 // HMR
9844 {
9845 instance.ceReload = newStyles => {
9846 // always reset styles
9847 if (this._styles) {
9848 this._styles.forEach(s => this.shadowRoot.removeChild(s));
9849 this._styles.length = 0;
9850 }
9851 this._applyStyles(newStyles);
9852 // if this is an async component, ceReload is called from the inner
9853 // component so no need to reload the async wrapper
9854 if (!this._def.__asyncLoader) {
9855 // reload
9856 this._instance = null;
9857 this._update();
9858 }
9859 };
9860 }
9861 // intercept emit
9862 instance.emit = (event, ...args) => {
9863 this.dispatchEvent(new CustomEvent(event, {
9864 detail: args
9865 }));
9866 };
9867 // locate nearest Vue custom element parent for provide/inject
9868 let parent = this;
9869 while ((parent =
9870 parent && (parent.parentNode || parent.host))) {
9871 if (parent instanceof VueElement) {
9872 instance.parent = parent._instance;
9873 break;
9874 }
9875 }
9876 };
9877 }
9878 return vnode;
9879 }
9880 _applyStyles(styles) {
9881 if (styles) {
9882 styles.forEach(css => {
9883 const s = document.createElement('style');
9884 s.textContent = css;
9885 this.shadowRoot.appendChild(s);
9886 // record for HMR
9887 {
9888 (this._styles || (this._styles = [])).push(s);
9889 }
9890 });
9891 }
9892 }
9893}
9894
9895function useCssModule(name = '$style') {
9896 /* istanbul ignore else */
9897 {
9898 const instance = getCurrentInstance();
9899 if (!instance) {
9900 warn$1(`useCssModule must be called inside setup()`);
9901 return EMPTY_OBJ;
9902 }
9903 const modules = instance.type.__cssModules;
9904 if (!modules) {
9905 warn$1(`Current instance does not have CSS modules injected.`);
9906 return EMPTY_OBJ;
9907 }
9908 const mod = modules[name];
9909 if (!mod) {
9910 warn$1(`Current instance does not have CSS module named "${name}".`);
9911 return EMPTY_OBJ;
9912 }
9913 return mod;
9914 }
9915}
9916
9917/**
9918 * Runtime helper for SFC's CSS variable injection feature.
9919 * @private
9920 */
9921function useCssVars(getter) {
9922 const instance = getCurrentInstance();
9923 /* istanbul ignore next */
9924 if (!instance) {
9925 warn$1(`useCssVars is called without current active component instance.`);
9926 return;
9927 }
9928 const setVars = () => setVarsOnVNode(instance.subTree, getter(instance.proxy));
9929 watchPostEffect(setVars);
9930 onMounted(() => {
9931 const ob = new MutationObserver(setVars);
9932 ob.observe(instance.subTree.el.parentNode, { childList: true });
9933 onUnmounted(() => ob.disconnect());
9934 });
9935}
9936function setVarsOnVNode(vnode, vars) {
9937 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
9938 const suspense = vnode.suspense;
9939 vnode = suspense.activeBranch;
9940 if (suspense.pendingBranch && !suspense.isHydrating) {
9941 suspense.effects.push(() => {
9942 setVarsOnVNode(suspense.activeBranch, vars);
9943 });
9944 }
9945 }
9946 // drill down HOCs until it's a non-component vnode
9947 while (vnode.component) {
9948 vnode = vnode.component.subTree;
9949 }
9950 if (vnode.shapeFlag & 1 /* ELEMENT */ && vnode.el) {
9951 setVarsOnNode(vnode.el, vars);
9952 }
9953 else if (vnode.type === Fragment) {
9954 vnode.children.forEach(c => setVarsOnVNode(c, vars));
9955 }
9956 else if (vnode.type === Static) {
9957 let { el, anchor } = vnode;
9958 while (el) {
9959 setVarsOnNode(el, vars);
9960 if (el === anchor)
9961 break;
9962 el = el.nextSibling;
9963 }
9964 }
9965}
9966function setVarsOnNode(el, vars) {
9967 if (el.nodeType === 1) {
9968 const style = el.style;
9969 for (const key in vars) {
9970 style.setProperty(`--${key}`, vars[key]);
9971 }
9972 }
9973}
9974
9975const TRANSITION = 'transition';
9976const ANIMATION = 'animation';
9977// DOM Transition is a higher-order-component based on the platform-agnostic
9978// base Transition component, with DOM-specific logic.
9979const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
9980Transition.displayName = 'Transition';
9981const DOMTransitionPropsValidators = {
9982 name: String,
9983 type: String,
9984 css: {
9985 type: Boolean,
9986 default: true
9987 },
9988 duration: [String, Number, Object],
9989 enterFromClass: String,
9990 enterActiveClass: String,
9991 enterToClass: String,
9992 appearFromClass: String,
9993 appearActiveClass: String,
9994 appearToClass: String,
9995 leaveFromClass: String,
9996 leaveActiveClass: String,
9997 leaveToClass: String
9998};
9999const TransitionPropsValidators = (Transition.props =
10000 /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
10001/**
10002 * #3227 Incoming hooks may be merged into arrays when wrapping Transition
10003 * with custom HOCs.
10004 */
10005const callHook$1 = (hook, args = []) => {
10006 if (isArray(hook)) {
10007 hook.forEach(h => h(...args));
10008 }
10009 else if (hook) {
10010 hook(...args);
10011 }
10012};
10013/**
10014 * Check if a hook expects a callback (2nd arg), which means the user
10015 * intends to explicitly control the end of the transition.
10016 */
10017const hasExplicitCallback = (hook) => {
10018 return hook
10019 ? isArray(hook)
10020 ? hook.some(h => h.length > 1)
10021 : hook.length > 1
10022 : false;
10023};
10024function resolveTransitionProps(rawProps) {
10025 const baseProps = {};
10026 for (const key in rawProps) {
10027 if (!(key in DOMTransitionPropsValidators)) {
10028 baseProps[key] = rawProps[key];
10029 }
10030 }
10031 if (rawProps.css === false) {
10032 return baseProps;
10033 }
10034 const { name = 'v', type, 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;
10035 const durations = normalizeDuration(duration);
10036 const enterDuration = durations && durations[0];
10037 const leaveDuration = durations && durations[1];
10038 const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
10039 const finishEnter = (el, isAppear, done) => {
10040 removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
10041 removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
10042 done && done();
10043 };
10044 const finishLeave = (el, done) => {
10045 removeTransitionClass(el, leaveToClass);
10046 removeTransitionClass(el, leaveActiveClass);
10047 done && done();
10048 };
10049 const makeEnterHook = (isAppear) => {
10050 return (el, done) => {
10051 const hook = isAppear ? onAppear : onEnter;
10052 const resolve = () => finishEnter(el, isAppear, done);
10053 callHook$1(hook, [el, resolve]);
10054 nextFrame(() => {
10055 removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
10056 addTransitionClass(el, isAppear ? appearToClass : enterToClass);
10057 if (!hasExplicitCallback(hook)) {
10058 whenTransitionEnds(el, type, enterDuration, resolve);
10059 }
10060 });
10061 };
10062 };
10063 return extend(baseProps, {
10064 onBeforeEnter(el) {
10065 callHook$1(onBeforeEnter, [el]);
10066 addTransitionClass(el, enterFromClass);
10067 addTransitionClass(el, enterActiveClass);
10068 },
10069 onBeforeAppear(el) {
10070 callHook$1(onBeforeAppear, [el]);
10071 addTransitionClass(el, appearFromClass);
10072 addTransitionClass(el, appearActiveClass);
10073 },
10074 onEnter: makeEnterHook(false),
10075 onAppear: makeEnterHook(true),
10076 onLeave(el, done) {
10077 const resolve = () => finishLeave(el, done);
10078 addTransitionClass(el, leaveFromClass);
10079 // force reflow so *-leave-from classes immediately take effect (#2593)
10080 forceReflow();
10081 addTransitionClass(el, leaveActiveClass);
10082 nextFrame(() => {
10083 removeTransitionClass(el, leaveFromClass);
10084 addTransitionClass(el, leaveToClass);
10085 if (!hasExplicitCallback(onLeave)) {
10086 whenTransitionEnds(el, type, leaveDuration, resolve);
10087 }
10088 });
10089 callHook$1(onLeave, [el, resolve]);
10090 },
10091 onEnterCancelled(el) {
10092 finishEnter(el, false);
10093 callHook$1(onEnterCancelled, [el]);
10094 },
10095 onAppearCancelled(el) {
10096 finishEnter(el, true);
10097 callHook$1(onAppearCancelled, [el]);
10098 },
10099 onLeaveCancelled(el) {
10100 finishLeave(el);
10101 callHook$1(onLeaveCancelled, [el]);
10102 }
10103 });
10104}
10105function normalizeDuration(duration) {
10106 if (duration == null) {
10107 return null;
10108 }
10109 else if (isObject(duration)) {
10110 return [NumberOf(duration.enter), NumberOf(duration.leave)];
10111 }
10112 else {
10113 const n = NumberOf(duration);
10114 return [n, n];
10115 }
10116}
10117function NumberOf(val) {
10118 const res = toNumber(val);
10119 validateDuration(res);
10120 return res;
10121}
10122function validateDuration(val) {
10123 if (typeof val !== 'number') {
10124 warn$1(`<transition> explicit duration is not a valid number - ` +
10125 `got ${JSON.stringify(val)}.`);
10126 }
10127 else if (isNaN(val)) {
10128 warn$1(`<transition> explicit duration is NaN - ` +
10129 'the duration expression might be incorrect.');
10130 }
10131}
10132function addTransitionClass(el, cls) {
10133 cls.split(/\s+/).forEach(c => c && el.classList.add(c));
10134 (el._vtc ||
10135 (el._vtc = new Set())).add(cls);
10136}
10137function removeTransitionClass(el, cls) {
10138 cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
10139 const { _vtc } = el;
10140 if (_vtc) {
10141 _vtc.delete(cls);
10142 if (!_vtc.size) {
10143 el._vtc = undefined;
10144 }
10145 }
10146}
10147function nextFrame(cb) {
10148 requestAnimationFrame(() => {
10149 requestAnimationFrame(cb);
10150 });
10151}
10152let endId = 0;
10153function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
10154 const id = (el._endId = ++endId);
10155 const resolveIfNotStale = () => {
10156 if (id === el._endId) {
10157 resolve();
10158 }
10159 };
10160 if (explicitTimeout) {
10161 return setTimeout(resolveIfNotStale, explicitTimeout);
10162 }
10163 const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
10164 if (!type) {
10165 return resolve();
10166 }
10167 const endEvent = type + 'end';
10168 let ended = 0;
10169 const end = () => {
10170 el.removeEventListener(endEvent, onEnd);
10171 resolveIfNotStale();
10172 };
10173 const onEnd = (e) => {
10174 if (e.target === el && ++ended >= propCount) {
10175 end();
10176 }
10177 };
10178 setTimeout(() => {
10179 if (ended < propCount) {
10180 end();
10181 }
10182 }, timeout + 1);
10183 el.addEventListener(endEvent, onEnd);
10184}
10185function getTransitionInfo(el, expectedType) {
10186 const styles = window.getComputedStyle(el);
10187 // JSDOM may return undefined for transition properties
10188 const getStyleProperties = (key) => (styles[key] || '').split(', ');
10189 const transitionDelays = getStyleProperties(TRANSITION + 'Delay');
10190 const transitionDurations = getStyleProperties(TRANSITION + 'Duration');
10191 const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
10192 const animationDelays = getStyleProperties(ANIMATION + 'Delay');
10193 const animationDurations = getStyleProperties(ANIMATION + 'Duration');
10194 const animationTimeout = getTimeout(animationDelays, animationDurations);
10195 let type = null;
10196 let timeout = 0;
10197 let propCount = 0;
10198 /* istanbul ignore if */
10199 if (expectedType === TRANSITION) {
10200 if (transitionTimeout > 0) {
10201 type = TRANSITION;
10202 timeout = transitionTimeout;
10203 propCount = transitionDurations.length;
10204 }
10205 }
10206 else if (expectedType === ANIMATION) {
10207 if (animationTimeout > 0) {
10208 type = ANIMATION;
10209 timeout = animationTimeout;
10210 propCount = animationDurations.length;
10211 }
10212 }
10213 else {
10214 timeout = Math.max(transitionTimeout, animationTimeout);
10215 type =
10216 timeout > 0
10217 ? transitionTimeout > animationTimeout
10218 ? TRANSITION
10219 : ANIMATION
10220 : null;
10221 propCount = type
10222 ? type === TRANSITION
10223 ? transitionDurations.length
10224 : animationDurations.length
10225 : 0;
10226 }
10227 const hasTransform = type === TRANSITION &&
10228 /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']);
10229 return {
10230 type,
10231 timeout,
10232 propCount,
10233 hasTransform
10234 };
10235}
10236function getTimeout(delays, durations) {
10237 while (delays.length < durations.length) {
10238 delays = delays.concat(delays);
10239 }
10240 return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
10241}
10242// Old versions of Chromium (below 61.0.3163.100) formats floating pointer
10243// numbers in a locale-dependent way, using a comma instead of a dot.
10244// If comma is not replaced with a dot, the input will be rounded down
10245// (i.e. acting as a floor function) causing unexpected behaviors
10246function toMs(s) {
10247 return Number(s.slice(0, -1).replace(',', '.')) * 1000;
10248}
10249// synchronously force layout to put elements into a certain state
10250function forceReflow() {
10251 return document.body.offsetHeight;
10252}
10253
10254const positionMap = new WeakMap();
10255const newPositionMap = new WeakMap();
10256const TransitionGroupImpl = {
10257 name: 'TransitionGroup',
10258 props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
10259 tag: String,
10260 moveClass: String
10261 }),
10262 setup(props, { slots }) {
10263 const instance = getCurrentInstance();
10264 const state = useTransitionState();
10265 let prevChildren;
10266 let children;
10267 onUpdated(() => {
10268 // children is guaranteed to exist after initial render
10269 if (!prevChildren.length) {
10270 return;
10271 }
10272 const moveClass = props.moveClass || `${props.name || 'v'}-move`;
10273 if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
10274 return;
10275 }
10276 // we divide the work into three loops to avoid mixing DOM reads and writes
10277 // in each iteration - which helps prevent layout thrashing.
10278 prevChildren.forEach(callPendingCbs);
10279 prevChildren.forEach(recordPosition);
10280 const movedChildren = prevChildren.filter(applyTranslation);
10281 // force reflow to put everything in position
10282 forceReflow();
10283 movedChildren.forEach(c => {
10284 const el = c.el;
10285 const style = el.style;
10286 addTransitionClass(el, moveClass);
10287 style.transform = style.webkitTransform = style.transitionDuration = '';
10288 const cb = (el._moveCb = (e) => {
10289 if (e && e.target !== el) {
10290 return;
10291 }
10292 if (!e || /transform$/.test(e.propertyName)) {
10293 el.removeEventListener('transitionend', cb);
10294 el._moveCb = null;
10295 removeTransitionClass(el, moveClass);
10296 }
10297 });
10298 el.addEventListener('transitionend', cb);
10299 });
10300 });
10301 return () => {
10302 const rawProps = toRaw(props);
10303 const cssTransitionProps = resolveTransitionProps(rawProps);
10304 let tag = rawProps.tag || Fragment;
10305 prevChildren = children;
10306 children = slots.default ? getTransitionRawChildren(slots.default()) : [];
10307 for (let i = 0; i < children.length; i++) {
10308 const child = children[i];
10309 if (child.key != null) {
10310 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
10311 }
10312 else {
10313 warn$1(`<TransitionGroup> children must be keyed.`);
10314 }
10315 }
10316 if (prevChildren) {
10317 for (let i = 0; i < prevChildren.length; i++) {
10318 const child = prevChildren[i];
10319 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
10320 positionMap.set(child, child.el.getBoundingClientRect());
10321 }
10322 }
10323 return createVNode(tag, null, children);
10324 };
10325 }
10326};
10327const TransitionGroup = TransitionGroupImpl;
10328function callPendingCbs(c) {
10329 const el = c.el;
10330 if (el._moveCb) {
10331 el._moveCb();
10332 }
10333 if (el._enterCb) {
10334 el._enterCb();
10335 }
10336}
10337function recordPosition(c) {
10338 newPositionMap.set(c, c.el.getBoundingClientRect());
10339}
10340function applyTranslation(c) {
10341 const oldPos = positionMap.get(c);
10342 const newPos = newPositionMap.get(c);
10343 const dx = oldPos.left - newPos.left;
10344 const dy = oldPos.top - newPos.top;
10345 if (dx || dy) {
10346 const s = c.el.style;
10347 s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
10348 s.transitionDuration = '0s';
10349 return c;
10350 }
10351}
10352function hasCSSTransform(el, root, moveClass) {
10353 // Detect whether an element with the move class applied has
10354 // CSS transitions. Since the element may be inside an entering
10355 // transition at this very moment, we make a clone of it and remove
10356 // all other transition classes applied to ensure only the move class
10357 // is applied.
10358 const clone = el.cloneNode();
10359 if (el._vtc) {
10360 el._vtc.forEach(cls => {
10361 cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
10362 });
10363 }
10364 moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
10365 clone.style.display = 'none';
10366 const container = (root.nodeType === 1 ? root : root.parentNode);
10367 container.appendChild(clone);
10368 const { hasTransform } = getTransitionInfo(clone);
10369 container.removeChild(clone);
10370 return hasTransform;
10371}
10372
10373const getModelAssigner = (vnode) => {
10374 const fn = vnode.props['onUpdate:modelValue'];
10375 return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
10376};
10377function onCompositionStart(e) {
10378 e.target.composing = true;
10379}
10380function onCompositionEnd(e) {
10381 const target = e.target;
10382 if (target.composing) {
10383 target.composing = false;
10384 trigger$1(target, 'input');
10385 }
10386}
10387function trigger$1(el, type) {
10388 const e = document.createEvent('HTMLEvents');
10389 e.initEvent(type, true, true);
10390 el.dispatchEvent(e);
10391}
10392// We are exporting the v-model runtime directly as vnode hooks so that it can
10393// be tree-shaken in case v-model is never used.
10394const vModelText = {
10395 created(el, { modifiers: { lazy, trim, number } }, vnode) {
10396 el._assign = getModelAssigner(vnode);
10397 const castToNumber = number || (vnode.props && vnode.props.type === 'number');
10398 addEventListener(el, lazy ? 'change' : 'input', e => {
10399 if (e.target.composing)
10400 return;
10401 let domValue = el.value;
10402 if (trim) {
10403 domValue = domValue.trim();
10404 }
10405 else if (castToNumber) {
10406 domValue = toNumber(domValue);
10407 }
10408 el._assign(domValue);
10409 });
10410 if (trim) {
10411 addEventListener(el, 'change', () => {
10412 el.value = el.value.trim();
10413 });
10414 }
10415 if (!lazy) {
10416 addEventListener(el, 'compositionstart', onCompositionStart);
10417 addEventListener(el, 'compositionend', onCompositionEnd);
10418 // Safari < 10.2 & UIWebView doesn't fire compositionend when
10419 // switching focus before confirming composition choice
10420 // this also fixes the issue where some browsers e.g. iOS Chrome
10421 // fires "change" instead of "input" on autocomplete.
10422 addEventListener(el, 'change', onCompositionEnd);
10423 }
10424 },
10425 // set value on mounted so it's after min/max for type="range"
10426 mounted(el, { value }) {
10427 el.value = value == null ? '' : value;
10428 },
10429 beforeUpdate(el, { value, modifiers: { lazy, trim, number } }, vnode) {
10430 el._assign = getModelAssigner(vnode);
10431 // avoid clearing unresolved text. #2302
10432 if (el.composing)
10433 return;
10434 if (document.activeElement === el) {
10435 if (lazy) {
10436 return;
10437 }
10438 if (trim && el.value.trim() === value) {
10439 return;
10440 }
10441 if ((number || el.type === 'number') && toNumber(el.value) === value) {
10442 return;
10443 }
10444 }
10445 const newValue = value == null ? '' : value;
10446 if (el.value !== newValue) {
10447 el.value = newValue;
10448 }
10449 }
10450};
10451const vModelCheckbox = {
10452 // #4096 array checkboxes need to be deep traversed
10453 deep: true,
10454 created(el, _, vnode) {
10455 el._assign = getModelAssigner(vnode);
10456 addEventListener(el, 'change', () => {
10457 const modelValue = el._modelValue;
10458 const elementValue = getValue(el);
10459 const checked = el.checked;
10460 const assign = el._assign;
10461 if (isArray(modelValue)) {
10462 const index = looseIndexOf(modelValue, elementValue);
10463 const found = index !== -1;
10464 if (checked && !found) {
10465 assign(modelValue.concat(elementValue));
10466 }
10467 else if (!checked && found) {
10468 const filtered = [...modelValue];
10469 filtered.splice(index, 1);
10470 assign(filtered);
10471 }
10472 }
10473 else if (isSet(modelValue)) {
10474 const cloned = new Set(modelValue);
10475 if (checked) {
10476 cloned.add(elementValue);
10477 }
10478 else {
10479 cloned.delete(elementValue);
10480 }
10481 assign(cloned);
10482 }
10483 else {
10484 assign(getCheckboxValue(el, checked));
10485 }
10486 });
10487 },
10488 // set initial checked on mount to wait for true-value/false-value
10489 mounted: setChecked,
10490 beforeUpdate(el, binding, vnode) {
10491 el._assign = getModelAssigner(vnode);
10492 setChecked(el, binding, vnode);
10493 }
10494};
10495function setChecked(el, { value, oldValue }, vnode) {
10496 el._modelValue = value;
10497 if (isArray(value)) {
10498 el.checked = looseIndexOf(value, vnode.props.value) > -1;
10499 }
10500 else if (isSet(value)) {
10501 el.checked = value.has(vnode.props.value);
10502 }
10503 else if (value !== oldValue) {
10504 el.checked = looseEqual(value, getCheckboxValue(el, true));
10505 }
10506}
10507const vModelRadio = {
10508 created(el, { value }, vnode) {
10509 el.checked = looseEqual(value, vnode.props.value);
10510 el._assign = getModelAssigner(vnode);
10511 addEventListener(el, 'change', () => {
10512 el._assign(getValue(el));
10513 });
10514 },
10515 beforeUpdate(el, { value, oldValue }, vnode) {
10516 el._assign = getModelAssigner(vnode);
10517 if (value !== oldValue) {
10518 el.checked = looseEqual(value, vnode.props.value);
10519 }
10520 }
10521};
10522const vModelSelect = {
10523 // <select multiple> value need to be deep traversed
10524 deep: true,
10525 created(el, { value, modifiers: { number } }, vnode) {
10526 const isSetModel = isSet(value);
10527 addEventListener(el, 'change', () => {
10528 const selectedVal = Array.prototype.filter
10529 .call(el.options, (o) => o.selected)
10530 .map((o) => number ? toNumber(getValue(o)) : getValue(o));
10531 el._assign(el.multiple
10532 ? isSetModel
10533 ? new Set(selectedVal)
10534 : selectedVal
10535 : selectedVal[0]);
10536 });
10537 el._assign = getModelAssigner(vnode);
10538 },
10539 // set value in mounted & updated because <select> relies on its children
10540 // <option>s.
10541 mounted(el, { value }) {
10542 setSelected(el, value);
10543 },
10544 beforeUpdate(el, _binding, vnode) {
10545 el._assign = getModelAssigner(vnode);
10546 },
10547 updated(el, { value }) {
10548 setSelected(el, value);
10549 }
10550};
10551function setSelected(el, value) {
10552 const isMultiple = el.multiple;
10553 if (isMultiple && !isArray(value) && !isSet(value)) {
10554 warn$1(`<select multiple v-model> expects an Array or Set value for its binding, ` +
10555 `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
10556 return;
10557 }
10558 for (let i = 0, l = el.options.length; i < l; i++) {
10559 const option = el.options[i];
10560 const optionValue = getValue(option);
10561 if (isMultiple) {
10562 if (isArray(value)) {
10563 option.selected = looseIndexOf(value, optionValue) > -1;
10564 }
10565 else {
10566 option.selected = value.has(optionValue);
10567 }
10568 }
10569 else {
10570 if (looseEqual(getValue(option), value)) {
10571 if (el.selectedIndex !== i)
10572 el.selectedIndex = i;
10573 return;
10574 }
10575 }
10576 }
10577 if (!isMultiple && el.selectedIndex !== -1) {
10578 el.selectedIndex = -1;
10579 }
10580}
10581// retrieve raw value set via :value bindings
10582function getValue(el) {
10583 return '_value' in el ? el._value : el.value;
10584}
10585// retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
10586function getCheckboxValue(el, checked) {
10587 const key = checked ? '_trueValue' : '_falseValue';
10588 return key in el ? el[key] : checked;
10589}
10590const vModelDynamic = {
10591 created(el, binding, vnode) {
10592 callModelHook(el, binding, vnode, null, 'created');
10593 },
10594 mounted(el, binding, vnode) {
10595 callModelHook(el, binding, vnode, null, 'mounted');
10596 },
10597 beforeUpdate(el, binding, vnode, prevVNode) {
10598 callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
10599 },
10600 updated(el, binding, vnode, prevVNode) {
10601 callModelHook(el, binding, vnode, prevVNode, 'updated');
10602 }
10603};
10604function callModelHook(el, binding, vnode, prevVNode, hook) {
10605 let modelToUse;
10606 switch (el.tagName) {
10607 case 'SELECT':
10608 modelToUse = vModelSelect;
10609 break;
10610 case 'TEXTAREA':
10611 modelToUse = vModelText;
10612 break;
10613 default:
10614 switch (vnode.props && vnode.props.type) {
10615 case 'checkbox':
10616 modelToUse = vModelCheckbox;
10617 break;
10618 case 'radio':
10619 modelToUse = vModelRadio;
10620 break;
10621 default:
10622 modelToUse = vModelText;
10623 }
10624 }
10625 const fn = modelToUse[hook];
10626 fn && fn(el, binding, vnode, prevVNode);
10627}
10628
10629const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
10630const modifierGuards = {
10631 stop: e => e.stopPropagation(),
10632 prevent: e => e.preventDefault(),
10633 self: e => e.target !== e.currentTarget,
10634 ctrl: e => !e.ctrlKey,
10635 shift: e => !e.shiftKey,
10636 alt: e => !e.altKey,
10637 meta: e => !e.metaKey,
10638 left: e => 'button' in e && e.button !== 0,
10639 middle: e => 'button' in e && e.button !== 1,
10640 right: e => 'button' in e && e.button !== 2,
10641 exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
10642};
10643/**
10644 * @private
10645 */
10646const withModifiers = (fn, modifiers) => {
10647 return (event, ...args) => {
10648 for (let i = 0; i < modifiers.length; i++) {
10649 const guard = modifierGuards[modifiers[i]];
10650 if (guard && guard(event, modifiers))
10651 return;
10652 }
10653 return fn(event, ...args);
10654 };
10655};
10656// Kept for 2.x compat.
10657// Note: IE11 compat for `spacebar` and `del` is removed for now.
10658const keyNames = {
10659 esc: 'escape',
10660 space: ' ',
10661 up: 'arrow-up',
10662 left: 'arrow-left',
10663 right: 'arrow-right',
10664 down: 'arrow-down',
10665 delete: 'backspace'
10666};
10667/**
10668 * @private
10669 */
10670const withKeys = (fn, modifiers) => {
10671 return (event) => {
10672 if (!('key' in event)) {
10673 return;
10674 }
10675 const eventKey = hyphenate(event.key);
10676 if (modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
10677 return fn(event);
10678 }
10679 };
10680};
10681
10682const vShow = {
10683 beforeMount(el, { value }, { transition }) {
10684 el._vod = el.style.display === 'none' ? '' : el.style.display;
10685 if (transition && value) {
10686 transition.beforeEnter(el);
10687 }
10688 else {
10689 setDisplay(el, value);
10690 }
10691 },
10692 mounted(el, { value }, { transition }) {
10693 if (transition && value) {
10694 transition.enter(el);
10695 }
10696 },
10697 updated(el, { value, oldValue }, { transition }) {
10698 if (!value === !oldValue)
10699 return;
10700 if (transition) {
10701 if (value) {
10702 transition.beforeEnter(el);
10703 setDisplay(el, true);
10704 transition.enter(el);
10705 }
10706 else {
10707 transition.leave(el, () => {
10708 setDisplay(el, false);
10709 });
10710 }
10711 }
10712 else {
10713 setDisplay(el, value);
10714 }
10715 },
10716 beforeUnmount(el, { value }) {
10717 setDisplay(el, value);
10718 }
10719};
10720function setDisplay(el, value) {
10721 el.style.display = value ? el._vod : 'none';
10722}
10723
10724const rendererOptions = /*#__PURE__*/ extend({ patchProp }, nodeOps);
10725// lazy create the renderer - this makes core renderer logic tree-shakable
10726// in case the user only imports reactivity utilities from Vue.
10727let renderer;
10728let enabledHydration = false;
10729function ensureRenderer() {
10730 return (renderer ||
10731 (renderer = createRenderer(rendererOptions)));
10732}
10733function ensureHydrationRenderer() {
10734 renderer = enabledHydration
10735 ? renderer
10736 : createHydrationRenderer(rendererOptions);
10737 enabledHydration = true;
10738 return renderer;
10739}
10740// use explicit type casts here to avoid import() calls in rolled-up d.ts
10741const render = ((...args) => {
10742 ensureRenderer().render(...args);
10743});
10744const hydrate = ((...args) => {
10745 ensureHydrationRenderer().hydrate(...args);
10746});
10747const createApp = ((...args) => {
10748 const app = ensureRenderer().createApp(...args);
10749 {
10750 injectNativeTagCheck(app);
10751 injectCompilerOptionsCheck(app);
10752 }
10753 const { mount } = app;
10754 app.mount = (containerOrSelector) => {
10755 const container = normalizeContainer(containerOrSelector);
10756 if (!container)
10757 return;
10758 const component = app._component;
10759 if (!isFunction(component) && !component.render && !component.template) {
10760 // __UNSAFE__
10761 // Reason: potential execution of JS expressions in in-DOM template.
10762 // The user must make sure the in-DOM template is trusted. If it's
10763 // rendered by the server, the template should not contain any user data.
10764 component.template = container.innerHTML;
10765 }
10766 // clear content before mounting
10767 container.innerHTML = '';
10768 const proxy = mount(container, false, container instanceof SVGElement);
10769 if (container instanceof Element) {
10770 container.removeAttribute('v-cloak');
10771 container.setAttribute('data-v-app', '');
10772 }
10773 return proxy;
10774 };
10775 return app;
10776});
10777const createSSRApp = ((...args) => {
10778 const app = ensureHydrationRenderer().createApp(...args);
10779 {
10780 injectNativeTagCheck(app);
10781 injectCompilerOptionsCheck(app);
10782 }
10783 const { mount } = app;
10784 app.mount = (containerOrSelector) => {
10785 const container = normalizeContainer(containerOrSelector);
10786 if (container) {
10787 return mount(container, true, container instanceof SVGElement);
10788 }
10789 };
10790 return app;
10791});
10792function injectNativeTagCheck(app) {
10793 // Inject `isNativeTag`
10794 // this is used for component name validation (dev only)
10795 Object.defineProperty(app.config, 'isNativeTag', {
10796 value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
10797 writable: false
10798 });
10799}
10800// dev only
10801function injectCompilerOptionsCheck(app) {
10802 if (isRuntimeOnly()) {
10803 const isCustomElement = app.config.isCustomElement;
10804 Object.defineProperty(app.config, 'isCustomElement', {
10805 get() {
10806 return isCustomElement;
10807 },
10808 set() {
10809 warn$1(`The \`isCustomElement\` config option is deprecated. Use ` +
10810 `\`compilerOptions.isCustomElement\` instead.`);
10811 }
10812 });
10813 const compilerOptions = app.config.compilerOptions;
10814 const msg = `The \`compilerOptions\` config option is only respected when using ` +
10815 `a build of Vue.js that includes the runtime compiler (aka "full build"). ` +
10816 `Since you are using the runtime-only build, \`compilerOptions\` ` +
10817 `must be passed to \`@vue/compiler-dom\` in the build setup instead.\n` +
10818 `- For vue-loader: pass it via vue-loader's \`compilerOptions\` loader option.\n` +
10819 `- For vue-cli: see https://cli.vuejs.org/guide/webpack.html#modifying-options-of-a-loader\n` +
10820 `- For vite: pass it via @vitejs/plugin-vue options. See https://github.com/vitejs/vite/tree/main/packages/plugin-vue#example-for-passing-options-to-vuecompiler-dom`;
10821 Object.defineProperty(app.config, 'compilerOptions', {
10822 get() {
10823 warn$1(msg);
10824 return compilerOptions;
10825 },
10826 set() {
10827 warn$1(msg);
10828 }
10829 });
10830 }
10831}
10832function normalizeContainer(container) {
10833 if (isString(container)) {
10834 const res = document.querySelector(container);
10835 if (!res) {
10836 warn$1(`Failed to mount app: mount target selector "${container}" returned null.`);
10837 }
10838 return res;
10839 }
10840 if (window.ShadowRoot &&
10841 container instanceof window.ShadowRoot &&
10842 container.mode === 'closed') {
10843 warn$1(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`);
10844 }
10845 return container;
10846}
10847/**
10848 * @internal
10849 */
10850const initDirectivesForSSR = NOOP;
10851
10852var runtimeDom = /*#__PURE__*/Object.freeze({
10853 __proto__: null,
10854 render: render,
10855 hydrate: hydrate,
10856 createApp: createApp,
10857 createSSRApp: createSSRApp,
10858 initDirectivesForSSR: initDirectivesForSSR,
10859 defineCustomElement: defineCustomElement,
10860 defineSSRCustomElement: defineSSRCustomElement,
10861 VueElement: VueElement,
10862 useCssModule: useCssModule,
10863 useCssVars: useCssVars,
10864 Transition: Transition,
10865 TransitionGroup: TransitionGroup,
10866 vModelText: vModelText,
10867 vModelCheckbox: vModelCheckbox,
10868 vModelRadio: vModelRadio,
10869 vModelSelect: vModelSelect,
10870 vModelDynamic: vModelDynamic,
10871 withModifiers: withModifiers,
10872 withKeys: withKeys,
10873 vShow: vShow,
10874 reactive: reactive,
10875 ref: ref,
10876 readonly: readonly,
10877 unref: unref,
10878 proxyRefs: proxyRefs,
10879 isRef: isRef,
10880 toRef: toRef,
10881 toRefs: toRefs,
10882 isProxy: isProxy,
10883 isReactive: isReactive,
10884 isReadonly: isReadonly,
10885 isShallow: isShallow,
10886 customRef: customRef,
10887 triggerRef: triggerRef,
10888 shallowRef: shallowRef,
10889 shallowReactive: shallowReactive,
10890 shallowReadonly: shallowReadonly,
10891 markRaw: markRaw,
10892 toRaw: toRaw,
10893 effect: effect,
10894 stop: stop,
10895 ReactiveEffect: ReactiveEffect,
10896 effectScope: effectScope,
10897 EffectScope: EffectScope,
10898 getCurrentScope: getCurrentScope,
10899 onScopeDispose: onScopeDispose,
10900 computed: computed$1,
10901 watch: watch,
10902 watchEffect: watchEffect,
10903 watchPostEffect: watchPostEffect,
10904 watchSyncEffect: watchSyncEffect,
10905 onBeforeMount: onBeforeMount,
10906 onMounted: onMounted,
10907 onBeforeUpdate: onBeforeUpdate,
10908 onUpdated: onUpdated,
10909 onBeforeUnmount: onBeforeUnmount,
10910 onUnmounted: onUnmounted,
10911 onActivated: onActivated,
10912 onDeactivated: onDeactivated,
10913 onRenderTracked: onRenderTracked,
10914 onRenderTriggered: onRenderTriggered,
10915 onErrorCaptured: onErrorCaptured,
10916 onServerPrefetch: onServerPrefetch,
10917 provide: provide,
10918 inject: inject,
10919 nextTick: nextTick,
10920 defineComponent: defineComponent,
10921 defineAsyncComponent: defineAsyncComponent,
10922 useAttrs: useAttrs,
10923 useSlots: useSlots,
10924 defineProps: defineProps,
10925 defineEmits: defineEmits,
10926 defineExpose: defineExpose,
10927 withDefaults: withDefaults,
10928 mergeDefaults: mergeDefaults,
10929 createPropsRestProxy: createPropsRestProxy,
10930 withAsyncContext: withAsyncContext,
10931 getCurrentInstance: getCurrentInstance,
10932 h: h,
10933 createVNode: createVNode,
10934 cloneVNode: cloneVNode,
10935 mergeProps: mergeProps,
10936 isVNode: isVNode,
10937 Fragment: Fragment,
10938 Text: Text,
10939 Comment: Comment,
10940 Static: Static,
10941 Teleport: Teleport,
10942 Suspense: Suspense,
10943 KeepAlive: KeepAlive,
10944 BaseTransition: BaseTransition,
10945 withDirectives: withDirectives,
10946 useSSRContext: useSSRContext,
10947 ssrContextKey: ssrContextKey,
10948 createRenderer: createRenderer,
10949 createHydrationRenderer: createHydrationRenderer,
10950 queuePostFlushCb: queuePostFlushCb,
10951 warn: warn$1,
10952 handleError: handleError,
10953 callWithErrorHandling: callWithErrorHandling,
10954 callWithAsyncErrorHandling: callWithAsyncErrorHandling,
10955 resolveComponent: resolveComponent,
10956 resolveDirective: resolveDirective,
10957 resolveDynamicComponent: resolveDynamicComponent,
10958 registerRuntimeCompiler: registerRuntimeCompiler,
10959 isRuntimeOnly: isRuntimeOnly,
10960 useTransitionState: useTransitionState,
10961 resolveTransitionHooks: resolveTransitionHooks,
10962 setTransitionHooks: setTransitionHooks,
10963 getTransitionRawChildren: getTransitionRawChildren,
10964 initCustomFormatter: initCustomFormatter,
10965 get devtools () { return devtools; },
10966 setDevtoolsHook: setDevtoolsHook,
10967 withCtx: withCtx,
10968 pushScopeId: pushScopeId,
10969 popScopeId: popScopeId,
10970 withScopeId: withScopeId,
10971 renderList: renderList,
10972 toHandlers: toHandlers,
10973 renderSlot: renderSlot,
10974 createSlots: createSlots,
10975 withMemo: withMemo,
10976 isMemoSame: isMemoSame,
10977 openBlock: openBlock,
10978 createBlock: createBlock,
10979 setBlockTracking: setBlockTracking,
10980 createTextVNode: createTextVNode,
10981 createCommentVNode: createCommentVNode,
10982 createStaticVNode: createStaticVNode,
10983 createElementVNode: createBaseVNode,
10984 createElementBlock: createElementBlock,
10985 guardReactiveProps: guardReactiveProps,
10986 toDisplayString: toDisplayString,
10987 camelize: camelize,
10988 capitalize: capitalize,
10989 toHandlerKey: toHandlerKey,
10990 normalizeProps: normalizeProps,
10991 normalizeClass: normalizeClass,
10992 normalizeStyle: normalizeStyle,
10993 transformVNodeArgs: transformVNodeArgs,
10994 version: version,
10995 ssrUtils: ssrUtils,
10996 resolveFilter: resolveFilter,
10997 compatUtils: compatUtils
10998});
10999
11000function initDev() {
11001 {
11002 {
11003 console.info(`You are running a development build of Vue.\n` +
11004 `Make sure to use the production build (*.prod.js) when deploying for production.`);
11005 }
11006 initCustomFormatter();
11007 }
11008}
11009
11010function defaultOnError(error) {
11011 throw error;
11012}
11013function defaultOnWarn(msg) {
11014 console.warn(`[Vue warn] ${msg.message}`);
11015}
11016function createCompilerError(code, loc, messages, additionalMessage) {
11017 const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
11018 ;
11019 const error = new SyntaxError(String(msg));
11020 error.code = code;
11021 error.loc = loc;
11022 return error;
11023}
11024const errorMessages = {
11025 // parse errors
11026 [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
11027 [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
11028 [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
11029 [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
11030 [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
11031 [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
11032 [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
11033 [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
11034 [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
11035 [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
11036 [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
11037 [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
11038 [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
11039 [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
11040 [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
11041 [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
11042 [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
11043 [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
11044 [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
11045 [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
11046 [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
11047 [20 /* UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
11048 [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
11049 // Vue-specific parse errors
11050 [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
11051 [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
11052 [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
11053 [27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
11054 'Note that dynamic directive argument cannot contain spaces.',
11055 [26 /* X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
11056 // transform errors
11057 [28 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
11058 [29 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
11059 [30 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
11060 [31 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
11061 [32 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
11062 [33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
11063 [34 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
11064 [35 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
11065 [36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
11066 [37 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
11067 `When there are multiple named slots, all slots should use <template> ` +
11068 `syntax to avoid scope ambiguity.`,
11069 [38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
11070 [39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
11071 `default slot. These children will be ignored.`,
11072 [40 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
11073 [41 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
11074 [42 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
11075 [43 /* X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
11076 [44 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
11077 [45 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
11078 // generic errors
11079 [46 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
11080 [47 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
11081 [48 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
11082 [49 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
11083 // just to fulfill types
11084 [50 /* __EXTEND_POINT__ */]: ``
11085};
11086
11087const FRAGMENT = Symbol(`Fragment` );
11088const TELEPORT = Symbol(`Teleport` );
11089const SUSPENSE = Symbol(`Suspense` );
11090const KEEP_ALIVE = Symbol(`KeepAlive` );
11091const BASE_TRANSITION = Symbol(`BaseTransition` );
11092const OPEN_BLOCK = Symbol(`openBlock` );
11093const CREATE_BLOCK = Symbol(`createBlock` );
11094const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` );
11095const CREATE_VNODE = Symbol(`createVNode` );
11096const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
11097const CREATE_COMMENT = Symbol(`createCommentVNode` );
11098const CREATE_TEXT = Symbol(`createTextVNode` );
11099const CREATE_STATIC = Symbol(`createStaticVNode` );
11100const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
11101const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
11102const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
11103const RESOLVE_FILTER = Symbol(`resolveFilter` );
11104const WITH_DIRECTIVES = Symbol(`withDirectives` );
11105const RENDER_LIST = Symbol(`renderList` );
11106const RENDER_SLOT = Symbol(`renderSlot` );
11107const CREATE_SLOTS = Symbol(`createSlots` );
11108const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
11109const MERGE_PROPS = Symbol(`mergeProps` );
11110const NORMALIZE_CLASS = Symbol(`normalizeClass` );
11111const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
11112const NORMALIZE_PROPS = Symbol(`normalizeProps` );
11113const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
11114const TO_HANDLERS = Symbol(`toHandlers` );
11115const CAMELIZE = Symbol(`camelize` );
11116const CAPITALIZE = Symbol(`capitalize` );
11117const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
11118const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
11119const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
11120const POP_SCOPE_ID = Symbol(`popScopeId` );
11121const WITH_CTX = Symbol(`withCtx` );
11122const UNREF = Symbol(`unref` );
11123const IS_REF = Symbol(`isRef` );
11124const WITH_MEMO = Symbol(`withMemo` );
11125const IS_MEMO_SAME = Symbol(`isMemoSame` );
11126// Name mapping for runtime helpers that need to be imported from 'vue' in
11127// generated code. Make sure these are correctly exported in the runtime!
11128// Using `any` here because TS doesn't allow symbols as index type.
11129const helperNameMap = {
11130 [FRAGMENT]: `Fragment`,
11131 [TELEPORT]: `Teleport`,
11132 [SUSPENSE]: `Suspense`,
11133 [KEEP_ALIVE]: `KeepAlive`,
11134 [BASE_TRANSITION]: `BaseTransition`,
11135 [OPEN_BLOCK]: `openBlock`,
11136 [CREATE_BLOCK]: `createBlock`,
11137 [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
11138 [CREATE_VNODE]: `createVNode`,
11139 [CREATE_ELEMENT_VNODE]: `createElementVNode`,
11140 [CREATE_COMMENT]: `createCommentVNode`,
11141 [CREATE_TEXT]: `createTextVNode`,
11142 [CREATE_STATIC]: `createStaticVNode`,
11143 [RESOLVE_COMPONENT]: `resolveComponent`,
11144 [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
11145 [RESOLVE_DIRECTIVE]: `resolveDirective`,
11146 [RESOLVE_FILTER]: `resolveFilter`,
11147 [WITH_DIRECTIVES]: `withDirectives`,
11148 [RENDER_LIST]: `renderList`,
11149 [RENDER_SLOT]: `renderSlot`,
11150 [CREATE_SLOTS]: `createSlots`,
11151 [TO_DISPLAY_STRING]: `toDisplayString`,
11152 [MERGE_PROPS]: `mergeProps`,
11153 [NORMALIZE_CLASS]: `normalizeClass`,
11154 [NORMALIZE_STYLE]: `normalizeStyle`,
11155 [NORMALIZE_PROPS]: `normalizeProps`,
11156 [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
11157 [TO_HANDLERS]: `toHandlers`,
11158 [CAMELIZE]: `camelize`,
11159 [CAPITALIZE]: `capitalize`,
11160 [TO_HANDLER_KEY]: `toHandlerKey`,
11161 [SET_BLOCK_TRACKING]: `setBlockTracking`,
11162 [PUSH_SCOPE_ID]: `pushScopeId`,
11163 [POP_SCOPE_ID]: `popScopeId`,
11164 [WITH_CTX]: `withCtx`,
11165 [UNREF]: `unref`,
11166 [IS_REF]: `isRef`,
11167 [WITH_MEMO]: `withMemo`,
11168 [IS_MEMO_SAME]: `isMemoSame`
11169};
11170function registerRuntimeHelpers(helpers) {
11171 Object.getOwnPropertySymbols(helpers).forEach(s => {
11172 helperNameMap[s] = helpers[s];
11173 });
11174}
11175
11176// AST Utilities ---------------------------------------------------------------
11177// Some expressions, e.g. sequence and conditional expressions, are never
11178// associated with template nodes, so their source locations are just a stub.
11179// Container types like CompoundExpression also don't need a real location.
11180const locStub = {
11181 source: '',
11182 start: { line: 1, column: 1, offset: 0 },
11183 end: { line: 1, column: 1, offset: 0 }
11184};
11185function createRoot(children, loc = locStub) {
11186 return {
11187 type: 0 /* ROOT */,
11188 children,
11189 helpers: [],
11190 components: [],
11191 directives: [],
11192 hoists: [],
11193 imports: [],
11194 cached: 0,
11195 temps: 0,
11196 codegenNode: undefined,
11197 loc
11198 };
11199}
11200function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
11201 if (context) {
11202 if (isBlock) {
11203 context.helper(OPEN_BLOCK);
11204 context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
11205 }
11206 else {
11207 context.helper(getVNodeHelper(context.inSSR, isComponent));
11208 }
11209 if (directives) {
11210 context.helper(WITH_DIRECTIVES);
11211 }
11212 }
11213 return {
11214 type: 13 /* VNODE_CALL */,
11215 tag,
11216 props,
11217 children,
11218 patchFlag,
11219 dynamicProps,
11220 directives,
11221 isBlock,
11222 disableTracking,
11223 isComponent,
11224 loc
11225 };
11226}
11227function createArrayExpression(elements, loc = locStub) {
11228 return {
11229 type: 17 /* JS_ARRAY_EXPRESSION */,
11230 loc,
11231 elements
11232 };
11233}
11234function createObjectExpression(properties, loc = locStub) {
11235 return {
11236 type: 15 /* JS_OBJECT_EXPRESSION */,
11237 loc,
11238 properties
11239 };
11240}
11241function createObjectProperty(key, value) {
11242 return {
11243 type: 16 /* JS_PROPERTY */,
11244 loc: locStub,
11245 key: isString(key) ? createSimpleExpression(key, true) : key,
11246 value
11247 };
11248}
11249function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
11250 return {
11251 type: 4 /* SIMPLE_EXPRESSION */,
11252 loc,
11253 content,
11254 isStatic,
11255 constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
11256 };
11257}
11258function createCompoundExpression(children, loc = locStub) {
11259 return {
11260 type: 8 /* COMPOUND_EXPRESSION */,
11261 loc,
11262 children
11263 };
11264}
11265function createCallExpression(callee, args = [], loc = locStub) {
11266 return {
11267 type: 14 /* JS_CALL_EXPRESSION */,
11268 loc,
11269 callee,
11270 arguments: args
11271 };
11272}
11273function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
11274 return {
11275 type: 18 /* JS_FUNCTION_EXPRESSION */,
11276 params,
11277 returns,
11278 newline,
11279 isSlot,
11280 loc
11281 };
11282}
11283function createConditionalExpression(test, consequent, alternate, newline = true) {
11284 return {
11285 type: 19 /* JS_CONDITIONAL_EXPRESSION */,
11286 test,
11287 consequent,
11288 alternate,
11289 newline,
11290 loc: locStub
11291 };
11292}
11293function createCacheExpression(index, value, isVNode = false) {
11294 return {
11295 type: 20 /* JS_CACHE_EXPRESSION */,
11296 index,
11297 value,
11298 isVNode,
11299 loc: locStub
11300 };
11301}
11302function createBlockStatement(body) {
11303 return {
11304 type: 21 /* JS_BLOCK_STATEMENT */,
11305 body,
11306 loc: locStub
11307 };
11308}
11309
11310const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
11311const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
11312function isCoreComponent(tag) {
11313 if (isBuiltInType(tag, 'Teleport')) {
11314 return TELEPORT;
11315 }
11316 else if (isBuiltInType(tag, 'Suspense')) {
11317 return SUSPENSE;
11318 }
11319 else if (isBuiltInType(tag, 'KeepAlive')) {
11320 return KEEP_ALIVE;
11321 }
11322 else if (isBuiltInType(tag, 'BaseTransition')) {
11323 return BASE_TRANSITION;
11324 }
11325}
11326const nonIdentifierRE = /^\d|[^\$\w]/;
11327const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
11328const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
11329const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
11330const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
11331/**
11332 * Simple lexer to check if an expression is a member expression. This is
11333 * lax and only checks validity at the root level (i.e. does not validate exps
11334 * inside square brackets), but it's ok since these are only used on template
11335 * expressions and false positives are invalid expressions in the first place.
11336 */
11337const isMemberExpressionBrowser = (path) => {
11338 // remove whitespaces around . or [ first
11339 path = path.trim().replace(whitespaceRE, s => s.trim());
11340 let state = 0 /* inMemberExp */;
11341 let stateStack = [];
11342 let currentOpenBracketCount = 0;
11343 let currentOpenParensCount = 0;
11344 let currentStringType = null;
11345 for (let i = 0; i < path.length; i++) {
11346 const char = path.charAt(i);
11347 switch (state) {
11348 case 0 /* inMemberExp */:
11349 if (char === '[') {
11350 stateStack.push(state);
11351 state = 1 /* inBrackets */;
11352 currentOpenBracketCount++;
11353 }
11354 else if (char === '(') {
11355 stateStack.push(state);
11356 state = 2 /* inParens */;
11357 currentOpenParensCount++;
11358 }
11359 else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
11360 return false;
11361 }
11362 break;
11363 case 1 /* inBrackets */:
11364 if (char === `'` || char === `"` || char === '`') {
11365 stateStack.push(state);
11366 state = 3 /* inString */;
11367 currentStringType = char;
11368 }
11369 else if (char === `[`) {
11370 currentOpenBracketCount++;
11371 }
11372 else if (char === `]`) {
11373 if (!--currentOpenBracketCount) {
11374 state = stateStack.pop();
11375 }
11376 }
11377 break;
11378 case 2 /* inParens */:
11379 if (char === `'` || char === `"` || char === '`') {
11380 stateStack.push(state);
11381 state = 3 /* inString */;
11382 currentStringType = char;
11383 }
11384 else if (char === `(`) {
11385 currentOpenParensCount++;
11386 }
11387 else if (char === `)`) {
11388 // if the exp ends as a call then it should not be considered valid
11389 if (i === path.length - 1) {
11390 return false;
11391 }
11392 if (!--currentOpenParensCount) {
11393 state = stateStack.pop();
11394 }
11395 }
11396 break;
11397 case 3 /* inString */:
11398 if (char === currentStringType) {
11399 state = stateStack.pop();
11400 currentStringType = null;
11401 }
11402 break;
11403 }
11404 }
11405 return !currentOpenBracketCount && !currentOpenParensCount;
11406};
11407const isMemberExpression = isMemberExpressionBrowser
11408 ;
11409function getInnerRange(loc, offset, length) {
11410 const source = loc.source.slice(offset, offset + length);
11411 const newLoc = {
11412 source,
11413 start: advancePositionWithClone(loc.start, loc.source, offset),
11414 end: loc.end
11415 };
11416 if (length != null) {
11417 newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
11418 }
11419 return newLoc;
11420}
11421function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
11422 return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
11423}
11424// advance by mutation without cloning (for performance reasons), since this
11425// gets called a lot in the parser
11426function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
11427 let linesCount = 0;
11428 let lastNewLinePos = -1;
11429 for (let i = 0; i < numberOfCharacters; i++) {
11430 if (source.charCodeAt(i) === 10 /* newline char code */) {
11431 linesCount++;
11432 lastNewLinePos = i;
11433 }
11434 }
11435 pos.offset += numberOfCharacters;
11436 pos.line += linesCount;
11437 pos.column =
11438 lastNewLinePos === -1
11439 ? pos.column + numberOfCharacters
11440 : numberOfCharacters - lastNewLinePos;
11441 return pos;
11442}
11443function assert(condition, msg) {
11444 /* istanbul ignore if */
11445 if (!condition) {
11446 throw new Error(msg || `unexpected compiler condition`);
11447 }
11448}
11449function findDir(node, name, allowEmpty = false) {
11450 for (let i = 0; i < node.props.length; i++) {
11451 const p = node.props[i];
11452 if (p.type === 7 /* DIRECTIVE */ &&
11453 (allowEmpty || p.exp) &&
11454 (isString(name) ? p.name === name : name.test(p.name))) {
11455 return p;
11456 }
11457 }
11458}
11459function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
11460 for (let i = 0; i < node.props.length; i++) {
11461 const p = node.props[i];
11462 if (p.type === 6 /* ATTRIBUTE */) {
11463 if (dynamicOnly)
11464 continue;
11465 if (p.name === name && (p.value || allowEmpty)) {
11466 return p;
11467 }
11468 }
11469 else if (p.name === 'bind' &&
11470 (p.exp || allowEmpty) &&
11471 isStaticArgOf(p.arg, name)) {
11472 return p;
11473 }
11474 }
11475}
11476function isStaticArgOf(arg, name) {
11477 return !!(arg && isStaticExp(arg) && arg.content === name);
11478}
11479function hasDynamicKeyVBind(node) {
11480 return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
11481 p.name === 'bind' &&
11482 (!p.arg || // v-bind="obj"
11483 p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
11484 !p.arg.isStatic) // v-bind:[foo]
11485 );
11486}
11487function isText(node) {
11488 return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
11489}
11490function isVSlot(p) {
11491 return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
11492}
11493function isTemplateNode(node) {
11494 return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
11495}
11496function isSlotOutlet(node) {
11497 return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
11498}
11499function getVNodeHelper(ssr, isComponent) {
11500 return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
11501}
11502function getVNodeBlockHelper(ssr, isComponent) {
11503 return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
11504}
11505const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
11506function getUnnormalizedProps(props, callPath = []) {
11507 if (props &&
11508 !isString(props) &&
11509 props.type === 14 /* JS_CALL_EXPRESSION */) {
11510 const callee = props.callee;
11511 if (!isString(callee) && propsHelperSet.has(callee)) {
11512 return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
11513 }
11514 }
11515 return [props, callPath];
11516}
11517function injectProp(node, prop, context) {
11518 let propsWithInjection;
11519 /**
11520 * 1. mergeProps(...)
11521 * 2. toHandlers(...)
11522 * 3. normalizeProps(...)
11523 * 4. normalizeProps(guardReactiveProps(...))
11524 *
11525 * we need to get the real props before normalization
11526 */
11527 let props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
11528 let callPath = [];
11529 let parentCall;
11530 if (props &&
11531 !isString(props) &&
11532 props.type === 14 /* JS_CALL_EXPRESSION */) {
11533 const ret = getUnnormalizedProps(props);
11534 props = ret[0];
11535 callPath = ret[1];
11536 parentCall = callPath[callPath.length - 1];
11537 }
11538 if (props == null || isString(props)) {
11539 propsWithInjection = createObjectExpression([prop]);
11540 }
11541 else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
11542 // merged props... add ours
11543 // only inject key to object literal if it's the first argument so that
11544 // if doesn't override user provided keys
11545 const first = props.arguments[0];
11546 if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
11547 first.properties.unshift(prop);
11548 }
11549 else {
11550 if (props.callee === TO_HANDLERS) {
11551 // #2366
11552 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
11553 createObjectExpression([prop]),
11554 props
11555 ]);
11556 }
11557 else {
11558 props.arguments.unshift(createObjectExpression([prop]));
11559 }
11560 }
11561 !propsWithInjection && (propsWithInjection = props);
11562 }
11563 else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
11564 let alreadyExists = false;
11565 // check existing key to avoid overriding user provided keys
11566 if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
11567 const propKeyName = prop.key.content;
11568 alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
11569 p.key.content === propKeyName);
11570 }
11571 if (!alreadyExists) {
11572 props.properties.unshift(prop);
11573 }
11574 propsWithInjection = props;
11575 }
11576 else {
11577 // single v-bind with expression, return a merged replacement
11578 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
11579 createObjectExpression([prop]),
11580 props
11581 ]);
11582 // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
11583 // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
11584 // the `guardReactiveProps` will no longer be needed
11585 if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
11586 parentCall = callPath[callPath.length - 2];
11587 }
11588 }
11589 if (node.type === 13 /* VNODE_CALL */) {
11590 if (parentCall) {
11591 parentCall.arguments[0] = propsWithInjection;
11592 }
11593 else {
11594 node.props = propsWithInjection;
11595 }
11596 }
11597 else {
11598 if (parentCall) {
11599 parentCall.arguments[0] = propsWithInjection;
11600 }
11601 else {
11602 node.arguments[2] = propsWithInjection;
11603 }
11604 }
11605}
11606function toValidAssetId(name, type) {
11607 // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
11608 return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
11609 return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
11610 })}`;
11611}
11612function getMemoedVNodeCall(node) {
11613 if (node.type === 14 /* JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
11614 return node.arguments[1].returns;
11615 }
11616 else {
11617 return node;
11618 }
11619}
11620function makeBlock(node, { helper, removeHelper, inSSR }) {
11621 if (!node.isBlock) {
11622 node.isBlock = true;
11623 removeHelper(getVNodeHelper(inSSR, node.isComponent));
11624 helper(OPEN_BLOCK);
11625 helper(getVNodeBlockHelper(inSSR, node.isComponent));
11626 }
11627}
11628
11629const deprecationData = {
11630 ["COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */]: {
11631 message: `Platform-native elements with "is" prop will no longer be ` +
11632 `treated as components in Vue 3 unless the "is" value is explicitly ` +
11633 `prefixed with "vue:".`,
11634 link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html`
11635 },
11636 ["COMPILER_V_BIND_SYNC" /* COMPILER_V_BIND_SYNC */]: {
11637 message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
11638 `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
11639 `\`v-model:${key}\`.`,
11640 link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html`
11641 },
11642 ["COMPILER_V_BIND_PROP" /* COMPILER_V_BIND_PROP */]: {
11643 message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
11644 `Vue 3 will automatically set a binding as DOM property when appropriate.`
11645 },
11646 ["COMPILER_V_BIND_OBJECT_ORDER" /* COMPILER_V_BIND_OBJECT_ORDER */]: {
11647 message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
11648 `object spread: it will now overwrite an existing non-mergeable attribute ` +
11649 `that appears before v-bind in the case of conflict. ` +
11650 `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
11651 `You can also suppress this warning if the usage is intended.`,
11652 link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html`
11653 },
11654 ["COMPILER_V_ON_NATIVE" /* COMPILER_V_ON_NATIVE */]: {
11655 message: `.native modifier for v-on has been removed as is no longer necessary.`,
11656 link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html`
11657 },
11658 ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
11659 message: `v-if / v-for precedence when used on the same element has changed ` +
11660 `in Vue 3: v-if now takes higher precedence and will no longer have ` +
11661 `access to v-for scope variables. It is best to avoid the ambiguity ` +
11662 `with <template> tags or use a computed property that filters v-for ` +
11663 `data source.`,
11664 link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html`
11665 },
11666 ["COMPILER_NATIVE_TEMPLATE" /* COMPILER_NATIVE_TEMPLATE */]: {
11667 message: `<template> with no special directives will render as a native template ` +
11668 `element instead of its inner content in Vue 3.`
11669 },
11670 ["COMPILER_INLINE_TEMPLATE" /* COMPILER_INLINE_TEMPLATE */]: {
11671 message: `"inline-template" has been removed in Vue 3.`,
11672 link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html`
11673 },
11674 ["COMPILER_FILTER" /* COMPILER_FILTERS */]: {
11675 message: `filters have been removed in Vue 3. ` +
11676 `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
11677 `Use method calls or computed properties instead.`,
11678 link: `https://v3-migration.vuejs.org/breaking-changes/filters.html`
11679 }
11680};
11681function getCompatValue(key, context) {
11682 const config = context.options
11683 ? context.options.compatConfig
11684 : context.compatConfig;
11685 const value = config && config[key];
11686 if (key === 'MODE') {
11687 return value || 3; // compiler defaults to v3 behavior
11688 }
11689 else {
11690 return value;
11691 }
11692}
11693function isCompatEnabled(key, context) {
11694 const mode = getCompatValue('MODE', context);
11695 const value = getCompatValue(key, context);
11696 // in v3 mode, only enable if explicitly set to true
11697 // otherwise enable for any non-false value
11698 return mode === 3 ? value === true : value !== false;
11699}
11700function checkCompatEnabled(key, context, loc, ...args) {
11701 const enabled = isCompatEnabled(key, context);
11702 if (enabled) {
11703 warnDeprecation(key, context, loc, ...args);
11704 }
11705 return enabled;
11706}
11707function warnDeprecation(key, context, loc, ...args) {
11708 const val = getCompatValue(key, context);
11709 if (val === 'suppress-warning') {
11710 return;
11711 }
11712 const { message, link } = deprecationData[key];
11713 const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
11714 const err = new SyntaxError(msg);
11715 err.code = key;
11716 if (loc)
11717 err.loc = loc;
11718 context.onWarn(err);
11719}
11720
11721// The default decoder only provides escapes for characters reserved as part of
11722// the template syntax, and is only used if the custom renderer did not provide
11723// a platform-specific decoder.
11724const decodeRE = /&(gt|lt|amp|apos|quot);/g;
11725const decodeMap = {
11726 gt: '>',
11727 lt: '<',
11728 amp: '&',
11729 apos: "'",
11730 quot: '"'
11731};
11732const defaultParserOptions = {
11733 delimiters: [`{{`, `}}`],
11734 getNamespace: () => 0 /* HTML */,
11735 getTextMode: () => 0 /* DATA */,
11736 isVoidTag: NO,
11737 isPreTag: NO,
11738 isCustomElement: NO,
11739 decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
11740 onError: defaultOnError,
11741 onWarn: defaultOnWarn,
11742 comments: true
11743};
11744function baseParse(content, options = {}) {
11745 const context = createParserContext(content, options);
11746 const start = getCursor(context);
11747 return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
11748}
11749function createParserContext(content, rawOptions) {
11750 const options = extend({}, defaultParserOptions);
11751 let key;
11752 for (key in rawOptions) {
11753 // @ts-ignore
11754 options[key] =
11755 rawOptions[key] === undefined
11756 ? defaultParserOptions[key]
11757 : rawOptions[key];
11758 }
11759 return {
11760 options,
11761 column: 1,
11762 line: 1,
11763 offset: 0,
11764 originalSource: content,
11765 source: content,
11766 inPre: false,
11767 inVPre: false,
11768 onWarn: options.onWarn
11769 };
11770}
11771function parseChildren(context, mode, ancestors) {
11772 const parent = last(ancestors);
11773 const ns = parent ? parent.ns : 0 /* HTML */;
11774 const nodes = [];
11775 while (!isEnd(context, mode, ancestors)) {
11776 const s = context.source;
11777 let node = undefined;
11778 if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
11779 if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
11780 // '{{'
11781 node = parseInterpolation(context, mode);
11782 }
11783 else if (mode === 0 /* DATA */ && s[0] === '<') {
11784 // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
11785 if (s.length === 1) {
11786 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
11787 }
11788 else if (s[1] === '!') {
11789 // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
11790 if (startsWith(s, '<!--')) {
11791 node = parseComment(context);
11792 }
11793 else if (startsWith(s, '<!DOCTYPE')) {
11794 // Ignore DOCTYPE by a limitation.
11795 node = parseBogusComment(context);
11796 }
11797 else if (startsWith(s, '<![CDATA[')) {
11798 if (ns !== 0 /* HTML */) {
11799 node = parseCDATA(context, ancestors);
11800 }
11801 else {
11802 emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
11803 node = parseBogusComment(context);
11804 }
11805 }
11806 else {
11807 emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
11808 node = parseBogusComment(context);
11809 }
11810 }
11811 else if (s[1] === '/') {
11812 // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
11813 if (s.length === 2) {
11814 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
11815 }
11816 else if (s[2] === '>') {
11817 emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
11818 advanceBy(context, 3);
11819 continue;
11820 }
11821 else if (/[a-z]/i.test(s[2])) {
11822 emitError(context, 23 /* X_INVALID_END_TAG */);
11823 parseTag(context, 1 /* End */, parent);
11824 continue;
11825 }
11826 else {
11827 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
11828 node = parseBogusComment(context);
11829 }
11830 }
11831 else if (/[a-z]/i.test(s[1])) {
11832 node = parseElement(context, ancestors);
11833 }
11834 else if (s[1] === '?') {
11835 emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
11836 node = parseBogusComment(context);
11837 }
11838 else {
11839 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
11840 }
11841 }
11842 }
11843 if (!node) {
11844 node = parseText(context, mode);
11845 }
11846 if (isArray(node)) {
11847 for (let i = 0; i < node.length; i++) {
11848 pushNode(nodes, node[i]);
11849 }
11850 }
11851 else {
11852 pushNode(nodes, node);
11853 }
11854 }
11855 // Whitespace handling strategy like v2
11856 let removedWhitespace = false;
11857 if (mode !== 2 /* RAWTEXT */ && mode !== 1 /* RCDATA */) {
11858 const shouldCondense = context.options.whitespace !== 'preserve';
11859 for (let i = 0; i < nodes.length; i++) {
11860 const node = nodes[i];
11861 if (!context.inPre && node.type === 2 /* TEXT */) {
11862 if (!/[^\t\r\n\f ]/.test(node.content)) {
11863 const prev = nodes[i - 1];
11864 const next = nodes[i + 1];
11865 // Remove if:
11866 // - the whitespace is the first or last node, or:
11867 // - (condense mode) the whitespace is adjacent to a comment, or:
11868 // - (condense mode) the whitespace is between two elements AND contains newline
11869 if (!prev ||
11870 !next ||
11871 (shouldCondense &&
11872 (prev.type === 3 /* COMMENT */ ||
11873 next.type === 3 /* COMMENT */ ||
11874 (prev.type === 1 /* ELEMENT */ &&
11875 next.type === 1 /* ELEMENT */ &&
11876 /[\r\n]/.test(node.content))))) {
11877 removedWhitespace = true;
11878 nodes[i] = null;
11879 }
11880 else {
11881 // Otherwise, the whitespace is condensed into a single space
11882 node.content = ' ';
11883 }
11884 }
11885 else if (shouldCondense) {
11886 // in condense mode, consecutive whitespaces in text are condensed
11887 // down to a single space.
11888 node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
11889 }
11890 }
11891 // Remove comment nodes if desired by configuration.
11892 else if (node.type === 3 /* COMMENT */ && !context.options.comments) {
11893 removedWhitespace = true;
11894 nodes[i] = null;
11895 }
11896 }
11897 if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
11898 // remove leading newline per html spec
11899 // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
11900 const first = nodes[0];
11901 if (first && first.type === 2 /* TEXT */) {
11902 first.content = first.content.replace(/^\r?\n/, '');
11903 }
11904 }
11905 }
11906 return removedWhitespace ? nodes.filter(Boolean) : nodes;
11907}
11908function pushNode(nodes, node) {
11909 if (node.type === 2 /* TEXT */) {
11910 const prev = last(nodes);
11911 // Merge if both this and the previous node are text and those are
11912 // consecutive. This happens for cases like "a < b".
11913 if (prev &&
11914 prev.type === 2 /* TEXT */ &&
11915 prev.loc.end.offset === node.loc.start.offset) {
11916 prev.content += node.content;
11917 prev.loc.end = node.loc.end;
11918 prev.loc.source += node.loc.source;
11919 return;
11920 }
11921 }
11922 nodes.push(node);
11923}
11924function parseCDATA(context, ancestors) {
11925 advanceBy(context, 9);
11926 const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
11927 if (context.source.length === 0) {
11928 emitError(context, 6 /* EOF_IN_CDATA */);
11929 }
11930 else {
11931 advanceBy(context, 3);
11932 }
11933 return nodes;
11934}
11935function parseComment(context) {
11936 const start = getCursor(context);
11937 let content;
11938 // Regular comment.
11939 const match = /--(\!)?>/.exec(context.source);
11940 if (!match) {
11941 content = context.source.slice(4);
11942 advanceBy(context, context.source.length);
11943 emitError(context, 7 /* EOF_IN_COMMENT */);
11944 }
11945 else {
11946 if (match.index <= 3) {
11947 emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
11948 }
11949 if (match[1]) {
11950 emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
11951 }
11952 content = context.source.slice(4, match.index);
11953 // Advancing with reporting nested comments.
11954 const s = context.source.slice(0, match.index);
11955 let prevIndex = 1, nestedIndex = 0;
11956 while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
11957 advanceBy(context, nestedIndex - prevIndex + 1);
11958 if (nestedIndex + 4 < s.length) {
11959 emitError(context, 16 /* NESTED_COMMENT */);
11960 }
11961 prevIndex = nestedIndex + 1;
11962 }
11963 advanceBy(context, match.index + match[0].length - prevIndex + 1);
11964 }
11965 return {
11966 type: 3 /* COMMENT */,
11967 content,
11968 loc: getSelection(context, start)
11969 };
11970}
11971function parseBogusComment(context) {
11972 const start = getCursor(context);
11973 const contentStart = context.source[1] === '?' ? 1 : 2;
11974 let content;
11975 const closeIndex = context.source.indexOf('>');
11976 if (closeIndex === -1) {
11977 content = context.source.slice(contentStart);
11978 advanceBy(context, context.source.length);
11979 }
11980 else {
11981 content = context.source.slice(contentStart, closeIndex);
11982 advanceBy(context, closeIndex + 1);
11983 }
11984 return {
11985 type: 3 /* COMMENT */,
11986 content,
11987 loc: getSelection(context, start)
11988 };
11989}
11990function parseElement(context, ancestors) {
11991 // Start tag.
11992 const wasInPre = context.inPre;
11993 const wasInVPre = context.inVPre;
11994 const parent = last(ancestors);
11995 const element = parseTag(context, 0 /* Start */, parent);
11996 const isPreBoundary = context.inPre && !wasInPre;
11997 const isVPreBoundary = context.inVPre && !wasInVPre;
11998 if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
11999 // #4030 self-closing <pre> tag
12000 if (isPreBoundary) {
12001 context.inPre = false;
12002 }
12003 if (isVPreBoundary) {
12004 context.inVPre = false;
12005 }
12006 return element;
12007 }
12008 // Children.
12009 ancestors.push(element);
12010 const mode = context.options.getTextMode(element, parent);
12011 const children = parseChildren(context, mode, ancestors);
12012 ancestors.pop();
12013 element.children = children;
12014 // End tag.
12015 if (startsWithEndTagOpen(context.source, element.tag)) {
12016 parseTag(context, 1 /* End */, parent);
12017 }
12018 else {
12019 emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
12020 if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
12021 const first = children[0];
12022 if (first && startsWith(first.loc.source, '<!--')) {
12023 emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
12024 }
12025 }
12026 }
12027 element.loc = getSelection(context, element.loc.start);
12028 if (isPreBoundary) {
12029 context.inPre = false;
12030 }
12031 if (isVPreBoundary) {
12032 context.inVPre = false;
12033 }
12034 return element;
12035}
12036const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
12037function parseTag(context, type, parent) {
12038 // Tag open.
12039 const start = getCursor(context);
12040 const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
12041 const tag = match[1];
12042 const ns = context.options.getNamespace(tag, parent);
12043 advanceBy(context, match[0].length);
12044 advanceSpaces(context);
12045 // save current state in case we need to re-parse attributes with v-pre
12046 const cursor = getCursor(context);
12047 const currentSource = context.source;
12048 // check <pre> tag
12049 if (context.options.isPreTag(tag)) {
12050 context.inPre = true;
12051 }
12052 // Attributes.
12053 let props = parseAttributes(context, type);
12054 // check v-pre
12055 if (type === 0 /* Start */ &&
12056 !context.inVPre &&
12057 props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
12058 context.inVPre = true;
12059 // reset context
12060 extend(context, cursor);
12061 context.source = currentSource;
12062 // re-parse attrs and filter out v-pre itself
12063 props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
12064 }
12065 // Tag close.
12066 let isSelfClosing = false;
12067 if (context.source.length === 0) {
12068 emitError(context, 9 /* EOF_IN_TAG */);
12069 }
12070 else {
12071 isSelfClosing = startsWith(context.source, '/>');
12072 if (type === 1 /* End */ && isSelfClosing) {
12073 emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
12074 }
12075 advanceBy(context, isSelfClosing ? 2 : 1);
12076 }
12077 if (type === 1 /* End */) {
12078 return;
12079 }
12080 let tagType = 0 /* ELEMENT */;
12081 if (!context.inVPre) {
12082 if (tag === 'slot') {
12083 tagType = 2 /* SLOT */;
12084 }
12085 else if (tag === 'template') {
12086 if (props.some(p => p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
12087 tagType = 3 /* TEMPLATE */;
12088 }
12089 }
12090 else if (isComponent(tag, props, context)) {
12091 tagType = 1 /* COMPONENT */;
12092 }
12093 }
12094 return {
12095 type: 1 /* ELEMENT */,
12096 ns,
12097 tag,
12098 tagType,
12099 props,
12100 isSelfClosing,
12101 children: [],
12102 loc: getSelection(context, start),
12103 codegenNode: undefined // to be created during transform phase
12104 };
12105}
12106function isComponent(tag, props, context) {
12107 const options = context.options;
12108 if (options.isCustomElement(tag)) {
12109 return false;
12110 }
12111 if (tag === 'component' ||
12112 /^[A-Z]/.test(tag) ||
12113 isCoreComponent(tag) ||
12114 (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
12115 (options.isNativeTag && !options.isNativeTag(tag))) {
12116 return true;
12117 }
12118 // at this point the tag should be a native tag, but check for potential "is"
12119 // casting
12120 for (let i = 0; i < props.length; i++) {
12121 const p = props[i];
12122 if (p.type === 6 /* ATTRIBUTE */) {
12123 if (p.name === 'is' && p.value) {
12124 if (p.value.content.startsWith('vue:')) {
12125 return true;
12126 }
12127 }
12128 }
12129 else {
12130 // directive
12131 // v-is (TODO Deprecate)
12132 if (p.name === 'is') {
12133 return true;
12134 }
12135 else if (
12136 // :is on plain element - only treat as component in compat mode
12137 p.name === 'bind' &&
12138 isStaticArgOf(p.arg, 'is') &&
12139 false &&
12140 checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
12141 return true;
12142 }
12143 }
12144 }
12145}
12146function parseAttributes(context, type) {
12147 const props = [];
12148 const attributeNames = new Set();
12149 while (context.source.length > 0 &&
12150 !startsWith(context.source, '>') &&
12151 !startsWith(context.source, '/>')) {
12152 if (startsWith(context.source, '/')) {
12153 emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
12154 advanceBy(context, 1);
12155 advanceSpaces(context);
12156 continue;
12157 }
12158 if (type === 1 /* End */) {
12159 emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
12160 }
12161 const attr = parseAttribute(context, attributeNames);
12162 // Trim whitespace between class
12163 // https://github.com/vuejs/core/issues/4251
12164 if (attr.type === 6 /* ATTRIBUTE */ &&
12165 attr.value &&
12166 attr.name === 'class') {
12167 attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
12168 }
12169 if (type === 0 /* Start */) {
12170 props.push(attr);
12171 }
12172 if (/^[^\t\r\n\f />]/.test(context.source)) {
12173 emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
12174 }
12175 advanceSpaces(context);
12176 }
12177 return props;
12178}
12179function parseAttribute(context, nameSet) {
12180 // Name.
12181 const start = getCursor(context);
12182 const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
12183 const name = match[0];
12184 if (nameSet.has(name)) {
12185 emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
12186 }
12187 nameSet.add(name);
12188 if (name[0] === '=') {
12189 emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
12190 }
12191 {
12192 const pattern = /["'<]/g;
12193 let m;
12194 while ((m = pattern.exec(name))) {
12195 emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
12196 }
12197 }
12198 advanceBy(context, name.length);
12199 // Value
12200 let value = undefined;
12201 if (/^[\t\r\n\f ]*=/.test(context.source)) {
12202 advanceSpaces(context);
12203 advanceBy(context, 1);
12204 advanceSpaces(context);
12205 value = parseAttributeValue(context);
12206 if (!value) {
12207 emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
12208 }
12209 }
12210 const loc = getSelection(context, start);
12211 if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
12212 const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
12213 let isPropShorthand = startsWith(name, '.');
12214 let dirName = match[1] ||
12215 (isPropShorthand || startsWith(name, ':')
12216 ? 'bind'
12217 : startsWith(name, '@')
12218 ? 'on'
12219 : 'slot');
12220 let arg;
12221 if (match[2]) {
12222 const isSlot = dirName === 'slot';
12223 const startOffset = name.lastIndexOf(match[2]);
12224 const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
12225 let content = match[2];
12226 let isStatic = true;
12227 if (content.startsWith('[')) {
12228 isStatic = false;
12229 if (!content.endsWith(']')) {
12230 emitError(context, 27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
12231 content = content.slice(1);
12232 }
12233 else {
12234 content = content.slice(1, content.length - 1);
12235 }
12236 }
12237 else if (isSlot) {
12238 // #1241 special case for v-slot: vuetify relies extensively on slot
12239 // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
12240 // supports such usage so we are keeping it consistent with 2.x.
12241 content += match[3] || '';
12242 }
12243 arg = {
12244 type: 4 /* SIMPLE_EXPRESSION */,
12245 content,
12246 isStatic,
12247 constType: isStatic
12248 ? 3 /* CAN_STRINGIFY */
12249 : 0 /* NOT_CONSTANT */,
12250 loc
12251 };
12252 }
12253 if (value && value.isQuoted) {
12254 const valueLoc = value.loc;
12255 valueLoc.start.offset++;
12256 valueLoc.start.column++;
12257 valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
12258 valueLoc.source = valueLoc.source.slice(1, -1);
12259 }
12260 const modifiers = match[3] ? match[3].slice(1).split('.') : [];
12261 if (isPropShorthand)
12262 modifiers.push('prop');
12263 return {
12264 type: 7 /* DIRECTIVE */,
12265 name: dirName,
12266 exp: value && {
12267 type: 4 /* SIMPLE_EXPRESSION */,
12268 content: value.content,
12269 isStatic: false,
12270 // Treat as non-constant by default. This can be potentially set to
12271 // other values by `transformExpression` to make it eligible for hoisting.
12272 constType: 0 /* NOT_CONSTANT */,
12273 loc: value.loc
12274 },
12275 arg,
12276 modifiers,
12277 loc
12278 };
12279 }
12280 // missing directive name or illegal directive name
12281 if (!context.inVPre && startsWith(name, 'v-')) {
12282 emitError(context, 26 /* X_MISSING_DIRECTIVE_NAME */);
12283 }
12284 return {
12285 type: 6 /* ATTRIBUTE */,
12286 name,
12287 value: value && {
12288 type: 2 /* TEXT */,
12289 content: value.content,
12290 loc: value.loc
12291 },
12292 loc
12293 };
12294}
12295function parseAttributeValue(context) {
12296 const start = getCursor(context);
12297 let content;
12298 const quote = context.source[0];
12299 const isQuoted = quote === `"` || quote === `'`;
12300 if (isQuoted) {
12301 // Quoted value.
12302 advanceBy(context, 1);
12303 const endIndex = context.source.indexOf(quote);
12304 if (endIndex === -1) {
12305 content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
12306 }
12307 else {
12308 content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
12309 advanceBy(context, 1);
12310 }
12311 }
12312 else {
12313 // Unquoted
12314 const match = /^[^\t\r\n\f >]+/.exec(context.source);
12315 if (!match) {
12316 return undefined;
12317 }
12318 const unexpectedChars = /["'<=`]/g;
12319 let m;
12320 while ((m = unexpectedChars.exec(match[0]))) {
12321 emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
12322 }
12323 content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
12324 }
12325 return { content, isQuoted, loc: getSelection(context, start) };
12326}
12327function parseInterpolation(context, mode) {
12328 const [open, close] = context.options.delimiters;
12329 const closeIndex = context.source.indexOf(close, open.length);
12330 if (closeIndex === -1) {
12331 emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
12332 return undefined;
12333 }
12334 const start = getCursor(context);
12335 advanceBy(context, open.length);
12336 const innerStart = getCursor(context);
12337 const innerEnd = getCursor(context);
12338 const rawContentLength = closeIndex - open.length;
12339 const rawContent = context.source.slice(0, rawContentLength);
12340 const preTrimContent = parseTextData(context, rawContentLength, mode);
12341 const content = preTrimContent.trim();
12342 const startOffset = preTrimContent.indexOf(content);
12343 if (startOffset > 0) {
12344 advancePositionWithMutation(innerStart, rawContent, startOffset);
12345 }
12346 const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
12347 advancePositionWithMutation(innerEnd, rawContent, endOffset);
12348 advanceBy(context, close.length);
12349 return {
12350 type: 5 /* INTERPOLATION */,
12351 content: {
12352 type: 4 /* SIMPLE_EXPRESSION */,
12353 isStatic: false,
12354 // Set `isConstant` to false by default and will decide in transformExpression
12355 constType: 0 /* NOT_CONSTANT */,
12356 content,
12357 loc: getSelection(context, innerStart, innerEnd)
12358 },
12359 loc: getSelection(context, start)
12360 };
12361}
12362function parseText(context, mode) {
12363 const endTokens = mode === 3 /* CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
12364 let endIndex = context.source.length;
12365 for (let i = 0; i < endTokens.length; i++) {
12366 const index = context.source.indexOf(endTokens[i], 1);
12367 if (index !== -1 && endIndex > index) {
12368 endIndex = index;
12369 }
12370 }
12371 const start = getCursor(context);
12372 const content = parseTextData(context, endIndex, mode);
12373 return {
12374 type: 2 /* TEXT */,
12375 content,
12376 loc: getSelection(context, start)
12377 };
12378}
12379/**
12380 * Get text data with a given length from the current location.
12381 * This translates HTML entities in the text data.
12382 */
12383function parseTextData(context, length, mode) {
12384 const rawText = context.source.slice(0, length);
12385 advanceBy(context, length);
12386 if (mode === 2 /* RAWTEXT */ ||
12387 mode === 3 /* CDATA */ ||
12388 !rawText.includes('&')) {
12389 return rawText;
12390 }
12391 else {
12392 // DATA or RCDATA containing "&"". Entity decoding required.
12393 return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
12394 }
12395}
12396function getCursor(context) {
12397 const { column, line, offset } = context;
12398 return { column, line, offset };
12399}
12400function getSelection(context, start, end) {
12401 end = end || getCursor(context);
12402 return {
12403 start,
12404 end,
12405 source: context.originalSource.slice(start.offset, end.offset)
12406 };
12407}
12408function last(xs) {
12409 return xs[xs.length - 1];
12410}
12411function startsWith(source, searchString) {
12412 return source.startsWith(searchString);
12413}
12414function advanceBy(context, numberOfCharacters) {
12415 const { source } = context;
12416 advancePositionWithMutation(context, source, numberOfCharacters);
12417 context.source = source.slice(numberOfCharacters);
12418}
12419function advanceSpaces(context) {
12420 const match = /^[\t\r\n\f ]+/.exec(context.source);
12421 if (match) {
12422 advanceBy(context, match[0].length);
12423 }
12424}
12425function getNewPosition(context, start, numberOfCharacters) {
12426 return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
12427}
12428function emitError(context, code, offset, loc = getCursor(context)) {
12429 if (offset) {
12430 loc.offset += offset;
12431 loc.column += offset;
12432 }
12433 context.options.onError(createCompilerError(code, {
12434 start: loc,
12435 end: loc,
12436 source: ''
12437 }));
12438}
12439function isEnd(context, mode, ancestors) {
12440 const s = context.source;
12441 switch (mode) {
12442 case 0 /* DATA */:
12443 if (startsWith(s, '</')) {
12444 // TODO: probably bad performance
12445 for (let i = ancestors.length - 1; i >= 0; --i) {
12446 if (startsWithEndTagOpen(s, ancestors[i].tag)) {
12447 return true;
12448 }
12449 }
12450 }
12451 break;
12452 case 1 /* RCDATA */:
12453 case 2 /* RAWTEXT */: {
12454 const parent = last(ancestors);
12455 if (parent && startsWithEndTagOpen(s, parent.tag)) {
12456 return true;
12457 }
12458 break;
12459 }
12460 case 3 /* CDATA */:
12461 if (startsWith(s, ']]>')) {
12462 return true;
12463 }
12464 break;
12465 }
12466 return !s;
12467}
12468function startsWithEndTagOpen(source, tag) {
12469 return (startsWith(source, '</') &&
12470 source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() &&
12471 /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
12472}
12473
12474function hoistStatic(root, context) {
12475 walk(root, context,
12476 // Root node is unfortunately non-hoistable due to potential parent
12477 // fallthrough attributes.
12478 isSingleElementRoot(root, root.children[0]));
12479}
12480function isSingleElementRoot(root, child) {
12481 const { children } = root;
12482 return (children.length === 1 &&
12483 child.type === 1 /* ELEMENT */ &&
12484 !isSlotOutlet(child));
12485}
12486function walk(node, context, doNotHoistNode = false) {
12487 const { children } = node;
12488 const originalCount = children.length;
12489 let hoistedCount = 0;
12490 for (let i = 0; i < children.length; i++) {
12491 const child = children[i];
12492 // only plain elements & text calls are eligible for hoisting.
12493 if (child.type === 1 /* ELEMENT */ &&
12494 child.tagType === 0 /* ELEMENT */) {
12495 const constantType = doNotHoistNode
12496 ? 0 /* NOT_CONSTANT */
12497 : getConstantType(child, context);
12498 if (constantType > 0 /* NOT_CONSTANT */) {
12499 if (constantType >= 2 /* CAN_HOIST */) {
12500 child.codegenNode.patchFlag =
12501 -1 /* HOISTED */ + (` /* HOISTED */` );
12502 child.codegenNode = context.hoist(child.codegenNode);
12503 hoistedCount++;
12504 continue;
12505 }
12506 }
12507 else {
12508 // node may contain dynamic children, but its props may be eligible for
12509 // hoisting.
12510 const codegenNode = child.codegenNode;
12511 if (codegenNode.type === 13 /* VNODE_CALL */) {
12512 const flag = getPatchFlag(codegenNode);
12513 if ((!flag ||
12514 flag === 512 /* NEED_PATCH */ ||
12515 flag === 1 /* TEXT */) &&
12516 getGeneratedPropsConstantType(child, context) >=
12517 2 /* CAN_HOIST */) {
12518 const props = getNodeProps(child);
12519 if (props) {
12520 codegenNode.props = context.hoist(props);
12521 }
12522 }
12523 if (codegenNode.dynamicProps) {
12524 codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
12525 }
12526 }
12527 }
12528 }
12529 else if (child.type === 12 /* TEXT_CALL */ &&
12530 getConstantType(child.content, context) >= 2 /* CAN_HOIST */) {
12531 child.codegenNode = context.hoist(child.codegenNode);
12532 hoistedCount++;
12533 }
12534 // walk further
12535 if (child.type === 1 /* ELEMENT */) {
12536 const isComponent = child.tagType === 1 /* COMPONENT */;
12537 if (isComponent) {
12538 context.scopes.vSlot++;
12539 }
12540 walk(child, context);
12541 if (isComponent) {
12542 context.scopes.vSlot--;
12543 }
12544 }
12545 else if (child.type === 11 /* FOR */) {
12546 // Do not hoist v-for single child because it has to be a block
12547 walk(child, context, child.children.length === 1);
12548 }
12549 else if (child.type === 9 /* IF */) {
12550 for (let i = 0; i < child.branches.length; i++) {
12551 // Do not hoist v-if single child because it has to be a block
12552 walk(child.branches[i], context, child.branches[i].children.length === 1);
12553 }
12554 }
12555 }
12556 if (hoistedCount && context.transformHoist) {
12557 context.transformHoist(children, context, node);
12558 }
12559 // all children were hoisted - the entire children array is hoistable.
12560 if (hoistedCount &&
12561 hoistedCount === originalCount &&
12562 node.type === 1 /* ELEMENT */ &&
12563 node.tagType === 0 /* ELEMENT */ &&
12564 node.codegenNode &&
12565 node.codegenNode.type === 13 /* VNODE_CALL */ &&
12566 isArray(node.codegenNode.children)) {
12567 node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
12568 }
12569}
12570function getConstantType(node, context) {
12571 const { constantCache } = context;
12572 switch (node.type) {
12573 case 1 /* ELEMENT */:
12574 if (node.tagType !== 0 /* ELEMENT */) {
12575 return 0 /* NOT_CONSTANT */;
12576 }
12577 const cached = constantCache.get(node);
12578 if (cached !== undefined) {
12579 return cached;
12580 }
12581 const codegenNode = node.codegenNode;
12582 if (codegenNode.type !== 13 /* VNODE_CALL */) {
12583 return 0 /* NOT_CONSTANT */;
12584 }
12585 if (codegenNode.isBlock &&
12586 node.tag !== 'svg' &&
12587 node.tag !== 'foreignObject') {
12588 return 0 /* NOT_CONSTANT */;
12589 }
12590 const flag = getPatchFlag(codegenNode);
12591 if (!flag) {
12592 let returnType = 3 /* CAN_STRINGIFY */;
12593 // Element itself has no patch flag. However we still need to check:
12594 // 1. Even for a node with no patch flag, it is possible for it to contain
12595 // non-hoistable expressions that refers to scope variables, e.g. compiler
12596 // injected keys or cached event handlers. Therefore we need to always
12597 // check the codegenNode's props to be sure.
12598 const generatedPropsType = getGeneratedPropsConstantType(node, context);
12599 if (generatedPropsType === 0 /* NOT_CONSTANT */) {
12600 constantCache.set(node, 0 /* NOT_CONSTANT */);
12601 return 0 /* NOT_CONSTANT */;
12602 }
12603 if (generatedPropsType < returnType) {
12604 returnType = generatedPropsType;
12605 }
12606 // 2. its children.
12607 for (let i = 0; i < node.children.length; i++) {
12608 const childType = getConstantType(node.children[i], context);
12609 if (childType === 0 /* NOT_CONSTANT */) {
12610 constantCache.set(node, 0 /* NOT_CONSTANT */);
12611 return 0 /* NOT_CONSTANT */;
12612 }
12613 if (childType < returnType) {
12614 returnType = childType;
12615 }
12616 }
12617 // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
12618 // type, check if any of the props can cause the type to be lowered
12619 // we can skip can_patch because it's guaranteed by the absence of a
12620 // patchFlag.
12621 if (returnType > 1 /* CAN_SKIP_PATCH */) {
12622 for (let i = 0; i < node.props.length; i++) {
12623 const p = node.props[i];
12624 if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
12625 const expType = getConstantType(p.exp, context);
12626 if (expType === 0 /* NOT_CONSTANT */) {
12627 constantCache.set(node, 0 /* NOT_CONSTANT */);
12628 return 0 /* NOT_CONSTANT */;
12629 }
12630 if (expType < returnType) {
12631 returnType = expType;
12632 }
12633 }
12634 }
12635 }
12636 // only svg/foreignObject could be block here, however if they are
12637 // static then they don't need to be blocks since there will be no
12638 // nested updates.
12639 if (codegenNode.isBlock) {
12640 context.removeHelper(OPEN_BLOCK);
12641 context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
12642 codegenNode.isBlock = false;
12643 context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
12644 }
12645 constantCache.set(node, returnType);
12646 return returnType;
12647 }
12648 else {
12649 constantCache.set(node, 0 /* NOT_CONSTANT */);
12650 return 0 /* NOT_CONSTANT */;
12651 }
12652 case 2 /* TEXT */:
12653 case 3 /* COMMENT */:
12654 return 3 /* CAN_STRINGIFY */;
12655 case 9 /* IF */:
12656 case 11 /* FOR */:
12657 case 10 /* IF_BRANCH */:
12658 return 0 /* NOT_CONSTANT */;
12659 case 5 /* INTERPOLATION */:
12660 case 12 /* TEXT_CALL */:
12661 return getConstantType(node.content, context);
12662 case 4 /* SIMPLE_EXPRESSION */:
12663 return node.constType;
12664 case 8 /* COMPOUND_EXPRESSION */:
12665 let returnType = 3 /* CAN_STRINGIFY */;
12666 for (let i = 0; i < node.children.length; i++) {
12667 const child = node.children[i];
12668 if (isString(child) || isSymbol(child)) {
12669 continue;
12670 }
12671 const childType = getConstantType(child, context);
12672 if (childType === 0 /* NOT_CONSTANT */) {
12673 return 0 /* NOT_CONSTANT */;
12674 }
12675 else if (childType < returnType) {
12676 returnType = childType;
12677 }
12678 }
12679 return returnType;
12680 default:
12681 return 0 /* NOT_CONSTANT */;
12682 }
12683}
12684const allowHoistedHelperSet = new Set([
12685 NORMALIZE_CLASS,
12686 NORMALIZE_STYLE,
12687 NORMALIZE_PROPS,
12688 GUARD_REACTIVE_PROPS
12689]);
12690function getConstantTypeOfHelperCall(value, context) {
12691 if (value.type === 14 /* JS_CALL_EXPRESSION */ &&
12692 !isString(value.callee) &&
12693 allowHoistedHelperSet.has(value.callee)) {
12694 const arg = value.arguments[0];
12695 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
12696 return getConstantType(arg, context);
12697 }
12698 else if (arg.type === 14 /* JS_CALL_EXPRESSION */) {
12699 // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
12700 return getConstantTypeOfHelperCall(arg, context);
12701 }
12702 }
12703 return 0 /* NOT_CONSTANT */;
12704}
12705function getGeneratedPropsConstantType(node, context) {
12706 let returnType = 3 /* CAN_STRINGIFY */;
12707 const props = getNodeProps(node);
12708 if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
12709 const { properties } = props;
12710 for (let i = 0; i < properties.length; i++) {
12711 const { key, value } = properties[i];
12712 const keyType = getConstantType(key, context);
12713 if (keyType === 0 /* NOT_CONSTANT */) {
12714 return keyType;
12715 }
12716 if (keyType < returnType) {
12717 returnType = keyType;
12718 }
12719 let valueType;
12720 if (value.type === 4 /* SIMPLE_EXPRESSION */) {
12721 valueType = getConstantType(value, context);
12722 }
12723 else if (value.type === 14 /* JS_CALL_EXPRESSION */) {
12724 // some helper calls can be hoisted,
12725 // such as the `normalizeProps` generated by the compiler for pre-normalize class,
12726 // in this case we need to respect the ConstantType of the helper's arguments
12727 valueType = getConstantTypeOfHelperCall(value, context);
12728 }
12729 else {
12730 valueType = 0 /* NOT_CONSTANT */;
12731 }
12732 if (valueType === 0 /* NOT_CONSTANT */) {
12733 return valueType;
12734 }
12735 if (valueType < returnType) {
12736 returnType = valueType;
12737 }
12738 }
12739 }
12740 return returnType;
12741}
12742function getNodeProps(node) {
12743 const codegenNode = node.codegenNode;
12744 if (codegenNode.type === 13 /* VNODE_CALL */) {
12745 return codegenNode.props;
12746 }
12747}
12748function getPatchFlag(node) {
12749 const flag = node.patchFlag;
12750 return flag ? parseInt(flag, 10) : undefined;
12751}
12752
12753function createTransformContext(root, { filename = '', prefixIdentifiers = false, hoistStatic = false, cacheHandlers = false, nodeTransforms = [], directiveTransforms = {}, transformHoist = null, isBuiltInComponent = NOOP, isCustomElement = NOOP, expressionPlugins = [], scopeId = null, slotted = true, ssr = false, inSSR = false, ssrCssVars = ``, bindingMetadata = EMPTY_OBJ, inline = false, isTS = false, onError = defaultOnError, onWarn = defaultOnWarn, compatConfig }) {
12754 const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
12755 const context = {
12756 // options
12757 selfName: nameMatch && capitalize(camelize(nameMatch[1])),
12758 prefixIdentifiers,
12759 hoistStatic,
12760 cacheHandlers,
12761 nodeTransforms,
12762 directiveTransforms,
12763 transformHoist,
12764 isBuiltInComponent,
12765 isCustomElement,
12766 expressionPlugins,
12767 scopeId,
12768 slotted,
12769 ssr,
12770 inSSR,
12771 ssrCssVars,
12772 bindingMetadata,
12773 inline,
12774 isTS,
12775 onError,
12776 onWarn,
12777 compatConfig,
12778 // state
12779 root,
12780 helpers: new Map(),
12781 components: new Set(),
12782 directives: new Set(),
12783 hoists: [],
12784 imports: [],
12785 constantCache: new Map(),
12786 temps: 0,
12787 cached: 0,
12788 identifiers: Object.create(null),
12789 scopes: {
12790 vFor: 0,
12791 vSlot: 0,
12792 vPre: 0,
12793 vOnce: 0
12794 },
12795 parent: null,
12796 currentNode: root,
12797 childIndex: 0,
12798 inVOnce: false,
12799 // methods
12800 helper(name) {
12801 const count = context.helpers.get(name) || 0;
12802 context.helpers.set(name, count + 1);
12803 return name;
12804 },
12805 removeHelper(name) {
12806 const count = context.helpers.get(name);
12807 if (count) {
12808 const currentCount = count - 1;
12809 if (!currentCount) {
12810 context.helpers.delete(name);
12811 }
12812 else {
12813 context.helpers.set(name, currentCount);
12814 }
12815 }
12816 },
12817 helperString(name) {
12818 return `_${helperNameMap[context.helper(name)]}`;
12819 },
12820 replaceNode(node) {
12821 /* istanbul ignore if */
12822 {
12823 if (!context.currentNode) {
12824 throw new Error(`Node being replaced is already removed.`);
12825 }
12826 if (!context.parent) {
12827 throw new Error(`Cannot replace root node.`);
12828 }
12829 }
12830 context.parent.children[context.childIndex] = context.currentNode = node;
12831 },
12832 removeNode(node) {
12833 if (!context.parent) {
12834 throw new Error(`Cannot remove root node.`);
12835 }
12836 const list = context.parent.children;
12837 const removalIndex = node
12838 ? list.indexOf(node)
12839 : context.currentNode
12840 ? context.childIndex
12841 : -1;
12842 /* istanbul ignore if */
12843 if (removalIndex < 0) {
12844 throw new Error(`node being removed is not a child of current parent`);
12845 }
12846 if (!node || node === context.currentNode) {
12847 // current node removed
12848 context.currentNode = null;
12849 context.onNodeRemoved();
12850 }
12851 else {
12852 // sibling node removed
12853 if (context.childIndex > removalIndex) {
12854 context.childIndex--;
12855 context.onNodeRemoved();
12856 }
12857 }
12858 context.parent.children.splice(removalIndex, 1);
12859 },
12860 onNodeRemoved: () => { },
12861 addIdentifiers(exp) {
12862 },
12863 removeIdentifiers(exp) {
12864 },
12865 hoist(exp) {
12866 if (isString(exp))
12867 exp = createSimpleExpression(exp);
12868 context.hoists.push(exp);
12869 const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
12870 identifier.hoisted = exp;
12871 return identifier;
12872 },
12873 cache(exp, isVNode = false) {
12874 return createCacheExpression(context.cached++, exp, isVNode);
12875 }
12876 };
12877 return context;
12878}
12879function transform(root, options) {
12880 const context = createTransformContext(root, options);
12881 traverseNode(root, context);
12882 if (options.hoistStatic) {
12883 hoistStatic(root, context);
12884 }
12885 if (!options.ssr) {
12886 createRootCodegen(root, context);
12887 }
12888 // finalize meta information
12889 root.helpers = [...context.helpers.keys()];
12890 root.components = [...context.components];
12891 root.directives = [...context.directives];
12892 root.imports = context.imports;
12893 root.hoists = context.hoists;
12894 root.temps = context.temps;
12895 root.cached = context.cached;
12896}
12897function createRootCodegen(root, context) {
12898 const { helper } = context;
12899 const { children } = root;
12900 if (children.length === 1) {
12901 const child = children[0];
12902 // if the single child is an element, turn it into a block.
12903 if (isSingleElementRoot(root, child) && child.codegenNode) {
12904 // single element root is never hoisted so codegenNode will never be
12905 // SimpleExpressionNode
12906 const codegenNode = child.codegenNode;
12907 if (codegenNode.type === 13 /* VNODE_CALL */) {
12908 makeBlock(codegenNode, context);
12909 }
12910 root.codegenNode = codegenNode;
12911 }
12912 else {
12913 // - single <slot/>, IfNode, ForNode: already blocks.
12914 // - single text node: always patched.
12915 // root codegen falls through via genNode()
12916 root.codegenNode = child;
12917 }
12918 }
12919 else if (children.length > 1) {
12920 // root has multiple nodes - return a fragment block.
12921 let patchFlag = 64 /* STABLE_FRAGMENT */;
12922 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
12923 // check if the fragment actually contains a single valid child with
12924 // the rest being comments
12925 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
12926 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
12927 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
12928 }
12929 root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, undefined, false /* isComponent */);
12930 }
12931 else ;
12932}
12933function traverseChildren(parent, context) {
12934 let i = 0;
12935 const nodeRemoved = () => {
12936 i--;
12937 };
12938 for (; i < parent.children.length; i++) {
12939 const child = parent.children[i];
12940 if (isString(child))
12941 continue;
12942 context.parent = parent;
12943 context.childIndex = i;
12944 context.onNodeRemoved = nodeRemoved;
12945 traverseNode(child, context);
12946 }
12947}
12948function traverseNode(node, context) {
12949 context.currentNode = node;
12950 // apply transform plugins
12951 const { nodeTransforms } = context;
12952 const exitFns = [];
12953 for (let i = 0; i < nodeTransforms.length; i++) {
12954 const onExit = nodeTransforms[i](node, context);
12955 if (onExit) {
12956 if (isArray(onExit)) {
12957 exitFns.push(...onExit);
12958 }
12959 else {
12960 exitFns.push(onExit);
12961 }
12962 }
12963 if (!context.currentNode) {
12964 // node was removed
12965 return;
12966 }
12967 else {
12968 // node may have been replaced
12969 node = context.currentNode;
12970 }
12971 }
12972 switch (node.type) {
12973 case 3 /* COMMENT */:
12974 if (!context.ssr) {
12975 // inject import for the Comment symbol, which is needed for creating
12976 // comment nodes with `createVNode`
12977 context.helper(CREATE_COMMENT);
12978 }
12979 break;
12980 case 5 /* INTERPOLATION */:
12981 // no need to traverse, but we need to inject toString helper
12982 if (!context.ssr) {
12983 context.helper(TO_DISPLAY_STRING);
12984 }
12985 break;
12986 // for container types, further traverse downwards
12987 case 9 /* IF */:
12988 for (let i = 0; i < node.branches.length; i++) {
12989 traverseNode(node.branches[i], context);
12990 }
12991 break;
12992 case 10 /* IF_BRANCH */:
12993 case 11 /* FOR */:
12994 case 1 /* ELEMENT */:
12995 case 0 /* ROOT */:
12996 traverseChildren(node, context);
12997 break;
12998 }
12999 // exit transforms
13000 context.currentNode = node;
13001 let i = exitFns.length;
13002 while (i--) {
13003 exitFns[i]();
13004 }
13005}
13006function createStructuralDirectiveTransform(name, fn) {
13007 const matches = isString(name)
13008 ? (n) => n === name
13009 : (n) => name.test(n);
13010 return (node, context) => {
13011 if (node.type === 1 /* ELEMENT */) {
13012 const { props } = node;
13013 // structural directive transforms are not concerned with slots
13014 // as they are handled separately in vSlot.ts
13015 if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
13016 return;
13017 }
13018 const exitFns = [];
13019 for (let i = 0; i < props.length; i++) {
13020 const prop = props[i];
13021 if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
13022 // structural directives are removed to avoid infinite recursion
13023 // also we remove them *before* applying so that it can further
13024 // traverse itself in case it moves the node around
13025 props.splice(i, 1);
13026 i--;
13027 const onExit = fn(node, prop, context);
13028 if (onExit)
13029 exitFns.push(onExit);
13030 }
13031 }
13032 return exitFns;
13033 }
13034 };
13035}
13036
13037const PURE_ANNOTATION = `/*#__PURE__*/`;
13038function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssrRuntimeModuleName = 'vue/server-renderer', ssr = false, isTS = false, inSSR = false }) {
13039 const context = {
13040 mode,
13041 prefixIdentifiers,
13042 sourceMap,
13043 filename,
13044 scopeId,
13045 optimizeImports,
13046 runtimeGlobalName,
13047 runtimeModuleName,
13048 ssrRuntimeModuleName,
13049 ssr,
13050 isTS,
13051 inSSR,
13052 source: ast.loc.source,
13053 code: ``,
13054 column: 1,
13055 line: 1,
13056 offset: 0,
13057 indentLevel: 0,
13058 pure: false,
13059 map: undefined,
13060 helper(key) {
13061 return `_${helperNameMap[key]}`;
13062 },
13063 push(code, node) {
13064 context.code += code;
13065 },
13066 indent() {
13067 newline(++context.indentLevel);
13068 },
13069 deindent(withoutNewLine = false) {
13070 if (withoutNewLine) {
13071 --context.indentLevel;
13072 }
13073 else {
13074 newline(--context.indentLevel);
13075 }
13076 },
13077 newline() {
13078 newline(context.indentLevel);
13079 }
13080 };
13081 function newline(n) {
13082 context.push('\n' + ` `.repeat(n));
13083 }
13084 return context;
13085}
13086function generate(ast, options = {}) {
13087 const context = createCodegenContext(ast, options);
13088 if (options.onContextCreated)
13089 options.onContextCreated(context);
13090 const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
13091 const hasHelpers = ast.helpers.length > 0;
13092 const useWithBlock = !prefixIdentifiers && mode !== 'module';
13093 // preambles
13094 // in setup() inline mode, the preamble is generated in a sub context
13095 // and returned separately.
13096 const preambleContext = context;
13097 {
13098 genFunctionPreamble(ast, preambleContext);
13099 }
13100 // enter render function
13101 const functionName = ssr ? `ssrRender` : `render`;
13102 const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
13103 const signature = args.join(', ');
13104 {
13105 push(`function ${functionName}(${signature}) {`);
13106 }
13107 indent();
13108 if (useWithBlock) {
13109 push(`with (_ctx) {`);
13110 indent();
13111 // function mode const declarations should be inside with block
13112 // also they should be renamed to avoid collision with user properties
13113 if (hasHelpers) {
13114 push(`const { ${ast.helpers
13115 .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
13116 .join(', ')} } = _Vue`);
13117 push(`\n`);
13118 newline();
13119 }
13120 }
13121 // generate asset resolution statements
13122 if (ast.components.length) {
13123 genAssets(ast.components, 'component', context);
13124 if (ast.directives.length || ast.temps > 0) {
13125 newline();
13126 }
13127 }
13128 if (ast.directives.length) {
13129 genAssets(ast.directives, 'directive', context);
13130 if (ast.temps > 0) {
13131 newline();
13132 }
13133 }
13134 if (ast.temps > 0) {
13135 push(`let `);
13136 for (let i = 0; i < ast.temps; i++) {
13137 push(`${i > 0 ? `, ` : ``}_temp${i}`);
13138 }
13139 }
13140 if (ast.components.length || ast.directives.length || ast.temps) {
13141 push(`\n`);
13142 newline();
13143 }
13144 // generate the VNode tree expression
13145 if (!ssr) {
13146 push(`return `);
13147 }
13148 if (ast.codegenNode) {
13149 genNode(ast.codegenNode, context);
13150 }
13151 else {
13152 push(`null`);
13153 }
13154 if (useWithBlock) {
13155 deindent();
13156 push(`}`);
13157 }
13158 deindent();
13159 push(`}`);
13160 return {
13161 ast,
13162 code: context.code,
13163 preamble: ``,
13164 // SourceMapGenerator does have toJSON() method but it's not in the types
13165 map: context.map ? context.map.toJSON() : undefined
13166 };
13167}
13168function genFunctionPreamble(ast, context) {
13169 const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName, ssrRuntimeModuleName } = context;
13170 const VueBinding = runtimeGlobalName;
13171 const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
13172 // Generate const declaration for helpers
13173 // In prefix mode, we place the const declaration at top so it's done
13174 // only once; But if we not prefixing, we place the declaration inside the
13175 // with block so it doesn't incur the `in` check cost for every helper access.
13176 if (ast.helpers.length > 0) {
13177 {
13178 // "with" mode.
13179 // save Vue in a separate variable to avoid collision
13180 push(`const _Vue = ${VueBinding}\n`);
13181 // in "with" mode, helpers are declared inside the with block to avoid
13182 // has check cost, but hoists are lifted out of the function - we need
13183 // to provide the helper here.
13184 if (ast.hoists.length) {
13185 const staticHelpers = [
13186 CREATE_VNODE,
13187 CREATE_ELEMENT_VNODE,
13188 CREATE_COMMENT,
13189 CREATE_TEXT,
13190 CREATE_STATIC
13191 ]
13192 .filter(helper => ast.helpers.includes(helper))
13193 .map(aliasHelper)
13194 .join(', ');
13195 push(`const { ${staticHelpers} } = _Vue\n`);
13196 }
13197 }
13198 }
13199 genHoists(ast.hoists, context);
13200 newline();
13201 push(`return `);
13202}
13203function genAssets(assets, type, { helper, push, newline, isTS }) {
13204 const resolver = helper(type === 'component'
13205 ? RESOLVE_COMPONENT
13206 : RESOLVE_DIRECTIVE);
13207 for (let i = 0; i < assets.length; i++) {
13208 let id = assets[i];
13209 // potential component implicit self-reference inferred from SFC filename
13210 const maybeSelfReference = id.endsWith('__self');
13211 if (maybeSelfReference) {
13212 id = id.slice(0, -6);
13213 }
13214 push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
13215 if (i < assets.length - 1) {
13216 newline();
13217 }
13218 }
13219}
13220function genHoists(hoists, context) {
13221 if (!hoists.length) {
13222 return;
13223 }
13224 context.pure = true;
13225 const { push, newline, helper, scopeId, mode } = context;
13226 newline();
13227 for (let i = 0; i < hoists.length; i++) {
13228 const exp = hoists[i];
13229 if (exp) {
13230 push(`const _hoisted_${i + 1} = ${``}`);
13231 genNode(exp, context);
13232 newline();
13233 }
13234 }
13235 context.pure = false;
13236}
13237function isText$1(n) {
13238 return (isString(n) ||
13239 n.type === 4 /* SIMPLE_EXPRESSION */ ||
13240 n.type === 2 /* TEXT */ ||
13241 n.type === 5 /* INTERPOLATION */ ||
13242 n.type === 8 /* COMPOUND_EXPRESSION */);
13243}
13244function genNodeListAsArray(nodes, context) {
13245 const multilines = nodes.length > 3 ||
13246 (nodes.some(n => isArray(n) || !isText$1(n)));
13247 context.push(`[`);
13248 multilines && context.indent();
13249 genNodeList(nodes, context, multilines);
13250 multilines && context.deindent();
13251 context.push(`]`);
13252}
13253function genNodeList(nodes, context, multilines = false, comma = true) {
13254 const { push, newline } = context;
13255 for (let i = 0; i < nodes.length; i++) {
13256 const node = nodes[i];
13257 if (isString(node)) {
13258 push(node);
13259 }
13260 else if (isArray(node)) {
13261 genNodeListAsArray(node, context);
13262 }
13263 else {
13264 genNode(node, context);
13265 }
13266 if (i < nodes.length - 1) {
13267 if (multilines) {
13268 comma && push(',');
13269 newline();
13270 }
13271 else {
13272 comma && push(', ');
13273 }
13274 }
13275 }
13276}
13277function genNode(node, context) {
13278 if (isString(node)) {
13279 context.push(node);
13280 return;
13281 }
13282 if (isSymbol(node)) {
13283 context.push(context.helper(node));
13284 return;
13285 }
13286 switch (node.type) {
13287 case 1 /* ELEMENT */:
13288 case 9 /* IF */:
13289 case 11 /* FOR */:
13290 assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
13291 `Apply appropriate transforms first.`);
13292 genNode(node.codegenNode, context);
13293 break;
13294 case 2 /* TEXT */:
13295 genText(node, context);
13296 break;
13297 case 4 /* SIMPLE_EXPRESSION */:
13298 genExpression(node, context);
13299 break;
13300 case 5 /* INTERPOLATION */:
13301 genInterpolation(node, context);
13302 break;
13303 case 12 /* TEXT_CALL */:
13304 genNode(node.codegenNode, context);
13305 break;
13306 case 8 /* COMPOUND_EXPRESSION */:
13307 genCompoundExpression(node, context);
13308 break;
13309 case 3 /* COMMENT */:
13310 genComment(node, context);
13311 break;
13312 case 13 /* VNODE_CALL */:
13313 genVNodeCall(node, context);
13314 break;
13315 case 14 /* JS_CALL_EXPRESSION */:
13316 genCallExpression(node, context);
13317 break;
13318 case 15 /* JS_OBJECT_EXPRESSION */:
13319 genObjectExpression(node, context);
13320 break;
13321 case 17 /* JS_ARRAY_EXPRESSION */:
13322 genArrayExpression(node, context);
13323 break;
13324 case 18 /* JS_FUNCTION_EXPRESSION */:
13325 genFunctionExpression(node, context);
13326 break;
13327 case 19 /* JS_CONDITIONAL_EXPRESSION */:
13328 genConditionalExpression(node, context);
13329 break;
13330 case 20 /* JS_CACHE_EXPRESSION */:
13331 genCacheExpression(node, context);
13332 break;
13333 case 21 /* JS_BLOCK_STATEMENT */:
13334 genNodeList(node.body, context, true, false);
13335 break;
13336 // SSR only types
13337 case 22 /* JS_TEMPLATE_LITERAL */:
13338 break;
13339 case 23 /* JS_IF_STATEMENT */:
13340 break;
13341 case 24 /* JS_ASSIGNMENT_EXPRESSION */:
13342 break;
13343 case 25 /* JS_SEQUENCE_EXPRESSION */:
13344 break;
13345 case 26 /* JS_RETURN_STATEMENT */:
13346 break;
13347 /* istanbul ignore next */
13348 case 10 /* IF_BRANCH */:
13349 // noop
13350 break;
13351 default:
13352 {
13353 assert(false, `unhandled codegen node type: ${node.type}`);
13354 // make sure we exhaust all possible types
13355 const exhaustiveCheck = node;
13356 return exhaustiveCheck;
13357 }
13358 }
13359}
13360function genText(node, context) {
13361 context.push(JSON.stringify(node.content), node);
13362}
13363function genExpression(node, context) {
13364 const { content, isStatic } = node;
13365 context.push(isStatic ? JSON.stringify(content) : content, node);
13366}
13367function genInterpolation(node, context) {
13368 const { push, helper, pure } = context;
13369 if (pure)
13370 push(PURE_ANNOTATION);
13371 push(`${helper(TO_DISPLAY_STRING)}(`);
13372 genNode(node.content, context);
13373 push(`)`);
13374}
13375function genCompoundExpression(node, context) {
13376 for (let i = 0; i < node.children.length; i++) {
13377 const child = node.children[i];
13378 if (isString(child)) {
13379 context.push(child);
13380 }
13381 else {
13382 genNode(child, context);
13383 }
13384 }
13385}
13386function genExpressionAsPropertyKey(node, context) {
13387 const { push } = context;
13388 if (node.type === 8 /* COMPOUND_EXPRESSION */) {
13389 push(`[`);
13390 genCompoundExpression(node, context);
13391 push(`]`);
13392 }
13393 else if (node.isStatic) {
13394 // only quote keys if necessary
13395 const text = isSimpleIdentifier(node.content)
13396 ? node.content
13397 : JSON.stringify(node.content);
13398 push(text, node);
13399 }
13400 else {
13401 push(`[${node.content}]`, node);
13402 }
13403}
13404function genComment(node, context) {
13405 const { push, helper, pure } = context;
13406 if (pure) {
13407 push(PURE_ANNOTATION);
13408 }
13409 push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
13410}
13411function genVNodeCall(node, context) {
13412 const { push, helper, pure } = context;
13413 const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
13414 if (directives) {
13415 push(helper(WITH_DIRECTIVES) + `(`);
13416 }
13417 if (isBlock) {
13418 push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
13419 }
13420 if (pure) {
13421 push(PURE_ANNOTATION);
13422 }
13423 const callHelper = isBlock
13424 ? getVNodeBlockHelper(context.inSSR, isComponent)
13425 : getVNodeHelper(context.inSSR, isComponent);
13426 push(helper(callHelper) + `(`, node);
13427 genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
13428 push(`)`);
13429 if (isBlock) {
13430 push(`)`);
13431 }
13432 if (directives) {
13433 push(`, `);
13434 genNode(directives, context);
13435 push(`)`);
13436 }
13437}
13438function genNullableArgs(args) {
13439 let i = args.length;
13440 while (i--) {
13441 if (args[i] != null)
13442 break;
13443 }
13444 return args.slice(0, i + 1).map(arg => arg || `null`);
13445}
13446// JavaScript
13447function genCallExpression(node, context) {
13448 const { push, helper, pure } = context;
13449 const callee = isString(node.callee) ? node.callee : helper(node.callee);
13450 if (pure) {
13451 push(PURE_ANNOTATION);
13452 }
13453 push(callee + `(`, node);
13454 genNodeList(node.arguments, context);
13455 push(`)`);
13456}
13457function genObjectExpression(node, context) {
13458 const { push, indent, deindent, newline } = context;
13459 const { properties } = node;
13460 if (!properties.length) {
13461 push(`{}`, node);
13462 return;
13463 }
13464 const multilines = properties.length > 1 ||
13465 (properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
13466 push(multilines ? `{` : `{ `);
13467 multilines && indent();
13468 for (let i = 0; i < properties.length; i++) {
13469 const { key, value } = properties[i];
13470 // key
13471 genExpressionAsPropertyKey(key, context);
13472 push(`: `);
13473 // value
13474 genNode(value, context);
13475 if (i < properties.length - 1) {
13476 // will only reach this if it's multilines
13477 push(`,`);
13478 newline();
13479 }
13480 }
13481 multilines && deindent();
13482 push(multilines ? `}` : ` }`);
13483}
13484function genArrayExpression(node, context) {
13485 genNodeListAsArray(node.elements, context);
13486}
13487function genFunctionExpression(node, context) {
13488 const { push, indent, deindent } = context;
13489 const { params, returns, body, newline, isSlot } = node;
13490 if (isSlot) {
13491 // wrap slot functions with owner context
13492 push(`_${helperNameMap[WITH_CTX]}(`);
13493 }
13494 push(`(`, node);
13495 if (isArray(params)) {
13496 genNodeList(params, context);
13497 }
13498 else if (params) {
13499 genNode(params, context);
13500 }
13501 push(`) => `);
13502 if (newline || body) {
13503 push(`{`);
13504 indent();
13505 }
13506 if (returns) {
13507 if (newline) {
13508 push(`return `);
13509 }
13510 if (isArray(returns)) {
13511 genNodeListAsArray(returns, context);
13512 }
13513 else {
13514 genNode(returns, context);
13515 }
13516 }
13517 else if (body) {
13518 genNode(body, context);
13519 }
13520 if (newline || body) {
13521 deindent();
13522 push(`}`);
13523 }
13524 if (isSlot) {
13525 push(`)`);
13526 }
13527}
13528function genConditionalExpression(node, context) {
13529 const { test, consequent, alternate, newline: needNewline } = node;
13530 const { push, indent, deindent, newline } = context;
13531 if (test.type === 4 /* SIMPLE_EXPRESSION */) {
13532 const needsParens = !isSimpleIdentifier(test.content);
13533 needsParens && push(`(`);
13534 genExpression(test, context);
13535 needsParens && push(`)`);
13536 }
13537 else {
13538 push(`(`);
13539 genNode(test, context);
13540 push(`)`);
13541 }
13542 needNewline && indent();
13543 context.indentLevel++;
13544 needNewline || push(` `);
13545 push(`? `);
13546 genNode(consequent, context);
13547 context.indentLevel--;
13548 needNewline && newline();
13549 needNewline || push(` `);
13550 push(`: `);
13551 const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
13552 if (!isNested) {
13553 context.indentLevel++;
13554 }
13555 genNode(alternate, context);
13556 if (!isNested) {
13557 context.indentLevel--;
13558 }
13559 needNewline && deindent(true /* without newline */);
13560}
13561function genCacheExpression(node, context) {
13562 const { push, helper, indent, deindent, newline } = context;
13563 push(`_cache[${node.index}] || (`);
13564 if (node.isVNode) {
13565 indent();
13566 push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
13567 newline();
13568 }
13569 push(`_cache[${node.index}] = `);
13570 genNode(node.value, context);
13571 if (node.isVNode) {
13572 push(`,`);
13573 newline();
13574 push(`${helper(SET_BLOCK_TRACKING)}(1),`);
13575 newline();
13576 push(`_cache[${node.index}]`);
13577 deindent();
13578 }
13579 push(`)`);
13580}
13581
13582// these keywords should not appear inside expressions, but operators like
13583// typeof, instanceof and in are allowed
13584const prohibitedKeywordRE = new RegExp('\\b' +
13585 ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
13586 'super,throw,while,yield,delete,export,import,return,switch,default,' +
13587 'extends,finally,continue,debugger,function,arguments,typeof,void')
13588 .split(',')
13589 .join('\\b|\\b') +
13590 '\\b');
13591// strip strings in expressions
13592const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
13593/**
13594 * Validate a non-prefixed expression.
13595 * This is only called when using the in-browser runtime compiler since it
13596 * doesn't prefix expressions.
13597 */
13598function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
13599 const exp = node.content;
13600 // empty expressions are validated per-directive since some directives
13601 // do allow empty expressions.
13602 if (!exp.trim()) {
13603 return;
13604 }
13605 try {
13606 new Function(asRawStatements
13607 ? ` ${exp} `
13608 : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
13609 }
13610 catch (e) {
13611 let message = e.message;
13612 const keywordMatch = exp
13613 .replace(stripStringRE, '')
13614 .match(prohibitedKeywordRE);
13615 if (keywordMatch) {
13616 message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
13617 }
13618 context.onError(createCompilerError(44 /* X_INVALID_EXPRESSION */, node.loc, undefined, message));
13619 }
13620}
13621
13622const transformExpression = (node, context) => {
13623 if (node.type === 5 /* INTERPOLATION */) {
13624 node.content = processExpression(node.content, context);
13625 }
13626 else if (node.type === 1 /* ELEMENT */) {
13627 // handle directives on element
13628 for (let i = 0; i < node.props.length; i++) {
13629 const dir = node.props[i];
13630 // do not process for v-on & v-for since they are special handled
13631 if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
13632 const exp = dir.exp;
13633 const arg = dir.arg;
13634 // do not process exp if this is v-on:arg - we need special handling
13635 // for wrapping inline statements.
13636 if (exp &&
13637 exp.type === 4 /* SIMPLE_EXPRESSION */ &&
13638 !(dir.name === 'on' && arg)) {
13639 dir.exp = processExpression(exp, context,
13640 // slot args must be processed as function params
13641 dir.name === 'slot');
13642 }
13643 if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
13644 dir.arg = processExpression(arg, context);
13645 }
13646 }
13647 }
13648 }
13649};
13650// Important: since this function uses Node.js only dependencies, it should
13651// always be used with a leading !true check so that it can be
13652// tree-shaken from the browser build.
13653function processExpression(node, context,
13654// some expressions like v-slot props & v-for aliases should be parsed as
13655// function params
13656asParams = false,
13657// v-on handler values may contain multiple statements
13658asRawStatements = false, localVars = Object.create(context.identifiers)) {
13659 {
13660 {
13661 // simple in-browser validation (same logic in 2.x)
13662 validateBrowserExpression(node, context, asParams, asRawStatements);
13663 }
13664 return node;
13665 }
13666}
13667
13668const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
13669 return processIf(node, dir, context, (ifNode, branch, isRoot) => {
13670 // #1587: We need to dynamically increment the key based on the current
13671 // node's sibling nodes, since chained v-if/else branches are
13672 // rendered at the same depth
13673 const siblings = context.parent.children;
13674 let i = siblings.indexOf(ifNode);
13675 let key = 0;
13676 while (i-- >= 0) {
13677 const sibling = siblings[i];
13678 if (sibling && sibling.type === 9 /* IF */) {
13679 key += sibling.branches.length;
13680 }
13681 }
13682 // Exit callback. Complete the codegenNode when all children have been
13683 // transformed.
13684 return () => {
13685 if (isRoot) {
13686 ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
13687 }
13688 else {
13689 // attach this branch's codegen node to the v-if root.
13690 const parentCondition = getParentCondition(ifNode.codegenNode);
13691 parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
13692 }
13693 };
13694 });
13695});
13696// target-agnostic transform used for both Client and SSR
13697function processIf(node, dir, context, processCodegen) {
13698 if (dir.name !== 'else' &&
13699 (!dir.exp || !dir.exp.content.trim())) {
13700 const loc = dir.exp ? dir.exp.loc : node.loc;
13701 context.onError(createCompilerError(28 /* X_V_IF_NO_EXPRESSION */, dir.loc));
13702 dir.exp = createSimpleExpression(`true`, false, loc);
13703 }
13704 if (dir.exp) {
13705 validateBrowserExpression(dir.exp, context);
13706 }
13707 if (dir.name === 'if') {
13708 const branch = createIfBranch(node, dir);
13709 const ifNode = {
13710 type: 9 /* IF */,
13711 loc: node.loc,
13712 branches: [branch]
13713 };
13714 context.replaceNode(ifNode);
13715 if (processCodegen) {
13716 return processCodegen(ifNode, branch, true);
13717 }
13718 }
13719 else {
13720 // locate the adjacent v-if
13721 const siblings = context.parent.children;
13722 const comments = [];
13723 let i = siblings.indexOf(node);
13724 while (i-- >= -1) {
13725 const sibling = siblings[i];
13726 if (sibling && sibling.type === 3 /* COMMENT */) {
13727 context.removeNode(sibling);
13728 comments.unshift(sibling);
13729 continue;
13730 }
13731 if (sibling &&
13732 sibling.type === 2 /* TEXT */ &&
13733 !sibling.content.trim().length) {
13734 context.removeNode(sibling);
13735 continue;
13736 }
13737 if (sibling && sibling.type === 9 /* IF */) {
13738 // Check if v-else was followed by v-else-if
13739 if (dir.name === 'else-if' &&
13740 sibling.branches[sibling.branches.length - 1].condition === undefined) {
13741 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
13742 }
13743 // move the node to the if node's branches
13744 context.removeNode();
13745 const branch = createIfBranch(node, dir);
13746 if (comments.length &&
13747 // #3619 ignore comments if the v-if is direct child of <transition>
13748 !(context.parent &&
13749 context.parent.type === 1 /* ELEMENT */ &&
13750 isBuiltInType(context.parent.tag, 'transition'))) {
13751 branch.children = [...comments, ...branch.children];
13752 }
13753 // check if user is forcing same key on different branches
13754 {
13755 const key = branch.userKey;
13756 if (key) {
13757 sibling.branches.forEach(({ userKey }) => {
13758 if (isSameKey(userKey, key)) {
13759 context.onError(createCompilerError(29 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
13760 }
13761 });
13762 }
13763 }
13764 sibling.branches.push(branch);
13765 const onExit = processCodegen && processCodegen(sibling, branch, false);
13766 // since the branch was removed, it will not be traversed.
13767 // make sure to traverse here.
13768 traverseNode(branch, context);
13769 // call on exit
13770 if (onExit)
13771 onExit();
13772 // make sure to reset currentNode after traversal to indicate this
13773 // node has been removed.
13774 context.currentNode = null;
13775 }
13776 else {
13777 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
13778 }
13779 break;
13780 }
13781 }
13782}
13783function createIfBranch(node, dir) {
13784 return {
13785 type: 10 /* IF_BRANCH */,
13786 loc: node.loc,
13787 condition: dir.name === 'else' ? undefined : dir.exp,
13788 children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
13789 ? node.children
13790 : [node],
13791 userKey: findProp(node, `key`)
13792 };
13793}
13794function createCodegenNodeForBranch(branch, keyIndex, context) {
13795 if (branch.condition) {
13796 return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
13797 // make sure to pass in asBlock: true so that the comment node call
13798 // closes the current block.
13799 createCallExpression(context.helper(CREATE_COMMENT), [
13800 '"v-if"' ,
13801 'true'
13802 ]));
13803 }
13804 else {
13805 return createChildrenCodegenNode(branch, keyIndex, context);
13806 }
13807}
13808function createChildrenCodegenNode(branch, keyIndex, context) {
13809 const { helper } = context;
13810 const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
13811 const { children } = branch;
13812 const firstChild = children[0];
13813 const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
13814 if (needFragmentWrapper) {
13815 if (children.length === 1 && firstChild.type === 11 /* FOR */) {
13816 // optimize away nested fragments when child is a ForNode
13817 const vnodeCall = firstChild.codegenNode;
13818 injectProp(vnodeCall, keyProperty, context);
13819 return vnodeCall;
13820 }
13821 else {
13822 let patchFlag = 64 /* STABLE_FRAGMENT */;
13823 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
13824 // check if the fragment actually contains a single valid child with
13825 // the rest being comments
13826 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
13827 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
13828 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
13829 }
13830 return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
13831 }
13832 }
13833 else {
13834 const ret = firstChild.codegenNode;
13835 const vnodeCall = getMemoedVNodeCall(ret);
13836 // Change createVNode to createBlock.
13837 if (vnodeCall.type === 13 /* VNODE_CALL */) {
13838 makeBlock(vnodeCall, context);
13839 }
13840 // inject branch key
13841 injectProp(vnodeCall, keyProperty, context);
13842 return ret;
13843 }
13844}
13845function isSameKey(a, b) {
13846 if (!a || a.type !== b.type) {
13847 return false;
13848 }
13849 if (a.type === 6 /* ATTRIBUTE */) {
13850 if (a.value.content !== b.value.content) {
13851 return false;
13852 }
13853 }
13854 else {
13855 // directive
13856 const exp = a.exp;
13857 const branchExp = b.exp;
13858 if (exp.type !== branchExp.type) {
13859 return false;
13860 }
13861 if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
13862 exp.isStatic !== branchExp.isStatic ||
13863 exp.content !== branchExp.content) {
13864 return false;
13865 }
13866 }
13867 return true;
13868}
13869function getParentCondition(node) {
13870 while (true) {
13871 if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
13872 if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
13873 node = node.alternate;
13874 }
13875 else {
13876 return node;
13877 }
13878 }
13879 else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
13880 node = node.value;
13881 }
13882 }
13883}
13884
13885const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
13886 const { helper, removeHelper } = context;
13887 return processFor(node, dir, context, forNode => {
13888 // create the loop render function expression now, and add the
13889 // iterator on exit after all children have been traversed
13890 const renderExp = createCallExpression(helper(RENDER_LIST), [
13891 forNode.source
13892 ]);
13893 const isTemplate = isTemplateNode(node);
13894 const memo = findDir(node, 'memo');
13895 const keyProp = findProp(node, `key`);
13896 const keyExp = keyProp &&
13897 (keyProp.type === 6 /* ATTRIBUTE */
13898 ? createSimpleExpression(keyProp.value.content, true)
13899 : keyProp.exp);
13900 const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
13901 const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
13902 forNode.source.constType > 0 /* NOT_CONSTANT */;
13903 const fragmentFlag = isStableFragment
13904 ? 64 /* STABLE_FRAGMENT */
13905 : keyProp
13906 ? 128 /* KEYED_FRAGMENT */
13907 : 256 /* UNKEYED_FRAGMENT */;
13908 forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
13909 (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
13910 return () => {
13911 // finish the codegen now that all children have been traversed
13912 let childBlock;
13913 const { children } = forNode;
13914 // check <template v-for> key placement
13915 if (isTemplate) {
13916 node.children.some(c => {
13917 if (c.type === 1 /* ELEMENT */) {
13918 const key = findProp(c, 'key');
13919 if (key) {
13920 context.onError(createCompilerError(33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
13921 return true;
13922 }
13923 }
13924 });
13925 }
13926 const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
13927 const slotOutlet = isSlotOutlet(node)
13928 ? node
13929 : isTemplate &&
13930 node.children.length === 1 &&
13931 isSlotOutlet(node.children[0])
13932 ? node.children[0] // api-extractor somehow fails to infer this
13933 : null;
13934 if (slotOutlet) {
13935 // <slot v-for="..."> or <template v-for="..."><slot/></template>
13936 childBlock = slotOutlet.codegenNode;
13937 if (isTemplate && keyProperty) {
13938 // <template v-for="..." :key="..."><slot/></template>
13939 // we need to inject the key to the renderSlot() call.
13940 // the props for renderSlot is passed as the 3rd argument.
13941 injectProp(childBlock, keyProperty, context);
13942 }
13943 }
13944 else if (needFragmentWrapper) {
13945 // <template v-for="..."> with text or multi-elements
13946 // should generate a fragment block for each loop
13947 childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
13948 (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
13949 ), undefined, undefined, true, undefined, false /* isComponent */);
13950 }
13951 else {
13952 // Normal element v-for. Directly use the child's codegenNode
13953 // but mark it as a block.
13954 childBlock = children[0]
13955 .codegenNode;
13956 if (isTemplate && keyProperty) {
13957 injectProp(childBlock, keyProperty, context);
13958 }
13959 if (childBlock.isBlock !== !isStableFragment) {
13960 if (childBlock.isBlock) {
13961 // switch from block to vnode
13962 removeHelper(OPEN_BLOCK);
13963 removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
13964 }
13965 else {
13966 // switch from vnode to block
13967 removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
13968 }
13969 }
13970 childBlock.isBlock = !isStableFragment;
13971 if (childBlock.isBlock) {
13972 helper(OPEN_BLOCK);
13973 helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
13974 }
13975 else {
13976 helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
13977 }
13978 }
13979 if (memo) {
13980 const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
13981 createSimpleExpression(`_cached`)
13982 ]));
13983 loop.body = createBlockStatement([
13984 createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
13985 createCompoundExpression([
13986 `if (_cached`,
13987 ...(keyExp ? [` && _cached.key === `, keyExp] : []),
13988 ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
13989 ]),
13990 createCompoundExpression([`const _item = `, childBlock]),
13991 createSimpleExpression(`_item.memo = _memo`),
13992 createSimpleExpression(`return _item`)
13993 ]);
13994 renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
13995 }
13996 else {
13997 renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
13998 }
13999 };
14000 });
14001});
14002// target-agnostic transform used for both Client and SSR
14003function processFor(node, dir, context, processCodegen) {
14004 if (!dir.exp) {
14005 context.onError(createCompilerError(31 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
14006 return;
14007 }
14008 const parseResult = parseForExpression(
14009 // can only be simple expression because vFor transform is applied
14010 // before expression transform.
14011 dir.exp, context);
14012 if (!parseResult) {
14013 context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
14014 return;
14015 }
14016 const { addIdentifiers, removeIdentifiers, scopes } = context;
14017 const { source, value, key, index } = parseResult;
14018 const forNode = {
14019 type: 11 /* FOR */,
14020 loc: dir.loc,
14021 source,
14022 valueAlias: value,
14023 keyAlias: key,
14024 objectIndexAlias: index,
14025 parseResult,
14026 children: isTemplateNode(node) ? node.children : [node]
14027 };
14028 context.replaceNode(forNode);
14029 // bookkeeping
14030 scopes.vFor++;
14031 const onExit = processCodegen && processCodegen(forNode);
14032 return () => {
14033 scopes.vFor--;
14034 if (onExit)
14035 onExit();
14036 };
14037}
14038const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
14039// This regex doesn't cover the case if key or index aliases have destructuring,
14040// but those do not make sense in the first place, so this works in practice.
14041const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
14042const stripParensRE = /^\(|\)$/g;
14043function parseForExpression(input, context) {
14044 const loc = input.loc;
14045 const exp = input.content;
14046 const inMatch = exp.match(forAliasRE);
14047 if (!inMatch)
14048 return;
14049 const [, LHS, RHS] = inMatch;
14050 const result = {
14051 source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
14052 value: undefined,
14053 key: undefined,
14054 index: undefined
14055 };
14056 {
14057 validateBrowserExpression(result.source, context);
14058 }
14059 let valueContent = LHS.trim().replace(stripParensRE, '').trim();
14060 const trimmedOffset = LHS.indexOf(valueContent);
14061 const iteratorMatch = valueContent.match(forIteratorRE);
14062 if (iteratorMatch) {
14063 valueContent = valueContent.replace(forIteratorRE, '').trim();
14064 const keyContent = iteratorMatch[1].trim();
14065 let keyOffset;
14066 if (keyContent) {
14067 keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
14068 result.key = createAliasExpression(loc, keyContent, keyOffset);
14069 {
14070 validateBrowserExpression(result.key, context, true);
14071 }
14072 }
14073 if (iteratorMatch[2]) {
14074 const indexContent = iteratorMatch[2].trim();
14075 if (indexContent) {
14076 result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
14077 ? keyOffset + keyContent.length
14078 : trimmedOffset + valueContent.length));
14079 {
14080 validateBrowserExpression(result.index, context, true);
14081 }
14082 }
14083 }
14084 }
14085 if (valueContent) {
14086 result.value = createAliasExpression(loc, valueContent, trimmedOffset);
14087 {
14088 validateBrowserExpression(result.value, context, true);
14089 }
14090 }
14091 return result;
14092}
14093function createAliasExpression(range, content, offset) {
14094 return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
14095}
14096function createForLoopParams({ value, key, index }, memoArgs = []) {
14097 return createParamsList([value, key, index, ...memoArgs]);
14098}
14099function createParamsList(args) {
14100 let i = args.length;
14101 while (i--) {
14102 if (args[i])
14103 break;
14104 }
14105 return args
14106 .slice(0, i + 1)
14107 .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
14108}
14109
14110const defaultFallback = createSimpleExpression(`undefined`, false);
14111// A NodeTransform that:
14112// 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
14113// by transformExpression. This is only applied in non-browser builds with
14114// { prefixIdentifiers: true }.
14115// 2. Track v-slot depths so that we know a slot is inside another slot.
14116// Note the exit callback is executed before buildSlots() on the same node,
14117// so only nested slots see positive numbers.
14118const trackSlotScopes = (node, context) => {
14119 if (node.type === 1 /* ELEMENT */ &&
14120 (node.tagType === 1 /* COMPONENT */ ||
14121 node.tagType === 3 /* TEMPLATE */)) {
14122 // We are only checking non-empty v-slot here
14123 // since we only care about slots that introduce scope variables.
14124 const vSlot = findDir(node, 'slot');
14125 if (vSlot) {
14126 vSlot.exp;
14127 context.scopes.vSlot++;
14128 return () => {
14129 context.scopes.vSlot--;
14130 };
14131 }
14132 }
14133};
14134const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
14135// Instead of being a DirectiveTransform, v-slot processing is called during
14136// transformElement to build the slots object for a component.
14137function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
14138 context.helper(WITH_CTX);
14139 const { children, loc } = node;
14140 const slotsProperties = [];
14141 const dynamicSlots = [];
14142 // If the slot is inside a v-for or another v-slot, force it to be dynamic
14143 // since it likely uses a scope variable.
14144 let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
14145 // 1. Check for slot with slotProps on component itself.
14146 // <Comp v-slot="{ prop }"/>
14147 const onComponentSlot = findDir(node, 'slot', true);
14148 if (onComponentSlot) {
14149 const { arg, exp } = onComponentSlot;
14150 if (arg && !isStaticExp(arg)) {
14151 hasDynamicSlots = true;
14152 }
14153 slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
14154 }
14155 // 2. Iterate through children and check for template slots
14156 // <template v-slot:foo="{ prop }">
14157 let hasTemplateSlots = false;
14158 let hasNamedDefaultSlot = false;
14159 const implicitDefaultChildren = [];
14160 const seenSlotNames = new Set();
14161 for (let i = 0; i < children.length; i++) {
14162 const slotElement = children[i];
14163 let slotDir;
14164 if (!isTemplateNode(slotElement) ||
14165 !(slotDir = findDir(slotElement, 'slot', true))) {
14166 // not a <template v-slot>, skip.
14167 if (slotElement.type !== 3 /* COMMENT */) {
14168 implicitDefaultChildren.push(slotElement);
14169 }
14170 continue;
14171 }
14172 if (onComponentSlot) {
14173 // already has on-component slot - this is incorrect usage.
14174 context.onError(createCompilerError(37 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
14175 break;
14176 }
14177 hasTemplateSlots = true;
14178 const { children: slotChildren, loc: slotLoc } = slotElement;
14179 const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
14180 // check if name is dynamic.
14181 let staticSlotName;
14182 if (isStaticExp(slotName)) {
14183 staticSlotName = slotName ? slotName.content : `default`;
14184 }
14185 else {
14186 hasDynamicSlots = true;
14187 }
14188 const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
14189 // check if this slot is conditional (v-if/v-for)
14190 let vIf;
14191 let vElse;
14192 let vFor;
14193 if ((vIf = findDir(slotElement, 'if'))) {
14194 hasDynamicSlots = true;
14195 dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
14196 }
14197 else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
14198 // find adjacent v-if
14199 let j = i;
14200 let prev;
14201 while (j--) {
14202 prev = children[j];
14203 if (prev.type !== 3 /* COMMENT */) {
14204 break;
14205 }
14206 }
14207 if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
14208 // remove node
14209 children.splice(i, 1);
14210 i--;
14211 // attach this slot to previous conditional
14212 let conditional = dynamicSlots[dynamicSlots.length - 1];
14213 while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
14214 conditional = conditional.alternate;
14215 }
14216 conditional.alternate = vElse.exp
14217 ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
14218 : buildDynamicSlot(slotName, slotFunction);
14219 }
14220 else {
14221 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
14222 }
14223 }
14224 else if ((vFor = findDir(slotElement, 'for'))) {
14225 hasDynamicSlots = true;
14226 const parseResult = vFor.parseResult ||
14227 parseForExpression(vFor.exp, context);
14228 if (parseResult) {
14229 // Render the dynamic slots as an array and add it to the createSlot()
14230 // args. The runtime knows how to handle it appropriately.
14231 dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
14232 parseResult.source,
14233 createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
14234 ]));
14235 }
14236 else {
14237 context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
14238 }
14239 }
14240 else {
14241 // check duplicate static names
14242 if (staticSlotName) {
14243 if (seenSlotNames.has(staticSlotName)) {
14244 context.onError(createCompilerError(38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
14245 continue;
14246 }
14247 seenSlotNames.add(staticSlotName);
14248 if (staticSlotName === 'default') {
14249 hasNamedDefaultSlot = true;
14250 }
14251 }
14252 slotsProperties.push(createObjectProperty(slotName, slotFunction));
14253 }
14254 }
14255 if (!onComponentSlot) {
14256 const buildDefaultSlotProperty = (props, children) => {
14257 const fn = buildSlotFn(props, children, loc);
14258 return createObjectProperty(`default`, fn);
14259 };
14260 if (!hasTemplateSlots) {
14261 // implicit default slot (on component)
14262 slotsProperties.push(buildDefaultSlotProperty(undefined, children));
14263 }
14264 else if (implicitDefaultChildren.length &&
14265 // #3766
14266 // with whitespace: 'preserve', whitespaces between slots will end up in
14267 // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
14268 implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
14269 // implicit default slot (mixed with named slots)
14270 if (hasNamedDefaultSlot) {
14271 context.onError(createCompilerError(39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
14272 }
14273 else {
14274 slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
14275 }
14276 }
14277 }
14278 const slotFlag = hasDynamicSlots
14279 ? 2 /* DYNAMIC */
14280 : hasForwardedSlots(node.children)
14281 ? 3 /* FORWARDED */
14282 : 1 /* STABLE */;
14283 let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
14284 // 2 = compiled but dynamic = can skip normalization, but must run diff
14285 // 1 = compiled and static = can skip normalization AND diff as optimized
14286 createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
14287 if (dynamicSlots.length) {
14288 slots = createCallExpression(context.helper(CREATE_SLOTS), [
14289 slots,
14290 createArrayExpression(dynamicSlots)
14291 ]);
14292 }
14293 return {
14294 slots,
14295 hasDynamicSlots
14296 };
14297}
14298function buildDynamicSlot(name, fn) {
14299 return createObjectExpression([
14300 createObjectProperty(`name`, name),
14301 createObjectProperty(`fn`, fn)
14302 ]);
14303}
14304function hasForwardedSlots(children) {
14305 for (let i = 0; i < children.length; i++) {
14306 const child = children[i];
14307 switch (child.type) {
14308 case 1 /* ELEMENT */:
14309 if (child.tagType === 2 /* SLOT */ ||
14310 hasForwardedSlots(child.children)) {
14311 return true;
14312 }
14313 break;
14314 case 9 /* IF */:
14315 if (hasForwardedSlots(child.branches))
14316 return true;
14317 break;
14318 case 10 /* IF_BRANCH */:
14319 case 11 /* FOR */:
14320 if (hasForwardedSlots(child.children))
14321 return true;
14322 break;
14323 }
14324 }
14325 return false;
14326}
14327function isNonWhitespaceContent(node) {
14328 if (node.type !== 2 /* TEXT */ && node.type !== 12 /* TEXT_CALL */)
14329 return true;
14330 return node.type === 2 /* TEXT */
14331 ? !!node.content.trim()
14332 : isNonWhitespaceContent(node.content);
14333}
14334
14335// some directive transforms (e.g. v-model) may return a symbol for runtime
14336// import, which should be used instead of a resolveDirective call.
14337const directiveImportMap = new WeakMap();
14338// generate a JavaScript AST for this element's codegen
14339const transformElement = (node, context) => {
14340 // perform the work on exit, after all child expressions have been
14341 // processed and merged.
14342 return function postTransformElement() {
14343 node = context.currentNode;
14344 if (!(node.type === 1 /* ELEMENT */ &&
14345 (node.tagType === 0 /* ELEMENT */ ||
14346 node.tagType === 1 /* COMPONENT */))) {
14347 return;
14348 }
14349 const { tag, props } = node;
14350 const isComponent = node.tagType === 1 /* COMPONENT */;
14351 // The goal of the transform is to create a codegenNode implementing the
14352 // VNodeCall interface.
14353 let vnodeTag = isComponent
14354 ? resolveComponentType(node, context)
14355 : `"${tag}"`;
14356 const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
14357 let vnodeProps;
14358 let vnodeChildren;
14359 let vnodePatchFlag;
14360 let patchFlag = 0;
14361 let vnodeDynamicProps;
14362 let dynamicPropNames;
14363 let vnodeDirectives;
14364 let shouldUseBlock =
14365 // dynamic component may resolve to plain elements
14366 isDynamicComponent ||
14367 vnodeTag === TELEPORT ||
14368 vnodeTag === SUSPENSE ||
14369 (!isComponent &&
14370 // <svg> and <foreignObject> must be forced into blocks so that block
14371 // updates inside get proper isSVG flag at runtime. (#639, #643)
14372 // This is technically web-specific, but splitting the logic out of core
14373 // leads to too much unnecessary complexity.
14374 (tag === 'svg' || tag === 'foreignObject'));
14375 // props
14376 if (props.length > 0) {
14377 const propsBuildResult = buildProps(node, context);
14378 vnodeProps = propsBuildResult.props;
14379 patchFlag = propsBuildResult.patchFlag;
14380 dynamicPropNames = propsBuildResult.dynamicPropNames;
14381 const directives = propsBuildResult.directives;
14382 vnodeDirectives =
14383 directives && directives.length
14384 ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
14385 : undefined;
14386 if (propsBuildResult.shouldUseBlock) {
14387 shouldUseBlock = true;
14388 }
14389 }
14390 // children
14391 if (node.children.length > 0) {
14392 if (vnodeTag === KEEP_ALIVE) {
14393 // Although a built-in component, we compile KeepAlive with raw children
14394 // instead of slot functions so that it can be used inside Transition
14395 // or other Transition-wrapping HOCs.
14396 // To ensure correct updates with block optimizations, we need to:
14397 // 1. Force keep-alive into a block. This avoids its children being
14398 // collected by a parent block.
14399 shouldUseBlock = true;
14400 // 2. Force keep-alive to always be updated, since it uses raw children.
14401 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
14402 if (node.children.length > 1) {
14403 context.onError(createCompilerError(45 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
14404 start: node.children[0].loc.start,
14405 end: node.children[node.children.length - 1].loc.end,
14406 source: ''
14407 }));
14408 }
14409 }
14410 const shouldBuildAsSlots = isComponent &&
14411 // Teleport is not a real component and has dedicated runtime handling
14412 vnodeTag !== TELEPORT &&
14413 // explained above.
14414 vnodeTag !== KEEP_ALIVE;
14415 if (shouldBuildAsSlots) {
14416 const { slots, hasDynamicSlots } = buildSlots(node, context);
14417 vnodeChildren = slots;
14418 if (hasDynamicSlots) {
14419 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
14420 }
14421 }
14422 else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
14423 const child = node.children[0];
14424 const type = child.type;
14425 // check for dynamic text children
14426 const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
14427 type === 8 /* COMPOUND_EXPRESSION */;
14428 if (hasDynamicTextChild &&
14429 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
14430 patchFlag |= 1 /* TEXT */;
14431 }
14432 // pass directly if the only child is a text node
14433 // (plain / interpolation / expression)
14434 if (hasDynamicTextChild || type === 2 /* TEXT */) {
14435 vnodeChildren = child;
14436 }
14437 else {
14438 vnodeChildren = node.children;
14439 }
14440 }
14441 else {
14442 vnodeChildren = node.children;
14443 }
14444 }
14445 // patchFlag & dynamicPropNames
14446 if (patchFlag !== 0) {
14447 {
14448 if (patchFlag < 0) {
14449 // special flags (negative and mutually exclusive)
14450 vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
14451 }
14452 else {
14453 // bitwise flags
14454 const flagNames = Object.keys(PatchFlagNames)
14455 .map(Number)
14456 .filter(n => n > 0 && patchFlag & n)
14457 .map(n => PatchFlagNames[n])
14458 .join(`, `);
14459 vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
14460 }
14461 }
14462 if (dynamicPropNames && dynamicPropNames.length) {
14463 vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
14464 }
14465 }
14466 node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
14467 };
14468};
14469function resolveComponentType(node, context, ssr = false) {
14470 let { tag } = node;
14471 // 1. dynamic component
14472 const isExplicitDynamic = isComponentTag(tag);
14473 const isProp = findProp(node, 'is');
14474 if (isProp) {
14475 if (isExplicitDynamic ||
14476 (false )) {
14477 const exp = isProp.type === 6 /* ATTRIBUTE */
14478 ? isProp.value && createSimpleExpression(isProp.value.content, true)
14479 : isProp.exp;
14480 if (exp) {
14481 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
14482 exp
14483 ]);
14484 }
14485 }
14486 else if (isProp.type === 6 /* ATTRIBUTE */ &&
14487 isProp.value.content.startsWith('vue:')) {
14488 // <button is="vue:xxx">
14489 // if not <component>, only is value that starts with "vue:" will be
14490 // treated as component by the parse phase and reach here, unless it's
14491 // compat mode where all is values are considered components
14492 tag = isProp.value.content.slice(4);
14493 }
14494 }
14495 // 1.5 v-is (TODO: Deprecate)
14496 const isDir = !isExplicitDynamic && findDir(node, 'is');
14497 if (isDir && isDir.exp) {
14498 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
14499 isDir.exp
14500 ]);
14501 }
14502 // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
14503 const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
14504 if (builtIn) {
14505 // built-ins are simply fallthroughs / have special handling during ssr
14506 // so we don't need to import their runtime equivalents
14507 if (!ssr)
14508 context.helper(builtIn);
14509 return builtIn;
14510 }
14511 // 5. user component (resolve)
14512 context.helper(RESOLVE_COMPONENT);
14513 context.components.add(tag);
14514 return toValidAssetId(tag, `component`);
14515}
14516function buildProps(node, context, props = node.props, ssr = false) {
14517 const { tag, loc: elementLoc, children } = node;
14518 const isComponent = node.tagType === 1 /* COMPONENT */;
14519 let properties = [];
14520 const mergeArgs = [];
14521 const runtimeDirectives = [];
14522 const hasChildren = children.length > 0;
14523 let shouldUseBlock = false;
14524 // patchFlag analysis
14525 let patchFlag = 0;
14526 let hasRef = false;
14527 let hasClassBinding = false;
14528 let hasStyleBinding = false;
14529 let hasHydrationEventBinding = false;
14530 let hasDynamicKeys = false;
14531 let hasVnodeHook = false;
14532 const dynamicPropNames = [];
14533 const analyzePatchFlag = ({ key, value }) => {
14534 if (isStaticExp(key)) {
14535 const name = key.content;
14536 const isEventHandler = isOn(name);
14537 if (!isComponent &&
14538 isEventHandler &&
14539 // omit the flag for click handlers because hydration gives click
14540 // dedicated fast path.
14541 name.toLowerCase() !== 'onclick' &&
14542 // omit v-model handlers
14543 name !== 'onUpdate:modelValue' &&
14544 // omit onVnodeXXX hooks
14545 !isReservedProp(name)) {
14546 hasHydrationEventBinding = true;
14547 }
14548 if (isEventHandler && isReservedProp(name)) {
14549 hasVnodeHook = true;
14550 }
14551 if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
14552 ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
14553 value.type === 8 /* COMPOUND_EXPRESSION */) &&
14554 getConstantType(value, context) > 0)) {
14555 // skip if the prop is a cached handler or has constant value
14556 return;
14557 }
14558 if (name === 'ref') {
14559 hasRef = true;
14560 }
14561 else if (name === 'class') {
14562 hasClassBinding = true;
14563 }
14564 else if (name === 'style') {
14565 hasStyleBinding = true;
14566 }
14567 else if (name !== 'key' && !dynamicPropNames.includes(name)) {
14568 dynamicPropNames.push(name);
14569 }
14570 // treat the dynamic class and style binding of the component as dynamic props
14571 if (isComponent &&
14572 (name === 'class' || name === 'style') &&
14573 !dynamicPropNames.includes(name)) {
14574 dynamicPropNames.push(name);
14575 }
14576 }
14577 else {
14578 hasDynamicKeys = true;
14579 }
14580 };
14581 for (let i = 0; i < props.length; i++) {
14582 // static attribute
14583 const prop = props[i];
14584 if (prop.type === 6 /* ATTRIBUTE */) {
14585 const { loc, name, value } = prop;
14586 let isStatic = true;
14587 if (name === 'ref') {
14588 hasRef = true;
14589 if (context.scopes.vFor > 0) {
14590 properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
14591 }
14592 }
14593 // skip is on <component>, or is="vue:xxx"
14594 if (name === 'is' &&
14595 (isComponentTag(tag) ||
14596 (value && value.content.startsWith('vue:')) ||
14597 (false ))) {
14598 continue;
14599 }
14600 properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
14601 }
14602 else {
14603 // directives
14604 const { name, arg, exp, loc } = prop;
14605 const isVBind = name === 'bind';
14606 const isVOn = name === 'on';
14607 // skip v-slot - it is handled by its dedicated transform.
14608 if (name === 'slot') {
14609 if (!isComponent) {
14610 context.onError(createCompilerError(40 /* X_V_SLOT_MISPLACED */, loc));
14611 }
14612 continue;
14613 }
14614 // skip v-once/v-memo - they are handled by dedicated transforms.
14615 if (name === 'once' || name === 'memo') {
14616 continue;
14617 }
14618 // skip v-is and :is on <component>
14619 if (name === 'is' ||
14620 (isVBind &&
14621 isStaticArgOf(arg, 'is') &&
14622 (isComponentTag(tag) ||
14623 (false )))) {
14624 continue;
14625 }
14626 // skip v-on in SSR compilation
14627 if (isVOn && ssr) {
14628 continue;
14629 }
14630 if (
14631 // #938: elements with dynamic keys should be forced into blocks
14632 (isVBind && isStaticArgOf(arg, 'key')) ||
14633 // inline before-update hooks need to force block so that it is invoked
14634 // before children
14635 (isVOn && hasChildren && isStaticArgOf(arg, 'vue:before-update'))) {
14636 shouldUseBlock = true;
14637 }
14638 if (isVBind && isStaticArgOf(arg, 'ref') && context.scopes.vFor > 0) {
14639 properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
14640 }
14641 // special case for v-bind and v-on with no argument
14642 if (!arg && (isVBind || isVOn)) {
14643 hasDynamicKeys = true;
14644 if (exp) {
14645 if (properties.length) {
14646 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
14647 properties = [];
14648 }
14649 if (isVBind) {
14650 mergeArgs.push(exp);
14651 }
14652 else {
14653 // v-on="obj" -> toHandlers(obj)
14654 mergeArgs.push({
14655 type: 14 /* JS_CALL_EXPRESSION */,
14656 loc,
14657 callee: context.helper(TO_HANDLERS),
14658 arguments: [exp]
14659 });
14660 }
14661 }
14662 else {
14663 context.onError(createCompilerError(isVBind
14664 ? 34 /* X_V_BIND_NO_EXPRESSION */
14665 : 35 /* X_V_ON_NO_EXPRESSION */, loc));
14666 }
14667 continue;
14668 }
14669 const directiveTransform = context.directiveTransforms[name];
14670 if (directiveTransform) {
14671 // has built-in directive transform.
14672 const { props, needRuntime } = directiveTransform(prop, node, context);
14673 !ssr && props.forEach(analyzePatchFlag);
14674 properties.push(...props);
14675 if (needRuntime) {
14676 runtimeDirectives.push(prop);
14677 if (isSymbol(needRuntime)) {
14678 directiveImportMap.set(prop, needRuntime);
14679 }
14680 }
14681 }
14682 else if (!isBuiltInDirective(name)) {
14683 // no built-in transform, this is a user custom directive.
14684 runtimeDirectives.push(prop);
14685 // custom dirs may use beforeUpdate so they need to force blocks
14686 // to ensure before-update gets called before children update
14687 if (hasChildren) {
14688 shouldUseBlock = true;
14689 }
14690 }
14691 }
14692 }
14693 let propsExpression = undefined;
14694 // has v-bind="object" or v-on="object", wrap with mergeProps
14695 if (mergeArgs.length) {
14696 if (properties.length) {
14697 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
14698 }
14699 if (mergeArgs.length > 1) {
14700 propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
14701 }
14702 else {
14703 // single v-bind with nothing else - no need for a mergeProps call
14704 propsExpression = mergeArgs[0];
14705 }
14706 }
14707 else if (properties.length) {
14708 propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
14709 }
14710 // patchFlag analysis
14711 if (hasDynamicKeys) {
14712 patchFlag |= 16 /* FULL_PROPS */;
14713 }
14714 else {
14715 if (hasClassBinding && !isComponent) {
14716 patchFlag |= 2 /* CLASS */;
14717 }
14718 if (hasStyleBinding && !isComponent) {
14719 patchFlag |= 4 /* STYLE */;
14720 }
14721 if (dynamicPropNames.length) {
14722 patchFlag |= 8 /* PROPS */;
14723 }
14724 if (hasHydrationEventBinding) {
14725 patchFlag |= 32 /* HYDRATE_EVENTS */;
14726 }
14727 }
14728 if (!shouldUseBlock &&
14729 (patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
14730 (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
14731 patchFlag |= 512 /* NEED_PATCH */;
14732 }
14733 // pre-normalize props, SSR is skipped for now
14734 if (!context.inSSR && propsExpression) {
14735 switch (propsExpression.type) {
14736 case 15 /* JS_OBJECT_EXPRESSION */:
14737 // means that there is no v-bind,
14738 // but still need to deal with dynamic key binding
14739 let classKeyIndex = -1;
14740 let styleKeyIndex = -1;
14741 let hasDynamicKey = false;
14742 for (let i = 0; i < propsExpression.properties.length; i++) {
14743 const key = propsExpression.properties[i].key;
14744 if (isStaticExp(key)) {
14745 if (key.content === 'class') {
14746 classKeyIndex = i;
14747 }
14748 else if (key.content === 'style') {
14749 styleKeyIndex = i;
14750 }
14751 }
14752 else if (!key.isHandlerKey) {
14753 hasDynamicKey = true;
14754 }
14755 }
14756 const classProp = propsExpression.properties[classKeyIndex];
14757 const styleProp = propsExpression.properties[styleKeyIndex];
14758 // no dynamic key
14759 if (!hasDynamicKey) {
14760 if (classProp && !isStaticExp(classProp.value)) {
14761 classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
14762 }
14763 if (styleProp &&
14764 !isStaticExp(styleProp.value) &&
14765 // the static style is compiled into an object,
14766 // so use `hasStyleBinding` to ensure that it is a dynamic style binding
14767 (hasStyleBinding ||
14768 // v-bind:style and style both exist,
14769 // v-bind:style with static literal object
14770 styleProp.value.type === 17 /* JS_ARRAY_EXPRESSION */)) {
14771 styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
14772 }
14773 }
14774 else {
14775 // dynamic key binding, wrap with `normalizeProps`
14776 propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
14777 }
14778 break;
14779 case 14 /* JS_CALL_EXPRESSION */:
14780 // mergeProps call, do nothing
14781 break;
14782 default:
14783 // single v-bind
14784 propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
14785 createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
14786 propsExpression
14787 ])
14788 ]);
14789 break;
14790 }
14791 }
14792 return {
14793 props: propsExpression,
14794 directives: runtimeDirectives,
14795 patchFlag,
14796 dynamicPropNames,
14797 shouldUseBlock
14798 };
14799}
14800// Dedupe props in an object literal.
14801// Literal duplicated attributes would have been warned during the parse phase,
14802// however, it's possible to encounter duplicated `onXXX` handlers with different
14803// modifiers. We also need to merge static and dynamic class / style attributes.
14804// - onXXX handlers / style: merge into array
14805// - class: merge into single expression with concatenation
14806function dedupeProperties(properties) {
14807 const knownProps = new Map();
14808 const deduped = [];
14809 for (let i = 0; i < properties.length; i++) {
14810 const prop = properties[i];
14811 // dynamic keys are always allowed
14812 if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
14813 deduped.push(prop);
14814 continue;
14815 }
14816 const name = prop.key.content;
14817 const existing = knownProps.get(name);
14818 if (existing) {
14819 if (name === 'style' || name === 'class' || isOn(name)) {
14820 mergeAsArray$1(existing, prop);
14821 }
14822 // unexpected duplicate, should have emitted error during parse
14823 }
14824 else {
14825 knownProps.set(name, prop);
14826 deduped.push(prop);
14827 }
14828 }
14829 return deduped;
14830}
14831function mergeAsArray$1(existing, incoming) {
14832 if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
14833 existing.value.elements.push(incoming.value);
14834 }
14835 else {
14836 existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
14837 }
14838}
14839function buildDirectiveArgs(dir, context) {
14840 const dirArgs = [];
14841 const runtime = directiveImportMap.get(dir);
14842 if (runtime) {
14843 // built-in directive with runtime
14844 dirArgs.push(context.helperString(runtime));
14845 }
14846 else {
14847 {
14848 // inject statement for resolving directive
14849 context.helper(RESOLVE_DIRECTIVE);
14850 context.directives.add(dir.name);
14851 dirArgs.push(toValidAssetId(dir.name, `directive`));
14852 }
14853 }
14854 const { loc } = dir;
14855 if (dir.exp)
14856 dirArgs.push(dir.exp);
14857 if (dir.arg) {
14858 if (!dir.exp) {
14859 dirArgs.push(`void 0`);
14860 }
14861 dirArgs.push(dir.arg);
14862 }
14863 if (Object.keys(dir.modifiers).length) {
14864 if (!dir.arg) {
14865 if (!dir.exp) {
14866 dirArgs.push(`void 0`);
14867 }
14868 dirArgs.push(`void 0`);
14869 }
14870 const trueExpression = createSimpleExpression(`true`, false, loc);
14871 dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
14872 }
14873 return createArrayExpression(dirArgs, dir.loc);
14874}
14875function stringifyDynamicPropNames(props) {
14876 let propsNamesString = `[`;
14877 for (let i = 0, l = props.length; i < l; i++) {
14878 propsNamesString += JSON.stringify(props[i]);
14879 if (i < l - 1)
14880 propsNamesString += ', ';
14881 }
14882 return propsNamesString + `]`;
14883}
14884function isComponentTag(tag) {
14885 return tag === 'component' || tag === 'Component';
14886}
14887
14888const transformSlotOutlet = (node, context) => {
14889 if (isSlotOutlet(node)) {
14890 const { children, loc } = node;
14891 const { slotName, slotProps } = processSlotOutlet(node, context);
14892 const slotArgs = [
14893 context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
14894 slotName,
14895 '{}',
14896 'undefined',
14897 'true'
14898 ];
14899 let expectedLen = 2;
14900 if (slotProps) {
14901 slotArgs[2] = slotProps;
14902 expectedLen = 3;
14903 }
14904 if (children.length) {
14905 slotArgs[3] = createFunctionExpression([], children, false, false, loc);
14906 expectedLen = 4;
14907 }
14908 if (context.scopeId && !context.slotted) {
14909 expectedLen = 5;
14910 }
14911 slotArgs.splice(expectedLen); // remove unused arguments
14912 node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
14913 }
14914};
14915function processSlotOutlet(node, context) {
14916 let slotName = `"default"`;
14917 let slotProps = undefined;
14918 const nonNameProps = [];
14919 for (let i = 0; i < node.props.length; i++) {
14920 const p = node.props[i];
14921 if (p.type === 6 /* ATTRIBUTE */) {
14922 if (p.value) {
14923 if (p.name === 'name') {
14924 slotName = JSON.stringify(p.value.content);
14925 }
14926 else {
14927 p.name = camelize(p.name);
14928 nonNameProps.push(p);
14929 }
14930 }
14931 }
14932 else {
14933 if (p.name === 'bind' && isStaticArgOf(p.arg, 'name')) {
14934 if (p.exp)
14935 slotName = p.exp;
14936 }
14937 else {
14938 if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
14939 p.arg.content = camelize(p.arg.content);
14940 }
14941 nonNameProps.push(p);
14942 }
14943 }
14944 }
14945 if (nonNameProps.length > 0) {
14946 const { props, directives } = buildProps(node, context, nonNameProps);
14947 slotProps = props;
14948 if (directives.length) {
14949 context.onError(createCompilerError(36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
14950 }
14951 }
14952 return {
14953 slotName,
14954 slotProps
14955 };
14956}
14957
14958const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/;
14959const transformOn = (dir, node, context, augmentor) => {
14960 const { loc, modifiers, arg } = dir;
14961 if (!dir.exp && !modifiers.length) {
14962 context.onError(createCompilerError(35 /* X_V_ON_NO_EXPRESSION */, loc));
14963 }
14964 let eventName;
14965 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
14966 if (arg.isStatic) {
14967 let rawName = arg.content;
14968 // TODO deprecate @vnodeXXX usage
14969 if (rawName.startsWith('vue:')) {
14970 rawName = `vnode-${rawName.slice(4)}`;
14971 }
14972 // for all event listeners, auto convert it to camelCase. See issue #2249
14973 eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
14974 }
14975 else {
14976 // #2388
14977 eventName = createCompoundExpression([
14978 `${context.helperString(TO_HANDLER_KEY)}(`,
14979 arg,
14980 `)`
14981 ]);
14982 }
14983 }
14984 else {
14985 // already a compound expression.
14986 eventName = arg;
14987 eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
14988 eventName.children.push(`)`);
14989 }
14990 // handler processing
14991 let exp = dir.exp;
14992 if (exp && !exp.content.trim()) {
14993 exp = undefined;
14994 }
14995 let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
14996 if (exp) {
14997 const isMemberExp = isMemberExpression(exp.content);
14998 const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
14999 const hasMultipleStatements = exp.content.includes(`;`);
15000 {
15001 validateBrowserExpression(exp, context, false, hasMultipleStatements);
15002 }
15003 if (isInlineStatement || (shouldCache && isMemberExp)) {
15004 // wrap inline statement in a function expression
15005 exp = createCompoundExpression([
15006 `${isInlineStatement
15007 ? `$event`
15008 : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
15009 exp,
15010 hasMultipleStatements ? `}` : `)`
15011 ]);
15012 }
15013 }
15014 let ret = {
15015 props: [
15016 createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
15017 ]
15018 };
15019 // apply extended compiler augmentor
15020 if (augmentor) {
15021 ret = augmentor(ret);
15022 }
15023 if (shouldCache) {
15024 // cache handlers so that it's always the same handler being passed down.
15025 // this avoids unnecessary re-renders when users use inline handlers on
15026 // components.
15027 ret.props[0].value = context.cache(ret.props[0].value);
15028 }
15029 // mark the key as handler for props normalization check
15030 ret.props.forEach(p => (p.key.isHandlerKey = true));
15031 return ret;
15032};
15033
15034// v-bind without arg is handled directly in ./transformElements.ts due to it affecting
15035// codegen for the entire props object. This transform here is only for v-bind
15036// *with* args.
15037const transformBind = (dir, _node, context) => {
15038 const { exp, modifiers, loc } = dir;
15039 const arg = dir.arg;
15040 if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
15041 arg.children.unshift(`(`);
15042 arg.children.push(`) || ""`);
15043 }
15044 else if (!arg.isStatic) {
15045 arg.content = `${arg.content} || ""`;
15046 }
15047 // .sync is replaced by v-model:arg
15048 if (modifiers.includes('camel')) {
15049 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
15050 if (arg.isStatic) {
15051 arg.content = camelize(arg.content);
15052 }
15053 else {
15054 arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
15055 }
15056 }
15057 else {
15058 arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
15059 arg.children.push(`)`);
15060 }
15061 }
15062 if (!context.inSSR) {
15063 if (modifiers.includes('prop')) {
15064 injectPrefix(arg, '.');
15065 }
15066 if (modifiers.includes('attr')) {
15067 injectPrefix(arg, '^');
15068 }
15069 }
15070 if (!exp ||
15071 (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
15072 context.onError(createCompilerError(34 /* X_V_BIND_NO_EXPRESSION */, loc));
15073 return {
15074 props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
15075 };
15076 }
15077 return {
15078 props: [createObjectProperty(arg, exp)]
15079 };
15080};
15081const injectPrefix = (arg, prefix) => {
15082 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
15083 if (arg.isStatic) {
15084 arg.content = prefix + arg.content;
15085 }
15086 else {
15087 arg.content = `\`${prefix}\${${arg.content}}\``;
15088 }
15089 }
15090 else {
15091 arg.children.unshift(`'${prefix}' + (`);
15092 arg.children.push(`)`);
15093 }
15094};
15095
15096// Merge adjacent text nodes and expressions into a single expression
15097// e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
15098const transformText = (node, context) => {
15099 if (node.type === 0 /* ROOT */ ||
15100 node.type === 1 /* ELEMENT */ ||
15101 node.type === 11 /* FOR */ ||
15102 node.type === 10 /* IF_BRANCH */) {
15103 // perform the transform on node exit so that all expressions have already
15104 // been processed.
15105 return () => {
15106 const children = node.children;
15107 let currentContainer = undefined;
15108 let hasText = false;
15109 for (let i = 0; i < children.length; i++) {
15110 const child = children[i];
15111 if (isText(child)) {
15112 hasText = true;
15113 for (let j = i + 1; j < children.length; j++) {
15114 const next = children[j];
15115 if (isText(next)) {
15116 if (!currentContainer) {
15117 currentContainer = children[i] = {
15118 type: 8 /* COMPOUND_EXPRESSION */,
15119 loc: child.loc,
15120 children: [child]
15121 };
15122 }
15123 // merge adjacent text node into current
15124 currentContainer.children.push(` + `, next);
15125 children.splice(j, 1);
15126 j--;
15127 }
15128 else {
15129 currentContainer = undefined;
15130 break;
15131 }
15132 }
15133 }
15134 }
15135 if (!hasText ||
15136 // if this is a plain element with a single text child, leave it
15137 // as-is since the runtime has dedicated fast path for this by directly
15138 // setting textContent of the element.
15139 // for component root it's always normalized anyway.
15140 (children.length === 1 &&
15141 (node.type === 0 /* ROOT */ ||
15142 (node.type === 1 /* ELEMENT */ &&
15143 node.tagType === 0 /* ELEMENT */ &&
15144 // #3756
15145 // custom directives can potentially add DOM elements arbitrarily,
15146 // we need to avoid setting textContent of the element at runtime
15147 // to avoid accidentally overwriting the DOM elements added
15148 // by the user through custom directives.
15149 !node.props.find(p => p.type === 7 /* DIRECTIVE */ &&
15150 !context.directiveTransforms[p.name]) &&
15151 // in compat mode, <template> tags with no special directives
15152 // will be rendered as a fragment so its children must be
15153 // converted into vnodes.
15154 !(false ))))) {
15155 return;
15156 }
15157 // pre-convert text nodes into createTextVNode(text) calls to avoid
15158 // runtime normalization.
15159 for (let i = 0; i < children.length; i++) {
15160 const child = children[i];
15161 if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
15162 const callArgs = [];
15163 // createTextVNode defaults to single whitespace, so if it is a
15164 // single space the code could be an empty call to save bytes.
15165 if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
15166 callArgs.push(child);
15167 }
15168 // mark dynamic text with flag so it gets patched inside a block
15169 if (!context.ssr &&
15170 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
15171 callArgs.push(1 /* TEXT */ +
15172 (` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
15173 }
15174 children[i] = {
15175 type: 12 /* TEXT_CALL */,
15176 content: child,
15177 loc: child.loc,
15178 codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
15179 };
15180 }
15181 }
15182 };
15183 }
15184};
15185
15186const seen = new WeakSet();
15187const transformOnce = (node, context) => {
15188 if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
15189 if (seen.has(node) || context.inVOnce) {
15190 return;
15191 }
15192 seen.add(node);
15193 context.inVOnce = true;
15194 context.helper(SET_BLOCK_TRACKING);
15195 return () => {
15196 context.inVOnce = false;
15197 const cur = context.currentNode;
15198 if (cur.codegenNode) {
15199 cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
15200 }
15201 };
15202 }
15203};
15204
15205const transformModel = (dir, node, context) => {
15206 const { exp, arg } = dir;
15207 if (!exp) {
15208 context.onError(createCompilerError(41 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
15209 return createTransformProps();
15210 }
15211 const rawExp = exp.loc.source;
15212 const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
15213 // im SFC <script setup> inline mode, the exp may have been transformed into
15214 // _unref(exp)
15215 context.bindingMetadata[rawExp];
15216 const maybeRef = !true /* SETUP_CONST */;
15217 if (!expString.trim() ||
15218 (!isMemberExpression(expString) && !maybeRef)) {
15219 context.onError(createCompilerError(42 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
15220 return createTransformProps();
15221 }
15222 const propName = arg ? arg : createSimpleExpression('modelValue', true);
15223 const eventName = arg
15224 ? isStaticExp(arg)
15225 ? `onUpdate:${arg.content}`
15226 : createCompoundExpression(['"onUpdate:" + ', arg])
15227 : `onUpdate:modelValue`;
15228 let assignmentExp;
15229 const eventArg = context.isTS ? `($event: any)` : `$event`;
15230 {
15231 assignmentExp = createCompoundExpression([
15232 `${eventArg} => ((`,
15233 exp,
15234 `) = $event)`
15235 ]);
15236 }
15237 const props = [
15238 // modelValue: foo
15239 createObjectProperty(propName, dir.exp),
15240 // "onUpdate:modelValue": $event => (foo = $event)
15241 createObjectProperty(eventName, assignmentExp)
15242 ];
15243 // modelModifiers: { foo: true, "bar-baz": true }
15244 if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
15245 const modifiers = dir.modifiers
15246 .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
15247 .join(`, `);
15248 const modifiersKey = arg
15249 ? isStaticExp(arg)
15250 ? `${arg.content}Modifiers`
15251 : createCompoundExpression([arg, ' + "Modifiers"'])
15252 : `modelModifiers`;
15253 props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
15254 }
15255 return createTransformProps(props);
15256};
15257function createTransformProps(props = []) {
15258 return { props };
15259}
15260
15261const seen$1 = new WeakSet();
15262const transformMemo = (node, context) => {
15263 if (node.type === 1 /* ELEMENT */) {
15264 const dir = findDir(node, 'memo');
15265 if (!dir || seen$1.has(node)) {
15266 return;
15267 }
15268 seen$1.add(node);
15269 return () => {
15270 const codegenNode = node.codegenNode ||
15271 context.currentNode.codegenNode;
15272 if (codegenNode && codegenNode.type === 13 /* VNODE_CALL */) {
15273 // non-component sub tree should be turned into a block
15274 if (node.tagType !== 1 /* COMPONENT */) {
15275 makeBlock(codegenNode, context);
15276 }
15277 node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
15278 dir.exp,
15279 createFunctionExpression(undefined, codegenNode),
15280 `_cache`,
15281 String(context.cached++)
15282 ]);
15283 }
15284 };
15285 }
15286};
15287
15288function getBaseTransformPreset(prefixIdentifiers) {
15289 return [
15290 [
15291 transformOnce,
15292 transformIf,
15293 transformMemo,
15294 transformFor,
15295 ...([]),
15296 ...([transformExpression]
15297 ),
15298 transformSlotOutlet,
15299 transformElement,
15300 trackSlotScopes,
15301 transformText
15302 ],
15303 {
15304 on: transformOn,
15305 bind: transformBind,
15306 model: transformModel
15307 }
15308 ];
15309}
15310// we name it `baseCompile` so that higher order compilers like
15311// @vue/compiler-dom can export `compile` while re-exporting everything else.
15312function baseCompile(template, options = {}) {
15313 const onError = options.onError || defaultOnError;
15314 const isModuleMode = options.mode === 'module';
15315 /* istanbul ignore if */
15316 {
15317 if (options.prefixIdentifiers === true) {
15318 onError(createCompilerError(46 /* X_PREFIX_ID_NOT_SUPPORTED */));
15319 }
15320 else if (isModuleMode) {
15321 onError(createCompilerError(47 /* X_MODULE_MODE_NOT_SUPPORTED */));
15322 }
15323 }
15324 const prefixIdentifiers = !true ;
15325 if (options.cacheHandlers) {
15326 onError(createCompilerError(48 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
15327 }
15328 if (options.scopeId && !isModuleMode) {
15329 onError(createCompilerError(49 /* X_SCOPE_ID_NOT_SUPPORTED */));
15330 }
15331 const ast = isString(template) ? baseParse(template, options) : template;
15332 const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
15333 transform(ast, extend({}, options, {
15334 prefixIdentifiers,
15335 nodeTransforms: [
15336 ...nodeTransforms,
15337 ...(options.nodeTransforms || []) // user transforms
15338 ],
15339 directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
15340 )
15341 }));
15342 return generate(ast, extend({}, options, {
15343 prefixIdentifiers
15344 }));
15345}
15346
15347const noopDirectiveTransform = () => ({ props: [] });
15348
15349const V_MODEL_RADIO = Symbol(`vModelRadio` );
15350const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
15351const V_MODEL_TEXT = Symbol(`vModelText` );
15352const V_MODEL_SELECT = Symbol(`vModelSelect` );
15353const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
15354const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
15355const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
15356const V_SHOW = Symbol(`vShow` );
15357const TRANSITION$1 = Symbol(`Transition` );
15358const TRANSITION_GROUP = Symbol(`TransitionGroup` );
15359registerRuntimeHelpers({
15360 [V_MODEL_RADIO]: `vModelRadio`,
15361 [V_MODEL_CHECKBOX]: `vModelCheckbox`,
15362 [V_MODEL_TEXT]: `vModelText`,
15363 [V_MODEL_SELECT]: `vModelSelect`,
15364 [V_MODEL_DYNAMIC]: `vModelDynamic`,
15365 [V_ON_WITH_MODIFIERS]: `withModifiers`,
15366 [V_ON_WITH_KEYS]: `withKeys`,
15367 [V_SHOW]: `vShow`,
15368 [TRANSITION$1]: `Transition`,
15369 [TRANSITION_GROUP]: `TransitionGroup`
15370});
15371
15372/* eslint-disable no-restricted-globals */
15373let decoder;
15374function decodeHtmlBrowser(raw, asAttr = false) {
15375 if (!decoder) {
15376 decoder = document.createElement('div');
15377 }
15378 if (asAttr) {
15379 decoder.innerHTML = `<div foo="${raw.replace(/"/g, '&quot;')}">`;
15380 return decoder.children[0].getAttribute('foo');
15381 }
15382 else {
15383 decoder.innerHTML = raw;
15384 return decoder.textContent;
15385 }
15386}
15387
15388const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
15389const parserOptions = {
15390 isVoidTag,
15391 isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
15392 isPreTag: tag => tag === 'pre',
15393 decodeEntities: decodeHtmlBrowser ,
15394 isBuiltInComponent: (tag) => {
15395 if (isBuiltInType(tag, `Transition`)) {
15396 return TRANSITION$1;
15397 }
15398 else if (isBuiltInType(tag, `TransitionGroup`)) {
15399 return TRANSITION_GROUP;
15400 }
15401 },
15402 // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
15403 getNamespace(tag, parent) {
15404 let ns = parent ? parent.ns : 0 /* HTML */;
15405 if (parent && ns === 2 /* MATH_ML */) {
15406 if (parent.tag === 'annotation-xml') {
15407 if (tag === 'svg') {
15408 return 1 /* SVG */;
15409 }
15410 if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
15411 a.name === 'encoding' &&
15412 a.value != null &&
15413 (a.value.content === 'text/html' ||
15414 a.value.content === 'application/xhtml+xml'))) {
15415 ns = 0 /* HTML */;
15416 }
15417 }
15418 else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
15419 tag !== 'mglyph' &&
15420 tag !== 'malignmark') {
15421 ns = 0 /* HTML */;
15422 }
15423 }
15424 else if (parent && ns === 1 /* SVG */) {
15425 if (parent.tag === 'foreignObject' ||
15426 parent.tag === 'desc' ||
15427 parent.tag === 'title') {
15428 ns = 0 /* HTML */;
15429 }
15430 }
15431 if (ns === 0 /* HTML */) {
15432 if (tag === 'svg') {
15433 return 1 /* SVG */;
15434 }
15435 if (tag === 'math') {
15436 return 2 /* MATH_ML */;
15437 }
15438 }
15439 return ns;
15440 },
15441 // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
15442 getTextMode({ tag, ns }) {
15443 if (ns === 0 /* HTML */) {
15444 if (tag === 'textarea' || tag === 'title') {
15445 return 1 /* RCDATA */;
15446 }
15447 if (isRawTextContainer(tag)) {
15448 return 2 /* RAWTEXT */;
15449 }
15450 }
15451 return 0 /* DATA */;
15452 }
15453};
15454
15455// Parse inline CSS strings for static style attributes into an object.
15456// This is a NodeTransform since it works on the static `style` attribute and
15457// converts it into a dynamic equivalent:
15458// style="color: red" -> :style='{ "color": "red" }'
15459// It is then processed by `transformElement` and included in the generated
15460// props.
15461const transformStyle = node => {
15462 if (node.type === 1 /* ELEMENT */) {
15463 node.props.forEach((p, i) => {
15464 if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
15465 // replace p with an expression node
15466 node.props[i] = {
15467 type: 7 /* DIRECTIVE */,
15468 name: `bind`,
15469 arg: createSimpleExpression(`style`, true, p.loc),
15470 exp: parseInlineCSS(p.value.content, p.loc),
15471 modifiers: [],
15472 loc: p.loc
15473 };
15474 }
15475 });
15476 }
15477};
15478const parseInlineCSS = (cssText, loc) => {
15479 const normalized = parseStringStyle(cssText);
15480 return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
15481};
15482
15483function createDOMCompilerError(code, loc) {
15484 return createCompilerError(code, loc, DOMErrorMessages );
15485}
15486const DOMErrorMessages = {
15487 [50 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
15488 [51 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
15489 [52 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
15490 [53 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
15491 [54 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
15492 [55 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
15493 [56 /* 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.`,
15494 [57 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
15495 [58 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
15496 [59 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
15497 [60 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
15498};
15499
15500const transformVHtml = (dir, node, context) => {
15501 const { exp, loc } = dir;
15502 if (!exp) {
15503 context.onError(createDOMCompilerError(50 /* X_V_HTML_NO_EXPRESSION */, loc));
15504 }
15505 if (node.children.length) {
15506 context.onError(createDOMCompilerError(51 /* X_V_HTML_WITH_CHILDREN */, loc));
15507 node.children.length = 0;
15508 }
15509 return {
15510 props: [
15511 createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
15512 ]
15513 };
15514};
15515
15516const transformVText = (dir, node, context) => {
15517 const { exp, loc } = dir;
15518 if (!exp) {
15519 context.onError(createDOMCompilerError(52 /* X_V_TEXT_NO_EXPRESSION */, loc));
15520 }
15521 if (node.children.length) {
15522 context.onError(createDOMCompilerError(53 /* X_V_TEXT_WITH_CHILDREN */, loc));
15523 node.children.length = 0;
15524 }
15525 return {
15526 props: [
15527 createObjectProperty(createSimpleExpression(`textContent`, true), exp
15528 ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
15529 : createSimpleExpression('', true))
15530 ]
15531 };
15532};
15533
15534const transformModel$1 = (dir, node, context) => {
15535 const baseResult = transformModel(dir, node, context);
15536 // base transform has errors OR component v-model (only need props)
15537 if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
15538 return baseResult;
15539 }
15540 if (dir.arg) {
15541 context.onError(createDOMCompilerError(55 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
15542 }
15543 function checkDuplicatedValue() {
15544 const value = findProp(node, 'value');
15545 if (value) {
15546 context.onError(createDOMCompilerError(57 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
15547 }
15548 }
15549 const { tag } = node;
15550 const isCustomElement = context.isCustomElement(tag);
15551 if (tag === 'input' ||
15552 tag === 'textarea' ||
15553 tag === 'select' ||
15554 isCustomElement) {
15555 let directiveToUse = V_MODEL_TEXT;
15556 let isInvalidType = false;
15557 if (tag === 'input' || isCustomElement) {
15558 const type = findProp(node, `type`);
15559 if (type) {
15560 if (type.type === 7 /* DIRECTIVE */) {
15561 // :type="foo"
15562 directiveToUse = V_MODEL_DYNAMIC;
15563 }
15564 else if (type.value) {
15565 switch (type.value.content) {
15566 case 'radio':
15567 directiveToUse = V_MODEL_RADIO;
15568 break;
15569 case 'checkbox':
15570 directiveToUse = V_MODEL_CHECKBOX;
15571 break;
15572 case 'file':
15573 isInvalidType = true;
15574 context.onError(createDOMCompilerError(56 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
15575 break;
15576 default:
15577 // text type
15578 checkDuplicatedValue();
15579 break;
15580 }
15581 }
15582 }
15583 else if (hasDynamicKeyVBind(node)) {
15584 // element has bindings with dynamic keys, which can possibly contain
15585 // "type".
15586 directiveToUse = V_MODEL_DYNAMIC;
15587 }
15588 else {
15589 // text type
15590 checkDuplicatedValue();
15591 }
15592 }
15593 else if (tag === 'select') {
15594 directiveToUse = V_MODEL_SELECT;
15595 }
15596 else {
15597 // textarea
15598 checkDuplicatedValue();
15599 }
15600 // inject runtime directive
15601 // by returning the helper symbol via needRuntime
15602 // the import will replaced a resolveDirective call.
15603 if (!isInvalidType) {
15604 baseResult.needRuntime = context.helper(directiveToUse);
15605 }
15606 }
15607 else {
15608 context.onError(createDOMCompilerError(54 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
15609 }
15610 // native vmodel doesn't need the `modelValue` props since they are also
15611 // passed to the runtime as `binding.value`. removing it reduces code size.
15612 baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
15613 p.key.content === 'modelValue'));
15614 return baseResult;
15615};
15616
15617const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
15618const isNonKeyModifier = /*#__PURE__*/ makeMap(
15619// event propagation management
15620`stop,prevent,self,` +
15621 // system modifiers + exact
15622 `ctrl,shift,alt,meta,exact,` +
15623 // mouse
15624 `middle`);
15625// left & right could be mouse or key modifiers based on event type
15626const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
15627const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
15628const resolveModifiers = (key, modifiers, context, loc) => {
15629 const keyModifiers = [];
15630 const nonKeyModifiers = [];
15631 const eventOptionModifiers = [];
15632 for (let i = 0; i < modifiers.length; i++) {
15633 const modifier = modifiers[i];
15634 if (isEventOptionModifier(modifier)) {
15635 // eventOptionModifiers: modifiers for addEventListener() options,
15636 // e.g. .passive & .capture
15637 eventOptionModifiers.push(modifier);
15638 }
15639 else {
15640 // runtimeModifiers: modifiers that needs runtime guards
15641 if (maybeKeyModifier(modifier)) {
15642 if (isStaticExp(key)) {
15643 if (isKeyboardEvent(key.content)) {
15644 keyModifiers.push(modifier);
15645 }
15646 else {
15647 nonKeyModifiers.push(modifier);
15648 }
15649 }
15650 else {
15651 keyModifiers.push(modifier);
15652 nonKeyModifiers.push(modifier);
15653 }
15654 }
15655 else {
15656 if (isNonKeyModifier(modifier)) {
15657 nonKeyModifiers.push(modifier);
15658 }
15659 else {
15660 keyModifiers.push(modifier);
15661 }
15662 }
15663 }
15664 }
15665 return {
15666 keyModifiers,
15667 nonKeyModifiers,
15668 eventOptionModifiers
15669 };
15670};
15671const transformClick = (key, event) => {
15672 const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
15673 return isStaticClick
15674 ? createSimpleExpression(event, true)
15675 : key.type !== 4 /* SIMPLE_EXPRESSION */
15676 ? createCompoundExpression([
15677 `(`,
15678 key,
15679 `) === "onClick" ? "${event}" : (`,
15680 key,
15681 `)`
15682 ])
15683 : key;
15684};
15685const transformOn$1 = (dir, node, context) => {
15686 return transformOn(dir, node, context, baseResult => {
15687 const { modifiers } = dir;
15688 if (!modifiers.length)
15689 return baseResult;
15690 let { key, value: handlerExp } = baseResult.props[0];
15691 const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
15692 // normalize click.right and click.middle since they don't actually fire
15693 if (nonKeyModifiers.includes('right')) {
15694 key = transformClick(key, `onContextmenu`);
15695 }
15696 if (nonKeyModifiers.includes('middle')) {
15697 key = transformClick(key, `onMouseup`);
15698 }
15699 if (nonKeyModifiers.length) {
15700 handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
15701 handlerExp,
15702 JSON.stringify(nonKeyModifiers)
15703 ]);
15704 }
15705 if (keyModifiers.length &&
15706 // if event name is dynamic, always wrap with keys guard
15707 (!isStaticExp(key) || isKeyboardEvent(key.content))) {
15708 handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
15709 handlerExp,
15710 JSON.stringify(keyModifiers)
15711 ]);
15712 }
15713 if (eventOptionModifiers.length) {
15714 const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
15715 key = isStaticExp(key)
15716 ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
15717 : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
15718 }
15719 return {
15720 props: [createObjectProperty(key, handlerExp)]
15721 };
15722 });
15723};
15724
15725const transformShow = (dir, node, context) => {
15726 const { exp, loc } = dir;
15727 if (!exp) {
15728 context.onError(createDOMCompilerError(58 /* X_V_SHOW_NO_EXPRESSION */, loc));
15729 }
15730 return {
15731 props: [],
15732 needRuntime: context.helper(V_SHOW)
15733 };
15734};
15735
15736const warnTransitionChildren = (node, context) => {
15737 if (node.type === 1 /* ELEMENT */ &&
15738 node.tagType === 1 /* COMPONENT */) {
15739 const component = context.isBuiltInComponent(node.tag);
15740 if (component === TRANSITION$1) {
15741 return () => {
15742 if (node.children.length && hasMultipleChildren(node)) {
15743 context.onError(createDOMCompilerError(59 /* X_TRANSITION_INVALID_CHILDREN */, {
15744 start: node.children[0].loc.start,
15745 end: node.children[node.children.length - 1].loc.end,
15746 source: ''
15747 }));
15748 }
15749 };
15750 }
15751 }
15752};
15753function hasMultipleChildren(node) {
15754 // #1352 filter out potential comment nodes.
15755 const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */ &&
15756 !(c.type === 2 /* TEXT */ && !c.content.trim())));
15757 const child = children[0];
15758 return (children.length !== 1 ||
15759 child.type === 11 /* FOR */ ||
15760 (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
15761}
15762
15763const ignoreSideEffectTags = (node, context) => {
15764 if (node.type === 1 /* ELEMENT */ &&
15765 node.tagType === 0 /* ELEMENT */ &&
15766 (node.tag === 'script' || node.tag === 'style')) {
15767 context.onError(createDOMCompilerError(60 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
15768 context.removeNode();
15769 }
15770};
15771
15772const DOMNodeTransforms = [
15773 transformStyle,
15774 ...([warnTransitionChildren] )
15775];
15776const DOMDirectiveTransforms = {
15777 cloak: noopDirectiveTransform,
15778 html: transformVHtml,
15779 text: transformVText,
15780 model: transformModel$1,
15781 on: transformOn$1,
15782 show: transformShow
15783};
15784function compile$1(template, options = {}) {
15785 return baseCompile(template, extend({}, parserOptions, options, {
15786 nodeTransforms: [
15787 // ignore <script> and <tag>
15788 // this is not put inside DOMNodeTransforms because that list is used
15789 // by compiler-ssr to generate vnode fallback branches
15790 ignoreSideEffectTags,
15791 ...DOMNodeTransforms,
15792 ...(options.nodeTransforms || [])
15793 ],
15794 directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
15795 transformHoist: null
15796 }));
15797}
15798
15799// This entry is the "full-build" that includes both the runtime
15800{
15801 initDev();
15802}
15803const compileCache = Object.create(null);
15804function compileToFunction(template, options) {
15805 if (!isString(template)) {
15806 if (template.nodeType) {
15807 template = template.innerHTML;
15808 }
15809 else {
15810 warn$1(`invalid template option: `, template);
15811 return NOOP;
15812 }
15813 }
15814 const key = template;
15815 const cached = compileCache[key];
15816 if (cached) {
15817 return cached;
15818 }
15819 if (template[0] === '#') {
15820 const el = document.querySelector(template);
15821 if (!el) {
15822 warn$1(`Template element not found or is empty: ${template}`);
15823 }
15824 // __UNSAFE__
15825 // Reason: potential execution of JS expressions in in-DOM template.
15826 // The user must make sure the in-DOM template is trusted. If it's rendered
15827 // by the server, the template should not contain any user data.
15828 template = el ? el.innerHTML : ``;
15829 }
15830 const { code } = compile$1(template, extend({
15831 hoistStatic: true,
15832 onError: onError ,
15833 onWarn: e => onError(e, true)
15834 }, options));
15835 function onError(err, asWarning = false) {
15836 const message = asWarning
15837 ? err.message
15838 : `Template compilation error: ${err.message}`;
15839 const codeFrame = err.loc &&
15840 generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
15841 warn$1(codeFrame ? `${message}\n${codeFrame}` : message);
15842 }
15843 // The wildcard import results in a huge object with every export
15844 // with keys that cannot be mangled, and can be quite heavy size-wise.
15845 // In the global build we know `Vue` is available globally so we can avoid
15846 // the wildcard object.
15847 const render = (new Function('Vue', code)(runtimeDom));
15848 render._rc = true;
15849 return (compileCache[key] = render);
15850}
15851registerRuntimeCompiler(compileToFunction);
15852
15853export { BaseTransition, Comment, EffectScope, Fragment, KeepAlive, ReactiveEffect, Static, Suspense, Teleport, Text, Transition, TransitionGroup, VueElement, callWithAsyncErrorHandling, callWithErrorHandling, camelize, capitalize, cloneVNode, compatUtils, compileToFunction as compile, computed$1 as computed, createApp, createBlock, createCommentVNode, createElementBlock, createBaseVNode as createElementVNode, createHydrationRenderer, createPropsRestProxy, createRenderer, createSSRApp, createSlots, createStaticVNode, createTextVNode, createVNode, customRef, defineAsyncComponent, defineComponent, defineCustomElement, defineEmits, defineExpose, defineProps, defineSSRCustomElement, devtools, effect, effectScope, getCurrentInstance, getCurrentScope, getTransitionRawChildren, guardReactiveProps, h, handleError, hydrate, initCustomFormatter, initDirectivesForSSR, inject, isMemoSame, isProxy, isReactive, isReadonly, isRef, isRuntimeOnly, isShallow, isVNode, markRaw, mergeDefaults, mergeProps, nextTick, normalizeClass, normalizeProps, normalizeStyle, onActivated, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onErrorCaptured, onMounted, onRenderTracked, onRenderTriggered, onScopeDispose, onServerPrefetch, onUnmounted, onUpdated, openBlock, popScopeId, provide, proxyRefs, pushScopeId, queuePostFlushCb, reactive, readonly, ref, registerRuntimeCompiler, render, renderList, renderSlot, resolveComponent, resolveDirective, resolveDynamicComponent, resolveFilter, resolveTransitionHooks, setBlockTracking, setDevtoolsHook, setTransitionHooks, shallowReactive, shallowReadonly, shallowRef, ssrContextKey, ssrUtils, stop, toDisplayString, toHandlerKey, toHandlers, toRaw, toRef, toRefs, transformVNodeArgs, triggerRef, unref, useAttrs, useCssModule, useCssVars, useSSRContext, useSlots, useTransitionState, vModelCheckbox, vModelDynamic, vModelRadio, vModelSelect, vModelText, vShow, version, warn$1 as warn, watch, watchEffect, watchPostEffect, watchSyncEffect, withAsyncContext, withCtx, withDefaults, withDirectives, withKeys, withMemo, withModifiers, withScopeId };