diff --git a/.agents/decisions/0124-lint-the-patterns-agent-rebuilds-repeat.md b/.agents/decisions/0124-lint-the-patterns-agent-rebuilds-repeat.md index 182aa305..2a831185 100644 --- a/.agents/decisions/0124-lint-the-patterns-agent-rebuilds-repeat.md +++ b/.agents/decisions/0124-lint-the-patterns-agent-rebuilds-repeat.md @@ -10,8 +10,9 @@ Nine agents rebuilt a reference feature from its PRD: six to-do rebuilds and three greeting rebuilds. Every rebuild passed every gate, and each still carried patterns a reviewer would reject. Six of them recurred, can be found in -one file with no type information, and had no false positive in the -reference. Several are what agents reach for in place of a banned form: with +one file with no type information, and leave the fixed reference with no +finding. Two later to-do rebuilds, r7 and r8, repeated them and added one +variant, a status read through a lookup object. Several are what agents reach for in place of a banned form: with `noUncheckedIndexedAccess` on and the non-null assertion banned, a test that needs a value writes `?? ''`, because the repository offered no sanctioned way to unwrap one. @@ -23,43 +24,82 @@ result-root override, `{apps,packages}/*/src/**/*.{ts,tsx}` and `showcase/*/*/src/**/*.{ts,tsx}`: - `policy/one-status-from-hooks`: a `use*` hook returns one `status` union, - and one object it returns reads at most one of a query's `data`, `error`, - `status`, `isPending`, `isLoading`, `isFetching`, `isError` and - `isSuccess`, following one `const` binding. -- `policy/test-unwraps-values`: a test unwraps a value with `present()`. - `?? ''` and an `x.ok ? … : ` stand-in fail. The rule also runs on - each result's `web/e2e/**/*.ts`, in an override of its own. + and one object it returns reads at most one of a query's `data`, `status`, + `isPending`, `isLoading`, `isError` and `isSuccess`. A query is a `const` + bound to the result of `useQuery`, `useSuspenseQuery` or `useInfiniteQuery`. + A lookup keyed by the status, such as `STATES[list.status]`, reads + `status`. The rule follows one `const` binding, and resolves each name in + its own scope. `error` and `isFetching` describe a state rather than choose + one, so `{ status: list.status, problem: list.error }` and + `{ list: list.data, refreshing: list.isFetching }` pass, as does a mutation + hook's `{ submitting, problem }`. +- `policy/test-unwraps-values`: a test takes a value with `present()` and an + outcome's value with `unwrap()`. `?? ''` fails, and so does a ternary on + `x.ok` whose other branch reads `x.value…` and whose fallback is a literal; + `response.ok ? 'passed' : 'failed'` passes. The rule also runs on each + result's `web/e2e/**/*.ts`, in an override of its own. - `policy/test-imports-the-type`: a test declares no interface or type alias - that a non-test module in its folder exports. -- `policy/message-uses-its-limit`: a string or JSX text holds no number that a - module-scope `const` of 10 or more in the same file names. Smaller numbers - appear in ordinary prose too often to tie to one constant. -- `policy/import-types-from-their-owner`: a module under `src/routes//` - or `src/features//`, other than `index.ts`, re-exports nothing, from - a source or from an import. + that a non-test module in its folder exports with a declaration at the + start of a line, so `export type` inside a string or comment does not + count. One scan of a folder serves all its tests until a module in it + changes. +- `policy/message-uses-its-limit`: a string, template or JSX text writes no + limit as a count. A limit is a module-scope `const` of 10 or more in the + same file whose name holds `MAX`, `MIN`, `MAXIMUM`, `MINIMUM`, `LIMIT`, + `LENGTH` or `LEN` (`TITLE_MAX_LENGTH`, `maxTitleLength`). A count is the + number, or its grouped form such as `1,000`, followed by a word + (`100 characters`), so `100%`, `gap-10` and a port in a URL pass. JSX + attribute values and import sources hold no message and are skipped. + Smaller numbers appear in ordinary prose too often to tie to one + constant. +- `policy/reexport-only-from-index`: a module under `src/routes//` or + `src/features//`, other than the slice's own `index.ts`, re-exports + nothing, from a source or from an import, so its siblings import each name + from the module that declares it. A nested barrel such as + `src/routes/todos/components/index.ts` is not the slice's public surface + and fails too: `no-restricted-imports` already admits only + `routes/*/index.ts` and `features/*/index.ts` as entry points. - `policy/keep-rejections`: a `.catch` or second `.then` handler that ignores its error and returns a literal, `undefined` or nothing fails, following one - `const` binding. + `const` binding resolved in the handler's own scope. When a caller means to + ignore a failure, settle the promise and read the result: + `void Promise.allSettled([prefetch()])` for a fire-and-forget call, or + `Promise.allSettled([save()]).then(([result]) => result?.status === 'fulfilled')` + for a yes or no. Both keep the rejection in the settled result and pass + `pnpm lint:policy`, `pnpm lint:anti-slop` and Biome. A handler that uses its + error, such as `.catch(report)`, also passes. Tests and specs are outside the three source rules, and inside the two test -rules. Ship `present` in `tooling/jest/present.ts`, beside the Jest setup that -holds the other shared test helpers. It returns a defined value or the value of -an ok outcome, and throws otherwise. The Jest setup makes it a global, typed by -`tooling/types/present.d.ts`, because a unit test in a package may import -nothing from outside that package (`policy/slice-isolation`). A result is -self-contained and a showcase copies the reference's `e2e/` folder, so each -result's `e2e/fixtures.ts` holds its own five-line `present` for defined -values, and each E2E spec imports it from there. +rules. Ship `present` and `unwrap` in `tooling/jest/test-globals.ts`, beside +the Jest setup that holds the other shared test helpers. `present(value)` +returns a value that is neither `null` nor `undefined` and throws otherwise. +`unwrap(outcome)` takes only an `{ ok: true, value } | { ok: false }` outcome, +returns its value, and throws with the failure otherwise. The Jest setup makes +both globals, because a unit test in a package may import nothing from outside +that package (`policy/slice-isolation`). `tooling/types/test-globals.d.ts` +types them, and only the test type programs, `tsconfig.test.json` and +`tsconfig.api.test.json`, include it: the web and api programs exclude test +files, so a production module that calls either fails `pnpm typecheck`. A +result is self-contained and a showcase copies the reference's `e2e/` folder, +so each result's `e2e/fixtures.ts` holds its own five-line `present`, which a +unit test holds to the same behaviour as the Jest global, and each E2E spec +imports it from there. ## Consequences The reference fixes its own hits in the same change: four in `application.test.ts`, five in `e2e/todos.spec.ts` and the restated `Todo` in `TodosPage.test.tsx`. Each rule fires on the rebuild samples it was mined -from. Until the pre-commit hook runs `pnpm lint:policy`, these rules fail at -pre-push and in CI rather than at commit. +from, and r7 and r8 confirm them. -`policy/one-status-from-hooks` reads only the returned object, so a hook that -splits the flags across helper functions passes. `policy/test-unwraps-values` -leaves other fallback strings such as `?? 'waiting'` to review, because a test -may render one on purpose. Both are trade-offs for a zero false-positive rate. +Each rule trades recall for precision, and its fixtures, valid and invalid, +mark the boundary. `policy/one-status-from-hooks` reads only the returned +object, so a hook that splits the flags across helper functions passes, and it +leaves `data` beside `error` to review. `policy/test-unwraps-values` leaves +other fallback strings such as `?? 'waiting'` to review, because a test may +render one on purpose. `policy/message-uses-its-limit` skips JSX attributes, so +a `placeholder` that restates a limit passes. The first version of these rules +reported five shapes that were not the pattern, found in review: a query's +`isFetching`, a mutation's state, a status beside its error, a flattened local +union and an `ok` check that never reads `value`. Each is now a passing +fixture. diff --git a/.agents/project/ARCHITECTURE.md b/.agents/project/ARCHITECTURE.md index 1b482243..41b244bc 100644 --- a/.agents/project/ARCHITECTURE.md +++ b/.agents/project/ARCHITECTURE.md @@ -143,7 +143,7 @@ each check's message names the fix. | Every file belongs to one role and one slice. | Fallow `coverage.requireAllFiles`; `policy/slice-isolation` for a loose file under `src/routes/` or `src/features/` | `pnpm arch:gate`, `pnpm lint:policy` | | A package reaches another only by its package name. | `policy/slice-isolation` (relative import out of the package) | `pnpm lint:policy` | | A module is imported through its `index.ts`. | Oxlint `no-restricted-imports`; API reports | `pnpm lint:policy`, `pnpm api:check` | -| A slice re-exports only from its `index.ts`; its other modules import each name from the module that declares it. | Oxlint `policy/import-types-from-their-owner` | `pnpm lint:policy` | +| A slice re-exports only from its own `index.ts`, the one barrel it keeps; its other modules import each name from the module that declares it. | Oxlint `policy/reexport-only-from-index` | `pnpm lint:policy` | | Procedures validate their input with Effect Schema. | Oxlint `policy/procedure-input-schema` | `pnpm lint:policy` | | Procedures delegate to application logic. | Fallow `api-procedures` value-imports only `api-trpc`, `api-application` | `pnpm arch:gate` | | Integrations import domain types only. | Fallow `api-integrations` allows `api-domain` through `allowTypeOnly` | `pnpm arch:gate`, `pnpm fallow:audit` | @@ -157,7 +157,7 @@ each check's message names the fix. | One React component per file. | Oxlint `policy/one-component-per-file` | `pnpm lint:policy` | | State, server state and form state live in `use*` hooks. | Oxlint `policy/state-and-effects-in-hooks` | `pnpm lint:policy` | | Forms validate with Effect Schema. | Oxlint `policy/form-uses-effect-schema` | `pnpm lint:policy` | -| Web code has the DOM and no Node; api code has no DOM and only erasable syntax; domain code has neither. | `tsconfig.json` (web, ui), `tsconfig.api.json` and `tsconfig.domain.json` over `tsconfig.base.json` | `pnpm typecheck` | +| Web code has the DOM and no Node; api code has no DOM and only erasable syntax; domain code has neither. Only tests see the Jest test globals. | `tsconfig.json` (web, ui), `tsconfig.api.json` and `tsconfig.domain.json` over `tsconfig.base.json`; `tsconfig.test.json` and `tsconfig.api.test.json` for tests | `pnpm typecheck` | | Behaviour is defined by each result's E2E specs. | Playwright, one project per result | `pnpm e2e` | Fallow loads [`contract.rules.jsonc`](../../tooling/architecture/contract.rules.jsonc) diff --git a/.agents/project/CONVENTIONS.md b/.agents/project/CONVENTIONS.md index 8e4a4710..ad1e991b 100644 --- a/.agents/project/CONVENTIONS.md +++ b/.agents/project/CONVENTIONS.md @@ -37,11 +37,11 @@ The Oxlint rules and Biome naming override run on `{apps,packages}/*/src/**` and | Functions defined inside a component start with `handle` (`handleAdd`). | Oxlint `policy/handler-names` | | Callback props start with `on` (`onAdd`). | Oxlint `policy/callback-prop-names` | | A hook returns one `status` union for its server state (`{ status: 'loading' } \| { status: 'failed' } \| { status: 'loaded'; todos }`), so the page renders exactly one state; it keeps a query's `data`, `isPending`, `isError` and `status` inside that union. | Oxlint `policy/one-status-from-hooks` ([ADR 0124](../decisions/0124-lint-the-patterns-agent-rebuilds-repeat.md)) | -| A test unwraps a value it expects with `present(value)`, which also takes an `{ ok, value }` outcome, so a missing value fails the test where it is read; `?? ''` and `x.ok ? x.value : ''` fail the gate. `present` is a Jest global, and an E2E spec imports it from `./fixtures`. | Oxlint `policy/test-unwraps-values` in unit tests and E2E specs ([ADR 0124](../decisions/0124-lint-the-patterns-agent-rebuilds-repeat.md)) | +| A test takes a value it expects with `present(value)`, which fails the test on `null` or `undefined`, and the value of an `{ ok, value }` outcome with `unwrap(outcome)`, which fails the test with the failure; `?? ''` and `x.ok ? x.value : ''` fail the gate. Both are Jest globals that only test files can see, and an E2E spec imports `present` from `./fixtures`. | Oxlint `policy/test-unwraps-values` in unit tests and E2E specs ([ADR 0124](../decisions/0124-lint-the-patterns-agent-rebuilds-repeat.md)) | | A test imports a type its folder already exports (`import type { Todo } from './useTodos'`), so it follows the real shape. | Oxlint `policy/test-imports-the-type` | -| A message interpolates the limit constant it describes (`` `Use ${TITLE_MAX_LENGTH} characters or fewer` ``), so the text changes with the limit. | Oxlint `policy/message-uses-its-limit` for module constants of 10 or more | -| A module under `src/routes/` or `src/features/` imports a name straight from the module that declares it; a slice re-exports only from its `index.ts`. | Oxlint `policy/import-types-from-their-owner` | -| A failure reaches the place that shows it (`onError`, a `failure` state) and the promise keeps its rejection; `.catch(() => undefined)` and `.then(ok, () => false)` fail the gate. | Oxlint `policy/keep-rejections` | +| A message interpolates the limit constant it describes (`` `Use ${TITLE_MAX_LENGTH} characters or fewer` ``), so the text changes with the limit. | Oxlint `policy/message-uses-its-limit` for module constants of 10 or more named as a limit (`MAX`, `MIN`, `LIMIT`, `LENGTH`), written as a count (`100 characters`) outside JSX attributes | +| A module under `src/routes/` or `src/features/` imports a name straight from the module that declares it; a slice re-exports only from its own `index.ts`, and a nested `components/index.ts` re-exports nothing. | Oxlint `policy/reexport-only-from-index` | +| A failure reaches the place that shows it (`onError`, a `failure` state) and the promise keeps its rejection; `.catch(() => undefined)` and `.then(ok, () => false)` fail the gate. To ignore a failure on purpose, settle the promise with `Promise.allSettled` and read its result (`void Promise.allSettled([prefetch()])`). | Oxlint `policy/keep-rejections` ([ADR 0124](../decisions/0124-lint-the-patterns-agent-rebuilds-repeat.md)) | | Page components (`Page`) live in `src/routes//`. | Oxlint `policy/pages-in-routes`, Fallow `web-routes` zone | | Each file under `src/routes/` or `src/features/` sits in a slice folder, and a slice imports no sibling slice. | Oxlint `policy/slice-isolation` for static relative module references; Fallow child zones for `apps/web` routes. Computed specifiers and non-relative aliases remain a gap in the Oxlint rule. | | A relative import stays inside its package; other packages are imported by name (`@repo/ui`). | Oxlint `policy/slice-isolation` | diff --git a/.agents/project/PR_QUALITY.md b/.agents/project/PR_QUALITY.md index 74720f8c..f594861a 100644 --- a/.agents/project/PR_QUALITY.md +++ b/.agents/project/PR_QUALITY.md @@ -9,7 +9,7 @@ A change is done when every checklist item holds and deterministic evidence veri - [ ] Installs stay stable. `pnpm check:lockfile` passes fresh installation and addition of two showcase importers without unrelated lockfile drift. - [ ] Behaviour is specified. New or changed behaviour is covered by a spec in the result's `web/e2e/` folder (the behaviour map), such as `apps/web/e2e/todos.spec.ts`. The product's contract is explicit. - [ ] Logic is unit-tested. Domain, application and procedures have `api` Jest tests; hooks and pages have `web` Jest tests that render through `TestApiProvider`. Coverage stays at/above the threshold in `jest.config.ts` (80%). -- [ ] Types check. `pnpm typecheck` passes its four programs, `tsconfig.json` (web and ui), `tsconfig.node.json` (configs and e2e), `tsconfig.api.json` (api) and `tsconfig.domain.json` (api domain, no Node), with no `any` and no weakened config. +- [ ] Types check. `pnpm typecheck` passes its six programs, `tsconfig.json` (web and ui), `tsconfig.node.json` (configs and e2e), `tsconfig.api.json` (api), `tsconfig.domain.json` (api domain, no Node), and `tsconfig.test.json` and `tsconfig.api.test.json` (tests), with no `any` and no weakened config. - [ ] Lint + format clean. `pnpm check` (Biome), `pnpm lint:policy` (Oxlint), `pnpm lint:anti-slop` (Oxlint anti-slop rules), and `pnpm react-doctor` pass; every disabled rule carries a written reason. - [ ] Code intelligence clean. `pnpm fallow:audit` reports no dead code, circular dependency, complexity, architecture or `contract/` finding in any file the change touches. - [ ] Architecture checks pass. `pnpm arch:check` passes: every file sits in a role, no forbidden import, every result passes the structure check, `docs/architecture/roles.mmd` and each result's `architecture.mmd` match `pnpm arch:diagram`, and every package's `etc/*.api.md` matches the code (`pnpm api:report` after an intended export change). diff --git a/.agents/project/QUALITY_GATES.md b/.agents/project/QUALITY_GATES.md index c79ce94d..bd5bfcba 100644 --- a/.agents/project/QUALITY_GATES.md +++ b/.agents/project/QUALITY_GATES.md @@ -108,12 +108,14 @@ See [ADR 0028](../decisions/0028-pre-push-runs-the-full-local-gate-suite.md). - React Doctor (`pnpm react-doctor`) owns the project-level checks the per-file plugins leave out, such as duplicated JSX across files. - TypeScript owns type semantics; `pnpm typecheck` checks them with the pinned - Bun's `bun check` ([ADR 0120](../decisions/0120-bun-checks-types.md)) over four programs: + Bun's `bun check` ([ADR 0120](../decisions/0120-bun-checks-types.md)) over six programs: `tsconfig.json` (web packages and `packages/ui`, with the DOM and no Node types), `tsconfig.node.json` (root configs, Vite configs and e2e specs, on Node), `tsconfig.api.json` (api packages, `NodeNext`, `.ts` import - extensions, `erasableSyntaxOnly`, no DOM) and `tsconfig.domain.json` (api - domain modules without Node types). All extend `tsconfig.base.json`. + extensions, `erasableSyntaxOnly`, no DOM), `tsconfig.domain.json` (api + domain modules without Node types), and `tsconfig.test.json` and + `tsconfig.api.test.json` (the web and api tests, which alone see the Jest + test globals `present` and `unwrap`). All extend `tsconfig.base.json`. See [ADR 0034](../decisions/0034-trial-harness-and-evidence.md) for the program boundaries and their limits. - Jest + React Testing Library own component, hook and api behaviour in diff --git a/apps/api/src/features/todos/application.test.ts b/apps/api/src/features/todos/application.test.ts index 24b9d749..fddf2c25 100644 --- a/apps/api/src/features/todos/application.test.ts +++ b/apps/api/src/features/todos/application.test.ts @@ -35,7 +35,7 @@ it('marks, renames and deletes a to-do in place', async () => { addTodo({ title: 'First' }); const added = addTodo({ title: 'Second' }); addTodo({ title: 'Third' }); - const { id } = present(added); + const { id } = unwrap(added); expect(setTodoDone({ id, done: true })).toEqual({ ok: true, @@ -68,7 +68,7 @@ it('answers not found for an unknown id', async () => { it('clears the done to-dos and returns their ids', async () => { const { addTodo, clearDoneTodos, listTodos, setTodoDone } = await application(); - const ids = ['First', 'Second', 'Third'].map((title) => present(addTodo({ title })).id); + const ids = ['First', 'Second', 'Third'].map((title) => unwrap(addTodo({ title })).id); setTodoDone({ id: present(ids[0]), done: true }); setTodoDone({ id: present(ids[2]), done: true }); diff --git a/oxlint.config.ts b/oxlint.config.ts index 08d36e85..823d4cb0 100644 --- a/oxlint.config.ts +++ b/oxlint.config.ts @@ -215,7 +215,7 @@ export default { 'policy/test-unwraps-values': 'error', 'policy/test-imports-the-type': 'error', 'policy/message-uses-its-limit': 'error', - 'policy/import-types-from-their-owner': 'error', + 'policy/reexport-only-from-index': 'error', 'policy/keep-rejections': 'error', 'max-depth': ['error', 4], 'no-restricted-imports': [ diff --git a/scripts/oxlint-policy.test.ts b/scripts/oxlint-policy.test.ts index 7592d1b0..62e0b751 100644 --- a/scripts/oxlint-policy.test.ts +++ b/scripts/oxlint-policy.test.ts @@ -4,7 +4,7 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'nod import { tmpdir } from 'node:os'; import { dirname, extname, join, matchesGlob, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; -import policy, { colourLiterals } from '../tooling/oxlint-plugin-policy.js'; +import policy, { colourLiterals, siblingTypes } from '../tooling/oxlint-plugin-policy.js'; import { findNegativePhrasing, findSlop } from './check-doc-phrasing.mjs'; const ROOT = resolve(__dirname, '..'); @@ -172,7 +172,7 @@ function ExtraPage() { return

; }` { path: `${root}/src/routes/slop/useSlop.ts`, source: - 'export function useSlop(list: { data: string; isError: boolean }) {\n return { text: list.data, failed: list.isError };\n}\n', + 'declare const useQuery: () => { data: string; isError: boolean };\nexport function useSlop() {\n const list = useQuery();\n return { text: list.data, failed: list.isError };\n}\n', code: 'policy(one-status-from-hooks)', }, { @@ -184,7 +184,7 @@ function ExtraPage() { return

; }` { path: `${root}/src/routes/slop/reexport.ts`, source: "export type { Slop } from './slop';\n", - code: 'policy(import-types-from-their-owner)', + code: 'policy(reexport-only-from-index)', }, { path: `${root}/src/routes/slop/keep.ts`, @@ -402,7 +402,7 @@ const contractFixtures: Fixture[] = [ ].map(([_label, source]) => ({ path: 'apps/web/src/routes/todos/hooks.ts', source: source, - codes: ['policy(state-and-effects-in-hooks)', 'policy(import-types-from-their-owner)'], + codes: ['policy(state-and-effects-in-hooks)', 'policy(reexport-only-from-index)'], })), ...[ ['a route imports another route', 'apps/web/src/routes/a/A.tsx', "import { B } from '../b';"], @@ -606,8 +606,10 @@ export function useTodos() { ].map((fixture, index) => ({ ...fixture, caseRoot: `contract-${index}` })); const statusMessage = (hook: string, fields: string, root: string) => `Return one \`status\` union from \`${hook}\` in place of ${fields} from \`${root}\`, for example \`{ status: 'loading' } | { status: 'failed' } | { status: 'loaded'; todos }\`, so the page renders exactly one state.`; +const presentMessage = (expression: string) => + `Unwrap \`${expression}\` with \`present(${expression})\`, a Jest global that an E2E spec imports from \`./fixtures\`, so a missing value fails the test here instead of standing in as \`''\`.`; const unwrapMessage = (expression: string) => - `Unwrap \`${expression}\` with \`present(${expression})\` (a Jest global; an E2E spec imports it from \`./fixtures\`), so a missing value fails the test here instead of standing in as \`''\`.`; + `Unwrap \`${expression}\` with \`unwrap(${expression})\`, a Jest global, so a failure fails the test here with its problem instead of standing in as \`''\`.`; const subject = (caseRoot: string, path: string, source = 'export const value = 1;\n') => ({ caseRoot, path, @@ -655,6 +657,111 @@ export const useGreeting = () => { code: 'policy(one-status-from-hooks)', messageContains: 'from `useGreeting`', }, + // r7 and r8 map the query's status through a lookup object. + { + path: 'apps/web/src/routes/todos/useTodos.ts', + source: ` +import { useQuery } from '@tanstack/react-query'; +declare const options: never; +const LIST_STATES = { pending: 'loading', error: 'failed', success: 'loaded' } as const; +export function useTodos() { + const list = useQuery(options); + const todos = list.data ?? []; + return { todos, listState: LIST_STATES[list.status] }; +} +`, + code: 'policy(one-status-from-hooks)', + message: statusMessage('useTodos', '`data`, `status`', 'list'), + }, + { + path: 'apps/web/src/routes/todos/useTodos.ts', + source: ` +import { useQuery } from '@tanstack/react-query'; +declare const options: never; +const LIST_STATUS = { pending: 'loading', error: 'failed', success: 'ready' } as const; +type ListStatus = (typeof LIST_STATUS)[keyof typeof LIST_STATUS]; +export function useTodos() { + const list = useQuery(options); + const listStatus: ListStatus = LIST_STATUS[list.status]; + return { todos: list.data ?? [], listStatus }; +} +`, + code: 'policy(one-status-from-hooks)', + message: statusMessage('useTodos', '`data`, `status`', 'list'), + }, + { + path: 'apps/web/src/routes/todos/useSuspenseTodos.ts', + source: ` +import { useInfiniteQuery, useSuspenseQuery } from '@tanstack/react-query'; +declare const options: never; +declare const trpc: { todos: { list: { useQuery: () => { data: string[]; isError: boolean } } } }; +export function useSuspenseTodos() { + const list = useSuspenseQuery(options); + return { loading: list.isPending, failed: list.isError }; +} +function usePages() { + const pages = useInfiniteQuery(options); + return { pages: pages.data, done: pages.isSuccess }; +} +function useClassic() { + const list = trpc.todos.list.useQuery(); + return { todos: list.data, failed: list.isError }; +} +export const hooks = [usePages, useClassic]; +`, + codes: [ + 'policy(one-status-from-hooks)', + 'policy(one-status-from-hooks)', + 'policy(one-status-from-hooks)', + ], + }, + // Reads that are not two states of one query pass. + { + path: 'apps/web/src/routes/todos/useRefreshing.ts', + source: ` +import { useQuery } from '@tanstack/react-query'; +declare const options: never; +export function useRefreshing() { + const list = useQuery(options); + return { list: list.data, refreshing: list.isFetching }; +} +`, + }, + { + path: 'apps/web/src/routes/todos/useSave.ts', + source: ` +import { useMutation } from '@tanstack/react-query'; +declare const options: never; +export function useSave() { + const save = useMutation(options); + return { submitting: save.isPending, problem: save.error, saved: save.data, failed: save.isError }; +} +`, + }, + { + path: 'apps/web/src/routes/todos/useListStatus.ts', + source: ` +import { useQuery } from '@tanstack/react-query'; +declare const options: never; +export function useListStatus() { + const list = useQuery(options); + return { status: list.status, problem: list.error }; +} +`, + }, + { + path: 'apps/web/src/routes/todos/useFlatList.ts', + source: ` +import { useQuery } from '@tanstack/react-query'; +declare const options: never; +type View = { status: 'loading'; data: undefined } | { status: 'loaded'; data: string[] }; +declare const toView: (query: unknown) => View; +export function useFlatList() { + const view = toView(useQuery(options)); + return { status: view.status, data: view.data }; +} +`, + }, { path: 'apps/web/src/routes/todos/useStatus.ts', source: ` @@ -662,8 +769,45 @@ export const useStatus = (list: { status: string; data: string[] }) => ({ status: list.status, todos: list.data, }); +`, + }, + // Each name resolves in its own scope, not to a same-named binding elsewhere. + { + path: 'apps/web/src/routes/todos/useShadowed.ts', + source: ` +import { useQuery } from '@tanstack/react-query'; +declare const options: never; +export function earlier(list: { data: string[] }) { + const todos = list.data; + return todos; +} +export function useShadowed(todos: string[]) { + const list = useQuery(options); + return { todos, failed: list.isError }; +} +function useSummary(list: { data: string[]; isError: boolean }) { + return { todos: list.data, failed: list.isError }; +} +export const hooks = [useSummary]; +`, + }, + { + path: 'apps/web/src/routes/todos/useOwnScope.ts', + source: ` +import { useQuery } from '@tanstack/react-query'; +declare const options: never; +export function useOwnScope() { + const list = useQuery(options); + const todos = list.data; + return { todos, failed: list.isError }; +} +export function later(todos: string[]) { + const list = { data: todos, isError: false }; + return list; +} `, code: 'policy(one-status-from-hooks)', + message: statusMessage('useOwnScope', '`data`, `isError`', 'list'), }, { path: 'apps/web/src/routes/todos/useTodos.ts', @@ -700,7 +844,7 @@ export function useTodos() { 'export function useFake(list: { data: string; isError: boolean }) {\n return { todos: list.data, failed: list.isError };\n}\n', }, subject('slop-status-test', 'apps/web/src/routes/todos/useTodos.ts'), - // policy/test-unwraps-values: the reference's api test and E2E spec, then present(). + // policy/test-unwraps-values: the reference's api test and E2E spec, then present() and unwrap(). { caseRoot: 'slop-unwrap-api', path: 'apps/api/src/features/todos/application.test.ts', @@ -730,7 +874,7 @@ declare const second: { id: string } | undefined; export const done = setDoneThroughApi(second?.id ?? ''); `, code: 'policy(test-unwraps-values)', - message: unwrapMessage('second?.id'), + message: presentMessage('second?.id'), }, { path: 'showcase/todo-01/web/e2e/todos.spec.ts', @@ -741,12 +885,18 @@ export const done = setDoneThroughApi(second?.id ?? ''); caseRoot: 'slop-unwrap-valid', path: 'apps/api/src/features/todos/application.test.ts', source: ` -declare const present: (value: Value | { ok: true; value: Value } | undefined) => Value; +declare const present: (value: Value | null | undefined) => Value; +declare const unwrap: (outcome: { ok: true; value: Value } | { ok: false }) => Value; declare const added: { ok: true; value: { id: string } } | { ok: false }; declare const ids: string[]; declare const message: string | undefined; -export const id = present(added).id; +declare const response: { ok: boolean; status: number }; +declare const other: { value: string }; +export const id = unwrap(added).id; export const fallback = added.ok ? added.value.id : undefined; +export const verdict = response.ok ? 'passed' : 'failed'; +export const code = !response.ok ? '' : response.status; +export const elsewhere = response.ok ? other.value : ''; export const first = present(ids[0]); export const shown = message ?? 'waiting'; `, @@ -796,6 +946,38 @@ export const todos: readonly Todo[] = []; 'apps/api/src/features/todos/domain.ts', 'export interface Problem {\n readonly kind: string;\n}\n', ), + // Only a declaration at the start of a line exports a type; text in strings and comments does not. + { + caseRoot: 'slop-type-text', + path: 'apps/web/src/routes/todos/TodosPage.test.tsx', + source: ` +interface Todo { + readonly id: string; +} +type Problem = { readonly message: string }; +export const cases: readonly [Todo, Problem] = [{ id: '1' }, { message: 'Enter a title' }]; +`, + }, + subject('slop-type-text', 'apps/web/src/routes/todos/TodosPage.tsx'), + subject( + 'slop-type-text', + 'apps/web/src/routes/todos/useTodos.ts', + "// export type Problem = string;\nexport const sample = 'export interface Todo { id: string }';\nexport const useTodos = () => [];\n", + ), + // Each test in a folder reads the same scan of its siblings. + ...['TodoItem', 'TodoList'].map((name) => ({ + caseRoot: 'slop-type-folder', + path: `apps/web/src/routes/todos/${name}.test.tsx`, + source: "type Todo = { readonly id: string };\nexport const todo: Todo = { id: '1' };\n", + code: 'policy(test-imports-the-type)', + })), + subject('slop-type-folder', 'apps/web/src/routes/todos/TodoItem.tsx'), + subject('slop-type-folder', 'apps/web/src/routes/todos/TodoList.tsx'), + subject( + 'slop-type-folder', + 'apps/web/src/routes/todos/useTodos.ts', + 'export type Todo = { id: string };\nexport const useTodos = () => [];\n', + ), { caseRoot: 'slop-type-valid', path: 'apps/web/src/routes/todos/TodosPage.test.tsx', @@ -840,6 +1022,53 @@ const RETRIES = 3; export const tooLong = \`Use \${TITLE_MAX_LENGTH} characters or fewer\`; export const retry = 'Try 3 times, up to 1000 items or 100ms'; export const used = RETRIES; +`, + }, + { + path: 'apps/web/src/routes/todos/itemLimit.ts', + source: ` +export const MAX_ITEMS = 1000; +export const maxTitleLength = 80; +export const tooMany = 'Keep 1,000 items or fewer'; +export const tooLong = \`Use 80 characters, not \${maxTitleLength + 1}\`; +`, + codes: ['policy(message-uses-its-limit)', 'policy(message-uses-its-limit)'], + message: + 'Interpolate `MAX_ITEMS` into this text in place of 1000, so the message changes with the limit.', + }, + { + path: 'apps/web/src/routes/todos/LimitHint.tsx', + source: ` +export const MAX_LENGTH = 100; +export function LimitHint() { + return

Up to 100 characters

; +} +`, + code: 'policy(message-uses-its-limit)', + }, + // A number that is not a limit, or not a count of words, passes. + { + path: 'apps/web/src/routes/todos/Layout.tsx', + source: ` +import { readings } from './100 readings'; +export const COLUMNS = 10; +export const ICON_SIZE = 24; +export const MAX_PERCENT = 100; +export const PORT = 3000; +export const PAGE_SIZE = 20; +export const MAX_LENGTH = 50; +export const done = '100% done'; +export const url = 'http://localhost:3000/api'; +export const audience = 'Ages 20 and over'; +export const hint = 'gap-10 p-4'; +export function Layout() { + return ( +
+ + +
+ ); +} `, }, { @@ -848,31 +1077,37 @@ export const used = RETRIES; source: "const LIMIT = 100;\nexport const expected = ['Use 100 characters or fewer', LIMIT];\n", }, subject('slop-limit-test', 'apps/api/src/features/todos/domain.ts'), - // policy/import-types-from-their-owner: r6's application, then the slice's index.ts. + // policy/reexport-only-from-index: r6's application, a nested barrel, then the slice's index.ts. { path: 'apps/api/src/features/todos/application.ts', source: "export type { Outcome, Problem } from './domain.ts';\nexport const value = 1;\n", - code: 'policy(import-types-from-their-owner)', + code: 'policy(reexport-only-from-index)', message: 'Import `Outcome, Problem` straight from `./domain.ts` and remove this re-export; a slice re-exports only from its `index.ts`.', }, { path: 'apps/web/src/routes/todos/types.ts', source: "export * from './useTodos';\n", - code: 'policy(import-types-from-their-owner)', + code: 'policy(reexport-only-from-index)', messageContains: 'Import each name you need straight from `./useTodos`', }, { path: 'apps/api/src/features/todos/procedures.ts', source: "import type { Todo } from './domain.ts';\nconst local = 1;\nexport type { Todo };\nexport { local };\n", - code: 'policy(import-types-from-their-owner)', + code: 'policy(reexport-only-from-index)', messageContains: 'Import `Todo` straight from `./domain.ts`', }, { path: 'apps/api/src/features/todos/index.ts', source: "export { todosRouter } from './procedures.ts';\n", }, + { + path: 'apps/web/src/routes/todos/components/index.ts', + source: "export { TodoItem } from './TodoItem';\n", + code: 'policy(reexport-only-from-index)', + messageContains: 'a slice re-exports only from its `index.ts`', + }, { path: 'apps/web/src/api-client/trpc.ts', source: "export { useQuery } from '@tanstack/react-query';\n", @@ -889,7 +1124,7 @@ export const used = RETRIES; 'export const succeeded = (change: Promise) => change.then(() => true, () => false);\n', code: 'policy(keep-rejections)', message: - 'Handle the failure where it shows (`onError`, a `failure` state) and let the promise reject; returning `false` hides the error from callers and tests.', + 'Handle the failure where it shows (`onError`, a `failure` state) and let the promise reject; returning `false` hides the error from callers and tests. To ignore a failure on purpose, settle the promise with `Promise.allSettled` and read its result.', }, { path: 'apps/web/src/routes/todos/useCreate.ts', @@ -924,6 +1159,43 @@ export const handled = (save: () => Promise) => [ save().then(() => true), save().then(() => true, (error: unknown) => report(error)), ]; +`, + }, + // A handler resolves in its own scope, not to a same-named binding elsewhere. + { + path: 'apps/web/src/routes/todos/useScopedHandlers.ts', + source: ` +export function quiet(save: () => Promise) { + const handle = () => undefined; + return save().catch(handle); +} +export function loud(save: () => Promise, report: (error: unknown) => void) { + const handle = (error: unknown) => report(error); + return save().catch(handle); +} +`, + code: 'policy(keep-rejections)', + }, + { + path: 'apps/web/src/routes/todos/useGivenHandler.ts', + source: ` +export function fallback() { + const handle = () => false; + return handle; +} +export function given(save: () => Promise, handle: (error: unknown) => void) { + return save().catch(handle); +} +`, + }, + // An ignored rejection that is meant: settle the promise and read the result. + { + path: 'apps/web/src/routes/todos/usePrefetch.ts', + source: ` +declare const prefetch: () => Promise; +declare const save: () => Promise; +export const warm = () => void Promise.allSettled([prefetch()]); +export const saved = () => Promise.allSettled([save()]).then(([result]) => result?.status === 'fulfilled'); `, }, { @@ -1549,12 +1821,28 @@ it('turns on every policy rule at error in result roots', () => { }); }); }); +it('scans the type exports of a folder once until a file in it changes', () => { + const folder = mkdtempSync(join(tmpdir(), 'sibling-types-')); + try { + writeFileSync(join(folder, 'useTodos.ts'), 'export type Todo = { id: string };\n'); + const first = siblingTypes(folder, false); + expect(siblingTypes(folder, false)).toBe(first); + expect([...first]).toEqual([['Todo', './useTodos']]); + writeFileSync(join(folder, 'domain.ts'), 'export interface Problem {}\n'); + expect([...siblingTypes(folder, true)]).toEqual([ + ['Problem', './domain.ts'], + ['Todo', './useTodos.ts'], + ]); + } finally { + rmSync(folder, { recursive: true, force: true }); + } +}); const minedRules = [ 'one-status-from-hooks', 'test-unwraps-values', 'test-imports-the-type', 'message-uses-its-limit', - 'import-types-from-their-owner', + 'reexport-only-from-index', 'keep-rejections', ]; const mined = Object.entries(policy.rules).filter(([name]) => minedRules.includes(name)); diff --git a/scripts/oxlint-rule-set.test.ts b/scripts/oxlint-rule-set.test.ts index 8783bd0e..b06f73a9 100644 --- a/scripts/oxlint-rule-set.test.ts +++ b/scripts/oxlint-rule-set.test.ts @@ -90,7 +90,7 @@ const RESULT_ROOT = { 'test-unwraps-values', 'test-imports-the-type', 'message-uses-its-limit', - 'import-types-from-their-owner', + 'reexport-only-from-index', 'keep-rejections', ].map((name) => [`policy/${name}`, ['error']]), ), diff --git a/scripts/typecheck.mjs b/scripts/typecheck.mjs index 7d5f4dfa..60d38050 100644 --- a/scripts/typecheck.mjs +++ b/scripts/typecheck.mjs @@ -11,11 +11,16 @@ import { realpathSync } from 'node:fs'; import { pathToFileURL } from 'node:url'; import { bunBinary } from './bun.mjs'; -/** Each program's `bun check` arguments. `-b` follows `tsconfig.json`'s reference to the api program. */ +/** + * Each program's `bun check` arguments. `-b` follows `tsconfig.json`'s reference to the api program. + * The two test programs come last: they alone see the Jest test globals. + */ export const PROGRAMS = [ ['-b', 'tsconfig.json'], ['-p', 'tsconfig.node.json'], ['-p', 'tsconfig.domain.json'], + ['-p', 'tsconfig.test.json'], + ['-p', 'tsconfig.api.test.json'], ]; /** Checks one program with its errors on this terminal, and returns Bun's exit code. Throws when Bun cannot start. */ diff --git a/scripts/typecheck.test.ts b/scripts/typecheck.test.ts index af940c83..6f68868d 100644 --- a/scripts/typecheck.test.ts +++ b/scripts/typecheck.test.ts @@ -9,13 +9,15 @@ const manifest = JSON.parse(readFileSync('package.json', 'utf8')); const bun = (args: string[]) => spawnSync(process.execPath, ['scripts/bun.mjs', ...args], { encoding: 'utf8' }); -test('typecheck runs Bun over the web, node and domain programs from one script', () => { +test('typecheck runs Bun over the web, node, domain and test programs from one script', () => { expect(manifest.scripts.typecheck).toBe('node scripts/typecheck.mjs'); expect(manifest.devDependencies.bun).toBe('1.4.4'); expect(PROGRAMS).toEqual([ ['-b', 'tsconfig.json'], ['-p', 'tsconfig.node.json'], ['-p', 'tsconfig.domain.json'], + ['-p', 'tsconfig.test.json'], + ['-p', 'tsconfig.api.test.json'], ]); }); diff --git a/tooling/jest/jest.setup.ts b/tooling/jest/jest.setup.ts index 2b6a39ea..a02e8454 100644 --- a/tooling/jest/jest.setup.ts +++ b/tooling/jest/jest.setup.ts @@ -4,13 +4,11 @@ import '@testing-library/jest-dom'; // `toHaveNoViolations` for jest-axe — lets unit tests assert accessibility. import { toHaveNoViolations } from 'jest-axe'; +// `present` and `unwrap` take a value a test expects, so a test file needs no import for them. +import { testGlobals } from './test-globals'; expect.extend(toHaveNoViolations); - -// `present` unwraps a value a test expects, so a test file needs no import for it. -import { present } from './present'; - -Object.assign(globalThis, { present }); +Object.assign(globalThis, testGlobals); // jsdom leaves out the encoding globals that browsers and Node both ship, and // Effect reads TextEncoder when it loads. diff --git a/tooling/jest/present.test.ts b/tooling/jest/present.test.ts deleted file mode 100644 index 398d5d77..00000000 --- a/tooling/jest/present.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { present } from './present'; - -type Outcome = { ok: true; value: { id: string } } | { ok: false; problem: { message: string } }; - -it('returns a value that is there', () => { - expect(present(['a'][0])).toBe('a'); - expect(present('')).toBe(''); - expect(present(0)).toBe(0); - expect(present(false)).toBe(false); -}); - -it.each([undefined, null])('fails the test on %p', (value) => { - expect(() => present(value)).toThrow(`Expected a value, received ${value}`); -}); - -it('returns the value of an ok outcome', () => { - const outcome: Outcome = { ok: true, value: { id: '1' } }; - expect(present(outcome).id).toBe('1'); -}); - -it('fails the test on a failed outcome and names its problem', () => { - const outcome: Outcome = { ok: false, problem: { message: 'Enter a title' } }; - expect(() => present(outcome)).toThrow( - 'Expected an ok outcome, received {"ok":false,"problem":{"message":"Enter a title"}}', - ); -}); - -it('is a global in every Jest test', () => { - expect(globalThis).toHaveProperty('present', present); -}); diff --git a/tooling/jest/present.ts b/tooling/jest/present.ts deleted file mode 100644 index 4f1d091a..00000000 --- a/tooling/jest/present.ts +++ /dev/null @@ -1,31 +0,0 @@ -interface Success { - readonly ok: true; - readonly value: Value; -} - -interface Failure { - readonly ok: false; -} - -const isOutcome = ( - value: Success | Failure | Value, -): value is Success | Failure => value instanceof Object && 'ok' in value; - -/** - * The value a test expects to be there: a defined value, or the value of an ok - * outcome. A missing value throws, so the test fails on the line that needed it. - */ -export function present(outcome: Success | Failure): Value; -export function present(value: Value | null | undefined): Value; -export function present(value: Success | Failure | Value | null | undefined): Value { - if (value === undefined || value === null) { - throw new Error(`Expected a value, received ${value}`); - } - if (!isOutcome(value)) { - return value; - } - if (!value.ok) { - throw new Error(`Expected an ok outcome, received ${JSON.stringify(value)}`); - } - return value.value; -} diff --git a/tooling/jest/test-globals.test.ts b/tooling/jest/test-globals.test.ts new file mode 100644 index 00000000..9ce7fc91 --- /dev/null +++ b/tooling/jest/test-globals.test.ts @@ -0,0 +1,44 @@ +import { present as presentInE2e } from '../../apps/web/e2e/fixtures'; +import { testGlobals } from './test-globals'; + +const { present, unwrap } = testGlobals; + +type Outcome = { ok: true; value: { id: string } } | { ok: false; problem: { message: string } }; + +describe.each([ + ['the Jest global', present], + ['the E2E fixtures copy', presentInE2e], +])('present, as %s', (_name, check) => { + it('returns a value that is there', () => { + expect(check(['a'][0])).toBe('a'); + expect(check('')).toBe(''); + expect(check(0)).toBe(0); + expect(check(false)).toBe(false); + }); + + it.each([undefined, null])('fails the test on %p', (value) => { + expect(() => check(value)).toThrow(`Expected a value, received ${value}`); + }); + + it('returns an outcome as it is, without reading its value', () => { + const outcome: Outcome = { ok: false, problem: { message: 'Enter a title' } }; + expect(check(outcome)).toBe(outcome); + }); +}); + +it('unwraps the value of a success', () => { + const outcome: Outcome = { ok: true, value: { id: '1' } }; + expect(unwrap(outcome).id).toBe('1'); +}); + +it('fails the test with the failure it received', () => { + const outcome: Outcome = { ok: false, problem: { message: 'Enter a title' } }; + expect(() => unwrap(outcome)).toThrow( + 'Expected a success, received {"ok":false,"problem":{"message":"Enter a title"}}', + ); +}); + +it('makes present and unwrap globals in every Jest test', () => { + expect(globalThis).toHaveProperty('present', present); + expect(globalThis).toHaveProperty('unwrap', unwrap); +}); diff --git a/tooling/jest/test-globals.ts b/tooling/jest/test-globals.ts new file mode 100644 index 00000000..c2754f7a --- /dev/null +++ b/tooling/jest/test-globals.ts @@ -0,0 +1,27 @@ +interface Success { + readonly ok: true; + readonly value: Value; +} + +interface Failure { + readonly ok: false; +} + +/** The value a test expects to be there. `null` or `undefined` throws, so the test fails on the line that needed it. */ +function present(value: Value | null | undefined): Value { + if (value === undefined || value === null) { + throw new Error(`Expected a value, received ${value}`); + } + return value; +} + +/** The value of a success. A failure throws with the failure, so the test fails on the line that needed the value. */ +function unwrap(outcome: Success | Failure): Value { + if (!outcome.ok) { + throw new Error(`Expected a success, received ${JSON.stringify(outcome)}`); + } + return outcome.value; +} + +/** The helpers the Jest setup makes globals, one object so no export shares a name with an E2E fixture. */ +export const testGlobals = { present, unwrap }; diff --git a/tooling/oxlint-plugin-policy.js b/tooling/oxlint-plugin-policy.js index e9447842..f06e571d 100644 --- a/tooling/oxlint-plugin-policy.js +++ b/tooling/oxlint-plugin-policy.js @@ -1,6 +1,6 @@ // Repository policy rules that no installed plugin expresses (ADR 0019, ADR 0103). Each // message names the fix, so an agent can act on the error alone. -import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; import { basename, dirname, extname, join, posix, relative, sep } from 'node:path'; const PASCAL_CASE = /^[A-Z][A-Za-z0-9]*$/; @@ -1084,12 +1084,12 @@ const unwrapChain = (node) => ? unwrapChain(node.expression) : node; -/** `{ root, names }` for a member chain such as `query.data?.message`, or null. */ +/** `{ root, node, names }` for a member chain such as `query.data?.message`, or null. */ function memberChain(node) { const current = unwrapChain(node); if (current?.type === 'Identifier') { - return { root: current.name, names: [] }; + return { root: current.name, node: current, names: [] }; } if (current?.type !== 'MemberExpression' || current.computed) { @@ -1098,36 +1098,76 @@ function memberChain(node) { const inner = memberChain(current.object); - return inner && { root: inner.root, names: [...inner.names, current.property.name] }; + return inner && { ...inner, names: [...inner.names, current.property.name] }; } +/** The variable `name` names where `node` sits, found through the scope chain, or undefined. */ +function variableAt(context, node, name) { + const lookup = (scope) => (scope ? (scope.set.get(name) ?? lookup(scope.upper)) : undefined); + + return lookup(context.sourceCode.getScope(node)); +} + +/** The initialiser of the `const` an identifier names in its own scope, or null. */ +function constInit(context, identifier) { + const [definition, ...others] = variableAt(context, identifier, identifier.name)?.defs ?? []; + + return others.length === 0 && + definition?.type === 'Variable' && + definition.parent?.kind === 'const' && + definition.node.id.type === 'Identifier' + ? definition.node.init + : null; +} + +const QUERY_HOOKS = new Set(['useQuery', 'useSuspenseQuery', 'useInfiniteQuery']); + +/** `useQuery(…)`, `useSuspenseQuery(…)`, `useInfiniteQuery(…)` or a client's `x.useQuery(…)`. */ +const isQueryCall = (node) => { + const callee = node?.type === 'CallExpression' ? unwrapChain(node.callee) : null; + const name = callee?.type === 'MemberExpression' ? callee.property.name : callee?.name; + + return QUERY_HOOKS.has(name); +}; + +// `error` and `isFetching` describe a state rather than choose one, so they stay out. const QUERY_STATUS_FIELDS = new Set([ 'data', - 'error', 'status', 'isPending', 'isLoading', - 'isFetching', 'isError', 'isSuccess', ]); -/** The query field a value reads first (`list.data ?? []` reads `data` of `list`), or null. */ -function statusField(node, constants) { +/** What a value reads through: the left of `a ?? b`, or the key of a lookup such as `STATES[list.status]`. */ +const READS_THROUGH = { + LogicalExpression: (node) => node.left, + MemberExpression: (node) => (node.computed ? node.property : null), +}; + +/** The expression a value reads, following one `const` binding resolved in its own scope. */ +function readExpression(context, node, follow) { const value = unwrapChain(node); + const inner = READS_THROUGH[value?.type]?.(value); - if (value?.type === 'LogicalExpression') { - return statusField(value.left, constants); + if (inner) { + return readExpression(context, inner, follow); } - if (value?.type === 'Identifier' && constants.has(value.name)) { - return statusField(constants.get(value.name), new Map()); - } + const bound = follow && value?.type === 'Identifier' ? constInit(context, value) : null; + + return bound ? readExpression(context, bound, false) : value; +} - const chain = memberChain(value); +/** The query state a value reads (`list.data ?? []` reads `data` of `list`), or null; only a query hook's result counts. */ +function statusField(context, node) { + const chain = memberChain(readExpression(context, node, true)); const field = chain?.names[0]; - return field && QUERY_STATUS_FIELDS.has(field) ? { root: chain.root, field } : null; + return QUERY_STATUS_FIELDS.has(field) && isQueryCall(constInit(context, chain.node)) + ? { root: chain.root, field } + : null; } /** The object a function returns: a `return { ... }` or an arrow's `({ ... })` body. */ @@ -1150,8 +1190,6 @@ const oneStatusFromHooks = { return {}; } - const constants = new Map(); - const check = (node) => { const object = unwrapChain(returnedObject(node)); const owner = context.sourceCode.getAncestors(node).findLast(isFunctionNode); @@ -1164,7 +1202,7 @@ const oneStatusFromHooks = { const reads = object.properties .filter((property) => property.type === 'Property') - .map((property) => statusField(property.value, constants)) + .map((property) => statusField(context, property.value)) .filter(Boolean); [...new Set(reads.map(({ root }) => root))] @@ -1182,33 +1220,40 @@ const oneStatusFromHooks = { }); }; - return { - 'VariableDeclaration[kind="const"] > VariableDeclarator[id.type="Identifier"]'(node) { - if (node.init) constants.set(node.id.name, node.init); - }, - ReturnStatement: check, - ArrowFunctionExpression: check, - }; + return { ReturnStatement: check, ArrowFunctionExpression: check }; }, }; const isEmptyString = (node) => node?.type === 'Literal' && node.value === ''; -/** The value `x.ok ? x.value… : ''` reads, as source text, or null. */ +/** Whether `chain` reads `.value…` of the outcome `outcome.ok` tests. */ +const readsValueOf = (chain, outcome) => + chain?.root === outcome.root && + [...outcome.names.slice(0, -1), 'value'].every((name, index) => chain.names[index] === name); + +/** The outcome and fallback of `x.ok ? x.value… : ''` or `!x.ok ? '' : x.value…`, or null. */ function placeholderOutcome(node) { const negated = node.test.type === 'UnaryExpression' && node.test.operator === '!'; const test = memberChain(negated ? node.test.argument : node.test); - const fallback = negated ? node.consequent : node.alternate; - - return test?.names.at(-1) === 'ok' && fallback.type === 'Literal' ? { ...test, fallback } : null; + const [read, fallback] = negated + ? [node.alternate, node.consequent] + : [node.consequent, node.alternate]; + + return test?.names.at(-1) === 'ok' && + fallback.type === 'Literal' && + readsValueOf(memberChain(read), test) + ? { ...test, fallback } + : null; } const testUnwrapsValues = { meta: { type: 'problem', messages: { + present: + 'Unwrap `{{expression}}` with `present({{expression}})`, a Jest global that an E2E spec imports from `./fixtures`, so a missing value fails the test here instead of standing in as `{{fallback}}`.', unwrap: - 'Unwrap `{{expression}}` with `present({{expression}})` (a Jest global; an E2E spec imports it from `./fixtures`), so a missing value fails the test here instead of standing in as `{{fallback}}`.', + 'Unwrap `{{expression}}` with `unwrap({{expression}})`, a Jest global, so a failure fails the test here with its problem instead of standing in as `{{fallback}}`.', }, schema: [], }, @@ -1217,42 +1262,70 @@ const testUnwrapsValues = { return {}; } - const report = (node, expression, fallback) => + const report = (node, messageId, expression, fallback) => context.report({ node, - messageId: 'unwrap', + messageId, data: { expression, fallback: context.sourceCode.getText(fallback) }, }); return { 'LogicalExpression[operator="??"]'(node) { if (isEmptyString(node.right)) { - report(node, context.sourceCode.getText(node.left), node.right); + report(node, 'present', context.sourceCode.getText(node.left), node.right); } }, ConditionalExpression(node) { const outcome = placeholderOutcome(node); if (outcome) { - report(node, [outcome.root, ...outcome.names.slice(0, -1)].join('.'), outcome.fallback); + report( + node, + 'unwrap', + [outcome.root, ...outcome.names.slice(0, -1)].join('.'), + outcome.fallback, + ); } }, }; }, }; -const EXPORTED_TYPE = /export\s+(?:declare\s+)?(?:interface|type)\s+([A-Za-z_$][\w$]*)/g; +// A declaration starts its line, so `export type` inside a string or a comment does not count. +const EXPORTED_TYPE = /^export\s+(?:declare\s+)?(?:interface|type)\s+([A-Za-z_$][\w$]*)/gm; +const siblingScans = new Map(); -/** Each type name a module exports by declaration, mapped to its module specifier. */ -function siblingTypes(directory, keepExtension) { - return readdirSync(directory) +/** A folder's non-test modules, sorted, each with its modification time. */ +const siblingModules = (directory) => + readdirSync(directory) .filter((file) => /\.tsx?$/.test(file) && !isSpecFile(file) && !file.endsWith('.d.ts')) - .flatMap((file) => - [...readFileSync(join(directory, file), 'utf8').matchAll(EXPORTED_TYPE)].map((match) => [ - match[1], - `./${keepExtension ? file : file.replace(/\.tsx?$/, '')}`, - ]), + .sort() + .map((file) => [file, statSync(join(directory, file)).mtimeMs]); + +/** + * Each type name a module in `directory` exports by declaration, mapped to its + * module specifier. One scan serves every test in the folder until a module + * in it is added, removed or changed. + */ +export function siblingTypes(directory, keepExtension) { + const modules = siblingModules(directory); + const key = `${directory}\0${keepExtension}\0${JSON.stringify(modules)}`; + + if (!siblingScans.has(key)) { + siblingScans.set( + key, + new Map( + modules.flatMap(([file]) => + [...readFileSync(join(directory, file), 'utf8').matchAll(EXPORTED_TYPE)].map((match) => [ + match[1], + `./${keepExtension ? file : file.replace(/\.tsx?$/, '')}`, + ]), + ), + ), ); + } + + return siblingScans.get(key); } const testImportsTheType = { @@ -1269,8 +1342,9 @@ const testImportsTheType = { return {}; } - const exported = new Map( - siblingTypes(dirname(context.filename), API_SOURCE.test(repositoryPath(context))), + const exported = siblingTypes( + dirname(context.filename), + API_SOURCE.test(repositoryPath(context)), ); const check = (node) => { @@ -1291,6 +1365,29 @@ const testImportsTheType = { // A limit below ten is too common in prose ("3 times") to tie to one constant. const SMALLEST_LIMIT = 10; +const LIMIT_WORDS = new Set(['MAX', 'MAXIMUM', 'MIN', 'MINIMUM', 'LIMIT', 'LENGTH', 'LEN']); + +/** `TITLE_MAX_LENGTH` or `maxTitleLength`: a name with a limit word in it. */ +const isLimitName = (name) => + name + .replace(/([a-z0-9])([A-Z])/g, '$1_$2') + .toUpperCase() + .split('_') + .some((word) => LIMIT_WORDS.has(word)); + +const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + +/** The limit written as a count of something: `100 characters`, `1,000 items`. */ +const countPattern = (value) => + new RegExp( + `(? + !context.sourceCode + .getAncestors(node) + .some((ancestor) => ancestor.type === 'JSXAttribute' || ancestor.source === node); const messageUsesItsLimit = { meta: { @@ -1306,8 +1403,11 @@ const messageUsesItsLimit = { return {}; } - const limits = new Map(); + const limits = []; const texts = []; + const addText = (node, text) => { + if (isMessageText(context, node)) texts.push([node, text]); + }; return { 'Program > VariableDeclaration[kind="const"] > VariableDeclarator, Program > ExportNamedDeclaration > VariableDeclaration[kind="const"] > VariableDeclarator'( @@ -1315,25 +1415,30 @@ const messageUsesItsLimit = { ) { const value = node.init?.type === 'Literal' ? node.init.value : undefined; - if (node.id.type === 'Identifier' && typeof value === 'number' && value >= SMALLEST_LIMIT) { - limits.set(String(value), node.id.name); + if ( + node.id.type === 'Identifier' && + isLimitName(node.id.name) && + typeof value === 'number' && + value >= SMALLEST_LIMIT + ) { + limits.push({ name: node.id.name, value, pattern: countPattern(value) }); } }, Literal(node) { - if (isStringLiteral(node)) texts.push([node, node.value]); + if (isStringLiteral(node)) addText(node, node.value); }, TemplateElement(node) { - texts.push([node, node.value.cooked ?? '']); + addText(node, node.value.cooked ?? ''); }, JSXText(node) { - texts.push([node, node.value]); + addText(node, node.value); }, 'Program:exit'() { texts.forEach(([node, text]) => { - [...limits] - .filter(([value]) => new RegExp(`(? { - context.report({ node, messageId: 'limit', data: { name, value } }); + limits + .filter(({ pattern }) => pattern.test(text)) + .forEach(({ name, value }) => { + context.report({ node, messageId: 'limit', data: { name, value: String(value) } }); }); }); }, @@ -1341,18 +1446,16 @@ const messageUsesItsLimit = { }, }; +/** A module in a slice other than the slice's own `index.ts`; a nested `components/index.ts` counts. */ const isSliceModule = (path) => { - const source = PACKAGE_SOURCE.exec(path); + const rest = sliceOf(PACKAGE_SOURCE.exec(path)?.[2] ?? '')?.rest ?? []; - return ( - Boolean(source && sliceOf(source[2])?.rest.length) && - !/^index\.[cm]?[jt]sx?$/.test(basename(path)) - ); + return rest.length > 0 && !(rest.length === 1 && /^index\.[cm]?[jt]sx?$/.test(rest[0])); }; const exportedName = (specifier) => specifier.local.name ?? specifier.local.value; -const importTypesFromTheirOwner = { +const reexportOnlyFromIndex = { meta: { type: 'problem', messages: { @@ -1449,7 +1552,7 @@ const keepRejections = { type: 'problem', messages: { swallowed: - 'Handle the failure where it shows (`onError`, a `failure` state) and let the promise reject; returning `{{value}}` hides the error from callers and tests.', + 'Handle the failure where it shows (`onError`, a `failure` state) and let the promise reject; returning `{{value}}` hides the error from callers and tests. To ignore a failure on purpose, settle the promise with `Promise.allSettled` and read its result.', }, schema: [], }, @@ -1458,31 +1561,19 @@ const keepRejections = { return {}; } - const constants = new Map(); - const handlers = []; - const resolve = (node) => - node?.type === 'Identifier' && constants.has(node.name) ? constants.get(node.name) : node; + node?.type === 'Identifier' ? (constInit(context, node) ?? node) : node; return { - 'VariableDeclaration[kind="const"] > VariableDeclarator[id.type="Identifier"]'(node) { - if (node.init) constants.set(node.id.name, node.init); - }, CallExpression(node) { const method = node.callee.type === 'MemberExpression' && !node.callee.computed ? node.callee.property.name : undefined; const handler = node.arguments[REJECTION_HANDLER.get(method) ?? node.arguments.length]; + const value = handler && swallowedValue(resolve(handler)); - if (handler) handlers.push([node, handler]); - }, - 'Program:exit'() { - handlers.forEach(([node, handler]) => { - const value = swallowedValue(resolve(handler)); - - if (value) context.report({ node, messageId: 'swallowed', data: { value } }); - }); + if (value) context.report({ node, messageId: 'swallowed', data: { value } }); }, }; }, @@ -1648,7 +1739,7 @@ export default { 'test-unwraps-values': testUnwrapsValues, 'test-imports-the-type': testImportsTheType, 'message-uses-its-limit': messageUsesItsLimit, - 'import-types-from-their-owner': importTypesFromTheirOwner, + 'reexport-only-from-index': reexportOnlyFromIndex, 'keep-rejections': keepRejections, }, }; diff --git a/tooling/trial/inclusion.test.ts b/tooling/trial/inclusion.test.ts index a18bd696..3898c0c2 100644 --- a/tooling/trial/inclusion.test.ts +++ b/tooling/trial/inclusion.test.ts @@ -38,6 +38,8 @@ const PNPM_IN_COPY = ['--config.verify-deps-before-run=false']; const TS = '@ts'; const WEB_FILE = 'web/src/routes/todos/TodosPage.tsx'; const API_FILE = 'api/src/features/todos/procedures.ts'; +const WEB_TEST = 'web/src/routes/todos/TodosPage.test.tsx'; +const API_TEST = 'api/src/features/todos/application.test.ts'; const env: NodeJS.ProcessEnv = { ...process.env, @@ -336,6 +338,13 @@ console.log(JSON.stringify(${JSON.stringify(paths)}.map(path => Object.fromEntri expect(filesOf('tsconfig.json')).toContain(`showcase/x/${WEB_FILE}`); expect(filesOf('tsconfig.api.json')).toContain(`showcase/x/${API_FILE}`); + expect(filesOf('tsconfig.test.json')).toContain(`showcase/x/${WEB_TEST}`); + expect(filesOf('tsconfig.api.test.json')).toContain(`showcase/x/${API_TEST}`); + expect( + [...filesOf('tsconfig.json'), ...filesOf('tsconfig.api.json')].filter((path) => + /\.test\.tsx?$/.test(path), + ), + ).toEqual([]); expect(filesOf('tsconfig.node.json')).toEqual( expect.arrayContaining(['showcase/x/web/e2e/todos.spec.ts', 'showcase/x/web/vite.config.ts']), ); @@ -358,6 +367,25 @@ console.log(JSON.stringify(${JSON.stringify(paths)}.map(path => Object.fromEntri expect(errors[0]).toMatch(/^showcase\/x\/api\/src\/features\/todos\/seed\.ts.*error TS2835/); }); + it.each([ + WEB_FILE.replace('TodosPage.tsx', 'leak.ts'), + API_FILE.replace('procedures.ts', 'leak.ts'), + ])('fails the type check on a production call to the test globals in %s', (file) => { + const checked = withSeed( + { + [`showcase/x/${file}`]: + 'export const leak = [present(1), unwrap({ ok: true, value: 1 })];\n', + }, + () => script('typecheck'), + ); + const errors = checked.output.split('\n').filter((line) => line.includes('error TS')); + + expect(checked.code).toBe(1); + expect(errors).toHaveLength(2); + expect(errors[0]).toMatch(/leak\.ts.*error TS2304: Cannot find name 'present'/); + expect(errors[1]).toMatch(/leak\.ts.*error TS2304: Cannot find name 'unwrap'/); + }); + it('passes the type check and the api report with a Node import in its api integrations', () => { const integrations = 'showcase/x/api/src/features/todos/integrations.ts'; expect(readFileSync(join(copy, integrations), 'utf8')).toContain("from 'node:crypto';"); diff --git a/tooling/types/present.d.ts b/tooling/types/present.d.ts deleted file mode 100644 index 5597d929..00000000 --- a/tooling/types/present.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -// The Jest setup makes `present` from tooling/jest/present.ts a global in every unit test. -declare const present: typeof import('../jest/present.ts').present; diff --git a/tooling/types/test-globals.d.ts b/tooling/types/test-globals.d.ts new file mode 100644 index 00000000..6d9bb988 --- /dev/null +++ b/tooling/types/test-globals.d.ts @@ -0,0 +1,5 @@ +// The Jest setup makes these helpers from tooling/jest/test-globals.ts globals in +// every unit test. Only the test type programs (tsconfig.test.json and +// tsconfig.api.test.json) include this file, so production code cannot call them. +declare const present: typeof import('../jest/test-globals.ts').testGlobals.present; +declare const unwrap: typeof import('../jest/test-globals.ts').testGlobals.unwrap; diff --git a/tsconfig.api.json b/tsconfig.api.json index c5d1fde4..62b240a1 100644 --- a/tsconfig.api.json +++ b/tsconfig.api.json @@ -18,10 +18,7 @@ "outDir": ".cache/types", "tsBuildInfoFile": ".cache/types/api.tsbuildinfo" }, - "include": [ - "apps/api/src", - "showcase/*/api/src", - "tooling/types/present.d.ts", - "tooling/jest/present.ts" - ] + "include": ["apps/api/src", "showcase/*/api/src"], + // Its tests type-check in tsconfig.api.test.json, which sees the Jest test globals. + "exclude": ["**/*.test.ts"] } diff --git a/tsconfig.api.test.json b/tsconfig.api.test.json new file mode 100644 index 00000000..54aff254 --- /dev/null +++ b/tsconfig.api.test.json @@ -0,0 +1,18 @@ +{ + // The Node program's unit, integration and contract tests, with the Jest test + // globals `present` and `unwrap` (tooling/types/test-globals.d.ts). Only the + // test programs include that file, so a production module that calls either + // fails to compile in tsconfig.api.json. + "extends": "./tsconfig.api.json", + "compilerOptions": { + "composite": false, + "emitDeclarationOnly": false, + "noEmit": true + }, + "include": [ + "apps/api/src/**/*.test.ts", + "showcase/*/api/src/**/*.test.ts", + "tooling/types/test-globals.d.ts" + ], + "exclude": [] +} diff --git a/tsconfig.json b/tsconfig.json index 70ba3d5b..31c998a0 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,6 +5,7 @@ // writes to `.cache/types`, so api source, Node imports included, is checked // by the api program alone. `pnpm typecheck` builds them with `tsc -b`. // The root configs and e2e specs run on Node: tsconfig.node.json. + // Its unit tests are checked by tsconfig.test.json. "extends": "./tsconfig.base.json", "compilerOptions": { "useDefineForClassFields": true, @@ -17,14 +18,10 @@ "types": ["jest", "@testing-library/jest-dom"] }, - "include": [ - "apps/web/src", - "showcase/*/web/src", - "packages/ui/src", - "tooling/types/styles.d.ts", - "tooling/types/present.d.ts" - ], - "exclude": ["**/*.contract.test.ts"], + "include": ["apps/web/src", "showcase/*/web/src", "packages/ui/src", "tooling/types/styles.d.ts"], + // Unit tests type-check in tsconfig.test.json, the one browser program that + // sees the Jest test globals; contract tests run on Node (tsconfig.node.json). + "exclude": ["**/*.test.ts", "**/*.test.tsx"], "references": [{ "path": "./tsconfig.api.json" }], "ts-node": { "transpileOnly": true, diff --git a/tsconfig.test.json b/tsconfig.test.json new file mode 100644 index 00000000..ef95049a --- /dev/null +++ b/tsconfig.test.json @@ -0,0 +1,22 @@ +{ + // The browser program's unit tests: the web and ui tests, with the Jest test + // globals `present` and `unwrap` (tooling/types/test-globals.d.ts). Only the + // test programs include that file, so a production module that calls either + // fails to compile in tsconfig.json. + "extends": "./tsconfig.json", + "compilerOptions": { + "tsBuildInfoFile": ".cache/types/web-test.tsbuildinfo" + }, + "include": [ + "apps/web/src/**/*.test.ts", + "apps/web/src/**/*.test.tsx", + "showcase/*/web/src/**/*.test.ts", + "showcase/*/web/src/**/*.test.tsx", + "packages/ui/src/**/*.test.ts", + "packages/ui/src/**/*.test.tsx", + "tooling/types/styles.d.ts", + "tooling/types/test-globals.d.ts" + ], + "exclude": ["**/*.contract.test.ts"], + "references": [{ "path": "./tsconfig.api.json" }] +}