index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var path = require('path');
  4. var estreeWalker = require('estree-walker');
  5. var pm = 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. const extractors = {
  13. ArrayPattern(names, param) {
  14. for (const element of param.elements) {
  15. if (element)
  16. extractors[element.type](names, element);
  17. }
  18. },
  19. AssignmentPattern(names, param) {
  20. extractors[param.left.type](names, param.left);
  21. },
  22. Identifier(names, param) {
  23. names.push(param.name);
  24. },
  25. MemberExpression() { },
  26. ObjectPattern(names, param) {
  27. for (const prop of param.properties) {
  28. // @ts-ignore Typescript reports that this is not a valid type
  29. if (prop.type === 'RestElement') {
  30. extractors.RestElement(names, prop);
  31. }
  32. else {
  33. extractors[prop.value.type](names, prop.value);
  34. }
  35. }
  36. },
  37. RestElement(names, param) {
  38. extractors[param.argument.type](names, param.argument);
  39. }
  40. };
  41. const extractAssignedNames = function extractAssignedNames(param) {
  42. const names = [];
  43. extractors[param.type](names, param);
  44. return names;
  45. };
  46. const blockDeclarations = {
  47. const: true,
  48. let: true
  49. };
  50. class Scope {
  51. constructor(options = {}) {
  52. this.parent = options.parent;
  53. this.isBlockScope = !!options.block;
  54. this.declarations = Object.create(null);
  55. if (options.params) {
  56. options.params.forEach((param) => {
  57. extractAssignedNames(param).forEach((name) => {
  58. this.declarations[name] = true;
  59. });
  60. });
  61. }
  62. }
  63. addDeclaration(node, isBlockDeclaration, isVar) {
  64. if (!isBlockDeclaration && this.isBlockScope) {
  65. // it's a `var` or function node, and this
  66. // is a block scope, so we need to go up
  67. this.parent.addDeclaration(node, isBlockDeclaration, isVar);
  68. }
  69. else if (node.id) {
  70. extractAssignedNames(node.id).forEach((name) => {
  71. this.declarations[name] = true;
  72. });
  73. }
  74. }
  75. contains(name) {
  76. return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
  77. }
  78. }
  79. const attachScopes = function attachScopes(ast, propertyName = 'scope') {
  80. let scope = new Scope();
  81. estreeWalker.walk(ast, {
  82. enter(n, parent) {
  83. const node = n;
  84. // function foo () {...}
  85. // class Foo {...}
  86. if (/(Function|Class)Declaration/.test(node.type)) {
  87. scope.addDeclaration(node, false, false);
  88. }
  89. // var foo = 1
  90. if (node.type === 'VariableDeclaration') {
  91. const { kind } = node;
  92. const isBlockDeclaration = blockDeclarations[kind];
  93. node.declarations.forEach((declaration) => {
  94. scope.addDeclaration(declaration, isBlockDeclaration, true);
  95. });
  96. }
  97. let newScope;
  98. // create new function scope
  99. if (/Function/.test(node.type)) {
  100. const func = node;
  101. newScope = new Scope({
  102. parent: scope,
  103. block: false,
  104. params: func.params
  105. });
  106. // named function expressions - the name is considered
  107. // part of the function's scope
  108. if (func.type === 'FunctionExpression' && func.id) {
  109. newScope.addDeclaration(func, false, false);
  110. }
  111. }
  112. // create new for scope
  113. if (/For(In|Of)?Statement/.test(node.type)) {
  114. newScope = new Scope({
  115. parent: scope,
  116. block: true
  117. });
  118. }
  119. // create new block scope
  120. if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) {
  121. newScope = new Scope({
  122. parent: scope,
  123. block: true
  124. });
  125. }
  126. // catch clause has its own block scope
  127. if (node.type === 'CatchClause') {
  128. newScope = new Scope({
  129. parent: scope,
  130. params: node.param ? [node.param] : [],
  131. block: true
  132. });
  133. }
  134. if (newScope) {
  135. Object.defineProperty(node, propertyName, {
  136. value: newScope,
  137. configurable: true
  138. });
  139. scope = newScope;
  140. }
  141. },
  142. leave(n) {
  143. const node = n;
  144. if (node[propertyName])
  145. scope = scope.parent;
  146. }
  147. });
  148. return scope;
  149. };
  150. // Helper since Typescript can't detect readonly arrays with Array.isArray
  151. function isArray(arg) {
  152. return Array.isArray(arg);
  153. }
  154. function ensureArray(thing) {
  155. if (isArray(thing))
  156. return thing;
  157. if (thing == null)
  158. return [];
  159. return [thing];
  160. }
  161. const normalizePath = function normalizePath(filename) {
  162. return filename.split(path.win32.sep).join(path.posix.sep);
  163. };
  164. function getMatcherString(id, resolutionBase) {
  165. if (resolutionBase === false || path.isAbsolute(id) || id.startsWith('*')) {
  166. return normalizePath(id);
  167. }
  168. // resolve('') is valid and will default to process.cwd()
  169. const basePath = normalizePath(path.resolve(resolutionBase || ''))
  170. // escape all possible (posix + win) path characters that might interfere with regex
  171. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  172. // Note that we use posix.join because:
  173. // 1. the basePath has been normalized to use /
  174. // 2. the incoming glob (id) matcher, also uses /
  175. // otherwise Node will force backslash (\) on windows
  176. return path.posix.join(basePath, normalizePath(id));
  177. }
  178. const createFilter = function createFilter(include, exclude, options) {
  179. const resolutionBase = options && options.resolve;
  180. const getMatcher = (id) => id instanceof RegExp
  181. ? id
  182. : {
  183. test: (what) => {
  184. // this refactor is a tad overly verbose but makes for easy debugging
  185. const pattern = getMatcherString(id, resolutionBase);
  186. const fn = pm(pattern, { dot: true });
  187. const result = fn(what);
  188. return result;
  189. }
  190. };
  191. const includeMatchers = ensureArray(include).map(getMatcher);
  192. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  193. return function result(id) {
  194. if (typeof id !== 'string')
  195. return false;
  196. if (/\0/.test(id))
  197. return false;
  198. const pathId = normalizePath(id);
  199. for (let i = 0; i < excludeMatchers.length; ++i) {
  200. const matcher = excludeMatchers[i];
  201. if (matcher.test(pathId))
  202. return false;
  203. }
  204. for (let i = 0; i < includeMatchers.length; ++i) {
  205. const matcher = includeMatchers[i];
  206. if (matcher.test(pathId))
  207. return true;
  208. }
  209. return !includeMatchers.length;
  210. };
  211. };
  212. 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';
  213. 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';
  214. const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
  215. forbiddenIdentifiers.add('');
  216. const makeLegalIdentifier = function makeLegalIdentifier(str) {
  217. let identifier = str
  218. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  219. .replace(/[^$_a-zA-Z0-9]/g, '_');
  220. if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {
  221. identifier = `_${identifier}`;
  222. }
  223. return identifier || '_';
  224. };
  225. function stringify(obj) {
  226. return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
  227. }
  228. function serializeArray(arr, indent, baseIndent) {
  229. let output = '[';
  230. const separator = indent ? `\n${baseIndent}${indent}` : '';
  231. for (let i = 0; i < arr.length; i++) {
  232. const key = arr[i];
  233. output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`;
  234. }
  235. return `${output}${indent ? `\n${baseIndent}` : ''}]`;
  236. }
  237. function serializeObject(obj, indent, baseIndent) {
  238. let output = '{';
  239. const separator = indent ? `\n${baseIndent}${indent}` : '';
  240. const entries = Object.entries(obj);
  241. for (let i = 0; i < entries.length; i++) {
  242. const [key, value] = entries[i];
  243. const stringKey = makeLegalIdentifier(key) === key ? key : stringify(key);
  244. output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`;
  245. }
  246. return `${output}${indent ? `\n${baseIndent}` : ''}}`;
  247. }
  248. function serialize(obj, indent, baseIndent) {
  249. if (typeof obj === 'object' && obj !== null) {
  250. if (Array.isArray(obj))
  251. return serializeArray(obj, indent, baseIndent);
  252. if (obj instanceof Date)
  253. return `new Date(${obj.getTime()})`;
  254. if (obj instanceof RegExp)
  255. return obj.toString();
  256. return serializeObject(obj, indent, baseIndent);
  257. }
  258. if (typeof obj === 'number') {
  259. if (obj === Infinity)
  260. return 'Infinity';
  261. if (obj === -Infinity)
  262. return '-Infinity';
  263. if (obj === 0)
  264. return 1 / obj === Infinity ? '0' : '-0';
  265. if (obj !== obj)
  266. return 'NaN'; // eslint-disable-line no-self-compare
  267. }
  268. if (typeof obj === 'symbol') {
  269. const key = Symbol.keyFor(obj);
  270. // eslint-disable-next-line no-undefined
  271. if (key !== undefined)
  272. return `Symbol.for(${stringify(key)})`;
  273. }
  274. if (typeof obj === 'bigint')
  275. return `${obj}n`;
  276. return stringify(obj);
  277. }
  278. const dataToEsm = function dataToEsm(data, options = {}) {
  279. const t = options.compact ? '' : 'indent' in options ? options.indent : '\t';
  280. const _ = options.compact ? '' : ' ';
  281. const n = options.compact ? '' : '\n';
  282. const declarationType = options.preferConst ? 'const' : 'var';
  283. if (options.namedExports === false ||
  284. typeof data !== 'object' ||
  285. Array.isArray(data) ||
  286. data instanceof Date ||
  287. data instanceof RegExp ||
  288. data === null) {
  289. const code = serialize(data, options.compact ? null : t, '');
  290. const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape
  291. return `export default${magic}${code};`;
  292. }
  293. let namedExportCode = '';
  294. const defaultExportRows = [];
  295. for (const [key, value] of Object.entries(data)) {
  296. if (key === makeLegalIdentifier(key)) {
  297. if (options.objectShorthand)
  298. defaultExportRows.push(key);
  299. else
  300. defaultExportRows.push(`${key}:${_}${key}`);
  301. namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
  302. }
  303. else {
  304. defaultExportRows.push(`${stringify(key)}:${_}${serialize(value, options.compact ? null : t, '')}`);
  305. }
  306. }
  307. return `${namedExportCode}export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
  308. };
  309. // TODO: remove this in next major
  310. var index = {
  311. addExtension,
  312. attachScopes,
  313. createFilter,
  314. dataToEsm,
  315. extractAssignedNames,
  316. makeLegalIdentifier,
  317. normalizePath
  318. };
  319. exports.addExtension = addExtension;
  320. exports.attachScopes = attachScopes;
  321. exports.createFilter = createFilter;
  322. exports.dataToEsm = dataToEsm;
  323. exports.default = index;
  324. exports.extractAssignedNames = extractAssignedNames;
  325. exports.makeLegalIdentifier = makeLegalIdentifier;
  326. exports.normalizePath = normalizePath;
  327. module.exports = Object.assign(exports.default, exports);
  328. //# sourceMappingURL=index.js.map