function relativePathForRequire({origin, request, pkgName, pkgPath}) {
  if (!path.isAbsolute(origin)) {
    throw new TypeError('`origin` must be an absolute path');
  }

  if (path.isAbsolute(request)) {
    return request;
  }

  const pkgRoot = path.dirname(pkgPath);
  let relative = path
    .relative(
      path.dirname(origin),
      request.replace(new RegExp('^' + pkgName), pkgRoot),
    )
    // `require` expects unix-style '/' separators, but `path.relative` will respect
    // `path.sep`.
    .split(path.sep)
    .join('/');

  // prefer `require('../')` over `require('..')`
  // match '..', '../..', but not 'foo..'
  if (relative.match(/(?:^|\/)\.\.$/)) {
    relative += '/';
  }

  if (!relative.startsWith('.')) {
    // peer files must lead with ./
    relative = './' + relative;
  }

  return relative;
}
Like path.relative, but for determining relative path between a filepath and
a module it requests in a `require`.
@param {Object} opts
@param {string} opts.origin - Originating file. Must be an absolute path.
@param {string} opts.request - Requested module in the require. e.g. @parcel/core
@param {string} opts.pkgName - name of the package in the package json
@param {string} opts.pkgPath - path to the package.json