You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.3 KiB

4 years ago
  1. 'use strict';
  2. var getFieldAsFn = require('./get-field-as-fn'),
  3. CustomError = require('./get-error');
  4. /**
  5. * Locate the root for input sources using the given codec hash
  6. * @throws Error Where the given codec is missing an encode function
  7. * @this {object} A loader or compilation
  8. * @param {{encode:function}} codec A single codec with an `encode` function
  9. * @returns {function(string):string|Error} An encode function that takes an absolute path
  10. */
  11. function locateRootWith(codec) {
  12. /* jshint validthis:true */
  13. var context = this,
  14. root = getFieldAsFn('root')(codec);
  15. if (!root) {
  16. return new CustomError('Specified format does not support encoding (it lacks a "root" function)');
  17. }
  18. else {
  19. return function locate() {
  20. // call the root
  21. var located;
  22. try {
  23. located = root.call(context);
  24. }
  25. catch (exception) {
  26. return getNamedError(exception);
  27. }
  28. return located;
  29. function getNamedError(details) {
  30. var name = codec.name || '(unnamed)',
  31. message = [
  32. 'Locating root with codec: ' + name,
  33. details && (details.stack ? details.stack : details)
  34. ]
  35. .filter(Boolean)
  36. .join('\n');
  37. return new Error(message);
  38. }
  39. };
  40. }
  41. }
  42. module.exports = locateRootWith;