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

create eslint-plugin-xstate package #221

Draft
wants to merge 14 commits into
base: main
Choose a base branch
from
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ apps/extension/client/scripts
.DS_Store
.turbo
.idea
yarn-error.log
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,10 @@
"@preconstruct/cli": "^2.1.0",
"@types/node": "^16.0.1",
"@typescript-eslint/eslint-plugin": "^4.23.0",
"@typescript-eslint/parser": "^4.23.0",
"@typescript-eslint/parser": "^5.37.0",
"concurrently": "6.2.0",
"esbuild": "^0.14.48",
"eslint": "^7.26.0",
"eslint": "^8.0.0",
Comment on lines +90 to +93
Copy link
Contributor Author

Choose a reason for hiding this comment

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

We have the config in .eslintrc.js commented out so updating these doesn't affect anything

"husky": ">=6",
"lint-staged": ">=10",
"prettier": "^2.3.1",
Expand Down
18 changes: 18 additions & 0 deletions packages/eslint-plugin-xstate/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/** @type {import('@jest/types').Config.InitialOptions} */
module.exports = {
testMatch: ["**/?(*.)+(spec|test).[jt]s?(x)"],
watchPathIgnorePatterns: [
"<rootDir>/src/__tests__/__examples__/*.typegen.ts",
],
watchPlugins: [
"jest-watch-typeahead/filename",
"jest-watch-typeahead/testname",
],
snapshotFormat: {
printBasicPrototype: false,
escapeString: false,
},
transform: {
"^.+\\.tsx?$": ["esbuild-jest", { sourcemap: true }],
},
};
32 changes: 32 additions & 0 deletions packages/eslint-plugin-xstate/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "eslint-plugin-xstate",
"version": "0.0.0",
"main": "dist/eslint-plugin-xstate.cjs.js",
"author": "with-heart <[email protected]>",
"license": "MIT",
"keywords": [
"eslint",
"eslintplugin"
],
"scripts": {
"test": "jest"
},
"dependencies": {
"@typescript-eslint/utils": "^5.37.0"
},
"devDependencies": {
"@typescript-eslint/parser": "^5.37.0",
"eslint": "^8.0.0",
"typescript": "^4.3.5"
},
"peerDependencies": {
"@typescript-eslint/parser": "^5.0.0",
"eslint": "^6.0.0 || ^7.0.0 || ^8.0.0",
"typescript": "*"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
}
Comment on lines +17 to +31
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm not entirely sure these dependencies are correct if we end up publishing this package. I somewhat copied the dependencies setup from @typescript-eslint/eslint-plugin, but they also don't have any of these as devDependencies which yarn whined about 🤷

}
21 changes: 21 additions & 0 deletions packages/eslint-plugin-xstate/src/estree-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { ASTUtils, AST_NODE_TYPES, TSESTree } from "@typescript-eslint/utils";

const is = <Type extends AST_NODE_TYPES>(type: Type) =>
ASTUtils.isNodeOfType(type);

export const isCallExpression = is(AST_NODE_TYPES.CallExpression);
export const isIdentifier = is(AST_NODE_TYPES.Identifier);
export const isImportNamespaceSpecifier = is(
AST_NODE_TYPES.ImportNamespaceSpecifier
);
export const isImportSpecifier = is(AST_NODE_TYPES.ImportSpecifier);
export const isLiteral = is(AST_NODE_TYPES.Literal);
export const isMemberExpression = is(AST_NODE_TYPES.MemberExpression);
export const isObjectExpression = is(AST_NODE_TYPES.ObjectExpression);
export const isProperty = is(AST_NODE_TYPES.Property);

export const isIdentifierWithName =
(name: string) =>
(node: TSESTree.Node): node is TSESTree.Identifier => {
return isIdentifier(node) && node.name === name;
};
25 changes: 25 additions & 0 deletions packages/eslint-plugin-xstate/src/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { TSESLint, TSESTree } from "@typescript-eslint/utils";
import { isCallExpression, isIdentifierWithName } from "./estree-utils";

export const findPrevTokenMatching = (
node: TSESTree.Node,
sourceCode: Readonly<TSESLint.SourceCode>,
match: string[]
): TSESTree.Token | null => {
let prevToken = sourceCode.getTokenBefore(node);

while (prevToken && !match.includes(prevToken.value)) {
prevToken = sourceCode.getTokenBefore(prevToken)!;
}

return prevToken && match.includes(prevToken.value) ? prevToken : null;
};

export const isCreateMachineFactory = (node?: TSESTree.Node): boolean =>
isCallExpression(node) &&
(isIdentifierWithName("createMachine")(node.callee) ||
isIdentifierWithName("createTestMachine")(node.callee));

export const hasCreateMachineFactoryAncestor = (ancestors: TSESTree.Node[]) => {
return ancestors.some((ancestor) => isCreateMachineFactory(ancestor));
};
3 changes: 3 additions & 0 deletions packages/eslint-plugin-xstate/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import rules from "./rules";

export { rules };
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { ESLintUtils } from "@typescript-eslint/utils";
import outdent from "outdent";
import rule from "./avoid-context-spread";

const ruleTester = new ESLintUtils.RuleTester({
parser: "@typescript-eslint/parser",
});

