Skip to content

Commit

Permalink
feat(eslint-plugin): add new use-client-directive rule
Browse files Browse the repository at this point in the history
  • Loading branch information
mainframev committed Oct 25, 2023
1 parent e68297b commit 744c368
Show file tree
Hide file tree
Showing 7 changed files with 90 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
// noop
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
// noop
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"compilerOptions": {
"strict": true,
"module": "ESNext",
"noEmit": true,
"moduleResolution": "node"
},
"include": ["*.test.ts", "../__fixtures__"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import dedent from "dedent";
import ruleTester from "../ruleTester";
import useClient from "../rules/useClient";

describe("use-client-directive", () => {
ruleTester.run("use-client-directive", useClient, {
valid: [
{
code: dedent`
"use client";
import React from "react";
import styled from 'styled-components';
`,
},
],
invalid: [
{
code: dedent`
import React from "react";
import styled from 'styled-components';
`,
errors: [{ messageId: "error" }],
output: dedent`
"use client";
import React from "react";
import styled from 'styled-components';
`,
},
],
});
});
2 changes: 2 additions & 0 deletions packages/eslint-plugin-orbit-components/src/consts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const RULE_URL =
"https://github.com/kiwicom/orbit/tree/master/packages/eslint-plugin-orbit-components/docs/rules";
41 changes: 41 additions & 0 deletions packages/eslint-plugin-orbit-components/src/rules/useClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { AST_NODE_TYPES, TSESTree as t, TSESLint } from "@typescript-eslint/utils";
import ruleCreator from "../utils/ruleCreator";

const useClient = ruleCreator({
name: "use-client-directive",
meta: {
type: "problem",
fixable: "code",
docs: {
description: "Prevents missing 'use client' directive in Orbit components",
},
messages: {
error: "Missing 'use client' directive in Orbit components",
},
schema: [],
},
defaultOptions: [],

create: context => {
return {
Program(node: t.Program) {
if (node.sourceType !== "module") return;
if (node.body.length === 0) return;

const noDirective = node.body.some(n => n.type === AST_NODE_TYPES.ExpressionStatement);

if (!noDirective) {
context.report({
node,
messageId: "error",
fix: fixer => {
return fixer.insertTextBefore(node.body[0], `"use client";\n`);
},
});
}
},
};
},
});

export default useClient;
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { ESLintUtils } from "@typescript-eslint/utils";

import { RULE_URL } from "../consts";

export default ESLintUtils.RuleCreator(name => `${RULE_URL}/${name}`);

0 comments on commit 744c368

Please sign in to comment.