util.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. 'use strict'
  2. // As Errlop uses Editions, we should use a specific Errlop edition
  3. // As otherwise, the circular reference may fail on some machines
  4. // https://github.com/bevry/errlop/issues/2
  5. import Errlop from 'errlop'
  6. interface ErrtionOptions {
  7. message: string
  8. code: string | number
  9. level?: string | number
  10. }
  11. interface Errtion extends Errlop, ErrtionOptions {}
  12. /**
  13. * Allow code and level inputs on Errlop.
  14. * We do this instead of a class extension, as class extensions do not interop well on node 0.8, which is our target.
  15. */
  16. export function errtion(
  17. this: void,
  18. opts: ErrtionOptions,
  19. parent?: Errlop | Error
  20. ): Errtion {
  21. const { message, code, level } = opts
  22. const error = new Errlop(message, parent) as Errtion
  23. if (code) error.code = code
  24. if (level) error.level = level
  25. return error
  26. }
  27. /** Converts anything to a string, by returning strings and serialising objects. */
  28. export function stringify(value: any): string {
  29. return typeof value === 'string' ? value : JSON.stringify(value)
  30. }
  31. /** Converts a version range like `4 || 6` to `>=4` */
  32. export function simplifyRange(range: string): string {
  33. return range.replace(/^([.\-\w]+)(\s.+)?$/, '>=$1')
  34. }