Skip to content

Commit

Permalink
Percent encode relative path like url.pathToFileURL (#134)
Browse files Browse the repository at this point in the history
  • Loading branch information
ntkme authored Apr 26, 2022
1 parent e81ab68 commit 086fe54
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
37 changes: 37 additions & 0 deletions lib/src/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import {pathToFileURL} from 'url';
import {pathToUrlString} from './utils';

describe('utils', () => {
describe('pathToUrlString', () => {
it('encode relative path like `pathToFileURL`', () => {
const baseURL = pathToFileURL('').toString();
for (let i = 0; i < 128; i++) {
const char = String.fromCharCode(i);
const filename = `${i}-${char}`;
expect(pathToUrlString(filename)).toEqual(
pathToFileURL(filename)
.toString()
.slice(baseURL.length + 1)
);
}
});

it('encode percent encoded string like `pathToFileURL`', () => {
const baseURL = pathToFileURL('').toString();
for (let i = 0; i < 128; i++) {
const lowercase = `%${i < 10 ? '0' : ''}${i.toString(16)}`;
expect(pathToUrlString(lowercase)).toEqual(
pathToFileURL(lowercase)
.toString()
.slice(baseURL.length + 1)
);
const uppercase = lowercase.toUpperCase();
expect(pathToUrlString(uppercase)).toEqual(
pathToFileURL(uppercase)
.toString()
.slice(baseURL.length + 1)
);
}
});
});
});
10 changes: 8 additions & 2 deletions lib/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,14 @@ export function valueError(message: string, name?: string): Error {
export function pathToUrlString(path: string): string {
if (p.isAbsolute(path)) return url.pathToFileURL(path).toString();

const components = p.sep === '\\' ? path.split(/[/\\]/) : path.split('/');
return components.map(encodeURIComponent).join('/');
// 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, '/');
}

/**
Expand Down

0 comments on commit 086fe54

Please sign in to comment.