Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions lib/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,18 +86,28 @@ export function valueError(message: string, name?: string): Error {
return Error(name ? `$${name}: ${message}.` : `${message}.`);
}

// Node changed its implementation of pathToFileURL:
// https://github.com/nodejs/node/pull/54545
const unsafePathToFileURL = url.pathToFileURL('~').pathname.endsWith('~');

/** Converts a (possibly relative) path on the local filesystem to a URL. */
export function pathToUrlString(path: string): string {
if (p.isAbsolute(path)) return url.pathToFileURL(path).toString();

// percent encode relative path like `pathToFileURL`
return encodeURI(path)
.replace(/[#?]/g, encodeURIComponent)
.replace(
process.platform === 'win32' ? /%(5B|5C|5D|5E|7C)/g : /%(5B|5D|5E|7C)/g,
decodeURIComponent,
)
.replace(/\\/g, '/');
let fileUrl = encodeURI(path).replace(/[#?]/g, encodeURIComponent);

if (unsafePathToFileURL) {
fileUrl = fileUrl.replace(/%(5B|5D|5E|7C)/g, decodeURIComponent);
} else {
fileUrl = fileUrl.replace(/~/g, '%7E');
}

if (process.platform === 'win32') {
fileUrl = fileUrl.replace(/%5C/g, '/');
}

return fileUrl;
}

/**
Expand Down
Loading