compiler-sfc.cjs.js 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var CompilerDOM = require('@vue/compiler-dom');
  4. var sourceMap = require('source-map');
  5. var hash = require('hash-sum');
  6. var path = require('path');
  7. var compilerCore = require('@vue/compiler-core');
  8. var url = require('url');
  9. var shared = require('@vue/shared');
  10. var CompilerSSR = require('@vue/compiler-ssr');
  11. var postcss = require('postcss');
  12. var selectorParser = require('postcss-selector-parser');
  13. var merge = require('merge-source-map');
  14. var MagicString = require('magic-string');
  15. var parser = require('@babel/parser');
  16. var estreeWalker = require('estree-walker');
  17. var refTransform = require('@vue/ref-transform');
  18. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; }
  19. function _interopNamespace(e) {
  20. if (e && e.__esModule) return e;
  21. var n = Object.create(null);
  22. if (e) {
  23. Object.keys(e).forEach(function (k) {
  24. n[k] = e[k];
  25. });
  26. }
  27. n['default'] = e;
  28. return Object.freeze(n);
  29. }
  30. var CompilerDOM__namespace = /*#__PURE__*/_interopNamespace(CompilerDOM);
  31. var hash__default = /*#__PURE__*/_interopDefaultLegacy(hash);
  32. var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
  33. var CompilerSSR__namespace = /*#__PURE__*/_interopNamespace(CompilerSSR);
  34. var postcss__default = /*#__PURE__*/_interopDefaultLegacy(postcss);
  35. var selectorParser__default = /*#__PURE__*/_interopDefaultLegacy(selectorParser);
  36. var merge__default = /*#__PURE__*/_interopDefaultLegacy(merge);
  37. var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
  38. const CSS_VARS_HELPER = `useCssVars`;
  39. const cssVarRE = /\bv-bind\(\s*(?:'([^']+)'|"([^"]+)"|([^'"][^)]*))\s*\)/g;
  40. function genCssVarsFromList(vars, id, isProd) {
  41. return `{\n ${vars
  42. .map(key => `"${genVarName(id, key, isProd)}": (${key})`)
  43. .join(',\n ')}\n}`;
  44. }
  45. function genVarName(id, raw, isProd) {
  46. if (isProd) {
  47. return hash__default(id + raw);
  48. }
  49. else {
  50. return `${id}-${raw.replace(/([^\w-])/g, '_')}`;
  51. }
  52. }
  53. function parseCssVars(sfc) {
  54. const vars = [];
  55. sfc.styles.forEach(style => {
  56. let match;
  57. // ignore v-bind() in comments /* ... */
  58. const content = style.content.replace(/\/\*([\s\S]*?)\*\//g, '');
  59. while ((match = cssVarRE.exec(content))) {
  60. const variable = match[1] || match[2] || match[3];
  61. if (!vars.includes(variable)) {
  62. vars.push(variable);
  63. }
  64. }
  65. });
  66. return vars;
  67. }
  68. const cssVarsPlugin = opts => {
  69. const { id, isProd } = opts;
  70. return {
  71. postcssPlugin: 'vue-sfc-vars',
  72. Declaration(decl) {
  73. // rewrite CSS variables
  74. if (cssVarRE.test(decl.value)) {
  75. decl.value = decl.value.replace(cssVarRE, (_, $1, $2, $3) => {
  76. return `var(--${genVarName(id, $1 || $2 || $3, isProd)})`;
  77. });
  78. }
  79. }
  80. };
  81. };
  82. cssVarsPlugin.postcss = true;
  83. function genCssVarsCode(vars, bindings, id, isProd) {
  84. const varsExp = genCssVarsFromList(vars, id, isProd);
  85. const exp = CompilerDOM.createSimpleExpression(varsExp, false);
  86. const context = CompilerDOM.createTransformContext(CompilerDOM.createRoot([]), {
  87. prefixIdentifiers: true,
  88. inline: true,
  89. bindingMetadata: bindings.__isScriptSetup === false ? undefined : bindings
  90. });
  91. const transformed = CompilerDOM.processExpression(exp, context);
  92. const transformedString = transformed.type === 4 /* SIMPLE_EXPRESSION */
  93. ? transformed.content
  94. : transformed.children
  95. .map(c => {
  96. return typeof c === 'string'
  97. ? c
  98. : c.content;
  99. })
  100. .join('');
  101. return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
  102. }
  103. // <script setup> already gets the calls injected as part of the transform
  104. // this is only for single normal <script>
  105. function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd) {
  106. return (`\nimport { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'\n` +
  107. `const __injectCSSVars__ = () => {\n${genCssVarsCode(cssVars, bindings, id, isProd)}}\n` +
  108. `const __setup__ = __default__.setup\n` +
  109. `__default__.setup = __setup__\n` +
  110. ` ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }\n` +
  111. ` : __injectCSSVars__\n`);
  112. }
  113. function createCache(size = 500) {
  114. return new (require('lru-cache'))(size);
  115. }
  116. const sourceToSFC = createCache();
  117. function parse(source, { sourceMap = true, filename = 'anonymous.vue', sourceRoot = '', pad = false, ignoreEmpty = true, compiler = CompilerDOM__namespace } = {}) {
  118. const sourceKey = source + sourceMap + filename + sourceRoot + pad + compiler.parse;
  119. const cache = sourceToSFC.get(sourceKey);
  120. if (cache) {
  121. return cache;
  122. }
  123. const descriptor = {
  124. filename,
  125. source,
  126. template: null,
  127. script: null,
  128. scriptSetup: null,
  129. styles: [],
  130. customBlocks: [],
  131. cssVars: [],
  132. slotted: false
  133. };
  134. const errors = [];
  135. const ast = compiler.parse(source, {
  136. // there are no components at SFC parsing level
  137. isNativeTag: () => true,
  138. // preserve all whitespaces
  139. isPreTag: () => true,
  140. getTextMode: ({ tag, props }, parent) => {
  141. // all top level elements except <template> are parsed as raw text
  142. // containers
  143. if ((!parent && tag !== 'template') ||
  144. // <template lang="xxx"> should also be treated as raw text
  145. (tag === 'template' &&
  146. props.some(p => p.type === 6 /* ATTRIBUTE */ &&
  147. p.name === 'lang' &&
  148. p.value &&
  149. p.value.content &&
  150. p.value.content !== 'html'))) {
  151. return 2 /* RAWTEXT */;
  152. }
  153. else {
  154. return 0 /* DATA */;
  155. }
  156. },
  157. onError: e => {
  158. errors.push(e);
  159. }
  160. });
  161. ast.children.forEach(node => {
  162. if (node.type !== 1 /* ELEMENT */) {
  163. return;
  164. }
  165. // we only want to keep the nodes that are not empty (when the tag is not a template)
  166. if (ignoreEmpty &&
  167. node.tag !== 'template' &&
  168. isEmpty(node) &&
  169. !hasSrc(node)) {
  170. return;
  171. }
  172. switch (node.tag) {
  173. case 'template':
  174. if (!descriptor.template) {
  175. const templateBlock = (descriptor.template = createBlock(node, source, false));
  176. templateBlock.ast = node;
  177. // warn against 2.x <template functional>
  178. if (templateBlock.attrs.functional) {
  179. const err = new SyntaxError(`<template functional> is no longer supported in Vue 3, since ` +
  180. `functional components no longer have significant performance ` +
  181. `difference from stateful ones. Just use a normal <template> ` +
  182. `instead.`);
  183. err.loc = node.props.find(p => p.name === 'functional').loc;
  184. errors.push(err);
  185. }
  186. }
  187. else {
  188. errors.push(createDuplicateBlockError(node));
  189. }
  190. break;
  191. case 'script':
  192. const scriptBlock = createBlock(node, source, pad);
  193. const isSetup = !!scriptBlock.attrs.setup;
  194. if (isSetup && !descriptor.scriptSetup) {
  195. descriptor.scriptSetup = scriptBlock;
  196. break;
  197. }
  198. if (!isSetup && !descriptor.script) {
  199. descriptor.script = scriptBlock;
  200. break;
  201. }
  202. errors.push(createDuplicateBlockError(node, isSetup));
  203. break;
  204. case 'style':
  205. const styleBlock = createBlock(node, source, pad);
  206. if (styleBlock.attrs.vars) {
  207. errors.push(new SyntaxError(`<style vars> has been replaced by a new proposal: ` +
  208. `https://github.com/vuejs/rfcs/pull/231`));
  209. }
  210. descriptor.styles.push(styleBlock);
  211. break;
  212. default:
  213. descriptor.customBlocks.push(createBlock(node, source, pad));
  214. break;
  215. }
  216. });
  217. if (descriptor.scriptSetup) {
  218. if (descriptor.scriptSetup.src) {
  219. errors.push(new SyntaxError(`<script setup> cannot use the "src" attribute because ` +
  220. `its syntax will be ambiguous outside of the component.`));
  221. descriptor.scriptSetup = null;
  222. }
  223. if (descriptor.script && descriptor.script.src) {
  224. errors.push(new SyntaxError(`<script> cannot use the "src" attribute when <script setup> is ` +
  225. `also present because they must be processed together.`));
  226. descriptor.script = null;
  227. }
  228. }
  229. if (sourceMap) {
  230. const genMap = (block) => {
  231. if (block && !block.src) {
  232. block.map = generateSourceMap(filename, source, block.content, sourceRoot, !pad || block.type === 'template' ? block.loc.start.line - 1 : 0);
  233. }
  234. };
  235. genMap(descriptor.template);
  236. genMap(descriptor.script);
  237. descriptor.styles.forEach(genMap);
  238. descriptor.customBlocks.forEach(genMap);
  239. }
  240. // parse CSS vars
  241. descriptor.cssVars = parseCssVars(descriptor);
  242. // check if the SFC uses :slotted
  243. const slottedRE = /(?:::v-|:)slotted\(/;
  244. descriptor.slotted = descriptor.styles.some(s => s.scoped && slottedRE.test(s.content));
  245. const result = {
  246. descriptor,
  247. errors
  248. };
  249. sourceToSFC.set(sourceKey, result);
  250. return result;
  251. }
  252. function createDuplicateBlockError(node, isScriptSetup = false) {
  253. const err = new SyntaxError(`Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`);
  254. err.loc = node.loc;
  255. return err;
  256. }
  257. function createBlock(node, source, pad) {
  258. const type = node.tag;
  259. let { start, end } = node.loc;
  260. let content = '';
  261. if (node.children.length) {
  262. start = node.children[0].loc.start;
  263. end = node.children[node.children.length - 1].loc.end;
  264. content = source.slice(start.offset, end.offset);
  265. }
  266. else {
  267. const offset = node.loc.source.indexOf(`</`);
  268. if (offset > -1) {
  269. start = {
  270. line: start.line,
  271. column: start.column + offset,
  272. offset: start.offset + offset
  273. };
  274. }
  275. end = Object.assign({}, start);
  276. }
  277. const loc = {
  278. source: content,
  279. start,
  280. end
  281. };
  282. const attrs = {};
  283. const block = {
  284. type,
  285. content,
  286. loc,
  287. attrs
  288. };
  289. if (pad) {
  290. block.content = padContent(source, block, pad) + block.content;
  291. }
  292. node.props.forEach(p => {
  293. if (p.type === 6 /* ATTRIBUTE */) {
  294. attrs[p.name] = p.value ? p.value.content || true : true;
  295. if (p.name === 'lang') {
  296. block.lang = p.value && p.value.content;
  297. }
  298. else if (p.name === 'src') {
  299. block.src = p.value && p.value.content;
  300. }
  301. else if (type === 'style') {
  302. if (p.name === 'scoped') {
  303. block.scoped = true;
  304. }
  305. else if (p.name === 'module') {
  306. block.module = attrs[p.name];
  307. }
  308. }
  309. else if (type === 'script' && p.name === 'setup') {
  310. block.setup = attrs.setup;
  311. }
  312. }
  313. });
  314. return block;
  315. }
  316. const splitRE = /\r?\n/g;
  317. const emptyRE = /^(?:\/\/)?\s*$/;
  318. const replaceRE = /./g;
  319. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset) {
  320. const map = new sourceMap.SourceMapGenerator({
  321. file: filename.replace(/\\/g, '/'),
  322. sourceRoot: sourceRoot.replace(/\\/g, '/')
  323. });
  324. map.setSourceContent(filename, source);
  325. generated.split(splitRE).forEach((line, index) => {
  326. if (!emptyRE.test(line)) {
  327. const originalLine = index + 1 + lineOffset;
  328. const generatedLine = index + 1;
  329. for (let i = 0; i < line.length; i++) {
  330. if (!/\s/.test(line[i])) {
  331. map.addMapping({
  332. source: filename,
  333. original: {
  334. line: originalLine,
  335. column: i
  336. },
  337. generated: {
  338. line: generatedLine,
  339. column: i
  340. }
  341. });
  342. }
  343. }
  344. }
  345. });
  346. return JSON.parse(map.toString());
  347. }
  348. function padContent(content, block, pad) {
  349. content = content.slice(0, block.loc.start.offset);
  350. if (pad === 'space') {
  351. return content.replace(replaceRE, ' ');
  352. }
  353. else {
  354. const offset = content.split(splitRE).length;
  355. const padChar = block.type === 'script' && !block.lang ? '//\n' : '\n';
  356. return Array(offset).join(padChar);
  357. }
  358. }
  359. function hasSrc(node) {
  360. return node.props.some(p => {
  361. if (p.type !== 6 /* ATTRIBUTE */) {
  362. return false;
  363. }
  364. return p.name === 'src';
  365. });
  366. }
  367. /**
  368. * Returns true if the node has no children
  369. * once the empty text nodes (trimmed content) have been filtered out.
  370. */
  371. function isEmpty(node) {
  372. return (node.children.filter(child => child.type !== 2 /* TEXT */ || child.content.trim() !== '').length === 0);
  373. }
  374. function isRelativeUrl(url) {
  375. const firstChar = url.charAt(0);
  376. return firstChar === '.' || firstChar === '~' || firstChar === '@';
  377. }
  378. const externalRE = /^https?:\/\//;
  379. function isExternalUrl(url) {
  380. return externalRE.test(url);
  381. }
  382. const dataUrlRE = /^\s*data:/i;
  383. function isDataUrl(url) {
  384. return dataUrlRE.test(url);
  385. }
  386. /**
  387. * Parses string url into URL object.
  388. */
  389. function parseUrl(url) {
  390. const firstChar = url.charAt(0);
  391. if (firstChar === '~') {
  392. const secondChar = url.charAt(1);
  393. url = url.slice(secondChar === '/' ? 2 : 1);
  394. }
  395. return parseUriParts(url);
  396. }
  397. /**
  398. * vuejs/component-compiler-utils#22 Support uri fragment in transformed require
  399. * @param urlString an url as a string
  400. */
  401. function parseUriParts(urlString) {
  402. // A TypeError is thrown if urlString is not a string
  403. // @see https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
  404. return url.parse(shared.isString(urlString) ? urlString : '', false, true);
  405. }
  406. const defaultAssetUrlOptions = {
  407. base: null,
  408. includeAbsolute: false,
  409. tags: {
  410. video: ['src', 'poster'],
  411. source: ['src'],
  412. img: ['src'],
  413. image: ['xlink:href', 'href'],
  414. use: ['xlink:href', 'href']
  415. }
  416. };
  417. const normalizeOptions = (options) => {
  418. if (Object.keys(options).some(key => shared.isArray(options[key]))) {
  419. // legacy option format which directly passes in tags config
  420. return Object.assign(Object.assign({}, defaultAssetUrlOptions), { tags: options });
  421. }
  422. return Object.assign(Object.assign({}, defaultAssetUrlOptions), options);
  423. };
  424. const createAssetUrlTransformWithOptions = (options) => {
  425. return (node, context) => transformAssetUrl(node, context, options);
  426. };
  427. /**
  428. * A `@vue/compiler-core` plugin that transforms relative asset urls into
  429. * either imports or absolute urls.
  430. *
  431. * ``` js
  432. * // Before
  433. * createVNode('img', { src: './logo.png' })
  434. *
  435. * // After
  436. * import _imports_0 from './logo.png'
  437. * createVNode('img', { src: _imports_0 })
  438. * ```
  439. */
  440. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  441. if (node.type === 1 /* ELEMENT */) {
  442. if (!node.props.length) {
  443. return;
  444. }
  445. const tags = options.tags || defaultAssetUrlOptions.tags;
  446. const attrs = tags[node.tag];
  447. const wildCardAttrs = tags['*'];
  448. if (!attrs && !wildCardAttrs) {
  449. return;
  450. }
  451. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  452. node.props.forEach((attr, index) => {
  453. if (attr.type !== 6 /* ATTRIBUTE */ ||
  454. !assetAttrs.includes(attr.name) ||
  455. !attr.value ||
  456. isExternalUrl(attr.value.content) ||
  457. isDataUrl(attr.value.content) ||
  458. attr.value.content[0] === '#' ||
  459. (!options.includeAbsolute && !isRelativeUrl(attr.value.content))) {
  460. return;
  461. }
  462. const url = parseUrl(attr.value.content);
  463. if (options.base && attr.value.content[0] === '.') {
  464. // explicit base - directly rewrite relative urls into absolute url
  465. // to avoid generating extra imports
  466. // Allow for full hostnames provided in options.base
  467. const base = parseUrl(options.base);
  468. const protocol = base.protocol || '';
  469. const host = base.host ? protocol + '//' + base.host : '';
  470. const basePath = base.path || '/';
  471. // when packaged in the browser, path will be using the posix-
  472. // only version provided by rollup-plugin-node-builtins.
  473. attr.value.content =
  474. host +
  475. (path__default.posix || path__default).join(basePath, url.path + (url.hash || ''));
  476. return;
  477. }
  478. // otherwise, transform the url into an import.
  479. // this assumes a bundler will resolve the import into the correct
  480. // absolute url (e.g. webpack file-loader)
  481. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  482. node.props[index] = {
  483. type: 7 /* DIRECTIVE */,
  484. name: 'bind',
  485. arg: compilerCore.createSimpleExpression(attr.name, true, attr.loc),
  486. exp,
  487. modifiers: [],
  488. loc: attr.loc
  489. };
  490. });
  491. }
  492. };
  493. function getImportsExpressionExp(path, hash, loc, context) {
  494. if (path) {
  495. const existing = context.imports.find(i => i.path === path);
  496. if (existing) {
  497. return existing.exp;
  498. }
  499. const name = `_imports_${context.imports.length}`;
  500. const exp = compilerCore.createSimpleExpression(name, false, loc, 2 /* CAN_HOIST */);
  501. context.imports.push({ exp, path });
  502. if (hash && path) {
  503. return context.hoist(compilerCore.createSimpleExpression(`${name} + '${hash}'`, false, loc, 2 /* CAN_HOIST */));
  504. }
  505. else {
  506. return exp;
  507. }
  508. }
  509. else {
  510. return compilerCore.createSimpleExpression(`''`, false, loc, 2 /* CAN_HOIST */);
  511. }
  512. }
  513. const srcsetTags = ['img', 'source'];
  514. // http://w3c.github.io/html/semantics-embedded-content.html#ref-for-image-candidate-string-5
  515. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  516. const createSrcsetTransformWithOptions = (options) => {
  517. return (node, context) => transformSrcset(node, context, options);
  518. };
  519. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  520. if (node.type === 1 /* ELEMENT */) {
  521. if (srcsetTags.includes(node.tag) && node.props.length) {
  522. node.props.forEach((attr, index) => {
  523. if (attr.name === 'srcset' && attr.type === 6 /* ATTRIBUTE */) {
  524. if (!attr.value)
  525. return;
  526. const value = attr.value.content;
  527. if (!value)
  528. return;
  529. const imageCandidates = value.split(',').map(s => {
  530. // The attribute value arrives here with all whitespace, except
  531. // normal spaces, represented by escape sequences
  532. const [url, descriptor] = s
  533. .replace(escapedSpaceCharacters, ' ')
  534. .trim()
  535. .split(' ', 2);
  536. return { url, descriptor };
  537. });
  538. // data urls contains comma after the ecoding so we need to re-merge
  539. // them
  540. for (let i = 0; i < imageCandidates.length; i++) {
  541. const { url } = imageCandidates[i];
  542. if (isDataUrl(url)) {
  543. imageCandidates[i + 1].url =
  544. url + ',' + imageCandidates[i + 1].url;
  545. imageCandidates.splice(i, 1);
  546. }
  547. }
  548. const hasQualifiedUrl = imageCandidates.some(({ url }) => {
  549. return (!isExternalUrl(url) &&
  550. !isDataUrl(url) &&
  551. (options.includeAbsolute || isRelativeUrl(url)));
  552. });
  553. // When srcset does not contain any qualified URLs, skip transforming
  554. if (!hasQualifiedUrl) {
  555. return;
  556. }
  557. if (options.base) {
  558. const base = options.base;
  559. const set = [];
  560. imageCandidates.forEach(({ url, descriptor }) => {
  561. descriptor = descriptor ? ` ${descriptor}` : ``;
  562. if (isRelativeUrl(url)) {
  563. set.push((path__default.posix || path__default).join(base, url) + descriptor);
  564. }
  565. else {
  566. set.push(url + descriptor);
  567. }
  568. });
  569. attr.value.content = set.join(', ');
  570. return;
  571. }
  572. const compoundExpression = compilerCore.createCompoundExpression([], attr.loc);
  573. imageCandidates.forEach(({ url, descriptor }, index) => {
  574. if (!isExternalUrl(url) &&
  575. !isDataUrl(url) &&
  576. (options.includeAbsolute || isRelativeUrl(url))) {
  577. const { path } = parseUrl(url);
  578. let exp;
  579. if (path) {
  580. const existingImportsIndex = context.imports.findIndex(i => i.path === path);
  581. if (existingImportsIndex > -1) {
  582. exp = compilerCore.createSimpleExpression(`_imports_${existingImportsIndex}`, false, attr.loc, 2 /* CAN_HOIST */);
  583. }
  584. else {
  585. exp = compilerCore.createSimpleExpression(`_imports_${context.imports.length}`, false, attr.loc, 2 /* CAN_HOIST */);
  586. context.imports.push({ exp, path });
  587. }
  588. compoundExpression.children.push(exp);
  589. }
  590. }
  591. else {
  592. const exp = compilerCore.createSimpleExpression(`"${url}"`, false, attr.loc, 2 /* CAN_HOIST */);
  593. compoundExpression.children.push(exp);
  594. }
  595. const isNotLast = imageCandidates.length - 1 > index;
  596. if (descriptor && isNotLast) {
  597. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  598. }
  599. else if (descriptor) {
  600. compoundExpression.children.push(` + ' ${descriptor}'`);
  601. }
  602. else if (isNotLast) {
  603. compoundExpression.children.push(` + ', ' + `);
  604. }
  605. });
  606. const hoisted = context.hoist(compoundExpression);
  607. hoisted.constType = 2 /* CAN_HOIST */;
  608. node.props[index] = {
  609. type: 7 /* DIRECTIVE */,
  610. name: 'bind',
  611. arg: compilerCore.createSimpleExpression('srcset', true, attr.loc),
  612. exp: hoisted,
  613. modifiers: [],
  614. loc: attr.loc
  615. };
  616. }
  617. });
  618. }
  619. }
  620. };
  621. const hasWarned = {};
  622. function warnOnce(msg) {
  623. const isNodeProd = typeof process !== 'undefined' && process.env.NODE_ENV === 'production';
  624. if (!isNodeProd && !false && !hasWarned[msg]) {
  625. hasWarned[msg] = true;
  626. warn(msg);
  627. }
  628. }
  629. function warn(msg) {
  630. console.warn(`\x1b[1m\x1b[33m[@vue/compiler-sfc]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`);
  631. }
  632. function preprocess({ source, filename, preprocessOptions }, preprocessor) {
  633. // Consolidate exposes a callback based API, but the callback is in fact
  634. // called synchronously for most templating engines. In our case, we have to
  635. // expose a synchronous API so that it is usable in Jest transforms (which
  636. // have to be sync because they are applied via Node.js require hooks)
  637. let res = '';
  638. let err = null;
  639. preprocessor.render(source, Object.assign({ filename }, preprocessOptions), (_err, _res) => {
  640. if (_err)
  641. err = _err;
  642. res = _res;
  643. });
  644. if (err)
  645. throw err;
  646. return res;
  647. }
  648. function compileTemplate(options) {
  649. const { preprocessLang, preprocessCustomRequire } = options;
  650. const preprocessor = preprocessLang
  651. ? preprocessCustomRequire
  652. ? preprocessCustomRequire(preprocessLang)
  653. : require('consolidate')[preprocessLang]
  654. : false;
  655. if (preprocessor) {
  656. try {
  657. return doCompileTemplate(Object.assign(Object.assign({}, options), { source: preprocess(options, preprocessor) }));
  658. }
  659. catch (e) {
  660. return {
  661. code: `export default function render() {}`,
  662. source: options.source,
  663. tips: [],
  664. errors: [e]
  665. };
  666. }
  667. }
  668. else if (preprocessLang) {
  669. return {
  670. code: `export default function render() {}`,
  671. source: options.source,
  672. tips: [
  673. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  674. ],
  675. errors: [
  676. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  677. ]
  678. };
  679. }
  680. else {
  681. return doCompileTemplate(options);
  682. }
  683. }
  684. function doCompileTemplate({ filename, id, scoped, slotted, inMap, source, ssr = false, ssrCssVars, isProd = false, compiler = ssr ? CompilerSSR__namespace : CompilerDOM__namespace, compilerOptions = {}, transformAssetUrls }) {
  685. const errors = [];
  686. const warnings = [];
  687. let nodeTransforms = [];
  688. if (shared.isObject(transformAssetUrls)) {
  689. const assetOptions = normalizeOptions(transformAssetUrls);
  690. nodeTransforms = [
  691. createAssetUrlTransformWithOptions(assetOptions),
  692. createSrcsetTransformWithOptions(assetOptions)
  693. ];
  694. }
  695. else if (transformAssetUrls !== false) {
  696. nodeTransforms = [transformAssetUrl, transformSrcset];
  697. }
  698. if (ssr && !ssrCssVars) {
  699. warnOnce(`compileTemplate is called with \`ssr: true\` but no ` +
  700. `corresponding \`cssVars\` option.\`.`);
  701. }
  702. if (!id) {
  703. warnOnce(`compileTemplate now requires the \`id\` option.\`.`);
  704. id = '';
  705. }
  706. const shortId = id.replace(/^data-v-/, '');
  707. const longId = `data-v-${shortId}`;
  708. let { code, ast, preamble, map } = compiler.compile(source, Object.assign(Object.assign({ mode: 'module', prefixIdentifiers: true, hoistStatic: true, cacheHandlers: true, ssrCssVars: ssr && ssrCssVars && ssrCssVars.length
  709. ? genCssVarsFromList(ssrCssVars, shortId, isProd)
  710. : '', scopeId: scoped ? longId : undefined, slotted }, compilerOptions), { nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []), filename, sourceMap: true, onError: e => errors.push(e), onWarn: w => warnings.push(w) }));
  711. // inMap should be the map produced by ./parse.ts which is a simple line-only
  712. // mapping. If it is present, we need to adjust the final map and errors to
  713. // reflect the original line numbers.
  714. if (inMap) {
  715. if (map) {
  716. map = mapLines(inMap, map);
  717. }
  718. if (errors.length) {
  719. patchErrors(errors, source, inMap);
  720. }
  721. }
  722. const tips = warnings.map(w => {
  723. let msg = w.message;
  724. if (w.loc) {
  725. msg += `\n${shared.generateCodeFrame(source, w.loc.start.offset, w.loc.end.offset)}`;
  726. }
  727. return msg;
  728. });
  729. return { code, ast, preamble, source, errors, tips, map };
  730. }
  731. function mapLines(oldMap, newMap) {
  732. if (!oldMap)
  733. return newMap;
  734. if (!newMap)
  735. return oldMap;
  736. const oldMapConsumer = new sourceMap.SourceMapConsumer(oldMap);
  737. const newMapConsumer = new sourceMap.SourceMapConsumer(newMap);
  738. const mergedMapGenerator = new sourceMap.SourceMapGenerator();
  739. newMapConsumer.eachMapping(m => {
  740. if (m.originalLine == null) {
  741. return;
  742. }
  743. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  744. line: m.originalLine,
  745. column: m.originalColumn
  746. });
  747. if (origPosInOldMap.source == null) {
  748. return;
  749. }
  750. mergedMapGenerator.addMapping({
  751. generated: {
  752. line: m.generatedLine,
  753. column: m.generatedColumn
  754. },
  755. original: {
  756. line: origPosInOldMap.line,
  757. // use current column, since the oldMap produced by @vue/compiler-sfc
  758. // does not
  759. column: m.originalColumn
  760. },
  761. source: origPosInOldMap.source,
  762. name: origPosInOldMap.name
  763. });
  764. });
  765. // source-map's type definition is incomplete
  766. const generator = mergedMapGenerator;
  767. oldMapConsumer.sources.forEach((sourceFile) => {
  768. generator._sources.add(sourceFile);
  769. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  770. if (sourceContent != null) {
  771. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  772. }
  773. });
  774. generator._sourceRoot = oldMap.sourceRoot;
  775. generator._file = oldMap.file;
  776. return generator.toJSON();
  777. }
  778. function patchErrors(errors, source, inMap) {
  779. const originalSource = inMap.sourcesContent[0];
  780. const offset = originalSource.indexOf(source);
  781. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  782. errors.forEach(err => {
  783. if (err.loc) {
  784. err.loc.start.line += lineOffset;
  785. err.loc.start.offset += offset;
  786. if (err.loc.end !== err.loc.start) {
  787. err.loc.end.line += lineOffset;
  788. err.loc.end.offset += offset;
  789. }
  790. }
  791. });
  792. }
  793. const trimPlugin = () => {
  794. return {
  795. postcssPlugin: 'vue-sfc-trim',
  796. Once(root) {
  797. root.walk(({ type, raws }) => {
  798. if (type === 'rule' || type === 'atrule') {
  799. if (raws.before)
  800. raws.before = '\n';
  801. if ('after' in raws && raws.after)
  802. raws.after = '\n';
  803. }
  804. });
  805. }
  806. };
  807. };
  808. trimPlugin.postcss = true;
  809. const animationNameRE = /^(-\w+-)?animation-name$/;
  810. const animationRE = /^(-\w+-)?animation$/;
  811. const scopedPlugin = (id = '') => {
  812. const keyframes = Object.create(null);
  813. const shortId = id.replace(/^data-v-/, '');
  814. return {
  815. postcssPlugin: 'vue-sfc-scoped',
  816. Rule(rule) {
  817. processRule(id, rule);
  818. },
  819. AtRule(node) {
  820. if (/-?keyframes$/.test(node.name) &&
  821. !node.params.endsWith(`-${shortId}`)) {
  822. // register keyframes
  823. keyframes[node.params] = node.params = node.params + '-' + shortId;
  824. }
  825. },
  826. OnceExit(root) {
  827. if (Object.keys(keyframes).length) {
  828. // If keyframes are found in this <style>, find and rewrite animation names
  829. // in declarations.
  830. // Caveat: this only works for keyframes and animation rules in the same
  831. // <style> element.
  832. // individual animation-name declaration
  833. root.walkDecls(decl => {
  834. if (animationNameRE.test(decl.prop)) {
  835. decl.value = decl.value
  836. .split(',')
  837. .map(v => keyframes[v.trim()] || v.trim())
  838. .join(',');
  839. }
  840. // shorthand
  841. if (animationRE.test(decl.prop)) {
  842. decl.value = decl.value
  843. .split(',')
  844. .map(v => {
  845. const vals = v.trim().split(/\s+/);
  846. const i = vals.findIndex(val => keyframes[val]);
  847. if (i !== -1) {
  848. vals.splice(i, 1, keyframes[vals[i]]);
  849. return vals.join(' ');
  850. }
  851. else {
  852. return v;
  853. }
  854. })
  855. .join(',');
  856. }
  857. });
  858. }
  859. }
  860. };
  861. };
  862. const processedRules = new WeakSet();
  863. function processRule(id, rule) {
  864. if (processedRules.has(rule) ||
  865. (rule.parent &&
  866. rule.parent.type === 'atrule' &&
  867. /-?keyframes$/.test(rule.parent.name))) {
  868. return;
  869. }
  870. processedRules.add(rule);
  871. rule.selector = selectorParser__default(selectorRoot => {
  872. selectorRoot.each(selector => {
  873. rewriteSelector(id, selector, selectorRoot);
  874. });
  875. }).processSync(rule.selector);
  876. }
  877. function rewriteSelector(id, selector, selectorRoot, slotted = false) {
  878. let node = null;
  879. let shouldInject = true;
  880. // find the last child node to insert attribute selector
  881. selector.each(n => {
  882. // DEPRECATED ">>>" and "/deep/" combinator
  883. if (n.type === 'combinator' &&
  884. (n.value === '>>>' || n.value === '/deep/')) {
  885. n.value = ' ';
  886. n.spaces.before = n.spaces.after = '';
  887. warn(`the >>> and /deep/ combinators have been deprecated. ` +
  888. `Use :deep() instead.`);
  889. return false;
  890. }
  891. if (n.type === 'pseudo') {
  892. const { value } = n;
  893. // deep: inject [id] attribute at the node before the ::v-deep
  894. // combinator.
  895. if (value === ':deep' || value === '::v-deep') {
  896. if (n.nodes.length) {
  897. // .foo ::v-deep(.bar) -> .foo[xxxxxxx] .bar
  898. // replace the current node with ::v-deep's inner selector
  899. let last = n;
  900. n.nodes[0].each(ss => {
  901. selector.insertAfter(last, ss);
  902. last = ss;
  903. });
  904. // insert a space combinator before if it doesn't already have one
  905. const prev = selector.at(selector.index(n) - 1);
  906. if (!prev || !isSpaceCombinator(prev)) {
  907. selector.insertAfter(n, selectorParser__default.combinator({
  908. value: ' '
  909. }));
  910. }
  911. selector.removeChild(n);
  912. }
  913. else {
  914. // DEPRECATED usage
  915. // .foo ::v-deep .bar -> .foo[xxxxxxx] .bar
  916. warn(`::v-deep usage as a combinator has ` +
  917. `been deprecated. Use :deep(<inner-selector>) instead.`);
  918. const prev = selector.at(selector.index(n) - 1);
  919. if (prev && isSpaceCombinator(prev)) {
  920. selector.removeChild(prev);
  921. }
  922. selector.removeChild(n);
  923. }
  924. return false;
  925. }
  926. // slot: use selector inside `::v-slotted` and inject [id + '-s']
  927. // instead.
  928. // ::v-slotted(.foo) -> .foo[xxxxxxx-s]
  929. if (value === ':slotted' || value === '::v-slotted') {
  930. rewriteSelector(id, n.nodes[0], selectorRoot, true /* slotted */);
  931. let last = n;
  932. n.nodes[0].each(ss => {
  933. selector.insertAfter(last, ss);
  934. last = ss;
  935. });
  936. // selector.insertAfter(n, n.nodes[0])
  937. selector.removeChild(n);
  938. // since slotted attribute already scopes the selector there's no
  939. // need for the non-slot attribute.
  940. shouldInject = false;
  941. return false;
  942. }
  943. // global: replace with inner selector and do not inject [id].
  944. // ::v-global(.foo) -> .foo
  945. if (value === ':global' || value === '::v-global') {
  946. selectorRoot.insertAfter(selector, n.nodes[0]);
  947. selectorRoot.removeChild(selector);
  948. return false;
  949. }
  950. }
  951. if (n.type !== 'pseudo' && n.type !== 'combinator') {
  952. node = n;
  953. }
  954. });
  955. if (node) {
  956. node.spaces.after = '';
  957. }
  958. else {
  959. // For deep selectors & standalone pseudo selectors,
  960. // the attribute selectors are prepended rather than appended.
  961. // So all leading spaces must be eliminated to avoid problems.
  962. selector.first.spaces.before = '';
  963. }
  964. if (shouldInject) {
  965. const idToAdd = slotted ? id + '-s' : id;
  966. selector.insertAfter(
  967. // If node is null it means we need to inject [id] at the start
  968. // insertAfter can handle `null` here
  969. node, selectorParser__default.attribute({
  970. attribute: idToAdd,
  971. value: idToAdd,
  972. raws: {},
  973. quoteMark: `"`
  974. }));
  975. }
  976. }
  977. function isSpaceCombinator(node) {
  978. return node.type === 'combinator' && /^\s+$/.test(node.value);
  979. }
  980. scopedPlugin.postcss = true;
  981. // .scss/.sass processor
  982. const scss = (source, map, options, load = require) => {
  983. const nodeSass = load('sass');
  984. const finalOptions = Object.assign(Object.assign({}, options), { data: getSource(source, options.filename, options.additionalData), file: options.filename, outFile: options.filename, sourceMap: !!map });
  985. try {
  986. const result = nodeSass.renderSync(finalOptions);
  987. const dependencies = result.stats.includedFiles;
  988. if (map) {
  989. return {
  990. code: result.css.toString(),
  991. map: merge__default(map, JSON.parse(result.map.toString())),
  992. errors: [],
  993. dependencies
  994. };
  995. }
  996. return { code: result.css.toString(), errors: [], dependencies };
  997. }
  998. catch (e) {
  999. return { code: '', errors: [e], dependencies: [] };
  1000. }
  1001. };
  1002. const sass = (source, map, options, load) => scss(source, map, Object.assign(Object.assign({}, options), { indentedSyntax: true }), load);
  1003. // .less
  1004. const less = (source, map, options, load = require) => {
  1005. const nodeLess = load('less');
  1006. let result;
  1007. let error = null;
  1008. nodeLess.render(getSource(source, options.filename, options.additionalData), Object.assign(Object.assign({}, options), { syncImport: true }), (err, output) => {
  1009. error = err;
  1010. result = output;
  1011. });
  1012. if (error)
  1013. return { code: '', errors: [error], dependencies: [] };
  1014. const dependencies = result.imports;
  1015. if (map) {
  1016. return {
  1017. code: result.css.toString(),
  1018. map: merge__default(map, result.map),
  1019. errors: [],
  1020. dependencies: dependencies
  1021. };
  1022. }
  1023. return {
  1024. code: result.css.toString(),
  1025. errors: [],
  1026. dependencies: dependencies
  1027. };
  1028. };
  1029. // .styl
  1030. const styl = (source, map, options, load = require) => {
  1031. const nodeStylus = load('stylus');
  1032. try {
  1033. const ref = nodeStylus(source);
  1034. Object.keys(options).forEach(key => ref.set(key, options[key]));
  1035. if (map)
  1036. ref.set('sourcemap', { inline: false, comment: false });
  1037. const result = ref.render();
  1038. const dependencies = ref.deps();
  1039. if (map) {
  1040. return {
  1041. code: result,
  1042. map: merge__default(map, ref.sourcemap),
  1043. errors: [],
  1044. dependencies
  1045. };
  1046. }
  1047. return { code: result, errors: [], dependencies };
  1048. }
  1049. catch (e) {
  1050. return { code: '', errors: [e], dependencies: [] };
  1051. }
  1052. };
  1053. function getSource(source, filename, additionalData) {
  1054. if (!additionalData)
  1055. return source;
  1056. if (shared.isFunction(additionalData)) {
  1057. return additionalData(source, filename);
  1058. }
  1059. return additionalData + source;
  1060. }
  1061. const processors = {
  1062. less,
  1063. sass,
  1064. scss,
  1065. styl,
  1066. stylus: styl
  1067. };
  1068. function compileStyle(options) {
  1069. return doCompileStyle(Object.assign(Object.assign({}, options), { isAsync: false }));
  1070. }
  1071. function compileStyleAsync(options) {
  1072. return doCompileStyle(Object.assign(Object.assign({}, options), { isAsync: true }));
  1073. }
  1074. function doCompileStyle(options) {
  1075. const { filename, id, scoped = false, trim = true, isProd = false, modules = false, modulesOptions = {}, preprocessLang, postcssOptions, postcssPlugins } = options;
  1076. const preprocessor = preprocessLang && processors[preprocessLang];
  1077. const preProcessedSource = preprocessor && preprocess$1(options, preprocessor);
  1078. const map = preProcessedSource
  1079. ? preProcessedSource.map
  1080. : options.inMap || options.map;
  1081. const source = preProcessedSource ? preProcessedSource.code : options.source;
  1082. const shortId = id.replace(/^data-v-/, '');
  1083. const longId = `data-v-${shortId}`;
  1084. const plugins = (postcssPlugins || []).slice();
  1085. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  1086. if (trim) {
  1087. plugins.push(trimPlugin());
  1088. }
  1089. if (scoped) {
  1090. plugins.push(scopedPlugin(longId));
  1091. }
  1092. let cssModules;
  1093. if (modules) {
  1094. if (!options.isAsync) {
  1095. throw new Error('[@vue/compiler-sfc] `modules` option can only be used with compileStyleAsync().');
  1096. }
  1097. plugins.push(require('postcss-modules')(Object.assign(Object.assign({}, modulesOptions), { getJSON: (_cssFileName, json) => {
  1098. cssModules = json;
  1099. } })));
  1100. }
  1101. const postCSSOptions = Object.assign(Object.assign({}, postcssOptions), { to: filename, from: filename });
  1102. if (map) {
  1103. postCSSOptions.map = {
  1104. inline: false,
  1105. annotation: false,
  1106. prev: map
  1107. };
  1108. }
  1109. let result;
  1110. let code;
  1111. let outMap;
  1112. // stylus output include plain css. so need remove the repeat item
  1113. const dependencies = new Set(preProcessedSource ? preProcessedSource.dependencies : []);
  1114. // sass has filename self when provided filename option
  1115. dependencies.delete(filename);
  1116. const errors = [];
  1117. if (preProcessedSource && preProcessedSource.errors.length) {
  1118. errors.push(...preProcessedSource.errors);
  1119. }
  1120. const recordPlainCssDependencies = (messages) => {
  1121. messages.forEach(msg => {
  1122. if (msg.type === 'dependency') {
  1123. // postcss output path is absolute position path
  1124. dependencies.add(msg.file);
  1125. }
  1126. });
  1127. return dependencies;
  1128. };
  1129. try {
  1130. result = postcss__default(plugins).process(source, postCSSOptions);
  1131. // In async mode, return a promise.
  1132. if (options.isAsync) {
  1133. return result
  1134. .then(result => ({
  1135. code: result.css || '',
  1136. map: result.map && result.map.toJSON(),
  1137. errors,
  1138. modules: cssModules,
  1139. rawResult: result,
  1140. dependencies: recordPlainCssDependencies(result.messages)
  1141. }))
  1142. .catch(error => ({
  1143. code: '',
  1144. map: undefined,
  1145. errors: [...errors, error],
  1146. rawResult: undefined,
  1147. dependencies
  1148. }));
  1149. }
  1150. recordPlainCssDependencies(result.messages);
  1151. // force synchronous transform (we know we only have sync plugins)
  1152. code = result.css;
  1153. outMap = result.map;
  1154. }
  1155. catch (e) {
  1156. errors.push(e);
  1157. }
  1158. return {
  1159. code: code || ``,
  1160. map: outMap && outMap.toJSON(),
  1161. errors,
  1162. rawResult: result,
  1163. dependencies
  1164. };
  1165. }
  1166. function preprocess$1(options, preprocessor) {
  1167. return preprocessor(options.source, options.inMap || options.map, Object.assign({ filename: options.filename }, options.preprocessOptions), options.preprocessCustomRequire);
  1168. }
  1169. const defaultExportRE = /((?:^|\n|;)\s*)export(\s*)default/;
  1170. const namedDefaultExportRE = /((?:^|\n|;)\s*)export(.+)as(\s*)default/s;
  1171. const exportDefaultClassRE = /((?:^|\n|;)\s*)export\s+default\s+class\s+([\w$]+)/;
  1172. /**
  1173. * Utility for rewriting `export default` in a script block into a variable
  1174. * declaration so that we can inject things into it
  1175. */
  1176. function rewriteDefault(input, as, parserPlugins) {
  1177. if (!hasDefaultExport(input)) {
  1178. return input + `\nconst ${as} = {}`;
  1179. }
  1180. let replaced;
  1181. const classMatch = input.match(exportDefaultClassRE);
  1182. if (classMatch) {
  1183. replaced =
  1184. input.replace(exportDefaultClassRE, '$1class $2') +
  1185. `\nconst ${as} = ${classMatch[2]}`;
  1186. }
  1187. else {
  1188. replaced = input.replace(defaultExportRE, `$1const ${as} =`);
  1189. }
  1190. if (!hasDefaultExport(replaced)) {
  1191. return replaced;
  1192. }
  1193. // if the script somehow still contains `default export`, it probably has
  1194. // multi-line comments or template strings. fallback to a full parse.
  1195. const s = new MagicString__default(input);
  1196. const ast = parser.parse(input, {
  1197. sourceType: 'module',
  1198. plugins: parserPlugins
  1199. }).program.body;
  1200. ast.forEach(node => {
  1201. if (node.type === 'ExportDefaultDeclaration') {
  1202. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  1203. }
  1204. if (node.type === 'ExportNamedDeclaration') {
  1205. node.specifiers.forEach(specifier => {
  1206. if (specifier.type === 'ExportSpecifier' &&
  1207. specifier.exported.type === 'Identifier' &&
  1208. specifier.exported.name === 'default') {
  1209. const end = specifier.end;
  1210. s.overwrite(specifier.start, input.charAt(end) === ',' ? end + 1 : end, ``);
  1211. s.append(`\nconst ${as} = ${specifier.local.name}`);
  1212. }
  1213. });
  1214. }
  1215. });
  1216. return s.toString();
  1217. }
  1218. function hasDefaultExport(input) {
  1219. return defaultExportRE.test(input) || namedDefaultExportRE.test(input);
  1220. }
  1221. // Special compiler macros
  1222. const DEFINE_PROPS = 'defineProps';
  1223. const DEFINE_EMITS = 'defineEmits';
  1224. const DEFINE_EXPOSE = 'defineExpose';
  1225. const WITH_DEFAULTS = 'withDefaults';
  1226. const isBuiltInDir = shared.makeMap(`once,memo,if,else,else-if,slot,text,html,on,bind,model,show,cloak,is`);
  1227. /**
  1228. * Compile `<script setup>`
  1229. * It requires the whole SFC descriptor because we need to handle and merge
  1230. * normal `<script>` + `<script setup>` if both are present.
  1231. */
  1232. function compileScript(sfc, options) {
  1233. let { script, scriptSetup, source, filename } = sfc;
  1234. // feature flags
  1235. const enableRefTransform = !!options.refSugar || !!options.refTransform;
  1236. let refBindings;
  1237. // for backwards compat
  1238. if (!options) {
  1239. options = { id: '' };
  1240. }
  1241. if (!options.id) {
  1242. warnOnce(`compileScript now requires passing the \`id\` option.\n` +
  1243. `Upgrade your vite or vue-loader version for compatibility with ` +
  1244. `the latest experimental proposals.`);
  1245. }
  1246. const scopeId = options.id ? options.id.replace(/^data-v-/, '') : '';
  1247. const cssVars = sfc.cssVars;
  1248. const scriptLang = script && script.lang;
  1249. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  1250. const isTS = scriptLang === 'ts' ||
  1251. scriptLang === 'tsx' ||
  1252. scriptSetupLang === 'ts' ||
  1253. scriptSetupLang === 'tsx';
  1254. const plugins = [...shared.babelParserDefaultPlugins];
  1255. if (!isTS || scriptLang === 'tsx' || scriptSetupLang === 'tsx') {
  1256. plugins.push('jsx');
  1257. }
  1258. if (options.babelParserPlugins)
  1259. plugins.push(...options.babelParserPlugins);
  1260. if (isTS)
  1261. plugins.push('typescript', 'decorators-legacy');
  1262. if (!scriptSetup) {
  1263. if (!script) {
  1264. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  1265. }
  1266. if (scriptLang && !isTS && scriptLang !== 'jsx') {
  1267. // do not process non js/ts script blocks
  1268. return script;
  1269. }
  1270. try {
  1271. let content = script.content;
  1272. let map = script.map;
  1273. const scriptAst = parser.parse(content, {
  1274. plugins,
  1275. sourceType: 'module'
  1276. }).program;
  1277. const bindings = analyzeScriptBindings(scriptAst.body);
  1278. if (enableRefTransform && refTransform.shouldTransform(content)) {
  1279. const s = new MagicString__default(source);
  1280. const startOffset = script.loc.start.offset;
  1281. const endOffset = script.loc.end.offset;
  1282. const { importedHelpers } = refTransform.transformAST(scriptAst, s, startOffset);
  1283. if (importedHelpers.length) {
  1284. s.prepend(`import { ${importedHelpers
  1285. .map(h => `${h} as _${h}`)
  1286. .join(', ')} } from 'vue'\n`);
  1287. }
  1288. s.remove(0, startOffset);
  1289. s.remove(endOffset, source.length);
  1290. content = s.toString();
  1291. map = s.generateMap({
  1292. source: filename,
  1293. hires: true,
  1294. includeContent: true
  1295. });
  1296. }
  1297. if (cssVars.length) {
  1298. content = rewriteDefault(content, `__default__`, plugins);
  1299. content += genNormalScriptCssVarsCode(cssVars, bindings, scopeId, !!options.isProd);
  1300. content += `\nexport default __default__`;
  1301. }
  1302. return Object.assign(Object.assign({}, script), { content,
  1303. map,
  1304. bindings, scriptAst: scriptAst.body });
  1305. }
  1306. catch (e) {
  1307. // silently fallback if parse fails since user may be using custom
  1308. // babel syntax
  1309. return script;
  1310. }
  1311. }
  1312. if (script && scriptLang !== scriptSetupLang) {
  1313. throw new Error(`[@vue/compiler-sfc] <script> and <script setup> must have the same ` +
  1314. `language type.`);
  1315. }
  1316. if (scriptSetupLang && !isTS && scriptSetupLang !== 'jsx') {
  1317. // do not process non js/ts script blocks
  1318. return scriptSetup;
  1319. }
  1320. // metadata that needs to be returned
  1321. const bindingMetadata = {};
  1322. const defaultTempVar = `__default__`;
  1323. const helperImports = new Set();
  1324. const userImports = Object.create(null);
  1325. const userImportAlias = Object.create(null);
  1326. const setupBindings = Object.create(null);
  1327. let defaultExport;
  1328. let hasDefinePropsCall = false;
  1329. let hasDefineEmitCall = false;
  1330. let hasDefineExposeCall = false;
  1331. let propsRuntimeDecl;
  1332. let propsRuntimeDefaults;
  1333. let propsTypeDecl;
  1334. let propsTypeDeclRaw;
  1335. let propsIdentifier;
  1336. let emitsRuntimeDecl;
  1337. let emitsTypeDecl;
  1338. let emitsTypeDeclRaw;
  1339. let emitIdentifier;
  1340. let hasAwait = false;
  1341. let hasInlinedSsrRenderFn = false;
  1342. // props/emits declared via types
  1343. const typeDeclaredProps = {};
  1344. const typeDeclaredEmits = new Set();
  1345. // record declared types for runtime props type generation
  1346. const declaredTypes = {};
  1347. // magic-string state
  1348. const s = new MagicString__default(source);
  1349. const startOffset = scriptSetup.loc.start.offset;
  1350. const endOffset = scriptSetup.loc.end.offset;
  1351. const scriptStartOffset = script && script.loc.start.offset;
  1352. const scriptEndOffset = script && script.loc.end.offset;
  1353. function helper(key) {
  1354. helperImports.add(key);
  1355. return `_${key}`;
  1356. }
  1357. function parse(input, options, offset) {
  1358. try {
  1359. return parser.parse(input, options).program;
  1360. }
  1361. catch (e) {
  1362. e.message = `[@vue/compiler-sfc] ${e.message}\n\n${sfc.filename}\n${shared.generateCodeFrame(source, e.pos + offset, e.pos + offset + 1)}`;
  1363. throw e;
  1364. }
  1365. }
  1366. function error(msg, node, end = node.end + startOffset) {
  1367. throw new Error(`[@vue/compiler-sfc] ${msg}\n\n${sfc.filename}\n${shared.generateCodeFrame(source, node.start + startOffset, end)}`);
  1368. }
  1369. function registerUserImport(source, local, imported, isType, isFromSetup) {
  1370. if (source === 'vue' && imported) {
  1371. userImportAlias[imported] = local;
  1372. }
  1373. let isUsedInTemplate = true;
  1374. if (isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
  1375. isUsedInTemplate = new RegExp(
  1376. // #4274 escape $ since it's a special char in regex
  1377. // (and is the only regex special char that is valid in identifiers)
  1378. `[^\\w$_]${local.replace(/\$/g, '\\$')}[^\\w$_]`).test(resolveTemplateUsageCheckString(sfc));
  1379. }
  1380. userImports[local] = {
  1381. isType,
  1382. imported: imported || 'default',
  1383. source,
  1384. isFromSetup,
  1385. isUsedInTemplate
  1386. };
  1387. }
  1388. function processDefineProps(node) {
  1389. if (!isCallOf(node, DEFINE_PROPS)) {
  1390. return false;
  1391. }
  1392. if (hasDefinePropsCall) {
  1393. error(`duplicate ${DEFINE_PROPS}() call`, node);
  1394. }
  1395. hasDefinePropsCall = true;
  1396. propsRuntimeDecl = node.arguments[0];
  1397. // call has type parameters - infer runtime types from it
  1398. if (node.typeParameters) {
  1399. if (propsRuntimeDecl) {
  1400. error(`${DEFINE_PROPS}() cannot accept both type and non-type arguments ` +
  1401. `at the same time. Use one or the other.`, node);
  1402. }
  1403. propsTypeDeclRaw = node.typeParameters.params[0];
  1404. propsTypeDecl = resolveQualifiedType(propsTypeDeclRaw, node => node.type === 'TSTypeLiteral');
  1405. if (!propsTypeDecl) {
  1406. error(`type argument passed to ${DEFINE_PROPS}() must be a literal type, ` +
  1407. `or a reference to an interface or literal type.`, propsTypeDeclRaw);
  1408. }
  1409. }
  1410. return true;
  1411. }
  1412. function processWithDefaults(node) {
  1413. if (!isCallOf(node, WITH_DEFAULTS)) {
  1414. return false;
  1415. }
  1416. if (processDefineProps(node.arguments[0])) {
  1417. if (propsRuntimeDecl) {
  1418. error(`${WITH_DEFAULTS} can only be used with type-based ` +
  1419. `${DEFINE_PROPS} declaration.`, node);
  1420. }
  1421. propsRuntimeDefaults = node.arguments[1];
  1422. if (!propsRuntimeDefaults ||
  1423. propsRuntimeDefaults.type !== 'ObjectExpression') {
  1424. error(`The 2nd argument of ${WITH_DEFAULTS} must be an object literal.`, propsRuntimeDefaults || node);
  1425. }
  1426. }
  1427. else {
  1428. error(`${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`, node.arguments[0] || node);
  1429. }
  1430. return true;
  1431. }
  1432. function processDefineEmits(node) {
  1433. if (!isCallOf(node, DEFINE_EMITS)) {
  1434. return false;
  1435. }
  1436. if (hasDefineEmitCall) {
  1437. error(`duplicate ${DEFINE_EMITS}() call`, node);
  1438. }
  1439. hasDefineEmitCall = true;
  1440. emitsRuntimeDecl = node.arguments[0];
  1441. if (node.typeParameters) {
  1442. if (emitsRuntimeDecl) {
  1443. error(`${DEFINE_EMITS}() cannot accept both type and non-type arguments ` +
  1444. `at the same time. Use one or the other.`, node);
  1445. }
  1446. emitsTypeDeclRaw = node.typeParameters.params[0];
  1447. emitsTypeDecl = resolveQualifiedType(emitsTypeDeclRaw, node => node.type === 'TSFunctionType' || node.type === 'TSTypeLiteral');
  1448. if (!emitsTypeDecl) {
  1449. error(`type argument passed to ${DEFINE_EMITS}() must be a function type, ` +
  1450. `a literal type with call signatures, or a reference to the above types.`, emitsTypeDeclRaw);
  1451. }
  1452. }
  1453. return true;
  1454. }
  1455. function resolveQualifiedType(node, qualifier) {
  1456. if (qualifier(node)) {
  1457. return node;
  1458. }
  1459. if (node.type === 'TSTypeReference' &&
  1460. node.typeName.type === 'Identifier') {
  1461. const refName = node.typeName.name;
  1462. const isQualifiedType = (node) => {
  1463. if (node.type === 'TSInterfaceDeclaration' &&
  1464. node.id.name === refName) {
  1465. return node.body;
  1466. }
  1467. else if (node.type === 'TSTypeAliasDeclaration' &&
  1468. node.id.name === refName &&
  1469. qualifier(node.typeAnnotation)) {
  1470. return node.typeAnnotation;
  1471. }
  1472. else if (node.type === 'ExportNamedDeclaration' && node.declaration) {
  1473. return isQualifiedType(node.declaration);
  1474. }
  1475. };
  1476. for (const node of scriptSetupAst.body) {
  1477. const qualified = isQualifiedType(node);
  1478. if (qualified) {
  1479. return qualified;
  1480. }
  1481. }
  1482. }
  1483. }
  1484. function processDefineExpose(node) {
  1485. if (isCallOf(node, DEFINE_EXPOSE)) {
  1486. if (hasDefineExposeCall) {
  1487. error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  1488. }
  1489. hasDefineExposeCall = true;
  1490. return true;
  1491. }
  1492. return false;
  1493. }
  1494. function checkInvalidScopeReference(node, method) {
  1495. if (!node)
  1496. return;
  1497. CompilerDOM.walkIdentifiers(node, id => {
  1498. if (setupBindings[id.name]) {
  1499. error(`\`${method}()\` in <script setup> cannot reference locally ` +
  1500. `declared variables because it will be hoisted outside of the ` +
  1501. `setup() function. If your component options requires initialization ` +
  1502. `in the module scope, use a separate normal <script> to export ` +
  1503. `the options instead.`, id);
  1504. }
  1505. });
  1506. }
  1507. /**
  1508. * await foo()
  1509. * -->
  1510. * (([__temp, __restore] = withAsyncContext(() => foo())),__temp=await __temp,__restore(),__temp)
  1511. */
  1512. function processAwait(node, isStatement) {
  1513. s.overwrite(node.start + startOffset, node.argument.start + startOffset, `${isStatement ? `;` : ``}(([__temp,__restore]=${helper(`withAsyncContext`)}(()=>(`);
  1514. s.appendLeft(node.end + startOffset, `))),__temp=await __temp,__restore()${isStatement ? `` : `,__temp`})`);
  1515. }
  1516. /**
  1517. * check defaults. If the default object is an object literal with only
  1518. * static properties, we can directly generate more optimzied default
  1519. * decalrations. Otherwise we will have to fallback to runtime merging.
  1520. */
  1521. function checkStaticDefaults() {
  1522. return (propsRuntimeDefaults &&
  1523. propsRuntimeDefaults.type === 'ObjectExpression' &&
  1524. propsRuntimeDefaults.properties.every(node => (node.type === 'ObjectProperty' && !node.computed) ||
  1525. node.type === 'ObjectMethod'));
  1526. }
  1527. function genRuntimeProps(props) {
  1528. const keys = Object.keys(props);
  1529. if (!keys.length) {
  1530. return ``;
  1531. }
  1532. const hasStaticDefaults = checkStaticDefaults();
  1533. const scriptSetupSource = scriptSetup.content;
  1534. let propsDecls = `{
  1535. ${keys
  1536. .map(key => {
  1537. let defaultString;
  1538. if (hasStaticDefaults) {
  1539. const prop = propsRuntimeDefaults.properties.find((node) => node.key.name === key);
  1540. if (prop) {
  1541. if (prop.type === 'ObjectProperty') {
  1542. // prop has corresponding static default value
  1543. defaultString = `default: ${scriptSetupSource.slice(prop.value.start, prop.value.end)}`;
  1544. }
  1545. else {
  1546. defaultString = `default() ${scriptSetupSource.slice(prop.body.start, prop.body.end)}`;
  1547. }
  1548. }
  1549. }
  1550. {
  1551. const { type, required } = props[key];
  1552. return `${key}: { type: ${toRuntimeTypeString(type)}, required: ${required}${defaultString ? `, ${defaultString}` : ``} }`;
  1553. }
  1554. })
  1555. .join(',\n ')}\n }`;
  1556. if (propsRuntimeDefaults && !hasStaticDefaults) {
  1557. propsDecls = `${helper('mergeDefaults')}(${propsDecls}, ${source.slice(propsRuntimeDefaults.start + startOffset, propsRuntimeDefaults.end + startOffset)})`;
  1558. }
  1559. return `\n props: ${propsDecls},`;
  1560. }
  1561. function genSetupPropsType(node) {
  1562. const scriptSetupSource = scriptSetup.content;
  1563. if (checkStaticDefaults()) {
  1564. // if withDefaults() is used, we need to remove the optional flags
  1565. // on props that have default values
  1566. let res = `{ `;
  1567. const members = node.type === 'TSTypeLiteral' ? node.members : node.body;
  1568. for (const m of members) {
  1569. if ((m.type === 'TSPropertySignature' ||
  1570. m.type === 'TSMethodSignature') &&
  1571. m.typeAnnotation &&
  1572. m.key.type === 'Identifier') {
  1573. if (propsRuntimeDefaults.properties.some((p) => p.key.name === m.key.name)) {
  1574. res +=
  1575. m.key.name +
  1576. (m.type === 'TSMethodSignature' ? '()' : '') +
  1577. scriptSetupSource.slice(m.typeAnnotation.start, m.typeAnnotation.end) +
  1578. ', ';
  1579. }
  1580. else {
  1581. res += scriptSetupSource.slice(m.start, m.end) + `, `;
  1582. }
  1583. }
  1584. }
  1585. return (res.length ? res.slice(0, -2) : res) + ` }`;
  1586. }
  1587. else {
  1588. return scriptSetupSource.slice(node.start, node.end);
  1589. }
  1590. }
  1591. // 1. process normal <script> first if it exists
  1592. let scriptAst;
  1593. if (script) {
  1594. // import dedupe between <script> and <script setup>
  1595. scriptAst = parse(script.content, {
  1596. plugins,
  1597. sourceType: 'module'
  1598. }, scriptStartOffset);
  1599. for (const node of scriptAst.body) {
  1600. if (node.type === 'ImportDeclaration') {
  1601. // record imports for dedupe
  1602. for (const specifier of node.specifiers) {
  1603. const imported = specifier.type === 'ImportSpecifier' &&
  1604. specifier.imported.type === 'Identifier' &&
  1605. specifier.imported.name;
  1606. registerUserImport(node.source.value, specifier.local.name, imported, node.importKind === 'type', false);
  1607. }
  1608. }
  1609. else if (node.type === 'ExportDefaultDeclaration') {
  1610. // export default
  1611. defaultExport = node;
  1612. const start = node.start + scriptStartOffset;
  1613. const end = node.declaration.start + scriptStartOffset;
  1614. s.overwrite(start, end, `const ${defaultTempVar} = `);
  1615. }
  1616. else if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
  1617. const defaultSpecifier = node.specifiers.find(s => s.exported.type === 'Identifier' && s.exported.name === 'default');
  1618. if (defaultSpecifier) {
  1619. defaultExport = node;
  1620. // 1. remove specifier
  1621. if (node.specifiers.length > 1) {
  1622. s.remove(defaultSpecifier.start + scriptStartOffset, defaultSpecifier.end + scriptStartOffset);
  1623. }
  1624. else {
  1625. s.remove(node.start + scriptStartOffset, node.end + scriptStartOffset);
  1626. }
  1627. if (node.source) {
  1628. // export { x as default } from './x'
  1629. // rewrite to `import { x as __default__ } from './x'` and
  1630. // add to top
  1631. s.prepend(`import { ${defaultSpecifier.local.name} as ${defaultTempVar} } from '${node.source.value}'\n`);
  1632. }
  1633. else {
  1634. // export { x as default }
  1635. // rewrite to `const __default__ = x` and move to end
  1636. s.append(`\nconst ${defaultTempVar} = ${defaultSpecifier.local.name}\n`);
  1637. }
  1638. }
  1639. }
  1640. else if ((node.type === 'VariableDeclaration' ||
  1641. node.type === 'FunctionDeclaration' ||
  1642. node.type === 'ClassDeclaration') &&
  1643. !node.declare) {
  1644. walkDeclaration(node, setupBindings, userImportAlias);
  1645. }
  1646. }
  1647. // apply ref transform
  1648. if (enableRefTransform && refTransform.shouldTransform(script.content)) {
  1649. const { rootVars, importedHelpers } = refTransform.transformAST(scriptAst, s, scriptStartOffset);
  1650. refBindings = rootVars;
  1651. for (const h of importedHelpers) {
  1652. helperImports.add(h);
  1653. }
  1654. }
  1655. }
  1656. // 2. parse <script setup> and walk over top level statements
  1657. const scriptSetupAst = parse(scriptSetup.content, {
  1658. plugins: [
  1659. ...plugins,
  1660. // allow top level await but only inside <script setup>
  1661. 'topLevelAwait'
  1662. ],
  1663. sourceType: 'module'
  1664. }, startOffset);
  1665. for (const node of scriptSetupAst.body) {
  1666. const start = node.start + startOffset;
  1667. let end = node.end + startOffset;
  1668. // locate comment
  1669. if (node.trailingComments && node.trailingComments.length > 0) {
  1670. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  1671. end = lastCommentNode.end + startOffset;
  1672. }
  1673. // locate the end of whitespace between this statement and the next
  1674. while (end <= source.length) {
  1675. if (!/\s/.test(source.charAt(end))) {
  1676. break;
  1677. }
  1678. end++;
  1679. }
  1680. // (Dropped) `ref: x` bindings
  1681. if (node.type === 'LabeledStatement' &&
  1682. node.label.name === 'ref' &&
  1683. node.body.type === 'ExpressionStatement') {
  1684. error(`ref sugar using the label syntax was an experimental proposal and ` +
  1685. `has been dropped based on community feedback. Please check out ` +
  1686. `the new proposal at https://github.com/vuejs/rfcs/discussions/369`, node);
  1687. }
  1688. if (node.type === 'ImportDeclaration') {
  1689. // import declarations are moved to top
  1690. s.move(start, end, 0);
  1691. // dedupe imports
  1692. let removed = 0;
  1693. const removeSpecifier = (i) => {
  1694. const removeLeft = i > removed;
  1695. removed++;
  1696. const current = node.specifiers[i];
  1697. const next = node.specifiers[i + 1];
  1698. s.remove(removeLeft
  1699. ? node.specifiers[i - 1].end + startOffset
  1700. : current.start + startOffset, next && !removeLeft
  1701. ? next.start + startOffset
  1702. : current.end + startOffset);
  1703. };
  1704. for (let i = 0; i < node.specifiers.length; i++) {
  1705. const specifier = node.specifiers[i];
  1706. const local = specifier.local.name;
  1707. const imported = specifier.type === 'ImportSpecifier' &&
  1708. specifier.imported.type === 'Identifier' &&
  1709. specifier.imported.name;
  1710. const source = node.source.value;
  1711. const existing = userImports[local];
  1712. if (source === 'vue' &&
  1713. (imported === DEFINE_PROPS ||
  1714. imported === DEFINE_EMITS ||
  1715. imported === DEFINE_EXPOSE)) {
  1716. warnOnce(`\`${imported}\` is a compiler macro and no longer needs to be imported.`);
  1717. removeSpecifier(i);
  1718. }
  1719. else if (existing) {
  1720. if (existing.source === source && existing.imported === imported) {
  1721. // already imported in <script setup>, dedupe
  1722. removeSpecifier(i);
  1723. }
  1724. else {
  1725. error(`different imports aliased to same local name.`, specifier);
  1726. }
  1727. }
  1728. else {
  1729. registerUserImport(source, local, imported, node.importKind === 'type', true);
  1730. }
  1731. }
  1732. if (node.specifiers.length && removed === node.specifiers.length) {
  1733. s.remove(node.start + startOffset, node.end + startOffset);
  1734. }
  1735. }
  1736. if (node.type === 'ExpressionStatement') {
  1737. // process `defineProps` and `defineEmit(s)` calls
  1738. if (processDefineProps(node.expression) ||
  1739. processDefineEmits(node.expression) ||
  1740. processWithDefaults(node.expression)) {
  1741. s.remove(node.start + startOffset, node.end + startOffset);
  1742. }
  1743. else if (processDefineExpose(node.expression)) {
  1744. // defineExpose({}) -> expose({})
  1745. const callee = node.expression.callee;
  1746. s.overwrite(callee.start + startOffset, callee.end + startOffset, 'expose');
  1747. }
  1748. }
  1749. if (node.type === 'VariableDeclaration' && !node.declare) {
  1750. const total = node.declarations.length;
  1751. let left = total;
  1752. for (let i = 0; i < total; i++) {
  1753. const decl = node.declarations[i];
  1754. if (decl.init) {
  1755. // defineProps / defineEmits
  1756. const isDefineProps = processDefineProps(decl.init) || processWithDefaults(decl.init);
  1757. if (isDefineProps) {
  1758. propsIdentifier = scriptSetup.content.slice(decl.id.start, decl.id.end);
  1759. }
  1760. const isDefineEmits = processDefineEmits(decl.init);
  1761. if (isDefineEmits) {
  1762. emitIdentifier = scriptSetup.content.slice(decl.id.start, decl.id.end);
  1763. }
  1764. if (isDefineProps || isDefineEmits) {
  1765. if (left === 1) {
  1766. s.remove(node.start + startOffset, node.end + startOffset);
  1767. }
  1768. else {
  1769. let start = decl.start + startOffset;
  1770. let end = decl.end + startOffset;
  1771. if (i < total - 1) {
  1772. // not the last one, locate the start of the next
  1773. end = node.declarations[i + 1].start + startOffset;
  1774. }
  1775. else {
  1776. // last one, locate the end of the prev
  1777. start = node.declarations[i - 1].end + startOffset;
  1778. }
  1779. s.remove(start, end);
  1780. left--;
  1781. }
  1782. }
  1783. }
  1784. }
  1785. }
  1786. // walk decalrations to record declared bindings
  1787. if ((node.type === 'VariableDeclaration' ||
  1788. node.type === 'FunctionDeclaration' ||
  1789. node.type === 'ClassDeclaration') &&
  1790. !node.declare) {
  1791. walkDeclaration(node, setupBindings, userImportAlias);
  1792. }
  1793. // walk statements & named exports / variable declarations for top level
  1794. // await
  1795. if ((node.type === 'VariableDeclaration' && !node.declare) ||
  1796. node.type.endsWith('Statement')) {
  1797. estreeWalker.walk(node, {
  1798. enter(child, parent) {
  1799. if (CompilerDOM.isFunctionType(child)) {
  1800. this.skip();
  1801. }
  1802. if (child.type === 'AwaitExpression') {
  1803. hasAwait = true;
  1804. processAwait(child, parent.type === 'ExpressionStatement');
  1805. }
  1806. }
  1807. });
  1808. }
  1809. if ((node.type === 'ExportNamedDeclaration' && node.exportKind !== 'type') ||
  1810. node.type === 'ExportAllDeclaration' ||
  1811. node.type === 'ExportDefaultDeclaration') {
  1812. error(`<script setup> cannot contain ES module exports. ` +
  1813. `If you are using a previous version of <script setup>, please ` +
  1814. `consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.`, node);
  1815. }
  1816. if (isTS) {
  1817. // runtime enum
  1818. if (node.type === 'TSEnumDeclaration') {
  1819. registerBinding(setupBindings, node.id, "setup-const" /* SETUP_CONST */);
  1820. }
  1821. // move all Type declarations to outer scope
  1822. if (node.type.startsWith('TS') ||
  1823. (node.type === 'ExportNamedDeclaration' &&
  1824. node.exportKind === 'type') ||
  1825. (node.type === 'VariableDeclaration' && node.declare)) {
  1826. recordType(node, declaredTypes);
  1827. s.move(start, end, 0);
  1828. }
  1829. }
  1830. }
  1831. // 3. Apply ref sugar transform
  1832. if (enableRefTransform && refTransform.shouldTransform(scriptSetup.content)) {
  1833. const { rootVars, importedHelpers } = refTransform.transformAST(scriptSetupAst, s, startOffset, refBindings);
  1834. refBindings = refBindings ? [...refBindings, ...rootVars] : rootVars;
  1835. for (const h of importedHelpers) {
  1836. helperImports.add(h);
  1837. }
  1838. }
  1839. // 4. extract runtime props/emits code from setup context type
  1840. if (propsTypeDecl) {
  1841. extractRuntimeProps(propsTypeDecl, typeDeclaredProps, declaredTypes);
  1842. }
  1843. if (emitsTypeDecl) {
  1844. extractRuntimeEmits(emitsTypeDecl, typeDeclaredEmits);
  1845. }
  1846. // 5. check useOptions args to make sure it doesn't reference setup scope
  1847. // variables
  1848. checkInvalidScopeReference(propsRuntimeDecl, DEFINE_PROPS);
  1849. checkInvalidScopeReference(propsRuntimeDefaults, DEFINE_PROPS);
  1850. checkInvalidScopeReference(emitsRuntimeDecl, DEFINE_PROPS);
  1851. // 6. remove non-script content
  1852. if (script) {
  1853. if (startOffset < scriptStartOffset) {
  1854. // <script setup> before <script>
  1855. s.remove(0, startOffset);
  1856. s.remove(endOffset, scriptStartOffset);
  1857. s.remove(scriptEndOffset, source.length);
  1858. }
  1859. else {
  1860. // <script> before <script setup>
  1861. s.remove(0, scriptStartOffset);
  1862. s.remove(scriptEndOffset, startOffset);
  1863. s.remove(endOffset, source.length);
  1864. }
  1865. }
  1866. else {
  1867. // only <script setup>
  1868. s.remove(0, startOffset);
  1869. s.remove(endOffset, source.length);
  1870. }
  1871. // 7. analyze binding metadata
  1872. if (scriptAst) {
  1873. Object.assign(bindingMetadata, analyzeScriptBindings(scriptAst.body));
  1874. }
  1875. if (propsRuntimeDecl) {
  1876. for (const key of getObjectOrArrayExpressionKeys(propsRuntimeDecl)) {
  1877. bindingMetadata[key] = "props" /* PROPS */;
  1878. }
  1879. }
  1880. for (const key in typeDeclaredProps) {
  1881. bindingMetadata[key] = "props" /* PROPS */;
  1882. }
  1883. for (const [key, { isType, imported, source }] of Object.entries(userImports)) {
  1884. if (isType)
  1885. continue;
  1886. bindingMetadata[key] =
  1887. (imported === 'default' && source.endsWith('.vue')) || source === 'vue'
  1888. ? "setup-const" /* SETUP_CONST */
  1889. : "setup-maybe-ref" /* SETUP_MAYBE_REF */;
  1890. }
  1891. for (const key in setupBindings) {
  1892. bindingMetadata[key] = setupBindings[key];
  1893. }
  1894. // known ref bindings
  1895. if (refBindings) {
  1896. for (const key of refBindings) {
  1897. bindingMetadata[key] = "setup-ref" /* SETUP_REF */;
  1898. }
  1899. }
  1900. // 8. inject `useCssVars` calls
  1901. if (cssVars.length) {
  1902. helperImports.add(CSS_VARS_HELPER);
  1903. helperImports.add('unref');
  1904. s.prependRight(startOffset, `\n${genCssVarsCode(cssVars, bindingMetadata, scopeId, !!options.isProd)}\n`);
  1905. }
  1906. // 9. finalize setup() argument signature
  1907. let args = `__props`;
  1908. if (propsTypeDecl) {
  1909. // mark as any and only cast on assignment
  1910. // since the user defined complex types may be incompatible with the
  1911. // inferred type from generated runtime declarations
  1912. args += `: any`;
  1913. }
  1914. // inject user assignment of props
  1915. // we use a default __props so that template expressions referencing props
  1916. // can use it directly
  1917. if (propsIdentifier) {
  1918. s.prependRight(startOffset, `\nconst ${propsIdentifier} = __props${propsTypeDecl ? ` as ${genSetupPropsType(propsTypeDecl)}` : ``}`);
  1919. }
  1920. // inject temp variables for async context preservation
  1921. if (hasAwait) {
  1922. const any = isTS ? `: any` : ``;
  1923. s.prependRight(startOffset, `\nlet __temp${any}, __restore${any}\n`);
  1924. }
  1925. const destructureElements = hasDefineExposeCall || !options.inlineTemplate ? [`expose`] : [];
  1926. if (emitIdentifier) {
  1927. destructureElements.push(emitIdentifier === `emit` ? `emit` : `emit: ${emitIdentifier}`);
  1928. }
  1929. if (destructureElements.length) {
  1930. args += `, { ${destructureElements.join(', ')} }`;
  1931. if (emitsTypeDecl) {
  1932. args += `: { emit: (${scriptSetup.content.slice(emitsTypeDecl.start, emitsTypeDecl.end)}), expose: any, slots: any, attrs: any }`;
  1933. }
  1934. }
  1935. // 10. generate return statement
  1936. let returned;
  1937. if (options.inlineTemplate) {
  1938. if (sfc.template && !sfc.template.src) {
  1939. if (options.templateOptions && options.templateOptions.ssr) {
  1940. hasInlinedSsrRenderFn = true;
  1941. }
  1942. // inline render function mode - we are going to compile the template and
  1943. // inline it right here
  1944. const { code, ast, preamble, tips, errors } = compileTemplate(Object.assign(Object.assign({ filename, source: sfc.template.content, inMap: sfc.template.map }, options.templateOptions), { id: scopeId, scoped: sfc.styles.some(s => s.scoped), isProd: options.isProd, ssrCssVars: sfc.cssVars, compilerOptions: Object.assign(Object.assign({}, (options.templateOptions &&
  1945. options.templateOptions.compilerOptions)), { inline: true, isTS,
  1946. bindingMetadata }) }));
  1947. if (tips.length) {
  1948. tips.forEach(warnOnce);
  1949. }
  1950. const err = errors[0];
  1951. if (typeof err === 'string') {
  1952. throw new Error(err);
  1953. }
  1954. else if (err) {
  1955. if (err.loc) {
  1956. err.message +=
  1957. `\n\n` +
  1958. sfc.filename +
  1959. '\n' +
  1960. shared.generateCodeFrame(source, err.loc.start.offset, err.loc.end.offset) +
  1961. `\n`;
  1962. }
  1963. throw err;
  1964. }
  1965. if (preamble) {
  1966. s.prepend(preamble);
  1967. }
  1968. // avoid duplicated unref import
  1969. // as this may get injected by the render function preamble OR the
  1970. // css vars codegen
  1971. if (ast && ast.helpers.includes(CompilerDOM.UNREF)) {
  1972. helperImports.delete('unref');
  1973. }
  1974. returned = code;
  1975. }
  1976. else {
  1977. returned = `() => {}`;
  1978. }
  1979. }
  1980. else {
  1981. // return bindings from setup
  1982. const allBindings = Object.assign({}, setupBindings);
  1983. for (const key in userImports) {
  1984. if (!userImports[key].isType && userImports[key].isUsedInTemplate) {
  1985. allBindings[key] = true;
  1986. }
  1987. }
  1988. returned = `{ ${Object.keys(allBindings).join(', ')} }`;
  1989. }
  1990. if (!options.inlineTemplate && !false) {
  1991. // in non-inline mode, the `__isScriptSetup: true` flag is used by
  1992. // componentPublicInstance proxy to allow properties that start with $ or _
  1993. s.appendRight(endOffset, `\nconst __returned__ = ${returned}\n` +
  1994. `Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })\n` +
  1995. `return __returned__` +
  1996. `\n}\n\n`);
  1997. }
  1998. else {
  1999. s.appendRight(endOffset, `\nreturn ${returned}\n}\n\n`);
  2000. }
  2001. // 11. finalize default export
  2002. let runtimeOptions = ``;
  2003. if (hasInlinedSsrRenderFn) {
  2004. runtimeOptions += `\n __ssrInlineRender: true,`;
  2005. }
  2006. if (propsRuntimeDecl) {
  2007. runtimeOptions += `\n props: ${scriptSetup.content
  2008. .slice(propsRuntimeDecl.start, propsRuntimeDecl.end)
  2009. .trim()},`;
  2010. }
  2011. else if (propsTypeDecl) {
  2012. runtimeOptions += genRuntimeProps(typeDeclaredProps);
  2013. }
  2014. if (emitsRuntimeDecl) {
  2015. runtimeOptions += `\n emits: ${scriptSetup.content
  2016. .slice(emitsRuntimeDecl.start, emitsRuntimeDecl.end)
  2017. .trim()},`;
  2018. }
  2019. else if (emitsTypeDecl) {
  2020. runtimeOptions += genRuntimeEmits(typeDeclaredEmits);
  2021. }
  2022. // <script setup> components are closed by default. If the user did not
  2023. // explicitly call `defineExpose`, call expose() with no args.
  2024. const exposeCall = hasDefineExposeCall || options.inlineTemplate ? `` : ` expose()\n`;
  2025. if (isTS) {
  2026. // for TS, make sure the exported type is still valid type with
  2027. // correct props information
  2028. // we have to use object spread for types to be merged properly
  2029. // user's TS setting should compile it down to proper targets
  2030. const def = defaultExport ? `\n ...${defaultTempVar},` : ``;
  2031. // wrap setup code with function.
  2032. // export the content of <script setup> as a named export, `setup`.
  2033. // this allows `import { setup } from '*.vue'` for testing purposes.
  2034. if (defaultExport) {
  2035. s.prependLeft(startOffset, `\n${hasAwait ? `async ` : ``}function setup(${args}) {\n`);
  2036. s.append(`\nexport default /*#__PURE__*/${helper(`defineComponent`)}({${def}${runtimeOptions}\n setup})`);
  2037. }
  2038. else {
  2039. s.prependLeft(startOffset, `\nexport default /*#__PURE__*/${helper(`defineComponent`)}({${def}${runtimeOptions}\n ${hasAwait ? `async ` : ``}setup(${args}) {\n${exposeCall}`);
  2040. s.appendRight(endOffset, `})`);
  2041. }
  2042. }
  2043. else {
  2044. if (defaultExport) {
  2045. // can't rely on spread operator in non ts mode
  2046. s.prependLeft(startOffset, `\n${hasAwait ? `async ` : ``}function setup(${args}) {\n`);
  2047. s.append(`\nexport default /*#__PURE__*/ Object.assign(${defaultTempVar}, {${runtimeOptions}\n setup\n})\n`);
  2048. }
  2049. else {
  2050. s.prependLeft(startOffset, `\nexport default {${runtimeOptions}\n ` +
  2051. `${hasAwait ? `async ` : ``}setup(${args}) {\n${exposeCall}`);
  2052. s.appendRight(endOffset, `}`);
  2053. }
  2054. }
  2055. // 12. finalize Vue helper imports
  2056. if (helperImports.size > 0) {
  2057. s.prepend(`import { ${[...helperImports]
  2058. .map(h => `${h} as _${h}`)
  2059. .join(', ')} } from 'vue'\n`);
  2060. }
  2061. s.trim();
  2062. return Object.assign(Object.assign({}, scriptSetup), { bindings: bindingMetadata, content: s.toString(), map: s.generateMap({
  2063. source: filename,
  2064. hires: true,
  2065. includeContent: true
  2066. }), scriptAst: scriptAst === null || scriptAst === void 0 ? void 0 : scriptAst.body, scriptSetupAst: scriptSetupAst === null || scriptSetupAst === void 0 ? void 0 : scriptSetupAst.body });
  2067. }
  2068. function registerBinding(bindings, node, type) {
  2069. bindings[node.name] = type;
  2070. }
  2071. function walkDeclaration(node, bindings, userImportAlias) {
  2072. if (node.type === 'VariableDeclaration') {
  2073. const isConst = node.kind === 'const';
  2074. // export const foo = ...
  2075. for (const { id, init } of node.declarations) {
  2076. const isDefineCall = !!(isConst &&
  2077. isCallOf(init, c => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS));
  2078. if (id.type === 'Identifier') {
  2079. let bindingType;
  2080. const userReactiveBinding = userImportAlias['reactive'] || 'reactive';
  2081. if (isCallOf(init, userReactiveBinding)) {
  2082. // treat reactive() calls as let since it's meant to be mutable
  2083. bindingType = "setup-let" /* SETUP_LET */;
  2084. }
  2085. else if (
  2086. // if a declaration is a const literal, we can mark it so that
  2087. // the generated render fn code doesn't need to unref() it
  2088. isDefineCall ||
  2089. (isConst && canNeverBeRef(init, userReactiveBinding))) {
  2090. bindingType = "setup-const" /* SETUP_CONST */;
  2091. }
  2092. else if (isConst) {
  2093. if (isCallOf(init, userImportAlias['ref'] || 'ref')) {
  2094. bindingType = "setup-ref" /* SETUP_REF */;
  2095. }
  2096. else {
  2097. bindingType = "setup-maybe-ref" /* SETUP_MAYBE_REF */;
  2098. }
  2099. }
  2100. else {
  2101. bindingType = "setup-let" /* SETUP_LET */;
  2102. }
  2103. registerBinding(bindings, id, bindingType);
  2104. }
  2105. else if (id.type === 'ObjectPattern') {
  2106. walkObjectPattern(id, bindings, isConst, isDefineCall);
  2107. }
  2108. else if (id.type === 'ArrayPattern') {
  2109. walkArrayPattern(id, bindings, isConst, isDefineCall);
  2110. }
  2111. }
  2112. }
  2113. else if (node.type === 'FunctionDeclaration' ||
  2114. node.type === 'ClassDeclaration') {
  2115. // export function foo() {} / export class Foo {}
  2116. // export declarations must be named.
  2117. bindings[node.id.name] = "setup-const" /* SETUP_CONST */;
  2118. }
  2119. }
  2120. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  2121. for (const p of node.properties) {
  2122. if (p.type === 'ObjectProperty') {
  2123. // key can only be Identifier in ObjectPattern
  2124. if (p.key.type === 'Identifier') {
  2125. if (p.key === p.value) {
  2126. // const { x } = ...
  2127. const type = isDefineCall
  2128. ? "setup-const" /* SETUP_CONST */
  2129. : isConst
  2130. ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
  2131. : "setup-let" /* SETUP_LET */;
  2132. registerBinding(bindings, p.key, type);
  2133. }
  2134. else {
  2135. walkPattern(p.value, bindings, isConst, isDefineCall);
  2136. }
  2137. }
  2138. }
  2139. else {
  2140. // ...rest
  2141. // argument can only be identifer when destructuring
  2142. const type = isConst ? "setup-const" /* SETUP_CONST */ : "setup-let" /* SETUP_LET */;
  2143. registerBinding(bindings, p.argument, type);
  2144. }
  2145. }
  2146. }
  2147. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  2148. for (const e of node.elements) {
  2149. e && walkPattern(e, bindings, isConst, isDefineCall);
  2150. }
  2151. }
  2152. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  2153. if (node.type === 'Identifier') {
  2154. const type = isDefineCall
  2155. ? "setup-const" /* SETUP_CONST */
  2156. : isConst
  2157. ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
  2158. : "setup-let" /* SETUP_LET */;
  2159. registerBinding(bindings, node, type);
  2160. }
  2161. else if (node.type === 'RestElement') {
  2162. // argument can only be identifer when destructuring
  2163. const type = isConst ? "setup-const" /* SETUP_CONST */ : "setup-let" /* SETUP_LET */;
  2164. registerBinding(bindings, node.argument, type);
  2165. }
  2166. else if (node.type === 'ObjectPattern') {
  2167. walkObjectPattern(node, bindings, isConst);
  2168. }
  2169. else if (node.type === 'ArrayPattern') {
  2170. walkArrayPattern(node, bindings, isConst);
  2171. }
  2172. else if (node.type === 'AssignmentPattern') {
  2173. if (node.left.type === 'Identifier') {
  2174. const type = isDefineCall
  2175. ? "setup-const" /* SETUP_CONST */
  2176. : isConst
  2177. ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
  2178. : "setup-let" /* SETUP_LET */;
  2179. registerBinding(bindings, node.left, type);
  2180. }
  2181. else {
  2182. walkPattern(node.left, bindings, isConst);
  2183. }
  2184. }
  2185. }
  2186. function recordType(node, declaredTypes) {
  2187. if (node.type === 'TSInterfaceDeclaration') {
  2188. declaredTypes[node.id.name] = [`Object`];
  2189. }
  2190. else if (node.type === 'TSTypeAliasDeclaration') {
  2191. declaredTypes[node.id.name] = inferRuntimeType(node.typeAnnotation, declaredTypes);
  2192. }
  2193. else if (node.type === 'ExportNamedDeclaration' && node.declaration) {
  2194. recordType(node.declaration, declaredTypes);
  2195. }
  2196. }
  2197. function extractRuntimeProps(node, props, declaredTypes) {
  2198. const members = node.type === 'TSTypeLiteral' ? node.members : node.body;
  2199. for (const m of members) {
  2200. if ((m.type === 'TSPropertySignature' || m.type === 'TSMethodSignature') &&
  2201. m.key.type === 'Identifier') {
  2202. let type;
  2203. {
  2204. if (m.type === 'TSMethodSignature') {
  2205. type = ['Function'];
  2206. }
  2207. else if (m.typeAnnotation) {
  2208. type = inferRuntimeType(m.typeAnnotation.typeAnnotation, declaredTypes);
  2209. }
  2210. }
  2211. props[m.key.name] = {
  2212. key: m.key.name,
  2213. required: !m.optional,
  2214. type: type || [`null`]
  2215. };
  2216. }
  2217. }
  2218. }
  2219. function inferRuntimeType(node, declaredTypes) {
  2220. switch (node.type) {
  2221. case 'TSStringKeyword':
  2222. return ['String'];
  2223. case 'TSNumberKeyword':
  2224. return ['Number'];
  2225. case 'TSBooleanKeyword':
  2226. return ['Boolean'];
  2227. case 'TSObjectKeyword':
  2228. return ['Object'];
  2229. case 'TSTypeLiteral':
  2230. // TODO (nice to have) generate runtime property validation
  2231. return ['Object'];
  2232. case 'TSFunctionType':
  2233. return ['Function'];
  2234. case 'TSArrayType':
  2235. case 'TSTupleType':
  2236. // TODO (nice to have) generate runtime element type/length checks
  2237. return ['Array'];
  2238. case 'TSLiteralType':
  2239. switch (node.literal.type) {
  2240. case 'StringLiteral':
  2241. return ['String'];
  2242. case 'BooleanLiteral':
  2243. return ['Boolean'];
  2244. case 'NumericLiteral':
  2245. case 'BigIntLiteral':
  2246. return ['Number'];
  2247. default:
  2248. return [`null`];
  2249. }
  2250. case 'TSTypeReference':
  2251. if (node.typeName.type === 'Identifier') {
  2252. if (declaredTypes[node.typeName.name]) {
  2253. return declaredTypes[node.typeName.name];
  2254. }
  2255. switch (node.typeName.name) {
  2256. case 'Array':
  2257. case 'Function':
  2258. case 'Object':
  2259. case 'Set':
  2260. case 'Map':
  2261. case 'WeakSet':
  2262. case 'WeakMap':
  2263. return [node.typeName.name];
  2264. case 'Record':
  2265. case 'Partial':
  2266. case 'Readonly':
  2267. case 'Pick':
  2268. case 'Omit':
  2269. case 'Exclude':
  2270. case 'Extract':
  2271. case 'Required':
  2272. case 'InstanceType':
  2273. return ['Object'];
  2274. }
  2275. }
  2276. return [`null`];
  2277. case 'TSParenthesizedType':
  2278. return inferRuntimeType(node.typeAnnotation, declaredTypes);
  2279. case 'TSUnionType':
  2280. return [
  2281. ...new Set([].concat(...node.types.map(t => inferRuntimeType(t, declaredTypes))))
  2282. ];
  2283. case 'TSIntersectionType':
  2284. return ['Object'];
  2285. default:
  2286. return [`null`]; // no runtime check
  2287. }
  2288. }
  2289. function toRuntimeTypeString(types) {
  2290. return types.length > 1 ? `[${types.join(', ')}]` : types[0];
  2291. }
  2292. function extractRuntimeEmits(node, emits) {
  2293. if (node.type === 'TSTypeLiteral' || node.type === 'TSInterfaceBody') {
  2294. const members = node.type === 'TSTypeLiteral' ? node.members : node.body;
  2295. for (let t of members) {
  2296. if (t.type === 'TSCallSignatureDeclaration') {
  2297. extractEventNames(t.parameters[0], emits);
  2298. }
  2299. }
  2300. return;
  2301. }
  2302. else {
  2303. extractEventNames(node.parameters[0], emits);
  2304. }
  2305. }
  2306. function extractEventNames(eventName, emits) {
  2307. if (eventName.type === 'Identifier' &&
  2308. eventName.typeAnnotation &&
  2309. eventName.typeAnnotation.type === 'TSTypeAnnotation') {
  2310. const typeNode = eventName.typeAnnotation.typeAnnotation;
  2311. if (typeNode.type === 'TSLiteralType') {
  2312. if (typeNode.literal.type !== 'UnaryExpression') {
  2313. emits.add(String(typeNode.literal.value));
  2314. }
  2315. }
  2316. else if (typeNode.type === 'TSUnionType') {
  2317. for (const t of typeNode.types) {
  2318. if (t.type === 'TSLiteralType' &&
  2319. t.literal.type !== 'UnaryExpression') {
  2320. emits.add(String(t.literal.value));
  2321. }
  2322. }
  2323. }
  2324. }
  2325. }
  2326. function genRuntimeEmits(emits) {
  2327. return emits.size
  2328. ? `\n emits: [${Array.from(emits)
  2329. .map(p => JSON.stringify(p))
  2330. .join(', ')}],`
  2331. : ``;
  2332. }
  2333. function isCallOf(node, test) {
  2334. return !!(node &&
  2335. node.type === 'CallExpression' &&
  2336. node.callee.type === 'Identifier' &&
  2337. (typeof test === 'string'
  2338. ? node.callee.name === test
  2339. : test(node.callee.name)));
  2340. }
  2341. function canNeverBeRef(node, userReactiveImport) {
  2342. if (isCallOf(node, userReactiveImport)) {
  2343. return true;
  2344. }
  2345. switch (node.type) {
  2346. case 'UnaryExpression':
  2347. case 'BinaryExpression':
  2348. case 'ArrayExpression':
  2349. case 'ObjectExpression':
  2350. case 'FunctionExpression':
  2351. case 'ArrowFunctionExpression':
  2352. case 'UpdateExpression':
  2353. case 'ClassExpression':
  2354. case 'TaggedTemplateExpression':
  2355. return true;
  2356. case 'SequenceExpression':
  2357. return canNeverBeRef(node.expressions[node.expressions.length - 1], userReactiveImport);
  2358. default:
  2359. if (node.type.endsWith('Literal')) {
  2360. return true;
  2361. }
  2362. return false;
  2363. }
  2364. }
  2365. /**
  2366. * Analyze bindings in normal `<script>`
  2367. * Note that `compileScriptSetup` already analyzes bindings as part of its
  2368. * compilation process so this should only be used on single `<script>` SFCs.
  2369. */
  2370. function analyzeScriptBindings(ast) {
  2371. for (const node of ast) {
  2372. if (node.type === 'ExportDefaultDeclaration' &&
  2373. node.declaration.type === 'ObjectExpression') {
  2374. return analyzeBindingsFromOptions(node.declaration);
  2375. }
  2376. }
  2377. return {};
  2378. }
  2379. function analyzeBindingsFromOptions(node) {
  2380. const bindings = {};
  2381. // #3270, #3275
  2382. // mark non-script-setup so we don't resolve components/directives from these
  2383. Object.defineProperty(bindings, '__isScriptSetup', {
  2384. enumerable: false,
  2385. value: false
  2386. });
  2387. for (const property of node.properties) {
  2388. if (property.type === 'ObjectProperty' &&
  2389. !property.computed &&
  2390. property.key.type === 'Identifier') {
  2391. // props
  2392. if (property.key.name === 'props') {
  2393. // props: ['foo']
  2394. // props: { foo: ... }
  2395. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  2396. bindings[key] = "props" /* PROPS */;
  2397. }
  2398. }
  2399. // inject
  2400. else if (property.key.name === 'inject') {
  2401. // inject: ['foo']
  2402. // inject: { foo: {} }
  2403. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  2404. bindings[key] = "options" /* OPTIONS */;
  2405. }
  2406. }
  2407. // computed & methods
  2408. else if (property.value.type === 'ObjectExpression' &&
  2409. (property.key.name === 'computed' || property.key.name === 'methods')) {
  2410. // methods: { foo() {} }
  2411. // computed: { foo() {} }
  2412. for (const key of getObjectExpressionKeys(property.value)) {
  2413. bindings[key] = "options" /* OPTIONS */;
  2414. }
  2415. }
  2416. }
  2417. // setup & data
  2418. else if (property.type === 'ObjectMethod' &&
  2419. property.key.type === 'Identifier' &&
  2420. (property.key.name === 'setup' || property.key.name === 'data')) {
  2421. for (const bodyItem of property.body.body) {
  2422. // setup() {
  2423. // return {
  2424. // foo: null
  2425. // }
  2426. // }
  2427. if (bodyItem.type === 'ReturnStatement' &&
  2428. bodyItem.argument &&
  2429. bodyItem.argument.type === 'ObjectExpression') {
  2430. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  2431. bindings[key] =
  2432. property.key.name === 'setup'
  2433. ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
  2434. : "data" /* DATA */;
  2435. }
  2436. }
  2437. }
  2438. }
  2439. }
  2440. return bindings;
  2441. }
  2442. function getObjectExpressionKeys(node) {
  2443. const keys = [];
  2444. for (const prop of node.properties) {
  2445. if ((prop.type === 'ObjectProperty' || prop.type === 'ObjectMethod') &&
  2446. !prop.computed) {
  2447. if (prop.key.type === 'Identifier') {
  2448. keys.push(prop.key.name);
  2449. }
  2450. else if (prop.key.type === 'StringLiteral') {
  2451. keys.push(prop.key.value);
  2452. }
  2453. }
  2454. }
  2455. return keys;
  2456. }
  2457. function getArrayExpressionKeys(node) {
  2458. const keys = [];
  2459. for (const element of node.elements) {
  2460. if (element && element.type === 'StringLiteral') {
  2461. keys.push(element.value);
  2462. }
  2463. }
  2464. return keys;
  2465. }
  2466. function getObjectOrArrayExpressionKeys(value) {
  2467. if (value.type === 'ArrayExpression') {
  2468. return getArrayExpressionKeys(value);
  2469. }
  2470. if (value.type === 'ObjectExpression') {
  2471. return getObjectExpressionKeys(value);
  2472. }
  2473. return [];
  2474. }
  2475. const templateUsageCheckCache = createCache();
  2476. function resolveTemplateUsageCheckString(sfc) {
  2477. const { content, ast } = sfc.template;
  2478. const cached = templateUsageCheckCache.get(content);
  2479. if (cached) {
  2480. return cached;
  2481. }
  2482. let code = '';
  2483. CompilerDOM.transform(CompilerDOM.createRoot([ast]), {
  2484. nodeTransforms: [
  2485. node => {
  2486. if (node.type === 1 /* ELEMENT */) {
  2487. if (!CompilerDOM.parserOptions.isNativeTag(node.tag) &&
  2488. !CompilerDOM.parserOptions.isBuiltInComponent(node.tag)) {
  2489. code += `,${shared.camelize(node.tag)},${shared.capitalize(shared.camelize(node.tag))}`;
  2490. }
  2491. for (let i = 0; i < node.props.length; i++) {
  2492. const prop = node.props[i];
  2493. if (prop.type === 7 /* DIRECTIVE */) {
  2494. if (!isBuiltInDir(prop.name)) {
  2495. code += `,v${shared.capitalize(shared.camelize(prop.name))}`;
  2496. }
  2497. if (prop.exp) {
  2498. code += `,${stripStrings(prop.exp.content)}`;
  2499. }
  2500. }
  2501. }
  2502. }
  2503. else if (node.type === 5 /* INTERPOLATION */) {
  2504. code += `,${stripStrings(node.content.content)}`;
  2505. }
  2506. }
  2507. ]
  2508. });
  2509. code += ';';
  2510. templateUsageCheckCache.set(content, code);
  2511. return code;
  2512. }
  2513. function stripStrings(exp) {
  2514. return exp
  2515. .replace(/'[^']+'|"[^"]+"/g, '')
  2516. .replace(/`[^`]+`/g, stripTemplateString);
  2517. }
  2518. function stripTemplateString(str) {
  2519. const interpMatch = str.match(/\${[^}]+}/g);
  2520. if (interpMatch) {
  2521. return interpMatch.map(m => m.slice(2, -1)).join(',');
  2522. }
  2523. return '';
  2524. }
  2525. exports.extractIdentifiers = compilerCore.extractIdentifiers;
  2526. exports.generateCodeFrame = compilerCore.generateCodeFrame;
  2527. exports.isInDestructureAssignment = compilerCore.isInDestructureAssignment;
  2528. exports.isStaticProperty = compilerCore.isStaticProperty;
  2529. exports.walkIdentifiers = compilerCore.walkIdentifiers;
  2530. exports.MagicString = MagicString__default;
  2531. exports.babelParse = parser.parse;
  2532. exports.walk = estreeWalker.walk;
  2533. exports.shouldTransformRef = refTransform.shouldTransform;
  2534. exports.transformRef = refTransform.transform;
  2535. exports.transformRefAST = refTransform.transformAST;
  2536. exports.compileScript = compileScript;
  2537. exports.compileStyle = compileStyle;
  2538. exports.compileStyleAsync = compileStyleAsync;
  2539. exports.compileTemplate = compileTemplate;
  2540. exports.parse = parse;
  2541. exports.rewriteDefault = rewriteDefault;