chore(server): lint rule refusing a Promise used as a plain value, and the misses it found

This commit is contained in:
jubnl
2026-09-21 21:39:39 +02:00
parent 953e2526bb
commit d73215f7f6
8 changed files with 427 additions and 7 deletions
@@ -0,0 +1,134 @@
import noPromiseAsValue from '../../../eslint-rules/no-promise-as-value.mjs';
import tsParser from '@typescript-eslint/parser';
import { RuleTester, type Rule } from 'eslint';
import path from 'path';
// The rule only exists because it is TYPE-aware, so the tester runs against a
// real TypeScript program: eslint-rules/fixtures/ holds a tsconfig whose single
// file is the one the tester feeds code into. It lives outside src/ and tests/
// so the deliberately-broken snippets below never reach tsc or the lint gates.
const fixtureRoot = path.resolve(__dirname, '../../../eslint-rules/fixtures');
const ruleTester = new RuleTester({
languageOptions: {
parser: tsParser,
parserOptions: {
project: './tsconfig.json',
tsconfigRootDir: fixtureRoot,
},
},
});
const PRELUDE = `
declare function getSettings(id: number): Promise<Record<string, string>>;
declare function getName(id: number): Promise<string>;
declare function getCount(): Promise<number>;
declare function getRows(): Promise<string[]>;
declare function maybeSettings(id: number): Promise<Record<string, string>> | null;
declare function syncName(id: number): string;
declare const rows: { id: number; active: boolean }[];
declare const expect: (value: unknown) => { resolves: { toBe(value: unknown): void } };
`;
/** Every case shares the declarations above; offsets never matter, only counts. */
const withPrelude = (code: string) => `${PRELUDE}${code}\n`;
const valid = [
// Awaited first — the shape every finding is fixed into.
`const s = await getSettings(1); const v = s['metric']; void v;`,
`const hit = (await getName(1)) === 'x'; void hit;`,
`const msg = \`\${await getCount()}\`; void msg;`,
`const all = [...(await getRows())]; void all;`,
`for (const r of await getRows()) { void r; }`,
`const keys = Object.keys(await getSettings(1)); void keys;`,
// Promise-shaped uses that are correct by construction.
`const n = getName(1).then((x) => x.length); void n;`,
`const both = await Promise.all([getName(1), getCount()]); void both;`,
`const joined = \`\${(await Promise.all([getName(1)]))[0]}\`; void joined;`,
`expect(getName(1)).resolves.toBe('x');`,
`const isP = getName(1) instanceof Promise; void isP;`,
// Existence / identity checks on a parked promise: the in-flight-map idiom the
// server uses everywhere, and the one a truthiness test would get wrong.
`const inflight = new Map<string, Promise<string>>(); const hit = inflight.get('k'); if (hit !== undefined) { void hit; }`,
`let building: Promise<string> = getName(1); if (building === null) { void 0; }`,
`const chains = new Map<number, Promise<void>>(); const next = Promise.resolve(); if (chains.get(1) === next) { void 0; }`,
`const chains = new Map<number, Promise<void>>(); const prev = chains.get(1) ?? Promise.resolve(); void prev;`,
`void getName(1);`,
// Non-promise values, and the array callbacks a promise legitimately flows through.
`const same = syncName(1) === 'x'; void same;`,
`const active = rows.filter((r) => r.active); void active;`,
`const pending = rows.map((r) => getName(r.id)); void pending;`,
].map((code) => ({ code: withPrelude(code), filename: path.join(fixtureRoot, 'file.ts') }));
const invalid = [
// Element access: compiles to `any` with strict mode off — the live miss Task 2 found.
`const v = getSettings(1)['metric']; void v;`,
// Property access on a promise-typed object, bracket-free.
`const v = getSettings(1).metric; void v;`,
// Comparisons: always false, no error.
`if (getName(1) === 'x') { void 0; }`,
`const n = getCount() + 1; void n;`,
`const has = 'metric' in getSettings(1); void has;`,
// Interpolation: "[object Promise]".
`const msg = \`\${getCount()}\`; void msg;`,
// Spread: neither iterable nor enumerable at runtime.
`const a = [...getRows()]; void a;`,
`const o = { ...getSettings(1) }; void o;`,
// Plain-value consumers.
`Object.keys(getSettings(1));`,
`JSON.stringify(getSettings(1));`,
`Array.isArray(getRows());`,
`const t = typeof getName(1); void t;`,
// Iteration.
`for (const r of getRows()) { void r; }`,
`for (const k in getSettings(1)) { void k; }`,
// Logical left operand: always truthy, so the fallback is dead code.
`const v = getName(1) || 'x'; void v;`,
// A predicate callback that returns a promise: every element passes.
`const active = rows.filter((r) => getName(r.id)); void active;`,
].map((code) => ({
code: withPrelude(code),
filename: path.join(fixtureRoot, 'file.ts'),
errors: [{ messageId: 'promiseAsValue' }],
}));
ruleTester.run('trek/no-promise-as-value', noPromiseAsValue as unknown as Rule.RuleModule, {
valid,
invalid,
});
// Under strictNullChecks a promise-returning call can genuinely be nullable, and
// `p ?? x` / `p === null` are then real checks rather than missing awaits. The
// server compiles with `strict: false`, where that union collapses and these
// branches are unreachable — so they get their own project to be tested in.
const strictTester = new RuleTester({
languageOptions: {
parser: tsParser,
parserOptions: { project: './tsconfig.strict.json', tsconfigRootDir: fixtureRoot },
},
});
const strictFile = path.join(fixtureRoot, 'strict.ts');
strictTester.run('trek/no-promise-as-value (strictNullChecks)', noPromiseAsValue as unknown as Rule.RuleModule, {
valid: [
{ code: withPrelude(`const f = maybeSettings(1) ?? null; void f;`), filename: strictFile },
{ code: withPrelude(`const missing = maybeSettings(1) === null; void missing;`), filename: strictFile },
],
invalid: [
{
// Nullable or not, indexing it is still a missing await.
code: withPrelude(`const v = maybeSettings(1)!['metric']; void v;`),
filename: strictFile,
errors: [{ messageId: 'promiseAsValue' }],
},
{
// A union of `Promise<T> | null` is still a promise once the nullish
// members are stripped — interpolating it is "[object Promise]".
code: withPrelude(`const msg = \`\${maybeSettings(1)}\`; void msg;`),
filename: strictFile,
errors: [{ messageId: 'promiseAsValue' }],
},
],
});
@@ -362,8 +362,8 @@ describe('instance-scope actions (admin)', () => {
.run(pluginId, key, key, scope);
}
const adminReq = { user: { id: 42 } } as unknown as Request;
function controller(invoke = vi.fn(async () => ({ ok: true, message: 'pong' }))) {
const rt = createPluginRuntime(new DatabaseService(dbConn));
async function controller(invoke = vi.fn(async () => ({ ok: true, message: 'pong' }))) {
const rt = await createPluginRuntime(new DatabaseService(dbConn));
// isActive normally reflects the supervisor's live child map, which nothing here
// spawns — so it's stubbed to read the same DB status the test itself flips,
// mirroring what an actually-activated plugin would report.
@@ -375,25 +375,25 @@ describe('instance-scope actions (admin)', () => {
beforeEach(() => { testDb.prepare('DELETE FROM plugin_actions').run(); });
it('ACT-ADM-001 — GET config lists the instance actions and none of the user ones', () => {
it('ACT-ADM-001 — GET config lists the instance actions and none of the user ones', async () => {
install('p');
declareAction('p', 'purge', 'instance');
declareAction('p', 'testConnection', 'user');
const { c } = controller();
const { c } = await controller();
expect(c.getConfig('p').actions).toEqual([{ key: 'purge', label: 'purge', hint: undefined, danger: false, scope: 'instance' }]);
});
it('ACT-ADM-002 — POST runs the action as the clicking admin in the instance scope', async () => {
install('p');
testDb.prepare("UPDATE plugins SET status = 'active', enabled = 1 WHERE id = 'p'").run();
const { c, invoke } = controller();
const { c, invoke } = await controller();
expect(await c.runAction('p', 'purge', adminReq)).toEqual({ ok: true, message: 'pong' });
expect(invoke).toHaveBeenCalledWith('p', 'purge', 42, 'instance');
});
it('ACT-ADM-003 — an inactive plugin answers 404 like the user route', async () => {
install('p');
const { c, invoke } = controller();
const { c, invoke } = await controller();
await expect(c.runAction('p', 'purge', adminReq)).rejects.toMatchObject({ status: 404, response: { error: 'Plugin is not active' } });
expect(invoke).not.toHaveBeenCalled();
});
@@ -401,7 +401,7 @@ describe('instance-scope actions (admin)', () => {
it('ACT-ADM-004 — a refused key is a failed RESULT, not a server error', async () => {
install('p');
testDb.prepare("UPDATE plugins SET status = 'active', enabled = 1 WHERE id = 'p'").run();
const { c } = controller(vi.fn(async () => { throw new Error('plugin p did not declare action "x" in scope instance'); }));
const { c } = await controller(vi.fn(async () => { throw new Error('plugin p did not declare action "x" in scope instance'); }));
expect(await c.runAction('p', 'x', adminReq)).toEqual({ ok: false, message: 'plugin p did not declare action "x" in scope instance' });
});
});