shared.esm-bundler.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. /**
  2. * Make a map and return a function for checking if a key
  3. * is in that map.
  4. * IMPORTANT: all calls of this function must be prefixed with
  5. * \/\*#\_\_PURE\_\_\*\/
  6. * So that rollup can tree-shake them if necessary.
  7. */
  8. function makeMap(str, expectsLowerCase) {
  9. const map = Object.create(null);
  10. const list = str.split(',');
  11. for (let i = 0; i < list.length; i++) {
  12. map[list[i]] = true;
  13. }
  14. return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val];
  15. }
  16. // Patch flags are optimization hints generated by the compiler.
  17. // when a block with dynamicChildren is encountered during diff, the algorithm
  18. // enters "optimized mode". In this mode, we know that the vdom is produced by
  19. // a render function generated by the compiler, so the algorithm only needs to
  20. // handle updates explicitly marked by these patch flags.
  21. // dev only flag -> name mapping
  22. const PatchFlagNames = {
  23. [1 /* TEXT */]: `TEXT`,
  24. [2 /* CLASS */]: `CLASS`,
  25. [4 /* STYLE */]: `STYLE`,
  26. [8 /* PROPS */]: `PROPS`,
  27. [16 /* FULL_PROPS */]: `FULL_PROPS`,
  28. [32 /* HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
  29. [64 /* STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
  30. [128 /* KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
  31. [256 /* UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
  32. [1024 /* DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
  33. [512 /* NEED_PATCH */]: `NEED_PATCH`,
  34. [-1 /* HOISTED */]: `HOISTED`,
  35. [-2 /* BAIL */]: `BAIL`
  36. };
  37. const GLOBALS_WHITE_LISTED = 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' +
  38. 'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' +
  39. 'Object,Boolean,String,RegExp,Map,Set,JSON,Intl';
  40. const isGloballyWhitelisted = /*#__PURE__*/ makeMap(GLOBALS_WHITE_LISTED);
  41. const range = 2;
  42. function generateCodeFrame(source, start = 0, end = source.length) {
  43. const lines = source.split(/\r?\n/);
  44. let count = 0;
  45. const res = [];
  46. for (let i = 0; i < lines.length; i++) {
  47. count += lines[i].length + 1;
  48. if (count >= start) {
  49. for (let j = i - range; j <= i + range || end > count; j++) {
  50. if (j < 0 || j >= lines.length)
  51. continue;
  52. const line = j + 1;
  53. res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
  54. const lineLength = lines[j].length;
  55. if (j === i) {
  56. // push underline
  57. const pad = start - (count - lineLength) + 1;
  58. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  59. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  60. }
  61. else if (j > i) {
  62. if (end > count) {
  63. const length = Math.max(Math.min(end - count, lineLength), 1);
  64. res.push(` | ` + '^'.repeat(length));
  65. }
  66. count += lineLength + 1;
  67. }
  68. }
  69. break;
  70. }
  71. }
  72. return res.join('\n');
  73. }
  74. /**
  75. * On the client we only need to offer special cases for boolean attributes that
  76. * have different names from their corresponding dom properties:
  77. * - itemscope -> N/A
  78. * - allowfullscreen -> allowFullscreen
  79. * - formnovalidate -> formNoValidate
  80. * - ismap -> isMap
  81. * - nomodule -> noModule
  82. * - novalidate -> noValidate
  83. * - readonly -> readOnly
  84. */
  85. const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
  86. const isSpecialBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs);
  87. /**
  88. * The full list is needed during SSR to produce the correct initial markup.
  89. */
  90. const isBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs +
  91. `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,` +
  92. `loop,open,required,reversed,scoped,seamless,` +
  93. `checked,muted,multiple,selected`);
  94. const unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/;
  95. const attrValidationCache = {};
  96. function isSSRSafeAttrName(name) {
  97. if (attrValidationCache.hasOwnProperty(name)) {
  98. return attrValidationCache[name];
  99. }
  100. const isUnsafe = unsafeAttrCharRE.test(name);
  101. if (isUnsafe) {
  102. console.error(`unsafe attribute name: ${name}`);
  103. }
  104. return (attrValidationCache[name] = !isUnsafe);
  105. }
  106. const propsToAttrMap = {
  107. acceptCharset: 'accept-charset',
  108. className: 'class',
  109. htmlFor: 'for',
  110. httpEquiv: 'http-equiv'
  111. };
  112. /**
  113. * CSS properties that accept plain numbers
  114. */
  115. const isNoUnitNumericStyleProp = /*#__PURE__*/ makeMap(`animation-iteration-count,border-image-outset,border-image-slice,` +
  116. `border-image-width,box-flex,box-flex-group,box-ordinal-group,column-count,` +
  117. `columns,flex,flex-grow,flex-positive,flex-shrink,flex-negative,flex-order,` +
  118. `grid-row,grid-row-end,grid-row-span,grid-row-start,grid-column,` +
  119. `grid-column-end,grid-column-span,grid-column-start,font-weight,line-clamp,` +
  120. `line-height,opacity,order,orphans,tab-size,widows,z-index,zoom,` +
  121. // SVG
  122. `fill-opacity,flood-opacity,stop-opacity,stroke-dasharray,stroke-dashoffset,` +
  123. `stroke-miterlimit,stroke-opacity,stroke-width`);
  124. /**
  125. * Known attributes, this is used for stringification of runtime static nodes
  126. * so that we don't stringify bindings that cannot be set from HTML.
  127. * Don't also forget to allow `data-*` and `aria-*`!
  128. * Generated from https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
  129. */
  130. const isKnownAttr = /*#__PURE__*/ makeMap(`accept,accept-charset,accesskey,action,align,allow,alt,async,` +
  131. `autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,` +
  132. `border,buffered,capture,challenge,charset,checked,cite,class,code,` +
  133. `codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,` +
  134. `coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,` +
  135. `disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,` +
  136. `formaction,formenctype,formmethod,formnovalidate,formtarget,headers,` +
  137. `height,hidden,high,href,hreflang,http-equiv,icon,id,importance,integrity,` +
  138. `ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,` +
  139. `manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,` +
  140. `open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,` +
  141. `referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,` +
  142. `selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,` +
  143. `start,step,style,summary,tabindex,target,title,translate,type,usemap,` +
  144. `value,width,wrap`);
  145. function normalizeStyle(value) {
  146. if (isArray(value)) {
  147. const res = {};
  148. for (let i = 0; i < value.length; i++) {
  149. const item = value[i];
  150. const normalized = normalizeStyle(isString(item) ? parseStringStyle(item) : item);
  151. if (normalized) {
  152. for (const key in normalized) {
  153. res[key] = normalized[key];
  154. }
  155. }
  156. }
  157. return res;
  158. }
  159. else if (isObject(value)) {
  160. return value;
  161. }
  162. }
  163. const listDelimiterRE = /;(?![^(]*\))/g;
  164. const propertyDelimiterRE = /:(.+)/;
  165. function parseStringStyle(cssText) {
  166. const ret = {};
  167. cssText.split(listDelimiterRE).forEach(item => {
  168. if (item) {
  169. const tmp = item.split(propertyDelimiterRE);
  170. tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
  171. }
  172. });
  173. return ret;
  174. }
  175. function stringifyStyle(styles) {
  176. let ret = '';
  177. if (!styles) {
  178. return ret;
  179. }
  180. for (const key in styles) {
  181. const value = styles[key];
  182. const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key);
  183. if (isString(value) ||
  184. (typeof value === 'number' && isNoUnitNumericStyleProp(normalizedKey))) {
  185. // only render valid values
  186. ret += `${normalizedKey}:${value};`;
  187. }
  188. }
  189. return ret;
  190. }
  191. function normalizeClass(value) {
  192. let res = '';
  193. if (isString(value)) {
  194. res = value;
  195. }
  196. else if (isArray(value)) {
  197. for (let i = 0; i < value.length; i++) {
  198. res += normalizeClass(value[i]) + ' ';
  199. }
  200. }
  201. else if (isObject(value)) {
  202. for (const name in value) {
  203. if (value[name]) {
  204. res += name + ' ';
  205. }
  206. }
  207. }
  208. return res.trim();
  209. }
  210. // These tag configs are shared between compiler-dom and runtime-dom, so they
  211. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  212. const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
  213. 'header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,' +
  214. 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
  215. 'data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,' +
  216. 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
  217. 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
  218. 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
  219. 'option,output,progress,select,textarea,details,dialog,menu,' +
  220. 'summary,template,blockquote,iframe,tfoot';
  221. // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
  222. const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
  223. 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
  224. 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
  225. 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
  226. 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
  227. 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
  228. 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
  229. 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
  230. 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
  231. 'text,textPath,title,tspan,unknown,use,view';
  232. const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
  233. const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
  234. const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
  235. const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
  236. const escapeRE = /["'&<>]/;
  237. function escapeHtml(string) {
  238. const str = '' + string;
  239. const match = escapeRE.exec(str);
  240. if (!match) {
  241. return str;
  242. }
  243. let html = '';
  244. let escaped;
  245. let index;
  246. let lastIndex = 0;
  247. for (index = match.index; index < str.length; index++) {
  248. switch (str.charCodeAt(index)) {
  249. case 34: // "
  250. escaped = '&quot;';
  251. break;
  252. case 38: // &
  253. escaped = '&amp;';
  254. break;
  255. case 39: // '
  256. escaped = '&#39;';
  257. break;
  258. case 60: // <
  259. escaped = '&lt;';
  260. break;
  261. case 62: // >
  262. escaped = '&gt;';
  263. break;
  264. default:
  265. continue;
  266. }
  267. if (lastIndex !== index) {
  268. html += str.substring(lastIndex, index);
  269. }
  270. lastIndex = index + 1;
  271. html += escaped;
  272. }
  273. return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
  274. }
  275. // https://www.w3.org/TR/html52/syntax.html#comments
  276. const commentStripRE = /^-?>|<!--|-->|--!>|<!-$/g;
  277. function escapeHtmlComment(src) {
  278. return src.replace(commentStripRE, '');
  279. }
  280. function looseCompareArrays(a, b) {
  281. if (a.length !== b.length)
  282. return false;
  283. let equal = true;
  284. for (let i = 0; equal && i < a.length; i++) {
  285. equal = looseEqual(a[i], b[i]);
  286. }
  287. return equal;
  288. }
  289. function looseEqual(a, b) {
  290. if (a === b)
  291. return true;
  292. let aValidType = isDate(a);
  293. let bValidType = isDate(b);
  294. if (aValidType || bValidType) {
  295. return aValidType && bValidType ? a.getTime() === b.getTime() : false;
  296. }
  297. aValidType = isArray(a);
  298. bValidType = isArray(b);
  299. if (aValidType || bValidType) {
  300. return aValidType && bValidType ? looseCompareArrays(a, b) : false;
  301. }
  302. aValidType = isObject(a);
  303. bValidType = isObject(b);
  304. if (aValidType || bValidType) {
  305. /* istanbul ignore if: this if will probably never be called */
  306. if (!aValidType || !bValidType) {
  307. return false;
  308. }
  309. const aKeysCount = Object.keys(a).length;
  310. const bKeysCount = Object.keys(b).length;
  311. if (aKeysCount !== bKeysCount) {
  312. return false;
  313. }
  314. for (const key in a) {
  315. const aHasKey = a.hasOwnProperty(key);
  316. const bHasKey = b.hasOwnProperty(key);
  317. if ((aHasKey && !bHasKey) ||
  318. (!aHasKey && bHasKey) ||
  319. !looseEqual(a[key], b[key])) {
  320. return false;
  321. }
  322. }
  323. }
  324. return String(a) === String(b);
  325. }
  326. function looseIndexOf(arr, val) {
  327. return arr.findIndex(item => looseEqual(item, val));
  328. }
  329. /**
  330. * For converting {{ interpolation }} values to displayed strings.
  331. * @private
  332. */
  333. const toDisplayString = (val) => {
  334. return val == null
  335. ? ''
  336. : isObject(val)
  337. ? JSON.stringify(val, replacer, 2)
  338. : String(val);
  339. };
  340. const replacer = (_key, val) => {
  341. if (isMap(val)) {
  342. return {
  343. [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
  344. entries[`${key} =>`] = val;
  345. return entries;
  346. }, {})
  347. };
  348. }
  349. else if (isSet(val)) {
  350. return {
  351. [`Set(${val.size})`]: [...val.values()]
  352. };
  353. }
  354. else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
  355. return String(val);
  356. }
  357. return val;
  358. };
  359. /**
  360. * List of @babel/parser plugins that are used for template expression
  361. * transforms and SFC script transforms. By default we enable proposals slated
  362. * for ES2020. This will need to be updated as the spec moves forward.
  363. * Full list at https://babeljs.io/docs/en/next/babel-parser#plugins
  364. */
  365. const babelParserDefaultPlugins = [
  366. 'bigInt',
  367. 'optionalChaining',
  368. 'nullishCoalescingOperator'
  369. ];
  370. const EMPTY_OBJ = (process.env.NODE_ENV !== 'production')
  371. ? Object.freeze({})
  372. : {};
  373. const EMPTY_ARR = (process.env.NODE_ENV !== 'production') ? Object.freeze([]) : [];
  374. const NOOP = () => { };
  375. /**
  376. * Always return false.
  377. */
  378. const NO = () => false;
  379. const onRE = /^on[^a-z]/;
  380. const isOn = (key) => onRE.test(key);
  381. const isModelListener = (key) => key.startsWith('onUpdate:');
  382. const extend = Object.assign;
  383. const remove = (arr, el) => {
  384. const i = arr.indexOf(el);
  385. if (i > -1) {
  386. arr.splice(i, 1);
  387. }
  388. };
  389. const hasOwnProperty = Object.prototype.hasOwnProperty;
  390. const hasOwn = (val, key) => hasOwnProperty.call(val, key);
  391. const isArray = Array.isArray;
  392. const isMap = (val) => toTypeString(val) === '[object Map]';
  393. const isSet = (val) => toTypeString(val) === '[object Set]';
  394. const isDate = (val) => val instanceof Date;
  395. const isFunction = (val) => typeof val === 'function';
  396. const isString = (val) => typeof val === 'string';
  397. const isSymbol = (val) => typeof val === 'symbol';
  398. const isObject = (val) => val !== null && typeof val === 'object';
  399. const isPromise = (val) => {
  400. return isObject(val) && isFunction(val.then) && isFunction(val.catch);
  401. };
  402. const objectToString = Object.prototype.toString;
  403. const toTypeString = (value) => objectToString.call(value);
  404. const toRawType = (value) => {
  405. // extract "RawType" from strings like "[object RawType]"
  406. return toTypeString(value).slice(8, -1);
  407. };
  408. const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  409. const isIntegerKey = (key) => isString(key) &&
  410. key !== 'NaN' &&
  411. key[0] !== '-' &&
  412. '' + parseInt(key, 10) === key;
  413. const isReservedProp = /*#__PURE__*/ makeMap(
  414. // the leading comma is intentional so empty string "" is also included
  415. ',key,ref,' +
  416. 'onVnodeBeforeMount,onVnodeMounted,' +
  417. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  418. 'onVnodeBeforeUnmount,onVnodeUnmounted');
  419. const cacheStringFunction = (fn) => {
  420. const cache = Object.create(null);
  421. return ((str) => {
  422. const hit = cache[str];
  423. return hit || (cache[str] = fn(str));
  424. });
  425. };
  426. const camelizeRE = /-(\w)/g;
  427. /**
  428. * @private
  429. */
  430. const camelize = cacheStringFunction((str) => {
  431. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  432. });
  433. const hyphenateRE = /\B([A-Z])/g;
  434. /**
  435. * @private
  436. */
  437. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
  438. /**
  439. * @private
  440. */
  441. const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  442. /**
  443. * @private
  444. */
  445. const toHandlerKey = cacheStringFunction((str) => (str ? `on${capitalize(str)}` : ``));
  446. // compare whether a value has changed, accounting for NaN.
  447. const hasChanged = (value, oldValue) => value !== oldValue && (value === value || oldValue === oldValue);
  448. const invokeArrayFns = (fns, arg) => {
  449. for (let i = 0; i < fns.length; i++) {
  450. fns[i](arg);
  451. }
  452. };
  453. const def = (obj, key, value) => {
  454. Object.defineProperty(obj, key, {
  455. configurable: true,
  456. enumerable: false,
  457. value
  458. });
  459. };
  460. const toNumber = (val) => {
  461. const n = parseFloat(val);
  462. return isNaN(n) ? val : n;
  463. };
  464. let _globalThis;
  465. const getGlobalThis = () => {
  466. return (_globalThis ||
  467. (_globalThis =
  468. typeof globalThis !== 'undefined'
  469. ? globalThis
  470. : typeof self !== 'undefined'
  471. ? self
  472. : typeof window !== 'undefined'
  473. ? window
  474. : typeof global !== 'undefined'
  475. ? global
  476. : {}));
  477. };
  478. export { EMPTY_ARR, EMPTY_OBJ, NO, NOOP, PatchFlagNames, babelParserDefaultPlugins, camelize, capitalize, def, escapeHtml, escapeHtmlComment, extend, generateCodeFrame, getGlobalThis, hasChanged, hasOwn, hyphenate, invokeArrayFns, isArray, isBooleanAttr, isDate, isFunction, isGloballyWhitelisted, isHTMLTag, isIntegerKey, isKnownAttr, isMap, isModelListener, isNoUnitNumericStyleProp, isObject, isOn, isPlainObject, isPromise, isReservedProp, isSSRSafeAttrName, isSVGTag, isSet, isSpecialBooleanAttr, isString, isSymbol, isVoidTag, looseEqual, looseIndexOf, makeMap, normalizeClass, normalizeStyle, objectToString, parseStringStyle, propsToAttrMap, remove, stringifyStyle, toDisplayString, toHandlerKey, toNumber, toRawType, toTypeString };