npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@travetto/eslint

v5.0.14

Published

ES Linting Rules

Downloads

376

Readme

ES Linting Rules

ES Linting Rules

Install: @travetto/eslint

npm install @travetto/eslint

# or

yarn add @travetto/eslint

ESLint is the standard for linting Typescript and Javascript code. This module provides some standard linting patterns and the ability to create custom rules. Due to the fact that the framework supports both CommonJS and Ecmascript Module formats, a novel solution was required to allow ESLint to load Ecmascript Module files.

Note: The ESLint has introduced a new configuration format which allows for Ecmascript Module files.

CLI - Register

In a new project, the first thing that will need to be done, post installation, is to create the eslint configuration file.

Terminal: Registering the Configuration

$ trv lint:register

Wrote eslint config to <workspace-root>/eslint.config.js

This is the file the linter will use, and any other tooling (e.g. IDEs).

Code: Sample configuration

process.env.TRV_MANIFEST = './.trv/output/node_modules/@travetto/eslint';

const { buildConfig } = require('./.trv/output/node_modules/@travetto/eslint/support/bin/eslint-config.js');
const { RuntimeIndex } = require('./.trv/output/node_modules/@travetto/runtime/__index__.js');

const pluginFiles = RuntimeIndex.find({ folder: f => f === 'support', file: f => /support\/eslint[.]/.test(f.relativeFile) });
const plugins = pluginFiles.map(x => require(x.outputFile));
const config = buildConfig(plugins);

module.exports = config;

The output is tied to whether or not you are using the CommonJS or Ecmascript Module format.

CLI - Lint

Once installed, using the linter is as simple as invoking it via the cli:

Terminal: Running the Linter

npx trv lint

Or pointing your IDE to reference the registered configuration file.

Custom Rules

It can be seen in the sample configuration, that the configuration is looking for files with the pattern of support/eslint/.*

These files will follow a given pattern of:

Code: Custom Rule Shape

import type eslint from 'eslint';

export type TrvEslintPlugin = {
  name: string;
  rules: Record<string, {
    defaultLevel?: string | boolean | number;
    create(context: eslint.Rule.RuleContext): eslint.Rule.RuleListener;
  }>;
};

An example plugin is used in the Travetto framework for enforcing import patterns:

Code: Import Order Rule

import type eslint from 'eslint';
import { Program, BaseExpression, Expression } from 'estree';

import type { TrvEslintPlugin } from '@travetto/eslint';

const groupTypeMap = {
  node: ['node', 'travetto', 'workspace'],
  travetto: ['travetto', 'workspace'],
  workspace: ['workspace'],
};

interface TSAsExpression extends BaseExpression {
  type: 'TSAsExpression';
  expression: Expression;
}

declare module 'estree' {
  interface ExpressionMap {
    TSAsExpression: TSAsExpression;
  }
}

export const ImportOrder: TrvEslintPlugin = {
  name: '@travetto-import',
  rules: {
    order: {
      defaultLevel: 'error',
      create(context) {
        function check({ body }: Program): void {
          let groupType: (keyof typeof groupTypeMap) | undefined;
          let groupSize = 0;
          let contiguous = false;
          let prev: eslint.AST.Program['body'][number] | undefined;

          for (const node of body) {

            let from: string | undefined;

            if (node.type === 'ImportDeclaration') {
              if (node.source?.value && typeof node.source.value === 'string') {
                from = node.source.value;
              }
            } else if (node.type === 'VariableDeclaration' && node.kind === 'const') {
              const [decl] = node.declarations;
              let call: Expression | undefined;
              const initType = decl?.init?.type;
              if (initType === 'CallExpression') {
                call = decl.init;
              } else if (initType === 'TSAsExpression') { // tslint support
                call = decl.init.expression;
              }
              if (
                call?.type === 'CallExpression' && call.callee.type === 'Identifier' &&
                call.callee.name === 'require' && call.arguments[0].type === 'Literal'
              ) {
                const arg1 = call.arguments[0];
                if (arg1.value && typeof arg1.value === 'string') {
                  from = arg1.value;
                }
              }
            }

            if (!from) {
              continue;
            }

            const lineType: typeof groupType = /^@travetto/.test(from) ? 'travetto' : /^[^.]/.test(from) ? 'node' : 'workspace';

            if (/module\/[^/]+\/doc\//.test(context.filename) && lineType === 'workspace' && from.startsWith('..')) {
              context.report({ message: 'Doc does not support parent imports', node });
            }

            if (groupType && !groupTypeMap[groupType].includes(lineType)) {
              context.report({ message: `Invalid transition from ${groupType} to ${lineType}`, node });
            }

            if (groupType === lineType) {
              groupSize += 1;
            } else if (((node.loc?.end.line ?? 0) - (prev?.loc?.end.line ?? 0)) > 1) {
              // Newlines
              contiguous = false;
              groupSize = 0;
            }

            if (groupSize === 0) { // New group, who dis
              groupSize = 1;
              groupType = lineType;
            } else if (groupType === lineType && !contiguous) { // Contiguous same
              // Do nothing
            } else if (groupSize === 1) { // Contiguous diff, count 1
              contiguous = true;
              groupType = lineType;
            } else { // Contiguous diff, count > 1
              context.report({ message: `Invalid contiguous groups ${groupType} and ${lineType}`, node });
            }
            prev = node;
          }
        }
        return { Program: check };
      }
    }
  }
};