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

feat: eslint-plugin-(ember-data|warp-drive) #9541

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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
28 changes: 28 additions & 0 deletions packages/eslint-plugin-ember-data/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# eslint-plugin-warp-drive

> [!TIP]
> This Package is also available as eslint-plugin-ember-data

## Rules

- 🛠️ has Autofix
- 〽️ has Partial Autofix
- ✅ Recommended
- 💜 TypeScript Aware

| Rule | Description | Category | ✨ |
| ---- | ----------- | -------- | -- |
| [no-create-record-rerender](./docs/no-create-record-rerender.md) | Helps avoid patterns that often lead to excess or broken renders | 🐞⚡️ | ✅ |
| no-methods-in-models | restricts adding methods to model classes | usage | ✅ |
| no-computeds-in-models | restricts adding computed properties to model classes | usage | ✅ |
| no-getters-in-models | restricts adding getters/setters to model classes | usage | ✅ |
| no-complex-derivations | Helps avoid patterns that often lead to buggy or brittle code | 🐞 | ✅ |
| no-legacy-transforms | Restricts usage of attr transforms on models that often lead to buggy or brittle code | 🐞 | ✅ |
| no-peek-all | Restricts peekAll usage to reduce bugs and improve perf | 🐞⚡️ | ✅ |
| no-peek-record | Restricts peekRecord usage to reduce bugs | 🐞 | ✅ |
| no-direct-imports | Assists in usage of a whitelabel/repackaged app/company configured experience | usage | 🛠️ |
| no-string-includes | Avoids a pattern that doesn't typecheck as nicely | usage | ✅ 🛠️ |
| no-invalid-relationships | Ensures relationship configuration is setup appropriately | usage | ✅ 〽️ |
| no-legacy-methods | Restricts usage of deprecated methods | usage | ✅ 〽️ |
| no-loose-resource-types | Prevents usage of incorrect resource-types | usage | ✅ 〽️ |
| no-loose-ids | Prevents usage of non-string IDs | usage | ✅ 🛠️ |
5 changes: 5 additions & 0 deletions packages/eslint-plugin-ember-data/docs/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# eslint-plugin-warp-drive

## Rules

- [no-create-record-rerender](./no-create-record-rerender.md)
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# eslint-plugin-warp-drive

## no-create-record-rerender

Helps avoid patterns that often lead to excess or broken renders.

## Don't use `createRecord` inside constructors, getters, or class properties

Calling `createRecord` in these places can cause unexpected re-renders and may blow up in EmberData 4.12+.

### Incorrect Code

```gjs
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { on } from '@ember/modifier';

class MyForm extends Component {
@service store;
// ERROR: Cannot call `store.createRecord` in a class property initializer.
// Calling `store.createRecord` inside constructors, getters, and class
// properties can cause issues with re-renders.
model = this.store.createRecord('user');

<template>
{{!-- Some Template !--}}
</template>
}

export default ParentComponent extends Component {
@tracked isShowingForm = false;

@action rerenderWithForm() {
this.isShowingForm = true;
}

<template>
{{#if this.isShowingForm}}
<MyForm />
{{/if}}
<button type="button" {{on "click" this.rerenderWithForm}}>Show the form</button>
</template>
}
```

### Correct Code

```gjs
// app/components/parent-component.gts
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { on } from '@ember/modifier';

class MyForm extends Component {
<template>
{{!-- Some Template !--}}
</template>
}

export default class ParentComponent extends Component {
@tracked isShowingForm = false;

rerenderForm = () => {
this.model = this.store.createRecord('user');
this.isShowingForm = true;
}

<template>
{{#if this.isShowingForm}}
<MyForm @model={{this.model}} />
{{/if}}
<button type="button" {{on "click" this.rerenderForm}}>Show the child component</button>
</template>
}
```
13 changes: 11 additions & 2 deletions packages/eslint-plugin-ember-data/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,21 @@
"volta": {
"extends": "../../package.json"
},
"dependencies": {
"requireindex": "^1.2.0",
"eslint": "^9.11.1",
"mocha": "^10.7.3"
},
"devDependencies": {
"@warp-drive/internal-config": "workspace:5.4.0-alpha.109"
},
"files": [
"src",
"CHANGELOG.md"
"docs",
"CHANGELOG.md",
"README.md"
],
"scripts": {}
"scripts": {
"test": "mocha tests"
}
}
6 changes: 5 additions & 1 deletion packages/eslint-plugin-ember-data/src/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
'use strict';

