Skip to content

Commit

Permalink
Fix hashing by generating random, stable key for non-objects
Browse files Browse the repository at this point in the history
Any object without any enumerable keys that isn't a plain
object will now receive a random key.
  • Loading branch information
kitten committed Mar 22, 2020
1 parent 6eb4716 commit d438195
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
15 changes: 9 additions & 6 deletions packages/core/src/utils/stringifyVariables.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,17 @@ it('stringifies dates correctly', () => {
expect(stringifyVariables(date)).toBe(date.toJSON());
});

it('stringifies dictionaries (Object.create(null)) correctly', () => {
expect(stringifyVariables(Object.create(null))).toBe('{}');
});

it('stringifies files correctly', () => {
const file = new File([0] as any, 'test.js');
Object.defineProperty(file, 'lastModified', { value: 123 });
const str = stringifyVariables(file);
expect(str).toBe(stringifyVariables(file));

expect(stringifyVariables(file)).toBe(
stringifyVariables({
name: 'test.js',
lastModified: 123,
})
);
const otherFile = new File([0] as any, 'otherFile.js');
Object.defineProperty(otherFile, 'lastModified', { value: 234 });
expect(str).not.toBe(stringifyVariables(otherFile));
});
12 changes: 10 additions & 2 deletions packages/core/src/utils/stringifyVariables.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const seen = new Set();
const cache = new WeakMap();

const stringify = (x: any): string => {
if (x === undefined) {
Expand Down Expand Up @@ -26,11 +27,18 @@ const stringify = (x: any): string => {
return out;
} else if (seen.has(x)) {
throw new TypeError('Converting circular structure to JSON');
} else if (typeof File === 'function' && x instanceof File) {
return stringify({ name: x.name, lastModified: x.lastModified });
}

const keys = Object.keys(x).sort();
if (!keys.length && x.constructor && x.constructor !== Object) {
const key =
cache.get(x) ||
Math.random()
.toString(36)
.slice(2);
cache.set(x, key);
return `{"__key":"${key}"}`;
}

seen.add(x);
out = '{';
Expand Down

0 comments on commit d438195

Please sign in to comment.