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

fix: input escape mapping #311

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
75 changes: 72 additions & 3 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ describe('stringify & parse', () => {
},
outputAnnotations: {
values: {
'a\\\\.1.b': ['set'],
'a\\\\\\.1.b': ['set'],
},
},
},
Expand Down Expand Up @@ -686,6 +686,26 @@ describe('stringify & parse', () => {
},
},
},
'repro #310: meta path escape bug': {
input: {
a: ["/'a'[0]: string that becomes a regex/"],
'a.0': /'a.0': regex that becomes a string/,
'b.0': "/'b.0': string that becomes a regex/",
'b\\': [/'b\\'[0]: regex that becomes a string/],
},
output: {
a: ["/'a'[0]: string that becomes a regex/"],
'a.0': "/'a.0': regex that becomes a string/",
'b.0': "/'b.0': string that becomes a regex/",
'b\\': ["/'b\\\\'[0]: regex that becomes a string/"],
},
outputAnnotations: {
values: {
'a\\.0': ['regexp'],
'b\\\\.0': ['regexp'],
},
},
},
};

function deepFreeze(object: any, alreadySeenObjects = new Set()) {
Expand Down Expand Up @@ -759,7 +779,13 @@ describe('stringify & parse', () => {
} else {
expect(json).toEqual(expectedOutput);
}
expect(meta).toEqual(expectedOutputAnnotations);
if (meta) {
const { v, ...rest } = meta;
expect(v).toBe(1);
expect(rest).toEqual(expectedOutputAnnotations);
} else {
expect(meta).toEqual(expectedOutputAnnotations);
}

const untransformed = SuperJSON.deserialize(
JSON.parse(JSON.stringify({ json, meta }))
Expand Down Expand Up @@ -800,6 +826,7 @@ describe('stringify & parse', () => {
});

expect(meta).toEqual({
v: 1,
values: {
s7: [['class', 'Train']],
},
Expand Down Expand Up @@ -863,6 +890,7 @@ describe('stringify & parse', () => {
a: '1000',
},
meta: {
v: 1,
values: {
a: ['bigint'],
},
Expand Down Expand Up @@ -946,7 +974,7 @@ test('regression #83: negative zero', () => {

const stringified = SuperJSON.stringify(input);
expect(stringified).toMatchInlineSnapshot(
`"{\\"json\\":\\"-0\\",\\"meta\\":{\\"values\\":[\\"number\\"]}}"`
`"{\\"json\\":\\"-0\\",\\"meta\\":{\\"values\\":[\\"number\\"],\\"v\\":1}}"`
);

const parsed: number = SuperJSON.parse(stringified);
Expand Down Expand Up @@ -1166,6 +1194,7 @@ test('regression #245: superjson referential equalities only use the top-most pa
"b",
],
},
"v": 1,
}
`);

Expand Down Expand Up @@ -1241,3 +1270,43 @@ test('doesnt iterate to keys that dont exist', () => {

expect(() => SuperJSON.deserialize(res)).toThrowError('index out of bounds');
});

test('#310 fixes backwards compat', () => {
expect(
SuperJSON.deserialize({
json: {
'a\\.1': {
b: [1, 2],
},
},
meta: {
values: {
'a\\\\.1.b': ['set'],
},
},
})
).toEqual({
'a\\.1': {
b: new Set([1, 2]),
},
});

expect(
SuperJSON.deserialize({
json: {
'a.1': {
b: [1, 2],
},
},
meta: {
values: {
'a\\.1.b': ['set'],
},
},
})
).toEqual({
'a.1': {
b: new Set([1, 2]),
},
});
});
7 changes: 5 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ export default class SuperJSON {
};
}

if (res.meta) res.meta.v = 1;

return res;
}

Expand All @@ -64,13 +66,14 @@ export default class SuperJSON {
let result: T = copy(json) as any;

if (meta?.values) {
result = applyValueAnnotations(result, meta.values, this);
result = applyValueAnnotations(result, meta.values, meta.v ?? 0, this);
}

if (meta?.referentialEqualities) {
result = applyReferentialEqualityAnnotations(
result,
meta.referentialEqualities
meta.referentialEqualities,
meta.v ?? 0
);
}

Expand Down
4 changes: 2 additions & 2 deletions src/pathstringifier.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ describe('parsePath', () => {
it.each([
['test.a.b', ['test', 'a', 'b']],
['test\\.a.b', ['test.a', 'b']],
['test\\\\.a.b', ['test\\.a', 'b']],
['test\\\\.a.b', ['test\\', 'a', 'b']],
['test\\a.b', ['test\\a', 'b']],
['test\\\\a.b', ['test\\\\a', 'b']],
['test\\\\a.b', ['test\\a', 'b']],
])('parsePath(%p) === %p', (input, expectedOutput) => {
expect(parsePath(input)).toEqual(expectedOutput);
});
Expand Down
14 changes: 12 additions & 2 deletions src/pathstringifier.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,31 @@
export type StringifiedPath = string;
type Path = string[];

export const escapeKey = (key: string) => key.replace(/\./g, '\\.');
export const escapeKey = (key: string) =>
key.replace(/\\/g, '\\\\').replace(/\./g, '\\.');

export const stringifyPath = (path: Path): StringifiedPath =>
path
.map(String)
.map(escapeKey)
.join('.');

export const parsePath = (string: StringifiedPath) => {
export const parsePath = (string: StringifiedPath, legacyPaths: boolean) => {
const result: string[] = [];

let segment = '';
for (let i = 0; i < string.length; i++) {
let char = string.charAt(i);

if (!legacyPaths) {
const isEscapedBackslash = char === '\\' && string.charAt(i + 1) === '\\';
if (isEscapedBackslash) {
segment += '\\';
i++;
continue;
}
}
Comment on lines +20 to +27

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This correctly handles escaped backslashes, but does not implement special behavior for backslashes that are in final position (e.g., "foo.bar.baz\\") or followed by something other than a dot or backslash (e.g., "foo.bar.b\\az" or "foo.bar.b\\\n"). I strongly recommend rejecting such input rather than treating it as synonymous with e.g. "foo.bar.baz\\\\"/"foo.bar.b\\\\az"/"foo.bar.b\\\\\n" (respectively).

Suggested change
if (!legacyPaths) {
const isEscapedBackslash = char === '\\' && string.charAt(i + 1) === '\\';
if (isEscapedBackslash) {
segment += '\\';
i++;
continue;
}
}
if (!legacyPaths && char === '\\') {
const escaped = string.charAt(i + 1);
if (escaped === '\\') {
segment += '\\';
i++;
continue;
} else if (escaped !== '.') {
throw Error('invalid path');
}
}


const isEscapedDot = char === '\\' && string.charAt(i + 1) === '.';
if (isEscapedDot) {
segment += '.';
Expand Down
47 changes: 35 additions & 12 deletions src/plainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,26 +24,36 @@ type InnerNode<T> = [T, Record<string, Tree<T>>];

export type MinimisedTree<T> = Tree<T> | Record<string, Tree<T>> | undefined;

const enableLegacyPaths = (version: number) => version < 1;

function traverse<T>(
tree: MinimisedTree<T>,
walker: (v: T, path: string[]) => void,
version: number,
origin: string[] = []
): void {
if (!tree) {
return;
}

const legacyPaths = enableLegacyPaths(version);
if (!isArray(tree)) {
forEach(tree, (subtree, key) =>
traverse(subtree, walker, [...origin, ...parsePath(key)])
traverse(subtree, walker, version, [
...origin,
...parsePath(key, legacyPaths),
])
);
return;
}

const [nodeValue, children] = tree;
if (children) {
forEach(children, (child, key) => {
traverse(child, walker, [...origin, ...parsePath(key)]);
traverse(child, walker, version, [
...origin,
...parsePath(key, legacyPaths),
]);
});
}

Expand All @@ -53,31 +63,44 @@ function traverse<T>(
export function applyValueAnnotations(
plain: any,
annotations: MinimisedTree<TypeAnnotation>,
version: number,
superJson: SuperJSON
) {
traverse(annotations, (type, path) => {
plain = setDeep(plain, path, v => untransformValue(v, type, superJson));
});
traverse(
annotations,
(type, path) => {
plain = setDeep(plain, path, v => untransformValue(v, type, superJson));
},
version
);

return plain;
}

export function applyReferentialEqualityAnnotations(
plain: any,
annotations: ReferentialEqualityAnnotations
annotations: ReferentialEqualityAnnotations,
version: number
) {
const legacyPaths = enableLegacyPaths(version);
function apply(identicalPaths: string[], path: string) {
const object = getDeep(plain, parsePath(path));
const object = getDeep(plain, parsePath(path, legacyPaths));

identicalPaths.map(parsePath).forEach(identicalObjectPath => {
plain = setDeep(plain, identicalObjectPath, () => object);
});
identicalPaths
.map(path => parsePath(path, legacyPaths))
.forEach(identicalObjectPath => {
plain = setDeep(plain, identicalObjectPath, () => object);
});
}

if (isArray(annotations)) {
const [root, other] = annotations;
root.forEach(identicalPath => {
plain = setDeep(plain, parsePath(identicalPath), () => plain);
plain = setDeep(
plain,
parsePath(identicalPath, legacyPaths),
() => plain
);
});

if (other) {
Expand Down Expand Up @@ -239,7 +262,7 @@ export const walker = (
transformedValue[index] = recursiveResult.transformedValue;

if (isArray(recursiveResult.annotations)) {
innerAnnotations[index] = recursiveResult.annotations;
innerAnnotations[escapeKey(index)] = recursiveResult.annotations;
} else if (isPlainObject(recursiveResult.annotations)) {
forEach(recursiveResult.annotations, (tree, key) => {
innerAnnotations[escapeKey(index) + '.' + key] = tree;
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,6 @@ export interface SuperJSONResult {
meta?: {
values?: MinimisedTree<TypeAnnotation>;
referentialEqualities?: ReferentialEqualityAnnotations;
v?: number;
};
}
Loading