reactivity-transform.cjs.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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. if (stmt.declare)
  137. continue;
  138. for (const decl of stmt.declarations) {
  139. let refCall;
  140. const isCall = decl.init &&
  141. decl.init.type === 'CallExpression' &&
  142. decl.init.callee.type === 'Identifier';
  143. if (isCall &&
  144. (refCall = isRefCreationCall(decl.init.callee.name))) {
  145. processRefDeclaration(refCall, decl.id, decl.init);
  146. }
  147. else {
  148. const isProps = isRoot &&
  149. isCall &&
  150. decl.init.callee.name === 'defineProps';
  151. for (const id of compilerCore.extractIdentifiers(decl.id)) {
  152. if (isProps) {
  153. // for defineProps destructure, only exclude them since they
  154. // are already passed in as knownProps
  155. excludedIds.add(id);
  156. }
  157. else {
  158. registerBinding(id);
  159. }
  160. }
  161. }
  162. }
  163. }
  164. else if (stmt.type === 'FunctionDeclaration' ||
  165. stmt.type === 'ClassDeclaration') {
  166. if (stmt.declare || !stmt.id)
  167. continue;
  168. registerBinding(stmt.id);
  169. }
  170. }
  171. }
  172. function processRefDeclaration(method, id, call) {
  173. excludedIds.add(call.callee);
  174. if (method === convertSymbol) {
  175. // $
  176. // remove macro
  177. s.remove(call.callee.start + offset, call.callee.end + offset);
  178. if (id.type === 'Identifier') {
  179. // single variable
  180. registerRefBinding(id);
  181. }
  182. else if (id.type === 'ObjectPattern') {
  183. processRefObjectPattern(id, call);
  184. }
  185. else if (id.type === 'ArrayPattern') {
  186. processRefArrayPattern(id, call);
  187. }
  188. }
  189. else {
  190. // shorthands
  191. if (id.type === 'Identifier') {
  192. registerRefBinding(id);
  193. // replace call
  194. s.overwrite(call.start + offset, call.start + method.length + offset, helper(method.slice(1)));
  195. }
  196. else {
  197. error(`${method}() cannot be used with destructure patterns.`, call);
  198. }
  199. }
  200. }
  201. function processRefObjectPattern(pattern, call, tempVar, path = []) {
  202. if (!tempVar) {
  203. tempVar = genTempVar();
  204. // const { x } = $(useFoo()) --> const __$temp_1 = useFoo()
  205. s.overwrite(pattern.start + offset, pattern.end + offset, tempVar);
  206. }
  207. for (const p of pattern.properties) {
  208. let nameId;
  209. let key;
  210. let defaultValue;
  211. if (p.type === 'ObjectProperty') {
  212. if (p.key.start === p.value.start) {
  213. // shorthand { foo }
  214. nameId = p.key;
  215. if (p.value.type === 'Identifier') {
  216. // avoid shorthand value identifier from being processed
  217. excludedIds.add(p.value);
  218. }
  219. else if (p.value.type === 'AssignmentPattern' &&
  220. p.value.left.type === 'Identifier') {
  221. // { foo = 1 }
  222. excludedIds.add(p.value.left);
  223. defaultValue = p.value.right;
  224. }
  225. }
  226. else {
  227. key = p.computed ? p.key : p.key.name;
  228. if (p.value.type === 'Identifier') {
  229. // { foo: bar }
  230. nameId = p.value;
  231. }
  232. else if (p.value.type === 'ObjectPattern') {
  233. processRefObjectPattern(p.value, call, tempVar, [...path, key]);
  234. }
  235. else if (p.value.type === 'ArrayPattern') {
  236. processRefArrayPattern(p.value, call, tempVar, [...path, key]);
  237. }
  238. else if (p.value.type === 'AssignmentPattern') {
  239. if (p.value.left.type === 'Identifier') {
  240. // { foo: bar = 1 }
  241. nameId = p.value.left;
  242. defaultValue = p.value.right;
  243. }
  244. else if (p.value.left.type === 'ObjectPattern') {
  245. processRefObjectPattern(p.value.left, call, tempVar, [
  246. ...path,
  247. [key, p.value.right]
  248. ]);
  249. }
  250. else if (p.value.left.type === 'ArrayPattern') {
  251. processRefArrayPattern(p.value.left, call, tempVar, [
  252. ...path,
  253. [key, p.value.right]
  254. ]);
  255. }
  256. else ;
  257. }
  258. }
  259. }
  260. else {
  261. // rest element { ...foo }
  262. error(`reactivity destructure does not support rest elements.`, p);
  263. }
  264. if (nameId) {
  265. registerRefBinding(nameId);
  266. // inject toRef() after original replaced pattern
  267. const source = pathToString(tempVar, path);
  268. const keyStr = shared.isString(key)
  269. ? `'${key}'`
  270. : key
  271. ? snip(key)
  272. : `'${nameId.name}'`;
  273. const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``;
  274. s.appendLeft(call.end + offset, `,\n ${nameId.name} = ${helper('toRef')}(${source}, ${keyStr}${defaultStr})`);
  275. }
  276. }
  277. }
  278. function processRefArrayPattern(pattern, call, tempVar, path = []) {
  279. if (!tempVar) {
  280. // const [x] = $(useFoo()) --> const __$temp_1 = useFoo()
  281. tempVar = genTempVar();
  282. s.overwrite(pattern.start + offset, pattern.end + offset, tempVar);
  283. }
  284. for (let i = 0; i < pattern.elements.length; i++) {
  285. const e = pattern.elements[i];
  286. if (!e)
  287. continue;
  288. let nameId;
  289. let defaultValue;
  290. if (e.type === 'Identifier') {
  291. // [a] --> [__a]
  292. nameId = e;
  293. }
  294. else if (e.type === 'AssignmentPattern') {
  295. // [a = 1]
  296. nameId = e.left;
  297. defaultValue = e.right;
  298. }
  299. else if (e.type === 'RestElement') {
  300. // [...a]
  301. error(`reactivity destructure does not support rest elements.`, e);
  302. }
  303. else if (e.type === 'ObjectPattern') {
  304. processRefObjectPattern(e, call, tempVar, [...path, i]);
  305. }
  306. else if (e.type === 'ArrayPattern') {
  307. processRefArrayPattern(e, call, tempVar, [...path, i]);
  308. }
  309. if (nameId) {
  310. registerRefBinding(nameId);
  311. // inject toRef() after original replaced pattern
  312. const source = pathToString(tempVar, path);
  313. const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``;
  314. s.appendLeft(call.end + offset, `,\n ${nameId.name} = ${helper('toRef')}(${source}, ${i}${defaultStr})`);
  315. }
  316. }
  317. }
  318. function pathToString(source, path) {
  319. if (path.length) {
  320. for (const seg of path) {
  321. if (shared.isArray(seg)) {
  322. source = `(${source}${segToString(seg[0])} || ${snip(seg[1])})`;
  323. }
  324. else {
  325. source += segToString(seg);
  326. }
  327. }
  328. }
  329. return source;
  330. }
  331. function segToString(seg) {
  332. if (typeof seg === 'number') {
  333. return `[${seg}]`;
  334. }
  335. else if (typeof seg === 'string') {
  336. return `.${seg}`;
  337. }
  338. else {
  339. return snip(seg);
  340. }
  341. }
  342. function rewriteId(scope, id, parent, parentStack) {
  343. if (shared.hasOwn(scope, id.name)) {
  344. const bindingType = scope[id.name];
  345. if (bindingType) {
  346. const isProp = bindingType === 'prop';
  347. if (compilerCore.isStaticProperty(parent) && parent.shorthand) {
  348. // let binding used in a property shorthand
  349. // skip for destructure patterns
  350. if (!parent.inPattern ||
  351. compilerCore.isInDestructureAssignment(parent, parentStack)) {
  352. if (isProp) {
  353. if (escapeScope) {
  354. // prop binding in $$()
  355. // { prop } -> { prop: __prop_prop }
  356. registerEscapedPropBinding(id);
  357. s.appendLeft(id.end + offset, `: __props_${propsLocalToPublicMap[id.name]}`);
  358. }
  359. else {
  360. // { prop } -> { prop: __prop.prop }
  361. s.appendLeft(id.end + offset, `: __props.${propsLocalToPublicMap[id.name]}`);
  362. }
  363. }
  364. else {
  365. // { foo } -> { foo: foo.value }
  366. s.appendLeft(id.end + offset, `: ${id.name}.value`);
  367. }
  368. }
  369. }
  370. else {
  371. if (isProp) {
  372. if (escapeScope) {
  373. // x --> __props_x
  374. registerEscapedPropBinding(id);
  375. s.overwrite(id.start + offset, id.end + offset, `__props_${propsLocalToPublicMap[id.name]}`);
  376. }
  377. else {
  378. // x --> __props.x
  379. s.overwrite(id.start + offset, id.end + offset, `__props.${propsLocalToPublicMap[id.name]}`);
  380. }
  381. }
  382. else {
  383. // x --> x.value
  384. s.appendLeft(id.end + offset, '.value');
  385. }
  386. }
  387. }
  388. return true;
  389. }
  390. return false;
  391. }
  392. const propBindingRefs = {};
  393. function registerEscapedPropBinding(id) {
  394. if (!propBindingRefs.hasOwnProperty(id.name)) {
  395. propBindingRefs[id.name] = true;
  396. const publicKey = propsLocalToPublicMap[id.name];
  397. s.prependRight(offset, `const __props_${publicKey} = ${helper(`toRef`)}(__props, '${publicKey}')\n`);
  398. }
  399. }
  400. // check root scope first
  401. walkScope(ast, true);
  402. estreeWalker.walk(ast, {
  403. enter(node, parent) {
  404. parent && parentStack.push(parent);
  405. // function scopes
  406. if (compilerCore.isFunctionType(node)) {
  407. scopeStack.push((currentScope = {}));
  408. compilerCore.walkFunctionParams(node, registerBinding);
  409. if (node.body.type === 'BlockStatement') {
  410. walkScope(node.body);
  411. }
  412. return;
  413. }
  414. // non-function block scopes
  415. if (node.type === 'BlockStatement' && !compilerCore.isFunctionType(parent)) {
  416. scopeStack.push((currentScope = {}));
  417. walkScope(node);
  418. return;
  419. }
  420. if (parent &&
  421. parent.type.startsWith('TS') &&
  422. parent.type !== 'TSAsExpression' &&
  423. parent.type !== 'TSNonNullExpression' &&
  424. parent.type !== 'TSTypeAssertion') {
  425. return this.skip();
  426. }
  427. if (node.type === 'Identifier' &&
  428. // if inside $$(), skip unless this is a destructured prop binding
  429. !(escapeScope && rootScope[node.name] !== 'prop') &&
  430. compilerCore.isReferencedIdentifier(node, parent, parentStack) &&
  431. !excludedIds.has(node)) {
  432. // walk up the scope chain to check if id should be appended .value
  433. let i = scopeStack.length;
  434. while (i--) {
  435. if (rewriteId(scopeStack[i], node, parent, parentStack)) {
  436. return;
  437. }
  438. }
  439. }
  440. if (node.type === 'CallExpression' && node.callee.type === 'Identifier') {
  441. const callee = node.callee.name;
  442. const refCall = isRefCreationCall(callee);
  443. if (refCall && (!parent || parent.type !== 'VariableDeclarator')) {
  444. return error(`${refCall} can only be used as the initializer of ` +
  445. `a variable declaration.`, node);
  446. }
  447. if (callee === escapeSymbol) {
  448. s.remove(node.callee.start + offset, node.callee.end + offset);
  449. escapeScope = node;
  450. }
  451. // TODO remove when out of experimental
  452. if (callee === '$raw') {
  453. error(`$raw() has been replaced by $$(). ` +
  454. `See ${RFC_LINK} for latest updates.`, node);
  455. }
  456. if (callee === '$fromRef') {
  457. error(`$fromRef() has been replaced by $(). ` +
  458. `See ${RFC_LINK} for latest updates.`, node);
  459. }
  460. }
  461. },
  462. leave(node, parent) {
  463. parent && parentStack.pop();
  464. if ((node.type === 'BlockStatement' && !compilerCore.isFunctionType(parent)) ||
  465. compilerCore.isFunctionType(node)) {
  466. scopeStack.pop();
  467. currentScope = scopeStack[scopeStack.length - 1] || null;
  468. }
  469. if (node === escapeScope) {
  470. escapeScope = undefined;
  471. }
  472. }
  473. });
  474. return {
  475. rootRefs: Object.keys(rootScope).filter(key => rootScope[key] === true),
  476. importedHelpers: [...importedHelpers]
  477. };
  478. }
  479. const RFC_LINK = `https://github.com/vuejs/rfcs/discussions/369`;
  480. const hasWarned = {};
  481. function warnExperimental() {
  482. // eslint-disable-next-line
  483. if (typeof window !== 'undefined') {
  484. return;
  485. }
  486. warnOnce(`Reactivity transform is an experimental feature.\n` +
  487. `Experimental features may change behavior between patch versions.\n` +
  488. `It is recommended to pin your vue dependencies to exact versions to avoid breakage.\n` +
  489. `You can follow the proposal's status at ${RFC_LINK}.`);
  490. }
  491. function warnOnce(msg) {
  492. const isNodeProd = typeof process !== 'undefined' && process.env.NODE_ENV === 'production';
  493. if (!isNodeProd && !false && !hasWarned[msg]) {
  494. hasWarned[msg] = true;
  495. warn(msg);
  496. }
  497. }
  498. function warn(msg) {
  499. console.warn(`\x1b[1m\x1b[33m[@vue/ref-transform]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`);
  500. }
  501. exports.shouldTransform = shouldTransform;
  502. exports.transform = transform;
  503. exports.transformAST = transformAST;