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.

48 lines
1.4 KiB

4 years ago
  1. 'use strict';
  2. var getFieldAsFn = require('./get-field-as-fn'),
  3. CustomError = require('./get-error');
  4. /**
  5. * Create an encoder for output 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|false} An encode function that takes an absolute path
  10. */
  11. function encodeSourcesWith(codec) {
  12. /* jshint validthis:true */
  13. var context = this,
  14. encoder = getFieldAsFn('encode')(codec);
  15. if (!encoder) {
  16. return new CustomError('Specified format does not support encoding (it lacks an "encoder" function)');
  17. }
  18. else {
  19. return function encode(absoluteSource) {
  20. // call the encoder
  21. var encoded;
  22. try {
  23. encoded = absoluteSource && encoder.call(context, absoluteSource);
  24. }
  25. catch (exception) {
  26. return getNamedError(exception);
  27. }
  28. return encoded;
  29. function getNamedError(details) {
  30. var name = codec.name || '(unnamed)',
  31. message = [
  32. 'Encoding with codec: ' + name,
  33. 'Absolute source: ' + absoluteSource,
  34. details && (details.stack ? details.stack : details)
  35. ]
  36. .filter(Boolean)
  37. .join('\n');
  38. return new Error(message);
  39. }
  40. };
  41. }
  42. }
  43. module.exports = encodeSourcesWith;