static.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. const npm = {
  2. stream: require('stream'),
  3. util: require('util')
  4. };
  5. /////////////////////////////////////
  6. // Checks if the value is a promise;
  7. function isPromise(value) {
  8. return value && typeof value.then === 'function';
  9. }
  10. ////////////////////////////////////////////
  11. // Checks object for being a readable stream;
  12. function isReadableStream(obj) {
  13. return obj instanceof npm.stream.Stream &&
  14. typeof obj._read === 'function' &&
  15. typeof obj._readableState === 'object';
  16. }
  17. ////////////////////////////////////////////////////////////
  18. // Sets an object property as read-only and non-enumerable.
  19. function extend(obj, name, value) {
  20. Object.defineProperty(obj, name, {
  21. value: value,
  22. configurable: false,
  23. enumerable: false,
  24. writable: false
  25. });
  26. }
  27. ///////////////////////////////////////////
  28. // Returns a space gap for console output;
  29. function messageGap(level) {
  30. return ' '.repeat(level * 4);
  31. }
  32. function formatError(error, level) {
  33. const names = ['BatchError', 'PageError', 'SequenceError'];
  34. let msg = npm.util.inspect(error);
  35. if (error instanceof Error) {
  36. if (names.indexOf(error.name) === -1) {
  37. const gap = messageGap(level);
  38. msg = msg.split('\n').map((line, index) => {
  39. return (index ? gap : '') + line;
  40. }).join('\n');
  41. } else {
  42. msg = error.toString(level);
  43. }
  44. }
  45. return msg;
  46. }
  47. ////////////////////////////////////////////////////////
  48. // Adds prototype inspection, with support of the newer
  49. // Custom Inspection, which was added in Node.js 6.x
  50. function addInspection(type, cb) {
  51. // istanbul ignore next;
  52. if (npm.util.inspect.custom) {
  53. // Custom inspection is supported:
  54. type.prototype[npm.util.inspect.custom] = cb;
  55. } else {
  56. // Use classic inspection:
  57. type.prototype.inspect = cb;
  58. }
  59. }
  60. module.exports = {
  61. addInspection: addInspection,
  62. formatError: formatError,
  63. isPromise: isPromise,
  64. isReadableStream: isReadableStream,
  65. messageGap: messageGap,
  66. extend: extend
  67. };