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
1 change: 1 addition & 0 deletions .github/skills/agentic-workflows/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ If GitHub API, `gh api`, or GitHub MCP downloads return HTTP 403 (including a to
- `.github/aw/cli-commands.md`
- `.github/aw/compat.md`
- `.github/aw/configure-agentic-engine.md`
- `.github/aw/connectors.md`
- `.github/aw/context.md`
- `.github/aw/create-agentic-workflow-trigger-details.md`
- `.github/aw/create-agentic-workflow.md`
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/ponytail-reviewer.lock.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .github/workflows/pr-code-quality-reviewer.lock.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .github/workflows/pr-specification-reviewer.lock.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 23 additions & 0 deletions eslint-factory/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ negative controls and validated readable traces without live effects.
| [`prefer-actions-exec-over-child-process`](#prefer-actions-exec-over-child-process) | Prefer `@actions/exec` over `child_process` to spawn processes that run to completion |
| [`no-unguarded-async-timer-callback`](#no-unguarded-async-timer-callback) | Require async timer callbacks to wrap their entire body in try/catch |
| [`require-finite-check-before-date-toisostring`](#require-finite-check-before-date-toisostring) | Validate dynamic dates before calling `toISOString()` or `toJSON()` |
| [`require-null-check-with-typeof-object`](#require-null-check-with-typeof-object) | Require a null check for the same value alongside `typeof value === "object"` |
| [`require-per-page-on-github-list-call`](#require-per-page-on-github-list-call) | Require explicit `per_page` values on paginated Octokit REST list calls |

### `no-ad-hoc-jsonl-parser`
Expand Down Expand Up @@ -1334,3 +1335,25 @@ const comments = await github.rest.issues.listComments({ owner, repo, issue_numb
const page = await github.rest.issues.listComments({ owner, repo, issue_number: 1, per_page: 100 });
const allComments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number: 1, per_page: 100 });
```

### `require-null-check-with-typeof-object`

Require a null check for the same value when `typeof value === "object"` or `typeof value == "object"` is used. `typeof null` is `"object"`, so a `null` value passes these checks and later property access (for example `value.counts` or `Object.values(value)`) throws a `TypeError`. Inequality comparisons (`!==` and `!=`) exclude `null` and are not flagged. In `actions/setup/js` this shows up when parsing state files and API payloads where `null` is a valid JSON value.

**Flagged forms:**
```js
const ok = !!parsed && typeof parsed.counts === "object"; // parsed.counts may be null
const states = typeof result === "object" ? Object.values(result.claims || {}) : [];
```

**Safe alternatives:**
```js
const ok = !!parsed && parsed.counts !== null && typeof parsed.counts === "object";
const states = result && typeof result === "object" ? Object.values(result.claims || {}) : [];
```

**Not flagged:**
- A null/truthiness guard for the same value makes the conjunction fail for `null`, or a top-level early-exit `if` in the same function exits for `null`/falsy values before the check.
- A loose comparison against `undefined` (`value != undefined`) excludes `null`; strict comparisons (`!== undefined` or `=== undefined`) do not.
- Other `typeof` comparisons such as `"string"` or `"function"`.
- `typeof` operands that are not a plain identifier or non-computed member chain (calls, computed access).
1 change: 1 addition & 0 deletions eslint-factory/eslint.config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ module.exports = [
"gh-aw-custom/prefer-actions-exec-over-child-process": "warn",
"gh-aw-custom/no-misplaced-error-code-definition": "warn",
"gh-aw-custom/require-finite-check-before-date-toisostring": "warn",
"gh-aw-custom/require-null-check-with-typeof-object": "warn",
},
},
{
Expand Down
2 changes: 2 additions & 0 deletions eslint-factory/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ import { requirePerPageOnGithubListCallRule } from "./rules/require-per-page-on-
import { noAsyncForEachCallbackRule } from "./rules/no-async-foreach-callback";
import { noUnguardedAsyncTimerCallbackRule } from "./rules/no-unguarded-async-timer-callback";
import { requireFiniteCheckBeforeDateToIsoStringRule } from "./rules/require-finite-check-before-date-toisostring";
import { requireNullCheckWithTypeofObjectRule } from "./rules/require-null-check-with-typeof-object";
import { noSplitFilterTrimWithoutTrimMapRule } from "./rules/no-split-filter-trim-without-trim-map";

const plugin = {
Expand Down Expand Up @@ -152,6 +153,7 @@ const plugin = {
"no-async-foreach-callback": noAsyncForEachCallbackRule,
"no-split-filter-trim-without-trim-map": noSplitFilterTrimWithoutTrimMapRule,
"require-finite-check-before-date-toisostring": requireFiniteCheckBeforeDateToIsoStringRule,
"require-null-check-with-typeof-object": requireNullCheckWithTypeofObjectRule,
},
};

Expand Down
108 changes: 108 additions & 0 deletions eslint-factory/src/rules/require-null-check-with-typeof-object.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { RuleTester } from "eslint";
import { describe, expect, it } from "vitest";
import { requireNullCheckWithTypeofObjectRule } from "./require-null-check-with-typeof-object";

const cjsRuleTester = new RuleTester({
languageOptions: {
ecmaVersion: 2022,
sourceType: "commonjs",
},
});

const messageFor = (subject: string, operator = "===") =>
`\`typeof ${subject} ${operator} "object"\` is also satisfied by \`null\`. Guard \`${subject}\` in the same conjunction or exit early for null before this check; otherwise a null value is treated as an object and later property access throws.`;

describe("require-null-check-with-typeof-object", () => {
it("uses the correct docs URL", () => {
expect(requireNullCheckWithTypeofObjectRule.meta.docs.url).toBe("https://github.com/github/gh-aw/tree/main/eslint-factory#require-null-check-with-typeof-object");
});

it("invalid: typeof object checks with no null guard are flagged", () => {
cjsRuleTester.run("require-null-check-with-typeof-object", requireNullCheckWithTypeofObjectRule, {
valid: [],
invalid: [
{
code: `function f(headers) { if (typeof headers === "object") { return Object.values(headers); } }`,
errors: [{ message: messageFor("headers") }],
},
{
code: `const states = typeof result === "object" ? Object.values(result.claims || {}) : [];`,
errors: [{ message: messageFor("result") }],
},
{
code: `const ok = !!parsed && typeof parsed.counts === "object";`,
errors: [{ message: messageFor("parsed.counts") }],
},
{
code: `if (value !== undefined && typeof value === "object") Object.keys(value);`,
errors: [{ message: messageFor("value") }],
},
{
code: `const isObj = "object" === typeof value;`,
errors: [{ message: messageFor("value") }],
},
{
code: `function f(value) { if (value !== undefined) return; return typeof value === "object" ? Object.keys(value) : []; }`,
errors: [{ message: messageFor("value") }],
},
{
code: `function f(a, b) { if (b !== null) {} return typeof a === "object"; }`,
errors: [{ message: messageFor("a") }],
},
{
code: `function f(a) { return typeof a === "object"; } function g(a) { if (a) {} }`,
errors: [{ message: messageFor("a") }],
},
{
code: `function f(value) { function helper(value) { if (value) return; } if (typeof value === "object") return Object.keys(value); }`,
errors: [{ message: messageFor("value") }],
},
{
code: `function f(value, condition) { const result = condition && value; return typeof value === "object" ? Object.keys(value) : result; }`,
errors: [{ message: messageFor("value") }],
},
{
code: `function f(value) { if (value) log("set"); return typeof value === "object" ? Object.keys(value) : []; }`,
errors: [{ message: messageFor("value") }],
},
{
code: `if (value == null || typeof value === "object") Object.keys(value);`,
errors: [{ message: messageFor("value") }],
},
{
code: `function helper(x) { if (x) return; } const ok = typeof x === "object";`,
errors: [{ message: messageFor("x") }],
},
],
});
});

it("valid: null or truthiness guards, and unrelated typeof checks, are accepted", () => {
cjsRuleTester.run("require-null-check-with-typeof-object", requireNullCheckWithTypeofObjectRule, {
valid: [
{ code: `const ok = value && typeof value === "object";` },
{ code: `const ok = value !== null && typeof value === "object";` },
{ code: `const ok = typeof value === "object" && value !== null;` },
{ code: `const ok = value != null && typeof value === "object";` },
{ code: `const ok = typeof value === "object" && value !== undefined && value !== null;` },
{ code: `const ok = value != undefined && typeof value === "object";` },
{ code: `const ok = value !== null && typeof value === "object" && !Array.isArray(value);` },
{ code: `const ok = Boolean(value) && typeof value === "object";` },
{ code: `const ok = !value || typeof value !== "object";` },
{ code: `const ok = value == null || typeof value !== "object";` },
{ code: `const notObj = typeof value != "object";` },
{ code: `const notObj = typeof value !== "object";` },
{ code: `const ok = result?.target && typeof result.target === "object" ? result.target : undefined;` },
{ code: `function f(headers) { if (headers == null) { return false; } if (typeof headers === "object") { return true; } return false; }` },
{ code: `function f(value) { if (value === null) return 1; return typeof value === "object" ? 2 : 3; }` },
{ code: `function f(value) { if (!value) return 1; if (typeof value === "object") return 2; return 3; }` },
{ code: `const isString = typeof value === "string";` },
{ code: `const isFn = typeof value === "function";` },
{ code: `const t = typeof value === kind;` },
{ code: `const t = typeof fn() === "object";` },
{ code: `const t = typeof value[key] === "object";` },
],
invalid: [],
});
});
});
145 changes: 145 additions & 0 deletions eslint-factory/src/rules/require-null-check-with-typeof-object.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { AST_NODE_TYPES, ESLintUtils, TSESLint, TSESTree } from "@typescript-eslint/utils";

const createRule = ESLintUtils.RuleCreator(name => `https://github.com/github/gh-aw/tree/main/eslint-factory#${name}`);

const EQUALITY_OPERATORS = new Set(["===", "!==", "==", "!="]);
const TYPEOF_OBJECT_OPERATORS = new Set(["===", "=="]);

/** Source-level name of an identifier or non-computed member chain (optional chaining ignored); null for any other expression. */
function subjectText(node: TSESTree.Node): string | null {
let current: TSESTree.Node = node;
while (current.type === AST_NODE_TYPES.ChainExpression) current = current.expression;
if (current.type === AST_NODE_TYPES.Identifier) return current.name;
if (current.type === AST_NODE_TYPES.ThisExpression) return "this";
if (current.type === AST_NODE_TYPES.MemberExpression && !current.computed && current.property.type === AST_NODE_TYPES.Identifier) {
const objectText = subjectText(current.object);
return objectText === null ? null : `${objectText}.${current.property.name}`;
}
return null;
}

function isNullish(node: TSESTree.Node): boolean {
return (node.type === AST_NODE_TYPES.Literal && node.value === null && node.raw === "null") || (node.type === AST_NODE_TYPES.Identifier && node.name === "undefined");
}

/** Matches `typeof <subject> <op> "object"` in either operand order. */
function matchTypeofObject(node: TSESTree.BinaryExpression): { text: string; operator: string } | null {
if (!TYPEOF_OBJECT_OPERATORS.has(node.operator)) return null;
const isObjectLiteral = (n: TSESTree.Node) => n.type === AST_NODE_TYPES.Literal && n.value === "object";
const typeofSide = isObjectLiteral(node.right) ? node.left : isObjectLiteral(node.left) ? node.right : null;
if (!typeofSide || typeofSide.type !== AST_NODE_TYPES.UnaryExpression || typeofSide.operator !== "typeof") return null;
const text = subjectText(typeofSide.argument);
return text === null ? null : { text, operator: node.operator };
}

type GuardEffect = "nonNull" | "nullish" | null;

/** Describes whether a true result from `node` proves `text` non-null or nullish. */
function guardEffect(node: TSESTree.Node, text: string): GuardEffect {
if (node.type === AST_NODE_TYPES.UnaryExpression && node.operator === "!") {
const effect = guardEffect(node.argument, text);
return effect === "nonNull" ? "nullish" : effect === "nullish" ? "nonNull" : null;
}
if (node.type === AST_NODE_TYPES.CallExpression && node.callee.type === AST_NODE_TYPES.Identifier && node.callee.name === "Boolean" && node.arguments.length === 1) {
return subjectText(node.arguments[0]) === text ? "nonNull" : null;
}
if (node.type === AST_NODE_TYPES.BinaryExpression && EQUALITY_OPERATORS.has(node.operator)) {
const other = isNullish(node.right) ? node.left : isNullish(node.left) ? node.right : null;
if (other === null || subjectText(other) !== text) return null;
const nullLiteral = (node.left.type === AST_NODE_TYPES.Literal && node.left.value === null) || (node.right.type === AST_NODE_TYPES.Literal && node.right.value === null);
if (nullLiteral) {
return node.operator === "!=" || node.operator === "!==" ? "nonNull" : "nullish";
}
if (node.operator === "==") return "nullish";
if (node.operator === "!=") return "nonNull";
return null;
}
return subjectText(node) === text ? "nonNull" : null;
}

/** True when a conjunction guards the `typeof` check with a test for `text`. */
function hasSameExpressionGuard(node: TSESTree.Node, text: string): boolean {
let chain = node;
while (chain.parent?.type === AST_NODE_TYPES.LogicalExpression && chain.parent.operator === "&&") {
chain = chain.parent;
}
const operands: TSESTree.Node[] = [];
const flattenAnd = (current: TSESTree.Node) => {
if (current.type === AST_NODE_TYPES.LogicalExpression && current.operator === "&&") {
flattenAnd(current.left);
flattenAnd(current.right);
} else {
operands.push(current);
}
};
flattenAnd(chain);
const nodeIndex = operands.indexOf(node);
const isGuardSyntax = (candidate: TSESTree.Node) =>
guardEffect(candidate, text) !== null ||
(candidate.type === AST_NODE_TYPES.BinaryExpression &&
EQUALITY_OPERATORS.has(candidate.operator) &&
((isNullish(candidate.left) && subjectText(candidate.right) === text) || (isNullish(candidate.right) && subjectText(candidate.left) === text)));
if (nodeIndex >= 0) {
for (let index = 0; index < operands.length; index++) {
if (index === nodeIndex || guardEffect(operands[index], text) !== "nonNull") continue;
if (index < nodeIndex || operands.slice(nodeIndex + 1, index).every(isGuardSyntax)) return true;
}
}

return false;
}

function enclosingFunction(node: TSESTree.Node): TSESTree.FunctionDeclaration | TSESTree.FunctionExpression | TSESTree.ArrowFunctionExpression | null {
let current: TSESTree.Node | undefined = node.parent;
while (current) {
if (current.type === AST_NODE_TYPES.FunctionDeclaration || current.type === AST_NODE_TYPES.FunctionExpression || current.type === AST_NODE_TYPES.ArrowFunctionExpression) {
return current;
}
current = current.parent;
}
return null;
}

function exitsUnconditionally(statement: TSESTree.Statement): boolean {
if (statement.type === AST_NODE_TYPES.ReturnStatement || statement.type === AST_NODE_TYPES.ThrowStatement) return true;
return statement.type === AST_NODE_TYPES.BlockStatement && statement.body.length > 0 && exitsUnconditionally(statement.body[statement.body.length - 1]);
}

/** Earlier guards count only when a top-level early exit excludes null before this check. */
function hasEarlierExitGuard(node: TSESTree.Node, text: string): boolean {
const fn = enclosingFunction(node);
if (!fn || fn.body.type !== AST_NODE_TYPES.BlockStatement) return false;
return fn.body.body.some(statement => statement.range[1] < node.range[0] && statement.type === AST_NODE_TYPES.IfStatement && guardEffect(statement.test, text) === "nullish" && exitsUnconditionally(statement.consequent));
}

export const requireNullCheckWithTypeofObjectRule = createRule({
name: "require-null-check-with-typeof-object",
meta: {
type: "problem",
docs: {
description: 'Require a null check for the same value alongside `typeof value === "object"`, because `typeof null === "object"` and a null value would otherwise be treated as an object.',
},
schema: [],
messages: {
missingNullCheck:
'`typeof {{subject}} {{operator}} "object"` is also satisfied by `null`. Guard `{{subject}}` in the same conjunction or exit early for null before this check; otherwise a null value is treated as an object and later property access throws.',
},
},
defaultOptions: [],
create(context: Readonly<TSESLint.RuleContext<"missingNullCheck", []>>) {
return {
BinaryExpression(node: TSESTree.BinaryExpression) {
const match = matchTypeofObject(node);
if (!match) return;

if (hasSameExpressionGuard(node, match.text) || hasEarlierExitGuard(node, match.text)) return;

context.report({
node,
messageId: "missingNullCheck",
data: { subject: match.text, operator: match.operator },
});
},
};
},
});
Loading