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 df17305..f6feb94 100644 --- a/README.md +++ b/README.md @@ -55,8 +55,17 @@ Run all code-quality to validate changes: $ yarn run check ``` -This runs the TypeScript typecheck, Prettier check, lint, and tests. -Individual checks can also be run with `yarn typecheck`, `yarn prettify:check`, `yarn lint`, and `yarn test`. +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: `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 +`yarn lint:cached` locally and `yarn lint:baseline:prune` after legacy fixes. +Review baseline increases explicitly; never regenerate in CI. ## Some development tips diff --git a/eslint-suppressions.json b/eslint-suppressions.json new file mode 100644 index 0000000..28a432b --- /dev/null +++ b/eslint-suppressions.json @@ -0,0 +1,199 @@ +{ + "src/data/__tests__/api-futures.spec.ts": { + "eyeseetea/http-client-access": { + "count": 2 + } + }, + "src/domain/entities/generic/Collection.ts": { + "@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-unsafe-return": { + "count": 2 + }, + "no-restricted-syntax": { + "count": 2 + } + }, + "src/domain/entities/generic/Future.ts": { + "@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 + }, + "no-restricted-syntax": { + "count": 3 + } + }, + "src/domain/entities/generic/HashMap.ts": { + "@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 + } + }, + "src/domain/entities/generic/Struct.ts": { + "@typescript-eslint/no-unsafe-member-access": { + "count": 1 + }, + "@typescript-eslint/no-unsafe-return": { + "count": 1 + }, + "@typescript-eslint/no-unsafe-type-assertion": { + "count": 4 + }, + "no-restricted-syntax": { + "count": 1 + } + }, + "src/domain/entities/generic/__tests__/Future.spec.ts": { + "@typescript-eslint/no-unsafe-argument": { + "count": 1 + }, + "@typescript-eslint/no-unsafe-assignment": { + "count": 1 + }, + "@typescript-eslint/no-unsafe-type-assertion": { + "count": 1 + }, + "no-restricted-syntax": { + "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 + } + } +} diff --git a/eslint.config.mjs b/eslint.config.mjs index 5fe5fe9..049c191 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -1,133 +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 baselineConfig from "./eslint/baseline-config.mjs"; -import requireFutureBlockCapture from "./eslint/rules/require-future-block-capture.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. -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: { - local: { - rules: { - "require-future-block-capture": requireFutureBlockCapture, - }, - }, - "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: "$" }, - ], - "local/require-future-block-capture": "error", - }, - }, - - { - 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", - }, - }, - - { - files: ["**/*.js"], - languageOptions: { parserOptions: { project: null } }, - rules: { "@typescript-eslint/no-misused-promises": "off" }, - } -); +// 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 new file mode 100644 index 0000000..8fda607 --- /dev/null +++ b/eslint/MIGRATION.md @@ -0,0 +1,298 @@ +# 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 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 + +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 +`{"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` | 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. | +| 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. | + +Architecture rules accept layout options; `client-construction` also accepts factory +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 + +For repositories under `src/data//`, presentation under `src/presentation/`, +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/layer-dependencies": ["warn", { paths }], + "eyeseetea/http-client-access": ["warn", { paths }], + "eyeseetea/client-construction": ["warn", { + paths, + clientFactories: ["createApp", "createTest"] + }] + } +}]; +``` + +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. + +[Policy-only composition](#incorporate-the-configuration) leaves 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. +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. + +### 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 +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", // Optional stricter local policy: includes constraints. + }, + }, + { + 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 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. + +## 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). + +### 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 new file mode 100644 index 0000000..4dc7a37 --- /dev/null +++ b/eslint/README.md @@ -0,0 +1,130 @@ +# EyeSeeTea ESLint policy + +`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 + +`eyeseetea-plugin.ts` exports the custom rules under the `eyeseetea` namespace: +[layer-dependencies](rules/layer-dependencies/README.md), +[http-client-access](rules/http-client-access/README.md), +[client-construction](rules/client-construction/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`; 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`. + +`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. +- `baseline-config.mjs`: company policy promoted to errors, applied last to override framework defaults. + +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/layer-dependencies": "warn", + "eyeseetea/http-client-access": "off", + "eyeseetea/client-construction": "off" + } +}]; +``` + +The rules share [path matching and TypeScript resolution](rules/shared/README.md) +while retaining independent configuration. + +## Severity and legacy code + +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`, 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 +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 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. | +| 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` / `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/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/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..b8bfae8 --- /dev/null +++ b/eslint/baseline.spec.mjs @@ -0,0 +1,64 @@ +import path from "node:path"; +import { expect, test } from "vitest"; + +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( + 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 new file mode 100644 index 0000000..08ace71 --- /dev/null +++ b/eslint/eyeseetea-config.spec.ts @@ -0,0 +1,222 @@ +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; + 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" } + ); + const messages = result!.messages.filter( + message => + message.ruleId === "@typescript-eslint/no-unsafe-type-assertion" || message.fatal + ); + expect(messages).toHaveLength(3); + 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/")) { + for (const rule of [ + "layer-dependencies", + "http-client-access", + "client-construction", + ]) { + expect(config?.rules?.[`eyeseetea/${rule}`]).toEqual( + expect.arrayContaining([2]) + ); + } + expect(config?.rules?.["eyeseetea/no-collection-mutation"]).toEqual( + expect.arrayContaining([2]) + ); + } else { + for (const rule of [ + "layer-dependencies", + "http-client-access", + "client-construction", + ]) { + expect(config!.rules![`eyeseetea/${rule}`]).toBeUndefined(); + } + expect(config!.rules!["eyeseetea/no-collection-mutation"]).toBeUndefined(); + } + } + }); + 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: 2 }), + 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("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'); + `, + [ + { + languageOptions: { parser }, + rules: { "no-restricted-syntax": config!.rules!["no-restricted-syntax"] }, + }, + ] + ); + expect(result).toHaveLength(4); + expect(result.every(message => message.severity === 2)).toBe(true); + }); +}); diff --git a/eslint/eyeseetea-config.ts b/eslint/eyeseetea-config.ts new file mode 100644 index 0000000..77e9fc7 --- /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 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']", + 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/layer-dependencies": "warn", + "eyeseetea/http-client-access": "warn", + "eyeseetea/client-construction": "warn", + "eyeseetea/no-collection-mutation": "warn", + "prefer-const": "warn", + "no-var": "warn", + "no-param-reassign": ["warn", { props: true }], + // 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", ...productionSyntax], + "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": "off", + "@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", + ...productionSyntax, + { + selector: "TSTypeReference[typeName.name='Promise']", + message: "Return FutureData instead of Promise in domain and data.", + }, + ], + }, + }, + { + files: tests, + plugins: { "testing-library": testingLibrary }, + rules: { + "eyeseetea/no-collection-mutation": "off", + "no-restricted-syntax": [ + "warn", + anySyntax, + { + 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", + 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='$$']", + 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..2e077e0 --- /dev/null +++ b/eslint/eyeseetea-plugin.ts @@ -0,0 +1,16 @@ +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 noCollectionMutation from "./rules/no-collection-mutation/rule.ts"; +import requireFutureBlockCapture from "./rules/require-future-block-capture/rule.ts"; + +export default { + rules: { + "layer-dependencies": layerDependencies, + "http-client-access": httpClientAccess, + "client-construction": clientConstruction, + "no-collection-mutation": noCollectionMutation, + "require-future-block-capture": requireFutureBlockCapture, + }, +} satisfies TSESLint.FlatConfig.Plugin; 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/rules/client-construction/README.md b/eslint/rules/client-construction/README.md new file mode 100644 index 0000000..57806dc --- /dev/null +++ b/eslint/rules/client-construction/README.md @@ -0,0 +1,34 @@ +# 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 [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. + +## Limitations + +Checks direct syntax, not transitive dependencies or whole-program data flow; +see [shared limitations](../shared/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..280419f --- /dev/null +++ b/eslint/rules/client-construction/rule.ts @@ -0,0 +1,7 @@ +import { createArchitectureRule } from "../shared/architecture.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..1fb70e6 --- /dev/null +++ b/eslint/rules/http-client-access/README.md @@ -0,0 +1,52 @@ +# 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. +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 + +```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 [shared architecture options](../shared/README.md#options) for `paths` groups, +globs, defaults, and replacement semantics. Roots and adapters override layer membership. + +`clientFactories` applies only to `client-construction`. + +## Limitations + +Checks direct syntax, not transitive dependencies or whole-program data flow; +see [shared limitations](../shared/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. + +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. 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..1416f52 --- /dev/null +++ b/eslint/rules/http-client-access/rule.spec.ts @@ -0,0 +1,70 @@ +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("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');", + [ + { + 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..33406df --- /dev/null +++ b/eslint/rules/http-client-access/rule.ts @@ -0,0 +1,7 @@ +import { createArchitectureRule } from "../shared/architecture.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..405c79a --- /dev/null +++ b/eslint/rules/layer-dependencies/README.md @@ -0,0 +1,36 @@ +# 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 [shared architecture options](../shared/README.md#options) for `paths` groups, +globs, defaults, and replacement semantics. Roots and adapters override layer membership. + +`clientFactories` applies only to `client-construction`. + +## Limitations + +Checks direct syntax, not transitive dependencies or whole-program data flow; +see [shared limitations](../shared/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..647c1ff --- /dev/null +++ b/eslint/rules/layer-dependencies/rule.ts @@ -0,0 +1,7 @@ +import { createArchitectureRule } from "../shared/architecture.ts"; + +export default createArchitectureRule( + "layer-dependencies", + "Check dependency directions between application layers.", + "layerDependencies" +); diff --git a/eslint/rules/no-collection-mutation/README.md b/eslint/rules/no-collection-mutation/README.md new file mode 100644 index 0000000..940b172 --- /dev/null +++ b/eslint/rules/no-collection-mutation/README.md @@ -0,0 +1,47 @@ +# eyeseetea/no-collection-mutation + +Prefer new collections over in-place mutations. Enabled as a warning for +production `src/**/*.{ts,tsx}` by the EyeSeeTea config. Test scopes are excluded +to allow mutable fixture builders. 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..68ae2c8 --- /dev/null +++ b/eslint/rules/no-collection-mutation/rule.spec.ts @@ -0,0 +1,79 @@ +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.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( + "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..e5f9ac3 --- /dev/null +++ b/eslint/rules/no-collection-mutation/rule.ts @@ -0,0 +1,65 @@ +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 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)) + 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/eslint/rules/shared/README.md b/eslint/rules/shared/README.md new file mode 100644 index 0000000..6b0d52b --- /dev/null +++ b/eslint/rules/shared/README.md @@ -0,0 +1,104 @@ +# Shared architecture configuration + +The [layer-dependencies](../layer-dependencies/README.md), +[http-client-access](../http-client-access/README.md), and +[client-construction](../client-construction/README.md) rules share path matching, +TypeScript resolution, and boundary helpers. Enable and configure each rule independently. + +## Rule Details + +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. + +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 + +The skeleton layout and `getWebappCompositionRoot` factory are the defaults. +Pass `paths` to each enabled rule; pass `clientFactories` only to `client-construction`: + +```js +"eyeseetea/client-construction": ["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"] +}] +``` + +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. + +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 + +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. + +## Exceptions + +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). +Disabling `http-client-access` leaves layer dependency and client-construction checks active. diff --git a/eslint/rules/shared/architecture.spec.ts b/eslint/rules/shared/architecture.spec.ts new file mode 100644 index 0000000..8636e9c --- /dev/null +++ b/eslint/rules/shared/architecture.spec.ts @@ -0,0 +1,351 @@ +import path from "node:path"; +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"; +import { afterAll, beforeAll, describe, expect, test } from "vitest"; +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: TestOptions = {}, + cwd = globalThis.process.cwd() +) { + return new Linter({ cwd }).verify( + code, + [ + { + files: ["**/*.ts"], + languageOptions: { parser }, + plugins: { eyeseetea: plugin }, + 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) } + ); +} + +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.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( + "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([]); + }); +}); + +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: TestOptions = {}) => + 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("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"], + ["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("disables rules independently", () => { + expect( + lint("import '@/presentation/View'; fetch('/api');", "src/domain/Probe.ts", { + disabledRules: ["layer-dependencies"], + }) + ).toHaveLength(1); + expect( + lint("import '@/presentation/View'; fetch('/api');", "src/domain/Probe.ts", { + disabledRules: ["http-client-access"], + }) + ).toHaveLength(1); + expect( + lint( + "import { D2Api } from '@eyeseetea/d2-api'; new D2Api();", + "src/data/users/UserRepository.ts", + { disabledRules: ["client-construction"] } + ) + ).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", { paths: { typo: [] } } as ArchitectureOptions) + ).toThrow(); + }); + test.each([ + [ + "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", + [], + ], + ])("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("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", + 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/shared/architecture.ts b/eslint/rules/shared/architecture.ts new file mode 100644 index 0000000..648e7c8 --- /dev/null +++ b/eslint/rules/shared/architecture.ts @@ -0,0 +1,343 @@ +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 globalNamespaces = new Set(["window", "globalThis", "self"]); +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[]; +}; + +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 = "layerDependencies" | "httpClientAccess" | "clientConstruction"; + +export function createArchitectureRule( + ruleName: string, + description: string, + check: 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 === "clientConstruction" + ? { + clientFactories: { + type: "array", + items: { type: "string", minLength: 1 }, + uniqueItems: true, + }, + } + : {}), + }, + }, + ], + 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 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 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) { + if ( + (check !== "layerDependencies" && check !== "httpClientAccess") || + typeof source !== "string" + ) + return; + const target = resolveModule(source); + const targetMatches = (key: keyof typeof defaultPaths) => + target !== undefined && matches(key, target); + 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))})` : ""}.${guidance ? ` ${guidance}` : ""}` + ); + if (check === "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 (check === "httpClientAccess") { + if ( + domain && + (httpPackages.test(source) || + infrastructurePackages.test(source) || + isBuiltin(source)) + ) + boundary("Domain", "platform infrastructure"); + else if ((repository || presentation) && httpPackages.test(source)) + boundary( + repository ? "Repositories" : "Presentation", + "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 && + !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 (check !== "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" && + def.parent.type === "ImportDeclaration" && + isClientSource(def.parent.source.value) + ); + 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 (check !== "httpClientAccess") return; + for (const scope of sourceCode.scopeManager?.scopes ?? []) { + for (const reference of scope.references) { + 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; + 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(qualifiedName) + ) + report( + reference.identifier, + "Use d2-api for DHIS2 access. For an external API, add a justified exception for this rule." + ); + 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/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", + }, + }, +]; 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 b1f9fa3..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", @@ -91,22 +91,28 @@ "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": "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/", "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", "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/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..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}"], + include: ["src/**/*.spec.{ts,tsx,mjs}"], setupFiles: "./src/tests/setup.ts", exclude: ["**/node_modules/**", "**/src/tests/playwright/**"], globals: true, diff --git a/yarn.lock b/yarn.lock index 67e77ab..6f2f9c5 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 @@ -7119,10 +7105,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 +7118,7 @@ __metadata: optional: true bin: handlebars: bin/handlebars - checksum: 10c0/22f8105a7e68e81aff2662bb434edf05f757d21d850731d71cec886d69c10cd33d3c43e34b2892968ec62de8241611851d3d0674c8ef324ea3e01dc66262faa9 + checksum: 10c0/9b5573584ae5836172ae3f1502d9819568ba1b92ee83b81b18223beeb4c07486595e7b0fa633102beabc66ed06fe6e7da1dd9a9ea8c7072b9550b9a88809165c languageName: node linkType: hard @@ -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: @@ -8565,7 +8537,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 @@ -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,16 +9100,9 @@ __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" + version: 3.1.7 + resolution: "pbkdf2@npm:3.1.7" dependencies: create-hash: "npm:^1.2.0" create-hmac: "npm:^1.1.7" @@ -9138,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 @@ -10377,9 +10349,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 @@ -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