6.11 No new module-level shared state: examples

Rule: §6.11 in the code standards.

Why

Importing shared state works like a service locator: the module reaches out for what it needs, and its signature no longer shows the dependency. Every importer then shares one copy for the life of the process, so a test has to reset it between blocks (B8.13).

The rule covers three shapes:

  • an exported mutable binding (export let, or an exported Set or Map that other modules change);
  • a module-level registry that other modules read or change through imported functions;
  • a module-level slot that a setter fills at startup and the module’s functions read later.

These are not shared state: a constant table built once at import and never changed (allDefs in src/groups/groupCatalogue.ts), and a module-private cache of a fixed value (getServerVersion in src/shared/version.ts).

Good: state owned by an object the factory builds

src/transport/runtimeConnection.ts:93-96 keeps the runtime channel and its port inside the closure that createRuntimeConnection returns, so each instance has its own:

let runtimeChannel: Channel | undefined = opts?.explicitRuntimePort
  ? createRuntimeChannel(opts.explicitRuntimePort)
  : undefined;
let cachedRuntimePort: number | undefined = opts?.explicitRuntimePort ? Number(opts.explicitRuntimePort) : undefined;

Bad: an exported mutable set

src/groups/groupState.ts:12 is an existing case, listed in B7:

export const loadedGroups = new Set<string>();

Another module changes it through the import, src/groups/groupActivation.ts:178 and :213:

loadedGroups.delete(groupName);
loadedGroups.add(group.name);

Bad: a slot a setter fills

src/index.ts:81-82 builds the hook pipeline at the root, which 6.10 asks for, but hands it over through a module slot instead of a parameter:

const hookPipeline = createHookPipeline();
setGlobalHookPipeline(hookPipeline);

src/registration/toolRegistry.ts:38 holds the slot, and line 227 reads it:

let globalHookPipeline: HookPipeline | undefined = undefined;
const pipeline = opts.hookPipeline ?? globalHookPipeline;

Both are existing cases, listed in B7.

Source


This site uses Just the Docs, a documentation theme for Jekyll.