compileScript.ts 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664
  1. import MagicString from 'magic-string'
  2. import { BindingMetadata, BindingTypes, UNREF } from '@vue/compiler-core'
  3. import { SFCDescriptor, SFCScriptBlock } from './parse'
  4. import { parse as _parse, ParserOptions, ParserPlugin } from '@babel/parser'
  5. import { babelParserDefaultPlugins, generateCodeFrame } from '@vue/shared'
  6. import {
  7. Node,
  8. Declaration,
  9. ObjectPattern,
  10. ObjectExpression,
  11. ArrayPattern,
  12. Identifier,
  13. ExportSpecifier,
  14. Function as FunctionNode,
  15. TSType,
  16. TSTypeLiteral,
  17. TSFunctionType,
  18. ObjectProperty,
  19. ArrayExpression,
  20. Statement,
  21. Expression,
  22. LabeledStatement,
  23. TSUnionType,
  24. CallExpression
  25. } from '@babel/types'
  26. import { walk } from 'estree-walker'
  27. import { RawSourceMap } from 'source-map'
  28. import {
  29. CSS_VARS_HELPER,
  30. genCssVarsCode,
  31. genNormalScriptCssVarsCode
  32. } from './cssVars'
  33. import { compileTemplate, SFCTemplateCompileOptions } from './compileTemplate'
  34. import { warnExperimental, warnOnce } from './warn'
  35. import { rewriteDefault } from './rewriteDefault'
  36. const DEFINE_PROPS = 'defineProps'
  37. const DEFINE_EMIT = 'defineEmit'
  38. export interface SFCScriptCompileOptions {
  39. /**
  40. * Scope ID for prefixing injected CSS varialbes.
  41. * This must be consistent with the `id` passed to `compileStyle`.
  42. */
  43. id: string
  44. /**
  45. * Production mode. Used to determine whether to generate hashed CSS variables
  46. */
  47. isProd?: boolean
  48. /**
  49. * https://babeljs.io/docs/en/babel-parser#plugins
  50. */
  51. babelParserPlugins?: ParserPlugin[]
  52. /**
  53. * Enable ref: label sugar
  54. * https://github.com/vuejs/rfcs/pull/228
  55. * @default true
  56. */
  57. refSugar?: boolean
  58. /**
  59. * Compile the template and inline the resulting render function
  60. * directly inside setup().
  61. * - Only affects <script setup>
  62. * - This should only be used in production because it prevents the template
  63. * from being hot-reloaded separately from component state.
  64. */
  65. inlineTemplate?: boolean
  66. templateOptions?: Partial<SFCTemplateCompileOptions>
  67. }
  68. /**
  69. * Compile `<script setup>`
  70. * It requires the whole SFC descriptor because we need to handle and merge
  71. * normal `<script>` + `<script setup>` if both are present.
  72. */
  73. export function compileScript(
  74. sfc: SFCDescriptor,
  75. options: SFCScriptCompileOptions
  76. ): SFCScriptBlock {
  77. const { script, scriptSetup, source, filename } = sfc
  78. if (scriptSetup) {
  79. warnExperimental(`<script setup>`, 227)
  80. }
  81. // for backwards compat
  82. if (!options) {
  83. options = { id: '' }
  84. }
  85. if (!options.id) {
  86. warnOnce(
  87. `compileScript now requires passing the \`id\` option.\n` +
  88. `Upgrade your vite or vue-loader version for compatibility with ` +
  89. `the latest experimental proposals.`
  90. )
  91. }
  92. const scopeId = options.id ? options.id.replace(/^data-v-/, '') : ''
  93. const cssVars = sfc.cssVars
  94. const hasInheritAttrsFlag =
  95. sfc.template && sfc.template.attrs['inherit-attrs'] === 'false'
  96. const scriptLang = script && script.lang
  97. const scriptSetupLang = scriptSetup && scriptSetup.lang
  98. const isTS = scriptLang === 'ts' || scriptSetupLang === 'ts'
  99. const plugins: ParserPlugin[] = [...babelParserDefaultPlugins, 'jsx']
  100. if (options.babelParserPlugins) plugins.push(...options.babelParserPlugins)
  101. if (isTS) plugins.push('typescript', 'decorators-legacy')
  102. if (!scriptSetup) {
  103. if (!script) {
  104. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`)
  105. }
  106. if (scriptLang && scriptLang !== 'ts') {
  107. // do not process non js/ts script blocks
  108. return script
  109. }
  110. try {
  111. const scriptAst = _parse(script.content, {
  112. plugins,
  113. sourceType: 'module'
  114. }).program.body
  115. const bindings = analyzeScriptBindings(scriptAst)
  116. const needRewrite = cssVars.length || hasInheritAttrsFlag
  117. let content = script.content
  118. if (needRewrite) {
  119. content = rewriteDefault(content, `__default__`, plugins)
  120. if (cssVars.length) {
  121. content += genNormalScriptCssVarsCode(
  122. cssVars,
  123. bindings,
  124. scopeId,
  125. !!options.isProd
  126. )
  127. }
  128. if (hasInheritAttrsFlag) {
  129. content += `__default__.inheritAttrs = false`
  130. }
  131. content += `\nexport default __default__`
  132. }
  133. return {
  134. ...script,
  135. content,
  136. bindings,
  137. scriptAst
  138. }
  139. } catch (e) {
  140. // silently fallback if parse fails since user may be using custom
  141. // babel syntax
  142. return script
  143. }
  144. }
  145. if (script && scriptLang !== scriptSetupLang) {
  146. throw new Error(
  147. `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`
  148. )
  149. }
  150. if (scriptSetupLang && scriptSetupLang !== 'ts') {
  151. // do not process non js/ts script blocks
  152. return scriptSetup
  153. }
  154. const defaultTempVar = `__default__`
  155. const bindingMetadata: BindingMetadata = {}
  156. const helperImports: Set<string> = new Set()
  157. const userImports: Record<
  158. string,
  159. {
  160. isType: boolean
  161. imported: string
  162. source: string
  163. }
  164. > = Object.create(null)
  165. const userImportAlias: Record<string, string> = Object.create(null)
  166. const setupBindings: Record<string, BindingTypes> = Object.create(null)
  167. const refBindings: Record<string, BindingTypes> = Object.create(null)
  168. const refIdentifiers: Set<Identifier> = new Set()
  169. const enableRefSugar = options.refSugar !== false
  170. let defaultExport: Node | undefined
  171. let hasDefinePropsCall = false
  172. let hasDefineEmitCall = false
  173. let propsRuntimeDecl: Node | undefined
  174. let propsTypeDecl: TSTypeLiteral | undefined
  175. let propsIdentifier: string | undefined
  176. let emitRuntimeDecl: Node | undefined
  177. let emitTypeDecl: TSFunctionType | TSUnionType | undefined
  178. let emitIdentifier: string | undefined
  179. let hasAwait = false
  180. let hasInlinedSsrRenderFn = false
  181. // props/emits declared via types
  182. const typeDeclaredProps: Record<string, PropTypeData> = {}
  183. const typeDeclaredEmits: Set<string> = new Set()
  184. // record declared types for runtime props type generation
  185. const declaredTypes: Record<string, string[]> = {}
  186. // magic-string state
  187. const s = new MagicString(source)
  188. const startOffset = scriptSetup.loc.start.offset
  189. const endOffset = scriptSetup.loc.end.offset
  190. const scriptStartOffset = script && script.loc.start.offset
  191. const scriptEndOffset = script && script.loc.end.offset
  192. function helper(key: string): string {
  193. helperImports.add(key)
  194. return `_${key}`
  195. }
  196. function parse(
  197. input: string,
  198. options: ParserOptions,
  199. offset: number
  200. ): Statement[] {
  201. try {
  202. return _parse(input, options).program.body
  203. } catch (e) {
  204. e.message = `[@vue/compiler-sfc] ${e.message}\n\n${
  205. sfc.filename
  206. }\n${generateCodeFrame(source, e.pos + offset, e.pos + offset + 1)}`
  207. throw e
  208. }
  209. }
  210. function error(
  211. msg: string,
  212. node: Node,
  213. end: number = node.end! + startOffset
  214. ) {
  215. throw new Error(
  216. `[@vue/compiler-sfc] ${msg}\n\n${sfc.filename}\n${generateCodeFrame(
  217. source,
  218. node.start! + startOffset,
  219. end
  220. )}`
  221. )
  222. }
  223. function registerUserImport(
  224. source: string,
  225. local: string,
  226. imported: string | false,
  227. isType: boolean
  228. ) {
  229. if (source === 'vue' && imported) {
  230. userImportAlias[imported] = local
  231. }
  232. userImports[local] = {
  233. isType,
  234. imported: imported || 'default',
  235. source
  236. }
  237. }
  238. function processDefineProps(node: Node): boolean {
  239. if (isCallOf(node, DEFINE_PROPS)) {
  240. if (hasDefinePropsCall) {
  241. error(`duplicate ${DEFINE_PROPS}() call`, node)
  242. }
  243. hasDefinePropsCall = true
  244. propsRuntimeDecl = node.arguments[0]
  245. // context call has type parameters - infer runtime types from it
  246. if (node.typeParameters) {
  247. if (propsRuntimeDecl) {
  248. error(
  249. `${DEFINE_PROPS}() cannot accept both type and non-type arguments ` +
  250. `at the same time. Use one or the other.`,
  251. node
  252. )
  253. }
  254. const typeArg = node.typeParameters.params[0]
  255. if (typeArg.type === 'TSTypeLiteral') {
  256. propsTypeDecl = typeArg
  257. } else {
  258. error(
  259. `type argument passed to ${DEFINE_PROPS}() must be a literal type.`,
  260. typeArg
  261. )
  262. }
  263. }
  264. return true
  265. }
  266. return false
  267. }
  268. function processDefineEmit(node: Node): boolean {
  269. if (isCallOf(node, DEFINE_EMIT)) {
  270. if (hasDefineEmitCall) {
  271. error(`duplicate ${DEFINE_EMIT}() call`, node)
  272. }
  273. hasDefineEmitCall = true
  274. emitRuntimeDecl = node.arguments[0]
  275. if (node.typeParameters) {
  276. if (emitRuntimeDecl) {
  277. error(
  278. `${DEFINE_EMIT}() cannot accept both type and non-type arguments ` +
  279. `at the same time. Use one or the other.`,
  280. node
  281. )
  282. }
  283. const typeArg = node.typeParameters.params[0]
  284. if (
  285. typeArg.type === 'TSFunctionType' ||
  286. typeArg.type === 'TSUnionType'
  287. ) {
  288. emitTypeDecl = typeArg
  289. } else {
  290. error(
  291. `type argument passed to ${DEFINE_EMIT}() must be a function type ` +
  292. `or a union of function types.`,
  293. typeArg
  294. )
  295. }
  296. }
  297. return true
  298. }
  299. return false
  300. }
  301. function checkInvalidScopeReference(node: Node | undefined, method: string) {
  302. if (!node) return
  303. walkIdentifiers(node, id => {
  304. if (setupBindings[id.name]) {
  305. error(
  306. `\`${method}()\` in <script setup> cannot reference locally ` +
  307. `declared variables because it will be hoisted outside of the ` +
  308. `setup() function. If your component options requires initialization ` +
  309. `in the module scope, use a separate normal <script> to export ` +
  310. `the options instead.`,
  311. id
  312. )
  313. }
  314. })
  315. }
  316. function processRefExpression(exp: Expression, statement: LabeledStatement) {
  317. if (exp.type === 'AssignmentExpression') {
  318. const { left, right } = exp
  319. if (left.type === 'Identifier') {
  320. registerRefBinding(left)
  321. s.prependRight(right.start! + startOffset, `${helper('ref')}(`)
  322. s.appendLeft(right.end! + startOffset, ')')
  323. } else if (left.type === 'ObjectPattern') {
  324. // remove wrapping parens
  325. for (let i = left.start!; i > 0; i--) {
  326. const char = source[i + startOffset]
  327. if (char === '(') {
  328. s.remove(i + startOffset, i + startOffset + 1)
  329. break
  330. }
  331. }
  332. for (let i = left.end!; i > 0; i++) {
  333. const char = source[i + startOffset]
  334. if (char === ')') {
  335. s.remove(i + startOffset, i + startOffset + 1)
  336. break
  337. }
  338. }
  339. processRefObjectPattern(left, statement)
  340. } else if (left.type === 'ArrayPattern') {
  341. processRefArrayPattern(left, statement)
  342. }
  343. } else if (exp.type === 'SequenceExpression') {
  344. // possible multiple declarations
  345. // ref: x = 1, y = 2
  346. exp.expressions.forEach(e => processRefExpression(e, statement))
  347. } else if (exp.type === 'Identifier') {
  348. registerRefBinding(exp)
  349. s.appendLeft(exp.end! + startOffset, ` = ${helper('ref')}()`)
  350. } else {
  351. error(`ref: statements can only contain assignment expressions.`, exp)
  352. }
  353. }
  354. function registerRefBinding(id: Identifier) {
  355. if (id.name[0] === '$') {
  356. error(`ref variable identifiers cannot start with $.`, id)
  357. }
  358. refBindings[id.name] = setupBindings[id.name] = BindingTypes.SETUP_REF
  359. refIdentifiers.add(id)
  360. }
  361. function processRefObjectPattern(
  362. pattern: ObjectPattern,
  363. statement: LabeledStatement
  364. ) {
  365. for (const p of pattern.properties) {
  366. let nameId: Identifier | undefined
  367. if (p.type === 'ObjectProperty') {
  368. if (p.key.start! === p.value.start!) {
  369. // shorthand { foo } --> { foo: __foo }
  370. nameId = p.key as Identifier
  371. s.appendLeft(nameId.end! + startOffset, `: __${nameId.name}`)
  372. if (p.value.type === 'AssignmentPattern') {
  373. // { foo = 1 }
  374. refIdentifiers.add(p.value.left as Identifier)
  375. }
  376. } else {
  377. if (p.value.type === 'Identifier') {
  378. // { foo: bar } --> { foo: __bar }
  379. nameId = p.value
  380. s.prependRight(nameId.start! + startOffset, `__`)
  381. } else if (p.value.type === 'ObjectPattern') {
  382. processRefObjectPattern(p.value, statement)
  383. } else if (p.value.type === 'ArrayPattern') {
  384. processRefArrayPattern(p.value, statement)
  385. } else if (p.value.type === 'AssignmentPattern') {
  386. // { foo: bar = 1 } --> { foo: __bar = 1 }
  387. nameId = p.value.left as Identifier
  388. s.prependRight(nameId.start! + startOffset, `__`)
  389. }
  390. }
  391. } else {
  392. // rest element { ...foo } --> { ...__foo }
  393. nameId = p.argument as Identifier
  394. s.prependRight(nameId.start! + startOffset, `__`)
  395. }
  396. if (nameId) {
  397. registerRefBinding(nameId)
  398. // append binding declarations after the parent statement
  399. s.appendLeft(
  400. statement.end! + startOffset,
  401. `\nconst ${nameId.name} = ${helper('ref')}(__${nameId.name});`
  402. )
  403. }
  404. }
  405. }
  406. function processRefArrayPattern(
  407. pattern: ArrayPattern,
  408. statement: LabeledStatement
  409. ) {
  410. for (const e of pattern.elements) {
  411. if (!e) continue
  412. let nameId: Identifier | undefined
  413. if (e.type === 'Identifier') {
  414. // [a] --> [__a]
  415. nameId = e
  416. } else if (e.type === 'AssignmentPattern') {
  417. // [a = 1] --> [__a = 1]
  418. nameId = e.left as Identifier
  419. } else if (e.type === 'RestElement') {
  420. // [...a] --> [...__a]
  421. nameId = e.argument as Identifier
  422. } else if (e.type === 'ObjectPattern') {
  423. processRefObjectPattern(e, statement)
  424. } else if (e.type === 'ArrayPattern') {
  425. processRefArrayPattern(e, statement)
  426. }
  427. if (nameId) {
  428. registerRefBinding(nameId)
  429. // prefix original
  430. s.prependRight(nameId.start! + startOffset, `__`)
  431. // append binding declarations after the parent statement
  432. s.appendLeft(
  433. statement.end! + startOffset,
  434. `\nconst ${nameId.name} = ${helper('ref')}(__${nameId.name});`
  435. )
  436. }
  437. }
  438. }
  439. // 1. process normal <script> first if it exists
  440. let scriptAst
  441. if (script) {
  442. // import dedupe between <script> and <script setup>
  443. scriptAst = parse(
  444. script.content,
  445. {
  446. plugins,
  447. sourceType: 'module'
  448. },
  449. scriptStartOffset!
  450. )
  451. for (const node of scriptAst) {
  452. if (node.type === 'ImportDeclaration') {
  453. // record imports for dedupe
  454. for (const specifier of node.specifiers) {
  455. const imported =
  456. specifier.type === 'ImportSpecifier' &&
  457. specifier.imported.type === 'Identifier' &&
  458. specifier.imported.name
  459. registerUserImport(
  460. node.source.value,
  461. specifier.local.name,
  462. imported,
  463. node.importKind === 'type'
  464. )
  465. }
  466. } else if (node.type === 'ExportDefaultDeclaration') {
  467. // export default
  468. defaultExport = node
  469. const start = node.start! + scriptStartOffset!
  470. s.overwrite(
  471. start,
  472. start + `export default`.length,
  473. `const ${defaultTempVar} =`
  474. )
  475. } else if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
  476. const defaultSpecifier = node.specifiers.find(
  477. s => s.exported.type === 'Identifier' && s.exported.name === 'default'
  478. ) as ExportSpecifier
  479. if (defaultSpecifier) {
  480. defaultExport = node
  481. // 1. remove specifier
  482. if (node.specifiers.length > 1) {
  483. s.remove(
  484. defaultSpecifier.start! + scriptStartOffset!,
  485. defaultSpecifier.end! + scriptStartOffset!
  486. )
  487. } else {
  488. s.remove(
  489. node.start! + scriptStartOffset!,
  490. node.end! + scriptStartOffset!
  491. )
  492. }
  493. if (node.source) {
  494. // export { x as default } from './x'
  495. // rewrite to `import { x as __default__ } from './x'` and
  496. // add to top
  497. s.prepend(
  498. `import { ${
  499. defaultSpecifier.local.name
  500. } as ${defaultTempVar} } from '${node.source.value}'\n`
  501. )
  502. } else {
  503. // export { x as default }
  504. // rewrite to `const __default__ = x` and move to end
  505. s.append(
  506. `\nconst ${defaultTempVar} = ${defaultSpecifier.local.name}\n`
  507. )
  508. }
  509. }
  510. }
  511. }
  512. }
  513. // 2. parse <script setup> and walk over top level statements
  514. const scriptSetupAst = parse(
  515. scriptSetup.content,
  516. {
  517. plugins: [
  518. ...plugins,
  519. // allow top level await but only inside <script setup>
  520. 'topLevelAwait'
  521. ],
  522. sourceType: 'module'
  523. },
  524. startOffset
  525. )
  526. for (const node of scriptSetupAst) {
  527. const start = node.start! + startOffset
  528. let end = node.end! + startOffset
  529. // import or type declarations: move to top
  530. // locate comment
  531. if (node.trailingComments && node.trailingComments.length > 0) {
  532. const lastCommentNode =
  533. node.trailingComments[node.trailingComments.length - 1]
  534. end = lastCommentNode.end + startOffset
  535. }
  536. // locate the end of whitespace between this statement and the next
  537. while (end <= source.length) {
  538. if (!/\s/.test(source.charAt(end))) {
  539. break
  540. }
  541. end++
  542. }
  543. // process `ref: x` bindings (convert to refs)
  544. if (
  545. node.type === 'LabeledStatement' &&
  546. node.label.name === 'ref' &&
  547. node.body.type === 'ExpressionStatement'
  548. ) {
  549. if (enableRefSugar) {
  550. warnExperimental(`ref: sugar`, 228)
  551. s.overwrite(
  552. node.label.start! + startOffset,
  553. node.body.start! + startOffset,
  554. 'const '
  555. )
  556. processRefExpression(node.body.expression, node)
  557. } else {
  558. // TODO if we end up shipping ref: sugar as an opt-in feature,
  559. // need to proxy the option in vite, vue-loader and rollup-plugin-vue.
  560. error(
  561. `ref: sugar needs to be explicitly enabled via vite or vue-loader options.`,
  562. node
  563. )
  564. }
  565. }
  566. if (node.type === 'ImportDeclaration') {
  567. // import declarations are moved to top
  568. s.move(start, end, 0)
  569. // dedupe imports
  570. let removed = 0
  571. let prev: Node | undefined, next: Node | undefined
  572. const removeSpecifier = (node: Node) => {
  573. removed++
  574. s.remove(
  575. prev ? prev.end! + startOffset : node.start! + startOffset,
  576. next && !prev ? next.start! + startOffset : node.end! + startOffset
  577. )
  578. }
  579. for (let i = 0; i < node.specifiers.length; i++) {
  580. const specifier = node.specifiers[i]
  581. prev = node.specifiers[i - 1]
  582. next = node.specifiers[i + 1]
  583. const local = specifier.local.name
  584. const imported =
  585. specifier.type === 'ImportSpecifier' &&
  586. specifier.imported.type === 'Identifier' &&
  587. specifier.imported.name
  588. const source = node.source.value
  589. const existing = userImports[local]
  590. if (
  591. source === 'vue' &&
  592. (imported === DEFINE_PROPS || imported === DEFINE_EMIT)
  593. ) {
  594. removeSpecifier(specifier)
  595. } else if (existing) {
  596. if (existing.source === source && existing.imported === imported) {
  597. // already imported in <script setup>, dedupe
  598. removeSpecifier(specifier)
  599. } else {
  600. error(`different imports aliased to same local name.`, specifier)
  601. }
  602. } else {
  603. registerUserImport(
  604. source,
  605. local,
  606. imported,
  607. node.importKind === 'type'
  608. )
  609. }
  610. }
  611. if (node.specifiers.length && removed === node.specifiers.length) {
  612. s.remove(node.start! + startOffset, node.end! + startOffset)
  613. }
  614. }
  615. // process `defineProps` and `defineEmit` calls
  616. if (
  617. node.type === 'ExpressionStatement' &&
  618. (processDefineProps(node.expression) ||
  619. processDefineEmit(node.expression))
  620. ) {
  621. s.remove(node.start! + startOffset, node.end! + startOffset)
  622. }
  623. if (node.type === 'VariableDeclaration' && !node.declare) {
  624. for (const decl of node.declarations) {
  625. if (decl.init) {
  626. const isDefineProps = processDefineProps(decl.init)
  627. if (isDefineProps) {
  628. propsIdentifier = scriptSetup.content.slice(
  629. decl.id.start!,
  630. decl.id.end!
  631. )
  632. }
  633. const isDefineEmit = processDefineEmit(decl.init)
  634. if (isDefineEmit) {
  635. emitIdentifier = scriptSetup.content.slice(
  636. decl.id.start!,
  637. decl.id.end!
  638. )
  639. }
  640. if (isDefineProps || isDefineEmit)
  641. if (node.declarations.length === 1) {
  642. s.remove(node.start! + startOffset, node.end! + startOffset)
  643. } else {
  644. s.remove(decl.start! + startOffset, decl.end! + startOffset)
  645. }
  646. }
  647. }
  648. }
  649. // walk decalrations to record declared bindings
  650. if (
  651. (node.type === 'VariableDeclaration' ||
  652. node.type === 'FunctionDeclaration' ||
  653. node.type === 'ClassDeclaration') &&
  654. !node.declare
  655. ) {
  656. walkDeclaration(node, setupBindings, userImportAlias)
  657. }
  658. // Type declarations
  659. if (node.type === 'VariableDeclaration' && node.declare) {
  660. s.remove(start, end)
  661. }
  662. // move all type declarations to outer scope
  663. if (
  664. node.type.startsWith('TS') ||
  665. (node.type === 'ExportNamedDeclaration' && node.exportKind === 'type')
  666. ) {
  667. recordType(node, declaredTypes)
  668. s.move(start, end, 0)
  669. }
  670. // walk statements & named exports / variable declarations for top level
  671. // await
  672. if (
  673. (node.type === 'VariableDeclaration' && !node.declare) ||
  674. node.type.endsWith('Statement')
  675. ) {
  676. ;(walk as any)(node, {
  677. enter(node: Node) {
  678. if (isFunction(node)) {
  679. this.skip()
  680. }
  681. if (node.type === 'AwaitExpression') {
  682. hasAwait = true
  683. }
  684. }
  685. })
  686. }
  687. if (
  688. (node.type === 'ExportNamedDeclaration' && node.exportKind !== 'type') ||
  689. node.type === 'ExportAllDeclaration' ||
  690. node.type === 'ExportDefaultDeclaration'
  691. ) {
  692. error(
  693. `<script setup> cannot contain ES module exports. ` +
  694. `If you are using a previous version of <script setup>, please ` +
  695. `consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.`,
  696. node
  697. )
  698. }
  699. }
  700. // 3. Do a full walk to rewrite identifiers referencing let exports with ref
  701. // value access
  702. if (enableRefSugar && Object.keys(refBindings).length) {
  703. for (const node of scriptSetupAst) {
  704. if (node.type !== 'ImportDeclaration') {
  705. walkIdentifiers(node, (id, parent, parentStack) => {
  706. if (refBindings[id.name] && !refIdentifiers.has(id)) {
  707. if (isStaticProperty(parent) && parent.shorthand) {
  708. // let binding used in a property shorthand
  709. // { foo } -> { foo: foo.value }
  710. // skip for destructure patterns
  711. if (
  712. !(parent as any).inPattern ||
  713. isInDestructureAssignment(parent, parentStack)
  714. ) {
  715. s.appendLeft(id.end! + startOffset, `: ${id.name}.value`)
  716. }
  717. } else {
  718. s.appendLeft(id.end! + startOffset, '.value')
  719. }
  720. } else if (id.name[0] === '$' && refBindings[id.name.slice(1)]) {
  721. // $xxx raw ref access variables, remove the $ prefix
  722. s.remove(id.start! + startOffset, id.start! + startOffset + 1)
  723. }
  724. })
  725. }
  726. }
  727. }
  728. // 4. extract runtime props/emits code from setup context type
  729. if (propsTypeDecl) {
  730. extractRuntimeProps(propsTypeDecl, typeDeclaredProps, declaredTypes)
  731. }
  732. if (emitTypeDecl) {
  733. extractRuntimeEmits(emitTypeDecl, typeDeclaredEmits)
  734. }
  735. // 5. check useOptions args to make sure it doesn't reference setup scope
  736. // variables
  737. checkInvalidScopeReference(propsRuntimeDecl, DEFINE_PROPS)
  738. checkInvalidScopeReference(emitRuntimeDecl, DEFINE_PROPS)
  739. // 6. remove non-script content
  740. if (script) {
  741. if (startOffset < scriptStartOffset!) {
  742. // <script setup> before <script>
  743. s.remove(0, startOffset)
  744. s.remove(endOffset, scriptStartOffset!)
  745. s.remove(scriptEndOffset!, source.length)
  746. } else {
  747. // <script> before <script setup>
  748. s.remove(0, scriptStartOffset!)
  749. s.remove(scriptEndOffset!, startOffset)
  750. s.remove(endOffset, source.length)
  751. }
  752. } else {
  753. // only <script setup>
  754. s.remove(0, startOffset)
  755. s.remove(endOffset, source.length)
  756. }
  757. // 7. analyze binding metadata
  758. if (scriptAst) {
  759. Object.assign(bindingMetadata, analyzeScriptBindings(scriptAst))
  760. }
  761. if (propsRuntimeDecl) {
  762. for (const key of getObjectOrArrayExpressionKeys(propsRuntimeDecl)) {
  763. bindingMetadata[key] = BindingTypes.PROPS
  764. }
  765. }
  766. for (const key in typeDeclaredProps) {
  767. bindingMetadata[key] = BindingTypes.PROPS
  768. }
  769. for (const [key, { isType, imported, source }] of Object.entries(
  770. userImports
  771. )) {
  772. if (isType) continue
  773. bindingMetadata[key] =
  774. (imported === 'default' && source.endsWith('.vue')) || source === 'vue'
  775. ? BindingTypes.SETUP_CONST
  776. : BindingTypes.SETUP_MAYBE_REF
  777. }
  778. for (const key in setupBindings) {
  779. bindingMetadata[key] = setupBindings[key]
  780. }
  781. // 8. inject `useCssVars` calls
  782. if (cssVars.length) {
  783. helperImports.add(CSS_VARS_HELPER)
  784. helperImports.add('unref')
  785. s.prependRight(
  786. startOffset,
  787. `\n${genCssVarsCode(
  788. cssVars,
  789. bindingMetadata,
  790. scopeId,
  791. !!options.isProd
  792. )}\n`
  793. )
  794. }
  795. // 9. finalize setup() argument signature
  796. let args = `__props`
  797. if (propsTypeDecl) {
  798. args += `: ${scriptSetup.content.slice(
  799. propsTypeDecl.start!,
  800. propsTypeDecl.end!
  801. )}`
  802. }
  803. // inject user assignment of props
  804. // we use a default __props so that template expressions referencing props
  805. // can use it directly
  806. if (propsIdentifier) {
  807. s.prependRight(startOffset, `\nconst ${propsIdentifier} = __props`)
  808. }
  809. if (emitIdentifier) {
  810. args +=
  811. emitIdentifier === `emit` ? `, { emit }` : `, { emit: ${emitIdentifier} }`
  812. if (emitTypeDecl) {
  813. args += `: {
  814. emit: (${scriptSetup.content.slice(
  815. emitTypeDecl.start!,
  816. emitTypeDecl.end!
  817. )}),
  818. slots: any,
  819. attrs: any
  820. }`
  821. }
  822. }
  823. // 10. generate return statement
  824. let returned
  825. if (options.inlineTemplate) {
  826. if (sfc.template && !sfc.template.src) {
  827. if (options.templateOptions && options.templateOptions.ssr) {
  828. hasInlinedSsrRenderFn = true
  829. }
  830. // inline render function mode - we are going to compile the template and
  831. // inline it right here
  832. const { code, ast, preamble, tips, errors } = compileTemplate({
  833. filename,
  834. source: sfc.template.content,
  835. inMap: sfc.template.map,
  836. ...options.templateOptions,
  837. id: scopeId,
  838. scoped: sfc.styles.some(s => s.scoped),
  839. isProd: options.isProd,
  840. ssrCssVars: sfc.cssVars,
  841. compilerOptions: {
  842. ...(options.templateOptions &&
  843. options.templateOptions.compilerOptions),
  844. inline: true,
  845. isTS,
  846. bindingMetadata
  847. }
  848. })
  849. if (tips.length) {
  850. tips.forEach(warnOnce)
  851. }
  852. const err = errors[0]
  853. if (typeof err === 'string') {
  854. throw new Error(err)
  855. } else if (err) {
  856. if (err.loc) {
  857. err.message +=
  858. `\n\n` +
  859. sfc.filename +
  860. '\n' +
  861. generateCodeFrame(
  862. source,
  863. err.loc.start.offset,
  864. err.loc.end.offset
  865. ) +
  866. `\n`
  867. }
  868. throw err
  869. }
  870. if (preamble) {
  871. s.prepend(preamble)
  872. }
  873. // avoid duplicated unref import
  874. // as this may get injected by the render function preamble OR the
  875. // css vars codegen
  876. if (ast && ast.helpers.includes(UNREF)) {
  877. helperImports.delete('unref')
  878. }
  879. returned = code
  880. } else {
  881. returned = `() => {}`
  882. }
  883. } else {
  884. // return bindings from setup
  885. const allBindings: Record<string, any> = { ...setupBindings }
  886. for (const key in userImports) {
  887. if (!userImports[key].isType) {
  888. allBindings[key] = true
  889. }
  890. }
  891. returned = `{ ${Object.keys(allBindings).join(', ')} }`
  892. }
  893. s.appendRight(endOffset, `\nreturn ${returned}\n}\n\n`)
  894. // 11. finalize default export
  895. // expose: [] makes <script setup> components "closed" by default.
  896. let runtimeOptions = `\n expose: [],`
  897. if (hasInheritAttrsFlag) {
  898. runtimeOptions += `\n inheritAttrs: false,`
  899. }
  900. if (hasInlinedSsrRenderFn) {
  901. runtimeOptions += `\n __ssrInlineRender: true,`
  902. }
  903. if (propsRuntimeDecl) {
  904. runtimeOptions += `\n props: ${scriptSetup.content
  905. .slice(propsRuntimeDecl.start!, propsRuntimeDecl.end!)
  906. .trim()},`
  907. } else if (propsTypeDecl) {
  908. runtimeOptions += genRuntimeProps(typeDeclaredProps)
  909. }
  910. if (emitRuntimeDecl) {
  911. runtimeOptions += `\n emits: ${scriptSetup.content
  912. .slice(emitRuntimeDecl.start!, emitRuntimeDecl.end!)
  913. .trim()},`
  914. } else if (emitTypeDecl) {
  915. runtimeOptions += genRuntimeEmits(typeDeclaredEmits)
  916. }
  917. if (isTS) {
  918. // for TS, make sure the exported type is still valid type with
  919. // correct props information
  920. // we have to use object spread for types to be merged properly
  921. // user's TS setting should compile it down to proper targets
  922. const def = defaultExport ? `\n ...${defaultTempVar},` : ``
  923. // wrap setup code with function.
  924. // export the content of <script setup> as a named export, `setup`.
  925. // this allows `import { setup } from '*.vue'` for testing purposes.
  926. s.prependLeft(
  927. startOffset,
  928. `\nexport default ${helper(
  929. `defineComponent`
  930. )}({${def}${runtimeOptions}\n ${
  931. hasAwait ? `async ` : ``
  932. }setup(${args}) {\n`
  933. )
  934. s.appendRight(endOffset, `})`)
  935. } else {
  936. if (defaultExport) {
  937. // can't rely on spread operator in non ts mode
  938. s.prependLeft(
  939. startOffset,
  940. `\n${hasAwait ? `async ` : ``}function setup(${args}) {\n`
  941. )
  942. s.append(
  943. `\nexport default /*#__PURE__*/ Object.assign(${defaultTempVar}, {${runtimeOptions}\n setup\n})\n`
  944. )
  945. } else {
  946. s.prependLeft(
  947. startOffset,
  948. `\nexport default {${runtimeOptions}\n ` +
  949. `${hasAwait ? `async ` : ``}setup(${args}) {\n`
  950. )
  951. s.appendRight(endOffset, `}`)
  952. }
  953. }
  954. // 12. finalize Vue helper imports
  955. if (helperImports.size > 0) {
  956. s.prepend(
  957. `import { ${[...helperImports]
  958. .map(h => `${h} as _${h}`)
  959. .join(', ')} } from 'vue'\n`
  960. )
  961. }
  962. s.trim()
  963. return {
  964. ...scriptSetup,
  965. bindings: bindingMetadata,
  966. content: s.toString(),
  967. map: (s.generateMap({
  968. source: filename,
  969. hires: true,
  970. includeContent: true
  971. }) as unknown) as RawSourceMap,
  972. scriptAst,
  973. scriptSetupAst
  974. }
  975. }
  976. function walkDeclaration(
  977. node: Declaration,
  978. bindings: Record<string, BindingTypes>,
  979. userImportAlias: Record<string, string>
  980. ) {
  981. if (node.type === 'VariableDeclaration') {
  982. const isConst = node.kind === 'const'
  983. // export const foo = ...
  984. for (const { id, init } of node.declarations) {
  985. const isDefineCall = !!(
  986. isConst &&
  987. (isCallOf(init, DEFINE_PROPS) || isCallOf(init, DEFINE_EMIT))
  988. )
  989. if (id.type === 'Identifier') {
  990. let bindingType
  991. const userReactiveBinding = userImportAlias['reactive'] || 'reactive'
  992. if (isCallOf(init, userReactiveBinding)) {
  993. // treat reactive() calls as let since it's meant to be mutable
  994. bindingType = BindingTypes.SETUP_LET
  995. } else if (
  996. // if a declaration is a const literal, we can mark it so that
  997. // the generated render fn code doesn't need to unref() it
  998. isDefineCall ||
  999. (isConst && canNeverBeRef(init!, userReactiveBinding))
  1000. ) {
  1001. bindingType = BindingTypes.SETUP_CONST
  1002. } else if (isConst) {
  1003. if (isCallOf(init, userImportAlias['ref'] || 'ref')) {
  1004. bindingType = BindingTypes.SETUP_REF
  1005. } else {
  1006. bindingType = BindingTypes.SETUP_MAYBE_REF
  1007. }
  1008. } else {
  1009. bindingType = BindingTypes.SETUP_LET
  1010. }
  1011. bindings[id.name] = bindingType
  1012. } else if (id.type === 'ObjectPattern') {
  1013. walkObjectPattern(id, bindings, isConst, isDefineCall)
  1014. } else if (id.type === 'ArrayPattern') {
  1015. walkArrayPattern(id, bindings, isConst, isDefineCall)
  1016. }
  1017. }
  1018. } else if (
  1019. node.type === 'FunctionDeclaration' ||
  1020. node.type === 'ClassDeclaration'
  1021. ) {
  1022. // export function foo() {} / export class Foo {}
  1023. // export declarations must be named.
  1024. bindings[node.id!.name] = BindingTypes.SETUP_CONST
  1025. }
  1026. }
  1027. function walkObjectPattern(
  1028. node: ObjectPattern,
  1029. bindings: Record<string, BindingTypes>,
  1030. isConst: boolean,
  1031. isDefineCall = false
  1032. ) {
  1033. for (const p of node.properties) {
  1034. if (p.type === 'ObjectProperty') {
  1035. // key can only be Identifier in ObjectPattern
  1036. if (p.key.type === 'Identifier') {
  1037. if (p.key === p.value) {
  1038. // const { x } = ...
  1039. bindings[p.key.name] = isDefineCall
  1040. ? BindingTypes.SETUP_CONST
  1041. : isConst
  1042. ? BindingTypes.SETUP_MAYBE_REF
  1043. : BindingTypes.SETUP_LET
  1044. } else {
  1045. walkPattern(p.value, bindings, isConst, isDefineCall)
  1046. }
  1047. }
  1048. } else {
  1049. // ...rest
  1050. // argument can only be identifer when destructuring
  1051. bindings[(p.argument as Identifier).name] = isConst
  1052. ? BindingTypes.SETUP_CONST
  1053. : BindingTypes.SETUP_LET
  1054. }
  1055. }
  1056. }
  1057. function walkArrayPattern(
  1058. node: ArrayPattern,
  1059. bindings: Record<string, BindingTypes>,
  1060. isConst: boolean,
  1061. isDefineCall = false
  1062. ) {
  1063. for (const e of node.elements) {
  1064. e && walkPattern(e, bindings, isConst, isDefineCall)
  1065. }
  1066. }
  1067. function walkPattern(
  1068. node: Node,
  1069. bindings: Record<string, BindingTypes>,
  1070. isConst: boolean,
  1071. isDefineCall = false
  1072. ) {
  1073. if (node.type === 'Identifier') {
  1074. bindings[node.name] = isDefineCall
  1075. ? BindingTypes.SETUP_CONST
  1076. : isConst
  1077. ? BindingTypes.SETUP_MAYBE_REF
  1078. : BindingTypes.SETUP_LET
  1079. } else if (node.type === 'RestElement') {
  1080. // argument can only be identifer when destructuring
  1081. bindings[(node.argument as Identifier).name] = isConst
  1082. ? BindingTypes.SETUP_CONST
  1083. : BindingTypes.SETUP_LET
  1084. } else if (node.type === 'ObjectPattern') {
  1085. walkObjectPattern(node, bindings, isConst)
  1086. } else if (node.type === 'ArrayPattern') {
  1087. walkArrayPattern(node, bindings, isConst)
  1088. } else if (node.type === 'AssignmentPattern') {
  1089. if (node.left.type === 'Identifier') {
  1090. bindings[node.left.name] = isDefineCall
  1091. ? BindingTypes.SETUP_CONST
  1092. : isConst
  1093. ? BindingTypes.SETUP_MAYBE_REF
  1094. : BindingTypes.SETUP_LET
  1095. } else {
  1096. walkPattern(node.left, bindings, isConst)
  1097. }
  1098. }
  1099. }
  1100. interface PropTypeData {
  1101. key: string
  1102. type: string[]
  1103. required: boolean
  1104. }
  1105. function recordType(node: Node, declaredTypes: Record<string, string[]>) {
  1106. if (node.type === 'TSInterfaceDeclaration') {
  1107. declaredTypes[node.id.name] = [`Object`]
  1108. } else if (node.type === 'TSTypeAliasDeclaration') {
  1109. declaredTypes[node.id.name] = inferRuntimeType(
  1110. node.typeAnnotation,
  1111. declaredTypes
  1112. )
  1113. } else if (node.type === 'ExportNamedDeclaration' && node.declaration) {
  1114. recordType(node.declaration, declaredTypes)
  1115. }
  1116. }
  1117. function extractRuntimeProps(
  1118. node: TSTypeLiteral,
  1119. props: Record<string, PropTypeData>,
  1120. declaredTypes: Record<string, string[]>
  1121. ) {
  1122. for (const m of node.members) {
  1123. if (m.type === 'TSPropertySignature' && m.key.type === 'Identifier') {
  1124. props[m.key.name] = {
  1125. key: m.key.name,
  1126. required: !m.optional,
  1127. type:
  1128. __DEV__ && m.typeAnnotation
  1129. ? inferRuntimeType(m.typeAnnotation.typeAnnotation, declaredTypes)
  1130. : [`null`]
  1131. }
  1132. }
  1133. }
  1134. }
  1135. function inferRuntimeType(
  1136. node: TSType,
  1137. declaredTypes: Record<string, string[]>
  1138. ): string[] {
  1139. switch (node.type) {
  1140. case 'TSStringKeyword':
  1141. return ['String']
  1142. case 'TSNumberKeyword':
  1143. return ['Number']
  1144. case 'TSBooleanKeyword':
  1145. return ['Boolean']
  1146. case 'TSObjectKeyword':
  1147. return ['Object']
  1148. case 'TSTypeLiteral':
  1149. // TODO (nice to have) generate runtime property validation
  1150. return ['Object']
  1151. case 'TSFunctionType':
  1152. return ['Function']
  1153. case 'TSArrayType':
  1154. case 'TSTupleType':
  1155. // TODO (nice to have) generate runtime element type/length checks
  1156. return ['Array']
  1157. case 'TSLiteralType':
  1158. switch (node.literal.type) {
  1159. case 'StringLiteral':
  1160. return ['String']
  1161. case 'BooleanLiteral':
  1162. return ['Boolean']
  1163. case 'NumericLiteral':
  1164. case 'BigIntLiteral':
  1165. return ['Number']
  1166. default:
  1167. return [`null`]
  1168. }
  1169. case 'TSTypeReference':
  1170. if (node.typeName.type === 'Identifier') {
  1171. if (declaredTypes[node.typeName.name]) {
  1172. return declaredTypes[node.typeName.name]
  1173. }
  1174. switch (node.typeName.name) {
  1175. case 'Array':
  1176. case 'Function':
  1177. case 'Object':
  1178. case 'Set':
  1179. case 'Map':
  1180. case 'WeakSet':
  1181. case 'WeakMap':
  1182. return [node.typeName.name]
  1183. case 'Record':
  1184. case 'Partial':
  1185. case 'Readonly':
  1186. case 'Pick':
  1187. case 'Omit':
  1188. case 'Exclude':
  1189. case 'Extract':
  1190. case 'Required':
  1191. case 'InstanceType':
  1192. return ['Object']
  1193. }
  1194. }
  1195. return [`null`]
  1196. case 'TSUnionType':
  1197. return [
  1198. ...new Set(
  1199. [].concat(node.types.map(t =>
  1200. inferRuntimeType(t, declaredTypes)
  1201. ) as any)
  1202. )
  1203. ]
  1204. case 'TSIntersectionType':
  1205. return ['Object']
  1206. default:
  1207. return [`null`] // no runtime check
  1208. }
  1209. }
  1210. function genRuntimeProps(props: Record<string, PropTypeData>) {
  1211. const keys = Object.keys(props)
  1212. if (!keys.length) {
  1213. return ``
  1214. }
  1215. if (!__DEV__) {
  1216. // production: generate array version only
  1217. return `\n props: [\n ${keys
  1218. .map(k => JSON.stringify(k))
  1219. .join(',\n ')}\n ] as unknown as undefined,`
  1220. }
  1221. return `\n props: {\n ${keys
  1222. .map(key => {
  1223. const { type, required } = props[key]
  1224. return `${key}: { type: ${toRuntimeTypeString(
  1225. type
  1226. )}, required: ${required} }`
  1227. })
  1228. .join(',\n ')}\n } as unknown as undefined,`
  1229. }
  1230. function toRuntimeTypeString(types: string[]) {
  1231. return types.some(t => t === 'null')
  1232. ? `null`
  1233. : types.length > 1
  1234. ? `[${types.join(', ')}]`
  1235. : types[0]
  1236. }
  1237. function extractRuntimeEmits(
  1238. node: TSFunctionType | TSUnionType,
  1239. emits: Set<string>
  1240. ) {
  1241. if (node.type === 'TSUnionType') {
  1242. for (let t of node.types) {
  1243. if (t.type === 'TSParenthesizedType') t = t.typeAnnotation
  1244. if (t.type === 'TSFunctionType') {
  1245. extractRuntimeEmits(t, emits)
  1246. }
  1247. }
  1248. return
  1249. }
  1250. const eventName = node.parameters[0]
  1251. if (
  1252. eventName.type === 'Identifier' &&
  1253. eventName.typeAnnotation &&
  1254. eventName.typeAnnotation.type === 'TSTypeAnnotation'
  1255. ) {
  1256. const typeNode = eventName.typeAnnotation.typeAnnotation
  1257. if (typeNode.type === 'TSLiteralType') {
  1258. emits.add(String(typeNode.literal.value))
  1259. } else if (typeNode.type === 'TSUnionType') {
  1260. for (const t of typeNode.types) {
  1261. if (t.type === 'TSLiteralType') {
  1262. emits.add(String(t.literal.value))
  1263. }
  1264. }
  1265. }
  1266. }
  1267. }
  1268. function genRuntimeEmits(emits: Set<string>) {
  1269. return emits.size
  1270. ? `\n emits: [${Array.from(emits)
  1271. .map(p => JSON.stringify(p))
  1272. .join(', ')}] as unknown as undefined,`
  1273. : ``
  1274. }
  1275. /**
  1276. * Walk an AST and find identifiers that are variable references.
  1277. * This is largely the same logic with `transformExpressions` in compiler-core
  1278. * but with some subtle differences as this needs to handle a wider range of
  1279. * possible syntax.
  1280. */
  1281. function walkIdentifiers(
  1282. root: Node,
  1283. onIdentifier: (node: Identifier, parent: Node, parentStack: Node[]) => void
  1284. ) {
  1285. const parentStack: Node[] = []
  1286. const knownIds: Record<string, number> = Object.create(null)
  1287. ;(walk as any)(root, {
  1288. enter(node: Node & { scopeIds?: Set<string> }, parent: Node | undefined) {
  1289. parent && parentStack.push(parent)
  1290. if (node.type === 'Identifier') {
  1291. if (
  1292. !knownIds[node.name] &&
  1293. isRefIdentifier(node, parent!, parentStack)
  1294. ) {
  1295. onIdentifier(node, parent!, parentStack)
  1296. }
  1297. } else if (isFunction(node)) {
  1298. // walk function expressions and add its arguments to known identifiers
  1299. // so that we don't prefix them
  1300. node.params.forEach(p =>
  1301. (walk as any)(p, {
  1302. enter(child: Node, parent: Node) {
  1303. if (
  1304. child.type === 'Identifier' &&
  1305. // do not record as scope variable if is a destructured key
  1306. !isStaticPropertyKey(child, parent) &&
  1307. // do not record if this is a default value
  1308. // assignment of a destructured variable
  1309. !(
  1310. parent &&
  1311. parent.type === 'AssignmentPattern' &&
  1312. parent.right === child
  1313. )
  1314. ) {
  1315. const { name } = child
  1316. if (node.scopeIds && node.scopeIds.has(name)) {
  1317. return
  1318. }
  1319. if (name in knownIds) {
  1320. knownIds[name]++
  1321. } else {
  1322. knownIds[name] = 1
  1323. }
  1324. ;(node.scopeIds || (node.scopeIds = new Set())).add(name)
  1325. }
  1326. }
  1327. })
  1328. )
  1329. } else if (
  1330. node.type === 'ObjectProperty' &&
  1331. parent!.type === 'ObjectPattern'
  1332. ) {
  1333. // mark property in destructure pattern
  1334. ;(node as any).inPattern = true
  1335. }
  1336. },
  1337. leave(node: Node & { scopeIds?: Set<string> }, parent: Node | undefined) {
  1338. parent && parentStack.pop()
  1339. if (node.scopeIds) {
  1340. node.scopeIds.forEach((id: string) => {
  1341. knownIds[id]--
  1342. if (knownIds[id] === 0) {
  1343. delete knownIds[id]
  1344. }
  1345. })
  1346. }
  1347. }
  1348. })
  1349. }
  1350. function isRefIdentifier(id: Identifier, parent: Node, parentStack: Node[]) {
  1351. // declaration id
  1352. if (
  1353. (parent.type === 'VariableDeclarator' ||
  1354. parent.type === 'ClassDeclaration') &&
  1355. parent.id === id
  1356. ) {
  1357. return false
  1358. }
  1359. if (isFunction(parent)) {
  1360. // function decalration/expression id
  1361. if ((parent as any).id === id) {
  1362. return false
  1363. }
  1364. // params list
  1365. if (parent.params.includes(id)) {
  1366. return false
  1367. }
  1368. }
  1369. // property key
  1370. // this also covers object destructure pattern
  1371. if (isStaticPropertyKey(id, parent)) {
  1372. return false
  1373. }
  1374. // non-assignment array destructure pattern
  1375. if (
  1376. parent.type === 'ArrayPattern' &&
  1377. !isInDestructureAssignment(parent, parentStack)
  1378. ) {
  1379. return false
  1380. }
  1381. // member expression property
  1382. if (
  1383. (parent.type === 'MemberExpression' ||
  1384. parent.type === 'OptionalMemberExpression') &&
  1385. parent.property === id &&
  1386. !parent.computed
  1387. ) {
  1388. return false
  1389. }
  1390. // is a special keyword but parsed as identifier
  1391. if (id.name === 'arguments') {
  1392. return false
  1393. }
  1394. return true
  1395. }
  1396. const isStaticProperty = (node: Node): node is ObjectProperty =>
  1397. node &&
  1398. (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
  1399. !node.computed
  1400. const isStaticPropertyKey = (node: Node, parent: Node) =>
  1401. isStaticProperty(parent) && parent.key === node
  1402. function isFunction(node: Node): node is FunctionNode {
  1403. return /Function(?:Expression|Declaration)$|Method$/.test(node.type)
  1404. }
  1405. function isCallOf(node: Node | null, name: string): node is CallExpression {
  1406. return !!(
  1407. node &&
  1408. node.type === 'CallExpression' &&
  1409. node.callee.type === 'Identifier' &&
  1410. node.callee.name === name
  1411. )
  1412. }
  1413. function canNeverBeRef(node: Node, userReactiveImport: string): boolean {
  1414. if (isCallOf(node, userReactiveImport)) {
  1415. return true
  1416. }
  1417. switch (node.type) {
  1418. case 'UnaryExpression':
  1419. case 'BinaryExpression':
  1420. case 'ArrayExpression':
  1421. case 'ObjectExpression':
  1422. case 'FunctionExpression':
  1423. case 'ArrowFunctionExpression':
  1424. case 'UpdateExpression':
  1425. case 'ClassExpression':
  1426. case 'TaggedTemplateExpression':
  1427. return true
  1428. case 'SequenceExpression':
  1429. return canNeverBeRef(
  1430. node.expressions[node.expressions.length - 1],
  1431. userReactiveImport
  1432. )
  1433. default:
  1434. if (node.type.endsWith('Literal')) {
  1435. return true
  1436. }
  1437. return false
  1438. }
  1439. }
  1440. function isInDestructureAssignment(parent: Node, parentStack: Node[]): boolean {
  1441. if (
  1442. parent &&
  1443. (parent.type === 'ObjectProperty' || parent.type === 'ArrayPattern')
  1444. ) {
  1445. let i = parentStack.length
  1446. while (i--) {
  1447. const p = parentStack[i]
  1448. if (p.type === 'AssignmentExpression') {
  1449. const root = parentStack[0]
  1450. // if this is a ref: destructure, it should be treated like a
  1451. // variable decalration!
  1452. return !(root.type === 'LabeledStatement' && root.label.name === 'ref')
  1453. } else if (p.type !== 'ObjectProperty' && !p.type.endsWith('Pattern')) {
  1454. break
  1455. }
  1456. }
  1457. }
  1458. return false
  1459. }
  1460. /**
  1461. * Analyze bindings in normal `<script>`
  1462. * Note that `compileScriptSetup` already analyzes bindings as part of its
  1463. * compilation process so this should only be used on single `<script>` SFCs.
  1464. */
  1465. function analyzeScriptBindings(ast: Statement[]): BindingMetadata {
  1466. for (const node of ast) {
  1467. if (
  1468. node.type === 'ExportDefaultDeclaration' &&
  1469. node.declaration.type === 'ObjectExpression'
  1470. ) {
  1471. return analyzeBindingsFromOptions(node.declaration)
  1472. }
  1473. }
  1474. return {}
  1475. }
  1476. function analyzeBindingsFromOptions(node: ObjectExpression): BindingMetadata {
  1477. const bindings: BindingMetadata = {}
  1478. for (const property of node.properties) {
  1479. if (
  1480. property.type === 'ObjectProperty' &&
  1481. !property.computed &&
  1482. property.key.type === 'Identifier'
  1483. ) {
  1484. // props
  1485. if (property.key.name === 'props') {
  1486. // props: ['foo']
  1487. // props: { foo: ... }
  1488. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  1489. bindings[key] = BindingTypes.PROPS
  1490. }
  1491. }
  1492. // inject
  1493. else if (property.key.name === 'inject') {
  1494. // inject: ['foo']
  1495. // inject: { foo: {} }
  1496. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  1497. bindings[key] = BindingTypes.OPTIONS
  1498. }
  1499. }
  1500. // computed & methods
  1501. else if (
  1502. property.value.type === 'ObjectExpression' &&
  1503. (property.key.name === 'computed' || property.key.name === 'methods')
  1504. ) {
  1505. // methods: { foo() {} }
  1506. // computed: { foo() {} }
  1507. for (const key of getObjectExpressionKeys(property.value)) {
  1508. bindings[key] = BindingTypes.OPTIONS
  1509. }
  1510. }
  1511. }
  1512. // setup & data
  1513. else if (
  1514. property.type === 'ObjectMethod' &&
  1515. property.key.type === 'Identifier' &&
  1516. (property.key.name === 'setup' || property.key.name === 'data')
  1517. ) {
  1518. for (const bodyItem of property.body.body) {
  1519. // setup() {
  1520. // return {
  1521. // foo: null
  1522. // }
  1523. // }
  1524. if (
  1525. bodyItem.type === 'ReturnStatement' &&
  1526. bodyItem.argument &&
  1527. bodyItem.argument.type === 'ObjectExpression'
  1528. ) {
  1529. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  1530. bindings[key] =
  1531. property.key.name === 'setup'
  1532. ? BindingTypes.SETUP_MAYBE_REF
  1533. : BindingTypes.DATA
  1534. }
  1535. }
  1536. }
  1537. }
  1538. }
  1539. return bindings
  1540. }
  1541. function getObjectExpressionKeys(node: ObjectExpression): string[] {
  1542. const keys = []
  1543. for (const prop of node.properties) {
  1544. if (
  1545. (prop.type === 'ObjectProperty' || prop.type === 'ObjectMethod') &&
  1546. !prop.computed
  1547. ) {
  1548. if (prop.key.type === 'Identifier') {
  1549. keys.push(prop.key.name)
  1550. } else if (prop.key.type === 'StringLiteral') {
  1551. keys.push(prop.key.value)
  1552. }
  1553. }
  1554. }
  1555. return keys
  1556. }
  1557. function getArrayExpressionKeys(node: ArrayExpression): string[] {
  1558. const keys = []
  1559. for (const element of node.elements) {
  1560. if (element && element.type === 'StringLiteral') {
  1561. keys.push(element.value)
  1562. }
  1563. }
  1564. return keys
  1565. }
  1566. function getObjectOrArrayExpressionKeys(value: Node): string[] {
  1567. if (value.type === 'ArrayExpression') {
  1568. return getArrayExpressionKeys(value)
  1569. }
  1570. if (value.type === 'ObjectExpression') {
  1571. return getObjectExpressionKeys(value)
  1572. }
  1573. return []
  1574. }