Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update relative pathToFileURL to match node #352

Merged
merged 2 commits into from
Dec 12, 2024
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