Skip to content

chore: add ESLint rules - #123

Draft
MatiasArriola wants to merge 14 commits into
masterfrom
chore/add-eslint-rules
Draft

MatiasArriola wants to merge 14 commits into
masterfrom
chore/add-eslint-rules

Conversation

@MatiasArriola

Copy link
Copy Markdown
Contributor

📌 References

📝 Implementation

  • Objective of this PR is to explore enforcement of company coding guidelines through static code analysis. This would be specially useful for LLM-generated code, instead of relying entirely in prompts and manual code review.
  • ESLint presets and custom rules are provided as an attempt to reflect coding and architecture guidelines. We need to decide on the set of rules, make tradeoffs and experiment in other projects.
  • ESLint supressions and different npm scripts were added as an attempt to make adoption easier. For example, this project contained multiple lint errors that are now "accepted" in eslint-suppressions.json. yarn lint:all excludes suppressions allowing to fix existing issues. Not perfect since it only compare error counts per file.
  • Marking this as draft because I consider we need to discuss internally before making these changes.

What follows is an AI-generated detail of the changes included:

Purpose

Automate the mechanically checkable parts of EyeSeeTea's coding conventions while
allowing existing projects to adopt them without first rewriting legacy code.
The skeleton now fails lint when errors exceed accepted legacy counts, keeps the
full backlog available for inspection, and provides a reusable warning-first policy
for downstream projects.

This is especially useful for LLM-generated code: agents can miss or inconsistently
apply written conventions, while static checks provide repeatable, blocking feedback
regardless of who wrote the code. For mechanically checkable rules, this is stronger
enforcement than agent instructions alone and lets agents correct violations before
handing work back for review.

The tradeoff is narrower coverage and ongoing rule maintenance: static analysis
cannot reliably judge design intent, business semantics, or every legitimate
exception, and overly broad checks can produce false positives. Agent instructions
and human review still supply that context; lint enforces the subset that can be
checked reliably. The count-based legacy baseline also leaves same-count replacements
to review, as described below.

This PR changes tooling and documentation; it does not migrate application code.
Static checks provide partial convention coverage and complement code review.

Changes

  • Split ESLint configuration into base, React, testing, and company-policy modules.
  • Add independent eyeseetea/layer-dependencies, eyeseetea/http-client-access,
    and eyeseetea/client-construction rules with shared boundary helpers.
  • Add type-aware collection mutation checks and targeted TypeScript, async,
    styling, testing, and security restrictions using existing dependencies.
  • Move the existing Future capture rule into the eyeseetea namespace without
    changing its behavior.
  • Add an error-level baseline profile, committed native ESLint suppressions,
    baseline commands, rule documentation, and downstream adoption guidance.
  • Separate application tests (yarn test) from ESLint tooling tests (yarn test:eslint),
    with both required by yarn check. Tooling tests run in Node without React setup
    or browser polyfills.
  • Include .mjs files in formatting and test discovery; allow local .ts imports
    in the no-emit TypeScript configuration.

Convention mapping

Source: ai-dev-skeleton/.est_ai/rules/, using generic/, lang/typescript.md,
and dhis2-react/. Kotlin and Android conventions do not apply.

Covered means the stated syntax or structural check is implemented.
Partial means related cases still require review. Review means no dedicated
check is introduced here. The table describes detection before baseline suppression.

