Skip to content
Merged
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
40 changes: 39 additions & 1 deletion eslint-factory/src/rules/require-json-parse-try-catch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const esmRuleTester = new RuleTester({
describe("require-json-parse-try-catch", () => {
it("valid: JSON.parse inside try block passes (CommonJS)", () => {
cjsRuleTester.run("require-json-parse-try-catch", requireJsonParseTryCatchRule, {
valid: [`try { const x = JSON.parse(str); } catch (e) {}`, `try { return JSON.parse(str); } catch (e) {}`, `function f() { try { JSON.parse(str); } catch (e) {} }`],
valid: [`try { const x = JSON.parse(str); } catch (e) {}`, `try { return JSON.parse(str); } catch (e) {}`, `function f() { try { JSON.parse(str); } catch (e) {} }`, `try { const x = JSON["parse"](str); } catch (e) {}`],
invalid: [],
});
});
Expand Down Expand Up @@ -113,4 +113,42 @@ describe("require-json-parse-try-catch", () => {
],
});
});

it('invalid: computed JSON["parse"] access is flagged when not in try block', () => {
cjsRuleTester.run("require-json-parse-try-catch", requireJsonParseTryCatchRule, {
valid: [],
invalid: [
{
code: `const data = JSON["parse"](rawInput);`,
errors: [
{
messageId: "requireTryCatch",
data: { arg: "rawInput" },
suggestions: [
{
messageId: "useHelper",
output: `try {\n const data = JSON["parse"](rawInput);\n} catch (err) {\n throw err;\n}`,
},
],
},
],
},
{
code: `JSON["parse"](response.body);`,
errors: [
{
messageId: "requireTryCatch",
data: { arg: "response.body" },
suggestions: [
{
messageId: "useHelper",
output: `try {\n JSON["parse"](response.body);\n} catch (err) {\n throw err;\n}`,
},
],
},
],
},
],
});
});
});
12 changes: 8 additions & 4 deletions eslint-factory/src/rules/require-json-parse-try-catch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,15 @@ export const requireJsonParseTryCatchRule = createRule({
return;
}

if (node.callee.property.type !== "Identifier") {
return;
}
// Accept both direct property access (JSON.parse) and computed string-literal
// access (JSON["parse"]). Aliased (const p = JSON.parse; p(raw)) and
// destructured (const { parse } = JSON; parse(raw)) bindings are intentionally
// out of scope: tracking them reliably requires full scope analysis and is
// disproportionate to the current risk surface.
const property = node.callee.property;
const isParseProperty = (property.type === "Identifier" && property.name === "parse") || (property.type === "Literal" && property.value === "parse");
Comment on lines +63 to +69

if (node.callee.property.name !== "parse") {
if (!isParseProperty) {
return;
Comment on lines +68 to 72
}

Expand Down