index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  4. var path = require('path');
  5. var pm = _interopDefault(require('picomatch'));
  6. const addExtension = function addExtension(filename, ext = '.js') {
  7. let result = `${filename}`;
  8. if (!path.extname(filename))
  9. result += ext;
  10. return result;
  11. };
  12. function walk(ast, { enter, leave }) {
  13. return visit(ast, null, enter, leave);
  14. }
  15. let should_skip = false;
  16. let should_remove = false;
  17. let replacement = null;
  18. const context = {
  19. skip: () => should_skip = true,
  20. remove: () => should_remove = true,
  21. replace: (node) => replacement = node
  22. };
  23. function replace(parent, prop, index, node) {
  24. if (parent) {
  25. if (index !== null) {
  26. parent[prop][index] = node;
  27. } else {
  28. parent[prop] = node;
  29. }
  30. }
  31. }
  32. function remove(parent, prop, index) {
  33. if (parent) {
  34. if (index !== null) {
  35. parent[prop].splice(index, 1);
  36. } else {
  37. delete parent[prop];
  38. }
  39. }
  40. }
  41. function visit(
  42. node,
  43. parent,
  44. enter,
  45. leave,
  46. prop,
  47. index
  48. ) {
  49. if (node) {
  50. if (enter) {
  51. const _should_skip = should_skip;
  52. const _should_remove = should_remove;
  53. const _replacement = replacement;
  54. should_skip = false;
  55. should_remove = false;
  56. replacement = null;
  57. enter.call(context, node, parent, prop, index);
  58. if (replacement) {
  59. node = replacement;
  60. replace(parent, prop, index, node);
  61. }
  62. if (should_remove) {
  63. remove(parent, prop, index);
  64. }
  65. const skipped = should_skip;
  66. const removed = should_remove;
  67. should_skip = _should_skip;
  68. should_remove = _should_remove;
  69. replacement = _replacement;
  70. if (skipped) return node;
  71. if (removed) return null;
  72. }
  73. for (const key in node) {
  74. const value = (node )[key];
  75. if (typeof value !== 'object') {
  76. continue;
  77. }
  78. else if (Array.isArray(value)) {
  79. for (let j = 0, k = 0; j < value.length; j += 1, k += 1) {
  80. if (value[j] !== null && typeof value[j].type === 'string') {
  81. if (!visit(value[j], node, enter, leave, key, k)) {
  82. // removed
  83. j--;
  84. }
  85. }
  86. }
  87. }
  88. else if (value !== null && typeof value.type === 'string') {
  89. visit(value, node, enter, leave, key, null);
  90. }
  91. }
  92. if (leave) {
  93. const _replacement = replacement;
  94. const _should_remove = should_remove;
  95. replacement = null;
  96. should_remove = false;
  97. leave.call(context, node, parent, prop, index);
  98. if (replacement) {
  99. node = replacement;
  100. replace(parent, prop, index, node);
  101. }
  102. if (should_remove) {
  103. remove(parent, prop, index);
  104. }
  105. const removed = should_remove;
  106. replacement = _replacement;
  107. should_remove = _should_remove;
  108. if (removed) return null;
  109. }
  110. }
  111. return node;
  112. }
  113. const extractors = {
  114. ArrayPattern(names, param) {
  115. for (const element of param.elements) {
  116. if (element)
  117. extractors[element.type](names, element);
  118. }
  119. },
  120. AssignmentPattern(names, param) {
  121. extractors[param.left.type](names, param.left);
  122. },
  123. Identifier(names, param) {
  124. names.push(param.name);
  125. },
  126. MemberExpression() { },
  127. ObjectPattern(names, param) {
  128. for (const prop of param.properties) {
  129. // @ts-ignore Typescript reports that this is not a valid type
  130. if (prop.type === 'RestElement') {
  131. extractors.RestElement(names, prop);
  132. }
  133. else {
  134. extractors[prop.value.type](names, prop.value);
  135. }
  136. }
  137. },
  138. RestElement(names, param) {
  139. extractors[param.argument.type](names, param.argument);
  140. }
  141. };
  142. const extractAssignedNames = function extractAssignedNames(param) {
  143. const names = [];
  144. extractors[param.type](names, param);
  145. return names;
  146. };
  147. const blockDeclarations = {
  148. const: true,
  149. let: true
  150. };
  151. class Scope {
  152. constructor(options = {}) {
  153. this.parent = options.parent;
  154. this.isBlockScope = !!options.block;
  155. this.declarations = Object.create(null);
  156. if (options.params) {
  157. options.params.forEach((param) => {
  158. extractAssignedNames(param).forEach((name) => {
  159. this.declarations[name] = true;
  160. });
  161. });
  162. }
  163. }
  164. addDeclaration(node, isBlockDeclaration, isVar) {
  165. if (!isBlockDeclaration && this.isBlockScope) {
  166. // it's a `var` or function node, and this
  167. // is a block scope, so we need to go up
  168. this.parent.addDeclaration(node, isBlockDeclaration, isVar);
  169. }
  170. else if (node.id) {
  171. extractAssignedNames(node.id).forEach((name) => {
  172. this.declarations[name] = true;
  173. });
  174. }
  175. }
  176. contains(name) {
  177. return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
  178. }
  179. }
  180. const attachScopes = function attachScopes(ast, propertyName = 'scope') {
  181. let scope = new Scope();
  182. walk(ast, {
  183. enter(n, parent) {
  184. const node = n;
  185. // function foo () {...}
  186. // class Foo {...}
  187. if (/(Function|Class)Declaration/.test(node.type)) {
  188. scope.addDeclaration(node, false, false);
  189. }
  190. // var foo = 1
  191. if (node.type === 'VariableDeclaration') {
  192. const { kind } = node;
  193. const isBlockDeclaration = blockDeclarations[kind];
  194. // don't add const/let declarations in the body of a for loop #113
  195. const parentType = parent ? parent.type : '';
  196. if (!(isBlockDeclaration && /ForOfStatement/.test(parentType))) {
  197. node.declarations.forEach((declaration) => {
  198. scope.addDeclaration(declaration, isBlockDeclaration, true);
  199. });
  200. }
  201. }
  202. let newScope;
  203. // create new function scope
  204. if (/Function/.test(node.type)) {
  205. const func = node;
  206. newScope = new Scope({
  207. parent: scope,
  208. block: false,
  209. params: func.params
  210. });
  211. // named function expressions - the name is considered
  212. // part of the function's scope
  213. if (func.type === 'FunctionExpression' && func.id) {
  214. newScope.addDeclaration(func, false, false);
  215. }
  216. }
  217. // create new block scope
  218. if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) {
  219. newScope = new Scope({
  220. parent: scope,
  221. block: true
  222. });
  223. }
  224. // catch clause has its own block scope
  225. if (node.type === 'CatchClause') {
  226. newScope = new Scope({
  227. parent: scope,
  228. params: node.param ? [node.param] : [],
  229. block: true
  230. });
  231. }
  232. if (newScope) {
  233. Object.defineProperty(node, propertyName, {
  234. value: newScope,
  235. configurable: true
  236. });
  237. scope = newScope;
  238. }
  239. },
  240. leave(n) {
  241. const node = n;
  242. if (node[propertyName])
  243. scope = scope.parent;
  244. }
  245. });
  246. return scope;
  247. };
  248. // Helper since Typescript can't detect readonly arrays with Array.isArray
  249. function isArray(arg) {
  250. return Array.isArray(arg);
  251. }
  252. function ensureArray(thing) {
  253. if (isArray(thing))
  254. return thing;
  255. if (thing == null)
  256. return [];
  257. return [thing];
  258. }
  259. function getMatcherString(id, resolutionBase) {
  260. if (resolutionBase === false) {
  261. return id;
  262. }
  263. // resolve('') is valid and will default to process.cwd()
  264. const basePath = path.resolve(resolutionBase || '')
  265. .split(path.sep)
  266. .join('/')
  267. // escape all possible (posix + win) path characters that might interfere with regex
  268. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  269. // Note that we use posix.join because:
  270. // 1. the basePath has been normalized to use /
  271. // 2. the incoming glob (id) matcher, also uses /
  272. // otherwise Node will force backslash (\) on windows
  273. return path.posix.join(basePath, id);
  274. }
  275. const createFilter = function createFilter(include, exclude, options) {
  276. const resolutionBase = options && options.resolve;
  277. const getMatcher = (id) => id instanceof RegExp
  278. ? id
  279. : {
  280. test: (what) => {
  281. // this refactor is a tad overly verbose but makes for easy debugging
  282. const pattern = getMatcherString(id, resolutionBase);
  283. const fn = pm(pattern, { dot: true });
  284. const result = fn(what);
  285. return result;
  286. }
  287. };
  288. const includeMatchers = ensureArray(include).map(getMatcher);
  289. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  290. return function result(id) {
  291. if (typeof id !== 'string')
  292. return false;
  293. if (/\0/.test(id))
  294. return false;
  295. const pathId = id.split(path.sep).join('/');
  296. for (let i = 0; i < excludeMatchers.length; ++i) {
  297. const matcher = excludeMatchers[i];
  298. if (matcher.test(pathId))
  299. return false;
  300. }
  301. for (let i = 0; i < includeMatchers.length; ++i) {
  302. const matcher = includeMatchers[i];
  303. if (matcher.test(pathId))
  304. return true;
  305. }
  306. return !includeMatchers.length;
  307. };
  308. };
  309. const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
  310. const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
  311. const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
  312. forbiddenIdentifiers.add('');
  313. const makeLegalIdentifier = function makeLegalIdentifier(str) {
  314. let identifier = str
  315. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  316. .replace(/[^$_a-zA-Z0-9]/g, '_');
  317. if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {
  318. identifier = `_${identifier}`;
  319. }
  320. return identifier || '_';
  321. };
  322. function stringify(obj) {
  323. return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
  324. }
  325. function serializeArray(arr, indent, baseIndent) {
  326. let output = '[';
  327. const separator = indent ? `\n${baseIndent}${indent}` : '';
  328. for (let i = 0; i < arr.length; i++) {
  329. const key = arr[i];
  330. output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`;
  331. }
  332. return `${output}${indent ? `\n${baseIndent}` : ''}]`;
  333. }
  334. function serializeObject(obj, indent, baseIndent) {
  335. let output = '{';
  336. const separator = indent ? `\n${baseIndent}${indent}` : '';
  337. const entries = Object.entries(obj);
  338. for (let i = 0; i < entries.length; i++) {
  339. const [key, value] = entries[i];
  340. const stringKey = makeLegalIdentifier(key) === key ? key : stringify(key);
  341. output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`;
  342. }
  343. return `${output}${indent ? `\n${baseIndent}` : ''}}`;
  344. }
  345. function serialize(obj, indent, baseIndent) {
  346. if (obj === Infinity)
  347. return 'Infinity';
  348. if (obj === -Infinity)
  349. return '-Infinity';
  350. if (obj === 0 && 1 / obj === -Infinity)
  351. return '-0';
  352. if (obj instanceof Date)
  353. return `new Date(${obj.getTime()})`;
  354. if (obj instanceof RegExp)
  355. return obj.toString();
  356. if (obj !== obj)
  357. return 'NaN'; // eslint-disable-line no-self-compare
  358. if (Array.isArray(obj))
  359. return serializeArray(obj, indent, baseIndent);
  360. if (obj === null)
  361. return 'null';
  362. if (typeof obj === 'object')
  363. return serializeObject(obj, indent, baseIndent);
  364. return stringify(obj);
  365. }
  366. const dataToEsm = function dataToEsm(data, options = {}) {
  367. const t = options.compact ? '' : 'indent' in options ? options.indent : '\t';
  368. const _ = options.compact ? '' : ' ';
  369. const n = options.compact ? '' : '\n';
  370. const declarationType = options.preferConst ? 'const' : 'var';
  371. if (options.namedExports === false ||
  372. typeof data !== 'object' ||
  373. Array.isArray(data) ||
  374. data instanceof Date ||
  375. data instanceof RegExp ||
  376. data === null) {
  377. const code = serialize(data, options.compact ? null : t, '');
  378. const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape
  379. return `export default${magic}${code};`;
  380. }
  381. let namedExportCode = '';
  382. const defaultExportRows = [];
  383. for (const [key, value] of Object.entries(data)) {
  384. if (key === makeLegalIdentifier(key)) {
  385. if (options.objectShorthand)
  386. defaultExportRows.push(key);
  387. else
  388. defaultExportRows.push(`${key}:${_}${key}`);
  389. namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
  390. }
  391. else {
  392. defaultExportRows.push(`${stringify(key)}:${_}${serialize(value, options.compact ? null : t, '')}`);
  393. }
  394. }
  395. return `${namedExportCode}export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
  396. };
  397. // TODO: remove this in next major
  398. var index = {
  399. addExtension,
  400. attachScopes,
  401. createFilter,
  402. dataToEsm,
  403. extractAssignedNames,
  404. makeLegalIdentifier
  405. };
  406. exports.addExtension = addExtension;
  407. exports.attachScopes = attachScopes;
  408. exports.createFilter = createFilter;
  409. exports.dataToEsm = dataToEsm;
  410. exports.default = index;
  411. exports.extractAssignedNames = extractAssignedNames;
  412. exports.makeLegalIdentifier = makeLegalIdentifier;