Skip to content

Commit

Permalink
fix: decodePointer does not handle percent character (#83)
Browse files Browse the repository at this point in the history
  • Loading branch information
P0lip authored May 6, 2021
1 parent eb5065b commit 6c347e4
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
3 changes: 3 additions & 0 deletions src/__tests__/decodePointer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,7 @@ test('decodePointer', () => {
expect(decodePointer('paths/~1users')).toEqual('paths//users');
expect(decodePointer('paths/foo~0users')).toEqual('paths/foo~users');
expect(decodePointer('#/foo')).toEqual('#/foo');
expect(decodePointer('#/foo%20%5E%20bar')).toEqual('#/foo ^ bar');
expect(decodePointer('#/users% ')).toEqual('#/users% ');
expect(decodePointer('#/users%%20%5E%')).toEqual('#/users% ^%');
});
2 changes: 2 additions & 0 deletions src/__tests__/pointerToPath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ test('pointerToPath', () => {
expect(pointerToPath('#/paths/foo~0users')).toEqual(['paths', 'foo~users']);
expect(pointerToPath('#')).toEqual([]);
expect(pointerToPath('#/')).toEqual(['']);
expect(pointerToPath('#/foo%20%5E%20bar')).toEqual(['foo ^ bar']);
expect(pointerToPath('#/users% ')).toEqual(['users% ']);
});
19 changes: 18 additions & 1 deletion src/decodePointer.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,27 @@
import { replaceInString } from './_utils';

function safeDecodeURIComponent(value: string): string {
try {
return decodeURIComponent(value);
} catch {
return value;
}
}

const PERCENT_ENCODING_OCTET = /%[0-9a-f]+/gi;

/**
* Removes special json pointer characters in a value. Example:
*
* decodePointer('#/paths/~1users) => '#/paths//users'
*/
export const decodePointer = (value: string): string => {
return replaceInString(replaceInString(decodeURIComponent('' + value), '~1', '/'), '~0', '~');
let decoded;
try {
decoded = decodeURIComponent(value);
} catch {
decoded = value.replace(PERCENT_ENCODING_OCTET, safeDecodeURIComponent);
}

return replaceInString(replaceInString(decoded, '~1', '/'), '~0', '~');
};

0 comments on commit 6c347e4

Please sign in to comment.