const requireIndex = require('requireindex');

module.exports = {
rules: {},
rules: requireIndex(`${__dirname}/rules`),
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
// @ts-check

const messageId = 'noCreateRecordRerender';
const createRecordExpression = 'CallExpression[callee.property.name="createRecord"]';
const emberObjectExtendExpression = 'CallExpression[callee.property.name="extend"]';
const forbiddenParentMethodKeyNames = [
'init',
'initRecord', // legacy modals
'didReceiveAttrs',
'willRender',
'didInsertElement',
'didRender',
'didUpdateAttrs',
'willUpdate',
'willDestroyElement',
'willClearRender',
'didDestroyElement',
];

/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'Disallow use of `store.createRecord` in getters, constructors, and class properties',
category: 'Possible Errors',
recommended: true,
url: 'https://github.com/emberjs/data/tree/main/packages/eslint-plugin-ember-data/docs/rules/no-create-record-rerender.md',
},
messages: {
[messageId]:
'Cannot call `store.createRecord` in {{location}}. Calling `store.createRecord` inside constructors, getters, and class properties can cause issues with re-renders.',
},
},

create(context) {
return {
/**
* Handle class constructor
* @param {import('eslint').Rule.Node} node
*/
[`MethodDefinition[kind="constructor"] ${createRecordExpression}`](node) {
const maybeParentFunction = getParentFunction(node);
if (maybeParentFunction && !parentFunctionIsConstructor(maybeParentFunction)) {
return;
}
context.report({
node,
messageId,
data: { location: 'a constructor' },
});
},

/**
* Handle class getter
* @param {import('eslint').Rule.Node} node
*/
[`MethodDefinition[kind="get"] ${createRecordExpression}`](node) {
context.report({
node,
messageId,
data: { location: 'a getter' },
});
},

/**
* Handle class property initializer
* @param {import('eslint').Rule.Node} node
*/
[`PropertyDefinition ${createRecordExpression}`](node) {
if (getParentFunction(node)) {
return;
}
context.report({
node,
messageId,
data: { location: 'a class property initializer' },
});
},

/**
* Handle lifecycle hooks in a class
* @param {import('eslint').Rule.Node} node
*/
[`MethodDefinition[key.name=/${forbiddenParentMethodKeyNames.join('|')}/] FunctionExpression ${createRecordExpression}`](
node
) {
const maybeParentFunction = getParentFunction(node);
if (maybeParentFunction && !parentFunctionIsInit(maybeParentFunction)) {
return;
}
context.report({
node,
messageId,
data: { location: 'a lifecycle hook' },
});
},

/**
* Handle the init method in an EmberObject
* @param {import('eslint').Rule.Node} node
*/
[`${emberObjectExtendExpression} Property[key.name=/${forbiddenParentMethodKeyNames.join('|')}/] FunctionExpression ${createRecordExpression}`](
node
) {
const maybeParentFunction = getParentFunction(node);
if (maybeParentFunction && !parentFunctionIsInit(maybeParentFunction)) {
return;
}
context.report({
node,
messageId,
data: { location: 'a lifecycle hook' },
});
},

/**
* Handle a property initializer in an EmberObject
* @param {import('eslint').Rule.Node} node
*/
[`${emberObjectExtendExpression} Property > ${createRecordExpression}`](node) {
context.report({
node,
messageId,
data: { location: 'an object property initializer' },
});
},
};
},
};

function getParentFunction(/** @type {import('eslint').Rule.Node} */ node) {
if (node.parent) {
if (node.parent.type === 'ArrowFunctionExpression' || node.parent.type === 'FunctionExpression') {
return node.parent;
} else if (node.parent.type === 'ClassBody') {
return null;
}
return getParentFunction(node.parent);
}
return null;
}

/**
*
* @param {import('eslint').Rule.Node} maybeParentFunction
* @returns {boolean}
*/
function parentFunctionIsConstructor(maybeParentFunction) {
return 'kind' in maybeParentFunction.parent && maybeParentFunction.parent.kind === 'constructor';
}

/**
*
* @param {import('eslint').Rule.Node} maybeParentFunction
* @returns {boolean}
*/
function parentFunctionIsInit(maybeParentFunction) {
return (
'key' in maybeParentFunction.parent &&
maybeParentFunction.parent.key.type === 'Identifier' &&
forbiddenParentMethodKeyNames.includes(maybeParentFunction.parent.key.name)
);
}
Loading
Loading