Custom eslint rules

Valeriy Kuzmin

Moonfare, Berlin, 2022

Plan

  1. Custom eslint rules
  2. No-v3-DI-smuggling
  3. ast-tools helper
  4. Everything together

Intro

Problem

  • Code review works with a diff, not the whole project
  • People can miss things in complex projects
  • We have a ton of custom conventions

 

  • Architectural errors
  • Too tight coupling
  • Minor annoying errors

 

Solution

  • Linting to the rescue!
  • Run in CI
  • Run in IDE

 

  • Limited to the pre-defined rules
  • Cannot cover custom conventions

 

But...

What is a custom eslint rule?

Rule

Walker

Meta

docs + messages

Loader

eslint-local-rules.js

Loader

eslint-local-rules.js

eslint-plugin-local-rules

Node type => analyzer

Loader

eslint-local-rules.js

Tests

valid cases

invalid cases

Welcome back to AST

No-v3-DI-smuggling

Problem

Non-v3

V3

TOKEN_V2

Impl v2

TOKEN_V3

Impl v3

Examples (from tests)

// ok
bind<DocumentAccessValidatorInterface>(PROFESSIONALISATION_DOCUMENT_ACCESS_VALIDATOR_INTERNAL)
	.to(ProfessionalisationDocumentAccessValidatorImpl)

// ok
container.bind<DocumentAccessValidatorInterface>(PROFESSIONALISATION_DOCUMENT_ACCESS_VALIDATOR_INTERNAL)
  .to(ProfessionalisationDocumentAccessValidatorImpl)

// not ok 
bind<AuthorizationService>(AUTHORIZATION_SERVICE).to(AuthorizationService)
context.report({
  node,
  messageId: 'noSmuggling',
  data: {
    token: bindArgument,
    implementation: toArgument,
  },
});

Demo 1

ast-tools helper

Idea

1. Analyze the whole codebase first with TS

2. Save data to files

3. Synchronously read in the rule

What we want from the helper

  1. What is a v3 file vs non-v3 file vs ignored file?
  2. What is token declaration?
  3. What is implementation?
  4. Where does the token come from?
  5. What about uniqueness?

Demo 2

Everything together

Validation

Unique?

Yes

Import path doesn't matter

No

v2 binds to v3 = error

v3 token and v2 class?

Yes

No or unclear

assume no error

Drawbacks

1. Reexports are not followed - you can fool the rule

2. Impls are only properly checked if all non-unique are in v2

Demo 3

Done! Questions?

Custom eslint rules

By Valeriy Kuzmin

Custom eslint rules

  • 156