async.cjs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. const path = require('path');
  3. const {promisify} = require('util');
  4. const readFile = promisify(require('fs').readFile);
  5. const isNodeModules = require('./is-node-modules.cjs');
  6. const resultsCache = require('./cache.cjs');
  7. const promiseCache = new Map();
  8. async function getDirectoryTypeActual(directory) {
  9. if (isNodeModules(directory)) {
  10. return 'commonjs';
  11. }
  12. try {
  13. return JSON.parse(await readFile(path.resolve(directory, 'package.json'))).type || 'commonjs';
  14. } catch (_) {
  15. }
  16. const parent = path.dirname(directory);
  17. if (parent === directory) {
  18. return 'commonjs';
  19. }
  20. return getDirectoryType(parent);
  21. }
  22. async function getDirectoryType(directory) {
  23. if (resultsCache.has(directory)) {
  24. return resultsCache.get(directory);
  25. }
  26. if (promiseCache.has(directory)) {
  27. return promiseCache.get(directory);
  28. }
  29. const promise = getDirectoryTypeActual(directory);
  30. promiseCache.set(directory, promise);
  31. const result = await promise;
  32. resultsCache.set(directory, result);
  33. promiseCache.delete(directory);
  34. return result;
  35. }
  36. function getPackageType(filename) {
  37. return getDirectoryType(path.resolve(path.dirname(filename)));
  38. }
  39. module.exports = getPackageType;