concatenate.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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, ...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. }
  116. let i = 0;
  117. let nameWithNumber = Template.toIdentifier(`${name}_${i}`);
  118. while (
  119. usedNamed1.has(nameWithNumber) ||
  120. // eslint-disable-next-line no-unmodified-loop-condition
  121. (usedNamed2 && usedNamed2.has(nameWithNumber))
  122. ) {
  123. i++;
  124. nameWithNumber = Template.toIdentifier(`${name}_${i}`);
  125. }
  126. return nameWithNumber;
  127. }
  128. /** @typedef {Set<Scope>} ScopeSet */
  129. /**
  130. * @param {Scope | null} s scope
  131. * @param {UsedNames} nameSet name set
  132. * @param {ScopeSet} scopeSet1 scope set 1
  133. * @param {ScopeSet} scopeSet2 scope set 2
  134. */
  135. const addScopeSymbols = (s, nameSet, scopeSet1, scopeSet2) => {
  136. let scope = s;
  137. while (scope) {
  138. if (scopeSet1.has(scope)) break;
  139. if (scopeSet2.has(scope)) break;
  140. scopeSet1.add(scope);
  141. for (const variable of scope.variables) {
  142. nameSet.add(variable.name);
  143. }
  144. scope = scope.upper;
  145. }
  146. };
  147. const RESERVED_NAMES = new Set(
  148. [
  149. // internal names (should always be renamed)
  150. DEFAULT_EXPORT,
  151. NAMESPACE_OBJECT_EXPORT,
  152. // keywords
  153. "abstract,arguments,async,await,boolean,break,byte,case,catch,char,class,const,continue",
  154. "debugger,default,delete,do,double,else,enum,eval,export,extends,false,final,finally,float",
  155. "for,function,goto,if,implements,import,in,instanceof,int,interface,let,long,native,new,null",
  156. "package,private,protected,public,return,short,static,super,switch,synchronized,this,throw",
  157. "throws,transient,true,try,typeof,var,void,volatile,while,with,yield",
  158. // commonjs/amd
  159. "module,__dirname,__filename,exports,require,define",
  160. // js globals
  161. "Array,Date,eval,function,hasOwnProperty,Infinity,isFinite,isNaN,isPrototypeOf,length,Math",
  162. "NaN,name,Number,Object,prototype,String,Symbol,toString,undefined,valueOf",
  163. // browser globals
  164. "alert,all,anchor,anchors,area,assign,blur,button,checkbox,clearInterval,clearTimeout",
  165. "clientInformation,close,closed,confirm,constructor,crypto,decodeURI,decodeURIComponent",
  166. "defaultStatus,document,element,elements,embed,embeds,encodeURI,encodeURIComponent,escape",
  167. "event,fileUpload,focus,form,forms,frame,innerHeight,innerWidth,layer,layers,link,location",
  168. "mimeTypes,navigate,navigator,frames,frameRate,hidden,history,image,images,offscreenBuffering",
  169. "open,opener,option,outerHeight,outerWidth,packages,pageXOffset,pageYOffset,parent,parseFloat",
  170. "parseInt,password,pkcs11,plugin,prompt,propertyIsEnum,radio,reset,screenX,screenY,scroll",
  171. "secure,select,self,setInterval,setTimeout,status,submit,taint,text,textarea,top,unescape",
  172. "untaint,window",
  173. // window events
  174. "onblur,onclick,onerror,onfocus,onkeydown,onkeypress,onkeyup,onmouseover,onload,onmouseup,onmousedown,onsubmit"
  175. ]
  176. .join(",")
  177. .split(",")
  178. );
  179. /** @typedef {{ usedNames: UsedNames, alreadyCheckedScopes: ScopeSet }} ScopeInfo */
  180. /**
  181. * @param {Map<string, ScopeInfo>} usedNamesInScopeInfo used names in scope info
  182. * @param {string} module module identifier
  183. * @param {string} id export id
  184. * @returns {ScopeInfo} info
  185. */
  186. const getUsedNamesInScopeInfo = (usedNamesInScopeInfo, module, id) => {
  187. const key = `${module}-${id}`;
  188. let info = usedNamesInScopeInfo.get(key);
  189. if (info === undefined) {
  190. info = {
  191. usedNames: new Set(),
  192. alreadyCheckedScopes: new Set()
  193. };
  194. usedNamesInScopeInfo.set(key, info);
  195. }
  196. return info;
  197. };
  198. module.exports = {
  199. DEFAULT_EXPORT,
  200. NAMESPACE_OBJECT_EXPORT,
  201. RESERVED_NAMES,
  202. addScopeSymbols,
  203. findNewName,
  204. getAllReferences,
  205. getPathInAst,
  206. getUsedNamesInScopeInfo
  207. };