path-arg.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { parse, resolve } from 'path';
  2. import { inspect } from 'util';
  3. import platform from './platform.js';
  4. const pathArg = (path, opt = {}) => {
  5. const type = typeof path;
  6. if (type !== 'string') {
  7. const ctor = path && type === 'object' && path.constructor;
  8. const received = ctor && ctor.name ? `an instance of ${ctor.name}`
  9. : type === 'object' ? inspect(path)
  10. : `type ${type} ${path}`;
  11. const msg = 'The "path" argument must be of type string. ' + `Received ${received}`;
  12. throw Object.assign(new TypeError(msg), {
  13. path,
  14. code: 'ERR_INVALID_ARG_TYPE',
  15. });
  16. }
  17. if (/\0/.test(path)) {
  18. // simulate same failure that node raises
  19. const msg = 'path must be a string without null bytes';
  20. throw Object.assign(new TypeError(msg), {
  21. path,
  22. code: 'ERR_INVALID_ARG_VALUE',
  23. });
  24. }
  25. path = resolve(path);
  26. const { root } = parse(path);
  27. if (path === root && opt.preserveRoot !== false) {
  28. const msg = 'refusing to remove root directory without preserveRoot:false';
  29. throw Object.assign(new Error(msg), {
  30. path,
  31. code: 'ERR_PRESERVE_ROOT',
  32. });
  33. }
  34. if (platform === 'win32') {
  35. const badWinChars = /[*|"<>?:]/;
  36. const { root } = parse(path);
  37. if (badWinChars.test(path.substring(root.length))) {
  38. throw Object.assign(new Error('Illegal characters in path.'), {
  39. path,
  40. code: 'EINVAL',
  41. });
  42. }
  43. }
  44. return path;
  45. };
  46. export default pathArg;
  47. //# sourceMappingURL=path-arg.js.map