UNPKG

603 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 this.active = true;
431 this.effects = [];
432 this.cleanups = [];
433 if (!detached && activeEffectScope) {
434 this.parent = activeEffectScope;
435 this.index =
436 (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(this) - 1;
437 }
438 }
439 run(fn) {
440 if (this.active) {
441 try {
442 activeEffectScope = this;
443 return fn();
444 }
445 finally {
446 activeEffectScope = this.parent;
447 }
448 }
449 else {
450 warn(`cannot run an inactive effect scope.`);
451 }
452 }
453 on() {
454 activeEffectScope = this;
455 }
456 off() {
457 activeEffectScope = this.parent;
458 }
459 stop(fromParent) {
460 if (this.active) {
461 let i, l;
462 for (i = 0, l = this.effects.length; i < l; i++) {
463 this.effects[i].stop();
464 }
465 for (i = 0, l = this.cleanups.length; i < l; i++) {
466 this.cleanups[i]();
467 }
468 if (this.scopes) {
469 for (i = 0, l = this.scopes.length; i < l; i++) {
470 this.scopes[i].stop(true);
471 }
472 }
473 // nested scope, dereference from parent to avoid memory leaks
474 if (this.parent && !fromParent) {
475 // optimized O(1) removal
476 const last = this.parent.scopes.pop();
477 if (last && last !== this) {
478 this.parent.scopes[this.index] = last;
479 last.index = this.index;
480 }
481 }
482 this.active = false;
483 }
484 }
485}
486function effectScope(detached) {
487 return new EffectScope(detached);
488}
489function recordEffectScope(effect, scope = activeEffectScope) {
490 if (scope && scope.active) {
491 scope.effects.push(effect);
492 }
493}
494function getCurrentScope() {
495 return activeEffectScope;
496}
497function onScopeDispose(fn) {
498 if (activeEffectScope) {
499 activeEffectScope.cleanups.push(fn);
500 }
501 else {
502 warn(`onScopeDispose() is called when there is no active effect scope` +
503 ` to be associated with.`);
504 }
505}
506
507const createDep = (effects) => {
508 const dep = new Set(effects);
509 dep.w = 0;
510 dep.n = 0;
511 return dep;
512};
513const wasTracked = (dep) => (dep.w & trackOpBit) > 0;
514const newTracked = (dep) => (dep.n & trackOpBit) > 0;
515const initDepMarkers = ({ deps }) => {
516 if (deps.length) {
517 for (let i = 0; i < deps.length; i++) {
518 deps[i].w |= trackOpBit; // set was tracked
519 }
520 }
521};
522const finalizeDepMarkers = (effect) => {
523 const { deps } = effect;
524 if (deps.length) {
525 let ptr = 0;
526 for (let i = 0; i < deps.length; i++) {
527 const dep = deps[i];
528 if (wasTracked(dep) && !newTracked(dep)) {
529 dep.delete(effect);
530 }
531 else {
532 deps[ptr++] = dep;
533 }
534 // clear bits
535 dep.w &= ~trackOpBit;
536 dep.n &= ~trackOpBit;
537 }
538 deps.length = ptr;
539 }
540};
541
542const targetMap = new WeakMap();
543// The number of effects currently being tracked recursively.
544let effectTrackDepth = 0;
545let trackOpBit = 1;
546/**
547 * The bitwise track markers support at most 30 levels of recursion.
548 * This value is chosen to enable modern JS engines to use a SMI on all platforms.
549 * When recursion depth is greater, fall back to using a full cleanup.
550 */
551const maxMarkerBits = 30;
552let activeEffect;
553const ITERATE_KEY = Symbol('iterate' );
554const MAP_KEY_ITERATE_KEY = Symbol('Map key iterate' );
555class ReactiveEffect {
556 constructor(fn, scheduler = null, scope) {
557 this.fn = fn;
558 this.scheduler = scheduler;
559 this.active = true;
560 this.deps = [];
561 this.parent = undefined;
562 recordEffectScope(this, scope);
563 }
564 run() {
565 if (!this.active) {
566 return this.fn();
567 }
568 let parent = activeEffect;
569 let lastShouldTrack = shouldTrack;
570 while (parent) {
571 if (parent === this) {
572 return;
573 }
574 parent = parent.parent;
575 }
576 try {
577 this.parent = activeEffect;
578 activeEffect = this;
579 shouldTrack = true;
580 trackOpBit = 1 << ++effectTrackDepth;
581 if (effectTrackDepth <= maxMarkerBits) {
582 initDepMarkers(this);
583 }
584 else {
585 cleanupEffect(this);
586 }
587 return this.fn();
588 }
589 finally {
590 if (effectTrackDepth <= maxMarkerBits) {
591 finalizeDepMarkers(this);
592 }
593 trackOpBit = 1 << --effectTrackDepth;
594 activeEffect = this.parent;
595 shouldTrack = lastShouldTrack;
596 this.parent = undefined;
597 }
598 }
599 stop() {
600 if (this.active) {
601 cleanupEffect(this);
602 if (this.onStop) {
603 this.onStop();
604 }
605 this.active = false;
606 }
607 }
608}
609function cleanupEffect(effect) {
610 const { deps } = effect;
611 if (deps.length) {
612 for (let i = 0; i < deps.length; i++) {
613 deps[i].delete(effect);
614 }
615 deps.length = 0;
616 }
617}
618function effect(fn, options) {
619 if (fn.effect) {
620 fn = fn.effect.fn;
621 }
622 const _effect = new ReactiveEffect(fn);
623 if (options) {
624 extend(_effect, options);
625 if (options.scope)
626 recordEffectScope(_effect, options.scope);
627 }
628 if (!options || !options.lazy) {
629 _effect.run();
630 }
631 const runner = _effect.run.bind(_effect);
632 runner.effect = _effect;
633 return runner;
634}
635function stop(runner) {
636 runner.effect.stop();
637}
638let shouldTrack = true;
639const trackStack = [];
640function pauseTracking() {
641 trackStack.push(shouldTrack);
642 shouldTrack = false;
643}
644function resetTracking() {
645 const last = trackStack.pop();
646 shouldTrack = last === undefined ? true : last;
647}
648function track(target, type, key) {
649 if (shouldTrack && activeEffect) {
650 let depsMap = targetMap.get(target);
651 if (!depsMap) {
652 targetMap.set(target, (depsMap = new Map()));
653 }
654 let dep = depsMap.get(key);
655 if (!dep) {
656 depsMap.set(key, (dep = createDep()));
657 }
658 const eventInfo = { effect: activeEffect, target, type, key }
659 ;
660 trackEffects(dep, eventInfo);
661 }
662}
663function trackEffects(dep, debuggerEventExtraInfo) {
664 let shouldTrack = false;
665 if (effectTrackDepth <= maxMarkerBits) {
666 if (!newTracked(dep)) {
667 dep.n |= trackOpBit; // set newly tracked
668 shouldTrack = !wasTracked(dep);
669 }
670 }
671 else {
672 // Full cleanup mode.
673 shouldTrack = !dep.has(activeEffect);
674 }
675 if (shouldTrack) {
676 dep.add(activeEffect);
677 activeEffect.deps.push(dep);
678 if (activeEffect.onTrack) {
679 activeEffect.onTrack(Object.assign({
680 effect: activeEffect
681 }, debuggerEventExtraInfo));
682 }
683 }
684}
685function trigger(target, type, key, newValue, oldValue, oldTarget) {
686 const depsMap = targetMap.get(target);
687 if (!depsMap) {
688 // never been tracked
689 return;
690 }
691 let deps = [];
692 if (type === "clear" /* CLEAR */) {
693 // collection being cleared
694 // trigger all effects for target
695 deps = [...depsMap.values()];
696 }
697 else if (key === 'length' && isArray(target)) {
698 depsMap.forEach((dep, key) => {
699 if (key === 'length' || key >= newValue) {
700 deps.push(dep);
701 }
702 });
703 }
704 else {
705 // schedule runs for SET | ADD | DELETE
706 if (key !== void 0) {
707 deps.push(depsMap.get(key));
708 }
709 // also run for iteration key on ADD | DELETE | Map.SET
710 switch (type) {
711 case "add" /* ADD */:
712 if (!isArray(target)) {
713 deps.push(depsMap.get(ITERATE_KEY));
714 if (isMap(target)) {
715 deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
716 }
717 }
718 else if (isIntegerKey(key)) {
719 // new index added to array -> length changes
720 deps.push(depsMap.get('length'));
721 }
722 break;
723 case "delete" /* DELETE */:
724 if (!isArray(target)) {
725 deps.push(depsMap.get(ITERATE_KEY));
726 if (isMap(target)) {
727 deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
728 }
729 }
730 break;
731 case "set" /* SET */:
732 if (isMap(target)) {
733 deps.push(depsMap.get(ITERATE_KEY));
734 }
735 break;
736 }
737 }
738 const eventInfo = { target, type, key, newValue, oldValue, oldTarget }
739 ;
740 if (deps.length === 1) {
741 if (deps[0]) {
742 {
743 triggerEffects(deps[0], eventInfo);
744 }
745 }
746 }
747 else {
748 const effects = [];
749 for (const dep of deps) {
750 if (dep) {
751 effects.push(...dep);
752 }
753 }
754 {
755 triggerEffects(createDep(effects), eventInfo);
756 }
757 }
758}
759function triggerEffects(dep, debuggerEventExtraInfo) {
760 // spread into array for stabilization
761 for (const effect of isArray(dep) ? dep : [...dep]) {
762 if (effect !== activeEffect || effect.allowRecurse) {
763 if (effect.onTrigger) {
764 effect.onTrigger(extend({ effect }, debuggerEventExtraInfo));
765 }
766 if (effect.scheduler) {
767 effect.scheduler();
768 }
769 else {
770 effect.run();
771 }
772 }
773 }
774}
775
776const isNonTrackableKeys = /*#__PURE__*/ makeMap(`__proto__,__v_isRef,__isVue`);
777const builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol)
778 .map(key => Symbol[key])
779 .filter(isSymbol));
780const get = /*#__PURE__*/ createGetter();
781const shallowGet = /*#__PURE__*/ createGetter(false, true);
782const readonlyGet = /*#__PURE__*/ createGetter(true);
783const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
784const arrayInstrumentations = /*#__PURE__*/ createArrayInstrumentations();
785function createArrayInstrumentations() {
786 const instrumentations = {};
787 ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
788 instrumentations[key] = function (...args) {
789 const arr = toRaw(this);
790 for (let i = 0, l = this.length; i < l; i++) {
791 track(arr, "get" /* GET */, i + '');
792 }
793 // we run the method using the original args first (which may be reactive)
794 const res = arr[key](...args);
795 if (res === -1 || res === false) {
796 // if that didn't work, run it again using raw values.
797 return arr[key](...args.map(toRaw));
798 }
799 else {
800 return res;
801 }
802 };
803 });
804 ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
805 instrumentations[key] = function (...args) {
806 pauseTracking();
807 const res = toRaw(this)[key].apply(this, args);
808 resetTracking();
809 return res;
810 };
811 });
812 return instrumentations;
813}
814function createGetter(isReadonly = false, shallow = false) {
815 return function get(target, key, receiver) {
816 if (key === "__v_isReactive" /* IS_REACTIVE */) {
817 return !isReadonly;
818 }
819 else if (key === "__v_isReadonly" /* IS_READONLY */) {
820 return isReadonly;
821 }
822 else if (key === "__v_isShallow" /* IS_SHALLOW */) {
823 return shallow;
824 }
825 else if (key === "__v_raw" /* RAW */ &&
826 receiver ===
827 (isReadonly
828 ? shallow
829 ? shallowReadonlyMap
830 : readonlyMap
831 : shallow
832 ? shallowReactiveMap
833 : reactiveMap).get(target)) {
834 return target;
835 }
836 const targetIsArray = isArray(target);
837 if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) {
838 return Reflect.get(arrayInstrumentations, key, receiver);
839 }
840 const res = Reflect.get(target, key, receiver);
841 if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
842 return res;
843 }
844 if (!isReadonly) {
845 track(target, "get" /* GET */, key);
846 }
847 if (shallow) {
848 return res;
849 }
850 if (isRef(res)) {
851 // ref unwrapping - does not apply for Array + integer key.
852 const shouldUnwrap = !targetIsArray || !isIntegerKey(key);
853 return shouldUnwrap ? res.value : res;
854 }
855 if (isObject(res)) {
856 // Convert returned value into a proxy as well. we do the isObject check
857 // here to avoid invalid value warning. Also need to lazy access readonly
858 // and reactive here to avoid circular dependency.
859 return isReadonly ? readonly(res) : reactive(res);
860 }
861 return res;
862 };
863}
864const set = /*#__PURE__*/ createSetter();
865const shallowSet = /*#__PURE__*/ createSetter(true);
866function createSetter(shallow = false) {
867 return function set(target, key, value, receiver) {
868 let oldValue = target[key];
869 if (isReadonly(oldValue) && isRef(oldValue) && !isRef(value)) {
870 return false;
871 }
872 if (!shallow && !isReadonly(value)) {
873 if (!isShallow(value)) {
874 value = toRaw(value);
875 oldValue = toRaw(oldValue);
876 }
877 if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
878 oldValue.value = value;
879 return true;
880 }
881 }
882 const hadKey = isArray(target) && isIntegerKey(key)
883 ? Number(key) < target.length
884 : hasOwn(target, key);
885 const result = Reflect.set(target, key, value, receiver);
886 // don't trigger if target is something up in the prototype chain of original
887 if (target === toRaw(receiver)) {
888 if (!hadKey) {
889 trigger(target, "add" /* ADD */, key, value);
890 }
891 else if (hasChanged(value, oldValue)) {
892 trigger(target, "set" /* SET */, key, value, oldValue);
893 }
894 }
895 return result;
896 };
897}
898function deleteProperty(target, key) {
899 const hadKey = hasOwn(target, key);
900 const oldValue = target[key];
901 const result = Reflect.deleteProperty(target, key);
902 if (result && hadKey) {
903 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
904 }
905 return result;
906}
907function has(target, key) {
908 const result = Reflect.has(target, key);
909 if (!isSymbol(key) || !builtInSymbols.has(key)) {
910 track(target, "has" /* HAS */, key);
911 }
912 return result;
913}
914function ownKeys(target) {
915 track(target, "iterate" /* ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
916 return Reflect.ownKeys(target);
917}
918const mutableHandlers = {
919 get,
920 set,
921 deleteProperty,
922 has,
923 ownKeys
924};
925const readonlyHandlers = {
926 get: readonlyGet,
927 set(target, key) {
928 {
929 console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
930 }
931 return true;
932 },
933 deleteProperty(target, key) {
934 {
935 console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
936 }
937 return true;
938 }
939};
940const shallowReactiveHandlers = /*#__PURE__*/ extend({}, mutableHandlers, {
941 get: shallowGet,
942 set: shallowSet
943});
944// Props handlers are special in the sense that it should not unwrap top-level
945// refs (in order to allow refs to be explicitly passed down), but should
946// retain the reactivity of the normal readonly object.
947const shallowReadonlyHandlers = /*#__PURE__*/ extend({}, readonlyHandlers, {
948 get: shallowReadonlyGet
949});
950
951const toShallow = (value) => value;
952const getProto = (v) => Reflect.getPrototypeOf(v);
953function get$1(target, key, isReadonly = false, isShallow = false) {
954 // #1772: readonly(reactive(Map)) should return readonly + reactive version
955 // of the value
956 target = target["__v_raw" /* RAW */];
957 const rawTarget = toRaw(target);
958 const rawKey = toRaw(key);
959 if (key !== rawKey) {
960 !isReadonly && track(rawTarget, "get" /* GET */, key);
961 }
962 !isReadonly && track(rawTarget, "get" /* GET */, rawKey);
963 const { has } = getProto(rawTarget);
964 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
965 if (has.call(rawTarget, key)) {
966 return wrap(target.get(key));
967 }
968 else if (has.call(rawTarget, rawKey)) {
969 return wrap(target.get(rawKey));
970 }
971 else if (target !== rawTarget) {
972 // #3602 readonly(reactive(Map))
973 // ensure that the nested reactive `Map` can do tracking for itself
974 target.get(key);
975 }
976}
977function has$1(key, isReadonly = false) {
978 const target = this["__v_raw" /* RAW */];
979 const rawTarget = toRaw(target);
980 const rawKey = toRaw(key);
981 if (key !== rawKey) {
982 !isReadonly && track(rawTarget, "has" /* HAS */, key);
983 }
984 !isReadonly && track(rawTarget, "has" /* HAS */, rawKey);
985 return key === rawKey
986 ? target.has(key)
987 : target.has(key) || target.has(rawKey);
988}
989function size(target, isReadonly = false) {
990 target = target["__v_raw" /* RAW */];
991 !isReadonly && track(toRaw(target), "iterate" /* ITERATE */, ITERATE_KEY);
992 return Reflect.get(target, 'size', target);
993}
994function add(value) {
995 value = toRaw(value);
996 const target = toRaw(this);
997 const proto = getProto(target);
998 const hadKey = proto.has.call(target, value);
999 if (!hadKey) {
1000 target.add(value);
1001 trigger(target, "add" /* ADD */, value, value);
1002 }
1003 return this;
1004}
1005function set$1(key, value) {
1006 value = toRaw(value);
1007 const target = toRaw(this);
1008 const { has, get } = getProto(target);
1009 let hadKey = has.call(target, key);
1010 if (!hadKey) {
1011 key = toRaw(key);
1012 hadKey = has.call(target, key);
1013 }
1014 else {
1015 checkIdentityKeys(target, has, key);
1016 }
1017 const oldValue = get.call(target, key);
1018 target.set(key, value);
1019 if (!hadKey) {
1020 trigger(target, "add" /* ADD */, key, value);
1021 }
1022 else if (hasChanged(value, oldValue)) {
1023 trigger(target, "set" /* SET */, key, value, oldValue);
1024 }
1025 return this;
1026}
1027function deleteEntry(key) {
1028 const target = toRaw(this);
1029 const { has, get } = getProto(target);
1030 let hadKey = has.call(target, key);
1031 if (!hadKey) {
1032 key = toRaw(key);
1033 hadKey = has.call(target, key);
1034 }
1035 else {
1036 checkIdentityKeys(target, has, key);
1037 }
1038 const oldValue = get ? get.call(target, key) : undefined;
1039 // forward the operation before queueing reactions
1040 const result = target.delete(key);
1041 if (hadKey) {
1042 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
1043 }
1044 return result;
1045}
1046function clear() {
1047 const target = toRaw(this);
1048 const hadItems = target.size !== 0;
1049 const oldTarget = isMap(target)
1050 ? new Map(target)
1051 : new Set(target)
1052 ;
1053 // forward the operation before queueing reactions
1054 const result = target.clear();
1055 if (hadItems) {
1056 trigger(target, "clear" /* CLEAR */, undefined, undefined, oldTarget);
1057 }
1058 return result;
1059}
1060function createForEach(isReadonly, isShallow) {
1061 return function forEach(callback, thisArg) {
1062 const observed = this;
1063 const target = observed["__v_raw" /* RAW */];
1064 const rawTarget = toRaw(target);
1065 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
1066 !isReadonly && track(rawTarget, "iterate" /* ITERATE */, ITERATE_KEY);
1067 return target.forEach((value, key) => {
1068 // important: make sure the callback is
1069 // 1. invoked with the reactive map as `this` and 3rd arg
1070 // 2. the value received should be a corresponding reactive/readonly.
1071 return callback.call(thisArg, wrap(value), wrap(key), observed);
1072 });
1073 };
1074}
1075function createIterableMethod(method, isReadonly, isShallow) {
1076 return function (...args) {
1077 const target = this["__v_raw" /* RAW */];
1078 const rawTarget = toRaw(target);
1079 const targetIsMap = isMap(rawTarget);
1080 const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
1081 const isKeyOnly = method === 'keys' && targetIsMap;
1082 const innerIterator = target[method](...args);
1083 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
1084 !isReadonly &&
1085 track(rawTarget, "iterate" /* ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
1086 // return a wrapped iterator which returns observed versions of the
1087 // values emitted from the real iterator
1088 return {
1089 // iterator protocol
1090 next() {
1091 const { value, done } = innerIterator.next();
1092 return done
1093 ? { value, done }
1094 : {
1095 value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
1096 done
1097 };
1098 },
1099 // iterable protocol
1100 [Symbol.iterator]() {
1101 return this;
1102 }
1103 };
1104 };
1105}
1106function createReadonlyMethod(type) {
1107 return function (...args) {
1108 {
1109 const key = args[0] ? `on key "${args[0]}" ` : ``;
1110 console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
1111 }
1112 return type === "delete" /* DELETE */ ? false : this;
1113 };
1114}
1115function createInstrumentations() {
1116 const mutableInstrumentations = {
1117 get(key) {
1118 return get$1(this, key);
1119 },
1120 get size() {
1121 return size(this);
1122 },
1123 has: has$1,
1124 add,
1125 set: set$1,
1126 delete: deleteEntry,
1127 clear,
1128 forEach: createForEach(false, false)
1129 };
1130 const shallowInstrumentations = {
1131 get(key) {
1132 return get$1(this, key, false, true);
1133 },
1134 get size() {
1135 return size(this);
1136 },
1137 has: has$1,
1138 add,
1139 set: set$1,
1140 delete: deleteEntry,
1141 clear,
1142 forEach: createForEach(false, true)
1143 };
1144 const readonlyInstrumentations = {
1145 get(key) {
1146 return get$1(this, key, true);
1147 },
1148 get size() {
1149 return size(this, true);
1150 },
1151 has(key) {
1152 return has$1.call(this, key, true);
1153 },
1154 add: createReadonlyMethod("add" /* ADD */),
1155 set: createReadonlyMethod("set" /* SET */),
1156 delete: createReadonlyMethod("delete" /* DELETE */),
1157 clear: createReadonlyMethod("clear" /* CLEAR */),
1158 forEach: createForEach(true, false)
1159 };
1160 const shallowReadonlyInstrumentations = {
1161 get(key) {
1162 return get$1(this, key, true, true);
1163 },
1164 get size() {
1165 return size(this, true);
1166 },
1167 has(key) {
1168 return has$1.call(this, key, true);
1169 },
1170 add: createReadonlyMethod("add" /* ADD */),
1171 set: createReadonlyMethod("set" /* SET */),
1172 delete: createReadonlyMethod("delete" /* DELETE */),
1173 clear: createReadonlyMethod("clear" /* CLEAR */),
1174 forEach: createForEach(true, true)
1175 };
1176 const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
1177 iteratorMethods.forEach(method => {
1178 mutableInstrumentations[method] = createIterableMethod(method, false, false);
1179 readonlyInstrumentations[method] = createIterableMethod(method, true, false);
1180 shallowInstrumentations[method] = createIterableMethod(method, false, true);
1181 shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true);
1182 });
1183 return [
1184 mutableInstrumentations,
1185 readonlyInstrumentations,
1186 shallowInstrumentations,
1187 shallowReadonlyInstrumentations
1188 ];
1189}
1190const [mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations] = /* #__PURE__*/ createInstrumentations();
1191function createInstrumentationGetter(isReadonly, shallow) {
1192 const instrumentations = shallow
1193 ? isReadonly
1194 ? shallowReadonlyInstrumentations
1195 : shallowInstrumentations
1196 : isReadonly
1197 ? readonlyInstrumentations
1198 : mutableInstrumentations;
1199 return (target, key, receiver) => {
1200 if (key === "__v_isReactive" /* IS_REACTIVE */) {
1201 return !isReadonly;
1202 }
1203 else if (key === "__v_isReadonly" /* IS_READONLY */) {
1204 return isReadonly;
1205 }
1206 else if (key === "__v_raw" /* RAW */) {
1207 return target;
1208 }
1209 return Reflect.get(hasOwn(instrumentations, key) && key in target
1210 ? instrumentations
1211 : target, key, receiver);
1212 };
1213}
1214const mutableCollectionHandlers = {
1215 get: /*#__PURE__*/ createInstrumentationGetter(false, false)
1216};
1217const shallowCollectionHandlers = {
1218 get: /*#__PURE__*/ createInstrumentationGetter(false, true)
1219};
1220const readonlyCollectionHandlers = {
1221 get: /*#__PURE__*/ createInstrumentationGetter(true, false)
1222};
1223const shallowReadonlyCollectionHandlers = {
1224 get: /*#__PURE__*/ createInstrumentationGetter(true, true)
1225};
1226function checkIdentityKeys(target, has, key) {
1227 const rawKey = toRaw(key);
1228 if (rawKey !== key && has.call(target, rawKey)) {
1229 const type = toRawType(target);
1230 console.warn(`Reactive ${type} contains both the raw and reactive ` +
1231 `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
1232 `which can lead to inconsistencies. ` +
1233 `Avoid differentiating between the raw and reactive versions ` +
1234 `of an object and only use the reactive version if possible.`);
1235 }
1236}
1237
1238const reactiveMap = new WeakMap();
1239const shallowReactiveMap = new WeakMap();
1240const readonlyMap = new WeakMap();
1241const shallowReadonlyMap = new WeakMap();
1242function targetTypeMap(rawType) {
1243 switch (rawType) {
1244 case 'Object':
1245 case 'Array':
1246 return 1 /* COMMON */;
1247 case 'Map':
1248 case 'Set':
1249 case 'WeakMap':
1250 case 'WeakSet':
1251 return 2 /* COLLECTION */;
1252 default:
1253 return 0 /* INVALID */;
1254 }
1255}
1256function getTargetType(value) {
1257 return value["__v_skip" /* SKIP */] || !Object.isExtensible(value)
1258 ? 0 /* INVALID */
1259 : targetTypeMap(toRawType(value));
1260}
1261function reactive(target) {
1262 // if trying to observe a readonly proxy, return the readonly version.
1263 if (isReadonly(target)) {
1264 return target;
1265 }
1266 return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
1267}
1268/**
1269 * Return a shallowly-reactive copy of the original object, where only the root
1270 * level properties are reactive. It also does not auto-unwrap refs (even at the
1271 * root level).
1272 */
1273function shallowReactive(target) {
1274 return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
1275}
1276/**
1277 * Creates a readonly copy of the original object. Note the returned copy is not
1278 * made reactive, but `readonly` can be called on an already reactive object.
1279 */
1280function readonly(target) {
1281 return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
1282}
1283/**
1284 * Returns a reactive-copy of the original object, where only the root level
1285 * properties are readonly, and does NOT unwrap refs nor recursively convert
1286 * returned properties.
1287 * This is used for creating the props proxy object for stateful components.
1288 */
1289function shallowReadonly(target) {
1290 return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap);
1291}
1292function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) {
1293 if (!isObject(target)) {
1294 {
1295 console.warn(`value cannot be made reactive: ${String(target)}`);
1296 }
1297 return target;
1298 }
1299 // target is already a Proxy, return it.
1300 // exception: calling readonly() on a reactive object
1301 if (target["__v_raw" /* RAW */] &&
1302 !(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) {
1303 return target;
1304 }
1305 // target already has corresponding Proxy
1306 const existingProxy = proxyMap.get(target);
1307 if (existingProxy) {
1308 return existingProxy;
1309 }
1310 // only a whitelist of value types can be observed.
1311 const targetType = getTargetType(target);
1312 if (targetType === 0 /* INVALID */) {
1313 return target;
1314 }
1315 const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers);
1316 proxyMap.set(target, proxy);
1317 return proxy;
1318}
1319function isReactive(value) {
1320 if (isReadonly(value)) {
1321 return isReactive(value["__v_raw" /* RAW */]);
1322 }
1323 return !!(value && value["__v_isReactive" /* IS_REACTIVE */]);
1324}
1325function isReadonly(value) {
1326 return !!(value && value["__v_isReadonly" /* IS_READONLY */]);
1327}
1328function isShallow(value) {
1329 return !!(value && value["__v_isShallow" /* IS_SHALLOW */]);
1330}
1331function isProxy(value) {
1332 return isReactive(value) || isReadonly(value);
1333}
1334function toRaw(observed) {
1335 const raw = observed && observed["__v_raw" /* RAW */];
1336 return raw ? toRaw(raw) : observed;
1337}
1338function markRaw(value) {
1339 def(value, "__v_skip" /* SKIP */, true);
1340 return value;
1341}
1342const toReactive = (value) => isObject(value) ? reactive(value) : value;
1343const toReadonly = (value) => isObject(value) ? readonly(value) : value;
1344
1345function trackRefValue(ref) {
1346 if (shouldTrack && activeEffect) {
1347 ref = toRaw(ref);
1348 {
1349 trackEffects(ref.dep || (ref.dep = createDep()), {
1350 target: ref,
1351 type: "get" /* GET */,
1352 key: 'value'
1353 });
1354 }
1355 }
1356}
1357function triggerRefValue(ref, newVal) {
1358 ref = toRaw(ref);
1359 if (ref.dep) {
1360 {
1361 triggerEffects(ref.dep, {
1362 target: ref,
1363 type: "set" /* SET */,
1364 key: 'value',
1365 newValue: newVal
1366 });
1367 }
1368 }
1369}
1370function isRef(r) {
1371 return !!(r && r.__v_isRef === true);
1372}
1373function ref(value) {
1374 return createRef(value, false);
1375}
1376function shallowRef(value) {
1377 return createRef(value, true);
1378}
1379function createRef(rawValue, shallow) {
1380 if (isRef(rawValue)) {
1381 return rawValue;
1382 }
1383 return new RefImpl(rawValue, shallow);
1384}
1385class RefImpl {
1386 constructor(value, __v_isShallow) {
1387 this.__v_isShallow = __v_isShallow;
1388 this.dep = undefined;
1389 this.__v_isRef = true;
1390 this._rawValue = __v_isShallow ? value : toRaw(value);
1391 this._value = __v_isShallow ? value : toReactive(value);
1392 }
1393 get value() {
1394 trackRefValue(this);
1395 return this._value;
1396 }
1397 set value(newVal) {
1398 newVal = this.__v_isShallow ? newVal : toRaw(newVal);
1399 if (hasChanged(newVal, this._rawValue)) {
1400 this._rawValue = newVal;
1401 this._value = this.__v_isShallow ? newVal : toReactive(newVal);
1402 triggerRefValue(this, newVal);
1403 }
1404 }
1405}
1406function triggerRef(ref) {
1407 triggerRefValue(ref, ref.value );
1408}
1409function unref(ref) {
1410 return isRef(ref) ? ref.value : ref;
1411}
1412const shallowUnwrapHandlers = {
1413 get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
1414 set: (target, key, value, receiver) => {
1415 const oldValue = target[key];
1416 if (isRef(oldValue) && !isRef(value)) {
1417 oldValue.value = value;
1418 return true;
1419 }
1420 else {
1421 return Reflect.set(target, key, value, receiver);
1422 }
1423 }
1424};
1425function proxyRefs(objectWithRefs) {
1426 return isReactive(objectWithRefs)
1427 ? objectWithRefs
1428 : new Proxy(objectWithRefs, shallowUnwrapHandlers);
1429}
1430class CustomRefImpl {
1431 constructor(factory) {
1432 this.dep = undefined;
1433 this.__v_isRef = true;
1434 const { get, set } = factory(() => trackRefValue(this), () => triggerRefValue(this));
1435 this._get = get;
1436 this._set = set;
1437 }
1438 get value() {
1439 return this._get();
1440 }
1441 set value(newVal) {
1442 this._set(newVal);
1443 }
1444}
1445function customRef(factory) {
1446 return new CustomRefImpl(factory);
1447}
1448function toRefs(object) {
1449 if (!isProxy(object)) {
1450 console.warn(`toRefs() expects a reactive object but received a plain one.`);
1451 }
1452 const ret = isArray(object) ? new Array(object.length) : {};
1453 for (const key in object) {
1454 ret[key] = toRef(object, key);
1455 }
1456 return ret;
1457}
1458class ObjectRefImpl {
1459 constructor(_object, _key, _defaultValue) {
1460 this._object = _object;
1461 this._key = _key;
1462 this._defaultValue = _defaultValue;
1463 this.__v_isRef = true;
1464 }
1465 get value() {
1466 const val = this._object[this._key];
1467 return val === undefined ? this._defaultValue : val;
1468 }
1469 set value(newVal) {
1470 this._object[this._key] = newVal;
1471 }
1472}
1473function toRef(object, key, defaultValue) {
1474 const val = object[key];
1475 return isRef(val)
1476 ? val
1477 : new ObjectRefImpl(object, key, defaultValue);
1478}
1479
1480class ComputedRefImpl {
1481 constructor(getter, _setter, isReadonly, isSSR) {
1482 this._setter = _setter;
1483 this.dep = undefined;
1484 this.__v_isRef = true;
1485 this._dirty = true;
1486 this.effect = new ReactiveEffect(getter, () => {
1487 if (!this._dirty) {
1488 this._dirty = true;
1489 triggerRefValue(this);
1490 }
1491 });
1492 this.effect.computed = this;
1493 this.effect.active = this._cacheable = !isSSR;
1494 this["__v_isReadonly" /* IS_READONLY */] = isReadonly;
1495 }
1496 get value() {
1497 // the computed ref may get wrapped by other proxies e.g. readonly() #3376
1498 const self = toRaw(this);
1499 trackRefValue(self);
1500 if (self._dirty || !self._cacheable) {
1501 self._dirty = false;
1502 self._value = self.effect.run();
1503 }
1504 return self._value;
1505 }
1506 set value(newValue) {
1507 this._setter(newValue);
1508 }
1509}
1510function computed(getterOrOptions, debugOptions, isSSR = false) {
1511 let getter;
1512 let setter;
1513 const onlyGetter = isFunction(getterOrOptions);
1514 if (onlyGetter) {
1515 getter = getterOrOptions;
1516 setter = () => {
1517 console.warn('Write operation failed: computed value is readonly');
1518 }
1519 ;
1520 }
1521 else {
1522 getter = getterOrOptions.get;
1523 setter = getterOrOptions.set;
1524 }
1525 const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR);
1526 if (debugOptions && !isSSR) {
1527 cRef.effect.onTrack = debugOptions.onTrack;
1528 cRef.effect.onTrigger = debugOptions.onTrigger;
1529 }
1530 return cRef;
1531}
1532
1533const stack = [];
1534function pushWarningContext(vnode) {
1535 stack.push(vnode);
1536}
1537function popWarningContext() {
1538 stack.pop();
1539}
1540function warn$1(msg, ...args) {
1541 // avoid props formatting or warn handler tracking deps that might be mutated
1542 // during patch, leading to infinite recursion.
1543 pauseTracking();
1544 const instance = stack.length ? stack[stack.length - 1].component : null;
1545 const appWarnHandler = instance && instance.appContext.config.warnHandler;
1546 const trace = getComponentTrace();
1547 if (appWarnHandler) {
1548 callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [
1549 msg + args.join(''),
1550 instance && instance.proxy,
1551 trace
1552 .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
1553 .join('\n'),
1554 trace
1555 ]);
1556 }
1557 else {
1558 const warnArgs = [`[Vue warn]: ${msg}`, ...args];
1559 /* istanbul ignore if */
1560 if (trace.length &&
1561 // avoid spamming console during tests
1562 !false) {
1563 warnArgs.push(`\n`, ...formatTrace(trace));
1564 }
1565 console.warn(...warnArgs);
1566 }
1567 resetTracking();
1568}
1569function getComponentTrace() {
1570 let currentVNode = stack[stack.length - 1];
1571 if (!currentVNode) {
1572 return [];
1573 }
1574 // we can't just use the stack because it will be incomplete during updates
1575 // that did not start from the root. Re-construct the parent chain using
1576 // instance parent pointers.
1577 const normalizedStack = [];
1578 while (currentVNode) {
1579 const last = normalizedStack[0];
1580 if (last && last.vnode === currentVNode) {
1581 last.recurseCount++;
1582 }
1583 else {
1584 normalizedStack.push({
1585 vnode: currentVNode,
1586 recurseCount: 0
1587 });
1588 }
1589 const parentInstance = currentVNode.component && currentVNode.component.parent;
1590 currentVNode = parentInstance && parentInstance.vnode;
1591 }
1592 return normalizedStack;
1593}
1594/* istanbul ignore next */
1595function formatTrace(trace) {
1596 const logs = [];
1597 trace.forEach((entry, i) => {
1598 logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
1599 });
1600 return logs;
1601}
1602function formatTraceEntry({ vnode, recurseCount }) {
1603 const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
1604 const isRoot = vnode.component ? vnode.component.parent == null : false;
1605 const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
1606 const close = `>` + postfix;
1607 return vnode.props
1608 ? [open, ...formatProps(vnode.props), close]
1609 : [open + close];
1610}
1611/* istanbul ignore next */
1612function formatProps(props) {
1613 const res = [];
1614 const keys = Object.keys(props);
1615 keys.slice(0, 3).forEach(key => {
1616 res.push(...formatProp(key, props[key]));
1617 });
1618 if (keys.length > 3) {
1619 res.push(` ...`);
1620 }
1621 return res;
1622}
1623/* istanbul ignore next */
1624function formatProp(key, value, raw) {
1625 if (isString(value)) {
1626 value = JSON.stringify(value);
1627 return raw ? value : [`${key}=${value}`];
1628 }
1629 else if (typeof value === 'number' ||
1630 typeof value === 'boolean' ||
1631 value == null) {
1632 return raw ? value : [`${key}=${value}`];
1633 }
1634 else if (isRef(value)) {
1635 value = formatProp(key, toRaw(value.value), true);
1636 return raw ? value : [`${key}=Ref<`, value, `>`];
1637 }
1638 else if (isFunction(value)) {
1639 return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
1640 }
1641 else {
1642 value = toRaw(value);
1643 return raw ? value : [`${key}=`, value];
1644 }
1645}
1646
1647const ErrorTypeStrings = {
1648 ["sp" /* SERVER_PREFETCH */]: 'serverPrefetch hook',
1649 ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',
1650 ["c" /* CREATED */]: 'created hook',
1651 ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',
1652 ["m" /* MOUNTED */]: 'mounted hook',
1653 ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',
1654 ["u" /* UPDATED */]: 'updated',
1655 ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',
1656 ["um" /* UNMOUNTED */]: 'unmounted hook',
1657 ["a" /* ACTIVATED */]: 'activated hook',
1658 ["da" /* DEACTIVATED */]: 'deactivated hook',
1659 ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',
1660 ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',
1661 ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',
1662 [0 /* SETUP_FUNCTION */]: 'setup function',
1663 [1 /* RENDER_FUNCTION */]: 'render function',
1664 [2 /* WATCH_GETTER */]: 'watcher getter',
1665 [3 /* WATCH_CALLBACK */]: 'watcher callback',
1666 [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',
1667 [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',
1668 [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',
1669 [7 /* VNODE_HOOK */]: 'vnode hook',
1670 [8 /* DIRECTIVE_HOOK */]: 'directive hook',
1671 [9 /* TRANSITION_HOOK */]: 'transition hook',
1672 [10 /* APP_ERROR_HANDLER */]: 'app errorHandler',
1673 [11 /* APP_WARN_HANDLER */]: 'app warnHandler',
1674 [12 /* FUNCTION_REF */]: 'ref function',
1675 [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader',
1676 [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
1677 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/core'
1678};
1679function callWithErrorHandling(fn, instance, type, args) {
1680 let res;
1681 try {
1682 res = args ? fn(...args) : fn();
1683 }
1684 catch (err) {
1685 handleError(err, instance, type);
1686 }
1687 return res;
1688}
1689function callWithAsyncErrorHandling(fn, instance, type, args) {
1690 if (isFunction(fn)) {
1691 const res = callWithErrorHandling(fn, instance, type, args);
1692 if (res && isPromise(res)) {
1693 res.catch(err => {
1694 handleError(err, instance, type);
1695 });
1696 }
1697 return res;
1698 }
1699 const values = [];
1700 for (let i = 0; i < fn.length; i++) {
1701 values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
1702 }
1703 return values;
1704}
1705function handleError(err, instance, type, throwInDev = true) {
1706 const contextVNode = instance ? instance.vnode : null;
1707 if (instance) {
1708 let cur = instance.parent;
1709 // the exposed instance is the render proxy to keep it consistent with 2.x
1710 const exposedInstance = instance.proxy;
1711 // in production the hook receives only the error code
1712 const errorInfo = ErrorTypeStrings[type] ;
1713 while (cur) {
1714 const errorCapturedHooks = cur.ec;
1715 if (errorCapturedHooks) {
1716 for (let i = 0; i < errorCapturedHooks.length; i++) {
1717 if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
1718 return;
1719 }
1720 }
1721 }
1722 cur = cur.parent;
1723 }
1724 // app-level handling
1725 const appErrorHandler = instance.appContext.config.errorHandler;
1726 if (appErrorHandler) {
1727 callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
1728 return;
1729 }
1730 }
1731 logError(err, type, contextVNode, throwInDev);
1732}
1733function logError(err, type, contextVNode, throwInDev = true) {
1734 {
1735 const info = ErrorTypeStrings[type];
1736 if (contextVNode) {
1737 pushWarningContext(contextVNode);
1738 }
1739 warn$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
1740 if (contextVNode) {
1741 popWarningContext();
1742 }
1743 // crash in dev by default so it's more noticeable
1744 if (throwInDev) {
1745 throw err;
1746 }
1747 else {
1748 console.error(err);
1749 }
1750 }
1751}
1752
1753let isFlushing = false;
1754let isFlushPending = false;
1755const queue = [];
1756let flushIndex = 0;
1757const pendingPreFlushCbs = [];
1758let activePreFlushCbs = null;
1759let preFlushIndex = 0;
1760const pendingPostFlushCbs = [];
1761let activePostFlushCbs = null;
1762let postFlushIndex = 0;
1763const resolvedPromise = Promise.resolve();
1764let currentFlushPromise = null;
1765let currentPreFlushParentJob = null;
1766const RECURSION_LIMIT = 100;
1767function nextTick(fn) {
1768 const p = currentFlushPromise || resolvedPromise;
1769 return fn ? p.then(this ? fn.bind(this) : fn) : p;
1770}
1771// #2768
1772// Use binary-search to find a suitable position in the queue,
1773// so that the queue maintains the increasing order of job's id,
1774// which can prevent the job from being skipped and also can avoid repeated patching.
1775function findInsertionIndex(id) {
1776 // the start index should be `flushIndex + 1`
1777 let start = flushIndex + 1;
1778 let end = queue.length;
1779 while (start < end) {
1780 const middle = (start + end) >>> 1;
1781 const middleJobId = getId(queue[middle]);
1782 middleJobId < id ? (start = middle + 1) : (end = middle);
1783 }
1784 return start;
1785}
1786function queueJob(job) {
1787 // the dedupe search uses the startIndex argument of Array.includes()
1788 // by default the search index includes the current job that is being run
1789 // so it cannot recursively trigger itself again.
1790 // if the job is a watch() callback, the search will start with a +1 index to
1791 // allow it recursively trigger itself - it is the user's responsibility to
1792 // ensure it doesn't end up in an infinite loop.
1793 if ((!queue.length ||
1794 !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) &&
1795 job !== currentPreFlushParentJob) {
1796 if (job.id == null) {
1797 queue.push(job);
1798 }
1799 else {
1800 queue.splice(findInsertionIndex(job.id), 0, job);
1801 }
1802 queueFlush();
1803 }
1804}
1805function queueFlush() {
1806 if (!isFlushing && !isFlushPending) {
1807 isFlushPending = true;
1808 currentFlushPromise = resolvedPromise.then(flushJobs);
1809 }
1810}
1811function invalidateJob(job) {
1812 const i = queue.indexOf(job);
1813 if (i > flushIndex) {
1814 queue.splice(i, 1);
1815 }
1816}
1817function queueCb(cb, activeQueue, pendingQueue, index) {
1818 if (!isArray(cb)) {
1819 if (!activeQueue ||
1820 !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) {
1821 pendingQueue.push(cb);
1822 }
1823 }
1824 else {
1825 // if cb is an array, it is a component lifecycle hook which can only be
1826 // triggered by a job, which is already deduped in the main queue, so
1827 // we can skip duplicate check here to improve perf
1828 pendingQueue.push(...cb);
1829 }
1830 queueFlush();
1831}
1832function queuePreFlushCb(cb) {
1833 queueCb(cb, activePreFlushCbs, pendingPreFlushCbs, preFlushIndex);
1834}
1835function queuePostFlushCb(cb) {
1836 queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex);
1837}
1838function flushPreFlushCbs(seen, parentJob = null) {
1839 if (pendingPreFlushCbs.length) {
1840 currentPreFlushParentJob = parentJob;
1841 activePreFlushCbs = [...new Set(pendingPreFlushCbs)];
1842 pendingPreFlushCbs.length = 0;
1843 {
1844 seen = seen || new Map();
1845 }
1846 for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) {
1847 if (checkRecursiveUpdates(seen, activePreFlushCbs[preFlushIndex])) {
1848 continue;
1849 }
1850 activePreFlushCbs[preFlushIndex]();
1851 }
1852 activePreFlushCbs = null;
1853 preFlushIndex = 0;
1854 currentPreFlushParentJob = null;
1855 // recursively flush until it drains
1856 flushPreFlushCbs(seen, parentJob);
1857 }
1858}
1859function flushPostFlushCbs(seen) {
1860 if (pendingPostFlushCbs.length) {
1861 const deduped = [...new Set(pendingPostFlushCbs)];
1862 pendingPostFlushCbs.length = 0;
1863 // #1947 already has active queue, nested flushPostFlushCbs call
1864 if (activePostFlushCbs) {
1865 activePostFlushCbs.push(...deduped);
1866 return;
1867 }
1868 activePostFlushCbs = deduped;
1869 {
1870 seen = seen || new Map();
1871 }
1872 activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
1873 for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
1874 if (checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) {
1875 continue;
1876 }
1877 activePostFlushCbs[postFlushIndex]();
1878 }
1879 activePostFlushCbs = null;
1880 postFlushIndex = 0;
1881 }
1882}
1883const getId = (job) => job.id == null ? Infinity : job.id;
1884function flushJobs(seen) {
1885 isFlushPending = false;
1886 isFlushing = true;
1887 {
1888 seen = seen || new Map();
1889 }
1890 flushPreFlushCbs(seen);
1891 // Sort queue before flush.
1892 // This ensures that:
1893 // 1. Components are updated from parent to child. (because parent is always
1894 // created before the child so its render effect will have smaller
1895 // priority number)
1896 // 2. If a component is unmounted during a parent component's update,
1897 // its update can be skipped.
1898 queue.sort((a, b) => getId(a) - getId(b));
1899 // conditional usage of checkRecursiveUpdate must be determined out of
1900 // try ... catch block since Rollup by default de-optimizes treeshaking
1901 // inside try-catch. This can leave all warning code unshaked. Although
1902 // they would get eventually shaken by a minifier like terser, some minifiers
1903 // would fail to do that (e.g. https://github.com/evanw/esbuild/issues/1610)
1904 const check = (job) => checkRecursiveUpdates(seen, job)
1905 ;
1906 try {
1907 for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
1908 const job = queue[flushIndex];
1909 if (job && job.active !== false) {
1910 if (true && check(job)) {
1911 continue;
1912 }
1913 // console.log(`running:`, job.id)
1914 callWithErrorHandling(job, null, 14 /* SCHEDULER */);
1915 }
1916 }
1917 }
1918 finally {
1919 flushIndex = 0;
1920 queue.length = 0;
1921 flushPostFlushCbs(seen);
1922 isFlushing = false;
1923 currentFlushPromise = null;
1924 // some postFlushCb queued jobs!
1925 // keep flushing until it drains.
1926 if (queue.length ||
1927 pendingPreFlushCbs.length ||
1928 pendingPostFlushCbs.length) {
1929 flushJobs(seen);
1930 }
1931 }
1932}
1933function checkRecursiveUpdates(seen, fn) {
1934 if (!seen.has(fn)) {
1935 seen.set(fn, 1);
1936 }
1937 else {
1938 const count = seen.get(fn);
1939 if (count > RECURSION_LIMIT) {
1940 const instance = fn.ownerInstance;
1941 const componentName = instance && getComponentName(instance.type);
1942 warn$1(`Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. ` +
1943 `This means you have a reactive effect that is mutating its own ` +
1944 `dependencies and thus recursively triggering itself. Possible sources ` +
1945 `include component template, render function, updated hook or ` +
1946 `watcher source function.`);
1947 return true;
1948 }
1949 else {
1950 seen.set(fn, count + 1);
1951 }
1952 }
1953}
1954
1955/* eslint-disable no-restricted-globals */
1956let isHmrUpdating = false;
1957const hmrDirtyComponents = new Set();
1958// Expose the HMR runtime on the global object
1959// This makes it entirely tree-shakable without polluting the exports and makes
1960// it easier to be used in toolings like vue-loader
1961// Note: for a component to be eligible for HMR it also needs the __hmrId option
1962// to be set so that its instances can be registered / removed.
1963{
1964 getGlobalThis().__VUE_HMR_RUNTIME__ = {
1965 createRecord: tryWrap(createRecord),
1966 rerender: tryWrap(rerender),
1967 reload: tryWrap(reload)
1968 };
1969}
1970const map = new Map();
1971function registerHMR(instance) {
1972 const id = instance.type.__hmrId;
1973 let record = map.get(id);
1974 if (!record) {
1975 createRecord(id, instance.type);
1976 record = map.get(id);
1977 }
1978 record.instances.add(instance);
1979}
1980function unregisterHMR(instance) {
1981 map.get(instance.type.__hmrId).instances.delete(instance);
1982}
1983function createRecord(id, initialDef) {
1984 if (map.has(id)) {
1985 return false;
1986 }
1987 map.set(id, {
1988 initialDef: normalizeClassComponent(initialDef),
1989 instances: new Set()
1990 });
1991 return true;
1992}
1993function normalizeClassComponent(component) {
1994 return isClassComponent(component) ? component.__vccOpts : component;
1995}
1996function rerender(id, newRender) {
1997 const record = map.get(id);
1998 if (!record) {
1999 return;
2000 }
2001 // update initial record (for not-yet-rendered component)
2002 record.initialDef.render = newRender;
2003 [...record.instances].forEach(instance => {
2004 if (newRender) {
2005 instance.render = newRender;
2006 normalizeClassComponent(instance.type).render = newRender;
2007 }
2008 instance.renderCache = [];
2009 // this flag forces child components with slot content to update
2010 isHmrUpdating = true;
2011 instance.update();
2012 isHmrUpdating = false;
2013 });
2014}
2015function reload(id, newComp) {
2016 const record = map.get(id);
2017 if (!record)
2018 return;
2019 newComp = normalizeClassComponent(newComp);
2020 // update initial def (for not-yet-rendered components)
2021 updateComponentDef(record.initialDef, newComp);
2022 // create a snapshot which avoids the set being mutated during updates
2023 const instances = [...record.instances];
2024 for (const instance of instances) {
2025 const oldComp = normalizeClassComponent(instance.type);
2026 if (!hmrDirtyComponents.has(oldComp)) {
2027 // 1. Update existing comp definition to match new one
2028 if (oldComp !== record.initialDef) {
2029 updateComponentDef(oldComp, newComp);
2030 }
2031 // 2. mark definition dirty. This forces the renderer to replace the
2032 // component on patch.
2033 hmrDirtyComponents.add(oldComp);
2034 }
2035 // 3. invalidate options resolution cache
2036 instance.appContext.optionsCache.delete(instance.type);
2037 // 4. actually update
2038 if (instance.ceReload) {
2039 // custom element
2040 hmrDirtyComponents.add(oldComp);
2041 instance.ceReload(newComp.styles);
2042 hmrDirtyComponents.delete(oldComp);
2043 }
2044 else if (instance.parent) {
2045 // 4. Force the parent instance to re-render. This will cause all updated
2046 // components to be unmounted and re-mounted. Queue the update so that we
2047 // don't end up forcing the same parent to re-render multiple times.
2048 queueJob(instance.parent.update);
2049 // instance is the inner component of an async custom element
2050 // invoke to reset styles
2051 if (instance.parent.type.__asyncLoader &&
2052 instance.parent.ceReload) {
2053 instance.parent.ceReload(newComp.styles);
2054 }
2055 }
2056 else if (instance.appContext.reload) {
2057 // root instance mounted via createApp() has a reload method
2058 instance.appContext.reload();
2059 }
2060 else if (typeof window !== 'undefined') {
2061 // root instance inside tree created via raw render(). Force reload.
2062 window.location.reload();
2063 }
2064 else {
2065 console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
2066 }
2067 }
2068 // 5. make sure to cleanup dirty hmr components after update
2069 queuePostFlushCb(() => {
2070 for (const instance of instances) {
2071 hmrDirtyComponents.delete(normalizeClassComponent(instance.type));
2072 }
2073 });
2074}
2075function updateComponentDef(oldComp, newComp) {
2076 extend(oldComp, newComp);
2077 for (const key in oldComp) {
2078 if (key !== '__file' && !(key in newComp)) {
2079 delete oldComp[key];
2080 }
2081 }
2082}
2083function tryWrap(fn) {
2084 return (id, arg) => {
2085 try {
2086 return fn(id, arg);
2087 }
2088 catch (e) {
2089 console.error(e);
2090 console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
2091 `Full reload required.`);
2092 }
2093 };
2094}
2095
2096let devtools;
2097let buffer = [];
2098let devtoolsNotInstalled = false;
2099function emit(event, ...args) {
2100 if (devtools) {
2101 devtools.emit(event, ...args);
2102 }
2103 else if (!devtoolsNotInstalled) {
2104 buffer.push({ event, args });
2105 }
2106}
2107function setDevtoolsHook(hook, target) {
2108 var _a, _b;
2109 devtools = hook;
2110 if (devtools) {
2111 devtools.enabled = true;
2112 buffer.forEach(({ event, args }) => devtools.emit(event, ...args));
2113 buffer = [];
2114 }
2115 else if (
2116 // handle late devtools injection - only do this if we are in an actual
2117 // browser environment to avoid the timer handle stalling test runner exit
2118 // (#4815)
2119 // eslint-disable-next-line no-restricted-globals
2120 typeof window !== 'undefined' &&
2121 // some envs mock window but not fully
2122 window.HTMLElement &&
2123 // also exclude jsdom
2124 !((_b = (_a = window.navigator) === null || _a === void 0 ? void 0 : _a.userAgent) === null || _b === void 0 ? void 0 : _b.includes('jsdom'))) {
2125 const replay = (target.__VUE_DEVTOOLS_HOOK_REPLAY__ =
2126 target.__VUE_DEVTOOLS_HOOK_REPLAY__ || []);
2127 replay.push((newHook) => {
2128 setDevtoolsHook(newHook, target);
2129 });
2130 // clear buffer after 3s - the user probably doesn't have devtools installed
2131 // at all, and keeping the buffer will cause memory leaks (#4738)
2132 setTimeout(() => {
2133 if (!devtools) {
2134 target.__VUE_DEVTOOLS_HOOK_REPLAY__ = null;
2135 devtoolsNotInstalled = true;
2136 buffer = [];
2137 }
2138 }, 3000);
2139 }
2140 else {
2141 // non-browser env, assume not installed
2142 devtoolsNotInstalled = true;
2143 buffer = [];
2144 }
2145}
2146function devtoolsInitApp(app, version) {
2147 emit("app:init" /* APP_INIT */, app, version, {
2148 Fragment,
2149 Text,
2150 Comment,
2151 Static
2152 });
2153}
2154function devtoolsUnmountApp(app) {
2155 emit("app:unmount" /* APP_UNMOUNT */, app);
2156}
2157const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* COMPONENT_ADDED */);
2158const devtoolsComponentUpdated =
2159/*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */);
2160const devtoolsComponentRemoved =
2161/*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* COMPONENT_REMOVED */);
2162function createDevtoolsComponentHook(hook) {
2163 return (component) => {
2164 emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component);
2165 };
2166}
2167const devtoolsPerfStart = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:start" /* PERFORMANCE_START */);
2168const devtoolsPerfEnd = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:end" /* PERFORMANCE_END */);
2169function createDevtoolsPerformanceHook(hook) {
2170 return (component, type, time) => {
2171 emit(hook, component.appContext.app, component.uid, component, type, time);
2172 };
2173}
2174function devtoolsComponentEmit(component, event, params) {
2175 emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params);
2176}
2177
2178function emit$1(instance, event, ...rawArgs) {
2179 const props = instance.vnode.props || EMPTY_OBJ;
2180 {
2181 const { emitsOptions, propsOptions: [propsOptions] } = instance;
2182 if (emitsOptions) {
2183 if (!(event in emitsOptions) &&
2184 !(false )) {
2185 if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
2186 warn$1(`Component emitted event "${event}" but it is neither declared in ` +
2187 `the emits option nor as an "${toHandlerKey(event)}" prop.`);
2188 }
2189 }
2190 else {
2191 const validator = emitsOptions[event];
2192 if (isFunction(validator)) {
2193 const isValid = validator(...rawArgs);
2194 if (!isValid) {
2195 warn$1(`Invalid event arguments: event validation failed for event "${event}".`);
2196 }
2197 }
2198 }
2199 }
2200 }
2201 let args = rawArgs;
2202 const isModelListener = event.startsWith('update:');
2203 // for v-model update:xxx events, apply modifiers on args
2204 const modelArg = isModelListener && event.slice(7);
2205 if (modelArg && modelArg in props) {
2206 const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
2207 const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
2208 if (trim) {
2209 args = rawArgs.map(a => a.trim());
2210 }
2211 else if (number) {
2212 args = rawArgs.map(toNumber);
2213 }
2214 }
2215 {
2216 devtoolsComponentEmit(instance, event, args);
2217 }
2218 {
2219 const lowerCaseEvent = event.toLowerCase();
2220 if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
2221 warn$1(`Event "${lowerCaseEvent}" is emitted in component ` +
2222 `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
2223 `Note that HTML attributes are case-insensitive and you cannot use ` +
2224 `v-on to listen to camelCase events when using in-DOM templates. ` +
2225 `You should probably use "${hyphenate(event)}" instead of "${event}".`);
2226 }
2227 }
2228 let handlerName;
2229 let handler = props[(handlerName = toHandlerKey(event))] ||
2230 // also try camelCase event handler (#2249)
2231 props[(handlerName = toHandlerKey(camelize(event)))];
2232 // for v-model update:xxx events, also trigger kebab-case equivalent
2233 // for props passed via kebab-case
2234 if (!handler && isModelListener) {
2235 handler = props[(handlerName = toHandlerKey(hyphenate(event)))];
2236 }
2237 if (handler) {
2238 callWithAsyncErrorHandling(handler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
2239 }
2240 const onceHandler = props[handlerName + `Once`];
2241 if (onceHandler) {
2242 if (!instance.emitted) {
2243 instance.emitted = {};
2244 }
2245 else if (instance.emitted[handlerName]) {
2246 return;
2247 }
2248 instance.emitted[handlerName] = true;
2249 callWithAsyncErrorHandling(onceHandler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
2250 }
2251}
2252function normalizeEmitsOptions(comp, appContext, asMixin = false) {
2253 const cache = appContext.emitsCache;
2254 const cached = cache.get(comp);
2255 if (cached !== undefined) {
2256 return cached;
2257 }
2258 const raw = comp.emits;
2259 let normalized = {};
2260 // apply mixin/extends props
2261 let hasExtends = false;
2262 if (!isFunction(comp)) {
2263 const extendEmits = (raw) => {
2264 const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true);
2265 if (normalizedFromExtend) {
2266 hasExtends = true;
2267 extend(normalized, normalizedFromExtend);
2268 }
2269 };
2270 if (!asMixin && appContext.mixins.length) {
2271 appContext.mixins.forEach(extendEmits);
2272 }
2273 if (comp.extends) {
2274 extendEmits(comp.extends);
2275 }
2276 if (comp.mixins) {
2277 comp.mixins.forEach(extendEmits);
2278 }
2279 }
2280 if (!raw && !hasExtends) {
2281 cache.set(comp, null);
2282 return null;
2283 }
2284 if (isArray(raw)) {
2285 raw.forEach(key => (normalized[key] = null));
2286 }
2287 else {
2288 extend(normalized, raw);
2289 }
2290 cache.set(comp, normalized);
2291 return normalized;
2292}
2293// Check if an incoming prop key is a declared emit event listener.
2294// e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
2295// both considered matched listeners.
2296function isEmitListener(options, key) {
2297 if (!options || !isOn(key)) {
2298 return false;
2299 }
2300 key = key.slice(2).replace(/Once$/, '');
2301 return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||
2302 hasOwn(options, hyphenate(key)) ||
2303 hasOwn(options, key));
2304}
2305
2306/**
2307 * mark the current rendering instance for asset resolution (e.g.
2308 * resolveComponent, resolveDirective) during render
2309 */
2310let currentRenderingInstance = null;
2311let currentScopeId = null;
2312/**
2313 * Note: rendering calls maybe nested. The function returns the parent rendering
2314 * instance if present, which should be restored after the render is done:
2315 *
2316 * ```js
2317 * const prev = setCurrentRenderingInstance(i)
2318 * // ...render
2319 * setCurrentRenderingInstance(prev)
2320 * ```
2321 */
2322function setCurrentRenderingInstance(instance) {
2323 const prev = currentRenderingInstance;
2324 currentRenderingInstance = instance;
2325 currentScopeId = (instance && instance.type.__scopeId) || null;
2326 return prev;
2327}
2328/**
2329 * Set scope id when creating hoisted vnodes.
2330 * @private compiler helper
2331 */
2332function pushScopeId(id) {
2333 currentScopeId = id;
2334}
2335/**
2336 * Technically we no longer need this after 3.0.8 but we need to keep the same
2337 * API for backwards compat w/ code generated by compilers.
2338 * @private
2339 */
2340function popScopeId() {
2341 currentScopeId = null;
2342}
2343/**
2344 * Only for backwards compat
2345 * @private
2346 */
2347const withScopeId = (_id) => withCtx;
2348/**
2349 * Wrap a slot function to memoize current rendering instance
2350 * @private compiler helper
2351 */
2352function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot // false only
2353) {
2354 if (!ctx)
2355 return fn;
2356 // already normalized
2357 if (fn._n) {
2358 return fn;
2359 }
2360 const renderFnWithContext = (...args) => {
2361 // If a user calls a compiled slot inside a template expression (#1745), it
2362 // can mess up block tracking, so by default we disable block tracking and
2363 // force bail out when invoking a compiled slot (indicated by the ._d flag).
2364 // This isn't necessary if rendering a compiled `<slot>`, so we flip the
2365 // ._d flag off when invoking the wrapped fn inside `renderSlot`.
2366 if (renderFnWithContext._d) {
2367 setBlockTracking(-1);
2368 }
2369 const prevInstance = setCurrentRenderingInstance(ctx);
2370 const res = fn(...args);
2371 setCurrentRenderingInstance(prevInstance);
2372 if (renderFnWithContext._d) {
2373 setBlockTracking(1);
2374 }
2375 {
2376 devtoolsComponentUpdated(ctx);
2377 }
2378 return res;
2379 };
2380 // mark normalized to avoid duplicated wrapping
2381 renderFnWithContext._n = true;
2382 // mark this as compiled by default
2383 // this is used in vnode.ts -> normalizeChildren() to set the slot
2384 // rendering flag.
2385 renderFnWithContext._c = true;
2386 // disable block tracking by default
2387 renderFnWithContext._d = true;
2388 return renderFnWithContext;
2389}
2390
2391/**
2392 * dev only flag to track whether $attrs was used during render.
2393 * If $attrs was used during render then the warning for failed attrs
2394 * fallthrough can be suppressed.
2395 */
2396let accessedAttrs = false;
2397function markAttrsAccessed() {
2398 accessedAttrs = true;
2399}
2400function renderComponentRoot(instance) {
2401 const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx, inheritAttrs } = instance;
2402 let result;
2403 let fallthroughAttrs;
2404 const prev = setCurrentRenderingInstance(instance);
2405 {
2406 accessedAttrs = false;
2407 }
2408 try {
2409 if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
2410 // withProxy is a proxy with a different `has` trap only for
2411 // runtime-compiled render functions using `with` block.
2412 const proxyToUse = withProxy || proxy;
2413 result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
2414 fallthroughAttrs = attrs;
2415 }
2416 else {
2417 // functional
2418 const render = Component;
2419 // in dev, mark attrs accessed if optional props (attrs === props)
2420 if (true && attrs === props) {
2421 markAttrsAccessed();
2422 }
2423 result = normalizeVNode(render.length > 1
2424 ? render(props, true
2425 ? {
2426 get attrs() {
2427 markAttrsAccessed();
2428 return attrs;
2429 },
2430 slots,
2431 emit
2432 }
2433 : { attrs, slots, emit })
2434 : render(props, null /* we know it doesn't need it */));
2435 fallthroughAttrs = Component.props
2436 ? attrs
2437 : getFunctionalFallthrough(attrs);
2438 }
2439 }
2440 catch (err) {
2441 blockStack.length = 0;
2442 handleError(err, instance, 1 /* RENDER_FUNCTION */);
2443 result = createVNode(Comment);
2444 }
2445 // attr merging
2446 // in dev mode, comments are preserved, and it's possible for a template
2447 // to have comments along side the root element which makes it a fragment
2448 let root = result;
2449 let setRoot = undefined;
2450 if (result.patchFlag > 0 &&
2451 result.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
2452 [root, setRoot] = getChildRoot(result);
2453 }
2454 if (fallthroughAttrs && inheritAttrs !== false) {
2455 const keys = Object.keys(fallthroughAttrs);
2456 const { shapeFlag } = root;
2457 if (keys.length) {
2458 if (shapeFlag & (1 /* ELEMENT */ | 6 /* COMPONENT */)) {
2459 if (propsOptions && keys.some(isModelListener)) {
2460 // If a v-model listener (onUpdate:xxx) has a corresponding declared
2461 // prop, it indicates this component expects to handle v-model and
2462 // it should not fallthrough.
2463 // related: #1543, #1643, #1989
2464 fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
2465 }
2466 root = cloneVNode(root, fallthroughAttrs);
2467 }
2468 else if (!accessedAttrs && root.type !== Comment) {
2469 const allAttrs = Object.keys(attrs);
2470 const eventAttrs = [];
2471 const extraAttrs = [];
2472 for (let i = 0, l = allAttrs.length; i < l; i++) {
2473 const key = allAttrs[i];
2474 if (isOn(key)) {
2475 // ignore v-model handlers when they fail to fallthrough
2476 if (!isModelListener(key)) {
2477 // remove `on`, lowercase first letter to reflect event casing
2478 // accurately
2479 eventAttrs.push(key[2].toLowerCase() + key.slice(3));
2480 }
2481 }
2482 else {
2483 extraAttrs.push(key);
2484 }
2485 }
2486 if (extraAttrs.length) {
2487 warn$1(`Extraneous non-props attributes (` +
2488 `${extraAttrs.join(', ')}) ` +
2489 `were passed to component but could not be automatically inherited ` +
2490 `because component renders fragment or text root nodes.`);
2491 }
2492 if (eventAttrs.length) {
2493 warn$1(`Extraneous non-emits event listeners (` +
2494 `${eventAttrs.join(', ')}) ` +
2495 `were passed to component but could not be automatically inherited ` +
2496 `because component renders fragment or text root nodes. ` +
2497 `If the listener is intended to be a component custom event listener only, ` +
2498 `declare it using the "emits" option.`);
2499 }
2500 }
2501 }
2502 }
2503 // inherit directives
2504 if (vnode.dirs) {
2505 if (!isElementRoot(root)) {
2506 warn$1(`Runtime directive used on component with non-element root node. ` +
2507 `The directives will not function as intended.`);
2508 }
2509 root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
2510 }
2511 // inherit transition data
2512 if (vnode.transition) {
2513 if (!isElementRoot(root)) {
2514 warn$1(`Component inside <Transition> renders non-element root node ` +
2515 `that cannot be animated.`);
2516 }
2517 root.transition = vnode.transition;
2518 }
2519 if (setRoot) {
2520 setRoot(root);
2521 }
2522 else {
2523 result = root;
2524 }
2525 setCurrentRenderingInstance(prev);
2526 return result;
2527}
2528/**
2529 * dev only
2530 * In dev mode, template root level comments are rendered, which turns the
2531 * template into a fragment root, but we need to locate the single element
2532 * root for attrs and scope id processing.
2533 */
2534const getChildRoot = (vnode) => {
2535 const rawChildren = vnode.children;
2536 const dynamicChildren = vnode.dynamicChildren;
2537 const childRoot = filterSingleRoot(rawChildren);
2538 if (!childRoot) {
2539 return [vnode, undefined];
2540 }
2541 const index = rawChildren.indexOf(childRoot);
2542 const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
2543 const setRoot = (updatedRoot) => {
2544 rawChildren[index] = updatedRoot;
2545 if (dynamicChildren) {
2546 if (dynamicIndex > -1) {
2547 dynamicChildren[dynamicIndex] = updatedRoot;
2548 }
2549 else if (updatedRoot.patchFlag > 0) {
2550 vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
2551 }
2552 }
2553 };
2554 return [normalizeVNode(childRoot), setRoot];
2555};
2556function filterSingleRoot(children) {
2557 let singleRoot;
2558 for (let i = 0; i < children.length; i++) {
2559 const child = children[i];
2560 if (isVNode(child)) {
2561 // ignore user comment
2562 if (child.type !== Comment || child.children === 'v-if') {
2563 if (singleRoot) {
2564 // has more than 1 non-comment child, return now
2565 return;
2566 }
2567 else {
2568 singleRoot = child;
2569 }
2570 }
2571 }
2572 else {
2573 return;
2574 }
2575 }
2576 return singleRoot;
2577}
2578const getFunctionalFallthrough = (attrs) => {
2579 let res;
2580 for (const key in attrs) {
2581 if (key === 'class' || key === 'style' || isOn(key)) {
2582 (res || (res = {}))[key] = attrs[key];
2583 }
2584 }
2585 return res;
2586};
2587const filterModelListeners = (attrs, props) => {
2588 const res = {};
2589 for (const key in attrs) {
2590 if (!isModelListener(key) || !(key.slice(9) in props)) {
2591 res[key] = attrs[key];
2592 }
2593 }
2594 return res;
2595};
2596const isElementRoot = (vnode) => {
2597 return (vnode.shapeFlag & (6 /* COMPONENT */ | 1 /* ELEMENT */) ||
2598 vnode.type === Comment // potential v-if branch switch
2599 );
2600};
2601function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
2602 const { props: prevProps, children: prevChildren, component } = prevVNode;
2603 const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
2604 const emits = component.emitsOptions;
2605 // Parent component's render function was hot-updated. Since this may have
2606 // caused the child component's slots content to have changed, we need to
2607 // force the child to update as well.
2608 if ((prevChildren || nextChildren) && isHmrUpdating) {
2609 return true;
2610 }
2611 // force child update for runtime directive or transition on component vnode.
2612 if (nextVNode.dirs || nextVNode.transition) {
2613 return true;
2614 }
2615 if (optimized && patchFlag >= 0) {
2616 if (patchFlag & 1024 /* DYNAMIC_SLOTS */) {
2617 // slot content that references values that might have changed,
2618 // e.g. in a v-for
2619 return true;
2620 }
2621 if (patchFlag & 16 /* FULL_PROPS */) {
2622 if (!prevProps) {
2623 return !!nextProps;
2624 }
2625 // presence of this flag indicates props are always non-null
2626 return hasPropsChanged(prevProps, nextProps, emits);
2627 }
2628 else if (patchFlag & 8 /* PROPS */) {
2629 const dynamicProps = nextVNode.dynamicProps;
2630 for (let i = 0; i < dynamicProps.length; i++) {
2631 const key = dynamicProps[i];
2632 if (nextProps[key] !== prevProps[key] &&
2633 !isEmitListener(emits, key)) {
2634 return true;
2635 }
2636 }
2637 }
2638 }
2639 else {
2640 // this path is only taken by manually written render functions
2641 // so presence of any children leads to a forced update
2642 if (prevChildren || nextChildren) {
2643 if (!nextChildren || !nextChildren.$stable) {
2644 return true;
2645 }
2646 }
2647 if (prevProps === nextProps) {
2648 return false;
2649 }
2650 if (!prevProps) {
2651 return !!nextProps;
2652 }
2653 if (!nextProps) {
2654 return true;
2655 }
2656 return hasPropsChanged(prevProps, nextProps, emits);
2657 }
2658 return false;
2659}
2660function hasPropsChanged(prevProps, nextProps, emitsOptions) {
2661 const nextKeys = Object.keys(nextProps);
2662 if (nextKeys.length !== Object.keys(prevProps).length) {
2663 return true;
2664 }
2665 for (let i = 0; i < nextKeys.length; i++) {
2666 const key = nextKeys[i];
2667 if (nextProps[key] !== prevProps[key] &&
2668 !isEmitListener(emitsOptions, key)) {
2669 return true;
2670 }
2671 }
2672 return false;
2673}
2674function updateHOCHostEl({ vnode, parent }, el // HostNode
2675) {
2676 while (parent && parent.subTree === vnode) {
2677 (vnode = parent.vnode).el = el;
2678 parent = parent.parent;
2679 }
2680}
2681
2682const isSuspense = (type) => type.__isSuspense;
2683// Suspense exposes a component-like API, and is treated like a component
2684// in the compiler, but internally it's a special built-in type that hooks
2685// directly into the renderer.
2686const SuspenseImpl = {
2687 name: 'Suspense',
2688 // In order to make Suspense tree-shakable, we need to avoid importing it
2689 // directly in the renderer. The renderer checks for the __isSuspense flag
2690 // on a vnode's type and calls the `process` method, passing in renderer
2691 // internals.
2692 __isSuspense: true,
2693 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized,
2694 // platform-specific impl passed from renderer
2695 rendererInternals) {
2696 if (n1 == null) {
2697 mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals);
2698 }
2699 else {
2700 patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, rendererInternals);
2701 }
2702 },
2703 hydrate: hydrateSuspense,
2704 create: createSuspenseBoundary,
2705 normalize: normalizeSuspenseChildren
2706};
2707// Force-casted public typing for h and TSX props inference
2708const Suspense = (SuspenseImpl );
2709function triggerEvent(vnode, name) {
2710 const eventListener = vnode.props && vnode.props[name];
2711 if (isFunction(eventListener)) {
2712 eventListener();
2713 }
2714}
2715function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals) {
2716 const { p: patch, o: { createElement } } = rendererInternals;
2717 const hiddenContainer = createElement('div');
2718 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals));
2719 // start mounting the content subtree in an off-dom container
2720 patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds);
2721 // now check if we have encountered any async deps
2722 if (suspense.deps > 0) {
2723 // has async
2724 // invoke @fallback event
2725 triggerEvent(vnode, 'onPending');
2726 triggerEvent(vnode, 'onFallback');
2727 // mount the fallback tree
2728 patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2729 isSVG, slotScopeIds);
2730 setActiveBranch(suspense, vnode.ssFallback);
2731 }
2732 else {
2733 // Suspense has no async deps. Just resolve.
2734 suspense.resolve();
2735 }
2736}
2737function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) {
2738 const suspense = (n2.suspense = n1.suspense);
2739 suspense.vnode = n2;
2740 n2.el = n1.el;
2741 const newBranch = n2.ssContent;
2742 const newFallback = n2.ssFallback;
2743 const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
2744 if (pendingBranch) {
2745 suspense.pendingBranch = newBranch;
2746 if (isSameVNodeType(newBranch, pendingBranch)) {
2747 // same root type but content may have changed.
2748 patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2749 if (suspense.deps <= 0) {
2750 suspense.resolve();
2751 }
2752 else if (isInFallback) {
2753 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2754 isSVG, slotScopeIds, optimized);
2755 setActiveBranch(suspense, newFallback);
2756 }
2757 }
2758 else {
2759 // toggled before pending tree is resolved
2760 suspense.pendingId++;
2761 if (isHydrating) {
2762 // if toggled before hydration is finished, the current DOM tree is
2763 // no longer valid. set it as the active branch so it will be unmounted
2764 // when resolved
2765 suspense.isHydrating = false;
2766 suspense.activeBranch = pendingBranch;
2767 }
2768 else {
2769 unmount(pendingBranch, parentComponent, suspense);
2770 }
2771 // increment pending ID. this is used to invalidate async callbacks
2772 // reset suspense state
2773 suspense.deps = 0;
2774 // discard effects from pending branch
2775 suspense.effects.length = 0;
2776 // discard previous container
2777 suspense.hiddenContainer = createElement('div');
2778 if (isInFallback) {
2779 // already in fallback state
2780 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2781 if (suspense.deps <= 0) {
2782 suspense.resolve();
2783 }
2784 else {
2785 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2786 isSVG, slotScopeIds, optimized);
2787 setActiveBranch(suspense, newFallback);
2788 }
2789 }
2790 else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2791 // toggled "back" to current active branch
2792 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2793 // force resolve
2794 suspense.resolve(true);
2795 }
2796 else {
2797 // switched to a 3rd branch
2798 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2799 if (suspense.deps <= 0) {
2800 suspense.resolve();
2801 }
2802 }
2803 }
2804 }
2805 else {
2806 if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2807 // root did not change, just normal patch
2808 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2809 setActiveBranch(suspense, newBranch);
2810 }
2811 else {
2812 // root node toggled
2813 // invoke @pending event
2814 triggerEvent(n2, 'onPending');
2815 // mount pending branch in off-dom container
2816 suspense.pendingBranch = newBranch;
2817 suspense.pendingId++;
2818 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2819 if (suspense.deps <= 0) {
2820 // incoming branch has no async deps, resolve now.
2821 suspense.resolve();
2822 }
2823 else {
2824 const { timeout, pendingId } = suspense;
2825 if (timeout > 0) {
2826 setTimeout(() => {
2827 if (suspense.pendingId === pendingId) {
2828 suspense.fallback(newFallback);
2829 }
2830 }, timeout);
2831 }
2832 else if (timeout === 0) {
2833 suspense.fallback(newFallback);
2834 }
2835 }
2836 }
2837 }
2838}
2839let hasWarned = false;
2840function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals, isHydrating = false) {
2841 /* istanbul ignore if */
2842 if (!hasWarned) {
2843 hasWarned = true;
2844 // @ts-ignore `console.info` cannot be null error
2845 console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
2846 }
2847 const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
2848 const timeout = toNumber(vnode.props && vnode.props.timeout);
2849 const suspense = {
2850 vnode,
2851 parent,
2852 parentComponent,
2853 isSVG,
2854 container,
2855 hiddenContainer,
2856 anchor,
2857 deps: 0,
2858 pendingId: 0,
2859 timeout: typeof timeout === 'number' ? timeout : -1,
2860 activeBranch: null,
2861 pendingBranch: null,
2862 isInFallback: true,
2863 isHydrating,
2864 isUnmounted: false,
2865 effects: [],
2866 resolve(resume = false) {
2867 {
2868 if (!resume && !suspense.pendingBranch) {
2869 throw new Error(`suspense.resolve() is called without a pending branch.`);
2870 }
2871 if (suspense.isUnmounted) {
2872 throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
2873 }
2874 }
2875 const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
2876 if (suspense.isHydrating) {
2877 suspense.isHydrating = false;
2878 }
2879 else if (!resume) {
2880 const delayEnter = activeBranch &&
2881 pendingBranch.transition &&
2882 pendingBranch.transition.mode === 'out-in';
2883 if (delayEnter) {
2884 activeBranch.transition.afterLeave = () => {
2885 if (pendingId === suspense.pendingId) {
2886 move(pendingBranch, container, anchor, 0 /* ENTER */);
2887 }
2888 };
2889 }
2890 // this is initial anchor on mount
2891 let { anchor } = suspense;
2892 // unmount current active tree
2893 if (activeBranch) {
2894 // if the fallback tree was mounted, it may have been moved
2895 // as part of a parent suspense. get the latest anchor for insertion
2896 anchor = next(activeBranch);
2897 unmount(activeBranch, parentComponent, suspense, true);
2898 }
2899 if (!delayEnter) {
2900 // move content from off-dom container to actual container
2901 move(pendingBranch, container, anchor, 0 /* ENTER */);
2902 }
2903 }
2904 setActiveBranch(suspense, pendingBranch);
2905 suspense.pendingBranch = null;
2906 suspense.isInFallback = false;
2907 // flush buffered effects
2908 // check if there is a pending parent suspense
2909 let parent = suspense.parent;
2910 let hasUnresolvedAncestor = false;
2911 while (parent) {
2912 if (parent.pendingBranch) {
2913 // found a pending parent suspense, merge buffered post jobs
2914 // into that parent
2915 parent.effects.push(...effects);
2916 hasUnresolvedAncestor = true;
2917 break;
2918 }
2919 parent = parent.parent;
2920 }
2921 // no pending parent suspense, flush all jobs
2922 if (!hasUnresolvedAncestor) {
2923 queuePostFlushCb(effects);
2924 }
2925 suspense.effects = [];
2926 // invoke @resolve event
2927 triggerEvent(vnode, 'onResolve');
2928 },
2929 fallback(fallbackVNode) {
2930 if (!suspense.pendingBranch) {
2931 return;
2932 }
2933 const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
2934 // invoke @fallback event
2935 triggerEvent(vnode, 'onFallback');
2936 const anchor = next(activeBranch);
2937 const mountFallback = () => {
2938 if (!suspense.isInFallback) {
2939 return;
2940 }
2941 // mount the fallback tree
2942 patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2943 isSVG, slotScopeIds, optimized);
2944 setActiveBranch(suspense, fallbackVNode);
2945 };
2946 const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
2947 if (delayEnter) {
2948 activeBranch.transition.afterLeave = mountFallback;
2949 }
2950 suspense.isInFallback = true;
2951 // unmount current active branch
2952 unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
2953 true // shouldRemove
2954 );
2955 if (!delayEnter) {
2956 mountFallback();
2957 }
2958 },
2959 move(container, anchor, type) {
2960 suspense.activeBranch &&
2961 move(suspense.activeBranch, container, anchor, type);
2962 suspense.container = container;
2963 },
2964 next() {
2965 return suspense.activeBranch && next(suspense.activeBranch);
2966 },
2967 registerDep(instance, setupRenderEffect) {
2968 const isInPendingSuspense = !!suspense.pendingBranch;
2969 if (isInPendingSuspense) {
2970 suspense.deps++;
2971 }
2972 const hydratedEl = instance.vnode.el;
2973 instance
2974 .asyncDep.catch(err => {
2975 handleError(err, instance, 0 /* SETUP_FUNCTION */);
2976 })
2977 .then(asyncSetupResult => {
2978 // retry when the setup() promise resolves.
2979 // component may have been unmounted before resolve.
2980 if (instance.isUnmounted ||
2981 suspense.isUnmounted ||
2982 suspense.pendingId !== instance.suspenseId) {
2983 return;
2984 }
2985 // retry from this component
2986 instance.asyncResolved = true;
2987 const { vnode } = instance;
2988 {
2989 pushWarningContext(vnode);
2990 }
2991 handleSetupResult(instance, asyncSetupResult, false);
2992 if (hydratedEl) {
2993 // vnode may have been replaced if an update happened before the
2994 // async dep is resolved.
2995 vnode.el = hydratedEl;
2996 }
2997 const placeholder = !hydratedEl && instance.subTree.el;
2998 setupRenderEffect(instance, vnode,
2999 // component may have been moved before resolve.
3000 // if this is not a hydration, instance.subTree will be the comment
3001 // placeholder.
3002 parentNode(hydratedEl || instance.subTree.el),
3003 // anchor will not be used if this is hydration, so only need to
3004 // consider the comment placeholder case.
3005 hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
3006 if (placeholder) {
3007 remove(placeholder);
3008 }
3009 updateHOCHostEl(instance, vnode.el);
3010 {
3011 popWarningContext();
3012 }
3013 // only decrease deps count if suspense is not already resolved
3014 if (isInPendingSuspense && --suspense.deps === 0) {
3015 suspense.resolve();
3016 }
3017 });
3018 },
3019 unmount(parentSuspense, doRemove) {
3020 suspense.isUnmounted = true;
3021 if (suspense.activeBranch) {
3022 unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
3023 }
3024 if (suspense.pendingBranch) {
3025 unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
3026 }
3027 }
3028 };
3029 return suspense;
3030}
3031function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals, hydrateNode) {
3032 /* eslint-disable no-restricted-globals */
3033 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, slotScopeIds, optimized, rendererInternals, true /* hydrating */));
3034 // there are two possible scenarios for server-rendered suspense:
3035 // - success: ssr content should be fully resolved
3036 // - failure: ssr content should be the fallback branch.
3037 // however, on the client we don't really know if it has failed or not
3038 // attempt to hydrate the DOM assuming it has succeeded, but we still
3039 // need to construct a suspense boundary first
3040 const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, slotScopeIds, optimized);
3041 if (suspense.deps === 0) {
3042 suspense.resolve();
3043 }
3044 return result;
3045 /* eslint-enable no-restricted-globals */
3046}
3047function normalizeSuspenseChildren(vnode) {
3048 const { shapeFlag, children } = vnode;
3049 const isSlotChildren = shapeFlag & 32 /* SLOTS_CHILDREN */;
3050 vnode.ssContent = normalizeSuspenseSlot(isSlotChildren ? children.default : children);
3051 vnode.ssFallback = isSlotChildren
3052 ? normalizeSuspenseSlot(children.fallback)
3053 : createVNode(Comment);
3054}
3055function normalizeSuspenseSlot(s) {
3056 let block;
3057 if (isFunction(s)) {
3058 const trackBlock = isBlockTreeEnabled && s._c;
3059 if (trackBlock) {
3060 // disableTracking: false
3061 // allow block tracking for compiled slots
3062 // (see ./componentRenderContext.ts)
3063 s._d = false;
3064 openBlock();
3065 }
3066 s = s();
3067 if (trackBlock) {
3068 s._d = true;
3069 block = currentBlock;
3070 closeBlock();
3071 }
3072 }
3073 if (isArray(s)) {
3074 const singleChild = filterSingleRoot(s);
3075 if (!singleChild) {
3076 warn$1(`<Suspense> slots expect a single root node.`);
3077 }
3078 s = singleChild;
3079 }
3080 s = normalizeVNode(s);
3081 if (block && !s.dynamicChildren) {
3082 s.dynamicChildren = block.filter(c => c !== s);
3083 }
3084 return s;
3085}
3086function queueEffectWithSuspense(fn, suspense) {
3087 if (suspense && suspense.pendingBranch) {
3088 if (isArray(fn)) {
3089 suspense.effects.push(...fn);
3090 }
3091 else {
3092 suspense.effects.push(fn);
3093 }
3094 }
3095 else {
3096 queuePostFlushCb(fn);
3097 }
3098}
3099function setActiveBranch(suspense, branch) {
3100 suspense.activeBranch = branch;
3101 const { vnode, parentComponent } = suspense;
3102 const el = (vnode.el = branch.el);
3103 // in case suspense is the root node of a component,
3104 // recursively update the HOC el
3105 if (parentComponent && parentComponent.subTree === vnode) {
3106 parentComponent.vnode.el = el;
3107 updateHOCHostEl(parentComponent, el);
3108 }
3109}
3110
3111function provide(key, value) {
3112 if (!currentInstance) {
3113 {
3114 warn$1(`provide() can only be used inside setup().`);
3115 }
3116 }
3117 else {
3118 let provides = currentInstance.provides;
3119 // by default an instance inherits its parent's provides object
3120 // but when it needs to provide values of its own, it creates its
3121 // own provides object using parent provides object as prototype.
3122 // this way in `inject` we can simply look up injections from direct
3123 // parent and let the prototype chain do the work.
3124 const parentProvides = currentInstance.parent && currentInstance.parent.provides;
3125 if (parentProvides === provides) {
3126 provides = currentInstance.provides = Object.create(parentProvides);
3127 }
3128 // TS doesn't allow symbol as index type
3129 provides[key] = value;
3130 }
3131}
3132function inject(key, defaultValue, treatDefaultAsFactory = false) {
3133 // fallback to `currentRenderingInstance` so that this can be called in
3134 // a functional component
3135 const instance = currentInstance || currentRenderingInstance;
3136 if (instance) {
3137 // #2400
3138 // to support `app.use` plugins,
3139 // fallback to appContext's `provides` if the instance is at root
3140 const provides = instance.parent == null
3141 ? instance.vnode.appContext && instance.vnode.appContext.provides
3142 : instance.parent.provides;
3143 if (provides && key in provides) {
3144 // TS doesn't allow symbol as index type
3145 return provides[key];
3146 }
3147 else if (arguments.length > 1) {
3148 return treatDefaultAsFactory && isFunction(defaultValue)
3149 ? defaultValue.call(instance.proxy)
3150 : defaultValue;
3151 }
3152 else {
3153 warn$1(`injection "${String(key)}" not found.`);
3154 }
3155 }
3156 else {
3157 warn$1(`inject() can only be used inside setup() or functional components.`);
3158 }
3159}
3160
3161// Simple effect.
3162function watchEffect(effect, options) {
3163 return doWatch(effect, null, options);
3164}
3165function watchPostEffect(effect, options) {
3166 return doWatch(effect, null, (Object.assign(options || {}, { flush: 'post' })
3167 ));
3168}
3169function watchSyncEffect(effect, options) {
3170 return doWatch(effect, null, (Object.assign(options || {}, { flush: 'sync' })
3171 ));
3172}
3173// initial value for watchers to trigger on undefined initial values
3174const INITIAL_WATCHER_VALUE = {};
3175// implementation
3176function watch(source, cb, options) {
3177 if (!isFunction(cb)) {
3178 warn$1(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
3179 `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
3180 `supports \`watch(source, cb, options?) signature.`);
3181 }
3182 return doWatch(source, cb, options);
3183}
3184function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ) {
3185 if (!cb) {
3186 if (immediate !== undefined) {
3187 warn$1(`watch() "immediate" option is only respected when using the ` +
3188 `watch(source, callback, options?) signature.`);
3189 }
3190 if (deep !== undefined) {
3191 warn$1(`watch() "deep" option is only respected when using the ` +
3192 `watch(source, callback, options?) signature.`);
3193 }
3194 }
3195 const warnInvalidSource = (s) => {
3196 warn$1(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
3197 `a reactive object, or an array of these types.`);
3198 };
3199 const instance = currentInstance;
3200 let getter;
3201 let forceTrigger = false;
3202 let isMultiSource = false;
3203 if (isRef(source)) {
3204 getter = () => source.value;
3205 forceTrigger = isShallow(source);
3206 }
3207 else if (isReactive(source)) {
3208 getter = () => source;
3209 deep = true;
3210 }
3211 else if (isArray(source)) {
3212 isMultiSource = true;
3213 forceTrigger = source.some(isReactive);
3214 getter = () => source.map(s => {
3215 if (isRef(s)) {
3216 return s.value;
3217 }
3218 else if (isReactive(s)) {
3219 return traverse(s);
3220 }
3221 else if (isFunction(s)) {
3222 return callWithErrorHandling(s, instance, 2 /* WATCH_GETTER */);
3223 }
3224 else {
3225 warnInvalidSource(s);
3226 }
3227 });
3228 }
3229 else if (isFunction(source)) {
3230 if (cb) {
3231 // getter with cb
3232 getter = () => callWithErrorHandling(source, instance, 2 /* WATCH_GETTER */);
3233 }
3234 else {
3235 // no cb -> simple effect
3236 getter = () => {
3237 if (instance && instance.isUnmounted) {
3238 return;
3239 }
3240 if (cleanup) {
3241 cleanup();
3242 }
3243 return callWithAsyncErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onCleanup]);
3244 };
3245 }
3246 }
3247 else {
3248 getter = NOOP;
3249 warnInvalidSource(source);
3250 }
3251 if (cb && deep) {
3252 const baseGetter = getter;
3253 getter = () => traverse(baseGetter());
3254 }
3255 let cleanup;
3256 let onCleanup = (fn) => {
3257 cleanup = effect.onStop = () => {
3258 callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */);
3259 };
3260 };
3261 let oldValue = isMultiSource ? [] : INITIAL_WATCHER_VALUE;
3262 const job = () => {
3263 if (!effect.active) {
3264 return;
3265 }
3266 if (cb) {
3267 // watch(source, cb)
3268 const newValue = effect.run();
3269 if (deep ||
3270 forceTrigger ||
3271 (isMultiSource
3272 ? newValue.some((v, i) => hasChanged(v, oldValue[i]))
3273 : hasChanged(newValue, oldValue)) ||
3274 (false )) {
3275 // cleanup before running cb again
3276 if (cleanup) {
3277 cleanup();
3278 }
3279 callWithAsyncErrorHandling(cb, instance, 3 /* WATCH_CALLBACK */, [
3280 newValue,
3281 // pass undefined as the old value when it's changed for the first time
3282 oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
3283 onCleanup
3284 ]);
3285 oldValue = newValue;
3286 }
3287 }
3288 else {
3289 // watchEffect
3290 effect.run();
3291 }
3292 };
3293 // important: mark the job as a watcher callback so that scheduler knows
3294 // it is allowed to self-trigger (#1727)
3295 job.allowRecurse = !!cb;
3296 let scheduler;
3297 if (flush === 'sync') {
3298 scheduler = job; // the scheduler function gets called directly
3299 }
3300 else if (flush === 'post') {
3301 scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
3302 }
3303 else {
3304 // default: 'pre'
3305 scheduler = () => {
3306 if (!instance || instance.isMounted) {
3307 queuePreFlushCb(job);
3308 }
3309 else {
3310 // with 'pre' option, the first call must happen before
3311 // the component is mounted so it is called synchronously.
3312 job();
3313 }
3314 };
3315 }
3316 const effect = new ReactiveEffect(getter, scheduler);
3317 {
3318 effect.onTrack = onTrack;
3319 effect.onTrigger = onTrigger;
3320 }
3321 // initial run
3322 if (cb) {
3323 if (immediate) {
3324 job();
3325 }
3326 else {
3327 oldValue = effect.run();
3328 }
3329 }
3330 else if (flush === 'post') {
3331 queuePostRenderEffect(effect.run.bind(effect), instance && instance.suspense);
3332 }
3333 else {
3334 effect.run();
3335 }
3336 return () => {
3337 effect.stop();
3338 if (instance && instance.scope) {
3339 remove(instance.scope.effects, effect);
3340 }
3341 };
3342}
3343// this.$watch
3344function instanceWatch(source, value, options) {
3345 const publicThis = this.proxy;
3346 const getter = isString(source)
3347 ? source.includes('.')
3348 ? createPathGetter(publicThis, source)
3349 : () => publicThis[source]
3350 : source.bind(publicThis, publicThis);
3351 let cb;
3352 if (isFunction(value)) {
3353 cb = value;
3354 }
3355 else {
3356 cb = value.handler;
3357 options = value;
3358 }
3359 const cur = currentInstance;
3360 setCurrentInstance(this);
3361 const res = doWatch(getter, cb.bind(publicThis), options);
3362 if (cur) {
3363 setCurrentInstance(cur);
3364 }
3365 else {
3366 unsetCurrentInstance();
3367 }
3368 return res;
3369}
3370function createPathGetter(ctx, path) {
3371 const segments = path.split('.');
3372 return () => {
3373 let cur = ctx;
3374 for (let i = 0; i < segments.length && cur; i++) {
3375 cur = cur[segments[i]];
3376 }
3377 return cur;
3378 };
3379}
3380function traverse(value, seen) {
3381 if (!isObject(value) || value["__v_skip" /* SKIP */]) {
3382 return value;
3383 }
3384 seen = seen || new Set();
3385 if (seen.has(value)) {
3386 return value;
3387 }
3388 seen.add(value);
3389 if (isRef(value)) {
3390 traverse(value.value, seen);
3391 }
3392 else if (isArray(value)) {
3393 for (let i = 0; i < value.length; i++) {
3394 traverse(value[i], seen);
3395 }
3396 }
3397 else if (isSet(value) || isMap(value)) {
3398 value.forEach((v) => {
3399 traverse(v, seen);
3400 });
3401 }
3402 else if (isPlainObject(value)) {
3403 for (const key in value) {
3404 traverse(value[key], seen);
3405 }
3406 }
3407 return value;
3408}
3409
3410function useTransitionState() {
3411 const state = {
3412 isMounted: false,
3413 isLeaving: false,
3414 isUnmounting: false,
3415 leavingVNodes: new Map()
3416 };
3417 onMounted(() => {
3418 state.isMounted = true;
3419 });
3420 onBeforeUnmount(() => {
3421 state.isUnmounting = true;
3422 });
3423 return state;
3424}
3425const TransitionHookValidator = [Function, Array];
3426const BaseTransitionImpl = {
3427 name: `BaseTransition`,
3428 props: {
3429 mode: String,
3430 appear: Boolean,
3431 persisted: Boolean,
3432 // enter
3433 onBeforeEnter: TransitionHookValidator,
3434 onEnter: TransitionHookValidator,
3435 onAfterEnter: TransitionHookValidator,
3436 onEnterCancelled: TransitionHookValidator,
3437 // leave
3438 onBeforeLeave: TransitionHookValidator,
3439 onLeave: TransitionHookValidator,
3440 onAfterLeave: TransitionHookValidator,
3441 onLeaveCancelled: TransitionHookValidator,
3442 // appear
3443 onBeforeAppear: TransitionHookValidator,
3444 onAppear: TransitionHookValidator,
3445 onAfterAppear: TransitionHookValidator,
3446 onAppearCancelled: TransitionHookValidator
3447 },
3448 setup(props, { slots }) {
3449 const instance = getCurrentInstance();
3450 const state = useTransitionState();
3451 let prevTransitionKey;
3452 return () => {
3453 const children = slots.default && getTransitionRawChildren(slots.default(), true);
3454 if (!children || !children.length) {
3455 return;
3456 }
3457 // warn multiple elements
3458 if (children.length > 1) {
3459 warn$1('<transition> can only be used on a single element or component. Use ' +
3460 '<transition-group> for lists.');
3461 }
3462 // there's no need to track reactivity for these props so use the raw
3463 // props for a bit better perf
3464 const rawProps = toRaw(props);
3465 const { mode } = rawProps;
3466 // check mode
3467 if (mode &&
3468 mode !== 'in-out' && mode !== 'out-in' && mode !== 'default') {
3469 warn$1(`invalid <transition> mode: ${mode}`);
3470 }
3471 // at this point children has a guaranteed length of 1.
3472 const child = children[0];
3473 if (state.isLeaving) {
3474 return emptyPlaceholder(child);
3475 }
3476 // in the case of <transition><keep-alive/></transition>, we need to
3477 // compare the type of the kept-alive children.
3478 const innerChild = getKeepAliveChild(child);
3479 if (!innerChild) {
3480 return emptyPlaceholder(child);
3481 }
3482 const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
3483 setTransitionHooks(innerChild, enterHooks);
3484 const oldChild = instance.subTree;
3485 const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
3486 let transitionKeyChanged = false;
3487 const { getTransitionKey } = innerChild.type;
3488 if (getTransitionKey) {
3489 const key = getTransitionKey();
3490 if (prevTransitionKey === undefined) {
3491 prevTransitionKey = key;
3492 }
3493 else if (key !== prevTransitionKey) {
3494 prevTransitionKey = key;
3495 transitionKeyChanged = true;
3496 }
3497 }
3498 // handle mode
3499 if (oldInnerChild &&
3500 oldInnerChild.type !== Comment &&
3501 (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
3502 const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
3503 // update old tree's hooks in case of dynamic transition
3504 setTransitionHooks(oldInnerChild, leavingHooks);
3505 // switching between different views
3506 if (mode === 'out-in') {
3507 state.isLeaving = true;
3508 // return placeholder node and queue update when leave finishes
3509 leavingHooks.afterLeave = () => {
3510 state.isLeaving = false;
3511 instance.update();
3512 };
3513 return emptyPlaceholder(child);
3514 }
3515 else if (mode === 'in-out' && innerChild.type !== Comment) {
3516 leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
3517 const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
3518 leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
3519 // early removal callback
3520 el._leaveCb = () => {
3521 earlyRemove();
3522 el._leaveCb = undefined;
3523 delete enterHooks.delayedLeave;
3524 };
3525 enterHooks.delayedLeave = delayedLeave;
3526 };
3527 }
3528 }
3529 return child;
3530 };
3531 }
3532};
3533// export the public type for h/tsx inference
3534// also to avoid inline import() in generated d.ts files
3535const BaseTransition = BaseTransitionImpl;
3536function getLeavingNodesForType(state, vnode) {
3537 const { leavingVNodes } = state;
3538 let leavingVNodesCache = leavingVNodes.get(vnode.type);
3539 if (!leavingVNodesCache) {
3540 leavingVNodesCache = Object.create(null);
3541 leavingVNodes.set(vnode.type, leavingVNodesCache);
3542 }
3543 return leavingVNodesCache;
3544}
3545// The transition hooks are attached to the vnode as vnode.transition
3546// and will be called at appropriate timing in the renderer.
3547function resolveTransitionHooks(vnode, props, state, instance) {
3548 const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
3549 const key = String(vnode.key);
3550 const leavingVNodesCache = getLeavingNodesForType(state, vnode);
3551 const callHook = (hook, args) => {
3552 hook &&
3553 callWithAsyncErrorHandling(hook, instance, 9 /* TRANSITION_HOOK */, args);
3554 };
3555 const hooks = {
3556 mode,
3557 persisted,
3558 beforeEnter(el) {
3559 let hook = onBeforeEnter;
3560 if (!state.isMounted) {
3561 if (appear) {
3562 hook = onBeforeAppear || onBeforeEnter;
3563 }
3564 else {
3565 return;
3566 }
3567 }
3568 // for same element (v-show)
3569 if (el._leaveCb) {
3570 el._leaveCb(true /* cancelled */);
3571 }
3572 // for toggled element with same key (v-if)
3573 const leavingVNode = leavingVNodesCache[key];
3574 if (leavingVNode &&
3575 isSameVNodeType(vnode, leavingVNode) &&
3576 leavingVNode.el._leaveCb) {
3577 // force early removal (not cancelled)
3578 leavingVNode.el._leaveCb();
3579 }
3580 callHook(hook, [el]);
3581 },
3582 enter(el) {
3583 let hook = onEnter;
3584 let afterHook = onAfterEnter;
3585 let cancelHook = onEnterCancelled;
3586 if (!state.isMounted) {
3587 if (appear) {
3588 hook = onAppear || onEnter;
3589 afterHook = onAfterAppear || onAfterEnter;
3590 cancelHook = onAppearCancelled || onEnterCancelled;
3591 }
3592 else {
3593 return;
3594 }
3595 }
3596 let called = false;
3597 const done = (el._enterCb = (cancelled) => {
3598 if (called)
3599 return;
3600 called = true;
3601 if (cancelled) {
3602 callHook(cancelHook, [el]);
3603 }
3604 else {
3605 callHook(afterHook, [el]);
3606 }
3607 if (hooks.delayedLeave) {
3608 hooks.delayedLeave();
3609 }
3610 el._enterCb = undefined;
3611 });
3612 if (hook) {
3613 hook(el, done);
3614 if (hook.length <= 1) {
3615 done();
3616 }
3617 }
3618 else {
3619 done();
3620 }
3621 },
3622 leave(el, remove) {
3623 const key = String(vnode.key);
3624 if (el._enterCb) {
3625 el._enterCb(true /* cancelled */);
3626 }
3627 if (state.isUnmounting) {
3628 return remove();
3629 }
3630 callHook(onBeforeLeave, [el]);
3631 let called = false;
3632 const done = (el._leaveCb = (cancelled) => {
3633 if (called)
3634 return;
3635 called = true;
3636 remove();
3637 if (cancelled) {
3638 callHook(onLeaveCancelled, [el]);
3639 }
3640 else {
3641 callHook(onAfterLeave, [el]);
3642 }
3643 el._leaveCb = undefined;
3644 if (leavingVNodesCache[key] === vnode) {
3645 delete leavingVNodesCache[key];
3646 }
3647 });
3648 leavingVNodesCache[key] = vnode;
3649 if (onLeave) {
3650 onLeave(el, done);
3651 if (onLeave.length <= 1) {
3652 done();
3653 }
3654 }
3655 else {
3656 done();
3657 }
3658 },
3659 clone(vnode) {
3660 return resolveTransitionHooks(vnode, props, state, instance);
3661 }
3662 };
3663 return hooks;
3664}
3665// the placeholder really only handles one special case: KeepAlive
3666// in the case of a KeepAlive in a leave phase we need to return a KeepAlive
3667// placeholder with empty content to avoid the KeepAlive instance from being
3668// unmounted.
3669function emptyPlaceholder(vnode) {
3670 if (isKeepAlive(vnode)) {
3671 vnode = cloneVNode(vnode);
3672 vnode.children = null;
3673 return vnode;
3674 }
3675}
3676function getKeepAliveChild(vnode) {
3677 return isKeepAlive(vnode)
3678 ? vnode.children
3679 ? vnode.children[0]
3680 : undefined
3681 : vnode;
3682}
3683function setTransitionHooks(vnode, hooks) {
3684 if (vnode.shapeFlag & 6 /* COMPONENT */ && vnode.component) {
3685 setTransitionHooks(vnode.component.subTree, hooks);
3686 }
3687 else if (vnode.shapeFlag & 128 /* SUSPENSE */) {
3688 vnode.ssContent.transition = hooks.clone(vnode.ssContent);
3689 vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
3690 }
3691 else {
3692 vnode.transition = hooks;
3693 }
3694}
3695function getTransitionRawChildren(children, keepComment = false) {
3696 let ret = [];
3697 let keyedFragmentCount = 0;
3698 for (let i = 0; i < children.length; i++) {
3699 const child = children[i];
3700 // handle fragment children case, e.g. v-for
3701 if (child.type === Fragment) {
3702 if (child.patchFlag & 128 /* KEYED_FRAGMENT */)
3703 keyedFragmentCount++;
3704 ret = ret.concat(getTransitionRawChildren(child.children, keepComment));
3705 }
3706 // comment placeholders should be skipped, e.g. v-if
3707 else if (keepComment || child.type !== Comment) {
3708 ret.push(child);
3709 }
3710 }
3711 // #1126 if a transition children list contains multiple sub fragments, these
3712 // fragments will be merged into a flat children array. Since each v-for
3713 // fragment may contain different static bindings inside, we need to de-op
3714 // these children to force full diffs to ensure correct behavior.
3715 if (keyedFragmentCount > 1) {
3716 for (let i = 0; i < ret.length; i++) {
3717 ret[i].patchFlag = -2 /* BAIL */;
3718 }
3719 }
3720 return ret;
3721}
3722
3723// implementation, close to no-op
3724function defineComponent(options) {
3725 return isFunction(options) ? { setup: options, name: options.name } : options;
3726}
3727
3728const isAsyncWrapper = (i) => !!i.type.__asyncLoader;
3729function defineAsyncComponent(source) {
3730 if (isFunction(source)) {
3731 source = { loader: source };
3732 }
3733 const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out
3734 suspensible = true, onError: userOnError } = source;
3735 let pendingRequest = null;
3736 let resolvedComp;
3737 let retries = 0;
3738 const retry = () => {
3739 retries++;
3740 pendingRequest = null;
3741 return load();
3742 };
3743 const load = () => {
3744 let thisRequest;
3745 return (pendingRequest ||
3746 (thisRequest = pendingRequest =
3747 loader()
3748 .catch(err => {
3749 err = err instanceof Error ? err : new Error(String(err));
3750 if (userOnError) {
3751 return new Promise((resolve, reject) => {
3752 const userRetry = () => resolve(retry());
3753 const userFail = () => reject(err);
3754 userOnError(err, userRetry, userFail, retries + 1);
3755 });
3756 }
3757 else {
3758 throw err;
3759 }
3760 })
3761 .then((comp) => {
3762 if (thisRequest !== pendingRequest && pendingRequest) {
3763 return pendingRequest;
3764 }
3765 if (!comp) {
3766 warn$1(`Async component loader resolved to undefined. ` +
3767 `If you are using retry(), make sure to return its return value.`);
3768 }
3769 // interop module default
3770 if (comp &&
3771 (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
3772 comp = comp.default;
3773 }
3774 if (comp && !isObject(comp) && !isFunction(comp)) {
3775 throw new Error(`Invalid async component load result: ${comp}`);
3776 }
3777 resolvedComp = comp;
3778 return comp;
3779 })));
3780 };
3781 return defineComponent({
3782 name: 'AsyncComponentWrapper',
3783 __asyncLoader: load,
3784 get __asyncResolved() {
3785 return resolvedComp;
3786 },
3787 setup() {
3788 const instance = currentInstance;
3789 // already resolved
3790 if (resolvedComp) {
3791 return () => createInnerComp(resolvedComp, instance);
3792 }
3793 const onError = (err) => {
3794 pendingRequest = null;
3795 handleError(err, instance, 13 /* ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
3796 };
3797 // suspense-controlled or SSR.
3798 if ((suspensible && instance.suspense) ||
3799 (false )) {
3800 return load()
3801 .then(comp => {
3802 return () => createInnerComp(comp, instance);
3803 })
3804 .catch(err => {
3805 onError(err);
3806 return () => errorComponent
3807 ? createVNode(errorComponent, {
3808 error: err
3809 })
3810 : null;
3811 });
3812 }
3813 const loaded = ref(false);
3814 const error = ref();
3815 const delayed = ref(!!delay);
3816 if (delay) {
3817 setTimeout(() => {
3818 delayed.value = false;
3819 }, delay);
3820 }
3821 if (timeout != null) {
3822 setTimeout(() => {
3823 if (!loaded.value && !error.value) {
3824 const err = new Error(`Async component timed out after ${timeout}ms.`);
3825 onError(err);
3826 error.value = err;
3827 }
3828 }, timeout);
3829 }
3830 load()
3831 .then(() => {
3832 loaded.value = true;
3833 if (instance.parent && isKeepAlive(instance.parent.vnode)) {
3834 // parent is keep-alive, force update so the loaded component's
3835 // name is taken into account
3836 queueJob(instance.parent.update);
3837 }
3838 })
3839 .catch(err => {
3840 onError(err);
3841 error.value = err;
3842 });
3843 return () => {
3844 if (loaded.value && resolvedComp) {
3845 return createInnerComp(resolvedComp, instance);
3846 }
3847 else if (error.value && errorComponent) {
3848 return createVNode(errorComponent, {
3849 error: error.value
3850 });
3851 }
3852 else if (loadingComponent && !delayed.value) {
3853 return createVNode(loadingComponent);
3854 }
3855 };
3856 }
3857 });
3858}
3859function createInnerComp(comp, { vnode: { ref, props, children } }) {
3860 const vnode = createVNode(comp, props, children);
3861 // ensure inner component inherits the async wrapper's ref owner
3862 vnode.ref = ref;
3863 return vnode;
3864}
3865
3866const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
3867const KeepAliveImpl = {
3868 name: `KeepAlive`,
3869 // Marker for special handling inside the renderer. We are not using a ===
3870 // check directly on KeepAlive in the renderer, because importing it directly
3871 // would prevent it from being tree-shaken.
3872 __isKeepAlive: true,
3873 props: {
3874 include: [String, RegExp, Array],
3875 exclude: [String, RegExp, Array],
3876 max: [String, Number]
3877 },
3878 setup(props, { slots }) {
3879 const instance = getCurrentInstance();
3880 // KeepAlive communicates with the instantiated renderer via the
3881 // ctx where the renderer passes in its internals,
3882 // and the KeepAlive instance exposes activate/deactivate implementations.
3883 // The whole point of this is to avoid importing KeepAlive directly in the
3884 // renderer to facilitate tree-shaking.
3885 const sharedContext = instance.ctx;
3886 // if the internal renderer is not registered, it indicates that this is server-side rendering,
3887 // for KeepAlive, we just need to render its children
3888 if (!sharedContext.renderer) {
3889 return slots.default;
3890 }
3891 const cache = new Map();
3892 const keys = new Set();
3893 let current = null;
3894 {
3895 instance.__v_cache = cache;
3896 }
3897 const parentSuspense = instance.suspense;
3898 const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
3899 const storageContainer = createElement('div');
3900 sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
3901 const instance = vnode.component;
3902 move(vnode, container, anchor, 0 /* ENTER */, parentSuspense);
3903 // in case props have changed
3904 patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, vnode.slotScopeIds, optimized);
3905 queuePostRenderEffect(() => {
3906 instance.isDeactivated = false;
3907 if (instance.a) {
3908 invokeArrayFns(instance.a);
3909 }
3910 const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
3911 if (vnodeHook) {
3912 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3913 }
3914 }, parentSuspense);
3915 {
3916 // Update components tree
3917 devtoolsComponentAdded(instance);
3918 }
3919 };
3920 sharedContext.deactivate = (vnode) => {
3921 const instance = vnode.component;
3922 move(vnode, storageContainer, null, 1 /* LEAVE */, parentSuspense);
3923 queuePostRenderEffect(() => {
3924 if (instance.da) {
3925 invokeArrayFns(instance.da);
3926 }
3927 const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
3928 if (vnodeHook) {
3929 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3930 }
3931 instance.isDeactivated = true;
3932 }, parentSuspense);
3933 {
3934 // Update components tree
3935 devtoolsComponentAdded(instance);
3936 }
3937 };
3938 function unmount(vnode) {
3939 // reset the shapeFlag so it can be properly unmounted
3940 resetShapeFlag(vnode);
3941 _unmount(vnode, instance, parentSuspense, true);
3942 }
3943 function pruneCache(filter) {
3944 cache.forEach((vnode, key) => {
3945 const name = getComponentName(vnode.type);
3946 if (name && (!filter || !filter(name))) {
3947 pruneCacheEntry(key);
3948 }
3949 });
3950 }
3951 function pruneCacheEntry(key) {
3952 const cached = cache.get(key);
3953 if (!current || cached.type !== current.type) {
3954 unmount(cached);
3955 }
3956 else if (current) {
3957 // current active instance should no longer be kept-alive.
3958 // we can't unmount it now but it might be later, so reset its flag now.
3959 resetShapeFlag(current);
3960 }
3961 cache.delete(key);
3962 keys.delete(key);
3963 }
3964 // prune cache on include/exclude prop change
3965 watch(() => [props.include, props.exclude], ([include, exclude]) => {
3966 include && pruneCache(name => matches(include, name));
3967 exclude && pruneCache(name => !matches(exclude, name));
3968 },
3969 // prune post-render after `current` has been updated
3970 { flush: 'post', deep: true });
3971 // cache sub tree after render
3972 let pendingCacheKey = null;
3973 const cacheSubtree = () => {
3974 // fix #1621, the pendingCacheKey could be 0
3975 if (pendingCacheKey != null) {
3976 cache.set(pendingCacheKey, getInnerChild(instance.subTree));
3977 }
3978 };
3979 onMounted(cacheSubtree);
3980 onUpdated(cacheSubtree);
3981 onBeforeUnmount(() => {
3982 cache.forEach(cached => {
3983 const { subTree, suspense } = instance;
3984 const vnode = getInnerChild(subTree);
3985 if (cached.type === vnode.type) {
3986 // current instance will be unmounted as part of keep-alive's unmount
3987 resetShapeFlag(vnode);
3988 // but invoke its deactivated hook here
3989 const da = vnode.component.da;
3990 da && queuePostRenderEffect(da, suspense);
3991 return;
3992 }
3993 unmount(cached);
3994 });
3995 });
3996 return () => {
3997 pendingCacheKey = null;
3998 if (!slots.default) {
3999 return null;
4000 }
4001 const children = slots.default();
4002 const rawVNode = children[0];
4003 if (children.length > 1) {
4004 {
4005 warn$1(`KeepAlive should contain exactly one component child.`);
4006 }
4007 current = null;
4008 return children;
4009 }
4010 else if (!isVNode(rawVNode) ||
4011 (!(rawVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) &&
4012 !(rawVNode.shapeFlag & 128 /* SUSPENSE */))) {
4013 current = null;
4014 return rawVNode;
4015 }
4016 let vnode = getInnerChild(rawVNode);
4017 const comp = vnode.type;
4018 // for async components, name check should be based in its loaded
4019 // inner component if available
4020 const name = getComponentName(isAsyncWrapper(vnode)
4021 ? vnode.type.__asyncResolved || {}
4022 : comp);
4023 const { include, exclude, max } = props;
4024 if ((include && (!name || !matches(include, name))) ||
4025 (exclude && name && matches(exclude, name))) {
4026 current = vnode;
4027 return rawVNode;
4028 }
4029 const key = vnode.key == null ? comp : vnode.key;
4030 const cachedVNode = cache.get(key);
4031 // clone vnode if it's reused because we are going to mutate it
4032 if (vnode.el) {
4033 vnode = cloneVNode(vnode);
4034 if (rawVNode.shapeFlag & 128 /* SUSPENSE */) {
4035 rawVNode.ssContent = vnode;
4036 }
4037 }
4038 // #1513 it's possible for the returned vnode to be cloned due to attr
4039 // fallthrough or scopeId, so the vnode here may not be the final vnode
4040 // that is mounted. Instead of caching it directly, we store the pending
4041 // key and cache `instance.subTree` (the normalized vnode) in
4042 // beforeMount/beforeUpdate hooks.
4043 pendingCacheKey = key;
4044 if (cachedVNode) {
4045 // copy over mounted state
4046 vnode.el = cachedVNode.el;
4047 vnode.component = cachedVNode.component;
4048 if (vnode.transition) {
4049 // recursively update transition hooks on subTree
4050 setTransitionHooks(vnode, vnode.transition);
4051 }
4052 // avoid vnode being mounted as fresh
4053 vnode.shapeFlag |= 512 /* COMPONENT_KEPT_ALIVE */;
4054 // make this key the freshest
4055 keys.delete(key);
4056 keys.add(key);
4057 }
4058 else {
4059 keys.add(key);
4060 // prune oldest entry
4061 if (max && keys.size > parseInt(max, 10)) {
4062 pruneCacheEntry(keys.values().next().value);
4063 }
4064 }
4065 // avoid vnode being unmounted
4066 vnode.shapeFlag |= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
4067 current = vnode;
4068 return rawVNode;
4069 };
4070 }
4071};
4072// export the public type for h/tsx inference
4073// also to avoid inline import() in generated d.ts files
4074const KeepAlive = KeepAliveImpl;
4075function matches(pattern, name) {
4076 if (isArray(pattern)) {
4077 return pattern.some((p) => matches(p, name));
4078 }
4079 else if (isString(pattern)) {
4080 return pattern.split(',').includes(name);
4081 }
4082 else if (pattern.test) {
4083 return pattern.test(name);
4084 }
4085 /* istanbul ignore next */
4086 return false;
4087}
4088function onActivated(hook, target) {
4089 registerKeepAliveHook(hook, "a" /* ACTIVATED */, target);
4090}
4091function onDeactivated(hook, target) {
4092 registerKeepAliveHook(hook, "da" /* DEACTIVATED */, target);
4093}
4094function registerKeepAliveHook(hook, type, target = currentInstance) {
4095 // cache the deactivate branch check wrapper for injected hooks so the same
4096 // hook can be properly deduped by the scheduler. "__wdc" stands for "with
4097 // deactivation check".
4098 const wrappedHook = hook.__wdc ||
4099 (hook.__wdc = () => {
4100 // only fire the hook if the target instance is NOT in a deactivated branch.
4101 let current = target;
4102 while (current) {
4103 if (current.isDeactivated) {
4104 return;
4105 }
4106 current = current.parent;
4107 }
4108 return hook();
4109 });
4110 injectHook(type, wrappedHook, target);
4111 // In addition to registering it on the target instance, we walk up the parent
4112 // chain and register it on all ancestor instances that are keep-alive roots.
4113 // This avoids the need to walk the entire component tree when invoking these
4114 // hooks, and more importantly, avoids the need to track child components in
4115 // arrays.
4116 if (target) {
4117 let current = target.parent;
4118 while (current && current.parent) {
4119 if (isKeepAlive(current.parent.vnode)) {
4120 injectToKeepAliveRoot(wrappedHook, type, target, current);
4121 }
4122 current = current.parent;
4123 }
4124 }
4125}
4126function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
4127 // injectHook wraps the original for error handling, so make sure to remove
4128 // the wrapped version.
4129 const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
4130 onUnmounted(() => {
4131 remove(keepAliveRoot[type], injected);
4132 }, target);
4133}
4134function resetShapeFlag(vnode) {
4135 let shapeFlag = vnode.shapeFlag;
4136 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
4137 shapeFlag -= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
4138 }
4139 if (shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
4140 shapeFlag -= 512 /* COMPONENT_KEPT_ALIVE */;
4141 }
4142 vnode.shapeFlag = shapeFlag;
4143}
4144function getInnerChild(vnode) {
4145 return vnode.shapeFlag & 128 /* SUSPENSE */ ? vnode.ssContent : vnode;
4146}
4147
4148function injectHook(type, hook, target = currentInstance, prepend = false) {
4149 if (target) {
4150 const hooks = target[type] || (target[type] = []);
4151 // cache the error handling wrapper for injected hooks so the same hook
4152 // can be properly deduped by the scheduler. "__weh" stands for "with error
4153 // handling".
4154 const wrappedHook = hook.__weh ||
4155 (hook.__weh = (...args) => {
4156 if (target.isUnmounted) {
4157 return;
4158 }
4159 // disable tracking inside all lifecycle hooks
4160 // since they can potentially be called inside effects.
4161 pauseTracking();
4162 // Set currentInstance during hook invocation.
4163 // This assumes the hook does not synchronously trigger other hooks, which
4164 // can only be false when the user does something really funky.
4165 setCurrentInstance(target);
4166 const res = callWithAsyncErrorHandling(hook, target, type, args);
4167 unsetCurrentInstance();
4168 resetTracking();
4169 return res;
4170 });
4171 if (prepend) {
4172 hooks.unshift(wrappedHook);
4173 }
4174 else {
4175 hooks.push(wrappedHook);
4176 }
4177 return wrappedHook;
4178 }
4179 else {
4180 const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
4181 warn$1(`${apiName} is called when there is no active component instance to be ` +
4182 `associated with. ` +
4183 `Lifecycle injection APIs can only be used during execution of setup().` +
4184 (` If you are using async setup(), make sure to register lifecycle ` +
4185 `hooks before the first await statement.`
4186 ));
4187 }
4188}
4189const createHook = (lifecycle) => (hook, target = currentInstance) =>
4190// post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
4191(!isInSSRComponentSetup || lifecycle === "sp" /* SERVER_PREFETCH */) &&
4192 injectHook(lifecycle, hook, target);
4193const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */);
4194const onMounted = createHook("m" /* MOUNTED */);
4195const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */);
4196const onUpdated = createHook("u" /* UPDATED */);
4197const onBeforeUnmount = createHook("bum" /* BEFORE_UNMOUNT */);
4198const onUnmounted = createHook("um" /* UNMOUNTED */);
4199const onServerPrefetch = createHook("sp" /* SERVER_PREFETCH */);
4200const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */);
4201const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */);
4202function onErrorCaptured(hook, target = currentInstance) {
4203 injectHook("ec" /* ERROR_CAPTURED */, hook, target);
4204}
4205
4206function createDuplicateChecker() {
4207 const cache = Object.create(null);
4208 return (type, key) => {
4209 if (cache[key]) {
4210 warn$1(`${type} property "${key}" is already defined in ${cache[key]}.`);
4211 }
4212 else {
4213 cache[key] = type;
4214 }
4215 };
4216}
4217let shouldCacheAccess = true;
4218function applyOptions(instance) {
4219 const options = resolveMergedOptions(instance);
4220 const publicThis = instance.proxy;
4221 const ctx = instance.ctx;
4222 // do not cache property access on public proxy during state initialization
4223 shouldCacheAccess = false;
4224 // call beforeCreate first before accessing other options since
4225 // the hook may mutate resolved options (#2791)
4226 if (options.beforeCreate) {
4227 callHook(options.beforeCreate, instance, "bc" /* BEFORE_CREATE */);
4228 }
4229 const {
4230 // state
4231 data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
4232 // lifecycle
4233 created, beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured, serverPrefetch,
4234 // public API
4235 expose, inheritAttrs,
4236 // assets
4237 components, directives, filters } = options;
4238 const checkDuplicateProperties = createDuplicateChecker() ;
4239 {
4240 const [propsOptions] = instance.propsOptions;
4241 if (propsOptions) {
4242 for (const key in propsOptions) {
4243 checkDuplicateProperties("Props" /* PROPS */, key);
4244 }
4245 }
4246 }
4247 // options initialization order (to be consistent with Vue 2):
4248 // - props (already done outside of this function)
4249 // - inject
4250 // - methods
4251 // - data (deferred since it relies on `this` access)
4252 // - computed
4253 // - watch (deferred since it relies on `this` access)
4254 if (injectOptions) {
4255 resolveInjections(injectOptions, ctx, checkDuplicateProperties, instance.appContext.config.unwrapInjectedRef);
4256 }
4257 if (methods) {
4258 for (const key in methods) {
4259 const methodHandler = methods[key];
4260 if (isFunction(methodHandler)) {
4261 // In dev mode, we use the `createRenderContext` function to define
4262 // methods to the proxy target, and those are read-only but
4263 // reconfigurable, so it needs to be redefined here
4264 {
4265 Object.defineProperty(ctx, key, {
4266 value: methodHandler.bind(publicThis),
4267 configurable: true,
4268 enumerable: true,
4269 writable: true
4270 });
4271 }
4272 {
4273 checkDuplicateProperties("Methods" /* METHODS */, key);
4274 }
4275 }
4276 else {
4277 warn$1(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
4278 `Did you reference the function correctly?`);
4279 }
4280 }
4281 }
4282 if (dataOptions) {
4283 if (!isFunction(dataOptions)) {
4284 warn$1(`The data option must be a function. ` +
4285 `Plain object usage is no longer supported.`);
4286 }
4287 const data = dataOptions.call(publicThis, publicThis);
4288 if (isPromise(data)) {
4289 warn$1(`data() returned a Promise - note data() cannot be async; If you ` +
4290 `intend to perform data fetching before component renders, use ` +
4291 `async setup() + <Suspense>.`);
4292 }
4293 if (!isObject(data)) {
4294 warn$1(`data() should return an object.`);
4295 }
4296 else {
4297 instance.data = reactive(data);
4298 {
4299 for (const key in data) {
4300 checkDuplicateProperties("Data" /* DATA */, key);
4301 // expose data on ctx during dev
4302 if (key[0] !== '$' && key[0] !== '_') {
4303 Object.defineProperty(ctx, key, {
4304 configurable: true,
4305 enumerable: true,
4306 get: () => data[key],
4307 set: NOOP
4308 });
4309 }
4310 }
4311 }
4312 }
4313 }
4314 // state initialization complete at this point - start caching access
4315 shouldCacheAccess = true;
4316 if (computedOptions) {
4317 for (const key in computedOptions) {
4318 const opt = computedOptions[key];
4319 const get = isFunction(opt)
4320 ? opt.bind(publicThis, publicThis)
4321 : isFunction(opt.get)
4322 ? opt.get.bind(publicThis, publicThis)
4323 : NOOP;
4324 if (get === NOOP) {
4325 warn$1(`Computed property "${key}" has no getter.`);
4326 }
4327 const set = !isFunction(opt) && isFunction(opt.set)
4328 ? opt.set.bind(publicThis)
4329 : () => {
4330 warn$1(`Write operation failed: computed property "${key}" is readonly.`);
4331 }
4332 ;
4333 const c = computed$1({
4334 get,
4335 set
4336 });
4337 Object.defineProperty(ctx, key, {
4338 enumerable: true,
4339 configurable: true,
4340 get: () => c.value,
4341 set: v => (c.value = v)
4342 });
4343 {
4344 checkDuplicateProperties("Computed" /* COMPUTED */, key);
4345 }
4346 }
4347 }
4348 if (watchOptions) {
4349 for (const key in watchOptions) {
4350 createWatcher(watchOptions[key], ctx, publicThis, key);
4351 }
4352 }
4353 if (provideOptions) {
4354 const provides = isFunction(provideOptions)
4355 ? provideOptions.call(publicThis)
4356 : provideOptions;
4357 Reflect.ownKeys(provides).forEach(key => {
4358 provide(key, provides[key]);
4359 });
4360 }
4361 if (created) {
4362 callHook(created, instance, "c" /* CREATED */);
4363 }
4364 function registerLifecycleHook(register, hook) {
4365 if (isArray(hook)) {
4366 hook.forEach(_hook => register(_hook.bind(publicThis)));
4367 }
4368 else if (hook) {
4369 register(hook.bind(publicThis));
4370 }
4371 }
4372 registerLifecycleHook(onBeforeMount, beforeMount);
4373 registerLifecycleHook(onMounted, mounted);
4374 registerLifecycleHook(onBeforeUpdate, beforeUpdate);
4375 registerLifecycleHook(onUpdated, updated);
4376 registerLifecycleHook(onActivated, activated);
4377 registerLifecycleHook(onDeactivated, deactivated);
4378 registerLifecycleHook(onErrorCaptured, errorCaptured);
4379 registerLifecycleHook(onRenderTracked, renderTracked);
4380 registerLifecycleHook(onRenderTriggered, renderTriggered);
4381 registerLifecycleHook(onBeforeUnmount, beforeUnmount);
4382 registerLifecycleHook(onUnmounted, unmounted);
4383 registerLifecycleHook(onServerPrefetch, serverPrefetch);
4384 if (isArray(expose)) {
4385 if (expose.length) {
4386 const exposed = instance.exposed || (instance.exposed = {});
4387 expose.forEach(key => {
4388 Object.defineProperty(exposed, key, {
4389 get: () => publicThis[key],
4390 set: val => (publicThis[key] = val)
4391 });
4392 });
4393 }
4394 else if (!instance.exposed) {
4395 instance.exposed = {};
4396 }
4397 }
4398 // options that are handled when creating the instance but also need to be
4399 // applied from mixins
4400 if (render && instance.render === NOOP) {
4401 instance.render = render;
4402 }
4403 if (inheritAttrs != null) {
4404 instance.inheritAttrs = inheritAttrs;
4405 }
4406 // asset options.
4407 if (components)
4408 instance.components = components;
4409 if (directives)
4410 instance.directives = directives;
4411}
4412function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP, unwrapRef = false) {
4413 if (isArray(injectOptions)) {
4414 injectOptions = normalizeInject(injectOptions);
4415 }
4416 for (const key in injectOptions) {
4417 const opt = injectOptions[key];
4418 let injected;
4419 if (isObject(opt)) {
4420 if ('default' in opt) {
4421 injected = inject(opt.from || key, opt.default, true /* treat default function as factory */);
4422 }
4423 else {
4424 injected = inject(opt.from || key);
4425 }
4426 }
4427 else {
4428 injected = inject(opt);
4429 }
4430 if (isRef(injected)) {
4431 // TODO remove the check in 3.3
4432 if (unwrapRef) {
4433 Object.defineProperty(ctx, key, {
4434 enumerable: true,
4435 configurable: true,
4436 get: () => injected.value,
4437 set: v => (injected.value = v)
4438 });
4439 }
4440 else {
4441 {
4442 warn$1(`injected property "${key}" is a ref and will be auto-unwrapped ` +
4443 `and no longer needs \`.value\` in the next minor release. ` +
4444 `To opt-in to the new behavior now, ` +
4445 `set \`app.config.unwrapInjectedRef = true\` (this config is ` +
4446 `temporary and will not be needed in the future.)`);
4447 }
4448 ctx[key] = injected;
4449 }
4450 }
4451 else {
4452 ctx[key] = injected;
4453 }
4454 {
4455 checkDuplicateProperties("Inject" /* INJECT */, key);
4456 }
4457 }
4458}
4459function callHook(hook, instance, type) {
4460 callWithAsyncErrorHandling(isArray(hook)
4461 ? hook.map(h => h.bind(instance.proxy))
4462 : hook.bind(instance.proxy), instance, type);
4463}
4464function createWatcher(raw, ctx, publicThis, key) {
4465 const getter = key.includes('.')
4466 ? createPathGetter(publicThis, key)
4467 : () => publicThis[key];
4468 if (isString(raw)) {
4469 const handler = ctx[raw];
4470 if (isFunction(handler)) {
4471 watch(getter, handler);
4472 }
4473 else {
4474 warn$1(`Invalid watch handler specified by key "${raw}"`, handler);
4475 }
4476 }
4477 else if (isFunction(raw)) {
4478 watch(getter, raw.bind(publicThis));
4479 }
4480 else if (isObject(raw)) {
4481 if (isArray(raw)) {
4482 raw.forEach(r => createWatcher(r, ctx, publicThis, key));
4483 }
4484 else {
4485 const handler = isFunction(raw.handler)
4486 ? raw.handler.bind(publicThis)
4487 : ctx[raw.handler];
4488 if (isFunction(handler)) {
4489 watch(getter, handler, raw);
4490 }
4491 else {
4492 warn$1(`Invalid watch handler specified by key "${raw.handler}"`, handler);
4493 }
4494 }
4495 }
4496 else {
4497 warn$1(`Invalid watch option: "${key}"`, raw);
4498 }
4499}
4500/**
4501 * Resolve merged options and cache it on the component.
4502 * This is done only once per-component since the merging does not involve
4503 * instances.
4504 */
4505function resolveMergedOptions(instance) {
4506 const base = instance.type;
4507 const { mixins, extends: extendsOptions } = base;
4508 const { mixins: globalMixins, optionsCache: cache, config: { optionMergeStrategies } } = instance.appContext;
4509 const cached = cache.get(base);
4510 let resolved;
4511 if (cached) {
4512 resolved = cached;
4513 }
4514 else if (!globalMixins.length && !mixins && !extendsOptions) {
4515 {
4516 resolved = base;
4517 }
4518 }
4519 else {
4520 resolved = {};
4521 if (globalMixins.length) {
4522 globalMixins.forEach(m => mergeOptions(resolved, m, optionMergeStrategies, true));
4523 }
4524 mergeOptions(resolved, base, optionMergeStrategies);
4525 }
4526 cache.set(base, resolved);
4527 return resolved;
4528}
4529function mergeOptions(to, from, strats, asMixin = false) {
4530 const { mixins, extends: extendsOptions } = from;
4531 if (extendsOptions) {
4532 mergeOptions(to, extendsOptions, strats, true);
4533 }
4534 if (mixins) {
4535 mixins.forEach((m) => mergeOptions(to, m, strats, true));
4536 }
4537 for (const key in from) {
4538 if (asMixin && key === 'expose') {
4539 warn$1(`"expose" option is ignored when declared in mixins or extends. ` +
4540 `It should only be declared in the base component itself.`);
4541 }
4542 else {
4543 const strat = internalOptionMergeStrats[key] || (strats && strats[key]);
4544 to[key] = strat ? strat(to[key], from[key]) : from[key];
4545 }
4546 }
4547 return to;
4548}
4549const internalOptionMergeStrats = {
4550 data: mergeDataFn,
4551 props: mergeObjectOptions,
4552 emits: mergeObjectOptions,
4553 // objects
4554 methods: mergeObjectOptions,
4555 computed: mergeObjectOptions,
4556 // lifecycle
4557 beforeCreate: mergeAsArray,
4558 created: mergeAsArray,
4559 beforeMount: mergeAsArray,
4560 mounted: mergeAsArray,
4561 beforeUpdate: mergeAsArray,
4562 updated: mergeAsArray,
4563 beforeDestroy: mergeAsArray,
4564 beforeUnmount: mergeAsArray,
4565 destroyed: mergeAsArray,
4566 unmounted: mergeAsArray,
4567 activated: mergeAsArray,
4568 deactivated: mergeAsArray,
4569 errorCaptured: mergeAsArray,
4570 serverPrefetch: mergeAsArray,
4571 // assets
4572 components: mergeObjectOptions,
4573 directives: mergeObjectOptions,
4574 // watch
4575 watch: mergeWatchOptions,
4576 // provide / inject
4577 provide: mergeDataFn,
4578 inject: mergeInject
4579};
4580function mergeDataFn(to, from) {
4581 if (!from) {
4582 return to;
4583 }
4584 if (!to) {
4585 return from;
4586 }
4587 return function mergedDataFn() {
4588 return (extend)(isFunction(to) ? to.call(this, this) : to, isFunction(from) ? from.call(this, this) : from);
4589 };
4590}
4591function mergeInject(to, from) {
4592 return mergeObjectOptions(normalizeInject(to), normalizeInject(from));
4593}
4594function normalizeInject(raw) {
4595 if (isArray(raw)) {
4596 const res = {};
4597 for (let i = 0; i < raw.length; i++) {
4598 res[raw[i]] = raw[i];
4599 }
4600 return res;
4601 }
4602 return raw;
4603}
4604function mergeAsArray(to, from) {
4605 return to ? [...new Set([].concat(to, from))] : from;
4606}
4607function mergeObjectOptions(to, from) {
4608 return to ? extend(extend(Object.create(null), to), from) : from;
4609}
4610function mergeWatchOptions(to, from) {
4611 if (!to)
4612 return from;
4613 if (!from)
4614 return to;
4615 const merged = extend(Object.create(null), to);
4616 for (const key in from) {
4617 merged[key] = mergeAsArray(to[key], from[key]);
4618 }
4619 return merged;
4620}
4621
4622function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
4623isSSR = false) {
4624 const props = {};
4625 const attrs = {};
4626 def(attrs, InternalObjectKey, 1);
4627 instance.propsDefaults = Object.create(null);
4628 setFullProps(instance, rawProps, props, attrs);
4629 // ensure all declared prop keys are present
4630 for (const key in instance.propsOptions[0]) {
4631 if (!(key in props)) {
4632 props[key] = undefined;
4633 }
4634 }
4635 // validation
4636 {
4637 validateProps(rawProps || {}, props, instance);
4638 }
4639 if (isStateful) {
4640 // stateful
4641 instance.props = isSSR ? props : shallowReactive(props);
4642 }
4643 else {
4644 if (!instance.type.props) {
4645 // functional w/ optional props, props === attrs
4646 instance.props = attrs;
4647 }
4648 else {
4649 // functional w/ declared props
4650 instance.props = props;
4651 }
4652 }
4653 instance.attrs = attrs;
4654}
4655function updateProps(instance, rawProps, rawPrevProps, optimized) {
4656 const { props, attrs, vnode: { patchFlag } } = instance;
4657 const rawCurrentProps = toRaw(props);
4658 const [options] = instance.propsOptions;
4659 let hasAttrsChanged = false;
4660 if (
4661 // always force full diff in dev
4662 // - #1942 if hmr is enabled with sfc component
4663 // - vite#872 non-sfc component used by sfc component
4664 !((instance.type.__hmrId ||
4665 (instance.parent && instance.parent.type.__hmrId))) &&
4666 (optimized || patchFlag > 0) &&
4667 !(patchFlag & 16 /* FULL_PROPS */)) {
4668 if (patchFlag & 8 /* PROPS */) {
4669 // Compiler-generated props & no keys change, just set the updated
4670 // the props.
4671 const propsToUpdate = instance.vnode.dynamicProps;
4672 for (let i = 0; i < propsToUpdate.length; i++) {
4673 let key = propsToUpdate[i];
4674 // PROPS flag guarantees rawProps to be non-null
4675 const value = rawProps[key];
4676 if (options) {
4677 // attr / props separation was done on init and will be consistent
4678 // in this code path, so just check if attrs have it.
4679 if (hasOwn(attrs, key)) {
4680 if (value !== attrs[key]) {
4681 attrs[key] = value;
4682 hasAttrsChanged = true;
4683 }
4684 }
4685 else {
4686 const camelizedKey = camelize(key);
4687 props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance, false /* isAbsent */);
4688 }
4689 }
4690 else {
4691 if (value !== attrs[key]) {
4692 attrs[key] = value;
4693 hasAttrsChanged = true;
4694 }
4695 }
4696 }
4697 }
4698 }
4699 else {
4700 // full props update.
4701 if (setFullProps(instance, rawProps, props, attrs)) {
4702 hasAttrsChanged = true;
4703 }
4704 // in case of dynamic props, check if we need to delete keys from
4705 // the props object
4706 let kebabKey;
4707 for (const key in rawCurrentProps) {
4708 if (!rawProps ||
4709 // for camelCase
4710 (!hasOwn(rawProps, key) &&
4711 // it's possible the original props was passed in as kebab-case
4712 // and converted to camelCase (#955)
4713 ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
4714 if (options) {
4715 if (rawPrevProps &&
4716 // for camelCase
4717 (rawPrevProps[key] !== undefined ||
4718 // for kebab-case
4719 rawPrevProps[kebabKey] !== undefined)) {
4720 props[key] = resolvePropValue(options, rawCurrentProps, key, undefined, instance, true /* isAbsent */);
4721 }
4722 }
4723 else {
4724 delete props[key];
4725 }
4726 }
4727 }
4728 // in the case of functional component w/o props declaration, props and
4729 // attrs point to the same object so it should already have been updated.
4730 if (attrs !== rawCurrentProps) {
4731 for (const key in attrs) {
4732 if (!rawProps ||
4733 (!hasOwn(rawProps, key) &&
4734 (!false ))) {
4735 delete attrs[key];
4736 hasAttrsChanged = true;
4737 }
4738 }
4739 }
4740 }
4741 // trigger updates for $attrs in case it's used in component slots
4742 if (hasAttrsChanged) {
4743 trigger(instance, "set" /* SET */, '$attrs');
4744 }
4745 {
4746 validateProps(rawProps || {}, props, instance);
4747 }
4748}
4749function setFullProps(instance, rawProps, props, attrs) {
4750 const [options, needCastKeys] = instance.propsOptions;
4751 let hasAttrsChanged = false;
4752 let rawCastValues;
4753 if (rawProps) {
4754 for (let key in rawProps) {
4755 // key, ref are reserved and never passed down
4756 if (isReservedProp(key)) {
4757 continue;
4758 }
4759 const value = rawProps[key];
4760 // prop option names are camelized during normalization, so to support
4761 // kebab -> camel conversion here we need to camelize the key.
4762 let camelKey;
4763 if (options && hasOwn(options, (camelKey = camelize(key)))) {
4764 if (!needCastKeys || !needCastKeys.includes(camelKey)) {
4765 props[camelKey] = value;
4766 }
4767 else {
4768 (rawCastValues || (rawCastValues = {}))[camelKey] = value;
4769 }
4770 }
4771 else if (!isEmitListener(instance.emitsOptions, key)) {
4772 if (!(key in attrs) || value !== attrs[key]) {
4773 attrs[key] = value;
4774 hasAttrsChanged = true;
4775 }
4776 }
4777 }
4778 }
4779 if (needCastKeys) {
4780 const rawCurrentProps = toRaw(props);
4781 const castValues = rawCastValues || EMPTY_OBJ;
4782 for (let i = 0; i < needCastKeys.length; i++) {
4783 const key = needCastKeys[i];
4784 props[key] = resolvePropValue(options, rawCurrentProps, key, castValues[key], instance, !hasOwn(castValues, key));
4785 }
4786 }
4787 return hasAttrsChanged;
4788}
4789function resolvePropValue(options, props, key, value, instance, isAbsent) {
4790 const opt = options[key];
4791 if (opt != null) {
4792 const hasDefault = hasOwn(opt, 'default');
4793 // default values
4794 if (hasDefault && value === undefined) {
4795 const defaultValue = opt.default;
4796 if (opt.type !== Function && isFunction(defaultValue)) {
4797 const { propsDefaults } = instance;
4798 if (key in propsDefaults) {
4799 value = propsDefaults[key];
4800 }
4801 else {
4802 setCurrentInstance(instance);
4803 value = propsDefaults[key] = defaultValue.call(null, props);
4804 unsetCurrentInstance();
4805 }
4806 }
4807 else {
4808 value = defaultValue;
4809 }
4810 }
4811 // boolean casting
4812 if (opt[0 /* shouldCast */]) {
4813 if (isAbsent && !hasDefault) {
4814 value = false;
4815 }
4816 else if (opt[1 /* shouldCastTrue */] &&
4817 (value === '' || value === hyphenate(key))) {
4818 value = true;
4819 }
4820 }
4821 }
4822 return value;
4823}
4824function normalizePropsOptions(comp, appContext, asMixin = false) {
4825 const cache = appContext.propsCache;
4826 const cached = cache.get(comp);
4827 if (cached) {
4828 return cached;
4829 }
4830 const raw = comp.props;
4831 const normalized = {};
4832 const needCastKeys = [];
4833 // apply mixin/extends props
4834 let hasExtends = false;
4835 if (!isFunction(comp)) {
4836 const extendProps = (raw) => {
4837 hasExtends = true;
4838 const [props, keys] = normalizePropsOptions(raw, appContext, true);
4839 extend(normalized, props);
4840 if (keys)
4841 needCastKeys.push(...keys);
4842 };
4843 if (!asMixin && appContext.mixins.length) {
4844 appContext.mixins.forEach(extendProps);
4845 }
4846 if (comp.extends) {
4847 extendProps(comp.extends);
4848 }
4849 if (comp.mixins) {
4850 comp.mixins.forEach(extendProps);
4851 }
4852 }
4853 if (!raw && !hasExtends) {
4854 cache.set(comp, EMPTY_ARR);
4855 return EMPTY_ARR;
4856 }
4857 if (isArray(raw)) {
4858 for (let i = 0; i < raw.length; i++) {
4859 if (!isString(raw[i])) {
4860 warn$1(`props must be strings when using array syntax.`, raw[i]);
4861 }
4862 const normalizedKey = camelize(raw[i]);
4863 if (validatePropName(normalizedKey)) {
4864 normalized[normalizedKey] = EMPTY_OBJ;
4865 }
4866 }
4867 }
4868 else if (raw) {
4869 if (!isObject(raw)) {
4870 warn$1(`invalid props options`, raw);
4871 }
4872 for (const key in raw) {
4873 const normalizedKey = camelize(key);
4874 if (validatePropName(normalizedKey)) {
4875 const opt = raw[key];
4876 const prop = (normalized[normalizedKey] =
4877 isArray(opt) || isFunction(opt) ? { type: opt } : opt);
4878 if (prop) {
4879 const booleanIndex = getTypeIndex(Boolean, prop.type);
4880 const stringIndex = getTypeIndex(String, prop.type);
4881 prop[0 /* shouldCast */] = booleanIndex > -1;
4882 prop[1 /* shouldCastTrue */] =
4883 stringIndex < 0 || booleanIndex < stringIndex;
4884 // if the prop needs boolean casting or default value
4885 if (booleanIndex > -1 || hasOwn(prop, 'default')) {
4886 needCastKeys.push(normalizedKey);
4887 }
4888 }
4889 }
4890 }
4891 }
4892 const res = [normalized, needCastKeys];
4893 cache.set(comp, res);
4894 return res;
4895}
4896function validatePropName(key) {
4897 if (key[0] !== '$') {
4898 return true;
4899 }
4900 else {
4901 warn$1(`Invalid prop name: "${key}" is a reserved property.`);
4902 }
4903 return false;
4904}
4905// use function string name to check type constructors
4906// so that it works across vms / iframes.
4907function getType(ctor) {
4908 const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
4909 return match ? match[1] : ctor === null ? 'null' : '';
4910}
4911function isSameType(a, b) {
4912 return getType(a) === getType(b);
4913}
4914function getTypeIndex(type, expectedTypes) {
4915 if (isArray(expectedTypes)) {
4916 return expectedTypes.findIndex(t => isSameType(t, type));
4917 }
4918 else if (isFunction(expectedTypes)) {
4919 return isSameType(expectedTypes, type) ? 0 : -1;
4920 }
4921 return -1;
4922}
4923/**
4924 * dev only
4925 */
4926function validateProps(rawProps, props, instance) {
4927 const resolvedValues = toRaw(props);
4928 const options = instance.propsOptions[0];
4929 for (const key in options) {
4930 let opt = options[key];
4931 if (opt == null)
4932 continue;
4933 validateProp(key, resolvedValues[key], opt, !hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key)));
4934 }
4935}
4936/**
4937 * dev only
4938 */
4939function validateProp(name, value, prop, isAbsent) {
4940 const { type, required, validator } = prop;
4941 // required!
4942 if (required && isAbsent) {
4943 warn$1('Missing required prop: "' + name + '"');
4944 return;
4945 }
4946 // missing but optional
4947 if (value == null && !prop.required) {
4948 return;
4949 }
4950 // type check
4951 if (type != null && type !== true) {
4952 let isValid = false;
4953 const types = isArray(type) ? type : [type];
4954 const expectedTypes = [];
4955 // value is valid as long as one of the specified types match
4956 for (let i = 0; i < types.length && !isValid; i++) {
4957 const { valid, expectedType } = assertType(value, types[i]);
4958 expectedTypes.push(expectedType || '');
4959 isValid = valid;
4960 }
4961 if (!isValid) {
4962 warn$1(getInvalidTypeMessage(name, value, expectedTypes));
4963 return;
4964 }
4965 }
4966 // custom validator
4967 if (validator && !validator(value)) {
4968 warn$1('Invalid prop: custom validator check failed for prop "' + name + '".');
4969 }
4970}
4971const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol,BigInt');
4972/**
4973 * dev only
4974 */
4975function assertType(value, type) {
4976 let valid;
4977 const expectedType = getType(type);
4978 if (isSimpleType(expectedType)) {
4979 const t = typeof value;
4980 valid = t === expectedType.toLowerCase();
4981 // for primitive wrapper objects
4982 if (!valid && t === 'object') {
4983 valid = value instanceof type;
4984 }
4985 }
4986 else if (expectedType === 'Object') {
4987 valid = isObject(value);
4988 }
4989 else if (expectedType === 'Array') {
4990 valid = isArray(value);
4991 }
4992 else if (expectedType === 'null') {
4993 valid = value === null;
4994 }
4995 else {
4996 valid = value instanceof type;
4997 }
4998 return {
4999 valid,
5000 expectedType
5001 };
5002}
5003/**
5004 * dev only
5005 */
5006function getInvalidTypeMessage(name, value, expectedTypes) {
5007 let message = `Invalid prop: type check failed for prop "${name}".` +
5008 ` Expected ${expectedTypes.map(capitalize).join(' | ')}`;
5009 const expectedType = expectedTypes[0];
5010 const receivedType = toRawType(value);
5011 const expectedValue = styleValue(value, expectedType);
5012 const receivedValue = styleValue(value, receivedType);
5013 // check if we need to specify expected value
5014 if (expectedTypes.length === 1 &&
5015 isExplicable(expectedType) &&
5016 !isBoolean(expectedType, receivedType)) {
5017 message += ` with value ${expectedValue}`;
5018 }
5019 message += `, got ${receivedType} `;
5020 // check if we need to specify received value
5021 if (isExplicable(receivedType)) {
5022 message += `with value ${receivedValue}.`;
5023 }
5024 return message;
5025}
5026/**
5027 * dev only
5028 */
5029function styleValue(value, type) {
5030 if (type === 'String') {
5031 return `"${value}"`;
5032 }
5033 else if (type === 'Number') {
5034 return `${Number(value)}`;
5035 }
5036 else {
5037 return `${value}`;
5038 }
5039}
5040/**
5041 * dev only
5042 */
5043function isExplicable(type) {
5044 const explicitTypes = ['string', 'number', 'boolean'];
5045 return explicitTypes.some(elem => type.toLowerCase() === elem);
5046}
5047/**
5048 * dev only
5049 */
5050function isBoolean(...args) {
5051 return args.some(elem => elem.toLowerCase() === 'boolean');
5052}
5053
5054const isInternalKey = (key) => key[0] === '_' || key === '$stable';
5055const normalizeSlotValue = (value) => isArray(value)
5056 ? value.map(normalizeVNode)
5057 : [normalizeVNode(value)];
5058const normalizeSlot = (key, rawSlot, ctx) => {
5059 const normalized = withCtx((...args) => {
5060 if (currentInstance) {
5061 warn$1(`Slot "${key}" invoked outside of the render function: ` +
5062 `this will not track dependencies used in the slot. ` +
5063 `Invoke the slot function inside the render function instead.`);
5064 }
5065 return normalizeSlotValue(rawSlot(...args));
5066 }, ctx);
5067 normalized._c = false;
5068 return normalized;
5069};
5070const normalizeObjectSlots = (rawSlots, slots, instance) => {
5071 const ctx = rawSlots._ctx;
5072 for (const key in rawSlots) {
5073 if (isInternalKey(key))
5074 continue;
5075 const value = rawSlots[key];
5076 if (isFunction(value)) {
5077 slots[key] = normalizeSlot(key, value, ctx);
5078 }
5079 else if (value != null) {
5080 {
5081 warn$1(`Non-function value encountered for slot "${key}". ` +
5082 `Prefer function slots for better performance.`);
5083 }
5084 const normalized = normalizeSlotValue(value);
5085 slots[key] = () => normalized;
5086 }
5087 }
5088};
5089const normalizeVNodeSlots = (instance, children) => {
5090 if (!isKeepAlive(instance.vnode) &&
5091 !(false )) {
5092 warn$1(`Non-function value encountered for default slot. ` +
5093 `Prefer function slots for better performance.`);
5094 }
5095 const normalized = normalizeSlotValue(children);
5096 instance.slots.default = () => normalized;
5097};
5098const initSlots = (instance, children) => {
5099 if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
5100 const type = children._;
5101 if (type) {
5102 // users can get the shallow readonly version of the slots object through `this.$slots`,
5103 // we should avoid the proxy object polluting the slots of the internal instance
5104 instance.slots = toRaw(children);
5105 // make compiler marker non-enumerable
5106 def(children, '_', type);
5107 }
5108 else {
5109 normalizeObjectSlots(children, (instance.slots = {}));
5110 }
5111 }
5112 else {
5113 instance.slots = {};
5114 if (children) {
5115 normalizeVNodeSlots(instance, children);
5116 }
5117 }
5118 def(instance.slots, InternalObjectKey, 1);
5119};
5120const updateSlots = (instance, children, optimized) => {
5121 const { vnode, slots } = instance;
5122 let needDeletionCheck = true;
5123 let deletionComparisonTarget = EMPTY_OBJ;
5124 if (vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
5125 const type = children._;
5126 if (type) {
5127 // compiled slots.
5128 if (isHmrUpdating) {
5129 // Parent was HMR updated so slot content may have changed.
5130 // force update slots and mark instance for hmr as well
5131 extend(slots, children);
5132 }
5133 else if (optimized && type === 1 /* STABLE */) {
5134 // compiled AND stable.
5135 // no need to update, and skip stale slots removal.
5136 needDeletionCheck = false;
5137 }
5138 else {
5139 // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
5140 // normalization.
5141 extend(slots, children);
5142 // #2893
5143 // when rendering the optimized slots by manually written render function,
5144 // we need to delete the `slots._` flag if necessary to make subsequent updates reliable,
5145 // i.e. let the `renderSlot` create the bailed Fragment
5146 if (!optimized && type === 1 /* STABLE */) {
5147 delete slots._;
5148 }
5149 }
5150 }
5151 else {
5152 needDeletionCheck = !children.$stable;
5153 normalizeObjectSlots(children, slots);
5154 }
5155 deletionComparisonTarget = children;
5156 }
5157 else if (children) {
5158 // non slot object children (direct value) passed to a component
5159 normalizeVNodeSlots(instance, children);
5160 deletionComparisonTarget = { default: 1 };
5161 }
5162 // delete stale slots
5163 if (needDeletionCheck) {
5164 for (const key in slots) {
5165 if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
5166 delete slots[key];
5167 }
5168 }
5169 }
5170};
5171
5172/**
5173Runtime helper for applying directives to a vnode. Example usage:
5174
5175const comp = resolveComponent('comp')
5176const foo = resolveDirective('foo')
5177const bar = resolveDirective('bar')
5178
5179return withDirectives(h(comp), [
5180 [foo, this.x],
5181 [bar, this.y]
5182])
5183*/
5184function validateDirectiveName(name) {
5185 if (isBuiltInDirective(name)) {
5186 warn$1('Do not use built-in directive ids as custom directive id: ' + name);
5187 }
5188}
5189/**
5190 * Adds directives to a VNode.
5191 */
5192function withDirectives(vnode, directives) {
5193 const internalInstance = currentRenderingInstance;
5194 if (internalInstance === null) {
5195 warn$1(`withDirectives can only be used inside render functions.`);
5196 return vnode;
5197 }
5198 const instance = internalInstance.proxy;
5199 const bindings = vnode.dirs || (vnode.dirs = []);
5200 for (let i = 0; i < directives.length; i++) {
5201 let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
5202 if (isFunction(dir)) {
5203 dir = {
5204 mounted: dir,
5205 updated: dir
5206 };
5207 }
5208 if (dir.deep) {
5209 traverse(value);
5210 }
5211 bindings.push({
5212 dir,
5213 instance,
5214 value,
5215 oldValue: void 0,
5216 arg,
5217 modifiers
5218 });
5219 }
5220 return vnode;
5221}
5222function invokeDirectiveHook(vnode, prevVNode, instance, name) {
5223 const bindings = vnode.dirs;
5224 const oldBindings = prevVNode && prevVNode.dirs;
5225 for (let i = 0; i < bindings.length; i++) {
5226 const binding = bindings[i];
5227 if (oldBindings) {
5228 binding.oldValue = oldBindings[i].value;
5229 }
5230 let hook = binding.dir[name];
5231 if (hook) {
5232 // disable tracking inside all lifecycle hooks
5233 // since they can potentially be called inside effects.
5234 pauseTracking();
5235 callWithAsyncErrorHandling(hook, instance, 8 /* DIRECTIVE_HOOK */, [
5236 vnode.el,
5237 binding,
5238 vnode,
5239 prevVNode
5240 ]);
5241 resetTracking();
5242 }
5243 }
5244}
5245
5246function createAppContext() {
5247 return {
5248 app: null,
5249 config: {
5250 isNativeTag: NO,
5251 performance: false,
5252 globalProperties: {},
5253 optionMergeStrategies: {},
5254 errorHandler: undefined,
5255 warnHandler: undefined,
5256 compilerOptions: {}
5257 },
5258 mixins: [],
5259 components: {},
5260 directives: {},
5261 provides: Object.create(null),
5262 optionsCache: new WeakMap(),
5263 propsCache: new WeakMap(),
5264 emitsCache: new WeakMap()
5265 };
5266}
5267let uid = 0;
5268function createAppAPI(render, hydrate) {
5269 return function createApp(rootComponent, rootProps = null) {
5270 if (rootProps != null && !isObject(rootProps)) {
5271 warn$1(`root props passed to app.mount() must be an object.`);
5272 rootProps = null;
5273 }
5274 const context = createAppContext();
5275 const installedPlugins = new Set();
5276 let isMounted = false;
5277 const app = (context.app = {
5278 _uid: uid++,
5279 _component: rootComponent,
5280 _props: rootProps,
5281 _container: null,
5282 _context: context,
5283 _instance: null,
5284 version,
5285 get config() {
5286 return context.config;
5287 },
5288 set config(v) {
5289 {
5290 warn$1(`app.config cannot be replaced. Modify individual options instead.`);
5291 }
5292 },
5293 use(plugin, ...options) {
5294 if (installedPlugins.has(plugin)) {
5295 warn$1(`Plugin has already been applied to target app.`);
5296 }
5297 else if (plugin && isFunction(plugin.install)) {
5298 installedPlugins.add(plugin);
5299 plugin.install(app, ...options);
5300 }
5301 else if (isFunction(plugin)) {
5302 installedPlugins.add(plugin);
5303 plugin(app, ...options);
5304 }
5305 else {
5306 warn$1(`A plugin must either be a function or an object with an "install" ` +
5307 `function.`);
5308 }
5309 return app;
5310 },
5311 mixin(mixin) {
5312 {
5313 if (!context.mixins.includes(mixin)) {
5314 context.mixins.push(mixin);
5315 }
5316 else {
5317 warn$1('Mixin has already been applied to target app' +
5318 (mixin.name ? `: ${mixin.name}` : ''));
5319 }
5320 }
5321 return app;
5322 },
5323 component(name, component) {
5324 {
5325 validateComponentName(name, context.config);
5326 }
5327 if (!component) {
5328 return context.components[name];
5329 }
5330 if (context.components[name]) {
5331 warn$1(`Component "${name}" has already been registered in target app.`);
5332 }
5333 context.components[name] = component;
5334 return app;
5335 },
5336 directive(name, directive) {
5337 {
5338 validateDirectiveName(name);
5339 }
5340 if (!directive) {
5341 return context.directives[name];
5342 }
5343 if (context.directives[name]) {
5344 warn$1(`Directive "${name}" has already been registered in target app.`);
5345 }
5346 context.directives[name] = directive;
5347 return app;
5348 },
5349 mount(rootContainer, isHydrate, isSVG) {
5350 if (!isMounted) {
5351 const vnode = createVNode(rootComponent, rootProps);
5352 // store app context on the root VNode.
5353 // this will be set on the root instance on initial mount.
5354 vnode.appContext = context;
5355 // HMR root reload
5356 {
5357 context.reload = () => {
5358 render(cloneVNode(vnode), rootContainer, isSVG);
5359 };
5360 }
5361 if (isHydrate && hydrate) {
5362 hydrate(vnode, rootContainer);
5363 }
5364 else {
5365 render(vnode, rootContainer, isSVG);
5366 }
5367 isMounted = true;
5368 app._container = rootContainer;
5369 rootContainer.__vue_app__ = app;
5370 {
5371 app._instance = vnode.component;
5372 devtoolsInitApp(app, version);
5373 }
5374 return getExposeProxy(vnode.component) || vnode.component.proxy;
5375 }
5376 else {
5377 warn$1(`App has already been mounted.\n` +
5378 `If you want to remount the same app, move your app creation logic ` +
5379 `into a factory function and create fresh app instances for each ` +
5380 `mount - e.g. \`const createMyApp = () => createApp(App)\``);
5381 }
5382 },
5383 unmount() {
5384 if (isMounted) {
5385 render(null, app._container);
5386 {
5387 app._instance = null;
5388 devtoolsUnmountApp(app);
5389 }
5390 delete app._container.__vue_app__;
5391 }
5392 else {
5393 warn$1(`Cannot unmount an app that is not mounted.`);
5394 }
5395 },
5396 provide(key, value) {
5397 if (key in context.provides) {
5398 warn$1(`App already provides property with key "${String(key)}". ` +
5399 `It will be overwritten with the new value.`);
5400 }
5401 // TypeScript doesn't allow symbols as index type
5402 // https://github.com/Microsoft/TypeScript/issues/24587
5403 context.provides[key] = value;
5404 return app;
5405 }
5406 });
5407 return app;
5408 };
5409}
5410
5411/**
5412 * Function for handling a template ref
5413 */
5414function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) {
5415 if (isArray(rawRef)) {
5416 rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode, isUnmount));
5417 return;
5418 }
5419 if (isAsyncWrapper(vnode) && !isUnmount) {
5420 // when mounting async components, nothing needs to be done,
5421 // because the template ref is forwarded to inner component
5422 return;
5423 }
5424 const refValue = vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */
5425 ? getExposeProxy(vnode.component) || vnode.component.proxy
5426 : vnode.el;
5427 const value = isUnmount ? null : refValue;
5428 const { i: owner, r: ref } = rawRef;
5429 if (!owner) {
5430 warn$1(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
5431 `A vnode with ref must be created inside the render function.`);
5432 return;
5433 }
5434 const oldRef = oldRawRef && oldRawRef.r;
5435 const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
5436 const setupState = owner.setupState;
5437 // dynamic ref changed. unset old ref
5438 if (oldRef != null && oldRef !== ref) {
5439 if (isString(oldRef)) {
5440 refs[oldRef] = null;
5441 if (hasOwn(setupState, oldRef)) {
5442 setupState[oldRef] = null;
5443 }
5444 }
5445 else if (isRef(oldRef)) {
5446 oldRef.value = null;
5447 }
5448 }
5449 if (isFunction(ref)) {
5450 callWithErrorHandling(ref, owner, 12 /* FUNCTION_REF */, [value, refs]);
5451 }
5452 else {
5453 const _isString = isString(ref);
5454 const _isRef = isRef(ref);
5455 if (_isString || _isRef) {
5456 const doSet = () => {
5457 if (rawRef.f) {
5458 const existing = _isString ? refs[ref] : ref.value;
5459 if (isUnmount) {
5460 isArray(existing) && remove(existing, refValue);
5461 }
5462 else {
5463 if (!isArray(existing)) {
5464 if (_isString) {
5465 refs[ref] = [refValue];
5466 }
5467 else {
5468 ref.value = [refValue];
5469 if (rawRef.k)
5470 refs[rawRef.k] = ref.value;
5471 }
5472 }
5473 else if (!existing.includes(refValue)) {
5474 existing.push(refValue);
5475 }
5476 }
5477 }
5478 else if (_isString) {
5479 refs[ref] = value;
5480 if (hasOwn(setupState, ref)) {
5481 setupState[ref] = value;
5482 }
5483 }
5484 else if (isRef(ref)) {
5485 ref.value = value;
5486 if (rawRef.k)
5487 refs[rawRef.k] = value;
5488 }
5489 else {
5490 warn$1('Invalid template ref type:', ref, `(${typeof ref})`);
5491 }
5492 };
5493 if (value) {
5494 doSet.id = -1;
5495 queuePostRenderEffect(doSet, parentSuspense);
5496 }
5497 else {
5498 doSet();
5499 }
5500 }
5501 else {
5502 warn$1('Invalid template ref type:', ref, `(${typeof ref})`);
5503 }
5504 }
5505}
5506
5507let hasMismatch = false;
5508const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
5509const isComment = (node) => node.nodeType === 8 /* COMMENT */;
5510// Note: hydration is DOM-specific
5511// But we have to place it in core due to tight coupling with core - splitting
5512// it out creates a ton of unnecessary complexity.
5513// Hydration also depends on some renderer internal logic which needs to be
5514// passed in via arguments.
5515function createHydrationFunctions(rendererInternals) {
5516 const { mt: mountComponent, p: patch, o: { patchProp, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
5517 const hydrate = (vnode, container) => {
5518 if (!container.hasChildNodes()) {
5519 warn$1(`Attempting to hydrate existing markup but container is empty. ` +
5520 `Performing full mount instead.`);
5521 patch(null, vnode, container);
5522 flushPostFlushCbs();
5523 return;
5524 }
5525 hasMismatch = false;
5526 hydrateNode(container.firstChild, vnode, null, null, null);
5527 flushPostFlushCbs();
5528 if (hasMismatch && !false) {
5529 // this error should show up in production
5530 console.error(`Hydration completed but contains mismatches.`);
5531 }
5532 };
5533 const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => {
5534 const isFragmentStart = isComment(node) && node.data === '[';
5535 const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragmentStart);
5536 const { type, ref, shapeFlag } = vnode;
5537 const domType = node.nodeType;
5538 vnode.el = node;
5539 let nextNode = null;
5540 switch (type) {
5541 case Text:
5542 if (domType !== 3 /* TEXT */) {
5543 nextNode = onMismatch();
5544 }
5545 else {
5546 if (node.data !== vnode.children) {
5547 hasMismatch = true;
5548 warn$1(`Hydration text mismatch:` +
5549 `\n- Client: ${JSON.stringify(node.data)}` +
5550 `\n- Server: ${JSON.stringify(vnode.children)}`);
5551 node.data = vnode.children;
5552 }
5553 nextNode = nextSibling(node);
5554 }
5555 break;
5556 case Comment:
5557 if (domType !== 8 /* COMMENT */ || isFragmentStart) {
5558 nextNode = onMismatch();
5559 }
5560 else {
5561 nextNode = nextSibling(node);
5562 }
5563 break;
5564 case Static:
5565 if (domType !== 1 /* ELEMENT */) {
5566 nextNode = onMismatch();
5567 }
5568 else {
5569 // determine anchor, adopt content
5570 nextNode = node;
5571 // if the static vnode has its content stripped during build,
5572 // adopt it from the server-rendered HTML.
5573 const needToAdoptContent = !vnode.children.length;
5574 for (let i = 0; i < vnode.staticCount; i++) {
5575 if (needToAdoptContent)
5576 vnode.children += nextNode.outerHTML;
5577 if (i === vnode.staticCount - 1) {
5578 vnode.anchor = nextNode;
5579 }
5580 nextNode = nextSibling(nextNode);
5581 }
5582 return nextNode;
5583 }
5584 break;
5585 case Fragment:
5586 if (!isFragmentStart) {
5587 nextNode = onMismatch();
5588 }
5589 else {
5590 nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5591 }
5592 break;
5593 default:
5594 if (shapeFlag & 1 /* ELEMENT */) {
5595 if (domType !== 1 /* ELEMENT */ ||
5596 vnode.type.toLowerCase() !==
5597 node.tagName.toLowerCase()) {
5598 nextNode = onMismatch();
5599 }
5600 else {
5601 nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5602 }
5603 }
5604 else if (shapeFlag & 6 /* COMPONENT */) {
5605 // when setting up the render effect, if the initial vnode already
5606 // has .el set, the component will perform hydration instead of mount
5607 // on its sub-tree.
5608 vnode.slotScopeIds = slotScopeIds;
5609 const container = parentNode(node);
5610 mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
5611 // component may be async, so in the case of fragments we cannot rely
5612 // on component's rendered output to determine the end of the fragment
5613 // instead, we do a lookahead to find the end anchor node.
5614 nextNode = isFragmentStart
5615 ? locateClosingAsyncAnchor(node)
5616 : nextSibling(node);
5617 // #3787
5618 // if component is async, it may get moved / unmounted before its
5619 // inner component is loaded, so we need to give it a placeholder
5620 // vnode that matches its adopted DOM.
5621 if (isAsyncWrapper(vnode)) {
5622 let subTree;
5623 if (isFragmentStart) {
5624 subTree = createVNode(Fragment);
5625 subTree.anchor = nextNode
5626 ? nextNode.previousSibling
5627 : container.lastChild;
5628 }
5629 else {
5630 subTree =
5631 node.nodeType === 3 ? createTextVNode('') : createVNode('div');
5632 }
5633 subTree.el = node;
5634 vnode.component.subTree = subTree;
5635 }
5636 }
5637 else if (shapeFlag & 64 /* TELEPORT */) {
5638 if (domType !== 8 /* COMMENT */) {
5639 nextNode = onMismatch();
5640 }
5641 else {
5642 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, rendererInternals, hydrateChildren);
5643 }
5644 }
5645 else if (shapeFlag & 128 /* SUSPENSE */) {
5646 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), slotScopeIds, optimized, rendererInternals, hydrateNode);
5647 }
5648 else {
5649 warn$1('Invalid HostVNode type:', type, `(${typeof type})`);
5650 }
5651 }
5652 if (ref != null) {
5653 setRef(ref, null, parentSuspense, vnode);
5654 }
5655 return nextNode;
5656 };
5657 const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5658 optimized = optimized || !!vnode.dynamicChildren;
5659 const { type, props, patchFlag, shapeFlag, dirs } = vnode;
5660 // #4006 for form elements with non-string v-model value bindings
5661 // e.g. <option :value="obj">, <input type="checkbox" :true-value="1">
5662 const forcePatchValue = (type === 'input' && dirs) || type === 'option';
5663 // skip props & children if this is hoisted static nodes
5664 // #5405 in dev, always hydrate children for HMR
5665 {
5666 if (dirs) {
5667 invokeDirectiveHook(vnode, null, parentComponent, 'created');
5668 }
5669 // props
5670 if (props) {
5671 if (forcePatchValue ||
5672 !optimized ||
5673 patchFlag & (16 /* FULL_PROPS */ | 32 /* HYDRATE_EVENTS */)) {
5674 for (const key in props) {
5675 if ((forcePatchValue && key.endsWith('value')) ||
5676 (isOn(key) && !isReservedProp(key))) {
5677 patchProp(el, key, null, props[key], false, undefined, parentComponent);
5678 }
5679 }
5680 }
5681 else if (props.onClick) {
5682 // Fast path for click listeners (which is most often) to avoid
5683 // iterating through props.
5684 patchProp(el, 'onClick', null, props.onClick, false, undefined, parentComponent);
5685 }
5686 }
5687 // vnode / directive hooks
5688 let vnodeHooks;
5689 if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
5690 invokeVNodeHook(vnodeHooks, parentComponent, vnode);
5691 }
5692 if (dirs) {
5693 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
5694 }
5695 if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
5696 queueEffectWithSuspense(() => {
5697 vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
5698 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
5699 }, parentSuspense);
5700 }
5701 // children
5702 if (shapeFlag & 16 /* ARRAY_CHILDREN */ &&
5703 // skip if element has innerHTML / textContent
5704 !(props && (props.innerHTML || props.textContent))) {
5705 let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, slotScopeIds, optimized);
5706 let hasWarned = false;
5707 while (next) {
5708 hasMismatch = true;
5709 if (!hasWarned) {
5710 warn$1(`Hydration children mismatch in <${vnode.type}>: ` +
5711 `server rendered element contains more child nodes than client vdom.`);
5712 hasWarned = true;
5713 }
5714 // The SSRed DOM contains more nodes than it should. Remove them.
5715 const cur = next;
5716 next = next.nextSibling;
5717 remove(cur);
5718 }
5719 }
5720 else if (shapeFlag & 8 /* TEXT_CHILDREN */) {
5721 if (el.textContent !== vnode.children) {
5722 hasMismatch = true;
5723 warn$1(`Hydration text content mismatch in <${vnode.type}>:\n` +
5724 `- Client: ${el.textContent}\n` +
5725 `- Server: ${vnode.children}`);
5726 el.textContent = vnode.children;
5727 }
5728 }
5729 }
5730 return el.nextSibling;
5731 };
5732 const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5733 optimized = optimized || !!parentVNode.dynamicChildren;
5734 const children = parentVNode.children;
5735 const l = children.length;
5736 let hasWarned = false;
5737 for (let i = 0; i < l; i++) {
5738 const vnode = optimized
5739 ? children[i]
5740 : (children[i] = normalizeVNode(children[i]));
5741 if (node) {
5742 node = hydrateNode(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5743 }
5744 else if (vnode.type === Text && !vnode.children) {
5745 continue;
5746 }
5747 else {
5748 hasMismatch = true;
5749 if (!hasWarned) {
5750 warn$1(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
5751 `server rendered element contains fewer child nodes than client vdom.`);
5752 hasWarned = true;
5753 }
5754 // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
5755 patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
5756 }
5757 }
5758 return node;
5759 };
5760 const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5761 const { slotScopeIds: fragmentSlotScopeIds } = vnode;
5762 if (fragmentSlotScopeIds) {
5763 slotScopeIds = slotScopeIds
5764 ? slotScopeIds.concat(fragmentSlotScopeIds)
5765 : fragmentSlotScopeIds;
5766 }
5767 const container = parentNode(node);
5768 const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, slotScopeIds, optimized);
5769 if (next && isComment(next) && next.data === ']') {
5770 return nextSibling((vnode.anchor = next));
5771 }
5772 else {
5773 // fragment didn't hydrate successfully, since we didn't get a end anchor
5774 // back. This should have led to node/children mismatch warnings.
5775 hasMismatch = true;
5776 // since the anchor is missing, we need to create one and insert it
5777 insert((vnode.anchor = createComment(`]`)), container, next);
5778 return next;
5779 }
5780 };
5781 const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => {
5782 hasMismatch = true;
5783 warn$1(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* TEXT */
5784 ? `(text)`
5785 : isComment(node) && node.data === '['
5786 ? `(start of fragment)`
5787 : ``);
5788 vnode.el = null;
5789 if (isFragment) {
5790 // remove excessive fragment nodes
5791 const end = locateClosingAsyncAnchor(node);
5792 while (true) {
5793 const next = nextSibling(node);
5794 if (next && next !== end) {
5795 remove(next);
5796 }
5797 else {
5798 break;
5799 }
5800 }
5801 }
5802 const next = nextSibling(node);
5803 const container = parentNode(node);
5804 remove(node);
5805 patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
5806 return next;
5807 };
5808 const locateClosingAsyncAnchor = (node) => {
5809 let match = 0;
5810 while (node) {
5811 node = nextSibling(node);
5812 if (node && isComment(node)) {
5813 if (node.data === '[')
5814 match++;
5815 if (node.data === ']') {
5816 if (match === 0) {
5817 return nextSibling(node);
5818 }
5819 else {
5820 match--;
5821 }
5822 }
5823 }
5824 }
5825 return node;
5826 };
5827 return [hydrate, hydrateNode];
5828}
5829
5830/* eslint-disable no-restricted-globals */
5831let supported;
5832let perf;
5833function startMeasure(instance, type) {
5834 if (instance.appContext.config.performance && isSupported()) {
5835 perf.mark(`vue-${type}-${instance.uid}`);
5836 }
5837 {
5838 devtoolsPerfStart(instance, type, supported ? perf.now() : Date.now());
5839 }
5840}
5841function endMeasure(instance, type) {
5842 if (instance.appContext.config.performance && isSupported()) {
5843 const startTag = `vue-${type}-${instance.uid}`;
5844 const endTag = startTag + `:end`;
5845 perf.mark(endTag);
5846 perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
5847 perf.clearMarks(startTag);
5848 perf.clearMarks(endTag);
5849 }
5850 {
5851 devtoolsPerfEnd(instance, type, supported ? perf.now() : Date.now());
5852 }
5853}
5854function isSupported() {
5855 if (supported !== undefined) {
5856 return supported;
5857 }
5858 if (typeof window !== 'undefined' && window.performance) {
5859 supported = true;
5860 perf = window.performance;
5861 }
5862 else {
5863 supported = false;
5864 }
5865 return supported;
5866}
5867
5868const queuePostRenderEffect = queueEffectWithSuspense
5869 ;
5870/**
5871 * The createRenderer function accepts two generic arguments:
5872 * HostNode and HostElement, corresponding to Node and Element types in the
5873 * host environment. For example, for runtime-dom, HostNode would be the DOM
5874 * `Node` interface and HostElement would be the DOM `Element` interface.
5875 *
5876 * Custom renderers can pass in the platform specific types like this:
5877 *
5878 * ``` js
5879 * const { render, createApp } = createRenderer<Node, Element>({
5880 * patchProp,
5881 * ...nodeOps
5882 * })
5883 * ```
5884 */
5885function createRenderer(options) {
5886 return baseCreateRenderer(options);
5887}
5888// Separate API for creating hydration-enabled renderer.
5889// Hydration logic is only used when calling this function, making it
5890// tree-shakable.
5891function createHydrationRenderer(options) {
5892 return baseCreateRenderer(options, createHydrationFunctions);
5893}
5894// implementation
5895function baseCreateRenderer(options, createHydrationFns) {
5896 const target = getGlobalThis();
5897 target.__VUE__ = true;
5898 {
5899 setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__, target);
5900 }
5901 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;
5902 // Note: functions inside this closure should use `const xxx = () => {}`
5903 // style in order to prevent being inlined by minifiers.
5904 const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, slotScopeIds = null, optimized = isHmrUpdating ? false : !!n2.dynamicChildren) => {
5905 if (n1 === n2) {
5906 return;
5907 }
5908 // patching & not same type, unmount old tree
5909 if (n1 && !isSameVNodeType(n1, n2)) {
5910 anchor = getNextHostNode(n1);
5911 unmount(n1, parentComponent, parentSuspense, true);
5912 n1 = null;
5913 }
5914 if (n2.patchFlag === -2 /* BAIL */) {
5915 optimized = false;
5916 n2.dynamicChildren = null;
5917 }
5918 const { type, ref, shapeFlag } = n2;
5919 switch (type) {
5920 case Text:
5921 processText(n1, n2, container, anchor);
5922 break;
5923 case Comment:
5924 processCommentNode(n1, n2, container, anchor);
5925 break;
5926 case Static:
5927 if (n1 == null) {
5928 mountStaticNode(n2, container, anchor, isSVG);
5929 }
5930 else {
5931 patchStaticNode(n1, n2, container, isSVG);
5932 }
5933 break;
5934 case Fragment:
5935 processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5936 break;
5937 default:
5938 if (shapeFlag & 1 /* ELEMENT */) {
5939 processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5940 }
5941 else if (shapeFlag & 6 /* COMPONENT */) {
5942 processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5943 }
5944 else if (shapeFlag & 64 /* TELEPORT */) {
5945 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
5946 }
5947 else if (shapeFlag & 128 /* SUSPENSE */) {
5948 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
5949 }
5950 else {
5951 warn$1('Invalid VNode type:', type, `(${typeof type})`);
5952 }
5953 }
5954 // set ref
5955 if (ref != null && parentComponent) {
5956 setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2);
5957 }
5958 };
5959 const processText = (n1, n2, container, anchor) => {
5960 if (n1 == null) {
5961 hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
5962 }
5963 else {
5964 const el = (n2.el = n1.el);
5965 if (n2.children !== n1.children) {
5966 hostSetText(el, n2.children);
5967 }
5968 }
5969 };
5970 const processCommentNode = (n1, n2, container, anchor) => {
5971 if (n1 == null) {
5972 hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
5973 }
5974 else {
5975 // there's no support for dynamic comments
5976 n2.el = n1.el;
5977 }
5978 };
5979 const mountStaticNode = (n2, container, anchor, isSVG) => {
5980 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG, n2.el, n2.anchor);
5981 };
5982 /**
5983 * Dev / HMR only
5984 */
5985 const patchStaticNode = (n1, n2, container, isSVG) => {
5986 // static nodes are only patched during dev for HMR
5987 if (n2.children !== n1.children) {
5988 const anchor = hostNextSibling(n1.anchor);
5989 // remove existing
5990 removeStaticNode(n1);
5991 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
5992 }
5993 else {
5994 n2.el = n1.el;
5995 n2.anchor = n1.anchor;
5996 }
5997 };
5998 const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
5999 let next;
6000 while (el && el !== anchor) {
6001 next = hostNextSibling(el);
6002 hostInsert(el, container, nextSibling);
6003 el = next;
6004 }
6005 hostInsert(anchor, container, nextSibling);
6006 };
6007 const removeStaticNode = ({ el, anchor }) => {
6008 let next;
6009 while (el && el !== anchor) {
6010 next = hostNextSibling(el);
6011 hostRemove(el);
6012 el = next;
6013 }
6014 hostRemove(anchor);
6015 };
6016 const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6017 isSVG = isSVG || n2.type === 'svg';
6018 if (n1 == null) {
6019 mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6020 }
6021 else {
6022 patchElement(n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6023 }
6024 };
6025 const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6026 let el;
6027 let vnodeHook;
6028 const { type, props, shapeFlag, transition, patchFlag, dirs } = vnode;
6029 {
6030 el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is, props);
6031 // mount children first, since some props may rely on child content
6032 // being already rendered, e.g. `<select value>`
6033 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
6034 hostSetElementText(el, vnode.children);
6035 }
6036 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6037 mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', slotScopeIds, optimized);
6038 }
6039 if (dirs) {
6040 invokeDirectiveHook(vnode, null, parentComponent, 'created');
6041 }
6042 // props
6043 if (props) {
6044 for (const key in props) {
6045 if (key !== 'value' && !isReservedProp(key)) {
6046 hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6047 }
6048 }
6049 /**
6050 * Special case for setting value on DOM elements:
6051 * - it can be order-sensitive (e.g. should be set *after* min/max, #2325, #4024)
6052 * - it needs to be forced (#1471)
6053 * #2353 proposes adding another renderer option to configure this, but
6054 * the properties affects are so finite it is worth special casing it
6055 * here to reduce the complexity. (Special casing it also should not
6056 * affect non-DOM renderers)
6057 */
6058 if ('value' in props) {
6059 hostPatchProp(el, 'value', null, props.value);
6060 }
6061 if ((vnodeHook = props.onVnodeBeforeMount)) {
6062 invokeVNodeHook(vnodeHook, parentComponent, vnode);
6063 }
6064 }
6065 // scopeId
6066 setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
6067 }
6068 {
6069 Object.defineProperty(el, '__vnode', {
6070 value: vnode,
6071 enumerable: false
6072 });
6073 Object.defineProperty(el, '__vueParentComponent', {
6074 value: parentComponent,
6075 enumerable: false
6076 });
6077 }
6078 if (dirs) {
6079 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
6080 }
6081 // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
6082 // #1689 For inside suspense + suspense resolved case, just call it
6083 const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
6084 transition &&
6085 !transition.persisted;
6086 if (needCallTransitionHooks) {
6087 transition.beforeEnter(el);
6088 }
6089 hostInsert(el, container, anchor);
6090 if ((vnodeHook = props && props.onVnodeMounted) ||
6091 needCallTransitionHooks ||
6092 dirs) {
6093 queuePostRenderEffect(() => {
6094 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
6095 needCallTransitionHooks && transition.enter(el);
6096 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
6097 }, parentSuspense);
6098 }
6099 };
6100 const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => {
6101 if (scopeId) {
6102 hostSetScopeId(el, scopeId);
6103 }
6104 if (slotScopeIds) {
6105 for (let i = 0; i < slotScopeIds.length; i++) {
6106 hostSetScopeId(el, slotScopeIds[i]);
6107 }
6108 }
6109 if (parentComponent) {
6110 let subTree = parentComponent.subTree;
6111 if (subTree.patchFlag > 0 &&
6112 subTree.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
6113 subTree =
6114 filterSingleRoot(subTree.children) || subTree;
6115 }
6116 if (vnode === subTree) {
6117 const parentVNode = parentComponent.vnode;
6118 setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent);
6119 }
6120 }
6121 };
6122 const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, start = 0) => {
6123 for (let i = start; i < children.length; i++) {
6124 const child = (children[i] = optimized
6125 ? cloneIfMounted(children[i])
6126 : normalizeVNode(children[i]));
6127 patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6128 }
6129 };
6130 const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6131 const el = (n2.el = n1.el);
6132 let { patchFlag, dynamicChildren, dirs } = n2;
6133 // #1426 take the old vnode's patch flag into account since user may clone a
6134 // compiler-generated vnode, which de-opts to FULL_PROPS
6135 patchFlag |= n1.patchFlag & 16 /* FULL_PROPS */;
6136 const oldProps = n1.props || EMPTY_OBJ;
6137 const newProps = n2.props || EMPTY_OBJ;
6138 let vnodeHook;
6139 // disable recurse in beforeUpdate hooks
6140 parentComponent && toggleRecurse(parentComponent, false);
6141 if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
6142 invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
6143 }
6144 if (dirs) {
6145 invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
6146 }
6147 parentComponent && toggleRecurse(parentComponent, true);
6148 if (isHmrUpdating) {
6149 // HMR updated, force full diff
6150 patchFlag = 0;
6151 optimized = false;
6152 dynamicChildren = null;
6153 }
6154 const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
6155 if (dynamicChildren) {
6156 patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds);
6157 if (parentComponent && parentComponent.type.__hmrId) {
6158 traverseStaticChildren(n1, n2);
6159 }
6160 }
6161 else if (!optimized) {
6162 // full diff
6163 patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds, false);
6164 }
6165 if (patchFlag > 0) {
6166 // the presence of a patchFlag means this element's render code was
6167 // generated by the compiler and can take the fast path.
6168 // in this path old node and new node are guaranteed to have the same shape
6169 // (i.e. at the exact same position in the source template)
6170 if (patchFlag & 16 /* FULL_PROPS */) {
6171 // element props contain dynamic keys, full diff needed
6172 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
6173 }
6174 else {
6175 // class
6176 // this flag is matched when the element has dynamic class bindings.
6177 if (patchFlag & 2 /* CLASS */) {
6178 if (oldProps.class !== newProps.class) {
6179 hostPatchProp(el, 'class', null, newProps.class, isSVG);
6180 }
6181 }
6182 // style
6183 // this flag is matched when the element has dynamic style bindings
6184 if (patchFlag & 4 /* STYLE */) {
6185 hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
6186 }
6187 // props
6188 // This flag is matched when the element has dynamic prop/attr bindings
6189 // other than class and style. The keys of dynamic prop/attrs are saved for
6190 // faster iteration.
6191 // Note dynamic keys like :[foo]="bar" will cause this optimization to
6192 // bail out and go through a full diff because we need to unset the old key
6193 if (patchFlag & 8 /* PROPS */) {
6194 // if the flag is present then dynamicProps must be non-null
6195 const propsToUpdate = n2.dynamicProps;
6196 for (let i = 0; i < propsToUpdate.length; i++) {
6197 const key = propsToUpdate[i];
6198 const prev = oldProps[key];
6199 const next = newProps[key];
6200 // #1471 force patch value
6201 if (next !== prev || key === 'value') {
6202 hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
6203 }
6204 }
6205 }
6206 }
6207 // text
6208 // This flag is matched when the element has only dynamic text children.
6209 if (patchFlag & 1 /* TEXT */) {
6210 if (n1.children !== n2.children) {
6211 hostSetElementText(el, n2.children);
6212 }
6213 }
6214 }
6215 else if (!optimized && dynamicChildren == null) {
6216 // unoptimized, full diff
6217 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
6218 }
6219 if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
6220 queuePostRenderEffect(() => {
6221 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
6222 dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
6223 }, parentSuspense);
6224 }
6225 };
6226 // The fast path for blocks.
6227 const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG, slotScopeIds) => {
6228 for (let i = 0; i < newChildren.length; i++) {
6229 const oldVNode = oldChildren[i];
6230 const newVNode = newChildren[i];
6231 // Determine the container (parent element) for the patch.
6232 const container =
6233 // oldVNode may be an errored async setup() component inside Suspense
6234 // which will not have a mounted element
6235 oldVNode.el &&
6236 // - In the case of a Fragment, we need to provide the actual parent
6237 // of the Fragment itself so it can move its children.
6238 (oldVNode.type === Fragment ||
6239 // - In the case of different nodes, there is going to be a replacement
6240 // which also requires the correct parent container
6241 !isSameVNodeType(oldVNode, newVNode) ||
6242 // - In the case of a component, it could contain anything.
6243 oldVNode.shapeFlag & (6 /* COMPONENT */ | 64 /* TELEPORT */))
6244 ? hostParentNode(oldVNode.el)
6245 : // In other cases, the parent container is not actually used so we
6246 // just pass the block element here to avoid a DOM parentNode call.
6247 fallbackContainer;
6248 patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, true);
6249 }
6250 };
6251 const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
6252 if (oldProps !== newProps) {
6253 for (const key in newProps) {
6254 // empty string is not valid prop
6255 if (isReservedProp(key))
6256 continue;
6257 const next = newProps[key];
6258 const prev = oldProps[key];
6259 // defer patching value
6260 if (next !== prev && key !== 'value') {
6261 hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6262 }
6263 }
6264 if (oldProps !== EMPTY_OBJ) {
6265 for (const key in oldProps) {
6266 if (!isReservedProp(key) && !(key in newProps)) {
6267 hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6268 }
6269 }
6270 }
6271 if ('value' in newProps) {
6272 hostPatchProp(el, 'value', oldProps.value, newProps.value);
6273 }
6274 }
6275 };
6276 const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6277 const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
6278 const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
6279 let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;
6280 if (isHmrUpdating) {
6281 // HMR updated, force full diff
6282 patchFlag = 0;
6283 optimized = false;
6284 dynamicChildren = null;
6285 }
6286 // check if this is a slot fragment with :slotted scope ids
6287 if (fragmentSlotScopeIds) {
6288 slotScopeIds = slotScopeIds
6289 ? slotScopeIds.concat(fragmentSlotScopeIds)
6290 : fragmentSlotScopeIds;
6291 }
6292 if (n1 == null) {
6293 hostInsert(fragmentStartAnchor, container, anchor);
6294 hostInsert(fragmentEndAnchor, container, anchor);
6295 // a fragment can only have array children
6296 // since they are either generated by the compiler, or implicitly created
6297 // from arrays.
6298 mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6299 }
6300 else {
6301 if (patchFlag > 0 &&
6302 patchFlag & 64 /* STABLE_FRAGMENT */ &&
6303 dynamicChildren &&
6304 // #2715 the previous fragment could've been a BAILed one as a result
6305 // of renderSlot() with no valid children
6306 n1.dynamicChildren) {
6307 // a stable fragment (template root or <template v-for>) doesn't need to
6308 // patch children order, but it may contain dynamicChildren.
6309 patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG, slotScopeIds);
6310 if (parentComponent && parentComponent.type.__hmrId) {
6311 traverseStaticChildren(n1, n2);
6312 }
6313 else if (
6314 // #2080 if the stable fragment has a key, it's a <template v-for> that may
6315 // get moved around. Make sure all root level vnodes inherit el.
6316 // #2134 or if it's a component root, it may also get moved around
6317 // as the component is being moved.
6318 n2.key != null ||
6319 (parentComponent && n2 === parentComponent.subTree)) {
6320 traverseStaticChildren(n1, n2, true /* shallow */);
6321 }
6322 }
6323 else {
6324 // keyed / unkeyed, or manual fragments.
6325 // for keyed & unkeyed, since they are compiler generated from v-for,
6326 // each child is guaranteed to be a block so the fragment will never
6327 // have dynamicChildren.
6328 patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6329 }
6330 }
6331 };
6332 const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6333 n2.slotScopeIds = slotScopeIds;
6334 if (n1 == null) {
6335 if (n2.shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
6336 parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
6337 }
6338 else {
6339 mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
6340 }
6341 }
6342 else {
6343 updateComponent(n1, n2, optimized);
6344 }
6345 };
6346 const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
6347 const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
6348 if (instance.type.__hmrId) {
6349 registerHMR(instance);
6350 }
6351 {
6352 pushWarningContext(initialVNode);
6353 startMeasure(instance, `mount`);
6354 }
6355 // inject renderer internals for keepAlive
6356 if (isKeepAlive(initialVNode)) {
6357 instance.ctx.renderer = internals;
6358 }
6359 // resolve props and slots for setup context
6360 {
6361 {
6362 startMeasure(instance, `init`);
6363 }
6364 setupComponent(instance);
6365 {
6366 endMeasure(instance, `init`);
6367 }
6368 }
6369 // setup() is async. This component relies on async logic to be resolved
6370 // before proceeding
6371 if (instance.asyncDep) {
6372 parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
6373 // Give it a placeholder if this is not hydration
6374 // TODO handle self-defined fallback
6375 if (!initialVNode.el) {
6376 const placeholder = (instance.subTree = createVNode(Comment));
6377 processCommentNode(null, placeholder, container, anchor);
6378 }
6379 return;
6380 }
6381 setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
6382 {
6383 popWarningContext();
6384 endMeasure(instance, `mount`);
6385 }
6386 };
6387 const updateComponent = (n1, n2, optimized) => {
6388 const instance = (n2.component = n1.component);
6389 if (shouldUpdateComponent(n1, n2, optimized)) {
6390 if (instance.asyncDep &&
6391 !instance.asyncResolved) {
6392 // async & still pending - just update props and slots
6393 // since the component's reactive effect for render isn't set-up yet
6394 {
6395 pushWarningContext(n2);
6396 }
6397 updateComponentPreRender(instance, n2, optimized);
6398 {
6399 popWarningContext();
6400 }
6401 return;
6402 }
6403 else {
6404 // normal update
6405 instance.next = n2;
6406 // in case the child component is also queued, remove it to avoid
6407 // double updating the same child component in the same flush.
6408 invalidateJob(instance.update);
6409 // instance.update is the reactive effect.
6410 instance.update();
6411 }
6412 }
6413 else {
6414 // no update needed. just copy over properties
6415 n2.component = n1.component;
6416 n2.el = n1.el;
6417 instance.vnode = n2;
6418 }
6419 };
6420 const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
6421 const componentUpdateFn = () => {
6422 if (!instance.isMounted) {
6423 let vnodeHook;
6424 const { el, props } = initialVNode;
6425 const { bm, m, parent } = instance;
6426 const isAsyncWrapperVNode = isAsyncWrapper(initialVNode);
6427 toggleRecurse(instance, false);
6428 // beforeMount hook
6429 if (bm) {
6430 invokeArrayFns(bm);
6431 }
6432 // onVnodeBeforeMount
6433 if (!isAsyncWrapperVNode &&
6434 (vnodeHook = props && props.onVnodeBeforeMount)) {
6435 invokeVNodeHook(vnodeHook, parent, initialVNode);
6436 }
6437 toggleRecurse(instance, true);
6438 if (el && hydrateNode) {
6439 // vnode has adopted host node - perform hydration instead of mount.
6440 const hydrateSubTree = () => {
6441 {
6442 startMeasure(instance, `render`);
6443 }
6444 instance.subTree = renderComponentRoot(instance);
6445 {
6446 endMeasure(instance, `render`);
6447 }
6448 {
6449 startMeasure(instance, `hydrate`);
6450 }
6451 hydrateNode(el, instance.subTree, instance, parentSuspense, null);
6452 {
6453 endMeasure(instance, `hydrate`);
6454 }
6455 };
6456 if (isAsyncWrapperVNode) {
6457 initialVNode.type.__asyncLoader().then(
6458 // note: we are moving the render call into an async callback,
6459 // which means it won't track dependencies - but it's ok because
6460 // a server-rendered async wrapper is already in resolved state
6461 // and it will never need to change.
6462 () => !instance.isUnmounted && hydrateSubTree());
6463 }
6464 else {
6465 hydrateSubTree();
6466 }
6467 }
6468 else {
6469 {
6470 startMeasure(instance, `render`);
6471 }
6472 const subTree = (instance.subTree = renderComponentRoot(instance));
6473 {
6474 endMeasure(instance, `render`);
6475 }
6476 {
6477 startMeasure(instance, `patch`);
6478 }
6479 patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
6480 {
6481 endMeasure(instance, `patch`);
6482 }
6483 initialVNode.el = subTree.el;
6484 }
6485 // mounted hook
6486 if (m) {
6487 queuePostRenderEffect(m, parentSuspense);
6488 }
6489 // onVnodeMounted
6490 if (!isAsyncWrapperVNode &&
6491 (vnodeHook = props && props.onVnodeMounted)) {
6492 const scopedInitialVNode = initialVNode;
6493 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), parentSuspense);
6494 }
6495 // activated hook for keep-alive roots.
6496 // #1742 activated hook must be accessed after first render
6497 // since the hook may be injected by a child keep-alive
6498 if (initialVNode.shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
6499 instance.a && queuePostRenderEffect(instance.a, parentSuspense);
6500 }
6501 instance.isMounted = true;
6502 {
6503 devtoolsComponentAdded(instance);
6504 }
6505 // #2458: deference mount-only object parameters to prevent memleaks
6506 initialVNode = container = anchor = null;
6507 }
6508 else {
6509 // updateComponent
6510 // This is triggered by mutation of component's own state (next: null)
6511 // OR parent calling processComponent (next: VNode)
6512 let { next, bu, u, parent, vnode } = instance;
6513 let originNext = next;
6514 let vnodeHook;
6515 {
6516 pushWarningContext(next || instance.vnode);
6517 }
6518 // Disallow component effect recursion during pre-lifecycle hooks.
6519 toggleRecurse(instance, false);
6520 if (next) {
6521 next.el = vnode.el;
6522 updateComponentPreRender(instance, next, optimized);
6523 }
6524 else {
6525 next = vnode;
6526 }
6527 // beforeUpdate hook
6528 if (bu) {
6529 invokeArrayFns(bu);
6530 }
6531 // onVnodeBeforeUpdate
6532 if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
6533 invokeVNodeHook(vnodeHook, parent, next, vnode);
6534 }
6535 toggleRecurse(instance, true);
6536 // render
6537 {
6538 startMeasure(instance, `render`);
6539 }
6540 const nextTree = renderComponentRoot(instance);
6541 {
6542 endMeasure(instance, `render`);
6543 }
6544 const prevTree = instance.subTree;
6545 instance.subTree = nextTree;
6546 {
6547 startMeasure(instance, `patch`);
6548 }
6549 patch(prevTree, nextTree,
6550 // parent may have changed if it's in a teleport
6551 hostParentNode(prevTree.el),
6552 // anchor may have changed if it's in a fragment
6553 getNextHostNode(prevTree), instance, parentSuspense, isSVG);
6554 {
6555 endMeasure(instance, `patch`);
6556 }
6557 next.el = nextTree.el;
6558 if (originNext === null) {
6559 // self-triggered update. In case of HOC, update parent component
6560 // vnode el. HOC is indicated by parent instance's subTree pointing
6561 // to child component's vnode
6562 updateHOCHostEl(instance, nextTree.el);
6563 }
6564 // updated hook
6565 if (u) {
6566 queuePostRenderEffect(u, parentSuspense);
6567 }
6568 // onVnodeUpdated
6569 if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
6570 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, next, vnode), parentSuspense);
6571 }
6572 {
6573 devtoolsComponentUpdated(instance);
6574 }
6575 {
6576 popWarningContext();
6577 }
6578 }
6579 };
6580 // create reactive effect for rendering
6581 const effect = (instance.effect = new ReactiveEffect(componentUpdateFn, () => queueJob(instance.update), instance.scope // track it in component's effect scope
6582 ));
6583 const update = (instance.update = effect.run.bind(effect));
6584 update.id = instance.uid;
6585 // allowRecurse
6586 // #1801, #2043 component render effects should allow recursive updates
6587 toggleRecurse(instance, true);
6588 {
6589 effect.onTrack = instance.rtc
6590 ? e => invokeArrayFns(instance.rtc, e)
6591 : void 0;
6592 effect.onTrigger = instance.rtg
6593 ? e => invokeArrayFns(instance.rtg, e)
6594 : void 0;
6595 // @ts-ignore (for scheduler)
6596 update.ownerInstance = instance;
6597 }
6598 update();
6599 };
6600 const updateComponentPreRender = (instance, nextVNode, optimized) => {
6601 nextVNode.component = instance;
6602 const prevProps = instance.vnode.props;
6603 instance.vnode = nextVNode;
6604 instance.next = null;
6605 updateProps(instance, nextVNode.props, prevProps, optimized);
6606 updateSlots(instance, nextVNode.children, optimized);
6607 pauseTracking();
6608 // props update may have triggered pre-flush watchers.
6609 // flush them before the render update.
6610 flushPreFlushCbs(undefined, instance.update);
6611 resetTracking();
6612 };
6613 const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized = false) => {
6614 const c1 = n1 && n1.children;
6615 const prevShapeFlag = n1 ? n1.shapeFlag : 0;
6616 const c2 = n2.children;
6617 const { patchFlag, shapeFlag } = n2;
6618 // fast path
6619 if (patchFlag > 0) {
6620 if (patchFlag & 128 /* KEYED_FRAGMENT */) {
6621 // this could be either fully-keyed or mixed (some keyed some not)
6622 // presence of patchFlag means children are guaranteed to be arrays
6623 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6624 return;
6625 }
6626 else if (patchFlag & 256 /* UNKEYED_FRAGMENT */) {
6627 // unkeyed
6628 patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6629 return;
6630 }
6631 }
6632 // children has 3 possibilities: text, array or no children.
6633 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
6634 // text children fast path
6635 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
6636 unmountChildren(c1, parentComponent, parentSuspense);
6637 }
6638 if (c2 !== c1) {
6639 hostSetElementText(container, c2);
6640 }
6641 }
6642 else {
6643 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
6644 // prev children was array
6645 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6646 // two arrays, cannot assume anything, do full diff
6647 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6648 }
6649 else {
6650 // no new children, just unmount old
6651 unmountChildren(c1, parentComponent, parentSuspense, true);
6652 }
6653 }
6654 else {
6655 // prev children was text OR null
6656 // new children is array OR null
6657 if (prevShapeFlag & 8 /* TEXT_CHILDREN */) {
6658 hostSetElementText(container, '');
6659 }
6660 // mount new if array
6661 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6662 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6663 }
6664 }
6665 }
6666 };
6667 const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6668 c1 = c1 || EMPTY_ARR;
6669 c2 = c2 || EMPTY_ARR;
6670 const oldLength = c1.length;
6671 const newLength = c2.length;
6672 const commonLength = Math.min(oldLength, newLength);
6673 let i;
6674 for (i = 0; i < commonLength; i++) {
6675 const nextChild = (c2[i] = optimized
6676 ? cloneIfMounted(c2[i])
6677 : normalizeVNode(c2[i]));
6678 patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6679 }
6680 if (oldLength > newLength) {
6681 // remove old
6682 unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
6683 }
6684 else {
6685 // mount new
6686 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, commonLength);
6687 }
6688 };
6689 // can be all-keyed or mixed
6690 const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6691 let i = 0;
6692 const l2 = c2.length;
6693 let e1 = c1.length - 1; // prev ending index
6694 let e2 = l2 - 1; // next ending index
6695 // 1. sync from start
6696 // (a b) c
6697 // (a b) d e
6698 while (i <= e1 && i <= e2) {
6699 const n1 = c1[i];
6700 const n2 = (c2[i] = optimized
6701 ? cloneIfMounted(c2[i])
6702 : normalizeVNode(c2[i]));
6703 if (isSameVNodeType(n1, n2)) {
6704 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6705 }
6706 else {
6707 break;
6708 }
6709 i++;
6710 }
6711 // 2. sync from end
6712 // a (b c)
6713 // d e (b c)
6714 while (i <= e1 && i <= e2) {
6715 const n1 = c1[e1];
6716 const n2 = (c2[e2] = optimized
6717 ? cloneIfMounted(c2[e2])
6718 : normalizeVNode(c2[e2]));
6719 if (isSameVNodeType(n1, n2)) {
6720 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6721 }
6722 else {
6723 break;
6724 }
6725 e1--;
6726 e2--;
6727 }
6728 // 3. common sequence + mount
6729 // (a b)
6730 // (a b) c
6731 // i = 2, e1 = 1, e2 = 2
6732 // (a b)
6733 // c (a b)
6734 // i = 0, e1 = -1, e2 = 0
6735 if (i > e1) {
6736 if (i <= e2) {
6737 const nextPos = e2 + 1;
6738 const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
6739 while (i <= e2) {
6740 patch(null, (c2[i] = optimized
6741 ? cloneIfMounted(c2[i])
6742 : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6743 i++;
6744 }
6745 }
6746 }
6747 // 4. common sequence + unmount
6748 // (a b) c
6749 // (a b)
6750 // i = 2, e1 = 2, e2 = 1
6751 // a (b c)
6752 // (b c)
6753 // i = 0, e1 = 0, e2 = -1
6754 else if (i > e2) {
6755 while (i <= e1) {
6756 unmount(c1[i], parentComponent, parentSuspense, true);
6757 i++;
6758 }
6759 }
6760 // 5. unknown sequence
6761 // [i ... e1 + 1]: a b [c d e] f g
6762 // [i ... e2 + 1]: a b [e d c h] f g
6763 // i = 2, e1 = 4, e2 = 5
6764 else {
6765 const s1 = i; // prev starting index
6766 const s2 = i; // next starting index
6767 // 5.1 build key:index map for newChildren
6768 const keyToNewIndexMap = new Map();
6769 for (i = s2; i <= e2; i++) {
6770 const nextChild = (c2[i] = optimized
6771 ? cloneIfMounted(c2[i])
6772 : normalizeVNode(c2[i]));
6773 if (nextChild.key != null) {
6774 if (keyToNewIndexMap.has(nextChild.key)) {
6775 warn$1(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
6776 }
6777 keyToNewIndexMap.set(nextChild.key, i);
6778 }
6779 }
6780 // 5.2 loop through old children left to be patched and try to patch
6781 // matching nodes & remove nodes that are no longer present
6782 let j;
6783 let patched = 0;
6784 const toBePatched = e2 - s2 + 1;
6785 let moved = false;
6786 // used to track whether any node has moved
6787 let maxNewIndexSoFar = 0;
6788 // works as Map<newIndex, oldIndex>
6789 // Note that oldIndex is offset by +1
6790 // and oldIndex = 0 is a special value indicating the new node has
6791 // no corresponding old node.
6792 // used for determining longest stable subsequence
6793 const newIndexToOldIndexMap = new Array(toBePatched);
6794 for (i = 0; i < toBePatched; i++)
6795 newIndexToOldIndexMap[i] = 0;
6796 for (i = s1; i <= e1; i++) {
6797 const prevChild = c1[i];
6798 if (patched >= toBePatched) {
6799 // all new children have been patched so this can only be a removal
6800 unmount(prevChild, parentComponent, parentSuspense, true);
6801 continue;
6802 }
6803 let newIndex;
6804 if (prevChild.key != null) {
6805 newIndex = keyToNewIndexMap.get(prevChild.key);
6806 }
6807 else {
6808 // key-less node, try to locate a key-less node of the same type
6809 for (j = s2; j <= e2; j++) {
6810 if (newIndexToOldIndexMap[j - s2] === 0 &&
6811 isSameVNodeType(prevChild, c2[j])) {
6812 newIndex = j;
6813 break;
6814 }
6815 }
6816 }
6817 if (newIndex === undefined) {
6818 unmount(prevChild, parentComponent, parentSuspense, true);
6819 }
6820 else {
6821 newIndexToOldIndexMap[newIndex - s2] = i + 1;
6822 if (newIndex >= maxNewIndexSoFar) {
6823 maxNewIndexSoFar = newIndex;
6824 }
6825 else {
6826 moved = true;
6827 }
6828 patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6829 patched++;
6830 }
6831 }
6832 // 5.3 move and mount
6833 // generate longest stable subsequence only when nodes have moved
6834 const increasingNewIndexSequence = moved
6835 ? getSequence(newIndexToOldIndexMap)
6836 : EMPTY_ARR;
6837 j = increasingNewIndexSequence.length - 1;
6838 // looping backwards so that we can use last patched node as anchor
6839 for (i = toBePatched - 1; i >= 0; i--) {
6840 const nextIndex = s2 + i;
6841 const nextChild = c2[nextIndex];
6842 const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
6843 if (newIndexToOldIndexMap[i] === 0) {
6844 // mount new
6845 patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6846 }
6847 else if (moved) {
6848 // move if:
6849 // There is no stable subsequence (e.g. a reverse)
6850 // OR current node is not among the stable sequence
6851 if (j < 0 || i !== increasingNewIndexSequence[j]) {
6852 move(nextChild, container, anchor, 2 /* REORDER */);
6853 }
6854 else {
6855 j--;
6856 }
6857 }
6858 }
6859 }
6860 };
6861 const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
6862 const { el, type, transition, children, shapeFlag } = vnode;
6863 if (shapeFlag & 6 /* COMPONENT */) {
6864 move(vnode.component.subTree, container, anchor, moveType);
6865 return;
6866 }
6867 if (shapeFlag & 128 /* SUSPENSE */) {
6868 vnode.suspense.move(container, anchor, moveType);
6869 return;
6870 }
6871 if (shapeFlag & 64 /* TELEPORT */) {
6872 type.move(vnode, container, anchor, internals);
6873 return;
6874 }
6875 if (type === Fragment) {
6876 hostInsert(el, container, anchor);
6877 for (let i = 0; i < children.length; i++) {
6878 move(children[i], container, anchor, moveType);
6879 }
6880 hostInsert(vnode.anchor, container, anchor);
6881 return;
6882 }
6883 if (type === Static) {
6884 moveStaticNode(vnode, container, anchor);
6885 return;
6886 }
6887 // single nodes
6888 const needTransition = moveType !== 2 /* REORDER */ &&
6889 shapeFlag & 1 /* ELEMENT */ &&
6890 transition;
6891 if (needTransition) {
6892 if (moveType === 0 /* ENTER */) {
6893 transition.beforeEnter(el);
6894 hostInsert(el, container, anchor);
6895 queuePostRenderEffect(() => transition.enter(el), parentSuspense);
6896 }
6897 else {
6898 const { leave, delayLeave, afterLeave } = transition;
6899 const remove = () => hostInsert(el, container, anchor);
6900 const performLeave = () => {
6901 leave(el, () => {
6902 remove();
6903 afterLeave && afterLeave();
6904 });
6905 };
6906 if (delayLeave) {
6907 delayLeave(el, remove, performLeave);
6908 }
6909 else {
6910 performLeave();
6911 }
6912 }
6913 }
6914 else {
6915 hostInsert(el, container, anchor);
6916 }
6917 };
6918 const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
6919 const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
6920 // unset ref
6921 if (ref != null) {
6922 setRef(ref, null, parentSuspense, vnode, true);
6923 }
6924 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
6925 parentComponent.ctx.deactivate(vnode);
6926 return;
6927 }
6928 const shouldInvokeDirs = shapeFlag & 1 /* ELEMENT */ && dirs;
6929 const shouldInvokeVnodeHook = !isAsyncWrapper(vnode);
6930 let vnodeHook;
6931 if (shouldInvokeVnodeHook &&
6932 (vnodeHook = props && props.onVnodeBeforeUnmount)) {
6933 invokeVNodeHook(vnodeHook, parentComponent, vnode);
6934 }
6935 if (shapeFlag & 6 /* COMPONENT */) {
6936 unmountComponent(vnode.component, parentSuspense, doRemove);
6937 }
6938 else {
6939 if (shapeFlag & 128 /* SUSPENSE */) {
6940 vnode.suspense.unmount(parentSuspense, doRemove);
6941 return;
6942 }
6943 if (shouldInvokeDirs) {
6944 invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
6945 }
6946 if (shapeFlag & 64 /* TELEPORT */) {
6947 vnode.type.remove(vnode, parentComponent, parentSuspense, optimized, internals, doRemove);
6948 }
6949 else if (dynamicChildren &&
6950 // #1153: fast path should not be taken for non-stable (v-for) fragments
6951 (type !== Fragment ||
6952 (patchFlag > 0 && patchFlag & 64 /* STABLE_FRAGMENT */))) {
6953 // fast path for block nodes: only need to unmount dynamic children.
6954 unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
6955 }
6956 else if ((type === Fragment &&
6957 patchFlag &
6958 (128 /* KEYED_FRAGMENT */ | 256 /* UNKEYED_FRAGMENT */)) ||
6959 (!optimized && shapeFlag & 16 /* ARRAY_CHILDREN */)) {
6960 unmountChildren(children, parentComponent, parentSuspense);
6961 }
6962 if (doRemove) {
6963 remove(vnode);
6964 }
6965 }
6966 if ((shouldInvokeVnodeHook &&
6967 (vnodeHook = props && props.onVnodeUnmounted)) ||
6968 shouldInvokeDirs) {
6969 queuePostRenderEffect(() => {
6970 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
6971 shouldInvokeDirs &&
6972 invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
6973 }, parentSuspense);
6974 }
6975 };
6976 const remove = vnode => {
6977 const { type, el, anchor, transition } = vnode;
6978 if (type === Fragment) {
6979 removeFragment(el, anchor);
6980 return;
6981 }
6982 if (type === Static) {
6983 removeStaticNode(vnode);
6984 return;
6985 }
6986 const performRemove = () => {
6987 hostRemove(el);
6988 if (transition && !transition.persisted && transition.afterLeave) {
6989 transition.afterLeave();
6990 }
6991 };
6992 if (vnode.shapeFlag & 1 /* ELEMENT */ &&
6993 transition &&
6994 !transition.persisted) {
6995 const { leave, delayLeave } = transition;
6996 const performLeave = () => leave(el, performRemove);
6997 if (delayLeave) {
6998 delayLeave(vnode.el, performRemove, performLeave);
6999 }
7000 else {
7001 performLeave();
7002 }
7003 }
7004 else {
7005 performRemove();
7006 }
7007 };
7008 const removeFragment = (cur, end) => {
7009 // For fragments, directly remove all contained DOM nodes.
7010 // (fragment child nodes cannot have transition)
7011 let next;
7012 while (cur !== end) {
7013 next = hostNextSibling(cur);
7014 hostRemove(cur);
7015 cur = next;
7016 }
7017 hostRemove(end);
7018 };
7019 const unmountComponent = (instance, parentSuspense, doRemove) => {
7020 if (instance.type.__hmrId) {
7021 unregisterHMR(instance);
7022 }
7023 const { bum, scope, update, subTree, um } = instance;
7024 // beforeUnmount hook
7025 if (bum) {
7026 invokeArrayFns(bum);
7027 }
7028 // stop effects in component scope
7029 scope.stop();
7030 // update may be null if a component is unmounted before its async
7031 // setup has resolved.
7032 if (update) {
7033 // so that scheduler will no longer invoke it
7034 update.active = false;
7035 unmount(subTree, instance, parentSuspense, doRemove);
7036 }
7037 // unmounted hook
7038 if (um) {
7039 queuePostRenderEffect(um, parentSuspense);
7040 }
7041 queuePostRenderEffect(() => {
7042 instance.isUnmounted = true;
7043 }, parentSuspense);
7044 // A component with async dep inside a pending suspense is unmounted before
7045 // its async dep resolves. This should remove the dep from the suspense, and
7046 // cause the suspense to resolve immediately if that was the last dep.
7047 if (parentSuspense &&
7048 parentSuspense.pendingBranch &&
7049 !parentSuspense.isUnmounted &&
7050 instance.asyncDep &&
7051 !instance.asyncResolved &&
7052 instance.suspenseId === parentSuspense.pendingId) {
7053 parentSuspense.deps--;
7054 if (parentSuspense.deps === 0) {
7055 parentSuspense.resolve();
7056 }
7057 }
7058 {
7059 devtoolsComponentRemoved(instance);
7060 }
7061 };
7062 const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
7063 for (let i = start; i < children.length; i++) {
7064 unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
7065 }
7066 };
7067 const getNextHostNode = vnode => {
7068 if (vnode.shapeFlag & 6 /* COMPONENT */) {
7069 return getNextHostNode(vnode.component.subTree);
7070 }
7071 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
7072 return vnode.suspense.next();
7073 }
7074 return hostNextSibling((vnode.anchor || vnode.el));
7075 };
7076 const render = (vnode, container, isSVG) => {
7077 if (vnode == null) {
7078 if (container._vnode) {
7079 unmount(container._vnode, null, null, true);
7080 }
7081 }
7082 else {
7083 patch(container._vnode || null, vnode, container, null, null, null, isSVG);
7084 }
7085 flushPostFlushCbs();
7086 container._vnode = vnode;
7087 };
7088 const internals = {
7089 p: patch,
7090 um: unmount,
7091 m: move,
7092 r: remove,
7093 mt: mountComponent,
7094 mc: mountChildren,
7095 pc: patchChildren,
7096 pbc: patchBlockChildren,
7097 n: getNextHostNode,
7098 o: options
7099 };
7100 let hydrate;
7101 let hydrateNode;
7102 if (createHydrationFns) {
7103 [hydrate, hydrateNode] = createHydrationFns(internals);
7104 }
7105 return {
7106 render,
7107 hydrate,
7108 createApp: createAppAPI(render, hydrate)
7109 };
7110}
7111function toggleRecurse({ effect, update }, allowed) {
7112 effect.allowRecurse = update.allowRecurse = allowed;
7113}
7114/**
7115 * #1156
7116 * When a component is HMR-enabled, we need to make sure that all static nodes
7117 * inside a block also inherit the DOM element from the previous tree so that
7118 * HMR updates (which are full updates) can retrieve the element for patching.
7119 *
7120 * #2080
7121 * Inside keyed `template` fragment static children, if a fragment is moved,
7122 * the children will always be moved. Therefore, in order to ensure correct move
7123 * position, el should be inherited from previous nodes.
7124 */
7125function traverseStaticChildren(n1, n2, shallow = false) {
7126 const ch1 = n1.children;
7127 const ch2 = n2.children;
7128 if (isArray(ch1) && isArray(ch2)) {
7129 for (let i = 0; i < ch1.length; i++) {
7130 // this is only called in the optimized path so array children are
7131 // guaranteed to be vnodes
7132 const c1 = ch1[i];
7133 let c2 = ch2[i];
7134 if (c2.shapeFlag & 1 /* ELEMENT */ && !c2.dynamicChildren) {
7135 if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* HYDRATE_EVENTS */) {
7136 c2 = ch2[i] = cloneIfMounted(ch2[i]);
7137 c2.el = c1.el;
7138 }
7139 if (!shallow)
7140 traverseStaticChildren(c1, c2);
7141 }
7142 // also inherit for comment nodes, but not placeholders (e.g. v-if which
7143 // would have received .el during block patch)
7144 if (c2.type === Comment && !c2.el) {
7145 c2.el = c1.el;
7146 }
7147 }
7148 }
7149}
7150// https://en.wikipedia.org/wiki/Longest_increasing_subsequence
7151function getSequence(arr) {
7152 const p = arr.slice();
7153 const result = [0];
7154 let i, j, u, v, c;
7155 const len = arr.length;
7156 for (i = 0; i < len; i++) {
7157 const arrI = arr[i];
7158 if (arrI !== 0) {
7159 j = result[result.length - 1];
7160 if (arr[j] < arrI) {
7161 p[i] = j;
7162 result.push(i);
7163 continue;
7164 }
7165 u = 0;
7166 v = result.length - 1;
7167 while (u < v) {
7168 c = (u + v) >> 1;
7169 if (arr[result[c]] < arrI) {
7170 u = c + 1;
7171 }
7172 else {
7173 v = c;
7174 }
7175 }
7176 if (arrI < arr[result[u]]) {
7177 if (u > 0) {
7178 p[i] = result[u - 1];
7179 }
7180 result[u] = i;
7181 }
7182 }
7183 }
7184 u = result.length;
7185 v = result[u - 1];
7186 while (u-- > 0) {
7187 result[u] = v;
7188 v = p[v];
7189 }
7190 return result;
7191}
7192
7193const isTeleport = (type) => type.__isTeleport;
7194const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
7195const isTargetSVG = (target) => typeof SVGElement !== 'undefined' && target instanceof SVGElement;
7196const resolveTarget = (props, select) => {
7197 const targetSelector = props && props.to;
7198 if (isString(targetSelector)) {
7199 if (!select) {
7200 warn$1(`Current renderer does not support string target for Teleports. ` +
7201 `(missing querySelector renderer option)`);
7202 return null;
7203 }
7204 else {
7205 const target = select(targetSelector);
7206 if (!target) {
7207 warn$1(`Failed to locate Teleport target with selector "${targetSelector}". ` +
7208 `Note the target element must exist before the component is mounted - ` +
7209 `i.e. the target cannot be rendered by the component itself, and ` +
7210 `ideally should be outside of the entire Vue component tree.`);
7211 }
7212 return target;
7213 }
7214 }
7215 else {
7216 if (!targetSelector && !isTeleportDisabled(props)) {
7217 warn$1(`Invalid Teleport target: ${targetSelector}`);
7218 }
7219 return targetSelector;
7220 }
7221};
7222const TeleportImpl = {
7223 __isTeleport: true,
7224 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals) {
7225 const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
7226 const disabled = isTeleportDisabled(n2.props);
7227 let { shapeFlag, children, dynamicChildren } = n2;
7228 // #3302
7229 // HMR updated, force full diff
7230 if (isHmrUpdating) {
7231 optimized = false;
7232 dynamicChildren = null;
7233 }
7234 if (n1 == null) {
7235 // insert anchors in the main view
7236 const placeholder = (n2.el = createComment('teleport start')
7237 );
7238 const mainAnchor = (n2.anchor = createComment('teleport end')
7239 );
7240 insert(placeholder, container, anchor);
7241 insert(mainAnchor, container, anchor);
7242 const target = (n2.target = resolveTarget(n2.props, querySelector));
7243 const targetAnchor = (n2.targetAnchor = createText(''));
7244 if (target) {
7245 insert(targetAnchor, target);
7246 // #2652 we could be teleporting from a non-SVG tree into an SVG tree
7247 isSVG = isSVG || isTargetSVG(target);
7248 }
7249 else if (!disabled) {
7250 warn$1('Invalid Teleport target on mount:', target, `(${typeof target})`);
7251 }
7252 const mount = (container, anchor) => {
7253 // Teleport *always* has Array children. This is enforced in both the
7254 // compiler and vnode children normalization.
7255 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7256 mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7257 }
7258 };
7259 if (disabled) {
7260 mount(container, mainAnchor);
7261 }
7262 else if (target) {
7263 mount(target, targetAnchor);
7264 }
7265 }
7266 else {
7267 // update content
7268 n2.el = n1.el;
7269 const mainAnchor = (n2.anchor = n1.anchor);
7270 const target = (n2.target = n1.target);
7271 const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
7272 const wasDisabled = isTeleportDisabled(n1.props);
7273 const currentContainer = wasDisabled ? container : target;
7274 const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
7275 isSVG = isSVG || isTargetSVG(target);
7276 if (dynamicChildren) {
7277 // fast path when the teleport happens to be a block root
7278 patchBlockChildren(n1.dynamicChildren, dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG, slotScopeIds);
7279 // even in block tree mode we need to make sure all root-level nodes
7280 // in the teleport inherit previous DOM references so that they can
7281 // be moved in future patches.
7282 traverseStaticChildren(n1, n2, true);
7283 }
7284 else if (!optimized) {
7285 patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, false);
7286 }
7287 if (disabled) {
7288 if (!wasDisabled) {
7289 // enabled -> disabled
7290 // move into main container
7291 moveTeleport(n2, container, mainAnchor, internals, 1 /* TOGGLE */);
7292 }
7293 }
7294 else {
7295 // target changed
7296 if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
7297 const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
7298 if (nextTarget) {
7299 moveTeleport(n2, nextTarget, null, internals, 0 /* TARGET_CHANGE */);
7300 }
7301 else {
7302 warn$1('Invalid Teleport target on update:', target, `(${typeof target})`);
7303 }
7304 }
7305 else if (wasDisabled) {
7306 // disabled -> enabled
7307 // move into teleport target
7308 moveTeleport(n2, target, targetAnchor, internals, 1 /* TOGGLE */);
7309 }
7310 }
7311 }
7312 },
7313 remove(vnode, parentComponent, parentSuspense, optimized, { um: unmount, o: { remove: hostRemove } }, doRemove) {
7314 const { shapeFlag, children, anchor, targetAnchor, target, props } = vnode;
7315 if (target) {
7316 hostRemove(targetAnchor);
7317 }
7318 // an unmounted teleport should always remove its children if not disabled
7319 if (doRemove || !isTeleportDisabled(props)) {
7320 hostRemove(anchor);
7321 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7322 for (let i = 0; i < children.length; i++) {
7323 const child = children[i];
7324 unmount(child, parentComponent, parentSuspense, true, !!child.dynamicChildren);
7325 }
7326 }
7327 }
7328 },
7329 move: moveTeleport,
7330 hydrate: hydrateTeleport
7331};
7332function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* REORDER */) {
7333 // move target anchor if this is a target change.
7334 if (moveType === 0 /* TARGET_CHANGE */) {
7335 insert(vnode.targetAnchor, container, parentAnchor);
7336 }
7337 const { el, anchor, shapeFlag, children, props } = vnode;
7338 const isReorder = moveType === 2 /* REORDER */;
7339 // move main view anchor if this is a re-order.
7340 if (isReorder) {
7341 insert(el, container, parentAnchor);
7342 }
7343 // if this is a re-order and teleport is enabled (content is in target)
7344 // do not move children. So the opposite is: only move children if this
7345 // is not a reorder, or the teleport is disabled
7346 if (!isReorder || isTeleportDisabled(props)) {
7347 // Teleport has either Array children or no children.
7348 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7349 for (let i = 0; i < children.length; i++) {
7350 move(children[i], container, parentAnchor, 2 /* REORDER */);
7351 }
7352 }
7353 }
7354 // move main view anchor if this is a re-order.
7355 if (isReorder) {
7356 insert(anchor, container, parentAnchor);
7357 }
7358}
7359function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
7360 const target = (vnode.target = resolveTarget(vnode.props, querySelector));
7361 if (target) {
7362 // if multiple teleports rendered to the same target element, we need to
7363 // pick up from where the last teleport finished instead of the first node
7364 const targetNode = target._lpa || target.firstChild;
7365 if (vnode.shapeFlag & 16 /* ARRAY_CHILDREN */) {
7366 if (isTeleportDisabled(vnode.props)) {
7367 vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, slotScopeIds, optimized);
7368 vnode.targetAnchor = targetNode;
7369 }
7370 else {
7371 vnode.anchor = nextSibling(node);
7372 vnode.targetAnchor = hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, slotScopeIds, optimized);
7373 }
7374 target._lpa =
7375 vnode.targetAnchor && nextSibling(vnode.targetAnchor);
7376 }
7377 }
7378 return vnode.anchor && nextSibling(vnode.anchor);
7379}
7380// Force-casted public typing for h and TSX props inference
7381const Teleport = TeleportImpl;
7382
7383const COMPONENTS = 'components';
7384const DIRECTIVES = 'directives';
7385/**
7386 * @private
7387 */
7388function resolveComponent(name, maybeSelfReference) {
7389 return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name;
7390}
7391const NULL_DYNAMIC_COMPONENT = Symbol();
7392/**
7393 * @private
7394 */
7395function resolveDynamicComponent(component) {
7396 if (isString(component)) {
7397 return resolveAsset(COMPONENTS, component, false) || component;
7398 }
7399 else {
7400 // invalid types will fallthrough to createVNode and raise warning
7401 return (component || NULL_DYNAMIC_COMPONENT);
7402 }
7403}
7404/**
7405 * @private
7406 */
7407function resolveDirective(name) {
7408 return resolveAsset(DIRECTIVES, name);
7409}
7410// implementation
7411function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {
7412 const instance = currentRenderingInstance || currentInstance;
7413 if (instance) {
7414 const Component = instance.type;
7415 // explicit self name has highest priority
7416 if (type === COMPONENTS) {
7417 const selfName = getComponentName(Component);
7418 if (selfName &&
7419 (selfName === name ||
7420 selfName === camelize(name) ||
7421 selfName === capitalize(camelize(name)))) {
7422 return Component;
7423 }
7424 }
7425 const res =
7426 // local registration
7427 // check instance[type] first which is resolved for options API
7428 resolve(instance[type] || Component[type], name) ||
7429 // global registration
7430 resolve(instance.appContext[type], name);
7431 if (!res && maybeSelfReference) {
7432 // fallback to implicit self-reference
7433 return Component;
7434 }
7435 if (warnMissing && !res) {
7436 const extra = type === COMPONENTS
7437 ? `\nIf this is a native custom element, make sure to exclude it from ` +
7438 `component resolution via compilerOptions.isCustomElement.`
7439 : ``;
7440 warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`);
7441 }
7442 return res;
7443 }
7444 else {
7445 warn$1(`resolve${capitalize(type.slice(0, -1))} ` +
7446 `can only be used in render() or setup().`);
7447 }
7448}
7449function resolve(registry, name) {
7450 return (registry &&
7451 (registry[name] ||
7452 registry[camelize(name)] ||
7453 registry[capitalize(camelize(name))]));
7454}
7455
7456const Fragment = Symbol('Fragment' );
7457const Text = Symbol('Text' );
7458const Comment = Symbol('Comment' );
7459const Static = Symbol('Static' );
7460// Since v-if and v-for are the two possible ways node structure can dynamically
7461// change, once we consider v-if branches and each v-for fragment a block, we
7462// can divide a template into nested blocks, and within each block the node
7463// structure would be stable. This allows us to skip most children diffing
7464// and only worry about the dynamic nodes (indicated by patch flags).
7465const blockStack = [];
7466let currentBlock = null;
7467/**
7468 * Open a block.
7469 * This must be called before `createBlock`. It cannot be part of `createBlock`
7470 * because the children of the block are evaluated before `createBlock` itself
7471 * is called. The generated code typically looks like this:
7472 *
7473 * ```js
7474 * function render() {
7475 * return (openBlock(),createBlock('div', null, [...]))
7476 * }
7477 * ```
7478 * disableTracking is true when creating a v-for fragment block, since a v-for
7479 * fragment always diffs its children.
7480 *
7481 * @private
7482 */
7483function openBlock(disableTracking = false) {
7484 blockStack.push((currentBlock = disableTracking ? null : []));
7485}
7486function closeBlock() {
7487 blockStack.pop();
7488 currentBlock = blockStack[blockStack.length - 1] || null;
7489}
7490// Whether we should be tracking dynamic child nodes inside a block.
7491// Only tracks when this value is > 0
7492// We are not using a simple boolean because this value may need to be
7493// incremented/decremented by nested usage of v-once (see below)
7494let isBlockTreeEnabled = 1;
7495/**
7496 * Block tracking sometimes needs to be disabled, for example during the
7497 * creation of a tree that needs to be cached by v-once. The compiler generates
7498 * code like this:
7499 *
7500 * ``` js
7501 * _cache[1] || (
7502 * setBlockTracking(-1),
7503 * _cache[1] = createVNode(...),
7504 * setBlockTracking(1),
7505 * _cache[1]
7506 * )
7507 * ```
7508 *
7509 * @private
7510 */
7511function setBlockTracking(value) {
7512 isBlockTreeEnabled += value;
7513}
7514function setupBlock(vnode) {
7515 // save current block children on the block vnode
7516 vnode.dynamicChildren =
7517 isBlockTreeEnabled > 0 ? currentBlock || EMPTY_ARR : null;
7518 // close block
7519 closeBlock();
7520 // a block is always going to be patched, so track it as a child of its
7521 // parent block
7522 if (isBlockTreeEnabled > 0 && currentBlock) {
7523 currentBlock.push(vnode);
7524 }
7525 return vnode;
7526}
7527/**
7528 * @private
7529 */
7530function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) {
7531 return setupBlock(createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, true /* isBlock */));
7532}
7533/**
7534 * Create a block root vnode. Takes the same exact arguments as `createVNode`.
7535 * A block root keeps track of dynamic nodes within the block in the
7536 * `dynamicChildren` array.
7537 *
7538 * @private
7539 */
7540function createBlock(type, props, children, patchFlag, dynamicProps) {
7541 return setupBlock(createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */));
7542}
7543function isVNode(value) {
7544 return value ? value.__v_isVNode === true : false;
7545}
7546function isSameVNodeType(n1, n2) {
7547 if (n2.shapeFlag & 6 /* COMPONENT */ &&
7548 hmrDirtyComponents.has(n2.type)) {
7549 // HMR only: if the component has been hot-updated, force a reload.
7550 return false;
7551 }
7552 return n1.type === n2.type && n1.key === n2.key;
7553}
7554let vnodeArgsTransformer;
7555/**
7556 * Internal API for registering an arguments transform for createVNode
7557 * used for creating stubs in the test-utils
7558 * It is *internal* but needs to be exposed for test-utils to pick up proper
7559 * typings
7560 */
7561function transformVNodeArgs(transformer) {
7562 vnodeArgsTransformer = transformer;
7563}
7564const createVNodeWithArgsTransform = (...args) => {
7565 return _createVNode(...(vnodeArgsTransformer
7566 ? vnodeArgsTransformer(args, currentRenderingInstance)
7567 : args));
7568};
7569const InternalObjectKey = `__vInternal`;
7570const normalizeKey = ({ key }) => key != null ? key : null;
7571const normalizeRef = ({ ref, ref_key, ref_for }) => {
7572 return (ref != null
7573 ? isString(ref) || isRef(ref) || isFunction(ref)
7574 ? { i: currentRenderingInstance, r: ref, k: ref_key, f: !!ref_for }
7575 : ref
7576 : null);
7577};
7578function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1 /* ELEMENT */, isBlockNode = false, needFullChildrenNormalization = false) {
7579 const vnode = {
7580 __v_isVNode: true,
7581 __v_skip: true,
7582 type,
7583 props,
7584 key: props && normalizeKey(props),
7585 ref: props && normalizeRef(props),
7586 scopeId: currentScopeId,
7587 slotScopeIds: null,
7588 children,
7589 component: null,
7590 suspense: null,
7591 ssContent: null,
7592 ssFallback: null,
7593 dirs: null,
7594 transition: null,
7595 el: null,
7596 anchor: null,
7597 target: null,
7598 targetAnchor: null,
7599 staticCount: 0,
7600 shapeFlag,
7601 patchFlag,
7602 dynamicProps,
7603 dynamicChildren: null,
7604 appContext: null
7605 };
7606 if (needFullChildrenNormalization) {
7607 normalizeChildren(vnode, children);
7608 // normalize suspense children
7609 if (shapeFlag & 128 /* SUSPENSE */) {
7610 type.normalize(vnode);
7611 }
7612 }
7613 else if (children) {
7614 // compiled element vnode - if children is passed, only possible types are
7615 // string or Array.
7616 vnode.shapeFlag |= isString(children)
7617 ? 8 /* TEXT_CHILDREN */
7618 : 16 /* ARRAY_CHILDREN */;
7619 }
7620 // validate key
7621 if (vnode.key !== vnode.key) {
7622 warn$1(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
7623 }
7624 // track vnode for block tree
7625 if (isBlockTreeEnabled > 0 &&
7626 // avoid a block node from tracking itself
7627 !isBlockNode &&
7628 // has current parent block
7629 currentBlock &&
7630 // presence of a patch flag indicates this node needs patching on updates.
7631 // component nodes also should always be patched, because even if the
7632 // component doesn't need to update, it needs to persist the instance on to
7633 // the next vnode so that it can be properly unmounted later.
7634 (vnode.patchFlag > 0 || shapeFlag & 6 /* COMPONENT */) &&
7635 // the EVENTS flag is only for hydration and if it is the only flag, the
7636 // vnode should not be considered dynamic due to handler caching.
7637 vnode.patchFlag !== 32 /* HYDRATE_EVENTS */) {
7638 currentBlock.push(vnode);
7639 }
7640 return vnode;
7641}
7642const createVNode = (createVNodeWithArgsTransform );
7643function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
7644 if (!type || type === NULL_DYNAMIC_COMPONENT) {
7645 if (!type) {
7646 warn$1(`Invalid vnode type when creating vnode: ${type}.`);
7647 }
7648 type = Comment;
7649 }
7650 if (isVNode(type)) {
7651 // createVNode receiving an existing vnode. This happens in cases like
7652 // <component :is="vnode"/>
7653 // #2078 make sure to merge refs during the clone instead of overwriting it
7654 const cloned = cloneVNode(type, props, true /* mergeRef: true */);
7655 if (children) {
7656 normalizeChildren(cloned, children);
7657 }
7658 return cloned;
7659 }
7660 // class component normalization.
7661 if (isClassComponent(type)) {
7662 type = type.__vccOpts;
7663 }
7664 // class & style normalization.
7665 if (props) {
7666 // for reactive or proxy objects, we need to clone it to enable mutation.
7667 props = guardReactiveProps(props);
7668 let { class: klass, style } = props;
7669 if (klass && !isString(klass)) {
7670 props.class = normalizeClass(klass);
7671 }
7672 if (isObject(style)) {
7673 // reactive state objects need to be cloned since they are likely to be
7674 // mutated
7675 if (isProxy(style) && !isArray(style)) {
7676 style = extend({}, style);
7677 }
7678 props.style = normalizeStyle(style);
7679 }
7680 }
7681 // encode the vnode type information into a bitmap
7682 const shapeFlag = isString(type)
7683 ? 1 /* ELEMENT */
7684 : isSuspense(type)
7685 ? 128 /* SUSPENSE */
7686 : isTeleport(type)
7687 ? 64 /* TELEPORT */
7688 : isObject(type)
7689 ? 4 /* STATEFUL_COMPONENT */
7690 : isFunction(type)
7691 ? 2 /* FUNCTIONAL_COMPONENT */
7692 : 0;
7693 if (shapeFlag & 4 /* STATEFUL_COMPONENT */ && isProxy(type)) {
7694 type = toRaw(type);
7695 warn$1(`Vue received a Component which was made a reactive object. This can ` +
7696 `lead to unnecessary performance overhead, and should be avoided by ` +
7697 `marking the component with \`markRaw\` or using \`shallowRef\` ` +
7698 `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
7699 }
7700 return createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, isBlockNode, true);
7701}
7702function guardReactiveProps(props) {
7703 if (!props)
7704 return null;
7705 return isProxy(props) || InternalObjectKey in props
7706 ? extend({}, props)
7707 : props;
7708}
7709function cloneVNode(vnode, extraProps, mergeRef = false) {
7710 // This is intentionally NOT using spread or extend to avoid the runtime
7711 // key enumeration cost.
7712 const { props, ref, patchFlag, children } = vnode;
7713 const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
7714 const cloned = {
7715 __v_isVNode: true,
7716 __v_skip: true,
7717 type: vnode.type,
7718 props: mergedProps,
7719 key: mergedProps && normalizeKey(mergedProps),
7720 ref: extraProps && extraProps.ref
7721 ? // #2078 in the case of <component :is="vnode" ref="extra"/>
7722 // if the vnode itself already has a ref, cloneVNode will need to merge
7723 // the refs so the single vnode can be set on multiple refs
7724 mergeRef && ref
7725 ? isArray(ref)
7726 ? ref.concat(normalizeRef(extraProps))
7727 : [ref, normalizeRef(extraProps)]
7728 : normalizeRef(extraProps)
7729 : ref,
7730 scopeId: vnode.scopeId,
7731 slotScopeIds: vnode.slotScopeIds,
7732 children: patchFlag === -1 /* HOISTED */ && isArray(children)
7733 ? children.map(deepCloneVNode)
7734 : children,
7735 target: vnode.target,
7736 targetAnchor: vnode.targetAnchor,
7737 staticCount: vnode.staticCount,
7738 shapeFlag: vnode.shapeFlag,
7739 // if the vnode is cloned with extra props, we can no longer assume its
7740 // existing patch flag to be reliable and need to add the FULL_PROPS flag.
7741 // note: preserve flag for fragments since they use the flag for children
7742 // fast paths only.
7743 patchFlag: extraProps && vnode.type !== Fragment
7744 ? patchFlag === -1 // hoisted node
7745 ? 16 /* FULL_PROPS */
7746 : patchFlag | 16 /* FULL_PROPS */
7747 : patchFlag,
7748 dynamicProps: vnode.dynamicProps,
7749 dynamicChildren: vnode.dynamicChildren,
7750 appContext: vnode.appContext,
7751 dirs: vnode.dirs,
7752 transition: vnode.transition,
7753 // These should technically only be non-null on mounted VNodes. However,
7754 // they *should* be copied for kept-alive vnodes. So we just always copy
7755 // them since them being non-null during a mount doesn't affect the logic as
7756 // they will simply be overwritten.
7757 component: vnode.component,
7758 suspense: vnode.suspense,
7759 ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
7760 ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
7761 el: vnode.el,
7762 anchor: vnode.anchor
7763 };
7764 return cloned;
7765}
7766/**
7767 * Dev only, for HMR of hoisted vnodes reused in v-for
7768 * https://github.com/vitejs/vite/issues/2022
7769 */
7770function deepCloneVNode(vnode) {
7771 const cloned = cloneVNode(vnode);
7772 if (isArray(vnode.children)) {
7773 cloned.children = vnode.children.map(deepCloneVNode);
7774 }
7775 return cloned;
7776}
7777/**
7778 * @private
7779 */
7780function createTextVNode(text = ' ', flag = 0) {
7781 return createVNode(Text, null, text, flag);
7782}
7783/**
7784 * @private
7785 */
7786function createStaticVNode(content, numberOfNodes) {
7787 // A static vnode can contain multiple stringified elements, and the number
7788 // of elements is necessary for hydration.
7789 const vnode = createVNode(Static, null, content);
7790 vnode.staticCount = numberOfNodes;
7791 return vnode;
7792}
7793/**
7794 * @private
7795 */
7796function createCommentVNode(text = '',
7797// when used as the v-else branch, the comment node must be created as a
7798// block to ensure correct updates.
7799asBlock = false) {
7800 return asBlock
7801 ? (openBlock(), createBlock(Comment, null, text))
7802 : createVNode(Comment, null, text);
7803}
7804function normalizeVNode(child) {
7805 if (child == null || typeof child === 'boolean') {
7806 // empty placeholder
7807 return createVNode(Comment);
7808 }
7809 else if (isArray(child)) {
7810 // fragment
7811 return createVNode(Fragment, null,
7812 // #3666, avoid reference pollution when reusing vnode
7813 child.slice());
7814 }
7815 else if (typeof child === 'object') {
7816 // already vnode, this should be the most common since compiled templates
7817 // always produce all-vnode children arrays
7818 return cloneIfMounted(child);
7819 }
7820 else {
7821 // strings and numbers
7822 return createVNode(Text, null, String(child));
7823 }
7824}
7825// optimized normalization for template-compiled render fns
7826function cloneIfMounted(child) {
7827 return child.el === null || child.memo ? child : cloneVNode(child);
7828}
7829function normalizeChildren(vnode, children) {
7830 let type = 0;
7831 const { shapeFlag } = vnode;
7832 if (children == null) {
7833 children = null;
7834 }
7835 else if (isArray(children)) {
7836 type = 16 /* ARRAY_CHILDREN */;
7837 }
7838 else if (typeof children === 'object') {
7839 if (shapeFlag & (1 /* ELEMENT */ | 64 /* TELEPORT */)) {
7840 // Normalize slot to plain children for plain element and Teleport
7841 const slot = children.default;
7842 if (slot) {
7843 // _c marker is added by withCtx() indicating this is a compiled slot
7844 slot._c && (slot._d = false);
7845 normalizeChildren(vnode, slot());
7846 slot._c && (slot._d = true);
7847 }
7848 return;
7849 }
7850 else {
7851 type = 32 /* SLOTS_CHILDREN */;
7852 const slotFlag = children._;
7853 if (!slotFlag && !(InternalObjectKey in children)) {
7854 children._ctx = currentRenderingInstance;
7855 }
7856 else if (slotFlag === 3 /* FORWARDED */ && currentRenderingInstance) {
7857 // a child component receives forwarded slots from the parent.
7858 // its slot type is determined by its parent's slot type.
7859 if (currentRenderingInstance.slots._ === 1 /* STABLE */) {
7860 children._ = 1 /* STABLE */;
7861 }
7862 else {
7863 children._ = 2 /* DYNAMIC */;
7864 vnode.patchFlag |= 1024 /* DYNAMIC_SLOTS */;
7865 }
7866 }
7867 }
7868 }
7869 else if (isFunction(children)) {
7870 children = { default: children, _ctx: currentRenderingInstance };
7871 type = 32 /* SLOTS_CHILDREN */;
7872 }
7873 else {
7874 children = String(children);
7875 // force teleport children to array so it can be moved around
7876 if (shapeFlag & 64 /* TELEPORT */) {
7877 type = 16 /* ARRAY_CHILDREN */;
7878 children = [createTextVNode(children)];
7879 }
7880 else {
7881 type = 8 /* TEXT_CHILDREN */;
7882 }
7883 }
7884 vnode.children = children;
7885 vnode.shapeFlag |= type;
7886}
7887function mergeProps(...args) {
7888 const ret = {};
7889 for (let i = 0; i < args.length; i++) {
7890 const toMerge = args[i];
7891 for (const key in toMerge) {
7892 if (key === 'class') {
7893 if (ret.class !== toMerge.class) {
7894 ret.class = normalizeClass([ret.class, toMerge.class]);
7895 }
7896 }
7897 else if (key === 'style') {
7898 ret.style = normalizeStyle([ret.style, toMerge.style]);
7899 }
7900 else if (isOn(key)) {
7901 const existing = ret[key];
7902 const incoming = toMerge[key];
7903 if (incoming &&
7904 existing !== incoming &&
7905 !(isArray(existing) && existing.includes(incoming))) {
7906 ret[key] = existing
7907 ? [].concat(existing, incoming)
7908 : incoming;
7909 }
7910 }
7911 else if (key !== '') {
7912 ret[key] = toMerge[key];
7913 }
7914 }
7915 }
7916 return ret;
7917}
7918function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
7919 callWithAsyncErrorHandling(hook, instance, 7 /* VNODE_HOOK */, [
7920 vnode,
7921 prevVNode
7922 ]);
7923}
7924
7925/**
7926 * Actual implementation
7927 */
7928function renderList(source, renderItem, cache, index) {
7929 let ret;
7930 const cached = (cache && cache[index]);
7931 if (isArray(source) || isString(source)) {
7932 ret = new Array(source.length);
7933 for (let i = 0, l = source.length; i < l; i++) {
7934 ret[i] = renderItem(source[i], i, undefined, cached && cached[i]);
7935 }
7936 }
7937 else if (typeof source === 'number') {
7938 if (!Number.isInteger(source)) {
7939 warn$1(`The v-for range expect an integer value but got ${source}.`);
7940 return [];
7941 }
7942 ret = new Array(source);
7943 for (let i = 0; i < source; i++) {
7944 ret[i] = renderItem(i + 1, i, undefined, cached && cached[i]);
7945 }
7946 }
7947 else if (isObject(source)) {
7948 if (source[Symbol.iterator]) {
7949 ret = Array.from(source, (item, i) => renderItem(item, i, undefined, cached && cached[i]));
7950 }
7951 else {
7952 const keys = Object.keys(source);
7953 ret = new Array(keys.length);
7954 for (let i = 0, l = keys.length; i < l; i++) {
7955 const key = keys[i];
7956 ret[i] = renderItem(source[key], key, i, cached && cached[i]);
7957 }
7958 }
7959 }
7960 else {
7961 ret = [];
7962 }
7963 if (cache) {
7964 cache[index] = ret;
7965 }
7966 return ret;
7967}
7968
7969/**
7970 * Compiler runtime helper for creating dynamic slots object
7971 * @private
7972 */
7973function createSlots(slots, dynamicSlots) {
7974 for (let i = 0; i < dynamicSlots.length; i++) {
7975 const slot = dynamicSlots[i];
7976 // array of dynamic slot generated by <template v-for="..." #[...]>
7977 if (isArray(slot)) {
7978 for (let j = 0; j < slot.length; j++) {
7979 slots[slot[j].name] = slot[j].fn;
7980 }
7981 }
7982 else if (slot) {
7983 // conditional single slot generated by <template v-if="..." #foo>
7984 slots[slot.name] = slot.fn;
7985 }
7986 }
7987 return slots;
7988}
7989
7990/**
7991 * Compiler runtime helper for rendering `<slot/>`
7992 * @private
7993 */
7994function renderSlot(slots, name, props = {},
7995// this is not a user-facing function, so the fallback is always generated by
7996// the compiler and guaranteed to be a function returning an array
7997fallback, noSlotted) {
7998 if (currentRenderingInstance.isCE) {
7999 return createVNode('slot', name === 'default' ? null : { name }, fallback && fallback());
8000 }
8001 let slot = slots[name];
8002 if (slot && slot.length > 1) {
8003 warn$1(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
8004 `function. You need to mark this component with $dynamic-slots in the ` +
8005 `parent template.`);
8006 slot = () => [];
8007 }
8008 // a compiled slot disables block tracking by default to avoid manual
8009 // invocation interfering with template-based block tracking, but in
8010 // `renderSlot` we can be sure that it's template-based so we can force
8011 // enable it.
8012 if (slot && slot._c) {
8013 slot._d = false;
8014 }
8015 openBlock();
8016 const validSlotContent = slot && ensureValidVNode(slot(props));
8017 const rendered = createBlock(Fragment, { key: props.key || `_${name}` }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 /* STABLE */
8018 ? 64 /* STABLE_FRAGMENT */
8019 : -2 /* BAIL */);
8020 if (!noSlotted && rendered.scopeId) {
8021 rendered.slotScopeIds = [rendered.scopeId + '-s'];
8022 }
8023 if (slot && slot._c) {
8024 slot._d = true;
8025 }
8026 return rendered;
8027}
8028function ensureValidVNode(vnodes) {
8029 return vnodes.some(child => {
8030 if (!isVNode(child))
8031 return true;
8032 if (child.type === Comment)
8033 return false;
8034 if (child.type === Fragment &&
8035 !ensureValidVNode(child.children))
8036 return false;
8037 return true;
8038 })
8039 ? vnodes
8040 : null;
8041}
8042
8043/**
8044 * For prefixing keys in v-on="obj" with "on"
8045 * @private
8046 */
8047function toHandlers(obj) {
8048 const ret = {};
8049 if (!isObject(obj)) {
8050 warn$1(`v-on with no argument expects an object value.`);
8051 return ret;
8052 }
8053 for (const key in obj) {
8054 ret[toHandlerKey(key)] = obj[key];
8055 }
8056 return ret;
8057}
8058
8059/**
8060 * #2437 In Vue 3, functional components do not have a public instance proxy but
8061 * they exist in the internal parent chain. For code that relies on traversing
8062 * public $parent chains, skip functional ones and go to the parent instead.
8063 */
8064const getPublicInstance = (i) => {
8065 if (!i)
8066 return null;
8067 if (isStatefulComponent(i))
8068 return getExposeProxy(i) || i.proxy;
8069 return getPublicInstance(i.parent);
8070};
8071const publicPropertiesMap = extend(Object.create(null), {
8072 $: i => i,
8073 $el: i => i.vnode.el,
8074 $data: i => i.data,
8075 $props: i => (shallowReadonly(i.props) ),
8076 $attrs: i => (shallowReadonly(i.attrs) ),
8077 $slots: i => (shallowReadonly(i.slots) ),
8078 $refs: i => (shallowReadonly(i.refs) ),
8079 $parent: i => getPublicInstance(i.parent),
8080 $root: i => getPublicInstance(i.root),
8081 $emit: i => i.emit,
8082 $options: i => (resolveMergedOptions(i) ),
8083 $forceUpdate: i => () => queueJob(i.update),
8084 $nextTick: i => nextTick.bind(i.proxy),
8085 $watch: i => (instanceWatch.bind(i) )
8086});
8087const PublicInstanceProxyHandlers = {
8088 get({ _: instance }, key) {
8089 const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
8090 // for internal formatters to know that this is a Vue instance
8091 if (key === '__isVue') {
8092 return true;
8093 }
8094 // prioritize <script setup> bindings during dev.
8095 // this allows even properties that start with _ or $ to be used - so that
8096 // it aligns with the production behavior where the render fn is inlined and
8097 // indeed has access to all declared variables.
8098 if (setupState !== EMPTY_OBJ &&
8099 setupState.__isScriptSetup &&
8100 hasOwn(setupState, key)) {
8101 return setupState[key];
8102 }
8103 // data / props / ctx
8104 // This getter gets called for every property access on the render context
8105 // during render and is a major hotspot. The most expensive part of this
8106 // is the multiple hasOwn() calls. It's much faster to do a simple property
8107 // access on a plain object, so we use an accessCache object (with null
8108 // prototype) to memoize what access type a key corresponds to.
8109 let normalizedProps;
8110 if (key[0] !== '$') {
8111 const n = accessCache[key];
8112 if (n !== undefined) {
8113 switch (n) {
8114 case 1 /* SETUP */:
8115 return setupState[key];
8116 case 2 /* DATA */:
8117 return data[key];
8118 case 4 /* CONTEXT */:
8119 return ctx[key];
8120 case 3 /* PROPS */:
8121 return props[key];
8122 // default: just fallthrough
8123 }
8124 }
8125 else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
8126 accessCache[key] = 1 /* SETUP */;
8127 return setupState[key];
8128 }
8129 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
8130 accessCache[key] = 2 /* DATA */;
8131 return data[key];
8132 }
8133 else if (
8134 // only cache other properties when instance has declared (thus stable)
8135 // props
8136 (normalizedProps = instance.propsOptions[0]) &&
8137 hasOwn(normalizedProps, key)) {
8138 accessCache[key] = 3 /* PROPS */;
8139 return props[key];
8140 }
8141 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
8142 accessCache[key] = 4 /* CONTEXT */;
8143 return ctx[key];
8144 }
8145 else if (shouldCacheAccess) {
8146 accessCache[key] = 0 /* OTHER */;
8147 }
8148 }
8149 const publicGetter = publicPropertiesMap[key];
8150 let cssModule, globalProperties;
8151 // public $xxx properties
8152 if (publicGetter) {
8153 if (key === '$attrs') {
8154 track(instance, "get" /* GET */, key);
8155 markAttrsAccessed();
8156 }
8157 return publicGetter(instance);
8158 }
8159 else if (
8160 // css module (injected by vue-loader)
8161 (cssModule = type.__cssModules) &&
8162 (cssModule = cssModule[key])) {
8163 return cssModule;
8164 }
8165 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
8166 // user may set custom properties to `this` that start with `$`
8167 accessCache[key] = 4 /* CONTEXT */;
8168 return ctx[key];
8169 }
8170 else if (
8171 // global properties
8172 ((globalProperties = appContext.config.globalProperties),
8173 hasOwn(globalProperties, key))) {
8174 {
8175 return globalProperties[key];
8176 }
8177 }
8178 else if (currentRenderingInstance &&
8179 (!isString(key) ||
8180 // #1091 avoid internal isRef/isVNode checks on component instance leading
8181 // to infinite warning loop
8182 key.indexOf('__v') !== 0)) {
8183 if (data !== EMPTY_OBJ &&
8184 (key[0] === '$' || key[0] === '_') &&
8185 hasOwn(data, key)) {
8186 warn$1(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
8187 `character ("$" or "_") and is not proxied on the render context.`);
8188 }
8189 else if (instance === currentRenderingInstance) {
8190 warn$1(`Property ${JSON.stringify(key)} was accessed during render ` +
8191 `but is not defined on instance.`);
8192 }
8193 }
8194 },
8195 set({ _: instance }, key, value) {
8196 const { data, setupState, ctx } = instance;
8197 if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
8198 setupState[key] = value;
8199 return true;
8200 }
8201 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
8202 data[key] = value;
8203 return true;
8204 }
8205 else if (hasOwn(instance.props, key)) {
8206 warn$1(`Attempting to mutate prop "${key}". Props are readonly.`, instance);
8207 return false;
8208 }
8209 if (key[0] === '$' && key.slice(1) in instance) {
8210 warn$1(`Attempting to mutate public property "${key}". ` +
8211 `Properties starting with $ are reserved and readonly.`, instance);
8212 return false;
8213 }
8214 else {
8215 if (key in instance.appContext.config.globalProperties) {
8216 Object.defineProperty(ctx, key, {
8217 enumerable: true,
8218 configurable: true,
8219 value
8220 });
8221 }
8222 else {
8223 ctx[key] = value;
8224 }
8225 }
8226 return true;
8227 },
8228 has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
8229 let normalizedProps;
8230 return (!!accessCache[key] ||
8231 (data !== EMPTY_OBJ && hasOwn(data, key)) ||
8232 (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
8233 ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
8234 hasOwn(ctx, key) ||
8235 hasOwn(publicPropertiesMap, key) ||
8236 hasOwn(appContext.config.globalProperties, key));
8237 },
8238 defineProperty(target, key, descriptor) {
8239 if (descriptor.get != null) {
8240 this.set(target, key, descriptor.get(), null);
8241 }
8242 else if (descriptor.value != null) {
8243 this.set(target, key, descriptor.value, null);
8244 }
8245 return Reflect.defineProperty(target, key, descriptor);
8246 }
8247};
8248{
8249 PublicInstanceProxyHandlers.ownKeys = (target) => {
8250 warn$1(`Avoid app logic that relies on enumerating keys on a component instance. ` +
8251 `The keys will be empty in production mode to avoid performance overhead.`);
8252 return Reflect.ownKeys(target);
8253 };
8254}
8255const RuntimeCompiledPublicInstanceProxyHandlers = /*#__PURE__*/ extend({}, PublicInstanceProxyHandlers, {
8256 get(target, key) {
8257 // fast path for unscopables when using `with` block
8258 if (key === Symbol.unscopables) {
8259 return;
8260 }
8261 return PublicInstanceProxyHandlers.get(target, key, target);
8262 },
8263 has(_, key) {
8264 const has = key[0] !== '_' && !isGloballyWhitelisted(key);
8265 if (!has && PublicInstanceProxyHandlers.has(_, key)) {
8266 warn$1(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
8267 }
8268 return has;
8269 }
8270});
8271// dev only
8272// In dev mode, the proxy target exposes the same properties as seen on `this`
8273// for easier console inspection. In prod mode it will be an empty object so
8274// these properties definitions can be skipped.
8275function createDevRenderContext(instance) {
8276 const target = {};
8277 // expose internal instance for proxy handlers
8278 Object.defineProperty(target, `_`, {
8279 configurable: true,
8280 enumerable: false,
8281 get: () => instance
8282 });
8283 // expose public properties
8284 Object.keys(publicPropertiesMap).forEach(key => {
8285 Object.defineProperty(target, key, {
8286 configurable: true,
8287 enumerable: false,
8288 get: () => publicPropertiesMap[key](instance),
8289 // intercepted by the proxy so no need for implementation,
8290 // but needed to prevent set errors
8291 set: NOOP
8292 });
8293 });
8294 return target;
8295}
8296// dev only
8297function exposePropsOnRenderContext(instance) {
8298 const { ctx, propsOptions: [propsOptions] } = instance;
8299 if (propsOptions) {
8300 Object.keys(propsOptions).forEach(key => {
8301 Object.defineProperty(ctx, key, {
8302 enumerable: true,
8303 configurable: true,
8304 get: () => instance.props[key],
8305 set: NOOP
8306 });
8307 });
8308 }
8309}
8310// dev only
8311function exposeSetupStateOnRenderContext(instance) {
8312 const { ctx, setupState } = instance;
8313 Object.keys(toRaw(setupState)).forEach(key => {
8314 if (!setupState.__isScriptSetup) {
8315 if (key[0] === '$' || key[0] === '_') {
8316 warn$1(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
8317 `which are reserved prefixes for Vue internals.`);
8318 return;
8319 }
8320 Object.defineProperty(ctx, key, {
8321 enumerable: true,
8322 configurable: true,
8323 get: () => setupState[key],
8324 set: NOOP
8325 });
8326 }
8327 });
8328}
8329
8330const emptyAppContext = createAppContext();
8331let uid$1 = 0;
8332function createComponentInstance(vnode, parent, suspense) {
8333 const type = vnode.type;
8334 // inherit parent app context - or - if root, adopt from root vnode
8335 const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
8336 const instance = {
8337 uid: uid$1++,
8338 vnode,
8339 type,
8340 parent,
8341 appContext,
8342 root: null,
8343 next: null,
8344 subTree: null,
8345 effect: null,
8346 update: null,
8347 scope: new EffectScope(true /* detached */),
8348 render: null,
8349 proxy: null,
8350 exposed: null,
8351 exposeProxy: null,
8352 withProxy: null,
8353 provides: parent ? parent.provides : Object.create(appContext.provides),
8354 accessCache: null,
8355 renderCache: [],
8356 // local resovled assets
8357 components: null,
8358 directives: null,
8359 // resolved props and emits options
8360 propsOptions: normalizePropsOptions(type, appContext),
8361 emitsOptions: normalizeEmitsOptions(type, appContext),
8362 // emit
8363 emit: null,
8364 emitted: null,
8365 // props default value
8366 propsDefaults: EMPTY_OBJ,
8367 // inheritAttrs
8368 inheritAttrs: type.inheritAttrs,
8369 // state
8370 ctx: EMPTY_OBJ,
8371 data: EMPTY_OBJ,
8372 props: EMPTY_OBJ,
8373 attrs: EMPTY_OBJ,
8374 slots: EMPTY_OBJ,
8375 refs: EMPTY_OBJ,
8376 setupState: EMPTY_OBJ,
8377 setupContext: null,
8378 // suspense related
8379 suspense,
8380 suspenseId: suspense ? suspense.pendingId : 0,
8381 asyncDep: null,
8382 asyncResolved: false,
8383 // lifecycle hooks
8384 // not using enums here because it results in computed properties
8385 isMounted: false,
8386 isUnmounted: false,
8387 isDeactivated: false,
8388 bc: null,
8389 c: null,
8390 bm: null,
8391 m: null,
8392 bu: null,
8393 u: null,
8394 um: null,
8395 bum: null,
8396 da: null,
8397 a: null,
8398 rtg: null,
8399 rtc: null,
8400 ec: null,
8401 sp: null
8402 };
8403 {
8404 instance.ctx = createDevRenderContext(instance);
8405 }
8406 instance.root = parent ? parent.root : instance;
8407 instance.emit = emit$1.bind(null, instance);
8408 // apply custom element special handling
8409 if (vnode.ce) {
8410 vnode.ce(instance);
8411 }
8412 return instance;
8413}
8414let currentInstance = null;
8415const getCurrentInstance = () => currentInstance || currentRenderingInstance;
8416const setCurrentInstance = (instance) => {
8417 currentInstance = instance;
8418 instance.scope.on();
8419};
8420const unsetCurrentInstance = () => {
8421 currentInstance && currentInstance.scope.off();
8422 currentInstance = null;
8423};
8424const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
8425function validateComponentName(name, config) {
8426 const appIsNativeTag = config.isNativeTag || NO;
8427 if (isBuiltInTag(name) || appIsNativeTag(name)) {
8428 warn$1('Do not use built-in or reserved HTML elements as component id: ' + name);
8429 }
8430}
8431function isStatefulComponent(instance) {
8432 return instance.vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */;
8433}
8434let isInSSRComponentSetup = false;
8435function setupComponent(instance, isSSR = false) {
8436 isInSSRComponentSetup = isSSR;
8437 const { props, children } = instance.vnode;
8438 const isStateful = isStatefulComponent(instance);
8439 initProps(instance, props, isStateful, isSSR);
8440 initSlots(instance, children);
8441 const setupResult = isStateful
8442 ? setupStatefulComponent(instance, isSSR)
8443 : undefined;
8444 isInSSRComponentSetup = false;
8445 return setupResult;
8446}
8447function setupStatefulComponent(instance, isSSR) {
8448 const Component = instance.type;
8449 {
8450 if (Component.name) {
8451 validateComponentName(Component.name, instance.appContext.config);
8452 }
8453 if (Component.components) {
8454 const names = Object.keys(Component.components);
8455 for (let i = 0; i < names.length; i++) {
8456 validateComponentName(names[i], instance.appContext.config);
8457 }
8458 }
8459 if (Component.directives) {
8460 const names = Object.keys(Component.directives);
8461 for (let i = 0; i < names.length; i++) {
8462 validateDirectiveName(names[i]);
8463 }
8464 }
8465 if (Component.compilerOptions && isRuntimeOnly()) {
8466 warn$1(`"compilerOptions" is only supported when using a build of Vue that ` +
8467 `includes the runtime compiler. Since you are using a runtime-only ` +
8468 `build, the options should be passed via your build tool config instead.`);
8469 }
8470 }
8471 // 0. create render proxy property access cache
8472 instance.accessCache = Object.create(null);
8473 // 1. create public instance / render proxy
8474 // also mark it raw so it's never observed
8475 instance.proxy = markRaw(new Proxy(instance.ctx, PublicInstanceProxyHandlers));
8476 {
8477 exposePropsOnRenderContext(instance);
8478 }
8479 // 2. call setup()
8480 const { setup } = Component;
8481 if (setup) {
8482 const setupContext = (instance.setupContext =
8483 setup.length > 1 ? createSetupContext(instance) : null);
8484 setCurrentInstance(instance);
8485 pauseTracking();
8486 const setupResult = callWithErrorHandling(setup, instance, 0 /* SETUP_FUNCTION */, [shallowReadonly(instance.props) , setupContext]);
8487 resetTracking();
8488 unsetCurrentInstance();
8489 if (isPromise(setupResult)) {
8490 setupResult.then(unsetCurrentInstance, unsetCurrentInstance);
8491 if (isSSR) {
8492 // return the promise so server-renderer can wait on it
8493 return setupResult
8494 .then((resolvedResult) => {
8495 handleSetupResult(instance, resolvedResult, isSSR);
8496 })
8497 .catch(e => {
8498 handleError(e, instance, 0 /* SETUP_FUNCTION */);
8499 });
8500 }
8501 else {
8502 // async setup returned Promise.
8503 // bail here and wait for re-entry.
8504 instance.asyncDep = setupResult;
8505 }
8506 }
8507 else {
8508 handleSetupResult(instance, setupResult, isSSR);
8509 }
8510 }
8511 else {
8512 finishComponentSetup(instance, isSSR);
8513 }
8514}
8515function handleSetupResult(instance, setupResult, isSSR) {
8516 if (isFunction(setupResult)) {
8517 // setup returned an inline render function
8518 {
8519 instance.render = setupResult;
8520 }
8521 }
8522 else if (isObject(setupResult)) {
8523 if (isVNode(setupResult)) {
8524 warn$1(`setup() should not return VNodes directly - ` +
8525 `return a render function instead.`);
8526 }
8527 // setup returned bindings.
8528 // assuming a render function compiled from template is present.
8529 {
8530 instance.devtoolsRawSetupState = setupResult;
8531 }
8532 instance.setupState = proxyRefs(setupResult);
8533 {
8534 exposeSetupStateOnRenderContext(instance);
8535 }
8536 }
8537 else if (setupResult !== undefined) {
8538 warn$1(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
8539 }
8540 finishComponentSetup(instance, isSSR);
8541}
8542let compile;
8543let installWithProxy;
8544/**
8545 * For runtime-dom to register the compiler.
8546 * Note the exported method uses any to avoid d.ts relying on the compiler types.
8547 */
8548function registerRuntimeCompiler(_compile) {
8549 compile = _compile;
8550 installWithProxy = i => {
8551 if (i.render._rc) {
8552 i.withProxy = new Proxy(i.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
8553 }
8554 };
8555}
8556// dev only
8557const isRuntimeOnly = () => !compile;
8558function finishComponentSetup(instance, isSSR, skipOptions) {
8559 const Component = instance.type;
8560 // template / render function normalization
8561 // could be already set when returned from setup()
8562 if (!instance.render) {
8563 // only do on-the-fly compile if not in SSR - SSR on-the-fly compilation
8564 // is done by server-renderer
8565 if (!isSSR && compile && !Component.render) {
8566 const template = Component.template;
8567 if (template) {
8568 {
8569 startMeasure(instance, `compile`);
8570 }
8571 const { isCustomElement, compilerOptions } = instance.appContext.config;
8572 const { delimiters, compilerOptions: componentCompilerOptions } = Component;
8573 const finalCompilerOptions = extend(extend({
8574 isCustomElement,
8575 delimiters
8576 }, compilerOptions), componentCompilerOptions);
8577 Component.render = compile(template, finalCompilerOptions);
8578 {
8579 endMeasure(instance, `compile`);
8580 }
8581 }
8582 }
8583 instance.render = (Component.render || NOOP);
8584 // for runtime-compiled render functions using `with` blocks, the render
8585 // proxy used needs a different `has` handler which is more performant and
8586 // also only allows a whitelist of globals to fallthrough.
8587 if (installWithProxy) {
8588 installWithProxy(instance);
8589 }
8590 }
8591 // support for 2.x options
8592 {
8593 setCurrentInstance(instance);
8594 pauseTracking();
8595 applyOptions(instance);
8596 resetTracking();
8597 unsetCurrentInstance();
8598 }
8599 // warn missing template/render
8600 // the runtime compilation of template in SSR is done by server-render
8601 if (!Component.render && instance.render === NOOP && !isSSR) {
8602 /* istanbul ignore if */
8603 if (!compile && Component.template) {
8604 warn$1(`Component provided template option but ` +
8605 `runtime compilation is not supported in this build of Vue.` +
8606 (` Use "vue.esm-browser.js" instead.`
8607 ) /* should not happen */);
8608 }
8609 else {
8610 warn$1(`Component is missing template or render function.`);
8611 }
8612 }
8613}
8614function createAttrsProxy(instance) {
8615 return new Proxy(instance.attrs, {
8616 get(target, key) {
8617 markAttrsAccessed();
8618 track(instance, "get" /* GET */, '$attrs');
8619 return target[key];
8620 },
8621 set() {
8622 warn$1(`setupContext.attrs is readonly.`);
8623 return false;
8624 },
8625 deleteProperty() {
8626 warn$1(`setupContext.attrs is readonly.`);
8627 return false;
8628 }
8629 }
8630 );
8631}
8632function createSetupContext(instance) {
8633 const expose = exposed => {
8634 if (instance.exposed) {
8635 warn$1(`expose() should be called only once per setup().`);
8636 }
8637 instance.exposed = exposed || {};
8638 };
8639 let attrs;
8640 {
8641 // We use getters in dev in case libs like test-utils overwrite instance
8642 // properties (overwrites should not be done in prod)
8643 return Object.freeze({
8644 get attrs() {
8645 return attrs || (attrs = createAttrsProxy(instance));
8646 },
8647 get slots() {
8648 return shallowReadonly(instance.slots);
8649 },
8650 get emit() {
8651 return (event, ...args) => instance.emit(event, ...args);
8652 },
8653 expose
8654 });
8655 }
8656}
8657function getExposeProxy(instance) {
8658 if (instance.exposed) {
8659 return (instance.exposeProxy ||
8660 (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), {
8661 get(target, key) {
8662 if (key in target) {
8663 return target[key];
8664 }
8665 else if (key in publicPropertiesMap) {
8666 return publicPropertiesMap[key](instance);
8667 }
8668 }
8669 })));
8670 }
8671}
8672const classifyRE = /(?:^|[-_])(\w)/g;
8673const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
8674function getComponentName(Component) {
8675 return isFunction(Component)
8676 ? Component.displayName || Component.name
8677 : Component.name;
8678}
8679/* istanbul ignore next */
8680function formatComponentName(instance, Component, isRoot = false) {
8681 let name = getComponentName(Component);
8682 if (!name && Component.__file) {
8683 const match = Component.__file.match(/([^/\\]+)\.\w+$/);
8684 if (match) {
8685 name = match[1];
8686 }
8687 }
8688 if (!name && instance && instance.parent) {
8689 // try to infer the name based on reverse resolution
8690 const inferFromRegistry = (registry) => {
8691 for (const key in registry) {
8692 if (registry[key] === Component) {
8693 return key;
8694 }
8695 }
8696 };
8697 name =
8698 inferFromRegistry(instance.components ||
8699 instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
8700 }
8701 return name ? classify(name) : isRoot ? `App` : `Anonymous`;
8702}
8703function isClassComponent(value) {
8704 return isFunction(value) && '__vccOpts' in value;
8705}
8706
8707const computed$1 = ((getterOrOptions, debugOptions) => {
8708 // @ts-ignore
8709 return computed(getterOrOptions, debugOptions, isInSSRComponentSetup);
8710});
8711
8712// dev only
8713const warnRuntimeUsage = (method) => warn$1(`${method}() is a compiler-hint helper that is only usable inside ` +
8714 `<script setup> of a single file component. Its arguments should be ` +
8715 `compiled away and passing it at runtime has no effect.`);
8716// implementation
8717function defineProps() {
8718 {
8719 warnRuntimeUsage(`defineProps`);
8720 }
8721 return null;
8722}
8723// implementation
8724function defineEmits() {
8725 {
8726 warnRuntimeUsage(`defineEmits`);
8727 }
8728 return null;
8729}
8730/**
8731 * Vue `<script setup>` compiler macro for declaring a component's exposed
8732 * instance properties when it is accessed by a parent component via template
8733 * refs.
8734 *
8735 * `<script setup>` components are closed by default - i.e. variables inside
8736 * the `<script setup>` scope is not exposed to parent unless explicitly exposed
8737 * via `defineExpose`.
8738 *
8739 * This is only usable inside `<script setup>`, is compiled away in the
8740 * output and should **not** be actually called at runtime.
8741 */
8742function defineExpose(exposed) {
8743 {
8744 warnRuntimeUsage(`defineExpose`);
8745 }
8746}
8747/**
8748 * Vue `<script setup>` compiler macro for providing props default values when
8749 * using type-based `defineProps` declaration.
8750 *
8751 * Example usage:
8752 * ```ts
8753 * withDefaults(defineProps<{
8754 * size?: number
8755 * labels?: string[]
8756 * }>(), {
8757 * size: 3,
8758 * labels: () => ['default label']
8759 * })
8760 * ```
8761 *
8762 * This is only usable inside `<script setup>`, is compiled away in the output
8763 * and should **not** be actually called at runtime.
8764 */
8765function withDefaults(props, defaults) {
8766 {
8767 warnRuntimeUsage(`withDefaults`);
8768 }
8769 return null;
8770}
8771function useSlots() {
8772 return getContext().slots;
8773}
8774function useAttrs() {
8775 return getContext().attrs;
8776}
8777function getContext() {
8778 const i = getCurrentInstance();
8779 if (!i) {
8780 warn$1(`useContext() called without active instance.`);
8781 }
8782 return i.setupContext || (i.setupContext = createSetupContext(i));
8783}
8784/**
8785 * Runtime helper for merging default declarations. Imported by compiled code
8786 * only.
8787 * @internal
8788 */
8789function mergeDefaults(raw, defaults) {
8790 const props = isArray(raw)
8791 ? raw.reduce((normalized, p) => ((normalized[p] = {}), normalized), {})
8792 : raw;
8793 for (const key in defaults) {
8794 const opt = props[key];
8795 if (opt) {
8796 if (isArray(opt) || isFunction(opt)) {
8797 props[key] = { type: opt, default: defaults[key] };
8798 }
8799 else {
8800 opt.default = defaults[key];
8801 }
8802 }
8803 else if (opt === null) {
8804 props[key] = { default: defaults[key] };
8805 }
8806 else {
8807 warn$1(`props default key "${key}" has no corresponding declaration.`);
8808 }
8809 }
8810 return props;
8811}
8812/**
8813 * Used to create a proxy for the rest element when destructuring props with
8814 * defineProps().
8815 * @internal
8816 */
8817function createPropsRestProxy(props, excludedKeys) {
8818 const ret = {};
8819 for (const key in props) {
8820 if (!excludedKeys.includes(key)) {
8821 Object.defineProperty(ret, key, {
8822 enumerable: true,
8823 get: () => props[key]
8824 });
8825 }
8826 }
8827 return ret;
8828}
8829/**
8830 * `<script setup>` helper for persisting the current instance context over
8831 * async/await flows.
8832 *
8833 * `@vue/compiler-sfc` converts the following:
8834 *
8835 * ```ts
8836 * const x = await foo()
8837 * ```
8838 *
8839 * into:
8840 *
8841 * ```ts
8842 * let __temp, __restore
8843 * const x = (([__temp, __restore] = withAsyncContext(() => foo())),__temp=await __temp,__restore(),__temp)
8844 * ```
8845 * @internal
8846 */
8847function withAsyncContext(getAwaitable) {
8848 const ctx = getCurrentInstance();
8849 if (!ctx) {
8850 warn$1(`withAsyncContext called without active current instance. ` +
8851 `This is likely a bug.`);
8852 }
8853 let awaitable = getAwaitable();
8854 unsetCurrentInstance();
8855 if (isPromise(awaitable)) {
8856 awaitable = awaitable.catch(e => {
8857 setCurrentInstance(ctx);
8858 throw e;
8859 });
8860 }
8861 return [awaitable, () => setCurrentInstance(ctx)];
8862}
8863
8864// Actual implementation
8865function h(type, propsOrChildren, children) {
8866 const l = arguments.length;
8867 if (l === 2) {
8868 if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
8869 // single vnode without props
8870 if (isVNode(propsOrChildren)) {
8871 return createVNode(type, null, [propsOrChildren]);
8872 }
8873 // props without children
8874 return createVNode(type, propsOrChildren);
8875 }
8876 else {
8877 // omit props
8878 return createVNode(type, null, propsOrChildren);
8879 }
8880 }
8881 else {
8882 if (l > 3) {
8883 children = Array.prototype.slice.call(arguments, 2);
8884 }
8885 else if (l === 3 && isVNode(children)) {
8886 children = [children];
8887 }
8888 return createVNode(type, propsOrChildren, children);
8889 }
8890}
8891
8892const ssrContextKey = Symbol(`ssrContext` );
8893const useSSRContext = () => {
8894 {
8895 const ctx = inject(ssrContextKey);
8896 if (!ctx) {
8897 warn$1(`Server rendering context not provided. Make sure to only call ` +
8898 `useSSRContext() conditionally in the server build.`);
8899 }
8900 return ctx;
8901 }
8902};
8903
8904function initCustomFormatter() {
8905 /* eslint-disable no-restricted-globals */
8906 if (typeof window === 'undefined') {
8907 return;
8908 }
8909 const vueStyle = { style: 'color:#3ba776' };
8910 const numberStyle = { style: 'color:#0b1bc9' };
8911 const stringStyle = { style: 'color:#b62e24' };
8912 const keywordStyle = { style: 'color:#9d288c' };
8913 // custom formatter for Chrome
8914 // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
8915 const formatter = {
8916 header(obj) {
8917 // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
8918 if (!isObject(obj)) {
8919 return null;
8920 }
8921 if (obj.__isVue) {
8922 return ['div', vueStyle, `VueInstance`];
8923 }
8924 else if (isRef(obj)) {
8925 return [
8926 'div',
8927 {},
8928 ['span', vueStyle, genRefFlag(obj)],
8929 '<',
8930 formatValue(obj.value),
8931 `>`
8932 ];
8933 }
8934 else if (isReactive(obj)) {
8935 return [
8936 'div',
8937 {},
8938 ['span', vueStyle, isShallow(obj) ? 'ShallowReactive' : 'Reactive'],
8939 '<',
8940 formatValue(obj),
8941 `>${isReadonly(obj) ? ` (readonly)` : ``}`
8942 ];
8943 }
8944 else if (isReadonly(obj)) {
8945 return [
8946 'div',
8947 {},
8948 ['span', vueStyle, isShallow(obj) ? 'ShallowReadonly' : 'Readonly'],
8949 '<',
8950 formatValue(obj),
8951 '>'
8952 ];
8953 }
8954 return null;
8955 },
8956 hasBody(obj) {
8957 return obj && obj.__isVue;
8958 },
8959 body(obj) {
8960 if (obj && obj.__isVue) {
8961 return [
8962 'div',
8963 {},
8964 ...formatInstance(obj.$)
8965 ];
8966 }
8967 }
8968 };
8969 function formatInstance(instance) {
8970 const blocks = [];
8971 if (instance.type.props && instance.props) {
8972 blocks.push(createInstanceBlock('props', toRaw(instance.props)));
8973 }
8974 if (instance.setupState !== EMPTY_OBJ) {
8975 blocks.push(createInstanceBlock('setup', instance.setupState));
8976 }
8977 if (instance.data !== EMPTY_OBJ) {
8978 blocks.push(createInstanceBlock('data', toRaw(instance.data)));
8979 }
8980 const computed = extractKeys(instance, 'computed');
8981 if (computed) {
8982 blocks.push(createInstanceBlock('computed', computed));
8983 }
8984 const injected = extractKeys(instance, 'inject');
8985 if (injected) {
8986 blocks.push(createInstanceBlock('injected', injected));
8987 }
8988 blocks.push([
8989 'div',
8990 {},
8991 [
8992 'span',
8993 {
8994 style: keywordStyle.style + ';opacity:0.66'
8995 },
8996 '$ (internal): '
8997 ],
8998 ['object', { object: instance }]
8999 ]);
9000 return blocks;
9001 }
9002 function createInstanceBlock(type, target) {
9003 target = extend({}, target);
9004 if (!Object.keys(target).length) {
9005 return ['span', {}];
9006 }
9007 return [
9008 'div',
9009 { style: 'line-height:1.25em;margin-bottom:0.6em' },
9010 [
9011 'div',
9012 {
9013 style: 'color:#476582'
9014 },
9015 type
9016 ],
9017 [
9018 'div',
9019 {
9020 style: 'padding-left:1.25em'
9021 },
9022 ...Object.keys(target).map(key => {
9023 return [
9024 'div',
9025 {},
9026 ['span', keywordStyle, key + ': '],
9027 formatValue(target[key], false)
9028 ];
9029 })
9030 ]
9031 ];
9032 }
9033 function formatValue(v, asRaw = true) {
9034 if (typeof v === 'number') {
9035 return ['span', numberStyle, v];
9036 }
9037 else if (typeof v === 'string') {
9038 return ['span', stringStyle, JSON.stringify(v)];
9039 }
9040 else if (typeof v === 'boolean') {
9041 return ['span', keywordStyle, v];
9042 }
9043 else if (isObject(v)) {
9044 return ['object', { object: asRaw ? toRaw(v) : v }];
9045 }
9046 else {
9047 return ['span', stringStyle, String(v)];
9048 }
9049 }
9050 function extractKeys(instance, type) {
9051 const Comp = instance.type;
9052 if (isFunction(Comp)) {
9053 return;
9054 }
9055 const extracted = {};
9056 for (const key in instance.ctx) {
9057 if (isKeyOfType(Comp, key, type)) {
9058 extracted[key] = instance.ctx[key];
9059 }
9060 }
9061 return extracted;
9062 }
9063 function isKeyOfType(Comp, key, type) {
9064 const opts = Comp[type];
9065 if ((isArray(opts) && opts.includes(key)) ||
9066 (isObject(opts) && key in opts)) {
9067 return true;
9068 }
9069 if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
9070 return true;
9071 }
9072 if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
9073 return true;
9074 }
9075 }
9076 function genRefFlag(v) {
9077 if (isShallow(v)) {
9078 return `ShallowRef`;
9079 }
9080 if (v.effect) {
9081 return `ComputedRef`;
9082 }
9083 return `Ref`;
9084 }
9085 if (window.devtoolsFormatters) {
9086 window.devtoolsFormatters.push(formatter);
9087 }
9088 else {
9089 window.devtoolsFormatters = [formatter];
9090 }
9091}
9092
9093function withMemo(memo, render, cache, index) {
9094 const cached = cache[index];
9095 if (cached && isMemoSame(cached, memo)) {
9096 return cached;
9097 }
9098 const ret = render();
9099 // shallow clone
9100 ret.memo = memo.slice();
9101 return (cache[index] = ret);
9102}
9103function isMemoSame(cached, memo) {
9104 const prev = cached.memo;
9105 if (prev.length != memo.length) {
9106 return false;
9107 }
9108 for (let i = 0; i < prev.length; i++) {
9109 if (prev[i] !== memo[i]) {
9110 return false;
9111 }
9112 }
9113 // make sure to let parent block track it when returning cached
9114 if (isBlockTreeEnabled > 0 && currentBlock) {
9115 currentBlock.push(cached);
9116 }
9117 return true;
9118}
9119
9120// Core API ------------------------------------------------------------------
9121const version = "3.2.31";
9122/**
9123 * SSR utils for \@vue/server-renderer. Only exposed in cjs builds.
9124 * @internal
9125 */
9126const ssrUtils = (null);
9127/**
9128 * @internal only exposed in compat builds
9129 */
9130const resolveFilter = null;
9131/**
9132 * @internal only exposed in compat builds.
9133 */
9134const compatUtils = (null);
9135
9136const svgNS = 'http://www.w3.org/2000/svg';
9137const doc = (typeof document !== 'undefined' ? document : null);
9138const templateContainer = doc && doc.createElement('template');
9139const nodeOps = {
9140 insert: (child, parent, anchor) => {
9141 parent.insertBefore(child, anchor || null);
9142 },
9143 remove: child => {
9144 const parent = child.parentNode;
9145 if (parent) {
9146 parent.removeChild(child);
9147 }
9148 },
9149 createElement: (tag, isSVG, is, props) => {
9150 const el = isSVG
9151 ? doc.createElementNS(svgNS, tag)
9152 : doc.createElement(tag, is ? { is } : undefined);
9153 if (tag === 'select' && props && props.multiple != null) {
9154 el.setAttribute('multiple', props.multiple);
9155 }
9156 return el;
9157 },
9158 createText: text => doc.createTextNode(text),
9159 createComment: text => doc.createComment(text),
9160 setText: (node, text) => {
9161 node.nodeValue = text;
9162 },
9163 setElementText: (el, text) => {
9164 el.textContent = text;
9165 },
9166 parentNode: node => node.parentNode,
9167 nextSibling: node => node.nextSibling,
9168 querySelector: selector => doc.querySelector(selector),
9169 setScopeId(el, id) {
9170 el.setAttribute(id, '');
9171 },
9172 cloneNode(el) {
9173 const cloned = el.cloneNode(true);
9174 // #3072
9175 // - in `patchDOMProp`, we store the actual value in the `el._value` property.
9176 // - normally, elements using `:value` bindings will not be hoisted, but if
9177 // the bound value is a constant, e.g. `:value="true"` - they do get
9178 // hoisted.
9179 // - in production, hoisted nodes are cloned when subsequent inserts, but
9180 // cloneNode() does not copy the custom property we attached.
9181 // - This may need to account for other custom DOM properties we attach to
9182 // elements in addition to `_value` in the future.
9183 if (`_value` in el) {
9184 cloned._value = el._value;
9185 }
9186 return cloned;
9187 },
9188 // __UNSAFE__
9189 // Reason: innerHTML.
9190 // Static content here can only come from compiled templates.
9191 // As long as the user only uses trusted templates, this is safe.
9192 insertStaticContent(content, parent, anchor, isSVG, start, end) {
9193 // <parent> before | first ... last | anchor </parent>
9194 const before = anchor ? anchor.previousSibling : parent.lastChild;
9195 // #5308 can only take cached path if:
9196 // - has a single root node
9197 // - nextSibling info is still available
9198 if (start && (start === end || start.nextSibling)) {
9199 // cached
9200 while (true) {
9201 parent.insertBefore(start.cloneNode(true), anchor);
9202 if (start === end || !(start = start.nextSibling))
9203 break;
9204 }
9205 }
9206 else {
9207 // fresh insert
9208 templateContainer.innerHTML = isSVG ? `<svg>${content}</svg>` : content;
9209 const template = templateContainer.content;
9210 if (isSVG) {
9211 // remove outer svg wrapper
9212 const wrapper = template.firstChild;
9213 while (wrapper.firstChild) {
9214 template.appendChild(wrapper.firstChild);
9215 }
9216 template.removeChild(wrapper);
9217 }
9218 parent.insertBefore(template, anchor);
9219 }
9220 return [
9221 // first
9222 before ? before.nextSibling : parent.firstChild,
9223 // last
9224 anchor ? anchor.previousSibling : parent.lastChild
9225 ];
9226 }
9227};
9228
9229// compiler should normalize class + :class bindings on the same element
9230// into a single binding ['staticClass', dynamic]
9231function patchClass(el, value, isSVG) {
9232 // directly setting className should be faster than setAttribute in theory
9233 // if this is an element during a transition, take the temporary transition
9234 // classes into account.
9235 const transitionClasses = el._vtc;
9236 if (transitionClasses) {
9237 value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(' ');
9238 }
9239 if (value == null) {
9240 el.removeAttribute('class');
9241 }
9242 else if (isSVG) {
9243 el.setAttribute('class', value);
9244 }
9245 else {
9246 el.className = value;
9247 }
9248}
9249
9250function patchStyle(el, prev, next) {
9251 const style = el.style;
9252 const isCssString = isString(next);
9253 if (next && !isCssString) {
9254 for (const key in next) {
9255 setStyle(style, key, next[key]);
9256 }
9257 if (prev && !isString(prev)) {
9258 for (const key in prev) {
9259 if (next[key] == null) {
9260 setStyle(style, key, '');
9261 }
9262 }
9263 }
9264 }
9265 else {
9266 const currentDisplay = style.display;
9267 if (isCssString) {
9268 if (prev !== next) {
9269 style.cssText = next;
9270 }
9271 }
9272 else if (prev) {
9273 el.removeAttribute('style');
9274 }
9275 // indicates that the `display` of the element is controlled by `v-show`,
9276 // so we always keep the current `display` value regardless of the `style`
9277 // value, thus handing over control to `v-show`.
9278 if ('_vod' in el) {
9279 style.display = currentDisplay;
9280 }
9281 }
9282}
9283const importantRE = /\s*!important$/;
9284function setStyle(style, name, val) {
9285 if (isArray(val)) {
9286 val.forEach(v => setStyle(style, name, v));
9287 }
9288 else {
9289 if (name.startsWith('--')) {
9290 // custom property definition
9291 style.setProperty(name, val);
9292 }
9293 else {
9294 const prefixed = autoPrefix(style, name);
9295 if (importantRE.test(val)) {
9296 // !important
9297 style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
9298 }
9299 else {
9300 style[prefixed] = val;
9301 }
9302 }
9303 }
9304}
9305const prefixes = ['Webkit', 'Moz', 'ms'];
9306const prefixCache = {};
9307function autoPrefix(style, rawName) {
9308 const cached = prefixCache[rawName];
9309 if (cached) {
9310 return cached;
9311 }
9312 let name = camelize(rawName);
9313 if (name !== 'filter' && name in style) {
9314 return (prefixCache[rawName] = name);
9315 }
9316 name = capitalize(name);
9317 for (let i = 0; i < prefixes.length; i++) {
9318 const prefixed = prefixes[i] + name;
9319 if (prefixed in style) {
9320 return (prefixCache[rawName] = prefixed);
9321 }
9322 }
9323 return rawName;
9324}
9325
9326const xlinkNS = 'http://www.w3.org/1999/xlink';
9327function patchAttr(el, key, value, isSVG, instance) {
9328 if (isSVG && key.startsWith('xlink:')) {
9329 if (value == null) {
9330 el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
9331 }
9332 else {
9333 el.setAttributeNS(xlinkNS, key, value);
9334 }
9335 }
9336 else {
9337 // note we are only checking boolean attributes that don't have a
9338 // corresponding dom prop of the same name here.
9339 const isBoolean = isSpecialBooleanAttr(key);
9340 if (value == null || (isBoolean && !includeBooleanAttr(value))) {
9341 el.removeAttribute(key);
9342 }
9343 else {
9344 el.setAttribute(key, isBoolean ? '' : value);
9345 }
9346 }
9347}
9348
9349// __UNSAFE__
9350// functions. The user is responsible for using them with only trusted content.
9351function patchDOMProp(el, key, value,
9352// the following args are passed only due to potential innerHTML/textContent
9353// overriding existing VNodes, in which case the old tree must be properly
9354// unmounted.
9355prevChildren, parentComponent, parentSuspense, unmountChildren) {
9356 if (key === 'innerHTML' || key === 'textContent') {
9357 if (prevChildren) {
9358 unmountChildren(prevChildren, parentComponent, parentSuspense);
9359 }
9360 el[key] = value == null ? '' : value;
9361 return;
9362 }
9363 if (key === 'value' &&
9364 el.tagName !== 'PROGRESS' &&
9365 // custom elements may use _value internally
9366 !el.tagName.includes('-')) {
9367 // store value as _value as well since
9368 // non-string values will be stringified.
9369 el._value = value;
9370 const newValue = value == null ? '' : value;
9371 if (el.value !== newValue ||
9372 // #4956: always set for OPTION elements because its value falls back to
9373 // textContent if no value attribute is present. And setting .value for
9374 // OPTION has no side effect
9375 el.tagName === 'OPTION') {
9376 el.value = newValue;
9377 }
9378 if (value == null) {
9379 el.removeAttribute(key);
9380 }
9381 return;
9382 }
9383 if (value === '' || value == null) {
9384 const type = typeof el[key];
9385 if (type === 'boolean') {
9386 // e.g. <select multiple> compiles to { multiple: '' }
9387 el[key] = includeBooleanAttr(value);
9388 return;
9389 }
9390 else if (value == null && type === 'string') {
9391 // e.g. <div :id="null">
9392 el[key] = '';
9393 el.removeAttribute(key);
9394 return;
9395 }
9396 else if (type === 'number') {
9397 // e.g. <img :width="null">
9398 // the value of some IDL attr must be greater than 0, e.g. input.size = 0 -> error
9399 try {
9400 el[key] = 0;
9401 }
9402 catch (_a) { }
9403 el.removeAttribute(key);
9404 return;
9405 }
9406 }
9407 // some properties perform value validation and throw
9408 try {
9409 el[key] = value;
9410 }
9411 catch (e) {
9412 {
9413 warn$1(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
9414 `value ${value} is invalid.`, e);
9415 }
9416 }
9417}
9418
9419// Async edge case fix requires storing an event listener's attach timestamp.
9420let _getNow = Date.now;
9421let skipTimestampCheck = false;
9422if (typeof window !== 'undefined') {
9423 // Determine what event timestamp the browser is using. Annoyingly, the
9424 // timestamp can either be hi-res (relative to page load) or low-res
9425 // (relative to UNIX epoch), so in order to compare time we have to use the
9426 // same timestamp type when saving the flush timestamp.
9427 if (_getNow() > document.createEvent('Event').timeStamp) {
9428 // if the low-res timestamp which is bigger than the event timestamp
9429 // (which is evaluated AFTER) it means the event is using a hi-res timestamp,
9430 // and we need to use the hi-res version for event listeners as well.
9431 _getNow = () => performance.now();
9432 }
9433 // #3485: Firefox <= 53 has incorrect Event.timeStamp implementation
9434 // and does not fire microtasks in between event propagation, so safe to exclude.
9435 const ffMatch = navigator.userAgent.match(/firefox\/(\d+)/i);
9436 skipTimestampCheck = !!(ffMatch && Number(ffMatch[1]) <= 53);
9437}
9438// To avoid the overhead of repeatedly calling performance.now(), we cache
9439// and use the same timestamp for all event listeners attached in the same tick.
9440let cachedNow = 0;
9441const p = Promise.resolve();
9442const reset = () => {
9443 cachedNow = 0;
9444};
9445const getNow = () => cachedNow || (p.then(reset), (cachedNow = _getNow()));
9446function addEventListener(el, event, handler, options) {
9447 el.addEventListener(event, handler, options);
9448}
9449function removeEventListener(el, event, handler, options) {
9450 el.removeEventListener(event, handler, options);
9451}
9452function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
9453 // vei = vue event invokers
9454 const invokers = el._vei || (el._vei = {});
9455 const existingInvoker = invokers[rawName];
9456 if (nextValue && existingInvoker) {
9457 // patch
9458 existingInvoker.value = nextValue;
9459 }
9460 else {
9461 const [name, options] = parseName(rawName);
9462 if (nextValue) {
9463 // add
9464 const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
9465 addEventListener(el, name, invoker, options);
9466 }
9467 else if (existingInvoker) {
9468 // remove
9469 removeEventListener(el, name, existingInvoker, options);
9470 invokers[rawName] = undefined;
9471 }
9472 }
9473}
9474const optionsModifierRE = /(?:Once|Passive|Capture)$/;
9475function parseName(name) {
9476 let options;
9477 if (optionsModifierRE.test(name)) {
9478 options = {};
9479 let m;
9480 while ((m = name.match(optionsModifierRE))) {
9481 name = name.slice(0, name.length - m[0].length);
9482 options[m[0].toLowerCase()] = true;
9483 }
9484 }
9485 return [hyphenate(name.slice(2)), options];
9486}
9487function createInvoker(initialValue, instance) {
9488 const invoker = (e) => {
9489 // async edge case #6566: inner click event triggers patch, event handler
9490 // attached to outer element during patch, and triggered again. This
9491 // happens because browsers fire microtask ticks between event propagation.
9492 // the solution is simple: we save the timestamp when a handler is attached,
9493 // and the handler would only fire if the event passed to it was fired
9494 // AFTER it was attached.
9495 const timeStamp = e.timeStamp || _getNow();
9496 if (skipTimestampCheck || timeStamp >= invoker.attached - 1) {
9497 callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* NATIVE_EVENT_HANDLER */, [e]);
9498 }
9499 };
9500 invoker.value = initialValue;
9501 invoker.attached = getNow();
9502 return invoker;
9503}
9504function patchStopImmediatePropagation(e, value) {
9505 if (isArray(value)) {
9506 const originalStop = e.stopImmediatePropagation;
9507 e.stopImmediatePropagation = () => {
9508 originalStop.call(e);
9509 e._stopped = true;
9510 };
9511 return value.map(fn => (e) => !e._stopped && fn && fn(e));
9512 }
9513 else {
9514 return value;
9515 }
9516}
9517
9518const nativeOnRE = /^on[a-z]/;
9519const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
9520 if (key === 'class') {
9521 patchClass(el, nextValue, isSVG);
9522 }
9523 else if (key === 'style') {
9524 patchStyle(el, prevValue, nextValue);
9525 }
9526 else if (isOn(key)) {
9527 // ignore v-model listeners
9528 if (!isModelListener(key)) {
9529 patchEvent(el, key, prevValue, nextValue, parentComponent);
9530 }
9531 }
9532 else if (key[0] === '.'
9533 ? ((key = key.slice(1)), true)
9534 : key[0] === '^'
9535 ? ((key = key.slice(1)), false)
9536 : shouldSetAsProp(el, key, nextValue, isSVG)) {
9537 patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
9538 }
9539 else {
9540 // special case for <input v-model type="checkbox"> with
9541 // :true-value & :false-value
9542 // store value as dom properties since non-string values will be
9543 // stringified.
9544 if (key === 'true-value') {
9545 el._trueValue = nextValue;
9546 }
9547 else if (key === 'false-value') {
9548 el._falseValue = nextValue;
9549 }
9550 patchAttr(el, key, nextValue, isSVG);
9551 }
9552};
9553function shouldSetAsProp(el, key, value, isSVG) {
9554 if (isSVG) {
9555 // most keys must be set as attribute on svg elements to work
9556 // ...except innerHTML & textContent
9557 if (key === 'innerHTML' || key === 'textContent') {
9558 return true;
9559 }
9560 // or native onclick with function values
9561 if (key in el && nativeOnRE.test(key) && isFunction(value)) {
9562 return true;
9563 }
9564 return false;
9565 }
9566 // spellcheck and draggable are numerated attrs, however their
9567 // corresponding DOM properties are actually booleans - this leads to
9568 // setting it with a string "false" value leading it to be coerced to
9569 // `true`, so we need to always treat them as attributes.
9570 // Note that `contentEditable` doesn't have this problem: its DOM
9571 // property is also enumerated string values.
9572 if (key === 'spellcheck' || key === 'draggable') {
9573 return false;
9574 }
9575 // #1787, #2840 form property on form elements is readonly and must be set as
9576 // attribute.
9577 if (key === 'form') {
9578 return false;
9579 }
9580 // #1526 <input list> must be set as attribute
9581 if (key === 'list' && el.tagName === 'INPUT') {
9582 return false;
9583 }
9584 // #2766 <textarea type> must be set as attribute
9585 if (key === 'type' && el.tagName === 'TEXTAREA') {
9586 return false;
9587 }
9588 // native onclick with string value, must be set as attribute
9589 if (nativeOnRE.test(key) && isString(value)) {
9590 return false;
9591 }
9592 return key in el;
9593}
9594
9595function defineCustomElement(options, hydate) {
9596 const Comp = defineComponent(options);
9597 class VueCustomElement extends VueElement {
9598 constructor(initialProps) {
9599 super(Comp, initialProps, hydate);
9600 }
9601 }
9602 VueCustomElement.def = Comp;
9603 return VueCustomElement;
9604}
9605const defineSSRCustomElement = ((options) => {
9606 // @ts-ignore
9607 return defineCustomElement(options, hydrate);
9608});
9609const BaseClass = (typeof HTMLElement !== 'undefined' ? HTMLElement : class {
9610});
9611class VueElement extends BaseClass {
9612 constructor(_def, _props = {}, hydrate) {
9613 super();
9614 this._def = _def;
9615 this._props = _props;
9616 /**
9617 * @internal
9618 */
9619 this._instance = null;
9620 this._connected = false;
9621 this._resolved = false;
9622 this._numberProps = null;
9623 if (this.shadowRoot && hydrate) {
9624 hydrate(this._createVNode(), this.shadowRoot);
9625 }
9626 else {
9627 if (this.shadowRoot) {
9628 warn$1(`Custom element has pre-rendered declarative shadow root but is not ` +
9629 `defined as hydratable. Use \`defineSSRCustomElement\`.`);
9630 }
9631 this.attachShadow({ mode: 'open' });
9632 }
9633 }
9634 connectedCallback() {
9635 this._connected = true;
9636 if (!this._instance) {
9637 this._resolveDef();
9638 }
9639 }
9640 disconnectedCallback() {
9641 this._connected = false;
9642 nextTick(() => {
9643 if (!this._connected) {
9644 render(null, this.shadowRoot);
9645 this._instance = null;
9646 }
9647 });
9648 }
9649 /**
9650 * resolve inner component definition (handle possible async component)
9651 */
9652 _resolveDef() {
9653 if (this._resolved) {
9654 return;
9655 }
9656 this._resolved = true;
9657 // set initial attrs
9658 for (let i = 0; i < this.attributes.length; i++) {
9659 this._setAttr(this.attributes[i].name);
9660 }
9661 // watch future attr changes
9662 new MutationObserver(mutations => {
9663 for (const m of mutations) {
9664 this._setAttr(m.attributeName);
9665 }
9666 }).observe(this, { attributes: true });
9667 const resolve = (def) => {
9668 const { props, styles } = def;
9669 const hasOptions = !isArray(props);
9670 const rawKeys = props ? (hasOptions ? Object.keys(props) : props) : [];
9671 // cast Number-type props set before resolve
9672 let numberProps;
9673 if (hasOptions) {
9674 for (const key in this._props) {
9675 const opt = props[key];
9676 if (opt === Number || (opt && opt.type === Number)) {
9677 this._props[key] = toNumber(this._props[key]);
9678 (numberProps || (numberProps = Object.create(null)))[key] = true;
9679 }
9680 }
9681 }
9682 this._numberProps = numberProps;
9683 // check if there are props set pre-upgrade or connect
9684 for (const key of Object.keys(this)) {
9685 if (key[0] !== '_') {
9686 this._setProp(key, this[key], true, false);
9687 }
9688 }
9689 // defining getter/setters on prototype
9690 for (const key of rawKeys.map(camelize)) {
9691 Object.defineProperty(this, key, {
9692 get() {
9693 return this._getProp(key);
9694 },
9695 set(val) {
9696 this._setProp(key, val);
9697 }
9698 });
9699 }
9700 // apply CSS
9701 this._applyStyles(styles);
9702 // initial render
9703 this._update();
9704 };
9705 const asyncDef = this._def.__asyncLoader;
9706 if (asyncDef) {
9707 asyncDef().then(resolve);
9708 }
9709 else {
9710 resolve(this._def);
9711 }
9712 }
9713 _setAttr(key) {
9714 let value = this.getAttribute(key);
9715 if (this._numberProps && this._numberProps[key]) {
9716 value = toNumber(value);
9717 }
9718 this._setProp(camelize(key), value, false);
9719 }
9720 /**
9721 * @internal
9722 */
9723 _getProp(key) {
9724 return this._props[key];
9725 }
9726 /**
9727 * @internal
9728 */
9729 _setProp(key, val, shouldReflect = true, shouldUpdate = true) {
9730 if (val !== this._props[key]) {
9731 this._props[key] = val;
9732 if (shouldUpdate && this._instance) {
9733 this._update();
9734 }
9735 // reflect
9736 if (shouldReflect) {
9737 if (val === true) {
9738 this.setAttribute(hyphenate(key), '');
9739 }
9740 else if (typeof val === 'string' || typeof val === 'number') {
9741 this.setAttribute(hyphenate(key), val + '');
9742 }
9743 else if (!val) {
9744 this.removeAttribute(hyphenate(key));
9745 }
9746 }
9747 }
9748 }
9749 _update() {
9750 render(this._createVNode(), this.shadowRoot);
9751 }
9752 _createVNode() {
9753 const vnode = createVNode(this._def, extend({}, this._props));
9754 if (!this._instance) {
9755 vnode.ce = instance => {
9756 this._instance = instance;
9757 instance.isCE = true;
9758 // HMR
9759 {
9760 instance.ceReload = newStyles => {
9761 // always reset styles
9762 if (this._styles) {
9763 this._styles.forEach(s => this.shadowRoot.removeChild(s));
9764 this._styles.length = 0;
9765 }
9766 this._applyStyles(newStyles);
9767 // if this is an async component, ceReload is called from the inner
9768 // component so no need to reload the async wrapper
9769 if (!this._def.__asyncLoader) {
9770 // reload
9771 this._instance = null;
9772 this._update();
9773 }
9774 };
9775 }
9776 // intercept emit
9777 instance.emit = (event, ...args) => {
9778 this.dispatchEvent(new CustomEvent(event, {
9779 detail: args
9780 }));
9781 };
9782 // locate nearest Vue custom element parent for provide/inject
9783 let parent = this;
9784 while ((parent =
9785 parent && (parent.parentNode || parent.host))) {
9786 if (parent instanceof VueElement) {
9787 instance.parent = parent._instance;
9788 break;
9789 }
9790 }
9791 };
9792 }
9793 return vnode;
9794 }
9795 _applyStyles(styles) {
9796 if (styles) {
9797 styles.forEach(css => {
9798 const s = document.createElement('style');
9799 s.textContent = css;
9800 this.shadowRoot.appendChild(s);
9801 // record for HMR
9802 {
9803 (this._styles || (this._styles = [])).push(s);
9804 }
9805 });
9806 }
9807 }
9808}
9809
9810function useCssModule(name = '$style') {
9811 /* istanbul ignore else */
9812 {
9813 const instance = getCurrentInstance();
9814 if (!instance) {
9815 warn$1(`useCssModule must be called inside setup()`);
9816 return EMPTY_OBJ;
9817 }
9818 const modules = instance.type.__cssModules;
9819 if (!modules) {
9820 warn$1(`Current instance does not have CSS modules injected.`);
9821 return EMPTY_OBJ;
9822 }
9823 const mod = modules[name];
9824 if (!mod) {
9825 warn$1(`Current instance does not have CSS module named "${name}".`);
9826 return EMPTY_OBJ;
9827 }
9828 return mod;
9829 }
9830}
9831
9832/**
9833 * Runtime helper for SFC's CSS variable injection feature.
9834 * @private
9835 */
9836function useCssVars(getter) {
9837 const instance = getCurrentInstance();
9838 /* istanbul ignore next */
9839 if (!instance) {
9840 warn$1(`useCssVars is called without current active component instance.`);
9841 return;
9842 }
9843 const setVars = () => setVarsOnVNode(instance.subTree, getter(instance.proxy));
9844 watchPostEffect(setVars);
9845 onMounted(() => {
9846 const ob = new MutationObserver(setVars);
9847 ob.observe(instance.subTree.el.parentNode, { childList: true });
9848 onUnmounted(() => ob.disconnect());
9849 });
9850}
9851function setVarsOnVNode(vnode, vars) {
9852 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
9853 const suspense = vnode.suspense;
9854 vnode = suspense.activeBranch;
9855 if (suspense.pendingBranch && !suspense.isHydrating) {
9856 suspense.effects.push(() => {
9857 setVarsOnVNode(suspense.activeBranch, vars);
9858 });
9859 }
9860 }
9861 // drill down HOCs until it's a non-component vnode
9862 while (vnode.component) {
9863 vnode = vnode.component.subTree;
9864 }
9865 if (vnode.shapeFlag & 1 /* ELEMENT */ && vnode.el) {
9866 setVarsOnNode(vnode.el, vars);
9867 }
9868 else if (vnode.type === Fragment) {
9869 vnode.children.forEach(c => setVarsOnVNode(c, vars));
9870 }
9871 else if (vnode.type === Static) {
9872 let { el, anchor } = vnode;
9873 while (el) {
9874 setVarsOnNode(el, vars);
9875 if (el === anchor)
9876 break;
9877 el = el.nextSibling;
9878 }
9879 }
9880}
9881function setVarsOnNode(el, vars) {
9882 if (el.nodeType === 1) {
9883 const style = el.style;
9884 for (const key in vars) {
9885 style.setProperty(`--${key}`, vars[key]);
9886 }
9887 }
9888}
9889
9890const TRANSITION = 'transition';
9891const ANIMATION = 'animation';
9892// DOM Transition is a higher-order-component based on the platform-agnostic
9893// base Transition component, with DOM-specific logic.
9894const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
9895Transition.displayName = 'Transition';
9896const DOMTransitionPropsValidators = {
9897 name: String,
9898 type: String,
9899 css: {
9900 type: Boolean,
9901 default: true
9902 },
9903 duration: [String, Number, Object],
9904 enterFromClass: String,
9905 enterActiveClass: String,
9906 enterToClass: String,
9907 appearFromClass: String,
9908 appearActiveClass: String,
9909 appearToClass: String,
9910 leaveFromClass: String,
9911 leaveActiveClass: String,
9912 leaveToClass: String
9913};
9914const TransitionPropsValidators = (Transition.props =
9915 /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
9916/**
9917 * #3227 Incoming hooks may be merged into arrays when wrapping Transition
9918 * with custom HOCs.
9919 */
9920const callHook$1 = (hook, args = []) => {
9921 if (isArray(hook)) {
9922 hook.forEach(h => h(...args));
9923 }
9924 else if (hook) {
9925 hook(...args);
9926 }
9927};
9928/**
9929 * Check if a hook expects a callback (2nd arg), which means the user
9930 * intends to explicitly control the end of the transition.
9931 */
9932const hasExplicitCallback = (hook) => {
9933 return hook
9934 ? isArray(hook)
9935 ? hook.some(h => h.length > 1)
9936 : hook.length > 1
9937 : false;
9938};
9939function resolveTransitionProps(rawProps) {
9940 const baseProps = {};
9941 for (const key in rawProps) {
9942 if (!(key in DOMTransitionPropsValidators)) {
9943 baseProps[key] = rawProps[key];
9944 }
9945 }
9946 if (rawProps.css === false) {
9947 return baseProps;
9948 }
9949 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;
9950 const durations = normalizeDuration(duration);
9951 const enterDuration = durations && durations[0];
9952 const leaveDuration = durations && durations[1];
9953 const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
9954 const finishEnter = (el, isAppear, done) => {
9955 removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
9956 removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
9957 done && done();
9958 };
9959 const finishLeave = (el, done) => {
9960 removeTransitionClass(el, leaveToClass);
9961 removeTransitionClass(el, leaveActiveClass);
9962 done && done();
9963 };
9964 const makeEnterHook = (isAppear) => {
9965 return (el, done) => {
9966 const hook = isAppear ? onAppear : onEnter;
9967 const resolve = () => finishEnter(el, isAppear, done);
9968 callHook$1(hook, [el, resolve]);
9969 nextFrame(() => {
9970 removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
9971 addTransitionClass(el, isAppear ? appearToClass : enterToClass);
9972 if (!hasExplicitCallback(hook)) {
9973 whenTransitionEnds(el, type, enterDuration, resolve);
9974 }
9975 });
9976 };
9977 };
9978 return extend(baseProps, {
9979 onBeforeEnter(el) {
9980 callHook$1(onBeforeEnter, [el]);
9981 addTransitionClass(el, enterFromClass);
9982 addTransitionClass(el, enterActiveClass);
9983 },
9984 onBeforeAppear(el) {
9985 callHook$1(onBeforeAppear, [el]);
9986 addTransitionClass(el, appearFromClass);
9987 addTransitionClass(el, appearActiveClass);
9988 },
9989 onEnter: makeEnterHook(false),
9990 onAppear: makeEnterHook(true),
9991 onLeave(el, done) {
9992 const resolve = () => finishLeave(el, done);
9993 addTransitionClass(el, leaveFromClass);
9994 // force reflow so *-leave-from classes immediately take effect (#2593)
9995 forceReflow();
9996 addTransitionClass(el, leaveActiveClass);
9997 nextFrame(() => {
9998 removeTransitionClass(el, leaveFromClass);
9999 addTransitionClass(el, leaveToClass);
10000 if (!hasExplicitCallback(onLeave)) {
10001 whenTransitionEnds(el, type, leaveDuration, resolve);
10002 }
10003 });
10004 callHook$1(onLeave, [el, resolve]);
10005 },
10006 onEnterCancelled(el) {
10007 finishEnter(el, false);
10008 callHook$1(onEnterCancelled, [el]);
10009 },
10010 onAppearCancelled(el) {
10011 finishEnter(el, true);
10012 callHook$1(onAppearCancelled, [el]);
10013 },
10014 onLeaveCancelled(el) {
10015 finishLeave(el);
10016 callHook$1(onLeaveCancelled, [el]);
10017 }
10018 });
10019}
10020function normalizeDuration(duration) {
10021 if (duration == null) {
10022 return null;
10023 }
10024 else if (isObject(duration)) {
10025 return [NumberOf(duration.enter), NumberOf(duration.leave)];
10026 }
10027 else {
10028 const n = NumberOf(duration);
10029 return [n, n];
10030 }
10031}
10032function NumberOf(val) {
10033 const res = toNumber(val);
10034 validateDuration(res);
10035 return res;
10036}
10037function validateDuration(val) {
10038 if (typeof val !== 'number') {
10039 warn$1(`<transition> explicit duration is not a valid number - ` +
10040 `got ${JSON.stringify(val)}.`);
10041 }
10042 else if (isNaN(val)) {
10043 warn$1(`<transition> explicit duration is NaN - ` +
10044 'the duration expression might be incorrect.');
10045 }
10046}
10047function addTransitionClass(el, cls) {
10048 cls.split(/\s+/).forEach(c => c && el.classList.add(c));
10049 (el._vtc ||
10050 (el._vtc = new Set())).add(cls);
10051}
10052function removeTransitionClass(el, cls) {
10053 cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
10054 const { _vtc } = el;
10055 if (_vtc) {
10056 _vtc.delete(cls);
10057 if (!_vtc.size) {
10058 el._vtc = undefined;
10059 }
10060 }
10061}
10062function nextFrame(cb) {
10063 requestAnimationFrame(() => {
10064 requestAnimationFrame(cb);
10065 });
10066}
10067let endId = 0;
10068function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
10069 const id = (el._endId = ++endId);
10070 const resolveIfNotStale = () => {
10071 if (id === el._endId) {
10072 resolve();
10073 }
10074 };
10075 if (explicitTimeout) {
10076 return setTimeout(resolveIfNotStale, explicitTimeout);
10077 }
10078 const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
10079 if (!type) {
10080 return resolve();
10081 }
10082 const endEvent = type + 'end';
10083 let ended = 0;
10084 const end = () => {
10085 el.removeEventListener(endEvent, onEnd);
10086 resolveIfNotStale();
10087 };
10088 const onEnd = (e) => {
10089 if (e.target === el && ++ended >= propCount) {
10090 end();
10091 }
10092 };
10093 setTimeout(() => {
10094 if (ended < propCount) {
10095 end();
10096 }
10097 }, timeout + 1);
10098 el.addEventListener(endEvent, onEnd);
10099}
10100function getTransitionInfo(el, expectedType) {
10101 const styles = window.getComputedStyle(el);
10102 // JSDOM may return undefined for transition properties
10103 const getStyleProperties = (key) => (styles[key] || '').split(', ');
10104 const transitionDelays = getStyleProperties(TRANSITION + 'Delay');
10105 const transitionDurations = getStyleProperties(TRANSITION + 'Duration');
10106 const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
10107 const animationDelays = getStyleProperties(ANIMATION + 'Delay');
10108 const animationDurations = getStyleProperties(ANIMATION + 'Duration');
10109 const animationTimeout = getTimeout(animationDelays, animationDurations);
10110 let type = null;
10111 let timeout = 0;
10112 let propCount = 0;
10113 /* istanbul ignore if */
10114 if (expectedType === TRANSITION) {
10115 if (transitionTimeout > 0) {
10116 type = TRANSITION;
10117 timeout = transitionTimeout;
10118 propCount = transitionDurations.length;
10119 }
10120 }
10121 else if (expectedType === ANIMATION) {
10122 if (animationTimeout > 0) {
10123 type = ANIMATION;
10124 timeout = animationTimeout;
10125 propCount = animationDurations.length;
10126 }
10127 }
10128 else {
10129 timeout = Math.max(transitionTimeout, animationTimeout);
10130 type =
10131 timeout > 0
10132 ? transitionTimeout > animationTimeout
10133 ? TRANSITION
10134 : ANIMATION
10135 : null;
10136 propCount = type
10137 ? type === TRANSITION
10138 ? transitionDurations.length
10139 : animationDurations.length
10140 : 0;
10141 }
10142 const hasTransform = type === TRANSITION &&
10143 /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']);
10144 return {
10145 type,
10146 timeout,
10147 propCount,
10148 hasTransform
10149 };
10150}
10151function getTimeout(delays, durations) {
10152 while (delays.length < durations.length) {
10153 delays = delays.concat(delays);
10154 }
10155 return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
10156}
10157// Old versions of Chromium (below 61.0.3163.100) formats floating pointer
10158// numbers in a locale-dependent way, using a comma instead of a dot.
10159// If comma is not replaced with a dot, the input will be rounded down
10160// (i.e. acting as a floor function) causing unexpected behaviors
10161function toMs(s) {
10162 return Number(s.slice(0, -1).replace(',', '.')) * 1000;
10163}
10164// synchronously force layout to put elements into a certain state
10165function forceReflow() {
10166 return document.body.offsetHeight;
10167}
10168
10169const positionMap = new WeakMap();
10170const newPositionMap = new WeakMap();
10171const TransitionGroupImpl = {
10172 name: 'TransitionGroup',
10173 props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
10174 tag: String,
10175 moveClass: String
10176 }),
10177 setup(props, { slots }) {
10178 const instance = getCurrentInstance();
10179 const state = useTransitionState();
10180 let prevChildren;
10181 let children;
10182 onUpdated(() => {
10183 // children is guaranteed to exist after initial render
10184 if (!prevChildren.length) {
10185 return;
10186 }
10187 const moveClass = props.moveClass || `${props.name || 'v'}-move`;
10188 if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
10189 return;
10190 }
10191 // we divide the work into three loops to avoid mixing DOM reads and writes
10192 // in each iteration - which helps prevent layout thrashing.
10193 prevChildren.forEach(callPendingCbs);
10194 prevChildren.forEach(recordPosition);
10195 const movedChildren = prevChildren.filter(applyTranslation);
10196 // force reflow to put everything in position
10197 forceReflow();
10198 movedChildren.forEach(c => {
10199 const el = c.el;
10200 const style = el.style;
10201 addTransitionClass(el, moveClass);
10202 style.transform = style.webkitTransform = style.transitionDuration = '';
10203 const cb = (el._moveCb = (e) => {
10204 if (e && e.target !== el) {
10205 return;
10206 }
10207 if (!e || /transform$/.test(e.propertyName)) {
10208 el.removeEventListener('transitionend', cb);
10209 el._moveCb = null;
10210 removeTransitionClass(el, moveClass);
10211 }
10212 });
10213 el.addEventListener('transitionend', cb);
10214 });
10215 });
10216 return () => {
10217 const rawProps = toRaw(props);
10218 const cssTransitionProps = resolveTransitionProps(rawProps);
10219 let tag = rawProps.tag || Fragment;
10220 prevChildren = children;
10221 children = slots.default ? getTransitionRawChildren(slots.default()) : [];
10222 for (let i = 0; i < children.length; i++) {
10223 const child = children[i];
10224 if (child.key != null) {
10225 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
10226 }
10227 else {
10228 warn$1(`<TransitionGroup> children must be keyed.`);
10229 }
10230 }
10231 if (prevChildren) {
10232 for (let i = 0; i < prevChildren.length; i++) {
10233 const child = prevChildren[i];
10234 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
10235 positionMap.set(child, child.el.getBoundingClientRect());
10236 }
10237 }
10238 return createVNode(tag, null, children);
10239 };
10240 }
10241};
10242const TransitionGroup = TransitionGroupImpl;
10243function callPendingCbs(c) {
10244 const el = c.el;
10245 if (el._moveCb) {
10246 el._moveCb();
10247 }
10248 if (el._enterCb) {
10249 el._enterCb();
10250 }
10251}
10252function recordPosition(c) {
10253 newPositionMap.set(c, c.el.getBoundingClientRect());
10254}
10255function applyTranslation(c) {
10256 const oldPos = positionMap.get(c);
10257 const newPos = newPositionMap.get(c);
10258 const dx = oldPos.left - newPos.left;
10259 const dy = oldPos.top - newPos.top;
10260 if (dx || dy) {
10261 const s = c.el.style;
10262 s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
10263 s.transitionDuration = '0s';
10264 return c;
10265 }
10266}
10267function hasCSSTransform(el, root, moveClass) {
10268 // Detect whether an element with the move class applied has
10269 // CSS transitions. Since the element may be inside an entering
10270 // transition at this very moment, we make a clone of it and remove
10271 // all other transition classes applied to ensure only the move class
10272 // is applied.
10273 const clone = el.cloneNode();
10274 if (el._vtc) {
10275 el._vtc.forEach(cls => {
10276 cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
10277 });
10278 }
10279 moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
10280 clone.style.display = 'none';
10281 const container = (root.nodeType === 1 ? root : root.parentNode);
10282 container.appendChild(clone);
10283 const { hasTransform } = getTransitionInfo(clone);
10284 container.removeChild(clone);
10285 return hasTransform;
10286}
10287
10288const getModelAssigner = (vnode) => {
10289 const fn = vnode.props['onUpdate:modelValue'];
10290 return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
10291};
10292function onCompositionStart(e) {
10293 e.target.composing = true;
10294}
10295function onCompositionEnd(e) {
10296 const target = e.target;
10297 if (target.composing) {
10298 target.composing = false;
10299 trigger$1(target, 'input');
10300 }
10301}
10302function trigger$1(el, type) {
10303 const e = document.createEvent('HTMLEvents');
10304 e.initEvent(type, true, true);
10305 el.dispatchEvent(e);
10306}
10307// We are exporting the v-model runtime directly as vnode hooks so that it can
10308// be tree-shaken in case v-model is never used.
10309const vModelText = {
10310 created(el, { modifiers: { lazy, trim, number } }, vnode) {
10311 el._assign = getModelAssigner(vnode);
10312 const castToNumber = number || (vnode.props && vnode.props.type === 'number');
10313 addEventListener(el, lazy ? 'change' : 'input', e => {
10314 if (e.target.composing)
10315 return;
10316 let domValue = el.value;
10317 if (trim) {
10318 domValue = domValue.trim();
10319 }
10320 else if (castToNumber) {
10321 domValue = toNumber(domValue);
10322 }
10323 el._assign(domValue);
10324 });
10325 if (trim) {
10326 addEventListener(el, 'change', () => {
10327 el.value = el.value.trim();
10328 });
10329 }
10330 if (!lazy) {
10331 addEventListener(el, 'compositionstart', onCompositionStart);
10332 addEventListener(el, 'compositionend', onCompositionEnd);
10333 // Safari < 10.2 & UIWebView doesn't fire compositionend when
10334 // switching focus before confirming composition choice
10335 // this also fixes the issue where some browsers e.g. iOS Chrome
10336 // fires "change" instead of "input" on autocomplete.
10337 addEventListener(el, 'change', onCompositionEnd);
10338 }
10339 },
10340 // set value on mounted so it's after min/max for type="range"
10341 mounted(el, { value }) {
10342 el.value = value == null ? '' : value;
10343 },
10344 beforeUpdate(el, { value, modifiers: { lazy, trim, number } }, vnode) {
10345 el._assign = getModelAssigner(vnode);
10346 // avoid clearing unresolved text. #2302
10347 if (el.composing)
10348 return;
10349 if (document.activeElement === el) {
10350 if (lazy) {
10351 return;
10352 }
10353 if (trim && el.value.trim() === value) {
10354 return;
10355 }
10356 if ((number || el.type === 'number') && toNumber(el.value) === value) {
10357 return;
10358 }
10359 }
10360 const newValue = value == null ? '' : value;
10361 if (el.value !== newValue) {
10362 el.value = newValue;
10363 }
10364 }
10365};
10366const vModelCheckbox = {
10367 // #4096 array checkboxes need to be deep traversed
10368 deep: true,
10369 created(el, _, vnode) {
10370 el._assign = getModelAssigner(vnode);
10371 addEventListener(el, 'change', () => {
10372 const modelValue = el._modelValue;
10373 const elementValue = getValue(el);
10374 const checked = el.checked;
10375 const assign = el._assign;
10376 if (isArray(modelValue)) {
10377 const index = looseIndexOf(modelValue, elementValue);
10378 const found = index !== -1;
10379 if (checked && !found) {
10380 assign(modelValue.concat(elementValue));
10381 }
10382 else if (!checked && found) {
10383 const filtered = [...modelValue];
10384 filtered.splice(index, 1);
10385 assign(filtered);
10386 }
10387 }
10388 else if (isSet(modelValue)) {
10389 const cloned = new Set(modelValue);
10390 if (checked) {
10391 cloned.add(elementValue);
10392 }
10393 else {
10394 cloned.delete(elementValue);
10395 }
10396 assign(cloned);
10397 }
10398 else {
10399 assign(getCheckboxValue(el, checked));
10400 }
10401 });
10402 },
10403 // set initial checked on mount to wait for true-value/false-value
10404 mounted: setChecked,
10405 beforeUpdate(el, binding, vnode) {
10406 el._assign = getModelAssigner(vnode);
10407 setChecked(el, binding, vnode);
10408 }
10409};
10410function setChecked(el, { value, oldValue }, vnode) {
10411 el._modelValue = value;
10412 if (isArray(value)) {
10413 el.checked = looseIndexOf(value, vnode.props.value) > -1;
10414 }
10415 else if (isSet(value)) {
10416 el.checked = value.has(vnode.props.value);
10417 }
10418 else if (value !== oldValue) {
10419 el.checked = looseEqual(value, getCheckboxValue(el, true));
10420 }
10421}
10422const vModelRadio = {
10423 created(el, { value }, vnode) {
10424 el.checked = looseEqual(value, vnode.props.value);
10425 el._assign = getModelAssigner(vnode);
10426 addEventListener(el, 'change', () => {
10427 el._assign(getValue(el));
10428 });
10429 },
10430 beforeUpdate(el, { value, oldValue }, vnode) {
10431 el._assign = getModelAssigner(vnode);
10432 if (value !== oldValue) {
10433 el.checked = looseEqual(value, vnode.props.value);
10434 }
10435 }
10436};
10437const vModelSelect = {
10438 // <select multiple> value need to be deep traversed
10439 deep: true,
10440 created(el, { value, modifiers: { number } }, vnode) {
10441 const isSetModel = isSet(value);
10442 addEventListener(el, 'change', () => {
10443 const selectedVal = Array.prototype.filter
10444 .call(el.options, (o) => o.selected)
10445 .map((o) => number ? toNumber(getValue(o)) : getValue(o));
10446 el._assign(el.multiple
10447 ? isSetModel
10448 ? new Set(selectedVal)
10449 : selectedVal
10450 : selectedVal[0]);
10451 });
10452 el._assign = getModelAssigner(vnode);
10453 },
10454 // set value in mounted & updated because <select> relies on its children
10455 // <option>s.
10456 mounted(el, { value }) {
10457 setSelected(el, value);
10458 },
10459 beforeUpdate(el, _binding, vnode) {
10460 el._assign = getModelAssigner(vnode);
10461 },
10462 updated(el, { value }) {
10463 setSelected(el, value);
10464 }
10465};
10466function setSelected(el, value) {
10467 const isMultiple = el.multiple;
10468 if (isMultiple && !isArray(value) && !isSet(value)) {
10469 warn$1(`<select multiple v-model> expects an Array or Set value for its binding, ` +
10470 `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
10471 return;
10472 }
10473 for (let i = 0, l = el.options.length; i < l; i++) {
10474 const option = el.options[i];
10475 const optionValue = getValue(option);
10476 if (isMultiple) {
10477 if (isArray(value)) {
10478 option.selected = looseIndexOf(value, optionValue) > -1;
10479 }
10480 else {
10481 option.selected = value.has(optionValue);
10482 }
10483 }
10484 else {
10485 if (looseEqual(getValue(option), value)) {
10486 if (el.selectedIndex !== i)
10487 el.selectedIndex = i;
10488 return;
10489 }
10490 }
10491 }
10492 if (!isMultiple && el.selectedIndex !== -1) {
10493 el.selectedIndex = -1;
10494 }
10495}
10496// retrieve raw value set via :value bindings
10497function getValue(el) {
10498 return '_value' in el ? el._value : el.value;
10499}
10500// retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
10501function getCheckboxValue(el, checked) {
10502 const key = checked ? '_trueValue' : '_falseValue';
10503 return key in el ? el[key] : checked;
10504}
10505const vModelDynamic = {
10506 created(el, binding, vnode) {
10507 callModelHook(el, binding, vnode, null, 'created');
10508 },
10509 mounted(el, binding, vnode) {
10510 callModelHook(el, binding, vnode, null, 'mounted');
10511 },
10512 beforeUpdate(el, binding, vnode, prevVNode) {
10513 callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
10514 },
10515 updated(el, binding, vnode, prevVNode) {
10516 callModelHook(el, binding, vnode, prevVNode, 'updated');
10517 }
10518};
10519function callModelHook(el, binding, vnode, prevVNode, hook) {
10520 let modelToUse;
10521 switch (el.tagName) {
10522 case 'SELECT':
10523 modelToUse = vModelSelect;
10524 break;
10525 case 'TEXTAREA':
10526 modelToUse = vModelText;
10527 break;
10528 default:
10529 switch (vnode.props && vnode.props.type) {
10530 case 'checkbox':
10531 modelToUse = vModelCheckbox;
10532 break;
10533 case 'radio':
10534 modelToUse = vModelRadio;
10535 break;
10536 default:
10537 modelToUse = vModelText;
10538 }
10539 }
10540 const fn = modelToUse[hook];
10541 fn && fn(el, binding, vnode, prevVNode);
10542}
10543
10544const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
10545const modifierGuards = {
10546 stop: e => e.stopPropagation(),
10547 prevent: e => e.preventDefault(),
10548 self: e => e.target !== e.currentTarget,
10549 ctrl: e => !e.ctrlKey,
10550 shift: e => !e.shiftKey,
10551 alt: e => !e.altKey,
10552 meta: e => !e.metaKey,
10553 left: e => 'button' in e && e.button !== 0,
10554 middle: e => 'button' in e && e.button !== 1,
10555 right: e => 'button' in e && e.button !== 2,
10556 exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
10557};
10558/**
10559 * @private
10560 */
10561const withModifiers = (fn, modifiers) => {
10562 return (event, ...args) => {
10563 for (let i = 0; i < modifiers.length; i++) {
10564 const guard = modifierGuards[modifiers[i]];
10565 if (guard && guard(event, modifiers))
10566 return;
10567 }
10568 return fn(event, ...args);
10569 };
10570};
10571// Kept for 2.x compat.
10572// Note: IE11 compat for `spacebar` and `del` is removed for now.
10573const keyNames = {
10574 esc: 'escape',
10575 space: ' ',
10576 up: 'arrow-up',
10577 left: 'arrow-left',
10578 right: 'arrow-right',
10579 down: 'arrow-down',
10580 delete: 'backspace'
10581};
10582/**
10583 * @private
10584 */
10585const withKeys = (fn, modifiers) => {
10586 return (event) => {
10587 if (!('key' in event)) {
10588 return;
10589 }
10590 const eventKey = hyphenate(event.key);
10591 if (modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
10592 return fn(event);
10593 }
10594 };
10595};
10596
10597const vShow = {
10598 beforeMount(el, { value }, { transition }) {
10599 el._vod = el.style.display === 'none' ? '' : el.style.display;
10600 if (transition && value) {
10601 transition.beforeEnter(el);
10602 }
10603 else {
10604 setDisplay(el, value);
10605 }
10606 },
10607 mounted(el, { value }, { transition }) {
10608 if (transition && value) {
10609 transition.enter(el);
10610 }
10611 },
10612 updated(el, { value, oldValue }, { transition }) {
10613 if (!value === !oldValue)
10614 return;
10615 if (transition) {
10616 if (value) {
10617 transition.beforeEnter(el);
10618 setDisplay(el, true);
10619 transition.enter(el);
10620 }
10621 else {
10622 transition.leave(el, () => {
10623 setDisplay(el, false);
10624 });
10625 }
10626 }
10627 else {
10628 setDisplay(el, value);
10629 }
10630 },
10631 beforeUnmount(el, { value }) {
10632 setDisplay(el, value);
10633 }
10634};
10635function setDisplay(el, value) {
10636 el.style.display = value ? el._vod : 'none';
10637}
10638
10639const rendererOptions = extend({ patchProp }, nodeOps);
10640// lazy create the renderer - this makes core renderer logic tree-shakable
10641// in case the user only imports reactivity utilities from Vue.
10642let renderer;
10643let enabledHydration = false;
10644function ensureRenderer() {
10645 return (renderer ||
10646 (renderer = createRenderer(rendererOptions)));
10647}
10648function ensureHydrationRenderer() {
10649 renderer = enabledHydration
10650 ? renderer
10651 : createHydrationRenderer(rendererOptions);
10652 enabledHydration = true;
10653 return renderer;
10654}
10655// use explicit type casts here to avoid import() calls in rolled-up d.ts
10656const render = ((...args) => {
10657 ensureRenderer().render(...args);
10658});
10659const hydrate = ((...args) => {
10660 ensureHydrationRenderer().hydrate(...args);
10661});
10662const createApp = ((...args) => {
10663 const app = ensureRenderer().createApp(...args);
10664 {
10665 injectNativeTagCheck(app);
10666 injectCompilerOptionsCheck(app);
10667 }
10668 const { mount } = app;
10669 app.mount = (containerOrSelector) => {
10670 const container = normalizeContainer(containerOrSelector);
10671 if (!container)
10672 return;
10673 const component = app._component;
10674 if (!isFunction(component) && !component.render && !component.template) {
10675 // __UNSAFE__
10676 // Reason: potential execution of JS expressions in in-DOM template.
10677 // The user must make sure the in-DOM template is trusted. If it's
10678 // rendered by the server, the template should not contain any user data.
10679 component.template = container.innerHTML;
10680 }
10681 // clear content before mounting
10682 container.innerHTML = '';
10683 const proxy = mount(container, false, container instanceof SVGElement);
10684 if (container instanceof Element) {
10685 container.removeAttribute('v-cloak');
10686 container.setAttribute('data-v-app', '');
10687 }
10688 return proxy;
10689 };
10690 return app;
10691});
10692const createSSRApp = ((...args) => {
10693 const app = ensureHydrationRenderer().createApp(...args);
10694 {
10695 injectNativeTagCheck(app);
10696 injectCompilerOptionsCheck(app);
10697 }
10698 const { mount } = app;
10699 app.mount = (containerOrSelector) => {
10700 const container = normalizeContainer(containerOrSelector);
10701 if (container) {
10702 return mount(container, true, container instanceof SVGElement);
10703 }
10704 };
10705 return app;
10706});
10707function injectNativeTagCheck(app) {
10708 // Inject `isNativeTag`
10709 // this is used for component name validation (dev only)
10710 Object.defineProperty(app.config, 'isNativeTag', {
10711 value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
10712 writable: false
10713 });
10714}
10715// dev only
10716function injectCompilerOptionsCheck(app) {
10717 if (isRuntimeOnly()) {
10718 const isCustomElement = app.config.isCustomElement;
10719 Object.defineProperty(app.config, 'isCustomElement', {
10720 get() {
10721 return isCustomElement;
10722 },
10723 set() {
10724 warn$1(`The \`isCustomElement\` config option is deprecated. Use ` +
10725 `\`compilerOptions.isCustomElement\` instead.`);
10726 }
10727 });
10728 const compilerOptions = app.config.compilerOptions;
10729 const msg = `The \`compilerOptions\` config option is only respected when using ` +
10730 `a build of Vue.js that includes the runtime compiler (aka "full build"). ` +
10731 `Since you are using the runtime-only build, \`compilerOptions\` ` +
10732 `must be passed to \`@vue/compiler-dom\` in the build setup instead.\n` +
10733 `- For vue-loader: pass it via vue-loader's \`compilerOptions\` loader option.\n` +
10734 `- For vue-cli: see https://cli.vuejs.org/guide/webpack.html#modifying-options-of-a-loader\n` +
10735 `- 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`;
10736 Object.defineProperty(app.config, 'compilerOptions', {
10737 get() {
10738 warn$1(msg);
10739 return compilerOptions;
10740 },
10741 set() {
10742 warn$1(msg);
10743 }
10744 });
10745 }
10746}
10747function normalizeContainer(container) {
10748 if (isString(container)) {
10749 const res = document.querySelector(container);
10750 if (!res) {
10751 warn$1(`Failed to mount app: mount target selector "${container}" returned null.`);
10752 }
10753 return res;
10754 }
10755 if (window.ShadowRoot &&
10756 container instanceof window.ShadowRoot &&
10757 container.mode === 'closed') {
10758 warn$1(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`);
10759 }
10760 return container;
10761}
10762/**
10763 * @internal
10764 */
10765const initDirectivesForSSR = NOOP;
10766
10767var runtimeDom = /*#__PURE__*/Object.freeze({
10768 __proto__: null,
10769 render: render,
10770 hydrate: hydrate,
10771 createApp: createApp,
10772 createSSRApp: createSSRApp,
10773 initDirectivesForSSR: initDirectivesForSSR,
10774 defineCustomElement: defineCustomElement,
10775 defineSSRCustomElement: defineSSRCustomElement,
10776 VueElement: VueElement,
10777 useCssModule: useCssModule,
10778 useCssVars: useCssVars,
10779 Transition: Transition,
10780 TransitionGroup: TransitionGroup,
10781 vModelText: vModelText,
10782 vModelCheckbox: vModelCheckbox,
10783 vModelRadio: vModelRadio,
10784 vModelSelect: vModelSelect,
10785 vModelDynamic: vModelDynamic,
10786 withModifiers: withModifiers,
10787 withKeys: withKeys,
10788 vShow: vShow,
10789 reactive: reactive,
10790 ref: ref,
10791 readonly: readonly,
10792 unref: unref,
10793 proxyRefs: proxyRefs,
10794 isRef: isRef,
10795 toRef: toRef,
10796 toRefs: toRefs,
10797 isProxy: isProxy,
10798 isReactive: isReactive,
10799 isReadonly: isReadonly,
10800 isShallow: isShallow,
10801 customRef: customRef,
10802 triggerRef: triggerRef,
10803 shallowRef: shallowRef,
10804 shallowReactive: shallowReactive,
10805 shallowReadonly: shallowReadonly,
10806 markRaw: markRaw,
10807 toRaw: toRaw,
10808 effect: effect,
10809 stop: stop,
10810 ReactiveEffect: ReactiveEffect,
10811 effectScope: effectScope,
10812 EffectScope: EffectScope,
10813 getCurrentScope: getCurrentScope,
10814 onScopeDispose: onScopeDispose,
10815 computed: computed$1,
10816 watch: watch,
10817 watchEffect: watchEffect,
10818 watchPostEffect: watchPostEffect,
10819 watchSyncEffect: watchSyncEffect,
10820 onBeforeMount: onBeforeMount,
10821 onMounted: onMounted,
10822 onBeforeUpdate: onBeforeUpdate,
10823 onUpdated: onUpdated,
10824 onBeforeUnmount: onBeforeUnmount,
10825 onUnmounted: onUnmounted,
10826 onActivated: onActivated,
10827 onDeactivated: onDeactivated,
10828 onRenderTracked: onRenderTracked,
10829 onRenderTriggered: onRenderTriggered,
10830 onErrorCaptured: onErrorCaptured,
10831 onServerPrefetch: onServerPrefetch,
10832 provide: provide,
10833 inject: inject,
10834 nextTick: nextTick,
10835 defineComponent: defineComponent,
10836 defineAsyncComponent: defineAsyncComponent,
10837 useAttrs: useAttrs,
10838 useSlots: useSlots,
10839 defineProps: defineProps,
10840 defineEmits: defineEmits,
10841 defineExpose: defineExpose,
10842 withDefaults: withDefaults,
10843 mergeDefaults: mergeDefaults,
10844 createPropsRestProxy: createPropsRestProxy,
10845 withAsyncContext: withAsyncContext,
10846 getCurrentInstance: getCurrentInstance,
10847 h: h,
10848 createVNode: createVNode,
10849 cloneVNode: cloneVNode,
10850 mergeProps: mergeProps,
10851 isVNode: isVNode,
10852 Fragment: Fragment,
10853 Text: Text,
10854 Comment: Comment,
10855 Static: Static,
10856 Teleport: Teleport,
10857 Suspense: Suspense,
10858 KeepAlive: KeepAlive,
10859 BaseTransition: BaseTransition,
10860 withDirectives: withDirectives,
10861 useSSRContext: useSSRContext,
10862 ssrContextKey: ssrContextKey,
10863 createRenderer: createRenderer,
10864 createHydrationRenderer: createHydrationRenderer,
10865 queuePostFlushCb: queuePostFlushCb,
10866 warn: warn$1,
10867 handleError: handleError,
10868 callWithErrorHandling: callWithErrorHandling,
10869 callWithAsyncErrorHandling: callWithAsyncErrorHandling,
10870 resolveComponent: resolveComponent,
10871 resolveDirective: resolveDirective,
10872 resolveDynamicComponent: resolveDynamicComponent,
10873 registerRuntimeCompiler: registerRuntimeCompiler,
10874 isRuntimeOnly: isRuntimeOnly,
10875 useTransitionState: useTransitionState,
10876 resolveTransitionHooks: resolveTransitionHooks,
10877 setTransitionHooks: setTransitionHooks,
10878 getTransitionRawChildren: getTransitionRawChildren,
10879 initCustomFormatter: initCustomFormatter,
10880 get devtools () { return devtools; },
10881 setDevtoolsHook: setDevtoolsHook,
10882 withCtx: withCtx,
10883 pushScopeId: pushScopeId,
10884 popScopeId: popScopeId,
10885 withScopeId: withScopeId,
10886 renderList: renderList,
10887 toHandlers: toHandlers,
10888 renderSlot: renderSlot,
10889 createSlots: createSlots,
10890 withMemo: withMemo,
10891 isMemoSame: isMemoSame,
10892 openBlock: openBlock,
10893 createBlock: createBlock,
10894 setBlockTracking: setBlockTracking,
10895 createTextVNode: createTextVNode,
10896 createCommentVNode: createCommentVNode,
10897 createStaticVNode: createStaticVNode,
10898 createElementVNode: createBaseVNode,
10899 createElementBlock: createElementBlock,
10900 guardReactiveProps: guardReactiveProps,
10901 toDisplayString: toDisplayString,
10902 camelize: camelize,
10903 capitalize: capitalize,
10904 toHandlerKey: toHandlerKey,
10905 normalizeProps: normalizeProps,
10906 normalizeClass: normalizeClass,
10907 normalizeStyle: normalizeStyle,
10908 transformVNodeArgs: transformVNodeArgs,
10909 version: version,
10910 ssrUtils: ssrUtils,
10911 resolveFilter: resolveFilter,
10912 compatUtils: compatUtils
10913});
10914
10915function initDev() {
10916 {
10917 {
10918 console.info(`You are running a development build of Vue.\n` +
10919 `Make sure to use the production build (*.prod.js) when deploying for production.`);
10920 }
10921 initCustomFormatter();
10922 }
10923}
10924
10925function defaultOnError(error) {
10926 throw error;
10927}
10928function defaultOnWarn(msg) {
10929 console.warn(`[Vue warn] ${msg.message}`);
10930}
10931function createCompilerError(code, loc, messages, additionalMessage) {
10932 const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
10933 ;
10934 const error = new SyntaxError(String(msg));
10935 error.code = code;
10936 error.loc = loc;
10937 return error;
10938}
10939const errorMessages = {
10940 // parse errors
10941 [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
10942 [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
10943 [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
10944 [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
10945 [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
10946 [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
10947 [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
10948 [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
10949 [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
10950 [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
10951 [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
10952 [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
10953 [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
10954 [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
10955 [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
10956 [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
10957 [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
10958 [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
10959 [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
10960 [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
10961 [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
10962 [20 /* UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
10963 [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
10964 // Vue-specific parse errors
10965 [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
10966 [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
10967 [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
10968 [27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
10969 'Note that dynamic directive argument cannot contain spaces.',
10970 [26 /* X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
10971 // transform errors
10972 [28 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
10973 [29 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
10974 [30 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
10975 [31 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
10976 [32 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
10977 [33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
10978 [34 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
10979 [35 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
10980 [36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
10981 [37 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
10982 `When there are multiple named slots, all slots should use <template> ` +
10983 `syntax to avoid scope ambiguity.`,
10984 [38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
10985 [39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
10986 `default slot. These children will be ignored.`,
10987 [40 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
10988 [41 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
10989 [42 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
10990 [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.`,
10991 [44 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
10992 [45 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
10993 // generic errors
10994 [46 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
10995 [47 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
10996 [48 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
10997 [49 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
10998 // just to fulfill types
10999 [50 /* __EXTEND_POINT__ */]: ``
11000};
11001
11002const FRAGMENT = Symbol(`Fragment` );
11003const TELEPORT = Symbol(`Teleport` );
11004const SUSPENSE = Symbol(`Suspense` );
11005const KEEP_ALIVE = Symbol(`KeepAlive` );
11006const BASE_TRANSITION = Symbol(`BaseTransition` );
11007const OPEN_BLOCK = Symbol(`openBlock` );
11008const CREATE_BLOCK = Symbol(`createBlock` );
11009const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` );
11010const CREATE_VNODE = Symbol(`createVNode` );
11011const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
11012const CREATE_COMMENT = Symbol(`createCommentVNode` );
11013const CREATE_TEXT = Symbol(`createTextVNode` );
11014const CREATE_STATIC = Symbol(`createStaticVNode` );
11015const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
11016const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
11017const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
11018const RESOLVE_FILTER = Symbol(`resolveFilter` );
11019const WITH_DIRECTIVES = Symbol(`withDirectives` );
11020const RENDER_LIST = Symbol(`renderList` );
11021const RENDER_SLOT = Symbol(`renderSlot` );
11022const CREATE_SLOTS = Symbol(`createSlots` );
11023const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
11024const MERGE_PROPS = Symbol(`mergeProps` );
11025const NORMALIZE_CLASS = Symbol(`normalizeClass` );
11026const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
11027const NORMALIZE_PROPS = Symbol(`normalizeProps` );
11028const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
11029const TO_HANDLERS = Symbol(`toHandlers` );
11030const CAMELIZE = Symbol(`camelize` );
11031const CAPITALIZE = Symbol(`capitalize` );
11032const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
11033const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
11034const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
11035const POP_SCOPE_ID = Symbol(`popScopeId` );
11036const WITH_CTX = Symbol(`withCtx` );
11037const UNREF = Symbol(`unref` );
11038const IS_REF = Symbol(`isRef` );
11039const WITH_MEMO = Symbol(`withMemo` );
11040const IS_MEMO_SAME = Symbol(`isMemoSame` );
11041// Name mapping for runtime helpers that need to be imported from 'vue' in
11042// generated code. Make sure these are correctly exported in the runtime!
11043// Using `any` here because TS doesn't allow symbols as index type.
11044const helperNameMap = {
11045 [FRAGMENT]: `Fragment`,
11046 [TELEPORT]: `Teleport`,
11047 [SUSPENSE]: `Suspense`,
11048 [KEEP_ALIVE]: `KeepAlive`,
11049 [BASE_TRANSITION]: `BaseTransition`,
11050 [OPEN_BLOCK]: `openBlock`,
11051 [CREATE_BLOCK]: `createBlock`,
11052 [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
11053 [CREATE_VNODE]: `createVNode`,
11054 [CREATE_ELEMENT_VNODE]: `createElementVNode`,
11055 [CREATE_COMMENT]: `createCommentVNode`,
11056 [CREATE_TEXT]: `createTextVNode`,
11057 [CREATE_STATIC]: `createStaticVNode`,
11058 [RESOLVE_COMPONENT]: `resolveComponent`,
11059 [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
11060 [RESOLVE_DIRECTIVE]: `resolveDirective`,
11061 [RESOLVE_FILTER]: `resolveFilter`,
11062 [WITH_DIRECTIVES]: `withDirectives`,
11063 [RENDER_LIST]: `renderList`,
11064 [RENDER_SLOT]: `renderSlot`,
11065 [CREATE_SLOTS]: `createSlots`,
11066 [TO_DISPLAY_STRING]: `toDisplayString`,
11067 [MERGE_PROPS]: `mergeProps`,
11068 [NORMALIZE_CLASS]: `normalizeClass`,
11069 [NORMALIZE_STYLE]: `normalizeStyle`,
11070 [NORMALIZE_PROPS]: `normalizeProps`,
11071 [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
11072 [TO_HANDLERS]: `toHandlers`,
11073 [CAMELIZE]: `camelize`,
11074 [CAPITALIZE]: `capitalize`,
11075 [TO_HANDLER_KEY]: `toHandlerKey`,
11076 [SET_BLOCK_TRACKING]: `setBlockTracking`,
11077 [PUSH_SCOPE_ID]: `pushScopeId`,
11078 [POP_SCOPE_ID]: `popScopeId`,
11079 [WITH_CTX]: `withCtx`,
11080 [UNREF]: `unref`,
11081 [IS_REF]: `isRef`,
11082 [WITH_MEMO]: `withMemo`,
11083 [IS_MEMO_SAME]: `isMemoSame`
11084};
11085function registerRuntimeHelpers(helpers) {
11086 Object.getOwnPropertySymbols(helpers).forEach(s => {
11087 helperNameMap[s] = helpers[s];
11088 });
11089}
11090
11091// AST Utilities ---------------------------------------------------------------
11092// Some expressions, e.g. sequence and conditional expressions, are never
11093// associated with template nodes, so their source locations are just a stub.
11094// Container types like CompoundExpression also don't need a real location.
11095const locStub = {
11096 source: '',
11097 start: { line: 1, column: 1, offset: 0 },
11098 end: { line: 1, column: 1, offset: 0 }
11099};
11100function createRoot(children, loc = locStub) {
11101 return {
11102 type: 0 /* ROOT */,
11103 children,
11104 helpers: [],
11105 components: [],
11106 directives: [],
11107 hoists: [],
11108 imports: [],
11109 cached: 0,
11110 temps: 0,
11111 codegenNode: undefined,
11112 loc
11113 };
11114}
11115function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
11116 if (context) {
11117 if (isBlock) {
11118 context.helper(OPEN_BLOCK);
11119 context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
11120 }
11121 else {
11122 context.helper(getVNodeHelper(context.inSSR, isComponent));
11123 }
11124 if (directives) {
11125 context.helper(WITH_DIRECTIVES);
11126 }
11127 }
11128 return {
11129 type: 13 /* VNODE_CALL */,
11130 tag,
11131 props,
11132 children,
11133 patchFlag,
11134 dynamicProps,
11135 directives,
11136 isBlock,
11137 disableTracking,
11138 isComponent,
11139 loc
11140 };
11141}
11142function createArrayExpression(elements, loc = locStub) {
11143 return {
11144 type: 17 /* JS_ARRAY_EXPRESSION */,
11145 loc,
11146 elements
11147 };
11148}
11149function createObjectExpression(properties, loc = locStub) {
11150 return {
11151 type: 15 /* JS_OBJECT_EXPRESSION */,
11152 loc,
11153 properties
11154 };
11155}
11156function createObjectProperty(key, value) {
11157 return {
11158 type: 16 /* JS_PROPERTY */,
11159 loc: locStub,
11160 key: isString(key) ? createSimpleExpression(key, true) : key,
11161 value
11162 };
11163}
11164function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
11165 return {
11166 type: 4 /* SIMPLE_EXPRESSION */,
11167 loc,
11168 content,
11169 isStatic,
11170 constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
11171 };
11172}
11173function createCompoundExpression(children, loc = locStub) {
11174 return {
11175 type: 8 /* COMPOUND_EXPRESSION */,
11176 loc,
11177 children
11178 };
11179}
11180function createCallExpression(callee, args = [], loc = locStub) {
11181 return {
11182 type: 14 /* JS_CALL_EXPRESSION */,
11183 loc,
11184 callee,
11185 arguments: args
11186 };
11187}
11188function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
11189 return {
11190 type: 18 /* JS_FUNCTION_EXPRESSION */,
11191 params,
11192 returns,
11193 newline,
11194 isSlot,
11195 loc
11196 };
11197}
11198function createConditionalExpression(test, consequent, alternate, newline = true) {
11199 return {
11200 type: 19 /* JS_CONDITIONAL_EXPRESSION */,
11201 test,
11202 consequent,
11203 alternate,
11204 newline,
11205 loc: locStub
11206 };
11207}
11208function createCacheExpression(index, value, isVNode = false) {
11209 return {
11210 type: 20 /* JS_CACHE_EXPRESSION */,
11211 index,
11212 value,
11213 isVNode,
11214 loc: locStub
11215 };
11216}
11217function createBlockStatement(body) {
11218 return {
11219 type: 21 /* JS_BLOCK_STATEMENT */,
11220 body,
11221 loc: locStub
11222 };
11223}
11224
11225const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
11226const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
11227function isCoreComponent(tag) {
11228 if (isBuiltInType(tag, 'Teleport')) {
11229 return TELEPORT;
11230 }
11231 else if (isBuiltInType(tag, 'Suspense')) {
11232 return SUSPENSE;
11233 }
11234 else if (isBuiltInType(tag, 'KeepAlive')) {
11235 return KEEP_ALIVE;
11236 }
11237 else if (isBuiltInType(tag, 'BaseTransition')) {
11238 return BASE_TRANSITION;
11239 }
11240}
11241const nonIdentifierRE = /^\d|[^\$\w]/;
11242const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
11243const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
11244const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
11245const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
11246/**
11247 * Simple lexer to check if an expression is a member expression. This is
11248 * lax and only checks validity at the root level (i.e. does not validate exps
11249 * inside square brackets), but it's ok since these are only used on template
11250 * expressions and false positives are invalid expressions in the first place.
11251 */
11252const isMemberExpressionBrowser = (path) => {
11253 // remove whitespaces around . or [ first
11254 path = path.trim().replace(whitespaceRE, s => s.trim());
11255 let state = 0 /* inMemberExp */;
11256 let stateStack = [];
11257 let currentOpenBracketCount = 0;
11258 let currentOpenParensCount = 0;
11259 let currentStringType = null;
11260 for (let i = 0; i < path.length; i++) {
11261 const char = path.charAt(i);
11262 switch (state) {
11263 case 0 /* inMemberExp */:
11264 if (char === '[') {
11265 stateStack.push(state);
11266 state = 1 /* inBrackets */;
11267 currentOpenBracketCount++;
11268 }
11269 else if (char === '(') {
11270 stateStack.push(state);
11271 state = 2 /* inParens */;
11272 currentOpenParensCount++;
11273 }
11274 else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
11275 return false;
11276 }
11277 break;
11278 case 1 /* inBrackets */:
11279 if (char === `'` || char === `"` || char === '`') {
11280 stateStack.push(state);
11281 state = 3 /* inString */;
11282 currentStringType = char;
11283 }
11284 else if (char === `[`) {
11285 currentOpenBracketCount++;
11286 }
11287 else if (char === `]`) {
11288 if (!--currentOpenBracketCount) {
11289 state = stateStack.pop();
11290 }
11291 }
11292 break;
11293 case 2 /* inParens */:
11294 if (char === `'` || char === `"` || char === '`') {
11295 stateStack.push(state);
11296 state = 3 /* inString */;
11297 currentStringType = char;
11298 }
11299 else if (char === `(`) {
11300 currentOpenParensCount++;
11301 }
11302 else if (char === `)`) {
11303 // if the exp ends as a call then it should not be considered valid
11304 if (i === path.length - 1) {
11305 return false;
11306 }
11307 if (!--currentOpenParensCount) {
11308 state = stateStack.pop();
11309 }
11310 }
11311 break;
11312 case 3 /* inString */:
11313 if (char === currentStringType) {
11314 state = stateStack.pop();
11315 currentStringType = null;
11316 }
11317 break;
11318 }
11319 }
11320 return !currentOpenBracketCount && !currentOpenParensCount;
11321};
11322const isMemberExpression = isMemberExpressionBrowser
11323 ;
11324function getInnerRange(loc, offset, length) {
11325 const source = loc.source.slice(offset, offset + length);
11326 const newLoc = {
11327 source,
11328 start: advancePositionWithClone(loc.start, loc.source, offset),
11329 end: loc.end
11330 };
11331 if (length != null) {
11332 newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
11333 }
11334 return newLoc;
11335}
11336function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
11337 return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
11338}
11339// advance by mutation without cloning (for performance reasons), since this
11340// gets called a lot in the parser
11341function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
11342 let linesCount = 0;
11343 let lastNewLinePos = -1;
11344 for (let i = 0; i < numberOfCharacters; i++) {
11345 if (source.charCodeAt(i) === 10 /* newline char code */) {
11346 linesCount++;
11347 lastNewLinePos = i;
11348 }
11349 }
11350 pos.offset += numberOfCharacters;
11351 pos.line += linesCount;
11352 pos.column =
11353 lastNewLinePos === -1
11354 ? pos.column + numberOfCharacters
11355 : numberOfCharacters - lastNewLinePos;
11356 return pos;
11357}
11358function assert(condition, msg) {
11359 /* istanbul ignore if */
11360 if (!condition) {
11361 throw new Error(msg || `unexpected compiler condition`);
11362 }
11363}
11364function findDir(node, name, allowEmpty = false) {
11365 for (let i = 0; i < node.props.length; i++) {
11366 const p = node.props[i];
11367 if (p.type === 7 /* DIRECTIVE */ &&
11368 (allowEmpty || p.exp) &&
11369 (isString(name) ? p.name === name : name.test(p.name))) {
11370 return p;
11371 }
11372 }
11373}
11374function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
11375 for (let i = 0; i < node.props.length; i++) {
11376 const p = node.props[i];
11377 if (p.type === 6 /* ATTRIBUTE */) {
11378 if (dynamicOnly)
11379 continue;
11380 if (p.name === name && (p.value || allowEmpty)) {
11381 return p;
11382 }
11383 }
11384 else if (p.name === 'bind' &&
11385 (p.exp || allowEmpty) &&
11386 isStaticArgOf(p.arg, name)) {
11387 return p;
11388 }
11389 }
11390}
11391function isStaticArgOf(arg, name) {
11392 return !!(arg && isStaticExp(arg) && arg.content === name);
11393}
11394function hasDynamicKeyVBind(node) {
11395 return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
11396 p.name === 'bind' &&
11397 (!p.arg || // v-bind="obj"
11398 p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
11399 !p.arg.isStatic) // v-bind:[foo]
11400 );
11401}
11402function isText(node) {
11403 return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
11404}
11405function isVSlot(p) {
11406 return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
11407}
11408function isTemplateNode(node) {
11409 return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
11410}
11411function isSlotOutlet(node) {
11412 return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
11413}
11414function getVNodeHelper(ssr, isComponent) {
11415 return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
11416}
11417function getVNodeBlockHelper(ssr, isComponent) {
11418 return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
11419}
11420const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
11421function getUnnormalizedProps(props, callPath = []) {
11422 if (props &&
11423 !isString(props) &&
11424 props.type === 14 /* JS_CALL_EXPRESSION */) {
11425 const callee = props.callee;
11426 if (!isString(callee) && propsHelperSet.has(callee)) {
11427 return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
11428 }
11429 }
11430 return [props, callPath];
11431}
11432function injectProp(node, prop, context) {
11433 let propsWithInjection;
11434 /**
11435 * 1. mergeProps(...)
11436 * 2. toHandlers(...)
11437 * 3. normalizeProps(...)
11438 * 4. normalizeProps(guardReactiveProps(...))
11439 *
11440 * we need to get the real props before normalization
11441 */
11442 let props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
11443 let callPath = [];
11444 let parentCall;
11445 if (props &&
11446 !isString(props) &&
11447 props.type === 14 /* JS_CALL_EXPRESSION */) {
11448 const ret = getUnnormalizedProps(props);
11449 props = ret[0];
11450 callPath = ret[1];
11451 parentCall = callPath[callPath.length - 1];
11452 }
11453 if (props == null || isString(props)) {
11454 propsWithInjection = createObjectExpression([prop]);
11455 }
11456 else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
11457 // merged props... add ours
11458 // only inject key to object literal if it's the first argument so that
11459 // if doesn't override user provided keys
11460 const first = props.arguments[0];
11461 if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
11462 first.properties.unshift(prop);
11463 }
11464 else {
11465 if (props.callee === TO_HANDLERS) {
11466 // #2366
11467 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
11468 createObjectExpression([prop]),
11469 props
11470 ]);
11471 }
11472 else {
11473 props.arguments.unshift(createObjectExpression([prop]));
11474 }
11475 }
11476 !propsWithInjection && (propsWithInjection = props);
11477 }
11478 else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
11479 let alreadyExists = false;
11480 // check existing key to avoid overriding user provided keys
11481 if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
11482 const propKeyName = prop.key.content;
11483 alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
11484 p.key.content === propKeyName);
11485 }
11486 if (!alreadyExists) {
11487 props.properties.unshift(prop);
11488 }
11489 propsWithInjection = props;
11490 }
11491 else {
11492 // single v-bind with expression, return a merged replacement
11493 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
11494 createObjectExpression([prop]),
11495 props
11496 ]);
11497 // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
11498 // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
11499 // the `guardReactiveProps` will no longer be needed
11500 if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
11501 parentCall = callPath[callPath.length - 2];
11502 }
11503 }
11504 if (node.type === 13 /* VNODE_CALL */) {
11505 if (parentCall) {
11506 parentCall.arguments[0] = propsWithInjection;
11507 }
11508 else {
11509 node.props = propsWithInjection;
11510 }
11511 }
11512 else {
11513 if (parentCall) {
11514 parentCall.arguments[0] = propsWithInjection;
11515 }
11516 else {
11517 node.arguments[2] = propsWithInjection;
11518 }
11519 }
11520}
11521function toValidAssetId(name, type) {
11522 // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
11523 return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
11524 return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
11525 })}`;
11526}
11527function getMemoedVNodeCall(node) {
11528 if (node.type === 14 /* JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
11529 return node.arguments[1].returns;
11530 }
11531 else {
11532 return node;
11533 }
11534}
11535function makeBlock(node, { helper, removeHelper, inSSR }) {
11536 if (!node.isBlock) {
11537 node.isBlock = true;
11538 removeHelper(getVNodeHelper(inSSR, node.isComponent));
11539 helper(OPEN_BLOCK);
11540 helper(getVNodeBlockHelper(inSSR, node.isComponent));
11541 }
11542}
11543
11544const deprecationData = {
11545 ["COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */]: {
11546 message: `Platform-native elements with "is" prop will no longer be ` +
11547 `treated as components in Vue 3 unless the "is" value is explicitly ` +
11548 `prefixed with "vue:".`,
11549 link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html`
11550 },
11551 ["COMPILER_V_BIND_SYNC" /* COMPILER_V_BIND_SYNC */]: {
11552 message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
11553 `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
11554 `\`v-model:${key}\`.`,
11555 link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html`
11556 },
11557 ["COMPILER_V_BIND_PROP" /* COMPILER_V_BIND_PROP */]: {
11558 message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
11559 `Vue 3 will automatically set a binding as DOM property when appropriate.`
11560 },
11561 ["COMPILER_V_BIND_OBJECT_ORDER" /* COMPILER_V_BIND_OBJECT_ORDER */]: {
11562 message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
11563 `object spread: it will now overwrite an existing non-mergeable attribute ` +
11564 `that appears before v-bind in the case of conflict. ` +
11565 `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
11566 `You can also suppress this warning if the usage is intended.`,
11567 link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html`
11568 },
11569 ["COMPILER_V_ON_NATIVE" /* COMPILER_V_ON_NATIVE */]: {
11570 message: `.native modifier for v-on has been removed as is no longer necessary.`,
11571 link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html`
11572 },
11573 ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
11574 message: `v-if / v-for precedence when used on the same element has changed ` +
11575 `in Vue 3: v-if now takes higher precedence and will no longer have ` +
11576 `access to v-for scope variables. It is best to avoid the ambiguity ` +
11577 `with <template> tags or use a computed property that filters v-for ` +
11578 `data source.`,
11579 link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html`
11580 },
11581 ["COMPILER_NATIVE_TEMPLATE" /* COMPILER_NATIVE_TEMPLATE */]: {
11582 message: `<template> with no special directives will render as a native template ` +
11583 `element instead of its inner content in Vue 3.`
11584 },
11585 ["COMPILER_INLINE_TEMPLATE" /* COMPILER_INLINE_TEMPLATE */]: {
11586 message: `"inline-template" has been removed in Vue 3.`,
11587 link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html`
11588 },
11589 ["COMPILER_FILTER" /* COMPILER_FILTERS */]: {
11590 message: `filters have been removed in Vue 3. ` +
11591 `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
11592 `Use method calls or computed properties instead.`,
11593 link: `https://v3-migration.vuejs.org/breaking-changes/filters.html`
11594 }
11595};
11596function getCompatValue(key, context) {
11597 const config = context.options
11598 ? context.options.compatConfig
11599 : context.compatConfig;
11600 const value = config && config[key];
11601 if (key === 'MODE') {
11602 return value || 3; // compiler defaults to v3 behavior
11603 }
11604 else {
11605 return value;
11606 }
11607}
11608function isCompatEnabled(key, context) {
11609 const mode = getCompatValue('MODE', context);
11610 const value = getCompatValue(key, context);
11611 // in v3 mode, only enable if explicitly set to true
11612 // otherwise enable for any non-false value
11613 return mode === 3 ? value === true : value !== false;
11614}
11615function checkCompatEnabled(key, context, loc, ...args) {
11616 const enabled = isCompatEnabled(key, context);
11617 if (enabled) {
11618 warnDeprecation(key, context, loc, ...args);
11619 }
11620 return enabled;
11621}
11622function warnDeprecation(key, context, loc, ...args) {
11623 const val = getCompatValue(key, context);
11624 if (val === 'suppress-warning') {
11625 return;
11626 }
11627 const { message, link } = deprecationData[key];
11628 const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
11629 const err = new SyntaxError(msg);
11630 err.code = key;
11631 if (loc)
11632 err.loc = loc;
11633 context.onWarn(err);
11634}
11635
11636// The default decoder only provides escapes for characters reserved as part of
11637// the template syntax, and is only used if the custom renderer did not provide
11638// a platform-specific decoder.
11639const decodeRE = /&(gt|lt|amp|apos|quot);/g;
11640const decodeMap = {
11641 gt: '>',
11642 lt: '<',
11643 amp: '&',
11644 apos: "'",
11645 quot: '"'
11646};
11647const defaultParserOptions = {
11648 delimiters: [`{{`, `}}`],
11649 getNamespace: () => 0 /* HTML */,
11650 getTextMode: () => 0 /* DATA */,
11651 isVoidTag: NO,
11652 isPreTag: NO,
11653 isCustomElement: NO,
11654 decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
11655 onError: defaultOnError,
11656 onWarn: defaultOnWarn,
11657 comments: true
11658};
11659function baseParse(content, options = {}) {
11660 const context = createParserContext(content, options);
11661 const start = getCursor(context);
11662 return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
11663}
11664function createParserContext(content, rawOptions) {
11665 const options = extend({}, defaultParserOptions);
11666 let key;
11667 for (key in rawOptions) {
11668 // @ts-ignore
11669 options[key] =
11670 rawOptions[key] === undefined
11671 ? defaultParserOptions[key]
11672 : rawOptions[key];
11673 }
11674 return {
11675 options,
11676 column: 1,
11677 line: 1,
11678 offset: 0,
11679 originalSource: content,
11680 source: content,
11681 inPre: false,
11682 inVPre: false,
11683 onWarn: options.onWarn
11684 };
11685}
11686function parseChildren(context, mode, ancestors) {
11687 const parent = last(ancestors);
11688 const ns = parent ? parent.ns : 0 /* HTML */;
11689 const nodes = [];
11690 while (!isEnd(context, mode, ancestors)) {
11691 const s = context.source;
11692 let node = undefined;
11693 if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
11694 if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
11695 // '{{'
11696 node = parseInterpolation(context, mode);
11697 }
11698 else if (mode === 0 /* DATA */ && s[0] === '<') {
11699 // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
11700 if (s.length === 1) {
11701 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
11702 }
11703 else if (s[1] === '!') {
11704 // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
11705 if (startsWith(s, '<!--')) {
11706 node = parseComment(context);
11707 }
11708 else if (startsWith(s, '<!DOCTYPE')) {
11709 // Ignore DOCTYPE by a limitation.
11710 node = parseBogusComment(context);
11711 }
11712 else if (startsWith(s, '<![CDATA[')) {
11713 if (ns !== 0 /* HTML */) {
11714 node = parseCDATA(context, ancestors);
11715 }
11716 else {
11717 emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
11718 node = parseBogusComment(context);
11719 }
11720 }
11721 else {
11722 emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
11723 node = parseBogusComment(context);
11724 }
11725 }
11726 else if (s[1] === '/') {
11727 // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
11728 if (s.length === 2) {
11729 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
11730 }
11731 else if (s[2] === '>') {
11732 emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
11733 advanceBy(context, 3);
11734 continue;
11735 }
11736 else if (/[a-z]/i.test(s[2])) {
11737 emitError(context, 23 /* X_INVALID_END_TAG */);
11738 parseTag(context, 1 /* End */, parent);
11739 continue;
11740 }
11741 else {
11742 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
11743 node = parseBogusComment(context);
11744 }
11745 }
11746 else if (/[a-z]/i.test(s[1])) {
11747 node = parseElement(context, ancestors);
11748 }
11749 else if (s[1] === '?') {
11750 emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
11751 node = parseBogusComment(context);
11752 }
11753 else {
11754 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
11755 }
11756 }
11757 }
11758 if (!node) {
11759 node = parseText(context, mode);
11760 }
11761 if (isArray(node)) {
11762 for (let i = 0; i < node.length; i++) {
11763 pushNode(nodes, node[i]);
11764 }
11765 }
11766 else {
11767 pushNode(nodes, node);
11768 }
11769 }
11770 // Whitespace handling strategy like v2
11771 let removedWhitespace = false;
11772 if (mode !== 2 /* RAWTEXT */ && mode !== 1 /* RCDATA */) {
11773 const shouldCondense = context.options.whitespace !== 'preserve';
11774 for (let i = 0; i < nodes.length; i++) {
11775 const node = nodes[i];
11776 if (!context.inPre && node.type === 2 /* TEXT */) {
11777 if (!/[^\t\r\n\f ]/.test(node.content)) {
11778 const prev = nodes[i - 1];
11779 const next = nodes[i + 1];
11780 // Remove if:
11781 // - the whitespace is the first or last node, or:
11782 // - (condense mode) the whitespace is adjacent to a comment, or:
11783 // - (condense mode) the whitespace is between two elements AND contains newline
11784 if (!prev ||
11785 !next ||
11786 (shouldCondense &&
11787 (prev.type === 3 /* COMMENT */ ||
11788 next.type === 3 /* COMMENT */ ||
11789 (prev.type === 1 /* ELEMENT */ &&
11790 next.type === 1 /* ELEMENT */ &&
11791 /[\r\n]/.test(node.content))))) {
11792 removedWhitespace = true;
11793 nodes[i] = null;
11794 }
11795 else {
11796 // Otherwise, the whitespace is condensed into a single space
11797 node.content = ' ';
11798 }
11799 }
11800 else if (shouldCondense) {
11801 // in condense mode, consecutive whitespaces in text are condensed
11802 // down to a single space.
11803 node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
11804 }
11805 }
11806 // Remove comment nodes if desired by configuration.
11807 else if (node.type === 3 /* COMMENT */ && !context.options.comments) {
11808 removedWhitespace = true;
11809 nodes[i] = null;
11810 }
11811 }
11812 if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
11813 // remove leading newline per html spec
11814 // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
11815 const first = nodes[0];
11816 if (first && first.type === 2 /* TEXT */) {
11817 first.content = first.content.replace(/^\r?\n/, '');
11818 }
11819 }
11820 }
11821 return removedWhitespace ? nodes.filter(Boolean) : nodes;
11822}
11823function pushNode(nodes, node) {
11824 if (node.type === 2 /* TEXT */) {
11825 const prev = last(nodes);
11826 // Merge if both this and the previous node are text and those are
11827 // consecutive. This happens for cases like "a < b".
11828 if (prev &&
11829 prev.type === 2 /* TEXT */ &&
11830 prev.loc.end.offset === node.loc.start.offset) {
11831 prev.content += node.content;
11832 prev.loc.end = node.loc.end;
11833 prev.loc.source += node.loc.source;
11834 return;
11835 }
11836 }
11837 nodes.push(node);
11838}
11839function parseCDATA(context, ancestors) {
11840 advanceBy(context, 9);
11841 const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
11842 if (context.source.length === 0) {
11843 emitError(context, 6 /* EOF_IN_CDATA */);
11844 }
11845 else {
11846 advanceBy(context, 3);
11847 }
11848 return nodes;
11849}
11850function parseComment(context) {
11851 const start = getCursor(context);
11852 let content;
11853 // Regular comment.
11854 const match = /--(\!)?>/.exec(context.source);
11855 if (!match) {
11856 content = context.source.slice(4);
11857 advanceBy(context, context.source.length);
11858 emitError(context, 7 /* EOF_IN_COMMENT */);
11859 }
11860 else {
11861 if (match.index <= 3) {
11862 emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
11863 }
11864 if (match[1]) {
11865 emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
11866 }
11867 content = context.source.slice(4, match.index);
11868 // Advancing with reporting nested comments.
11869 const s = context.source.slice(0, match.index);
11870 let prevIndex = 1, nestedIndex = 0;
11871 while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
11872 advanceBy(context, nestedIndex - prevIndex + 1);
11873 if (nestedIndex + 4 < s.length) {
11874 emitError(context, 16 /* NESTED_COMMENT */);
11875 }
11876 prevIndex = nestedIndex + 1;
11877 }
11878 advanceBy(context, match.index + match[0].length - prevIndex + 1);
11879 }
11880 return {
11881 type: 3 /* COMMENT */,
11882 content,
11883 loc: getSelection(context, start)
11884 };
11885}
11886function parseBogusComment(context) {
11887 const start = getCursor(context);
11888 const contentStart = context.source[1] === '?' ? 1 : 2;
11889 let content;
11890 const closeIndex = context.source.indexOf('>');
11891 if (closeIndex === -1) {
11892 content = context.source.slice(contentStart);
11893 advanceBy(context, context.source.length);
11894 }
11895 else {
11896 content = context.source.slice(contentStart, closeIndex);
11897 advanceBy(context, closeIndex + 1);
11898 }
11899 return {
11900 type: 3 /* COMMENT */,
11901 content,
11902 loc: getSelection(context, start)
11903 };
11904}
11905function parseElement(context, ancestors) {
11906 // Start tag.
11907 const wasInPre = context.inPre;
11908 const wasInVPre = context.inVPre;
11909 const parent = last(ancestors);
11910 const element = parseTag(context, 0 /* Start */, parent);
11911 const isPreBoundary = context.inPre && !wasInPre;
11912 const isVPreBoundary = context.inVPre && !wasInVPre;
11913 if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
11914 // #4030 self-closing <pre> tag
11915 if (isPreBoundary) {
11916 context.inPre = false;
11917 }
11918 if (isVPreBoundary) {
11919 context.inVPre = false;
11920 }
11921 return element;
11922 }
11923 // Children.
11924 ancestors.push(element);
11925 const mode = context.options.getTextMode(element, parent);
11926 const children = parseChildren(context, mode, ancestors);
11927 ancestors.pop();
11928 element.children = children;
11929 // End tag.
11930 if (startsWithEndTagOpen(context.source, element.tag)) {
11931 parseTag(context, 1 /* End */, parent);
11932 }
11933 else {
11934 emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
11935 if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
11936 const first = children[0];
11937 if (first && startsWith(first.loc.source, '<!--')) {
11938 emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
11939 }
11940 }
11941 }
11942 element.loc = getSelection(context, element.loc.start);
11943 if (isPreBoundary) {
11944 context.inPre = false;
11945 }
11946 if (isVPreBoundary) {
11947 context.inVPre = false;
11948 }
11949 return element;
11950}
11951const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
11952function parseTag(context, type, parent) {
11953 // Tag open.
11954 const start = getCursor(context);
11955 const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
11956 const tag = match[1];
11957 const ns = context.options.getNamespace(tag, parent);
11958 advanceBy(context, match[0].length);
11959 advanceSpaces(context);
11960 // save current state in case we need to re-parse attributes with v-pre
11961 const cursor = getCursor(context);
11962 const currentSource = context.source;
11963 // check <pre> tag
11964 if (context.options.isPreTag(tag)) {
11965 context.inPre = true;
11966 }
11967 // Attributes.
11968 let props = parseAttributes(context, type);
11969 // check v-pre
11970 if (type === 0 /* Start */ &&
11971 !context.inVPre &&
11972 props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
11973 context.inVPre = true;
11974 // reset context
11975 extend(context, cursor);
11976 context.source = currentSource;
11977 // re-parse attrs and filter out v-pre itself
11978 props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
11979 }
11980 // Tag close.
11981 let isSelfClosing = false;
11982 if (context.source.length === 0) {
11983 emitError(context, 9 /* EOF_IN_TAG */);
11984 }
11985 else {
11986 isSelfClosing = startsWith(context.source, '/>');
11987 if (type === 1 /* End */ && isSelfClosing) {
11988 emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
11989 }
11990 advanceBy(context, isSelfClosing ? 2 : 1);
11991 }
11992 if (type === 1 /* End */) {
11993 return;
11994 }
11995 let tagType = 0 /* ELEMENT */;
11996 if (!context.inVPre) {
11997 if (tag === 'slot') {
11998 tagType = 2 /* SLOT */;
11999 }
12000 else if (tag === 'template') {
12001 if (props.some(p => p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
12002 tagType = 3 /* TEMPLATE */;
12003 }
12004 }
12005 else if (isComponent(tag, props, context)) {
12006 tagType = 1 /* COMPONENT */;
12007 }
12008 }
12009 return {
12010 type: 1 /* ELEMENT */,
12011 ns,
12012 tag,
12013 tagType,
12014 props,
12015 isSelfClosing,
12016 children: [],
12017 loc: getSelection(context, start),
12018 codegenNode: undefined // to be created during transform phase
12019 };
12020}
12021function isComponent(tag, props, context) {
12022 const options = context.options;
12023 if (options.isCustomElement(tag)) {
12024 return false;
12025 }
12026 if (tag === 'component' ||
12027 /^[A-Z]/.test(tag) ||
12028 isCoreComponent(tag) ||
12029 (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
12030 (options.isNativeTag && !options.isNativeTag(tag))) {
12031 return true;
12032 }
12033 // at this point the tag should be a native tag, but check for potential "is"
12034 // casting
12035 for (let i = 0; i < props.length; i++) {
12036 const p = props[i];
12037 if (p.type === 6 /* ATTRIBUTE */) {
12038 if (p.name === 'is' && p.value) {
12039 if (p.value.content.startsWith('vue:')) {
12040 return true;
12041 }
12042 }
12043 }
12044 else {
12045 // directive
12046 // v-is (TODO Deprecate)
12047 if (p.name === 'is') {
12048 return true;
12049 }
12050 else if (
12051 // :is on plain element - only treat as component in compat mode
12052 p.name === 'bind' &&
12053 isStaticArgOf(p.arg, 'is') &&
12054 false &&
12055 checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
12056 return true;
12057 }
12058 }
12059 }
12060}
12061function parseAttributes(context, type) {
12062 const props = [];
12063 const attributeNames = new Set();
12064 while (context.source.length > 0 &&
12065 !startsWith(context.source, '>') &&
12066 !startsWith(context.source, '/>')) {
12067 if (startsWith(context.source, '/')) {
12068 emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
12069 advanceBy(context, 1);
12070 advanceSpaces(context);
12071 continue;
12072 }
12073 if (type === 1 /* End */) {
12074 emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
12075 }
12076 const attr = parseAttribute(context, attributeNames);
12077 // Trim whitespace between class
12078 // https://github.com/vuejs/core/issues/4251
12079 if (attr.type === 6 /* ATTRIBUTE */ &&
12080 attr.value &&
12081 attr.name === 'class') {
12082 attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
12083 }
12084 if (type === 0 /* Start */) {
12085 props.push(attr);
12086 }
12087 if (/^[^\t\r\n\f />]/.test(context.source)) {
12088 emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
12089 }
12090 advanceSpaces(context);
12091 }
12092 return props;
12093}
12094function parseAttribute(context, nameSet) {
12095 // Name.
12096 const start = getCursor(context);
12097 const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
12098 const name = match[0];
12099 if (nameSet.has(name)) {
12100 emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
12101 }
12102 nameSet.add(name);
12103 if (name[0] === '=') {
12104 emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
12105 }
12106 {
12107 const pattern = /["'<]/g;
12108 let m;
12109 while ((m = pattern.exec(name))) {
12110 emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
12111 }
12112 }
12113 advanceBy(context, name.length);
12114 // Value
12115 let value = undefined;
12116 if (/^[\t\r\n\f ]*=/.test(context.source)) {
12117 advanceSpaces(context);
12118 advanceBy(context, 1);
12119 advanceSpaces(context);
12120 value = parseAttributeValue(context);
12121 if (!value) {
12122 emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
12123 }
12124 }
12125 const loc = getSelection(context, start);
12126 if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
12127 const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
12128 let isPropShorthand = startsWith(name, '.');
12129 let dirName = match[1] ||
12130 (isPropShorthand || startsWith(name, ':')
12131 ? 'bind'
12132 : startsWith(name, '@')
12133 ? 'on'
12134 : 'slot');
12135 let arg;
12136 if (match[2]) {
12137 const isSlot = dirName === 'slot';
12138 const startOffset = name.lastIndexOf(match[2]);
12139 const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
12140 let content = match[2];
12141 let isStatic = true;
12142 if (content.startsWith('[')) {
12143 isStatic = false;
12144 if (!content.endsWith(']')) {
12145 emitError(context, 27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
12146 content = content.slice(1);
12147 }
12148 else {
12149 content = content.slice(1, content.length - 1);
12150 }
12151 }
12152 else if (isSlot) {
12153 // #1241 special case for v-slot: vuetify relies extensively on slot
12154 // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
12155 // supports such usage so we are keeping it consistent with 2.x.
12156 content += match[3] || '';
12157 }
12158 arg = {
12159 type: 4 /* SIMPLE_EXPRESSION */,
12160 content,
12161 isStatic,
12162 constType: isStatic
12163 ? 3 /* CAN_STRINGIFY */
12164 : 0 /* NOT_CONSTANT */,
12165 loc
12166 };
12167 }
12168 if (value && value.isQuoted) {
12169 const valueLoc = value.loc;
12170 valueLoc.start.offset++;
12171 valueLoc.start.column++;
12172 valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
12173 valueLoc.source = valueLoc.source.slice(1, -1);
12174 }
12175 const modifiers = match[3] ? match[3].slice(1).split('.') : [];
12176 if (isPropShorthand)
12177 modifiers.push('prop');
12178 return {
12179 type: 7 /* DIRECTIVE */,
12180 name: dirName,
12181 exp: value && {
12182 type: 4 /* SIMPLE_EXPRESSION */,
12183 content: value.content,
12184 isStatic: false,
12185 // Treat as non-constant by default. This can be potentially set to
12186 // other values by `transformExpression` to make it eligible for hoisting.
12187 constType: 0 /* NOT_CONSTANT */,
12188 loc: value.loc
12189 },
12190 arg,
12191 modifiers,
12192 loc
12193 };
12194 }
12195 // missing directive name or illegal directive name
12196 if (!context.inVPre && startsWith(name, 'v-')) {
12197 emitError(context, 26 /* X_MISSING_DIRECTIVE_NAME */);
12198 }
12199 return {
12200 type: 6 /* ATTRIBUTE */,
12201 name,
12202 value: value && {
12203 type: 2 /* TEXT */,
12204 content: value.content,
12205 loc: value.loc
12206 },
12207 loc
12208 };
12209}
12210function parseAttributeValue(context) {
12211 const start = getCursor(context);
12212 let content;
12213 const quote = context.source[0];
12214 const isQuoted = quote === `"` || quote === `'`;
12215 if (isQuoted) {
12216 // Quoted value.
12217 advanceBy(context, 1);
12218 const endIndex = context.source.indexOf(quote);
12219 if (endIndex === -1) {
12220 content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
12221 }
12222 else {
12223 content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
12224 advanceBy(context, 1);
12225 }
12226 }
12227 else {
12228 // Unquoted
12229 const match = /^[^\t\r\n\f >]+/.exec(context.source);
12230 if (!match) {
12231 return undefined;
12232 }
12233 const unexpectedChars = /["'<=`]/g;
12234 let m;
12235 while ((m = unexpectedChars.exec(match[0]))) {
12236 emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
12237 }
12238 content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
12239 }
12240 return { content, isQuoted, loc: getSelection(context, start) };
12241}
12242function parseInterpolation(context, mode) {
12243 const [open, close] = context.options.delimiters;
12244 const closeIndex = context.source.indexOf(close, open.length);
12245 if (closeIndex === -1) {
12246 emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
12247 return undefined;
12248 }
12249 const start = getCursor(context);
12250 advanceBy(context, open.length);
12251 const innerStart = getCursor(context);
12252 const innerEnd = getCursor(context);
12253 const rawContentLength = closeIndex - open.length;
12254 const rawContent = context.source.slice(0, rawContentLength);
12255 const preTrimContent = parseTextData(context, rawContentLength, mode);
12256 const content = preTrimContent.trim();
12257 const startOffset = preTrimContent.indexOf(content);
12258 if (startOffset > 0) {
12259 advancePositionWithMutation(innerStart, rawContent, startOffset);
12260 }
12261 const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
12262 advancePositionWithMutation(innerEnd, rawContent, endOffset);
12263 advanceBy(context, close.length);
12264 return {
12265 type: 5 /* INTERPOLATION */,
12266 content: {
12267 type: 4 /* SIMPLE_EXPRESSION */,
12268 isStatic: false,
12269 // Set `isConstant` to false by default and will decide in transformExpression
12270 constType: 0 /* NOT_CONSTANT */,
12271 content,
12272 loc: getSelection(context, innerStart, innerEnd)
12273 },
12274 loc: getSelection(context, start)
12275 };
12276}
12277function parseText(context, mode) {
12278 const endTokens = mode === 3 /* CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
12279 let endIndex = context.source.length;
12280 for (let i = 0; i < endTokens.length; i++) {
12281 const index = context.source.indexOf(endTokens[i], 1);
12282 if (index !== -1 && endIndex > index) {
12283 endIndex = index;
12284 }
12285 }
12286 const start = getCursor(context);
12287 const content = parseTextData(context, endIndex, mode);
12288 return {
12289 type: 2 /* TEXT */,
12290 content,
12291 loc: getSelection(context, start)
12292 };
12293}
12294/**
12295 * Get text data with a given length from the current location.
12296 * This translates HTML entities in the text data.
12297 */
12298function parseTextData(context, length, mode) {
12299 const rawText = context.source.slice(0, length);
12300 advanceBy(context, length);
12301 if (mode === 2 /* RAWTEXT */ ||
12302 mode === 3 /* CDATA */ ||
12303 !rawText.includes('&')) {
12304 return rawText;
12305 }
12306 else {
12307 // DATA or RCDATA containing "&"". Entity decoding required.
12308 return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
12309 }
12310}
12311function getCursor(context) {
12312 const { column, line, offset } = context;
12313 return { column, line, offset };
12314}
12315function getSelection(context, start, end) {
12316 end = end || getCursor(context);
12317 return {
12318 start,
12319 end,
12320 source: context.originalSource.slice(start.offset, end.offset)
12321 };
12322}
12323function last(xs) {
12324 return xs[xs.length - 1];
12325}
12326function startsWith(source, searchString) {
12327 return source.startsWith(searchString);
12328}
12329function advanceBy(context, numberOfCharacters) {
12330 const { source } = context;
12331 advancePositionWithMutation(context, source, numberOfCharacters);
12332 context.source = source.slice(numberOfCharacters);
12333}
12334function advanceSpaces(context) {
12335 const match = /^[\t\r\n\f ]+/.exec(context.source);
12336 if (match) {
12337 advanceBy(context, match[0].length);
12338 }
12339}
12340function getNewPosition(context, start, numberOfCharacters) {
12341 return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
12342}
12343function emitError(context, code, offset, loc = getCursor(context)) {
12344 if (offset) {
12345 loc.offset += offset;
12346 loc.column += offset;
12347 }
12348 context.options.onError(createCompilerError(code, {
12349 start: loc,
12350 end: loc,
12351 source: ''
12352 }));
12353}
12354function isEnd(context, mode, ancestors) {
12355 const s = context.source;
12356 switch (mode) {
12357 case 0 /* DATA */:
12358 if (startsWith(s, '</')) {
12359 // TODO: probably bad performance
12360 for (let i = ancestors.length - 1; i >= 0; --i) {
12361 if (startsWithEndTagOpen(s, ancestors[i].tag)) {
12362 return true;
12363 }
12364 }
12365 }
12366 break;
12367 case 1 /* RCDATA */:
12368 case 2 /* RAWTEXT */: {
12369 const parent = last(ancestors);
12370 if (parent && startsWithEndTagOpen(s, parent.tag)) {
12371 return true;
12372 }
12373 break;
12374 }
12375 case 3 /* CDATA */:
12376 if (startsWith(s, ']]>')) {
12377 return true;
12378 }
12379 break;
12380 }
12381 return !s;
12382}
12383function startsWithEndTagOpen(source, tag) {
12384 return (startsWith(source, '</') &&
12385 source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() &&
12386 /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
12387}
12388
12389function hoistStatic(root, context) {
12390 walk(root, context,
12391 // Root node is unfortunately non-hoistable due to potential parent
12392 // fallthrough attributes.
12393 isSingleElementRoot(root, root.children[0]));
12394}
12395function isSingleElementRoot(root, child) {
12396 const { children } = root;
12397 return (children.length === 1 &&
12398 child.type === 1 /* ELEMENT */ &&
12399 !isSlotOutlet(child));
12400}
12401function walk(node, context, doNotHoistNode = false) {
12402 const { children } = node;
12403 const originalCount = children.length;
12404 let hoistedCount = 0;
12405 for (let i = 0; i < children.length; i++) {
12406 const child = children[i];
12407 // only plain elements & text calls are eligible for hoisting.
12408 if (child.type === 1 /* ELEMENT */ &&
12409 child.tagType === 0 /* ELEMENT */) {
12410 const constantType = doNotHoistNode
12411 ? 0 /* NOT_CONSTANT */
12412 : getConstantType(child, context);
12413 if (constantType > 0 /* NOT_CONSTANT */) {
12414 if (constantType >= 2 /* CAN_HOIST */) {
12415 child.codegenNode.patchFlag =
12416 -1 /* HOISTED */ + (` /* HOISTED */` );
12417 child.codegenNode = context.hoist(child.codegenNode);
12418 hoistedCount++;
12419 continue;
12420 }
12421 }
12422 else {
12423 // node may contain dynamic children, but its props may be eligible for
12424 // hoisting.
12425 const codegenNode = child.codegenNode;
12426 if (codegenNode.type === 13 /* VNODE_CALL */) {
12427 const flag = getPatchFlag(codegenNode);
12428 if ((!flag ||
12429 flag === 512 /* NEED_PATCH */ ||
12430 flag === 1 /* TEXT */) &&
12431 getGeneratedPropsConstantType(child, context) >=
12432 2 /* CAN_HOIST */) {
12433 const props = getNodeProps(child);
12434 if (props) {
12435 codegenNode.props = context.hoist(props);
12436 }
12437 }
12438 if (codegenNode.dynamicProps) {
12439 codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
12440 }
12441 }
12442 }
12443 }
12444 else if (child.type === 12 /* TEXT_CALL */ &&
12445 getConstantType(child.content, context) >= 2 /* CAN_HOIST */) {
12446 child.codegenNode = context.hoist(child.codegenNode);
12447 hoistedCount++;
12448 }
12449 // walk further
12450 if (child.type === 1 /* ELEMENT */) {
12451 const isComponent = child.tagType === 1 /* COMPONENT */;
12452 if (isComponent) {
12453 context.scopes.vSlot++;
12454 }
12455 walk(child, context);
12456 if (isComponent) {
12457 context.scopes.vSlot--;
12458 }
12459 }
12460 else if (child.type === 11 /* FOR */) {
12461 // Do not hoist v-for single child because it has to be a block
12462 walk(child, context, child.children.length === 1);
12463 }
12464 else if (child.type === 9 /* IF */) {
12465 for (let i = 0; i < child.branches.length; i++) {
12466 // Do not hoist v-if single child because it has to be a block
12467 walk(child.branches[i], context, child.branches[i].children.length === 1);
12468 }
12469 }
12470 }
12471 if (hoistedCount && context.transformHoist) {
12472 context.transformHoist(children, context, node);
12473 }
12474 // all children were hoisted - the entire children array is hoistable.
12475 if (hoistedCount &&
12476 hoistedCount === originalCount &&
12477 node.type === 1 /* ELEMENT */ &&
12478 node.tagType === 0 /* ELEMENT */ &&
12479 node.codegenNode &&
12480 node.codegenNode.type === 13 /* VNODE_CALL */ &&
12481 isArray(node.codegenNode.children)) {
12482 node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
12483 }
12484}
12485function getConstantType(node, context) {
12486 const { constantCache } = context;
12487 switch (node.type) {
12488 case 1 /* ELEMENT */:
12489 if (node.tagType !== 0 /* ELEMENT */) {
12490 return 0 /* NOT_CONSTANT */;
12491 }
12492 const cached = constantCache.get(node);
12493 if (cached !== undefined) {
12494 return cached;
12495 }
12496 const codegenNode = node.codegenNode;
12497 if (codegenNode.type !== 13 /* VNODE_CALL */) {
12498 return 0 /* NOT_CONSTANT */;
12499 }
12500 if (codegenNode.isBlock &&
12501 node.tag !== 'svg' &&
12502 node.tag !== 'foreignObject') {
12503 return 0 /* NOT_CONSTANT */;
12504 }
12505 const flag = getPatchFlag(codegenNode);
12506 if (!flag) {
12507 let returnType = 3 /* CAN_STRINGIFY */;
12508 // Element itself has no patch flag. However we still need to check:
12509 // 1. Even for a node with no patch flag, it is possible for it to contain
12510 // non-hoistable expressions that refers to scope variables, e.g. compiler
12511 // injected keys or cached event handlers. Therefore we need to always
12512 // check the codegenNode's props to be sure.
12513 const generatedPropsType = getGeneratedPropsConstantType(node, context);
12514 if (generatedPropsType === 0 /* NOT_CONSTANT */) {
12515 constantCache.set(node, 0 /* NOT_CONSTANT */);
12516 return 0 /* NOT_CONSTANT */;
12517 }
12518 if (generatedPropsType < returnType) {
12519 returnType = generatedPropsType;
12520 }
12521 // 2. its children.
12522 for (let i = 0; i < node.children.length; i++) {
12523 const childType = getConstantType(node.children[i], context);
12524 if (childType === 0 /* NOT_CONSTANT */) {
12525 constantCache.set(node, 0 /* NOT_CONSTANT */);
12526 return 0 /* NOT_CONSTANT */;
12527 }
12528 if (childType < returnType) {
12529 returnType = childType;
12530 }
12531 }
12532 // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
12533 // type, check if any of the props can cause the type to be lowered
12534 // we can skip can_patch because it's guaranteed by the absence of a
12535 // patchFlag.
12536 if (returnType > 1 /* CAN_SKIP_PATCH */) {
12537 for (let i = 0; i < node.props.length; i++) {
12538 const p = node.props[i];
12539 if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
12540 const expType = getConstantType(p.exp, context);
12541 if (expType === 0 /* NOT_CONSTANT */) {
12542 constantCache.set(node, 0 /* NOT_CONSTANT */);
12543 return 0 /* NOT_CONSTANT */;
12544 }
12545 if (expType < returnType) {
12546 returnType = expType;
12547 }
12548 }
12549 }
12550 }
12551 // only svg/foreignObject could be block here, however if they are
12552 // static then they don't need to be blocks since there will be no
12553 // nested updates.
12554 if (codegenNode.isBlock) {
12555 context.removeHelper(OPEN_BLOCK);
12556 context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
12557 codegenNode.isBlock = false;
12558 context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
12559 }
12560 constantCache.set(node, returnType);
12561 return returnType;
12562 }
12563 else {
12564 constantCache.set(node, 0 /* NOT_CONSTANT */);
12565 return 0 /* NOT_CONSTANT */;
12566 }
12567 case 2 /* TEXT */:
12568 case 3 /* COMMENT */:
12569 return 3 /* CAN_STRINGIFY */;
12570 case 9 /* IF */:
12571 case 11 /* FOR */:
12572 case 10 /* IF_BRANCH */:
12573 return 0 /* NOT_CONSTANT */;
12574 case 5 /* INTERPOLATION */:
12575 case 12 /* TEXT_CALL */:
12576 return getConstantType(node.content, context);
12577 case 4 /* SIMPLE_EXPRESSION */:
12578 return node.constType;
12579 case 8 /* COMPOUND_EXPRESSION */:
12580 let returnType = 3 /* CAN_STRINGIFY */;
12581 for (let i = 0; i < node.children.length; i++) {
12582 const child = node.children[i];
12583 if (isString(child) || isSymbol(child)) {
12584 continue;
12585 }
12586 const childType = getConstantType(child, context);
12587 if (childType === 0 /* NOT_CONSTANT */) {
12588 return 0 /* NOT_CONSTANT */;
12589 }
12590 else if (childType < returnType) {
12591 returnType = childType;
12592 }
12593 }
12594 return returnType;
12595 default:
12596 return 0 /* NOT_CONSTANT */;
12597 }
12598}
12599const allowHoistedHelperSet = new Set([
12600 NORMALIZE_CLASS,
12601 NORMALIZE_STYLE,
12602 NORMALIZE_PROPS,
12603 GUARD_REACTIVE_PROPS
12604]);
12605function getConstantTypeOfHelperCall(value, context) {
12606 if (value.type === 14 /* JS_CALL_EXPRESSION */ &&
12607 !isString(value.callee) &&
12608 allowHoistedHelperSet.has(value.callee)) {
12609 const arg = value.arguments[0];
12610 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
12611 return getConstantType(arg, context);
12612 }
12613 else if (arg.type === 14 /* JS_CALL_EXPRESSION */) {
12614 // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
12615 return getConstantTypeOfHelperCall(arg, context);
12616 }
12617 }
12618 return 0 /* NOT_CONSTANT */;
12619}
12620function getGeneratedPropsConstantType(node, context) {
12621 let returnType = 3 /* CAN_STRINGIFY */;
12622 const props = getNodeProps(node);
12623 if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
12624 const { properties } = props;
12625 for (let i = 0; i < properties.length; i++) {
12626 const { key, value } = properties[i];
12627 const keyType = getConstantType(key, context);
12628 if (keyType === 0 /* NOT_CONSTANT */) {
12629 return keyType;
12630 }
12631 if (keyType < returnType) {
12632 returnType = keyType;
12633 }
12634 let valueType;
12635 if (value.type === 4 /* SIMPLE_EXPRESSION */) {
12636 valueType = getConstantType(value, context);
12637 }
12638 else if (value.type === 14 /* JS_CALL_EXPRESSION */) {
12639 // some helper calls can be hoisted,
12640 // such as the `normalizeProps` generated by the compiler for pre-normalize class,
12641 // in this case we need to respect the ConstantType of the helper's arguments
12642 valueType = getConstantTypeOfHelperCall(value, context);
12643 }
12644 else {
12645 valueType = 0 /* NOT_CONSTANT */;
12646 }
12647 if (valueType === 0 /* NOT_CONSTANT */) {
12648 return valueType;
12649 }
12650 if (valueType < returnType) {
12651 returnType = valueType;
12652 }
12653 }
12654 }
12655 return returnType;
12656}
12657function getNodeProps(node) {
12658 const codegenNode = node.codegenNode;
12659 if (codegenNode.type === 13 /* VNODE_CALL */) {
12660 return codegenNode.props;
12661 }
12662}
12663function getPatchFlag(node) {
12664 const flag = node.patchFlag;
12665 return flag ? parseInt(flag, 10) : undefined;
12666}
12667
12668function 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 }) {
12669 const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
12670 const context = {
12671 // options
12672 selfName: nameMatch && capitalize(camelize(nameMatch[1])),
12673 prefixIdentifiers,
12674 hoistStatic,
12675 cacheHandlers,
12676 nodeTransforms,
12677 directiveTransforms,
12678 transformHoist,
12679 isBuiltInComponent,
12680 isCustomElement,
12681 expressionPlugins,
12682 scopeId,
12683 slotted,
12684 ssr,
12685 inSSR,
12686 ssrCssVars,
12687 bindingMetadata,
12688 inline,
12689 isTS,
12690 onError,
12691 onWarn,
12692 compatConfig,
12693 // state
12694 root,
12695 helpers: new Map(),
12696 components: new Set(),
12697 directives: new Set(),
12698 hoists: [],
12699 imports: [],
12700 constantCache: new Map(),
12701 temps: 0,
12702 cached: 0,
12703 identifiers: Object.create(null),
12704 scopes: {
12705 vFor: 0,
12706 vSlot: 0,
12707 vPre: 0,
12708 vOnce: 0
12709 },
12710 parent: null,
12711 currentNode: root,
12712 childIndex: 0,
12713 inVOnce: false,
12714 // methods
12715 helper(name) {
12716 const count = context.helpers.get(name) || 0;
12717 context.helpers.set(name, count + 1);
12718 return name;
12719 },
12720 removeHelper(name) {
12721 const count = context.helpers.get(name);
12722 if (count) {
12723 const currentCount = count - 1;
12724 if (!currentCount) {
12725 context.helpers.delete(name);
12726 }
12727 else {
12728 context.helpers.set(name, currentCount);
12729 }
12730 }
12731 },
12732 helperString(name) {
12733 return `_${helperNameMap[context.helper(name)]}`;
12734 },
12735 replaceNode(node) {
12736 /* istanbul ignore if */
12737 {
12738 if (!context.currentNode) {
12739 throw new Error(`Node being replaced is already removed.`);
12740 }
12741 if (!context.parent) {
12742 throw new Error(`Cannot replace root node.`);
12743 }
12744 }
12745 context.parent.children[context.childIndex] = context.currentNode = node;
12746 },
12747 removeNode(node) {
12748 if (!context.parent) {
12749 throw new Error(`Cannot remove root node.`);
12750 }
12751 const list = context.parent.children;
12752 const removalIndex = node
12753 ? list.indexOf(node)
12754 : context.currentNode
12755 ? context.childIndex
12756 : -1;
12757 /* istanbul ignore if */
12758 if (removalIndex < 0) {
12759 throw new Error(`node being removed is not a child of current parent`);
12760 }
12761 if (!node || node === context.currentNode) {
12762 // current node removed
12763 context.currentNode = null;
12764 context.onNodeRemoved();
12765 }
12766 else {
12767 // sibling node removed
12768 if (context.childIndex > removalIndex) {
12769 context.childIndex--;
12770 context.onNodeRemoved();
12771 }
12772 }
12773 context.parent.children.splice(removalIndex, 1);
12774 },
12775 onNodeRemoved: () => { },
12776 addIdentifiers(exp) {
12777 },
12778 removeIdentifiers(exp) {
12779 },
12780 hoist(exp) {
12781 if (isString(exp))
12782 exp = createSimpleExpression(exp);
12783 context.hoists.push(exp);
12784 const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
12785 identifier.hoisted = exp;
12786 return identifier;
12787 },
12788 cache(exp, isVNode = false) {
12789 return createCacheExpression(context.cached++, exp, isVNode);
12790 }
12791 };
12792 return context;
12793}
12794function transform(root, options) {
12795 const context = createTransformContext(root, options);
12796 traverseNode(root, context);
12797 if (options.hoistStatic) {
12798 hoistStatic(root, context);
12799 }
12800 if (!options.ssr) {
12801 createRootCodegen(root, context);
12802 }
12803 // finalize meta information
12804 root.helpers = [...context.helpers.keys()];
12805 root.components = [...context.components];
12806 root.directives = [...context.directives];
12807 root.imports = context.imports;
12808 root.hoists = context.hoists;
12809 root.temps = context.temps;
12810 root.cached = context.cached;
12811}
12812function createRootCodegen(root, context) {
12813 const { helper } = context;
12814 const { children } = root;
12815 if (children.length === 1) {
12816 const child = children[0];
12817 // if the single child is an element, turn it into a block.
12818 if (isSingleElementRoot(root, child) && child.codegenNode) {
12819 // single element root is never hoisted so codegenNode will never be
12820 // SimpleExpressionNode
12821 const codegenNode = child.codegenNode;
12822 if (codegenNode.type === 13 /* VNODE_CALL */) {
12823 makeBlock(codegenNode, context);
12824 }
12825 root.codegenNode = codegenNode;
12826 }
12827 else {
12828 // - single <slot/>, IfNode, ForNode: already blocks.
12829 // - single text node: always patched.
12830 // root codegen falls through via genNode()
12831 root.codegenNode = child;
12832 }
12833 }
12834 else if (children.length > 1) {
12835 // root has multiple nodes - return a fragment block.
12836 let patchFlag = 64 /* STABLE_FRAGMENT */;
12837 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
12838 // check if the fragment actually contains a single valid child with
12839 // the rest being comments
12840 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
12841 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
12842 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
12843 }
12844 root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, undefined, false /* isComponent */);
12845 }
12846 else ;
12847}
12848function traverseChildren(parent, context) {
12849 let i = 0;
12850 const nodeRemoved = () => {
12851 i--;
12852 };
12853 for (; i < parent.children.length; i++) {
12854 const child = parent.children[i];
12855 if (isString(child))
12856 continue;
12857 context.parent = parent;
12858 context.childIndex = i;
12859 context.onNodeRemoved = nodeRemoved;
12860 traverseNode(child, context);
12861 }
12862}
12863function traverseNode(node, context) {
12864 context.currentNode = node;
12865 // apply transform plugins
12866 const { nodeTransforms } = context;
12867 const exitFns = [];
12868 for (let i = 0; i < nodeTransforms.length; i++) {
12869 const onExit = nodeTransforms[i](node, context);
12870 if (onExit) {
12871 if (isArray(onExit)) {
12872 exitFns.push(...onExit);
12873 }
12874 else {
12875 exitFns.push(onExit);
12876 }
12877 }
12878 if (!context.currentNode) {
12879 // node was removed
12880 return;
12881 }
12882 else {
12883 // node may have been replaced
12884 node = context.currentNode;
12885 }
12886 }
12887 switch (node.type) {
12888 case 3 /* COMMENT */:
12889 if (!context.ssr) {
12890 // inject import for the Comment symbol, which is needed for creating
12891 // comment nodes with `createVNode`
12892 context.helper(CREATE_COMMENT);
12893 }
12894 break;
12895 case 5 /* INTERPOLATION */:
12896 // no need to traverse, but we need to inject toString helper
12897 if (!context.ssr) {
12898 context.helper(TO_DISPLAY_STRING);
12899 }
12900 break;
12901 // for container types, further traverse downwards
12902 case 9 /* IF */:
12903 for (let i = 0; i < node.branches.length; i++) {
12904 traverseNode(node.branches[i], context);
12905 }
12906 break;
12907 case 10 /* IF_BRANCH */:
12908 case 11 /* FOR */:
12909 case 1 /* ELEMENT */:
12910 case 0 /* ROOT */:
12911 traverseChildren(node, context);
12912 break;
12913 }
12914 // exit transforms
12915 context.currentNode = node;
12916 let i = exitFns.length;
12917 while (i--) {
12918 exitFns[i]();
12919 }
12920}
12921function createStructuralDirectiveTransform(name, fn) {
12922 const matches = isString(name)
12923 ? (n) => n === name
12924 : (n) => name.test(n);
12925 return (node, context) => {
12926 if (node.type === 1 /* ELEMENT */) {
12927 const { props } = node;
12928 // structural directive transforms are not concerned with slots
12929 // as they are handled separately in vSlot.ts
12930 if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
12931 return;
12932 }
12933 const exitFns = [];
12934 for (let i = 0; i < props.length; i++) {
12935 const prop = props[i];
12936 if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
12937 // structural directives are removed to avoid infinite recursion
12938 // also we remove them *before* applying so that it can further
12939 // traverse itself in case it moves the node around
12940 props.splice(i, 1);
12941 i--;
12942 const onExit = fn(node, prop, context);
12943 if (onExit)
12944 exitFns.push(onExit);
12945 }
12946 }
12947 return exitFns;
12948 }
12949 };
12950}
12951
12952const PURE_ANNOTATION = `/*#__PURE__*/`;
12953function 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 }) {
12954 const context = {
12955 mode,
12956 prefixIdentifiers,
12957 sourceMap,
12958 filename,
12959 scopeId,
12960 optimizeImports,
12961 runtimeGlobalName,
12962 runtimeModuleName,
12963 ssrRuntimeModuleName,
12964 ssr,
12965 isTS,
12966 inSSR,
12967 source: ast.loc.source,
12968 code: ``,
12969 column: 1,
12970 line: 1,
12971 offset: 0,
12972 indentLevel: 0,
12973 pure: false,
12974 map: undefined,
12975 helper(key) {
12976 return `_${helperNameMap[key]}`;
12977 },
12978 push(code, node) {
12979 context.code += code;
12980 },
12981 indent() {
12982 newline(++context.indentLevel);
12983 },
12984 deindent(withoutNewLine = false) {
12985 if (withoutNewLine) {
12986 --context.indentLevel;
12987 }
12988 else {
12989 newline(--context.indentLevel);
12990 }
12991 },
12992 newline() {
12993 newline(context.indentLevel);
12994 }
12995 };
12996 function newline(n) {
12997 context.push('\n' + ` `.repeat(n));
12998 }
12999 return context;
13000}
13001function generate(ast, options = {}) {
13002 const context = createCodegenContext(ast, options);
13003 if (options.onContextCreated)
13004 options.onContextCreated(context);
13005 const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
13006 const hasHelpers = ast.helpers.length > 0;
13007 const useWithBlock = !prefixIdentifiers && mode !== 'module';
13008 // preambles
13009 // in setup() inline mode, the preamble is generated in a sub context
13010 // and returned separately.
13011 const preambleContext = context;
13012 {
13013 genFunctionPreamble(ast, preambleContext);
13014 }
13015 // enter render function
13016 const functionName = ssr ? `ssrRender` : `render`;
13017 const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
13018 const signature = args.join(', ');
13019 {
13020 push(`function ${functionName}(${signature}) {`);
13021 }
13022 indent();
13023 if (useWithBlock) {
13024 push(`with (_ctx) {`);
13025 indent();
13026 // function mode const declarations should be inside with block
13027 // also they should be renamed to avoid collision with user properties
13028 if (hasHelpers) {
13029 push(`const { ${ast.helpers
13030 .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
13031 .join(', ')} } = _Vue`);
13032 push(`\n`);
13033 newline();
13034 }
13035 }
13036 // generate asset resolution statements
13037 if (ast.components.length) {
13038 genAssets(ast.components, 'component', context);
13039 if (ast.directives.length || ast.temps > 0) {
13040 newline();
13041 }
13042 }
13043 if (ast.directives.length) {
13044 genAssets(ast.directives, 'directive', context);
13045 if (ast.temps > 0) {
13046 newline();
13047 }
13048 }
13049 if (ast.temps > 0) {
13050 push(`let `);
13051 for (let i = 0; i < ast.temps; i++) {
13052 push(`${i > 0 ? `, ` : ``}_temp${i}`);
13053 }
13054 }
13055 if (ast.components.length || ast.directives.length || ast.temps) {
13056 push(`\n`);
13057 newline();
13058 }
13059 // generate the VNode tree expression
13060 if (!ssr) {
13061 push(`return `);
13062 }
13063 if (ast.codegenNode) {
13064 genNode(ast.codegenNode, context);
13065 }
13066 else {
13067 push(`null`);
13068 }
13069 if (useWithBlock) {
13070 deindent();
13071 push(`}`);
13072 }
13073 deindent();
13074 push(`}`);
13075 return {
13076 ast,
13077 code: context.code,
13078 preamble: ``,
13079 // SourceMapGenerator does have toJSON() method but it's not in the types
13080 map: context.map ? context.map.toJSON() : undefined
13081 };
13082}
13083function genFunctionPreamble(ast, context) {
13084 const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName, ssrRuntimeModuleName } = context;
13085 const VueBinding = runtimeGlobalName;
13086 const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
13087 // Generate const declaration for helpers
13088 // In prefix mode, we place the const declaration at top so it's done
13089 // only once; But if we not prefixing, we place the declaration inside the
13090 // with block so it doesn't incur the `in` check cost for every helper access.
13091 if (ast.helpers.length > 0) {
13092 {
13093 // "with" mode.
13094 // save Vue in a separate variable to avoid collision
13095 push(`const _Vue = ${VueBinding}\n`);
13096 // in "with" mode, helpers are declared inside the with block to avoid
13097 // has check cost, but hoists are lifted out of the function - we need
13098 // to provide the helper here.
13099 if (ast.hoists.length) {
13100 const staticHelpers = [
13101 CREATE_VNODE,
13102 CREATE_ELEMENT_VNODE,
13103 CREATE_COMMENT,
13104 CREATE_TEXT,
13105 CREATE_STATIC
13106 ]
13107 .filter(helper => ast.helpers.includes(helper))
13108 .map(aliasHelper)
13109 .join(', ');
13110 push(`const { ${staticHelpers} } = _Vue\n`);
13111 }
13112 }
13113 }
13114 genHoists(ast.hoists, context);
13115 newline();
13116 push(`return `);
13117}
13118function genAssets(assets, type, { helper, push, newline, isTS }) {
13119 const resolver = helper(type === 'component'
13120 ? RESOLVE_COMPONENT
13121 : RESOLVE_DIRECTIVE);
13122 for (let i = 0; i < assets.length; i++) {
13123 let id = assets[i];
13124 // potential component implicit self-reference inferred from SFC filename
13125 const maybeSelfReference = id.endsWith('__self');
13126 if (maybeSelfReference) {
13127 id = id.slice(0, -6);
13128 }
13129 push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
13130 if (i < assets.length - 1) {
13131 newline();
13132 }
13133 }
13134}
13135function genHoists(hoists, context) {
13136 if (!hoists.length) {
13137 return;
13138 }
13139 context.pure = true;
13140 const { push, newline, helper, scopeId, mode } = context;
13141 newline();
13142 for (let i = 0; i < hoists.length; i++) {
13143 const exp = hoists[i];
13144 if (exp) {
13145 push(`const _hoisted_${i + 1} = ${``}`);
13146 genNode(exp, context);
13147 newline();
13148 }
13149 }
13150 context.pure = false;
13151}
13152function isText$1(n) {
13153 return (isString(n) ||
13154 n.type === 4 /* SIMPLE_EXPRESSION */ ||
13155 n.type === 2 /* TEXT */ ||
13156 n.type === 5 /* INTERPOLATION */ ||
13157 n.type === 8 /* COMPOUND_EXPRESSION */);
13158}
13159function genNodeListAsArray(nodes, context) {
13160 const multilines = nodes.length > 3 ||
13161 (nodes.some(n => isArray(n) || !isText$1(n)));
13162 context.push(`[`);
13163 multilines && context.indent();
13164 genNodeList(nodes, context, multilines);
13165 multilines && context.deindent();
13166 context.push(`]`);
13167}
13168function genNodeList(nodes, context, multilines = false, comma = true) {
13169 const { push, newline } = context;
13170 for (let i = 0; i < nodes.length; i++) {
13171 const node = nodes[i];
13172 if (isString(node)) {
13173 push(node);
13174 }
13175 else if (isArray(node)) {
13176 genNodeListAsArray(node, context);
13177 }
13178 else {
13179 genNode(node, context);
13180 }
13181 if (i < nodes.length - 1) {
13182 if (multilines) {
13183 comma && push(',');
13184 newline();
13185 }
13186 else {
13187 comma && push(', ');
13188 }
13189 }
13190 }
13191}
13192function genNode(node, context) {
13193 if (isString(node)) {
13194 context.push(node);
13195 return;
13196 }
13197 if (isSymbol(node)) {
13198 context.push(context.helper(node));
13199 return;
13200 }
13201 switch (node.type) {
13202 case 1 /* ELEMENT */:
13203 case 9 /* IF */:
13204 case 11 /* FOR */:
13205 assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
13206 `Apply appropriate transforms first.`);
13207 genNode(node.codegenNode, context);
13208 break;
13209 case 2 /* TEXT */:
13210 genText(node, context);
13211 break;
13212 case 4 /* SIMPLE_EXPRESSION */:
13213 genExpression(node, context);
13214 break;
13215 case 5 /* INTERPOLATION */:
13216 genInterpolation(node, context);
13217 break;
13218 case 12 /* TEXT_CALL */:
13219 genNode(node.codegenNode, context);
13220 break;
13221 case 8 /* COMPOUND_EXPRESSION */:
13222 genCompoundExpression(node, context);
13223 break;
13224 case 3 /* COMMENT */:
13225 genComment(node, context);
13226 break;
13227 case 13 /* VNODE_CALL */:
13228 genVNodeCall(node, context);
13229 break;
13230 case 14 /* JS_CALL_EXPRESSION */:
13231 genCallExpression(node, context);
13232 break;
13233 case 15 /* JS_OBJECT_EXPRESSION */:
13234 genObjectExpression(node, context);
13235 break;
13236 case 17 /* JS_ARRAY_EXPRESSION */:
13237 genArrayExpression(node, context);
13238 break;
13239 case 18 /* JS_FUNCTION_EXPRESSION */:
13240 genFunctionExpression(node, context);
13241 break;
13242 case 19 /* JS_CONDITIONAL_EXPRESSION */:
13243 genConditionalExpression(node, context);
13244 break;
13245 case 20 /* JS_CACHE_EXPRESSION */:
13246 genCacheExpression(node, context);
13247 break;
13248 case 21 /* JS_BLOCK_STATEMENT */:
13249 genNodeList(node.body, context, true, false);
13250 break;
13251 // SSR only types
13252 case 22 /* JS_TEMPLATE_LITERAL */:
13253 break;
13254 case 23 /* JS_IF_STATEMENT */:
13255 break;
13256 case 24 /* JS_ASSIGNMENT_EXPRESSION */:
13257 break;
13258 case 25 /* JS_SEQUENCE_EXPRESSION */:
13259 break;
13260 case 26 /* JS_RETURN_STATEMENT */:
13261 break;
13262 /* istanbul ignore next */
13263 case 10 /* IF_BRANCH */:
13264 // noop
13265 break;
13266 default:
13267 {
13268 assert(false, `unhandled codegen node type: ${node.type}`);
13269 // make sure we exhaust all possible types
13270 const exhaustiveCheck = node;
13271 return exhaustiveCheck;
13272 }
13273 }
13274}
13275function genText(node, context) {
13276 context.push(JSON.stringify(node.content), node);
13277}
13278function genExpression(node, context) {
13279 const { content, isStatic } = node;
13280 context.push(isStatic ? JSON.stringify(content) : content, node);
13281}
13282function genInterpolation(node, context) {
13283 const { push, helper, pure } = context;
13284 if (pure)
13285 push(PURE_ANNOTATION);
13286 push(`${helper(TO_DISPLAY_STRING)}(`);
13287 genNode(node.content, context);
13288 push(`)`);
13289}
13290function genCompoundExpression(node, context) {
13291 for (let i = 0; i < node.children.length; i++) {
13292 const child = node.children[i];
13293 if (isString(child)) {
13294 context.push(child);
13295 }
13296 else {
13297 genNode(child, context);
13298 }
13299 }
13300}
13301function genExpressionAsPropertyKey(node, context) {
13302 const { push } = context;
13303 if (node.type === 8 /* COMPOUND_EXPRESSION */) {
13304 push(`[`);
13305 genCompoundExpression(node, context);
13306 push(`]`);
13307 }
13308 else if (node.isStatic) {
13309 // only quote keys if necessary
13310 const text = isSimpleIdentifier(node.content)
13311 ? node.content
13312 : JSON.stringify(node.content);
13313 push(text, node);
13314 }
13315 else {
13316 push(`[${node.content}]`, node);
13317 }
13318}
13319function genComment(node, context) {
13320 const { push, helper, pure } = context;
13321 if (pure) {
13322 push(PURE_ANNOTATION);
13323 }
13324 push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
13325}
13326function genVNodeCall(node, context) {
13327 const { push, helper, pure } = context;
13328 const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
13329 if (directives) {
13330 push(helper(WITH_DIRECTIVES) + `(`);
13331 }
13332 if (isBlock) {
13333 push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
13334 }
13335 if (pure) {
13336 push(PURE_ANNOTATION);
13337 }
13338 const callHelper = isBlock
13339 ? getVNodeBlockHelper(context.inSSR, isComponent)
13340 : getVNodeHelper(context.inSSR, isComponent);
13341 push(helper(callHelper) + `(`, node);
13342 genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
13343 push(`)`);
13344 if (isBlock) {
13345 push(`)`);
13346 }
13347 if (directives) {
13348 push(`, `);
13349 genNode(directives, context);
13350 push(`)`);
13351 }
13352}
13353function genNullableArgs(args) {
13354 let i = args.length;
13355 while (i--) {
13356 if (args[i] != null)
13357 break;
13358 }
13359 return args.slice(0, i + 1).map(arg => arg || `null`);
13360}
13361// JavaScript
13362function genCallExpression(node, context) {
13363 const { push, helper, pure } = context;
13364 const callee = isString(node.callee) ? node.callee : helper(node.callee);
13365 if (pure) {
13366 push(PURE_ANNOTATION);
13367 }
13368 push(callee + `(`, node);
13369 genNodeList(node.arguments, context);
13370 push(`)`);
13371}
13372function genObjectExpression(node, context) {
13373 const { push, indent, deindent, newline } = context;
13374 const { properties } = node;
13375 if (!properties.length) {
13376 push(`{}`, node);
13377 return;
13378 }
13379 const multilines = properties.length > 1 ||
13380 (properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
13381 push(multilines ? `{` : `{ `);
13382 multilines && indent();
13383 for (let i = 0; i < properties.length; i++) {
13384 const { key, value } = properties[i];
13385 // key
13386 genExpressionAsPropertyKey(key, context);
13387 push(`: `);
13388 // value
13389 genNode(value, context);
13390 if (i < properties.length - 1) {
13391 // will only reach this if it's multilines
13392 push(`,`);
13393 newline();
13394 }
13395 }
13396 multilines && deindent();
13397 push(multilines ? `}` : ` }`);
13398}
13399function genArrayExpression(node, context) {
13400 genNodeListAsArray(node.elements, context);
13401}
13402function genFunctionExpression(node, context) {
13403 const { push, indent, deindent } = context;
13404 const { params, returns, body, newline, isSlot } = node;
13405 if (isSlot) {
13406 // wrap slot functions with owner context
13407 push(`_${helperNameMap[WITH_CTX]}(`);
13408 }
13409 push(`(`, node);
13410 if (isArray(params)) {
13411 genNodeList(params, context);
13412 }
13413 else if (params) {
13414 genNode(params, context);
13415 }
13416 push(`) => `);
13417 if (newline || body) {
13418 push(`{`);
13419 indent();
13420 }
13421 if (returns) {
13422 if (newline) {
13423 push(`return `);
13424 }
13425 if (isArray(returns)) {
13426 genNodeListAsArray(returns, context);
13427 }
13428 else {
13429 genNode(returns, context);
13430 }
13431 }
13432 else if (body) {
13433 genNode(body, context);
13434 }
13435 if (newline || body) {
13436 deindent();
13437 push(`}`);
13438 }
13439 if (isSlot) {
13440 push(`)`);
13441 }
13442}
13443function genConditionalExpression(node, context) {
13444 const { test, consequent, alternate, newline: needNewline } = node;
13445 const { push, indent, deindent, newline } = context;
13446 if (test.type === 4 /* SIMPLE_EXPRESSION */) {
13447 const needsParens = !isSimpleIdentifier(test.content);
13448 needsParens && push(`(`);
13449 genExpression(test, context);
13450 needsParens && push(`)`);
13451 }
13452 else {
13453 push(`(`);
13454 genNode(test, context);
13455 push(`)`);
13456 }
13457 needNewline && indent();
13458 context.indentLevel++;
13459 needNewline || push(` `);
13460 push(`? `);
13461 genNode(consequent, context);
13462 context.indentLevel--;
13463 needNewline && newline();
13464 needNewline || push(` `);
13465 push(`: `);
13466 const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
13467 if (!isNested) {
13468 context.indentLevel++;
13469 }
13470 genNode(alternate, context);
13471 if (!isNested) {
13472 context.indentLevel--;
13473 }
13474 needNewline && deindent(true /* without newline */);
13475}
13476function genCacheExpression(node, context) {
13477 const { push, helper, indent, deindent, newline } = context;
13478 push(`_cache[${node.index}] || (`);
13479 if (node.isVNode) {
13480 indent();
13481 push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
13482 newline();
13483 }
13484 push(`_cache[${node.index}] = `);
13485 genNode(node.value, context);
13486 if (node.isVNode) {
13487 push(`,`);
13488 newline();
13489 push(`${helper(SET_BLOCK_TRACKING)}(1),`);
13490 newline();
13491 push(`_cache[${node.index}]`);
13492 deindent();
13493 }
13494 push(`)`);
13495}
13496
13497// these keywords should not appear inside expressions, but operators like
13498// typeof, instanceof and in are allowed
13499const prohibitedKeywordRE = new RegExp('\\b' +
13500 ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
13501 'super,throw,while,yield,delete,export,import,return,switch,default,' +
13502 'extends,finally,continue,debugger,function,arguments,typeof,void')
13503 .split(',')
13504 .join('\\b|\\b') +
13505 '\\b');
13506// strip strings in expressions
13507const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
13508/**
13509 * Validate a non-prefixed expression.
13510 * This is only called when using the in-browser runtime compiler since it
13511 * doesn't prefix expressions.
13512 */
13513function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
13514 const exp = node.content;
13515 // empty expressions are validated per-directive since some directives
13516 // do allow empty expressions.
13517 if (!exp.trim()) {
13518 return;
13519 }
13520 try {
13521 new Function(asRawStatements
13522 ? ` ${exp} `
13523 : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
13524 }
13525 catch (e) {
13526 let message = e.message;
13527 const keywordMatch = exp
13528 .replace(stripStringRE, '')
13529 .match(prohibitedKeywordRE);
13530 if (keywordMatch) {
13531 message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
13532 }
13533 context.onError(createCompilerError(44 /* X_INVALID_EXPRESSION */, node.loc, undefined, message));
13534 }
13535}
13536
13537const transformExpression = (node, context) => {
13538 if (node.type === 5 /* INTERPOLATION */) {
13539 node.content = processExpression(node.content, context);
13540 }
13541 else if (node.type === 1 /* ELEMENT */) {
13542 // handle directives on element
13543 for (let i = 0; i < node.props.length; i++) {
13544 const dir = node.props[i];
13545 // do not process for v-on & v-for since they are special handled
13546 if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
13547 const exp = dir.exp;
13548 const arg = dir.arg;
13549 // do not process exp if this is v-on:arg - we need special handling
13550 // for wrapping inline statements.
13551 if (exp &&
13552 exp.type === 4 /* SIMPLE_EXPRESSION */ &&
13553 !(dir.name === 'on' && arg)) {
13554 dir.exp = processExpression(exp, context,
13555 // slot args must be processed as function params
13556 dir.name === 'slot');
13557 }
13558 if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
13559 dir.arg = processExpression(arg, context);
13560 }
13561 }
13562 }
13563 }
13564};
13565// Important: since this function uses Node.js only dependencies, it should
13566// always be used with a leading !true check so that it can be
13567// tree-shaken from the browser build.
13568function processExpression(node, context,
13569// some expressions like v-slot props & v-for aliases should be parsed as
13570// function params
13571asParams = false,
13572// v-on handler values may contain multiple statements
13573asRawStatements = false, localVars = Object.create(context.identifiers)) {
13574 {
13575 {
13576 // simple in-browser validation (same logic in 2.x)
13577 validateBrowserExpression(node, context, asParams, asRawStatements);
13578 }
13579 return node;
13580 }
13581}
13582
13583const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
13584 return processIf(node, dir, context, (ifNode, branch, isRoot) => {
13585 // #1587: We need to dynamically increment the key based on the current
13586 // node's sibling nodes, since chained v-if/else branches are
13587 // rendered at the same depth
13588 const siblings = context.parent.children;
13589 let i = siblings.indexOf(ifNode);
13590 let key = 0;
13591 while (i-- >= 0) {
13592 const sibling = siblings[i];
13593 if (sibling && sibling.type === 9 /* IF */) {
13594 key += sibling.branches.length;
13595 }
13596 }
13597 // Exit callback. Complete the codegenNode when all children have been
13598 // transformed.
13599 return () => {
13600 if (isRoot) {
13601 ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
13602 }
13603 else {
13604 // attach this branch's codegen node to the v-if root.
13605 const parentCondition = getParentCondition(ifNode.codegenNode);
13606 parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
13607 }
13608 };
13609 });
13610});
13611// target-agnostic transform used for both Client and SSR
13612function processIf(node, dir, context, processCodegen) {
13613 if (dir.name !== 'else' &&
13614 (!dir.exp || !dir.exp.content.trim())) {
13615 const loc = dir.exp ? dir.exp.loc : node.loc;
13616 context.onError(createCompilerError(28 /* X_V_IF_NO_EXPRESSION */, dir.loc));
13617 dir.exp = createSimpleExpression(`true`, false, loc);
13618 }
13619 if (dir.exp) {
13620 validateBrowserExpression(dir.exp, context);
13621 }
13622 if (dir.name === 'if') {
13623 const branch = createIfBranch(node, dir);
13624 const ifNode = {
13625 type: 9 /* IF */,
13626 loc: node.loc,
13627 branches: [branch]
13628 };
13629 context.replaceNode(ifNode);
13630 if (processCodegen) {
13631 return processCodegen(ifNode, branch, true);
13632 }
13633 }
13634 else {
13635 // locate the adjacent v-if
13636 const siblings = context.parent.children;
13637 const comments = [];
13638 let i = siblings.indexOf(node);
13639 while (i-- >= -1) {
13640 const sibling = siblings[i];
13641 if (sibling && sibling.type === 3 /* COMMENT */) {
13642 context.removeNode(sibling);
13643 comments.unshift(sibling);
13644 continue;
13645 }
13646 if (sibling &&
13647 sibling.type === 2 /* TEXT */ &&
13648 !sibling.content.trim().length) {
13649 context.removeNode(sibling);
13650 continue;
13651 }
13652 if (sibling && sibling.type === 9 /* IF */) {
13653 // Check if v-else was followed by v-else-if
13654 if (dir.name === 'else-if' &&
13655 sibling.branches[sibling.branches.length - 1].condition === undefined) {
13656 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
13657 }
13658 // move the node to the if node's branches
13659 context.removeNode();
13660 const branch = createIfBranch(node, dir);
13661 if (comments.length &&
13662 // #3619 ignore comments if the v-if is direct child of <transition>
13663 !(context.parent &&
13664 context.parent.type === 1 /* ELEMENT */ &&
13665 isBuiltInType(context.parent.tag, 'transition'))) {
13666 branch.children = [...comments, ...branch.children];
13667 }
13668 // check if user is forcing same key on different branches
13669 {
13670 const key = branch.userKey;
13671 if (key) {
13672 sibling.branches.forEach(({ userKey }) => {
13673 if (isSameKey(userKey, key)) {
13674 context.onError(createCompilerError(29 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
13675 }
13676 });
13677 }
13678 }
13679 sibling.branches.push(branch);
13680 const onExit = processCodegen && processCodegen(sibling, branch, false);
13681 // since the branch was removed, it will not be traversed.
13682 // make sure to traverse here.
13683 traverseNode(branch, context);
13684 // call on exit
13685 if (onExit)
13686 onExit();
13687 // make sure to reset currentNode after traversal to indicate this
13688 // node has been removed.
13689 context.currentNode = null;
13690 }
13691 else {
13692 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
13693 }
13694 break;
13695 }
13696 }
13697}
13698function createIfBranch(node, dir) {
13699 return {
13700 type: 10 /* IF_BRANCH */,
13701 loc: node.loc,
13702 condition: dir.name === 'else' ? undefined : dir.exp,
13703 children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
13704 ? node.children
13705 : [node],
13706 userKey: findProp(node, `key`)
13707 };
13708}
13709function createCodegenNodeForBranch(branch, keyIndex, context) {
13710 if (branch.condition) {
13711 return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
13712 // make sure to pass in asBlock: true so that the comment node call
13713 // closes the current block.
13714 createCallExpression(context.helper(CREATE_COMMENT), [
13715 '"v-if"' ,
13716 'true'
13717 ]));
13718 }
13719 else {
13720 return createChildrenCodegenNode(branch, keyIndex, context);
13721 }
13722}
13723function createChildrenCodegenNode(branch, keyIndex, context) {
13724 const { helper } = context;
13725 const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
13726 const { children } = branch;
13727 const firstChild = children[0];
13728 const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
13729 if (needFragmentWrapper) {
13730 if (children.length === 1 && firstChild.type === 11 /* FOR */) {
13731 // optimize away nested fragments when child is a ForNode
13732 const vnodeCall = firstChild.codegenNode;
13733 injectProp(vnodeCall, keyProperty, context);
13734 return vnodeCall;
13735 }
13736 else {
13737 let patchFlag = 64 /* STABLE_FRAGMENT */;
13738 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
13739 // check if the fragment actually contains a single valid child with
13740 // the rest being comments
13741 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
13742 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
13743 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
13744 }
13745 return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
13746 }
13747 }
13748 else {
13749 const ret = firstChild.codegenNode;
13750 const vnodeCall = getMemoedVNodeCall(ret);
13751 // Change createVNode to createBlock.
13752 if (vnodeCall.type === 13 /* VNODE_CALL */) {
13753 makeBlock(vnodeCall, context);
13754 }
13755 // inject branch key
13756 injectProp(vnodeCall, keyProperty, context);
13757 return ret;
13758 }
13759}
13760function isSameKey(a, b) {
13761 if (!a || a.type !== b.type) {
13762 return false;
13763 }
13764 if (a.type === 6 /* ATTRIBUTE */) {
13765 if (a.value.content !== b.value.content) {
13766 return false;
13767 }
13768 }
13769 else {
13770 // directive
13771 const exp = a.exp;
13772 const branchExp = b.exp;
13773 if (exp.type !== branchExp.type) {
13774 return false;
13775 }
13776 if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
13777 exp.isStatic !== branchExp.isStatic ||
13778 exp.content !== branchExp.content) {
13779 return false;
13780 }
13781 }
13782 return true;
13783}
13784function getParentCondition(node) {
13785 while (true) {
13786 if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
13787 if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
13788 node = node.alternate;
13789 }
13790 else {
13791 return node;
13792 }
13793 }
13794 else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
13795 node = node.value;
13796 }
13797 }
13798}
13799
13800const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
13801 const { helper, removeHelper } = context;
13802 return processFor(node, dir, context, forNode => {
13803 // create the loop render function expression now, and add the
13804 // iterator on exit after all children have been traversed
13805 const renderExp = createCallExpression(helper(RENDER_LIST), [
13806 forNode.source
13807 ]);
13808 const isTemplate = isTemplateNode(node);
13809 const memo = findDir(node, 'memo');
13810 const keyProp = findProp(node, `key`);
13811 const keyExp = keyProp &&
13812 (keyProp.type === 6 /* ATTRIBUTE */
13813 ? createSimpleExpression(keyProp.value.content, true)
13814 : keyProp.exp);
13815 const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
13816 const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
13817 forNode.source.constType > 0 /* NOT_CONSTANT */;
13818 const fragmentFlag = isStableFragment
13819 ? 64 /* STABLE_FRAGMENT */
13820 : keyProp
13821 ? 128 /* KEYED_FRAGMENT */
13822 : 256 /* UNKEYED_FRAGMENT */;
13823 forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
13824 (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
13825 return () => {
13826 // finish the codegen now that all children have been traversed
13827 let childBlock;
13828 const { children } = forNode;
13829 // check <template v-for> key placement
13830 if (isTemplate) {
13831 node.children.some(c => {
13832 if (c.type === 1 /* ELEMENT */) {
13833 const key = findProp(c, 'key');
13834 if (key) {
13835 context.onError(createCompilerError(33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
13836 return true;
13837 }
13838 }
13839 });
13840 }
13841 const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
13842 const slotOutlet = isSlotOutlet(node)
13843 ? node
13844 : isTemplate &&
13845 node.children.length === 1 &&
13846 isSlotOutlet(node.children[0])
13847 ? node.children[0] // api-extractor somehow fails to infer this
13848 : null;
13849 if (slotOutlet) {
13850 // <slot v-for="..."> or <template v-for="..."><slot/></template>
13851 childBlock = slotOutlet.codegenNode;
13852 if (isTemplate && keyProperty) {
13853 // <template v-for="..." :key="..."><slot/></template>
13854 // we need to inject the key to the renderSlot() call.
13855 // the props for renderSlot is passed as the 3rd argument.
13856 injectProp(childBlock, keyProperty, context);
13857 }
13858 }
13859 else if (needFragmentWrapper) {
13860 // <template v-for="..."> with text or multi-elements
13861 // should generate a fragment block for each loop
13862 childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
13863 (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
13864 ), undefined, undefined, true, undefined, false /* isComponent */);
13865 }
13866 else {
13867 // Normal element v-for. Directly use the child's codegenNode
13868 // but mark it as a block.
13869 childBlock = children[0]
13870 .codegenNode;
13871 if (isTemplate && keyProperty) {
13872 injectProp(childBlock, keyProperty, context);
13873 }
13874 if (childBlock.isBlock !== !isStableFragment) {
13875 if (childBlock.isBlock) {
13876 // switch from block to vnode
13877 removeHelper(OPEN_BLOCK);
13878 removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
13879 }
13880 else {
13881 // switch from vnode to block
13882 removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
13883 }
13884 }
13885 childBlock.isBlock = !isStableFragment;
13886 if (childBlock.isBlock) {
13887 helper(OPEN_BLOCK);
13888 helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
13889 }
13890 else {
13891 helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
13892 }
13893 }
13894 if (memo) {
13895 const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
13896 createSimpleExpression(`_cached`)
13897 ]));
13898 loop.body = createBlockStatement([
13899 createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
13900 createCompoundExpression([
13901 `if (_cached`,
13902 ...(keyExp ? [` && _cached.key === `, keyExp] : []),
13903 ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
13904 ]),
13905 createCompoundExpression([`const _item = `, childBlock]),
13906 createSimpleExpression(`_item.memo = _memo`),
13907 createSimpleExpression(`return _item`)
13908 ]);
13909 renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
13910 }
13911 else {
13912 renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
13913 }
13914 };
13915 });
13916});
13917// target-agnostic transform used for both Client and SSR
13918function processFor(node, dir, context, processCodegen) {
13919 if (!dir.exp) {
13920 context.onError(createCompilerError(31 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
13921 return;
13922 }
13923 const parseResult = parseForExpression(
13924 // can only be simple expression because vFor transform is applied
13925 // before expression transform.
13926 dir.exp, context);
13927 if (!parseResult) {
13928 context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
13929 return;
13930 }
13931 const { addIdentifiers, removeIdentifiers, scopes } = context;
13932 const { source, value, key, index } = parseResult;
13933 const forNode = {
13934 type: 11 /* FOR */,
13935 loc: dir.loc,
13936 source,
13937 valueAlias: value,
13938 keyAlias: key,
13939 objectIndexAlias: index,
13940 parseResult,
13941 children: isTemplateNode(node) ? node.children : [node]
13942 };
13943 context.replaceNode(forNode);
13944 // bookkeeping
13945 scopes.vFor++;
13946 const onExit = processCodegen && processCodegen(forNode);
13947 return () => {
13948 scopes.vFor--;
13949 if (onExit)
13950 onExit();
13951 };
13952}
13953const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
13954// This regex doesn't cover the case if key or index aliases have destructuring,
13955// but those do not make sense in the first place, so this works in practice.
13956const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
13957const stripParensRE = /^\(|\)$/g;
13958function parseForExpression(input, context) {
13959 const loc = input.loc;
13960 const exp = input.content;
13961 const inMatch = exp.match(forAliasRE);
13962 if (!inMatch)
13963 return;
13964 const [, LHS, RHS] = inMatch;
13965 const result = {
13966 source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
13967 value: undefined,
13968 key: undefined,
13969 index: undefined
13970 };
13971 {
13972 validateBrowserExpression(result.source, context);
13973 }
13974 let valueContent = LHS.trim().replace(stripParensRE, '').trim();
13975 const trimmedOffset = LHS.indexOf(valueContent);
13976 const iteratorMatch = valueContent.match(forIteratorRE);
13977 if (iteratorMatch) {
13978 valueContent = valueContent.replace(forIteratorRE, '').trim();
13979 const keyContent = iteratorMatch[1].trim();
13980 let keyOffset;
13981 if (keyContent) {
13982 keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
13983 result.key = createAliasExpression(loc, keyContent, keyOffset);
13984 {
13985 validateBrowserExpression(result.key, context, true);
13986 }
13987 }
13988 if (iteratorMatch[2]) {
13989 const indexContent = iteratorMatch[2].trim();
13990 if (indexContent) {
13991 result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
13992 ? keyOffset + keyContent.length
13993 : trimmedOffset + valueContent.length));
13994 {
13995 validateBrowserExpression(result.index, context, true);
13996 }
13997 }
13998 }
13999 }
14000 if (valueContent) {
14001 result.value = createAliasExpression(loc, valueContent, trimmedOffset);
14002 {
14003 validateBrowserExpression(result.value, context, true);
14004 }
14005 }
14006 return result;
14007}
14008function createAliasExpression(range, content, offset) {
14009 return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
14010}
14011function createForLoopParams({ value, key, index }, memoArgs = []) {
14012 return createParamsList([value, key, index, ...memoArgs]);
14013}
14014function createParamsList(args) {
14015 let i = args.length;
14016 while (i--) {
14017 if (args[i])
14018 break;
14019 }
14020 return args
14021 .slice(0, i + 1)
14022 .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
14023}
14024
14025const defaultFallback = createSimpleExpression(`undefined`, false);
14026// A NodeTransform that:
14027// 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
14028// by transformExpression. This is only applied in non-browser builds with
14029// { prefixIdentifiers: true }.
14030// 2. Track v-slot depths so that we know a slot is inside another slot.
14031// Note the exit callback is executed before buildSlots() on the same node,
14032// so only nested slots see positive numbers.
14033const trackSlotScopes = (node, context) => {
14034 if (node.type === 1 /* ELEMENT */ &&
14035 (node.tagType === 1 /* COMPONENT */ ||
14036 node.tagType === 3 /* TEMPLATE */)) {
14037 // We are only checking non-empty v-slot here
14038 // since we only care about slots that introduce scope variables.
14039 const vSlot = findDir(node, 'slot');
14040 if (vSlot) {
14041 vSlot.exp;
14042 context.scopes.vSlot++;
14043 return () => {
14044 context.scopes.vSlot--;
14045 };
14046 }
14047 }
14048};
14049const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
14050// Instead of being a DirectiveTransform, v-slot processing is called during
14051// transformElement to build the slots object for a component.
14052function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
14053 context.helper(WITH_CTX);
14054 const { children, loc } = node;
14055 const slotsProperties = [];
14056 const dynamicSlots = [];
14057 // If the slot is inside a v-for or another v-slot, force it to be dynamic
14058 // since it likely uses a scope variable.
14059 let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
14060 // 1. Check for slot with slotProps on component itself.
14061 // <Comp v-slot="{ prop }"/>
14062 const onComponentSlot = findDir(node, 'slot', true);
14063 if (onComponentSlot) {
14064 const { arg, exp } = onComponentSlot;
14065 if (arg && !isStaticExp(arg)) {
14066 hasDynamicSlots = true;
14067 }
14068 slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
14069 }
14070 // 2. Iterate through children and check for template slots
14071 // <template v-slot:foo="{ prop }">
14072 let hasTemplateSlots = false;
14073 let hasNamedDefaultSlot = false;
14074 const implicitDefaultChildren = [];
14075 const seenSlotNames = new Set();
14076 for (let i = 0; i < children.length; i++) {
14077 const slotElement = children[i];
14078 let slotDir;
14079 if (!isTemplateNode(slotElement) ||
14080 !(slotDir = findDir(slotElement, 'slot', true))) {
14081 // not a <template v-slot>, skip.
14082 if (slotElement.type !== 3 /* COMMENT */) {
14083 implicitDefaultChildren.push(slotElement);
14084 }
14085 continue;
14086 }
14087 if (onComponentSlot) {
14088 // already has on-component slot - this is incorrect usage.
14089 context.onError(createCompilerError(37 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
14090 break;
14091 }
14092 hasTemplateSlots = true;
14093 const { children: slotChildren, loc: slotLoc } = slotElement;
14094 const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
14095 // check if name is dynamic.
14096 let staticSlotName;
14097 if (isStaticExp(slotName)) {
14098 staticSlotName = slotName ? slotName.content : `default`;
14099 }
14100 else {
14101 hasDynamicSlots = true;
14102 }
14103 const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
14104 // check if this slot is conditional (v-if/v-for)
14105 let vIf;
14106 let vElse;
14107 let vFor;
14108 if ((vIf = findDir(slotElement, 'if'))) {
14109 hasDynamicSlots = true;
14110 dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
14111 }
14112 else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
14113 // find adjacent v-if
14114 let j = i;
14115 let prev;
14116 while (j--) {
14117 prev = children[j];
14118 if (prev.type !== 3 /* COMMENT */) {
14119 break;
14120 }
14121 }
14122 if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
14123 // remove node
14124 children.splice(i, 1);
14125 i--;
14126 // attach this slot to previous conditional
14127 let conditional = dynamicSlots[dynamicSlots.length - 1];
14128 while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
14129 conditional = conditional.alternate;
14130 }
14131 conditional.alternate = vElse.exp
14132 ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
14133 : buildDynamicSlot(slotName, slotFunction);
14134 }
14135 else {
14136 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
14137 }
14138 }
14139 else if ((vFor = findDir(slotElement, 'for'))) {
14140 hasDynamicSlots = true;
14141 const parseResult = vFor.parseResult ||
14142 parseForExpression(vFor.exp, context);
14143 if (parseResult) {
14144 // Render the dynamic slots as an array and add it to the createSlot()
14145 // args. The runtime knows how to handle it appropriately.
14146 dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
14147 parseResult.source,
14148 createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
14149 ]));
14150 }
14151 else {
14152 context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
14153 }
14154 }
14155 else {
14156 // check duplicate static names
14157 if (staticSlotName) {
14158 if (seenSlotNames.has(staticSlotName)) {
14159 context.onError(createCompilerError(38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
14160 continue;
14161 }
14162 seenSlotNames.add(staticSlotName);
14163 if (staticSlotName === 'default') {
14164 hasNamedDefaultSlot = true;
14165 }
14166 }
14167 slotsProperties.push(createObjectProperty(slotName, slotFunction));
14168 }
14169 }
14170 if (!onComponentSlot) {
14171 const buildDefaultSlotProperty = (props, children) => {
14172 const fn = buildSlotFn(props, children, loc);
14173 return createObjectProperty(`default`, fn);
14174 };
14175 if (!hasTemplateSlots) {
14176 // implicit default slot (on component)
14177 slotsProperties.push(buildDefaultSlotProperty(undefined, children));
14178 }
14179 else if (implicitDefaultChildren.length &&
14180 // #3766
14181 // with whitespace: 'preserve', whitespaces between slots will end up in
14182 // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
14183 implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
14184 // implicit default slot (mixed with named slots)
14185 if (hasNamedDefaultSlot) {
14186 context.onError(createCompilerError(39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
14187 }
14188 else {
14189 slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
14190 }
14191 }
14192 }
14193 const slotFlag = hasDynamicSlots
14194 ? 2 /* DYNAMIC */
14195 : hasForwardedSlots(node.children)
14196 ? 3 /* FORWARDED */
14197 : 1 /* STABLE */;
14198 let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
14199 // 2 = compiled but dynamic = can skip normalization, but must run diff
14200 // 1 = compiled and static = can skip normalization AND diff as optimized
14201 createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
14202 if (dynamicSlots.length) {
14203 slots = createCallExpression(context.helper(CREATE_SLOTS), [
14204 slots,
14205 createArrayExpression(dynamicSlots)
14206 ]);
14207 }
14208 return {
14209 slots,
14210 hasDynamicSlots
14211 };
14212}
14213function buildDynamicSlot(name, fn) {
14214 return createObjectExpression([
14215 createObjectProperty(`name`, name),
14216 createObjectProperty(`fn`, fn)
14217 ]);
14218}
14219function hasForwardedSlots(children) {
14220 for (let i = 0; i < children.length; i++) {
14221 const child = children[i];
14222 switch (child.type) {
14223 case 1 /* ELEMENT */:
14224 if (child.tagType === 2 /* SLOT */ ||
14225 hasForwardedSlots(child.children)) {
14226 return true;
14227 }
14228 break;
14229 case 9 /* IF */:
14230 if (hasForwardedSlots(child.branches))
14231 return true;
14232 break;
14233 case 10 /* IF_BRANCH */:
14234 case 11 /* FOR */:
14235 if (hasForwardedSlots(child.children))
14236 return true;
14237 break;
14238 }
14239 }
14240 return false;
14241}
14242function isNonWhitespaceContent(node) {
14243 if (node.type !== 2 /* TEXT */ && node.type !== 12 /* TEXT_CALL */)
14244 return true;
14245 return node.type === 2 /* TEXT */
14246 ? !!node.content.trim()
14247 : isNonWhitespaceContent(node.content);
14248}
14249
14250// some directive transforms (e.g. v-model) may return a symbol for runtime
14251// import, which should be used instead of a resolveDirective call.
14252const directiveImportMap = new WeakMap();
14253// generate a JavaScript AST for this element's codegen
14254const transformElement = (node, context) => {
14255 // perform the work on exit, after all child expressions have been
14256 // processed and merged.
14257 return function postTransformElement() {
14258 node = context.currentNode;
14259 if (!(node.type === 1 /* ELEMENT */ &&
14260 (node.tagType === 0 /* ELEMENT */ ||
14261 node.tagType === 1 /* COMPONENT */))) {
14262 return;
14263 }
14264 const { tag, props } = node;
14265 const isComponent = node.tagType === 1 /* COMPONENT */;
14266 // The goal of the transform is to create a codegenNode implementing the
14267 // VNodeCall interface.
14268 let vnodeTag = isComponent
14269 ? resolveComponentType(node, context)
14270 : `"${tag}"`;
14271 const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
14272 let vnodeProps;
14273 let vnodeChildren;
14274 let vnodePatchFlag;
14275 let patchFlag = 0;
14276 let vnodeDynamicProps;
14277 let dynamicPropNames;
14278 let vnodeDirectives;
14279 let shouldUseBlock =
14280 // dynamic component may resolve to plain elements
14281 isDynamicComponent ||
14282 vnodeTag === TELEPORT ||
14283 vnodeTag === SUSPENSE ||
14284 (!isComponent &&
14285 // <svg> and <foreignObject> must be forced into blocks so that block
14286 // updates inside get proper isSVG flag at runtime. (#639, #643)
14287 // This is technically web-specific, but splitting the logic out of core
14288 // leads to too much unnecessary complexity.
14289 (tag === 'svg' || tag === 'foreignObject'));
14290 // props
14291 if (props.length > 0) {
14292 const propsBuildResult = buildProps(node, context);
14293 vnodeProps = propsBuildResult.props;
14294 patchFlag = propsBuildResult.patchFlag;
14295 dynamicPropNames = propsBuildResult.dynamicPropNames;
14296 const directives = propsBuildResult.directives;
14297 vnodeDirectives =
14298 directives && directives.length
14299 ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
14300 : undefined;
14301 if (propsBuildResult.shouldUseBlock) {
14302 shouldUseBlock = true;
14303 }
14304 }
14305 // children
14306 if (node.children.length > 0) {
14307 if (vnodeTag === KEEP_ALIVE) {
14308 // Although a built-in component, we compile KeepAlive with raw children
14309 // instead of slot functions so that it can be used inside Transition
14310 // or other Transition-wrapping HOCs.
14311 // To ensure correct updates with block optimizations, we need to:
14312 // 1. Force keep-alive into a block. This avoids its children being
14313 // collected by a parent block.
14314 shouldUseBlock = true;
14315 // 2. Force keep-alive to always be updated, since it uses raw children.
14316 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
14317 if (node.children.length > 1) {
14318 context.onError(createCompilerError(45 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
14319 start: node.children[0].loc.start,
14320 end: node.children[node.children.length - 1].loc.end,
14321 source: ''
14322 }));
14323 }
14324 }
14325 const shouldBuildAsSlots = isComponent &&
14326 // Teleport is not a real component and has dedicated runtime handling
14327 vnodeTag !== TELEPORT &&
14328 // explained above.
14329 vnodeTag !== KEEP_ALIVE;
14330 if (shouldBuildAsSlots) {
14331 const { slots, hasDynamicSlots } = buildSlots(node, context);
14332 vnodeChildren = slots;
14333 if (hasDynamicSlots) {
14334 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
14335 }
14336 }
14337 else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
14338 const child = node.children[0];
14339 const type = child.type;
14340 // check for dynamic text children
14341 const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
14342 type === 8 /* COMPOUND_EXPRESSION */;
14343 if (hasDynamicTextChild &&
14344 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
14345 patchFlag |= 1 /* TEXT */;
14346 }
14347 // pass directly if the only child is a text node
14348 // (plain / interpolation / expression)
14349 if (hasDynamicTextChild || type === 2 /* TEXT */) {
14350 vnodeChildren = child;
14351 }
14352 else {
14353 vnodeChildren = node.children;
14354 }
14355 }
14356 else {
14357 vnodeChildren = node.children;
14358 }
14359 }
14360 // patchFlag & dynamicPropNames
14361 if (patchFlag !== 0) {
14362 {
14363 if (patchFlag < 0) {
14364 // special flags (negative and mutually exclusive)
14365 vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
14366 }
14367 else {
14368 // bitwise flags
14369 const flagNames = Object.keys(PatchFlagNames)
14370 .map(Number)
14371 .filter(n => n > 0 && patchFlag & n)
14372 .map(n => PatchFlagNames[n])
14373 .join(`, `);
14374 vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
14375 }
14376 }
14377 if (dynamicPropNames && dynamicPropNames.length) {
14378 vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
14379 }
14380 }
14381 node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
14382 };
14383};
14384function resolveComponentType(node, context, ssr = false) {
14385 let { tag } = node;
14386 // 1. dynamic component
14387 const isExplicitDynamic = isComponentTag(tag);
14388 const isProp = findProp(node, 'is');
14389 if (isProp) {
14390 if (isExplicitDynamic ||
14391 (false )) {
14392 const exp = isProp.type === 6 /* ATTRIBUTE */
14393 ? isProp.value && createSimpleExpression(isProp.value.content, true)
14394 : isProp.exp;
14395 if (exp) {
14396 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
14397 exp
14398 ]);
14399 }
14400 }
14401 else if (isProp.type === 6 /* ATTRIBUTE */ &&
14402 isProp.value.content.startsWith('vue:')) {
14403 // <button is="vue:xxx">
14404 // if not <component>, only is value that starts with "vue:" will be
14405 // treated as component by the parse phase and reach here, unless it's
14406 // compat mode where all is values are considered components
14407 tag = isProp.value.content.slice(4);
14408 }
14409 }
14410 // 1.5 v-is (TODO: Deprecate)
14411 const isDir = !isExplicitDynamic && findDir(node, 'is');
14412 if (isDir && isDir.exp) {
14413 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
14414 isDir.exp
14415 ]);
14416 }
14417 // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
14418 const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
14419 if (builtIn) {
14420 // built-ins are simply fallthroughs / have special handling during ssr
14421 // so we don't need to import their runtime equivalents
14422 if (!ssr)
14423 context.helper(builtIn);
14424 return builtIn;
14425 }
14426 // 5. user component (resolve)
14427 context.helper(RESOLVE_COMPONENT);
14428 context.components.add(tag);
14429 return toValidAssetId(tag, `component`);
14430}
14431function buildProps(node, context, props = node.props, ssr = false) {
14432 const { tag, loc: elementLoc, children } = node;
14433 const isComponent = node.tagType === 1 /* COMPONENT */;
14434 let properties = [];
14435 const mergeArgs = [];
14436 const runtimeDirectives = [];
14437 const hasChildren = children.length > 0;
14438 let shouldUseBlock = false;
14439 // patchFlag analysis
14440 let patchFlag = 0;
14441 let hasRef = false;
14442 let hasClassBinding = false;
14443 let hasStyleBinding = false;
14444 let hasHydrationEventBinding = false;
14445 let hasDynamicKeys = false;
14446 let hasVnodeHook = false;
14447 const dynamicPropNames = [];
14448 const analyzePatchFlag = ({ key, value }) => {
14449 if (isStaticExp(key)) {
14450 const name = key.content;
14451 const isEventHandler = isOn(name);
14452 if (!isComponent &&
14453 isEventHandler &&
14454 // omit the flag for click handlers because hydration gives click
14455 // dedicated fast path.
14456 name.toLowerCase() !== 'onclick' &&
14457 // omit v-model handlers
14458 name !== 'onUpdate:modelValue' &&
14459 // omit onVnodeXXX hooks
14460 !isReservedProp(name)) {
14461 hasHydrationEventBinding = true;
14462 }
14463 if (isEventHandler && isReservedProp(name)) {
14464 hasVnodeHook = true;
14465 }
14466 if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
14467 ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
14468 value.type === 8 /* COMPOUND_EXPRESSION */) &&
14469 getConstantType(value, context) > 0)) {
14470 // skip if the prop is a cached handler or has constant value
14471 return;
14472 }
14473 if (name === 'ref') {
14474 hasRef = true;
14475 }
14476 else if (name === 'class') {
14477 hasClassBinding = true;
14478 }
14479 else if (name === 'style') {
14480 hasStyleBinding = true;
14481 }
14482 else if (name !== 'key' && !dynamicPropNames.includes(name)) {
14483 dynamicPropNames.push(name);
14484 }
14485 // treat the dynamic class and style binding of the component as dynamic props
14486 if (isComponent &&
14487 (name === 'class' || name === 'style') &&
14488 !dynamicPropNames.includes(name)) {
14489 dynamicPropNames.push(name);
14490 }
14491 }
14492 else {
14493 hasDynamicKeys = true;
14494 }
14495 };
14496 for (let i = 0; i < props.length; i++) {
14497 // static attribute
14498 const prop = props[i];
14499 if (prop.type === 6 /* ATTRIBUTE */) {
14500 const { loc, name, value } = prop;
14501 let isStatic = true;
14502 if (name === 'ref') {
14503 hasRef = true;
14504 if (context.scopes.vFor > 0) {
14505 properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
14506 }
14507 }
14508 // skip is on <component>, or is="vue:xxx"
14509 if (name === 'is' &&
14510 (isComponentTag(tag) ||
14511 (value && value.content.startsWith('vue:')) ||
14512 (false ))) {
14513 continue;
14514 }
14515 properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
14516 }
14517 else {
14518 // directives
14519 const { name, arg, exp, loc } = prop;
14520 const isVBind = name === 'bind';
14521 const isVOn = name === 'on';
14522 // skip v-slot - it is handled by its dedicated transform.
14523 if (name === 'slot') {
14524 if (!isComponent) {
14525 context.onError(createCompilerError(40 /* X_V_SLOT_MISPLACED */, loc));
14526 }
14527 continue;
14528 }
14529 // skip v-once/v-memo - they are handled by dedicated transforms.
14530 if (name === 'once' || name === 'memo') {
14531 continue;
14532 }
14533 // skip v-is and :is on <component>
14534 if (name === 'is' ||
14535 (isVBind &&
14536 isStaticArgOf(arg, 'is') &&
14537 (isComponentTag(tag) ||
14538 (false )))) {
14539 continue;
14540 }
14541 // skip v-on in SSR compilation
14542 if (isVOn && ssr) {
14543 continue;
14544 }
14545 if (
14546 // #938: elements with dynamic keys should be forced into blocks
14547 (isVBind && isStaticArgOf(arg, 'key')) ||
14548 // inline before-update hooks need to force block so that it is invoked
14549 // before children
14550 (isVOn && hasChildren && isStaticArgOf(arg, 'vue:before-update'))) {
14551 shouldUseBlock = true;
14552 }
14553 if (isVBind && isStaticArgOf(arg, 'ref') && context.scopes.vFor > 0) {
14554 properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
14555 }
14556 // special case for v-bind and v-on with no argument
14557 if (!arg && (isVBind || isVOn)) {
14558 hasDynamicKeys = true;
14559 if (exp) {
14560 if (properties.length) {
14561 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
14562 properties = [];
14563 }
14564 if (isVBind) {
14565 mergeArgs.push(exp);
14566 }
14567 else {
14568 // v-on="obj" -> toHandlers(obj)
14569 mergeArgs.push({
14570 type: 14 /* JS_CALL_EXPRESSION */,
14571 loc,
14572 callee: context.helper(TO_HANDLERS),
14573 arguments: [exp]
14574 });
14575 }
14576 }
14577 else {
14578 context.onError(createCompilerError(isVBind
14579 ? 34 /* X_V_BIND_NO_EXPRESSION */
14580 : 35 /* X_V_ON_NO_EXPRESSION */, loc));
14581 }
14582 continue;
14583 }
14584 const directiveTransform = context.directiveTransforms[name];
14585 if (directiveTransform) {
14586 // has built-in directive transform.
14587 const { props, needRuntime } = directiveTransform(prop, node, context);
14588 !ssr && props.forEach(analyzePatchFlag);
14589 properties.push(...props);
14590 if (needRuntime) {
14591 runtimeDirectives.push(prop);
14592 if (isSymbol(needRuntime)) {
14593 directiveImportMap.set(prop, needRuntime);
14594 }
14595 }
14596 }
14597 else if (!isBuiltInDirective(name)) {
14598 // no built-in transform, this is a user custom directive.
14599 runtimeDirectives.push(prop);
14600 // custom dirs may use beforeUpdate so they need to force blocks
14601 // to ensure before-update gets called before children update
14602 if (hasChildren) {
14603 shouldUseBlock = true;
14604 }
14605 }
14606 }
14607 }
14608 let propsExpression = undefined;
14609 // has v-bind="object" or v-on="object", wrap with mergeProps
14610 if (mergeArgs.length) {
14611 if (properties.length) {
14612 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
14613 }
14614 if (mergeArgs.length > 1) {
14615 propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
14616 }
14617 else {
14618 // single v-bind with nothing else - no need for a mergeProps call
14619 propsExpression = mergeArgs[0];
14620 }
14621 }
14622 else if (properties.length) {
14623 propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
14624 }
14625 // patchFlag analysis
14626 if (hasDynamicKeys) {
14627 patchFlag |= 16 /* FULL_PROPS */;
14628 }
14629 else {
14630 if (hasClassBinding && !isComponent) {
14631 patchFlag |= 2 /* CLASS */;
14632 }
14633 if (hasStyleBinding && !isComponent) {
14634 patchFlag |= 4 /* STYLE */;
14635 }
14636 if (dynamicPropNames.length) {
14637 patchFlag |= 8 /* PROPS */;
14638 }
14639 if (hasHydrationEventBinding) {
14640 patchFlag |= 32 /* HYDRATE_EVENTS */;
14641 }
14642 }
14643 if (!shouldUseBlock &&
14644 (patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
14645 (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
14646 patchFlag |= 512 /* NEED_PATCH */;
14647 }
14648 // pre-normalize props, SSR is skipped for now
14649 if (!context.inSSR && propsExpression) {
14650 switch (propsExpression.type) {
14651 case 15 /* JS_OBJECT_EXPRESSION */:
14652 // means that there is no v-bind,
14653 // but still need to deal with dynamic key binding
14654 let classKeyIndex = -1;
14655 let styleKeyIndex = -1;
14656 let hasDynamicKey = false;
14657 for (let i = 0; i < propsExpression.properties.length; i++) {
14658 const key = propsExpression.properties[i].key;
14659 if (isStaticExp(key)) {
14660 if (key.content === 'class') {
14661 classKeyIndex = i;
14662 }
14663 else if (key.content === 'style') {
14664 styleKeyIndex = i;
14665 }
14666 }
14667 else if (!key.isHandlerKey) {
14668 hasDynamicKey = true;
14669 }
14670 }
14671 const classProp = propsExpression.properties[classKeyIndex];
14672 const styleProp = propsExpression.properties[styleKeyIndex];
14673 // no dynamic key
14674 if (!hasDynamicKey) {
14675 if (classProp && !isStaticExp(classProp.value)) {
14676 classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
14677 }
14678 if (styleProp &&
14679 !isStaticExp(styleProp.value) &&
14680 // the static style is compiled into an object,
14681 // so use `hasStyleBinding` to ensure that it is a dynamic style binding
14682 (hasStyleBinding ||
14683 // v-bind:style and style both exist,
14684 // v-bind:style with static literal object
14685 styleProp.value.type === 17 /* JS_ARRAY_EXPRESSION */)) {
14686 styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
14687 }
14688 }
14689 else {
14690 // dynamic key binding, wrap with `normalizeProps`
14691 propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
14692 }
14693 break;
14694 case 14 /* JS_CALL_EXPRESSION */:
14695 // mergeProps call, do nothing
14696 break;
14697 default:
14698 // single v-bind
14699 propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
14700 createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
14701 propsExpression
14702 ])
14703 ]);
14704 break;
14705 }
14706 }
14707 return {
14708 props: propsExpression,
14709 directives: runtimeDirectives,
14710 patchFlag,
14711 dynamicPropNames,
14712 shouldUseBlock
14713 };
14714}
14715// Dedupe props in an object literal.
14716// Literal duplicated attributes would have been warned during the parse phase,
14717// however, it's possible to encounter duplicated `onXXX` handlers with different
14718// modifiers. We also need to merge static and dynamic class / style attributes.
14719// - onXXX handlers / style: merge into array
14720// - class: merge into single expression with concatenation
14721function dedupeProperties(properties) {
14722 const knownProps = new Map();
14723 const deduped = [];
14724 for (let i = 0; i < properties.length; i++) {
14725 const prop = properties[i];
14726 // dynamic keys are always allowed
14727 if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
14728 deduped.push(prop);
14729 continue;
14730 }
14731 const name = prop.key.content;
14732 const existing = knownProps.get(name);
14733 if (existing) {
14734 if (name === 'style' || name === 'class' || isOn(name)) {
14735 mergeAsArray$1(existing, prop);
14736 }
14737 // unexpected duplicate, should have emitted error during parse
14738 }
14739 else {
14740 knownProps.set(name, prop);
14741 deduped.push(prop);
14742 }
14743 }
14744 return deduped;
14745}
14746function mergeAsArray$1(existing, incoming) {
14747 if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
14748 existing.value.elements.push(incoming.value);
14749 }
14750 else {
14751 existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
14752 }
14753}
14754function buildDirectiveArgs(dir, context) {
14755 const dirArgs = [];
14756 const runtime = directiveImportMap.get(dir);
14757 if (runtime) {
14758 // built-in directive with runtime
14759 dirArgs.push(context.helperString(runtime));
14760 }
14761 else {
14762 {
14763 // inject statement for resolving directive
14764 context.helper(RESOLVE_DIRECTIVE);
14765 context.directives.add(dir.name);
14766 dirArgs.push(toValidAssetId(dir.name, `directive`));
14767 }
14768 }
14769 const { loc } = dir;
14770 if (dir.exp)
14771 dirArgs.push(dir.exp);
14772 if (dir.arg) {
14773 if (!dir.exp) {
14774 dirArgs.push(`void 0`);
14775 }
14776 dirArgs.push(dir.arg);
14777 }
14778 if (Object.keys(dir.modifiers).length) {
14779 if (!dir.arg) {
14780 if (!dir.exp) {
14781 dirArgs.push(`void 0`);
14782 }
14783 dirArgs.push(`void 0`);
14784 }
14785 const trueExpression = createSimpleExpression(`true`, false, loc);
14786 dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
14787 }
14788 return createArrayExpression(dirArgs, dir.loc);
14789}
14790function stringifyDynamicPropNames(props) {
14791 let propsNamesString = `[`;
14792 for (let i = 0, l = props.length; i < l; i++) {
14793 propsNamesString += JSON.stringify(props[i]);
14794 if (i < l - 1)
14795 propsNamesString += ', ';
14796 }
14797 return propsNamesString + `]`;
14798}
14799function isComponentTag(tag) {
14800 return tag === 'component' || tag === 'Component';
14801}
14802
14803const transformSlotOutlet = (node, context) => {
14804 if (isSlotOutlet(node)) {
14805 const { children, loc } = node;
14806 const { slotName, slotProps } = processSlotOutlet(node, context);
14807 const slotArgs = [
14808 context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
14809 slotName,
14810 '{}',
14811 'undefined',
14812 'true'
14813 ];
14814 let expectedLen = 2;
14815 if (slotProps) {
14816 slotArgs[2] = slotProps;
14817 expectedLen = 3;
14818 }
14819 if (children.length) {
14820 slotArgs[3] = createFunctionExpression([], children, false, false, loc);
14821 expectedLen = 4;
14822 }
14823 if (context.scopeId && !context.slotted) {
14824 expectedLen = 5;
14825 }
14826 slotArgs.splice(expectedLen); // remove unused arguments
14827 node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
14828 }
14829};
14830function processSlotOutlet(node, context) {
14831 let slotName = `"default"`;
14832 let slotProps = undefined;
14833 const nonNameProps = [];
14834 for (let i = 0; i < node.props.length; i++) {
14835 const p = node.props[i];
14836 if (p.type === 6 /* ATTRIBUTE */) {
14837 if (p.value) {
14838 if (p.name === 'name') {
14839 slotName = JSON.stringify(p.value.content);
14840 }
14841 else {
14842 p.name = camelize(p.name);
14843 nonNameProps.push(p);
14844 }
14845 }
14846 }
14847 else {
14848 if (p.name === 'bind' && isStaticArgOf(p.arg, 'name')) {
14849 if (p.exp)
14850 slotName = p.exp;
14851 }
14852 else {
14853 if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
14854 p.arg.content = camelize(p.arg.content);
14855 }
14856 nonNameProps.push(p);
14857 }
14858 }
14859 }
14860 if (nonNameProps.length > 0) {
14861 const { props, directives } = buildProps(node, context, nonNameProps);
14862 slotProps = props;
14863 if (directives.length) {
14864 context.onError(createCompilerError(36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
14865 }
14866 }
14867 return {
14868 slotName,
14869 slotProps
14870 };
14871}
14872
14873const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/;
14874const transformOn = (dir, node, context, augmentor) => {
14875 const { loc, modifiers, arg } = dir;
14876 if (!dir.exp && !modifiers.length) {
14877 context.onError(createCompilerError(35 /* X_V_ON_NO_EXPRESSION */, loc));
14878 }
14879 let eventName;
14880 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
14881 if (arg.isStatic) {
14882 let rawName = arg.content;
14883 // TODO deprecate @vnodeXXX usage
14884 if (rawName.startsWith('vue:')) {
14885 rawName = `vnode-${rawName.slice(4)}`;
14886 }
14887 // for all event listeners, auto convert it to camelCase. See issue #2249
14888 eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
14889 }
14890 else {
14891 // #2388
14892 eventName = createCompoundExpression([
14893 `${context.helperString(TO_HANDLER_KEY)}(`,
14894 arg,
14895 `)`
14896 ]);
14897 }
14898 }
14899 else {
14900 // already a compound expression.
14901 eventName = arg;
14902 eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
14903 eventName.children.push(`)`);
14904 }
14905 // handler processing
14906 let exp = dir.exp;
14907 if (exp && !exp.content.trim()) {
14908 exp = undefined;
14909 }
14910 let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
14911 if (exp) {
14912 const isMemberExp = isMemberExpression(exp.content);
14913 const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
14914 const hasMultipleStatements = exp.content.includes(`;`);
14915 {
14916 validateBrowserExpression(exp, context, false, hasMultipleStatements);
14917 }
14918 if (isInlineStatement || (shouldCache && isMemberExp)) {
14919 // wrap inline statement in a function expression
14920 exp = createCompoundExpression([
14921 `${isInlineStatement
14922 ? `$event`
14923 : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
14924 exp,
14925 hasMultipleStatements ? `}` : `)`
14926 ]);
14927 }
14928 }
14929 let ret = {
14930 props: [
14931 createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
14932 ]
14933 };
14934 // apply extended compiler augmentor
14935 if (augmentor) {
14936 ret = augmentor(ret);
14937 }
14938 if (shouldCache) {
14939 // cache handlers so that it's always the same handler being passed down.
14940 // this avoids unnecessary re-renders when users use inline handlers on
14941 // components.
14942 ret.props[0].value = context.cache(ret.props[0].value);
14943 }
14944 // mark the key as handler for props normalization check
14945 ret.props.forEach(p => (p.key.isHandlerKey = true));
14946 return ret;
14947};
14948
14949// v-bind without arg is handled directly in ./transformElements.ts due to it affecting
14950// codegen for the entire props object. This transform here is only for v-bind
14951// *with* args.
14952const transformBind = (dir, _node, context) => {
14953 const { exp, modifiers, loc } = dir;
14954 const arg = dir.arg;
14955 if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
14956 arg.children.unshift(`(`);
14957 arg.children.push(`) || ""`);
14958 }
14959 else if (!arg.isStatic) {
14960 arg.content = `${arg.content} || ""`;
14961 }
14962 // .sync is replaced by v-model:arg
14963 if (modifiers.includes('camel')) {
14964 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
14965 if (arg.isStatic) {
14966 arg.content = camelize(arg.content);
14967 }
14968 else {
14969 arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
14970 }
14971 }
14972 else {
14973 arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
14974 arg.children.push(`)`);
14975 }
14976 }
14977 if (!context.inSSR) {
14978 if (modifiers.includes('prop')) {
14979 injectPrefix(arg, '.');
14980 }
14981 if (modifiers.includes('attr')) {
14982 injectPrefix(arg, '^');
14983 }
14984 }
14985 if (!exp ||
14986 (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
14987 context.onError(createCompilerError(34 /* X_V_BIND_NO_EXPRESSION */, loc));
14988 return {
14989 props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
14990 };
14991 }
14992 return {
14993 props: [createObjectProperty(arg, exp)]
14994 };
14995};
14996const injectPrefix = (arg, prefix) => {
14997 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
14998 if (arg.isStatic) {
14999 arg.content = prefix + arg.content;
15000 }
15001 else {
15002 arg.content = `\`${prefix}\${${arg.content}}\``;
15003 }
15004 }
15005 else {
15006 arg.children.unshift(`'${prefix}' + (`);
15007 arg.children.push(`)`);
15008 }
15009};
15010
15011// Merge adjacent text nodes and expressions into a single expression
15012// e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
15013const transformText = (node, context) => {
15014 if (node.type === 0 /* ROOT */ ||
15015 node.type === 1 /* ELEMENT */ ||
15016 node.type === 11 /* FOR */ ||
15017 node.type === 10 /* IF_BRANCH */) {
15018 // perform the transform on node exit so that all expressions have already
15019 // been processed.
15020 return () => {
15021 const children = node.children;
15022 let currentContainer = undefined;
15023 let hasText = false;
15024 for (let i = 0; i < children.length; i++) {
15025 const child = children[i];
15026 if (isText(child)) {
15027 hasText = true;
15028 for (let j = i + 1; j < children.length; j++) {
15029 const next = children[j];
15030 if (isText(next)) {
15031 if (!currentContainer) {
15032 currentContainer = children[i] = {
15033 type: 8 /* COMPOUND_EXPRESSION */,
15034 loc: child.loc,
15035 children: [child]
15036 };
15037 }
15038 // merge adjacent text node into current
15039 currentContainer.children.push(` + `, next);
15040 children.splice(j, 1);
15041 j--;
15042 }
15043 else {
15044 currentContainer = undefined;
15045 break;
15046 }
15047 }
15048 }
15049 }
15050 if (!hasText ||
15051 // if this is a plain element with a single text child, leave it
15052 // as-is since the runtime has dedicated fast path for this by directly
15053 // setting textContent of the element.
15054 // for component root it's always normalized anyway.
15055 (children.length === 1 &&
15056 (node.type === 0 /* ROOT */ ||
15057 (node.type === 1 /* ELEMENT */ &&
15058 node.tagType === 0 /* ELEMENT */ &&
15059 // #3756
15060 // custom directives can potentially add DOM elements arbitrarily,
15061 // we need to avoid setting textContent of the element at runtime
15062 // to avoid accidentally overwriting the DOM elements added
15063 // by the user through custom directives.
15064 !node.props.find(p => p.type === 7 /* DIRECTIVE */ &&
15065 !context.directiveTransforms[p.name]) &&
15066 // in compat mode, <template> tags with no special directives
15067 // will be rendered as a fragment so its children must be
15068 // converted into vnodes.
15069 !(false ))))) {
15070 return;
15071 }
15072 // pre-convert text nodes into createTextVNode(text) calls to avoid
15073 // runtime normalization.
15074 for (let i = 0; i < children.length; i++) {
15075 const child = children[i];
15076 if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
15077 const callArgs = [];
15078 // createTextVNode defaults to single whitespace, so if it is a
15079 // single space the code could be an empty call to save bytes.
15080 if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
15081 callArgs.push(child);
15082 }
15083 // mark dynamic text with flag so it gets patched inside a block
15084 if (!context.ssr &&
15085 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
15086 callArgs.push(1 /* TEXT */ +
15087 (` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
15088 }
15089 children[i] = {
15090 type: 12 /* TEXT_CALL */,
15091 content: child,
15092 loc: child.loc,
15093 codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
15094 };
15095 }
15096 }
15097 };
15098 }
15099};
15100
15101const seen = new WeakSet();
15102const transformOnce = (node, context) => {
15103 if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
15104 if (seen.has(node) || context.inVOnce) {
15105 return;
15106 }
15107 seen.add(node);
15108 context.inVOnce = true;
15109 context.helper(SET_BLOCK_TRACKING);
15110 return () => {
15111 context.inVOnce = false;
15112 const cur = context.currentNode;
15113 if (cur.codegenNode) {
15114 cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
15115 }
15116 };
15117 }
15118};
15119
15120const transformModel = (dir, node, context) => {
15121 const { exp, arg } = dir;
15122 if (!exp) {
15123 context.onError(createCompilerError(41 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
15124 return createTransformProps();
15125 }
15126 const rawExp = exp.loc.source;
15127 const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
15128 // im SFC <script setup> inline mode, the exp may have been transformed into
15129 // _unref(exp)
15130 context.bindingMetadata[rawExp];
15131 const maybeRef = !true /* SETUP_CONST */;
15132 if (!expString.trim() ||
15133 (!isMemberExpression(expString) && !maybeRef)) {
15134 context.onError(createCompilerError(42 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
15135 return createTransformProps();
15136 }
15137 const propName = arg ? arg : createSimpleExpression('modelValue', true);
15138 const eventName = arg
15139 ? isStaticExp(arg)
15140 ? `onUpdate:${arg.content}`
15141 : createCompoundExpression(['"onUpdate:" + ', arg])
15142 : `onUpdate:modelValue`;
15143 let assignmentExp;
15144 const eventArg = context.isTS ? `($event: any)` : `$event`;
15145 {
15146 assignmentExp = createCompoundExpression([
15147 `${eventArg} => ((`,
15148 exp,
15149 `) = $event)`
15150 ]);
15151 }
15152 const props = [
15153 // modelValue: foo
15154 createObjectProperty(propName, dir.exp),
15155 // "onUpdate:modelValue": $event => (foo = $event)
15156 createObjectProperty(eventName, assignmentExp)
15157 ];
15158 // modelModifiers: { foo: true, "bar-baz": true }
15159 if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
15160 const modifiers = dir.modifiers
15161 .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
15162 .join(`, `);
15163 const modifiersKey = arg
15164 ? isStaticExp(arg)
15165 ? `${arg.content}Modifiers`
15166 : createCompoundExpression([arg, ' + "Modifiers"'])
15167 : `modelModifiers`;
15168 props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
15169 }
15170 return createTransformProps(props);
15171};
15172function createTransformProps(props = []) {
15173 return { props };
15174}
15175
15176const seen$1 = new WeakSet();
15177const transformMemo = (node, context) => {
15178 if (node.type === 1 /* ELEMENT */) {
15179 const dir = findDir(node, 'memo');
15180 if (!dir || seen$1.has(node)) {
15181 return;
15182 }
15183 seen$1.add(node);
15184 return () => {
15185 const codegenNode = node.codegenNode ||
15186 context.currentNode.codegenNode;
15187 if (codegenNode && codegenNode.type === 13 /* VNODE_CALL */) {
15188 // non-component sub tree should be turned into a block
15189 if (node.tagType !== 1 /* COMPONENT */) {
15190 makeBlock(codegenNode, context);
15191 }
15192 node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
15193 dir.exp,
15194 createFunctionExpression(undefined, codegenNode),
15195 `_cache`,
15196 String(context.cached++)
15197 ]);
15198 }
15199 };
15200 }
15201};
15202
15203function getBaseTransformPreset(prefixIdentifiers) {
15204 return [
15205 [
15206 transformOnce,
15207 transformIf,
15208 transformMemo,
15209 transformFor,
15210 ...([]),
15211 ...([transformExpression]
15212 ),
15213 transformSlotOutlet,
15214 transformElement,
15215 trackSlotScopes,
15216 transformText
15217 ],
15218 {
15219 on: transformOn,
15220 bind: transformBind,
15221 model: transformModel
15222 }
15223 ];
15224}
15225// we name it `baseCompile` so that higher order compilers like
15226// @vue/compiler-dom can export `compile` while re-exporting everything else.
15227function baseCompile(template, options = {}) {
15228 const onError = options.onError || defaultOnError;
15229 const isModuleMode = options.mode === 'module';
15230 /* istanbul ignore if */
15231 {
15232 if (options.prefixIdentifiers === true) {
15233 onError(createCompilerError(46 /* X_PREFIX_ID_NOT_SUPPORTED */));
15234 }
15235 else if (isModuleMode) {
15236 onError(createCompilerError(47 /* X_MODULE_MODE_NOT_SUPPORTED */));
15237 }
15238 }
15239 const prefixIdentifiers = !true ;
15240 if (options.cacheHandlers) {
15241 onError(createCompilerError(48 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
15242 }
15243 if (options.scopeId && !isModuleMode) {
15244 onError(createCompilerError(49 /* X_SCOPE_ID_NOT_SUPPORTED */));
15245 }
15246 const ast = isString(template) ? baseParse(template, options) : template;
15247 const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
15248 transform(ast, extend({}, options, {
15249 prefixIdentifiers,
15250 nodeTransforms: [
15251 ...nodeTransforms,
15252 ...(options.nodeTransforms || []) // user transforms
15253 ],
15254 directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
15255 )
15256 }));
15257 return generate(ast, extend({}, options, {
15258 prefixIdentifiers
15259 }));
15260}
15261
15262const noopDirectiveTransform = () => ({ props: [] });
15263
15264const V_MODEL_RADIO = Symbol(`vModelRadio` );
15265const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
15266const V_MODEL_TEXT = Symbol(`vModelText` );
15267const V_MODEL_SELECT = Symbol(`vModelSelect` );
15268const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
15269const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
15270const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
15271const V_SHOW = Symbol(`vShow` );
15272const TRANSITION$1 = Symbol(`Transition` );
15273const TRANSITION_GROUP = Symbol(`TransitionGroup` );
15274registerRuntimeHelpers({
15275 [V_MODEL_RADIO]: `vModelRadio`,
15276 [V_MODEL_CHECKBOX]: `vModelCheckbox`,
15277 [V_MODEL_TEXT]: `vModelText`,
15278 [V_MODEL_SELECT]: `vModelSelect`,
15279 [V_MODEL_DYNAMIC]: `vModelDynamic`,
15280 [V_ON_WITH_MODIFIERS]: `withModifiers`,
15281 [V_ON_WITH_KEYS]: `withKeys`,
15282 [V_SHOW]: `vShow`,
15283 [TRANSITION$1]: `Transition`,
15284 [TRANSITION_GROUP]: `TransitionGroup`
15285});
15286
15287/* eslint-disable no-restricted-globals */
15288let decoder;
15289function decodeHtmlBrowser(raw, asAttr = false) {
15290 if (!decoder) {
15291 decoder = document.createElement('div');
15292 }
15293 if (asAttr) {
15294 decoder.innerHTML = `<div foo="${raw.replace(/"/g, '&quot;')}">`;
15295 return decoder.children[0].getAttribute('foo');
15296 }
15297 else {
15298 decoder.innerHTML = raw;
15299 return decoder.textContent;
15300 }
15301}
15302
15303const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
15304const parserOptions = {
15305 isVoidTag,
15306 isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
15307 isPreTag: tag => tag === 'pre',
15308 decodeEntities: decodeHtmlBrowser ,
15309 isBuiltInComponent: (tag) => {
15310 if (isBuiltInType(tag, `Transition`)) {
15311 return TRANSITION$1;
15312 }
15313 else if (isBuiltInType(tag, `TransitionGroup`)) {
15314 return TRANSITION_GROUP;
15315 }
15316 },
15317 // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
15318 getNamespace(tag, parent) {
15319 let ns = parent ? parent.ns : 0 /* HTML */;
15320 if (parent && ns === 2 /* MATH_ML */) {
15321 if (parent.tag === 'annotation-xml') {
15322 if (tag === 'svg') {
15323 return 1 /* SVG */;
15324 }
15325 if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
15326 a.name === 'encoding' &&
15327 a.value != null &&
15328 (a.value.content === 'text/html' ||
15329 a.value.content === 'application/xhtml+xml'))) {
15330 ns = 0 /* HTML */;
15331 }
15332 }
15333 else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
15334 tag !== 'mglyph' &&
15335 tag !== 'malignmark') {
15336 ns = 0 /* HTML */;
15337 }
15338 }
15339 else if (parent && ns === 1 /* SVG */) {
15340 if (parent.tag === 'foreignObject' ||
15341 parent.tag === 'desc' ||
15342 parent.tag === 'title') {
15343 ns = 0 /* HTML */;
15344 }
15345 }
15346 if (ns === 0 /* HTML */) {
15347 if (tag === 'svg') {
15348 return 1 /* SVG */;
15349 }
15350 if (tag === 'math') {
15351 return 2 /* MATH_ML */;
15352 }
15353 }
15354 return ns;
15355 },
15356 // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
15357 getTextMode({ tag, ns }) {
15358 if (ns === 0 /* HTML */) {
15359 if (tag === 'textarea' || tag === 'title') {
15360 return 1 /* RCDATA */;
15361 }
15362 if (isRawTextContainer(tag)) {
15363 return 2 /* RAWTEXT */;
15364 }
15365 }
15366 return 0 /* DATA */;
15367 }
15368};
15369
15370// Parse inline CSS strings for static style attributes into an object.
15371// This is a NodeTransform since it works on the static `style` attribute and
15372// converts it into a dynamic equivalent:
15373// style="color: red" -> :style='{ "color": "red" }'
15374// It is then processed by `transformElement` and included in the generated
15375// props.
15376const transformStyle = node => {
15377 if (node.type === 1 /* ELEMENT */) {
15378 node.props.forEach((p, i) => {
15379 if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
15380 // replace p with an expression node
15381 node.props[i] = {
15382 type: 7 /* DIRECTIVE */,
15383 name: `bind`,
15384 arg: createSimpleExpression(`style`, true, p.loc),
15385 exp: parseInlineCSS(p.value.content, p.loc),
15386 modifiers: [],
15387 loc: p.loc
15388 };
15389 }
15390 });
15391 }
15392};
15393const parseInlineCSS = (cssText, loc) => {
15394 const normalized = parseStringStyle(cssText);
15395 return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
15396};
15397
15398function createDOMCompilerError(code, loc) {
15399 return createCompilerError(code, loc, DOMErrorMessages );
15400}
15401const DOMErrorMessages = {
15402 [50 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
15403 [51 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
15404 [52 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
15405 [53 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
15406 [54 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
15407 [55 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
15408 [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.`,
15409 [57 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
15410 [58 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
15411 [59 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
15412 [60 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
15413};
15414
15415const transformVHtml = (dir, node, context) => {
15416 const { exp, loc } = dir;
15417 if (!exp) {
15418 context.onError(createDOMCompilerError(50 /* X_V_HTML_NO_EXPRESSION */, loc));
15419 }
15420 if (node.children.length) {
15421 context.onError(createDOMCompilerError(51 /* X_V_HTML_WITH_CHILDREN */, loc));
15422 node.children.length = 0;
15423 }
15424 return {
15425 props: [
15426 createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
15427 ]
15428 };
15429};
15430
15431const transformVText = (dir, node, context) => {
15432 const { exp, loc } = dir;
15433 if (!exp) {
15434 context.onError(createDOMCompilerError(52 /* X_V_TEXT_NO_EXPRESSION */, loc));
15435 }
15436 if (node.children.length) {
15437 context.onError(createDOMCompilerError(53 /* X_V_TEXT_WITH_CHILDREN */, loc));
15438 node.children.length = 0;
15439 }
15440 return {
15441 props: [
15442 createObjectProperty(createSimpleExpression(`textContent`, true), exp
15443 ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
15444 : createSimpleExpression('', true))
15445 ]
15446 };
15447};
15448
15449const transformModel$1 = (dir, node, context) => {
15450 const baseResult = transformModel(dir, node, context);
15451 // base transform has errors OR component v-model (only need props)
15452 if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
15453 return baseResult;
15454 }
15455 if (dir.arg) {
15456 context.onError(createDOMCompilerError(55 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
15457 }
15458 function checkDuplicatedValue() {
15459 const value = findProp(node, 'value');
15460 if (value) {
15461 context.onError(createDOMCompilerError(57 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
15462 }
15463 }
15464 const { tag } = node;
15465 const isCustomElement = context.isCustomElement(tag);
15466 if (tag === 'input' ||
15467 tag === 'textarea' ||
15468 tag === 'select' ||
15469 isCustomElement) {
15470 let directiveToUse = V_MODEL_TEXT;
15471 let isInvalidType = false;
15472 if (tag === 'input' || isCustomElement) {
15473 const type = findProp(node, `type`);
15474 if (type) {
15475 if (type.type === 7 /* DIRECTIVE */) {
15476 // :type="foo"
15477 directiveToUse = V_MODEL_DYNAMIC;
15478 }
15479 else if (type.value) {
15480 switch (type.value.content) {
15481 case 'radio':
15482 directiveToUse = V_MODEL_RADIO;
15483 break;
15484 case 'checkbox':
15485 directiveToUse = V_MODEL_CHECKBOX;
15486 break;
15487 case 'file':
15488 isInvalidType = true;
15489 context.onError(createDOMCompilerError(56 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
15490 break;
15491 default:
15492 // text type
15493 checkDuplicatedValue();
15494 break;
15495 }
15496 }
15497 }
15498 else if (hasDynamicKeyVBind(node)) {
15499 // element has bindings with dynamic keys, which can possibly contain
15500 // "type".
15501 directiveToUse = V_MODEL_DYNAMIC;
15502 }
15503 else {
15504 // text type
15505 checkDuplicatedValue();
15506 }
15507 }
15508 else if (tag === 'select') {
15509 directiveToUse = V_MODEL_SELECT;
15510 }
15511 else {
15512 // textarea
15513 checkDuplicatedValue();
15514 }
15515 // inject runtime directive
15516 // by returning the helper symbol via needRuntime
15517 // the import will replaced a resolveDirective call.
15518 if (!isInvalidType) {
15519 baseResult.needRuntime = context.helper(directiveToUse);
15520 }
15521 }
15522 else {
15523 context.onError(createDOMCompilerError(54 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
15524 }
15525 // native vmodel doesn't need the `modelValue` props since they are also
15526 // passed to the runtime as `binding.value`. removing it reduces code size.
15527 baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
15528 p.key.content === 'modelValue'));
15529 return baseResult;
15530};
15531
15532const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
15533const isNonKeyModifier = /*#__PURE__*/ makeMap(
15534// event propagation management
15535`stop,prevent,self,` +
15536 // system modifiers + exact
15537 `ctrl,shift,alt,meta,exact,` +
15538 // mouse
15539 `middle`);
15540// left & right could be mouse or key modifiers based on event type
15541const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
15542const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
15543const resolveModifiers = (key, modifiers, context, loc) => {
15544 const keyModifiers = [];
15545 const nonKeyModifiers = [];
15546 const eventOptionModifiers = [];
15547 for (let i = 0; i < modifiers.length; i++) {
15548 const modifier = modifiers[i];
15549 if (isEventOptionModifier(modifier)) {
15550 // eventOptionModifiers: modifiers for addEventListener() options,
15551 // e.g. .passive & .capture
15552 eventOptionModifiers.push(modifier);
15553 }
15554 else {
15555 // runtimeModifiers: modifiers that needs runtime guards
15556 if (maybeKeyModifier(modifier)) {
15557 if (isStaticExp(key)) {
15558 if (isKeyboardEvent(key.content)) {
15559 keyModifiers.push(modifier);
15560 }
15561 else {
15562 nonKeyModifiers.push(modifier);
15563 }
15564 }
15565 else {
15566 keyModifiers.push(modifier);
15567 nonKeyModifiers.push(modifier);
15568 }
15569 }
15570 else {
15571 if (isNonKeyModifier(modifier)) {
15572 nonKeyModifiers.push(modifier);
15573 }
15574 else {
15575 keyModifiers.push(modifier);
15576 }
15577 }
15578 }
15579 }
15580 return {
15581 keyModifiers,
15582 nonKeyModifiers,
15583 eventOptionModifiers
15584 };
15585};
15586const transformClick = (key, event) => {
15587 const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
15588 return isStaticClick
15589 ? createSimpleExpression(event, true)
15590 : key.type !== 4 /* SIMPLE_EXPRESSION */
15591 ? createCompoundExpression([
15592 `(`,
15593 key,
15594 `) === "onClick" ? "${event}" : (`,
15595 key,
15596 `)`
15597 ])
15598 : key;
15599};
15600const transformOn$1 = (dir, node, context) => {
15601 return transformOn(dir, node, context, baseResult => {
15602 const { modifiers } = dir;
15603 if (!modifiers.length)
15604 return baseResult;
15605 let { key, value: handlerExp } = baseResult.props[0];
15606 const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
15607 // normalize click.right and click.middle since they don't actually fire
15608 if (nonKeyModifiers.includes('right')) {
15609 key = transformClick(key, `onContextmenu`);
15610 }
15611 if (nonKeyModifiers.includes('middle')) {
15612 key = transformClick(key, `onMouseup`);
15613 }
15614 if (nonKeyModifiers.length) {
15615 handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
15616 handlerExp,
15617 JSON.stringify(nonKeyModifiers)
15618 ]);
15619 }
15620 if (keyModifiers.length &&
15621 // if event name is dynamic, always wrap with keys guard
15622 (!isStaticExp(key) || isKeyboardEvent(key.content))) {
15623 handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
15624 handlerExp,
15625 JSON.stringify(keyModifiers)
15626 ]);
15627 }
15628 if (eventOptionModifiers.length) {
15629 const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
15630 key = isStaticExp(key)
15631 ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
15632 : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
15633 }
15634 return {
15635 props: [createObjectProperty(key, handlerExp)]
15636 };
15637 });
15638};
15639
15640const transformShow = (dir, node, context) => {
15641 const { exp, loc } = dir;
15642 if (!exp) {
15643 context.onError(createDOMCompilerError(58 /* X_V_SHOW_NO_EXPRESSION */, loc));
15644 }
15645 return {
15646 props: [],
15647 needRuntime: context.helper(V_SHOW)
15648 };
15649};
15650
15651const warnTransitionChildren = (node, context) => {
15652 if (node.type === 1 /* ELEMENT */ &&
15653 node.tagType === 1 /* COMPONENT */) {
15654 const component = context.isBuiltInComponent(node.tag);
15655 if (component === TRANSITION$1) {
15656 return () => {
15657 if (node.children.length && hasMultipleChildren(node)) {
15658 context.onError(createDOMCompilerError(59 /* X_TRANSITION_INVALID_CHILDREN */, {
15659 start: node.children[0].loc.start,
15660 end: node.children[node.children.length - 1].loc.end,
15661 source: ''
15662 }));
15663 }
15664 };
15665 }
15666 }
15667};
15668function hasMultipleChildren(node) {
15669 // #1352 filter out potential comment nodes.
15670 const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */ &&
15671 !(c.type === 2 /* TEXT */ && !c.content.trim())));
15672 const child = children[0];
15673 return (children.length !== 1 ||
15674 child.type === 11 /* FOR */ ||
15675 (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
15676}
15677
15678const ignoreSideEffectTags = (node, context) => {
15679 if (node.type === 1 /* ELEMENT */ &&
15680 node.tagType === 0 /* ELEMENT */ &&
15681 (node.tag === 'script' || node.tag === 'style')) {
15682 context.onError(createDOMCompilerError(60 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
15683 context.removeNode();
15684 }
15685};
15686
15687const DOMNodeTransforms = [
15688 transformStyle,
15689 ...([warnTransitionChildren] )
15690];
15691const DOMDirectiveTransforms = {
15692 cloak: noopDirectiveTransform,
15693 html: transformVHtml,
15694 text: transformVText,
15695 model: transformModel$1,
15696 on: transformOn$1,
15697 show: transformShow
15698};
15699function compile$1(template, options = {}) {
15700 return baseCompile(template, extend({}, parserOptions, options, {
15701 nodeTransforms: [
15702 // ignore <script> and <tag>
15703 // this is not put inside DOMNodeTransforms because that list is used
15704 // by compiler-ssr to generate vnode fallback branches
15705 ignoreSideEffectTags,
15706 ...DOMNodeTransforms,
15707 ...(options.nodeTransforms || [])
15708 ],
15709 directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
15710 transformHoist: null
15711 }));
15712}
15713
15714// This entry is the "full-build" that includes both the runtime
15715{
15716 initDev();
15717}
15718const compileCache = Object.create(null);
15719function compileToFunction(template, options) {
15720 if (!isString(template)) {
15721 if (template.nodeType) {
15722 template = template.innerHTML;
15723 }
15724 else {
15725 warn$1(`invalid template option: `, template);
15726 return NOOP;
15727 }
15728 }
15729 const key = template;
15730 const cached = compileCache[key];
15731 if (cached) {
15732 return cached;
15733 }
15734 if (template[0] === '#') {
15735 const el = document.querySelector(template);
15736 if (!el) {
15737 warn$1(`Template element not found or is empty: ${template}`);
15738 }
15739 // __UNSAFE__
15740 // Reason: potential execution of JS expressions in in-DOM template.
15741 // The user must make sure the in-DOM template is trusted. If it's rendered
15742 // by the server, the template should not contain any user data.
15743 template = el ? el.innerHTML : ``;
15744 }
15745 const { code } = compile$1(template, extend({
15746 hoistStatic: true,
15747 onError: onError ,
15748 onWarn: e => onError(e, true)
15749 }, options));
15750 function onError(err, asWarning = false) {
15751 const message = asWarning
15752 ? err.message
15753 : `Template compilation error: ${err.message}`;
15754 const codeFrame = err.loc &&
15755 generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
15756 warn$1(codeFrame ? `${message}\n${codeFrame}` : message);
15757 }
15758 // The wildcard import results in a huge object with every export
15759 // with keys that cannot be mangled, and can be quite heavy size-wise.
15760 // In the global build we know `Vue` is available globally so we can avoid
15761 // the wildcard object.
15762 const render = (new Function('Vue', code)(runtimeDom));
15763 render._rc = true;
15764 return (compileCache[key] = render);
15765}
15766registerRuntimeCompiler(compileToFunction);
15767
15768export { 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 };