EST convention / source Rule or implementation Coverage and limits
Immutable bindings — generic/functional, lang/typescript prefer-const, no-var Covered for bindings; does not prove values are immutable.
No collection or argument mutation — same sources eyeseetea/no-collection-mutation; no-param-reassign with props: true Partial: typed Array/tuple, Map/Set mutator calls, including constrained generics and literal computed access; argument assignments. General object mutation, indexed collection writes, aliasing, and shared state remain unchecked.
Declarative transformations, immutable types, composition — same sources Collection mutation checks provide limited feedback Partial: no blanket loop/inheritance ban; mutable accumulators, search loops, and Readonly declarations are not enforced.
No unsafe casts; typed parameters — lang/typescript @typescript-eslint/no-unsafe-type-assertion, unsafe operation rules, no-explicit-any; syntax restrictions for as unknown and as Type[]; existing strict TypeScript Partial: downcasts and common escape hatches detected; safe widening and as const allowed. Explicit any is restricted more broadly than the source wording.
Derive unions from runtime const arrays; reuse types through Pick/Omit — lang/typescript No dedicated check Review.
Domain must not import data, presentation, or infrastructure; data must not import presentation — generic/architecture eyeseetea/layer-dependencies, eyeseetea/http-client-access Partial: TypeScript-resolved imports, re-exports, literal dynamic imports and require; Node builtins and selected platform APIs, including qualified globals. Transitive dependencies, nonliteral imports, and arbitrary aliases remain unchecked.
Domain/use-case tests do not import infrastructure — dhis2-react/testing Architecture checks remain enabled in tests Partial: same direct-dependency limits as production code.
Repositories use d2-api rather than direct HTTP — dhis2-react/architecture eyeseetea/http-client-access Partial: known HTTP client imports and direct/qualified fetch or XMLHttpRequest; arbitrary data flow and aliased access remain unchecked.
Restrict D2Api usage and construction — dhis2-react/architecture eyeseetea/http-client-access, eyeseetea/client-construction Partial: import boundaries and named imported constructors, including aliases. Construction requires a configured root and enclosing factory. Namespace constructors, indirect factories, and all client usage are not covered.
Futures rather than Promises in domain/data — dhis2-react/architecture no-restricted-globals and syntax selectors Partial: explicit Promise value/type references detected; inferred Promise returns are not. Tests and the two Future implementation files are excluded from Promise restrictions.
.toPromise() only in tests — dhis2-react/architecture no-restricted-syntax member-call selector Partial: production calls named toPromise are reported; receiver identity and aliases are not resolved.
Execute Futures through .run() inside useEffect — dhis2-react/architecture No dedicated check; existing Future capture rule retained Review for execution placement. Capture rule separately requires captured awaits inside recognized Future.block callbacks.
No new makeStyles; use styled-components — dhis2-react/react no-restricted-imports Partial: common named and default import entry points restricted; namespace access is not fully covered. Does not require or install styled-components.
Concrete assertions when exact values are knowable — generic/testing, dhis2-react/testing Syntax selectors for toBeTruthy and toBeDefined Partial and stricter: detects those matcher names without deciding whether an exact value is knowable.
Accessible E2E queries — dhis2-react/testing Syntax selectors for locator, getByTestId, $, $$ Partial: common calls reported in Playwright/E2E scopes; aliases and receiver identity are not resolved.
Secrets, boundary validation, safe handling of untrusted input — generic/security no-eval, no-implied-eval, no-new-func, existing React safety checks Partial: selected unsafe operations restricted; no secret scanning, validation proof, injection analysis, or sanitization verification.
Domain modeling, repository/use-case contracts, composition-root completeness — generic/architecture, dhis2-react/architecture No dedicated checks Review: includes entity behavior/relationships, D2* domain types, MetadataPick, repository/use-case cross-calls, public APIs, and wiring.
Render-only components, presentation logic in hooks, context access — dhis2-react/react Existing Hooks checks provide related correctness checks Review for responsibility boundaries, useAppContext() access, and one global context.
Behavior-focused tests, required business-rule coverage, repository test doubles, grouping — generic/testing, dhis2-react/testing No dedicated checks Review; assertion and Testing Library checks do not establish these properties.
Planning, verification, human review, shared-system approval — generic/process Existing yarn check integrates local verification Review/workflow enforcement; ESLint cannot establish process compliance.

Additional restrictions and explicit exceptions

The policy is an implementation of selected conventions, not an exact encoding of
every source rule:

  • All explicit any is flagged, beyond the source prohibition on contract-bypassing
    casts and untyped parameters.
  • Truthiness/existence assertions are flagged unconditionally. Under the skeleton's
    baseline profile these are errors, including legitimate conditional exceptions.
  • Testing Library user-event, presence-query, and explicit-assertion preferences;
    floating Promises; unused imports; callback returns; and categorical evaluation
    bans add correctness or style checks beyond the literal EST rules.
  • Presentation imports from data/ are prohibited, including infrastructure helpers
    located there. Direct HTTP restrictions also apply to presentation.
  • Configured composition roots and API adapters may import clients as infrastructure
    exceptions to repository-only usage. Adapters cannot construct clients outside
    a permitted root/factory.
  • Existing framework checks remain in place. Future capture predates this PR.

Baseline behavior

The reusable eyeseetea-config.ts defaults most additions to warnings. This skeleton
uses baseline-config.mjs to promote policy warnings to errors while preserving
options and scopes, because native ESLint suppressions apply only to errors.
Other framework/base warnings remain advisory.

