reactivity-transform.cjs.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var MagicString = require('magic-string');
  4. var estreeWalker = require('estree-walker');
  5. var compilerCore = require('@vue/compiler-core');
  6. var parser = require('@babel/parser');
  7. var shared = require('@vue/shared');
  8. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; }
  9. var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
  10. const CONVERT_SYMBOL = '$';
  11. const ESCAPE_SYMBOL = '$$';
  12. const shorthands = ['ref', 'computed', 'shallowRef', 'toRef', 'customRef'];
  13. const transformCheckRE = /[^\w]\$(?:\$|ref|computed|shallowRef)?\s*(\(|\<)/;
  14. function shouldTransform(src) {
  15. return transformCheckRE.test(src);
  16. }
  17. function transform(src, { filename, sourceMap, parserPlugins, importHelpersFrom = 'vue' } = {}) {
  18. const plugins = parserPlugins || [];
  19. if (filename) {
  20. if (/\.tsx?$/.test(filename)) {
  21. plugins.push('typescript');
  22. }
  23. if (filename.endsWith('x')) {
  24. plugins.push('jsx');
  25. }
  26. }
  27. const ast = parser.parse(src, {
  28. sourceType: 'module',
  29. plugins
  30. });
  31. const s = new MagicString__default(src);
  32. const res = transformAST(ast.program, s, 0);
  33. // inject helper imports
  34. if (res.importedHelpers.length) {
  35. s.prepend(`import { ${res.importedHelpers
  36. .map(h => `${h} as _${h}`)
  37. .join(', ')} } from '${importHelpersFrom}'\n`);
  38. }
  39. return Object.assign(Object.assign({}, res), { code: s.toString(), map: sourceMap
  40. ? s.generateMap({
  41. source: filename,
  42. hires: true,
  43. includeContent: true
  44. })
  45. : null });
  46. }
  47. function transformAST(ast, s, offset = 0, knownRefs, knownProps) {
  48. // TODO remove when out of experimental
  49. warnExperimental();
  50. let convertSymbol = CONVERT_SYMBOL;
  51. let escapeSymbol = ESCAPE_SYMBOL;
  52. // macro import handling
  53. for (const node of ast.body) {
  54. if (node.type === 'ImportDeclaration' &&
  55. node.source.value === 'vue/macros') {
  56. // remove macro imports
  57. s.remove(node.start + offset, node.end + offset);
  58. // check aliasing
  59. for (const specifier of node.specifiers) {
  60. if (specifier.type === 'ImportSpecifier') {
  61. const imported = specifier.imported.name;
  62. const local = specifier.local.name;
  63. if (local !== imported) {
  64. if (imported === ESCAPE_SYMBOL) {
  65. escapeSymbol = local;
  66. }
  67. else if (imported === CONVERT_SYMBOL) {
  68. convertSymbol = local;
  69. }
  70. else {
  71. error(`macro imports for ref-creating methods do not support aliasing.`, specifier);
  72. }
  73. }
  74. }
  75. }
  76. }
  77. }
  78. const importedHelpers = new Set();
  79. const rootScope = {};
  80. const scopeStack = [rootScope];
  81. let currentScope = rootScope;
  82. let escapeScope; // inside $$()
  83. const excludedIds = new WeakSet();
  84. const parentStack = [];
  85. const propsLocalToPublicMap = Object.create(null);
  86. if (knownRefs) {
  87. for (const key of knownRefs) {
  88. rootScope[key] = true;
  89. }
  90. }
  91. if (knownProps) {
  92. for (const key in knownProps) {
  93. const { local } = knownProps[key];
  94. rootScope[local] = 'prop';
  95. propsLocalToPublicMap[local] = key;
  96. }
  97. }
  98. function isRefCreationCall(callee) {
  99. if (callee === convertSymbol) {
  100. return convertSymbol;
  101. }
  102. if (callee[0] === '$' && shorthands.includes(callee.slice(1))) {
  103. return callee;
  104. }
  105. return false;
  106. }
  107. function error(msg, node) {
  108. const e = new Error(msg);
  109. e.node = node;
  110. throw e;
  111. }
  112. function helper(msg) {
  113. importedHelpers.add(msg);
  114. return `_${msg}`;
  115. }
  116. function registerBinding(id, isRef = false) {
  117. excludedIds.add(id);
  118. if (currentScope) {
  119. currentScope[id.name] = isRef;
  120. }
  121. else {
  122. error('registerBinding called without active scope, something is wrong.', id);
  123. }
  124. }
  125. const registerRefBinding = (id) => registerBinding(id, true);
  126. let tempVarCount = 0;
  127. function genTempVar() {
  128. return `__$temp_${++tempVarCount}`;
  129. }
  130. function snip(node) {
  131. return s.original.slice(node.start + offset, node.end + offset);
  132. }
  133. function walkScope(node, isRoot = false) {
  134. for (const stmt of node.body) {
  135. if (stmt.type === 'VariableDeclaration') {
  136. walkVariableDeclaration(stmt, isRoot);
  137. }
  138. else if (stmt.type === 'FunctionDeclaration' ||
  139. stmt.type === 'ClassDeclaration') {
  140. if (stmt.declare || !stmt.id)
  141. continue;
  142. registerBinding(stmt.id);
  143. }
  144. else if ((stmt.type === 'ForOfStatement' || stmt.type === 'ForInStatement') &&
  145. stmt.left.type === 'VariableDeclaration') {
  146. walkVariableDeclaration(stmt.left);
  147. }
  148. else if (stmt.type === 'ExportNamedDeclaration' &&
  149. stmt.declaration &&
  150. stmt.declaration.type === 'VariableDeclaration') {
  151. walkVariableDeclaration(stmt.declaration, isRoot);
  152. }
  153. else if (stmt.type === 'LabeledStatement' &&
  154. stmt.body.type === 'VariableDeclaration') {
  155. walkVariableDeclaration(stmt.body, isRoot);
  156. }
  157. }
  158. }
  159. function walkVariableDeclaration(stmt, isRoot = false) {
  160. if (stmt.declare) {
  161. return;
  162. }
  163. for (const decl of stmt.declarations) {
  164. let refCall;
  165. const isCall = decl.init &&
  166. decl.init.type === 'CallExpression' &&
  167. decl.init.callee.type === 'Identifier';
  168. if (isCall &&
  169. (refCall = isRefCreationCall(decl.init.callee.name))) {
  170. processRefDeclaration(refCall, decl.id, decl.init);
  171. }
  172. else {
  173. const isProps = isRoot && isCall && decl.init.callee.name === 'defineProps';
  174. for (const id of compilerCore.extractIdentifiers(decl.id)) {
  175. if (isProps) {
  176. // for defineProps destructure, only exclude them since they
  177. // are already passed in as knownProps
  178. excludedIds.add(id);
  179. }
  180. else {
  181. registerBinding(id);
  182. }
  183. }
  184. }
  185. }
  186. }
  187. function processRefDeclaration(method, id, call) {
  188. excludedIds.add(call.callee);
  189. if (method === convertSymbol) {
  190. // $
  191. // remove macro
  192. s.remove(call.callee.start + offset, call.callee.end + offset);
  193. if (id.type === 'Identifier') {
  194. // single variable
  195. registerRefBinding(id);
  196. }
  197. else if (id.type === 'ObjectPattern') {
  198. processRefObjectPattern(id, call);
  199. }
  200. else if (id.type === 'ArrayPattern') {
  201. processRefArrayPattern(id, call);
  202. }
  203. }
  204. else {
  205. // shorthands
  206. if (id.type === 'Identifier') {
  207. registerRefBinding(id);
  208. // replace call
  209. s.overwrite(call.start + offset, call.start + method.length + offset, helper(method.slice(1)));
  210. }
  211. else {
  212. error(`${method}() cannot be used with destructure patterns.`, call);
  213. }
  214. }
  215. }
  216. function processRefObjectPattern(pattern, call, tempVar, path = []) {
  217. if (!tempVar) {
  218. tempVar = genTempVar();
  219. // const { x } = $(useFoo()) --> const __$temp_1 = useFoo()
  220. s.overwrite(pattern.start + offset, pattern.end + offset, tempVar);
  221. }
  222. for (const p of pattern.properties) {
  223. let nameId;
  224. let key;
  225. let defaultValue;
  226. if (p.type === 'ObjectProperty') {
  227. if (p.key.start === p.value.start) {
  228. // shorthand { foo }
  229. nameId = p.key;
  230. if (p.value.type === 'Identifier') {
  231. // avoid shorthand value identifier from being processed
  232. excludedIds.add(p.value);
  233. }
  234. else if (p.value.type === 'AssignmentPattern' &&
  235. p.value.left.type === 'Identifier') {
  236. // { foo = 1 }
  237. excludedIds.add(p.value.left);
  238. defaultValue = p.value.right;
  239. }
  240. }
  241. else {
  242. key = p.computed ? p.key : p.key.name;
  243. if (p.value.type === 'Identifier') {
  244. // { foo: bar }
  245. nameId = p.value;
  246. }
  247. else if (p.value.type === 'ObjectPattern') {
  248. processRefObjectPattern(p.value, call, tempVar, [...path, key]);
  249. }
  250. else if (p.value.type === 'ArrayPattern') {
  251. processRefArrayPattern(p.value, call, tempVar, [...path, key]);
  252. }
  253. else if (p.value.type === 'AssignmentPattern') {
  254. if (p.value.left.type === 'Identifier') {
  255. // { foo: bar = 1 }
  256. nameId = p.value.left;
  257. defaultValue = p.value.right;
  258. }
  259. else if (p.value.left.type === 'ObjectPattern') {
  260. processRefObjectPattern(p.value.left, call, tempVar, [
  261. ...path,
  262. [key, p.value.right]
  263. ]);
  264. }
  265. else if (p.value.left.type === 'ArrayPattern') {
  266. processRefArrayPattern(p.value.left, call, tempVar, [
  267. ...path,
  268. [key, p.value.right]
  269. ]);
  270. }
  271. else ;
  272. }
  273. }
  274. }
  275. else {
  276. // rest element { ...foo }
  277. error(`reactivity destructure does not support rest elements.`, p);
  278. }
  279. if (nameId) {
  280. registerRefBinding(nameId);
  281. // inject toRef() after original replaced pattern
  282. const source = pathToString(tempVar, path);
  283. const keyStr = shared.isString(key)
  284. ? `'${key}'`
  285. : key
  286. ? snip(key)
  287. : `'${nameId.name}'`;
  288. const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``;
  289. s.appendLeft(call.end + offset, `,\n ${nameId.name} = ${helper('toRef')}(${source}, ${keyStr}${defaultStr})`);
  290. }
  291. }
  292. }
  293. function processRefArrayPattern(pattern, call, tempVar, path = []) {
  294. if (!tempVar) {
  295. // const [x] = $(useFoo()) --> const __$temp_1 = useFoo()
  296. tempVar = genTempVar();
  297. s.overwrite(pattern.start + offset, pattern.end + offset, tempVar);
  298. }
  299. for (let i = 0; i < pattern.elements.length; i++) {
  300. const e = pattern.elements[i];
  301. if (!e)
  302. continue;
  303. let nameId;
  304. let defaultValue;
  305. if (e.type === 'Identifier') {
  306. // [a] --> [__a]
  307. nameId = e;
  308. }
  309. else if (e.type === 'AssignmentPattern') {
  310. // [a = 1]
  311. nameId = e.left;
  312. defaultValue = e.right;
  313. }
  314. else if (e.type === 'RestElement') {
  315. // [...a]
  316. error(`reactivity destructure does not support rest elements.`, e);
  317. }
  318. else if (e.type === 'ObjectPattern') {
  319. processRefObjectPattern(e, call, tempVar, [...path, i]);
  320. }
  321. else if (e.type === 'ArrayPattern') {
  322. processRefArrayPattern(e, call, tempVar, [...path, i]);
  323. }
  324. if (nameId) {
  325. registerRefBinding(nameId);
  326. // inject toRef() after original replaced pattern
  327. const source = pathToString(tempVar, path);
  328. const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``;
  329. s.appendLeft(call.end + offset, `,\n ${nameId.name} = ${helper('toRef')}(${source}, ${i}${defaultStr})`);
  330. }
  331. }
  332. }
  333. function pathToString(source, path) {
  334. if (path.length) {
  335. for (const seg of path) {
  336. if (shared.isArray(seg)) {
  337. source = `(${source}${segToString(seg[0])} || ${snip(seg[1])})`;
  338. }
  339. else {
  340. source += segToString(seg);
  341. }
  342. }
  343. }
  344. return source;
  345. }
  346. function segToString(seg) {
  347. if (typeof seg === 'number') {
  348. return `[${seg}]`;
  349. }
  350. else if (typeof seg === 'string') {
  351. return `.${seg}`;
  352. }
  353. else {
  354. return snip(seg);
  355. }
  356. }
  357. function rewriteId(scope, id, parent, parentStack) {
  358. if (shared.hasOwn(scope, id.name)) {
  359. const bindingType = scope[id.name];
  360. if (bindingType) {
  361. const isProp = bindingType === 'prop';
  362. if (compilerCore.isStaticProperty(parent) && parent.shorthand) {
  363. // let binding used in a property shorthand
  364. // skip for destructure patterns
  365. if (!parent.inPattern ||
  366. compilerCore.isInDestructureAssignment(parent, parentStack)) {
  367. if (isProp) {
  368. if (escapeScope) {
  369. // prop binding in $$()
  370. // { prop } -> { prop: __prop_prop }
  371. registerEscapedPropBinding(id);
  372. s.appendLeft(id.end + offset, `: __props_${propsLocalToPublicMap[id.name]}`);
  373. }
  374. else {
  375. // { prop } -> { prop: __prop.prop }
  376. s.appendLeft(id.end + offset, `: __props.${propsLocalToPublicMap[id.name]}`);
  377. }
  378. }
  379. else {
  380. // { foo } -> { foo: foo.value }
  381. s.appendLeft(id.end + offset, `: ${id.name}.value`);
  382. }
  383. }
  384. }
  385. else {
  386. if (isProp) {
  387. if (escapeScope) {
  388. // x --> __props_x
  389. registerEscapedPropBinding(id);
  390. s.overwrite(id.start + offset, id.end + offset, `__props_${propsLocalToPublicMap[id.name]}`);
  391. }
  392. else {
  393. // x --> __props.x
  394. s.overwrite(id.start + offset, id.end + offset, `__props.${propsLocalToPublicMap[id.name]}`);
  395. }
  396. }
  397. else {
  398. // x --> x.value
  399. s.appendLeft(id.end + offset, '.value');
  400. }
  401. }
  402. }
  403. return true;
  404. }
  405. return false;
  406. }
  407. const propBindingRefs = {};
  408. function registerEscapedPropBinding(id) {
  409. if (!propBindingRefs.hasOwnProperty(id.name)) {
  410. propBindingRefs[id.name] = true;
  411. const publicKey = propsLocalToPublicMap[id.name];
  412. s.prependRight(offset, `const __props_${publicKey} = ${helper(`toRef`)}(__props, '${publicKey}')\n`);
  413. }
  414. }
  415. // check root scope first
  416. walkScope(ast, true);
  417. estreeWalker.walk(ast, {
  418. enter(node, parent) {
  419. parent && parentStack.push(parent);
  420. // function scopes
  421. if (compilerCore.isFunctionType(node)) {
  422. scopeStack.push((currentScope = {}));
  423. compilerCore.walkFunctionParams(node, registerBinding);
  424. if (node.body.type === 'BlockStatement') {
  425. walkScope(node.body);
  426. }
  427. return;
  428. }
  429. // catch param
  430. if (node.type === 'CatchClause') {
  431. scopeStack.push((currentScope = {}));
  432. if (node.param && node.param.type === 'Identifier') {
  433. registerBinding(node.param);
  434. }
  435. walkScope(node.body);
  436. return;
  437. }
  438. // non-function block scopes
  439. if (node.type === 'BlockStatement' && !compilerCore.isFunctionType(parent)) {
  440. scopeStack.push((currentScope = {}));
  441. walkScope(node);
  442. return;
  443. }
  444. // skip type nodes
  445. if (parent &&
  446. parent.type.startsWith('TS') &&
  447. parent.type !== 'TSAsExpression' &&
  448. parent.type !== 'TSNonNullExpression' &&
  449. parent.type !== 'TSTypeAssertion') {
  450. return this.skip();
  451. }
  452. if (node.type === 'Identifier' &&
  453. // if inside $$(), skip unless this is a destructured prop binding
  454. !(escapeScope && rootScope[node.name] !== 'prop') &&
  455. compilerCore.isReferencedIdentifier(node, parent, parentStack) &&
  456. !excludedIds.has(node)) {
  457. // walk up the scope chain to check if id should be appended .value
  458. let i = scopeStack.length;
  459. while (i--) {
  460. if (rewriteId(scopeStack[i], node, parent, parentStack)) {
  461. return;
  462. }
  463. }
  464. }
  465. if (node.type === 'CallExpression' && node.callee.type === 'Identifier') {
  466. const callee = node.callee.name;
  467. const refCall = isRefCreationCall(callee);
  468. if (refCall && (!parent || parent.type !== 'VariableDeclarator')) {
  469. return error(`${refCall} can only be used as the initializer of ` +
  470. `a variable declaration.`, node);
  471. }
  472. if (callee === escapeSymbol) {
  473. s.remove(node.callee.start + offset, node.callee.end + offset);
  474. escapeScope = node;
  475. }
  476. // TODO remove when out of experimental
  477. if (callee === '$raw') {
  478. error(`$raw() has been replaced by $$(). ` +
  479. `See ${RFC_LINK} for latest updates.`, node);
  480. }
  481. if (callee === '$fromRef') {
  482. error(`$fromRef() has been replaced by $(). ` +
  483. `See ${RFC_LINK} for latest updates.`, node);
  484. }
  485. }
  486. },
  487. leave(node, parent) {
  488. parent && parentStack.pop();
  489. if ((node.type === 'BlockStatement' && !compilerCore.isFunctionType(parent)) ||
  490. compilerCore.isFunctionType(node)) {
  491. scopeStack.pop();
  492. currentScope = scopeStack[scopeStack.length - 1] || null;
  493. }
  494. if (node === escapeScope) {
  495. escapeScope = undefined;
  496. }
  497. }
  498. });
  499. return {
  500. rootRefs: Object.keys(rootScope).filter(key => rootScope[key] === true),
  501. importedHelpers: [...importedHelpers]
  502. };
  503. }
  504. const RFC_LINK = `https://github.com/vuejs/rfcs/discussions/369`;
  505. const hasWarned = {};
  506. function warnExperimental() {
  507. // eslint-disable-next-line
  508. if (typeof window !== 'undefined') {
  509. return;
  510. }
  511. warnOnce(`Reactivity transform is an experimental feature.\n` +
  512. `Experimental features may change behavior between patch versions.\n` +
  513. `It is recommended to pin your vue dependencies to exact versions to avoid breakage.\n` +
  514. `You can follow the proposal's status at ${RFC_LINK}.`);
  515. }
  516. function warnOnce(msg) {
  517. const isNodeProd = typeof process !== 'undefined' && process.env.NODE_ENV === 'production';
  518. if (!isNodeProd && !false && !hasWarned[msg]) {
  519. hasWarned[msg] = true;
  520. warn(msg);
  521. }
  522. }
  523. function warn(msg) {
  524. console.warn(`\x1b[1m\x1b[33m[@vue/reactivity-transform]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`);
  525. }
  526. exports.shouldTransform = shouldTransform;
  527. exports.transform = transform;
  528. exports.transformAST = transformAST;