Skip to content

Commit

Permalink
Update relative pathToFileURL to match node (#352)
Browse files Browse the repository at this point in the history
  • Loading branch information
ntkme authored Dec 12, 2024
1 parent ebeb169 commit 5a10661
Showing 1 changed file with 17 additions and 7 deletions.
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

0 comments on commit 5a10661

Please sign in to comment.