concatenate.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const Template = require("../Template");
  7. /** @typedef {import("eslint-scope").Scope} Scope */
  8. /** @typedef {import("eslint-scope").Reference} Reference */
  9. /** @typedef {import("eslint-scope").Variable} Variable */
  10. /** @typedef {import("estree").Node} Node */
  11. /** @typedef {import("../javascript/JavascriptParser").Range} Range */
  12. /** @typedef {import("../javascript/JavascriptParser").Program} Program */
  13. /** @typedef {Set<string>} UsedNames */
  14. const DEFAULT_EXPORT = "__WEBPACK_DEFAULT_EXPORT__";
  15. const NAMESPACE_OBJECT_EXPORT = "__WEBPACK_NAMESPACE_OBJECT__";
  16. /**
  17. * @param {Variable} variable variable
  18. * @returns {Reference[]} references
  19. */
  20. const getAllReferences = variable => {
  21. let set = variable.references;
  22. // Look for inner scope variables too (like in class Foo { t() { Foo } })
  23. const identifiers = new Set(variable.identifiers);
  24. for (const scope of variable.scope.childScopes) {
  25. for (const innerVar of scope.variables) {
  26. if (innerVar.identifiers.some(id => identifiers.has(id))) {
  27. set = set.concat(innerVar.references);
  28. break;
  29. }
  30. }
  31. }
  32. return set;
  33. };
  34. /**
  35. * @param {Node | Node[]} ast ast
  36. * @param {Node} node node
  37. * @returns {undefined | Node[]} result
  38. */
  39. const getPathInAst = (ast, node) => {
  40. if (ast === node) {
  41. return [];
  42. }
  43. const nr = /** @type {Range} */ (node.range);
  44. /**
  45. * @param {Node} n node
  46. * @returns {Node[] | undefined} result
  47. */
  48. const enterNode = n => {
  49. if (!n) return;
  50. const r = n.range;
  51. if (r && r[0] <= nr[0] && r[1] >= nr[1]) {
  52. const path = getPathInAst(n, node);
  53. if (path) {
  54. path.push(n);
  55. return path;
  56. }
  57. }
  58. };
  59. if (Array.isArray(ast)) {
  60. for (let i = 0; i < ast.length; i++) {
  61. const enterResult = enterNode(ast[i]);
  62. if (enterResult !== undefined) return enterResult;
  63. }
  64. } else if (ast && typeof ast === "object") {
  65. const keys =
  66. /** @type {Array<keyof Node>} */
  67. (Object.keys(ast));
  68. for (let i = 0; i < keys.length; i++) {
  69. // We are making the faster check in `enterNode` using `n.range`
  70. const value =
  71. ast[
  72. /** @type {Exclude<keyof Node, "range" | "loc" | "leadingComments" | "trailingComments">} */
  73. (keys[i])
  74. ];
  75. if (Array.isArray(value)) {
  76. const pathResult = getPathInAst(value, node);
  77. if (pathResult !== undefined) return pathResult;
  78. } else if (value && typeof value === "object") {
  79. const enterResult = enterNode(value);
  80. if (enterResult !== undefined) return enterResult;
  81. }
  82. }
  83. }
  84. };
  85. /**
  86. * @param {string} oldName old name
  87. * @param {UsedNames} usedNamed1 used named 1
  88. * @param {UsedNames} usedNamed2 used named 2
  89. * @param {string} extraInfo extra info
  90. * @returns {string} found new name
  91. */
  92. function findNewName(oldName, usedNamed1, usedNamed2, extraInfo) {
  93. let name = oldName;
  94. if (name === DEFAULT_EXPORT) {
  95. name = "";
  96. }
  97. if (name === NAMESPACE_OBJECT_EXPORT) {
  98. name = "namespaceObject";
  99. }
  100. // Remove uncool stuff
  101. extraInfo = extraInfo.replace(
  102. /\.+\/|(\/index)?\.([a-zA-Z0-9]{1,4})($|\s|\?)|\s*\+\s*\d+\s*modules/g,
  103. ""
  104. );
  105. const splittedInfo = extraInfo.split("/");
  106. while (splittedInfo.length) {
  107. name = splittedInfo.pop() + (name ? `_${name}` : "");
  108. const nameIdent = Template.toIdentifier(name);
  109. if (
  110. !usedNamed1.has(nameIdent) &&
  111. (!usedNamed2 || !usedNamed2.has(nameIdent))
  112. )
  113. return nameIdent;
  114. }
  115. let i = 0;
  116. let nameWithNumber = Template.toIdentifier(`${name}_${i}`);
  117. while (
  118. usedNamed1.has(nameWithNumber) ||
  119. // eslint-disable-next-line no-unmodified-loop-condition
  120. (usedNamed2 && usedNamed2.has(nameWithNumber))
  121. ) {
  122. i++;
  123. nameWithNumber = Template.toIdentifier(`${name}_${i}`);
  124. }
  125. return nameWithNumber;
  126. }
  127. /**
  128. * @param {Scope | null} s scope
  129. * @param {UsedNames} nameSet name set
  130. * @param {TODO} scopeSet1 scope set 1
  131. * @param {TODO} scopeSet2 scope set 2
  132. */
  133. const addScopeSymbols = (s, nameSet, scopeSet1, scopeSet2) => {
  134. let scope = s;
  135. while (scope) {
  136. if (scopeSet1.has(scope)) break;
  137. if (scopeSet2.has(scope)) break;
  138. scopeSet1.add(scope);
  139. for (const variable of scope.variables) {
  140. nameSet.add(variable.name);
  141. }
  142. scope = scope.upper;
  143. }
  144. };
  145. const RESERVED_NAMES = new Set(
  146. [
  147. // internal names (should always be renamed)
  148. DEFAULT_EXPORT,
  149. NAMESPACE_OBJECT_EXPORT,
  150. // keywords
  151. "abstract,arguments,async,await,boolean,break,byte,case,catch,char,class,const,continue",
  152. "debugger,default,delete,do,double,else,enum,eval,export,extends,false,final,finally,float",
  153. "for,function,goto,if,implements,import,in,instanceof,int,interface,let,long,native,new,null",
  154. "package,private,protected,public,return,short,static,super,switch,synchronized,this,throw",
  155. "throws,transient,true,try,typeof,var,void,volatile,while,with,yield",
  156. // commonjs/amd
  157. "module,__dirname,__filename,exports,require,define",
  158. // js globals
  159. "Array,Date,eval,function,hasOwnProperty,Infinity,isFinite,isNaN,isPrototypeOf,length,Math",
  160. "NaN,name,Number,Object,prototype,String,Symbol,toString,undefined,valueOf",
  161. // browser globals
  162. "alert,all,anchor,anchors,area,assign,blur,button,checkbox,clearInterval,clearTimeout",
  163. "clientInformation,close,closed,confirm,constructor,crypto,decodeURI,decodeURIComponent",
  164. "defaultStatus,document,element,elements,embed,embeds,encodeURI,encodeURIComponent,escape",
  165. "event,fileUpload,focus,form,forms,frame,innerHeight,innerWidth,layer,layers,link,location",
  166. "mimeTypes,navigate,navigator,frames,frameRate,hidden,history,image,images,offscreenBuffering",
  167. "open,opener,option,outerHeight,outerWidth,packages,pageXOffset,pageYOffset,parent,parseFloat",
  168. "parseInt,password,pkcs11,plugin,prompt,propertyIsEnum,radio,reset,screenX,screenY,scroll",
  169. "secure,select,self,setInterval,setTimeout,status,submit,taint,text,textarea,top,unescape",
  170. "untaint,window",
  171. // window events
  172. "onblur,onclick,onerror,onfocus,onkeydown,onkeypress,onkeyup,onmouseover,onload,onmouseup,onmousedown,onsubmit"
  173. ]
  174. .join(",")
  175. .split(",")
  176. );
  177. /**
  178. * @param {Map<string, { usedNames: UsedNames, alreadyCheckedScopes: Set<TODO> }>} usedNamesInScopeInfo used names in scope info
  179. * @param {string} module module identifier
  180. * @param {string} id export id
  181. * @returns {{ usedNames: UsedNames, alreadyCheckedScopes: Set<TODO> }} info
  182. */
  183. const getUsedNamesInScopeInfo = (usedNamesInScopeInfo, module, id) => {
  184. const key = `${module}-${id}`;
  185. let info = usedNamesInScopeInfo.get(key);
  186. if (info === undefined) {
  187. info = {
  188. usedNames: new Set(),
  189. alreadyCheckedScopes: new Set()
  190. };
  191. usedNamesInScopeInfo.set(key, info);
  192. }
  193. return info;
  194. };
  195. module.exports = {
  196. getUsedNamesInScopeInfo,
  197. findNewName,
  198. getAllReferences,
  199. getPathInAst,
  200. NAMESPACE_OBJECT_EXPORT,
  201. DEFAULT_EXPORT,
  202. RESERVED_NAMES,
  203. addScopeSymbols
  204. };