Command Behavior
yarn lint / yarn lint:new Lint all src; fail on unsuppressed errors or stale accepted counts.
yarn lint:all Show all findings through a committed empty baseline; expected to fail while legacy errors remain.
yarn lint:cached Same gate with a content cache for local feedback.
yarn lint:baseline Create or increase accepted counts; deliberate acceptance only.
yarn lint:baseline:prune Remove/reduce obsolete counts after fixes without accepting new violations.

yarn check already invokes the gate through yarn lint. Normal lint and inspection
do not rewrite the baseline; CI must never regenerate it. A missing explicitly named
baseline fails. Keep eslint/empty-suppressions.json as {}. The existing lint-all
also runs ts-prune and is distinct from lint:all.

Guarantee: suppressions store a count per file and rule. Adding a fourth finding
to a bucket with three accepted findings fails and reports all four; the Git diff
identifies the introduced one. Fixing one and introducing another in the same bucket
can pass with an unchanged count. This is a count ratchet, not finding identity tracking
or proof that all accepted violations are legacy.

Review baseline changes, file moves, and rule upgrades explicitly. Commit pruning
alongside fixes. Required CI uses uncached lint: file caching may miss effects of
imported type/dependency changes. Editors and Node API integrations may still display
accepted findings unless they support bulk suppressions.

Adoption in another project

  1. Choose scope. Copy the full configuration, company policy plus rules, or selected
    custom rules from a recorded commit. Keep local overrides separate. See
    MIGRATION.md for dependency and integration details.
  2. Prepare the runtime. Use Node 24.13.1 or a compatible newer Node 24 release for
    native .ts imports, ESLint 9.24+ for suppressions, and compatible direct dependencies
    from package.json. Older runtimes need a loader or compiled policy. Include copied
    TypeScript rules in a no-emit typecheck with allowImportingTsExtensions.
  3. Adapt configuration. Register the required parser/plugins; configure the TS
    project, aliases, source/test/E2E scopes, and generated-file ignores. Share architecture
    paths across enabled rules and set clientFactories for client construction.
    Supplied path arrays replace defaults. Update old Future capture suppressions to
    the eyeseetea namespace.
  4. Choose enforcement. Retain the warning-first policy for gradual hardening, or
    copy baseline-config.mjs, empty-suppressions.json, and the baseline scripts.
    For the latter, compose the baseline profile after framework config and before
    deliberate local overrides.
  5. Review findings. Run unsuppressed lint, correct configuration mistakes, fix
    correctness defects, and identify accepted legacy findings. Generate a project-specific
    eslint-suppressions.json; never copy this skeleton's counts. lint:baseline accepts
    all current rule errors, including correctness errors; use native
    --suppress-rule <rule-id> for selective acceptance.
  6. Verify and require the gate. Adapt copied regression fixtures; run typecheck,
    formatting, lint, application tests, and test:eslint using the dedicated Node
    configuration. Require both suites in CI. Inspect effective config for production, tests, E2E,
    and adapters. Commit the reviewed baseline and require uncached lint:new or
    check in CI. Prune as legacy findings are fixed.

Performance

A downstream benchmark in metadata-synchronization compared its previous ESLint
configuration with the migrated configuration:

Median measurement Previous configuration Migrated configuration
Wall time 14.74 s 32.14 s
CPU time (user + system) 26.66 s 63.49 s
Peak RSS 1.51 GiB 2.29 GiB

The migrated run took 2.18× as long (+17.40 s, +118%) and used more peak memory.
This is a material adoption cost, especially for larger projects and constrained CI
runners. The migrated run reported 93 warnings and no errors; the previous run
reported no diagnostics. All invocations completed successfully.

Method: Node 22.22.0, one unmeasured warm-up and three alternating measured runs per
worktree, with a fresh Node process each time. ESLint's cache was disabled and the
filesystem cache was warm; installation and Yarn wrapper overhead were excluded.
The comparison used downstream origin/master at 13e300ce8614 (ESLint 8.57.1)
and branch chore/test-new-lint-rules at f3c41cf4691d plus uncommitted migration
changes (ESLint 9.39.5).

These are actual downstream worktree results, not an isolated measurement of this
PR: ESLint versions differ, and seven source files also changed (84 insertions,
65 deletions). The benchmark does not separate type-aware/custom-rule costs from
the migration or native suppression bookkeeping, and does not measure cold filesystem
or cached local runs. Its Node version also differs from this PR's recommended
Node 24 runtime.

Use lint:cached for local feedback; required CI remains uncached for correctness.
For larger consumers, profile rule execution and repeat the comparison on identical
source and the intended runtime before setting performance expectations.

