6.9 Pure modules import only pure modules and types: examples
Rule: §6.9 in the code standards.
Why
A pure module does no I/O, holds no module state and arms no timers, so its tests feed it plain values and check what comes back. If it imports one module with I/O or state, it stops being pure, and so does every module that imports it. Dependencies therefore point one way: code with I/O or state may import a pure module, never the reverse. Allowed imports for a pure module are other pure modules, side-effect-free Node built-ins such as node:path, import type, and third-party schema libraries such as Zod.
When callers want one entry point that both looks something up and applies a pure rule, put that composing function on the impure side.
Good: a pure check, imported by stateful code
src/security/pathGuard.ts:25 is the module’s only import, and it is type-only:
import type { PathGuard } from "../shared/types.js";
src/registration/toolRegistry.ts:21, a module with state of its own, imports the pure check:
import { checkPathGuard } from "../security/pathGuard.js";
Bad: the pure check reaches for its own data
A sketch, not code in the repo:
// src/security/pathGuard.ts
import { lookupProject } from "../registry.js";
registry.ts reads projects.json and holds a watcher. With this import, checkPathGuard can no longer be tested with plain values, and every tool module that imports PROJECT_FILE_PATH from pathGuard.ts now loads the registry as well. The lookup belongs with the caller, which passes the result in.
Source
- Mark Seemann, Dependency rejection: pure functions take direct input and return direct output, and impure code sits at the edges.
- TypeScript, Modules reference:
import typefor anything used only in type positions.