index.mjs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. import fs, { promises } from 'node:fs';
  2. import fsp from 'node:fs/promises';
  3. import { createRequire } from 'node:module';
  4. import path, { dirname, win32, join } from 'node:path';
  5. import process from 'node:process';
  6. import { fileURLToPath } from 'node:url';
  7. import { interopDefault, resolvePathSync } from 'mlly';
  8. /*
  9. How it works:
  10. `this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.
  11. */
  12. class Node {
  13. value;
  14. next;
  15. constructor(value) {
  16. this.value = value;
  17. }
  18. }
  19. class Queue {
  20. #head;
  21. #tail;
  22. #size;
  23. constructor() {
  24. this.clear();
  25. }
  26. enqueue(value) {
  27. const node = new Node(value);
  28. if (this.#head) {
  29. this.#tail.next = node;
  30. this.#tail = node;
  31. } else {
  32. this.#head = node;
  33. this.#tail = node;
  34. }
  35. this.#size++;
  36. }
  37. dequeue() {
  38. const current = this.#head;
  39. if (!current) {
  40. return;
  41. }
  42. this.#head = this.#head.next;
  43. this.#size--;
  44. return current.value;
  45. }
  46. clear() {
  47. this.#head = undefined;
  48. this.#tail = undefined;
  49. this.#size = 0;
  50. }
  51. get size() {
  52. return this.#size;
  53. }
  54. * [Symbol.iterator]() {
  55. let current = this.#head;
  56. while (current) {
  57. yield current.value;
  58. current = current.next;
  59. }
  60. }
  61. }
  62. function pLimit(concurrency) {
  63. if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {
  64. throw new TypeError('Expected `concurrency` to be a number from 1 and up');
  65. }
  66. const queue = new Queue();
  67. let activeCount = 0;
  68. const next = () => {
  69. activeCount--;
  70. if (queue.size > 0) {
  71. queue.dequeue()();
  72. }
  73. };
  74. const run = async (fn, resolve, args) => {
  75. activeCount++;
  76. const result = (async () => fn(...args))();
  77. resolve(result);
  78. try {
  79. await result;
  80. } catch {}
  81. next();
  82. };
  83. const enqueue = (fn, resolve, args) => {
  84. queue.enqueue(run.bind(undefined, fn, resolve, args));
  85. (async () => {
  86. // This function needs to wait until the next microtask before comparing
  87. // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
  88. // when the run function is dequeued and called. The comparison in the if-statement
  89. // needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
  90. await Promise.resolve();
  91. if (activeCount < concurrency && queue.size > 0) {
  92. queue.dequeue()();
  93. }
  94. })();
  95. };
  96. const generator = (fn, ...args) => new Promise(resolve => {
  97. enqueue(fn, resolve, args);
  98. });
  99. Object.defineProperties(generator, {
  100. activeCount: {
  101. get: () => activeCount,
  102. },
  103. pendingCount: {
  104. get: () => queue.size,
  105. },
  106. clearQueue: {
  107. value: () => {
  108. queue.clear();
  109. },
  110. },
  111. });
  112. return generator;
  113. }
  114. class EndError extends Error {
  115. constructor(value) {
  116. super();
  117. this.value = value;
  118. }
  119. }
  120. // The input can also be a promise, so we await it.
  121. const testElement = async (element, tester) => tester(await element);
  122. // The input can also be a promise, so we `Promise.all()` them both.
  123. const finder = async element => {
  124. const values = await Promise.all(element);
  125. if (values[1] === true) {
  126. throw new EndError(values[0]);
  127. }
  128. return false;
  129. };
  130. async function pLocate(
  131. iterable,
  132. tester,
  133. {
  134. concurrency = Number.POSITIVE_INFINITY,
  135. preserveOrder = true,
  136. } = {},
  137. ) {
  138. const limit = pLimit(concurrency);
  139. // Start all the promises concurrently with optional limit.
  140. const items = [...iterable].map(element => [element, limit(testElement, element, tester)]);
  141. // Check the promises either serially or concurrently.
  142. const checkLimit = pLimit(preserveOrder ? 1 : Number.POSITIVE_INFINITY);
  143. try {
  144. await Promise.all(items.map(element => checkLimit(finder, element)));
  145. } catch (error) {
  146. if (error instanceof EndError) {
  147. return error.value;
  148. }
  149. throw error;
  150. }
  151. }
  152. const typeMappings = {
  153. directory: 'isDirectory',
  154. file: 'isFile',
  155. };
  156. function checkType(type) {
  157. if (Object.hasOwnProperty.call(typeMappings, type)) {
  158. return;
  159. }
  160. throw new Error(`Invalid type specified: ${type}`);
  161. }
  162. const matchType = (type, stat) => stat[typeMappings[type]]();
  163. const toPath$1 = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;
  164. async function locatePath(
  165. paths,
  166. {
  167. cwd = process.cwd(),
  168. type = 'file',
  169. allowSymlinks = true,
  170. concurrency,
  171. preserveOrder,
  172. } = {},
  173. ) {
  174. checkType(type);
  175. cwd = toPath$1(cwd);
  176. const statFunction = allowSymlinks ? promises.stat : promises.lstat;
  177. return pLocate(paths, async path_ => {
  178. try {
  179. const stat = await statFunction(path.resolve(cwd, path_));
  180. return matchType(type, stat);
  181. } catch {
  182. return false;
  183. }
  184. }, {concurrency, preserveOrder});
  185. }
  186. const toPath = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;
  187. const findUpStop = Symbol('findUpStop');
  188. async function findUpMultiple(name, options = {}) {
  189. let directory = path.resolve(toPath(options.cwd) || '');
  190. const {root} = path.parse(directory);
  191. const stopAt = path.resolve(directory, options.stopAt || root);
  192. const limit = options.limit || Number.POSITIVE_INFINITY;
  193. const paths = [name].flat();
  194. const runMatcher = async locateOptions => {
  195. if (typeof name !== 'function') {
  196. return locatePath(paths, locateOptions);
  197. }
  198. const foundPath = await name(locateOptions.cwd);
  199. if (typeof foundPath === 'string') {
  200. return locatePath([foundPath], locateOptions);
  201. }
  202. return foundPath;
  203. };
  204. const matches = [];
  205. // eslint-disable-next-line no-constant-condition
  206. while (true) {
  207. // eslint-disable-next-line no-await-in-loop
  208. const foundPath = await runMatcher({...options, cwd: directory});
  209. if (foundPath === findUpStop) {
  210. break;
  211. }
  212. if (foundPath) {
  213. matches.push(path.resolve(directory, foundPath));
  214. }
  215. if (directory === stopAt || matches.length >= limit) {
  216. break;
  217. }
  218. directory = path.dirname(directory);
  219. }
  220. return matches;
  221. }
  222. async function findUp(name, options = {}) {
  223. const matches = await findUpMultiple(name, {...options, limit: 1});
  224. return matches[0];
  225. }
  226. function _resolve(path, options = {}) {
  227. if (options.platform === "auto" || !options.platform)
  228. options.platform = process.platform === "win32" ? "win32" : "posix";
  229. if (process.versions.pnp) {
  230. const paths = options.paths || [];
  231. if (paths.length === 0)
  232. paths.push(process.cwd());
  233. const targetRequire = createRequire(import.meta.url);
  234. try {
  235. return targetRequire.resolve(path, { paths });
  236. } catch {
  237. }
  238. }
  239. const modulePath = resolvePathSync(path, {
  240. url: options.paths
  241. });
  242. if (options.platform === "win32")
  243. return win32.normalize(modulePath);
  244. return modulePath;
  245. }
  246. function resolveModule(name, options = {}) {
  247. try {
  248. return _resolve(name, options);
  249. } catch {
  250. return void 0;
  251. }
  252. }
  253. async function importModule(path) {
  254. const i = await import(path);
  255. if (i)
  256. return interopDefault(i);
  257. return i;
  258. }
  259. function isPackageExists(name, options = {}) {
  260. return !!resolvePackage(name, options);
  261. }
  262. function getPackageJsonPath(name, options = {}) {
  263. const entry = resolvePackage(name, options);
  264. if (!entry)
  265. return;
  266. return searchPackageJSON(entry);
  267. }
  268. async function getPackageInfo(name, options = {}) {
  269. const packageJsonPath = getPackageJsonPath(name, options);
  270. if (!packageJsonPath)
  271. return;
  272. const packageJson = JSON.parse(await fs.promises.readFile(packageJsonPath, "utf8"));
  273. return {
  274. name,
  275. version: packageJson.version,
  276. rootPath: dirname(packageJsonPath),
  277. packageJsonPath,
  278. packageJson
  279. };
  280. }
  281. function getPackageInfoSync(name, options = {}) {
  282. const packageJsonPath = getPackageJsonPath(name, options);
  283. if (!packageJsonPath)
  284. return;
  285. const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
  286. return {
  287. name,
  288. version: packageJson.version,
  289. rootPath: dirname(packageJsonPath),
  290. packageJsonPath,
  291. packageJson
  292. };
  293. }
  294. function resolvePackage(name, options = {}) {
  295. try {
  296. return _resolve(`${name}/package.json`, options);
  297. } catch {
  298. }
  299. try {
  300. return _resolve(name, options);
  301. } catch (e) {
  302. if (e.code !== "MODULE_NOT_FOUND" && e.code !== "ERR_MODULE_NOT_FOUND")
  303. console.error(e);
  304. return false;
  305. }
  306. }
  307. function searchPackageJSON(dir) {
  308. let packageJsonPath;
  309. while (true) {
  310. if (!dir)
  311. return;
  312. const newDir = dirname(dir);
  313. if (newDir === dir)
  314. return;
  315. dir = newDir;
  316. packageJsonPath = join(dir, "package.json");
  317. if (fs.existsSync(packageJsonPath))
  318. break;
  319. }
  320. return packageJsonPath;
  321. }
  322. async function loadPackageJSON(cwd = process.cwd()) {
  323. const path = await findUp("package.json", { cwd });
  324. if (!path || !fs.existsSync(path))
  325. return null;
  326. return JSON.parse(await fsp.readFile(path, "utf-8"));
  327. }
  328. async function isPackageListed(name, cwd) {
  329. const pkg = await loadPackageJSON(cwd) || {};
  330. return name in (pkg.dependencies || {}) || name in (pkg.devDependencies || {});
  331. }
  332. export { getPackageInfo, getPackageInfoSync, importModule, isPackageExists, isPackageListed, loadPackageJSON, resolveModule };