Validation

Validation after separating application and tooling suites:

  • yarn typecheck
  • yarn prettify:check
  • yarn lint:new
  • yarn test:unit — 137 application tests across 13 files passed (jsdom)
  • yarn test:eslint — 83 tooling tests across 8 files passed (Node)
  • yarn check — full verification, including both suites, passed
  • git diff --check

@bundlemon

bundlemon Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

BundleMon

No change in files bundle size

Unchanged groups (1)
Status Path Size Limits
✅ Build Folder
./**/*
914.49KB +20%

Final result: ✅

View report in BundleMon website ➡️


Current branch size history | Target branch size history

@tokland
tokland self-requested a review October 15, 2026 08:53

@tokland tokland left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Tested on CPR development (8fc505a). New rules only. Counts: yarn lint:all hits / files.

KEEP

  • layer-dependencies (259/221): all real violations.
  • http-client-access (37/30): real hits. Rule fix: do not flag Blob used as a type.
  • no-collection-mutation (21/9): low noise. Config fix: exclude tests (fixture builders).
  • no-unsafe-type-assertion (183/81): most valuable for LLM code.
  • no-unsafe-* (101/27): real any leaks.
  • no-floating-promises (30/28): real hits.
  • toPromise() ban (8/7): 1 real hit; rest are composition roots, scripts and migrations.
  • Promise ban (50/8): real hits in domain; data hits are 5 adapter files, disable per file.
  • no-explicit-any (43/16): 25 in extends. Config fix: allow via no-restricted-syntax.
  • makeStyles ban (30/30): fine, CPR already uses styled-components (46 files).
  • no-param-reassign props (12/6): fine; only DOM code needs exceptions.
  • no-var, no-eval, no-new-func, rules-of-hooks, testing-library rules: 0 hits.
  • Ignoring existing errors (eslint-suppressions.json): makes adoption possible.

REMOVE (proposal)

  • as Type[] ban (35/25): redundant with no-unsafe-type-assertion.
  • as unknown ban (25/12): redundant with no-unsafe-type-assertion.
  • array-callback-return (25/20): flags legit uses like void Future.map; 24 false hits.

Notes

  • Lint time: 6.1s → 17.7s (2.9×). Type info +2.6s; new rules +9s, mostly no-unsafe-*.
  • Node 22.18+ already runs the .ts config natively; Node 24 is not required.
  • allowImportingTsExtensions needs TS 5; on TS 4.9 lint works but eslint/ is not typechecked.

Allow platform types, test fixture mutation, and generic any constraints. Remove noisy cast and callback checks, update adoption docs, and migrate suppressions.

Add regression coverage and improve test readability. Validated with yarn check and focused tests.
@MatiasArriola

Copy link
Copy Markdown
Contributor Author

Thanks @tokland!! Agreed on your proposals and the findings are very valuable. Included in latest commit:

  • Allow Blob and other platform globals as types while retaining runtime checks.
  • Exclude tests from collection mutation checks.
  • Allow any in generic constraints; defaults such as <T = any> remain restricted.
  • Remove the cast syntax bans, retaining type-aware unsafe assertion checks.
  • Disable array-callback-return because it also flags valid Future.map callbacks; document the resulting array-check coverage gap.
  • Update Node/TypeScript adoption guidance, migrate/prune suppressions, and add regression tests.

The other proposed “keep” rules remain enabled. Promise/toPromise() exceptions are documented for downstream projects to apply per file; no broad exemptions were added. Performance figures are documented, but profiling and a type-aware replacement for array-callback-return remain follow-up work.

I did some more testing in metadata-synchronization and tried some performance improvements like caching module resolution, but it did not introduce valuable gains. Using yarn lint:cached is the way to go locally, while we need the full check for CI or final fresh verification. Also a --concurrency option is available in ESLint, but for example, using 2 concurrency doubles memory usage while having a ~20% improvement in metadata sync.

Based on lint errors in metadata-sync, we have also some issues that could be considered "false positives" but maybe we can consider that belongs to a project-specific customization based on this template

@tokland

tokland commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Thanks Matias, the fixes all look good - verified Blob handling, test exclusions, generic-constraint any, and the removal of the cast-syntax bans.

One blocker: dependency-track-yarn4 is failing the vulnerability gate - the branch introduces 4 new critical and 2 new high instances vs base (likely transitive deps of the new ESLint tooling). Can you look into those?

Regarding the draft: whenever the internal discussion lands, happy to review the final state and approve.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants