index.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. const path = require(`path`);
  2. const {resolveModuleName} = require(`ts-pnp`);
  3. const {makeResolver} = require('./resolver');
  4. function nothing() {
  5. // ¯\_(ツ)_/¯
  6. }
  7. function getModuleLocator(module, pnpapi) {
  8. const moduleLocation = typeof module === `string`
  9. ? module
  10. : module.filename;
  11. if (!moduleLocation)
  12. throw new Error(`The specified module doesn't seem to exist on the filesystem`);
  13. const moduleLocator = pnpapi.findPackageLocator(moduleLocation);
  14. if (!moduleLocator)
  15. throw new Error(`the specified module doesn't seem to be part of the dependency tree`);
  16. return moduleLocator;
  17. }
  18. function getDependencyLocator(sourceLocator, name, pnpapi) {
  19. const {packageDependencies} = pnpapi.getPackageInformation(sourceLocator);
  20. const reference = packageDependencies.get(name);
  21. return {name, reference};
  22. }
  23. module.exports = process.versions.pnp ? {
  24. apply: makeResolver({pnpapi: require(`pnpapi`)}),
  25. } : {
  26. apply: nothing,
  27. };
  28. module.exports.makePlugin = (locator, filter) => process.versions.pnp ? {
  29. apply: makeResolver({sourceLocator: locator, filter, pnpapi: require(`pnpapi`)}),
  30. } : {
  31. apply: nothing,
  32. };
  33. module.exports.moduleLoader = (module) => {
  34. if (process.versions.pnp) {
  35. const pnpapi = require(`pnpapi`);
  36. return {
  37. apply: makeResolver({
  38. sourceLocator: getModuleLocator(module, pnpapi),
  39. pnpapi,
  40. }),
  41. };
  42. }
  43. return {
  44. apply: nothing,
  45. };
  46. };
  47. module.exports.topLevelLoader = process.versions.pnp ? {
  48. apply: makeResolver({sourceLocator: {name: null, reference: null}, pnpapi: require(`pnpapi`)}),
  49. } : {
  50. apply: nothing,
  51. };
  52. module.exports.bind = (filter, module, dependency) => {
  53. if (process.versions.pnp) {
  54. const pnpapi = require(`pnpapi`);
  55. return {
  56. apply: makeResolver({
  57. sourceLocator: dependency
  58. ? getDependencyLocator(getModuleLocator(module, pnpapi), dependency, pnpapi)
  59. : getModuleLocator(module, pnpapi),
  60. filter,
  61. pnpapi,
  62. }),
  63. };
  64. }
  65. return {
  66. apply: nothing,
  67. };
  68. };
  69. module.exports.tsLoaderOptions = (options = {}) => process.versions.pnp ? Object.assign({}, options, {
  70. resolveModuleName: resolveModuleName,
  71. resolveTypeReferenceDirective: resolveModuleName,
  72. }) : options;
  73. module.exports.forkTsCheckerOptions = (options = {}) => process.versions.pnp ? Object.assign({}, options, {
  74. resolveModuleNameModule: require.resolve(`./ts`),
  75. resolveTypeReferenceDirectiveModule: require.resolve(`./ts`),
  76. }) : options;