ruleTester.run("avoid-context-spread", rule, {
valid: [
{
code: outdent`
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Using outdent allows the code blocks to be displayed correctly in test output. Not sure if there's a better way to handle that but without it, the indentation was a mess.

machine.withContext({
key: 'value',
})
`,
},
],
invalid: [
{
code: outdent`
machine.withContext({
key: 'value',
...machine.context,
})
`,
output: outdent`
machine.withContext({
key: 'value',
})
`,
errors: [{ messageId: "avoidSpread" }],
},
{
code: outdent`
machine.withContext({
key: 'value', ...machine.context,
})
`,
output: outdent`
machine.withContext({
key: 'value',
})
`,
errors: [{ messageId: "avoidSpread" }],
},
],
});
117 changes: 117 additions & 0 deletions packages/eslint-plugin-xstate/src/rules/avoid-context-spread.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { ESLintUtils, TSESTree } from "@typescript-eslint/utils";
import {
isCallExpression,
isIdentifier,
isIdentifierWithName,
isMemberExpression,
} from "../estree-utils";
import { findPrevTokenMatching } from "../helpers";

const isContextIdentifier = isIdentifierWithName("context");
const isWithContextIdentifier = isIdentifierWithName("withContext");

const findContextMemberExpressionArgument = (node: TSESTree.SpreadElement) => {
return (
isMemberExpression(node.argument) &&
isContextIdentifier(node.argument.property) &&
node.argument
);
};

const findClosestCallExpression = (ancestors: TSESTree.Node[]) => {
return ancestors
.reverse()
.find((ancestor): ancestor is TSESTree.CallExpression =>
isCallExpression(ancestor)
);
};

const isWithContextCallExpression = (
node: TSESTree.CallExpression
): node is TSESTree.CallExpression & {
callee: TSESTree.MemberExpression;
} => {
return (
isMemberExpression(node.callee) &&
isWithContextIdentifier(node.callee.property)
);
};

const hasMatchingObjectIdentifier = (
node1: TSESTree.MemberExpression,
node2: TSESTree.MemberExpression
) => {
return (
isIdentifier(node1.object) &&
isIdentifier(node2.object) &&
node1.object.name === node2.object.name
);
};

const createRule = ESLintUtils.RuleCreator((name) => name);

const rule = createRule({
create(context) {
const sourceCode = context.getSourceCode();

return {
SpreadElement(node) {
const ancestors = context.getAncestors();

const contextArgument = findContextMemberExpressionArgument(node);
const parentCallExpression = findClosestCallExpression(ancestors);

if (
!contextArgument ||
!parentCallExpression ||
!isWithContextCallExpression(parentCallExpression) ||
!hasMatchingObjectIdentifier(
contextArgument,
parentCallExpression.callee
)
) {
return;
}

context.report({
node,
messageId: "avoidSpread",
fix(fixer) {
const prevToken = findPrevTokenMatching(node, sourceCode, [
",",
"{",
]);

let lastToken = sourceCode.getTokenAfter(node);
if (lastToken?.value !== ",") {
lastToken = sourceCode.getTokenBefore(lastToken!);
}

const start = prevToken?.range[1] ?? node.loc.start.line;
const end = lastToken?.range[1] ?? node.loc.end.line;

return fixer.removeRange([start, end]);
},
});
},
};
},
name: "avoid-context-spread",
meta: {
type: "problem",
fixable: "code",
messages: {
avoidSpread:
"`withContext` accepts partial `context`—no need to spread `machine.context`",
},
docs: {
description:
"Since `machine.withContext` now permits partial context, no need to spread `machine.context`",
recommended: "warn",
},
schema: [],
},
defaultOptions: [],
});

export default rule;
17 changes: 17 additions & 0 deletions packages/eslint-plugin-xstate/src/rules/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import avoidContextSpread from "./avoid-context-spread";
import noCond from "./no-cond";
import noEmittedFrom from "./no-emitted-from";
import noFactoryContextArg from "./no-factory-context-arg";
import requireObjectContext from "./require-object-context";
import requireParameterizedActionsParams from "./require-parameterized-actions-params";
import requireParameterizedGuardsParams from "./require-parameterized-guards-params";

export default {
"avoid-context-spread": avoidContextSpread,
"no-cond": noCond,
"no-emitted-from": noEmittedFrom,
"no-factory-context-arg": noFactoryContextArg,
"require-object-context": requireObjectContext,
"require-parameterized-actions-params": requireParameterizedActionsParams,
"require-parameterized-guards-params": requireParameterizedGuardsParams,
};
57 changes: 57 additions & 0 deletions packages/eslint-plugin-xstate/src/rules/no-cond.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { ESLintUtils } from "@typescript-eslint/utils";
import outdent from "outdent";
import rule from "./no-cond";

const ruleTester = new ESLintUtils.RuleTester({
parser: "@typescript-eslint/parser",
});

ruleTester.run("no-use-cond", rule, {
valid: [
{
code: outdent`
createMachine({
on: {
event: {
guard: 'guard'
}
}
})
`,
},
{
code: outdent`
const thing = {
on: {
event: {
cond: 'guard'
}
}
}
`,
},
],
invalid: [
{
code: outdent`
createMachine({
on: {
event: {
cond: 'guard'
}
}
})
`,
output: outdent`
createMachine({
on: {
event: {
guard: 'guard'
}
}
})
`,
errors: [{ messageId: "renameCond" }],
},
],
});
Loading