Skip to content

Commit

Permalink
Merge branch 'main' into release/10.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
legobeat authored Oct 21, 2024
2 parents ae88bbc + c12cc9c commit 76a47b6
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 22 deletions.
18 changes: 17 additions & 1 deletion src/json.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ describe('json', () => {
const [error] = validate(undefined, JsonStruct);
assert(error !== undefined);
expect(error.message).toBe(
'Expected the value to satisfy a union of `literal | boolean | finite number | string | array | record`, but received: undefined',
'Expected a value of type `JSON`, but received: `undefined`',
);
});
});
Expand Down Expand Up @@ -418,6 +418,22 @@ describe('json', () => {
assertIsJsonRpcRequest(JSON_RPC_REQUEST_FIXTURES.invalid[0]),
).toThrow('Invalid JSON-RPC request: oops');
});

it('is fast for large inputs', () => {
const request = {
jsonrpc: '2.0',
id: 'foo',
method: 'wallet_invokeSnap',
params: {
snapId: 'npm:@metamask/manage-state-example-snap',
request: {
method: 'setState',
params: { items: new Array(9999999).fill(2) },
},
},
};
expect(() => assertIsJsonRpcRequest(request)).not.toThrow();
});
});

describe('isJsonRpcSuccess', () => {
Expand Down
69 changes: 48 additions & 21 deletions src/json.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import {
any,
array,
boolean,
coerce,
create,
define,
integer,
is,
lazy,
literal,
nullable,
number,
Expand Down Expand Up @@ -154,33 +152,62 @@ export function exactOptional<Type, Schema>(
}

/**
* A struct to check if the given value is finite number. Superstruct's
* `number()` struct does not check if the value is finite.
* Validate an unknown input to be valid JSON.
*
* @returns A struct to check if the given value is finite number.
* Useful for constructing JSON structs.
*
* @param json - An unknown value.
* @returns True if the value is valid JSON, otherwise false.
*/
const finiteNumber = () =>
define<number>('finite number', (value) => {
return is(value, number()) && Number.isFinite(value);
});
function validateJson(json: unknown): boolean {
if (json === null || typeof json === 'boolean' || typeof json === 'string') {
return true;
}

if (typeof json === 'number' && Number.isFinite(json)) {
return true;
}

if (typeof json === 'object') {
let every = true;
if (Array.isArray(json)) {
// Ignoring linting error since for-of is significantly slower than a normal for-loop
// and performance is important in this specific function.
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < json.length; i++) {
if (!validateJson(json[i])) {
every = false;
break;
}
}
return every;
}

const entries = Object.entries(json);
// Ignoring linting errors since for-of is significantly slower than a normal for-loop
// and performance is important in this specific function.
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < entries.length; i++) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (typeof entries[i]![0] !== 'string' || !validateJson(entries[i]![1])) {
every = false;
break;
}
}
return every;
}

return false;
}

/**
* A struct to check if the given value is a valid JSON-serializable value.
*
* Note that this struct is unsafe. For safe validation, use {@link JsonStruct}.
*/
// We cannot infer the type of the struct, because it is recursive.
export const UnsafeJsonStruct: Struct<Json> = union([
literal(null),
boolean(),
finiteNumber(),
string(),
array(lazy(() => UnsafeJsonStruct)),
record(
string(),
lazy(() => UnsafeJsonStruct),
),
]);
export const UnsafeJsonStruct: Struct<Json> = define('JSON', (json) =>
validateJson(json),
);

/**
* A struct to check if the given value is a valid JSON-serializable value.
Expand Down

0 comments on commit 76a47b6

Please sign in to comment.