From 403945d65e8ccab633e001015af32d0959709b5c Mon Sep 17 00:00:00 2001 From: Matias Arriola Date: Wed, 7 Oct 2026 12:53:39 -0300 Subject: [PATCH 01/14] feat(eslint): add EyeSeeTea policy and custom rules --- README.md | 3 + eslint.config.mjs | 13 +- eslint/README.md | 85 ++++++++ eslint/eyeseetea-config.spec.ts | 158 +++++++++++++++ eslint/eyeseetea-config.ts | 157 +++++++++++++++ eslint/eyeseetea-plugin.ts | 12 ++ eslint/rules/architecture/README.md | 51 +++++ eslint/rules/architecture/rule.spec.ts | 85 ++++++++ eslint/rules/architecture/rule.ts | 184 ++++++++++++++++++ eslint/rules/no-collection-mutation/README.md | 46 +++++ .../rules/no-collection-mutation/rule.spec.ts | 51 +++++ eslint/rules/no-collection-mutation/rule.ts | 64 ++++++ eslint/rules/require-future-block-capture.md | 21 -- .../require-future-block-capture/README.md | 41 ++++ .../rule.spec.ts} | 6 +- .../rule.ts} | 3 +- package.json | 4 +- tsconfig.json | 1 + vite.config.ts | 2 +- 19 files changed, 950 insertions(+), 37 deletions(-) create mode 100644 eslint/README.md create mode 100644 eslint/eyeseetea-config.spec.ts create mode 100644 eslint/eyeseetea-config.ts create mode 100644 eslint/eyeseetea-plugin.ts create mode 100644 eslint/rules/architecture/README.md create mode 100644 eslint/rules/architecture/rule.spec.ts create mode 100644 eslint/rules/architecture/rule.ts create mode 100644 eslint/rules/no-collection-mutation/README.md create mode 100644 eslint/rules/no-collection-mutation/rule.spec.ts create mode 100644 eslint/rules/no-collection-mutation/rule.ts delete mode 100644 eslint/rules/require-future-block-capture.md create mode 100644 eslint/rules/require-future-block-capture/README.md rename eslint/rules/{require-future-block-capture.spec.ts => require-future-block-capture/rule.spec.ts} (94%) rename eslint/rules/{require-future-block-capture.ts => require-future-block-capture/rule.ts} (96%) diff --git a/README.md b/README.md index df17305..2172061 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,9 @@ $ yarn run check ``` This runs the TypeScript typecheck, Prettier check, lint, and tests. +The [EyeSeeTea ESLint policy](eslint/README.md) documents enforced conventions, warning/error levels, +legacy-code rollout, justified exceptions, and practices that still require review. + Individual checks can also be run with `yarn typecheck`, `yarn prettify:check`, `yarn lint`, and `yarn test`. ## Some development tips diff --git a/eslint.config.mjs b/eslint.config.mjs index 5fe5fe9..63d4463 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -6,10 +6,9 @@ import testingLibrary from "eslint-plugin-testing-library"; import noRelativeImportPaths from "eslint-plugin-no-relative-import-paths"; import unusedImports from "eslint-plugin-unused-imports"; -import requireFutureBlockCapture from "./eslint/rules/require-future-block-capture.ts"; +import eyeseeteaConfig from "./eslint/eyeseetea-config.ts"; -// ESLint 9 flat config, converted from .eslintrc.json. Same rule set: the file -// is longer because flat config spells out what `extends` and `env` used to imply. +// Framework defaults plus the EyeSeeTea policy in eslint/eyeseetea-config.ts. export default tseslint.config( { ignores: [ @@ -42,11 +41,6 @@ export default tseslint.config( react: { version: "detect" }, }, plugins: { - local: { - rules: { - "require-future-block-capture": requireFutureBlockCapture, - }, - }, "react-hooks": reactHooks, "no-relative-import-paths": noRelativeImportPaths, "unused-imports": unusedImports, @@ -108,7 +102,6 @@ export default tseslint.config( "error", { allowSameFolder: true, rootDir: "src", prefix: "$" }, ], - "local/require-future-block-capture": "error", }, }, @@ -125,6 +118,8 @@ export default tseslint.config( }, }, + ...eyeseeteaConfig, + { files: ["**/*.js"], languageOptions: { parserOptions: { project: null } }, diff --git a/eslint/README.md b/eslint/README.md new file mode 100644 index 0000000..b8244ab --- /dev/null +++ b/eslint/README.md @@ -0,0 +1,85 @@ +# EyeSeeTea ESLint policy + +`eyeseetea-config.ts` implements automated checks for EyeSeeTea's coding conventions. +The coverage below describes the enforced checks and their limitations. + +## Organization + +`eyeseetea-plugin.ts` exports the custom rules under the `eyeseetea` namespace: +[architecture](rules/architecture/README.md), +[no-collection-mutation](rules/no-collection-mutation/README.md), and +[require-future-block-capture](rules/require-future-block-capture/README.md). + +Each rule lives in `rules//` with `rule.ts`, `rule.spec.ts`, and +`README.md`. Documentation includes rule details, examples, options, and limitations; +rule metadata links to that reference through `meta.docs.url`. +Policy integration tests live in `eyeseetea-config.spec.ts`. + +`eyeseetea-config.ts` registers the plugin and defines policy severities and file +scopes, including conventions enforced through third-party rules. Framework defaults +and parser setup remain in the root `eslint.config.mjs`. + +The Future capture rule applies across the root configuration's linted files at +error severity; architecture and collection mutation apply to `src/**/*.{ts,tsx}` +as warnings. + +## Severity and legacy code + +EyeSeeTea additions start as **warnings** because the source rules apply to new code +and explicitly preserve legacy code. `yarn lint` still succeeds with warnings. +Warnings are actionable review feedback for new code, not permission to copy a legacy +pattern. ESLint cannot determine the age of code. Do not use `--max-warnings=0` until +a deliberate migration or baseline mechanism is agreed. Promote individual rules to +errors after their existing findings have been reviewed. + +Definite safety/correctness checks are **errors**: `no-eval`, `no-implied-eval`, +`no-new-func`, `array-callback-return`, and `react-hooks/rules-of-hooks`. +Existing project errors, including the Future capture rule, remain enabled. + +Use a narrow `eslint-disable-next-line -- ` for a justified exception. +Prefer explaining the adapter, legacy constraint, or library contract over disabling +an entire directory. The Promise exclusions name the two Future implementation files +that necessarily implement the abstraction; new business code receives no blanket exemption. + +## Coverage + +| Coding convention | Automated checks | Level / limits | +| --- | --- | --- | +| Immutability | `prefer-const`, `no-var`, `no-param-reassign` including properties; local collection mutation rule | Warn. Typed Array/tuple, standard Map/Set mutators; custom methods called `push` are allowed. Arbitrary object mutation, aliasing, and shared-state analysis still require review. | +| Type safety | Explicit `any`; type-aware unsafe assignment, argument, call, member access, return, and type assertion rules; restricted `as unknown` and `as Type[]` | Warn. Safe widening and `as const` are allowed. Type guards and `satisfies` are preferred. | +| Layer dependencies | Local architecture rule resolves imports using TypeScript configuration; checks static imports, re-exports, literal dynamic imports and `require` | Warn. Domain → data/UI/platform and data → UI are forbidden; presentation → concrete data is reported. Checks direct dependencies, not transitive architectural purity. | +| API boundaries | d2-api import boundaries, aliased named `D2Api` construction, HTTP imports and platform HTTP globals | Warn. Repository/client adapter/composition-root imports allowed. Named client construction belongs in `getWebappCompositionRoot` in `CompositionRoot.ts`. Namespace constructors, indirect factory calls, and nonliteral dynamic imports need review. | +| Asynchronous code | Promise value/type references in domain/data; production `toPromise()` calls; existing Future capture rule | Warn, except capture errors. Tests allow Promises and `toPromise`. `Future.block` async callbacks remain valid. Inferred Promise returns and APIs exposed through aliases are not fully covered. | +| React styling and Hooks | Restricted `makeStyles` imports; React Hooks rules | Styling warns; hook correctness errors; dependencies warn. Styling namespace imports and component-vs-hook responsibilities need review. | +| Unit and component testing | Weak existence/truthiness matchers warn; Testing Library async queries, presence queries, explicit assertions and user-event guidance | Warnings allow legitimate existence checks. No Jest plugin: this repository runs Vitest. | +| End-to-end testing | Playwright `locator`, `$`, `$$`, `getByTestId` warn in `src/tests/playwright/**` or `*.e2e.ts(x)` | Prefer `getByRole`, `getByLabel`, `getByText`. Testing Library does not enforce Playwright APIs. Aliased helper functions need review. | +| Security | Dangerous evaluation/function construction; existing React safety checks | Errors for evaluation. This does not prove sanitization, boundary validation, or secret safety. | + +Existing project warnings also cover console logging and unused variables. Unused +imports now warn through the already installed plugin. Floating Promises warn as a +correctness check. Strict TypeScript already rejects untyped function parameters. + +## Deliberately omitted + +- Blanket bans on loops, `forEach`, or inheritance: the EyeSeeTea rules target mutable + accumulation and prefer composition; they do not prohibit every iteration or subclass + (including subclasses of `Error`). Collection mutation checks target the concrete problem. +- A ban on every cast: safe widening is allowed by EyeSeeTea policy. The type-aware + `no-unsafe-type-assertion` rule detects narrowing rather than enforcing a syntax style. +- TODO warnings: no authoritative rule prohibits TODO comments. +- A blanket functional or security plugin preset: these add policy and false positives + beyond the source invariants. The targeted rules use existing dependencies. +- Forcing styled-components installation or migrating existing CSS: import checks prevent + new `makeStyles`; changing existing styling is a separate refactor. + +Single responsibility, domain modeling, repository contracts, input validation, +business-rule test coverage, composition-root completeness, and component/hook +responsibilities remain part of human/agent review. Static checks complement those +instructions; they cannot replace them. + +## Verification + +`yarn test` includes the EyeSeeTea policy regression tests as well as application tests. +`yarn lint` applies the EyeSeeTea policy to application TypeScript. Rule tests exercise +both positive and negative examples, including aliases, relative imports, legacy +interop exclusions, and legitimate similarly named methods. diff --git a/eslint/eyeseetea-config.spec.ts b/eslint/eyeseetea-config.spec.ts new file mode 100644 index 0000000..277954f --- /dev/null +++ b/eslint/eyeseetea-config.spec.ts @@ -0,0 +1,158 @@ +import { TSESLint } from "@typescript-eslint/utils"; +const { ESLint, Linter } = TSESLint; +import { parser } from "typescript-eslint"; +import { beforeAll, describe, expect, test } from "vitest"; + +const eslint = new ESLint({ + overrideConfig: [ + { + files: ["policy-probe.ts"], + languageOptions: { + parser, + parserOptions: { + project: null, + projectService: { allowDefaultProject: ["policy-probe.ts"] }, + }, + }, + rules: { + "eyeseetea/no-collection-mutation": "warn", + "@typescript-eslint/no-unsafe-type-assertion": "warn", + }, + }, + ], +}); + +async function lintMutation(code: string) { + const [result] = await eslint.lintText(code, { filePath: "policy-probe.ts" }); + return result!.messages.filter( + message => message.ruleId === "eyeseetea/no-collection-mutation" || message.fatal + ); +} + +async function policyMessages(code: string, filename: string) { + const [result] = await new ESLint().lintText(code, { filePath: filename }); + return result!.messages; +} + +// TypeScript project initialization is slower than individual checks, especially +// when application tests run concurrently. Keep this budget local to setup. +beforeAll(async () => { + await lintMutation("export {};"); +}, 20000); + +describe("type assertions", () => { + test("permits safe widening and as const but reports downcasts", async () => { + const [result] = await eslint.lintText( + ` + interface Animal { name: string } + interface Dog extends Animal { bark(): void } + declare const dog: Dog; + declare const animal: Animal; + const wide = dog as Animal; + const constant = ["a", "b"] as const; + const narrow = animal as Dog; + `, + { filePath: "policy-probe.ts" } + ); + const messages = result!.messages.filter( + message => + message.ruleId === "@typescript-eslint/no-unsafe-type-assertion" || message.fatal + ); + expect(messages).toHaveLength(1); + expect(messages[0]!.ruleId).toBe("@typescript-eslint/no-unsafe-type-assertion"); + }); +}); + +describe("effective EyeSeeTea configuration", () => { + test("custom rules retain their scopes and severities under the EyeSeeTea namespace", async () => { + const eslint = new ESLint(); + for (const filename of ["src/data/api-futures.ts", "eslint/probe.ts", "probe.js"]) { + const config = await eslint.calculateConfigForFile(filename); + expect(config?.rules?.["eyeseetea/require-future-block-capture"]).toEqual( + expect.arrayContaining([2]) + ); + expect(config?.plugins?.eyeseetea?.rules).toHaveProperty( + "require-future-block-capture" + ); + expect(config!.plugins).not.toHaveProperty("company"); + expect(config!.plugins).not.toHaveProperty("local"); + if (filename.startsWith("src/")) { + expect(config?.rules?.["eyeseetea/architecture"]).toEqual( + expect.arrayContaining([1]) + ); + expect(config?.rules?.["eyeseetea/no-collection-mutation"]).toEqual( + expect.arrayContaining([1]) + ); + } else { + expect(config!.rules!["eyeseetea/architecture"]).toBeUndefined(); + expect(config!.rules!["eyeseetea/no-collection-mutation"]).toBeUndefined(); + } + } + }); + test("styling is a warning and dangerous evaluation is an error", async () => { + const messages = await policyMessages( + "import { makeStyles } from '@material-ui/core'; eval('code');", + "src/webapp/components/share/Share.tsx" + ); + expect(messages).toEqual( + expect.arrayContaining([ + expect.objectContaining({ ruleId: "no-restricted-imports", severity: 1 }), + expect.objectContaining({ ruleId: "no-eval", severity: 2 }), + ]) + ); + }); + test("Promise and toPromise are reported in production domain", async () => { + const messages = await policyMessages( + "export function probe(): Promise { return Promise.resolve(1); } value.toPromise();", + "src/domain/usecases/GetUsersUseCase.ts" + ); + expect(messages).toEqual( + expect.arrayContaining([ + expect.objectContaining({ ruleId: "no-restricted-globals" }), + expect.objectContaining({ ruleId: "no-restricted-syntax" }), + ]) + ); + }); + test("test files can bridge Futures to Promises", async () => { + const messages = await policyMessages( + "const result: Promise = Promise.resolve(1); value.toPromise();", + "src/domain/usecases/__tests__/GetCurrentUserUseCase.spec.ts" + ); + expect( + messages.filter(message => + ["no-restricted-globals", "no-restricted-syntax"].includes(message.ruleId ?? "") + ) + ).toEqual([]); + }); + test("async callbacks inside Future.block are permitted", async () => { + const messages = await policyMessages( + "Future.block(async capture => await capture(value));", + "src/domain/usecases/GetUsersUseCase.ts" + ); + expect( + messages.filter(message => + [ + "no-restricted-globals", + "no-restricted-syntax", + "eyeseetea/require-future-block-capture", + ].includes(message.ruleId ?? "") + ) + ).toEqual([]); + }); + test("accessible E2E queries pass while CSS and test IDs warn", async () => { + const config = await new ESLint().calculateConfigForFile( + "src/tests/playwright/probe.e2e.ts" + ); + const result = new Linter().verify( + "page.getByRole('button'); page.locator('.button'); page.getByTestId('submit'); page.$('.button'); page.$$('.button');", + [ + { + languageOptions: { parser }, + rules: { "no-restricted-syntax": config!.rules!["no-restricted-syntax"] }, + }, + ] + ); + expect(result).toHaveLength(4); + expect(result.every(message => message.severity === 1)).toBe(true); + }); +}); diff --git a/eslint/eyeseetea-config.ts b/eslint/eyeseetea-config.ts new file mode 100644 index 0000000..ebea1d6 --- /dev/null +++ b/eslint/eyeseetea-config.ts @@ -0,0 +1,157 @@ +import type { TSESLint } from "@typescript-eslint/utils"; +// Keep this policy separate from the project's framework and parser setup. +import eyeseeteaPlugin from "./eyeseetea-plugin.ts"; +import testingLibrary from "eslint-plugin-testing-library"; + +const tests = [ + "**/*.{spec,test}.{ts,tsx}", + "**/__tests__/**", + "src/tests/**", + "src/tests/playwright/**", +]; +const syntax = [ + { + selector: + "TSAsExpression[typeAnnotation.type='TSUnknownKeyword'], TSTypeAssertion[typeAnnotation.type='TSUnknownKeyword']", + message: "Do not use as unknown to bypass a type contract; validate or narrow the value.", + }, + { + selector: + "TSAsExpression[typeAnnotation.type='TSArrayType'], TSTypeAssertion[typeAnnotation.type='TSArrayType']", + message: "Do not cast to Type[]; use a typed binding, satisfies, or a type guard.", + }, + { + selector: + "CallExpression[callee.type='MemberExpression'][callee.property.name='toPromise']", + message: + "Execute Futures with run(); toPromise() belongs in tests or an explicitly justified adapter.", + }, +]; + +export default [ + { + plugins: { eyeseetea: eyeseeteaPlugin }, + rules: { "eyeseetea/require-future-block-capture": "error" }, + }, + { + files: ["src/**/*.{ts,tsx}"], + rules: { + "eyeseetea/architecture": "warn", + "eyeseetea/no-collection-mutation": "warn", + "prefer-const": "warn", + "no-var": "warn", + "no-param-reassign": ["warn", { props: true }], + "array-callback-return": "error", + "no-eval": "error", + "no-implied-eval": "error", + "no-new-func": "error", + "no-restricted-syntax": ["warn", ...syntax], + "no-restricted-imports": [ + "warn", + { + paths: [ + { + name: "@material-ui/core", + importNames: ["makeStyles"], + message: "Use styled-components for new components.", + }, + { + name: "@material-ui/styles", + importNames: ["makeStyles"], + message: "Use styled-components for new components.", + }, + { + name: "@mui/styles", + importNames: ["makeStyles"], + message: "Use styled-components for new components.", + }, + { + name: "@material-ui/core/styles", + importNames: ["makeStyles"], + message: "Use styled-components for new components.", + }, + { + name: "@material-ui/core/styles/makeStyles", + message: "Use styled-components for new components.", + }, + { + name: "@material-ui/styles/makeStyles", + message: "Use styled-components for new components.", + }, + ], + }, + ], + "@typescript-eslint/no-explicit-any": "warn", + "@typescript-eslint/no-unsafe-assignment": "warn", + "@typescript-eslint/no-unsafe-argument": "warn", + "@typescript-eslint/no-unsafe-call": "warn", + "@typescript-eslint/no-unsafe-member-access": "warn", + "@typescript-eslint/no-unsafe-return": "warn", + "@typescript-eslint/no-unsafe-type-assertion": "warn", + "@typescript-eslint/no-floating-promises": "warn", + "unused-imports/no-unused-imports": "warn", + "react-hooks/rules-of-hooks": "error", + }, + }, + { + files: ["src/{domain,data}/**/*.{ts,tsx}"], + ignores: [ + ...tests, + "src/domain/entities/generic/Future.ts", + "src/domain/entities/generic/FutureWithAccumulation.ts", + ], + rules: { + "no-restricted-globals": [ + "warn", + { + name: "Promise", + message: + "Use FutureData in domain and data; isolate Promise interop in a documented adapter.", + }, + ], + // Async Future.block callbacks remain valid; do not ban async/await. + "no-restricted-syntax": [ + "warn", + ...syntax, + { + selector: "TSTypeReference[typeName.name='Promise']", + message: "Return FutureData instead of Promise in domain and data.", + }, + ], + }, + }, + { + files: tests, + plugins: { "testing-library": testingLibrary }, + rules: { + "no-restricted-syntax": [ + "warn", + ...syntax.slice(0, 2), + { + selector: + "CallExpression[callee.type='MemberExpression'][callee.property.name=/^(toBeTruthy|toBeDefined)$/]", + message: + "Prefer toBe/toEqual when the exact value is knowable; existence checks may be justified.", + }, + ], + "testing-library/prefer-user-event": "warn", + "testing-library/prefer-presence-queries": "warn", + "testing-library/prefer-explicit-assert": "warn", + }, + }, + { + files: ["src/tests/playwright/**/*.{ts,tsx}", "**/*.e2e.{ts,tsx}"], + rules: { + "no-restricted-syntax": [ + "warn", + ...syntax.slice(0, 2), + { + selector: + "CallExpression[callee.type='MemberExpression'][callee.property.name=/^(locator|getByTestId)$/], CallExpression[callee.type='MemberExpression'][callee.property.name='$'], CallExpression[callee.type='MemberExpression'][callee.property.name='$$']", + message: + "Prefer accessible Playwright queries: getByRole, getByLabel, or getByText.", + }, + ], + }, + }, +] satisfies TSESLint.FlatConfig.Config[]; diff --git a/eslint/eyeseetea-plugin.ts b/eslint/eyeseetea-plugin.ts new file mode 100644 index 0000000..a6f06ee --- /dev/null +++ b/eslint/eyeseetea-plugin.ts @@ -0,0 +1,12 @@ +import type { TSESLint } from "@typescript-eslint/utils"; +import architecture from "./rules/architecture/rule.ts"; +import noCollectionMutation from "./rules/no-collection-mutation/rule.ts"; +import requireFutureBlockCapture from "./rules/require-future-block-capture/rule.ts"; + +export default { + rules: { + architecture, + "no-collection-mutation": noCollectionMutation, + "require-future-block-capture": requireFutureBlockCapture, + }, +} satisfies TSESLint.FlatConfig.Plugin; diff --git a/eslint/rules/architecture/README.md b/eslint/rules/architecture/README.md new file mode 100644 index 0000000..06711a9 --- /dev/null +++ b/eslint/rules/architecture/README.md @@ -0,0 +1,51 @@ +# eyeseetea/architecture + +Enforce Clean Architecture dependency directions and DHIS2 client boundaries. +Enabled as a warning for `src/**/*.{ts,tsx}` by the EyeSeeTea config. + +## Rule Details + +Reports domain imports from data, presentation, the composition root, DHIS2 clients, +or platform infrastructure, and domain access to platform globals. Data must not +import presentation or the composition root. Presentation must not import concrete +data implementations. Repositories and presentation must not access HTTP directly. + +DHIS2 client imports belong in repositories, the composition root, or the named +infrastructure adapters (`src/types/d2-api.ts` and `src/data/api-futures.ts`). +Instantiate the imported `D2Api` only inside `getWebappCompositionRoot()` in +`src/CompositionRoot.ts`. + +Examples of **incorrect** code: + +```ts +// src/domain/usecases/GetUsersUseCase.ts +import { UserD2Repository } from "$/data/repositories/UserD2Repository"; + +// src/data/repositories/UserD2Repository.ts +fetch("/api/users"); +``` + +Examples of **correct** code: + +```ts +// src/domain/usecases/GetUsersUseCase.ts +import type { User } from "$/domain/entities/User"; + +// src/data/repositories/UserD2Repository.ts +import { D2Api } from "$/types/d2-api"; +``` + +## Options + +This rule has no options. + +## Limitations + +Checks direct imports, re-exports, literal dynamic imports, and literal `require` +calls. TypeScript resolution honors the project configuration. Transitive dependencies, +nonliteral imports, namespace constructors, and indirect factories require review. + +## When Not To Use It + +Disable this rule in projects with a different architecture or directory structure. +For a justified exception, use a narrow suppression with an explanation. diff --git a/eslint/rules/architecture/rule.spec.ts b/eslint/rules/architecture/rule.spec.ts new file mode 100644 index 0000000..3c53850 --- /dev/null +++ b/eslint/rules/architecture/rule.spec.ts @@ -0,0 +1,85 @@ +import path from "node:path"; +import { TSESLint } from "@typescript-eslint/utils"; +const { Linter } = TSESLint; +import { parser } from "typescript-eslint"; +import { describe, expect, test } from "vitest"; +import architecture from "./rule"; + +function lintArchitecture(code: string, filename = "src/domain/entities/PolicyProbe.ts") { + return new Linter().verify( + code, + [ + { + files: ["**/*.ts"], + languageOptions: { parser }, + plugins: { eyeseetea: { rules: { architecture } } }, + rules: { "eyeseetea/architecture": "warn" }, + }, + ], + { filename: path.resolve(filename) } + ); +} + +describe("EyeSeeTea architecture", () => { + test.each([ + "import { UserD2Repository } from '$/data/repositories/UserD2Repository';", + "export { UserD2Repository } from '../../data/repositories/UserD2Repository';", + "const repository = import('$/data/repositories/UserD2Repository');", + "const repository = require('$/data/repositories/UserD2Repository');", + "import type { D2Api } from '$/types/d2-api';", + "import React from 'react';", + 'window.location; document.title; fetch("/api");', + ])("reports infrastructure in domain: %s", code => { + expect(lintArchitecture(code).length).toBeGreaterThan(0); + }); + test("allows domain dependencies and shadowed platform names", () => { + expect( + lintArchitecture( + "import type { User } from './User'; function f(fetch: () => void) { fetch(); }" + ) + ).toEqual([]); + }); + test("reports data depending on UI", () => { + expect( + lintArchitecture( + "import { App } from '$/webapp/pages/app/App';", + "src/data/PolicyProbe.ts" + ) + ).toHaveLength(1); + }); + test("reports presentation depending on concrete repositories", () => { + expect( + lintArchitecture( + "import { UserD2Repository } from '$/data/repositories/UserD2Repository';", + "src/webapp/PolicyProbe.ts" + ) + ).toHaveLength(1); + }); + test("allows repository API imports, but rejects direct HTTP", () => { + expect( + lintArchitecture( + "import { D2Api } from '$/types/d2-api';", + "src/data/repositories/PolicyProbe.ts" + ) + ).toEqual([]); + expect( + lintArchitecture( + "import axios from 'axios'; fetch('/api');", + "src/data/repositories/PolicyProbe.ts" + ) + ).toHaveLength(2); + }); + test("checks aliased D2Api construction", () => { + const code = "import { D2Api as Client } from '$/types/d2-api'; new Client();"; + expect(lintArchitecture(code, "src/CompositionRoot.ts")).toHaveLength(1); + expect( + lintArchitecture( + "import { D2Api as Client } from '$/types/d2-api'; function getWebappCompositionRoot() { return new Client(); }", + "src/CompositionRoot.ts" + ) + ).toEqual([]); + }); + test("does not confuse a local class with the imported client", () => { + expect(lintArchitecture("class D2Api {} new D2Api();")).toEqual([]); + }); +}); diff --git a/eslint/rules/architecture/rule.ts b/eslint/rules/architecture/rule.ts new file mode 100644 index 0000000..e826e8c --- /dev/null +++ b/eslint/rules/architecture/rule.ts @@ -0,0 +1,184 @@ +import path from "node:path"; +import ts from "typescript"; +import { ESLintUtils, type TSESTree, type TSESLint } from "@typescript-eslint/utils"; + +const platformGlobals = new Set([ + "window", + "document", + "File", + "FileReader", + "Blob", + "HTMLElement", + "localStorage", + "sessionStorage", + "navigator", + "fetch", + "XMLHttpRequest", +]); +const httpPackages = /^(axios|node-fetch|cross-fetch|undici|got|ky)(\/|$)/; +const infrastructurePackages = + /^(react|react-dom|@material-ui\/|@mui\/|@dhis2\/|@eyeseetea\/d2-api|axios|node-fetch|node:|fs$|fs\/|path$|http$|https$)/; +const normalize = (value: string) => value.replaceAll("\\", "/"); + +export default ESLintUtils.RuleCreator( + name => + `https://github.com/EyeSeeTea/dhis2-app-skeleton/blob/master/eslint/rules/${name}/README.md` +)({ + name: "architecture", + defaultOptions: [], + meta: { + type: "problem", + docs: { + description: + "Check Clean Architecture dependency directions and DHIS2 client boundaries.", + }, + schema: [], + messages: { + boundary: "{{message}}", + }, + }, + create(context) { + const filename = normalize(context.filename); + const domain = filename.includes("/src/domain/"); + const data = filename.includes("/src/data/"); + const repository = filename.includes("/src/data/repositories/"); + const presentation = /\/src\/(webapp|scripts)\//.test(filename); + const root = filename.endsWith("/src/CompositionRoot.ts"); + const apiAdapter = + filename.endsWith("/src/types/d2-api.ts") || + filename.endsWith("/src/data/api-futures.ts"); + const sourceCode = context.sourceCode; + const program = sourceCode.parserServices?.program; + const options = program?.getCompilerOptions() ?? { + baseUrl: path.join(context.cwd, "src"), + paths: { "$/*": ["./*"] }, + }; + const report = (node: TSESTree.Node, message: string) => + context.report({ node, messageId: "boundary", data: { message } }); + function checkImport(node: TSESTree.Node, source: unknown) { + if (typeof source !== "string") return; + const resolved = ts.resolveModuleName( + source, + context.filename, + options, + ts.sys + ).resolvedModule; + const target = normalize(resolved?.resolvedFileName ?? source); + if ( + domain && + (/\/src\/(data|webapp|scripts)\//.test(target) || + target.endsWith("/src/CompositionRoot.ts") || + target.endsWith("/src/types/d2-api.ts") || + infrastructurePackages.test(source)) + ) { + report( + node, + "Domain must not depend on data, presentation, DHIS2 clients, or platform infrastructure." + ); + } else if ( + data && + (/\/src\/(webapp|scripts)\//.test(target) || + target.endsWith("/src/CompositionRoot.ts")) + ) { + report(node, "Data must not depend on presentation or the composition root."); + } + if ((repository || presentation) && httpPackages.test(source)) + report( + node, + "Repositories access HTTP through d2-api, not a separate HTTP client." + ); + if (presentation && target.includes("/src/data/")) + report( + node, + "Presentation accesses repositories through composition-root use cases." + ); + if ( + !domain && + !repository && + !root && + !apiAdapter && + (/^@eyeseetea\/d2-api(\/|$)/.test(source) || + target.endsWith("/src/types/d2-api.ts")) + ) { + report( + node, + "Keep the DHIS2 client in repositories, the composition root, or a documented infrastructure adapter." + ); + } + } + return { + ImportDeclaration(node) { + checkImport(node, node.source.value); + }, + ExportNamedDeclaration(node) { + if (node.source) checkImport(node, node.source.value); + }, + ExportAllDeclaration(node) { + checkImport(node, node.source.value); + }, + ImportExpression(node) { + if (node.source.type === "Literal") checkImport(node, node.source.value); + }, + CallExpression(node) { + if ( + node.callee.type === "Identifier" && + node.callee.name === "require" && + node.arguments[0]?.type === "Literal" + ) + checkImport(node, node.arguments[0].value); + }, + NewExpression(node) { + if (node.callee.type !== "Identifier") return; + let scope: TSESLint.Scope.Scope | null = sourceCode.getScope(node); + let variable; + while (scope && !variable) { + variable = scope.set.get(node.callee.name); + scope = scope.upper; + } + const importedApi = variable?.defs.some( + def => + def.type === "ImportBinding" && + def.node.type === "ImportSpecifier" && + def.node.imported.type === "Identifier" && + def.node.imported.name === "D2Api" + ); + if (!importedApi) return; + const inFactory = sourceCode + .getAncestors(node) + .some( + ancestor => + ancestor.type === "FunctionDeclaration" && + ancestor.id?.name === "getWebappCompositionRoot" + ); + if (!root || !inFactory) + report( + node, + "Instantiate D2Api only inside getWebappCompositionRoot() in CompositionRoot.ts." + ); + }, + "Program:exit"() { + for (const scope of sourceCode.scopeManager?.scopes ?? []) { + for (const reference of scope.references) { + if (reference.resolved?.defs.length) continue; + const name = reference.identifier.name; + if (domain && platformGlobals.has(name)) + report( + reference.identifier, + "Domain must not access runtime platform APIs." + ); + else if (repository && ["fetch", "XMLHttpRequest"].includes(name)) + report( + reference.identifier, + "Repositories access HTTP through d2-api." + ); + else if (presentation && ["fetch", "XMLHttpRequest"].includes(name)) + report( + reference.identifier, + "Move data access to a repository and call a composition-root use case." + ); + } + } + }, + }; + }, +}); diff --git a/eslint/rules/no-collection-mutation/README.md b/eslint/rules/no-collection-mutation/README.md new file mode 100644 index 0000000..3af4095 --- /dev/null +++ b/eslint/rules/no-collection-mutation/README.md @@ -0,0 +1,46 @@ +# eyeseetea/no-collection-mutation + +Prefer new collections over in-place mutations. Enabled as a warning for +`src/**/*.{ts,tsx}` by the EyeSeeTea config. Requires TypeScript type information. + +## Rule Details + +Reports mutating methods on typed arrays and tuples: `push`, `pop`, `shift`, +`unshift`, `splice`, `sort`, `reverse`, `fill`, and `copyWithin`. +Also reports standard-library Map `set`, `delete`, and `clear`, and Set `add`, +`delete`, and `clear`. Literal computed method access is checked too. + +Examples of **incorrect** code: + +```ts +const values = [1, 2]; +values.push(3); +values["sort"](); +const lookup = new Map(); +lookup.set("a", 1); +``` + +Examples of **correct** code: + +```ts +const values = [1, 2]; +const extended = [...values, 3]; +const sorted = [...values].toSorted(); +const lookup = new Map([["a", 1]]); +``` + +## Options + +This rule has no options. + +## Limitations + +Does not analyze aliasing, shared state, arbitrary property assignments, or +nonliteral computed method names. Unrelated application methods named `push`, +`set`, or `add` are allowed. There is no automatic fix because mutation and its +return value may be intentional. + +## When Not To Use It + +Disable this rule where a library contract or performance requirement calls for +mutation. Prefer a narrow suppression explaining the constraint. diff --git a/eslint/rules/no-collection-mutation/rule.spec.ts b/eslint/rules/no-collection-mutation/rule.spec.ts new file mode 100644 index 0000000..3779192 --- /dev/null +++ b/eslint/rules/no-collection-mutation/rule.spec.ts @@ -0,0 +1,51 @@ +import { TSESLint } from "@typescript-eslint/utils"; +const { ESLint } = TSESLint; +import { parser } from "typescript-eslint"; +import { beforeAll, describe, expect, test } from "vitest"; + +const eslint = new ESLint({ + overrideConfig: [ + { + files: ["policy-probe.ts"], + languageOptions: { + parser, + parserOptions: { + project: null, + projectService: { allowDefaultProject: ["policy-probe.ts"] }, + }, + }, + rules: { + "eyeseetea/no-collection-mutation": "warn", + "@typescript-eslint/no-unsafe-type-assertion": "warn", + }, + }, + ], +}); + +async function lintMutation(code: string) { + const [result] = await eslint.lintText(code, { filePath: "policy-probe.ts" }); + return result!.messages.filter( + message => message.ruleId === "eyeseetea/no-collection-mutation" || message.fatal + ); +} + +beforeAll(async () => { + await lintMutation("export {};"); +}, 20000); + +describe("collection mutation", () => { + test("detects typed array, Map, and Set mutation including computed access", async () => { + expect( + await lintMutation( + "const xs = [1]; xs.push(2); xs['sort'](); const map = new Map(); map.set('a', 1); const set = new Set(); set.add(1);" + ) + ).toHaveLength(4); + }); + test("allows immutable transformations and unrelated method names", async () => { + expect( + await lintMutation( + "const xs = [1]; const ys = xs.map(x => x + 1); const queue = { push(value: number) { return value; } }; queue.push(2);" + ) + ).toEqual([]); + }); +}); diff --git a/eslint/rules/no-collection-mutation/rule.ts b/eslint/rules/no-collection-mutation/rule.ts new file mode 100644 index 0000000..ea7ce06 --- /dev/null +++ b/eslint/rules/no-collection-mutation/rule.ts @@ -0,0 +1,64 @@ +import { ESLintUtils } from "@typescript-eslint/utils"; + +const arrayMutators = new Set([ + "push", + "pop", + "shift", + "unshift", + "splice", + "sort", + "reverse", + "fill", + "copyWithin", +]); +export default ESLintUtils.RuleCreator( + name => + `https://github.com/EyeSeeTea/dhis2-app-skeleton/blob/master/eslint/rules/${name}/README.md` +)({ + name: "no-collection-mutation", + defaultOptions: [], + meta: { + type: "suggestion", + docs: { description: "Prefer new collections over in-place mutations." }, + schema: [], + messages: { mutation: "Return a new collection instead of mutating it with {{method}}()." }, + }, + create(context) { + const services = ESLintUtils.getParserServices(context); + const checker = services.program.getTypeChecker(); + return { + CallExpression(node) { + if (node.callee.type !== "MemberExpression") return; + const member = node.callee; + const method = member.computed + ? member.property.type === "Literal" + ? member.property.value + : null + : member.property.type === "Identifier" + ? member.property.name + : null; + if (typeof method !== "string") return; + const type = services.getTypeAtLocation(member.object); + const types = type.isUnion() ? type.types : [type]; + const mutates = types.some(type => { + if (checker.isArrayType(type) || checker.isTupleType(type)) + return arrayMutators.has(method); + const symbol = type.getSymbol(); + // Only standard-library Map/Set, not similarly named application classes. + const builtin = symbol?.declarations?.some(declaration => + /[\\/]typescript[\\/]lib[\\/]lib\..*\.d\.ts$/.test( + declaration.getSourceFile().fileName + ) + ); + return ( + builtin && + symbol && + ((symbol.name === "Map" && ["set", "delete", "clear"].includes(method)) || + (symbol.name === "Set" && ["add", "delete", "clear"].includes(method))) + ); + }); + if (mutates) context.report({ node, messageId: "mutation", data: { method } }); + }, + }; + }, +}); diff --git a/eslint/rules/require-future-block-capture.md b/eslint/rules/require-future-block-capture.md deleted file mode 100644 index 6cf6897..0000000 --- a/eslint/rules/require-future-block-capture.md +++ /dev/null @@ -1,21 +0,0 @@ -# require-future-block-capture - -Inside a `Future.block` callback, await a `Future` through the callback's capture function. This lets the block track the operation's cancellation and failure. - -Incorrect: - -```ts -Future.block(async $ => { - const user = await loadUser(); - return user; -}); -``` - -Correct, when `loadUserFuture()` returns a `Future`: - -```ts -Future.block(async $ => { - const user = await $(loadUserFuture()); - return user; -}); -``` diff --git a/eslint/rules/require-future-block-capture/README.md b/eslint/rules/require-future-block-capture/README.md new file mode 100644 index 0000000..a2de1fa --- /dev/null +++ b/eslint/rules/require-future-block-capture/README.md @@ -0,0 +1,41 @@ +# eyeseetea/require-future-block-capture + +Inside a `Future.block` callback, await a `Future` through the callback's capture function. This lets the block track the operation's cancellation and failure. + +## Rule Details + +Checks direct awaits in callbacks passed to `Future.block` and `Future.block_`. +Awaits in nested functions are outside the callback and are not checked. + +Examples of **incorrect** code: + +```ts +Future.block(async $ => { + const user = await loadUser(); + return user; +}); +``` + +Examples of **correct** code, when `loadUserFuture()` returns a `Future`: + +```ts +Future.block(async $ => { + const user = await $(loadUserFuture()); + return user; +}); +``` + +## Options + +This rule has no options. The EyeSeeTea config enables it as an error. + +## Limitations + +Recognizes calls on the identifier `Future`; aliases are not checked. It checks +capture syntax rather than the awaited value's type. Native Promises must be +adapted to Futures before capture. No automatic fix is provided. + +## When Not To Use It + +Disable this rule if the project does not use this Future abstraction. For a +justified interoperability exception, use a narrow suppression with an explanation. diff --git a/eslint/rules/require-future-block-capture.spec.ts b/eslint/rules/require-future-block-capture/rule.spec.ts similarity index 94% rename from eslint/rules/require-future-block-capture.spec.ts rename to eslint/rules/require-future-block-capture/rule.spec.ts index ae645eb..bba299a 100644 --- a/eslint/rules/require-future-block-capture.spec.ts +++ b/eslint/rules/require-future-block-capture/rule.spec.ts @@ -1,18 +1,18 @@ import { TSESLint } from "@typescript-eslint/utils"; import { describe, expect, test } from "vitest"; -import requireFutureBlockCapture from "./require-future-block-capture"; +import requireFutureBlockCapture from "./rule"; function lint(source: string) { const linter = new TSESLint.Linter({ configType: "flat" }); const config = { languageOptions: { ecmaVersion: 2022, sourceType: "module" }, plugins: { - local: { + eyeseetea: { rules: { "require-future-block-capture": requireFutureBlockCapture }, }, }, - rules: { "local/require-future-block-capture": "error" }, + rules: { "eyeseetea/require-future-block-capture": "error" }, } satisfies TSESLint.FlatConfig.Config; return linter.verifyAndFix(source, config, {}); diff --git a/eslint/rules/require-future-block-capture.ts b/eslint/rules/require-future-block-capture/rule.ts similarity index 96% rename from eslint/rules/require-future-block-capture.ts rename to eslint/rules/require-future-block-capture/rule.ts index 94cfa5d..7226e74 100644 --- a/eslint/rules/require-future-block-capture.ts +++ b/eslint/rules/require-future-block-capture/rule.ts @@ -48,7 +48,8 @@ function isFutureBlockCallback(functionNode: FunctionNode): boolean { } const createRule = ESLintUtils.RuleCreator( - name => `https://github.com/EyeSeeTea/dhis2-app-skeleton/blob/master/eslint/rules/${name}.md` + name => + `https://github.com/EyeSeeTea/dhis2-app-skeleton/blob/master/eslint/rules/${name}/README.md` ); export default createRule({ diff --git a/package.json b/package.json index b1f9fa3..5c64699 100644 --- a/package.json +++ b/package.json @@ -101,8 +101,8 @@ "manifest": "d2-manifest package.json build/manifest.webapp", "postinstall": "yarn localize || echo '⚠ localize failed — run `yarn localize` before building'", "prepare": "corepack enable 2>/dev/null || true && husky install", - "prettify": "prettier \"./**/*.{js,jsx,json,css,ts,tsx}\" --write", - "prettify:check": "prettier \"./**/*.{js,jsx,json,css,ts,tsx}\" --check", + "prettify": "prettier \"./**/*.{js,mjs,jsx,json,css,ts,tsx}\" --write", + "prettify:check": "prettier \"./**/*.{js,mjs,jsx,json,css,ts,tsx}\" --check", "run-script": "tsx", "source-map-explorer": "yarn build --sourcemap=true && source-map-explorer --no-border-checks --only-mapped build/assets/*js", "start": "vite --strictPort", diff --git a/tsconfig.json b/tsconfig.json index 46fad69..1e44741 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,6 +4,7 @@ "useDefineForClassFields": true, "lib": ["DOM", "DOM.Iterable", "ESNext"], "allowJs": false, + "allowImportingTsExtensions": true, "skipLibCheck": true, "esModuleInterop": false, "allowSyntheticDefaultImports": true, diff --git a/vite.config.ts b/vite.config.ts index e61be0f..cd627ec 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -31,7 +31,7 @@ export default ({ mode }): UserConfig => { ], test: { environment: "jsdom", - include: ["**/*.spec.{ts,tsx}"], + include: ["**/*.spec.{ts,tsx,mjs}"], setupFiles: "./src/tests/setup.ts", exclude: ["**/node_modules/**", "**/src/tests/playwright/**"], globals: true, From 1229cf006f93d0d717e00fae688f69627e7e6bc3 Mon Sep 17 00:00:00 2001 From: Matias Arriola Date: Wed, 7 Oct 2026 12:59:32 -0300 Subject: [PATCH 02/14] refactor(eslint): split framework configuration into modules --- eslint.config.mjs | 130 ++------------------------------------ eslint/README.md | 9 ++- eslint/base-config.mjs | 91 ++++++++++++++++++++++++++ eslint/react-config.mjs | 23 +++++++ eslint/testing-config.mjs | 16 +++++ 5 files changed, 142 insertions(+), 127 deletions(-) create mode 100644 eslint/base-config.mjs create mode 100644 eslint/react-config.mjs create mode 100644 eslint/testing-config.mjs diff --git a/eslint.config.mjs b/eslint.config.mjs index 63d4463..e867ef4 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -1,128 +1,8 @@ -import js from "@eslint/js"; import tseslint from "typescript-eslint"; -import react from "eslint-plugin-react"; -import reactHooks from "eslint-plugin-react-hooks"; -import testingLibrary from "eslint-plugin-testing-library"; -import noRelativeImportPaths from "eslint-plugin-no-relative-import-paths"; -import unusedImports from "eslint-plugin-unused-imports"; - +import baseConfig from "./eslint/base-config.mjs"; +import reactConfig from "./eslint/react-config.mjs"; +import testingConfig from "./eslint/testing-config.mjs"; import eyeseeteaConfig from "./eslint/eyeseetea-config.ts"; -// Framework defaults plus the EyeSeeTea policy in eslint/eyeseetea-config.ts. -export default tseslint.config( - { - ignores: [ - "dist/**", - "build/**", - "node_modules/**", - "coverage/**", - "eslint.config.*", - "src/locales/**", - "src/**/snapshots/*.ts", - "**/*.d.ts", - ], - }, - - js.configs.recommended, - ...tseslint.configs.recommended, - react.configs.flat.recommended, - react.configs.flat["jsx-runtime"], - reactHooks.configs.flat.recommended, - - { - languageOptions: { - parserOptions: { - ecmaVersion: "latest", - project: "./tsconfig.json", - sourceType: "module", - }, - }, - settings: { - react: { version: "detect" }, - }, - plugins: { - "react-hooks": reactHooks, - "no-relative-import-paths": noRelativeImportPaths, - "unused-imports": unusedImports, - }, - rules: { - // TypeScript already resolves identifiers; core no-undef duplicates it - // and does not know about DOM or Node globals here. - "no-undef": "off", - - "no-console": ["warn", { allow: ["debug", "warn", "error", "info"] }], - "prefer-const": "warn", - "no-debugger": "warn", - "no-unused-expressions": "off", - "no-useless-concat": "off", - "no-useless-constructor": "off", - "no-unexpected-multiline": "off", - "no-use-before-define": "off", - "no-extra-semi": "off", - "no-mixed-spaces-and-tabs": "off", - "no-useless-rename": "off", - "default-case": "off", - "array-callback-return": "off", - - "@typescript-eslint/explicit-function-return-type": "off", - "@typescript-eslint/no-this-alias": "off", - "@typescript-eslint/no-unnecessary-type-constraint": "off", - "@typescript-eslint/no-unused-vars": [ - "warn", - { - argsIgnorePattern: "^_", - varsIgnorePattern: "^_", - caughtErrorsIgnorePattern: "^_", - }, - ], - "@typescript-eslint/no-unused-expressions": "warn", - "@typescript-eslint/no-use-before-define": "off", - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/no-empty-interface": "off", - "@typescript-eslint/no-empty-function": "off", - "@typescript-eslint/explicit-module-boundary-types": "off", - "@typescript-eslint/ban-ts-comment": "off", - "@typescript-eslint/no-var-requires": "off", - "@typescript-eslint/no-misused-promises": "warn", - // typescript-eslint v8 moved this from `recommended` to `strict`. - // Kept on so behaviour matches the previous config — the codebase - // already carries eslint-disable comments where it uses `!`. - "@typescript-eslint/no-non-null-assertion": "error", - - "react/prop-types": "off", - "react/display-name": "off", - "react/react-in-jsx-scope": "off", - - "react-hooks/rules-of-hooks": "warn", - "react-hooks/exhaustive-deps": "warn", - // TODO: Enable `react-hooks/set-state-in-effect`. - "react-hooks/set-state-in-effect": "off", - - "no-relative-import-paths/no-relative-import-paths": [ - "error", - { allowSameFolder: true, rootDir: "src", prefix: "$" }, - ], - }, - }, - - { - files: ["**/*.spec.{ts,tsx}"], - ...testingLibrary.configs["flat/react"], - rules: { - ...testingLibrary.configs["flat/react"].rules, - "testing-library/await-async-queries": "error", - "testing-library/no-await-sync-queries": "error", - "testing-library/prefer-screen-queries": "off", - "testing-library/no-debugging-utils": "off", - "testing-library/no-dom-import": "off", - }, - }, - - ...eyeseeteaConfig, - - { - files: ["**/*.js"], - languageOptions: { parserOptions: { project: null } }, - rules: { "@typescript-eslint/no-misused-promises": "off" }, - } -); +// Company policy comes last so its severities override framework defaults. +export default tseslint.config(...baseConfig, ...reactConfig, ...testingConfig, ...eyeseeteaConfig); diff --git a/eslint/README.md b/eslint/README.md index b8244ab..7c26a0f 100644 --- a/eslint/README.md +++ b/eslint/README.md @@ -16,8 +16,13 @@ rule metadata links to that reference through `meta.docs.url`. Policy integration tests live in `eyeseetea-config.spec.ts`. `eyeseetea-config.ts` registers the plugin and defines policy severities and file -scopes, including conventions enforced through third-party rules. Framework defaults -and parser setup remain in the root `eslint.config.mjs`. +scopes, including conventions enforced through third-party rules. The root +`eslint.config.mjs` composes these configurations in order: + +- `base-config.mjs`: JavaScript/TypeScript presets, parser setup, ignores, and general overrides. +- `react-config.mjs`: React and Hooks presets and project overrides. +- `testing-config.mjs`: Testing Library preset and test overrides. +- `eyeseetea-config.ts`: company policy, applied last to override framework defaults. The Future capture rule applies across the root configuration's linted files at error severity; architecture and collection mutation apply to `src/**/*.{ts,tsx}` diff --git a/eslint/base-config.mjs b/eslint/base-config.mjs new file mode 100644 index 0000000..a9fed26 --- /dev/null +++ b/eslint/base-config.mjs @@ -0,0 +1,91 @@ +import js from "@eslint/js"; +import tseslint from "typescript-eslint"; +import noRelativeImportPaths from "eslint-plugin-no-relative-import-paths"; +import unusedImports from "eslint-plugin-unused-imports"; + +export default tseslint.config( + { + ignores: [ + "dist/**", + "build/**", + "node_modules/**", + "coverage/**", + "eslint.config.*", + "src/locales/**", + "src/**/snapshots/*.ts", + "**/*.d.ts", + ], + }, + + js.configs.recommended, + ...tseslint.configs.recommended, + + { + languageOptions: { + parserOptions: { + ecmaVersion: "latest", + project: "./tsconfig.json", + sourceType: "module", + }, + }, + plugins: { + "no-relative-import-paths": noRelativeImportPaths, + "unused-imports": unusedImports, + }, + rules: { + // TypeScript already resolves identifiers; core no-undef duplicates it + // and does not know about DOM or Node globals here. + "no-undef": "off", + + "no-console": ["warn", { allow: ["debug", "warn", "error", "info"] }], + "prefer-const": "warn", + "no-debugger": "warn", + "no-unused-expressions": "off", + "no-useless-concat": "off", + "no-useless-constructor": "off", + "no-unexpected-multiline": "off", + "no-use-before-define": "off", + "no-extra-semi": "off", + "no-mixed-spaces-and-tabs": "off", + "no-useless-rename": "off", + "default-case": "off", + "array-callback-return": "off", + + "@typescript-eslint/explicit-function-return-type": "off", + "@typescript-eslint/no-this-alias": "off", + "@typescript-eslint/no-unnecessary-type-constraint": "off", + "@typescript-eslint/no-unused-vars": [ + "warn", + { + argsIgnorePattern: "^_", + varsIgnorePattern: "^_", + caughtErrorsIgnorePattern: "^_", + }, + ], + "@typescript-eslint/no-unused-expressions": "warn", + "@typescript-eslint/no-use-before-define": "off", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-empty-interface": "off", + "@typescript-eslint/no-empty-function": "off", + "@typescript-eslint/explicit-module-boundary-types": "off", + "@typescript-eslint/ban-ts-comment": "off", + "@typescript-eslint/no-var-requires": "off", + "@typescript-eslint/no-misused-promises": "warn", + // typescript-eslint v8 moved this from `recommended` to `strict`. + // Kept on so behaviour matches the previous config — the codebase + // already carries eslint-disable comments where it uses `!`. + "@typescript-eslint/no-non-null-assertion": "error", + + "no-relative-import-paths/no-relative-import-paths": [ + "error", + { allowSameFolder: true, rootDir: "src", prefix: "$" }, + ], + }, + }, + + { + files: ["**/*.js"], + languageOptions: { parserOptions: { project: null } }, + rules: { "@typescript-eslint/no-misused-promises": "off" }, + } +); diff --git a/eslint/react-config.mjs b/eslint/react-config.mjs new file mode 100644 index 0000000..47183dd --- /dev/null +++ b/eslint/react-config.mjs @@ -0,0 +1,23 @@ +import react from "eslint-plugin-react"; +import reactHooks from "eslint-plugin-react-hooks"; + +export default [ + react.configs.flat.recommended, + react.configs.flat["jsx-runtime"], + reactHooks.configs.flat.recommended, + { + settings: { + react: { version: "detect" }, + }, + rules: { + "react/prop-types": "off", + "react/display-name": "off", + "react/react-in-jsx-scope": "off", + + "react-hooks/rules-of-hooks": "warn", + "react-hooks/exhaustive-deps": "warn", + // TODO: Enable `react-hooks/set-state-in-effect`. + "react-hooks/set-state-in-effect": "off", + }, + }, +]; diff --git a/eslint/testing-config.mjs b/eslint/testing-config.mjs new file mode 100644 index 0000000..ab5ff78 --- /dev/null +++ b/eslint/testing-config.mjs @@ -0,0 +1,16 @@ +import testingLibrary from "eslint-plugin-testing-library"; + +export default [ + { + files: ["**/*.spec.{ts,tsx}"], + ...testingLibrary.configs["flat/react"], + rules: { + ...testingLibrary.configs["flat/react"].rules, + "testing-library/await-async-queries": "error", + "testing-library/no-await-sync-queries": "error", + "testing-library/prefer-screen-queries": "off", + "testing-library/no-debugging-utils": "off", + "testing-library/no-dom-import": "off", + }, + }, +]; From b8c7daf3fa912f14ea2a9d6dbc31e7d66f854ccc Mon Sep 17 00:00:00 2001 From: Matias Arriola Date: Wed, 7 Oct 2026 13:08:42 -0300 Subject: [PATCH 03/14] docs(eslint): add downstream migration and hardening guide --- eslint/MIGRATION.md | 227 ++++++++++++++++++++++++++++++++++++++++++++ eslint/README.md | 2 + 2 files changed, 229 insertions(+) create mode 100644 eslint/MIGRATION.md diff --git a/eslint/MIGRATION.md b/eslint/MIGRATION.md new file mode 100644 index 0000000..9340f36 --- /dev/null +++ b/eslint/MIGRATION.md @@ -0,0 +1,227 @@ +# Adopting the EyeSeeTea ESLint configuration + +Use this guide when bringing the policy into an existing downstream project. +The [policy reference](README.md) describes coverage and limitations. Adoption, +cleanup, and stricter enforcement should be separate changes so reviewers can +identify which findings come from the policy and which come from application edits. + +## 1. Choose the adoption scope + +The configuration currently ships as source in this repository, not as a published +ESLint package. Copy files from a recorded commit and record that revision in the +downstream project's tooling documentation. Compare upstream changes against that +revision when updating; keep project overrides separate from copied policy files. + +| Approach | Files to copy | When to use it | +| -------------------------------------------- | ------------------------------------------------------------------------------- | ----------------------------------------------------------------- | +| Full skeleton configuration | Root `eslint.config.mjs` and the complete `eslint/` directory | A DHIS2 React project using the skeleton's layout and conventions | +| Company policy with existing framework setup | `eslint/eyeseetea-config.ts`, `eslint/eyeseetea-plugin.ts`, and `eslint/rules/` | A project already using compatible ESLint flat config | +| Selected custom rules | `eslint/eyeseetea-plugin.ts` and `eslint/rules/` | A project whose architecture or Promise conventions differ | + +Keep rule documentation with the implementation. If copying policy regression tests, +adapt their fixture paths and test runner setup: they currently use Vitest and actual +skeleton source paths. Do not expect them to run unchanged in another application. + +### Runtime and dependencies + +Use Node 24.13.1 or a compatible newer Node 24 release consistently in developer shells, +CI, and the editor's ESLint runtime. The `.mjs` config imports local `.ts` files +using native type stripping. Installing a TypeScript parser alone does not enable +TypeScript execution. Older runtimes require a separately configured loader or a +compiled JavaScript distribution. An optional `eslint/package.json` containing +`{"type":"module"}` makes the policy's module format explicit without changing the +application's module format. + +Install direct development dependencies using compatible versions from this +repository's `package.json`, and commit the downstream lockfile: + +- All approaches: `eslint`, `typescript`, and `@typescript-eslint/utils`. +- Full configuration or company policy: `typescript-eslint`, + `eslint-plugin-testing-library`, `eslint-plugin-unused-imports`, and + `eslint-plugin-react-hooks`; register the latter two plugins in the consuming config. +- Full configuration also needs `@eslint/js`, `eslint-plugin-react`, and + `eslint-plugin-no-relative-import-paths`. +- Selected rules with an existing TS parser need a compatible + `@typescript-eslint/parser` or `typescript-eslint` setup. + +The company policy is not standalone: it expects a TypeScript parser and registered +`@typescript-eslint`, `unused-imports`, and `react-hooks` plugins. The full composition +provides them. Align typescript-eslint packages to the same version family; do not +rely on dependencies being available only transitively. + +If these files later become a shared package, publish compiled JavaScript and type +declarations. Native Node type stripping does not load `.ts` dependencies inside +`node_modules`. A published package is a future distribution option, not a required +migration step today. + +### Incorporate the configuration + +For full adoption, use the root composition from this repository. For policy-only +adoption, add it after the existing framework configuration and before local overrides: + +```js +// eslint.config.mjs +import tseslint from "typescript-eslint"; +import existingConfig from "./eslint/existing-config.mjs"; +import eyeseeteaConfig from "./eslint/eyeseetea-config.ts"; +import projectOverrides from "./eslint/project-overrides.mjs"; + +export default tseslint.config(...existingConfig, ...eyeseeteaConfig, ...projectOverrides); +``` + +Here `existing-config.mjs` is the project's existing flat config exported as an +array, including the parser and plugins listed above. `project-overrides.mjs` is a +local array of explicit adjustments. These two files are created by the downstream +project; they are not supplied by this repository. + +For selected-rule adoption, register the plugin in the existing typed configuration: + +```js +import eyeseeteaPlugin from "./eslint/eyeseetea-plugin.ts"; + +// Append this entry to the existing config array. +const selectedRules = { + files: ["src/**/*.{ts,tsx}"], + plugins: { eyeseetea: eyeseeteaPlugin }, + rules: { + "eyeseetea/no-collection-mutation": "warn", + "eyeseetea/require-future-block-capture": "error", + }, +}; +``` + +Omit Future capture if the project does not use this Future abstraction. Collection +mutation requires parser type information even when its severity is only `warn`. + +## 2. Check the project assumptions + +Review these before the first lint run: + +| Assumption | Downstream adjustment | +| ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| ESLint 9 flat config | Migrate an existing `.eslintrc` separately and verify its old checks remain enabled. | +| Commands run from the project root | Set the parser's `tsconfigRootDir` explicitly if tools use another working directory. | +| Parser uses `./tsconfig.json` | Include every linted TS file, or point `parserOptions.project` at a dedicated `tsconfig.eslint.json`. Preserve application build settings. | +| Typechecking includes `eslint/**/*.ts` and allows `.ts` import extensions | Include copied rules in a no-emit typecheck; use `allowImportingTsExtensions: true`. | +| Source is under `src/`, with `$/*` imports | Adapt policy file globs, base import-path options, and TS aliases. | +| Layers are `src/domain`, `src/data`, `src/webapp`, and `src/scripts` | The architecture rule hardcodes these paths, API adapters, `CompositionRoot.ts`, and `getWebappCompositionRoot`. It has no options. Disable it for a different layout or change its implementation and regression tests. Merely changing `files` does not change its boundaries. | +| Domain/data use Futures | Review Promise restrictions and the two Future implementation exclusions. Projects using native Promises should adopt selected rules or maintain an explicitly adapted policy. | +| React, Material UI, and Testing Library conventions apply | Omit irrelevant framework modules and adapt company rules; the styling rule recommends styled-components but does not install it. | +| Unit tests use `*.spec.ts(x)` | The framework testing preset covers `.spec` files, while company test overrides also cover `.test`, `__tests__`, and `src/tests`. Align both scopes with the project. | +| E2E tests use `src/tests/playwright` or `*.e2e.ts(x)` | Adapt both E2E checks and general test exclusions for other locations. | +| Generated files use skeleton paths | Review global ignores and lint command targets. An ignored file receives no checks. | + +The custom rules currently have no options. Severity and file scopes can be changed +through flat config; internal architecture boundaries and detection behavior require +an implementation change. Monorepos need per-package parser projects and scoped +config entries rather than assuming one root `src/` and one `tsconfig.json`. + +## 3. Establish a baseline and adopt in CI + +1. Record the existing lint/typecheck/test results before changing configuration. +2. Run the new configuration without autofixing and save a report: + `yarn eslint src --format json --output-file eslint-migration-report.json`. + A report can be written even when errors cause a nonzero exit code. +3. Classify findings into defects, intentional exceptions, and legacy cleanup. Assign + cleanup owners and track temporary exceptions with an issue and a review date. +4. Resolve configuration failures first: missing plugins, files outside the TS project, + incompatible runtimes, and incorrect file scopes are not application violations. +5. Fix error-level violations before making the new lint job required. The default + policy already makes Future capture, dangerous evaluation, callback returns, and + Hooks correctness errors. It does not introduce every rule as a warning. +6. Keep warnings visible in required CI with `yarn lint`, alongside typecheck and + tests. Avoid `--quiet` and a global `--max-warnings=0` while legacy warnings remain. + +A saved JSON report is an inventory, not an enforcement baseline. By default ESLint +cannot distinguish existing findings from newly introduced ones. During this stage, +review new warnings in PRs. If automated prevention is required, add a separately +reviewed baseline comparison or enforce selected rules in already cleaned scopes. +A total warning count alone can miss a new violation when an old one is removed. +Linting only changed files also reports old findings within those files and can miss +dependency changes elsewhere. + +## 4. Harden incrementally + +Promote one rule or one cleaned scope at a time. Start with checks whose findings +have been reviewed and resolved, then expand the strict scope as cleanup progresses. +Append downstream overrides after the EyeSeeTea policy: + +```js +// eslint/project-overrides.mjs +export default [ + { + files: ["src/domain/usecases/**/*.{ts,tsx}"], + rules: { + "eyeseetea/no-collection-mutation": "error", + "@typescript-eslint/no-floating-promises": "error", + "@typescript-eslint/no-explicit-any": "error", + }, + }, + { + linterOptions: { reportUnusedDisableDirectives: "error" }, + }, +]; +``` + +Severity-only overrides retain existing rule options. For example, +`"no-param-reassign": "error"` preserves the policy's `props: true` option. +Enable unused suppression errors after removing stale directives. Once the complete +lint target has zero accepted warnings, `yarn eslint src --max-warnings=0` can become +a required gate. Until then, enforce cleaned rules as errors without making unrelated +legacy warnings fail the build. + +Do not apply a blanket strict preset as part of adoption: additional rules need their +own review for applicability and false positives. Keep correctness checks enabled +while hardening type safety, architecture, and immutability independently. + +## 5. Tweak deliberately and keep exceptions narrow + +A project override should name the affected files, the exact rule, and the reason: + +```js +// Append to project-overrides.mjs. +const vendorAdapterException = { + files: ["src/data/adapters/VendorMutableBuffer.ts"], + rules: { + // Vendor API requires in-place buffer updates; review when the API changes. + "eyeseetea/no-collection-mutation": "off", + }, +}; +``` + +For a single statement, prefer a documented inline exception: + +```ts +// eslint-disable-next-line eyeseetea/no-collection-mutation -- Vendor API requires this mutable buffer. +buffer.push(value); +``` + +These examples must be appended to the exported config array to take effect. Avoid +broadly disabling rules for all data code or all tests to accommodate one adapter. +A block's `ignores` only excludes that block; a separate later block does not undo +an earlier rule by ignoring files. Use a scoped rule override to change its severity. + +When modifying options for `no-restricted-syntax` or `no-restricted-imports`, provide +the complete intended options: later arrays replace earlier options rather than +appending selectors or paths. In particular, replacing `no-restricted-syntax` to allow +`toPromise()` can also remove cast and test assertion checks. For substantial selector +changes, maintain an explicit policy adaptation with tests rather than relying on +array indexes in the upstream config. + +## 6. Verify adoption and upgrades + +Run lint, typecheck, and application tests, plus the copied/adapted rule regression +tests. Use `yarn eslint --print-config ` for an actual production file, +a unit test, an E2E test, and an adapter to confirm final severities, plugin registration, +and exclusions. Confirm developer shells, CI, and editor linting agree. + +On each upstream update, compare policy files and dependencies with the recorded +revision, review new checks and changed scopes, and repeat the baseline review before +raising severities. Keep dependency upgrades and policy hardening separately reviewable. +For rollback, revert the adoption/configuration commit and its dependency changes; +avoid disabling all lint checks to restore a passing build. + +References: [ESLint rule overrides](https://eslint.org/docs/latest/use/configure/rules), +[ESLint CLI](https://eslint.org/docs/latest/use/command-line-interface), +[typed parser configuration](https://typescript-eslint.io/packages/parser/), and +[Node TypeScript execution](https://nodejs.org/docs/latest-v24.x/api/typescript.html). diff --git a/eslint/README.md b/eslint/README.md index 7c26a0f..6db021e 100644 --- a/eslint/README.md +++ b/eslint/README.md @@ -2,6 +2,8 @@ `eyeseetea-config.ts` implements automated checks for EyeSeeTea's coding conventions. The coverage below describes the enforced checks and their limitations. +See the [downstream migration guide](MIGRATION.md) for adoption, gradual hardening, +and project-specific overrides. ## Organization From 2b1bdf0c2e0b560fc055758b087071eaa5314adc Mon Sep 17 00:00:00 2001 From: Matias Arriola Date: Wed, 7 Oct 2026 13:21:28 -0300 Subject: [PATCH 04/14] fix(eslint): reject HTTP client imports in domain --- eslint/rules/architecture/rule.spec.ts | 8 ++++++++ eslint/rules/architecture/rule.ts | 1 + 2 files changed, 9 insertions(+) diff --git a/eslint/rules/architecture/rule.spec.ts b/eslint/rules/architecture/rule.spec.ts index 3c53850..2689da0 100644 --- a/eslint/rules/architecture/rule.spec.ts +++ b/eslint/rules/architecture/rule.spec.ts @@ -39,6 +39,14 @@ describe("EyeSeeTea architecture", () => { ) ).toEqual([]); }); + test.each(["axios", "node-fetch", "cross-fetch", "undici", "got", "ky"])( + "reports HTTP client imports in domain: %s", + source => { + for (const module of [source, `${source}/client`]) { + expect(lintArchitecture(`import client from '${module}';`)).toHaveLength(1); + } + } + ); test("reports data depending on UI", () => { expect( lintArchitecture( diff --git a/eslint/rules/architecture/rule.ts b/eslint/rules/architecture/rule.ts index e826e8c..7655c3c 100644 --- a/eslint/rules/architecture/rule.ts +++ b/eslint/rules/architecture/rule.ts @@ -69,6 +69,7 @@ export default ESLintUtils.RuleCreator( (/\/src\/(data|webapp|scripts)\//.test(target) || target.endsWith("/src/CompositionRoot.ts") || target.endsWith("/src/types/d2-api.ts") || + httpPackages.test(source) || infrastructurePackages.test(source)) ) { report( From 883caa29f4bcab50fe2d03c66b8ae6ada50ba03d Mon Sep 17 00:00:00 2001 From: Matias Arriola Date: Wed, 7 Oct 2026 13:41:39 -0300 Subject: [PATCH 05/14] feat(eslint): configure architecture layout and checks --- eslint/MIGRATION.md | 40 +++- eslint/README.md | 4 +- eslint/rules/architecture/README.md | 66 ++++++- eslint/rules/architecture/rule.spec.ts | 150 ++++++++++++++- eslint/rules/architecture/rule.ts | 241 ++++++++++++++++++------- 5 files changed, 425 insertions(+), 76 deletions(-) diff --git a/eslint/MIGRATION.md b/eslint/MIGRATION.md index 9340f36..e47b010 100644 --- a/eslint/MIGRATION.md +++ b/eslint/MIGRATION.md @@ -104,18 +104,50 @@ Review these before the first lint run: | Parser uses `./tsconfig.json` | Include every linted TS file, or point `parserOptions.project` at a dedicated `tsconfig.eslint.json`. Preserve application build settings. | | Typechecking includes `eslint/**/*.ts` and allows `.ts` import extensions | Include copied rules in a no-emit typecheck; use `allowImportingTsExtensions: true`. | | Source is under `src/`, with `$/*` imports | Adapt policy file globs, base import-path options, and TS aliases. | -| Layers are `src/domain`, `src/data`, `src/webapp`, and `src/scripts` | The architecture rule hardcodes these paths, API adapters, `CompositionRoot.ts`, and `getWebappCompositionRoot`. It has no options. Disable it for a different layout or change its implementation and regression tests. Merely changing `files` does not change its boundaries. | +| Layers are `src/domain`, `src/data`, `src/webapp`, and `src/scripts` | Configure the architecture rule’s `paths` and `clientFactories` for the project layout. Roots and adapters take precedence over their containing layer. See the [architecture options](rules/architecture/README.md#options); no directory restructuring is required. | | Domain/data use Futures | Review Promise restrictions and the two Future implementation exclusions. Projects using native Promises should adopt selected rules or maintain an explicitly adapted policy. | | React, Material UI, and Testing Library conventions apply | Omit irrelevant framework modules and adapt company rules; the styling rule recommends styled-components but does not install it. | | Unit tests use `*.spec.ts(x)` | The framework testing preset covers `.spec` files, while company test overrides also cover `.test`, `__tests__`, and `src/tests`. Align both scopes with the project. | | E2E tests use `src/tests/playwright` or `*.e2e.ts(x)` | Adapt both E2E checks and general test exclusions for other locations. | | Generated files use skeleton paths | Review global ignores and lint command targets. An ignored file receives no checks. | -The custom rules currently have no options. Severity and file scopes can be changed -through flat config; internal architecture boundaries and detection behavior require -an implementation change. Monorepos need per-package parser projects and scoped +The architecture rule accepts layout, factory, and independent check options. The +other custom rules have no options. Severity and file scopes can be changed through +flat config. Monorepos need per-package parser projects and scoped config entries rather than assuming one root `src/` and one `tsconfig.json`. +### Feature-based layouts + +For repositories under `src/data//`, presentation under `src/presentation/`, +and multiple composition roots, append an override after the company policy: + +```js +export default [{ + files: ["src/**/*.{ts,tsx}"], + rules: { + "eyeseetea/architecture": ["warn", { + paths: { + presentation: ["src/presentation/**"], + repositories: ["src/data/**/*Repository.ts"], + compositionRoots: [ + "src/presentation/AppCompositionRoot.ts", + "src/presentation/TestCompositionRoot.ts" + ], + apiAdapters: ["src/data/common/utils/api-futures.ts"] + }, + clientFactories: ["createApp", "createTest"] + }] + } +}]; +``` + +Replace the example filenames and factory names with actual project names. Add any +client type wrapper to `apiAdapters`; supplied arrays replace defaults. Keep repository +patterns narrow rather than granting client access to all data files. To adopt only +layer checks, set `checks: { httpClientAccess: false, clientConstruction: false }`. +The [policy-only composition](#incorporate-the-configuration) keeps framework presets +under the consuming project's control. + ## 3. Establish a baseline and adopt in CI 1. Record the existing lint/typecheck/test results before changing configuration. diff --git a/eslint/README.md b/eslint/README.md index 6db021e..f316f59 100644 --- a/eslint/README.md +++ b/eslint/README.md @@ -54,8 +54,8 @@ that necessarily implement the abstraction; new business code receives no blanke | --- | --- | --- | | Immutability | `prefer-const`, `no-var`, `no-param-reassign` including properties; local collection mutation rule | Warn. Typed Array/tuple, standard Map/Set mutators; custom methods called `push` are allowed. Arbitrary object mutation, aliasing, and shared-state analysis still require review. | | Type safety | Explicit `any`; type-aware unsafe assignment, argument, call, member access, return, and type assertion rules; restricted `as unknown` and `as Type[]` | Warn. Safe widening and `as const` are allowed. Type guards and `satisfies` are preferred. | -| Layer dependencies | Local architecture rule resolves imports using TypeScript configuration; checks static imports, re-exports, literal dynamic imports and `require` | Warn. Domain → data/UI/platform and data → UI are forbidden; presentation → concrete data is reported. Checks direct dependencies, not transitive architectural purity. | -| API boundaries | d2-api import boundaries, aliased named `D2Api` construction, HTTP imports and platform HTTP globals | Warn. Repository/client adapter/composition-root imports allowed. Named client construction belongs in `getWebappCompositionRoot` in `CompositionRoot.ts`. Namespace constructors, indirect factory calls, and nonliteral dynamic imports need review. | +| Layer dependencies | Local architecture rule resolves imports using TypeScript configuration; checks static imports, re-exports, literal dynamic imports and `require` | Warn. Domain → data/UI/platform and data → UI are forbidden; presentation → concrete data is reported. Configurable layout paths. Checks direct dependencies, not transitive architectural purity. | +| API boundaries | d2-api import boundaries, aliased named `D2Api` construction, HTTP imports and platform HTTP globals | Warn. Repository/client adapter/composition-root imports allowed. By default, named client construction belongs in `getWebappCompositionRoot` in `CompositionRoot.ts`; roots, factory names, and individual architecture checks are configurable. Namespace constructors, indirect factory calls, and nonliteral dynamic imports need review. | | Asynchronous code | Promise value/type references in domain/data; production `toPromise()` calls; existing Future capture rule | Warn, except capture errors. Tests allow Promises and `toPromise`. `Future.block` async callbacks remain valid. Inferred Promise returns and APIs exposed through aliases are not fully covered. | | React styling and Hooks | Restricted `makeStyles` imports; React Hooks rules | Styling warns; hook correctness errors; dependencies warn. Styling namespace imports and component-vs-hook responsibilities need review. | | Unit and component testing | Weak existence/truthiness matchers warn; Testing Library async queries, presence queries, explicit assertions and user-event guidance | Warnings allow legitimate existence checks. No Jest plugin: this repository runs Vitest. | diff --git a/eslint/rules/architecture/README.md b/eslint/rules/architecture/README.md index 06711a9..acca1ec 100644 --- a/eslint/rules/architecture/README.md +++ b/eslint/rules/architecture/README.md @@ -37,7 +37,69 @@ import { D2Api } from "$/types/d2-api"; ## Options -This rule has no options. +The skeleton layout and `getWebappCompositionRoot` factory are the defaults. +Pass one options object to adapt the layout without modifying the shared rule: + +```js +"eyeseetea/architecture": ["warn", { + paths: { + domain: ["src/domain/**"], + data: ["src/data/**"], + presentation: ["src/presentation/**"], + repositories: ["src/data/**/*Repository.ts"], + compositionRoots: [ + "src/presentation/AppCompositionRoot.ts", + "src/presentation/TestCompositionRoot.ts" + ], + apiAdapters: ["src/data/common/utils/api-futures.ts"] + }, + clientFactories: ["createApp", "createTest"], + checks: { + layerDependencies: true, + httpClientAccess: true, + clientConstruction: true + } +}] +``` + +Paths are relative to ESLint's working directory. Use `/` separators. Patterns +support `*` (within one path segment), `**` (across segments), and `?` (one +non-separator character); `**/` also matches zero directories. Brace expansion, +negation, and extglobs are not supported. Omitted path groups retain their defaults; +provided arrays replace that group's defaults, and `[]` disables that group. + +| Path group | Default | +| --- | --- | +| `domain` | `src/domain/**` | +| `data` | `src/data/**` | +| `presentation` | `src/webapp/**`, `src/scripts/**` | +| `repositories` | `src/data/repositories/**` | +| `compositionRoots` | `src/CompositionRoot.ts` | +| `apiAdapters` | `src/types/d2-api.ts`, `src/data/api-futures.ts` | + +Roots and adapters take precedence over their containing domain/data/presentation +layer. This lets composition roots inside presentation import concrete repositories. +Repository patterns grant client-import permission, so keep them narrow. Adapters +may import clients, but are not permitted to construct them outside a configured root. +Imports of configured adapters are treated as infrastructure dependencies. + +`clientFactories` replaces the allowed factory names. Function declarations and +arrow/function expressions bound to named variables are supported. Construction +requires both a configured composition-root file and an enclosing permitted factory. +An empty factory list permits no construction. + +All checks default to `true` and can be toggled independently: + +- `layerDependencies`: domain → data/presentation/roots/adapters, data → + presentation/roots, and presentation → data imports. +- `httpClientAccess`: domain platform APIs/imports, repository/presentation HTTP + access, and DHIS2 client/adapter import permissions. +- `clientConstruction`: where imported named `D2Api` constructors may run. + +Diagnostics include the import specifier and resolved project-relative target. +Type-aware parser compiler options take precedence; without a parser program, the +rule reads the nearest `tsconfig.json` from ESLint's working directory. Missing local +modules cannot be classified by layer until TypeScript can resolve them. ## Limitations @@ -47,5 +109,5 @@ nonliteral imports, namespace constructors, and indirect factories require revie ## When Not To Use It -Disable this rule in projects with a different architecture or directory structure. +Configure paths and checks for a different directory structure or architecture. For a justified exception, use a narrow suppression with an explanation. diff --git a/eslint/rules/architecture/rule.spec.ts b/eslint/rules/architecture/rule.spec.ts index 2689da0..e5c71c9 100644 --- a/eslint/rules/architecture/rule.spec.ts +++ b/eslint/rules/architecture/rule.spec.ts @@ -1,22 +1,30 @@ import path from "node:path"; +// Access real Node modules because the app build aliases stdlib imports to browser shims. +const fs = globalThis.process.getBuiltinModule("fs"); +const os = globalThis.process.getBuiltinModule("os"); import { TSESLint } from "@typescript-eslint/utils"; const { Linter } = TSESLint; import { parser } from "typescript-eslint"; -import { describe, expect, test } from "vitest"; -import architecture from "./rule"; +import { afterAll, beforeAll, describe, expect, test } from "vitest"; +import architecture, { type ArchitectureOptions } from "./rule"; -function lintArchitecture(code: string, filename = "src/domain/entities/PolicyProbe.ts") { - return new Linter().verify( +function lintArchitecture( + code: string, + filename = "src/domain/entities/PolicyProbe.ts", + options: ArchitectureOptions = {}, + cwd = globalThis.process.cwd() +) { + return new Linter({ cwd }).verify( code, [ { files: ["**/*.ts"], languageOptions: { parser }, plugins: { eyeseetea: { rules: { architecture } } }, - rules: { "eyeseetea/architecture": "warn" }, + rules: { "eyeseetea/architecture": ["warn", options] }, }, ], - { filename: path.resolve(filename) } + { filename: path.resolve(cwd, filename) } ); } @@ -91,3 +99,133 @@ describe("EyeSeeTea architecture", () => { expect(lintArchitecture("class D2Api {} new D2Api();")).toEqual([]); }); }); + +describe("alternative architecture layout", () => { + const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "architecture-layout-")); + const options: ArchitectureOptions = { + paths: { + presentation: ["src/presentation/**"], + repositories: ["src/data/**/*Repository.ts"], + compositionRoots: [ + "src/presentation/AppCompositionRoot.ts", + "src/presentation/TestCompositionRoot.ts", + ], + apiAdapters: ["src/data/common/utils/api-futures.ts"], + }, + clientFactories: ["createApp", "createTest"], + }; + beforeAll(() => { + fs.writeFileSync( + path.join(cwd, "tsconfig.json"), + JSON.stringify({ + compilerOptions: { + baseUrl: ".", + paths: { "@/*": ["src/*"] }, + }, + }) + ); + for (const file of [ + "src/presentation/View.ts", + "src/data/users/UserRepository.ts", + "src/data/common/utils/api-futures.ts", + "src/presentation/AppCompositionRoot.ts", + "src/presentation/TestCompositionRoot.ts", + ]) { + fs.mkdirSync(path.dirname(path.join(cwd, file)), { recursive: true }); + fs.writeFileSync(path.join(cwd, file), "export {};\n"); + } + }); + afterAll(() => fs.rmSync(cwd, { recursive: true, force: true })); + const lint = (code: string, filename: string, overrides: ArchitectureOptions = {}) => + lintArchitecture(code, filename, { ...options, ...overrides }, cwd); + test.each([ + "import { View } from '@/presentation/View';", + "export { View } from '../../presentation/View';", + "export * from '@/presentation/View';", + "import('@/presentation/View');", + "require('@/presentation/View');", + ])("resolves domain boundary: %s", code => { + const messages = lint(code, "src/domain/entities/Probe.ts"); + expect(messages).toHaveLength(1); + expect(messages[0]?.message).toContain("src/presentation/View.ts"); + }); + test("checks data and presentation directions", () => { + expect(lint("import '@/presentation/View';", "src/data/users/Probe.ts")).toHaveLength(1); + expect( + lint("import '../data/users/UserRepository';", "src/presentation/View.ts") + ).toHaveLength(1); + expect( + lint("import '@/presentation/AppCompositionRoot';", "src/domain/Probe.ts") + ).toHaveLength(1); + }); + test("allows feature repositories and relocated adapters to import the client", () => { + for (const filename of [ + "src/data/users/UserRepository.ts", + "src/data/UserRepository.ts", + "src/data/common/utils/api-futures.ts", + ]) { + expect(lint("import { D2Api } from '@eyeseetea/d2-api';", filename)).toEqual([]); + } + expect( + lint("import { D2Api } from '@eyeseetea/d2-api';", "src/data/users/Helper.ts") + ).toHaveLength(1); + expect(lint("fetch('/api');", "src/data/users/UserRepository.ts")).toHaveLength(1); + }); + test("roots override presentation classification and permit named and arrow factories", () => { + for (const [filename, factory] of [ + ["src/presentation/AppCompositionRoot.ts", "createApp"], + ["src/presentation/TestCompositionRoot.ts", "createTest"], + ] as const) { + const imports = + "import '@/data/users/UserRepository'; import { D2Api as Client } from '@eyeseetea/d2-api';"; + for (const declaration of [ + `function ${factory}() { return new Client(); }`, + `const ${factory} = () => new Client();`, + `const ${factory} = function () { return new Client(); };`, + ]) { + expect(lint(imports + declaration, filename)).toEqual([]); + } + expect(lint(imports + "new Client();", filename)).toHaveLength(1); + expect( + lint(imports + "function other() { return new Client(); }", filename) + ).toHaveLength(1); + } + expect( + lint( + "import { D2Api } from '@eyeseetea/d2-api'; function createApp() { return new D2Api(); }", + "src/data/users/UserRepository.ts" + ) + ).toHaveLength(1); + }); + test("toggles checks independently", () => { + expect( + lint("import '@/presentation/View'; fetch('/api');", "src/domain/Probe.ts", { + checks: { layerDependencies: false }, + }) + ).toHaveLength(1); + expect( + lint("import '@/presentation/View'; fetch('/api');", "src/domain/Probe.ts", { + checks: { httpClientAccess: false }, + }) + ).toHaveLength(1); + expect( + lint( + "import { D2Api } from '@eyeseetea/d2-api'; new D2Api();", + "src/data/users/UserRepository.ts", + { checks: { clientConstruction: false } } + ) + ).toEqual([]); + }); + test("empty patterns replace defaults and do not classify similarly prefixed folders", () => { + expect(lint("fetch('/api');", "src/domain/Probe.ts", { paths: { domain: [] } })).toEqual( + [] + ); + expect(lint("fetch('/api');", "src/domain-other/Probe.ts")).toEqual([]); + expect(lint("import '@/data/users/UserRepository';", "src/webapp/Probe.ts")).toEqual([]); + }); + test("rejects misspelled options", () => { + expect(() => + lint("", "src/domain/Probe.ts", { checks: { typo: false } } as ArchitectureOptions) + ).toThrow(); + }); +}); diff --git a/eslint/rules/architecture/rule.ts b/eslint/rules/architecture/rule.ts index 7655c3c..f940ebb 100644 --- a/eslint/rules/architecture/rule.ts +++ b/eslint/rules/architecture/rule.ts @@ -20,39 +20,145 @@ const infrastructurePackages = /^(react|react-dom|@material-ui\/|@mui\/|@dhis2\/|@eyeseetea\/d2-api|axios|node-fetch|node:|fs$|fs\/|path$|http$|https$)/; const normalize = (value: string) => value.replaceAll("\\", "/"); +export type ArchitectureOptions = { + paths?: Partial< + Record< + | "domain" + | "data" + | "presentation" + | "repositories" + | "compositionRoots" + | "apiAdapters", + string[] + > + >; + clientFactories?: string[]; + checks?: { + layerDependencies?: boolean; + httpClientAccess?: boolean; + clientConstruction?: boolean; + }; +}; + +const defaultPaths = { + domain: ["src/domain/**"], + data: ["src/data/**"], + presentation: ["src/webapp/**", "src/scripts/**"], + repositories: ["src/data/repositories/**"], + compositionRoots: ["src/CompositionRoot.ts"], + apiAdapters: ["src/types/d2-api.ts", "src/data/api-futures.ts"], +}; + +// Project-relative globs support *, **, and ?. **/ also matches zero directories. +function compileGlob(pattern: string): RegExp { + const normalized = normalize(pattern).replace(/^\.\//, ""); + let expression = "^"; + for (let index = 0; index < normalized.length; index++) { + const char = normalized[index]!; + if (char === "*" && normalized[index + 1] === "*") { + index++; + if (normalized[index + 1] === "/") { + expression += "(?:.*/)?"; + index++; + } else expression += ".*"; + } else if (char === "*") expression += "[^/]*"; + else if (char === "?") expression += "[^/]"; + else expression += char.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + } + return new RegExp(expression + "$"); +} + export default ESLintUtils.RuleCreator( name => `https://github.com/EyeSeeTea/dhis2-app-skeleton/blob/master/eslint/rules/${name}/README.md` )({ name: "architecture", - defaultOptions: [], + defaultOptions: [{} as ArchitectureOptions], meta: { type: "problem", docs: { description: "Check Clean Architecture dependency directions and DHIS2 client boundaries.", }, - schema: [], + schema: [ + { + type: "object", + additionalProperties: false, + properties: { + paths: { + type: "object", + additionalProperties: false, + properties: Object.fromEntries( + Object.keys(defaultPaths).map(key => [ + key, + { + type: "array", + items: { type: "string", minLength: 1 }, + uniqueItems: true, + }, + ]) + ), + }, + clientFactories: { + type: "array", + items: { type: "string", minLength: 1 }, + uniqueItems: true, + }, + checks: { + type: "object", + additionalProperties: false, + properties: { + layerDependencies: { type: "boolean" }, + httpClientAccess: { type: "boolean" }, + clientConstruction: { type: "boolean" }, + }, + }, + }, + }, + ], messages: { boundary: "{{message}}", }, }, - create(context) { - const filename = normalize(context.filename); - const domain = filename.includes("/src/domain/"); - const data = filename.includes("/src/data/"); - const repository = filename.includes("/src/data/repositories/"); - const presentation = /\/src\/(webapp|scripts)\//.test(filename); - const root = filename.endsWith("/src/CompositionRoot.ts"); - const apiAdapter = - filename.endsWith("/src/types/d2-api.ts") || - filename.endsWith("/src/data/api-futures.ts"); + create(context, [configuration]) { + const paths = { ...defaultPaths, ...configuration.paths }; + const patterns = Object.fromEntries( + Object.entries(paths).map(([key, globs]) => [key, globs.map(compileGlob)]) + ); + const matches = (key: keyof typeof defaultPaths, filename: string) => + patterns[key]!.some(pattern => + pattern.test(normalize(path.relative(context.cwd, filename))) + ); + const filename = context.filename; + // Roots and adapters are infrastructure exceptions even when nested in a layer. + const root = matches("compositionRoots", filename); + const apiAdapter = matches("apiAdapters", filename); + const domain = !root && !apiAdapter && matches("domain", filename); + const data = !root && !apiAdapter && matches("data", filename); + const repository = matches("repositories", filename); + const presentation = !root && !apiAdapter && matches("presentation", filename); + const factories = configuration.clientFactories ?? ["getWebappCompositionRoot"]; + const checks = { + layerDependencies: true, + httpClientAccess: true, + clientConstruction: true, + ...configuration.checks, + }; const sourceCode = context.sourceCode; const program = sourceCode.parserServices?.program; - const options = program?.getCompilerOptions() ?? { - baseUrl: path.join(context.cwd, "src"), - paths: { "$/*": ["./*"] }, - }; + const configFile = !program && ts.findConfigFile(context.cwd, ts.sys.fileExists); + const parsedConfig = configFile + ? ts.readConfigFile(configFile, ts.sys.readFile) + : undefined; + const options = + program?.getCompilerOptions() ?? + (configFile && !parsedConfig?.error + ? ts.parseJsonConfigFileContent( + parsedConfig?.config, + ts.sys, + path.dirname(configFile) + ).options + : { baseUrl: path.join(context.cwd, "src"), paths: { "$/*": ["./*"] } }); const report = (node: TSESTree.Node, message: string) => context.report({ node, messageId: "boundary", data: { message } }); function checkImport(node: TSESTree.Node, source: unknown) { @@ -63,48 +169,50 @@ export default ESLintUtils.RuleCreator( options, ts.sys ).resolvedModule; - const target = normalize(resolved?.resolvedFileName ?? source); - if ( - domain && - (/\/src\/(data|webapp|scripts)\//.test(target) || - target.endsWith("/src/CompositionRoot.ts") || - target.endsWith("/src/types/d2-api.ts") || - httpPackages.test(source) || - infrastructurePackages.test(source)) - ) { + const target = resolved?.resolvedFileName; + const targetMatches = (key: keyof typeof defaultPaths) => + target !== undefined && matches(key, target); + const boundary = (layer: string, destination: string) => report( node, - "Domain must not depend on data, presentation, DHIS2 clients, or platform infrastructure." + `${layer} must not import ${destination} through '${source}'${target ? ` (resolved to ${normalize(path.relative(context.cwd, target))})` : ""}.` ); - } else if ( - data && - (/\/src\/(webapp|scripts)\//.test(target) || - target.endsWith("/src/CompositionRoot.ts")) - ) { - report(node, "Data must not depend on presentation or the composition root."); + if (checks.layerDependencies) { + if ( + domain && + (targetMatches("data") || + targetMatches("presentation") || + targetMatches("compositionRoots") || + targetMatches("apiAdapters")) + ) + boundary("Domain", "data, presentation, or infrastructure adapters"); + else if ( + data && + (targetMatches("presentation") || targetMatches("compositionRoots")) + ) + boundary("Data", "presentation or composition roots"); + if (presentation && targetMatches("data")) + boundary("Presentation", "data implementations"); } - if ((repository || presentation) && httpPackages.test(source)) - report( - node, - "Repositories access HTTP through d2-api, not a separate HTTP client." - ); - if (presentation && target.includes("/src/data/")) - report( - node, - "Presentation accesses repositories through composition-root use cases." - ); - if ( - !domain && - !repository && - !root && - !apiAdapter && - (/^@eyeseetea\/d2-api(\/|$)/.test(source) || - target.endsWith("/src/types/d2-api.ts")) - ) { - report( - node, - "Keep the DHIS2 client in repositories, the composition root, or a documented infrastructure adapter." - ); + if (checks.httpClientAccess) { + if (domain && (httpPackages.test(source) || infrastructurePackages.test(source))) + boundary("Domain", "platform infrastructure"); + else if ((repository || presentation) && httpPackages.test(source)) + boundary( + repository ? "Repositories" : "Presentation", + "HTTP clients; access HTTP through d2-api repositories" + ); + if ( + !domain && + !repository && + !root && + !apiAdapter && + (/^@eyeseetea\/d2-api(\/|$)/.test(source) || targetMatches("apiAdapters")) + ) + boundary( + "This file", + "DHIS2 clients or API adapters; keep them in repositories, composition roots, or adapters" + ); } } return { @@ -129,7 +237,7 @@ export default ESLintUtils.RuleCreator( checkImport(node, node.arguments[0].value); }, NewExpression(node) { - if (node.callee.type !== "Identifier") return; + if (!checks.clientConstruction || node.callee.type !== "Identifier") return; let scope: TSESLint.Scope.Scope | null = sourceCode.getScope(node); let variable; while (scope && !variable) { @@ -144,20 +252,29 @@ export default ESLintUtils.RuleCreator( def.node.imported.name === "D2Api" ); if (!importedApi) return; - const inFactory = sourceCode - .getAncestors(node) - .some( - ancestor => - ancestor.type === "FunctionDeclaration" && - ancestor.id?.name === "getWebappCompositionRoot" + const inFactory = sourceCode.getAncestors(node).some(ancestor => { + if (ancestor.type === "FunctionDeclaration") + return ancestor.id && factories.includes(ancestor.id.name); + if ( + ancestor.type !== "ArrowFunctionExpression" && + ancestor.type !== "FunctionExpression" + ) + return false; + const parent = ancestor.parent; + return ( + parent?.type === "VariableDeclarator" && + parent.id.type === "Identifier" && + factories.includes(parent.id.name) ); + }); if (!root || !inFactory) report( node, - "Instantiate D2Api only inside getWebappCompositionRoot() in CompositionRoot.ts." + `Instantiate D2Api only inside a configured client factory (${factories.join(", ") || "none"}) in a configured composition root.` ); }, "Program:exit"() { + if (!checks.httpClientAccess) return; for (const scope of sourceCode.scopeManager?.scopes ?? []) { for (const reference of scope.references) { if (reference.resolved?.defs.length) continue; From 3472fca9d4536a8a9949e88463bdbd5c5b5e9cc9 Mon Sep 17 00:00:00 2001 From: Matias Arriola Date: Tue, 13 Oct 2026 12:00:29 -0300 Subject: [PATCH 06/14] Add ESLint baseline enforcement and split architecture checks --- .prettierignore | 2 + README.md | 5 + eslint-suppressions.json | 215 ++++++++++++ eslint.config.mjs | 6 +- eslint/BASELINE.md | 79 +++++ eslint/MIGRATION.md | 62 ++-- eslint/README.md | 56 ++- eslint/baseline-config.mjs | 13 + eslint/baseline.spec.mjs | 66 ++++ eslint/empty-suppressions.json | 1 + eslint/eyeseetea-config.spec.ts | 32 +- eslint/eyeseetea-config.ts | 4 +- eslint/eyeseetea-plugin.ts | 6 + eslint/rules/architecture/README.md | 8 +- eslint/rules/architecture/rule.spec.ts | 53 ++- eslint/rules/architecture/rule.ts | 310 +---------------- eslint/rules/architecture/shared.ts | 324 ++++++++++++++++++ eslint/rules/client-construction/README.md | 36 ++ eslint/rules/client-construction/rule.spec.ts | 44 +++ eslint/rules/client-construction/rule.ts | 7 + eslint/rules/http-client-access/README.md | 39 +++ eslint/rules/http-client-access/rule.spec.ts | 44 +++ eslint/rules/http-client-access/rule.ts | 7 + eslint/rules/layer-dependencies/README.md | 37 ++ eslint/rules/layer-dependencies/rule.spec.ts | 44 +++ eslint/rules/layer-dependencies/rule.ts | 7 + package.json | 7 +- 27 files changed, 1157 insertions(+), 357 deletions(-) create mode 100644 eslint-suppressions.json create mode 100644 eslint/BASELINE.md create mode 100644 eslint/baseline-config.mjs create mode 100644 eslint/baseline.spec.mjs create mode 100644 eslint/empty-suppressions.json create mode 100644 eslint/rules/architecture/shared.ts create mode 100644 eslint/rules/client-construction/README.md create mode 100644 eslint/rules/client-construction/rule.spec.ts create mode 100644 eslint/rules/client-construction/rule.ts create mode 100644 eslint/rules/http-client-access/README.md create mode 100644 eslint/rules/http-client-access/rule.spec.ts create mode 100644 eslint/rules/http-client-access/rule.ts create mode 100644 eslint/rules/layer-dependencies/README.md create mode 100644 eslint/rules/layer-dependencies/rule.spec.ts create mode 100644 eslint/rules/layer-dependencies/rule.ts diff --git a/.prettierignore b/.prettierignore index c68849a..a521a6c 100644 --- a/.prettierignore +++ b/.prettierignore @@ -3,3 +3,5 @@ node_modules *.min.js *.min.css src/locales/ +# Generated and formatted by ESLint's native suppression commands. +eslint-suppressions.json diff --git a/README.md b/README.md index 2172061..87dfa60 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,11 @@ legacy-code rollout, justified exceptions, and practices that still require revi Individual checks can also be run with `yarn typecheck`, `yarn prettify:check`, `yarn lint`, and `yarn test`. +Lint uses a committed [ESLint baseline](eslint/BASELINE.md): `yarn lint:new` rejects +errors above accepted legacy counts; `yarn lint:all` shows the backlog. Use +`yarn lint:cached` locally and `yarn lint:baseline:prune` after legacy fixes. +Review baseline increases explicitly; never regenerate in CI. + ## Some development tips ### Data structures (`src/domain/entities/generic`) diff --git a/eslint-suppressions.json b/eslint-suppressions.json new file mode 100644 index 0000000..34680e9 --- /dev/null +++ b/eslint-suppressions.json @@ -0,0 +1,215 @@ +{ + "src/data/__tests__/api-futures.spec.ts": { + "eyeseetea/http-client-access": { + "count": 2 + } + }, + "src/domain/entities/generic/Collection.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + }, + "@typescript-eslint/no-unsafe-return": { + "count": 3 + }, + "@typescript-eslint/no-unsafe-type-assertion": { + "count": 9 + }, + "eyeseetea/no-collection-mutation": { + "count": 9 + }, + "no-restricted-syntax": { + "count": 3 + } + }, + "src/domain/entities/generic/Either.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + }, + "@typescript-eslint/no-unsafe-return": { + "count": 2 + } + }, + "src/domain/entities/generic/Future.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + }, + "@typescript-eslint/no-unsafe-argument": { + "count": 1 + }, + "@typescript-eslint/no-unsafe-assignment": { + "count": 1 + }, + "@typescript-eslint/no-unsafe-return": { + "count": 3 + }, + "@typescript-eslint/no-unsafe-type-assertion": { + "count": 1 + }, + "eyeseetea/http-client-access": { + "count": 1 + }, + "eyeseetea/no-collection-mutation": { + "count": 3 + } + }, + "src/domain/entities/generic/HashMap.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + }, + "@typescript-eslint/no-unsafe-type-assertion": { + "count": 1 + } + }, + "src/domain/entities/generic/Rec.ts": { + "@typescript-eslint/no-unsafe-type-assertion": { + "count": 6 + }, + "no-restricted-syntax": { + "count": 3 + } + }, + "src/domain/entities/generic/Struct.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + }, + "@typescript-eslint/no-unsafe-member-access": { + "count": 1 + }, + "@typescript-eslint/no-unsafe-return": { + "count": 1 + }, + "@typescript-eslint/no-unsafe-type-assertion": { + "count": 4 + } + }, + "src/domain/entities/generic/__tests__/Future.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + }, + "@typescript-eslint/no-unsafe-argument": { + "count": 1 + }, + "@typescript-eslint/no-unsafe-assignment": { + "count": 1 + }, + "@typescript-eslint/no-unsafe-type-assertion": { + "count": 1 + } + }, + "src/domain/entities/generic/__tests__/HashMap.spec.ts": { + "eyeseetea/no-collection-mutation": { + "count": 1 + } + }, + "src/domain/usecases/GetUserReportUseCase.ts": { + "eyeseetea/no-collection-mutation": { + "count": 1 + } + }, + "src/domain/usecases/__tests__/GetCurrentUserUseCase.spec.ts": { + "eyeseetea/layer-dependencies": { + "count": 1 + } + }, + "src/domain/usecases/__tests__/GetUserReportUseCase.spec.ts": { + "@typescript-eslint/no-unsafe-argument": { + "count": 1 + } + }, + "src/scripts/UsersReportScript.ts": { + "@typescript-eslint/no-floating-promises": { + "count": 1 + }, + "eyeseetea/client-construction": { + "count": 1 + }, + "eyeseetea/http-client-access": { + "count": 1 + }, + "eyeseetea/layer-dependencies": { + "count": 2 + }, + "no-restricted-syntax": { + "count": 1 + } + }, + "src/scripts/dev/UpdatePoScript.ts": { + "eyeseetea/no-collection-mutation": { + "count": 1 + } + }, + "src/utils/i18n-typed.ts": { + "@typescript-eslint/no-unsafe-assignment": { + "count": 1 + }, + "@typescript-eslint/no-unsafe-call": { + "count": 2 + }, + "@typescript-eslint/no-unsafe-member-access": { + "count": 2 + }, + "@typescript-eslint/no-unsafe-return": { + "count": 1 + } + }, + "src/utils/ts-utils.ts": { + "@typescript-eslint/no-unsafe-type-assertion": { + "count": 1 + } + }, + "src/utils/uid.ts": { + "@typescript-eslint/no-unsafe-assignment": { + "count": 1 + }, + "@typescript-eslint/no-unsafe-call": { + "count": 3 + }, + "@typescript-eslint/no-unsafe-member-access": { + "count": 2 + } + }, + "src/webapp/components/users-table/__tests__/UsersTable.spec.tsx": { + "eyeseetea/layer-dependencies": { + "count": 1 + }, + "testing-library/prefer-explicit-assert": { + "count": 1 + } + }, + "src/webapp/pages/app/App.tsx": { + "@typescript-eslint/no-floating-promises": { + "count": 1 + }, + "no-restricted-syntax": { + "count": 1 + } + }, + "src/webapp/pages/app/Dhis2App.tsx": { + "@typescript-eslint/no-unsafe-assignment": { + "count": 6 + }, + "@typescript-eslint/no-unsafe-call": { + "count": 1 + }, + "@typescript-eslint/no-unsafe-member-access": { + "count": 2 + }, + "@typescript-eslint/no-unsafe-return": { + "count": 1 + }, + "@typescript-eslint/no-unsafe-type-assertion": { + "count": 2 + }, + "eyeseetea/client-construction": { + "count": 2 + }, + "eyeseetea/http-client-access": { + "count": 2 + } + }, + "src/webapp/utils/__tests__/objects-table.spec.tsx": { + "eyeseetea/no-collection-mutation": { + "count": 1 + } + } +} \ No newline at end of file diff --git a/eslint.config.mjs b/eslint.config.mjs index e867ef4..049c191 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -2,7 +2,7 @@ import tseslint from "typescript-eslint"; import baseConfig from "./eslint/base-config.mjs"; import reactConfig from "./eslint/react-config.mjs"; import testingConfig from "./eslint/testing-config.mjs"; -import eyeseeteaConfig from "./eslint/eyeseetea-config.ts"; +import baselineConfig from "./eslint/baseline-config.mjs"; -// Company policy comes last so its severities override framework defaults. -export default tseslint.config(...baseConfig, ...reactConfig, ...testingConfig, ...eyeseeteaConfig); +// Company policy comes last; errors are ratcheted using native CLI suppressions. +export default tseslint.config(...baseConfig, ...reactConfig, ...testingConfig, ...baselineConfig); diff --git a/eslint/BASELINE.md b/eslint/BASELINE.md new file mode 100644 index 0000000..0d5ee50 --- /dev/null +++ b/eslint/BASELINE.md @@ -0,0 +1,79 @@ +# Native ESLint baseline + +ESLint 9 bulk suppressions accept legacy findings and reject count increases without +extra tooling. Run commands from the project root. + +## Commands + +| Command | Behavior | +| --- | --- | +| `yarn lint` / `yarn lint:new` | Lint all `src`; fail on unsuppressed errors or unused suppressions. | +| `yarn lint:all` | Show all findings using the committed empty baseline; fails while legacy errors remain. | +| `yarn lint:cached` | Run the baseline gate with ESLint's content cache for local feedback. | +| `yarn lint:baseline` | Create or increase accepted error counts; requires deliberate review. | +| `yarn lint:baseline:prune` | Remove or reduce stale counts after fixes; never accepts new violations. | + +`yarn check` uses this gate through `yarn lint`. `lint-all` also runs `ts-prune` +(unused-code analysis, not baselined); it is distinct from `lint:all`. + +## Configuration and adoption + +The reusable `eyeseetea-config.ts` defaults to warnings. The root config instead uses +`baseline-config.mjs`, which promotes policy warnings to errors without changing +scopes, exclusions, or options: native suppressions apply only to errors. Other +framework/base warnings remain advisory and unbaselined. + +Commit `eslint-suppressions.json` as accepted debt. The gate explicitly names it, +so a missing file fails. Keep `eslint/empty-suppressions.json` as `{}` so `lint:all` +shows unsuppressed findings. Normal lint and inspection never rewrite either file. + +To adopt in another project: + +1. Install ESLint 9.24+ and compose the baseline profile after framework config; + adapt layout and test scopes first. +2. Run `yarn lint:all`, review findings, fix correctness defects, and separate + legitimate legacy constraints from configuration mistakes. +3. Run `yarn lint:baseline`, review the generated file, and commit it with the + profile, config, and scripts. This accepts **all current rule errors**, including + correctness errors. Use `--suppress-rule ` for selective acceptance; + never regenerate merely to make an unexplained failure pass. +4. Require `yarn lint:new` or `yarn check` in CI; never regenerate the baseline there. + +For gradual adoption, retain `eyeseetea-config.ts` and promote selected rules through +scoped overrides. + +## Everyday workflow + +- Run `yarn lint:cached` locally; fix new violations rather than increasing counts. + Document justified exceptions with narrow rule suppressions. +- After legacy fixes, run `yarn lint:baseline:prune` and commit the reduction with + the fix. Normal lint fails on stale counts; keep + `--pass-on-unpruned-suppressions` out of required CI. +- Review baseline increases, rule/config upgrades, and file moves or renames: + baseline entries are path-specific. + +## Guarantee and limitations + +The baseline stores a **count per file and rule**, not violation identities or ages. +Exceeding a count fails and reports **all violations of that rule in the file**; +use the Git diff to identify the new one. New files have no accepted findings. + +Fixing one violation and introducing another of the same rule in the same file can +pass with an unchanged count. Review must catch these replacements and changes to +accepted debt. Promoting warnings also makes conditional guidance blocking: +legitimate truthiness assertions or adapter constraints may need documented exceptions. + +Editor integrations and direct Node API callers may show accepted findings unless +they support bulk suppressions. Policy regression tests intentionally inspect +unsuppressed diagnostics. + +## Performance + +CI runs one full lint pass plus native suppression bookkeeping. `lint:new` refers +to findings above accepted counts, not changed-line linting. + +The local cache reuses unchanged files but may miss effects of imported type or +dependency changes, so required CI runs uncached. Keep `.eslintcache` ignored; +measure cold/warm timings on large projects before changing this tradeoff. + +Reference: [ESLint bulk suppressions](https://eslint.org/docs/latest/use/suppressions). diff --git a/eslint/MIGRATION.md b/eslint/MIGRATION.md index e47b010..c3dd4b9 100644 --- a/eslint/MIGRATION.md +++ b/eslint/MIGRATION.md @@ -104,17 +104,17 @@ Review these before the first lint run: | Parser uses `./tsconfig.json` | Include every linted TS file, or point `parserOptions.project` at a dedicated `tsconfig.eslint.json`. Preserve application build settings. | | Typechecking includes `eslint/**/*.ts` and allows `.ts` import extensions | Include copied rules in a no-emit typecheck; use `allowImportingTsExtensions: true`. | | Source is under `src/`, with `$/*` imports | Adapt policy file globs, base import-path options, and TS aliases. | -| Layers are `src/domain`, `src/data`, `src/webapp`, and `src/scripts` | Configure the architecture rule’s `paths` and `clientFactories` for the project layout. Roots and adapters take precedence over their containing layer. See the [architecture options](rules/architecture/README.md#options); no directory restructuring is required. | +| Layers are `src/domain`, `src/data`, `src/webapp`, and `src/scripts` | Configure `paths` on each architecture rule and `clientFactories` on `client-construction` for the project layout. Roots and adapters take precedence over their containing layer. See the [architecture options](rules/architecture/README.md#options); no directory restructuring is required. | | Domain/data use Futures | Review Promise restrictions and the two Future implementation exclusions. Projects using native Promises should adopt selected rules or maintain an explicitly adapted policy. | | React, Material UI, and Testing Library conventions apply | Omit irrelevant framework modules and adapt company rules; the styling rule recommends styled-components but does not install it. | | Unit tests use `*.spec.ts(x)` | The framework testing preset covers `.spec` files, while company test overrides also cover `.test`, `__tests__`, and `src/tests`. Align both scopes with the project. | | E2E tests use `src/tests/playwright` or `*.e2e.ts(x)` | Adapt both E2E checks and general test exclusions for other locations. | | Generated files use skeleton paths | Review global ignores and lint command targets. An ignored file receives no checks. | -The architecture rule accepts layout, factory, and independent check options. The -other custom rules have no options. Severity and file scopes can be changed through -flat config. Monorepos need per-package parser projects and scoped -config entries rather than assuming one root `src/` and one `tsconfig.json`. +Architecture rules accept layout options; `client-construction` also accepts factory +names, and the compatibility wrapper retains `checks`. Other custom rules have no +options. Adjust severities and scopes through flat config; monorepos need per-package +parser projects and scoped entries. ### Feature-based layouts @@ -122,30 +122,39 @@ For repositories under `src/data//`, presentation under `src/presentati and multiple composition roots, append an override after the company policy: ```js +const paths = { + presentation: ["src/presentation/**"], + repositories: ["src/data/**/*Repository.ts"], + compositionRoots: [ + "src/presentation/AppCompositionRoot.ts", + "src/presentation/TestCompositionRoot.ts" + ], + apiAdapters: ["src/data/common/utils/api-futures.ts", "src/types/d2-api.ts"] +}; + export default [{ files: ["src/**/*.{ts,tsx}"], rules: { - "eyeseetea/architecture": ["warn", { - paths: { - presentation: ["src/presentation/**"], - repositories: ["src/data/**/*Repository.ts"], - compositionRoots: [ - "src/presentation/AppCompositionRoot.ts", - "src/presentation/TestCompositionRoot.ts" - ], - apiAdapters: ["src/data/common/utils/api-futures.ts"] - }, + "eyeseetea/architecture": "off", + "eyeseetea/layer-dependencies": ["warn", { paths }], + "eyeseetea/http-client-access": ["warn", { paths }], + "eyeseetea/client-construction": ["warn", { + paths, clientFactories: ["createApp", "createTest"] }] } }]; ``` -Replace the example filenames and factory names with actual project names. Add any -client type wrapper to `apiAdapters`; supplied arrays replace defaults. Keep repository -patterns narrow rather than granting client access to all data files. To adopt only -layer checks, set `checks: { httpClientAccess: false, clientConstruction: false }`. -The [policy-only composition](#incorporate-the-configuration) keeps framework presets +Use actual filenames and factories; include client type wrappers in `apiAdapters`. +Supplied arrays replace defaults. Keep repository patterns narrow: they grant client +access. For layer checks only, disable `http-client-access` and `client-construction` +in the final override. Each rule has independent severity and suppressions. + +Existing `eyeseetea/architecture` configurations, including `checks`, remain supported. +Disable individual rules when enabling the wrapper to avoid duplicate reports; +when switching away, update inline suppressions to the responsible rule. +[Policy-only composition](#incorporate-the-configuration) leaves framework presets under the consuming project's control. ## 3. Establish a baseline and adopt in CI @@ -172,6 +181,19 @@ A total warning count alone can miss a new violation when an old one is removed. Linting only changed files also reports old findings within those files and can miss dependency changes elsewhere. +### Native baseline alternative (used by this skeleton) + +The [native baseline profile](BASELINE.md) rejects count increases. Copy +`baseline-config.mjs` and `empty-suppressions.json` with the policy, use the profile +last in the root config instead of `eyeseetea-config.ts`, and copy the baseline scripts +from `package.json`. The profile promotes policy warnings without changing scopes or options. + +Review findings before generating **project-specific** `eslint-suppressions.json`; +never copy the skeleton's counts. Require `lint:new` in CI, prune after fixes, and +keep `empty-suppressions.json` as `{}` for unsuppressed `lint:all` inspection. +Matching is by file/rule count: replacing a violation with another in the same bucket +can pass. See the baseline guide for adoption steps and limitations. + ## 4. Harden incrementally Promote one rule or one cleaned scope at a time. Start with checks whose findings diff --git a/eslint/README.md b/eslint/README.md index f316f59..90baf2b 100644 --- a/eslint/README.md +++ b/eslint/README.md @@ -8,7 +8,10 @@ and project-specific overrides. ## Organization `eyeseetea-plugin.ts` exports the custom rules under the `eyeseetea` namespace: -[architecture](rules/architecture/README.md), +[layer-dependencies](rules/layer-dependencies/README.md), +[http-client-access](rules/http-client-access/README.md), +[client-construction](rules/client-construction/README.md), +the [architecture compatibility wrapper](rules/architecture/README.md), [no-collection-mutation](rules/no-collection-mutation/README.md), and [require-future-block-capture](rules/require-future-block-capture/README.md). @@ -17,27 +20,50 @@ Each rule lives in `rules//` with `rule.ts`, `rule.spec.ts`, and rule metadata links to that reference through `meta.docs.url`. Policy integration tests live in `eyeseetea-config.spec.ts`. -`eyeseetea-config.ts` registers the plugin and defines policy severities and file -scopes, including conventions enforced through third-party rules. The root -`eslint.config.mjs` composes these configurations in order: +`eyeseetea-config.ts` registers the plugin and defines policy scopes, options, and +severities, including third-party checks. The root `eslint.config.mjs` composes: - `base-config.mjs`: JavaScript/TypeScript presets, parser setup, ignores, and general overrides. - `react-config.mjs`: React and Hooks presets and project overrides. - `testing-config.mjs`: Testing Library preset and test overrides. -- `eyeseetea-config.ts`: company policy, applied last to override framework defaults. +- `baseline-config.mjs`: company policy promoted to errors, applied last to override framework defaults. -The Future capture rule applies across the root configuration's linted files at -error severity; architecture and collection mutation apply to `src/**/*.{ts,tsx}` -as warnings. +Future capture applies to all linted files; architecture and collection mutation +apply to `src/**/*.{ts,tsx}`. The severities below describe the reusable policy; +the skeleton promotes policy warnings through the [baseline profile](BASELINE.md). + +## Select architecture checks independently + +The three architecture rules have independent severities, options, and suppressions. +Share `paths` across them; pass `clientFactories` only to `client-construction`. +The reusable policy enables all three as warnings. For layer checks only, append: + +```js +export default [{ + rules: { + "eyeseetea/architecture": "off", + "eyeseetea/layer-dependencies": "warn", + "eyeseetea/http-client-access": "off", + "eyeseetea/client-construction": "off" + } +}]; +``` + +The compatibility wrapper retains the original options, including `checks`, and +shares the same implementation. Enable the wrapper or individual rules to avoid +duplicate reports. ## Severity and legacy code -EyeSeeTea additions start as **warnings** because the source rules apply to new code -and explicitly preserve legacy code. `yarn lint` still succeeds with warnings. -Warnings are actionable review feedback for new code, not permission to copy a legacy -pattern. ESLint cannot determine the age of code. Do not use `--max-warnings=0` until -a deliberate migration or baseline mechanism is agreed. Promote individual rules to -errors after their existing findings have been reviewed. +The reusable policy starts additions as **warnings** for gradual legacy adoption. +Review them before promoting rules to errors; warnings do not justify copying legacy +patterns. ESLint cannot determine code age. + +The skeleton's baseline profile promotes policy warnings to errors, preserving +scopes and options, and records accepted file/rule counts in `eslint-suppressions.json`. +`yarn lint` fails on increases or stale counts; `yarn lint:all` shows accepted findings +too. Other framework warnings remain advisory; review them before adding +`--max-warnings=0`. See [BASELINE.md](BASELINE.md) for commands and limitations. Definite safety/correctness checks are **errors**: `no-eval`, `no-implied-eval`, `no-new-func`, `array-callback-return`, and `react-hooks/rules-of-hooks`. @@ -54,7 +80,7 @@ that necessarily implement the abstraction; new business code receives no blanke | --- | --- | --- | | Immutability | `prefer-const`, `no-var`, `no-param-reassign` including properties; local collection mutation rule | Warn. Typed Array/tuple, standard Map/Set mutators; custom methods called `push` are allowed. Arbitrary object mutation, aliasing, and shared-state analysis still require review. | | Type safety | Explicit `any`; type-aware unsafe assignment, argument, call, member access, return, and type assertion rules; restricted `as unknown` and `as Type[]` | Warn. Safe widening and `as const` are allowed. Type guards and `satisfies` are preferred. | -| Layer dependencies | Local architecture rule resolves imports using TypeScript configuration; checks static imports, re-exports, literal dynamic imports and `require` | Warn. Domain → data/UI/platform and data → UI are forbidden; presentation → concrete data is reported. Configurable layout paths. Checks direct dependencies, not transitive architectural purity. | +| Layer dependencies | Layer dependency rule resolves imports using TypeScript configuration; checks static imports, re-exports, literal dynamic imports and `require` | Warn. Domain → data/UI/platform and data → UI are forbidden; presentation → concrete data is reported. Configurable layout paths. Checks direct dependencies, not transitive architectural purity. | | API boundaries | d2-api import boundaries, aliased named `D2Api` construction, HTTP imports and platform HTTP globals | Warn. Repository/client adapter/composition-root imports allowed. By default, named client construction belongs in `getWebappCompositionRoot` in `CompositionRoot.ts`; roots, factory names, and individual architecture checks are configurable. Namespace constructors, indirect factory calls, and nonliteral dynamic imports need review. | | Asynchronous code | Promise value/type references in domain/data; production `toPromise()` calls; existing Future capture rule | Warn, except capture errors. Tests allow Promises and `toPromise`. `Future.block` async callbacks remain valid. Inferred Promise returns and APIs exposed through aliases are not fully covered. | | React styling and Hooks | Restricted `makeStyles` imports; React Hooks rules | Styling warns; hook correctness errors; dependencies warn. Styling namespace imports and component-vs-hook responsibilities need review. | diff --git a/eslint/baseline-config.mjs b/eslint/baseline-config.mjs new file mode 100644 index 0000000..434e84b --- /dev/null +++ b/eslint/baseline-config.mjs @@ -0,0 +1,13 @@ +import eyeseeteaConfig from "./eyeseetea-config.ts"; + +// Native suppressions only apply to errors. Keep reusable policy defaults intact, +// preserving each block's file scope, exclusions, plugins, and rule options. +export default eyeseeteaConfig.map(config => ({ + ...config, + rules: Object.fromEntries( + Object.entries(config.rules ?? {}).map(([name, setting]) => { + const [severity, ...options] = Array.isArray(setting) ? setting : [setting]; + return [name, [severity === "warn" || severity === 1 ? "error" : severity, ...options]]; + }) + ), +})); diff --git a/eslint/baseline.spec.mjs b/eslint/baseline.spec.mjs new file mode 100644 index 0000000..51cd0ef --- /dev/null +++ b/eslint/baseline.spec.mjs @@ -0,0 +1,66 @@ +import path from "node:path"; +import { expect, test } from "vitest"; + +// The application Vite config aliases stdlib imports to browser shims. +const { spawnSync } = globalThis.process.getBuiltinModule("child_process"); +const { createRequire } = globalThis.process.getBuiltinModule("module"); +const { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } = + globalThis.process.getBuiltinModule("fs"); +const { tmpdir } = globalThis.process.getBuiltinModule("os"); +const require = createRequire(path.join(globalThis.process.cwd(), "package.json")); +const cli = path.join(path.dirname(require.resolve("eslint/package.json")), "bin/eslint.js"); +const { scripts } = JSON.parse( + readFileSync(path.join(globalThis.process.cwd(), "package.json"), "utf8") +); + +test("native baseline commands enforce accepted counts and prune resolved debt", () => { + const cwd = mkdtempSync(path.join(tmpdir(), "eslint-baseline-")); + const write = (filename, content) => writeFileSync(path.join(cwd, filename), content); + const run = name => { + const [executable, ...args] = scripts[name].split(/\s+/); + expect(executable).toBe("eslint"); + const result = spawnSync(globalThis.process.execPath, [cli, ...args], { + cwd, + encoding: "utf8", + }); + if (result.error) throw result.error; + return result; + }; + try { + mkdirSync(path.join(cwd, "src")); + mkdirSync(path.join(cwd, "eslint")); + write("eslint/empty-suppressions.json", "{}\n"); + write("eslint.config.mjs", 'export default [{ rules: { "no-var": "error" } }];\n'); + write("src/legacy.js", "var legacy = 1;\n"); + + // A missing committed baseline must fail rather than disable enforcement. + expect(run("lint:new").status).toBe(2); + expect(run("lint:baseline").status).toBe(0); + const baseline = readFileSync(path.join(cwd, "eslint-suppressions.json"), "utf8"); + expect(JSON.parse(baseline)["src/legacy.js"]["no-var"].count).toBe(1); + expect(run("lint:new").status).toBe(0); + expect(run("lint:all").status).toBe(1); + expect(readFileSync(path.join(cwd, "eslint-suppressions.json"), "utf8")).toBe(baseline); + + write("src/legacy.js", "var legacy = 1; var additional = 2;\n"); + expect(run("lint:new").status).toBe(1); + expect(run("lint:baseline:prune").status).toBe(1); + expect(readFileSync(path.join(cwd, "eslint-suppressions.json"), "utf8")).toBe(baseline); + + // Native matching is intentionally by count, not by violation identity. + write("src/legacy.js", "var replacement = 2;\n"); + expect(run("lint:new").status).toBe(0); + write("src/new.js", "var introduced = 3;\n"); + expect(run("lint:new").status).toBe(1); + write("src/new.js", "const introduced = 3;\n"); + write("src/legacy.js", "const replacement = 2;\n"); + expect(run("lint:new").status).toBe(2); + expect(run("lint:baseline:prune").status).toBe(0); + expect( + JSON.parse(readFileSync(path.join(cwd, "eslint-suppressions.json"), "utf8")) + ).toEqual({}); + expect(run("lint:new").status).toBe(0); + } finally { + rmSync(cwd, { recursive: true, force: true }); + } +}, 20000); diff --git a/eslint/empty-suppressions.json b/eslint/empty-suppressions.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/eslint/empty-suppressions.json @@ -0,0 +1 @@ +{} diff --git a/eslint/eyeseetea-config.spec.ts b/eslint/eyeseetea-config.spec.ts index 277954f..d8869ca 100644 --- a/eslint/eyeseetea-config.spec.ts +++ b/eslint/eyeseetea-config.spec.ts @@ -77,26 +77,40 @@ describe("effective EyeSeeTea configuration", () => { expect(config!.plugins).not.toHaveProperty("company"); expect(config!.plugins).not.toHaveProperty("local"); if (filename.startsWith("src/")) { - expect(config?.rules?.["eyeseetea/architecture"]).toEqual( - expect.arrayContaining([1]) - ); + for (const rule of [ + "layer-dependencies", + "http-client-access", + "client-construction", + ]) { + expect(config?.rules?.[`eyeseetea/${rule}`]).toEqual( + expect.arrayContaining([2]) + ); + } + expect(config?.rules?.["eyeseetea/architecture"]).toBeUndefined(); expect(config?.rules?.["eyeseetea/no-collection-mutation"]).toEqual( - expect.arrayContaining([1]) + expect.arrayContaining([2]) ); } else { - expect(config!.rules!["eyeseetea/architecture"]).toBeUndefined(); + for (const rule of [ + "architecture", + "layer-dependencies", + "http-client-access", + "client-construction", + ]) { + expect(config!.rules![`eyeseetea/${rule}`]).toBeUndefined(); + } expect(config!.rules!["eyeseetea/no-collection-mutation"]).toBeUndefined(); } } }); - test("styling is a warning and dangerous evaluation is an error", async () => { + test("baseline policy promotes styling while preserving correctness errors", async () => { const messages = await policyMessages( "import { makeStyles } from '@material-ui/core'; eval('code');", "src/webapp/components/share/Share.tsx" ); expect(messages).toEqual( expect.arrayContaining([ - expect.objectContaining({ ruleId: "no-restricted-imports", severity: 1 }), + expect.objectContaining({ ruleId: "no-restricted-imports", severity: 2 }), expect.objectContaining({ ruleId: "no-eval", severity: 2 }), ]) ); @@ -139,7 +153,7 @@ describe("effective EyeSeeTea configuration", () => { ) ).toEqual([]); }); - test("accessible E2E queries pass while CSS and test IDs warn", async () => { + test("accessible E2E queries pass while CSS and test IDs fail", async () => { const config = await new ESLint().calculateConfigForFile( "src/tests/playwright/probe.e2e.ts" ); @@ -153,6 +167,6 @@ describe("effective EyeSeeTea configuration", () => { ] ); expect(result).toHaveLength(4); - expect(result.every(message => message.severity === 1)).toBe(true); + expect(result.every(message => message.severity === 2)).toBe(true); }); }); diff --git a/eslint/eyeseetea-config.ts b/eslint/eyeseetea-config.ts index ebea1d6..980257f 100644 --- a/eslint/eyeseetea-config.ts +++ b/eslint/eyeseetea-config.ts @@ -36,7 +36,9 @@ export default [ { files: ["src/**/*.{ts,tsx}"], rules: { - "eyeseetea/architecture": "warn", + "eyeseetea/layer-dependencies": "warn", + "eyeseetea/http-client-access": "warn", + "eyeseetea/client-construction": "warn", "eyeseetea/no-collection-mutation": "warn", "prefer-const": "warn", "no-var": "warn", diff --git a/eslint/eyeseetea-plugin.ts b/eslint/eyeseetea-plugin.ts index a6f06ee..9fa0096 100644 --- a/eslint/eyeseetea-plugin.ts +++ b/eslint/eyeseetea-plugin.ts @@ -1,4 +1,7 @@ import type { TSESLint } from "@typescript-eslint/utils"; +import layerDependencies from "./rules/layer-dependencies/rule.ts"; +import httpClientAccess from "./rules/http-client-access/rule.ts"; +import clientConstruction from "./rules/client-construction/rule.ts"; import architecture from "./rules/architecture/rule.ts"; import noCollectionMutation from "./rules/no-collection-mutation/rule.ts"; import requireFutureBlockCapture from "./rules/require-future-block-capture/rule.ts"; @@ -6,6 +9,9 @@ import requireFutureBlockCapture from "./rules/require-future-block-capture/rule export default { rules: { architecture, + "layer-dependencies": layerDependencies, + "http-client-access": httpClientAccess, + "client-construction": clientConstruction, "no-collection-mutation": noCollectionMutation, "require-future-block-capture": requireFutureBlockCapture, }, diff --git a/eslint/rules/architecture/README.md b/eslint/rules/architecture/README.md index acca1ec..c1def9d 100644 --- a/eslint/rules/architecture/README.md +++ b/eslint/rules/architecture/README.md @@ -1,7 +1,11 @@ # eyeseetea/architecture -Enforce Clean Architecture dependency directions and DHIS2 client boundaries. -Enabled as a warning for `src/**/*.{ts,tsx}` by the EyeSeeTea config. +Compatibility wrapper enforcing the combined checks of +[layer-dependencies](../layer-dependencies/README.md), +[http-client-access](../http-client-access/README.md), and +[client-construction](../client-construction/README.md), with unchanged options. +The reusable company policy enables those rules individually as warnings; +disable them when enabling this wrapper to avoid duplicate reports. ## Rule Details diff --git a/eslint/rules/architecture/rule.spec.ts b/eslint/rules/architecture/rule.spec.ts index e5c71c9..bd641de 100644 --- a/eslint/rules/architecture/rule.spec.ts +++ b/eslint/rules/architecture/rule.spec.ts @@ -6,13 +6,15 @@ import { TSESLint } from "@typescript-eslint/utils"; const { Linter } = TSESLint; import { parser } from "typescript-eslint"; import { afterAll, beforeAll, describe, expect, test } from "vitest"; -import architecture, { type ArchitectureOptions } from "./rule"; +import type { ArchitectureOptions } from "./rule"; +import plugin from "../../eyeseetea-plugin.ts"; function lintArchitecture( code: string, filename = "src/domain/entities/PolicyProbe.ts", options: ArchitectureOptions = {}, - cwd = globalThis.process.cwd() + cwd = globalThis.process.cwd(), + independent = false ) { return new Linter({ cwd }).verify( code, @@ -20,8 +22,28 @@ function lintArchitecture( { files: ["**/*.ts"], languageOptions: { parser }, - plugins: { eyeseetea: { rules: { architecture } } }, - rules: { "eyeseetea/architecture": ["warn", options] }, + plugins: { eyeseetea: plugin }, + rules: independent + ? { + "eyeseetea/layer-dependencies": [ + options.checks?.layerDependencies === false ? "off" : "warn", + { ...(options.paths ? { paths: options.paths } : {}) }, + ], + "eyeseetea/http-client-access": [ + options.checks?.httpClientAccess === false ? "off" : "warn", + { ...(options.paths ? { paths: options.paths } : {}) }, + ], + "eyeseetea/client-construction": [ + options.checks?.clientConstruction === false ? "off" : "warn", + { + ...(options.paths ? { paths: options.paths } : {}), + ...(options.clientFactories + ? { clientFactories: options.clientFactories } + : {}), + }, + ], + } + : { "eyeseetea/architecture": ["warn", options] }, }, ], { filename: path.resolve(cwd, filename) } @@ -228,4 +250,27 @@ describe("alternative architecture layout", () => { lint("", "src/domain/Probe.ts", { checks: { typo: false } } as ArchitectureOptions) ).toThrow(); }); + test.each([ + ["import '@/presentation/View'; fetch('/api');", "src/domain/Probe.ts"], + ["import '@/presentation/View';", "src/data/users/Probe.ts"], + [ + "import '@/data/users/UserRepository'; import { D2Api } from '@eyeseetea/d2-api'; new D2Api();", + "src/presentation/View.ts", + ], + [ + "import { D2Api } from '@eyeseetea/d2-api'; new D2Api(); fetch('/api');", + "src/data/users/UserRepository.ts", + ], + [ + "import '@/data/users/UserRepository'; import { D2Api } from '@eyeseetea/d2-api'; const createApp = () => new D2Api();", + "src/presentation/AppCompositionRoot.ts", + ], + ])("wrapper matches independently enabled rules: %s", (code, filename) => { + const combined = lintArchitecture(code, filename, options, cwd); + const separate = lintArchitecture(code, filename, options, cwd, true); + const diagnostics = (messages: typeof combined) => + messages.map(({ ruleId: _ruleId, ...message }) => message); + expect(diagnostics(separate)).toEqual(diagnostics(combined)); + expect(separate.every(message => message.ruleId !== "eyeseetea/architecture")).toBe(true); + }); }); diff --git a/eslint/rules/architecture/rule.ts b/eslint/rules/architecture/rule.ts index f940ebb..5ed9cf8 100644 --- a/eslint/rules/architecture/rule.ts +++ b/eslint/rules/architecture/rule.ts @@ -1,302 +1,8 @@ -import path from "node:path"; -import ts from "typescript"; -import { ESLintUtils, type TSESTree, type TSESLint } from "@typescript-eslint/utils"; - -const platformGlobals = new Set([ - "window", - "document", - "File", - "FileReader", - "Blob", - "HTMLElement", - "localStorage", - "sessionStorage", - "navigator", - "fetch", - "XMLHttpRequest", -]); -const httpPackages = /^(axios|node-fetch|cross-fetch|undici|got|ky)(\/|$)/; -const infrastructurePackages = - /^(react|react-dom|@material-ui\/|@mui\/|@dhis2\/|@eyeseetea\/d2-api|axios|node-fetch|node:|fs$|fs\/|path$|http$|https$)/; -const normalize = (value: string) => value.replaceAll("\\", "/"); - -export type ArchitectureOptions = { - paths?: Partial< - Record< - | "domain" - | "data" - | "presentation" - | "repositories" - | "compositionRoots" - | "apiAdapters", - string[] - > - >; - clientFactories?: string[]; - checks?: { - layerDependencies?: boolean; - httpClientAccess?: boolean; - clientConstruction?: boolean; - }; -}; - -const defaultPaths = { - domain: ["src/domain/**"], - data: ["src/data/**"], - presentation: ["src/webapp/**", "src/scripts/**"], - repositories: ["src/data/repositories/**"], - compositionRoots: ["src/CompositionRoot.ts"], - apiAdapters: ["src/types/d2-api.ts", "src/data/api-futures.ts"], -}; - -// Project-relative globs support *, **, and ?. **/ also matches zero directories. -function compileGlob(pattern: string): RegExp { - const normalized = normalize(pattern).replace(/^\.\//, ""); - let expression = "^"; - for (let index = 0; index < normalized.length; index++) { - const char = normalized[index]!; - if (char === "*" && normalized[index + 1] === "*") { - index++; - if (normalized[index + 1] === "/") { - expression += "(?:.*/)?"; - index++; - } else expression += ".*"; - } else if (char === "*") expression += "[^/]*"; - else if (char === "?") expression += "[^/]"; - else expression += char.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - } - return new RegExp(expression + "$"); -} - -export default ESLintUtils.RuleCreator( - name => - `https://github.com/EyeSeeTea/dhis2-app-skeleton/blob/master/eslint/rules/${name}/README.md` -)({ - name: "architecture", - defaultOptions: [{} as ArchitectureOptions], - meta: { - type: "problem", - docs: { - description: - "Check Clean Architecture dependency directions and DHIS2 client boundaries.", - }, - schema: [ - { - type: "object", - additionalProperties: false, - properties: { - paths: { - type: "object", - additionalProperties: false, - properties: Object.fromEntries( - Object.keys(defaultPaths).map(key => [ - key, - { - type: "array", - items: { type: "string", minLength: 1 }, - uniqueItems: true, - }, - ]) - ), - }, - clientFactories: { - type: "array", - items: { type: "string", minLength: 1 }, - uniqueItems: true, - }, - checks: { - type: "object", - additionalProperties: false, - properties: { - layerDependencies: { type: "boolean" }, - httpClientAccess: { type: "boolean" }, - clientConstruction: { type: "boolean" }, - }, - }, - }, - }, - ], - messages: { - boundary: "{{message}}", - }, - }, - create(context, [configuration]) { - const paths = { ...defaultPaths, ...configuration.paths }; - const patterns = Object.fromEntries( - Object.entries(paths).map(([key, globs]) => [key, globs.map(compileGlob)]) - ); - const matches = (key: keyof typeof defaultPaths, filename: string) => - patterns[key]!.some(pattern => - pattern.test(normalize(path.relative(context.cwd, filename))) - ); - const filename = context.filename; - // Roots and adapters are infrastructure exceptions even when nested in a layer. - const root = matches("compositionRoots", filename); - const apiAdapter = matches("apiAdapters", filename); - const domain = !root && !apiAdapter && matches("domain", filename); - const data = !root && !apiAdapter && matches("data", filename); - const repository = matches("repositories", filename); - const presentation = !root && !apiAdapter && matches("presentation", filename); - const factories = configuration.clientFactories ?? ["getWebappCompositionRoot"]; - const checks = { - layerDependencies: true, - httpClientAccess: true, - clientConstruction: true, - ...configuration.checks, - }; - const sourceCode = context.sourceCode; - const program = sourceCode.parserServices?.program; - const configFile = !program && ts.findConfigFile(context.cwd, ts.sys.fileExists); - const parsedConfig = configFile - ? ts.readConfigFile(configFile, ts.sys.readFile) - : undefined; - const options = - program?.getCompilerOptions() ?? - (configFile && !parsedConfig?.error - ? ts.parseJsonConfigFileContent( - parsedConfig?.config, - ts.sys, - path.dirname(configFile) - ).options - : { baseUrl: path.join(context.cwd, "src"), paths: { "$/*": ["./*"] } }); - const report = (node: TSESTree.Node, message: string) => - context.report({ node, messageId: "boundary", data: { message } }); - function checkImport(node: TSESTree.Node, source: unknown) { - if (typeof source !== "string") return; - const resolved = ts.resolveModuleName( - source, - context.filename, - options, - ts.sys - ).resolvedModule; - const target = resolved?.resolvedFileName; - const targetMatches = (key: keyof typeof defaultPaths) => - target !== undefined && matches(key, target); - const boundary = (layer: string, destination: string) => - report( - node, - `${layer} must not import ${destination} through '${source}'${target ? ` (resolved to ${normalize(path.relative(context.cwd, target))})` : ""}.` - ); - if (checks.layerDependencies) { - if ( - domain && - (targetMatches("data") || - targetMatches("presentation") || - targetMatches("compositionRoots") || - targetMatches("apiAdapters")) - ) - boundary("Domain", "data, presentation, or infrastructure adapters"); - else if ( - data && - (targetMatches("presentation") || targetMatches("compositionRoots")) - ) - boundary("Data", "presentation or composition roots"); - if (presentation && targetMatches("data")) - boundary("Presentation", "data implementations"); - } - if (checks.httpClientAccess) { - if (domain && (httpPackages.test(source) || infrastructurePackages.test(source))) - boundary("Domain", "platform infrastructure"); - else if ((repository || presentation) && httpPackages.test(source)) - boundary( - repository ? "Repositories" : "Presentation", - "HTTP clients; access HTTP through d2-api repositories" - ); - if ( - !domain && - !repository && - !root && - !apiAdapter && - (/^@eyeseetea\/d2-api(\/|$)/.test(source) || targetMatches("apiAdapters")) - ) - boundary( - "This file", - "DHIS2 clients or API adapters; keep them in repositories, composition roots, or adapters" - ); - } - } - return { - ImportDeclaration(node) { - checkImport(node, node.source.value); - }, - ExportNamedDeclaration(node) { - if (node.source) checkImport(node, node.source.value); - }, - ExportAllDeclaration(node) { - checkImport(node, node.source.value); - }, - ImportExpression(node) { - if (node.source.type === "Literal") checkImport(node, node.source.value); - }, - CallExpression(node) { - if ( - node.callee.type === "Identifier" && - node.callee.name === "require" && - node.arguments[0]?.type === "Literal" - ) - checkImport(node, node.arguments[0].value); - }, - NewExpression(node) { - if (!checks.clientConstruction || node.callee.type !== "Identifier") return; - let scope: TSESLint.Scope.Scope | null = sourceCode.getScope(node); - let variable; - while (scope && !variable) { - variable = scope.set.get(node.callee.name); - scope = scope.upper; - } - const importedApi = variable?.defs.some( - def => - def.type === "ImportBinding" && - def.node.type === "ImportSpecifier" && - def.node.imported.type === "Identifier" && - def.node.imported.name === "D2Api" - ); - if (!importedApi) return; - const inFactory = sourceCode.getAncestors(node).some(ancestor => { - if (ancestor.type === "FunctionDeclaration") - return ancestor.id && factories.includes(ancestor.id.name); - if ( - ancestor.type !== "ArrowFunctionExpression" && - ancestor.type !== "FunctionExpression" - ) - return false; - const parent = ancestor.parent; - return ( - parent?.type === "VariableDeclarator" && - parent.id.type === "Identifier" && - factories.includes(parent.id.name) - ); - }); - if (!root || !inFactory) - report( - node, - `Instantiate D2Api only inside a configured client factory (${factories.join(", ") || "none"}) in a configured composition root.` - ); - }, - "Program:exit"() { - if (!checks.httpClientAccess) return; - for (const scope of sourceCode.scopeManager?.scopes ?? []) { - for (const reference of scope.references) { - if (reference.resolved?.defs.length) continue; - const name = reference.identifier.name; - if (domain && platformGlobals.has(name)) - report( - reference.identifier, - "Domain must not access runtime platform APIs." - ); - else if (repository && ["fetch", "XMLHttpRequest"].includes(name)) - report( - reference.identifier, - "Repositories access HTTP through d2-api." - ); - else if (presentation && ["fetch", "XMLHttpRequest"].includes(name)) - report( - reference.identifier, - "Move data access to a repository and call a composition-root use case." - ); - } - } - }, - }; - }, -}); +import { createArchitectureRule } from "./shared.ts"; +export type { ArchitectureOptions } from "./shared.ts"; + +// Compatibility wrapper for configurations that enable the original combined rule. +export default createArchitectureRule( + "architecture", + "Check Clean Architecture dependency directions and DHIS2 client boundaries." +); diff --git a/eslint/rules/architecture/shared.ts b/eslint/rules/architecture/shared.ts new file mode 100644 index 0000000..98f1f40 --- /dev/null +++ b/eslint/rules/architecture/shared.ts @@ -0,0 +1,324 @@ +import path from "node:path"; +import ts from "typescript"; +import { ESLintUtils, type TSESTree, type TSESLint } from "@typescript-eslint/utils"; + +const platformGlobals = new Set([ + "window", + "document", + "File", + "FileReader", + "Blob", + "HTMLElement", + "localStorage", + "sessionStorage", + "navigator", + "fetch", + "XMLHttpRequest", +]); +const httpPackages = /^(axios|node-fetch|cross-fetch|undici|got|ky)(\/|$)/; +const infrastructurePackages = + /^(react|react-dom|@material-ui\/|@mui\/|@dhis2\/|@eyeseetea\/d2-api|axios|node-fetch|node:|fs$|fs\/|path$|http$|https$)/; +const normalize = (value: string) => value.replaceAll("\\", "/"); + +export type ArchitectureOptions = { + paths?: Partial< + Record< + | "domain" + | "data" + | "presentation" + | "repositories" + | "compositionRoots" + | "apiAdapters", + string[] + > + >; + clientFactories?: string[]; + checks?: { + layerDependencies?: boolean; + httpClientAccess?: boolean; + clientConstruction?: boolean; + }; +}; + +const defaultPaths = { + domain: ["src/domain/**"], + data: ["src/data/**"], + presentation: ["src/webapp/**", "src/scripts/**"], + repositories: ["src/data/repositories/**"], + compositionRoots: ["src/CompositionRoot.ts"], + apiAdapters: ["src/types/d2-api.ts", "src/data/api-futures.ts"], +}; + +// Project-relative globs support *, **, and ?. **/ also matches zero directories. +function compileGlob(pattern: string): RegExp { + const normalized = normalize(pattern).replace(/^\.\//, ""); + let expression = "^"; + for (let index = 0; index < normalized.length; index++) { + const char = normalized[index]!; + if (char === "*" && normalized[index + 1] === "*") { + index++; + if (normalized[index + 1] === "/") { + expression += "(?:.*/)?"; + index++; + } else expression += ".*"; + } else if (char === "*") expression += "[^/]*"; + else if (char === "?") expression += "[^/]"; + else expression += char.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + } + return new RegExp(expression + "$"); +} + +type ArchitectureCheck = NonNullable; + +export function createArchitectureRule( + ruleName: string, + description: string, + check?: keyof ArchitectureCheck +) { + return ESLintUtils.RuleCreator( + name => + `https://github.com/EyeSeeTea/dhis2-app-skeleton/blob/master/eslint/rules/${name}/README.md` + )({ + name: ruleName, + defaultOptions: [{} as ArchitectureOptions], + meta: { + type: "problem", + docs: { + description, + }, + schema: [ + { + type: "object", + additionalProperties: false, + properties: { + paths: { + type: "object", + additionalProperties: false, + properties: Object.fromEntries( + Object.keys(defaultPaths).map(key => [ + key, + { + type: "array", + items: { type: "string", minLength: 1 }, + uniqueItems: true, + }, + ]) + ), + }, + ...(!check || check === "clientConstruction" + ? { + clientFactories: { + type: "array", + items: { type: "string", minLength: 1 }, + uniqueItems: true, + }, + } + : {}), + ...(!check + ? { + checks: { + type: "object", + additionalProperties: false, + properties: { + layerDependencies: { type: "boolean" }, + httpClientAccess: { type: "boolean" }, + clientConstruction: { type: "boolean" }, + }, + }, + } + : {}), + }, + }, + ], + messages: { + boundary: "{{message}}", + }, + }, + create(context, [configuration]) { + const paths = { ...defaultPaths, ...configuration.paths }; + const patterns = Object.fromEntries( + Object.entries(paths).map(([key, globs]) => [key, globs.map(compileGlob)]) + ); + const matches = (key: keyof typeof defaultPaths, filename: string) => + patterns[key]!.some(pattern => + pattern.test(normalize(path.relative(context.cwd, filename))) + ); + const filename = context.filename; + // Roots and adapters are infrastructure exceptions even when nested in a layer. + const root = matches("compositionRoots", filename); + const apiAdapter = matches("apiAdapters", filename); + const domain = !root && !apiAdapter && matches("domain", filename); + const data = !root && !apiAdapter && matches("data", filename); + const repository = matches("repositories", filename); + const presentation = !root && !apiAdapter && matches("presentation", filename); + const factories = configuration.clientFactories ?? ["getWebappCompositionRoot"]; + const checks = { + layerDependencies: !check || check === "layerDependencies", + httpClientAccess: !check || check === "httpClientAccess", + clientConstruction: !check || check === "clientConstruction", + ...configuration.checks, + }; + const sourceCode = context.sourceCode; + const program = sourceCode.parserServices?.program; + const configFile = !program && ts.findConfigFile(context.cwd, ts.sys.fileExists); + const parsedConfig = configFile + ? ts.readConfigFile(configFile, ts.sys.readFile) + : undefined; + const options = + program?.getCompilerOptions() ?? + (configFile && !parsedConfig?.error + ? ts.parseJsonConfigFileContent( + parsedConfig?.config, + ts.sys, + path.dirname(configFile) + ).options + : { baseUrl: path.join(context.cwd, "src"), paths: { "$/*": ["./*"] } }); + const report = (node: TSESTree.Node, message: string) => + context.report({ node, messageId: "boundary", data: { message } }); + function checkImport(node: TSESTree.Node, source: unknown) { + if ( + (!checks.layerDependencies && !checks.httpClientAccess) || + typeof source !== "string" + ) + return; + const resolved = ts.resolveModuleName( + source, + context.filename, + options, + ts.sys + ).resolvedModule; + const target = resolved?.resolvedFileName; + const targetMatches = (key: keyof typeof defaultPaths) => + target !== undefined && matches(key, target); + const boundary = (layer: string, destination: string) => + report( + node, + `${layer} must not import ${destination} through '${source}'${target ? ` (resolved to ${normalize(path.relative(context.cwd, target))})` : ""}.` + ); + if (checks.layerDependencies) { + if ( + domain && + (targetMatches("data") || + targetMatches("presentation") || + targetMatches("compositionRoots") || + targetMatches("apiAdapters")) + ) + boundary("Domain", "data, presentation, or infrastructure adapters"); + else if ( + data && + (targetMatches("presentation") || targetMatches("compositionRoots")) + ) + boundary("Data", "presentation or composition roots"); + if (presentation && targetMatches("data")) + boundary("Presentation", "data implementations"); + } + if (checks.httpClientAccess) { + if ( + domain && + (httpPackages.test(source) || infrastructurePackages.test(source)) + ) + boundary("Domain", "platform infrastructure"); + else if ((repository || presentation) && httpPackages.test(source)) + boundary( + repository ? "Repositories" : "Presentation", + "HTTP clients; access HTTP through d2-api repositories" + ); + if ( + !domain && + !repository && + !root && + !apiAdapter && + (/^@eyeseetea\/d2-api(\/|$)/.test(source) || targetMatches("apiAdapters")) + ) + boundary( + "This file", + "DHIS2 clients or API adapters; keep them in repositories, composition roots, or adapters" + ); + } + } + return { + ImportDeclaration(node) { + checkImport(node, node.source.value); + }, + ExportNamedDeclaration(node) { + if (node.source) checkImport(node, node.source.value); + }, + ExportAllDeclaration(node) { + checkImport(node, node.source.value); + }, + ImportExpression(node) { + if (node.source.type === "Literal") checkImport(node, node.source.value); + }, + CallExpression(node) { + if ( + node.callee.type === "Identifier" && + node.callee.name === "require" && + node.arguments[0]?.type === "Literal" + ) + checkImport(node, node.arguments[0].value); + }, + NewExpression(node) { + if (!checks.clientConstruction || node.callee.type !== "Identifier") return; + let scope: TSESLint.Scope.Scope | null = sourceCode.getScope(node); + let variable; + while (scope && !variable) { + variable = scope.set.get(node.callee.name); + scope = scope.upper; + } + const importedApi = variable?.defs.some( + def => + def.type === "ImportBinding" && + def.node.type === "ImportSpecifier" && + def.node.imported.type === "Identifier" && + def.node.imported.name === "D2Api" + ); + if (!importedApi) return; + const inFactory = sourceCode.getAncestors(node).some(ancestor => { + if (ancestor.type === "FunctionDeclaration") + return ancestor.id && factories.includes(ancestor.id.name); + if ( + ancestor.type !== "ArrowFunctionExpression" && + ancestor.type !== "FunctionExpression" + ) + return false; + const parent = ancestor.parent; + return ( + parent?.type === "VariableDeclarator" && + parent.id.type === "Identifier" && + factories.includes(parent.id.name) + ); + }); + if (!root || !inFactory) + report( + node, + `Instantiate D2Api only inside a configured client factory (${factories.join(", ") || "none"}) in a configured composition root.` + ); + }, + "Program:exit"() { + if (!checks.httpClientAccess) return; + for (const scope of sourceCode.scopeManager?.scopes ?? []) { + for (const reference of scope.references) { + if (reference.resolved?.defs.length) continue; + const name = reference.identifier.name; + if (domain && platformGlobals.has(name)) + report( + reference.identifier, + "Domain must not access runtime platform APIs." + ); + else if (repository && ["fetch", "XMLHttpRequest"].includes(name)) + report( + reference.identifier, + "Repositories access HTTP through d2-api." + ); + else if (presentation && ["fetch", "XMLHttpRequest"].includes(name)) + report( + reference.identifier, + "Move data access to a repository and call a composition-root use case." + ); + } + } + }, + }; + }, + }); +} diff --git a/eslint/rules/client-construction/README.md b/eslint/rules/client-construction/README.md new file mode 100644 index 0000000..257e3fb --- /dev/null +++ b/eslint/rules/client-construction/README.md @@ -0,0 +1,36 @@ +# eyeseetea/client-construction + +Restrict imported D2Api construction to configured factories. Enabled as a warning for `src/**/*.{ts,tsx}` by the company policy. + +## Rule Details + +Reports construction of the named imported `D2Api` (including import aliases) +unless both the file is a configured composition root and an enclosing factory has +an allowed name. Supports function declarations and arrow/function expressions +bound to named variables. It does not restrict imports or HTTP access. + +## Options + +```js +"eyeseetea/client-construction": ["warn", { + paths: { compositionRoots: ["src/presentation/AppCompositionRoot.ts"] }, + clientFactories: ["createApp"] +}] +``` + +See [architecture options](../architecture/README.md#options) for `paths` groups, +globs, defaults, and replacement semantics. Roots and adapters override layer membership. +`clientFactories` defaults to `["getWebappCompositionRoot"]` and replaces the list of +allowed names. An empty list permits no construction. + +This rule accepts no `checks` switches; select the rule and its severity directly. + +## Limitations + +Checks direct syntax, not transitive dependencies or whole-program data flow; +see [shared limitations](../architecture/README.md#limitations). + +## When Not To Use It + +Disable if the policy does not apply; adapt paths for other layouts and use narrow, +justified suppressions for exceptions. diff --git a/eslint/rules/client-construction/rule.spec.ts b/eslint/rules/client-construction/rule.spec.ts new file mode 100644 index 0000000..901f444 --- /dev/null +++ b/eslint/rules/client-construction/rule.spec.ts @@ -0,0 +1,44 @@ +import path from "node:path"; +import { TSESLint } from "@typescript-eslint/utils"; +import { parser } from "typescript-eslint"; +import { describe, expect, test } from "vitest"; +import rule from "./rule"; + +describe("client-construction", () => { + test("reports construction without enforcing layer imports or HTTP access", () => { + const messages = new TSESLint.Linter().verify( + "import '$/data/repositories/UserD2Repository'; import { D2Api } from '@eyeseetea/d2-api'; new D2Api(); fetch('/api');", + [ + { + files: ["**/*.ts"], + languageOptions: { parser }, + plugins: { eyeseetea: { rules: { "client-construction": rule } } }, + rules: { "eyeseetea/client-construction": "warn" }, + }, + ], + { filename: path.resolve("src/domain/Probe.ts") } + ); + expect(messages).toHaveLength(1); + expect(messages.every(message => message.ruleId === "eyeseetea/client-construction")).toBe( + true + ); + }); + test("permits construction in the default factory", () => { + const messages = new TSESLint.Linter().verify( + "import { D2Api } from '@eyeseetea/d2-api'; const getWebappCompositionRoot = () => new D2Api();", + [ + { + files: ["**/*.ts"], + languageOptions: { parser }, + plugins: { eyeseetea: { rules: { "client-construction": rule } } }, + rules: { "eyeseetea/client-construction": "warn" }, + }, + ], + { filename: path.resolve("src/CompositionRoot.ts") } + ); + expect(messages).toHaveLength(0); + expect(messages.every(message => message.ruleId === "eyeseetea/client-construction")).toBe( + true + ); + }); +}); diff --git a/eslint/rules/client-construction/rule.ts b/eslint/rules/client-construction/rule.ts new file mode 100644 index 0000000..345ca2b --- /dev/null +++ b/eslint/rules/client-construction/rule.ts @@ -0,0 +1,7 @@ +import { createArchitectureRule } from "../architecture/shared.ts"; + +export default createArchitectureRule( + "client-construction", + "Restrict D2Api construction to configured composition-root factories.", + "clientConstruction" +); diff --git a/eslint/rules/http-client-access/README.md b/eslint/rules/http-client-access/README.md new file mode 100644 index 0000000..b226ef2 --- /dev/null +++ b/eslint/rules/http-client-access/README.md @@ -0,0 +1,39 @@ +# eyeseetea/http-client-access + +Check platform and DHIS2 client access. Enabled as a warning for `src/**/*.{ts,tsx}` by the company policy. + +## Rule Details + +Reports domain platform globals and infrastructure imports, direct HTTP access in +repositories/presentation, and DHIS2 client or adapter imports outside repositories, +composition roots, and adapters. Shadowed platform names and local classes are allowed. +It does not enforce application-layer imports or constructor locations. + +## Options + +```js +"eyeseetea/http-client-access": ["warn", { + paths: { + presentation: ["src/presentation/**"], + repositories: ["src/data/**/*Repository.ts"], + compositionRoots: ["src/presentation/AppCompositionRoot.ts"], + apiAdapters: ["src/data/common/utils/api-futures.ts", "src/types/d2-api.ts"] + } +}] +``` + +See [architecture options](../architecture/README.md#options) for `paths` groups, +globs, defaults, and replacement semantics. Roots and adapters override layer membership. + +This rule accepts no `checks` switches; select the rule and its severity directly. +`clientFactories` applies only to `client-construction` and the compatibility wrapper. + +## Limitations + +Checks direct syntax, not transitive dependencies or whole-program data flow; +see [shared limitations](../architecture/README.md#limitations). + +## When Not To Use It + +Disable if the policy does not apply; adapt paths for other layouts and use narrow, +justified suppressions for exceptions. diff --git a/eslint/rules/http-client-access/rule.spec.ts b/eslint/rules/http-client-access/rule.spec.ts new file mode 100644 index 0000000..1dcee0b --- /dev/null +++ b/eslint/rules/http-client-access/rule.spec.ts @@ -0,0 +1,44 @@ +import path from "node:path"; +import { TSESLint } from "@typescript-eslint/utils"; +import { parser } from "typescript-eslint"; +import { describe, expect, test } from "vitest"; +import rule from "./rule"; + +describe("http-client-access", () => { + test("reports direct HTTP without enforcing layer imports", () => { + const messages = new TSESLint.Linter().verify( + "import '$/data/repositories/UserD2Repository'; fetch('/api');", + [ + { + files: ["**/*.ts"], + languageOptions: { parser }, + plugins: { eyeseetea: { rules: { "http-client-access": rule } } }, + rules: { "eyeseetea/http-client-access": "warn" }, + }, + ], + { filename: path.resolve("src/domain/Probe.ts") } + ); + expect(messages).toHaveLength(1); + expect(messages.every(message => message.ruleId === "eyeseetea/http-client-access")).toBe( + true + ); + }); + test("permits repository client imports and construction", () => { + const messages = new TSESLint.Linter().verify( + "import { D2Api } from '@eyeseetea/d2-api'; new D2Api();", + [ + { + files: ["**/*.ts"], + languageOptions: { parser }, + plugins: { eyeseetea: { rules: { "http-client-access": rule } } }, + rules: { "eyeseetea/http-client-access": "warn" }, + }, + ], + { filename: path.resolve("src/data/repositories/Probe.ts") } + ); + expect(messages).toHaveLength(0); + expect(messages.every(message => message.ruleId === "eyeseetea/http-client-access")).toBe( + true + ); + }); +}); diff --git a/eslint/rules/http-client-access/rule.ts b/eslint/rules/http-client-access/rule.ts new file mode 100644 index 0000000..f483851 --- /dev/null +++ b/eslint/rules/http-client-access/rule.ts @@ -0,0 +1,7 @@ +import { createArchitectureRule } from "../architecture/shared.ts"; + +export default createArchitectureRule( + "http-client-access", + "Check platform APIs, HTTP access, and DHIS2 client import boundaries.", + "httpClientAccess" +); diff --git a/eslint/rules/layer-dependencies/README.md b/eslint/rules/layer-dependencies/README.md new file mode 100644 index 0000000..e2bc5e7 --- /dev/null +++ b/eslint/rules/layer-dependencies/README.md @@ -0,0 +1,37 @@ +# eyeseetea/layer-dependencies + +Check application-layer dependency directions. Enabled as a warning for `src/**/*.{ts,tsx}` by the company policy. + +## Rule Details + +Reports domain imports from data, presentation, composition roots, and API adapters; +data imports from presentation or composition roots; and presentation imports from data. +It resolves imports, re-exports, literal dynamic imports, and literal `require` calls +through TypeScript before matching the target against the configured paths. + +## Options + +```js +"eyeseetea/layer-dependencies": ["warn", { + paths: { + presentation: ["src/presentation/**"], + compositionRoots: ["src/presentation/AppCompositionRoot.ts"] + } +}] +``` + +See [architecture options](../architecture/README.md#options) for `paths` groups, +globs, defaults, and replacement semantics. Roots and adapters override layer membership. + +This rule accepts no `checks` switches; select the rule and its severity directly. +`clientFactories` applies only to `client-construction` and the compatibility wrapper. + +## Limitations + +Checks direct syntax, not transitive dependencies or whole-program data flow; +see [shared limitations](../architecture/README.md#limitations). + +## When Not To Use It + +Disable if the policy does not apply; adapt paths for other layouts and use narrow, +justified suppressions for exceptions. diff --git a/eslint/rules/layer-dependencies/rule.spec.ts b/eslint/rules/layer-dependencies/rule.spec.ts new file mode 100644 index 0000000..e260298 --- /dev/null +++ b/eslint/rules/layer-dependencies/rule.spec.ts @@ -0,0 +1,44 @@ +import path from "node:path"; +import { TSESLint } from "@typescript-eslint/utils"; +import { parser } from "typescript-eslint"; +import { describe, expect, test } from "vitest"; +import rule from "./rule"; + +describe("layer-dependencies", () => { + test("reports layer imports without enforcing client access", () => { + const messages = new TSESLint.Linter().verify( + "import '$/data/repositories/UserD2Repository'; fetch('/api'); import { D2Api } from '@eyeseetea/d2-api'; new D2Api();", + [ + { + files: ["**/*.ts"], + languageOptions: { parser }, + plugins: { eyeseetea: { rules: { "layer-dependencies": rule } } }, + rules: { "eyeseetea/layer-dependencies": "warn" }, + }, + ], + { filename: path.resolve("src/domain/Probe.ts") } + ); + expect(messages).toHaveLength(1); + expect(messages.every(message => message.ruleId === "eyeseetea/layer-dependencies")).toBe( + true + ); + }); + test("does not enforce client construction in repositories", () => { + const messages = new TSESLint.Linter().verify( + "import { D2Api } from '@eyeseetea/d2-api'; new D2Api();", + [ + { + files: ["**/*.ts"], + languageOptions: { parser }, + plugins: { eyeseetea: { rules: { "layer-dependencies": rule } } }, + rules: { "eyeseetea/layer-dependencies": "warn" }, + }, + ], + { filename: path.resolve("src/data/repositories/Probe.ts") } + ); + expect(messages).toHaveLength(0); + expect(messages.every(message => message.ruleId === "eyeseetea/layer-dependencies")).toBe( + true + ); + }); +}); diff --git a/eslint/rules/layer-dependencies/rule.ts b/eslint/rules/layer-dependencies/rule.ts new file mode 100644 index 0000000..bb15d28 --- /dev/null +++ b/eslint/rules/layer-dependencies/rule.ts @@ -0,0 +1,7 @@ +import { createArchitectureRule } from "../architecture/shared.ts"; + +export default createArchitectureRule( + "layer-dependencies", + "Check dependency directions between application layers.", + "layerDependencies" +); diff --git a/package.json b/package.json index 5c64699..228fd4f 100644 --- a/package.json +++ b/package.json @@ -94,7 +94,12 @@ "check": "yarn typecheck && yarn prettify:check && yarn lint && yarn test", "extract-pot": "yarn d2-i18n-extract -p src/ -o i18n/", "generate-docs": "typedoc --entryPointStrategy expand ./src", - "lint": "eslint src", + "lint": "yarn lint:new", + "lint:all": "eslint src --suppressions-location eslint/empty-suppressions.json", + "lint:new": "eslint src --suppressions-location eslint-suppressions.json", + "lint:cached": "yarn lint:new --cache --cache-strategy content", + "lint:baseline": "eslint src --suppressions-location eslint-suppressions.json --suppress-all", + "lint:baseline:prune": "eslint src --suppressions-location eslint-suppressions.json --prune-suppressions", "lint-all": "yarn lint && yarn lint-unused", "lint-unused": "ts-prune --ignore 'ts-utils.ts'", "localize": "yarn update-po && d2-i18n-generate -l -n dhis2-skeleton-app -p ./i18n/ -o ./src/locales/", From b67ec6a2b4e10362ba21fabc4fe4e5634eb79e5c Mon Sep 17 00:00:00 2001 From: Matias Arriola Date: Tue, 13 Oct 2026 12:15:23 -0300 Subject: [PATCH 07/14] Fix architecture boundary and generic collection lint checks --- eslint/rules/architecture/rule.spec.ts | 74 +++++++++++++++++++ eslint/rules/architecture/shared.ts | 63 +++++++++++++--- .../rules/no-collection-mutation/rule.spec.ts | 20 +++++ eslint/rules/no-collection-mutation/rule.ts | 3 +- 4 files changed, 147 insertions(+), 13 deletions(-) diff --git a/eslint/rules/architecture/rule.spec.ts b/eslint/rules/architecture/rule.spec.ts index bd641de..1b8ed2d 100644 --- a/eslint/rules/architecture/rule.spec.ts +++ b/eslint/rules/architecture/rule.spec.ts @@ -193,6 +193,14 @@ describe("alternative architecture layout", () => { ).toHaveLength(1); expect(lint("fetch('/api');", "src/data/users/UserRepository.ts")).toHaveLength(1); }); + test("restricts constructors imported through a configured adapter", () => { + expect( + lint( + "import { D2Api as Client } from '@/data/common/utils/api-futures'; new Client();", + "src/data/users/UserRepository.ts" + ) + ).toHaveLength(1); + }); test("roots override presentation classification and permit named and arrow factories", () => { for (const [filename, factory] of [ ["src/presentation/AppCompositionRoot.ts", "createApp"], @@ -274,3 +282,69 @@ describe("alternative architecture layout", () => { expect(separate.every(message => message.ruleId !== "eyeseetea/architecture")).toBe(true); }); }); + +describe.each([false, true])("boundary regressions (independent rules: %s)", independent => { + const lint = (code: string, filename: string) => + lintArchitecture(code, filename, {}, globalThis.process.cwd(), independent); + + test.each(["window", "globalThis", "self", "globalThis.window"])( + "rejects qualified HTTP through %s in repositories and presentation", + namespace => { + for (const filename of ["src/data/repositories/Probe.ts", "src/webapp/Probe.ts"]) { + expect(lint(`${namespace}.fetch('/api');`, filename)).toHaveLength(1); + expect(lint(`new ${namespace}['XMLHttpRequest']();`, filename)).toHaveLength(1); + } + } + ); + test.each([ + "globalThis.fetch('/api');", + "globalThis['document'].title;", + "self.navigator.language;", + ])("rejects qualified platform access in domain: %s", code => + expect(lint(code, "src/domain/Probe.ts")).toHaveLength(1) + ); + test("allows shadowed global namespaces", () => { + for (const filename of [ + "src/domain/Probe.ts", + "src/data/repositories/Probe.ts", + "src/webapp/Probe.ts", + ]) { + expect( + lint( + "function f(window: any, globalThis: any, self: any) { window.fetch(); globalThis.document; self['XMLHttpRequest'](); }", + filename + ) + ).toEqual([]); + } + }); + test.each(["events", "path/posix", "fs/promises", "node:events", "node:test"])( + "rejects Node builtin imports from domain: %s", + source => expect(lint(`import '${source}';`, "src/domain/Probe.ts")).toHaveLength(1) + ); + test("allows non-builtin packages with similar names", () => { + expect( + lint("import 'events-extra'; import 'path-to-regexp';", "src/domain/Probe.ts") + ).toEqual([]); + }); + test("allows unrelated imports named D2Api, including aliases", () => { + expect( + lint("import { D2Api } from './Unrelated'; new D2Api();", "src/webapp/Probe.ts") + ).toEqual([]); + expect( + lint( + "import { D2Api as Client } from './Unrelated'; new Client();", + "src/webapp/Probe.ts" + ) + ).toEqual([]); + }); + test.each(["@eyeseetea/d2-api", "@eyeseetea/d2-api/2.40", "$/types/d2-api"])( + "still restricts DHIS2 constructor aliases from %s", + source => + expect( + lint( + `import { D2Api as Client } from '${source}'; new Client();`, + "src/data/repositories/Probe.ts" + ) + ).toHaveLength(1) + ); +}); diff --git a/eslint/rules/architecture/shared.ts b/eslint/rules/architecture/shared.ts index 98f1f40..7d17f22 100644 --- a/eslint/rules/architecture/shared.ts +++ b/eslint/rules/architecture/shared.ts @@ -2,6 +2,8 @@ import path from "node:path"; import ts from "typescript"; import { ESLintUtils, type TSESTree, type TSESLint } from "@typescript-eslint/utils"; +const { isBuiltin } = globalThis.process.getBuiltinModule("module"); +const globalNamespaces = new Set(["window", "globalThis", "self"]); const platformGlobals = new Set([ "window", "document", @@ -173,6 +175,16 @@ export function createArchitectureRule( path.dirname(configFile) ).options : { baseUrl: path.join(context.cwd, "src"), paths: { "$/*": ["./*"] } }); + const resolveModule = (source: string) => + ts.resolveModuleName(source, context.filename, options, ts.sys).resolvedModule + ?.resolvedFileName; + const isClientSource = (source: string) => { + const target = resolveModule(source); + return ( + /^@eyeseetea\/d2-api(\/|$)/.test(source) || + (target !== undefined && matches("apiAdapters", target)) + ); + }; const report = (node: TSESTree.Node, message: string) => context.report({ node, messageId: "boundary", data: { message } }); function checkImport(node: TSESTree.Node, source: unknown) { @@ -181,13 +193,7 @@ export function createArchitectureRule( typeof source !== "string" ) return; - const resolved = ts.resolveModuleName( - source, - context.filename, - options, - ts.sys - ).resolvedModule; - const target = resolved?.resolvedFileName; + const target = resolveModule(source); const targetMatches = (key: keyof typeof defaultPaths) => target !== undefined && matches(key, target); const boundary = (layer: string, destination: string) => @@ -215,7 +221,9 @@ export function createArchitectureRule( if (checks.httpClientAccess) { if ( domain && - (httpPackages.test(source) || infrastructurePackages.test(source)) + (httpPackages.test(source) || + infrastructurePackages.test(source) || + isBuiltin(source)) ) boundary("Domain", "platform infrastructure"); else if ((repository || presentation) && httpPackages.test(source)) @@ -270,7 +278,9 @@ export function createArchitectureRule( def.type === "ImportBinding" && def.node.type === "ImportSpecifier" && def.node.imported.type === "Identifier" && - def.node.imported.name === "D2Api" + def.node.imported.name === "D2Api" && + def.parent.type === "ImportDeclaration" && + isClientSource(def.parent.source.value) ); if (!importedApi) return; const inFactory = sourceCode.getAncestors(node).some(ancestor => { @@ -300,17 +310,46 @@ export function createArchitectureRule( for (const reference of scope.references) { if (reference.resolved?.defs.length) continue; const name = reference.identifier.name; - if (domain && platformGlobals.has(name)) + // Resolve qualified globals only when their namespace is unshadowed. + let access: TSESTree.Node = reference.identifier; + let qualifiedName = name; + while ( + globalNamespaces.has(qualifiedName) && + access.parent?.type === "MemberExpression" && + access.parent.object === access + ) { + const member: TSESTree.MemberExpression = access.parent; + const property = member.property; + qualifiedName = + !member.computed && property.type === "Identifier" + ? property.name + : member.computed && + property.type === "Literal" && + typeof property.value === "string" + ? property.value + : ""; + access = member; + } + if ( + domain && + (platformGlobals.has(name) || platformGlobals.has(qualifiedName)) + ) report( reference.identifier, "Domain must not access runtime platform APIs." ); - else if (repository && ["fetch", "XMLHttpRequest"].includes(name)) + else if ( + repository && + ["fetch", "XMLHttpRequest"].includes(qualifiedName) + ) report( reference.identifier, "Repositories access HTTP through d2-api." ); - else if (presentation && ["fetch", "XMLHttpRequest"].includes(name)) + else if ( + presentation && + ["fetch", "XMLHttpRequest"].includes(qualifiedName) + ) report( reference.identifier, "Move data access to a repository and call a composition-root use case." diff --git a/eslint/rules/no-collection-mutation/rule.spec.ts b/eslint/rules/no-collection-mutation/rule.spec.ts index 3779192..dee4c34 100644 --- a/eslint/rules/no-collection-mutation/rule.spec.ts +++ b/eslint/rules/no-collection-mutation/rule.spec.ts @@ -41,6 +41,26 @@ describe("collection mutation", () => { ) ).toHaveLength(4); }); + test.each([ + "export function mutate(xs: T) { xs.push(1); }", + "export function mutate(xs: T) { xs['sort'](); }", + "export function mutate>(xs: T) { xs.set('a', 1); }", + "export function mutate>(xs: T) { xs.add(1); }", + "export function mutate>(xs: T) { if (Array.isArray(xs)) xs.push(1); else xs.add(1); }", + ])("detects constrained generic collection mutation: %s", async code => { + const messages = await lintMutation(code); + expect(messages).toHaveLength(code.includes("Array.isArray") ? 2 : 1); + expect( + messages.every(message => message.ruleId === "eyeseetea/no-collection-mutation") + ).toBe(true); + }); + test("allows custom mutator names on constrained generic types", async () => { + expect( + await lintMutation( + "export function use(custom: T) { custom.push(1); custom.set(1); }" + ) + ).toEqual([]); + }); test("allows immutable transformations and unrelated method names", async () => { expect( await lintMutation( diff --git a/eslint/rules/no-collection-mutation/rule.ts b/eslint/rules/no-collection-mutation/rule.ts index ea7ce06..e5f9ac3 100644 --- a/eslint/rules/no-collection-mutation/rule.ts +++ b/eslint/rules/no-collection-mutation/rule.ts @@ -38,7 +38,8 @@ export default ESLintUtils.RuleCreator( ? member.property.name : null; if (typeof method !== "string") return; - const type = services.getTypeAtLocation(member.object); + const receiverType = services.getTypeAtLocation(member.object); + const type = checker.getBaseConstraintOfType(receiverType) ?? receiverType; const types = type.isUnion() ? type.types : [type]; const mutates = types.some(type => { if (checker.isArrayType(type) || checker.isTupleType(type)) From 4e20c9d70a51222f7af9f3f761c8496dd7dfb65e Mon Sep 17 00:00:00 2001 From: Matias Arriola Date: Tue, 13 Oct 2026 12:50:42 -0300 Subject: [PATCH 08/14] Separate ESLint tooling tests from application tests --- README.md | 5 +++-- eslint/MIGRATION.md | 6 ++++-- eslint/README.md | 4 +++- eslint/baseline.spec.mjs | 10 ++++------ eslint/rules/architecture/rule.spec.ts | 5 ++--- eslint/rules/architecture/shared.ts | 2 +- eslint/vitest.config.mjs | 8 ++++++++ package.json | 3 ++- vite.config.ts | 2 +- 9 files changed, 28 insertions(+), 17 deletions(-) create mode 100644 eslint/vitest.config.mjs diff --git a/README.md b/README.md index 87dfa60..f6feb94 100644 --- a/README.md +++ b/README.md @@ -55,11 +55,12 @@ Run all code-quality to validate changes: $ yarn run check ``` -This runs the TypeScript typecheck, Prettier check, lint, and tests. +This runs the TypeScript typecheck, Prettier check, lint, application tests, and ESLint tooling tests. The [EyeSeeTea ESLint policy](eslint/README.md) documents enforced conventions, warning/error levels, legacy-code rollout, justified exceptions, and practices that still require review. -Individual checks can also be run with `yarn typecheck`, `yarn prettify:check`, `yarn lint`, and `yarn test`. +Individual checks: `yarn typecheck`, `yarn prettify:check`, `yarn lint`, +`yarn test` (application), and `yarn test:eslint` (ESLint tooling). Lint uses a committed [ESLint baseline](eslint/BASELINE.md): `yarn lint:new` rejects errors above accepted legacy counts; `yarn lint:all` shows the backlog. Use diff --git a/eslint/MIGRATION.md b/eslint/MIGRATION.md index c3dd4b9..188889d 100644 --- a/eslint/MIGRATION.md +++ b/eslint/MIGRATION.md @@ -19,8 +19,10 @@ revision when updating; keep project overrides separate from copied policy files | Selected custom rules | `eslint/eyeseetea-plugin.ts` and `eslint/rules/` | A project whose architecture or Promise conventions differ | Keep rule documentation with the implementation. If copying policy regression tests, -adapt their fixture paths and test runner setup: they currently use Vitest and actual -skeleton source paths. Do not expect them to run unchanged in another application. +adapt their fixture paths and test runner setup: they use Vitest with a dedicated +Node configuration (`eslint/vitest.config.mjs`) and actual skeleton source paths. +Copy the `test:eslint` script and require it alongside application tests in CI; +do not expect fixtures to run unchanged in another application. ### Runtime and dependencies diff --git a/eslint/README.md b/eslint/README.md index 90baf2b..8e394ee 100644 --- a/eslint/README.md +++ b/eslint/README.md @@ -112,7 +112,9 @@ instructions; they cannot replace them. ## Verification -`yarn test` includes the EyeSeeTea policy regression tests as well as application tests. +`yarn test` / `yarn test:unit` runs application tests; `yarn test:eslint` runs policy, +rule, and baseline regression tests through `eslint/vitest.config.mjs` in Node, +without React setup or browser polyfills. `yarn check` requires both suites. `yarn lint` applies the EyeSeeTea policy to application TypeScript. Rule tests exercise both positive and negative examples, including aliases, relative imports, legacy interop exclusions, and legitimate similarly named methods. diff --git a/eslint/baseline.spec.mjs b/eslint/baseline.spec.mjs index 51cd0ef..b8bfae8 100644 --- a/eslint/baseline.spec.mjs +++ b/eslint/baseline.spec.mjs @@ -1,12 +1,10 @@ import path from "node:path"; import { expect, test } from "vitest"; -// The application Vite config aliases stdlib imports to browser shims. -const { spawnSync } = globalThis.process.getBuiltinModule("child_process"); -const { createRequire } = globalThis.process.getBuiltinModule("module"); -const { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } = - globalThis.process.getBuiltinModule("fs"); -const { tmpdir } = globalThis.process.getBuiltinModule("os"); +import { spawnSync } from "node:child_process"; +import { createRequire } from "node:module"; +import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; const require = createRequire(path.join(globalThis.process.cwd(), "package.json")); const cli = path.join(path.dirname(require.resolve("eslint/package.json")), "bin/eslint.js"); const { scripts } = JSON.parse( diff --git a/eslint/rules/architecture/rule.spec.ts b/eslint/rules/architecture/rule.spec.ts index 1b8ed2d..217b10f 100644 --- a/eslint/rules/architecture/rule.spec.ts +++ b/eslint/rules/architecture/rule.spec.ts @@ -1,7 +1,6 @@ import path from "node:path"; -// Access real Node modules because the app build aliases stdlib imports to browser shims. -const fs = globalThis.process.getBuiltinModule("fs"); -const os = globalThis.process.getBuiltinModule("os"); +import * as fs from "node:fs"; +import * as os from "node:os"; import { TSESLint } from "@typescript-eslint/utils"; const { Linter } = TSESLint; import { parser } from "typescript-eslint"; diff --git a/eslint/rules/architecture/shared.ts b/eslint/rules/architecture/shared.ts index 7d17f22..e4e4c7a 100644 --- a/eslint/rules/architecture/shared.ts +++ b/eslint/rules/architecture/shared.ts @@ -1,8 +1,8 @@ import path from "node:path"; +import { isBuiltin } from "node:module"; import ts from "typescript"; import { ESLintUtils, type TSESTree, type TSESLint } from "@typescript-eslint/utils"; -const { isBuiltin } = globalThis.process.getBuiltinModule("module"); const globalNamespaces = new Set(["window", "globalThis", "self"]); const platformGlobals = new Set([ "window", diff --git a/eslint/vitest.config.mjs b/eslint/vitest.config.mjs new file mode 100644 index 0000000..469d913 --- /dev/null +++ b/eslint/vitest.config.mjs @@ -0,0 +1,8 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + environment: "node", + include: ["eslint/**/*.spec.{ts,tsx,mjs}"], + }, +}); diff --git a/package.json b/package.json index 228fd4f..1e9b3d4 100644 --- a/package.json +++ b/package.json @@ -91,7 +91,7 @@ "build": "yarn localize && VITE_DHIS2_BASE_URL='' VITE_DHIS2_AUTH='' yarn build-folder && rm -f $npm_package_name.zip && cd build && zip --quiet -r ../$npm_package_name.zip *", "build-dependencies-visualizer": "vite-bundle-visualizer", "build-folder": "rm -rf build/ && d2-manifest package.json manifest.webapp && tsc && vite build --outDir=build && yarn run manifest && cp -r i18n icon.png build", - "check": "yarn typecheck && yarn prettify:check && yarn lint && yarn test", + "check": "yarn typecheck && yarn prettify:check && yarn lint && yarn test && yarn test:eslint", "extract-pot": "yarn d2-i18n-extract -p src/ -o i18n/", "generate-docs": "typedoc --entryPointStrategy expand ./src", "lint": "yarn lint:new", @@ -112,6 +112,7 @@ "source-map-explorer": "yarn build --sourcemap=true && source-map-explorer --no-border-checks --only-mapped build/assets/*js", "start": "vite --strictPort", "test": "yarn test:unit", + "test:eslint": "vitest run --config eslint/vitest.config.mjs", "test:unit": "vitest run", "test:unit:watch": "vitest watch", "typecheck": "tsc --noEmit", diff --git a/vite.config.ts b/vite.config.ts index cd627ec..db3bca5 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -31,7 +31,7 @@ export default ({ mode }): UserConfig => { ], test: { environment: "jsdom", - include: ["**/*.spec.{ts,tsx,mjs}"], + include: ["src/**/*.spec.{ts,tsx,mjs}"], setupFiles: "./src/tests/setup.ts", exclude: ["**/node_modules/**", "**/src/tests/playwright/**"], globals: true, From c0a7367b805c28ca87f0e1ae7dd070819c29a6d8 Mon Sep 17 00:00:00 2001 From: Matias Arriola Date: Tue, 13 Oct 2026 13:00:01 -0300 Subject: [PATCH 09/14] Document external API exceptions for HTTP access rule --- eslint/rules/architecture/README.md | 4 ++++ eslint/rules/architecture/shared.ts | 11 +++++++---- eslint/rules/http-client-access/README.md | 13 +++++++++++++ 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/eslint/rules/architecture/README.md b/eslint/rules/architecture/README.md index c1def9d..bdc40b0 100644 --- a/eslint/rules/architecture/README.md +++ b/eslint/rules/architecture/README.md @@ -115,3 +115,7 @@ nonliteral imports, namespace constructors, and indirect factories require revie Configure paths and checks for a different directory structure or architecture. For a justified exception, use a narrow suppression with an explanation. +External API repositories may need an HTTP exception; see +[external API guidance](../http-client-access/README.md#when-not-to-use-it). +Suppressing this wrapper also disables its layer and client-construction checks; +use the individual rules when those checks should remain enabled. diff --git a/eslint/rules/architecture/shared.ts b/eslint/rules/architecture/shared.ts index e4e4c7a..e0ac1a7 100644 --- a/eslint/rules/architecture/shared.ts +++ b/eslint/rules/architecture/shared.ts @@ -196,10 +196,10 @@ export function createArchitectureRule( const target = resolveModule(source); const targetMatches = (key: keyof typeof defaultPaths) => target !== undefined && matches(key, target); - const boundary = (layer: string, destination: string) => + const boundary = (layer: string, destination: string, guidance = "") => report( node, - `${layer} must not import ${destination} through '${source}'${target ? ` (resolved to ${normalize(path.relative(context.cwd, target))})` : ""}.` + `${layer} must not import ${destination} through '${source}'${target ? ` (resolved to ${normalize(path.relative(context.cwd, target))})` : ""}.${guidance ? ` ${guidance}` : ""}` ); if (checks.layerDependencies) { if ( @@ -229,7 +229,10 @@ export function createArchitectureRule( else if ((repository || presentation) && httpPackages.test(source)) boundary( repository ? "Repositories" : "Presentation", - "HTTP clients; access HTTP through d2-api repositories" + "HTTP clients", + repository + ? "Use d2-api for DHIS2 access. For an external API, add a justified exception for this rule." + : "Access HTTP through d2-api repositories." ); if ( !domain && @@ -344,7 +347,7 @@ export function createArchitectureRule( ) report( reference.identifier, - "Repositories access HTTP through d2-api." + "Use d2-api for DHIS2 access. For an external API, add a justified exception for this rule." ); else if ( presentation && diff --git a/eslint/rules/http-client-access/README.md b/eslint/rules/http-client-access/README.md index b226ef2..5762e12 100644 --- a/eslint/rules/http-client-access/README.md +++ b/eslint/rules/http-client-access/README.md @@ -37,3 +37,16 @@ see [shared limitations](../architecture/README.md#limitations). Disable if the policy does not apply; adapt paths for other layouts and use narrow, justified suppressions for exceptions. + +Repositories calling external APIs rather than DHIS2 may use an appropriate HTTP +client. Add a scoped config exception or, for a dedicated external API repository, +a file-level comment naming the integration and reason: + +```ts +/* eslint-disable eyeseetea/http-client-access -- Calls the external weather API; d2-api only supports DHIS2. */ +``` + +This disables all checks in this rule for the file; layer dependency and client +construction rules remain active. Prefer a statement-level exception for mixed +DHIS2/external access. If using the compatibility wrapper, suppress +`eyeseetea/architecture` instead; that also disables its layer and construction checks. From 8fc505a53f4b624db50093ca7eab13bcf0ad1b5d Mon Sep 17 00:00:00 2001 From: Matias Arriola Date: Tue, 13 Oct 2026 13:06:09 -0300 Subject: [PATCH 10/14] Remove architecture compatibility wrapper --- eslint/MIGRATION.md | 11 +-- eslint/README.md | 10 +-- eslint/eyeseetea-config.spec.ts | 2 - eslint/eyeseetea-plugin.ts | 2 - eslint/rules/architecture/rule.ts | 8 -- eslint/rules/client-construction/README.md | 6 +- eslint/rules/client-construction/rule.ts | 2 +- eslint/rules/http-client-access/README.md | 10 +-- eslint/rules/http-client-access/rule.ts | 2 +- eslint/rules/layer-dependencies/README.md | 7 +- eslint/rules/layer-dependencies/rule.ts | 2 +- .../rules/{architecture => shared}/README.md | 39 +++----- .../architecture.spec.ts} | 88 ++++++++++--------- .../shared.ts => shared/architecture.ts} | 40 ++------- 14 files changed, 83 insertions(+), 146 deletions(-) delete mode 100644 eslint/rules/architecture/rule.ts rename eslint/rules/{architecture => shared}/README.md (71%) rename eslint/rules/{architecture/rule.spec.ts => shared/architecture.spec.ts} (82%) rename eslint/rules/{architecture/shared.ts => shared/architecture.ts} (90%) diff --git a/eslint/MIGRATION.md b/eslint/MIGRATION.md index 188889d..a0dd380 100644 --- a/eslint/MIGRATION.md +++ b/eslint/MIGRATION.md @@ -106,7 +106,7 @@ Review these before the first lint run: | Parser uses `./tsconfig.json` | Include every linted TS file, or point `parserOptions.project` at a dedicated `tsconfig.eslint.json`. Preserve application build settings. | | Typechecking includes `eslint/**/*.ts` and allows `.ts` import extensions | Include copied rules in a no-emit typecheck; use `allowImportingTsExtensions: true`. | | Source is under `src/`, with `$/*` imports | Adapt policy file globs, base import-path options, and TS aliases. | -| Layers are `src/domain`, `src/data`, `src/webapp`, and `src/scripts` | Configure `paths` on each architecture rule and `clientFactories` on `client-construction` for the project layout. Roots and adapters take precedence over their containing layer. See the [architecture options](rules/architecture/README.md#options); no directory restructuring is required. | +| Layers are `src/domain`, `src/data`, `src/webapp`, and `src/scripts` | Configure `paths` on each architecture rule and `clientFactories` on `client-construction` for the project layout. Roots and adapters take precedence over their containing layer. See the [architecture options](rules/shared/README.md#options); no directory restructuring is required. | | Domain/data use Futures | Review Promise restrictions and the two Future implementation exclusions. Projects using native Promises should adopt selected rules or maintain an explicitly adapted policy. | | React, Material UI, and Testing Library conventions apply | Omit irrelevant framework modules and adapt company rules; the styling rule recommends styled-components but does not install it. | | Unit tests use `*.spec.ts(x)` | The framework testing preset covers `.spec` files, while company test overrides also cover `.test`, `__tests__`, and `src/tests`. Align both scopes with the project. | @@ -114,9 +114,8 @@ Review these before the first lint run: | Generated files use skeleton paths | Review global ignores and lint command targets. An ignored file receives no checks. | Architecture rules accept layout options; `client-construction` also accepts factory -names, and the compatibility wrapper retains `checks`. Other custom rules have no -options. Adjust severities and scopes through flat config; monorepos need per-package -parser projects and scoped entries. +names. Other custom rules have no options. Adjust severities and scopes through flat +config; monorepos need per-package parser projects and scoped entries. ### Feature-based layouts @@ -137,7 +136,6 @@ const paths = { export default [{ files: ["src/**/*.{ts,tsx}"], rules: { - "eyeseetea/architecture": "off", "eyeseetea/layer-dependencies": ["warn", { paths }], "eyeseetea/http-client-access": ["warn", { paths }], "eyeseetea/client-construction": ["warn", { @@ -153,9 +151,6 @@ Supplied arrays replace defaults. Keep repository patterns narrow: they grant cl access. For layer checks only, disable `http-client-access` and `client-construction` in the final override. Each rule has independent severity and suppressions. -Existing `eyeseetea/architecture` configurations, including `checks`, remain supported. -Disable individual rules when enabling the wrapper to avoid duplicate reports; -when switching away, update inline suppressions to the responsible rule. [Policy-only composition](#incorporate-the-configuration) leaves framework presets under the consuming project's control. diff --git a/eslint/README.md b/eslint/README.md index 8e394ee..1cfceac 100644 --- a/eslint/README.md +++ b/eslint/README.md @@ -11,12 +11,12 @@ and project-specific overrides. [layer-dependencies](rules/layer-dependencies/README.md), [http-client-access](rules/http-client-access/README.md), [client-construction](rules/client-construction/README.md), -the [architecture compatibility wrapper](rules/architecture/README.md), [no-collection-mutation](rules/no-collection-mutation/README.md), and [require-future-block-capture](rules/require-future-block-capture/README.md). Each rule lives in `rules//` with `rule.ts`, `rule.spec.ts`, and -`README.md`. Documentation includes rule details, examples, options, and limitations; +`README.md`; shared architecture helpers and regression tests live in `rules/shared/`. +Documentation includes rule details, examples, options, and limitations; rule metadata links to that reference through `meta.docs.url`. Policy integration tests live in `eyeseetea-config.spec.ts`. @@ -41,7 +41,6 @@ The reusable policy enables all three as warnings. For layer checks only, append ```js export default [{ rules: { - "eyeseetea/architecture": "off", "eyeseetea/layer-dependencies": "warn", "eyeseetea/http-client-access": "off", "eyeseetea/client-construction": "off" @@ -49,9 +48,8 @@ export default [{ }]; ``` -The compatibility wrapper retains the original options, including `checks`, and -shares the same implementation. Enable the wrapper or individual rules to avoid -duplicate reports. +The rules share [path matching and TypeScript resolution](rules/shared/README.md) +while retaining independent configuration. ## Severity and legacy code diff --git a/eslint/eyeseetea-config.spec.ts b/eslint/eyeseetea-config.spec.ts index d8869ca..df4f2de 100644 --- a/eslint/eyeseetea-config.spec.ts +++ b/eslint/eyeseetea-config.spec.ts @@ -86,13 +86,11 @@ describe("effective EyeSeeTea configuration", () => { expect.arrayContaining([2]) ); } - expect(config?.rules?.["eyeseetea/architecture"]).toBeUndefined(); expect(config?.rules?.["eyeseetea/no-collection-mutation"]).toEqual( expect.arrayContaining([2]) ); } else { for (const rule of [ - "architecture", "layer-dependencies", "http-client-access", "client-construction", diff --git a/eslint/eyeseetea-plugin.ts b/eslint/eyeseetea-plugin.ts index 9fa0096..2e077e0 100644 --- a/eslint/eyeseetea-plugin.ts +++ b/eslint/eyeseetea-plugin.ts @@ -2,13 +2,11 @@ import type { TSESLint } from "@typescript-eslint/utils"; import layerDependencies from "./rules/layer-dependencies/rule.ts"; import httpClientAccess from "./rules/http-client-access/rule.ts"; import clientConstruction from "./rules/client-construction/rule.ts"; -import architecture from "./rules/architecture/rule.ts"; import noCollectionMutation from "./rules/no-collection-mutation/rule.ts"; import requireFutureBlockCapture from "./rules/require-future-block-capture/rule.ts"; export default { rules: { - architecture, "layer-dependencies": layerDependencies, "http-client-access": httpClientAccess, "client-construction": clientConstruction, diff --git a/eslint/rules/architecture/rule.ts b/eslint/rules/architecture/rule.ts deleted file mode 100644 index 5ed9cf8..0000000 --- a/eslint/rules/architecture/rule.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { createArchitectureRule } from "./shared.ts"; -export type { ArchitectureOptions } from "./shared.ts"; - -// Compatibility wrapper for configurations that enable the original combined rule. -export default createArchitectureRule( - "architecture", - "Check Clean Architecture dependency directions and DHIS2 client boundaries." -); diff --git a/eslint/rules/client-construction/README.md b/eslint/rules/client-construction/README.md index 257e3fb..57806dc 100644 --- a/eslint/rules/client-construction/README.md +++ b/eslint/rules/client-construction/README.md @@ -18,17 +18,15 @@ bound to named variables. It does not restrict imports or HTTP access. }] ``` -See [architecture options](../architecture/README.md#options) for `paths` groups, +See [shared architecture options](../shared/README.md#options) for `paths` groups, globs, defaults, and replacement semantics. Roots and adapters override layer membership. `clientFactories` defaults to `["getWebappCompositionRoot"]` and replaces the list of allowed names. An empty list permits no construction. -This rule accepts no `checks` switches; select the rule and its severity directly. - ## Limitations Checks direct syntax, not transitive dependencies or whole-program data flow; -see [shared limitations](../architecture/README.md#limitations). +see [shared limitations](../shared/README.md#limitations). ## When Not To Use It diff --git a/eslint/rules/client-construction/rule.ts b/eslint/rules/client-construction/rule.ts index 345ca2b..280419f 100644 --- a/eslint/rules/client-construction/rule.ts +++ b/eslint/rules/client-construction/rule.ts @@ -1,4 +1,4 @@ -import { createArchitectureRule } from "../architecture/shared.ts"; +import { createArchitectureRule } from "../shared/architecture.ts"; export default createArchitectureRule( "client-construction", diff --git a/eslint/rules/http-client-access/README.md b/eslint/rules/http-client-access/README.md index 5762e12..79e1028 100644 --- a/eslint/rules/http-client-access/README.md +++ b/eslint/rules/http-client-access/README.md @@ -22,16 +22,15 @@ It does not enforce application-layer imports or constructor locations. }] ``` -See [architecture options](../architecture/README.md#options) for `paths` groups, +See [shared architecture options](../shared/README.md#options) for `paths` groups, globs, defaults, and replacement semantics. Roots and adapters override layer membership. -This rule accepts no `checks` switches; select the rule and its severity directly. -`clientFactories` applies only to `client-construction` and the compatibility wrapper. +`clientFactories` applies only to `client-construction`. ## Limitations Checks direct syntax, not transitive dependencies or whole-program data flow; -see [shared limitations](../architecture/README.md#limitations). +see [shared limitations](../shared/README.md#limitations). ## When Not To Use It @@ -48,5 +47,4 @@ a file-level comment naming the integration and reason: This disables all checks in this rule for the file; layer dependency and client construction rules remain active. Prefer a statement-level exception for mixed -DHIS2/external access. If using the compatibility wrapper, suppress -`eyeseetea/architecture` instead; that also disables its layer and construction checks. +DHIS2/external access. diff --git a/eslint/rules/http-client-access/rule.ts b/eslint/rules/http-client-access/rule.ts index f483851..33406df 100644 --- a/eslint/rules/http-client-access/rule.ts +++ b/eslint/rules/http-client-access/rule.ts @@ -1,4 +1,4 @@ -import { createArchitectureRule } from "../architecture/shared.ts"; +import { createArchitectureRule } from "../shared/architecture.ts"; export default createArchitectureRule( "http-client-access", diff --git a/eslint/rules/layer-dependencies/README.md b/eslint/rules/layer-dependencies/README.md index e2bc5e7..405c79a 100644 --- a/eslint/rules/layer-dependencies/README.md +++ b/eslint/rules/layer-dependencies/README.md @@ -20,16 +20,15 @@ through TypeScript before matching the target against the configured paths. }] ``` -See [architecture options](../architecture/README.md#options) for `paths` groups, +See [shared architecture options](../shared/README.md#options) for `paths` groups, globs, defaults, and replacement semantics. Roots and adapters override layer membership. -This rule accepts no `checks` switches; select the rule and its severity directly. -`clientFactories` applies only to `client-construction` and the compatibility wrapper. +`clientFactories` applies only to `client-construction`. ## Limitations Checks direct syntax, not transitive dependencies or whole-program data flow; -see [shared limitations](../architecture/README.md#limitations). +see [shared limitations](../shared/README.md#limitations). ## When Not To Use It diff --git a/eslint/rules/layer-dependencies/rule.ts b/eslint/rules/layer-dependencies/rule.ts index bb15d28..647c1ff 100644 --- a/eslint/rules/layer-dependencies/rule.ts +++ b/eslint/rules/layer-dependencies/rule.ts @@ -1,4 +1,4 @@ -import { createArchitectureRule } from "../architecture/shared.ts"; +import { createArchitectureRule } from "../shared/architecture.ts"; export default createArchitectureRule( "layer-dependencies", diff --git a/eslint/rules/architecture/README.md b/eslint/rules/shared/README.md similarity index 71% rename from eslint/rules/architecture/README.md rename to eslint/rules/shared/README.md index bdc40b0..6b0d52b 100644 --- a/eslint/rules/architecture/README.md +++ b/eslint/rules/shared/README.md @@ -1,15 +1,13 @@ -# eyeseetea/architecture +# Shared architecture configuration -Compatibility wrapper enforcing the combined checks of -[layer-dependencies](../layer-dependencies/README.md), +The [layer-dependencies](../layer-dependencies/README.md), [http-client-access](../http-client-access/README.md), and -[client-construction](../client-construction/README.md), with unchanged options. -The reusable company policy enables those rules individually as warnings; -disable them when enabling this wrapper to avoid duplicate reports. +[client-construction](../client-construction/README.md) rules share path matching, +TypeScript resolution, and boundary helpers. Enable and configure each rule independently. ## Rule Details -Reports domain imports from data, presentation, the composition root, DHIS2 clients, +The rules report domain imports from data, presentation, the composition root, DHIS2 clients, or platform infrastructure, and domain access to platform globals. Data must not import presentation or the composition root. Presentation must not import concrete data implementations. Repositories and presentation must not access HTTP directly. @@ -42,10 +40,10 @@ import { D2Api } from "$/types/d2-api"; ## Options The skeleton layout and `getWebappCompositionRoot` factory are the defaults. -Pass one options object to adapt the layout without modifying the shared rule: +Pass `paths` to each enabled rule; pass `clientFactories` only to `client-construction`: ```js -"eyeseetea/architecture": ["warn", { +"eyeseetea/client-construction": ["warn", { paths: { domain: ["src/domain/**"], data: ["src/data/**"], @@ -57,12 +55,7 @@ Pass one options object to adapt the layout without modifying the shared rule: ], apiAdapters: ["src/data/common/utils/api-futures.ts"] }, - clientFactories: ["createApp", "createTest"], - checks: { - layerDependencies: true, - httpClientAccess: true, - clientConstruction: true - } + clientFactories: ["createApp", "createTest"] }] ``` @@ -92,14 +85,6 @@ arrow/function expressions bound to named variables are supported. Construction requires both a configured composition-root file and an enclosing permitted factory. An empty factory list permits no construction. -All checks default to `true` and can be toggled independently: - -- `layerDependencies`: domain → data/presentation/roots/adapters, data → - presentation/roots, and presentation → data imports. -- `httpClientAccess`: domain platform APIs/imports, repository/presentation HTTP - access, and DHIS2 client/adapter import permissions. -- `clientConstruction`: where imported named `D2Api` constructors may run. - Diagnostics include the import specifier and resolved project-relative target. Type-aware parser compiler options take precedence; without a parser program, the rule reads the nearest `tsconfig.json` from ESLint's working directory. Missing local @@ -111,11 +96,9 @@ Checks direct imports, re-exports, literal dynamic imports, and literal `require calls. TypeScript resolution honors the project configuration. Transitive dependencies, nonliteral imports, namespace constructors, and indirect factories require review. -## When Not To Use It +## Exceptions -Configure paths and checks for a different directory structure or architecture. -For a justified exception, use a narrow suppression with an explanation. +Adapt paths for other layouts and use narrow, justified rule suppressions. External API repositories may need an HTTP exception; see [external API guidance](../http-client-access/README.md#when-not-to-use-it). -Suppressing this wrapper also disables its layer and client-construction checks; -use the individual rules when those checks should remain enabled. +Disabling `http-client-access` leaves layer dependency and client-construction checks active. diff --git a/eslint/rules/architecture/rule.spec.ts b/eslint/rules/shared/architecture.spec.ts similarity index 82% rename from eslint/rules/architecture/rule.spec.ts rename to eslint/rules/shared/architecture.spec.ts index 217b10f..8636e9c 100644 --- a/eslint/rules/architecture/rule.spec.ts +++ b/eslint/rules/shared/architecture.spec.ts @@ -5,15 +5,15 @@ import { TSESLint } from "@typescript-eslint/utils"; const { Linter } = TSESLint; import { parser } from "typescript-eslint"; import { afterAll, beforeAll, describe, expect, test } from "vitest"; -import type { ArchitectureOptions } from "./rule"; +import type { ArchitectureOptions } from "./architecture.ts"; +type TestOptions = ArchitectureOptions & { disabledRules?: string[] }; import plugin from "../../eyeseetea-plugin.ts"; function lintArchitecture( code: string, filename = "src/domain/entities/PolicyProbe.ts", - options: ArchitectureOptions = {}, - cwd = globalThis.process.cwd(), - independent = false + options: TestOptions = {}, + cwd = globalThis.process.cwd() ) { return new Linter({ cwd }).verify( code, @@ -22,27 +22,25 @@ function lintArchitecture( files: ["**/*.ts"], languageOptions: { parser }, plugins: { eyeseetea: plugin }, - rules: independent - ? { - "eyeseetea/layer-dependencies": [ - options.checks?.layerDependencies === false ? "off" : "warn", - { ...(options.paths ? { paths: options.paths } : {}) }, - ], - "eyeseetea/http-client-access": [ - options.checks?.httpClientAccess === false ? "off" : "warn", - { ...(options.paths ? { paths: options.paths } : {}) }, - ], - "eyeseetea/client-construction": [ - options.checks?.clientConstruction === false ? "off" : "warn", - { - ...(options.paths ? { paths: options.paths } : {}), - ...(options.clientFactories - ? { clientFactories: options.clientFactories } - : {}), - }, - ], - } - : { "eyeseetea/architecture": ["warn", options] }, + rules: { + "eyeseetea/layer-dependencies": [ + options.disabledRules?.includes("layer-dependencies") ? "off" : "warn", + { ...(options.paths ? { paths: options.paths } : {}) }, + ], + "eyeseetea/http-client-access": [ + options.disabledRules?.includes("http-client-access") ? "off" : "warn", + { ...(options.paths ? { paths: options.paths } : {}) }, + ], + "eyeseetea/client-construction": [ + options.disabledRules?.includes("client-construction") ? "off" : "warn", + { + ...(options.paths ? { paths: options.paths } : {}), + ...(options.clientFactories + ? { clientFactories: options.clientFactories } + : {}), + }, + ], + }, }, ], { filename: path.resolve(cwd, filename) } @@ -157,7 +155,7 @@ describe("alternative architecture layout", () => { } }); afterAll(() => fs.rmSync(cwd, { recursive: true, force: true })); - const lint = (code: string, filename: string, overrides: ArchitectureOptions = {}) => + const lint = (code: string, filename: string, overrides: TestOptions = {}) => lintArchitecture(code, filename, { ...options, ...overrides }, cwd); test.each([ "import { View } from '@/presentation/View';", @@ -226,22 +224,22 @@ describe("alternative architecture layout", () => { ) ).toHaveLength(1); }); - test("toggles checks independently", () => { + test("disables rules independently", () => { expect( lint("import '@/presentation/View'; fetch('/api');", "src/domain/Probe.ts", { - checks: { layerDependencies: false }, + disabledRules: ["layer-dependencies"], }) ).toHaveLength(1); expect( lint("import '@/presentation/View'; fetch('/api');", "src/domain/Probe.ts", { - checks: { httpClientAccess: false }, + disabledRules: ["http-client-access"], }) ).toHaveLength(1); expect( lint( "import { D2Api } from '@eyeseetea/d2-api'; new D2Api();", "src/data/users/UserRepository.ts", - { checks: { clientConstruction: false } } + { disabledRules: ["client-construction"] } ) ).toEqual([]); }); @@ -254,37 +252,41 @@ describe("alternative architecture layout", () => { }); test("rejects misspelled options", () => { expect(() => - lint("", "src/domain/Probe.ts", { checks: { typo: false } } as ArchitectureOptions) + lint("", "src/domain/Probe.ts", { paths: { typo: [] } } as ArchitectureOptions) ).toThrow(); }); test.each([ - ["import '@/presentation/View'; fetch('/api');", "src/domain/Probe.ts"], - ["import '@/presentation/View';", "src/data/users/Probe.ts"], + [ + "import '@/presentation/View'; fetch('/api');", + "src/domain/Probe.ts", + ["layer-dependencies", "http-client-access"], + ], + ["import '@/presentation/View';", "src/data/users/Probe.ts", ["layer-dependencies"]], [ "import '@/data/users/UserRepository'; import { D2Api } from '@eyeseetea/d2-api'; new D2Api();", "src/presentation/View.ts", + ["layer-dependencies", "http-client-access", "client-construction"], ], [ "import { D2Api } from '@eyeseetea/d2-api'; new D2Api(); fetch('/api');", "src/data/users/UserRepository.ts", + ["client-construction", "http-client-access"], ], [ "import '@/data/users/UserRepository'; import { D2Api } from '@eyeseetea/d2-api'; const createApp = () => new D2Api();", "src/presentation/AppCompositionRoot.ts", + [], ], - ])("wrapper matches independently enabled rules: %s", (code, filename) => { - const combined = lintArchitecture(code, filename, options, cwd); - const separate = lintArchitecture(code, filename, options, cwd, true); - const diagnostics = (messages: typeof combined) => - messages.map(({ ruleId: _ruleId, ...message }) => message); - expect(diagnostics(separate)).toEqual(diagnostics(combined)); - expect(separate.every(message => message.ruleId !== "eyeseetea/architecture")).toBe(true); + ])("reports independent rule IDs for mixed boundaries: %s", (code, filename, expected) => { + const messages = lintArchitecture(code as string, filename as string, options, cwd); + expect(messages.map(message => message.ruleId).sort()).toEqual( + (expected as string[]).map(name => `eyeseetea/${name}`).sort() + ); }); }); -describe.each([false, true])("boundary regressions (independent rules: %s)", independent => { - const lint = (code: string, filename: string) => - lintArchitecture(code, filename, {}, globalThis.process.cwd(), independent); +describe("boundary regressions", () => { + const lint = (code: string, filename: string) => lintArchitecture(code, filename); test.each(["window", "globalThis", "self", "globalThis.window"])( "rejects qualified HTTP through %s in repositories and presentation", diff --git a/eslint/rules/architecture/shared.ts b/eslint/rules/shared/architecture.ts similarity index 90% rename from eslint/rules/architecture/shared.ts rename to eslint/rules/shared/architecture.ts index e0ac1a7..29c146c 100644 --- a/eslint/rules/architecture/shared.ts +++ b/eslint/rules/shared/architecture.ts @@ -35,11 +35,6 @@ export type ArchitectureOptions = { > >; clientFactories?: string[]; - checks?: { - layerDependencies?: boolean; - httpClientAccess?: boolean; - clientConstruction?: boolean; - }; }; const defaultPaths = { @@ -70,12 +65,12 @@ function compileGlob(pattern: string): RegExp { return new RegExp(expression + "$"); } -type ArchitectureCheck = NonNullable; +type ArchitectureCheck = "layerDependencies" | "httpClientAccess" | "clientConstruction"; export function createArchitectureRule( ruleName: string, description: string, - check?: keyof ArchitectureCheck + check: ArchitectureCheck ) { return ESLintUtils.RuleCreator( name => @@ -107,7 +102,7 @@ export function createArchitectureRule( ]) ), }, - ...(!check || check === "clientConstruction" + ...(check === "clientConstruction" ? { clientFactories: { type: "array", @@ -116,19 +111,6 @@ export function createArchitectureRule( }, } : {}), - ...(!check - ? { - checks: { - type: "object", - additionalProperties: false, - properties: { - layerDependencies: { type: "boolean" }, - httpClientAccess: { type: "boolean" }, - clientConstruction: { type: "boolean" }, - }, - }, - } - : {}), }, }, ], @@ -154,12 +136,6 @@ export function createArchitectureRule( const repository = matches("repositories", filename); const presentation = !root && !apiAdapter && matches("presentation", filename); const factories = configuration.clientFactories ?? ["getWebappCompositionRoot"]; - const checks = { - layerDependencies: !check || check === "layerDependencies", - httpClientAccess: !check || check === "httpClientAccess", - clientConstruction: !check || check === "clientConstruction", - ...configuration.checks, - }; const sourceCode = context.sourceCode; const program = sourceCode.parserServices?.program; const configFile = !program && ts.findConfigFile(context.cwd, ts.sys.fileExists); @@ -189,7 +165,7 @@ export function createArchitectureRule( context.report({ node, messageId: "boundary", data: { message } }); function checkImport(node: TSESTree.Node, source: unknown) { if ( - (!checks.layerDependencies && !checks.httpClientAccess) || + (check !== "layerDependencies" && check !== "httpClientAccess") || typeof source !== "string" ) return; @@ -201,7 +177,7 @@ export function createArchitectureRule( node, `${layer} must not import ${destination} through '${source}'${target ? ` (resolved to ${normalize(path.relative(context.cwd, target))})` : ""}.${guidance ? ` ${guidance}` : ""}` ); - if (checks.layerDependencies) { + if (check === "layerDependencies") { if ( domain && (targetMatches("data") || @@ -218,7 +194,7 @@ export function createArchitectureRule( if (presentation && targetMatches("data")) boundary("Presentation", "data implementations"); } - if (checks.httpClientAccess) { + if (check === "httpClientAccess") { if ( domain && (httpPackages.test(source) || @@ -269,7 +245,7 @@ export function createArchitectureRule( checkImport(node, node.arguments[0].value); }, NewExpression(node) { - if (!checks.clientConstruction || node.callee.type !== "Identifier") return; + if (check !== "clientConstruction" || node.callee.type !== "Identifier") return; let scope: TSESLint.Scope.Scope | null = sourceCode.getScope(node); let variable; while (scope && !variable) { @@ -308,7 +284,7 @@ export function createArchitectureRule( ); }, "Program:exit"() { - if (!checks.httpClientAccess) return; + if (check !== "httpClientAccess") return; for (const scope of sourceCode.scopeManager?.scopes ?? []) { for (const reference of scope.references) { if (reference.resolved?.defs.length) continue; From ce7f2e3f0111a1cdd059acd34663b4c4d89d921d Mon Sep 17 00:00:00 2001 From: Matias Arriola Date: Thu, 15 Oct 2026 09:23:46 -0300 Subject: [PATCH 11/14] Address downstream ESLint policy review feedback 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. --- eslint-suppressions.json | 44 +++++---------- eslint/MIGRATION.md | 28 ++++++++-- eslint/README.md | 18 +++++- eslint/eyeseetea-config.spec.ts | 56 ++++++++++++++++++- eslint/eyeseetea-config.ts | 32 +++++------ eslint/rules/http-client-access/README.md | 2 + eslint/rules/http-client-access/rule.spec.ts | 26 +++++++++ eslint/rules/no-collection-mutation/README.md | 3 +- .../rules/no-collection-mutation/rule.spec.ts | 10 +++- eslint/rules/shared/architecture.ts | 3 +- 10 files changed, 163 insertions(+), 59 deletions(-) diff --git a/eslint-suppressions.json b/eslint-suppressions.json index 34680e9..28a432b 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -5,9 +5,6 @@ } }, "src/domain/entities/generic/Collection.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - }, "@typescript-eslint/no-unsafe-return": { "count": 3 }, @@ -22,17 +19,14 @@ } }, "src/domain/entities/generic/Either.ts": { - "@typescript-eslint/no-explicit-any": { + "@typescript-eslint/no-unsafe-return": { "count": 2 }, - "@typescript-eslint/no-unsafe-return": { + "no-restricted-syntax": { "count": 2 } }, "src/domain/entities/generic/Future.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - }, "@typescript-eslint/no-unsafe-argument": { "count": 1 }, @@ -50,28 +44,25 @@ }, "eyeseetea/no-collection-mutation": { "count": 3 + }, + "no-restricted-syntax": { + "count": 3 } }, "src/domain/entities/generic/HashMap.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - }, "@typescript-eslint/no-unsafe-type-assertion": { "count": 1 + }, + "no-restricted-syntax": { + "count": 1 } }, "src/domain/entities/generic/Rec.ts": { "@typescript-eslint/no-unsafe-type-assertion": { "count": 6 - }, - "no-restricted-syntax": { - "count": 3 } }, "src/domain/entities/generic/Struct.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - }, "@typescript-eslint/no-unsafe-member-access": { "count": 1 }, @@ -80,12 +71,12 @@ }, "@typescript-eslint/no-unsafe-type-assertion": { "count": 4 + }, + "no-restricted-syntax": { + "count": 1 } }, "src/domain/entities/generic/__tests__/Future.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - }, "@typescript-eslint/no-unsafe-argument": { "count": 1 }, @@ -94,10 +85,8 @@ }, "@typescript-eslint/no-unsafe-type-assertion": { "count": 1 - } - }, - "src/domain/entities/generic/__tests__/HashMap.spec.ts": { - "eyeseetea/no-collection-mutation": { + }, + "no-restricted-syntax": { "count": 1 } }, @@ -206,10 +195,5 @@ "eyeseetea/http-client-access": { "count": 2 } - }, - "src/webapp/utils/__tests__/objects-table.spec.tsx": { - "eyeseetea/no-collection-mutation": { - "count": 1 - } } -} \ No newline at end of file +} diff --git a/eslint/MIGRATION.md b/eslint/MIGRATION.md index a0dd380..8fda607 100644 --- a/eslint/MIGRATION.md +++ b/eslint/MIGRATION.md @@ -26,8 +26,10 @@ do not expect fixtures to run unchanged in another application. ### Runtime and dependencies -Use Node 24.13.1 or a compatible newer Node 24 release consistently in developer shells, -CI, and the editor's ESLint runtime. The `.mjs` config imports local `.ts` files +This repository pins Node 24; use a consistent runtime in developer shells, CI, +and the editor's ESLint runtime. Native type stripping is enabled by default in +Node 22.18+ and does not itself require Node 24. Verify the complete dependency +stack on the consuming project's chosen runtime. The `.mjs` config imports local `.ts` files using native type stripping. Installing a TypeScript parser alone does not enable TypeScript execution. Older runtimes require a separately configured loader or a compiled JavaScript distribution. An optional `eslint/package.json` containing @@ -205,7 +207,7 @@ export default [ rules: { "eyeseetea/no-collection-mutation": "error", "@typescript-eslint/no-floating-promises": "error", - "@typescript-eslint/no-explicit-any": "error", + "@typescript-eslint/no-explicit-any": "error", // Optional stricter local policy: includes constraints. }, }, { @@ -255,7 +257,7 @@ an earlier rule by ignoring files. Use a scoped rule override to change its seve When modifying options for `no-restricted-syntax` or `no-restricted-imports`, provide the complete intended options: later arrays replace earlier options rather than appending selectors or paths. In particular, replacing `no-restricted-syntax` to allow -`toPromise()` can also remove cast and test assertion checks. For substantial selector +`toPromise()` can also remove explicit-any and test assertion checks. For substantial selector changes, maintain an explicit policy adaptation with tests rather than relying on array indexes in the upstream config. @@ -276,3 +278,21 @@ References: [ESLint rule overrides](https://eslint.org/docs/latest/use/configure [ESLint CLI](https://eslint.org/docs/latest/use/command-line-interface), [typed parser configuration](https://typescript-eslint.io/packages/parser/), and [Node TypeScript execution](https://nodejs.org/docs/latest-v24.x/api/typescript.html). + +### Older TypeScript consumers + +`allowImportingTsExtensions` requires TypeScript 5+ and a no-emit (or declaration-only) +typecheck. On TypeScript 4.9, ESLint can execute these rules through Node, but that +does not typecheck the tooling. Use a separate tooling project with a compatible +TypeScript 5+ compiler, or distribute compiled JavaScript rules with declarations; +do not silently drop tooling typechecking. + +For Promise adapters, composition roots, scripts, and migrations, use documented +file-specific exceptions where interop is necessary. Promise value and type checks +are separate restrictions; preserve the other syntax selectors when overriding +them. Do not exempt whole layers. + +CPR downstream review reported lint time increasing from 6.1s to 17.7s (2.9×), +with 2.6s attributed to type information and approximately 9s to new rules, mostly +`no-unsafe-*`. These figures have not been independently reproduced here. Profile +identical source, dependencies, and runtime before attributing costs or optimizing. diff --git a/eslint/README.md b/eslint/README.md index 1cfceac..4dc7a37 100644 --- a/eslint/README.md +++ b/eslint/README.md @@ -64,9 +64,21 @@ too. Other framework warnings remain advisory; review them before adding `--max-warnings=0`. See [BASELINE.md](BASELINE.md) for commands and limitations. Definite safety/correctness checks are **errors**: `no-eval`, `no-implied-eval`, -`no-new-func`, `array-callback-return`, and `react-hooks/rules-of-hooks`. +`no-new-func`, and `react-hooks/rules-of-hooks`. Existing project errors, including the Future capture rule, remain enabled. +`array-callback-return` is disabled because it matches method names without checking +receiver types: legitimate production `Future.map` callbacks returning void are +reported as array errors. Restricting it to production would retain these false +positives. This trades away detection of missing returns in array callbacks such +as `map`, `filter`, and `sort`; no equivalent check currently replaces it. Restoring +that coverage requires a type-aware rule limited to Array/ReadonlyArray receivers. + +The explicit-`any` restriction allows generic constraints, including function +constraints, but still reports defaults such as `` and +``. Defaults introduce `any` when callers omit the type +argument; prefer a specific default or `unknown` where the contract permits it. + Use a narrow `eslint-disable-next-line -- ` for a justified exception. Prefer explaining the adapter, legacy constraint, or library contract over disabling an entire directory. The Promise exclusions name the two Future implementation files @@ -76,8 +88,8 @@ that necessarily implement the abstraction; new business code receives no blanke | Coding convention | Automated checks | Level / limits | | --- | --- | --- | -| Immutability | `prefer-const`, `no-var`, `no-param-reassign` including properties; local collection mutation rule | Warn. Typed Array/tuple, standard Map/Set mutators; custom methods called `push` are allowed. Arbitrary object mutation, aliasing, and shared-state analysis still require review. | -| Type safety | Explicit `any`; type-aware unsafe assignment, argument, call, member access, return, and type assertion rules; restricted `as unknown` and `as Type[]` | Warn. Safe widening and `as const` are allowed. Type guards and `satisfies` are preferred. | +| Immutability | `prefer-const`, `no-var`, `no-param-reassign` including properties; local collection mutation rule | Warn. Typed Array/tuple, standard Map/Set mutators in production; test fixture mutation is allowed; custom methods called `push` are allowed. Arbitrary object mutation, aliasing, and shared-state analysis still require review. | +| Type safety | Explicit `any` outside generic constraints; type-aware unsafe assignment, argument, call, member access, return, and type assertion rules | Warn. Safe widening, including `as unknown`, and `as const` are allowed. Type guards and `satisfies` are preferred. | | Layer dependencies | Layer dependency rule resolves imports using TypeScript configuration; checks static imports, re-exports, literal dynamic imports and `require` | Warn. Domain → data/UI/platform and data → UI are forbidden; presentation → concrete data is reported. Configurable layout paths. Checks direct dependencies, not transitive architectural purity. | | API boundaries | d2-api import boundaries, aliased named `D2Api` construction, HTTP imports and platform HTTP globals | Warn. Repository/client adapter/composition-root imports allowed. By default, named client construction belongs in `getWebappCompositionRoot` in `CompositionRoot.ts`; roots, factory names, and individual architecture checks are configurable. Namespace constructors, indirect factory calls, and nonliteral dynamic imports need review. | | Asynchronous code | Promise value/type references in domain/data; production `toPromise()` calls; existing Future capture rule | Warn, except capture errors. Tests allow Promises and `toPromise`. `Future.block` async callbacks remain valid. Inferred Promise returns and APIs exposed through aliases are not fully covered. | diff --git a/eslint/eyeseetea-config.spec.ts b/eslint/eyeseetea-config.spec.ts index df4f2de..08ace71 100644 --- a/eslint/eyeseetea-config.spec.ts +++ b/eslint/eyeseetea-config.spec.ts @@ -51,6 +51,10 @@ describe("type assertions", () => { const wide = dog as Animal; const constant = ["a", "b"] as const; const narrow = animal as Dog; + const opaque = dog as unknown; + const safeArray = [dog] as Animal[]; + const unsafeArray = [animal] as Dog[]; + const doubleAssertion = animal as unknown as Dog; `, { filePath: "policy-probe.ts" } ); @@ -58,7 +62,7 @@ describe("type assertions", () => { message => message.ruleId === "@typescript-eslint/no-unsafe-type-assertion" || message.fatal ); - expect(messages).toHaveLength(1); + expect(messages).toHaveLength(3); expect(messages[0]!.ruleId).toBe("@typescript-eslint/no-unsafe-type-assertion"); }); }); @@ -151,12 +155,60 @@ describe("effective EyeSeeTea configuration", () => { ) ).toEqual([]); }); + test("allows generic any constraints while rejecting other explicit any in every scope", async () => { + for (const filename of [ + "src/domain/probe.ts", + "src/domain/probe.spec.ts", + "src/tests/playwright/probe.e2e.ts", + ]) { + const config = await new ESLint().calculateConfigForFile(filename); + const messages = new Linter().verify( + ` + type Direct = T; + type Callback any> = T; + type Default = T; + type ConstrainedDefault = T; + let value: any; + function bad(arg: any): any { + return arg; + } + `, + [ + { + languageOptions: { parser }, + rules: { "no-restricted-syntax": config!.rules!["no-restricted-syntax"] }, + }, + ] + ); + expect(messages).toHaveLength(5); + expect(messages.every(message => message.ruleId === "no-restricted-syntax")).toBe(true); + } + }); + test("test fixtures allow mutation while production still checks it", async () => { + for (const filename of [ + "src/domain/probe.spec.ts", + "src/tests/probe.ts", + "src/tests/playwright/probe.e2e.ts", + ]) { + const config = await new ESLint().calculateConfigForFile(filename); + expect(config?.rules?.["eyeseetea/no-collection-mutation"]).toEqual([0]); + } + const config = await new ESLint().calculateConfigForFile("src/domain/probe.ts"); + expect(config?.rules?.["eyeseetea/no-collection-mutation"]).toEqual([2]); + expect(config?.rules?.["array-callback-return"]).toEqual(expect.arrayContaining([0])); + }); test("accessible E2E queries pass while CSS and test IDs fail", async () => { const config = await new ESLint().calculateConfigForFile( "src/tests/playwright/probe.e2e.ts" ); const result = new Linter().verify( - "page.getByRole('button'); page.locator('.button'); page.getByTestId('submit'); page.$('.button'); page.$$('.button');", + ` + page.getByRole('button'); + page.locator('.button'); + page.getByTestId('submit'); + page.$('.button'); + page.$$('.button'); + `, [ { languageOptions: { parser }, diff --git a/eslint/eyeseetea-config.ts b/eslint/eyeseetea-config.ts index 980257f..77e9fc7 100644 --- a/eslint/eyeseetea-config.ts +++ b/eslint/eyeseetea-config.ts @@ -9,17 +9,13 @@ const tests = [ "src/tests/**", "src/tests/playwright/**", ]; -const syntax = [ - { - selector: - "TSAsExpression[typeAnnotation.type='TSUnknownKeyword'], TSTypeAssertion[typeAnnotation.type='TSUnknownKeyword']", - message: "Do not use as unknown to bypass a type contract; validate or narrow the value.", - }, - { - selector: - "TSAsExpression[typeAnnotation.type='TSArrayType'], TSTypeAssertion[typeAnnotation.type='TSArrayType']", - message: "Do not cast to Type[]; use a typed binding, satisfies, or a type guard.", - }, +const anySyntax = { + selector: "TSAnyKeyword:not(TSTypeParameter > .constraint):not(TSTypeParameter .constraint *)", + message: + "Use a specific type or unknown; any is only allowed in generic constraints, not defaults.", +}; +const productionSyntax = [ + anySyntax, { selector: "CallExpression[callee.type='MemberExpression'][callee.property.name='toPromise']", @@ -43,11 +39,12 @@ export default [ "prefer-const": "warn", "no-var": "warn", "no-param-reassign": ["warn", { props: true }], - "array-callback-return": "error", + // Name-based matching also flags valid Future.map callbacks; see README tradeoff. + "array-callback-return": "off", "no-eval": "error", "no-implied-eval": "error", "no-new-func": "error", - "no-restricted-syntax": ["warn", ...syntax], + "no-restricted-syntax": ["warn", ...productionSyntax], "no-restricted-imports": [ "warn", { @@ -83,7 +80,7 @@ export default [ ], }, ], - "@typescript-eslint/no-explicit-any": "warn", + "@typescript-eslint/no-explicit-any": "off", "@typescript-eslint/no-unsafe-assignment": "warn", "@typescript-eslint/no-unsafe-argument": "warn", "@typescript-eslint/no-unsafe-call": "warn", @@ -114,7 +111,7 @@ export default [ // Async Future.block callbacks remain valid; do not ban async/await. "no-restricted-syntax": [ "warn", - ...syntax, + ...productionSyntax, { selector: "TSTypeReference[typeName.name='Promise']", message: "Return FutureData instead of Promise in domain and data.", @@ -126,9 +123,10 @@ export default [ files: tests, plugins: { "testing-library": testingLibrary }, rules: { + "eyeseetea/no-collection-mutation": "off", "no-restricted-syntax": [ "warn", - ...syntax.slice(0, 2), + anySyntax, { selector: "CallExpression[callee.type='MemberExpression'][callee.property.name=/^(toBeTruthy|toBeDefined)$/]", @@ -146,7 +144,7 @@ export default [ rules: { "no-restricted-syntax": [ "warn", - ...syntax.slice(0, 2), + anySyntax, { selector: "CallExpression[callee.type='MemberExpression'][callee.property.name=/^(locator|getByTestId)$/], CallExpression[callee.type='MemberExpression'][callee.property.name='$'], CallExpression[callee.type='MemberExpression'][callee.property.name='$$']", diff --git a/eslint/rules/http-client-access/README.md b/eslint/rules/http-client-access/README.md index 79e1028..1fb70e6 100644 --- a/eslint/rules/http-client-access/README.md +++ b/eslint/rules/http-client-access/README.md @@ -7,6 +7,8 @@ Check platform and DHIS2 client access. Enabled as a warning for `src/**/*.{ts,t Reports domain platform globals and infrastructure imports, direct HTTP access in repositories/presentation, and DHIS2 client or adapter imports outside repositories, composition roots, and adapters. Shadowed platform names and local classes are allowed. +Type-only platform references such as `payload: Blob` are allowed; runtime access +such as `new Blob()` in domain code is reported. It does not enforce application-layer imports or constructor locations. ## Options diff --git a/eslint/rules/http-client-access/rule.spec.ts b/eslint/rules/http-client-access/rule.spec.ts index 1dcee0b..1416f52 100644 --- a/eslint/rules/http-client-access/rule.spec.ts +++ b/eslint/rules/http-client-access/rule.spec.ts @@ -5,6 +5,32 @@ import { describe, expect, test } from "vitest"; import rule from "./rule"; describe("http-client-access", () => { + test("allows platform types and shadowed values but reports runtime globals", () => { + const messages = new TSESLint.Linter().verify( + ` + type Payload = Blob; + type Qualified = globalThis.Blob; + new Blob(); + new globalThis.Blob(); + function local(Blob: () => void) { + Blob(); + } + `, + [ + { + files: ["**/*.ts"], + languageOptions: { parser }, + plugins: { eyeseetea: { rules: { "http-client-access": rule } } }, + rules: { "eyeseetea/http-client-access": "warn" }, + }, + ], + { filename: path.resolve("src/domain/Probe.ts") } + ); + expect(messages).toHaveLength(2); + expect(messages.every(message => message.ruleId === "eyeseetea/http-client-access")).toBe( + true + ); + }); test("reports direct HTTP without enforcing layer imports", () => { const messages = new TSESLint.Linter().verify( "import '$/data/repositories/UserD2Repository'; fetch('/api');", diff --git a/eslint/rules/no-collection-mutation/README.md b/eslint/rules/no-collection-mutation/README.md index 3af4095..940b172 100644 --- a/eslint/rules/no-collection-mutation/README.md +++ b/eslint/rules/no-collection-mutation/README.md @@ -1,7 +1,8 @@ # eyeseetea/no-collection-mutation Prefer new collections over in-place mutations. Enabled as a warning for -`src/**/*.{ts,tsx}` by the EyeSeeTea config. Requires TypeScript type information. +production `src/**/*.{ts,tsx}` by the EyeSeeTea config. Test scopes are excluded +to allow mutable fixture builders. Requires TypeScript type information. ## Rule Details diff --git a/eslint/rules/no-collection-mutation/rule.spec.ts b/eslint/rules/no-collection-mutation/rule.spec.ts index dee4c34..68ae2c8 100644 --- a/eslint/rules/no-collection-mutation/rule.spec.ts +++ b/eslint/rules/no-collection-mutation/rule.spec.ts @@ -37,7 +37,15 @@ describe("collection mutation", () => { test("detects typed array, Map, and Set mutation including computed access", async () => { expect( await lintMutation( - "const xs = [1]; xs.push(2); xs['sort'](); const map = new Map(); map.set('a', 1); const set = new Set(); set.add(1);" + ` + const xs = [1]; + xs.push(2); + xs['sort'](); + const map = new Map(); + map.set('a', 1); + const set = new Set(); + set.add(1); + ` ) ).toHaveLength(4); }); diff --git a/eslint/rules/shared/architecture.ts b/eslint/rules/shared/architecture.ts index 29c146c..648e7c8 100644 --- a/eslint/rules/shared/architecture.ts +++ b/eslint/rules/shared/architecture.ts @@ -287,7 +287,8 @@ export function createArchitectureRule( if (check !== "httpClientAccess") return; for (const scope of sourceCode.scopeManager?.scopes ?? []) { for (const reference of scope.references) { - if (reference.resolved?.defs.length) continue; + if (!reference.isValueReference || reference.resolved?.defs.length) + continue; const name = reference.identifier.name; // Resolve qualified globals only when their namespace is unshadowed. let access: TSESTree.Node = reference.identifier; From 584237eadd5a5edeef9e634d16a4f32bf164d206 Mon Sep 17 00:00:00 2001 From: Matias Arriola Date: Mon, 26 Oct 2026 10:08:48 -0300 Subject: [PATCH 12/14] chore: upgrade handlebars and source-map-js Fixes critical/high advisories --- yarn.lock | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/yarn.lock b/yarn.lock index 67e77ab..e46d93a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7119,10 +7119,10 @@ __metadata: linkType: hard "handlebars@npm:^4.0.11": - version: 4.7.9 - resolution: "handlebars@npm:4.7.9" + version: 4.7.10 + resolution: "handlebars@npm:4.7.10" dependencies: - minimist: "npm:^1.2.5" + minimist: "npm:^1.2.8" neo-async: "npm:^2.6.2" source-map: "npm:^0.6.1" uglify-js: "npm:^3.1.4" @@ -7132,7 +7132,7 @@ __metadata: optional: true bin: handlebars: bin/handlebars - checksum: 10c0/22f8105a7e68e81aff2662bb434edf05f757d21d850731d71cec886d69c10cd33d3c43e34b2892968ec62de8241611851d3d0674c8ef324ea3e01dc66262faa9 + checksum: 10c0/9b5573584ae5836172ae3f1502d9819568ba1b92ee83b81b18223beeb4c07486595e7b0fa633102beabc66ed06fe6e7da1dd9a9ea8c7072b9550b9a88809165c languageName: node linkType: hard @@ -8565,7 +8565,7 @@ __metadata: languageName: node linkType: hard -"minimist@npm:^1.1.0, minimist@npm:^1.2.5, minimist@npm:^1.2.6": +"minimist@npm:^1.1.0, minimist@npm:^1.2.6, minimist@npm:^1.2.8": version: 1.2.8 resolution: "minimist@npm:1.2.8" checksum: 10c0/19d3fcdca050087b84c2029841a093691a91259a47def2f18222f41e7645a0b7c44ef4b40e88a1e58a40c84d2ef0ee6047c55594d298146d0eb3f6b737c20ce6 @@ -10377,9 +10377,9 @@ __metadata: linkType: hard "source-map-js@npm:^1.2.1": - version: 1.2.1 - resolution: "source-map-js@npm:1.2.1" - checksum: 10c0/7bda1fc4c197e3c6ff17de1b8b2c20e60af81b63a52cb32ec5a5d67a20a7d42651e2cb34ebe93833c5a2a084377e17455854fee3e21e7925c64a51b6a52b0faf + version: 1.2.2 + resolution: "source-map-js@npm:1.2.2" + checksum: 10c0/d5d6dec62266834f83dd4f8a2606a196fb1a006ca5d53b0ef80ee513b7eba2f4e2ae241f4bc129ae7e9b80dea24f6e3d92b446b7e6e96be7653cab8888168a94 languageName: node linkType: hard From 2316cdd71464bfc08f80de40773d11aae8bd3563 Mon Sep 17 00:00:00 2001 From: Matias Arriola Date: Mon, 26 Oct 2026 10:11:50 -0300 Subject: [PATCH 13/14] chore: upgrade Vitest to remove vulnerable tinypool --- package.json | 2 +- yarn.lock | 312 ++++++++++++++++++++------------------------------- 2 files changed, 125 insertions(+), 189 deletions(-) diff --git a/package.json b/package.json index 1e9b3d4..bac7030 100644 --- a/package.json +++ b/package.json @@ -73,7 +73,7 @@ "vite-bundle-visualizer": "^0", "vite-plugin-checker": "^0.14.5", "vite-plugin-node-polyfills": "^0.28.0", - "vitest": "^3.2.7" + "vitest": "^4.1.12" }, "resolutions": { "@types/react": "18.2.22", diff --git a/yarn.lock b/yarn.lock index e46d93a..1b17ac1 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3313,6 +3313,13 @@ __metadata: languageName: node linkType: hard +"@standard-schema/spec@npm:^1.1.0": + version: 1.1.0 + resolution: "@standard-schema/spec@npm:1.1.0" + checksum: 10c0/d90f55acde4b2deb983529c87e8025fa693de1a5e8b49ecc6eb84d1fd96328add0e03d7d551442156c7432fd78165b2c26ff561b970a9a881f046abb78d6a526 + languageName: node + linkType: hard + "@tanstack/query-core@npm:4.44.0": version: 4.44.0 resolution: "@tanstack/query-core@npm:4.44.0" @@ -4030,86 +4037,85 @@ __metadata: languageName: node linkType: hard -"@vitest/expect@npm:3.2.7": - version: 3.2.7 - resolution: "@vitest/expect@npm:3.2.7" +"@vitest/expect@npm:4.1.12": + version: 4.1.12 + resolution: "@vitest/expect@npm:4.1.12" dependencies: + "@standard-schema/spec": "npm:^1.1.0" "@types/chai": "npm:^5.2.2" - "@vitest/spy": "npm:3.2.7" - "@vitest/utils": "npm:3.2.7" - chai: "npm:^5.2.0" - tinyrainbow: "npm:^2.0.0" - checksum: 10c0/5a13fee261d1020d47a3517f4d9a2cb209d7475399c815f6ebe22be116ddb0c6c401592f07d24f9a8b1c192155d11f651397ee28061f886ea61f1f9181a8fd48 + "@vitest/spy": "npm:4.1.12" + "@vitest/utils": "npm:4.1.12" + chai: "npm:^6.2.2" + tinyrainbow: "npm:^3.1.0" + checksum: 10c0/386bbb6b7aadbfbfe8a5c7fc9d0a875a6da24a36edb3af519755e2d658359a0211bc4188a8dc38a1a34317c752624c4db58616752861323dcae475e3f1e6a975 languageName: node linkType: hard -"@vitest/mocker@npm:3.2.7": - version: 3.2.7 - resolution: "@vitest/mocker@npm:3.2.7" +"@vitest/mocker@npm:4.1.12": + version: 4.1.12 + resolution: "@vitest/mocker@npm:4.1.12" dependencies: - "@vitest/spy": "npm:3.2.7" + "@vitest/spy": "npm:4.1.12" estree-walker: "npm:^3.0.3" - magic-string: "npm:^0.30.17" + magic-string: "npm:^0.30.21" peerDependencies: msw: ^2.4.9 - vite: ^5.0.0 || ^6.0.0 || ^7.0.0-0 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 peerDependenciesMeta: msw: optional: true vite: optional: true - checksum: 10c0/e8d9a155723e77b3e14c5a1eba35d8966b94420ebc733ffd7119b7bede22006580c468eec2aec6612fb77852cbcdfa94c6f49218f3ca1427aa9363d545c624fd + checksum: 10c0/6fccf67d42830b7caadfdfc94b8e9f3166a4686edd5bdf9083773d981f906ea93f172c0207482568f91d4fd72a9843f0c6644687d2ba3b3ce7bc8b6e9541cfa1 languageName: node linkType: hard -"@vitest/pretty-format@npm:3.2.7, @vitest/pretty-format@npm:^3.2.7": - version: 3.2.7 - resolution: "@vitest/pretty-format@npm:3.2.7" +"@vitest/pretty-format@npm:4.1.12": + version: 4.1.12 + resolution: "@vitest/pretty-format@npm:4.1.12" dependencies: - tinyrainbow: "npm:^2.0.0" - checksum: 10c0/f556dd5f9e5240c7ab054d795622292c1b23f6aad3332d1e250f33d801783efbb7883387640b76d22cc91b81f30cb735b40371ec3e4f5293e735495f45d624df + tinyrainbow: "npm:^3.1.0" + checksum: 10c0/b3d3635a49e7f328afdb0a627a537ba66c16609e3082dc58adca4c32881007afdeff88975697a21c740eced31751369e1ad06e134f4194e573ac9a758d6016ea languageName: node linkType: hard -"@vitest/runner@npm:3.2.7": - version: 3.2.7 - resolution: "@vitest/runner@npm:3.2.7" +"@vitest/runner@npm:4.1.12": + version: 4.1.12 + resolution: "@vitest/runner@npm:4.1.12" dependencies: - "@vitest/utils": "npm:3.2.7" + "@vitest/utils": "npm:4.1.12" pathe: "npm:^2.0.3" - strip-literal: "npm:^3.0.0" - checksum: 10c0/d73ba6df95175ea2b545d37fde3e743d113ecd608693b444af1d4dc27956abe4d5b500e25e09ffe46ce720de6b7cec68c264fca20366fc6da0d9ce75c52047cc + checksum: 10c0/d39b42c4e004017752ba2cadd0964c71e13dfa1536653e3a9129bf60abe684e39974ad75a3fc4ba9fd137a8e1a79e8efea80e0469c78e35019f61c8ebbdaf500 languageName: node linkType: hard -"@vitest/snapshot@npm:3.2.7": - version: 3.2.7 - resolution: "@vitest/snapshot@npm:3.2.7" +"@vitest/snapshot@npm:4.1.12": + version: 4.1.12 + resolution: "@vitest/snapshot@npm:4.1.12" dependencies: - "@vitest/pretty-format": "npm:3.2.7" - magic-string: "npm:^0.30.17" + "@vitest/pretty-format": "npm:4.1.12" + "@vitest/utils": "npm:4.1.12" + magic-string: "npm:^0.30.21" pathe: "npm:^2.0.3" - checksum: 10c0/c58a17a2c98788e77d30d39837c024852eca91618efe9b53ec399cf76332365b8cc592a69617e0f7d696df716dcc341dac61c6cbea86ae98cdb49a4a84f48d19 + checksum: 10c0/c309ae2966b9cda46ca018540467872a91a5d641b150b82362c9ea4b21b493669ebcbf284729c1216f178c08af5a3884d3a434a01091a8edc90da77d207bb985 languageName: node linkType: hard -"@vitest/spy@npm:3.2.7": - version: 3.2.7 - resolution: "@vitest/spy@npm:3.2.7" - dependencies: - tinyspy: "npm:^4.0.3" - checksum: 10c0/cf2728b4ddc6137e0ca749215c7714845e8221a5f799e933bc623216a9958fd8b032cdd7f033ed8375df9e6ed84a18b64687ca2530f50e8a76bc3b1d16d88c42 +"@vitest/spy@npm:4.1.12": + version: 4.1.12 + resolution: "@vitest/spy@npm:4.1.12" + checksum: 10c0/4732cafd7015b4ae39616f09405e9d1e5907b6edfdcc6eeee3a70518d966453ac75b979585fa2453a70dcacee22ecfc92e4708ff4c1dcdca1cb927d3f25306ed languageName: node linkType: hard -"@vitest/utils@npm:3.2.7": - version: 3.2.7 - resolution: "@vitest/utils@npm:3.2.7" +"@vitest/utils@npm:4.1.12": + version: 4.1.12 + resolution: "@vitest/utils@npm:4.1.12" dependencies: - "@vitest/pretty-format": "npm:3.2.7" - loupe: "npm:^3.1.4" - tinyrainbow: "npm:^2.0.0" - checksum: 10c0/fea57d6cf66853926f54ea6e9bd249b707120b0abba565d96a3880c7f04d5c5cd4778546879b9074cc73c0b81b475c1873791d4b3b3e5a324115b5bcfd3a46bb + "@vitest/pretty-format": "npm:4.1.12" + convert-source-map: "npm:^2.0.0" + tinyrainbow: "npm:^3.1.0" + checksum: 10c0/b70518b3a046700e080537f3aecd1fca3a88733000df55b4bdb24751c0209bd45fddf80fb5e217862e1e7d6b3fb63da5113fe04a27a177a3c04c1c0231ecfe18 languageName: node linkType: hard @@ -5011,16 +5017,10 @@ __metadata: languageName: node linkType: hard -"chai@npm:^5.2.0": - version: 5.3.3 - resolution: "chai@npm:5.3.3" - dependencies: - assertion-error: "npm:^2.0.1" - check-error: "npm:^2.1.1" - deep-eql: "npm:^5.0.1" - loupe: "npm:^3.1.0" - pathval: "npm:^2.0.0" - checksum: 10c0/b360fd4d38861622e5010c2f709736988b05c7f31042305fa3f4e9911f6adb80ccfb4e302068bf8ed10e835c2e2520cba0f5edc13d878b886987e5aa62483f53 +"chai@npm:^6.2.2": + version: 6.3.0 + resolution: "chai@npm:6.3.0" + checksum: 10c0/fd1bf7fc41295ba1eba18a44d68e204b3cb11b79c9ad51fd071de3ee85323c20d94afc07a386f1f5ff44a5da4a116614d419fc44a2d459e4b5b574aef9af4431 languageName: node linkType: hard @@ -5066,13 +5066,6 @@ __metadata: languageName: node linkType: hard -"check-error@npm:^2.1.1": - version: 2.1.3 - resolution: "check-error@npm:2.1.3" - checksum: 10c0/878e99038fb6476316b74668cd6a498c7e66df3efe48158fa40db80a06ba4258742ac3ee2229c4a2a98c5e73f5dff84eb3e50ceb6b65bbd8f831eafc8338607d - languageName: node - linkType: hard - "chokidar@npm:^5.0.0": version: 5.0.0 resolution: "chokidar@npm:5.0.0" @@ -5604,13 +5597,6 @@ __metadata: languageName: node linkType: hard -"deep-eql@npm:^5.0.1": - version: 5.0.2 - resolution: "deep-eql@npm:5.0.2" - checksum: 10c0/7102cf3b7bb719c6b9c0db2e19bf0aa9318d141581befe8c7ce8ccd39af9eaa4346e5e05adef7f9bd7015da0f13a3a25dcfe306ef79dc8668aedbecb658dd247 - languageName: node - linkType: hard - "deep-equal@npm:^2.0.5": version: 2.2.3 resolution: "deep-equal@npm:2.2.3" @@ -5808,7 +5794,7 @@ __metadata: vite-bundle-visualizer: "npm:^0" vite-plugin-checker: "npm:^0.14.5" vite-plugin-node-polyfills: "npm:^0.28.0" - vitest: "npm:^3.2.7" + vitest: "npm:^4.1.12" languageName: unknown linkType: soft @@ -6175,10 +6161,10 @@ __metadata: languageName: node linkType: hard -"es-module-lexer@npm:^1.7.0": - version: 1.7.0 - resolution: "es-module-lexer@npm:1.7.0" - checksum: 10c0/4c935affcbfeba7fb4533e1da10fa8568043df1e3574b869385980de9e2d475ddc36769891936dbb07036edb3c3786a8b78ccf44964cd130dedc1f2c984b6c7b +"es-module-lexer@npm:^2.0.0": + version: 2.3.2 + resolution: "es-module-lexer@npm:2.3.2" + checksum: 10c0/5e7389424c43478439f12f9a6aca1750f6f99afa384fc3de329f4a45f152ab156671055008adaafc74960877abf8cc338aeebf6bed8c21297b146fd6eb7a22f8 languageName: node linkType: hard @@ -6623,7 +6609,7 @@ __metadata: languageName: node linkType: hard -"expect-type@npm:^1.2.1": +"expect-type@npm:^1.3.0": version: 1.4.0 resolution: "expect-type@npm:1.4.0" checksum: 10c0/d40d76b8570695d36587beb3cc28494da2ca3ec8f04e67f5622ed2d372d850e401a9adef19c6835e1a8173903f157c79540b34c7b3fbd7cd8ce726cc903c57b7 @@ -8003,13 +7989,6 @@ __metadata: languageName: node linkType: hard -"js-tokens@npm:^9.0.1": - version: 9.0.1 - resolution: "js-tokens@npm:9.0.1" - checksum: 10c0/68dcab8f233dde211a6b5fd98079783cbcd04b53617c1250e3553ee16ab3e6134f5e65478e41d82f6d351a052a63d71024553933808570f04dbf828d7921e80e - languageName: node - linkType: hard - "js-yaml@npm:^3.14.1": version: 3.15.1 resolution: "js-yaml@npm:3.15.1" @@ -8352,13 +8331,6 @@ __metadata: languageName: node linkType: hard -"loupe@npm:^3.1.0, loupe@npm:^3.1.4": - version: 3.2.1 - resolution: "loupe@npm:3.2.1" - checksum: 10c0/910c872cba291309664c2d094368d31a68907b6f5913e989d301b5c25f30e97d76d77f23ab3bf3b46d0f601ff0b6af8810c10c31b91d2c6b2f132809ca2cc705 - languageName: node - linkType: hard - "lru-cache@npm:^5.1.1": version: 5.1.1 resolution: "lru-cache@npm:5.1.1" @@ -8384,7 +8356,7 @@ __metadata: languageName: node linkType: hard -"magic-string@npm:^0.30.17, magic-string@npm:^0.30.21, magic-string@npm:^0.30.3": +"magic-string@npm:^0.30.21, magic-string@npm:^0.30.3": version: 0.30.21 resolution: "magic-string@npm:0.30.21" dependencies: @@ -8896,6 +8868,13 @@ __metadata: languageName: node linkType: hard +"obug@npm:^2.1.1": + version: 2.2.1 + resolution: "obug@npm:2.2.1" + checksum: 10c0/8a7c001847d880fa6ba83c7bbee6a80fd271ee628439cd508c8647d53b217abb1759e2d5e4aaeb09a35d0a274bdb225a0a5a78eded3213d63e656153cf411b63 + languageName: node + linkType: hard + "once@npm:^1.3.0, once@npm:^1.3.1, once@npm:^1.3.2, once@npm:^1.4.0": version: 1.4.0 resolution: "once@npm:1.4.0" @@ -9121,13 +9100,6 @@ __metadata: languageName: node linkType: hard -"pathval@npm:^2.0.0": - version: 2.0.1 - resolution: "pathval@npm:2.0.1" - checksum: 10c0/460f4709479fbf2c45903a65655fc8f0a5f6d808f989173aeef5fdea4ff4f303dc13f7870303999add60ec49d4c14733895c0a869392e9866f1091fa64fd7581 - languageName: node - linkType: hard - "pbkdf2@npm:^3.1.2, pbkdf2@npm:^3.1.5": version: 3.1.6 resolution: "pbkdf2@npm:3.1.6" @@ -10411,10 +10383,10 @@ __metadata: languageName: node linkType: hard -"std-env@npm:^3.9.0": - version: 3.10.0 - resolution: "std-env@npm:3.10.0" - checksum: 10c0/1814927a45004d36dde6707eaf17552a546769bc79a6421be2c16ce77d238158dfe5de30910b78ec30d95135cc1c59ea73ee22d2ca170f8b9753f84da34c427f +"std-env@npm:^4.0.0-rc.1": + version: 4.3.0 + resolution: "std-env@npm:4.3.0" + checksum: 10c0/1e90dc69f32f853375c6de45dbe7219c8399e2a3ab3a972fdcd1cf3c20fe0e3c13bf58d57d6193b551d37a81c50dfb3f51e07774e9e48a7dc5a22dabcad7acbd languageName: node linkType: hard @@ -10589,15 +10561,6 @@ __metadata: languageName: node linkType: hard -"strip-literal@npm:^3.0.0": - version: 3.1.0 - resolution: "strip-literal@npm:3.1.0" - dependencies: - js-tokens: "npm:^9.0.1" - checksum: 10c0/50918f669915d9ad0fe4b7599902b735f853f2201c97791ead00104a654259c0c61bc2bc8fa3db05109339b61f4cf09e47b94ecc874ffbd0e013965223893af8 - languageName: node - linkType: hard - "styled-jsx@npm:^5": version: 5.1.7 resolution: "styled-jsx@npm:5.1.7" @@ -10750,10 +10713,10 @@ __metadata: languageName: node linkType: hard -"tinyexec@npm:^0.3.2": - version: 0.3.2 - resolution: "tinyexec@npm:0.3.2" - checksum: 10c0/3efbf791a911be0bf0821eab37a3445c2ba07acc1522b1fa84ae1e55f10425076f1290f680286345ed919549ad67527d07281f1c19d584df3b74326909eb1f90 +"tinyexec@npm:^1.0.2": + version: 1.3.1 + resolution: "tinyexec@npm:1.3.1" + checksum: 10c0/c590369cb3fa73cc18a3998caec8a00f9712d91309c881be3ac52b160fb2f80c7b1fbf3591858ab6abab47ad55385b0c86ec19982e32441a01f55298dab9ccd2 languageName: node linkType: hard @@ -10767,34 +10730,10 @@ __metadata: languageName: node linkType: hard -"tinyglobby@npm:^0.2.14": - version: 0.2.17 - resolution: "tinyglobby@npm:0.2.17" - dependencies: - fdir: "npm:^6.5.0" - picomatch: "npm:^4.0.4" - checksum: 10c0/7f7bb0f197c88bc4b20c231e0deca4240ca3bf313a88f5a7fee93a872b84966a4d50220947c0455ad07a60b3b360961c5b7fd979222aeb716a9f99b412002e4c - languageName: node - linkType: hard - -"tinypool@npm:^1.1.1": - version: 1.1.1 - resolution: "tinypool@npm:1.1.1" - checksum: 10c0/bf26727d01443061b04fa863f571016950888ea994ba0cd8cba3a1c51e2458d84574341ab8dbc3664f1c3ab20885c8cf9ff1cc4b18201f04c2cde7d317fff69b - languageName: node - linkType: hard - -"tinyrainbow@npm:^2.0.0": - version: 2.0.0 - resolution: "tinyrainbow@npm:2.0.0" - checksum: 10c0/c83c52bef4e0ae7fb8ec6a722f70b5b6fa8d8be1c85792e829f56c0e1be94ab70b293c032dc5048d4d37cfe678f1f5babb04bdc65fd123098800148ca989184f - languageName: node - linkType: hard - -"tinyspy@npm:^4.0.3": - version: 4.0.4 - resolution: "tinyspy@npm:4.0.4" - checksum: 10c0/a8020fc17799251e06a8398dcc352601d2770aa91c556b9531ecd7a12581161fd1c14e81cbdaff0c1306c93bfdde8ff6d1c1a3f9bbe6d91604f0fd4e01e2f1eb +"tinyrainbow@npm:^3.1.0": + version: 3.2.0 + resolution: "tinyrainbow@npm:3.2.0" + checksum: 10c0/22d9c303cd807026898dcb5ac5ffbf725b5a2cc8d042449769aed8f1266be94de5e95206b76cac948f68facafba5b80e9a9257c82e5fed2651be3fecf2b624ab languageName: node linkType: hard @@ -11322,21 +11261,6 @@ __metadata: languageName: node linkType: hard -"vite-node@npm:3.2.4": - version: 3.2.4 - resolution: "vite-node@npm:3.2.4" - dependencies: - cac: "npm:^6.7.14" - debug: "npm:^4.4.1" - es-module-lexer: "npm:^1.7.0" - pathe: "npm:^2.0.3" - vite: "npm:^5.0.0 || ^6.0.0 || ^7.0.0-0" - bin: - vite-node: vite-node.mjs - checksum: 10c0/6ceca67c002f8ef6397d58b9539f80f2b5d79e103a18367288b3f00a8ab55affa3d711d86d9112fce5a7fa658a212a087a005a045eb8f4758947dd99af2a6c6b - languageName: node - linkType: hard - "vite-plugin-checker@npm:^0.14.5": version: 0.14.5 resolution: "vite-plugin-checker@npm:0.14.5" @@ -11391,7 +11315,7 @@ __metadata: languageName: node linkType: hard -"vite@npm:^5.0.0 || ^6.0.0 || ^7.0.0-0, vite@npm:^7.3.6": +"vite@npm:^6.0.0 || ^7.0.0 || ^8.0.0, vite@npm:^7.3.6": version: 7.3.6 resolution: "vite@npm:7.3.6" dependencies: @@ -11446,49 +11370,59 @@ __metadata: languageName: node linkType: hard -"vitest@npm:^3.2.7": - version: 3.2.7 - resolution: "vitest@npm:3.2.7" +"vitest@npm:^4.1.12": + version: 4.1.12 + resolution: "vitest@npm:4.1.12" dependencies: - "@types/chai": "npm:^5.2.2" - "@vitest/expect": "npm:3.2.7" - "@vitest/mocker": "npm:3.2.7" - "@vitest/pretty-format": "npm:^3.2.7" - "@vitest/runner": "npm:3.2.7" - "@vitest/snapshot": "npm:3.2.7" - "@vitest/spy": "npm:3.2.7" - "@vitest/utils": "npm:3.2.7" - chai: "npm:^5.2.0" - debug: "npm:^4.4.1" - expect-type: "npm:^1.2.1" - magic-string: "npm:^0.30.17" + "@vitest/expect": "npm:4.1.12" + "@vitest/mocker": "npm:4.1.12" + "@vitest/pretty-format": "npm:4.1.12" + "@vitest/runner": "npm:4.1.12" + "@vitest/snapshot": "npm:4.1.12" + "@vitest/spy": "npm:4.1.12" + "@vitest/utils": "npm:4.1.12" + es-module-lexer: "npm:^2.0.0" + expect-type: "npm:^1.3.0" + magic-string: "npm:^0.30.21" + obug: "npm:^2.1.1" pathe: "npm:^2.0.3" - picomatch: "npm:^4.0.2" - std-env: "npm:^3.9.0" + picomatch: "npm:^4.0.3" + std-env: "npm:^4.0.0-rc.1" tinybench: "npm:^2.9.0" - tinyexec: "npm:^0.3.2" - tinyglobby: "npm:^0.2.14" - tinypool: "npm:^1.1.1" - tinyrainbow: "npm:^2.0.0" - vite: "npm:^5.0.0 || ^6.0.0 || ^7.0.0-0" - vite-node: "npm:3.2.4" + tinyexec: "npm:^1.0.2" + tinyglobby: "npm:^0.2.15" + tinyrainbow: "npm:^3.1.0" + vite: "npm:^6.0.0 || ^7.0.0 || ^8.0.0" why-is-node-running: "npm:^2.3.0" peerDependencies: "@edge-runtime/vm": "*" - "@types/debug": ^4.1.12 - "@types/node": ^18.0.0 || ^20.0.0 || >=22.0.0 - "@vitest/browser": 3.2.7 - "@vitest/ui": 3.2.7 + "@opentelemetry/api": ^1.9.0 + "@types/node": ^20.0.0 || ^22.0.0 || >=24.0.0 + "@vitest/browser-playwright": 4.1.12 + "@vitest/browser-preview": 4.1.12 + "@vitest/browser-webdriverio": ^4.1.11 + "@vitest/coverage-istanbul": 4.1.12 + "@vitest/coverage-v8": 4.1.12 + "@vitest/ui": 4.1.12 happy-dom: "*" jsdom: "*" + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 peerDependenciesMeta: "@edge-runtime/vm": optional: true - "@types/debug": + "@opentelemetry/api": optional: true "@types/node": optional: true - "@vitest/browser": + "@vitest/browser-playwright": + optional: true + "@vitest/browser-preview": + optional: true + "@vitest/browser-webdriverio": + optional: true + "@vitest/coverage-istanbul": + optional: true + "@vitest/coverage-v8": optional: true "@vitest/ui": optional: true @@ -11496,9 +11430,11 @@ __metadata: optional: true jsdom: optional: true + vite: + optional: false bin: vitest: ./vitest.mjs - checksum: 10c0/4eb7a63a1d62b88c425bcbc609835055a5644a1994d6f47605fe396dddf732e3c0277c9ec89a028fe81557dc4051dd15fc15b9eba6a51d1466cd5c682ddc1261 + checksum: 10c0/0e571967f9fa2192170203afcb439434b04fbcd914a4dde176544fc45768e76226a284f6fa9d9a4e9bc9fce593bfbe6ab50ee25b3ca50c278eb33562345e0aaf languageName: node linkType: hard From 6919967fb575d7ab9b1272fabb2498337284a4e2 Mon Sep 17 00:00:00 2001 From: Matias Arriola Date: Mon, 26 Oct 2026 10:55:34 -0300 Subject: [PATCH 14/14] chore: upgrade pbkdf2 to fix denial of service vulnerability --- yarn.lock | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/yarn.lock b/yarn.lock index 1b17ac1..6f2f9c5 100644 --- a/yarn.lock +++ b/yarn.lock @@ -9101,8 +9101,8 @@ __metadata: linkType: hard "pbkdf2@npm:^3.1.2, pbkdf2@npm:^3.1.5": - version: 3.1.6 - resolution: "pbkdf2@npm:3.1.6" + version: 3.1.7 + resolution: "pbkdf2@npm:3.1.7" dependencies: create-hash: "npm:^1.2.0" create-hmac: "npm:^1.1.7" @@ -9110,7 +9110,7 @@ __metadata: safe-buffer: "npm:^5.2.1" sha.js: "npm:^2.4.12" to-buffer: "npm:^1.2.2" - checksum: 10c0/828be4a5eed15c502dfa490247506c6abd4e539f6e1ea265d2b8a668292c9e07af4e6d4d7a5d3aa8ad12274da7cea1bf1b3dfc1f5f19bcdeee5157d1bf83f7f3 + checksum: 10c0/0de7dd4c90313f4ca6ed87dbc763dded1490409e6c784028e2b178f8e9431c826571c62ebc633a08eadafc6c327c86f22975e291ad48e42fcca081e40e1f9277 languageName: node linkType: hard