How to use pushWarningContext method in Playwright Internal

Best JavaScript code snippet using playwright-internal

runtime-dom.esm-browser.js

Source:runtime-dom.esm-browser.js Github

copy

Full Screen

...670 }671}672673let stack = [];674function pushWarningContext(vnode) {675 stack.push(vnode);676}677function popWarningContext() {678 stack.pop();679}680function warn(msg, ...args) {681 const instance = stack.length ? stack[stack.length - 1].component : null;682 const appWarnHandler = instance && instance.appContext.config.warnHandler;683 const trace = getComponentTrace();684 if (appWarnHandler) {685 appWarnHandler(msg + args.join(''), instance && instance.renderProxy, formatTrace(trace).join(''));686 return;687 }688 console.warn(`[Vue warn]: ${msg}`, ...args);689 // avoid spamming console during tests690 if (typeof process !== 'undefined' && process.env.NODE_ENV === 'test') {691 return;692 }693 if (!trace.length) {694 return;695 }696 if (trace.length > 1 && console.groupCollapsed) {697 console.groupCollapsed('at', ...formatTraceEntry(trace[0]));698 const logs = [];699 trace.slice(1).forEach((entry, i) => {700 if (i !== 0)701 logs.push('\n');702 logs.push(...formatTraceEntry(entry, i + 1));703 });704 console.log(...logs);705 console.groupEnd();706 }707 else {708 console.log(...formatTrace(trace));709 }710}711function getComponentTrace() {712 let currentVNode = stack[stack.length - 1];713 if (!currentVNode) {714 return [];715 }716 // we can't just use the stack because it will be incomplete during updates717 // that did not start from the root. Re-construct the parent chain using718 // instance parent pointers.719 const normalizedStack = [];720 while (currentVNode) {721 const last = normalizedStack[0];722 if (last && last.vnode === currentVNode) {723 last.recurseCount++;724 }725 else {726 normalizedStack.push({727 vnode: currentVNode,728 recurseCount: 0729 });730 }731 const parentInstance = currentVNode.component732 .parent;733 currentVNode = parentInstance && parentInstance.vnode;734 }735 return normalizedStack;736}737function formatTrace(trace) {738 const logs = [];739 trace.forEach((entry, i) => {740 const formatted = formatTraceEntry(entry, i);741 if (i === 0) {742 logs.push('at', ...formatted);743 }744 else {745 logs.push('\n', ...formatted);746 }747 });748 return logs;749}750function formatTraceEntry({ vnode, recurseCount }, depth = 0) {751 const padding = depth === 0 ? '' : ' '.repeat(depth * 2 + 1);752 const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;753 const open = padding + `<${formatComponentName(vnode)}`;754 const close = `>` + postfix;755 const rootLabel = vnode.component.parent == null ? `(Root)` : ``;756 return vnode.props757 ? [open, ...formatProps(vnode.props), close, rootLabel]758 : [open + close, rootLabel];759}760const classifyRE = /(?:^|[-_])(\w)/g;761const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');762function formatComponentName(vnode, file) {763 const Component = vnode.type;764 let name = Component.displayName || Component.name;765 if (!name && file) {766 const match = file.match(/([^/\\]+)\.vue$/);767 if (match) {768 name = match[1];769 }770 }771 return name ? classify(name) : 'AnonymousComponent';772}773function formatProps(props) {774 const res = [];775 for (const key in props) {776 const value = props[key];777 if (isString(value)) {778 res.push(`${key}=${JSON.stringify(value)}`);779 }780 else {781 res.push(`${key}=`, toRaw(value));782 }783 }784 return res;785}786787const ErrorTypeStrings = {788 ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',789 ["c" /* CREATED */]: 'created hook',790 ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',791 ["m" /* MOUNTED */]: 'mounted hook',792 ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',793 ["u" /* UPDATED */]: 'updated',794 ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',795 ["um" /* UNMOUNTED */]: 'unmounted hook',796 ["a" /* ACTIVATED */]: 'activated hook',797 ["da" /* DEACTIVATED */]: 'deactivated hook',798 ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',799 ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',800 ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',801 [0 /* SETUP_FUNCTION */]: 'setup function',802 [1 /* RENDER_FUNCTION */]: 'render function',803 [2 /* WATCH_GETTER */]: 'watcher getter',804 [3 /* WATCH_CALLBACK */]: 'watcher callback',805 [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',806 [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',807 [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',808 [7 /* DIRECTIVE_HOOK */]: 'directive hook',809 [8 /* APP_ERROR_HANDLER */]: 'app errorHandler',810 [9 /* APP_WARN_HANDLER */]: 'app warnHandler',811 [10 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +812 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue'813};814function callWithErrorHandling(fn, instance, type, args) {815 let res;816 try {817 res = args ? fn(...args) : fn();818 }819 catch (err) {820 handleError(err, instance, type);821 }822 return res;823}824function callWithAsyncErrorHandling(fn, instance, type, args) {825 const res = callWithErrorHandling(fn, instance, type, args);826 if (res != null && !res._isVue && typeof res.then === 'function') {827 res.catch((err) => {828 handleError(err, instance, type);829 });830 }831 return res;832}833function handleError(err, instance, type) {834 const contextVNode = instance ? instance.vnode : null;835 if (instance) {836 let cur = instance.parent;837 // the exposed instance is the render proxy to keep it consistent with 2.x838 const exposedInstance = instance.renderProxy;839 // in production the hook receives only the error code840 const errorInfo = ErrorTypeStrings[type] ;841 while (cur) {842 const errorCapturedHooks = cur.ec;843 if (errorCapturedHooks !== null) {844 for (let i = 0; i < errorCapturedHooks.length; i++) {845 if (errorCapturedHooks[i](err, exposedInstance, errorInfo)) {846 return;847 }848 }849 }850 cur = cur.parent;851 }852 // app-level handling853 const appErrorHandler = instance.appContext.config.errorHandler;854 if (appErrorHandler) {855 callWithErrorHandling(appErrorHandler, null, 8 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);856 return;857 }858 }859 logError(err, type, contextVNode);860}861function logError(err, type, contextVNode) {862 // default behavior is crash in prod & test, recover in dev.863 // TODO we should probably make this configurable via `createApp`864 if (865 !(typeof process !== 'undefined' && process.env.NODE_ENV === 'test')) {866 const info = ErrorTypeStrings[type];867 if (contextVNode) {868 pushWarningContext(contextVNode);869 }870 warn(`Unhandled error${info ? ` during execution of ${info}` : ``}`);871 console.error(err);872 if (contextVNode) {873 popWarningContext();874 }875 }876 else {877 throw err;878 }879}880881const queue = [];882const postFlushCbs = [];883const p = Promise.resolve();884let isFlushing = false;885function nextTick(fn) {886 return fn ? p.then(fn) : p;887}888function queueJob(job) {889 if (queue.indexOf(job) === -1) {890 queue.push(job);891 if (!isFlushing) {892 nextTick(flushJobs);893 }894 }895}896function queuePostFlushCb(cb) {897 if (Array.isArray(cb)) {898 postFlushCbs.push.apply(postFlushCbs, cb);899 }900 else {901 postFlushCbs.push(cb);902 }903 if (!isFlushing) {904 nextTick(flushJobs);905 }906}907const dedupe = (cbs) => Array.from(new Set(cbs));908function flushPostFlushCbs() {909 if (postFlushCbs.length) {910 const cbs = dedupe(postFlushCbs);911 postFlushCbs.length = 0;912 for (let i = 0; i < cbs.length; i++) {913 cbs[i]();914 }915 }916}917const RECURSION_LIMIT = 100;918function flushJobs(seenJobs) {919 isFlushing = true;920 let job;921 {922 seenJobs = seenJobs || new Map();923 }924 while ((job = queue.shift())) {925 {926 const seen = seenJobs;927 if (!seen.has(job)) {928 seen.set(job, 1);929 }930 else {931 const count = seen.get(job);932 if (count > RECURSION_LIMIT) {933 throw new Error('Maximum recursive updates exceeded. ' +934 "You may have code that is mutating state in your component's " +935 'render function or updated hook.');936 }937 else {938 seen.set(job, count + 1);939 }940 }941 }942 try {943 job();944 }945 catch (err) {946 handleError(err, null, 10 /* SCHEDULER */);947 }948 }949 flushPostFlushCbs();950 isFlushing = false;951 // some postFlushCb queued jobs!952 // keep flushing until it drains.953 if (queue.length) {954 flushJobs(seenJobs);955 }956}957958const Fragment = Symbol('Fragment') ;959const Text = Symbol('Text') ;960const Comment = Symbol('Empty') ;961const Portal = Symbol('Portal') ;962const Suspense = Symbol('Suspense') ;963// Since v-if and v-for are the two possible ways node structure can dynamically964// change, once we consider v-if branches and each v-for fragment a block, we965// can divide a template into nested blocks, and within each block the node966// structure would be stable. This allows us to skip most children diffing967// and only worry about the dynamic nodes (indicated by patch flags).968const blockStack = [];969// Open a block.970// This must be called before `createBlock`. It cannot be part of `createBlock`971// because the children of the block are evaluated before `createBlock` itself972// is called. The generated code typically looks like this:973//974// function render() {975// return (openBlock(),createBlock('div', null, [...]))976// }977//978// disableTracking is true when creating a fragment block, since a fragment979// always diffs its children.980function openBlock(disableTracking) {981 blockStack.push(disableTracking ? null : []);982}983let shouldTrack$1 = true;984// Create a block root vnode. Takes the same exact arguments as `createVNode`.985// A block root keeps track of dynamic nodes within the block in the986// `dynamicChildren` array.987function createBlock(type, props, children, patchFlag, dynamicProps) {988 // avoid a block with optFlag tracking itself989 shouldTrack$1 = false;990 const vnode = createVNode(type, props, children, patchFlag, dynamicProps);991 shouldTrack$1 = true;992 const trackedNodes = blockStack.pop();993 vnode.dynamicChildren =994 trackedNodes && trackedNodes.length ? trackedNodes : EMPTY_ARR;995 // a block is always going to be patched996 trackDynamicNode(vnode);997 return vnode;998}999function isVNode(value) {1000 return value ? value._isVNode === true : false;1001}1002function createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null) {1003 // class & style normalization.1004 if (props !== null) {1005 // for reactive or proxy objects, we need to clone it to enable mutation.1006 if (isReactive(props) || SetupProxySymbol in props) {1007 props = extend({}, props);1008 }1009 // class normalization only needed if the vnode isn't generated by1010 // compiler-optimized code1011 if (props.class != null && !(patchFlag & 2 /* CLASS */)) {1012 props.class = normalizeClass(props.class);1013 }1014 let { style } = props;1015 if (style != null) {1016 // reactive state objects need to be cloned since they are likely to be1017 // mutated1018 if (isReactive(style) && !isArray(style)) {1019 style = extend({}, style);1020 }1021 props.style = normalizeStyle(style);1022 }1023 }1024 // encode the vnode type information into a bitmap1025 const shapeFlag = isString(type)1026 ? 1 /* ELEMENT */1027 : isObject(type)1028 ? 4 /* STATEFUL_COMPONENT */1029 : isFunction(type)1030 ? 2 /* FUNCTIONAL_COMPONENT */1031 : 0;1032 const vnode = {1033 _isVNode: true,1034 type,1035 props,1036 key: (props && props.key) || null,1037 ref: (props && props.ref) || null,1038 children: null,1039 component: null,1040 suspense: null,1041 el: null,1042 anchor: null,1043 target: null,1044 shapeFlag,1045 patchFlag,1046 dynamicProps,1047 dynamicChildren: null,1048 appContext: null1049 };1050 normalizeChildren(vnode, children);1051 // presence of a patch flag indicates this node needs patching on updates.1052 // component nodes also should always be patched, because even if the1053 // component doesn't need to update, it needs to persist the instance on to1054 // the next vnode so that it can be properly unmounted later.1055 if (shouldTrack$1 &&1056 (patchFlag ||1057 shapeFlag & 4 /* STATEFUL_COMPONENT */ ||1058 shapeFlag & 2 /* FUNCTIONAL_COMPONENT */)) {1059 trackDynamicNode(vnode);1060 }1061 return vnode;1062}1063function trackDynamicNode(vnode) {1064 const currentBlockDynamicNodes = blockStack[blockStack.length - 1];1065 if (currentBlockDynamicNodes != null) {1066 currentBlockDynamicNodes.push(vnode);1067 }1068}1069function cloneVNode(vnode) {1070 return {1071 _isVNode: true,1072 type: vnode.type,1073 props: vnode.props,1074 key: vnode.key,1075 ref: vnode.ref,1076 children: vnode.children,1077 target: vnode.target,1078 shapeFlag: vnode.shapeFlag,1079 patchFlag: vnode.patchFlag,1080 dynamicProps: vnode.dynamicProps,1081 dynamicChildren: vnode.dynamicChildren,1082 appContext: vnode.appContext,1083 // these should be set to null since they should only be present on1084 // mounted VNodes. If they are somehow not null, this means we have1085 // encountered an already-mounted vnode being used again.1086 component: null,1087 suspense: null,1088 el: null,1089 anchor: null1090 };1091}1092function normalizeVNode(child) {1093 if (child == null) {1094 // empty placeholder1095 return createVNode(Comment);1096 }1097 else if (isArray(child)) {1098 // fragment1099 return createVNode(Fragment, null, child);1100 }1101 else if (typeof child === 'object') {1102 // already vnode, this should be the most common since compiled templates1103 // always produce all-vnode children arrays1104 return child.el === null ? child : cloneVNode(child);1105 }1106 else {1107 // primitive types1108 return createVNode(Text, null, child + '');1109 }1110}1111function normalizeChildren(vnode, children) {1112 let type = 0;1113 if (children == null) {1114 children = null;1115 }1116 else if (isArray(children)) {1117 type = 16 /* ARRAY_CHILDREN */;1118 }1119 else if (typeof children === 'object') {1120 type = 32 /* SLOTS_CHILDREN */;1121 }1122 else if (isFunction(children)) {1123 children = { default: children };1124 type = 32 /* SLOTS_CHILDREN */;1125 }1126 else {1127 children = isString(children) ? children : children + '';1128 type = 8 /* TEXT_CHILDREN */;1129 }1130 vnode.children = children;1131 vnode.shapeFlag |= type;1132}1133function normalizeStyle(value) {1134 if (isArray(value)) {1135 const res = {};1136 for (let i = 0; i < value.length; i++) {1137 const normalized = normalizeStyle(value[i]);1138 if (normalized) {1139 for (const key in normalized) {1140 res[key] = normalized[key];1141 }1142 }1143 }1144 return res;1145 }1146 else if (isObject(value)) {1147 return value;1148 }1149}1150function normalizeClass(value) {1151 let res = '';1152 if (isString(value)) {1153 res = value;1154 }1155 else if (isArray(value)) {1156 for (let i = 0; i < value.length; i++) {1157 res += normalizeClass(value[i]) + ' ';1158 }1159 }1160 else if (isObject(value)) {1161 for (const name in value) {1162 if (value[name]) {1163 res += name + ' ';1164 }1165 }1166 }1167 return res.trim();1168}1169const handlersRE = /^on|^vnode/;1170function mergeProps(...args) {1171 const ret = {};1172 extend(ret, args[0]);1173 for (let i = 1; i < args.length; i++) {1174 const toMerge = args[i];1175 for (const key in toMerge) {1176 if (key === 'class') {1177 ret.class = normalizeClass([ret.class, toMerge.class]);1178 }1179 else if (key === 'style') {1180 ret.style = normalizeStyle([ret.style, toMerge.style]);1181 }1182 else if (handlersRE.test(key)) {1183 // on*, vnode*1184 const existing = ret[key];1185 ret[key] = existing1186 ? [].concat(existing, toMerge[key])1187 : toMerge[key];1188 }1189 else {1190 ret[key] = toMerge[key];1191 }1192 }1193 }1194 return ret;1195}11961197function injectHook(type, hook, target) {1198 if (target) {1199 (target[type] || (target[type] = [])).push((...args) => {1200 if (target.isUnmounted) {1201 return;1202 }1203 // disable tracking inside all lifecycle hooks1204 // since they can potentially be called inside effects.1205 pauseTracking();1206 // Set currentInstance during hook invocation.1207 // This assumes the hook does not synchronously trigger other hooks, which1208 // can only be false when the user does something really funky.1209 setCurrentInstance(target);1210 const res = callWithAsyncErrorHandling(hook, target, type, args);1211 setCurrentInstance(null);1212 resumeTracking();1213 return res;1214 });1215 }1216 else {1217 const apiName = `on${capitalize(ErrorTypeStrings[type].replace(/ hook$/, ''))}`;1218 warn(`${apiName} is called when there is no active component instance to be ` +1219 `associated with. ` +1220 `Lifecycle injection APIs can only be used during execution of setup().` +1221 ( ` If you are using async setup(), make sure to register lifecycle ` +1222 `hooks before the first await statement.`1223 ));1224 }1225}1226function onBeforeMount(hook, target = currentInstance) {1227 injectHook("bm" /* BEFORE_MOUNT */, hook, target);1228}1229function onMounted(hook, target = currentInstance) {1230 injectHook("m" /* MOUNTED */, hook, target);1231}1232function onBeforeUpdate(hook, target = currentInstance) {1233 injectHook("bu" /* BEFORE_UPDATE */, hook, target);1234}1235function onUpdated(hook, target = currentInstance) {1236 injectHook("u" /* UPDATED */, hook, target);1237}1238function onBeforeUnmount(hook, target = currentInstance) {1239 injectHook("bum" /* BEFORE_UNMOUNT */, hook, target);1240}1241function onUnmounted(hook, target = currentInstance) {1242 injectHook("um" /* UNMOUNTED */, hook, target);1243}1244function onRenderTriggered(hook, target = currentInstance) {1245 injectHook("rtg" /* RENDER_TRIGGERED */, hook, target);1246}1247function onRenderTracked(hook, target = currentInstance) {1248 injectHook("rtc" /* RENDER_TRACKED */, hook, target);1249}1250function onErrorCaptured(hook, target = currentInstance) {1251 injectHook("ec" /* ERROR_CAPTURED */, hook, target);1252}12531254// mark the current rendering instance for asset resolution (e.g.1255// resolveComponent, resolveDirective) during render1256let currentRenderingInstance = null;1257function renderComponentRoot(instance) {1258 const { type: Component, vnode, renderProxy, props, slots, attrs, emit } = instance;1259 let result;1260 currentRenderingInstance = instance;1261 try {1262 if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {1263 result = normalizeVNode(instance.render.call(renderProxy));1264 }1265 else {1266 // functional1267 const render = Component;1268 result = normalizeVNode(render.length > 11269 ? render(props, {1270 attrs,1271 slots,1272 emit1273 })1274 : render(props, null));1275 }1276 }1277 catch (err) {1278 handleError(err, instance, 1 /* RENDER_FUNCTION */);1279 result = createVNode(Comment);1280 }1281 currentRenderingInstance = null;1282 return result;1283}1284function shouldUpdateComponent(prevVNode, nextVNode, optimized) {1285 const { props: prevProps, children: prevChildren } = prevVNode;1286 const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;1287 if (patchFlag > 0) {1288 if (patchFlag & 256 /* DYNAMIC_SLOTS */) {1289 // slot content that references values that might have changed,1290 // e.g. in a v-for1291 return true;1292 }1293 if (patchFlag & 16 /* FULL_PROPS */) {1294 // presence of this flag indicates props are always non-null1295 return hasPropsChanged(prevProps, nextProps);1296 }1297 else if (patchFlag & 8 /* PROPS */) {1298 const dynamicProps = nextVNode.dynamicProps;1299 for (let i = 0; i < dynamicProps.length; i++) {1300 const key = dynamicProps[i];1301 if (nextProps[key] !== prevProps[key]) {1302 return true;1303 }1304 }1305 }1306 }1307 else if (!optimized) {1308 // this path is only taken by manually written render functions1309 // so presence of any children leads to a forced update1310 if (prevChildren != null || nextChildren != null) {1311 return true;1312 }1313 if (prevProps === nextProps) {1314 return false;1315 }1316 if (prevProps === null) {1317 return nextProps !== null;1318 }1319 if (nextProps === null) {1320 return prevProps !== null;1321 }1322 return hasPropsChanged(prevProps, nextProps);1323 }1324 return false;1325}1326function hasPropsChanged(prevProps, nextProps) {1327 const nextKeys = Object.keys(nextProps);1328 if (nextKeys.length !== Object.keys(prevProps).length) {1329 return true;1330 }1331 for (let i = 0; i < nextKeys.length; i++) {1332 const key = nextKeys[i];1333 if (nextProps[key] !== prevProps[key]) {1334 return true;1335 }1336 }1337 return false;1338}13391340// resolve raw VNode data.1341// - filter out reserved keys (key, ref, slots)1342// - extract class and style into $attrs (to be merged onto child1343// component root)1344// - for the rest:1345// - if has declared props: put declared ones in `props`, the rest in `attrs`1346// - else: everything goes in `props`.1347function resolveProps(instance, rawProps, _options) {1348 const hasDeclaredProps = _options != null;1349 const options = normalizePropsOptions(_options);1350 if (!rawProps && !hasDeclaredProps) {1351 return;1352 }1353 const props = {};1354 let attrs = void 0;1355 // update the instance propsProxy (passed to setup()) to trigger potential1356 // changes1357 const propsProxy = instance.propsProxy;1358 const setProp = propsProxy1359 ? (key, val) => {1360 props[key] = val;1361 propsProxy[key] = val;1362 }1363 : (key, val) => {1364 props[key] = val;1365 };1366 // allow mutation of propsProxy (which is readonly by default)1367 unlock();1368 if (rawProps != null) {1369 for (const key in rawProps) {1370 // key, ref are reserved1371 if (isReservedProp(key))1372 continue;1373 // any non-declared data are put into a separate `attrs` object1374 // for spreading1375 if (hasDeclaredProps && !hasOwn(options, key)) {1376 (attrs || (attrs = {}))[key] = rawProps[key];1377 }1378 else {1379 setProp(key, rawProps[key]);1380 }1381 }1382 }1383 // set default values, cast booleans & run validators1384 if (hasDeclaredProps) {1385 for (const key in options) {1386 let opt = options[key];1387 if (opt == null)1388 continue;1389 const isAbsent = !hasOwn(props, key);1390 const hasDefault = hasOwn(opt, 'default');1391 const currentValue = props[key];1392 // default values1393 if (hasDefault && currentValue === undefined) {1394 const defaultValue = opt.default;1395 setProp(key, isFunction(defaultValue) ? defaultValue() : defaultValue);1396 }1397 // boolean casting1398 if (opt["1" /* shouldCast */]) {1399 if (isAbsent && !hasDefault) {1400 setProp(key, false);1401 }1402 else if (opt["2" /* shouldCastTrue */] &&1403 (currentValue === '' || currentValue === hyphenate(key))) {1404 setProp(key, true);1405 }1406 }1407 // runtime validation1408 if ( rawProps) {1409 validateProp(key, toRaw(rawProps[key]), opt, isAbsent);1410 }1411 }1412 }1413 else {1414 // if component has no declared props, $attrs === $props1415 attrs = props;1416 }1417 // in case of dynamic props, check if we need to delete keys from1418 // the props proxy1419 const { patchFlag } = instance.vnode;1420 if (propsProxy !== null &&1421 (patchFlag === 0 || patchFlag & 16 /* FULL_PROPS */)) {1422 const rawInitialProps = toRaw(propsProxy);1423 for (const key in rawInitialProps) {1424 if (!hasOwn(props, key)) {1425 delete propsProxy[key];1426 }1427 }1428 }1429 // lock readonly1430 lock();1431 instance.props = readonly(props) ;1432 instance.attrs = options1433 ? attrs != null1434 ? readonly(attrs)1435 : attrs1436 : instance.props;1437}1438const normalizationMap = new WeakMap();1439function normalizePropsOptions(raw) {1440 if (!raw) {1441 return null;1442 }1443 if (normalizationMap.has(raw)) {1444 return normalizationMap.get(raw);1445 }1446 const normalized = {};1447 normalizationMap.set(raw, normalized);1448 if (isArray(raw)) {1449 for (let i = 0; i < raw.length; i++) {1450 if ( !isString(raw[i])) {1451 warn(`props must be strings when using array syntax.`, raw[i]);1452 }1453 const normalizedKey = camelize(raw[i]);1454 if (normalizedKey[0] !== '$') {1455 normalized[normalizedKey] = EMPTY_OBJ;1456 }1457 else {1458 warn(`Invalid prop name: "${normalizedKey}" is a reserved property.`);1459 }1460 }1461 }1462 else {1463 if ( !isObject(raw)) {1464 warn(`invalid props options`, raw);1465 }1466 for (const key in raw) {1467 const normalizedKey = camelize(key);1468 if (normalizedKey[0] !== '$') {1469 const opt = raw[key];1470 const prop = (normalized[normalizedKey] =1471 isArray(opt) || isFunction(opt) ? { type: opt } : opt);1472 if (prop != null) {1473 const booleanIndex = getTypeIndex(Boolean, prop.type);1474 const stringIndex = getTypeIndex(String, prop.type);1475 prop["1" /* shouldCast */] = booleanIndex > -1;1476 prop["2" /* shouldCastTrue */] = booleanIndex < stringIndex;1477 }1478 }1479 else {1480 warn(`Invalid prop name: "${normalizedKey}" is a reserved property.`);1481 }1482 }1483 }1484 return normalized;1485}1486// use function string name to check type constructors1487// so that it works across vms / iframes.1488function getType(ctor) {1489 const match = ctor && ctor.toString().match(/^\s*function (\w+)/);1490 return match ? match[1] : '';1491}1492function isSameType(a, b) {1493 return getType(a) === getType(b);1494}1495function getTypeIndex(type, expectedTypes) {1496 if (isArray(expectedTypes)) {1497 for (let i = 0, len = expectedTypes.length; i < len; i++) {1498 if (isSameType(expectedTypes[i], type)) {1499 return i;1500 }1501 }1502 }1503 else if (isObject(expectedTypes)) {1504 return isSameType(expectedTypes, type) ? 0 : -1;1505 }1506 return -1;1507}1508function validateProp(name, value, prop, isAbsent) {1509 const { type, required, validator } = prop;1510 // required!1511 if (required && isAbsent) {1512 warn('Missing required prop: "' + name + '"');1513 return;1514 }1515 // missing but optional1516 if (value == null && !prop.required) {1517 return;1518 }1519 // type check1520 if (type != null && type !== true) {1521 let isValid = false;1522 const types = isArray(type) ? type : [type];1523 const expectedTypes = [];1524 // value is valid as long as one of the specified types match1525 for (let i = 0; i < types.length && !isValid; i++) {1526 const { valid, expectedType } = assertType(value, types[i]);1527 expectedTypes.push(expectedType || '');1528 isValid = valid;1529 }1530 if (!isValid) {1531 warn(getInvalidTypeMessage(name, value, expectedTypes));1532 return;1533 }1534 }1535 // custom validator1536 if (validator && !validator(value)) {1537 warn('Invalid prop: custom validator check failed for prop "' + name + '".');1538 }1539}1540const simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/;1541function assertType(value, type) {1542 let valid;1543 const expectedType = getType(type);1544 if (simpleCheckRE.test(expectedType)) {1545 const t = typeof value;1546 valid = t === expectedType.toLowerCase();1547 // for primitive wrapper objects1548 if (!valid && t === 'object') {1549 valid = value instanceof type;1550 }1551 }1552 else if (expectedType === 'Object') {1553 valid = toRawType(value) === 'Object';1554 }1555 else if (expectedType === 'Array') {1556 valid = isArray(value);1557 }1558 else {1559 valid = value instanceof type;1560 }1561 return {1562 valid,1563 expectedType1564 };1565}1566function getInvalidTypeMessage(name, value, expectedTypes) {1567 let message = `Invalid prop: type check failed for prop "${name}".` +1568 ` Expected ${expectedTypes.map(capitalize).join(', ')}`;1569 const expectedType = expectedTypes[0];1570 const receivedType = toRawType(value);1571 const expectedValue = styleValue(value, expectedType);1572 const receivedValue = styleValue(value, receivedType);1573 // check if we need to specify expected value1574 if (expectedTypes.length === 1 &&1575 isExplicable(expectedType) &&1576 !isBoolean(expectedType, receivedType)) {1577 message += ` with value ${expectedValue}`;1578 }1579 message += `, got ${receivedType} `;1580 // check if we need to specify received value1581 if (isExplicable(receivedType)) {1582 message += `with value ${receivedValue}.`;1583 }1584 return message;1585}1586function styleValue(value, type) {1587 if (type === 'String') {1588 return `"${value}"`;1589 }1590 else if (type === 'Number') {1591 return `${Number(value)}`;1592 }1593 else {1594 return `${value}`;1595 }1596}1597function toRawType(value) {1598 return toTypeString(value).slice(8, -1);1599}1600function isExplicable(type) {1601 const explicitTypes = ['string', 'number', 'boolean'];1602 return explicitTypes.some(elem => type.toLowerCase() === elem);1603}1604function isBoolean(...args) {1605 return args.some(elem => elem.toLowerCase() === 'boolean');1606}16071608const normalizeSlotValue = (value) => isArray(value)1609 ? value.map(normalizeVNode)1610 : [normalizeVNode(value)];1611const normalizeSlot = (key, rawSlot) => (props) => {1612 if ( currentInstance != null) {1613 warn(`Slot "${key}" invoked outside of the render function: ` +1614 `this will not track dependencies used in the slot. ` +1615 `Invoke the slot function inside the render function instead.`);1616 }1617 return normalizeSlotValue(rawSlot(props));1618};1619function resolveSlots(instance, children) {1620 let slots;1621 if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {1622 if (children._compiled) {1623 // pre-normalized slots object generated by compiler1624 slots = children;1625 }1626 else {1627 slots = {};1628 for (const key in children) {1629 let value = children[key];1630 if (isFunction(value)) {1631 slots[key] = normalizeSlot(key, value);1632 }1633 else if (value != null) {1634 {1635 warn(`Non-function value encountered for slot "${key}". ` +1636 `Prefer function slots for better performance.`);1637 }1638 value = normalizeSlotValue(value);1639 slots[key] = () => value;1640 }1641 }1642 }1643 }1644 else if (children !== null) {1645 // non slot object children (direct value) passed to a component1646 {1647 warn(`Non-function value encountered for default slot. ` +1648 `Prefer function slots for better performance.`);1649 }1650 const normalized = normalizeSlotValue(children);1651 slots = { default: () => normalized };1652 }1653 if (slots !== void 0) {1654 instance.slots = slots;1655 }1656}16571658/**1659Runtime helper for applying directives to a vnode. Example usage:16601661const comp = resolveComponent('comp')1662const foo = resolveDirective('foo')1663const bar = resolveDirective('bar')16641665return applyDirectives(h(comp), [1666 [foo, this.x],1667 [bar, this.y]1668])1669*/1670const valueCache = new WeakMap();1671function applyDirective(props, instance, directive, value, arg, modifiers) {1672 let valueCacheForDir = valueCache.get(directive);1673 if (!valueCacheForDir) {1674 valueCacheForDir = new WeakMap();1675 valueCache.set(directive, valueCacheForDir);1676 }1677 for (const key in directive) {1678 const hook = directive[key];1679 const hookKey = `vnode` + key[0].toUpperCase() + key.slice(1);1680 const vnodeHook = (vnode, prevVNode) => {1681 let oldValue;1682 if (prevVNode != null) {1683 oldValue = valueCacheForDir.get(prevVNode);1684 valueCacheForDir.delete(prevVNode);1685 }1686 valueCacheForDir.set(vnode, value);1687 hook(vnode.el, {1688 instance: instance.renderProxy,1689 value,1690 oldValue,1691 arg,1692 modifiers1693 }, vnode, prevVNode);1694 };1695 const existing = props[hookKey];1696 props[hookKey] = existing1697 ? [].concat(existing, vnodeHook)1698 : vnodeHook;1699 }1700}1701function applyDirectives(vnode, directives) {1702 const instance = currentRenderingInstance;1703 if (instance !== null) {1704 vnode = cloneVNode(vnode);1705 vnode.props = vnode.props != null ? extend({}, vnode.props) : {};1706 for (let i = 0; i < directives.length; i++) {1707 applyDirective(vnode.props, instance, ...directives[i]);1708 }1709 }1710 else {1711 warn(`applyDirectives can only be used inside render functions.`);1712 }1713 return vnode;1714}1715function invokeDirectiveHook(hook, instance, vnode, prevVNode = null) {1716 const args = [vnode, prevVNode];1717 if (isArray(hook)) {1718 for (let i = 0; i < hook.length; i++) {1719 callWithAsyncErrorHandling(hook[i], instance, 7 /* DIRECTIVE_HOOK */, args);1720 }1721 }1722 else if (isFunction(hook)) {1723 callWithAsyncErrorHandling(hook, instance, 7 /* DIRECTIVE_HOOK */, args);1724 }1725}17261727function createAppContext() {1728 return {1729 config: {1730 devtools: true,1731 performance: false,1732 errorHandler: undefined,1733 warnHandler: undefined1734 },1735 mixins: [],1736 components: {},1737 directives: {},1738 provides: {}1739 };1740}1741function createAppAPI(render) {1742 return function createApp() {1743 const context = createAppContext();1744 let isMounted = false;1745 const app = {1746 get config() {1747 return context.config;1748 },1749 set config(v) {1750 {1751 warn(`app.config cannot be replaced. Modify individual options instead.`);1752 }1753 },1754 use(plugin) {1755 if (isFunction(plugin)) {1756 plugin(app);1757 }1758 else if (isFunction(plugin.install)) {1759 plugin.install(app);1760 }1761 else {1762 warn(`A plugin must either be a function or an object with an "install" ` +1763 `function.`);1764 }1765 return app;1766 },1767 mixin(mixin) {1768 context.mixins.push(mixin);1769 return app;1770 },1771 component(name, component) {1772 // TODO component name validation1773 if (!component) {1774 return context.components[name];1775 }1776 else {1777 context.components[name] = component;1778 return app;1779 }1780 },1781 directive(name, directive) {1782 // TODO directive name validation1783 if (!directive) {1784 return context.directives[name];1785 }1786 else {1787 context.directives[name] = directive;1788 return app;1789 }1790 },1791 mount(rootComponent, rootContainer, rootProps) {1792 if (!isMounted) {1793 const vnode = createVNode(rootComponent, rootProps);1794 // store app context on the root VNode.1795 // this will be set on the root instance on initial mount.1796 vnode.appContext = context;1797 render(vnode, rootContainer);1798 isMounted = true;1799 return vnode.component.renderProxy;1800 }1801 else {1802 warn(`App has already been mounted. Create a new app instance instead.`);1803 }1804 },1805 provide(key, value) {1806 if ( key in context.provides) {1807 warn(`App already provides property with key "${key}". ` +1808 `It will be overwritten with the new value.`);1809 }1810 context.provides[key] = value;1811 }1812 };1813 return app;1814 };1815}18161817function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, optimized) {1818 return {1819 vnode,1820 parent,1821 parentComponent,1822 isSVG,1823 optimized,1824 container,1825 hiddenContainer,1826 anchor,1827 deps: 0,1828 subTree: null,1829 fallbackTree: null,1830 isResolved: false,1831 isUnmounted: false,1832 effects: []1833 };1834}1835function normalizeSuspenseChildren(vnode) {1836 const { shapeFlag, children } = vnode;1837 if (shapeFlag & PublicShapeFlags.SLOTS_CHILDREN) {1838 const { default: d, fallback } = children;1839 return {1840 content: normalizeVNode(isFunction(d) ? d() : d),1841 fallback: normalizeVNode(isFunction(fallback) ? fallback() : fallback)1842 };1843 }1844 else {1845 return {1846 content: normalizeVNode(children),1847 fallback: normalizeVNode(null)1848 };1849 }1850}18511852function createDevEffectOptions(instance) {1853 return {1854 scheduler: queueJob,1855 onTrack: instance.rtc ? e => invokeHooks(instance.rtc, e) : void 0,1856 onTrigger: instance.rtg ? e => invokeHooks(instance.rtg, e) : void 01857 };1858}1859function isSameType$1(n1, n2) {1860 return n1.type === n2.type && n1.key === n2.key;1861}1862function invokeHooks(hooks, arg) {1863 for (let i = 0; i < hooks.length; i++) {1864 hooks[i](arg);1865 }1866}1867function queuePostRenderEffect(fn, suspense) {1868 if (suspense !== null && !suspense.isResolved) {1869 if (isArray(fn)) {1870 suspense.effects.push(...fn);1871 }1872 else {1873 suspense.effects.push(fn);1874 }1875 }1876 else {1877 queuePostFlushCb(fn);1878 }1879}1880/**1881 * The createRenderer function accepts two generic arguments:1882 * HostNode and HostElement, corresponding to Node and Element types in the1883 * host environment. For example, for runtime-dom, HostNode would be the DOM1884 * `Node` interface and HostElement would be the DOM `Element` interface.1885 *1886 * Custom renderers can pass in the platform specific types like this:1887 *1888 * ``` js1889 * const { render, createApp } = createRenderer<Node, Element>({1890 * patchProp,1891 * ...nodeOps1892 * })1893 * ```1894 */1895function createRenderer(options) {1896 const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, querySelector: hostQuerySelector } = options;1897 function patch(n1, // null means this is a mount1898 n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, optimized = false) {1899 // patching & not same type, unmount old tree1900 if (n1 != null && !isSameType$1(n1, n2)) {1901 anchor = getNextHostNode(n1);1902 unmount(n1, parentComponent, parentSuspense, true);1903 n1 = null;1904 }1905 const { type, shapeFlag } = n2;1906 switch (type) {1907 case Text:1908 processText(n1, n2, container, anchor);1909 break;1910 case Comment:1911 processCommentNode(n1, n2, container, anchor);1912 break;1913 case Fragment:1914 processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);1915 break;1916 case Portal:1917 processPortal(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);1918 break;1919 case Suspense:1920 {1921 processSuspense(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);1922 }1923 break;1924 default:1925 if (shapeFlag & 1 /* ELEMENT */) {1926 processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);1927 }1928 else if (shapeFlag & 6 /* COMPONENT */) {1929 processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);1930 }1931 else {1932 warn('Invalid HostVNode type:', n2.type, `(${typeof n2.type})`);1933 }1934 }1935 }1936 function processText(n1, n2, container, anchor) {1937 if (n1 == null) {1938 hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);1939 }1940 else {1941 const el = (n2.el = n1.el);1942 if (n2.children !== n1.children) {1943 hostSetText(el, n2.children);1944 }1945 }1946 }1947 function processCommentNode(n1, n2, container, anchor) {1948 if (n1 == null) {1949 hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);1950 }1951 else {1952 // there's no support for dynamic comments1953 n2.el = n1.el;1954 }1955 }1956 function processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) {1957 if (n1 == null) {1958 mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG);1959 }1960 else {1961 patchElement(n1, n2, parentComponent, parentSuspense, isSVG, optimized);1962 }1963 if (n2.ref !== null && parentComponent !== null) {1964 setRef(n2.ref, n1 && n1.ref, parentComponent, n2.el);1965 }1966 }1967 function mountElement(vnode, container, anchor, parentComponent, parentSuspense, isSVG) {1968 const tag = vnode.type;1969 isSVG = isSVG || tag === 'svg';1970 const el = (vnode.el = hostCreateElement(tag, isSVG));1971 const { props, shapeFlag } = vnode;1972 if (props != null) {1973 for (const key in props) {1974 if (isReservedProp(key))1975 continue;1976 hostPatchProp(el, key, props[key], null, isSVG);1977 }1978 if (props.vnodeBeforeMount != null) {1979 invokeDirectiveHook(props.vnodeBeforeMount, parentComponent, vnode);1980 }1981 }1982 if (shapeFlag & 8 /* TEXT_CHILDREN */) {1983 hostSetElementText(el, vnode.children);1984 }1985 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {1986 mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG);1987 }1988 hostInsert(el, container, anchor);1989 if (props != null && props.vnodeMounted != null) {1990 queuePostRenderEffect(() => {1991 invokeDirectiveHook(props.vnodeMounted, parentComponent, vnode);1992 }, parentSuspense);1993 }1994 }1995 function mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, start = 0) {1996 for (let i = start; i < children.length; i++) {1997 const child = (children[i] = normalizeVNode(children[i]));1998 patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG);1999 }2000 }2001 function patchElement(n1, n2, parentComponent, parentSuspense, isSVG, optimized) {2002 const el = (n2.el = n1.el);2003 const { patchFlag, dynamicChildren } = n2;2004 const oldProps = (n1 && n1.props) || EMPTY_OBJ;2005 const newProps = n2.props || EMPTY_OBJ;2006 if (newProps.vnodeBeforeUpdate != null) {2007 invokeDirectiveHook(newProps.vnodeBeforeUpdate, parentComponent, n2, n1);2008 }2009 if (patchFlag > 0) {2010 // the presence of a patchFlag means this element's render code was2011 // generated by the compiler and can take the fast path.2012 // in this path old node and new node are guaranteed to have the same shape2013 // (i.e. at the exact same position in the source template)2014 if (patchFlag & 16 /* FULL_PROPS */) {2015 // element props contain dynamic keys, full diff needed2016 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);2017 }2018 else {2019 // class2020 // this flag is matched when the element has dynamic class bindings.2021 if (patchFlag & 2 /* CLASS */) {2022 if (oldProps.class !== newProps.class) {2023 hostPatchProp(el, 'class', newProps.class, null, isSVG);2024 }2025 }2026 // style2027 // this flag is matched when the element has dynamic style bindings2028 if (patchFlag & 4 /* STYLE */) {2029 hostPatchProp(el, 'style', newProps.style, oldProps.style, isSVG);2030 }2031 // props2032 // This flag is matched when the element has dynamic prop/attr bindings2033 // other than class and style. The keys of dynamic prop/attrs are saved for2034 // faster iteration.2035 // Note dynamic keys like :[foo]="bar" will cause this optimization to2036 // bail out and go through a full diff because we need to unset the old key2037 if (patchFlag & 8 /* PROPS */) {2038 // if the flag is present then dynamicProps must be non-null2039 const propsToUpdate = n2.dynamicProps;2040 for (let i = 0; i < propsToUpdate.length; i++) {2041 const key = propsToUpdate[i];2042 const prev = oldProps[key];2043 const next = newProps[key];2044 if (prev !== next) {2045 hostPatchProp(el, key, next, prev, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);2046 }2047 }2048 }2049 }2050 // text2051 // This flag is matched when the element has only dynamic text children.2052 // this flag is terminal (i.e. skips children diffing).2053 if (patchFlag & 1 /* TEXT */) {2054 if (n1.children !== n2.children) {2055 hostSetElementText(el, n2.children);2056 }2057 return; // terminal2058 }2059 }2060 else if (!optimized) {2061 // unoptimized, full diff2062 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);2063 }2064 if (dynamicChildren != null) {2065 // children fast path2066 const oldDynamicChildren = n1.dynamicChildren;2067 for (let i = 0; i < dynamicChildren.length; i++) {2068 patch(oldDynamicChildren[i], dynamicChildren[i], el, null, parentComponent, parentSuspense, isSVG, true);2069 }2070 }2071 else if (!optimized) {2072 // full diff2073 patchChildren(n1, n2, el, null, parentComponent, parentSuspense, isSVG);2074 }2075 if (newProps.vnodeUpdated != null) {2076 queuePostRenderEffect(() => {2077 invokeDirectiveHook(newProps.vnodeUpdated, parentComponent, n2, n1);2078 }, parentSuspense);2079 }2080 }2081 function patchProps(el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) {2082 if (oldProps !== newProps) {2083 for (const key in newProps) {2084 if (isReservedProp(key))2085 continue;2086 const next = newProps[key];2087 const prev = oldProps[key];2088 if (next !== prev) {2089 hostPatchProp(el, key, next, prev, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);2090 }2091 }2092 if (oldProps !== EMPTY_OBJ) {2093 for (const key in oldProps) {2094 if (isReservedProp(key))2095 continue;2096 if (!(key in newProps)) {2097 hostPatchProp(el, key, null, null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);2098 }2099 }2100 }2101 }2102 }2103 function processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) {2104 const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateComment(''));2105 const fragmentEndAnchor = (n2.anchor = n12106 ? n1.anchor2107 : hostCreateComment(''));2108 if (n1 == null) {2109 hostInsert(fragmentStartAnchor, container, anchor);2110 hostInsert(fragmentEndAnchor, container, anchor);2111 // a fragment can only have array children2112 // since they are either generated by the compiler, or implicitly created2113 // from arrays.2114 mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG);2115 }2116 else {2117 patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, optimized);2118 }2119 }2120 function processPortal(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) {2121 const targetSelector = n2.props && n2.props.target;2122 const { patchFlag, shapeFlag, children } = n2;2123 if (n1 == null) {2124 const target = (n2.target = isString(targetSelector)2125 ? hostQuerySelector(targetSelector)2126 : null);2127 if (target != null) {2128 if (shapeFlag & 8 /* TEXT_CHILDREN */) {2129 hostSetElementText(target, children);2130 }2131 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {2132 mountChildren(children, target, null, parentComponent, parentSuspense, isSVG);2133 }2134 }2135 else {2136 warn('Invalid Portal target on mount:', target, `(${typeof target})`);2137 }2138 }2139 else {2140 // update content2141 const target = (n2.target = n1.target);2142 if (patchFlag === 1 /* TEXT */) {2143 hostSetElementText(target, children);2144 }2145 else if (!optimized) {2146 patchChildren(n1, n2, target, null, parentComponent, parentSuspense, isSVG);2147 }2148 // target changed2149 if (targetSelector !== (n1.props && n1.props.target)) {2150 const nextTarget = (n2.target = isString(targetSelector)2151 ? hostQuerySelector(targetSelector)2152 : null);2153 if (nextTarget != null) {2154 // move content2155 if (shapeFlag & 8 /* TEXT_CHILDREN */) {2156 hostSetElementText(target, '');2157 hostSetElementText(nextTarget, children);2158 }2159 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {2160 for (let i = 0; i < children.length; i++) {2161 move(children[i], nextTarget, null);2162 }2163 }2164 }2165 else {2166 warn('Invalid Portal target on update:', target, `(${typeof target})`);2167 }2168 }2169 }2170 // insert an empty node as the placeholder for the portal2171 processCommentNode(n1, n2, container, anchor);2172 }2173 function processSuspense(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) {2174 if (n1 == null) {2175 mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);2176 }2177 else {2178 patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, optimized);2179 }2180 }2181 function mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) {2182 const hiddenContainer = hostCreateElement('div');2183 const suspense = (n2.suspense = createSuspenseBoundary(n2, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, optimized));2184 const { content, fallback } = normalizeSuspenseChildren(n2);2185 suspense.subTree = content;2186 suspense.fallbackTree = fallback;2187 // start mounting the content subtree in an off-dom container2188 patch(null, content, hiddenContainer, null, parentComponent, suspense, isSVG, optimized);2189 // now check if we have encountered any async deps2190 if (suspense.deps > 0) {2191 // mount the fallback tree2192 patch(null, fallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context2193 isSVG, optimized);2194 n2.el = fallback.el;2195 }2196 else {2197 // Suspense has no async deps. Just resolve.2198 resolveSuspense(suspense);2199 }2200 }2201 function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, optimized) {2202 const suspense = (n2.suspense = n1.suspense);2203 suspense.vnode = n2;2204 const { content, fallback } = normalizeSuspenseChildren(n2);2205 const oldSubTree = suspense.subTree;2206 const oldFallbackTree = suspense.fallbackTree;2207 if (!suspense.isResolved) {2208 patch(oldSubTree, content, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, optimized);2209 if (suspense.deps > 0) {2210 // still pending. patch the fallback tree.2211 patch(oldFallbackTree, fallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context2212 isSVG, optimized);2213 n2.el = fallback.el;2214 }2215 // If deps somehow becomes 0 after the patch it means the patch caused an2216 // async dep component to unmount and removed its dep. It will cause the2217 // suspense to resolve and we don't need to do anything here.2218 }2219 else {2220 // just normal patch inner content as a fragment2221 patch(oldSubTree, content, container, anchor, parentComponent, suspense, isSVG, optimized);2222 n2.el = content.el;2223 }2224 suspense.subTree = content;2225 suspense.fallbackTree = fallback;2226 }2227 function resolveSuspense(suspense) {2228 {2229 if (suspense.isResolved) {2230 throw new Error(`resolveSuspense() is called on an already resolved suspense boundary.`);2231 }2232 if (suspense.isUnmounted) {2233 throw new Error(`resolveSuspense() is called on an already unmounted suspense boundary.`);2234 }2235 }2236 const { vnode, subTree, fallbackTree, effects, parentComponent, container } = suspense;2237 // this is initial anchor on mount2238 let { anchor } = suspense;2239 // unmount fallback tree2240 if (fallbackTree.el) {2241 // if the fallback tree was mounted, it may have been moved2242 // as part of a parent suspense. get the latest anchor for insertion2243 anchor = getNextHostNode(fallbackTree);2244 unmount(fallbackTree, parentComponent, suspense, true);2245 }2246 // move content from off-dom container to actual container2247 move(subTree, container, anchor);2248 const el = (vnode.el = subTree.el);2249 // suspense as the root node of a component...2250 if (parentComponent && parentComponent.subTree === vnode) {2251 parentComponent.vnode.el = el;2252 updateHOCHostEl(parentComponent, el);2253 }2254 // check if there is a pending parent suspense2255 let parent = suspense.parent;2256 let hasUnresolvedAncestor = false;2257 while (parent) {2258 if (!parent.isResolved) {2259 // found a pending parent suspense, merge buffered post jobs2260 // into that parent2261 parent.effects.push(...effects);2262 hasUnresolvedAncestor = true;2263 break;2264 }2265 parent = parent.parent;2266 }2267 // no pending parent suspense, flush all jobs2268 if (!hasUnresolvedAncestor) {2269 queuePostFlushCb(effects);2270 }2271 suspense.isResolved = true;2272 // invoke @resolve event2273 const onResolve = vnode.props && vnode.props.onResolve;2274 if (isFunction(onResolve)) {2275 onResolve();2276 }2277 }2278 function restartSuspense(suspense) {2279 suspense.isResolved = false;2280 const { vnode, subTree, fallbackTree, parentComponent, container, hiddenContainer, isSVG, optimized } = suspense;2281 // move content tree back to the off-dom container2282 const anchor = getNextHostNode(subTree);2283 move(subTree, hiddenContainer, null);2284 // remount the fallback tree2285 patch(null, fallbackTree, container, anchor, parentComponent, null, // fallback tree will not have suspense context2286 isSVG, optimized);2287 const el = (vnode.el = fallbackTree.el);2288 // suspense as the root node of a component...2289 if (parentComponent && parentComponent.subTree === vnode) {2290 parentComponent.vnode.el = el;2291 updateHOCHostEl(parentComponent, el);2292 }2293 // invoke @suspense event2294 const onSuspense = vnode.props && vnode.props.onSuspense;2295 if (isFunction(onSuspense)) {2296 onSuspense();2297 }2298 }2299 function processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) {2300 if (n1 == null) {2301 mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG);2302 }2303 else {2304 const instance = (n2.component = n1.component);2305 if (shouldUpdateComponent(n1, n2, optimized)) {2306 if (2307 instance.asyncDep &&2308 !instance.asyncResolved) {2309 // async & still pending - just update props and slots2310 // since the component's reactive effect for render isn't set-up yet2311 {2312 pushWarningContext(n2);2313 }2314 updateComponentPreRender(instance, n2);2315 {2316 popWarningContext();2317 }2318 return;2319 }2320 else {2321 // normal update2322 instance.next = n2;2323 // instance.update is the reactive effect runner.2324 instance.update();2325 }2326 }2327 else {2328 // no update needed. just copy over properties2329 n2.component = n1.component;2330 n2.el = n1.el;2331 }2332 }2333 if (n2.ref !== null && parentComponent !== null) {2334 setRef(n2.ref, n1 && n1.ref, parentComponent, n2.component.renderProxy);2335 }2336 }2337 function mountComponent(initialVNode, container, anchor, parentComponent, parentSuspense, isSVG) {2338 const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent));2339 {2340 pushWarningContext(initialVNode);2341 }2342 // resolve props and slots for setup context2343 const propsOptions = initialVNode.type.props;2344 resolveProps(instance, initialVNode.props, propsOptions);2345 resolveSlots(instance, initialVNode.children);2346 // setup stateful logic2347 if (initialVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {2348 setupStatefulComponent(instance, parentSuspense);2349 }2350 // setup() is async. This component relies on async logic to be resolved2351 // before proceeding2352 if ( instance.asyncDep) {2353 if (!parentSuspense) {2354 // TODO handle this properly2355 throw new Error('Async component without a suspense boundary!');2356 }2357 // parent suspense already resolved, need to re-suspense2358 // use queueJob so it's handled synchronously after patching the current2359 // suspense tree2360 if (parentSuspense.isResolved) {2361 queueJob(() => {2362 restartSuspense(parentSuspense);2363 });2364 }2365 parentSuspense.deps++;2366 instance.asyncDep2367 .catch(err => {2368 handleError(err, instance, 0 /* SETUP_FUNCTION */);2369 })2370 .then(asyncSetupResult => {2371 // component may be unmounted before resolve2372 if (!instance.isUnmounted && !parentSuspense.isUnmounted) {2373 retryAsyncComponent(instance, asyncSetupResult, parentSuspense, isSVG);2374 }2375 });2376 // give it a placeholder2377 const placeholder = (instance.subTree = createVNode(Comment));2378 processCommentNode(null, placeholder, container, anchor);2379 initialVNode.el = placeholder.el;2380 return;2381 }2382 setupRenderEffect(instance, parentSuspense, initialVNode, container, anchor, isSVG);2383 {2384 popWarningContext();2385 }2386 }2387 function retryAsyncComponent(instance, asyncSetupResult, parentSuspense, isSVG) {2388 parentSuspense.deps--;2389 // retry from this component2390 instance.asyncResolved = true;2391 const { vnode } = instance;2392 {2393 pushWarningContext(vnode);2394 }2395 handleSetupResult(instance, asyncSetupResult, parentSuspense);2396 setupRenderEffect(instance, parentSuspense, vnode,2397 // component may have been moved before resolve2398 hostParentNode(instance.subTree.el), getNextHostNode(instance.subTree), isSVG);2399 updateHOCHostEl(instance, vnode.el);2400 {2401 popWarningContext();2402 }2403 if (parentSuspense.deps === 0) {2404 resolveSuspense(parentSuspense);2405 }2406 }2407 function setupRenderEffect(instance, parentSuspense, initialVNode, container, anchor, isSVG) {2408 // create reactive effect for rendering2409 let mounted = false;2410 instance.update = effect(function componentEffect() {2411 if (!mounted) {2412 const subTree = (instance.subTree = renderComponentRoot(instance));2413 // beforeMount hook2414 if (instance.bm !== null) {2415 invokeHooks(instance.bm);2416 }2417 patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);2418 initialVNode.el = subTree.el;2419 // mounted hook2420 if (instance.m !== null) {2421 queuePostRenderEffect(instance.m, parentSuspense);2422 }2423 mounted = true;2424 }2425 else {2426 // updateComponent2427 // This is triggered by mutation of component's own state (next: null)2428 // OR parent calling processComponent (next: HostVNode)2429 const { next } = instance;2430 {2431 pushWarningContext(next || instance.vnode);2432 }2433 if (next !== null) {2434 updateComponentPreRender(instance, next);2435 }2436 const prevTree = instance.subTree;2437 const nextTree = (instance.subTree = renderComponentRoot(instance));2438 // beforeUpdate hook2439 if (instance.bu !== null) {2440 invokeHooks(instance.bu);2441 }2442 // reset refs2443 // only needed if previous patch had refs2444 if (instance.refs !== EMPTY_OBJ) {2445 instance.refs = {}; ...

Full Screen

Full Screen

runtime-core.cjs.js

Source:runtime-core.cjs.js Github

copy

Full Screen

...353 }354 return ret;355}356const stack = [];357function pushWarningContext(vnode) {358 stack.push(vnode);359}360function popWarningContext() {361 stack.pop();362}363function warn(msg, ...args) {364 // avoid props formatting or warn handler tracking deps that might be mutated365 // during patch, leading to infinite recursion.366 reactivity.pauseTracking();367 const instance = stack.length ? stack[stack.length - 1].component : null;368 const appWarnHandler = instance && instance.appContext.config.warnHandler;369 const trace = getComponentTrace();370 if (appWarnHandler) {371 callWithErrorHandling(appWarnHandler, instance, 9 /* APP_WARN_HANDLER */, [372 msg + args.join(''),373 instance && instance.renderProxy,374 trace375 .map(({ vnode }) => `at <${formatComponentName(vnode)}>`)376 .join('\n'),377 trace378 ]);379 }380 else {381 const warnArgs = [`[Vue warn]: ${msg}`, ...args];382 if (trace.length &&383 // avoid spamming console during tests384 !false) {385 warnArgs.push(`\n`, ...formatTrace(trace));386 }387 console.warn(...warnArgs);388 }389 reactivity.resumeTracking();390}391function getComponentTrace() {392 let currentVNode = stack[stack.length - 1];393 if (!currentVNode) {394 return [];395 }396 // we can't just use the stack because it will be incomplete during updates397 // that did not start from the root. Re-construct the parent chain using398 // instance parent pointers.399 const normalizedStack = [];400 while (currentVNode) {401 const last = normalizedStack[0];402 if (last && last.vnode === currentVNode) {403 last.recurseCount++;404 }405 else {406 normalizedStack.push({407 vnode: currentVNode,408 recurseCount: 0409 });410 }411 const parentInstance = currentVNode.component412 .parent;413 currentVNode = parentInstance && parentInstance.vnode;414 }415 return normalizedStack;416}417function formatTrace(trace) {418 const logs = [];419 trace.forEach((entry, i) => {420 logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));421 });422 return logs;423}424function formatTraceEntry({ vnode, recurseCount }) {425 const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;426 const open = ` at <${formatComponentName(vnode)}`;427 const close = `>` + postfix;428 const rootLabel = vnode.component.parent == null ? `(Root)` : ``;429 return vnode.props430 ? [open, ...formatProps(vnode.props), close, rootLabel]431 : [open + close, rootLabel];432}433const classifyRE = /(?:^|[-_])(\w)/g;434const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');435function formatComponentName(vnode, file) {436 const Component = vnode.type;437 let name = isFunction(Component)438 ? Component.displayName || Component.name439 : Component.name;440 if (!name && file) {441 const match = file.match(/([^/\\]+)\.vue$/);442 if (match) {443 name = match[1];444 }445 }446 return name ? classify(name) : 'Anonymous';447}448function formatProps(props) {449 const res = [];450 for (const key in props) {451 res.push(...formatProp(key, props[key]));452 }453 return res;454}455function formatProp(key, value, raw) {456 if (isString(value)) {457 value = JSON.stringify(value);458 return raw ? value : [`${key}=${value}`];459 }460 else if (typeof value === 'number' || value == null) {461 return raw ? value : [`${key}=${value}`];462 }463 else if (reactivity.isRef(value)) {464 value = formatProp(key, reactivity.toRaw(value.value), true);465 return raw ? value : [`${key}=Ref<`, value, `>`];466 }467 else {468 value = reactivity.toRaw(value);469 return raw ? value : [`${key}=`, value];470 }471}472const ErrorTypeStrings = {473 ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',474 ["c" /* CREATED */]: 'created hook',475 ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',476 ["m" /* MOUNTED */]: 'mounted hook',477 ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',478 ["u" /* UPDATED */]: 'updated',479 ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',480 ["um" /* UNMOUNTED */]: 'unmounted hook',481 ["a" /* ACTIVATED */]: 'activated hook',482 ["da" /* DEACTIVATED */]: 'deactivated hook',483 ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',484 ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',485 ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',486 [0 /* SETUP_FUNCTION */]: 'setup function',487 [1 /* RENDER_FUNCTION */]: 'render function',488 [2 /* WATCH_GETTER */]: 'watcher getter',489 [3 /* WATCH_CALLBACK */]: 'watcher callback',490 [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',491 [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',492 [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',493 [7 /* DIRECTIVE_HOOK */]: 'directive hook',494 [8 /* APP_ERROR_HANDLER */]: 'app errorHandler',495 [9 /* APP_WARN_HANDLER */]: 'app warnHandler',496 [10 /* FUNCTION_REF */]: 'ref function',497 [11 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +498 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue'499};500function callWithErrorHandling(fn, instance, type, args) {501 let res;502 try {503 res = args ? fn(...args) : fn();504 }505 catch (err) {506 handleError(err, instance, type);507 }508 return res;509}510function callWithAsyncErrorHandling(fn, instance, type, args) {511 if (isFunction(fn)) {512 const res = callWithErrorHandling(fn, instance, type, args);513 if (res != null && !res._isVue && isPromise(res)) {514 res.catch((err) => {515 handleError(err, instance, type);516 });517 }518 return res;519 }520 for (let i = 0; i < fn.length; i++) {521 callWithAsyncErrorHandling(fn[i], instance, type, args);522 }523}524function handleError(err, instance, type) {525 const contextVNode = instance ? instance.vnode : null;526 if (instance) {527 let cur = instance.parent;528 // the exposed instance is the render proxy to keep it consistent with 2.x529 const exposedInstance = instance.renderProxy;530 // in production the hook receives only the error code531 const errorInfo = ErrorTypeStrings[type] ;532 while (cur) {533 const errorCapturedHooks = cur.ec;534 if (errorCapturedHooks !== null) {535 for (let i = 0; i < errorCapturedHooks.length; i++) {536 if (errorCapturedHooks[i](err, exposedInstance, errorInfo)) {537 return;538 }539 }540 }541 cur = cur.parent;542 }543 // app-level handling544 const appErrorHandler = instance.appContext.config.errorHandler;545 if (appErrorHandler) {546 callWithErrorHandling(appErrorHandler, null, 8 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);547 return;548 }549 }550 logError(err, type, contextVNode);551}552// Test-only toggle for testing the uhandled warning behavior553let forceRecover = false;554function logError(err, type, contextVNode) {555 // default behavior is crash in prod & test, recover in dev.556 if ( (forceRecover || !false)) {557 const info = ErrorTypeStrings[type];558 if (contextVNode) {559 pushWarningContext(contextVNode);560 }561 warn(`Unhandled error${info ? ` during execution of ${info}` : ``}`);562 console.error(err);563 if (contextVNode) {564 popWarningContext();565 }566 }567 else {568 throw err;569 }570}571const queue = [];572const postFlushCbs = [];573const p = Promise.resolve();574let isFlushing = false;575let isFlushPending = false;576function nextTick(fn) {577 return fn ? p.then(fn) : p;578}579function queueJob(job) {580 if (!queue.includes(job)) {581 queue.push(job);582 queueFlush();583 }584}585function queuePostFlushCb(cb) {586 if (!isArray(cb)) {587 postFlushCbs.push(cb);588 }589 else {590 postFlushCbs.push(...cb);591 }592 queueFlush();593}594function queueFlush() {595 if (!isFlushing && !isFlushPending) {596 isFlushPending = true;597 nextTick(flushJobs);598 }599}600const dedupe = (cbs) => [...new Set(cbs)];601function flushPostFlushCbs() {602 if (postFlushCbs.length) {603 const cbs = dedupe(postFlushCbs);604 postFlushCbs.length = 0;605 for (let i = 0; i < cbs.length; i++) {606 cbs[i]();607 }608 }609}610const RECURSION_LIMIT = 100;611function flushJobs(seenJobs) {612 isFlushPending = false;613 isFlushing = true;614 let job;615 {616 seenJobs = seenJobs || new Map();617 }618 while ((job = queue.shift())) {619 {620 const seen = seenJobs;621 if (!seen.has(job)) {622 seen.set(job, 1);623 }624 else {625 const count = seen.get(job);626 if (count > RECURSION_LIMIT) {627 throw new Error('Maximum recursive updates exceeded. ' +628 "You may have code that is mutating state in your component's " +629 'render function or updated hook.');630 }631 else {632 seen.set(job, count + 1);633 }634 }635 }636 callWithErrorHandling(job, null, 11 /* SCHEDULER */);637 }638 flushPostFlushCbs();639 isFlushing = false;640 // some postFlushCb queued jobs!641 // keep flushing until it drains.642 if (queue.length || postFlushCbs.length) {643 flushJobs(seenJobs);644 }645}646// mark the current rendering instance for asset resolution (e.g.647// resolveComponent, resolveDirective) during render648let currentRenderingInstance = null;649// dev only flag to track whether $attrs was used during render.650// If $attrs was used during render then the warning for failed attrs651// fallthrough can be suppressed.652let accessedAttrs = false;653function markAttrsAccessed() {654 accessedAttrs = true;655}656function renderComponentRoot(instance) {657 const { type: Component, vnode, renderProxy, props, slots, attrs, emit } = instance;658 let result;659 currentRenderingInstance = instance;660 {661 accessedAttrs = false;662 }663 try {664 if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {665 result = normalizeVNode(instance.render.call(renderProxy));666 }667 else {668 // functional669 const render = Component;670 result = normalizeVNode(render.length > 1671 ? render(props, {672 attrs,673 slots,674 emit675 })676 : render(props, null /* we know it doesn't need it */));677 }678 // attr merging679 if (Component.props != null &&680 Component.inheritAttrs !== false &&681 attrs !== EMPTY_OBJ &&682 Object.keys(attrs).length) {683 if (result.shapeFlag & 1 /* ELEMENT */ ||684 result.shapeFlag & 6 /* COMPONENT */) {685 result = cloneVNode(result, attrs);686 }687 else if (true && !accessedAttrs) {688 warn(`Extraneous non-props attributes (${Object.keys(attrs).join(',')}) ` +689 `were passed to component but could not be automatically inhertied ` +690 `because component renders fragment or text root nodes.`);691 }692 }693 }694 catch (err) {695 handleError(err, instance, 1 /* RENDER_FUNCTION */);696 result = createVNode(Comment);697 }698 currentRenderingInstance = null;699 return result;700}701function shouldUpdateComponent(prevVNode, nextVNode, optimized) {702 const { props: prevProps, children: prevChildren } = prevVNode;703 const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;704 if (patchFlag > 0) {705 if (patchFlag & 256 /* DYNAMIC_SLOTS */) {706 // slot content that references values that might have changed,707 // e.g. in a v-for708 return true;709 }710 if (patchFlag & 16 /* FULL_PROPS */) {711 // presence of this flag indicates props are always non-null712 return hasPropsChanged(prevProps, nextProps);713 }714 else if (patchFlag & 8 /* PROPS */) {715 const dynamicProps = nextVNode.dynamicProps;716 for (let i = 0; i < dynamicProps.length; i++) {717 const key = dynamicProps[i];718 if (nextProps[key] !== prevProps[key]) {719 return true;720 }721 }722 }723 }724 else if (!optimized) {725 // this path is only taken by manually written render functions726 // so presence of any children leads to a forced update727 if (prevChildren != null || nextChildren != null) {728 return true;729 }730 if (prevProps === nextProps) {731 return false;732 }733 if (prevProps === null) {734 return nextProps !== null;735 }736 if (nextProps === null) {737 return true;738 }739 return hasPropsChanged(prevProps, nextProps);740 }741 return false;742}743function hasPropsChanged(prevProps, nextProps) {744 const nextKeys = Object.keys(nextProps);745 if (nextKeys.length !== Object.keys(prevProps).length) {746 return true;747 }748 for (let i = 0; i < nextKeys.length; i++) {749 const key = nextKeys[i];750 if (nextProps[key] !== prevProps[key]) {751 return true;752 }753 }754 return false;755}756function updateHOCHostEl({ vnode, parent }, el // HostNode757) {758 while (parent && parent.subTree === vnode) {759 (vnode = parent.vnode).el = el;760 parent = parent.parent;761 }762}763// resolve raw VNode data.764// - filter out reserved keys (key, ref, slots)765// - extract class and style into $attrs (to be merged onto child766// component root)767// - for the rest:768// - if has declared props: put declared ones in `props`, the rest in `attrs`769// - else: everything goes in `props`.770function resolveProps(instance, rawProps, _options) {771 const hasDeclaredProps = _options != null;772 const options = normalizePropsOptions(_options);773 if (!rawProps && !hasDeclaredProps) {774 return;775 }776 const props = {};777 let attrs = void 0;778 // update the instance propsProxy (passed to setup()) to trigger potential779 // changes780 const propsProxy = instance.propsProxy;781 const setProp = propsProxy782 ? (key, val) => {783 props[key] = val;784 propsProxy[key] = val;785 }786 : (key, val) => {787 props[key] = val;788 };789 // allow mutation of propsProxy (which is readonly by default)790 reactivity.unlock();791 if (rawProps != null) {792 for (const key in rawProps) {793 // key, ref are reserved794 if (isReservedProp(key))795 continue;796 // prop option names are camelized during normalization, so to support797 // kebab -> camel conversion here we need to camelize the key.798 const camelKey = camelize(key);799 if (hasDeclaredProps && !hasOwn(options, camelKey)) {800 (attrs || (attrs = {}))[key] = rawProps[key];801 }802 else {803 setProp(camelKey, rawProps[key]);804 }805 }806 }807 // set default values, cast booleans & run validators808 if (hasDeclaredProps) {809 for (const key in options) {810 let opt = options[key];811 if (opt == null)812 continue;813 const isAbsent = !hasOwn(props, key);814 const hasDefault = hasOwn(opt, 'default');815 const currentValue = props[key];816 // default values817 if (hasDefault && currentValue === undefined) {818 const defaultValue = opt.default;819 setProp(key, isFunction(defaultValue) ? defaultValue() : defaultValue);820 }821 // boolean casting822 if (opt["1" /* shouldCast */]) {823 if (isAbsent && !hasDefault) {824 setProp(key, false);825 }826 else if (opt["2" /* shouldCastTrue */] &&827 (currentValue === '' || currentValue === hyphenate(key))) {828 setProp(key, true);829 }830 }831 // runtime validation832 if ( rawProps) {833 let rawValue;834 if (!(key in rawProps) && hyphenate(key) in rawProps) {835 rawValue = rawProps[hyphenate(key)];836 }837 else {838 rawValue = rawProps[key];839 }840 validateProp(key, reactivity.toRaw(rawValue), opt, isAbsent);841 }842 }843 }844 else {845 // if component has no declared props, $attrs === $props846 attrs = props;847 }848 // in case of dynamic props, check if we need to delete keys from849 // the props proxy850 const { patchFlag } = instance.vnode;851 if (propsProxy !== null &&852 (patchFlag === 0 || patchFlag & 16 /* FULL_PROPS */)) {853 const rawInitialProps = reactivity.toRaw(propsProxy);854 for (const key in rawInitialProps) {855 if (!hasOwn(props, key)) {856 delete propsProxy[key];857 }858 }859 }860 // lock readonly861 reactivity.lock();862 instance.props = reactivity.readonly(props) ;863 instance.attrs = options864 ? attrs != null865 ? reactivity.readonly(attrs)866 : attrs || EMPTY_OBJ867 : instance.props;868}869const normalizationMap = new WeakMap();870function normalizePropsOptions(raw) {871 if (!raw) {872 return null;873 }874 if (normalizationMap.has(raw)) {875 return normalizationMap.get(raw);876 }877 const normalized = {};878 normalizationMap.set(raw, normalized);879 if (isArray(raw)) {880 for (let i = 0; i < raw.length; i++) {881 if ( !isString(raw[i])) {882 warn(`props must be strings when using array syntax.`, raw[i]);883 }884 const normalizedKey = camelize(raw[i]);885 if (normalizedKey[0] !== '$') {886 normalized[normalizedKey] = EMPTY_OBJ;887 }888 else {889 warn(`Invalid prop name: "${normalizedKey}" is a reserved property.`);890 }891 }892 }893 else {894 if ( !isObject(raw)) {895 warn(`invalid props options`, raw);896 }897 for (const key in raw) {898 const normalizedKey = camelize(key);899 if (normalizedKey[0] !== '$') {900 const opt = raw[key];901 const prop = (normalized[normalizedKey] =902 isArray(opt) || isFunction(opt) ? { type: opt } : opt);903 if (prop != null) {904 const booleanIndex = getTypeIndex(Boolean, prop.type);905 const stringIndex = getTypeIndex(String, prop.type);906 prop["1" /* shouldCast */] = booleanIndex > -1;907 prop["2" /* shouldCastTrue */] = booleanIndex < stringIndex;908 }909 }910 else {911 warn(`Invalid prop name: "${normalizedKey}" is a reserved property.`);912 }913 }914 }915 return normalized;916}917// use function string name to check type constructors918// so that it works across vms / iframes.919function getType(ctor) {920 const match = ctor && ctor.toString().match(/^\s*function (\w+)/);921 return match ? match[1] : '';922}923function isSameType(a, b) {924 return getType(a) === getType(b);925}926function getTypeIndex(type, expectedTypes) {927 if (isArray(expectedTypes)) {928 for (let i = 0, len = expectedTypes.length; i < len; i++) {929 if (isSameType(expectedTypes[i], type)) {930 return i;931 }932 }933 }934 else if (isObject(expectedTypes)) {935 return isSameType(expectedTypes, type) ? 0 : -1;936 }937 return -1;938}939function validateProp(name, value, prop, isAbsent) {940 const { type, required, validator } = prop;941 // required!942 if (required && isAbsent) {943 warn('Missing required prop: "' + name + '"');944 return;945 }946 // missing but optional947 if (value == null && !prop.required) {948 return;949 }950 // type check951 if (type != null && type !== true) {952 let isValid = false;953 const types = isArray(type) ? type : [type];954 const expectedTypes = [];955 // value is valid as long as one of the specified types match956 for (let i = 0; i < types.length && !isValid; i++) {957 const { valid, expectedType } = assertType(value, types[i]);958 expectedTypes.push(expectedType || '');959 isValid = valid;960 }961 if (!isValid) {962 warn(getInvalidTypeMessage(name, value, expectedTypes));963 return;964 }965 }966 // custom validator967 if (validator && !validator(value)) {968 warn('Invalid prop: custom validator check failed for prop "' + name + '".');969 }970}971const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol');972function assertType(value, type) {973 let valid;974 const expectedType = getType(type);975 if (isSimpleType(expectedType)) {976 const t = typeof value;977 valid = t === expectedType.toLowerCase();978 // for primitive wrapper objects979 if (!valid && t === 'object') {980 valid = value instanceof type;981 }982 }983 else if (expectedType === 'Object') {984 valid = toRawType(value) === 'Object';985 }986 else if (expectedType === 'Array') {987 valid = isArray(value);988 }989 else {990 valid = value instanceof type;991 }992 return {993 valid,994 expectedType995 };996}997function getInvalidTypeMessage(name, value, expectedTypes) {998 let message = `Invalid prop: type check failed for prop "${name}".` +999 ` Expected ${expectedTypes.map(capitalize).join(', ')}`;1000 const expectedType = expectedTypes[0];1001 const receivedType = toRawType(value);1002 const expectedValue = styleValue(value, expectedType);1003 const receivedValue = styleValue(value, receivedType);1004 // check if we need to specify expected value1005 if (expectedTypes.length === 1 &&1006 isExplicable(expectedType) &&1007 !isBoolean(expectedType, receivedType)) {1008 message += ` with value ${expectedValue}`;1009 }1010 message += `, got ${receivedType} `;1011 // check if we need to specify received value1012 if (isExplicable(receivedType)) {1013 message += `with value ${receivedValue}.`;1014 }1015 return message;1016}1017function styleValue(value, type) {1018 if (type === 'String') {1019 return `"${value}"`;1020 }1021 else if (type === 'Number') {1022 return `${Number(value)}`;1023 }1024 else {1025 return `${value}`;1026 }1027}1028function isExplicable(type) {1029 const explicitTypes = ['string', 'number', 'boolean'];1030 return explicitTypes.some(elem => type.toLowerCase() === elem);1031}1032function isBoolean(...args) {1033 return args.some(elem => elem.toLowerCase() === 'boolean');1034}1035const normalizeSlotValue = (value) => isArray(value)1036 ? value.map(normalizeVNode)1037 : [normalizeVNode(value)];1038const normalizeSlot = (key, rawSlot) => (props) => {1039 if ( currentInstance != null) {1040 warn(`Slot "${key}" invoked outside of the render function: ` +1041 `this will not track dependencies used in the slot. ` +1042 `Invoke the slot function inside the render function instead.`);1043 }1044 return normalizeSlotValue(rawSlot(props));1045};1046function resolveSlots(instance, children) {1047 let slots;1048 if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {1049 const rawSlots = children;1050 if (rawSlots._compiled) {1051 // pre-normalized slots object generated by compiler1052 slots = children;1053 }1054 else {1055 slots = {};1056 for (const key in rawSlots) {1057 const value = rawSlots[key];1058 if (isFunction(value)) {1059 slots[key] = normalizeSlot(key, value);1060 }1061 else if (value != null) {1062 {1063 warn(`Non-function value encountered for slot "${key}". ` +1064 `Prefer function slots for better performance.`);1065 }1066 const normalized = normalizeSlotValue(value);1067 slots[key] = () => normalized;1068 }1069 }1070 }1071 }1072 else if (children !== null) {1073 // non slot object children (direct value) passed to a component1074 {1075 warn(`Non-function value encountered for default slot. ` +1076 `Prefer function slots for better performance.`);1077 }1078 const normalized = normalizeSlotValue(children);1079 slots = { default: () => normalized };1080 }1081 if (slots !== void 0) {1082 instance.slots = slots;1083 }1084}1085/**1086Runtime helper for applying directives to a vnode. Example usage:1087const comp = resolveComponent('comp')1088const foo = resolveDirective('foo')1089const bar = resolveDirective('bar')1090return withDirectives(h(comp), [1091 [foo, this.x],1092 [bar, this.y]1093])1094*/1095const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text');1096function validateDirectiveName(name) {1097 if (isBuiltInDirective(name)) {1098 warn('Do not use built-in directive ids as custom directive id: ' + name);1099 }1100}1101const directiveToVnodeHooksMap = /*#__PURE__*/ [1102 'beforeMount',1103 'mounted',1104 'beforeUpdate',1105 'updated',1106 'beforeUnmount',1107 'unmounted'1108].reduce((map, key) => {1109 const vnodeKey = `onVnode` + key[0].toUpperCase() + key.slice(1);1110 const vnodeHook = (vnode, prevVnode) => {1111 const bindings = vnode.dirs;1112 const prevBindings = prevVnode ? prevVnode.dirs : EMPTY_ARR;1113 for (let i = 0; i < bindings.length; i++) {1114 const binding = bindings[i];1115 const hook = binding.dir[key];1116 if (hook != null) {1117 if (prevVnode != null) {1118 binding.oldValue = prevBindings[i].value;1119 }1120 hook(vnode.el, binding, vnode, prevVnode);1121 }1122 }1123 };1124 map[key] = [vnodeKey, vnodeHook];1125 return map;1126}, {});1127function withDirectives(vnode, directives) {1128 const internalInstance = currentRenderingInstance;1129 if (internalInstance === null) {1130 warn(`withDirectives can only be used inside render functions.`);1131 return vnode;1132 }1133 const instance = internalInstance.renderProxy;1134 const props = vnode.props || (vnode.props = {});1135 const bindings = vnode.dirs || (vnode.dirs = new Array(directives.length));1136 const injected = {};1137 for (let i = 0; i < directives.length; i++) {1138 let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];1139 if (isFunction(dir)) {1140 dir = {1141 mounted: dir,1142 updated: dir1143 };1144 }1145 bindings[i] = {1146 dir,1147 instance,1148 value,1149 oldValue: void 0,1150 arg,1151 modifiers1152 };1153 // inject onVnodeXXX hooks1154 for (const key in dir) {1155 if (!injected[key]) {1156 const { 0: hookName, 1: hook } = directiveToVnodeHooksMap[key];1157 const existing = props[hookName];1158 props[hookName] = existing ? [].concat(existing, hook) : hook;1159 injected[key] = true;1160 }1161 }1162 }1163 return vnode;1164}1165function invokeDirectiveHook(hook, instance, vnode, prevVNode = null) {1166 callWithAsyncErrorHandling(hook, instance, 7 /* DIRECTIVE_HOOK */, [1167 vnode,1168 prevVNode1169 ]);1170}1171function createAppContext() {1172 return {1173 config: {1174 devtools: true,1175 performance: false,1176 isNativeTag: NO,1177 isCustomElement: NO,1178 errorHandler: undefined,1179 warnHandler: undefined1180 },1181 mixins: [],1182 components: {},1183 directives: {},1184 provides: {}1185 };1186}1187function createAppAPI(render) {1188 return function createApp() {1189 const context = createAppContext();1190 let isMounted = false;1191 const app = {1192 get config() {1193 return context.config;1194 },1195 set config(v) {1196 {1197 warn(`app.config cannot be replaced. Modify individual options instead.`);1198 }1199 },1200 use(plugin) {1201 if (isFunction(plugin)) {1202 plugin(app);1203 }1204 else if (isFunction(plugin.install)) {1205 plugin.install(app);1206 }1207 else {1208 warn(`A plugin must either be a function or an object with an "install" ` +1209 `function.`);1210 }1211 return app;1212 },1213 mixin(mixin) {1214 if (!context.mixins.includes(mixin)) {1215 context.mixins.push(mixin);1216 }1217 else {1218 warn('Mixin has already been applied to target app' +1219 (mixin.name ? `: ${mixin.name}` : ''));1220 }1221 return app;1222 },1223 component(name, component) {1224 {1225 validateComponentName(name, context.config);1226 }1227 if (!component) {1228 return context.components[name];1229 }1230 else {1231 if ( context.components[name]) {1232 warn(`Component "${name}" has already been registered in target app.`);1233 }1234 context.components[name] = component;1235 return app;1236 }1237 },1238 directive(name, directive) {1239 {1240 validateDirectiveName(name);1241 }1242 if (!directive) {1243 return context.directives[name];1244 }1245 else {1246 if ( context.directives[name]) {1247 warn(`Directive "${name}" has already been registered in target app.`);1248 }1249 context.directives[name] = directive;1250 return app;1251 }1252 },1253 mount(rootComponent, rootContainer, rootProps) {1254 if (!isMounted) {1255 const vnode = createVNode(rootComponent, rootProps);1256 // store app context on the root VNode.1257 // this will be set on the root instance on initial mount.1258 vnode.appContext = context;1259 render(vnode, rootContainer);1260 isMounted = true;1261 return vnode.component.renderProxy;1262 }1263 else {1264 warn(`App has already been mounted. Create a new app instance instead.`);1265 }1266 },1267 provide(key, value) {1268 if ( key in context.provides) {1269 warn(`App already provides property with key "${key}". ` +1270 `It will be overwritten with the new value.`);1271 }1272 // TypeScript doesn't allow symbols as index type1273 // https://github.com/Microsoft/TypeScript/issues/245871274 context.provides[key] = value;1275 return app;1276 }1277 };1278 return app;1279 };1280}1281// Suspense exposes a component-like API, and is treated like a component1282// in the compiler, but internally it's a special built-in type that hooks1283// directly into the renderer.1284const SuspenseImpl = {1285 // In order to make Suspense tree-shakable, we need to avoid importing it1286 // directly in the renderer. The renderer checks for the __isSuspense flag1287 // on a vnode's type and calls the `process` method, passing in renderer1288 // internals.1289 __isSuspense: true,1290 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, 1291 // platform-specific impl passed from renderer1292 rendererInternals) {1293 if (n1 == null) {1294 mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, rendererInternals);1295 }1296 else {1297 patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, optimized, rendererInternals);1298 }1299 }1300};1301// Force-casted public typing for h and TSX props inference1302const Suspense = ( SuspenseImpl1303 );1304function mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, rendererInternals) {1305 const { patch, options: { createElement } } = rendererInternals;1306 const hiddenContainer = createElement('div');1307 const suspense = (n2.suspense = createSuspenseBoundary(n2, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, optimized, rendererInternals));1308 const { content, fallback } = normalizeSuspenseChildren(n2);1309 suspense.subTree = content;1310 suspense.fallbackTree = fallback;1311 // start mounting the content subtree in an off-dom container1312 patch(null, content, hiddenContainer, null, parentComponent, suspense, isSVG, optimized);1313 // now check if we have encountered any async deps1314 if (suspense.deps > 0) {1315 // mount the fallback tree1316 patch(null, fallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context1317 isSVG, optimized);1318 n2.el = fallback.el;1319 }1320 else {1321 // Suspense has no async deps. Just resolve.1322 suspense.resolve();1323 }1324}1325function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, optimized, { patch }) {1326 const suspense = (n2.suspense = n1.suspense);1327 suspense.vnode = n2;1328 const { content, fallback } = normalizeSuspenseChildren(n2);1329 const oldSubTree = suspense.subTree;1330 const oldFallbackTree = suspense.fallbackTree;1331 if (!suspense.isResolved) {1332 patch(oldSubTree, content, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, optimized);1333 if (suspense.deps > 0) {1334 // still pending. patch the fallback tree.1335 patch(oldFallbackTree, fallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context1336 isSVG, optimized);1337 n2.el = fallback.el;1338 }1339 // If deps somehow becomes 0 after the patch it means the patch caused an1340 // async dep component to unmount and removed its dep. It will cause the1341 // suspense to resolve and we don't need to do anything here.1342 }1343 else {1344 // just normal patch inner content as a fragment1345 patch(oldSubTree, content, container, anchor, parentComponent, suspense, isSVG, optimized);1346 n2.el = content.el;1347 }1348 suspense.subTree = content;1349 suspense.fallbackTree = fallback;1350}1351function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, optimized, rendererInternals) {1352 const { patch, move, unmount, next, options: { parentNode } } = rendererInternals;1353 const suspense = {1354 vnode,1355 parent,1356 parentComponent,1357 isSVG,1358 optimized,1359 container,1360 hiddenContainer,1361 anchor,1362 deps: 0,1363 subTree: null,1364 fallbackTree: null,1365 isResolved: false,1366 isUnmounted: false,1367 effects: [],1368 resolve() {1369 {1370 if (suspense.isResolved) {1371 throw new Error(`resolveSuspense() is called on an already resolved suspense boundary.`);1372 }1373 if (suspense.isUnmounted) {1374 throw new Error(`resolveSuspense() is called on an already unmounted suspense boundary.`);1375 }1376 }1377 const { vnode, subTree, fallbackTree, effects, parentComponent, container } = suspense;1378 // this is initial anchor on mount1379 let { anchor } = suspense;1380 // unmount fallback tree1381 if (fallbackTree.el) {1382 // if the fallback tree was mounted, it may have been moved1383 // as part of a parent suspense. get the latest anchor for insertion1384 anchor = next(fallbackTree);1385 unmount(fallbackTree, parentComponent, suspense, true);1386 }1387 // move content from off-dom container to actual container1388 move(subTree, container, anchor);1389 const el = (vnode.el = subTree.el);1390 // suspense as the root node of a component...1391 if (parentComponent && parentComponent.subTree === vnode) {1392 parentComponent.vnode.el = el;1393 updateHOCHostEl(parentComponent, el);1394 }1395 // check if there is a pending parent suspense1396 let parent = suspense.parent;1397 let hasUnresolvedAncestor = false;1398 while (parent) {1399 if (!parent.isResolved) {1400 // found a pending parent suspense, merge buffered post jobs1401 // into that parent1402 parent.effects.push(...effects);1403 hasUnresolvedAncestor = true;1404 break;1405 }1406 parent = parent.parent;1407 }1408 // no pending parent suspense, flush all jobs1409 if (!hasUnresolvedAncestor) {1410 queuePostFlushCb(effects);1411 }1412 suspense.isResolved = true;1413 // invoke @resolve event1414 const onResolve = vnode.props && vnode.props.onResolve;1415 if (isFunction(onResolve)) {1416 onResolve();1417 }1418 },1419 recede() {1420 suspense.isResolved = false;1421 const { vnode, subTree, fallbackTree, parentComponent, container, hiddenContainer, isSVG, optimized } = suspense;1422 // move content tree back to the off-dom container1423 const anchor = next(subTree);1424 move(subTree, hiddenContainer, null);1425 // remount the fallback tree1426 patch(null, fallbackTree, container, anchor, parentComponent, null, // fallback tree will not have suspense context1427 isSVG, optimized);1428 const el = (vnode.el = fallbackTree.el);1429 // suspense as the root node of a component...1430 if (parentComponent && parentComponent.subTree === vnode) {1431 parentComponent.vnode.el = el;1432 updateHOCHostEl(parentComponent, el);1433 }1434 // invoke @recede event1435 const onRecede = vnode.props && vnode.props.onRecede;1436 if (isFunction(onRecede)) {1437 onRecede();1438 }1439 },1440 move(container, anchor) {1441 move(suspense.isResolved ? suspense.subTree : suspense.fallbackTree, container, anchor);1442 suspense.container = container;1443 },1444 next() {1445 return next(suspense.isResolved ? suspense.subTree : suspense.fallbackTree);1446 },1447 registerDep(instance, setupRenderEffect) {1448 // suspense is already resolved, need to recede.1449 // use queueJob so it's handled synchronously after patching the current1450 // suspense tree1451 if (suspense.isResolved) {1452 queueJob(() => {1453 suspense.recede();1454 });1455 }1456 suspense.deps++;1457 instance1458 .asyncDep.catch(err => {1459 handleError(err, instance, 0 /* SETUP_FUNCTION */);1460 })1461 .then(asyncSetupResult => {1462 // retry when the setup() promise resolves.1463 // component may have been unmounted before resolve.1464 if (instance.isUnmounted || suspense.isUnmounted) {1465 return;1466 }1467 suspense.deps--;1468 // retry from this component1469 instance.asyncResolved = true;1470 const { vnode } = instance;1471 {1472 pushWarningContext(vnode);1473 }1474 handleSetupResult(instance, asyncSetupResult, suspense);1475 setupRenderEffect(instance, parentComponent, suspense, vnode, 1476 // component may have been moved before resolve1477 parentNode(instance.subTree.el), next(instance.subTree), isSVG);1478 updateHOCHostEl(instance, vnode.el);1479 {1480 popWarningContext();1481 }1482 if (suspense.deps === 0) {1483 suspense.resolve();1484 }1485 });1486 },1487 unmount(parentSuspense, doRemove) {1488 suspense.isUnmounted = true;1489 unmount(suspense.subTree, parentComponent, parentSuspense, doRemove);1490 if (!suspense.isResolved) {1491 unmount(suspense.fallbackTree, parentComponent, parentSuspense, doRemove);1492 }1493 }1494 };1495 return suspense;1496}1497function normalizeSuspenseChildren(vnode) {1498 const { shapeFlag, children } = vnode;1499 if (shapeFlag & 32 /* SLOTS_CHILDREN */) {1500 const { default: d, fallback } = children;1501 return {1502 content: normalizeVNode(isFunction(d) ? d() : d),1503 fallback: normalizeVNode(isFunction(fallback) ? fallback() : fallback)1504 };1505 }1506 else {1507 return {1508 content: normalizeVNode(children),1509 fallback: normalizeVNode(null)1510 };1511 }1512}1513function queueEffectWithSuspense(fn, suspense) {1514 if (suspense !== null && !suspense.isResolved) {1515 if (isArray(fn)) {1516 suspense.effects.push(...fn);1517 }1518 else {1519 suspense.effects.push(fn);1520 }1521 }1522 else {1523 queuePostFlushCb(fn);1524 }1525}1526function createDevEffectOptions(instance) {1527 return {1528 scheduler: queueJob,1529 onTrack: instance.rtc ? e => invokeHooks(instance.rtc, e) : void 0,1530 onTrigger: instance.rtg ? e => invokeHooks(instance.rtg, e) : void 01531 };1532}1533function isSameType$1(n1, n2) {1534 return n1.type === n2.type && n1.key === n2.key;1535}1536function invokeHooks(hooks, arg) {1537 for (let i = 0; i < hooks.length; i++) {1538 hooks[i](arg);1539 }1540}1541const queuePostRenderEffect = queueEffectWithSuspense1542 ;1543/**1544 * The createRenderer function accepts two generic arguments:1545 * HostNode and HostElement, corresponding to Node and Element types in the1546 * host environment. For example, for runtime-dom, HostNode would be the DOM1547 * `Node` interface and HostElement would be the DOM `Element` interface.1548 *1549 * Custom renderers can pass in the platform specific types like this:1550 *1551 * ``` js1552 * const { render, createApp } = createRenderer<Node, Element>({1553 * patchProp,1554 * ...nodeOps1555 * })1556 * ```1557 */1558function createRenderer(options) {1559 const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, querySelector: hostQuerySelector } = options;1560 const internals = {1561 patch,1562 unmount,1563 move,1564 next: getNextHostNode,1565 options1566 };1567 function patch(n1, // null means this is a mount1568 n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, optimized = false) {1569 // patching & not same type, unmount old tree1570 if (n1 != null && !isSameType$1(n1, n2)) {1571 anchor = getNextHostNode(n1);1572 unmount(n1, parentComponent, parentSuspense, true);1573 n1 = null;1574 }1575 const { type, shapeFlag } = n2;1576 switch (type) {1577 case Text:1578 processText(n1, n2, container, anchor);1579 break;1580 case Comment:1581 processCommentNode(n1, n2, container, anchor);1582 break;1583 case Fragment:1584 processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);1585 break;1586 case Portal:1587 processPortal(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);1588 break;1589 default:1590 if (shapeFlag & 1 /* ELEMENT */) {1591 processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);1592 }1593 else if (shapeFlag & 6 /* COMPONENT */) {1594 processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);1595 }1596 else if ( shapeFlag & 64 /* SUSPENSE */) {1597 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, internals);1598 }1599 else {1600 warn('Invalid HostVNode type:', n2.type, `(${typeof n2.type})`);1601 }1602 }1603 }1604 function processText(n1, n2, container, anchor) {1605 if (n1 == null) {1606 hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);1607 }1608 else {1609 const el = (n2.el = n1.el);1610 if (n2.children !== n1.children) {1611 hostSetText(el, n2.children);1612 }1613 }1614 }1615 function processCommentNode(n1, n2, container, anchor) {1616 if (n1 == null) {1617 hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);1618 }1619 else {1620 // there's no support for dynamic comments1621 n2.el = n1.el;1622 }1623 }1624 function processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) {1625 if (n1 == null) {1626 mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);1627 }1628 else {1629 patchElement(n1, n2, parentComponent, parentSuspense, isSVG, optimized);1630 }1631 if (n2.ref !== null && parentComponent !== null) {1632 setRef(n2.ref, n1 && n1.ref, parentComponent, n2.el);1633 }1634 }1635 function mountElement(vnode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) {1636 const tag = vnode.type;1637 isSVG = isSVG || tag === 'svg';1638 const el = (vnode.el = hostCreateElement(tag, isSVG));1639 const { props, shapeFlag } = vnode;1640 if (props != null) {1641 for (const key in props) {1642 if (isReservedProp(key))1643 continue;1644 hostPatchProp(el, key, props[key], null, isSVG);1645 }1646 if (props.onVnodeBeforeMount != null) {1647 invokeDirectiveHook(props.onVnodeBeforeMount, parentComponent, vnode);1648 }1649 }1650 if (shapeFlag & 8 /* TEXT_CHILDREN */) {1651 hostSetElementText(el, vnode.children);1652 }1653 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {1654 mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG, optimized || vnode.dynamicChildren !== null);1655 }1656 hostInsert(el, container, anchor);1657 if (props != null && props.onVnodeMounted != null) {1658 queuePostRenderEffect(() => {1659 invokeDirectiveHook(props.onVnodeMounted, parentComponent, vnode);1660 }, parentSuspense);1661 }1662 }1663 function mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, optimized, start = 0) {1664 for (let i = start; i < children.length; i++) {1665 const child = optimized1666 ? children[i]1667 : (children[i] = normalizeVNode(children[i]));1668 patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, optimized);1669 }1670 }1671 function patchElement(n1, n2, parentComponent, parentSuspense, isSVG, optimized) {1672 const el = (n2.el = n1.el);1673 const { patchFlag, dynamicChildren } = n2;1674 const oldProps = (n1 && n1.props) || EMPTY_OBJ;1675 const newProps = n2.props || EMPTY_OBJ;1676 if (newProps.onVnodeBeforeUpdate != null) {1677 invokeDirectiveHook(newProps.onVnodeBeforeUpdate, parentComponent, n2, n1);1678 }1679 if (patchFlag > 0) {1680 // the presence of a patchFlag means this element's render code was1681 // generated by the compiler and can take the fast path.1682 // in this path old node and new node are guaranteed to have the same shape1683 // (i.e. at the exact same position in the source template)1684 if (patchFlag & 16 /* FULL_PROPS */) {1685 // element props contain dynamic keys, full diff needed1686 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);1687 }1688 else {1689 // class1690 // this flag is matched when the element has dynamic class bindings.1691 if (patchFlag & 2 /* CLASS */) {1692 if (oldProps.class !== newProps.class) {1693 hostPatchProp(el, 'class', newProps.class, null, isSVG);1694 }1695 }1696 // style1697 // this flag is matched when the element has dynamic style bindings1698 if (patchFlag & 4 /* STYLE */) {1699 hostPatchProp(el, 'style', newProps.style, oldProps.style, isSVG);1700 }1701 // props1702 // This flag is matched when the element has dynamic prop/attr bindings1703 // other than class and style. The keys of dynamic prop/attrs are saved for1704 // faster iteration.1705 // Note dynamic keys like :[foo]="bar" will cause this optimization to1706 // bail out and go through a full diff because we need to unset the old key1707 if (patchFlag & 8 /* PROPS */) {1708 // if the flag is present then dynamicProps must be non-null1709 const propsToUpdate = n2.dynamicProps;1710 for (let i = 0; i < propsToUpdate.length; i++) {1711 const key = propsToUpdate[i];1712 const prev = oldProps[key];1713 const next = newProps[key];1714 if (prev !== next) {1715 hostPatchProp(el, key, next, prev, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);1716 }1717 }1718 }1719 }1720 // text1721 // This flag is matched when the element has only dynamic text children.1722 // this flag is terminal (i.e. skips children diffing).1723 if (patchFlag & 1 /* TEXT */) {1724 if (n1.children !== n2.children) {1725 hostSetElementText(el, n2.children);1726 }1727 return; // terminal1728 }1729 }1730 else if (!optimized && dynamicChildren == null) {1731 // unoptimized, full diff1732 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);1733 }1734 if (dynamicChildren != null) {1735 patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, isSVG);1736 }1737 else if (!optimized) {1738 // full diff1739 patchChildren(n1, n2, el, null, parentComponent, parentSuspense, isSVG);1740 }1741 if (newProps.onVnodeUpdated != null) {1742 queuePostRenderEffect(() => {1743 invokeDirectiveHook(newProps.onVnodeUpdated, parentComponent, n2, n1);1744 }, parentSuspense);1745 }1746 }1747 // The fast path for blocks.1748 function patchBlockChildren(oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG) {1749 for (let i = 0; i < newChildren.length; i++) {1750 const oldVNode = oldChildren[i];1751 patch(oldVNode, newChildren[i], 1752 // in the case of a Fragment, we need to provide the actual parent1753 // of the Fragment itself so it can move its children. In other cases,1754 // the parent container is not actually used so we just pass the1755 // block element here to avoid a DOM parentNode call.1756 oldVNode.type === Fragment1757 ? hostParentNode(oldVNode.el)1758 : fallbackContainer, null, parentComponent, parentSuspense, isSVG, true);1759 }1760 }1761 function patchProps(el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) {1762 if (oldProps !== newProps) {1763 for (const key in newProps) {1764 if (isReservedProp(key))1765 continue;1766 const next = newProps[key];1767 const prev = oldProps[key];1768 if (next !== prev) {1769 hostPatchProp(el, key, next, prev, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);1770 }1771 }1772 if (oldProps !== EMPTY_OBJ) {1773 for (const key in oldProps) {1774 if (isReservedProp(key))1775 continue;1776 if (!(key in newProps)) {1777 hostPatchProp(el, key, null, null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);1778 }1779 }1780 }1781 }1782 }1783 let devFragmentID = 0;1784 function processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) {1785 const fragmentStartAnchor = (n2.el = n11786 ? n1.el1787 : hostCreateComment( `fragment-${devFragmentID}-start` ));1788 const fragmentEndAnchor = (n2.anchor = n11789 ? n1.anchor1790 : hostCreateComment( `fragment-${devFragmentID}-end` ));1791 {1792 devFragmentID++;1793 }1794 if (n1 == null) {1795 hostInsert(fragmentStartAnchor, container, anchor);1796 hostInsert(fragmentEndAnchor, container, anchor);1797 // a fragment can only have array children1798 // since they are either generated by the compiler, or implicitly created1799 // from arrays.1800 mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, optimized);1801 }1802 else {1803 patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, optimized);1804 }1805 }1806 function processPortal(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) {1807 const targetSelector = n2.props && n2.props.target;1808 const { patchFlag, shapeFlag, children } = n2;1809 if (n1 == null) {1810 const target = (n2.target = isString(targetSelector)1811 ? hostQuerySelector(targetSelector)1812 : targetSelector);1813 if (target != null) {1814 if (shapeFlag & 8 /* TEXT_CHILDREN */) {1815 hostSetElementText(target, children);1816 }1817 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {1818 mountChildren(children, target, null, parentComponent, parentSuspense, isSVG, optimized);1819 }1820 }1821 else {1822 warn('Invalid Portal target on mount:', target, `(${typeof target})`);1823 }1824 }1825 else {1826 // update content1827 const target = (n2.target = n1.target);1828 if (patchFlag === 1 /* TEXT */) {1829 hostSetElementText(target, children);1830 }1831 else if (n2.dynamicChildren) {1832 // fast path when the portal happens to be a block root1833 patchBlockChildren(n1.dynamicChildren, n2.dynamicChildren, container, parentComponent, parentSuspense, isSVG);1834 }1835 else if (!optimized) {1836 patchChildren(n1, n2, target, null, parentComponent, parentSuspense, isSVG);1837 }1838 // target changed1839 if (targetSelector !== (n1.props && n1.props.target)) {1840 const nextTarget = (n2.target = isString(targetSelector)1841 ? hostQuerySelector(targetSelector)1842 : targetSelector);1843 if (nextTarget != null) {1844 // move content1845 if (shapeFlag & 8 /* TEXT_CHILDREN */) {1846 hostSetElementText(target, '');1847 hostSetElementText(nextTarget, children);1848 }1849 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {1850 for (let i = 0; i < children.length; i++) {1851 move(children[i], nextTarget, null);1852 }1853 }1854 }1855 else {1856 warn('Invalid Portal target on update:', target, `(${typeof target})`);1857 }1858 }1859 }1860 // insert an empty node as the placeholder for the portal1861 processCommentNode(n1, n2, container, anchor);1862 }1863 function processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) {1864 if (n1 == null) {1865 if (n2.shapeFlag & 256 /* COMPONENT_KEPT_ALIVE */) {1866 parentComponent.sink.activate(n2, container, anchor);1867 }1868 else {1869 mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG);1870 }1871 }1872 else {1873 const instance = (n2.component = n1.component);1874 if (shouldUpdateComponent(n1, n2, optimized)) {1875 if (1876 instance.asyncDep &&1877 !instance.asyncResolved) {1878 // async & still pending - just update props and slots1879 // since the component's reactive effect for render isn't set-up yet1880 {1881 pushWarningContext(n2);1882 }1883 updateComponentPreRender(instance, n2);1884 {1885 popWarningContext();1886 }1887 return;1888 }1889 else {1890 // normal update1891 instance.next = n2;1892 // instance.update is the reactive effect runner.1893 instance.update();1894 }1895 }1896 else {1897 // no update needed. just copy over properties1898 n2.component = n1.component;1899 n2.el = n1.el;1900 }1901 }1902 if (n2.ref !== null && parentComponent !== null) {1903 if ( !(n2.shapeFlag & 4 /* STATEFUL_COMPONENT */)) {1904 pushWarningContext(n2);1905 warn(`Functional components do not support "ref" because they do not ` +1906 `have instances.`);1907 popWarningContext();1908 }1909 setRef(n2.ref, n1 && n1.ref, parentComponent, n2.component.renderProxy);1910 }1911 }1912 function mountComponent(initialVNode, container, anchor, parentComponent, parentSuspense, isSVG) {1913 const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent));1914 {1915 pushWarningContext(initialVNode);1916 }1917 const Comp = initialVNode.type;1918 // inject renderer internals for keepAlive1919 if (Comp.__isKeepAlive) {1920 const sink = instance.sink;1921 sink.renderer = internals;1922 sink.parentSuspense = parentSuspense;1923 }1924 // resolve props and slots for setup context1925 const propsOptions = Comp.props;1926 resolveProps(instance, initialVNode.props, propsOptions);1927 resolveSlots(instance, initialVNode.children);1928 // setup stateful logic1929 if (initialVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {1930 setupStatefulComponent(instance, parentSuspense);1931 }1932 // setup() is async. This component relies on async logic to be resolved1933 // before proceeding1934 if ( instance.asyncDep) {1935 if (!parentSuspense) {1936 warn('async setup() is used without a suspense boundary!');1937 return;1938 }1939 parentSuspense.registerDep(instance, setupRenderEffect);1940 // give it a placeholder1941 const placeholder = (instance.subTree = createVNode(Comment));1942 processCommentNode(null, placeholder, container, anchor);1943 initialVNode.el = placeholder.el;1944 return;1945 }1946 setupRenderEffect(instance, parentComponent, parentSuspense, initialVNode, container, anchor, isSVG);1947 {1948 popWarningContext();1949 }1950 }1951 function setupRenderEffect(instance, parentComponent, parentSuspense, initialVNode, container, anchor, isSVG) {1952 // create reactive effect for rendering1953 let mounted = false;1954 instance.update = reactivity.effect(function componentEffect() {1955 if (!mounted) {1956 const subTree = (instance.subTree = renderComponentRoot(instance));1957 // beforeMount hook1958 if (instance.bm !== null) {1959 invokeHooks(instance.bm);1960 }1961 patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);1962 initialVNode.el = subTree.el;1963 // mounted hook1964 if (instance.m !== null) {1965 queuePostRenderEffect(instance.m, parentSuspense);1966 }1967 // activated hook for keep-alive roots.1968 if (instance.a !== null &&1969 instance.vnode.shapeFlag & 128 /* COMPONENT_SHOULD_KEEP_ALIVE */) {1970 queuePostRenderEffect(instance.a, parentSuspense);1971 }1972 mounted = true;1973 }1974 else {1975 // updateComponent1976 // This is triggered by mutation of component's own state (next: null)1977 // OR parent calling processComponent (next: HostVNode)1978 const { next } = instance;1979 {1980 pushWarningContext(next || instance.vnode);1981 }1982 if (next !== null) {1983 updateComponentPreRender(instance, next);1984 }1985 const prevTree = instance.subTree;1986 const nextTree = (instance.subTree = renderComponentRoot(instance));1987 // beforeUpdate hook1988 if (instance.bu !== null) {1989 invokeHooks(instance.bu);1990 }1991 // reset refs1992 // only needed if previous patch had refs1993 if (instance.refs !== EMPTY_OBJ) {1994 instance.refs = {};...

Full Screen

Full Screen

runtime-core.esm-bundler.js

Source:runtime-core.esm-bundler.js Github

copy

Full Screen

...57function createComponent(options) {58 return isFunction(options) ? { setup: options } : options;59}60let stack = [];61function pushWarningContext(vnode) {62 stack.push(vnode);63}64function popWarningContext() {65 stack.pop();66}67function warn(msg, ...args) {68 const instance = stack.length ? stack[stack.length - 1].component : null;69 const appWarnHandler = instance && instance.appContext.config.warnHandler;70 const trace = getComponentTrace();71 if (appWarnHandler) {72 appWarnHandler(msg + args.join(''), instance && instance.renderProxy, formatTrace(trace).join(''));73 return;74 }75 console.warn(`[Vue warn]: ${msg}`, ...args);76 // avoid spamming console during tests77 if (typeof process !== 'undefined' && process.env.NODE_ENV === 'test') {78 return;79 }80 if (!trace.length) {81 return;82 }83 if (trace.length > 1 && console.groupCollapsed) {84 console.groupCollapsed('at', ...formatTraceEntry(trace[0]));85 const logs = [];86 trace.slice(1).forEach((entry, i) => {87 if (i !== 0)88 logs.push('\n');89 logs.push(...formatTraceEntry(entry, i + 1));90 });91 console.log(...logs);92 console.groupEnd();93 }94 else {95 console.log(...formatTrace(trace));96 }97}98function getComponentTrace() {99 let currentVNode = stack[stack.length - 1];100 if (!currentVNode) {101 return [];102 }103 // we can't just use the stack because it will be incomplete during updates104 // that did not start from the root. Re-construct the parent chain using105 // instance parent pointers.106 const normalizedStack = [];107 while (currentVNode) {108 const last = normalizedStack[0];109 if (last && last.vnode === currentVNode) {110 last.recurseCount++;111 }112 else {113 normalizedStack.push({114 vnode: currentVNode,115 recurseCount: 0116 });117 }118 const parentInstance = currentVNode.component119 .parent;120 currentVNode = parentInstance && parentInstance.vnode;121 }122 return normalizedStack;123}124function formatTrace(trace) {125 const logs = [];126 trace.forEach((entry, i) => {127 const formatted = formatTraceEntry(entry, i);128 if (i === 0) {129 logs.push('at', ...formatted);130 }131 else {132 logs.push('\n', ...formatted);133 }134 });135 return logs;136}137function formatTraceEntry({ vnode, recurseCount }, depth = 0) {138 const padding = depth === 0 ? '' : ' '.repeat(depth * 2 + 1);139 const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;140 const open = padding + `<${formatComponentName(vnode)}`;141 const close = `>` + postfix;142 const rootLabel = vnode.component.parent == null ? `(Root)` : ``;143 return vnode.props144 ? [open, ...formatProps(vnode.props), close, rootLabel]145 : [open + close, rootLabel];146}147const classifyRE = /(?:^|[-_])(\w)/g;148const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');149function formatComponentName(vnode, file) {150 const Component = vnode.type;151 let name = Component.displayName || Component.name;152 if (!name && file) {153 const match = file.match(/([^/\\]+)\.vue$/);154 if (match) {155 name = match[1];156 }157 }158 return name ? classify(name) : 'AnonymousComponent';159}160function formatProps(props) {161 const res = [];162 for (const key in props) {163 const value = props[key];164 if (isString(value)) {165 res.push(`${key}=${JSON.stringify(value)}`);166 }167 else {168 res.push(`${key}=`, toRaw(value));169 }170 }171 return res;172}173const ErrorTypeStrings = {174 ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',175 ["c" /* CREATED */]: 'created hook',176 ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',177 ["m" /* MOUNTED */]: 'mounted hook',178 ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',179 ["u" /* UPDATED */]: 'updated',180 ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',181 ["um" /* UNMOUNTED */]: 'unmounted hook',182 ["a" /* ACTIVATED */]: 'activated hook',183 ["da" /* DEACTIVATED */]: 'deactivated hook',184 ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',185 ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',186 ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',187 [0 /* SETUP_FUNCTION */]: 'setup function',188 [1 /* RENDER_FUNCTION */]: 'render function',189 [2 /* WATCH_GETTER */]: 'watcher getter',190 [3 /* WATCH_CALLBACK */]: 'watcher callback',191 [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',192 [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',193 [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',194 [7 /* DIRECTIVE_HOOK */]: 'directive hook',195 [8 /* APP_ERROR_HANDLER */]: 'app errorHandler',196 [9 /* APP_WARN_HANDLER */]: 'app warnHandler',197 [10 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +198 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue'199};200function callWithErrorHandling(fn, instance, type, args) {201 let res;202 try {203 res = args ? fn(...args) : fn();204 }205 catch (err) {206 handleError(err, instance, type);207 }208 return res;209}210function callWithAsyncErrorHandling(fn, instance, type, args) {211 const res = callWithErrorHandling(fn, instance, type, args);212 if (res != null && !res._isVue && typeof res.then === 'function') {213 res.catch((err) => {214 handleError(err, instance, type);215 });216 }217 return res;218}219function handleError(err, instance, type) {220 const contextVNode = instance ? instance.vnode : null;221 if (instance) {222 let cur = instance.parent;223 // the exposed instance is the render proxy to keep it consistent with 2.x224 const exposedInstance = instance.renderProxy;225 // in production the hook receives only the error code226 const errorInfo = ErrorTypeStrings[type] ;227 while (cur) {228 const errorCapturedHooks = cur.ec;229 if (errorCapturedHooks !== null) {230 for (let i = 0; i < errorCapturedHooks.length; i++) {231 if (errorCapturedHooks[i](err, exposedInstance, errorInfo)) {232 return;233 }234 }235 }236 cur = cur.parent;237 }238 // app-level handling239 const appErrorHandler = instance.appContext.config.errorHandler;240 if (appErrorHandler) {241 callWithErrorHandling(appErrorHandler, null, 8 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);242 return;243 }244 }245 logError(err, type, contextVNode);246}247function logError(err, type, contextVNode) {248 // default behavior is crash in prod & test, recover in dev.249 // TODO we should probably make this configurable via `createApp`250 if (251 !(typeof process !== 'undefined' && process.env.NODE_ENV === 'test')) {252 const info = ErrorTypeStrings[type];253 if (contextVNode) {254 pushWarningContext(contextVNode);255 }256 warn(`Unhandled error${info ? ` during execution of ${info}` : ``}`);257 console.error(err);258 if (contextVNode) {259 popWarningContext();260 }261 }262 else {263 throw err;264 }265}266const queue = [];267const postFlushCbs = [];268const p = Promise.resolve();269let isFlushing = false;270function nextTick(fn) {271 return fn ? p.then(fn) : p;272}273function queueJob(job) {274 if (queue.indexOf(job) === -1) {275 queue.push(job);276 if (!isFlushing) {277 nextTick(flushJobs);278 }279 }280}281function queuePostFlushCb(cb) {282 if (Array.isArray(cb)) {283 postFlushCbs.push.apply(postFlushCbs, cb);284 }285 else {286 postFlushCbs.push(cb);287 }288 if (!isFlushing) {289 nextTick(flushJobs);290 }291}292const dedupe = (cbs) => Array.from(new Set(cbs));293function flushPostFlushCbs() {294 if (postFlushCbs.length) {295 const cbs = dedupe(postFlushCbs);296 postFlushCbs.length = 0;297 for (let i = 0; i < cbs.length; i++) {298 cbs[i]();299 }300 }301}302const RECURSION_LIMIT = 100;303function flushJobs(seenJobs) {304 isFlushing = true;305 let job;306 {307 seenJobs = seenJobs || new Map();308 }309 while ((job = queue.shift())) {310 {311 const seen = seenJobs;312 if (!seen.has(job)) {313 seen.set(job, 1);314 }315 else {316 const count = seen.get(job);317 if (count > RECURSION_LIMIT) {318 throw new Error('Maximum recursive updates exceeded. ' +319 "You may have code that is mutating state in your component's " +320 'render function or updated hook.');321 }322 else {323 seen.set(job, count + 1);324 }325 }326 }327 try {328 job();329 }330 catch (err) {331 handleError(err, null, 10 /* SCHEDULER */);332 }333 }334 flushPostFlushCbs();335 isFlushing = false;336 // some postFlushCb queued jobs!337 // keep flushing until it drains.338 if (queue.length) {339 flushJobs(seenJobs);340 }341}342const Fragment = Symbol('Fragment') ;343const Text = Symbol('Text') ;344const Comment = Symbol('Empty') ;345const Portal = Symbol('Portal') ;346const Suspense = Symbol('Suspense') ;347// Since v-if and v-for are the two possible ways node structure can dynamically348// change, once we consider v-if branches and each v-for fragment a block, we349// can divide a template into nested blocks, and within each block the node350// structure would be stable. This allows us to skip most children diffing351// and only worry about the dynamic nodes (indicated by patch flags).352const blockStack = [];353// Open a block.354// This must be called before `createBlock`. It cannot be part of `createBlock`355// because the children of the block are evaluated before `createBlock` itself356// is called. The generated code typically looks like this:357//358// function render() {359// return (openBlock(),createBlock('div', null, [...]))360// }361//362// disableTracking is true when creating a fragment block, since a fragment363// always diffs its children.364function openBlock(disableTracking) {365 blockStack.push(disableTracking ? null : []);366}367let shouldTrack = true;368// Create a block root vnode. Takes the same exact arguments as `createVNode`.369// A block root keeps track of dynamic nodes within the block in the370// `dynamicChildren` array.371function createBlock(type, props, children, patchFlag, dynamicProps) {372 // avoid a block with optFlag tracking itself373 shouldTrack = false;374 const vnode = createVNode(type, props, children, patchFlag, dynamicProps);375 shouldTrack = true;376 const trackedNodes = blockStack.pop();377 vnode.dynamicChildren =378 trackedNodes && trackedNodes.length ? trackedNodes : EMPTY_ARR;379 // a block is always going to be patched380 trackDynamicNode(vnode);381 return vnode;382}383function isVNode(value) {384 return value ? value._isVNode === true : false;385}386function createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null) {387 // class & style normalization.388 if (props !== null) {389 // for reactive or proxy objects, we need to clone it to enable mutation.390 if (isReactive(props) || SetupProxySymbol in props) {391 props = extend({}, props);392 }393 // class normalization only needed if the vnode isn't generated by394 // compiler-optimized code395 if (props.class != null && !(patchFlag & 2 /* CLASS */)) {396 props.class = normalizeClass(props.class);397 }398 let { style } = props;399 if (style != null) {400 // reactive state objects need to be cloned since they are likely to be401 // mutated402 if (isReactive(style) && !isArray(style)) {403 style = extend({}, style);404 }405 props.style = normalizeStyle(style);406 }407 }408 // encode the vnode type information into a bitmap409 const shapeFlag = isString(type)410 ? 1 /* ELEMENT */411 : isObject(type)412 ? 4 /* STATEFUL_COMPONENT */413 : isFunction(type)414 ? 2 /* FUNCTIONAL_COMPONENT */415 : 0;416 const vnode = {417 _isVNode: true,418 type,419 props,420 key: (props && props.key) || null,421 ref: (props && props.ref) || null,422 children: null,423 component: null,424 suspense: null,425 el: null,426 anchor: null,427 target: null,428 shapeFlag,429 patchFlag,430 dynamicProps,431 dynamicChildren: null,432 appContext: null433 };434 normalizeChildren(vnode, children);435 // presence of a patch flag indicates this node needs patching on updates.436 // component nodes also should always be patched, because even if the437 // component doesn't need to update, it needs to persist the instance on to438 // the next vnode so that it can be properly unmounted later.439 if (shouldTrack &&440 (patchFlag ||441 shapeFlag & 4 /* STATEFUL_COMPONENT */ ||442 shapeFlag & 2 /* FUNCTIONAL_COMPONENT */)) {443 trackDynamicNode(vnode);444 }445 return vnode;446}447function trackDynamicNode(vnode) {448 const currentBlockDynamicNodes = blockStack[blockStack.length - 1];449 if (currentBlockDynamicNodes != null) {450 currentBlockDynamicNodes.push(vnode);451 }452}453function cloneVNode(vnode) {454 return {455 _isVNode: true,456 type: vnode.type,457 props: vnode.props,458 key: vnode.key,459 ref: vnode.ref,460 children: vnode.children,461 target: vnode.target,462 shapeFlag: vnode.shapeFlag,463 patchFlag: vnode.patchFlag,464 dynamicProps: vnode.dynamicProps,465 dynamicChildren: vnode.dynamicChildren,466 appContext: vnode.appContext,467 // these should be set to null since they should only be present on468 // mounted VNodes. If they are somehow not null, this means we have469 // encountered an already-mounted vnode being used again.470 component: null,471 suspense: null,472 el: null,473 anchor: null474 };475}476function normalizeVNode(child) {477 if (child == null) {478 // empty placeholder479 return createVNode(Comment);480 }481 else if (isArray(child)) {482 // fragment483 return createVNode(Fragment, null, child);484 }485 else if (typeof child === 'object') {486 // already vnode, this should be the most common since compiled templates487 // always produce all-vnode children arrays488 return child.el === null ? child : cloneVNode(child);489 }490 else {491 // primitive types492 return createVNode(Text, null, child + '');493 }494}495function normalizeChildren(vnode, children) {496 let type = 0;497 if (children == null) {498 children = null;499 }500 else if (isArray(children)) {501 type = 16 /* ARRAY_CHILDREN */;502 }503 else if (typeof children === 'object') {504 type = 32 /* SLOTS_CHILDREN */;505 }506 else if (isFunction(children)) {507 children = { default: children };508 type = 32 /* SLOTS_CHILDREN */;509 }510 else {511 children = isString(children) ? children : children + '';512 type = 8 /* TEXT_CHILDREN */;513 }514 vnode.children = children;515 vnode.shapeFlag |= type;516}517function normalizeStyle(value) {518 if (isArray(value)) {519 const res = {};520 for (let i = 0; i < value.length; i++) {521 const normalized = normalizeStyle(value[i]);522 if (normalized) {523 for (const key in normalized) {524 res[key] = normalized[key];525 }526 }527 }528 return res;529 }530 else if (isObject(value)) {531 return value;532 }533}534function normalizeClass(value) {535 let res = '';536 if (isString(value)) {537 res = value;538 }539 else if (isArray(value)) {540 for (let i = 0; i < value.length; i++) {541 res += normalizeClass(value[i]) + ' ';542 }543 }544 else if (isObject(value)) {545 for (const name in value) {546 if (value[name]) {547 res += name + ' ';548 }549 }550 }551 return res.trim();552}553const handlersRE = /^on|^vnode/;554function mergeProps(...args) {555 const ret = {};556 extend(ret, args[0]);557 for (let i = 1; i < args.length; i++) {558 const toMerge = args[i];559 for (const key in toMerge) {560 if (key === 'class') {561 ret.class = normalizeClass([ret.class, toMerge.class]);562 }563 else if (key === 'style') {564 ret.style = normalizeStyle([ret.style, toMerge.style]);565 }566 else if (handlersRE.test(key)) {567 // on*, vnode*568 const existing = ret[key];569 ret[key] = existing570 ? [].concat(existing, toMerge[key])571 : toMerge[key];572 }573 else {574 ret[key] = toMerge[key];575 }576 }577 }578 return ret;579}580function injectHook(type, hook, target) {581 if (target) {582 (target[type] || (target[type] = [])).push((...args) => {583 if (target.isUnmounted) {584 return;585 }586 // disable tracking inside all lifecycle hooks587 // since they can potentially be called inside effects.588 pauseTracking();589 // Set currentInstance during hook invocation.590 // This assumes the hook does not synchronously trigger other hooks, which591 // can only be false when the user does something really funky.592 setCurrentInstance(target);593 const res = callWithAsyncErrorHandling(hook, target, type, args);594 setCurrentInstance(null);595 resumeTracking();596 return res;597 });598 }599 else {600 const apiName = `on${capitalize(ErrorTypeStrings[type].replace(/ hook$/, ''))}`;601 warn(`${apiName} is called when there is no active component instance to be ` +602 `associated with. ` +603 `Lifecycle injection APIs can only be used during execution of setup().` +604 ( ` If you are using async setup(), make sure to register lifecycle ` +605 `hooks before the first await statement.`606 ));607 }608}609function onBeforeMount(hook, target = currentInstance) {610 injectHook("bm" /* BEFORE_MOUNT */, hook, target);611}612function onMounted(hook, target = currentInstance) {613 injectHook("m" /* MOUNTED */, hook, target);614}615function onBeforeUpdate(hook, target = currentInstance) {616 injectHook("bu" /* BEFORE_UPDATE */, hook, target);617}618function onUpdated(hook, target = currentInstance) {619 injectHook("u" /* UPDATED */, hook, target);620}621function onBeforeUnmount(hook, target = currentInstance) {622 injectHook("bum" /* BEFORE_UNMOUNT */, hook, target);623}624function onUnmounted(hook, target = currentInstance) {625 injectHook("um" /* UNMOUNTED */, hook, target);626}627function onRenderTriggered(hook, target = currentInstance) {628 injectHook("rtg" /* RENDER_TRIGGERED */, hook, target);629}630function onRenderTracked(hook, target = currentInstance) {631 injectHook("rtc" /* RENDER_TRACKED */, hook, target);632}633function onErrorCaptured(hook, target = currentInstance) {634 injectHook("ec" /* ERROR_CAPTURED */, hook, target);635}636// mark the current rendering instance for asset resolution (e.g.637// resolveComponent, resolveDirective) during render638let currentRenderingInstance = null;639function renderComponentRoot(instance) {640 const { type: Component, vnode, renderProxy, props, slots, attrs, emit } = instance;641 let result;642 currentRenderingInstance = instance;643 try {644 if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {645 result = normalizeVNode(instance.render.call(renderProxy));646 }647 else {648 // functional649 const render = Component;650 result = normalizeVNode(render.length > 1651 ? render(props, {652 attrs,653 slots,654 emit655 })656 : render(props, null));657 }658 }659 catch (err) {660 handleError(err, instance, 1 /* RENDER_FUNCTION */);661 result = createVNode(Comment);662 }663 currentRenderingInstance = null;664 return result;665}666function shouldUpdateComponent(prevVNode, nextVNode, optimized) {667 const { props: prevProps, children: prevChildren } = prevVNode;668 const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;669 if (patchFlag > 0) {670 if (patchFlag & 256 /* DYNAMIC_SLOTS */) {671 // slot content that references values that might have changed,672 // e.g. in a v-for673 return true;674 }675 if (patchFlag & 16 /* FULL_PROPS */) {676 // presence of this flag indicates props are always non-null677 return hasPropsChanged(prevProps, nextProps);678 }679 else if (patchFlag & 8 /* PROPS */) {680 const dynamicProps = nextVNode.dynamicProps;681 for (let i = 0; i < dynamicProps.length; i++) {682 const key = dynamicProps[i];683 if (nextProps[key] !== prevProps[key]) {684 return true;685 }686 }687 }688 }689 else if (!optimized) {690 // this path is only taken by manually written render functions691 // so presence of any children leads to a forced update692 if (prevChildren != null || nextChildren != null) {693 return true;694 }695 if (prevProps === nextProps) {696 return false;697 }698 if (prevProps === null) {699 return nextProps !== null;700 }701 if (nextProps === null) {702 return prevProps !== null;703 }704 return hasPropsChanged(prevProps, nextProps);705 }706 return false;707}708function hasPropsChanged(prevProps, nextProps) {709 const nextKeys = Object.keys(nextProps);710 if (nextKeys.length !== Object.keys(prevProps).length) {711 return true;712 }713 for (let i = 0; i < nextKeys.length; i++) {714 const key = nextKeys[i];715 if (nextProps[key] !== prevProps[key]) {716 return true;717 }718 }719 return false;720}721// resolve raw VNode data.722// - filter out reserved keys (key, ref, slots)723// - extract class and style into $attrs (to be merged onto child724// component root)725// - for the rest:726// - if has declared props: put declared ones in `props`, the rest in `attrs`727// - else: everything goes in `props`.728function resolveProps(instance, rawProps, _options) {729 const hasDeclaredProps = _options != null;730 const options = normalizePropsOptions(_options);731 if (!rawProps && !hasDeclaredProps) {732 return;733 }734 const props = {};735 let attrs = void 0;736 // update the instance propsProxy (passed to setup()) to trigger potential737 // changes738 const propsProxy = instance.propsProxy;739 const setProp = propsProxy740 ? (key, val) => {741 props[key] = val;742 propsProxy[key] = val;743 }744 : (key, val) => {745 props[key] = val;746 };747 // allow mutation of propsProxy (which is readonly by default)748 unlock();749 if (rawProps != null) {750 for (const key in rawProps) {751 // key, ref are reserved752 if (isReservedProp(key))753 continue;754 // any non-declared data are put into a separate `attrs` object755 // for spreading756 if (hasDeclaredProps && !hasOwn(options, key)) {757 (attrs || (attrs = {}))[key] = rawProps[key];758 }759 else {760 setProp(key, rawProps[key]);761 }762 }763 }764 // set default values, cast booleans & run validators765 if (hasDeclaredProps) {766 for (const key in options) {767 let opt = options[key];768 if (opt == null)769 continue;770 const isAbsent = !hasOwn(props, key);771 const hasDefault = hasOwn(opt, 'default');772 const currentValue = props[key];773 // default values774 if (hasDefault && currentValue === undefined) {775 const defaultValue = opt.default;776 setProp(key, isFunction(defaultValue) ? defaultValue() : defaultValue);777 }778 // boolean casting779 if (opt["1" /* shouldCast */]) {780 if (isAbsent && !hasDefault) {781 setProp(key, false);782 }783 else if (opt["2" /* shouldCastTrue */] &&784 (currentValue === '' || currentValue === hyphenate(key))) {785 setProp(key, true);786 }787 }788 // runtime validation789 if ( rawProps) {790 validateProp(key, toRaw(rawProps[key]), opt, isAbsent);791 }792 }793 }794 else {795 // if component has no declared props, $attrs === $props796 attrs = props;797 }798 // in case of dynamic props, check if we need to delete keys from799 // the props proxy800 const { patchFlag } = instance.vnode;801 if (propsProxy !== null &&802 (patchFlag === 0 || patchFlag & 16 /* FULL_PROPS */)) {803 const rawInitialProps = toRaw(propsProxy);804 for (const key in rawInitialProps) {805 if (!hasOwn(props, key)) {806 delete propsProxy[key];807 }808 }809 }810 // lock readonly811 lock();812 instance.props = readonly(props) ;813 instance.attrs = options814 ? attrs != null815 ? readonly(attrs)816 : attrs817 : instance.props;818}819const normalizationMap = new WeakMap();820function normalizePropsOptions(raw) {821 if (!raw) {822 return null;823 }824 if (normalizationMap.has(raw)) {825 return normalizationMap.get(raw);826 }827 const normalized = {};828 normalizationMap.set(raw, normalized);829 if (isArray(raw)) {830 for (let i = 0; i < raw.length; i++) {831 if ( !isString(raw[i])) {832 warn(`props must be strings when using array syntax.`, raw[i]);833 }834 const normalizedKey = camelize(raw[i]);835 if (normalizedKey[0] !== '$') {836 normalized[normalizedKey] = EMPTY_OBJ;837 }838 else {839 warn(`Invalid prop name: "${normalizedKey}" is a reserved property.`);840 }841 }842 }843 else {844 if ( !isObject(raw)) {845 warn(`invalid props options`, raw);846 }847 for (const key in raw) {848 const normalizedKey = camelize(key);849 if (normalizedKey[0] !== '$') {850 const opt = raw[key];851 const prop = (normalized[normalizedKey] =852 isArray(opt) || isFunction(opt) ? { type: opt } : opt);853 if (prop != null) {854 const booleanIndex = getTypeIndex(Boolean, prop.type);855 const stringIndex = getTypeIndex(String, prop.type);856 prop["1" /* shouldCast */] = booleanIndex > -1;857 prop["2" /* shouldCastTrue */] = booleanIndex < stringIndex;858 }859 }860 else {861 warn(`Invalid prop name: "${normalizedKey}" is a reserved property.`);862 }863 }864 }865 return normalized;866}867// use function string name to check type constructors868// so that it works across vms / iframes.869function getType(ctor) {870 const match = ctor && ctor.toString().match(/^\s*function (\w+)/);871 return match ? match[1] : '';872}873function isSameType(a, b) {874 return getType(a) === getType(b);875}876function getTypeIndex(type, expectedTypes) {877 if (isArray(expectedTypes)) {878 for (let i = 0, len = expectedTypes.length; i < len; i++) {879 if (isSameType(expectedTypes[i], type)) {880 return i;881 }882 }883 }884 else if (isObject(expectedTypes)) {885 return isSameType(expectedTypes, type) ? 0 : -1;886 }887 return -1;888}889function validateProp(name, value, prop, isAbsent) {890 const { type, required, validator } = prop;891 // required!892 if (required && isAbsent) {893 warn('Missing required prop: "' + name + '"');894 return;895 }896 // missing but optional897 if (value == null && !prop.required) {898 return;899 }900 // type check901 if (type != null && type !== true) {902 let isValid = false;903 const types = isArray(type) ? type : [type];904 const expectedTypes = [];905 // value is valid as long as one of the specified types match906 for (let i = 0; i < types.length && !isValid; i++) {907 const { valid, expectedType } = assertType(value, types[i]);908 expectedTypes.push(expectedType || '');909 isValid = valid;910 }911 if (!isValid) {912 warn(getInvalidTypeMessage(name, value, expectedTypes));913 return;914 }915 }916 // custom validator917 if (validator && !validator(value)) {918 warn('Invalid prop: custom validator check failed for prop "' + name + '".');919 }920}921const simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/;922function assertType(value, type) {923 let valid;924 const expectedType = getType(type);925 if (simpleCheckRE.test(expectedType)) {926 const t = typeof value;927 valid = t === expectedType.toLowerCase();928 // for primitive wrapper objects929 if (!valid && t === 'object') {930 valid = value instanceof type;931 }932 }933 else if (expectedType === 'Object') {934 valid = toRawType(value) === 'Object';935 }936 else if (expectedType === 'Array') {937 valid = isArray(value);938 }939 else {940 valid = value instanceof type;941 }942 return {943 valid,944 expectedType945 };946}947function getInvalidTypeMessage(name, value, expectedTypes) {948 let message = `Invalid prop: type check failed for prop "${name}".` +949 ` Expected ${expectedTypes.map(capitalize).join(', ')}`;950 const expectedType = expectedTypes[0];951 const receivedType = toRawType(value);952 const expectedValue = styleValue(value, expectedType);953 const receivedValue = styleValue(value, receivedType);954 // check if we need to specify expected value955 if (expectedTypes.length === 1 &&956 isExplicable(expectedType) &&957 !isBoolean(expectedType, receivedType)) {958 message += ` with value ${expectedValue}`;959 }960 message += `, got ${receivedType} `;961 // check if we need to specify received value962 if (isExplicable(receivedType)) {963 message += `with value ${receivedValue}.`;964 }965 return message;966}967function styleValue(value, type) {968 if (type === 'String') {969 return `"${value}"`;970 }971 else if (type === 'Number') {972 return `${Number(value)}`;973 }974 else {975 return `${value}`;976 }977}978function toRawType(value) {979 return toTypeString(value).slice(8, -1);980}981function isExplicable(type) {982 const explicitTypes = ['string', 'number', 'boolean'];983 return explicitTypes.some(elem => type.toLowerCase() === elem);984}985function isBoolean(...args) {986 return args.some(elem => elem.toLowerCase() === 'boolean');987}988const normalizeSlotValue = (value) => isArray(value)989 ? value.map(normalizeVNode)990 : [normalizeVNode(value)];991const normalizeSlot = (key, rawSlot) => (props) => {992 if ( currentInstance != null) {993 warn(`Slot "${key}" invoked outside of the render function: ` +994 `this will not track dependencies used in the slot. ` +995 `Invoke the slot function inside the render function instead.`);996 }997 return normalizeSlotValue(rawSlot(props));998};999function resolveSlots(instance, children) {1000 let slots;1001 if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {1002 if (children._compiled) {1003 // pre-normalized slots object generated by compiler1004 slots = children;1005 }1006 else {1007 slots = {};1008 for (const key in children) {1009 let value = children[key];1010 if (isFunction(value)) {1011 slots[key] = normalizeSlot(key, value);1012 }1013 else if (value != null) {1014 {1015 warn(`Non-function value encountered for slot "${key}". ` +1016 `Prefer function slots for better performance.`);1017 }1018 value = normalizeSlotValue(value);1019 slots[key] = () => value;1020 }1021 }1022 }1023 }1024 else if (children !== null) {1025 // non slot object children (direct value) passed to a component1026 {1027 warn(`Non-function value encountered for default slot. ` +1028 `Prefer function slots for better performance.`);1029 }1030 const normalized = normalizeSlotValue(children);1031 slots = { default: () => normalized };1032 }1033 if (slots !== void 0) {1034 instance.slots = slots;1035 }1036}1037/**1038Runtime helper for applying directives to a vnode. Example usage:1039const comp = resolveComponent('comp')1040const foo = resolveDirective('foo')1041const bar = resolveDirective('bar')1042return applyDirectives(h(comp), [1043 [foo, this.x],1044 [bar, this.y]1045])1046*/1047const valueCache = new WeakMap();1048function applyDirective(props, instance, directive, value, arg, modifiers) {1049 let valueCacheForDir = valueCache.get(directive);1050 if (!valueCacheForDir) {1051 valueCacheForDir = new WeakMap();1052 valueCache.set(directive, valueCacheForDir);1053 }1054 for (const key in directive) {1055 const hook = directive[key];1056 const hookKey = `vnode` + key[0].toUpperCase() + key.slice(1);1057 const vnodeHook = (vnode, prevVNode) => {1058 let oldValue;1059 if (prevVNode != null) {1060 oldValue = valueCacheForDir.get(prevVNode);1061 valueCacheForDir.delete(prevVNode);1062 }1063 valueCacheForDir.set(vnode, value);1064 hook(vnode.el, {1065 instance: instance.renderProxy,1066 value,1067 oldValue,1068 arg,1069 modifiers1070 }, vnode, prevVNode);1071 };1072 const existing = props[hookKey];1073 props[hookKey] = existing1074 ? [].concat(existing, vnodeHook)1075 : vnodeHook;1076 }1077}1078function applyDirectives(vnode, directives) {1079 const instance = currentRenderingInstance;1080 if (instance !== null) {1081 vnode = cloneVNode(vnode);1082 vnode.props = vnode.props != null ? extend({}, vnode.props) : {};1083 for (let i = 0; i < directives.length; i++) {1084 applyDirective(vnode.props, instance, ...directives[i]);1085 }1086 }1087 else {1088 warn(`applyDirectives can only be used inside render functions.`);1089 }1090 return vnode;1091}1092function invokeDirectiveHook(hook, instance, vnode, prevVNode = null) {1093 const args = [vnode, prevVNode];1094 if (isArray(hook)) {1095 for (let i = 0; i < hook.length; i++) {1096 callWithAsyncErrorHandling(hook[i], instance, 7 /* DIRECTIVE_HOOK */, args);1097 }1098 }1099 else if (isFunction(hook)) {1100 callWithAsyncErrorHandling(hook, instance, 7 /* DIRECTIVE_HOOK */, args);1101 }1102}1103function createAppContext() {1104 return {1105 config: {1106 devtools: true,1107 performance: false,1108 errorHandler: undefined,1109 warnHandler: undefined1110 },1111 mixins: [],1112 components: {},1113 directives: {},1114 provides: {}1115 };1116}1117function createAppAPI(render) {1118 return function createApp() {1119 const context = createAppContext();1120 let isMounted = false;1121 const app = {1122 get config() {1123 return context.config;1124 },1125 set config(v) {1126 {1127 warn(`app.config cannot be replaced. Modify individual options instead.`);1128 }1129 },1130 use(plugin) {1131 if (isFunction(plugin)) {1132 plugin(app);1133 }1134 else if (isFunction(plugin.install)) {1135 plugin.install(app);1136 }1137 else {1138 warn(`A plugin must either be a function or an object with an "install" ` +1139 `function.`);1140 }1141 return app;1142 },1143 mixin(mixin) {1144 context.mixins.push(mixin);1145 return app;1146 },1147 component(name, component) {1148 // TODO component name validation1149 if (!component) {1150 return context.components[name];1151 }1152 else {1153 context.components[name] = component;1154 return app;1155 }1156 },1157 directive(name, directive) {1158 // TODO directive name validation1159 if (!directive) {1160 return context.directives[name];1161 }1162 else {1163 context.directives[name] = directive;1164 return app;1165 }1166 },1167 mount(rootComponent, rootContainer, rootProps) {1168 if (!isMounted) {1169 const vnode = createVNode(rootComponent, rootProps);1170 // store app context on the root VNode.1171 // this will be set on the root instance on initial mount.1172 vnode.appContext = context;1173 render(vnode, rootContainer);1174 isMounted = true;1175 return vnode.component.renderProxy;1176 }1177 else {1178 warn(`App has already been mounted. Create a new app instance instead.`);1179 }1180 },1181 provide(key, value) {1182 if ( key in context.provides) {1183 warn(`App already provides property with key "${key}". ` +1184 `It will be overwritten with the new value.`);1185 }1186 context.provides[key] = value;1187 }1188 };1189 return app;1190 };1191}1192function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, optimized) {1193 return {1194 vnode,1195 parent,1196 parentComponent,1197 isSVG,1198 optimized,1199 container,1200 hiddenContainer,1201 anchor,1202 deps: 0,1203 subTree: null,1204 fallbackTree: null,1205 isResolved: false,1206 isUnmounted: false,1207 effects: []1208 };1209}1210function normalizeSuspenseChildren(vnode) {1211 const { shapeFlag, children } = vnode;1212 if (shapeFlag & PublicShapeFlags.SLOTS_CHILDREN) {1213 const { default: d, fallback } = children;1214 return {1215 content: normalizeVNode(isFunction(d) ? d() : d),1216 fallback: normalizeVNode(isFunction(fallback) ? fallback() : fallback)1217 };1218 }1219 else {1220 return {1221 content: normalizeVNode(children),1222 fallback: normalizeVNode(null)1223 };1224 }1225}1226function createDevEffectOptions(instance) {1227 return {1228 scheduler: queueJob,1229 onTrack: instance.rtc ? e => invokeHooks(instance.rtc, e) : void 0,1230 onTrigger: instance.rtg ? e => invokeHooks(instance.rtg, e) : void 01231 };1232}1233function isSameType$1(n1, n2) {1234 return n1.type === n2.type && n1.key === n2.key;1235}1236function invokeHooks(hooks, arg) {1237 for (let i = 0; i < hooks.length; i++) {1238 hooks[i](arg);1239 }1240}1241function queuePostRenderEffect(fn, suspense) {1242 if (suspense !== null && !suspense.isResolved) {1243 if (isArray(fn)) {1244 suspense.effects.push(...fn);1245 }1246 else {1247 suspense.effects.push(fn);1248 }1249 }1250 else {1251 queuePostFlushCb(fn);1252 }1253}1254/**1255 * The createRenderer function accepts two generic arguments:1256 * HostNode and HostElement, corresponding to Node and Element types in the1257 * host environment. For example, for runtime-dom, HostNode would be the DOM1258 * `Node` interface and HostElement would be the DOM `Element` interface.1259 *1260 * Custom renderers can pass in the platform specific types like this:1261 *1262 * ``` js1263 * const { render, createApp } = createRenderer<Node, Element>({1264 * patchProp,1265 * ...nodeOps1266 * })1267 * ```1268 */1269function createRenderer(options) {1270 const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, querySelector: hostQuerySelector } = options;1271 function patch(n1, // null means this is a mount1272 n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, optimized = false) {1273 // patching & not same type, unmount old tree1274 if (n1 != null && !isSameType$1(n1, n2)) {1275 anchor = getNextHostNode(n1);1276 unmount(n1, parentComponent, parentSuspense, true);1277 n1 = null;1278 }1279 const { type, shapeFlag } = n2;1280 switch (type) {1281 case Text:1282 processText(n1, n2, container, anchor);1283 break;1284 case Comment:1285 processCommentNode(n1, n2, container, anchor);1286 break;1287 case Fragment:1288 processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);1289 break;1290 case Portal:1291 processPortal(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);1292 break;1293 case Suspense:1294 {1295 processSuspense(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);1296 }1297 break;1298 default:1299 if (shapeFlag & 1 /* ELEMENT */) {1300 processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);1301 }1302 else if (shapeFlag & 6 /* COMPONENT */) {1303 processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);1304 }1305 else {1306 warn('Invalid HostVNode type:', n2.type, `(${typeof n2.type})`);1307 }1308 }1309 }1310 function processText(n1, n2, container, anchor) {1311 if (n1 == null) {1312 hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);1313 }1314 else {1315 const el = (n2.el = n1.el);1316 if (n2.children !== n1.children) {1317 hostSetText(el, n2.children);1318 }1319 }1320 }1321 function processCommentNode(n1, n2, container, anchor) {1322 if (n1 == null) {1323 hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);1324 }1325 else {1326 // there's no support for dynamic comments1327 n2.el = n1.el;1328 }1329 }1330 function processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) {1331 if (n1 == null) {1332 mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG);1333 }1334 else {1335 patchElement(n1, n2, parentComponent, parentSuspense, isSVG, optimized);1336 }1337 if (n2.ref !== null && parentComponent !== null) {1338 setRef(n2.ref, n1 && n1.ref, parentComponent, n2.el);1339 }1340 }1341 function mountElement(vnode, container, anchor, parentComponent, parentSuspense, isSVG) {1342 const tag = vnode.type;1343 isSVG = isSVG || tag === 'svg';1344 const el = (vnode.el = hostCreateElement(tag, isSVG));1345 const { props, shapeFlag } = vnode;1346 if (props != null) {1347 for (const key in props) {1348 if (isReservedProp(key))1349 continue;1350 hostPatchProp(el, key, props[key], null, isSVG);1351 }1352 if (props.vnodeBeforeMount != null) {1353 invokeDirectiveHook(props.vnodeBeforeMount, parentComponent, vnode);1354 }1355 }1356 if (shapeFlag & 8 /* TEXT_CHILDREN */) {1357 hostSetElementText(el, vnode.children);1358 }1359 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {1360 mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG);1361 }1362 hostInsert(el, container, anchor);1363 if (props != null && props.vnodeMounted != null) {1364 queuePostRenderEffect(() => {1365 invokeDirectiveHook(props.vnodeMounted, parentComponent, vnode);1366 }, parentSuspense);1367 }1368 }1369 function mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, start = 0) {1370 for (let i = start; i < children.length; i++) {1371 const child = (children[i] = normalizeVNode(children[i]));1372 patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG);1373 }1374 }1375 function patchElement(n1, n2, parentComponent, parentSuspense, isSVG, optimized) {1376 const el = (n2.el = n1.el);1377 const { patchFlag, dynamicChildren } = n2;1378 const oldProps = (n1 && n1.props) || EMPTY_OBJ;1379 const newProps = n2.props || EMPTY_OBJ;1380 if (newProps.vnodeBeforeUpdate != null) {1381 invokeDirectiveHook(newProps.vnodeBeforeUpdate, parentComponent, n2, n1);1382 }1383 if (patchFlag > 0) {1384 // the presence of a patchFlag means this element's render code was1385 // generated by the compiler and can take the fast path.1386 // in this path old node and new node are guaranteed to have the same shape1387 // (i.e. at the exact same position in the source template)1388 if (patchFlag & 16 /* FULL_PROPS */) {1389 // element props contain dynamic keys, full diff needed1390 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);1391 }1392 else {1393 // class1394 // this flag is matched when the element has dynamic class bindings.1395 if (patchFlag & 2 /* CLASS */) {1396 if (oldProps.class !== newProps.class) {1397 hostPatchProp(el, 'class', newProps.class, null, isSVG);1398 }1399 }1400 // style1401 // this flag is matched when the element has dynamic style bindings1402 if (patchFlag & 4 /* STYLE */) {1403 hostPatchProp(el, 'style', newProps.style, oldProps.style, isSVG);1404 }1405 // props1406 // This flag is matched when the element has dynamic prop/attr bindings1407 // other than class and style. The keys of dynamic prop/attrs are saved for1408 // faster iteration.1409 // Note dynamic keys like :[foo]="bar" will cause this optimization to1410 // bail out and go through a full diff because we need to unset the old key1411 if (patchFlag & 8 /* PROPS */) {1412 // if the flag is present then dynamicProps must be non-null1413 const propsToUpdate = n2.dynamicProps;1414 for (let i = 0; i < propsToUpdate.length; i++) {1415 const key = propsToUpdate[i];1416 const prev = oldProps[key];1417 const next = newProps[key];1418 if (prev !== next) {1419 hostPatchProp(el, key, next, prev, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);1420 }1421 }1422 }1423 }1424 // text1425 // This flag is matched when the element has only dynamic text children.1426 // this flag is terminal (i.e. skips children diffing).1427 if (patchFlag & 1 /* TEXT */) {1428 if (n1.children !== n2.children) {1429 hostSetElementText(el, n2.children);1430 }1431 return; // terminal1432 }1433 }1434 else if (!optimized) {1435 // unoptimized, full diff1436 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);1437 }1438 if (dynamicChildren != null) {1439 // children fast path1440 const oldDynamicChildren = n1.dynamicChildren;1441 for (let i = 0; i < dynamicChildren.length; i++) {1442 patch(oldDynamicChildren[i], dynamicChildren[i], el, null, parentComponent, parentSuspense, isSVG, true);1443 }1444 }1445 else if (!optimized) {1446 // full diff1447 patchChildren(n1, n2, el, null, parentComponent, parentSuspense, isSVG);1448 }1449 if (newProps.vnodeUpdated != null) {1450 queuePostRenderEffect(() => {1451 invokeDirectiveHook(newProps.vnodeUpdated, parentComponent, n2, n1);1452 }, parentSuspense);1453 }1454 }1455 function patchProps(el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) {1456 if (oldProps !== newProps) {1457 for (const key in newProps) {1458 if (isReservedProp(key))1459 continue;1460 const next = newProps[key];1461 const prev = oldProps[key];1462 if (next !== prev) {1463 hostPatchProp(el, key, next, prev, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);1464 }1465 }1466 if (oldProps !== EMPTY_OBJ) {1467 for (const key in oldProps) {1468 if (isReservedProp(key))1469 continue;1470 if (!(key in newProps)) {1471 hostPatchProp(el, key, null, null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);1472 }1473 }1474 }1475 }1476 }1477 function processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) {1478 const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateComment(''));1479 const fragmentEndAnchor = (n2.anchor = n11480 ? n1.anchor1481 : hostCreateComment(''));1482 if (n1 == null) {1483 hostInsert(fragmentStartAnchor, container, anchor);1484 hostInsert(fragmentEndAnchor, container, anchor);1485 // a fragment can only have array children1486 // since they are either generated by the compiler, or implicitly created1487 // from arrays.1488 mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG);1489 }1490 else {1491 patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, optimized);1492 }1493 }1494 function processPortal(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) {1495 const targetSelector = n2.props && n2.props.target;1496 const { patchFlag, shapeFlag, children } = n2;1497 if (n1 == null) {1498 const target = (n2.target = isString(targetSelector)1499 ? hostQuerySelector(targetSelector)1500 : null);1501 if (target != null) {1502 if (shapeFlag & 8 /* TEXT_CHILDREN */) {1503 hostSetElementText(target, children);1504 }1505 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {1506 mountChildren(children, target, null, parentComponent, parentSuspense, isSVG);1507 }1508 }1509 else {1510 warn('Invalid Portal target on mount:', target, `(${typeof target})`);1511 }1512 }1513 else {1514 // update content1515 const target = (n2.target = n1.target);1516 if (patchFlag === 1 /* TEXT */) {1517 hostSetElementText(target, children);1518 }1519 else if (!optimized) {1520 patchChildren(n1, n2, target, null, parentComponent, parentSuspense, isSVG);1521 }1522 // target changed1523 if (targetSelector !== (n1.props && n1.props.target)) {1524 const nextTarget = (n2.target = isString(targetSelector)1525 ? hostQuerySelector(targetSelector)1526 : null);1527 if (nextTarget != null) {1528 // move content1529 if (shapeFlag & 8 /* TEXT_CHILDREN */) {1530 hostSetElementText(target, '');1531 hostSetElementText(nextTarget, children);1532 }1533 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {1534 for (let i = 0; i < children.length; i++) {1535 move(children[i], nextTarget, null);1536 }1537 }1538 }1539 else {1540 warn('Invalid Portal target on update:', target, `(${typeof target})`);1541 }1542 }1543 }1544 // insert an empty node as the placeholder for the portal1545 processCommentNode(n1, n2, container, anchor);1546 }1547 function processSuspense(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) {1548 if (n1 == null) {1549 mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);1550 }1551 else {1552 patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, optimized);1553 }1554 }1555 function mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) {1556 const hiddenContainer = hostCreateElement('div');1557 const suspense = (n2.suspense = createSuspenseBoundary(n2, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, optimized));1558 const { content, fallback } = normalizeSuspenseChildren(n2);1559 suspense.subTree = content;1560 suspense.fallbackTree = fallback;1561 // start mounting the content subtree in an off-dom container1562 patch(null, content, hiddenContainer, null, parentComponent, suspense, isSVG, optimized);1563 // now check if we have encountered any async deps1564 if (suspense.deps > 0) {1565 // mount the fallback tree1566 patch(null, fallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context1567 isSVG, optimized);1568 n2.el = fallback.el;1569 }1570 else {1571 // Suspense has no async deps. Just resolve.1572 resolveSuspense(suspense);1573 }1574 }1575 function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, optimized) {1576 const suspense = (n2.suspense = n1.suspense);1577 suspense.vnode = n2;1578 const { content, fallback } = normalizeSuspenseChildren(n2);1579 const oldSubTree = suspense.subTree;1580 const oldFallbackTree = suspense.fallbackTree;1581 if (!suspense.isResolved) {1582 patch(oldSubTree, content, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, optimized);1583 if (suspense.deps > 0) {1584 // still pending. patch the fallback tree.1585 patch(oldFallbackTree, fallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context1586 isSVG, optimized);1587 n2.el = fallback.el;1588 }1589 // If deps somehow becomes 0 after the patch it means the patch caused an1590 // async dep component to unmount and removed its dep. It will cause the1591 // suspense to resolve and we don't need to do anything here.1592 }1593 else {1594 // just normal patch inner content as a fragment1595 patch(oldSubTree, content, container, anchor, parentComponent, suspense, isSVG, optimized);1596 n2.el = content.el;1597 }1598 suspense.subTree = content;1599 suspense.fallbackTree = fallback;1600 }1601 function resolveSuspense(suspense) {1602 {1603 if (suspense.isResolved) {1604 throw new Error(`resolveSuspense() is called on an already resolved suspense boundary.`);1605 }1606 if (suspense.isUnmounted) {1607 throw new Error(`resolveSuspense() is called on an already unmounted suspense boundary.`);1608 }1609 }1610 const { vnode, subTree, fallbackTree, effects, parentComponent, container } = suspense;1611 // this is initial anchor on mount1612 let { anchor } = suspense;1613 // unmount fallback tree1614 if (fallbackTree.el) {1615 // if the fallback tree was mounted, it may have been moved1616 // as part of a parent suspense. get the latest anchor for insertion1617 anchor = getNextHostNode(fallbackTree);1618 unmount(fallbackTree, parentComponent, suspense, true);1619 }1620 // move content from off-dom container to actual container1621 move(subTree, container, anchor);1622 const el = (vnode.el = subTree.el);1623 // suspense as the root node of a component...1624 if (parentComponent && parentComponent.subTree === vnode) {1625 parentComponent.vnode.el = el;1626 updateHOCHostEl(parentComponent, el);1627 }1628 // check if there is a pending parent suspense1629 let parent = suspense.parent;1630 let hasUnresolvedAncestor = false;1631 while (parent) {1632 if (!parent.isResolved) {1633 // found a pending parent suspense, merge buffered post jobs1634 // into that parent1635 parent.effects.push(...effects);1636 hasUnresolvedAncestor = true;1637 break;1638 }1639 parent = parent.parent;1640 }1641 // no pending parent suspense, flush all jobs1642 if (!hasUnresolvedAncestor) {1643 queuePostFlushCb(effects);1644 }1645 suspense.isResolved = true;1646 // invoke @resolve event1647 const onResolve = vnode.props && vnode.props.onResolve;1648 if (isFunction(onResolve)) {1649 onResolve();1650 }1651 }1652 function restartSuspense(suspense) {1653 suspense.isResolved = false;1654 const { vnode, subTree, fallbackTree, parentComponent, container, hiddenContainer, isSVG, optimized } = suspense;1655 // move content tree back to the off-dom container1656 const anchor = getNextHostNode(subTree);1657 move(subTree, hiddenContainer, null);1658 // remount the fallback tree1659 patch(null, fallbackTree, container, anchor, parentComponent, null, // fallback tree will not have suspense context1660 isSVG, optimized);1661 const el = (vnode.el = fallbackTree.el);1662 // suspense as the root node of a component...1663 if (parentComponent && parentComponent.subTree === vnode) {1664 parentComponent.vnode.el = el;1665 updateHOCHostEl(parentComponent, el);1666 }1667 // invoke @suspense event1668 const onSuspense = vnode.props && vnode.props.onSuspense;1669 if (isFunction(onSuspense)) {1670 onSuspense();1671 }1672 }1673 function processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) {1674 if (n1 == null) {1675 mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG);1676 }1677 else {1678 const instance = (n2.component = n1.component);1679 if (shouldUpdateComponent(n1, n2, optimized)) {1680 if (1681 instance.asyncDep &&1682 !instance.asyncResolved) {1683 // async & still pending - just update props and slots1684 // since the component's reactive effect for render isn't set-up yet1685 {1686 pushWarningContext(n2);1687 }1688 updateComponentPreRender(instance, n2);1689 {1690 popWarningContext();1691 }1692 return;1693 }1694 else {1695 // normal update1696 instance.next = n2;1697 // instance.update is the reactive effect runner.1698 instance.update();1699 }1700 }1701 else {1702 // no update needed. just copy over properties1703 n2.component = n1.component;1704 n2.el = n1.el;1705 }1706 }1707 if (n2.ref !== null && parentComponent !== null) {1708 setRef(n2.ref, n1 && n1.ref, parentComponent, n2.component.renderProxy);1709 }1710 }1711 function mountComponent(initialVNode, container, anchor, parentComponent, parentSuspense, isSVG) {1712 const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent));1713 {1714 pushWarningContext(initialVNode);1715 }1716 // resolve props and slots for setup context1717 const propsOptions = initialVNode.type.props;1718 resolveProps(instance, initialVNode.props, propsOptions);1719 resolveSlots(instance, initialVNode.children);1720 // setup stateful logic1721 if (initialVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {1722 setupStatefulComponent(instance, parentSuspense);1723 }1724 // setup() is async. This component relies on async logic to be resolved1725 // before proceeding1726 if ( instance.asyncDep) {1727 if (!parentSuspense) {1728 // TODO handle this properly1729 throw new Error('Async component without a suspense boundary!');1730 }1731 // parent suspense already resolved, need to re-suspense1732 // use queueJob so it's handled synchronously after patching the current1733 // suspense tree1734 if (parentSuspense.isResolved) {1735 queueJob(() => {1736 restartSuspense(parentSuspense);1737 });1738 }1739 parentSuspense.deps++;1740 instance.asyncDep1741 .catch(err => {1742 handleError(err, instance, 0 /* SETUP_FUNCTION */);1743 })1744 .then(asyncSetupResult => {1745 // component may be unmounted before resolve1746 if (!instance.isUnmounted && !parentSuspense.isUnmounted) {1747 retryAsyncComponent(instance, asyncSetupResult, parentSuspense, isSVG);1748 }1749 });1750 // give it a placeholder1751 const placeholder = (instance.subTree = createVNode(Comment));1752 processCommentNode(null, placeholder, container, anchor);1753 initialVNode.el = placeholder.el;1754 return;1755 }1756 setupRenderEffect(instance, parentSuspense, initialVNode, container, anchor, isSVG);1757 {1758 popWarningContext();1759 }1760 }1761 function retryAsyncComponent(instance, asyncSetupResult, parentSuspense, isSVG) {1762 parentSuspense.deps--;1763 // retry from this component1764 instance.asyncResolved = true;1765 const { vnode } = instance;1766 {1767 pushWarningContext(vnode);1768 }1769 handleSetupResult(instance, asyncSetupResult, parentSuspense);1770 setupRenderEffect(instance, parentSuspense, vnode, 1771 // component may have been moved before resolve1772 hostParentNode(instance.subTree.el), getNextHostNode(instance.subTree), isSVG);1773 updateHOCHostEl(instance, vnode.el);1774 {1775 popWarningContext();1776 }1777 if (parentSuspense.deps === 0) {1778 resolveSuspense(parentSuspense);1779 }1780 }1781 function setupRenderEffect(instance, parentSuspense, initialVNode, container, anchor, isSVG) {1782 // create reactive effect for rendering1783 let mounted = false;1784 instance.update = effect(function componentEffect() {1785 if (!mounted) {1786 const subTree = (instance.subTree = renderComponentRoot(instance));1787 // beforeMount hook1788 if (instance.bm !== null) {1789 invokeHooks(instance.bm);1790 }1791 patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);1792 initialVNode.el = subTree.el;1793 // mounted hook1794 if (instance.m !== null) {1795 queuePostRenderEffect(instance.m, parentSuspense);1796 }1797 mounted = true;1798 }1799 else {1800 // updateComponent1801 // This is triggered by mutation of component's own state (next: null)1802 // OR parent calling processComponent (next: HostVNode)1803 const { next } = instance;1804 {1805 pushWarningContext(next || instance.vnode);1806 }1807 if (next !== null) {1808 updateComponentPreRender(instance, next);1809 }1810 const prevTree = instance.subTree;1811 const nextTree = (instance.subTree = renderComponentRoot(instance));1812 // beforeUpdate hook1813 if (instance.bu !== null) {1814 invokeHooks(instance.bu);1815 }1816 // reset refs1817 // only needed if previous patch had refs1818 if (instance.refs !== EMPTY_OBJ) {1819 instance.refs = {}; ...

Full Screen

Full Screen

createApp.js

Source:createApp.js Github

copy

Full Screen

...621 if ( instance.type.__hmrId) {622 registerHMR(instance);623 }624 {625 pushWarningContext(initialVNode);626 startMeasure(instance, `mount`);627 }628 // inject renderer internals for keepAlive629 if (isKeepAlive(initialVNode)) {630 instance.ctx.renderer = internals;631 }632 // resolve props and slots for setup context633 {634 startMeasure(instance, `init`);635 }636 setupComponent(instance);637 {638 endMeasure(instance, `init`);639 }640 // setup() is async. This component relies on async logic to be resolved641 // before proceeding642 if ( instance.asyncDep) {643 parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);644 // Give it a placeholder if this is not hydration645 // TODO handle self-defined fallback646 if (!initialVNode.el) {647 const placeholder = (instance.subTree = createVNode(Comment));648 processCommentNode(null, placeholder, container, anchor);649 }650 return;651 }652 setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);653 {654 popWarningContext();655 endMeasure(instance, `mount`);656 }657 };658 const updateComponent = (n1, n2, optimized) => {659 const instance = (n2.component = n1.component);660 if (shouldUpdateComponent(n1, n2, optimized)) {661 if (662 instance.asyncDep &&663 !instance.asyncResolved) {664 // async & still pending - just update props and slots665 // since the component's reactive effect for render isn't set-up yet666 {667 pushWarningContext(n2);668 }669 updateComponentPreRender(instance, n2, optimized);670 {671 popWarningContext();672 }673 return;674 }675 else {676 // normal update677 instance.next = n2;678 // in case the child component is also queued, remove it to avoid679 // double updating the same child component in the same flush.680 invalidateJob(instance.update);681 // instance.update is the reactive effect runner.682 instance.update();683 }684 }685 else {686 // no update needed. just copy over properties687 n2.component = n1.component;688 n2.el = n1.el;689 instance.vnode = n2;690 }691 };692 const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {693 // create reactive effect for rendering694 instance.update = effect(function componentEffect() {695 if (!instance.isMounted) {696 let vnodeHook;697 const { el, props } = initialVNode;698 const { bm, m, parent } = instance;699 // beforeMount hook700 if (bm) {701 invokeArrayFns(bm);702 }703 // onVnodeBeforeMount704 if ((vnodeHook = props && props.onVnodeBeforeMount)) {705 invokeVNodeHook(vnodeHook, parent, initialVNode);706 }707 // render708 {709 startMeasure(instance, `render`);710 }711 const subTree = (instance.subTree = renderComponentRoot(instance));712 {713 endMeasure(instance, `render`);714 }715 if (el && hydrateNode) {716 {717 startMeasure(instance, `hydrate`);718 }719 // vnode has adopted host node - perform hydration instead of mount.720 hydrateNode(initialVNode.el, subTree, instance, parentSuspense);721 {722 endMeasure(instance, `hydrate`);723 }724 }725 else {726 {727 startMeasure(instance, `patch`);728 }729 patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);730 {731 endMeasure(instance, `patch`);732 }733 initialVNode.el = subTree.el;734 }735 // mounted hook736 if (m) {737 queuePostRenderEffect(m, parentSuspense);738 }739 // onVnodeMounted740 if ((vnodeHook = props && props.onVnodeMounted)) {741 queuePostRenderEffect(() => {742 invokeVNodeHook(vnodeHook, parent, initialVNode);743 }, parentSuspense);744 }745 // activated hook for keep-alive roots.746 // #1742 activated hook must be accessed after first render747 // since the hook may be injected by a child keep-alive748 const { a } = instance;749 if (a &&750 initialVNode.shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {751 queuePostRenderEffect(a, parentSuspense);752 }753 instance.isMounted = true;754 }755 else {756 // updateComponent757 // This is triggered by mutation of component's own state (next: null)758 // OR parent calling processComponent (next: VNode)759 let { next, bu, u, parent, vnode } = instance;760 let originNext = next;761 let vnodeHook;762 {763 pushWarningContext(next || instance.vnode);764 }765 if (next) {766 updateComponentPreRender(instance, next, optimized);767 }768 else {769 next = vnode;770 }771 next.el = vnode.el;772 // beforeUpdate hook773 if (bu) {774 invokeArrayFns(bu);775 }776 // onVnodeBeforeUpdate777 if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {...

Full Screen

Full Screen

server-renderer.esm-bundler.js

Source:server-renderer.esm-bundler.js Github

copy

Full Screen

...664 }665 return name ? classify(name) : isRoot ? `App` : `Anonymous`;666}667const stack = [];668function pushWarningContext(vnode) {669 stack.push(vnode);670}671function popWarningContext() {672 stack.pop();673}674function warn(msg, ...args) {675 const instance = stack.length ? stack[stack.length - 1].component : null;676 const appWarnHandler = instance && instance.appContext.config.warnHandler;677 const trace = getComponentTrace();678 if (appWarnHandler) {679 callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [680 msg + args.join(''),681 instance && instance.proxy,682 trace683 .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)684 .join('\n'),685 trace686 ]);687 }688 else {689 const warnArgs = [`[Vue warn]: ${msg}`, ...args];690 /* istanbul ignore if */691 if (trace.length &&692 // avoid spamming console during tests693 !false) {694 warnArgs.push(`\n`, ...formatTrace(trace));695 }696 console.warn(...warnArgs);697 }698}699function getComponentTrace() {700 let currentVNode = stack[stack.length - 1];701 if (!currentVNode) {702 return [];703 }704 // we can't just use the stack because it will be incomplete during updates705 // that did not start from the root. Re-construct the parent chain using706 // instance parent pointers.707 const normalizedStack = [];708 while (currentVNode) {709 const last = normalizedStack[0];710 if (last && last.vnode === currentVNode) {711 last.recurseCount++;712 }713 else {714 normalizedStack.push({715 vnode: currentVNode,716 recurseCount: 0717 });718 }719 const parentInstance = currentVNode.component && currentVNode.component.parent;720 currentVNode = parentInstance && parentInstance.vnode;721 }722 return normalizedStack;723}724/* istanbul ignore next */725function formatTrace(trace) {726 const logs = [];727 trace.forEach((entry, i) => {728 logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));729 });730 return logs;731}732function formatTraceEntry({ vnode, recurseCount }) {733 const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;734 const isRoot = vnode.component ? vnode.component.parent == null : false;735 const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;736 const close = `>` + postfix;737 return vnode.props738 ? [open, ...formatProps(vnode.props), close]739 : [open + close];740}741/* istanbul ignore next */742function formatProps(props) {743 const res = [];744 const keys = Object.keys(props);745 keys.slice(0, 3).forEach(key => {746 res.push(...formatProp(key, props[key]));747 });748 if (keys.length > 3) {749 res.push(` ...`);750 }751 return res;752}753/* istanbul ignore next */754function formatProp(key, value, raw) {755 if (isString(value)) {756 value = JSON.stringify(value);757 return raw ? value : [`${key}=${value}`];758 }759 else if (typeof value === 'number' ||760 typeof value === 'boolean' ||761 value == null) {762 return raw ? value : [`${key}=${value}`];763 }764 else if (isRef(value)) {765 value = formatProp(key, toRaw(value.value), true);766 return raw ? value : [`${key}=Ref<`, value, `>`];767 }768 else if (isFunction(value)) {769 return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];770 }771 else {772 value = toRaw(value);773 return raw ? value : [`${key}=`, value];774 }775}776const ErrorTypeStrings = {777 ["sp" /* SERVER_PREFETCH */]: 'serverPrefetch hook',778 ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',779 ["c" /* CREATED */]: 'created hook',780 ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',781 ["m" /* MOUNTED */]: 'mounted hook',782 ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',783 ["u" /* UPDATED */]: 'updated',784 ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',785 ["um" /* UNMOUNTED */]: 'unmounted hook',786 ["a" /* ACTIVATED */]: 'activated hook',787 ["da" /* DEACTIVATED */]: 'deactivated hook',788 ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',789 ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',790 ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',791 [0 /* SETUP_FUNCTION */]: 'setup function',792 [1 /* RENDER_FUNCTION */]: 'render function',793 [2 /* WATCH_GETTER */]: 'watcher getter',794 [3 /* WATCH_CALLBACK */]: 'watcher callback',795 [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',796 [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',797 [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',798 [7 /* VNODE_HOOK */]: 'vnode hook',799 [8 /* DIRECTIVE_HOOK */]: 'directive hook',800 [9 /* TRANSITION_HOOK */]: 'transition hook',801 [10 /* APP_ERROR_HANDLER */]: 'app errorHandler',802 [11 /* APP_WARN_HANDLER */]: 'app warnHandler',803 [12 /* FUNCTION_REF */]: 'ref function',804 [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader',805 [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +806 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next'807};808function callWithErrorHandling(fn, instance, type, args) {809 let res;810 try {811 res = args ? fn(...args) : fn();812 }813 catch (err) {814 handleError(err, instance, type);815 }816 return res;817}818function handleError(err, instance, type, throwInDev = true) {819 const contextVNode = instance ? instance.vnode : null;820 if (instance) {821 let cur = instance.parent;822 // the exposed instance is the render proxy to keep it consistent with 2.x823 const exposedInstance = instance.proxy;824 // in production the hook receives only the error code825 const errorInfo = (process.env.NODE_ENV !== 'production') ? ErrorTypeStrings[type] : type;826 while (cur) {827 const errorCapturedHooks = cur.ec;828 if (errorCapturedHooks) {829 for (let i = 0; i < errorCapturedHooks.length; i++) {830 if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {831 return;832 }833 }834 }835 cur = cur.parent;836 }837 // app-level handling838 const appErrorHandler = instance.appContext.config.errorHandler;839 if (appErrorHandler) {840 callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);841 return;842 }843 }844 logError(err, type, contextVNode, throwInDev);845}846function logError(err, type, contextVNode, throwInDev = true) {847 if ((process.env.NODE_ENV !== 'production')) {848 const info = ErrorTypeStrings[type];849 if (contextVNode) {850 pushWarningContext(contextVNode);851 }852 warn(`Unhandled error${info ? ` during execution of ${info}` : ``}`);853 if (contextVNode) {854 popWarningContext();855 }856 // crash in dev by default so it's more noticeable857 if (throwInDev) {858 throw err;859 }860 else {861 console.error(err);862 }863 }864 else {...

Full Screen

Full Screen

server-renderer.cjs.js

Source:server-renderer.cjs.js Github

copy

Full Screen

...517function isRef(r) {518 return Boolean(r && r.__v_isRef === true);519}520const stack = [];521function pushWarningContext(vnode) {522 stack.push(vnode);523}524function popWarningContext() {525 stack.pop();526}527function warn(msg, ...args) {528 const instance = stack.length ? stack[stack.length - 1].component : null;529 const appWarnHandler = instance && instance.appContext.config.warnHandler;530 const trace = getComponentTrace();531 if (appWarnHandler) {532 callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [533 msg + args.join(''),534 instance && instance.proxy,535 trace536 .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)537 .join('\n'),538 trace539 ]);540 }541 else {542 const warnArgs = [`[Vue warn]: ${msg}`, ...args];543 /* istanbul ignore if */544 if (trace.length &&545 // avoid spamming console during tests546 !false) {547 warnArgs.push(`\n`, ...formatTrace(trace));548 }549 console.warn(...warnArgs);550 }551}552function getComponentTrace() {553 let currentVNode = stack[stack.length - 1];554 if (!currentVNode) {555 return [];556 }557 // we can't just use the stack because it will be incomplete during updates558 // that did not start from the root. Re-construct the parent chain using559 // instance parent pointers.560 const normalizedStack = [];561 while (currentVNode) {562 const last = normalizedStack[0];563 if (last && last.vnode === currentVNode) {564 last.recurseCount++;565 }566 else {567 normalizedStack.push({568 vnode: currentVNode,569 recurseCount: 0570 });571 }572 const parentInstance = currentVNode.component && currentVNode.component.parent;573 currentVNode = parentInstance && parentInstance.vnode;574 }575 return normalizedStack;576}577/* istanbul ignore next */578function formatTrace(trace) {579 const logs = [];580 trace.forEach((entry, i) => {581 logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));582 });583 return logs;584}585function formatTraceEntry({ vnode, recurseCount }) {586 const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;587 const isRoot = vnode.component ? vnode.component.parent == null : false;588 const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;589 const close = `>` + postfix;590 return vnode.props591 ? [open, ...formatProps(vnode.props), close]592 : [open + close];593}594/* istanbul ignore next */595function formatProps(props) {596 const res = [];597 const keys = Object.keys(props);598 keys.slice(0, 3).forEach(key => {599 res.push(...formatProp(key, props[key]));600 });601 if (keys.length > 3) {602 res.push(` ...`);603 }604 return res;605}606/* istanbul ignore next */607function formatProp(key, value, raw) {608 if (shared.isString(value)) {609 value = JSON.stringify(value);610 return raw ? value : [`${key}=${value}`];611 }612 else if (typeof value === 'number' ||613 typeof value === 'boolean' ||614 value == null) {615 return raw ? value : [`${key}=${value}`];616 }617 else if (isRef(value)) {618 value = formatProp(key, toRaw(value.value), true);619 return raw ? value : [`${key}=Ref<`, value, `>`];620 }621 else if (shared.isFunction(value)) {622 return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];623 }624 else {625 value = toRaw(value);626 return raw ? value : [`${key}=`, value];627 }628}629const ErrorTypeStrings = {630 ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',631 ["c" /* CREATED */]: 'created hook',632 ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',633 ["m" /* MOUNTED */]: 'mounted hook',634 ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',635 ["u" /* UPDATED */]: 'updated',636 ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',637 ["um" /* UNMOUNTED */]: 'unmounted hook',638 ["a" /* ACTIVATED */]: 'activated hook',639 ["da" /* DEACTIVATED */]: 'deactivated hook',640 ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',641 ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',642 ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',643 [0 /* SETUP_FUNCTION */]: 'setup function',644 [1 /* RENDER_FUNCTION */]: 'render function',645 [2 /* WATCH_GETTER */]: 'watcher getter',646 [3 /* WATCH_CALLBACK */]: 'watcher callback',647 [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',648 [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',649 [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',650 [7 /* VNODE_HOOK */]: 'vnode hook',651 [8 /* DIRECTIVE_HOOK */]: 'directive hook',652 [9 /* TRANSITION_HOOK */]: 'transition hook',653 [10 /* APP_ERROR_HANDLER */]: 'app errorHandler',654 [11 /* APP_WARN_HANDLER */]: 'app warnHandler',655 [12 /* FUNCTION_REF */]: 'ref function',656 [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader',657 [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +658 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next'659};660function callWithErrorHandling(fn, instance, type, args) {661 let res;662 try {663 res = args ? fn(...args) : fn();664 }665 catch (err) {666 handleError(err, instance, type);667 }668 return res;669}670function handleError(err, instance, type, throwInDev = true) {671 const contextVNode = instance ? instance.vnode : null;672 if (instance) {673 let cur = instance.parent;674 // the exposed instance is the render proxy to keep it consistent with 2.x675 const exposedInstance = instance.proxy;676 // in production the hook receives only the error code677 const errorInfo = ErrorTypeStrings[type] ;678 while (cur) {679 const errorCapturedHooks = cur.ec;680 if (errorCapturedHooks) {681 for (let i = 0; i < errorCapturedHooks.length; i++) {682 if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {683 return;684 }685 }686 }687 cur = cur.parent;688 }689 // app-level handling690 const appErrorHandler = instance.appContext.config.errorHandler;691 if (appErrorHandler) {692 callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);693 return;694 }695 }696 logError(err, type, contextVNode, throwInDev);697}698function logError(err, type, contextVNode, throwInDev = true) {699 {700 const info = ErrorTypeStrings[type];701 if (contextVNode) {702 pushWarningContext(contextVNode);703 }704 warn(`Unhandled error${info ? ` during execution of ${info}` : ``}`);705 if (contextVNode) {706 popWarningContext();707 }708 // crash in dev by default so it's more noticeable709 if (throwInDev) {710 throw err;711 }712 else {713 console.error(err);714 }715 }716}...

Full Screen

Full Screen

shouldComponentUpdate.js

Source:shouldComponentUpdate.js Github

copy

Full Screen

...16 !instance.asyncResolved) {17 // async & still pending - just update props and slots18 // since the component's reactive effect for render isn't set-up yet19 {20 pushWarningContext(n2);21 }22 updateComponentPreRender(instance, n2, optimized);23 {24 popWarningContext();25 }26 return;27 }28 else {29 // normal update30 instance.next = n2;31 // in case the child component is also queued, remove it to avoid32 // double updating the same child component in the same flush.33 invalidateJob(instance.update);34 // instance.update is the reactive effect runner....

Full Screen

Full Screen

2.js

Source:2.js Github

copy

Full Screen

...90 let { next, bu, u, parent, vnode } = instance;91 let originNext = next;92 let vnodeHook;93 {94 pushWarningContext(next || instance.vnode);95 }96 if (next) {97 next.el = vnode.el;98 updateComponentPreRender(instance, next, optimized);99 }100 else {101 next = vnode;102 }103 // Disallow component effect recursion during pre-lifecycle hooks.104 effect.allowRecurse = false;105 // beforeUpdate hook106 if (bu) {107 invokeArrayFns(bu);108 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2const { pushWarningContext } = require('playwright/lib/internal/stackTrace');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 pushWarningContext(context);7 await context.close();8 await browser.close();9})();10const { chromium } = require('playwright');11const { pushWarningContext } = require('playwright/lib/internal/stackTrace');12(async () => {13 const browser = await chromium.launch();14 const context = await browser.newContext();15 pushWarningContext(context);16 await context.close();17 await browser.close();18})();19const { chromium } = require('playwright');20const { pushWarningContext } = require('playwright/lib/internal/stackTrace');21(async () => {22 const browser = await chromium.launch();23 const context = await browser.newContext();24 pushWarningContext(context);25 await context.close();26 await browser.close();27})();28const { chromium } = require('playwright');29const { pushWarningContext } = require('playwright/lib/internal/stackTrace');30(async () => {31 const browser = await chromium.launch();32 const context = await browser.newContext();33 pushWarningContext(context);34 await context.close();35 await browser.close();36})();37const { chromium } = require('playwright');38const { pushWarningContext } = require('playwright/lib/internal/stackTrace');39(async () => {40 const browser = await chromium.launch();41 const context = await browser.newContext();42 pushWarningContext(context);43 await context.close();44 await browser.close();45})();46const { chromium } = require('playwright');47const { pushWarningContext } = require('playwright/lib/internal/stackTrace');48(async () => {49 const browser = await chromium.launch();50 const context = await browser.newContext();51 pushWarningContext(context);52 await context.close();53 await browser.close();54})();55const { chromium } = require('playwright');56const { pushWarningContext } = require('playwright/lib/internal

Full Screen

Using AI Code Generation

copy

Full Screen

1const { pushWarningContext } = require('playwright/lib/utils/stackTrace');2pushWarningContext('test');3const { popWarningContext } = require('playwright/lib/utils/stackTrace');4popWarningContext('test');5const { pushWarningContext } = require('playwright/lib/utils/stackTrace');6pushWarningContext('test');7const { popWarningContext } = require('playwright/lib/utils/stackTrace');8popWarningContext('test');9const { pushWarningContext } = require('playwright/lib/utils/stackTrace');10pushWarningContext('test');11const { popWarningContext } = require('playwright/lib/utils/stackTrace');12popWarningContext('test');13const { pushWarningContext } = require('playwright/lib/utils/stackTrace');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { pushWarningContext } = require('playwright-core/lib/server/browserContext');2const { chromium } = require('playwright-core');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 await pushWarningContext(context);7 await context.close();8 await browser.close();9})();10const { pushWarningContext } = require('playwright-core/lib/server/browserContext');11const { chromium } = require('playwright-core');12(async () => {13 const browser = await chromium.launch();14 const context = await browser.newContext();15 await pushWarningContext(context, "This is a test warning");16 await context.close();17 await browser.close();18})();19const { pushWarningContext } = require('playwright-core/lib/server/browserContext');20const { chromium } = require('playwright-core');21(async () => {22 const browser = await chromium.launch();23 const context = await browser.newContext();24 await pushWarningContext(context, new Error('This is a test error'));25 await context.close();26 await browser.close();27})();28const { pushWarningContext } = require('playwright-core/lib/server/browserContext');29const { chromium } = require('playwright-core');30(async () => {31 const browser = await chromium.launch();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Playwright } = require('playwright');2Playwright.pushWarningContext('test.js');3const { chromium } = require('playwright');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.screenshot({ path: `example.png` });9 await browser.close();10})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { pushWarningContext } = require('@playwright/test/lib/utils/stackTrace');2pushWarningContext('my test');3const { popWarningContext } = require('@playwright/test/lib/utils/stackTrace');4popWarningContext();5const { setWarningHandler } = require('@playwright/test/lib/utils/stackTrace');6setWarningHandler((warning) => {7 console.log(warning);8});9const { getWarningHandler } = require('@playwright/test/lib/utils/stackTrace');10getWarningHandler();11const { clearWarningHandler } = require('@playwright/test/lib/utils/stackTrace');12clearWarningHandler();13const { addWarning } = require('@playwright/test/lib/utils/stackTrace');14addWarning('my test');15const { removeWarning } = require('@playwright/test/lib/utils/stackTrace');16removeWarning();17const { setWarningHandler } = require('@playwright/test/lib/utils/stackTrace');18setWarningHandler((warning) => {19 console.log(warning);20});21const { getWarningHandler } = require('@playwright/test/lib/utils/stackTrace');22getWarningHandler();23const { clearWarningHandler } = require('@playwright/test/lib/utils/stackTrace');24clearWarningHandler();25const { setWarningHandler } = require('@playwright/test/lib/utils/stackTrace');26setWarningHandler((warning) => {27 console.log(warning);28});29const { getWarningHandler } = require('@playwright/test/lib/utils/stackTrace');30getWarningHandler();31const { clearWarningHandler } = require('@playwright/test/lib/utils/stackTrace');32clearWarningHandler();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2const { context } = require('playwright/lib/server/trace/viewer/traceModel');3const { pushWarningContext } = require('playwright/lib/utils/utils');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 pushWarningContext('test', context);8 await context.close();9 await browser.close();10})();11 at Object.pushWarningContext (C:\Users\user\Documents\playwright\utils\utils.js:38:13)12 at run (C:\Users\user\Documents\playwright\test.js:12:3)13 at processTicksAndRejections (internal/process/task_queues.js:93:5)

Full Screen

Using AI Code Generation

copy

Full Screen

1 at Object.<anonymous> (test.js:7:9)2 at Module._compile (internal/modules/cjs/loader.js:1137:30)3 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)4 at Module.load (internal/modules/cjs/loader.js:985:32)5 at Function.Module._load (internal/modules/cjs/loader.js:878:14)6 at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)7(async () => {8 await new Promise((resolve, reject) => {9 setTimeout(() => {10 reject(new Error('Some error'));11 }, 1000);12 });13 console.log('This message will not be printed');14})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { context } = require('@playwright/test');2context.pushWarningContext('my-context');3To use the pushWarningContext method of the Playwright Internal API, you need to import the context object from the @playwright/test package. Then, you can call the pushWarningContext method of the context object. The pushWarningContext method accepts a string as an argument that is used to create a warning message. The warning message is displayed before the actual warning message. For example:4const { context } = require('@playwright/test');5context.pushWarningContext('my-context');6To use the pushWarningContext method of the Playwright Internal API, you need to import the context object from the @playwright/test package. Then, you can call the pushWarningContext method of the context object. The pushWarningContext method accepts a string as an argument that is used to create a warning message. The warning message is displayed before the actual warning message. For example:7const { context } = require('@playwright/test');8context.pushWarningContext('my-context');9To use the pushWarningContext method of the Playwright Internal API, you need to import the context object from the @playwright/test package. Then, you can call the pushWarningContext method of the context object. The pushWarningContext method accepts a string as an argument that is used to create a warning message. The warning message is displayed before the actual warning message. For example:

Full Screen

Using AI Code Generation

copy

Full Screen

1const { InternalLogger } = require('playwright');2const { assert } = require('playwright');3const { test } = require('playwright');4const { expect } = require('playwright');5const { Locator } = require('playwright');6InternalLogger.pushWarningContext('test');7test('validate pushWarningContext', async ({ page }) => {8 InternalLogger.pushWarningContext('test');9 InternalLogger.warn('warning message');10 InternalLogger.popWarningContext();11});12test('validate popWarningContext', async ({ page }) => {13 InternalLogger.pushWarningContext('test');14 InternalLogger.warn('warning message');15 InternalLogger.popWarningContext();16});17test('validate warn', async ({ page }) => {18 InternalLogger.pushWarningContext('test');19 InternalLogger.warn('warning message');20 InternalLogger.popWarningContext();21});22test('validate warn', async ({ page }) => {23 InternalLogger.pushWarningContext('test');24 InternalLogger.warn('warning message');25 InternalLogger.popWarningContext();26});27test('validate warn', async ({ page }) => {28 InternalLogger.pushWarningContext('test');29 InternalLogger.warn('warning message');

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful