From 8eaf637fd94692e14f2d8aec4b7782a359746dbb Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 16:06:41 +0900 Subject: [PATCH 01/41] Follow helper-returned delivery arrays Track arrays of delivery promises returned by synchronous local helpers at their call sites, so awaiting an array cannot hide unfinished delivery. Keep mixed and unsupported return shapes quiet without losing independent completion-promise warnings. Cover helper chains, aggregation, callback positions, and diagnostic locations, and document the conservative analysis boundaries. Closes https://github.com/fedify-dev/fedify/issues/1070 Assisted-by: OpenCode:gpt-6.1-sol Assisted-by: OpenCode:kimi-k3.1-pro Assisted-by: OpenCode:gpt-6-astra Assisted-by: OpenCode:gemini-4-argon --- CHANGES.md | 7 + changes.d/lint/helper-delivery-arrays.md | 10 + docs/manual/lint.md | 16 +- .../outbox-listener-delivery-not-awaited.ts | 293 ++++++++++++++- ...tbox-listener-delivery-not-awaited.test.ts | 341 +++++++++++++++++- .../outbox-listener-delivery-rules.test.ts | 11 + 6 files changed, 651 insertions(+), 27 deletions(-) create mode 100644 changes.d/lint/helper-delivery-arrays.md diff --git a/CHANGES.md b/CHANGES.md index 99da4b268..fa4f5dea8 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -443,17 +443,24 @@ To be released. failures, and in Oxlint, where it has to be enabled by name. It is not registered in Deno Lint, which reports every plugin rule as an error. [[#1401], [#1443]] + - Changed `outbox-listener-delivery-not-awaited` to follow arrays of delivery + promises returned by synchronous local helpers. Awaiting or discarding + such an array now produces a warning; use `Promise.all()` to wait for its + deliveries. Mixed or unknown helper returns remain unreported. + [[#1070], [#1446]] - Extended `raw-property-iri-invalid` to check `withRawProperty()` and static record and tuple keys passed to `withRawProperties()`. The rule reports invalid property IRIs and compact prefixes such as `as:content` across Deno Lint, ESLint, and Oxlint. [[#1355], [#1420]] +[#1070]: https://github.com/fedify-dev/fedify/issues/1070 [#1272]: https://github.com/fedify-dev/fedify/issues/1272 [#1355]: https://github.com/fedify-dev/fedify/issues/1355 [#1356]: https://github.com/fedify-dev/fedify/pull/1356 [#1401]: https://github.com/fedify-dev/fedify/issues/1401 [#1420]: https://github.com/fedify-dev/fedify/pull/1420 [#1443]: https://github.com/fedify-dev/fedify/pull/1443 +[#1446]: https://github.com/fedify-dev/fedify/pull/1446 ### @fedify/mysql diff --git a/changes.d/lint/helper-delivery-arrays.md b/changes.d/lint/helper-delivery-arrays.md new file mode 100644 index 000000000..5eb7ab730 --- /dev/null +++ b/changes.d/lint/helper-delivery-arrays.md @@ -0,0 +1,10 @@ +--- +links: + '#1070': https://github.com/fedify-dev/fedify/issues/1070 + '#1446': https://github.com/fedify-dev/fedify/pull/1446 +--- + - Changed `outbox-listener-delivery-not-awaited` to follow arrays of delivery + promises returned by synchronous local helpers. Awaiting or discarding + such an array now produces a warning; use `Promise.all()` to wait for its + deliveries. Mixed or unknown helper returns remain unreported. + [[#1070], [#1446]] diff --git a/docs/manual/lint.md b/docs/manual/lint.md index 3b4d688a4..d2d1546fe 100644 --- a/docs/manual/lint.md +++ b/docs/manual/lint.md @@ -1017,13 +1017,15 @@ When it cannot tell where a promise goes, the rule stays quiet. In practice: reported. A callback that is invoked immediately, or given to `map()` or `then()`, is only as safe as the result of that call. The same holds for a function passed by name, as in `inboxes.forEach(deliver)`. - - A local helper that delivers is judged by how it is called: `deliver();` is - reported when `deliver()` awaits or returns a delivery, and - `await deliver();` is not. An array of promises, or an object holding one, - that a helper returns is not followed to where the helper is called, since - the caller may pass it to `Promise.all()`. So `await deliverAll();` and a - bare `deliverAll();` are not reported when `deliverAll()` returns the - result of `map()`. + - For a local helper that awaits or returns a delivery, the rule reports a + bare `deliver();` call but not `await deliver();`. A synchronous helper + that consistently returns an array of delivery promises is followed to its + call sites, including through other local helpers. `await deliverAll();`, + a bare `deliverAll();`, and returning that array from the listener are + reported; use `await Promise.all(deliverAll())` to wait for the deliveries. + Mixed or unclassifiable returns stay quiet. The rule does not follow + arrays returned by `async` helpers, recursive return chains, arrays + returned through stored variables, or objects returned by helpers. - A promise passed to a function the rule does not know, such as `queue.push(...)` or `setTimeout(...)`, is left alone, since the rule cannot tell what that function does with it. diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 0378f5105..ba96f89a7 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -35,7 +35,11 @@ type Fate = "dropped" | "awaited" | "returned" | "handled"; * or a `return`: the function that now carries the promise on to its own * callers. */ -type Outcome = { fate: Fate; owner: FunctionLikeNode | null }; +type Outcome = { + fate: Fate; + owner: FunctionLikeNode | null; + shape?: Shape; +}; const HANDLED: Outcome = { fate: "handled", owner: null }; const DROPPED: Outcome = { fate: "dropped", owner: null }; @@ -248,7 +252,11 @@ type Analysis = { * Where the value a callback returns goes, judged by the call that receives * the callback. */ -function callbackResultOutcome(call: Node, analysis: Analysis): Outcome { +function callbackResultOutcome( + call: Node, + analysis: Analysis, + callback: Node, +): Outcome { const callee = unwrap(asNode(get(call, "callee")) ?? call); const name = memberName(callee); // `forEach()` discards what its callback returns, which is the one callback @@ -256,6 +264,8 @@ function callbackResultOutcome(call: Node, analysis: Analysis): Outcome { // `setTimeout()`, may well keep it. if (name === "forEach") return DROPPED; if (name === "map" || name === "flatMap") { + // The optional second argument is thisArg, not another callback. + if ((get(call, "arguments") as Node[])[0] !== callback) return HANDLED; return fateOf(call, analysis, "promises"); } if (name != null && PROMISE_CHAIN_METHODS.has(name)) { @@ -278,7 +288,7 @@ function returnedOutcome( return fateOf(parent, analysis, "promise"); } if ((get(parent, "arguments") as unknown[]).includes(fn)) { - return callbackResultOutcome(parent, analysis); + return callbackResultOutcome(parent, analysis, fn); } } // A function declared or held under a name hands the promise to its @@ -295,8 +305,12 @@ function returnedOutcome( function returnedContainerOutcome( fn: FunctionLikeNode | null, analysis: Analysis, + shape: Shape, ): Outcome { - return fn === analysis.listener ? DROPPED : HANDLED; + if (fn === analysis.listener) return DROPPED; + return fn != null && shape === "promises" + ? { fate: "returned", owner: fn, shape } + : HANDLED; } /** Follows the value of `expression` up through its parents to where it ends up. */ @@ -327,13 +341,21 @@ function fateOf( case "ReturnStatement": return currentShape === "promise" ? returnedOutcome(enclosingFunction(parent), analysis) - : returnedContainerOutcome(enclosingFunction(parent), analysis); + : returnedContainerOutcome( + enclosingFunction(parent), + analysis, + currentShape, + ); case "ArrowFunctionExpression": if (get(parent, "body") !== current) return HANDLED; return currentShape === "promise" ? returnedOutcome(parent as FunctionLikeNode, analysis) - : returnedContainerOutcome(parent as FunctionLikeNode, analysis); + : returnedContainerOutcome( + parent as FunctionLikeNode, + analysis, + currentShape, + ); case "ExpressionStatement": return DROPPED; @@ -482,6 +504,193 @@ function fateOf( } } +/** A small proof of no normal fallthrough, not a general control-flow graph. */ +function exitsFunction(node: Node): boolean { + switch (node.type) { + case "ReturnStatement": + case "ThrowStatement": + return true; + case "BlockStatement": + return (get(node, "body") as Node[]).some(exitsFunction); + case "IfStatement": { + const test = asNode(get(node, "test")); + const consequent = asNode(get(node, "consequent")); + const alternate = asNode(get(node, "alternate")); + if (test?.type === "Literal") { + const branch = test.value ? consequent : alternate; + return branch != null && exitsFunction(branch); + } + return ( + consequent != null && + alternate != null && + exitsFunction(consequent) && + exitsFunction(alternate) + ); + } + default: + return false; + } +} + +/** + * Classifies the container a helper returns independently of whether it + * contains a delivery. The carrying walk supplies that evidence separately. + * Unknown dependencies and recursive cycles never certify an array. + */ +function helperReturnShapes( + scopes: readonly UsedScope[], + isDeliveryCall: (call: CallExpression) => boolean, +): { + shapes: ReadonlyMap; + arrayInvolved: ReadonlySet; +} { + const returns = new Map(); + const scopesByFunction = new Map(); + for (const scope of scopes) { + const fn = scope.fn; + if (fn == null) continue; + scopesByFunction.set(fn, scope); + const body = fn.body as Node; + returns.set( + fn, + body.type !== "BlockStatement" + ? [body] + : [ + ...scope.statements + .filter((node) => node.type === "ReturnStatement") + .map((node) => asNode(get(node, "argument"))), + ...(exitsFunction(body) ? [] : [null]), + ], + ); + } + + const helpersOf = (node: Node, scope: UsedScope): FunctionLikeNode[] => { + const callee = unwrap(asNode(get(node, "callee")) ?? node); + return callee.type === "Identifier" + ? (scope.functionsByName.get(callee.name) ?? []) + : []; + }; + // Keep array provenance even when a mixed or unsupported return has no + // shape. Otherwise legacy promise propagation could revive that helper. + const arrayInvolved = new Set(); + const involvesArray = (node: Node | null, scope: UsedScope): boolean => { + if (node == null) return false; + node = unwrap(node); + switch (node.type) { + case "ArrayExpression": + return true; + case "CallExpression": { + const name = memberName(unwrap(asNode(get(node, "callee")) ?? node)); + return ( + name === "map" || + name === "flatMap" || + helpersOf(node, scope).some( + (fn) => get(fn, "async") !== true && arrayInvolved.has(fn), + ) + ); + } + case "ConditionalExpression": + return ( + involvesArray(asNode(get(node, "consequent")), scope) || + involvesArray(asNode(get(node, "alternate")), scope) + ); + case "LogicalExpression": + return ( + involvesArray(asNode(get(node, "left")), scope) || + involvesArray(asNode(get(node, "right")), scope) + ); + case "SequenceExpression": + return involvesArray( + (get(node, "expressions") as Node[]).at(-1) ?? null, + scope, + ); + case "AwaitExpression": + return involvesArray(asNode(get(node, "argument")), scope); + default: + return false; + } + }; + for (let changed = true; changed;) { + changed = false; + for (const [fn, expressions] of returns) { + if ( + !arrayInvolved.has(fn) && + expressions.some((node) => + involvesArray(node, scopesByFunction.get(fn)!), + ) + ) { + arrayInvolved.add(fn); + changed = true; + } + } + } + + const shapes = new Map(); + const active = new Set(); + const agree = (values: (Shape | null)[]): Shape | null => + values.length > 0 && + values[0] != null && + values.every((value) => value === values[0]) + ? values[0] + : null; + const expressionShape = ( + node: Node | null, + scope: UsedScope, + ): Shape | null => { + if (node == null) return null; + node = unwrap(node); + switch (node.type) { + case "ArrayExpression": + return "promises"; + case "ConditionalExpression": + return agree([ + expressionShape(asNode(get(node, "consequent")), scope), + expressionShape(asNode(get(node, "alternate")), scope), + ]); + case "SequenceExpression": + return expressionShape( + (get(node, "expressions") as Node[]).at(-1) ?? null, + scope, + ); + case "CallExpression": { + if (isDeliveryCall(node as CallExpression)) return "promise"; + const callee = unwrap(asNode(get(node, "callee")) ?? node); + const name = memberName(callee); + if (name === "map" || name === "flatMap") return "promises"; + const object = asNode(get(callee, "object")); + if ( + object != null && + unwrap(object).type === "Identifier" && + get(unwrap(object), "name") === "Promise" && + name != null && + PROMISE_COMBINATORS.has(name) + ) + return "promise"; + return agree(helpersOf(node, scope).map(functionShape)); + } + default: + return null; + } + }; + const functionShape = (fn: FunctionLikeNode): Shape | null => { + if (shapes.has(fn)) return shapes.get(fn)!; + if (active.has(fn)) return null; + const scope = scopesByFunction.get(fn); + if (scope == null || get(fn, "generator") === true) return null; + active.add(fn); + let shape = agree( + (returns.get(fn) ?? []).map((node) => expressionShape(node, scope)), + ); + active.delete(fn); + // An async array return is Promise, not a completion promise. + if (shape === "promises" && get(fn, "async") === true) shape = null; + shapes.set(fn, shape); + return shape; + }; + for (const fn of returns.keys()) functionShape(fn); + return { shapes, arrayInvolved }; +} + /** Reports every place in `listener` where a delivery promise is dropped. */ function checkListener( listener: FunctionLikeNode, @@ -509,6 +718,7 @@ function checkListener( const mentioned = new Set(); collectReferencedNames(listener.body, mentioned, true); const analysis: Analysis = { listener, mentioned }; + const { shapes, arrayInvolved } = helperReturnShapes(scopes, isDeliveryCall); const callsByScope = scopes.map((scope) => { const calls: CallExpression[] = []; @@ -523,16 +733,46 @@ function checkListener( // inside a `map()` callback lands in whatever function awaits or returns // the `Promise.all()` around it. const carrying = new Map(); - const carriesDelivery = (call: CallExpression, scope: UsedScope): boolean => { - if (isDeliveryCall(call)) return true; + const carryingArrays = new Set(); + const carriesCompletion = (helpers: readonly FunctionLikeNode[]): boolean => + helpers.some((fn) => carrying.has(fn)) && + helpers.every((fn) => !arrayInvolved.has(fn) || get(fn, "async") === true); + const deliveryShape = ( + call: CallExpression, + scope: UsedScope, + ): Shape | null => { + if (isDeliveryCall(call)) return "promise"; const callee = unwrap(call.callee as Node); - if (callee.type !== "Identifier") return false; + if (callee.type !== "Identifier") return null; const helpers = scope.functionsByName.get(callee.name); - return helpers?.some((helper) => carrying.has(helper)) ?? false; + if (helpers == null || helpers.length === 0) return null; + if (carriesCompletion(helpers)) return "promise"; + if (helpers.some((fn) => arrayInvolved.has(fn))) { + if (!helpers.every((fn) => shapes.get(fn) === "promises")) return null; + return helpers.some((fn) => carryingArrays.has(fn)) ? "promises" : null; + } + return null; }; - const noteCarrying = ({ fate, owner }: Outcome): boolean => { + const noteCarrying = ({ + fate, + owner, + shape = "promise", + }: Outcome): boolean => { if (owner == null || owner === listener) return false; if (fate !== "awaited" && fate !== "returned") return false; + // An independently awaited delivery still makes an async helper's own + // completion promise significant, even if it later returns an array. + if ( + arrayInvolved.has(owner) && + !(fate === "awaited" && get(owner, "async") === true) + ) { + if (shape !== "promises" || shapes.get(owner) !== "promises") + return false; + if (carryingArrays.has(owner)) return false; + carryingArrays.add(owner); + return true; + } + if (shape !== "promise") return false; const known = carrying.get(owner); if (known === "awaited" || known === fate) return false; carrying.set(owner, fate); @@ -542,14 +782,28 @@ function checkListener( changed = false; for (const [index, scope] of scopes.entries()) { for (const call of callsByScope[index]) { - if ( - carriesDelivery(call, scope) && - noteCarrying(fateOf(call, analysis)) - ) { + const shape = deliveryShape(call, scope); + if (shape != null && noteCarrying(fateOf(call, analysis, shape))) { changed = true; } + for (const arg of call.arguments as Node[]) { + if (arg.type !== "Identifier") continue; + const helpers = scope.functionsByName.get(arg.name); + if (helpers == null || !carriesCompletion(helpers)) continue; + const outcome = callbackResultOutcome(call, analysis, arg); + if (outcome.shape === "promises" && noteCarrying(outcome)) { + changed = true; + } + } } } + // An inline async map callback carries delivery through its own promise + // into the returned array, without a named call to seed that array. + for (const [fn, kind] of carrying) { + if (kind !== "awaited") continue; + const outcome = returnedOutcome(fn, analysis); + if (outcome.shape === "promises" && noteCarrying(outcome)) changed = true; + } } const reported = new Set(); @@ -563,8 +817,9 @@ function checkListener( // dropped. for (const [index, scope] of scopes.entries()) { for (const call of callsByScope[index]) { - if (!carriesDelivery(call, scope)) continue; - if (fateOf(call, analysis).fate === "dropped") flag(call); + const shape = deliveryShape(call, scope); + if (shape == null) continue; + if (fateOf(call, analysis, shape).fate === "dropped") flag(call); } } @@ -588,8 +843,8 @@ function checkListener( for (const arg of call.arguments as Node[]) { if (arg.type !== "Identifier") continue; const held = scope.functionsByName.get(arg.name); - if (held == null || !held.some((fn) => carrying.has(fn))) continue; - if (callbackResultOutcome(call, analysis).fate === "dropped") { + if (held == null || !carriesCompletion(held)) continue; + if (callbackResultOutcome(call, analysis, arg).fate === "dropped") { flag(arg); } } diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index c2fd671f1..b01277ec3 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -1,10 +1,349 @@ +import * as tsParser from "@typescript-eslint/parser"; +import { Linter } from "eslint"; +import { deepStrictEqual } from "node:assert/strict"; import { test } from "node:test"; -import { RULE_IDS } from "../lib/const.ts"; +import { FEDERATION_SETUP, RULE_IDS } from "../lib/const.ts"; import lintTest from "../lib/test.ts"; import * as rule from "../rules/outbox-listener-delivery-not-awaited.ts"; const ruleName = RULE_IDS.outboxListenerDeliveryNotAwaited; +const arrayHelperDelivery = "ctx.sendActivity(sender, inbox, activity)"; +const arrayHelperMap = `inboxes.map((inbox) => ${arrayHelperDelivery})`; + +for (const [producer, definition] of [ + ["map", `const deliverAll = () => ${arrayHelperMap};`], + [ + "async map callback", + `const deliverAll = () => inboxes.map(async () => { await ${arrayHelperDelivery}; });`, + ], + [ + "named map callback", + `const deliverOne = () => ${arrayHelperDelivery}; const deliverAll = () => inboxes.map(deliverOne);`, + ], + [ + "named async map callback", + `const deliverOne = async () => { await ${arrayHelperDelivery}; }; const deliverAll = () => inboxes.map(deliverOne);`, + ], + [ + "flatMap", + `const deliverAll = () => inboxes.flatMap(() => ${arrayHelperDelivery});`, + ], + ["literal", `const deliverAll = () => [${arrayHelperDelivery}];`], + ["block", `function deliverAll() { return ${arrayHelperMap}; }`], + ["wrapper", `const deliverAll = () => ([${arrayHelperDelivery}] as const)!;`], + [ + "conditional", + `const deliverAll = () => condition ? [${arrayHelperDelivery}] : ${arrayHelperMap};`, + ], + [ + "branches", + `function deliverAll() { if (condition) return [${arrayHelperDelivery}]; else return ${arrayHelperMap}; }`, + ], + [ + "chain", + `const deliverAll = () => inner(); const inner = () => [${arrayHelperDelivery}];`, + ], + [ + "reverse chain", + `const inner = () => [${arrayHelperDelivery}]; const deliverAll = () => inner();`, + ], + [ + "spread", + `const inner = () => [${arrayHelperDelivery}]; const deliverAll = () => [...inner()];`, + ], + ["sequence", `const deliverAll = () => (log(), [${arrayHelperDelivery}]);`], + [ + "empty branch", + `const deliverAll = () => condition ? [] : [${arrayHelperDelivery}];`, + ], +] as const) { + for (const [consumer, code, dropped] of [ + ["bare", "deliverAll();", true], + ["await", "await deliverAll();", true], + ["return", "return deliverAll();", true], + ["forgotten", "const pending = deliverAll();", true], + ["dropped combinator", "Promise.all(deliverAll());", true], + [ + "stored", + "const pending = deliverAll(); await Promise.all(pending);", + false, + ], + ["void", "void deliverAll();", false], + ["unknown consumer", "own(deliverAll());", false], + ...["all", "allSettled", "race", "any"].map( + (method) => + [method, `await Promise.${method}(deliverAll());`, false] as const, + ), + ] as const) { + test( + `${ruleName}: array helper ${producer}, ${consumer}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const sender = { identifier: ctx.identifier }; + const inbox = new URL("https://example.com/inbox"); + ${definition} + ${code} + }); +`, + rule, + ruleName, + ...(dropped ? { expectedError: "Delivery is not awaited" } : {}), + }), + ); + } +} + +for (const [scenario, definition] of [ + [ + "mixed array first", + `function deliverAll() { if (condition) return [${arrayHelperDelivery}]; return ${arrayHelperDelivery}; }`, + ], + [ + "mixed promise first", + `function deliverAll() { if (condition) return ${arrayHelperDelivery}; return [${arrayHelperDelivery}]; }`, + ], + [ + "mixed conditional", + `const deliverAll = () => condition ? [${arrayHelperDelivery}] : ${arrayHelperDelivery};`, + ], + [ + "unknown first", + `function deliverAll() { if (condition) return unknown(); return [${arrayHelperDelivery}]; }`, + ], + [ + "unknown last", + `function deliverAll() { if (condition) return [${arrayHelperDelivery}]; return unknown(); }`, + ], + [ + "bare return", + `function deliverAll() { if (condition) return; return [${arrayHelperDelivery}]; }`, + ], + [ + "fallthrough", + `function deliverAll() { if (condition) return [${arrayHelperDelivery}]; }`, + ], + ["async array", `const deliverAll = async () => [${arrayHelperDelivery}];`], + ["object", `const deliverAll = () => ({ pending: ${arrayHelperMap} });`], + [ + "stored identifier", + `const deliverAll = () => { const pending = [${arrayHelperDelivery}]; return pending; };`, + ], + [ + "named thisArg", + `const deliverOne = () => ${arrayHelperDelivery}; const deliverAll = () => inboxes.map((inbox) => inbox, deliverOne);`, + ], + [ + "inline async thisArg", + `const deliverAll = () => inboxes.map((inbox) => inbox, async () => { await ${arrayHelperDelivery}; });`, + ], + [ + "inline returning thisArg", + `const deliverAll = () => inboxes.flatMap((inbox) => inbox, () => ${arrayHelperDelivery});`, + ], + [ + "self recursion", + `const deliverAll = () => condition ? [${arrayHelperDelivery}] : deliverAll();`, + ], + [ + "mutual recursion", + `const deliverAll = () => inner(); const inner = () => condition ? [${arrayHelperDelivery}] : deliverAll();`, + ], + [ + "conflicting bindings", + `let deliverAll = () => [${arrayHelperDelivery}]; deliverAll = () => ${arrayHelperDelivery};`, + ], +] as const) { + test( + `${ruleName}: opaque array helper ${scenario} stays quiet through callers and callbacks`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + ${definition} + const outer = () => deliverAll(); + await deliverAll(); + deliverAll(); + outer(); + inboxes.forEach(deliverAll); + inboxes.forEach(outer); + await Promise.all(await deliverAll()); + }); +`, + rule, + ruleName, + }), + ); +} + +for (const [scenario, definition, consumer, dropped] of [ + [ + "async array and returned completion bindings", + `let deliver = async () => []; if (condition) { deliver = () => ${arrayHelperDelivery}; }`, + "deliver();", + true, + ], + [ + "async array and returned completion callback", + `let deliver = async () => []; if (condition) { deliver = () => ${arrayHelperDelivery}; }`, + "inboxes.forEach(deliver);", + true, + ], + [ + "awaited async array and returned completion", + `let deliver = async () => []; if (condition) { deliver = () => ${arrayHelperDelivery}; }`, + "await deliver();", + false, + ], + [ + "mixed sync and async completion bindings", + `let deliver = async () => { await ${arrayHelperDelivery}; return []; }; if (condition) { deliver = () => ${arrayHelperDelivery}; }`, + "deliver();", + true, + ], + [ + "mixed completion callback bindings", + `let deliver = async () => { await ${arrayHelperDelivery}; return []; }; if (condition) { deliver = () => ${arrayHelperDelivery}; }`, + "inboxes.forEach(deliver);", + true, + ], + [ + "awaited mixed completion bindings", + `let deliver = async () => { await ${arrayHelperDelivery}; return []; }; if (condition) { deliver = () => ${arrayHelperDelivery}; }`, + "await deliver();", + false, + ], + [ + "async helper independently awaits delivery", + `const deliver = async () => { await ${arrayHelperDelivery}; return []; };`, + "deliver();", + true, + ], + [ + "async completion through a sync helper", + `const inner = async () => { await ${arrayHelperDelivery}; return []; }; const deliver = () => inner();`, + "deliver();", + true, + ], + [ + "awaited async helper independently awaits delivery", + `const deliver = async () => { await ${arrayHelperDelivery}; return []; };`, + "await deliver();", + false, + ], + [ + "async callback independently awaits delivery", + `const deliver = async () => { await ${arrayHelperDelivery}; return []; };`, + "inboxes.forEach(deliver);", + true, + ], + [ + "returned aggregate", + `const deliver = () => Promise.all(deliverAll());`, + "await deliver();", + false, + ], + [ + "dropped returned aggregate", + `const deliver = () => Promise.all(deliverAll());`, + "deliver();", + true, + ], + [ + "awaited aggregate", + `const deliver = async () => { await Promise.all(deliverAll()); };`, + "await deliver();", + false, + ], + [ + "dropped awaited aggregate", + `const deliver = async () => { await Promise.all(deliverAll()); };`, + "deliver();", + true, + ], + [ + "dead unknown return", + `function deliver() { return deliverAll(); return unknown(); }`, + "await deliver();", + true, + ], + [ + "dead branch", + `function deliver() { if (false) return unknown(); return deliverAll(); }`, + "await deliver();", + true, + ], + ["unused helper", "", "", false], + ["dead call", "", "if (false) deliverAll();", false], + [ + "named array callback", + "", + "await Promise.all(inboxes.map(deliverAll));", + false, + ], + [ + "promise chain callback", + "", + "await Promise.resolve().then(deliverAll);", + false, + ], +] as const) { + test( + `${ruleName}: array helper ${scenario}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const deliverAll = () => [${arrayHelperDelivery}]; + ${definition} + ${consumer} + }); +`, + rule, + ruleName, + ...(dropped ? { expectedError: "Delivery is not awaited" } : {}), + }), + ); +} + +test(`${ruleName}: array helper diagnostics identify only discarded call sites`, () => { + const code = `import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const deliverAll = () => [ctx.sendActivity(sender, inbox, activity)]; + await Promise.all(deliverAll()); + deliverAll(); + await deliverAll(); + Promise.all(deliverAll()); + return deliverAll(); + });`; + const messages = new Linter().verify( + `${FEDERATION_SETUP}\n\n${code}`, + [ + { + files: ["**/*.ts"], + languageOptions: { parser: tsParser }, + plugins: { fedify: { rules: { [ruleName]: rule.eslint } } }, + rules: { [`fedify/${ruleName}`]: "error" }, + }, + ], + "listener.ts", + ); + deepStrictEqual( + messages.map(({ ruleId, line, column }) => [ruleId, line, column]), + [6, 7, 8, 9].map((line) => [ + `fedify/${ruleName}`, + line + FEDERATION_SETUP.split("\n").length + 1, + line === 7 ? 11 : line === 8 ? 17 : line === 9 ? 12 : 5, + ]), + ); +}); + test( `${ruleName}: ✅ Good - awaited sendActivity call`, lintTest({ diff --git a/packages/lint/src/tests/outbox-listener-delivery-rules.test.ts b/packages/lint/src/tests/outbox-listener-delivery-rules.test.ts index b166415cc..8e910ad7a 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-rules.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-rules.test.ts @@ -15,6 +15,17 @@ const NOT_AWAITED_MESSAGE = "Delivery is not awaited"; // Every listener the not-awaited rule reports has a delivery call. const UNAWAITED: [title: string, code: string][] = [ + [ + "awaiting a local helper's delivery array", + ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const deliverAll = () => [ctx.sendActivity(sender, inbox, activity)]; + await deliverAll(); + }); +`, + ], [ "bare sendActivity call", ` From 32b6161291c4c0c7001237b2fe25452e41f7481a Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 16:51:09 +0900 Subject: [PATCH 02/41] Follow delivery arrays through intermediate awaits Await preserves an array value rather than waiting for its elements. Keep following that value so a later combinator or stored reference can handle delivery without a false diagnostic. Bare awaits still report when the resulting array is discarded. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4596660985 Assisted-by: OpenCode:gpt-6.1-sol --- docs/manual/lint.md | 9 ++++++--- .../rules/outbox-listener-delivery-not-awaited.ts | 13 ++++++++++--- .../outbox-listener-delivery-not-awaited.test.ts | 6 ++++++ 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/docs/manual/lint.md b/docs/manual/lint.md index d2d1546fe..a72764588 100644 --- a/docs/manual/lint.md +++ b/docs/manual/lint.md @@ -1023,9 +1023,12 @@ When it cannot tell where a promise goes, the rule stays quiet. In practice: call sites, including through other local helpers. `await deliverAll();`, a bare `deliverAll();`, and returning that array from the listener are reported; use `await Promise.all(deliverAll())` to wait for the deliveries. - Mixed or unclassifiable returns stay quiet. The rule does not follow - arrays returned by `async` helpers, recursive return chains, arrays - returned through stored variables, or objects returned by helpers. + An intermediate `await` preserves the array: + `await Promise.all(await deliverAll())` and storing `await deliverAll()` + for later aggregation are accepted. Mixed or unclassifiable returns stay + quiet. The rule does not follow arrays returned by `async` helpers, + recursive return chains, arrays returned through stored variables, or + objects returned by helpers. - A promise passed to a function the rule does not know, such as `queue.push(...)` or `setTimeout(...)`, is left alone, since the rule cannot tell what that function does with it. diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index ba96f89a7..7e42981e1 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -334,9 +334,16 @@ function fateOf( // Awaiting an array of promises, or an object holding one, waits for // none of them. case "AwaitExpression": - return currentShape === "promise" - ? { fate: "awaited", owner: enclosingFunction(parent) } - : DROPPED; + if (currentShape === "promise") { + return { fate: "awaited", owner: enclosingFunction(parent) }; + } + // Await preserves an array value; its eventual consumer may still + // aggregate the deliveries, store the array, or discard it. + if (currentShape === "promises") { + current = parent; + continue; + } + return DROPPED; case "ReturnStatement": return currentShape === "promise" diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index b01277ec3..131dd2621 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -61,6 +61,12 @@ for (const [producer, definition] of [ for (const [consumer, code, dropped] of [ ["bare", "deliverAll();", true], ["await", "await deliverAll();", true], + ["intermediate await", "await Promise.all(await deliverAll());", false], + [ + "stored intermediate await", + "const pending = await deliverAll(); await Promise.all(pending);", + false, + ], ["return", "return deliverAll();", true], ["forgotten", "const pending = deliverAll();", true], ["dropped combinator", "Promise.all(deliverAll());", true], From da40789bed83f6d8fde24dc8cd1ce3d2672a4d33 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 16:53:04 +0900 Subject: [PATCH 03/41] Keep array helper inference inside lexical regions Do not certify calls from merged helper candidates whose lexical declaration region does not contain the reference. Block-local helpers must not classify calls to unrelated module helpers outside that block. Keep ambiguous candidates quiet without changing shared reachability. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4596660995 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 52 +++++++++++++++---- ...tbox-listener-delivery-not-awaited.test.ts | 45 ++++++++++++++++ 2 files changed, 88 insertions(+), 9 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 7e42981e1..6b786984a 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -156,6 +156,42 @@ function enclosingFunction(node: Node): FunctionLikeNode | null { return null; } +/** + * The shared reachability map merges block-local functions. Do not use a + * candidate outside its lexical declaration region: another binding may be + * visible there, including one outside the listener that this rule ignores. + * Ambiguous merged candidates remain unclassified rather than filtered down + * to a possibly incomplete set. + */ +function helpersAt(node: Node, scope: UsedScope): FunctionLikeNode[] { + if (node.type !== "Identifier") return []; + const helpers = scope.functionsByName.get(node.name) ?? []; + for (const fn of helpers) { + let declaration: Node = fn; + while ( + parentOf(declaration) != null && + TRANSPARENT_WRAPPERS.has(parentOf(declaration)!.type) + ) { + declaration = parentOf(declaration)!; + } + const declarator = parentOf(declaration); + const variable = + declarator?.type === "VariableDeclarator" ? parentOf(declarator) : null; + const region = + fn.type === "FunctionDeclaration" + ? parentOf(fn) + : variable?.type === "VariableDeclaration" && + get(variable, "kind") !== "var" + ? parentOf(variable) + : null; + if (region == null) continue; + let current: Node | null = node; + while (current != null && current !== region) current = parentOf(current); + if (current == null) return []; + } + return helpers; +} + /** The names an object pattern binds the delivery methods to. */ function deliveryAliasesOf(pattern: Node, out: Set): void { if (pattern.type !== "ObjectPattern") return; @@ -573,9 +609,7 @@ function helperReturnShapes( const helpersOf = (node: Node, scope: UsedScope): FunctionLikeNode[] => { const callee = unwrap(asNode(get(node, "callee")) ?? node); - return callee.type === "Identifier" - ? (scope.functionsByName.get(callee.name) ?? []) - : []; + return helpersAt(callee, scope); }; // Keep array provenance even when a mixed or unsupported return has no // shape. Otherwise legacy promise propagation could revive that helper. @@ -751,8 +785,8 @@ function checkListener( if (isDeliveryCall(call)) return "promise"; const callee = unwrap(call.callee as Node); if (callee.type !== "Identifier") return null; - const helpers = scope.functionsByName.get(callee.name); - if (helpers == null || helpers.length === 0) return null; + const helpers = helpersAt(callee, scope); + if (helpers.length === 0) return null; if (carriesCompletion(helpers)) return "promise"; if (helpers.some((fn) => arrayInvolved.has(fn))) { if (!helpers.every((fn) => shapes.get(fn) === "promises")) return null; @@ -795,8 +829,8 @@ function checkListener( } for (const arg of call.arguments as Node[]) { if (arg.type !== "Identifier") continue; - const helpers = scope.functionsByName.get(arg.name); - if (helpers == null || !carriesCompletion(helpers)) continue; + const helpers = helpersAt(arg, scope); + if (!carriesCompletion(helpers)) continue; const outcome = callbackResultOutcome(call, analysis, arg); if (outcome.shape === "promises" && noteCarrying(outcome)) { changed = true; @@ -849,8 +883,8 @@ function checkListener( for (const call of callsByScope[index]) { for (const arg of call.arguments as Node[]) { if (arg.type !== "Identifier") continue; - const held = scope.functionsByName.get(arg.name); - if (held == null || !carriesCompletion(held)) continue; + const held = helpersAt(arg, scope); + if (!carriesCompletion(held)) continue; if (callbackResultOutcome(call, analysis, arg).fate === "dropped") { flag(arg); } diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 131dd2621..c4762163e 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -317,6 +317,51 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const declaration of [ + "const deliverAll = () => [ctx.sendActivity(sender, inbox, activity)];", + "function deliverAll() { return [ctx.sendActivity(sender, inbox, activity)]; }", +]) { + for (const outside of [ + "await deliverAll(ctx, activity);", + "inboxes.forEach(deliverAll);", + "const outer = () => deliverAll(ctx, activity); await outer();", + ]) { + test( + `${ruleName}: block-local array does not classify ${outside} (${declaration})`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +async function deliverAll(ctx, activity) { await ctx.sendActivity(sender, inbox, activity); } +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + { ${declaration} await Promise.all(deliverAll()); } + ${outside} + }); +`, + rule, + ruleName, + }), + ); + } +} + +test( + `${ruleName}: block-local array helper still reports its own dropped call`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + { const deliverAll = () => [ctx.sendActivity(sender, inbox, activity)]; + await deliverAll(); } + }); +`, + rule, + ruleName, + expectedError: "Delivery is not awaited", + }), +); + test(`${ruleName}: array helper diagnostics identify only discarded call sites`, () => { const code = `import { Activity } from "@fedify/vocab"; federation.setOutboxListeners("/users/{identifier}/outbox") From 313ee349e9ef6f71ff345af88980083d297c5ae2 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 16:57:53 +0900 Subject: [PATCH 04/41] Follow delivery arrays through callback consumers Propagate synchronous array-returning callbacks through flatMap, for both inline and named functions, and report arrays discarded by forEach. Keep nested map arrays and async array returns conservative, and exclude thisArg positions from callback handling. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4596600131 https://github.com/fedify-dev/fedify/pull/1446#discussion_r4596600136 https://github.com/fedify-dev/fedify/pull/1446#discussion_r4596600142 Assisted-by: OpenCode:gpt-6.1-sol --- docs/manual/lint.md | 6 +- .../outbox-listener-delivery-not-awaited.ts | 47 +++++++++++---- ...tbox-listener-delivery-not-awaited.test.ts | 58 +++++++++++++++++++ 3 files changed, 100 insertions(+), 11 deletions(-) diff --git a/docs/manual/lint.md b/docs/manual/lint.md index a72764588..c9298e856 100644 --- a/docs/manual/lint.md +++ b/docs/manual/lint.md @@ -1025,7 +1025,11 @@ When it cannot tell where a promise goes, the rule stays quiet. In practice: reported; use `await Promise.all(deliverAll())` to wait for the deliveries. An intermediate `await` preserves the array: `await Promise.all(await deliverAll())` and storing `await deliverAll()` - for later aggregation are accepted. Mixed or unclassifiable returns stay + for later aggregation are accepted. Arrays returned by synchronous + `flatMap()` callbacks are followed through the flattened result. A named + `forEach()` callback returning a delivery array is reported because + `forEach()` discards it; a helper passed as `thisArg` is not invoked. + Mixed or unclassifiable returns stay quiet. The rule does not follow arrays returned by `async` helpers, recursive return chains, arrays returned through stored variables, or objects returned by helpers. diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 6b786984a..c68783f9f 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -292,16 +292,22 @@ function callbackResultOutcome( call: Node, analysis: Analysis, callback: Node, + shape: Shape = "promise", ): Outcome { const callee = unwrap(asNode(get(call, "callee")) ?? call); const name = memberName(callee); // `forEach()` discards what its callback returns, which is the one callback // consumer the rule knows for certain. An unknown one, such as // `setTimeout()`, may well keep it. - if (name === "forEach") return DROPPED; - if (name === "map" || name === "flatMap") { + if (name === "forEach" || name === "map" || name === "flatMap") { // The optional second argument is thisArg, not another callback. if ((get(call, "arguments") as Node[])[0] !== callback) return HANDLED; + } + if (name === "forEach") return DROPPED; + // Only flatMap flattens returned arrays; map and promise callbacks would + // need nested-array or Promise tracking, which remains unsupported. + if (shape === "promises" && name !== "flatMap") return HANDLED; + if (name === "map" || name === "flatMap") { return fateOf(call, analysis, "promises"); } if (name != null && PROMISE_CHAIN_METHODS.has(name)) { @@ -344,6 +350,15 @@ function returnedContainerOutcome( shape: Shape, ): Outcome { if (fn === analysis.listener) return DROPPED; + if (fn != null && shape === "promises" && get(fn, "async") !== true) { + const parent = parentOf(fn); + if ( + parent?.type === "CallExpression" && + (get(parent, "arguments") as Node[]).includes(fn) + ) { + return callbackResultOutcome(parent, analysis, fn, shape); + } + } return fn != null && shape === "promises" ? { fate: "returned", owner: fn, shape } : HANDLED; @@ -778,6 +793,9 @@ function checkListener( const carriesCompletion = (helpers: readonly FunctionLikeNode[]): boolean => helpers.some((fn) => carrying.has(fn)) && helpers.every((fn) => !arrayInvolved.has(fn) || get(fn, "async") === true); + const carriesArray = (helpers: readonly FunctionLikeNode[]): boolean => + helpers.some((fn) => carryingArrays.has(fn)) && + helpers.every((fn) => shapes.get(fn) === "promises"); const deliveryShape = ( call: CallExpression, scope: UsedScope, @@ -788,10 +806,7 @@ function checkListener( const helpers = helpersAt(callee, scope); if (helpers.length === 0) return null; if (carriesCompletion(helpers)) return "promise"; - if (helpers.some((fn) => arrayInvolved.has(fn))) { - if (!helpers.every((fn) => shapes.get(fn) === "promises")) return null; - return helpers.some((fn) => carryingArrays.has(fn)) ? "promises" : null; - } + if (carriesArray(helpers)) return "promises"; return null; }; const noteCarrying = ({ @@ -830,8 +845,13 @@ function checkListener( for (const arg of call.arguments as Node[]) { if (arg.type !== "Identifier") continue; const helpers = helpersAt(arg, scope); - if (!carriesCompletion(helpers)) continue; - const outcome = callbackResultOutcome(call, analysis, arg); + const shape = carriesCompletion(helpers) + ? "promise" + : carriesArray(helpers) + ? "promises" + : null; + if (shape == null) continue; + const outcome = callbackResultOutcome(call, analysis, arg, shape); if (outcome.shape === "promises" && noteCarrying(outcome)) { changed = true; } @@ -884,8 +904,15 @@ function checkListener( for (const arg of call.arguments as Node[]) { if (arg.type !== "Identifier") continue; const held = helpersAt(arg, scope); - if (!carriesCompletion(held)) continue; - if (callbackResultOutcome(call, analysis, arg).fate === "dropped") { + const shape = carriesCompletion(held) + ? "promise" + : carriesArray(held) + ? "promises" + : null; + if (shape == null) continue; + if ( + callbackResultOutcome(call, analysis, arg, shape).fate === "dropped" + ) { flag(arg); } } diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index c4762163e..04ba00e6c 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -13,6 +13,14 @@ const arrayHelperMap = `inboxes.map((inbox) => ${arrayHelperDelivery})`; for (const [producer, definition] of [ ["map", `const deliverAll = () => ${arrayHelperMap};`], + [ + "inline flatMap array", + `const deliverAll = () => inboxes.flatMap(() => [${arrayHelperDelivery}]);`, + ], + [ + "named flatMap array", + `const deliverOne = () => [${arrayHelperDelivery}]; const deliverAll = () => inboxes.flatMap(deliverOne);`, + ], [ "async map callback", `const deliverAll = () => inboxes.map(async () => { await ${arrayHelperDelivery}; });`, @@ -187,6 +195,56 @@ federation.setOutboxListeners("/users/{identifier}/outbox") } for (const [scenario, definition, consumer, dropped] of [ + ["named array forEach", "", "inboxes.forEach(deliverAll);", true], + ["named array flatMap dropped", "", "inboxes.flatMap(deliverAll);", true], + [ + "named array flatMap aggregated", + "", + "await Promise.all(inboxes.flatMap(deliverAll));", + false, + ], + [ + "named array map nested", + "", + "await Promise.all(inboxes.map(deliverAll));", + false, + ], + [ + "named array forEach thisArg", + "", + "inboxes.forEach(() => {}, deliverAll);", + false, + ], + [ + "named array flatMap thisArg", + "", + "await inboxes.flatMap(() => [], deliverAll);", + false, + ], + [ + "inline array flatMap thisArg", + "", + "await inboxes.flatMap(() => [], () => [ctx.sendActivity(sender, inbox, activity)]);", + false, + ], + [ + "inline array forEach", + "", + "inboxes.forEach(() => [ctx.sendActivity(sender, inbox, activity)]);", + true, + ], + [ + "inline array map nested", + "", + "await Promise.all(inboxes.map(() => [ctx.sendActivity(sender, inbox, activity)]));", + false, + ], + [ + "async array flatMap", + "", + "await inboxes.flatMap(async () => [ctx.sendActivity(sender, inbox, activity)]);", + false, + ], [ "async array and returned completion bindings", `let deliver = async () => []; if (condition) { deliver = () => ${arrayHelperDelivery}; }`, From fe25d5307fe388f58c8d34396dfeb890da3bc76e Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 17:59:16 +0900 Subject: [PATCH 05/41] Preserve delivery evidence across returned arrays Classify synchronous array IIFE calls using the same return summaries as named helpers. Mixed and async array returns remain unclassified. Propagate named callback outcomes even after aggregation turns an array into a completion promise, so dropped enclosing calls are reported. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4596886542 https://github.com/fedify-dev/fedify/pull/1446#discussion_r4596886551 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 9 ++-- ...tbox-listener-delivery-not-awaited.test.ts | 47 +++++++++++++++++++ 2 files changed, 52 insertions(+), 4 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index c68783f9f..c00fd9687 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -624,7 +624,7 @@ function helperReturnShapes( const helpersOf = (node: Node, scope: UsedScope): FunctionLikeNode[] => { const callee = unwrap(asNode(get(node, "callee")) ?? node); - return helpersAt(callee, scope); + return isFunctionLikeNode(callee) ? [callee] : helpersAt(callee, scope); }; // Keep array provenance even when a mixed or unsupported return has no // shape. Otherwise legacy promise propagation could revive that helper. @@ -802,8 +802,9 @@ function checkListener( ): Shape | null => { if (isDeliveryCall(call)) return "promise"; const callee = unwrap(call.callee as Node); - if (callee.type !== "Identifier") return null; - const helpers = helpersAt(callee, scope); + const helpers = isFunctionLikeNode(callee) + ? [callee] + : helpersAt(callee, scope); if (helpers.length === 0) return null; if (carriesCompletion(helpers)) return "promise"; if (carriesArray(helpers)) return "promises"; @@ -852,7 +853,7 @@ function checkListener( : null; if (shape == null) continue; const outcome = callbackResultOutcome(call, analysis, arg, shape); - if (outcome.shape === "promises" && noteCarrying(outcome)) { + if (noteCarrying(outcome)) { changed = true; } } diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 04ba00e6c..ac8a51da6 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -13,6 +13,10 @@ const arrayHelperMap = `inboxes.map((inbox) => ${arrayHelperDelivery})`; for (const [producer, definition] of [ ["map", `const deliverAll = () => ${arrayHelperMap};`], + [ + "array IIFE", + `const deliverAll = () => (() => [${arrayHelperDelivery}])();`, + ], [ "inline flatMap array", `const deliverAll = () => inboxes.flatMap(() => [${arrayHelperDelivery}]);`, @@ -195,6 +199,49 @@ federation.setOutboxListeners("/users/{identifier}/outbox") } for (const [scenario, definition, consumer, dropped] of [ + [ + "named flatMap aggregate completion", + `const deliverOne = () => [${arrayHelperDelivery}]; const deliver = async () => { await Promise.all(inboxes.flatMap(deliverOne)); };`, + "deliver();", + true, + ], + [ + "named flatMap aggregate awaited", + `const deliverOne = () => [${arrayHelperDelivery}]; const deliver = async () => { await Promise.all(inboxes.flatMap(deliverOne)); };`, + "await deliver();", + false, + ], + [ + "named flatMap aggregate returned", + `const deliverOne = () => [${arrayHelperDelivery}]; const deliver = () => Promise.all(inboxes.flatMap(deliverOne));`, + "deliver();", + true, + ], + [ + "array IIFE directly awaited", + "", + `await (() => [${arrayHelperDelivery}])();`, + true, + ], + [ + "array IIFE aggregated", + "", + `await Promise.all((() => [${arrayHelperDelivery}])());`, + false, + ], + ["array IIFE bare", "", `(() => [${arrayHelperDelivery}])();`, true], + [ + "async array IIFE", + "", + `await (async () => [${arrayHelperDelivery}])();`, + false, + ], + [ + "mixed array IIFE", + "", + `await (() => condition ? [${arrayHelperDelivery}] : ${arrayHelperDelivery})();`, + false, + ], ["named array forEach", "", "inboxes.forEach(deliverAll);", true], ["named array flatMap dropped", "", "inboxes.flatMap(deliverAll);", true], [ From 826dbe7c4a518f7658da0c47879f0e2f90a76383 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 18:04:07 +0900 Subject: [PATCH 06/41] Suppress helper inference across shadow bindings Reject merged outer helper candidates when an intervening lexical binding declares the same name. Identifier aliases and destructured, loop, parameter, and catch bindings must not inherit an unrelated helper's array return shape. Keep shared reachability unchanged. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4596968776 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 66 ++++++++++++++++++- ...tbox-listener-delivery-not-awaited.test.ts | 30 +++++++++ 2 files changed, 95 insertions(+), 1 deletion(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index c00fd9687..b5c069bdc 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -156,6 +156,67 @@ function enclosingFunction(node: Node): FunctionLikeNode | null { return null; } +/** Checks binding patterns without treating property keys as bindings. */ +function bindsName(pattern: Node | null, name: string): boolean { + if (pattern == null) return false; + switch (pattern.type) { + case "Identifier": + return pattern.name === name; + case "RestElement": + return bindsName(asNode(get(pattern, "argument")), name); + case "AssignmentPattern": + return bindsName(asNode(get(pattern, "left")), name); + case "ArrayPattern": + return (get(pattern, "elements") as (Node | null)[]).some((item) => + bindsName(item, name), + ); + case "ObjectPattern": + return (get(pattern, "properties") as Node[]).some((prop) => + bindsName( + asNode(get(prop, prop.type === "RestElement" ? "argument" : "value")), + name, + ), + ); + default: + return false; + } +} + +/** A nearer lexical declaration makes a merged outer candidate ambiguous. */ +function shadowsName(region: Node, name: string): boolean { + if (isFunctionLikeNode(region)) { + return ( + (get(region, "params") as Node[]).some((param) => + bindsName(param, name), + ) || bindsName(asNode(get(region, "id")), name) + ); + } + if (region.type === "CatchClause") { + return bindsName(asNode(get(region, "param")), name); + } + const declarations: Node[] = + region.type === "BlockStatement" + ? (get(region, "body") as Node[]) + : region.type === "SwitchStatement" + ? (get(region, "cases") as Node[]).flatMap( + (clause) => get(clause, "consequent") as Node[], + ) + : region.type === "ForStatement" + ? ([asNode(get(region, "init"))].filter(isNode) as Node[]) + : region.type === "ForInStatement" || region.type === "ForOfStatement" + ? ([asNode(get(region, "left"))].filter(isNode) as Node[]) + : []; + return declarations.some((declaration) => + declaration.type === "VariableDeclaration" + ? (get(declaration, "declarations") as Node[]).some((item) => + bindsName(asNode(get(item, "id")), name), + ) + : (declaration.type === "FunctionDeclaration" || + declaration.type === "ClassDeclaration") && + bindsName(asNode(get(declaration, "id")), name), + ); +} + /** * The shared reachability map merges block-local functions. Do not use a * candidate outside its lexical declaration region: another binding may be @@ -186,7 +247,10 @@ function helpersAt(node: Node, scope: UsedScope): FunctionLikeNode[] { : null; if (region == null) continue; let current: Node | null = node; - while (current != null && current !== region) current = parentOf(current); + while (current != null && current !== region) { + if (shadowsName(current, node.name)) return []; + current = parentOf(current); + } if (current == null) return []; } return helpers; diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index ac8a51da6..e5c338cec 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -467,6 +467,36 @@ federation.setOutboxListeners("/users/{identifier}/outbox") }), ); +for (const consumer of [ + "{ const deliverAll = finish; await deliverAll(); }", + "{ let deliverAll = finish; await deliverAll(); }", + "{ const { run: deliverAll } = { run: finish }; await deliverAll(); }", + "{ const [deliverAll] = [finish]; await deliverAll(); }", + "for (const deliverAll of [finish]) { await deliverAll(); }", + "for (let deliverAll = finish; condition;) { await deliverAll(); }", + "try { throw finish; } catch (deliverAll) { await deliverAll(); }", + "switch (condition) { case true: { const deliverAll = finish; await deliverAll(); } }", + "{ const deliverAll = finish; inboxes.forEach(deliverAll); }", +]) { + test( + `${ruleName}: shadow binding does not use outer array helper: ${consumer}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const deliverAll = () => [ctx.sendActivity(sender, inbox, activity)]; + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + await Promise.all(deliverAll()); + ${consumer} + }); +`, + rule, + ruleName, + }), + ); +} + test(`${ruleName}: array helper diagnostics identify only discarded call sites`, () => { const code = `import { Activity } from "@fedify/vocab"; federation.setOutboxListeners("/users/{identifier}/outbox") From 5a63705fcf5aedc0ab0d67b1bdbbcec95b537290 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 18:23:49 +0900 Subject: [PATCH 07/41] Report dropped async IIFEs only once Use the invocation node for callback-completion diagnostics on IIFEs, matching the call-site pass so node-based deduplication works. Add exact-count regressions for arrow, function, and wrapped callees. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4597472692 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 9 +++++- ...tbox-listener-delivery-not-awaited.test.ts | 30 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index b5c069bdc..358638b0d 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -958,7 +958,14 @@ function checkListener( kind === "awaited" && returnedOutcome(fn, analysis).fate === "dropped" ) { - flag(fn); + const parent = parentOf(fn); + // The call-site pass also follows IIFE completion. Use the same node + // here so an unawaited invocation produces only one diagnostic. + flag( + parent?.type === "CallExpression" && get(parent, "callee") === fn + ? parent + : fn, + ); } } diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index e5c338cec..3c5e07276 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -497,6 +497,36 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const invocation of [ + "(async () => { await ctx.sendActivity(sender, inbox, activity); })()", + "(async function () { await ctx.sendActivity(sender, inbox, activity); })()", + "((async () => { await ctx.sendActivity(sender, inbox, activity); }) as () => Promise)()", +]) { + test(`${ruleName}: dropped async IIFE reports once: ${invocation}`, () => { + const code = `import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + ${invocation}; + });`; + const messages = new Linter().verify( + `${FEDERATION_SETUP}\n\n${code}`, + [ + { + files: ["**/*.ts"], + languageOptions: { parser: tsParser }, + plugins: { fedify: { rules: { [ruleName]: rule.eslint } } }, + rules: { [`fedify/${ruleName}`]: "error" }, + }, + ], + "listener.ts", + ); + deepStrictEqual( + messages.map(({ ruleId, line }) => [ruleId, line]), + [[`fedify/${ruleName}`, 4 + FEDERATION_SETUP.split("\n").length + 1]], + ); + }); +} + test(`${ruleName}: array helper diagnostics identify only discarded call sites`, () => { const code = `import { Activity } from "@fedify/vocab"; federation.setOutboxListeners("/users/{identifier}/outbox") From 269f34eb5970be58a7242be5fca55cdac07571af Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 18:26:58 +0900 Subject: [PATCH 08/41] Invalidate helper inference on unknown writes Identifier-valued assignments are not included in the shared helper candidate map. Conservatively suppress inference for helper names with unclassified writes so a replacement completion promise is not treated as the original delivery array. Include destructuring and closure writes without extending alias data flow or changing shared reachability. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4597562390 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 65 +++++++++++++++++-- ...tbox-listener-delivery-not-awaited.test.ts | 27 ++++++++ 2 files changed, 85 insertions(+), 7 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 358638b0d..d13cbc16c 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -224,8 +224,12 @@ function shadowsName(region: Node, name: string): boolean { * Ambiguous merged candidates remain unclassified rather than filtered down * to a possibly incomplete set. */ -function helpersAt(node: Node, scope: UsedScope): FunctionLikeNode[] { - if (node.type !== "Identifier") return []; +function helpersAt( + node: Node, + scope: UsedScope, + unknownWrites: ReadonlySet, +): FunctionLikeNode[] { + if (node.type !== "Identifier" || unknownWrites.has(node.name)) return []; const helpers = scope.functionsByName.get(node.name) ?? []; for (const fn of helpers) { let declaration: Node = fn; @@ -662,6 +666,7 @@ function exitsFunction(node: Node): boolean { function helperReturnShapes( scopes: readonly UsedScope[], isDeliveryCall: (call: CallExpression) => boolean, + unknownWrites: ReadonlySet, ): { shapes: ReadonlyMap; arrayInvolved: ReadonlySet; @@ -688,7 +693,9 @@ function helperReturnShapes( const helpersOf = (node: Node, scope: UsedScope): FunctionLikeNode[] => { const callee = unwrap(asNode(get(node, "callee")) ?? node); - return isFunctionLikeNode(callee) ? [callee] : helpersAt(callee, scope); + return isFunctionLikeNode(callee) + ? [callee] + : helpersAt(callee, scope, unknownWrites); }; // Keep array provenance even when a mixed or unsupported return has no // shape. Otherwise legacy promise propagation could revive that helper. @@ -819,6 +826,46 @@ function checkListener( const scopes: UsedScope[] = []; walkUsedScopes(listener.body as Node, (scope) => scopes.push(scope)); + // Shared reachability collects function-valued assignments, but not aliases + // or unknown replacement values. Without ordered binding data flow, any + // such write makes a same-named helper unsafe to infer, including in a + // closure. Name-wide invalidation is deliberately conservative. + const helperNames = new Set( + scopes.flatMap((scope) => [...scope.functionsByName.keys()]), + ); + const unknownWrites = new Set(); + for (const scope of scopes) { + for (const statement of scope.statements) { + visitAll( + statement, + (node) => { + if ( + node.type !== "AssignmentExpression" && + node.type !== "UpdateExpression" + ) + return; + const target = asNode( + get( + node, + node.type === "AssignmentExpression" ? "left" : "argument", + ), + ); + const value = asNode(get(node, "right")); + if ( + get(node, "operator") === "=" && + value != null && + isFunctionLikeNode(unwrap(value)) + ) + return; + for (const name of helperNames) { + if (bindsName(target, name)) unknownWrites.add(name); + } + }, + false, + ); + } + } + const targets = findDeliveryTargets(listener, scopes); if (targets.contextName == null && targets.aliases.size === 0) return; @@ -838,7 +885,11 @@ function checkListener( const mentioned = new Set(); collectReferencedNames(listener.body, mentioned, true); const analysis: Analysis = { listener, mentioned }; - const { shapes, arrayInvolved } = helperReturnShapes(scopes, isDeliveryCall); + const { shapes, arrayInvolved } = helperReturnShapes( + scopes, + isDeliveryCall, + unknownWrites, + ); const callsByScope = scopes.map((scope) => { const calls: CallExpression[] = []; @@ -868,7 +919,7 @@ function checkListener( const callee = unwrap(call.callee as Node); const helpers = isFunctionLikeNode(callee) ? [callee] - : helpersAt(callee, scope); + : helpersAt(callee, scope, unknownWrites); if (helpers.length === 0) return null; if (carriesCompletion(helpers)) return "promise"; if (carriesArray(helpers)) return "promises"; @@ -909,7 +960,7 @@ function checkListener( } for (const arg of call.arguments as Node[]) { if (arg.type !== "Identifier") continue; - const helpers = helpersAt(arg, scope); + const helpers = helpersAt(arg, scope, unknownWrites); const shape = carriesCompletion(helpers) ? "promise" : carriesArray(helpers) @@ -975,7 +1026,7 @@ function checkListener( for (const call of callsByScope[index]) { for (const arg of call.arguments as Node[]) { if (arg.type !== "Identifier") continue; - const held = helpersAt(arg, scope); + const held = helpersAt(arg, scope, unknownWrites); const shape = carriesCompletion(held) ? "promise" : carriesArray(held) diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 3c5e07276..b43991853 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -497,6 +497,33 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const replacement of [ + "deliverAll = finish;", + "deliverAll = chooseHelper();", + "({ run: deliverAll } = { run: finish });", + "[deliverAll] = [finish];", + "const replace = () => { deliverAll = finish; }; replace();", +]) { + test( + `${ruleName}: unclassified reassignment invalidates array inference: ${replacement}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + let deliverAll = () => [ctx.sendActivity(sender, inbox, activity)]; + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + await Promise.all(deliverAll()); + ${replacement} + await deliverAll(); + }); +`, + rule, + ruleName, + }), + ); +} + for (const invocation of [ "(async () => { await ctx.sendActivity(sender, inbox, activity); })()", "(async function () { await ctx.sendActivity(sender, inbox, activity); })()", From fa38c13558dc7e202fdb5165909c92282b1386c5 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 21:01:36 +0900 Subject: [PATCH 09/41] Invalidate array helpers on loop target writes Reachability emits for-in and for-of iterable expressions rather than the loop statements themselves. Use their parent loops to invalidate existing helper bindings assigned by each iteration, including patterns. Loop variable declarations do not assign the outer helper binding. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4597732174 Assisted-by: OpenCode:gpt-6.1-sol --- .../rules/outbox-listener-delivery-not-awaited.ts | 15 +++++++++++++++ .../outbox-listener-delivery-not-awaited.test.ts | 5 +++++ 2 files changed, 20 insertions(+) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index d13cbc16c..fcb6de6ed 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -836,6 +836,21 @@ function checkListener( const unknownWrites = new Set(); for (const scope of scopes) { for (const statement of scope.statements) { + // Reachability emits the iterable expression, not the loop statement. + // Its left-hand target writes an existing binding on each iteration. + const parent = parentOf(statement); + if ( + (parent?.type === "ForOfStatement" || + parent?.type === "ForInStatement") && + get(parent, "right") === statement + ) { + const target = asNode(get(parent, "left")); + if (target?.type !== "VariableDeclaration") { + for (const name of helperNames) { + if (bindsName(target, name)) unknownWrites.add(name); + } + } + } visitAll( statement, (node) => { diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index b43991853..c72a28e49 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -503,6 +503,11 @@ for (const replacement of [ "({ run: deliverAll } = { run: finish });", "[deliverAll] = [finish];", "const replace = () => { deliverAll = finish; }; replace();", + "for (deliverAll of [finish]) {}", + "for ({ run: deliverAll } of [{ run: finish }]) {}", + "for ([deliverAll] of [[finish]]) {}", + "for (deliverAll in {}) {} deliverAll = finish;", + "for (deliverAll in {}) {}", ]) { test( `${ruleName}: unclassified reassignment invalidates array inference: ${replacement}`, From 19dd69f08969051472a2854108a9cc32ca5a20c2 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 21:04:32 +0900 Subject: [PATCH 10/41] Require directly held helper bindings Do not certify a named callable using an unrelated function buried in an aggregate initializer. Keep destructured and aggregate candidates unclassified rather than selecting a function from another property. Establish the enclosing function body for var and assignment-derived candidates so nearer lexical bindings still prevent wrong inference. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4597753996 https://github.com/fedify-dev/fedify/pull/1446#pullrequestreview-5936047270 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 17 ++++++- ...tbox-listener-delivery-not-awaited.test.ts | 51 +++++++++++++++++++ 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index fcb6de6ed..c83e144f8 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -240,6 +240,19 @@ function helpersAt( declaration = parentOf(declaration)!; } const declarator = parentOf(declaration); + // A function buried in an aggregate initializer may belong to a different + // property or tuple element than the identifier being invoked. Only a + // directly held callable certifies a named helper here. + if (fn.type !== "FunctionDeclaration") { + const target = + declarator?.type === "VariableDeclarator" + ? asNode(get(declarator, "id")) + : declarator?.type === "AssignmentExpression" && + get(declarator, "operator") === "=" + ? asNode(get(declarator, "left")) + : null; + if (target?.type !== "Identifier" || target.name !== node.name) return []; + } const variable = declarator?.type === "VariableDeclarator" ? parentOf(declarator) : null; const region = @@ -248,8 +261,8 @@ function helpersAt( : variable?.type === "VariableDeclaration" && get(variable, "kind") !== "var" ? parentOf(variable) - : null; - if (region == null) continue; + : asNode(get(enclosingFunction(fn), "body")); + if (region == null) return []; let current: Node | null = node; while (current != null && current !== region) { if (shadowsName(current, node.name)) return []; diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index c72a28e49..38848bcd6 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -497,6 +497,57 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const declaration of [ + "const { run } = { run: finish, other: () => [ctx.sendActivity(sender, inbox, activity)] };", + "const [run] = [finish, () => [ctx.sendActivity(sender, inbox, activity)]];", + "const { run = finish } = { other: () => [ctx.sendActivity(sender, inbox, activity)] };", +]) { + test( + `${ruleName}: aggregate binding does not select an unrelated helper: ${declaration}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + ${declaration} + await run(); + }); +`, + rule, + ruleName, + }), + ); +} + +for (const declaration of [ + "var deliverAll = () => [ctx.sendActivity(sender, inbox, activity)];", + "let deliverAll; deliverAll = () => [ctx.sendActivity(sender, inbox, activity)];", +]) { + for (const shadowed of [true, false]) { + test( + `${ruleName}: var or assignment helper respects shadowing (${shadowed}): ${declaration}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + ${declaration} + await Promise.all(deliverAll()); + { + ${shadowed ? "const deliverAll = external;" : ""} + await deliverAll(); + } + }); +`, + rule, + ruleName, + ...(shadowed ? {} : { expectedError: "Delivery is not awaited" }), + }), + ); + } +} + for (const replacement of [ "deliverAll = finish;", "deliverAll = chooseHelper();", From 51f8024f9c28687e0335635ae868d6e61a178750 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 17 Nov 2026 23:08:47 +0900 Subject: [PATCH 11/41] Respect helper binding regions and var writes Find the nearest lexical declaration region for assignment-initialized helpers so block-local candidates cannot classify unrelated outer calls. Treat unknown var initializers and function-scoped loop targets as writes, including redeclarations and destructured loop targets, rather than retaining an earlier array shape for a replacement callable. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4599433504 https://github.com/fedify-dev/fedify/pull/1446#discussion_r4599433523 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 47 +++++++++++++++-- ...tbox-listener-delivery-not-awaited.test.ts | 51 +++++++++++++++++++ 2 files changed, 94 insertions(+), 4 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index c83e144f8..b6e54a25e 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -183,7 +183,7 @@ function bindsName(pattern: Node | null, name: string): boolean { } /** A nearer lexical declaration makes a merged outer candidate ambiguous. */ -function shadowsName(region: Node, name: string): boolean { +function shadowsName(region: Node, name: string, lexicalOnly = false): boolean { if (isFunctionLikeNode(region)) { return ( (get(region, "params") as Node[]).some((param) => @@ -208,7 +208,8 @@ function shadowsName(region: Node, name: string): boolean { : []; return declarations.some((declaration) => declaration.type === "VariableDeclaration" - ? (get(declaration, "declarations") as Node[]).some((item) => + ? (!lexicalOnly || get(declaration, "kind") !== "var") && + (get(declaration, "declarations") as Node[]).some((item) => bindsName(asNode(get(item, "id")), name), ) : (declaration.type === "FunctionDeclaration" || @@ -217,6 +218,19 @@ function shadowsName(region: Node, name: string): boolean { ); } +/** Finds the nearest lexical binding, with function scope as a fallback. */ +function assignmentRegion(assignment: Node, name: string): Node | null { + for ( + let current = parentOf(assignment); + current != null; + current = parentOf(current) + ) { + if (isFunctionLikeNode(current)) return asNode(get(current, "body")); + if (shadowsName(current, name, true)) return current; + } + return null; +} + /** * The shared reachability map merges block-local functions. Do not use a * candidate outside its lexical declaration region: another binding may be @@ -261,7 +275,9 @@ function helpersAt( : variable?.type === "VariableDeclaration" && get(variable, "kind") !== "var" ? parentOf(variable) - : asNode(get(enclosingFunction(fn), "body")); + : declarator?.type === "AssignmentExpression" + ? assignmentRegion(declarator, node.name) + : asNode(get(enclosingFunction(fn), "body")); if (region == null) return []; let current: Node | null = node; while (current != null && current !== region) { @@ -858,7 +874,17 @@ function checkListener( get(parent, "right") === statement ) { const target = asNode(get(parent, "left")); - if (target?.type !== "VariableDeclaration") { + if ( + target?.type === "VariableDeclaration" && + get(target, "kind") === "var" + ) { + for (const item of get(target, "declarations") as Node[]) { + for (const name of helperNames) { + if (bindsName(asNode(get(item, "id")), name)) + unknownWrites.add(name); + } + } + } else if (target?.type !== "VariableDeclaration") { for (const name of helperNames) { if (bindsName(target, name)) unknownWrites.add(name); } @@ -867,6 +893,19 @@ function checkListener( visitAll( statement, (node) => { + if ( + node.type === "VariableDeclarator" && + get(parentOf(node), "kind") === "var" + ) { + const value = asNode(get(node, "init")); + if (value != null && !isFunctionLikeNode(unwrap(value))) { + for (const name of helperNames) { + if (bindsName(asNode(get(node, "id")), name)) + unknownWrites.add(name); + } + } + return; + } if ( node.type !== "AssignmentExpression" && node.type !== "UpdateExpression" diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 38848bcd6..604dcf8ad 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -422,6 +422,57 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const replacement of [ + "var run = finish;", + "{ var run = finish; }", + "for (var run of [finish]) {}", + "for (var { run } of [{ run: finish }]) {}", + "for (var run in {}) {}", +]) { + test( + `${ruleName}: initialized var replacement invalidates array inference: ${replacement}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + var run = () => [ctx.sendActivity(sender, inbox, activity)]; + await Promise.all(run()); + ${replacement} + await run(); + }); +`, + rule, + ruleName, + }), + ); +} + +for (const local of [ + "{ let run; run = () => [ctx.sendActivity(sender, inbox, activity)]; await Promise.all(run()); }", + "{ let run; { run = () => [ctx.sendActivity(sender, inbox, activity)]; } await Promise.all(run()); }", + "for (let run of [null]) { run = () => [ctx.sendActivity(sender, inbox, activity)]; await Promise.all(run()); }", +]) { + test( + `${ruleName}: assignment helper does not escape its binding region: ${local}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + const run = finish; + ${local} + await run(); + }); +`, + rule, + ruleName, + }), + ); +} + for (const declaration of [ "const deliverAll = () => [ctx.sendActivity(sender, inbox, activity)];", "function deliverAll() { return [ctx.sendActivity(sender, inbox, activity)]; }", From c626972737b80d02532478195297916e139a827c Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Wed, 18 Nov 2026 03:02:03 +0900 Subject: [PATCH 12/41] Preserve block-initialized var helper inference A var declaration in the candidate's own function scope initializes the same binding even when it appears inside a block or loop head. Ignore those declarations during shadow checks while retaining lexical and cross-function shadow checks, restoring dropped-delivery diagnostics. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4600901567 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 12 ++++- ...tbox-listener-delivery-not-awaited.test.ts | 49 +++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index b6e54a25e..5241bab2b 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -279,9 +279,19 @@ function helpersAt( ? assignmentRegion(declarator, node.name) : asNode(get(enclosingFunction(fn), "body")); if (region == null) return []; + const functionScope = enclosingFunction(fn); let current: Node | null = node; while (current != null && current !== region) { - if (shadowsName(current, node.name)) return []; + // A var declaration in this function initializes the same binding, + // even inside a block or loop head. In another function it can shadow. + if ( + shadowsName( + current, + node.name, + enclosingFunction(current) === functionScope, + ) + ) + return []; current = parentOf(current); } if (current == null) return []; diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 604dcf8ad..8d7c39c8b 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -422,6 +422,55 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const definition of [ + "{ var deliver = () => ctx.sendActivity(sender, inbox, activity); CONSUMER }", + "for (var deliver = () => ctx.sendActivity(sender, inbox, activity); condition;) { CONSUMER }", + "{ var deliver = async () => { await ctx.sendActivity(sender, inbox, activity); }; CONSUMER }", + "{ var deliver = () => [ctx.sendActivity(sender, inbox, activity)]; CONSUMER }", +]) { + for (const shadowed of [false, true]) { + const consumer = shadowed + ? "{ const deliver = external; await deliver(); }" + : "deliver();"; + test( + `${ruleName}: function-scoped var helper retains inference (${shadowed}): ${definition}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + ${definition.replace("CONSUMER", consumer)} + }); +`, + rule, + ruleName, + ...(shadowed ? {} : { expectedError: "Delivery is not awaited" }), + }), + ); + } +} + +test( + `${ruleName}: nested function var still shadows an outer helper`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + var deliver = () => [ctx.sendActivity(sender, inbox, activity)]; + await Promise.all(deliver()); + async function inner() { + var deliver = external; + await deliver(); + } + await inner(); + }); +`, + rule, + ruleName, + }), +); + for (const replacement of [ "var run = finish;", "{ var run = finish; }", From 80326a891ab0793b972d479a6b83008f66a95007 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Wed, 18 Nov 2026 08:48:59 +0900 Subject: [PATCH 13/41] Invalidate helper shapes across nested writes Function-literal assignments in used nested functions do not update the enclosing caller's helper map. Invalidate those enclosing bindings while retaining inference for local assignments. Scan parameter defaults of used functions too, since their writes can replace the same helpers without appearing in the reachable body statements. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4603848638 https://github.com/fedify-dev/fedify/pull/1446#discussion_r4603848648 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 42 ++++++++++++++- ...tbox-listener-delivery-not-awaited.test.ts | 51 +++++++++++++++++++ 2 files changed, 91 insertions(+), 2 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 5241bab2b..49de6aae2 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -874,7 +874,35 @@ function checkListener( ); const unknownWrites = new Set(); for (const scope of scopes) { - for (const statement of scope.statements) { + const localFunctionNames = new Set(); + if (scope.fn != null) { + for (const name of helperNames) { + if (shadowsName(scope.fn, name)) localFunctionNames.add(name); + } + // var bindings belong to the whole function, including nested blocks. + for (const statement of scope.statements) { + visitAll( + statement, + (node) => { + if ( + node.type !== "VariableDeclarator" || + get(parentOf(node), "kind") !== "var" + ) + return; + for (const name of helperNames) { + if (bindsName(asNode(get(node, "id")), name)) + localFunctionNames.add(name); + } + }, + false, + ); + } + } + const expressions = [ + ...scope.statements, + ...(scope.fn == null ? [] : (get(scope.fn, "params") as Node[])), + ]; + for (const statement of expressions) { // Reachability emits the iterable expression, not the loop statement. // Its left-hand target writes an existing binding on each iteration. const parent = parentOf(statement); @@ -931,7 +959,17 @@ function checkListener( if ( get(node, "operator") === "=" && value != null && - isFunctionLikeNode(unwrap(value)) + isFunctionLikeNode(unwrap(value)) && + // Nested scope maps do not update the enclosing caller's map. + // Exempt a literal write only when its target is local. + (scope.fn == null || + (target?.type === "Identifier" && + (localFunctionNames.has(target.name) || + shadowsName( + assignmentRegion(node, target.name) ?? node, + target.name, + true, + )))) ) return; for (const name of helperNames) { diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 8d7c39c8b..f8702188a 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -422,6 +422,57 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const replace of [ + "const replace = () => { run = () => ctx.sendActivity(sender, inbox, activity); }; replace();", + "const replace = () => { run = async () => { await ctx.sendActivity(sender, inbox, activity); }; }; replace();", + "const replace = () => { const inner = () => { run = () => ctx.sendActivity(sender, inbox, activity); }; inner(); }; replace();", + "const replace = (value = (run = finish)) => value; replace();", + "const replace = ({ value = (run = finish) } = {}) => value; replace();", + "const replace = (value = (run = () => ctx.sendActivity(sender, inbox, activity))) => value; replace();", +]) { + test( + `${ruleName}: used helper writes invalidate enclosing array inference: ${replace}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + let run = () => [ctx.sendActivity(sender, inbox, activity)]; + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + await Promise.all(run()); + ${replace} + await run(); + }); +`, + rule, + ruleName, + }), + ); +} + +for (const declaration of ["let deliver;", "var deliver;"]) { + test( + `${ruleName}: local literal assignments in used helpers retain inference: ${declaration}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const outer = () => { + ${declaration} + deliver = () => ctx.sendActivity(sender, inbox, activity); + deliver(); + }; + outer(); + }); +`, + rule, + ruleName, + expectedError: "Delivery is not awaited", + }), + ); +} + for (const definition of [ "{ var deliver = () => ctx.sendActivity(sender, inbox, activity); CONSUMER }", "for (var deliver = () => ctx.sendActivity(sender, inbox, activity); condition;) { CONSUMER }", From 7e1d6c0d989e3429ed3a5ba6774aadd7872e4e85 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Wed, 18 Nov 2026 23:16:01 +0900 Subject: [PATCH 14/41] Cover wrapped and default-invoked helper writes Unwrap transparent TypeScript targets when checking writes, including inside destructuring. Do not exempt wrapped literal assignments that the shared candidate map cannot classify. Follow possible local callees from used parameter defaults for write invalidation, including chains, without extending delivery diagnostics or changing shared reachability. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4607468854 https://github.com/fedify-dev/fedify/pull/1446#discussion_r4607468860 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 50 +++++++++++++++---- ...tbox-listener-delivery-not-awaited.test.ts | 32 ++++++++++++ 2 files changed, 73 insertions(+), 9 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 49de6aae2..cfa5b0503 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -159,6 +159,7 @@ function enclosingFunction(node: Node): FunctionLikeNode | null { /** Checks binding patterns without treating property keys as bindings. */ function bindsName(pattern: Node | null, name: string): boolean { if (pattern == null) return false; + pattern = unwrap(pattern); switch (pattern.type) { case "Identifier": return pattern.name === name; @@ -865,15 +866,46 @@ function checkListener( const scopes: UsedScope[] = []; walkUsedScopes(listener.body as Node, (scope) => scopes.push(scope)); + // Parameter defaults are not part of shared body reachability. Follow their + // possible local callees only for invalidation, not delivery diagnostics. + const invalidationScopes = [...scopes]; + const invalidationFunctions = new Set(scopes.map((scope) => scope.fn)); + for (const [index, scope] of invalidationScopes.entries()) { + const names = new Set(); + collectReferencedNames(get(scope.fn, "params"), names); + if (index >= scopes.length) { + for (const statement of scope.statements) + collectReferencedNames(statement, names); + } + for (const name of names) { + for (const fn of scope.functionsByName.get(name) ?? []) { + if (invalidationFunctions.has(fn)) continue; + walkUsedScopes(fn.body as Node, (nested) => { + const nestedFn = nested.fn ?? fn; + if (invalidationFunctions.has(nestedFn)) return; + invalidationFunctions.add(nestedFn); + invalidationScopes.push({ + ...nested, + fn: nestedFn, + functionsByName: new Map([ + ...scope.functionsByName, + ...nested.functionsByName, + ]), + }); + }); + } + } + } + // Shared reachability collects function-valued assignments, but not aliases // or unknown replacement values. Without ordered binding data flow, any // such write makes a same-named helper unsafe to infer, including in a // closure. Name-wide invalidation is deliberately conservative. const helperNames = new Set( - scopes.flatMap((scope) => [...scope.functionsByName.keys()]), + invalidationScopes.flatMap((scope) => [...scope.functionsByName.keys()]), ); const unknownWrites = new Set(); - for (const scope of scopes) { + for (const scope of invalidationScopes) { const localFunctionNames = new Set(); if (scope.fn != null) { for (const name of helperNames) { @@ -962,14 +994,14 @@ function checkListener( isFunctionLikeNode(unwrap(value)) && // Nested scope maps do not update the enclosing caller's map. // Exempt a literal write only when its target is local. + target?.type === "Identifier" && (scope.fn == null || - (target?.type === "Identifier" && - (localFunctionNames.has(target.name) || - shadowsName( - assignmentRegion(node, target.name) ?? node, - target.name, - true, - )))) + localFunctionNames.has(target.name) || + shadowsName( + assignmentRegion(node, target.name) ?? node, + target.name, + true, + )) ) return; for (const name of helperNames) { diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index f8702188a..2cab4244e 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -422,6 +422,38 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const replace of [ + "run! = finish;", + "(run as Runner) = finish;", + "([run!] = [finish]);", + "({ run: run! } = { run: finish });", + "run! = () => ctx.sendActivity(sender, inbox, activity);", + "const replace = () => { run = finish; }; const invoke = (value = replace()) => value; invoke();", + "const replace = () => { run = () => ctx.sendActivity(sender, inbox, activity); }; const invoke = (value = replace()) => value; invoke();", + "const replace = () => { run = finish; }; const middle = () => replace(); const invoke = (value = middle()) => value; invoke();", + "const replace = () => { run = finish; }; const invoke = ({ value = replace() } = {}) => value; invoke();", + "const replace = () => { run = finish; }; const middle = (value = replace()) => value; const invoke = (value = middle()) => value; invoke();", +]) { + test( + `${ruleName}: wrapped writes and default-invoked helpers invalidate arrays: ${replace}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + let run = () => [ctx.sendActivity(sender, inbox, activity)]; + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + await Promise.all(run()); + ${replace} + await run(); + }); +`, + rule, + ruleName, + }), + ); +} + for (const replace of [ "const replace = () => { run = () => ctx.sendActivity(sender, inbox, activity); }; replace();", "const replace = () => { run = async () => { await ctx.sendActivity(sender, inbox, activity); }; }; replace();", From 26674a3993c4d1a23c67a552430ba40533f15901 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Wed, 18 Nov 2026 23:24:27 +0900 Subject: [PATCH 15/41] Test asserted patterns with the preserving parser Deno's lint AST omits non-null asserted targets inside destructuring patterns. Test those cases explicitly through ESLint, preserving full coverage there while retaining shared runtime coverage for direct asserted assignments and parameter-default helper invalidation. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4607468854 Changelog: none Assisted-by: OpenCode:gpt-6.1-sol --- ...tbox-listener-delivery-not-awaited.test.ts | 34 +++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 2cab4244e..a22aafc98 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -422,11 +422,41 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const replacement of [ + "([run!] = [finish]);", + "({ run: run! } = { run: finish });", +]) { + // Deno's AST omits these asserted destructuring targets. Exercise them + // explicitly through ESLint, whose parser preserves the target nodes. + test(`${ruleName}: ESLint wrapped destructuring write: ${replacement}`, () => { + const code = ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + let run = () => [ctx.sendActivity(sender, inbox, activity)]; + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + await Promise.all(run()); + ${replacement} + await run(); + });`; + const messages = new Linter().verify( + `${FEDERATION_SETUP}\n\n${code}`, + [ + { + files: ["**/*.ts"], + languageOptions: { parser: tsParser }, + plugins: { fedify: { rules: { [ruleName]: rule.eslint } } }, + rules: { [`fedify/${ruleName}`]: "error" }, + }, + ], + "listener.ts", + ); + deepStrictEqual(messages, []); + }); +} for (const replace of [ "run! = finish;", "(run as Runner) = finish;", - "([run!] = [finish]);", - "({ run: run! } = { run: finish });", "run! = () => ctx.sendActivity(sender, inbox, activity);", "const replace = () => { run = finish; }; const invoke = (value = replace()) => value; invoke();", "const replace = () => { run = () => ctx.sendActivity(sender, inbox, activity); }; const invoke = (value = replace()) => value; invoke();", From e6cdd155c4f10151ec2644d37ce903a453482157 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Thu, 19 Nov 2026 02:05:44 +0900 Subject: [PATCH 16/41] Cover executable binding writes in helper inference Include declaration defaults, computed keys, and catch bindings when finding mutators for invalidation. Require literal-write exemptions to match recorded candidates and do not treat a function declaration's name as a private local self-binding. Keep the extra discovery separate from delivery diagnostics and shared reachability. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4615729190 https://github.com/fedify-dev/fedify/pull/1446#discussion_r4615729218 https://github.com/fedify-dev/fedify/pull/1446#discussion_r4615729237 https://github.com/fedify-dev/fedify/pull/1446#discussion_r4615729245 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 45 ++++++++++++++--- ...tbox-listener-delivery-not-awaited.test.ts | 49 +++++++++++++++++++ 2 files changed, 88 insertions(+), 6 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index cfa5b0503..add358df5 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -189,7 +189,9 @@ function shadowsName(region: Node, name: string, lexicalOnly = false): boolean { return ( (get(region, "params") as Node[]).some((param) => bindsName(param, name), - ) || bindsName(asNode(get(region, "id")), name) + ) || + (region.type !== "FunctionDeclaration" && + bindsName(asNode(get(region, "id")), name)) ); } if (region.type === "CatchClause") { @@ -866,13 +868,44 @@ function checkListener( const scopes: UsedScope[] = []; walkUsedScopes(listener.body as Node, (scope) => scopes.push(scope)); + const invalidationExpressions = (scope: UsedScope): Node[] => { + const expressions = [ + ...scope.statements, + ...(scope.fn == null ? [] : (get(scope.fn, "params") as Node[])), + ]; + // Catch patterns can execute even when the catch body is empty. They are + // absent from the shared statement list, so scan them conservatively. + visitAll( + scope.fn?.body ?? listener.body, + (node) => { + if (node.type === "CatchClause") { + const param = asNode(get(node, "param")); + if (param != null) expressions.push(param); + } + }, + false, + ); + return expressions; + }; // Parameter defaults are not part of shared body reachability. Follow their // possible local callees only for invalidation, not delivery diagnostics. const invalidationScopes = [...scopes]; const invalidationFunctions = new Set(scopes.map((scope) => scope.fn)); for (const [index, scope] of invalidationScopes.entries()) { const names = new Set(); - collectReferencedNames(get(scope.fn, "params"), names); + const expressions = invalidationExpressions(scope); + for (const expression of expressions) { + // Declaration ids contain executable defaults and computed keys that + // collectReferencedNames intentionally omits from body reachability. + visitAll( + expression, + (node) => { + if (node.type === "CallExpression") + collectReferencedNames(node, names); + }, + false, + ); + } if (index >= scopes.length) { for (const statement of scope.statements) collectReferencedNames(statement, names); @@ -930,10 +963,7 @@ function checkListener( ); } } - const expressions = [ - ...scope.statements, - ...(scope.fn == null ? [] : (get(scope.fn, "params") as Node[])), - ]; + const expressions = invalidationExpressions(scope); for (const statement of expressions) { // Reachability emits the iterable expression, not the loop statement. // Its left-hand target writes an existing binding on each iteration. @@ -995,6 +1025,9 @@ function checkListener( // Nested scope maps do not update the enclosing caller's map. // Exempt a literal write only when its target is local. target?.type === "Identifier" && + scope.functionsByName + .get(target.name) + ?.includes(unwrap(value) as FunctionLikeNode) && (scope.fn == null || localFunctionNames.has(target.name) || shadowsName( diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index a22aafc98..7ece8d5c5 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -422,6 +422,55 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const mutation of [ + "const replace = () => { run = finish; }; const { value = replace() } = {};", + "const replace = () => { run = finish; }; const [value = replace()] = [];", + "const replace = () => { run = finish; return 'value'; }; const { [replace()]: value } = {};", + "const { value = (run = () => ctx.sendActivity(sender, inbox, activity)) } = {};", + "try { throw {}; } catch ({ value = (run = finish) }) {}", + "const replace = () => { run = finish; }; try { throw {}; } catch ({ value = replace() }) {}", + "const replace = () => { run = finish; return 'value'; }; try { throw {}; } catch ({ [replace()]: value }) {}", +]) { + test( + `${ruleName}: executable binding patterns invalidate helper shapes: ${mutation}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + let run = () => [ctx.sendActivity(sender, inbox, activity)]; + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + await Promise.all(run()); + ${mutation} + await run(); + }); +`, + rule, + ruleName, + }), + ); +} + +test( + `${ruleName}: declaration self-write invalidates enclosing helper shape`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + function run() { + run = () => ctx.sendActivity(sender, inbox, activity); + return [ctx.sendActivity(sender, inbox, activity)]; + } + await Promise.all(run()); + await run(); + }); +`, + rule, + ruleName, + }), +); + for (const replacement of [ "([run!] = [finish]);", "({ run: run! } = { run: finish });", From f1ca2cc678fea3d28d6ebea387e86b076cfe6c2d Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Thu, 19 Nov 2026 02:15:36 +0900 Subject: [PATCH 17/41] Retry interrupted compiler runtime downloads Deno can fail while streaming the base executable, not only while caching npm packages. Recognize that specific connection-body failure under base binary setup and reuse the bounded download retry policy. Keep deterministic failures and signaled compilers non-retryable. https://github.com/fedify-dev/fedify/actions/runs/44324101804/job/134871863305 Changelog: none Assisted-by: OpenCode:gpt-6.1-sol --- packages/cli/scripts/compile.test.ts | 77 +++++++++++++++++++++------- packages/cli/scripts/compile.ts | 11 ++-- 2 files changed, 66 insertions(+), 22 deletions(-) diff --git a/packages/cli/scripts/compile.test.ts b/packages/cli/scripts/compile.test.ts index f71a71c27..cd97b4fab 100644 --- a/packages/cli/scripts/compile.test.ts +++ b/packages/cli/scripts/compile.test.ts @@ -9,6 +9,39 @@ const failure = { "\u001b[0m\u001b[1m\u001b[31merror\u001b[0m: Failed caching npm package '@rollup/rollup-darwin-arm64@4.60.1'\r\n 0: error reading a body from connection", }; +const binaryFailure = { + ...failure, + stderr: + "error: Writing deno compile executable to temporary file '/tmp/fedify.tmp-123'\n\nCaused by:\n 0: Setting up base binary.\n 1: error reading a body from connection", +}; + +test("retries an interrupted base binary download with bounded attempts", async () => { + for (const succeeds of [true, false]) { + let calls = 0; + const delays: number[] = []; + const operation = compileWithDownloadRetries( + () => + Promise.resolve( + ++calls === 3 && succeeds + ? { success: true, code: 0, stderr: "" } + : binaryFailure, + ), + "aarch64-unknown-linux-gnu", + { + sleep: (delay) => { + delays.push(delay); + return Promise.resolve(); + }, + warn: () => {}, + }, + ); + if (succeeds) await operation; + else await rejects(operation, /exit code 1/); + strictEqual(calls, 3); + deepStrictEqual(delays, [2_000, 4_000]); + } +}); + test("retries an interrupted npm download and accepts a successful compile", async () => { let calls = 0; const delays: number[] = []; @@ -65,6 +98,12 @@ test("does not retry deterministic compile failures or unrelated connection erro "error: error reading a body from connection", "error: Failed caching npm package 'missing-package'\npackage not found\nunrelated: error reading a body from connection", failure.stderr + "\nerror: TS2307 Cannot find module './missing.ts'", + binaryFailure.stderr.replace( + "error reading a body from connection", + "Permission denied", + ), + binaryFailure.stderr + "\nerror: TS2307 Cannot find module './missing.ts'", + binaryFailure.stderr.replace("Setting up base binary.", "Writing output."), ]) { let calls = 0; await rejects( @@ -89,25 +128,27 @@ test("does not retry deterministic compile failures or unrelated connection erro } }); -test("does not retry a signaled compiler despite earlier download diagnostics", async () => { - let calls = 0; - await rejects( - compileWithDownloadRetries( - () => { - calls++; - return Promise.resolve({ ...failure, signal: "SIGTERM" }); - }, - "x86_64-unknown-linux-gnu", - { - sleep: () => { - throw new Error("must not wait"); +for (const downloadFailure of [failure, binaryFailure]) { + test(`does not retry a signaled compiler after ${downloadFailure === failure ? "npm" : "binary"} download diagnostics`, async () => { + let calls = 0; + await rejects( + compileWithDownloadRetries( + () => { + calls++; + return Promise.resolve({ ...downloadFailure, signal: "SIGTERM" }); }, - }, - ), - /exit code 1/, - ); - strictEqual(calls, 1); -}); + "x86_64-unknown-linux-gnu", + { + sleep: () => { + throw new Error("must not wait"); + }, + }, + ), + /exit code 1/, + ); + strictEqual(calls, 1); + }); +} test("propagates subprocess setup failures without retrying", async () => { let calls = 0; diff --git a/packages/cli/scripts/compile.ts b/packages/cli/scripts/compile.ts index 361d0cae9..b8949f357 100644 --- a/packages/cli/scripts/compile.ts +++ b/packages/cli/scripts/compile.ts @@ -10,7 +10,7 @@ interface RetryOptions { warn?: (message: string) => void; } -/** Retry interrupted npm downloads without masking deterministic compile errors. */ +/** Retry interrupted compiler downloads without masking deterministic errors. */ export async function compileWithDownloadRetries( compile: () => Promise, target: string, @@ -36,9 +36,12 @@ export async function compileWithDownloadRetries( const diagnostic = lastError < 0 ? "" : lines.slice(lastError).join("\n"); const interruptedDownload = !result.signal && - /^error: Failed caching npm package[^\r\n]*\r?\n\s*0: error reading a body from connection/.test( + (/^error: Failed caching npm package[^\r\n]*\r?\n\s*0: error reading a body from connection/.test( diagnostic, - ); + ) || + /^error: Writing deno compile executable to temporary file [^\r\n]*\r?\n\s*Caused by:\s*\r?\n\s*0: Setting up base binary\.\r?\n\s*1: error reading a body from connection/.test( + diagnostic, + )); if (!interruptedDownload || attempt === attempts) { throw new Error( `CLI compilation for ${target} failed with exit code ${result.code}`, @@ -46,7 +49,7 @@ export async function compileWithDownloadRetries( } const delay = attempt * 2_000; warn( - `npm download interrupted for ${target}; retrying compilation in ${delay}ms (${attempt + 1}/${attempts}).`, + `Compiler download interrupted for ${target}; retrying compilation in ${delay}ms (${attempt + 1}/${attempts}).`, ); await sleep(delay); } From 84632cf2942852fcb790b137392619b2e4dc6e1d Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Thu, 19 Nov 2026 02:17:38 +0900 Subject: [PATCH 18/41] Accept terminated POSIX zombie descendants macOS can retain a killed, reparented descendant as a zombie, just as Linux can. Use the POSIX process state to accept a zombie or an absent process without mistaking a successful signal-zero probe for a running child. Keep the Windows assertion unchanged. https://github.com/fedify-dev/fedify/actions/runs/44324101804/job/134870598577 Changelog: none Assisted-by: OpenCode:gpt-6.1-sol --- scripts/tooling_process.test.ts | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/scripts/tooling_process.test.ts b/scripts/tooling_process.test.ts index c52a54d20..213a573b2 100644 --- a/scripts/tooling_process.test.ts +++ b/scripts/tooling_process.test.ts @@ -57,19 +57,28 @@ test("stopping a command waits for its output and kills descendants", async () = const pid = Number(await readFile(pidFile, "utf8")); await child.stop(); await child.status; - // Linux may briefly retain a killed, reparented process as a zombie. - // Once it is reaped, opening its stat file fails with ENOENT, or reading - // an already opened one fails with ESRCH. - if (process.platform === "linux") { - try { - const stat = await readFile(`/proc/${pid}/stat`, "utf8"); - equal(stat.split(") ")[1][0], "Z", "descendant is no longer running"); - } catch (error) { - const { code } = error as NodeJS.ErrnoException; - if (code !== "ENOENT" && code !== "ESRCH") throw error; - } - } else { + if (process.platform === "win32") { throws(() => process.kill(pid, 0), { code: "ESRCH" }); + } else { + // Both Linux and macOS can retain a killed, reparented descendant as + // a zombie. Signal 0 still succeeds then, although it cannot run. + const state = await commandOutput("ps", [ + "-o", + "stat=", + "-p", + String(pid), + ]); + const stat = new TextDecoder().decode(state.stdout).trim(); + if (state.code === 0) { + equal( + stat.startsWith("Z"), + true, + `descendant is no longer running: ${stat}`, + ); + } else { + equal(state.code, 1, "ps reports a missing descendant"); + equal(stat, ""); + } } } finally { await child.stop(); From b6b31ad5ff1c9fdc5f01cd918e7a0c3d6ff66731 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Thu, 19 Nov 2026 06:22:41 +0900 Subject: [PATCH 19/41] Follow callable defaults during invalidation A binding default can pass a mutator as a value for a later call. Include references in default expressions when discovering invalidation scopes, without expanding delivery diagnostics. Cover parameter, declaration, and catch defaults with regression tests. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4618244281 Assisted-by: OpenCode:gpt-6.1-sol --- .../lint/src/rules/outbox-listener-delivery-not-awaited.ts | 2 ++ .../src/tests/outbox-listener-delivery-not-awaited.test.ts | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index add358df5..fa89bf77c 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -902,6 +902,8 @@ function checkListener( (node) => { if (node.type === "CallExpression") collectReferencedNames(node, names); + else if (node.type === "AssignmentPattern") + collectReferencedNames(get(node, "right"), names); }, false, ); diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 7ece8d5c5..3b9f94078 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -423,6 +423,10 @@ federation.setOutboxListeners("/users/{identifier}/outbox") } for (const mutation of [ + "const replace = () => { run = finish; }; const invoke = (callback = replace) => callback(); invoke();", + "const replace = () => { run = finish; }; const { callback = replace } = {}; callback();", + "const replace = () => { run = finish; }; const [callback = replace] = []; callback();", + "const replace = () => { run = finish; }; try { throw {}; } catch ({ callback = replace }) { callback(); }", "const replace = () => { run = finish; }; const { value = replace() } = {};", "const replace = () => { run = finish; }; const [value = replace()] = [];", "const replace = () => { run = finish; return 'value'; }; const { [replace()]: value } = {};", From bb118d751f819e07b4c215ae684b24c2c367e9d4 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Thu, 19 Nov 2026 06:24:08 +0900 Subject: [PATCH 20/41] Track adopted async delivery completion Returning a delivery promise from an async helper adopts its completion, even when another branch returns an array. Preserve that evidence apart from array classification, as for an explicitly awaited delivery. Cover dropped, awaited, callback, and forwarded calls for both return forms. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4618244266 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 6 +++--- .../outbox-listener-delivery-not-awaited.test.ts | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index fa89bf77c..d49045136 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -1114,11 +1114,11 @@ function checkListener( }: Outcome): boolean => { if (owner == null || owner === listener) return false; if (fate !== "awaited" && fate !== "returned") return false; - // An independently awaited delivery still makes an async helper's own - // completion promise significant, even if it later returns an array. + // Awaiting or adopting a delivery makes an async helper's own completion + // promise significant, even if another branch returns an array. if ( arrayInvolved.has(owner) && - !(fate === "awaited" && get(owner, "async") === true) + !(shape === "promise" && get(owner, "async") === true) ) { if (shape !== "promises" || shapes.get(owner) !== "promises") return false; diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 3b9f94078..4062dd875 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -334,6 +334,22 @@ for (const [scenario, definition, consumer, dropped] of [ "deliver();", true, ], + ...["return", "return await"].flatMap((returnSyntax) => + [ + ["dropped", "deliver();", true], + ["awaited", "await deliver();", false], + ["callback", "inboxes.forEach(deliver);", true], + ["chain", "const forward = () => deliver(); forward();", true], + ].map( + ([label, use, reports]) => + [ + `async mixed array adopts delivery: ${returnSyntax} ${label}`, + `async function deliver() { if (skip) return []; ${returnSyntax} ${arrayHelperDelivery}; }`, + use, + reports, + ] as const, + ), + ), [ "async completion through a sync helper", `const inner = async () => { await ${arrayHelperDelivery}; return []; }; const deliver = () => inner();`, From 5896cc7bf135cee42580c5e9b41b36f9c204b269 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Thu, 19 Nov 2026 08:36:56 +0900 Subject: [PATCH 21/41] Discover default callbacks and setter mutations Include inline default callbacks and member-assignment receivers when finding scopes that can invalidate a helper's return shape. A callback supplied by a default or a local setter can replace a helper even when shared delivery reachability does not visit its body. Keep the extra scope discovery confined to invalidation. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4621227288 https://github.com/fedify-dev/fedify/pull/1446#discussion_r4621227303 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 55 +++++++++++++------ ...tbox-listener-delivery-not-awaited.test.ts | 7 +++ 2 files changed, 45 insertions(+), 17 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index d49045136..d6e6ceab3 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -893,6 +893,7 @@ function checkListener( const invalidationFunctions = new Set(scopes.map((scope) => scope.fn)); for (const [index, scope] of invalidationScopes.entries()) { const names = new Set(); + const inlineDefaults = new Set(); const expressions = invalidationExpressions(scope); for (const expression of expressions) { // Declaration ids contain executable defaults and computed keys that @@ -902,8 +903,26 @@ function checkListener( (node) => { if (node.type === "CallExpression") collectReferencedNames(node, names); - else if (node.type === "AssignmentPattern") + else if (node.type === "AssignmentPattern") { collectReferencedNames(get(node, "right"), names); + // Default values can supply inline callbacks for a later call. + // Scan them only for invalidation, never for delivery diagnostics. + visitAll(get(node, "right"), (value) => { + if (isFunctionLikeNode(value)) inlineDefaults.add(value); + }); + } else if ( + node.type === "AssignmentExpression" || + node.type === "UpdateExpression" + ) { + const target = asNode( + get( + node, + node.type === "AssignmentExpression" ? "left" : "argument", + ), + ); + if (target != null && unwrap(target).type === "MemberExpression") + collectReferencedNames(unwrap(target), names); + } }, false, ); @@ -912,23 +931,25 @@ function checkListener( for (const statement of scope.statements) collectReferencedNames(statement, names); } - for (const name of names) { - for (const fn of scope.functionsByName.get(name) ?? []) { - if (invalidationFunctions.has(fn)) continue; - walkUsedScopes(fn.body as Node, (nested) => { - const nestedFn = nested.fn ?? fn; - if (invalidationFunctions.has(nestedFn)) return; - invalidationFunctions.add(nestedFn); - invalidationScopes.push({ - ...nested, - fn: nestedFn, - functionsByName: new Map([ - ...scope.functionsByName, - ...nested.functionsByName, - ]), - }); + const candidates = new Set([ + ...inlineDefaults, + ...[...names].flatMap((name) => scope.functionsByName.get(name) ?? []), + ]); + for (const fn of candidates) { + if (invalidationFunctions.has(fn)) continue; + walkUsedScopes(fn.body as Node, (nested) => { + const nestedFn = nested.fn ?? fn; + if (invalidationFunctions.has(nestedFn)) return; + invalidationFunctions.add(nestedFn); + invalidationScopes.push({ + ...nested, + fn: nestedFn, + functionsByName: new Map([ + ...scope.functionsByName, + ...nested.functionsByName, + ]), }); - } + }); } } diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 4062dd875..c416392e5 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -439,6 +439,13 @@ federation.setOutboxListeners("/users/{identifier}/outbox") } for (const mutation of [ + "const invoke = (callback = () => { run = finish; }) => callback(); invoke();", + "const invoke = (callback = function () { run = finish; }) => callback(); invoke();", + "const { callback = () => { run = finish; } } = {}; callback();", + "const [callback = () => { run = finish; }] = []; callback();", + "try { throw {}; } catch ({ callback = () => { run = finish; } }) { callback(); }", + "const holder = { set current(value) { run = value; } }; holder.current = finish;", + "const holder = { set current(value) { run = value; } }; holder['current'] = finish;", "const replace = () => { run = finish; }; const invoke = (callback = replace) => callback(); invoke();", "const replace = () => { run = finish; }; const { callback = replace } = {}; callback();", "const replace = () => { run = finish; }; const [callback = replace] = []; callback();", From 357d40abe07708cfda022ea4fab5ab205ed15957 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Thu, 19 Nov 2026 08:37:56 +0900 Subject: [PATCH 22/41] Keep static block helpers in their variable scope Use a class static block as the region of its var helpers instead of falling back to the enclosing listener. Stop assignment-region lookup at that boundary too, and include its declarations in shadow checks. This prevents a static-block helper's array shape from leaking to an unrelated outer alias. Cover initializers and later assignments. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4621227323 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 18 +++++++++-- ...tbox-listener-delivery-not-awaited.test.ts | 31 +++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index d6e6ceab3..b1c89eca6 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -156,6 +156,19 @@ function enclosingFunction(node: Node): FunctionLikeNode | null { return null; } +/** A static block, like a function body, owns its var bindings. */ +function variableRegion(node: Node): Node | null { + for ( + let current = parentOf(node); + current != null; + current = parentOf(current) + ) { + if (current.type === "StaticBlock") return current; + if (isFunctionLikeNode(current)) return asNode(get(current, "body")); + } + return null; +} + /** Checks binding patterns without treating property keys as bindings. */ function bindsName(pattern: Node | null, name: string): boolean { if (pattern == null) return false; @@ -198,7 +211,7 @@ function shadowsName(region: Node, name: string, lexicalOnly = false): boolean { return bindsName(asNode(get(region, "param")), name); } const declarations: Node[] = - region.type === "BlockStatement" + region.type === "BlockStatement" || region.type === "StaticBlock" ? (get(region, "body") as Node[]) : region.type === "SwitchStatement" ? (get(region, "cases") as Node[]).flatMap( @@ -229,6 +242,7 @@ function assignmentRegion(assignment: Node, name: string): Node | null { current = parentOf(current) ) { if (isFunctionLikeNode(current)) return asNode(get(current, "body")); + if (current.type === "StaticBlock") return current; if (shadowsName(current, name, true)) return current; } return null; @@ -280,7 +294,7 @@ function helpersAt( ? parentOf(variable) : declarator?.type === "AssignmentExpression" ? assignmentRegion(declarator, node.name) - : asNode(get(enclosingFunction(fn), "body")); + : variableRegion(fn); if (region == null) return []; const functionScope = enclosingFunction(fn); let current: Node | null = node; diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index c416392e5..6e75c922a 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -438,6 +438,37 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const declaration of [ + "var run = () => [ctx.sendActivity(sender, inbox, activity)];", + "var run; run = () => [ctx.sendActivity(sender, inbox, activity)];", + "var run; { run = () => [ctx.sendActivity(sender, inbox, activity)]; }", +]) { + test( + `${ruleName}: static block var helpers do not escape: ${declaration}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + const run = finish; + const pending = []; + const Holder = class { + static { + ${declaration} + pending.push(...run()); + } + }; + await Promise.all(pending); + await run(); + }); +`, + rule, + ruleName, + }), + ); +} + for (const mutation of [ "const invoke = (callback = () => { run = finish; }) => callback(); invoke();", "const invoke = (callback = function () { run = finish; }) => callback(); invoke();", From c3b48e30826763cd7d5da68173fc1264038d95e6 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Thu, 19 Nov 2026 12:51:19 +0900 Subject: [PATCH 23/41] Invalidate alias-initialized lexical helpers Check non-function initializers on lexical declarations as well as var bindings. Otherwise a later function-literal assignment can supply an array shape to earlier calls that still invoke the initial alias. Cover direct, object-destructured, and array-destructured let bindings. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4622494077 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 5 +--- ...tbox-listener-delivery-not-awaited.test.ts | 25 +++++++++++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index b1c89eca6..60877c00a 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -1030,10 +1030,7 @@ function checkListener( visitAll( statement, (node) => { - if ( - node.type === "VariableDeclarator" && - get(parentOf(node), "kind") === "var" - ) { + if (node.type === "VariableDeclarator") { const value = asNode(get(node, "init")); if (value != null && !isFunctionLikeNode(unwrap(value))) { for (const name of helperNames) { diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 6e75c922a..2c0dcea70 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -438,6 +438,31 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const binding of [ + "let run = finish", + "let { run } = { run: finish }", + "let [run] = [finish]", +]) { + test( + `${ruleName}: initial lexical alias invalidates later helper inference: ${binding}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + ${binding}; + await run(); + run = () => [ctx.sendActivity(sender, inbox, activity)]; + await Promise.all(run()); + }); +`, + rule, + ruleName, + }), + ); +} + for (const declaration of [ "var run = () => [ctx.sendActivity(sender, inbox, activity)];", "var run; run = () => [ctx.sendActivity(sender, inbox, activity)];", From 2701fe1b70e075ba302205dbd373c452482b493a Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Fri, 20 Nov 2026 03:44:40 +0900 Subject: [PATCH 24/41] Invalidate helper shapes across loop inputs Treat lexical iteration bindings as unknown incoming writes, just like var iteration bindings. Follow member receivers in loop targets for invalidation so local setter mutations cannot leave stale helper shapes. Cover lexical destructuring and setter targets in for-of and for-in. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4624183340 https://github.com/fedify-dev/fedify/pull/1446#discussion_r4624183349 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 23 ++++++++++---- ...tbox-listener-delivery-not-awaited.test.ts | 30 +++++++++++++++++++ 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 60877c00a..c05bfe88b 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -910,6 +910,22 @@ function checkListener( const inlineDefaults = new Set(); const expressions = invalidationExpressions(scope); for (const expression of expressions) { + const parent = parentOf(expression); + if ( + (parent?.type === "ForOfStatement" || + parent?.type === "ForInStatement") && + get(parent, "right") === expression + ) { + // Loop member targets can invoke setters without an assignment node. + visitAll( + get(parent, "left"), + (target) => { + if (target.type === "MemberExpression") + collectReferencedNames(target, names); + }, + false, + ); + } // Declaration ids contain executable defaults and computed keys that // collectReferencedNames intentionally omits from body reachability. visitAll( @@ -1011,17 +1027,14 @@ function checkListener( get(parent, "right") === statement ) { const target = asNode(get(parent, "left")); - if ( - target?.type === "VariableDeclaration" && - get(target, "kind") === "var" - ) { + if (target?.type === "VariableDeclaration") { for (const item of get(target, "declarations") as Node[]) { for (const name of helperNames) { if (bindsName(asNode(get(item, "id")), name)) unknownWrites.add(name); } } - } else if (target?.type !== "VariableDeclaration") { + } else { for (const name of helperNames) { if (bindsName(target, name)) unknownWrites.add(name); } diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 2c0dcea70..97f99e23a 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -438,6 +438,33 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const loop of [ + "for (let run of [finish])", + "for (let [run] of [[finish]])", + "for (let { run } of [{ run: finish }])", + "for (let run in { key: true })", +]) { + test( + `${ruleName}: lexical loop inputs invalidate later helper shapes: ${loop}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + ${loop} { + await run(); + run = () => [ctx.sendActivity(sender, inbox, activity)]; + await Promise.all(run()); + } + }); +`, + rule, + ruleName, + }), + ); +} + for (const binding of [ "let run = finish", "let { run } = { run: finish }", @@ -495,6 +522,9 @@ federation.setOutboxListeners("/users/{identifier}/outbox") } for (const mutation of [ + "const holder = { set current(value) { run = value; } }; for (holder.current of [finish]) {}", + "const holder = { set current(value) { run = finish; } }; for (holder.current in { key: true }) {}", + "const holder = { set current(value) { run = value; } }; for ([holder.current] of [[finish]]) {}", "const invoke = (callback = () => { run = finish; }) => callback(); invoke();", "const invoke = (callback = function () { run = finish; }) => callback(); invoke();", "const { callback = () => { run = finish; } } = {}; callback();", From 243bcfd4a6e85a8ef626d8e49a798fd4146d0804 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Fri, 20 Nov 2026 03:45:23 +0900 Subject: [PATCH 25/41] Discover inline calls in executable binding keys Include inline functions in calls when discovering invalidation scopes. Computed parameter keys can invoke a mutator without a default-value pattern, so name references alone miss the write. Cover parameter, declaration, and catch keys without expanding delivery diagnostics. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4624231650 Assisted-by: OpenCode:gpt-6.1-sol --- .../rules/outbox-listener-delivery-not-awaited.ts | 14 +++++++++----- .../outbox-listener-delivery-not-awaited.test.ts | 4 ++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index c05bfe88b..4589a7db0 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -907,7 +907,7 @@ function checkListener( const invalidationFunctions = new Set(scopes.map((scope) => scope.fn)); for (const [index, scope] of invalidationScopes.entries()) { const names = new Set(); - const inlineDefaults = new Set(); + const inlineFunctions = new Set(); const expressions = invalidationExpressions(scope); for (const expression of expressions) { const parent = parentOf(expression); @@ -931,14 +931,18 @@ function checkListener( visitAll( expression, (node) => { - if (node.type === "CallExpression") + if (node.type === "CallExpression") { collectReferencedNames(node, names); - else if (node.type === "AssignmentPattern") { + // An executable binding key can invoke an inline function. + visitAll(node, (value) => { + if (isFunctionLikeNode(value)) inlineFunctions.add(value); + }); + } else if (node.type === "AssignmentPattern") { collectReferencedNames(get(node, "right"), names); // Default values can supply inline callbacks for a later call. // Scan them only for invalidation, never for delivery diagnostics. visitAll(get(node, "right"), (value) => { - if (isFunctionLikeNode(value)) inlineDefaults.add(value); + if (isFunctionLikeNode(value)) inlineFunctions.add(value); }); } else if ( node.type === "AssignmentExpression" || @@ -962,7 +966,7 @@ function checkListener( collectReferencedNames(statement, names); } const candidates = new Set([ - ...inlineDefaults, + ...inlineFunctions, ...[...names].flatMap((name) => scope.functionsByName.get(name) ?? []), ]); for (const fn of candidates) { diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 97f99e23a..688c64bcc 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -525,6 +525,10 @@ for (const mutation of [ "const holder = { set current(value) { run = value; } }; for (holder.current of [finish]) {}", "const holder = { set current(value) { run = finish; } }; for (holder.current in { key: true }) {}", "const holder = { set current(value) { run = value; } }; for ([holder.current] of [[finish]]) {}", + "const replace = ({ [(() => { run = finish; return 'key'; })()]: value }) => value; replace({});", + "const replace = ({ [(function () { run = finish; return 'key'; })()]: value }) => value; replace({});", + "const { [(() => { run = finish; return 'key'; })()]: value } = {};", + "try { throw {}; } catch ({ [(() => { run = finish; return 'key'; })()]: value }) {}", "const invoke = (callback = () => { run = finish; }) => callback(); invoke();", "const invoke = (callback = function () { run = finish; }) => callback(); invoke();", "const { callback = () => { run = finish; } } = {}; callback();", From 75acf8b66db8de5b39d798ec7394944f330d0fde Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Fri, 20 Nov 2026 03:45:52 +0900 Subject: [PATCH 26/41] Exclude static vars from enclosing local names Only include a var binding in function-local write exemptions when its variable region is that function's body. A nested static block owns its own vars and must not make an outer-binding replacement look local. Add a regression for a static var followed by an outer helper write. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4624231657 Assisted-by: OpenCode:gpt-6.1-sol --- .../lint/src/rules/outbox-listener-delivery-not-awaited.ts | 3 ++- .../src/tests/outbox-listener-delivery-not-awaited.test.ts | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 4589a7db0..3a9124edc 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -1008,7 +1008,8 @@ function checkListener( (node) => { if ( node.type !== "VariableDeclarator" || - get(parentOf(node), "kind") !== "var" + get(parentOf(node), "kind") !== "var" || + variableRegion(node) !== scope.fn?.body ) return; for (const name of helperNames) { diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 688c64bcc..814e43ea7 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -529,6 +529,7 @@ for (const mutation of [ "const replace = ({ [(function () { run = finish; return 'key'; })()]: value }) => value; replace({});", "const { [(() => { run = finish; return 'key'; })()]: value } = {};", "try { throw {}; } catch ({ [(() => { run = finish; return 'key'; })()]: value }) {}", + "const replace = () => { class Holder { static { var run; } } run = async () => { await ctx.sendActivity(sender, inbox, activity); }; }; replace();", "const invoke = (callback = () => { run = finish; }) => callback(); invoke();", "const invoke = (callback = function () { run = finish; }) => callback(); invoke();", "const { callback = () => { run = finish; } } = {}; callback();", From 67d650c3f0a0790340b93340de4a33fab8b80ecd Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Fri, 20 Nov 2026 04:14:28 +0900 Subject: [PATCH 27/41] Follow member accessors during invalidation Collect executable member references for invalidation, including plain getter reads and setter targets in destructuring defaults. Both can replace a helper without a direct call or member assignment node. Cover computed binding keys, ordinary reads, and object and array assignment defaults without expanding delivery diagnostics. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4633549207 https://github.com/fedify-dev/fedify/pull/1446#discussion_r4633638553 Assisted-by: OpenCode:gpt-6.1-sol --- .../lint/src/rules/outbox-listener-delivery-not-awaited.ts | 4 ++++ .../src/tests/outbox-listener-delivery-not-awaited.test.ts | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 3a9124edc..07f260f3e 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -937,6 +937,10 @@ function checkListener( visitAll(node, (value) => { if (isFunctionLikeNode(value)) inlineFunctions.add(value); }); + } else if (node.type === "MemberExpression") { + // Reads can invoke getters; destructuring targets can invoke + // setters even without an AssignmentExpression at the member. + collectReferencedNames(node, names); } else if (node.type === "AssignmentPattern") { collectReferencedNames(get(node, "right"), names); // Default values can supply inline callbacks for a later call. diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 814e43ea7..6c9a1808d 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -522,6 +522,11 @@ federation.setOutboxListeners("/users/{identifier}/outbox") } for (const mutation of [ + "const holder = { get key() { run = finish; return 'key'; } }; const value = holder.key;", + "const holder = { get key() { run = finish; return 'key'; } }; const { [holder.key]: value } = {};", + "const holder = { get key() { run = finish; return 'key'; } }; const invoke = ({ [holder.key]: value }) => value; invoke({});", + "const holder = { set current(value) { run = value; } }; ({ current: holder.current = finish } = {});", + "const holder = { set current(value) { run = value; } }; [holder.current = finish] = [];", "const holder = { set current(value) { run = value; } }; for (holder.current of [finish]) {}", "const holder = { set current(value) { run = finish; } }; for (holder.current in { key: true }) {}", "const holder = { set current(value) { run = value; } }; for ([holder.current] of [[finish]]) {}", From ca441d8baf65ebcf7a86fcc678a33604c098711c Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Fri, 20 Nov 2026 04:15:11 +0900 Subject: [PATCH 28/41] Retain enclosing callees for parameter defaults Parameter defaults cannot see declarations in their own function body. Include enclosing helper candidates for parameter references during invalidation rather than relying only on the merged body-scope map. Cover called defaults, callable values, and computed parameter keys shadowed by a same-named declaration in the body. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4633638545 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 20 +++++++++++++++++++ ...tbox-listener-delivery-not-awaited.test.ts | 3 +++ 2 files changed, 23 insertions(+) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 07f260f3e..2d75cbe38 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -973,6 +973,26 @@ function checkListener( ...inlineFunctions, ...[...names].flatMap((name) => scope.functionsByName.get(name) ?? []), ]); + // Parameter defaults cannot see declarations in their own function body. + // Retain enclosing candidates as well as the merged body-scope candidates. + const parameterNames = new Set(); + collectReferencedNames(scope.fn?.params, parameterNames); + const enclosingFunctions = new Set(); + for ( + let outer = scope.fn == null ? null : enclosingFunction(scope.fn); + outer != null; + outer = enclosingFunction(outer) + ) { + enclosingFunctions.add(outer); + } + for (const enclosing of invalidationScopes) { + if (enclosing.fn != null && !enclosingFunctions.has(enclosing.fn)) + continue; + for (const name of parameterNames) { + for (const fn of enclosing.functionsByName.get(name) ?? []) + candidates.add(fn); + } + } for (const fn of candidates) { if (invalidationFunctions.has(fn)) continue; walkUsedScopes(fn.body as Node, (nested) => { diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 6c9a1808d..1fff27be8 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -522,6 +522,9 @@ federation.setOutboxListeners("/users/{identifier}/outbox") } for (const mutation of [ + "const replace = () => { run = finish; }; function invoke(value = replace()) { const replace = () => {}; } invoke();", + "const replace = () => { run = finish; }; function invoke(callback = replace) { const replace = () => {}; callback(); } invoke();", + "const replace = () => { run = finish; }; function invoke({ [replace()]: value }) { const replace = () => {}; } invoke({});", "const holder = { get key() { run = finish; return 'key'; } }; const value = holder.key;", "const holder = { get key() { run = finish; return 'key'; } }; const { [holder.key]: value } = {};", "const holder = { get key() { run = finish; return 'key'; } }; const invoke = ({ [holder.key]: value }) => value; invoke({});", From 3e672ee6d1746f281b8864ea3e71bf4e0141fec4 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Fri, 20 Nov 2026 04:15:46 +0900 Subject: [PATCH 29/41] Use switch scope for case-local helper bindings A declaration directly inside a switch case belongs to the whole switch. Use the enclosing switch statement as its binding region so sibling-case calls retain completion and delivery-array tracking. Cover dropped and properly awaited consumers for both return shapes. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4633638526 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 3 +- ...tbox-listener-delivery-not-awaited.test.ts | 38 +++++++++++++++++-- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 2d75cbe38..242a9b6bf 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -286,7 +286,7 @@ function helpersAt( } const variable = declarator?.type === "VariableDeclarator" ? parentOf(declarator) : null; - const region = + let region = fn.type === "FunctionDeclaration" ? parentOf(fn) : variable?.type === "VariableDeclaration" && @@ -295,6 +295,7 @@ function helpersAt( : declarator?.type === "AssignmentExpression" ? assignmentRegion(declarator, node.name) : variableRegion(fn); + if (region?.type === "SwitchCase") region = parentOf(region); if (region == null) return []; const functionScope = enclosingFunction(fn); let current: Node | null = node; diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 1fff27be8..e501b8d3c 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -438,6 +438,38 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const [returned, consumer, dropped] of [ + ["ctx.sendActivity(sender, inbox, activity)", "deliver();", true], + ["ctx.sendActivity(sender, inbox, activity)", "await deliver();", false], + ["[ctx.sendActivity(sender, inbox, activity)]", "await deliver();", true], + [ + "[ctx.sendActivity(sender, inbox, activity)]", + "await Promise.all(deliver());", + false, + ], +] as const) { + test( + `${ruleName}: helpers share switch case scope: ${returned} ${consumer}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + switch (kind) { + case 0: + function deliver() { return ${returned}; } + case 1: + ${consumer} + } + }); +`, + rule, + ruleName, + ...(dropped ? { expectedError: "Delivery is not awaited" } : {}), + }), + ); +} + for (const loop of [ "for (let run of [finish])", "for (let [run] of [[finish]])", @@ -522,14 +554,14 @@ federation.setOutboxListeners("/users/{identifier}/outbox") } for (const mutation of [ - "const replace = () => { run = finish; }; function invoke(value = replace()) { const replace = () => {}; } invoke();", - "const replace = () => { run = finish; }; function invoke(callback = replace) { const replace = () => {}; callback(); } invoke();", - "const replace = () => { run = finish; }; function invoke({ [replace()]: value }) { const replace = () => {}; } invoke({});", "const holder = { get key() { run = finish; return 'key'; } }; const value = holder.key;", "const holder = { get key() { run = finish; return 'key'; } }; const { [holder.key]: value } = {};", "const holder = { get key() { run = finish; return 'key'; } }; const invoke = ({ [holder.key]: value }) => value; invoke({});", "const holder = { set current(value) { run = value; } }; ({ current: holder.current = finish } = {});", "const holder = { set current(value) { run = value; } }; [holder.current = finish] = [];", + "const replace = () => { run = finish; }; function invoke(value = replace()) { const replace = () => {}; } invoke();", + "const replace = () => { run = finish; }; function invoke(callback = replace) { const replace = () => {}; callback(); } invoke();", + "const replace = () => { run = finish; }; function invoke({ [replace()]: value }) { const replace = () => {}; } invoke({});", "const holder = { set current(value) { run = value; } }; for (holder.current of [finish]) {}", "const holder = { set current(value) { run = finish; } }; for (holder.current in { key: true }) {}", "const holder = { set current(value) { run = value; } }; for ([holder.current] of [[finish]]) {}", From 39f067d4808f8821deeb08f68f7dc1991ac04944 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Fri, 20 Nov 2026 08:30:44 +0900 Subject: [PATCH 30/41] Invalidate incoming parameter and catch bindings Parameters and catch bindings receive values that helper inference does not classify. Treat them as unknown initial writes so a later literal assignment cannot supply an array shape to earlier calls. Cover direct, defaulted, and destructured parameters and destructured catch bindings. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4633914445 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 16 ++++++ ...tbox-listener-delivery-not-awaited.test.ts | 54 +++++++++++++++++++ 2 files changed, 70 insertions(+) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 242a9b6bf..fb77ba4f9 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -1021,6 +1021,22 @@ function checkListener( ); const unknownWrites = new Set(); for (const scope of invalidationScopes) { + const invalidateIncoming = (pattern: Node): void => { + for (const name of helperNames) { + if (bindsName(pattern, name)) unknownWrites.add(name); + } + }; + for (const param of scope.fn?.params ?? []) + invalidateIncoming(param as Node); + visitAll( + scope.fn?.body ?? listener.body, + (node) => { + if (node.type !== "CatchClause") return; + const param = asNode(get(node, "param")); + if (param != null) invalidateIncoming(param); + }, + false, + ); const localFunctionNames = new Set(); if (scope.fn != null) { for (const name of helperNames) { diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index e501b8d3c..9a834c8ce 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -438,6 +438,60 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const [parameters, argument] of [ + ["run", "finish"], + ["{ run }", "{ run: finish }"], + ["[run]", "[finish]"], + ["run = finish", "undefined"], +] as const) { + test( + `${ruleName}: incoming parameter values invalidate helper shapes: ${parameters}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + async function invoke(${parameters}) { + await run(); + run = () => [ctx.sendActivity(sender, inbox, activity)]; + await Promise.all(run()); + } + await invoke(${argument}); + }); +`, + rule, + ruleName, + }), + ); +} + +for (const [binding, thrown] of [ + ["run", "finish"], + ["{ run }", "{ run: finish }"], + ["[run]", "[finish]"], +] as const) { + test( + `${ruleName}: incoming catch values invalidate helper shapes: ${binding}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const finish = async () => { await ctx.sendActivity(sender, inbox, activity); }; + try { throw ${thrown}; } catch (${binding}) { + await run(); + run = () => [ctx.sendActivity(sender, inbox, activity)]; + await Promise.all(run()); + } + }); +`, + rule, + ruleName, + }), + ); +} + for (const [returned, consumer, dropped] of [ ["ctx.sendActivity(sender, inbox, activity)", "deliver();", true], ["ctx.sendActivity(sender, inbox, activity)", "await deliver();", false], From 08a256ab1823cc48e28f1adc52cb5e80284f8042 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Fri, 20 Nov 2026 08:31:23 +0900 Subject: [PATCH 31/41] Retain enclosing mutators for body references A flattened block binding can replace an enclosing callee in the merged scope map even when the reference lies outside that block. Include body references when retaining enclosing invalidation candidates, not only parameter defaults. Cover const, let, and function declarations inside a block followed by an outer mutator call. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4633914465 Assisted-by: OpenCode:gpt-6.1-sol --- .../src/rules/outbox-listener-delivery-not-awaited.ts | 11 ++++++----- .../outbox-listener-delivery-not-awaited.test.ts | 3 +++ 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index fb77ba4f9..37e8ae320 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -974,10 +974,11 @@ function checkListener( ...inlineFunctions, ...[...names].flatMap((name) => scope.functionsByName.get(name) ?? []), ]); - // Parameter defaults cannot see declarations in their own function body. - // Retain enclosing candidates as well as the merged body-scope candidates. - const parameterNames = new Set(); - collectReferencedNames(scope.fn?.params, parameterNames); + // Flattened block bindings can hide enclosing callees, and parameter + // defaults cannot see declarations in their own function body. Retain + // enclosing candidates for both body and parameter references. + const enclosingNames = new Set(names); + collectReferencedNames(scope.fn?.params, enclosingNames); const enclosingFunctions = new Set(); for ( let outer = scope.fn == null ? null : enclosingFunction(scope.fn); @@ -989,7 +990,7 @@ function checkListener( for (const enclosing of invalidationScopes) { if (enclosing.fn != null && !enclosingFunctions.has(enclosing.fn)) continue; - for (const name of parameterNames) { + for (const name of enclosingNames) { for (const fn of enclosing.functionsByName.get(name) ?? []) candidates.add(fn); } diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 9a834c8ce..389a84255 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -608,6 +608,9 @@ federation.setOutboxListeners("/users/{identifier}/outbox") } for (const mutation of [ + "const replace = () => { run = finish; }; function invoke() { { const replace = () => {}; } replace(); } invoke();", + "const replace = () => { run = finish; }; function invoke() { { let replace = () => {}; } replace(); } invoke();", + "const replace = () => { run = finish; }; function invoke() { { function replace() {} } replace(); } invoke();", "const holder = { get key() { run = finish; return 'key'; } }; const value = holder.key;", "const holder = { get key() { run = finish; return 'key'; } }; const { [holder.key]: value } = {};", "const holder = { get key() { run = finish; return 'key'; } }; const invoke = ({ [holder.key]: value }) => value; invoke({});", From 81e293d6cc3f2600e76253b30df390d586ceff20 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Fri, 20 Nov 2026 11:26:18 +0900 Subject: [PATCH 32/41] Preserve helper evidence across property writes Shared reachability records functions assigned to a callable's properties under the callable's name. Exclude those property candidates when resolving a direct helper call rather than rejecting the real callable. Cover direct, computed, and aggregate property writes with completion and delivery-array consumers. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4636621810 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 18 +++++++++- ...tbox-listener-delivery-not-awaited.test.ts | 35 +++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 37e8ae320..9cf755dec 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -261,7 +261,23 @@ function helpersAt( unknownWrites: ReadonlySet, ): FunctionLikeNode[] { if (node.type !== "Identifier" || unknownWrites.has(node.name)) return []; - const helpers = scope.functionsByName.get(node.name) ?? []; + const helpers = (scope.functionsByName.get(node.name) ?? []).filter((fn) => { + // Shared reachability also records functions stored on a callable's + // properties. Those writes do not replace the callable itself. + for ( + let current = parentOf(fn); + current != null; + current = parentOf(current) + ) { + if (isFunctionLikeNode(current) || current.type === "VariableDeclarator") + break; + if (current.type === "AssignmentExpression") { + const target = asNode(get(current, "left")); + return target == null || unwrap(target).type !== "MemberExpression"; + } + } + return true; + }); for (const fn of helpers) { let declaration: Node = fn; while ( diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 389a84255..e869f0ce5 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -438,6 +438,41 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const [returned, consumer, dropped] of [ + ["ctx.sendActivity(sender, inbox, activity)", "deliver();", true], + ["ctx.sendActivity(sender, inbox, activity)", "await deliver();", false], + ["[ctx.sendActivity(sender, inbox, activity)]", "await deliver();", true], + [ + "[ctx.sendActivity(sender, inbox, activity)]", + "await Promise.all(deliver());", + false, + ], +] as const) { + for (const property of [ + "deliver.extra = () => {};", + "deliver['extra'] = () => {};", + "deliver.extra = { nested: () => {} };", + ]) { + test( + `${ruleName}: function properties preserve helper evidence: ${returned} ${property} ${consumer}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + const deliver = () => ${returned}; + ${property} + ${consumer} + }); +`, + rule, + ruleName, + ...(dropped ? { expectedError: "Delivery is not awaited" } : {}), + }), + ); + } +} + for (const [parameters, argument] of [ ["run", "finish"], ["{ run }", "{ run: finish }"], From 86cf4bcfb381679ef41ab4278663ef9b1bacbafa Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Fri, 20 Nov 2026 11:27:15 +0900 Subject: [PATCH 33/41] Exclude discriminants from switch helper scope A switch discriminant executes before the case lexical environment exists. Reject case-local helper candidates for calls in that expression while retaining their shared scope across case clauses. Add a regression with an awaited module helper shadowed by a case-local array helper. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4636621820 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 6 ++++++ ...tbox-listener-delivery-not-awaited.test.ts | 20 +++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 9cf755dec..aab18a33b 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -316,6 +316,12 @@ function helpersAt( const functionScope = enclosingFunction(fn); let current: Node | null = node; while (current != null && current !== region) { + // The discriminant executes before the switch's case bindings exist. + if ( + region.type === "SwitchStatement" && + get(region, "discriminant") === current + ) + return []; // A var declaration in this function initializes the same binding, // even inside a block or loop head. In another function it can shadow. if ( diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index e869f0ce5..838fb3e0c 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -473,6 +473,26 @@ federation.setOutboxListeners("/users/{identifier}/outbox") } } +test( + `${ruleName}: switch discriminant excludes case-local helpers`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +async function run(ctx, activity) { await ctx.sendActivity(sender, inbox, activity); } +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + switch (!await run(ctx, activity)) { + case false: + function run() { return [ctx.sendActivity(sender, inbox, activity)]; } + await Promise.all(run()); + } + }); +`, + rule, + ruleName, + }), +); + for (const [parameters, argument] of [ ["run", "finish"], ["{ run }", "{ run: finish }"], From d8d978ef409ad788dd82a8e990809394cf4e39bf Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Fri, 20 Nov 2026 11:27:53 +0900 Subject: [PATCH 34/41] Discover constructor mutators in binding keys Constructor invocations can mutate helper bindings just like calls. Include new expressions in invalidation-only scope discovery, including inline constructors. Cover declaration, parameter, and catch binding keys without expanding delivery diagnostics. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4636621830 Assisted-by: OpenCode:gpt-6.1-sol --- .../lint/src/rules/outbox-listener-delivery-not-awaited.ts | 2 +- .../src/tests/outbox-listener-delivery-not-awaited.test.ts | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index aab18a33b..93089d24e 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -954,7 +954,7 @@ function checkListener( visitAll( expression, (node) => { - if (node.type === "CallExpression") { + if (node.type === "CallExpression" || node.type === "NewExpression") { collectReferencedNames(node, names); // An executable binding key can invoke an inline function. visitAll(node, (value) => { diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 838fb3e0c..3c954828b 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -663,6 +663,10 @@ federation.setOutboxListeners("/users/{identifier}/outbox") } for (const mutation of [ + "function Replace() { run = finish; } const { [new Replace()]: value } = {};", + "function Replace() { run = finish; } const invoke = ({ [new Replace()]: value }) => value; invoke({});", + "function Replace() { run = finish; } try { throw {}; } catch ({ [new Replace()]: value }) {}", + "const { [new (function () { run = finish; })()]: value } = {};", "const replace = () => { run = finish; }; function invoke() { { const replace = () => {}; } replace(); } invoke();", "const replace = () => { run = finish; }; function invoke() { { let replace = () => {}; } replace(); } invoke();", "const replace = () => { run = finish; }; function invoke() { { function replace() {} } replace(); } invoke();", From a80f2ae1331643b34f9baa96ad94737323a9bb90 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Sun, 22 Nov 2026 17:58:06 +0900 Subject: [PATCH 35/41] Stop property filtering at static block boundaries A helper declared inside a static block is not a property of the object that holds the enclosing class expression. Stop the property-candidate ancestor walk at that block so its direct callable evidence survives. Cover function declarations and var helpers in property-held classes. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4637812309 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 6 ++++- ...tbox-listener-delivery-not-awaited.test.ts | 26 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 93089d24e..da488d9a5 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -269,7 +269,11 @@ function helpersAt( current != null; current = parentOf(current) ) { - if (isFunctionLikeNode(current) || current.type === "VariableDeclarator") + if ( + isFunctionLikeNode(current) || + current.type === "StaticBlock" || + current.type === "VariableDeclarator" + ) break; if (current.type === "AssignmentExpression") { const target = asNode(get(current, "left")); diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 3c954828b..12172d0be 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -438,6 +438,32 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const declaration of [ + "function deliver() { return ctx.sendActivity(sender, inbox, activity); }", + "var deliver = () => ctx.sendActivity(sender, inbox, activity);", +]) { + test( + `${ruleName}: property-held classes retain static block helpers: ${declaration}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + holder.value = class { + static { + ${declaration} + deliver(); + } + }; + }); +`, + rule, + ruleName, + expectedError: "Delivery is not awaited", + }), + ); +} + for (const [returned, consumer, dropped] of [ ["ctx.sendActivity(sender, inbox, activity)", "deliver();", true], ["ctx.sendActivity(sender, inbox, activity)", "await deliver();", false], From 5a0cdbc77738923542d8a6b35b34a4652f999ad4 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Sun, 22 Nov 2026 17:59:03 +0900 Subject: [PATCH 36/41] Include root listener parameters in invalidation The root used scope has no function node. Fall back to the listener's parameters for incoming-value invalidation and parameter-expression scanning instead of silently omitting them. Cover direct and destructured listener defaults followed by an array-helper assignment. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4637839218 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 6 ++--- ...tbox-listener-delivery-not-awaited.test.ts | 23 +++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index da488d9a5..fa304d1e4 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -912,7 +912,7 @@ function checkListener( const invalidationExpressions = (scope: UsedScope): Node[] => { const expressions = [ ...scope.statements, - ...(scope.fn == null ? [] : (get(scope.fn, "params") as Node[])), + ...(get(scope.fn ?? listener, "params") as Node[]), ]; // Catch patterns can execute even when the catch body is empty. They are // absent from the shared statement list, so scan them conservatively. @@ -1004,7 +1004,7 @@ function checkListener( // defaults cannot see declarations in their own function body. Retain // enclosing candidates for both body and parameter references. const enclosingNames = new Set(names); - collectReferencedNames(scope.fn?.params, enclosingNames); + collectReferencedNames((scope.fn ?? listener).params, enclosingNames); const enclosingFunctions = new Set(); for ( let outer = scope.fn == null ? null : enclosingFunction(scope.fn); @@ -1053,7 +1053,7 @@ function checkListener( if (bindsName(pattern, name)) unknownWrites.add(name); } }; - for (const param of scope.fn?.params ?? []) + for (const param of (scope.fn ?? listener).params) invalidateIncoming(param as Node); visitAll( scope.fn?.body ?? listener.body, diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 12172d0be..31283bd70 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -464,6 +464,29 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const parameter of [ + "run = () => ctx.sendActivity(sender, inbox, activity)", + "{ run } = { run: () => ctx.sendActivity(sender, inbox, activity) }", + "[run] = [() => ctx.sendActivity(sender, inbox, activity)]", +]) { + test( + `${ruleName}: incoming root listener parameters invalidate helper shapes: ${parameter}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity, ${parameter}) => { + await run(); + run = () => [ctx.sendActivity(sender, inbox, activity)]; + await Promise.all(run()); + }); +`, + rule, + ruleName, + }), + ); +} + for (const [returned, consumer, dropped] of [ ["ctx.sendActivity(sender, inbox, activity)", "deliver();", true], ["ctx.sendActivity(sender, inbox, activity)", "await deliver();", false], From c1e2906bf79496397fea145b6f0378cffeaa0fff Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Sun, 22 Nov 2026 17:59:36 +0900 Subject: [PATCH 37/41] Discover tagged-template mutators in binding keys A tagged template invokes its tag just as a call invokes its callee. Include tagged templates in invalidation scope discovery so binding-key mutations cannot retain stale array shapes. Cover declaration, parameter, and catch keys, including an inline tag. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4637839224 Assisted-by: OpenCode:gpt-6.1-sol --- .../lint/src/rules/outbox-listener-delivery-not-awaited.ts | 6 +++++- .../src/tests/outbox-listener-delivery-not-awaited.test.ts | 4 ++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index fa304d1e4..2557ac2cd 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -958,7 +958,11 @@ function checkListener( visitAll( expression, (node) => { - if (node.type === "CallExpression" || node.type === "NewExpression") { + if ( + node.type === "CallExpression" || + node.type === "NewExpression" || + node.type === "TaggedTemplateExpression" + ) { collectReferencedNames(node, names); // An executable binding key can invoke an inline function. visitAll(node, (value) => { diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 31283bd70..503f1a3c5 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -712,6 +712,10 @@ federation.setOutboxListeners("/users/{identifier}/outbox") } for (const mutation of [ + "const replace = () => { run = finish; }; const { [replace``]: value } = {};", + "const replace = () => { run = finish; }; const invoke = ({ [replace``]: value }) => value; invoke({});", + "const replace = () => { run = finish; }; try { throw {}; } catch ({ [replace``]: value }) {}", + "const { [(() => { run = finish; })``]: value } = {};", "function Replace() { run = finish; } const { [new Replace()]: value } = {};", "function Replace() { run = finish; } const invoke = ({ [new Replace()]: value }) => value; invoke({});", "function Replace() { run = finish; } try { throw {}; } catch ({ [new Replace()]: value }) {}", From a35278f9819eb657bbba27dbb5b85434bcd6328e Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Sun, 22 Nov 2026 19:00:45 +0900 Subject: [PATCH 38/41] Discover body aliases in every invalidation scope Collect body value references for original scopes as well as scopes added during invalidation. Alias initializers can reference an enclosing mutator hidden by a flattened block-local candidate, even when calls mention only the alias. Cover const, let, and function block bindings. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4657480233 Assisted-by: OpenCode:gpt-6.1-sol --- .../src/rules/outbox-listener-delivery-not-awaited.ts | 8 +++----- .../tests/outbox-listener-delivery-not-awaited.test.ts | 3 +++ 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 2557ac2cd..978fb8d99 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -932,7 +932,7 @@ function checkListener( // possible local callees only for invalidation, not delivery diagnostics. const invalidationScopes = [...scopes]; const invalidationFunctions = new Set(scopes.map((scope) => scope.fn)); - for (const [index, scope] of invalidationScopes.entries()) { + for (const scope of invalidationScopes) { const names = new Set(); const inlineFunctions = new Set(); const expressions = invalidationExpressions(scope); @@ -996,10 +996,8 @@ function checkListener( false, ); } - if (index >= scopes.length) { - for (const statement of scope.statements) - collectReferencedNames(statement, names); - } + for (const statement of scope.statements) + collectReferencedNames(statement, names); const candidates = new Set([ ...inlineFunctions, ...[...names].flatMap((name) => scope.functionsByName.get(name) ?? []), diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 503f1a3c5..f3e7e7fa4 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -712,6 +712,9 @@ federation.setOutboxListeners("/users/{identifier}/outbox") } for (const mutation of [ + "const replace = () => { run = finish; }; function invoke() { { const replace = () => {}; } const call = replace; call(); } invoke();", + "const replace = () => { run = finish; }; function invoke() { { let replace = () => {}; } const call = replace; call(); } invoke();", + "const replace = () => { run = finish; }; function invoke() { { function replace() {} } const call = replace; call(); } invoke();", "const replace = () => { run = finish; }; const { [replace``]: value } = {};", "const replace = () => { run = finish; }; const invoke = ({ [replace``]: value }) => value; invoke({});", "const replace = () => { run = finish; }; try { throw {}; } catch ({ [replace``]: value }) {}", From 9a132a018e26d00240571f94450c60fb783fab06 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Sun, 22 Nov 2026 19:01:24 +0900 Subject: [PATCH 39/41] Discover computed-key coercion mutators A computed property key can execute a coercion hook even when its syntax is only a value reference. Include key references and inline hook functions in invalidation discovery before certifying helper shapes. Cover Symbol.toPrimitive, toString, parameter and catch keys, and an inline coercion object. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4657480237 Assisted-by: OpenCode:gpt-6.1-sol --- .../src/rules/outbox-listener-delivery-not-awaited.ts | 10 ++++++++++ .../tests/outbox-listener-delivery-not-awaited.test.ts | 5 +++++ 2 files changed, 15 insertions(+) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index 978fb8d99..bcc3f7f36 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -968,6 +968,16 @@ function checkListener( visitAll(node, (value) => { if (isFunctionLikeNode(value)) inlineFunctions.add(value); }); + } else if ( + node.type === "Property" && + get(node, "computed") === true + ) { + // Property-key coercion can invoke hooks even for a bare value. + const key = get(node, "key"); + collectReferencedNames(key, names); + visitAll(key, (value) => { + if (isFunctionLikeNode(value)) inlineFunctions.add(value); + }); } else if (node.type === "MemberExpression") { // Reads can invoke getters; destructuring targets can invoke // setters even without an AssignmentExpression at the member. diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index f3e7e7fa4..62c304fa3 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -715,6 +715,11 @@ for (const mutation of [ "const replace = () => { run = finish; }; function invoke() { { const replace = () => {}; } const call = replace; call(); } invoke();", "const replace = () => { run = finish; }; function invoke() { { let replace = () => {}; } const call = replace; call(); } invoke();", "const replace = () => { run = finish; }; function invoke() { { function replace() {} } const call = replace; call(); } invoke();", + "const key = { [Symbol.toPrimitive]() { run = finish; return 'value'; } }; const { [key]: value } = {};", + "const key = { toString() { run = finish; return 'value'; } }; const { [key]: value } = {};", + "const key = { [Symbol.toPrimitive]() { run = finish; return 'value'; } }; const invoke = ({ [key]: value }) => value; invoke({});", + "const key = { [Symbol.toPrimitive]() { run = finish; return 'value'; } }; try { throw {}; } catch ({ [key]: value }) {}", + "const { [{ toString() { run = finish; return 'value'; } }]: value } = {};", "const replace = () => { run = finish; }; const { [replace``]: value } = {};", "const replace = () => { run = finish; }; const invoke = ({ [replace``]: value }) => value; invoke({});", "const replace = () => { run = finish; }; try { throw {}; } catch ({ [replace``]: value }) {}", From e439e6deaa57845327f9d9b6c393448aea784199 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Sun, 22 Nov 2026 20:36:51 +0900 Subject: [PATCH 40/41] Restrict root helper writes to local bindings Apply the same local-binding proof to literal writes in the root listener as in nested helpers. Populate its local var names from the listener body rather than exempting every root assignment. Replacements of incoming module or enclosing bindings now invalidate helper inference. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4657667122 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 10 ++++---- ...tbox-listener-delivery-not-awaited.test.ts | 23 +++++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index bcc3f7f36..f962f0920 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -1077,9 +1077,10 @@ function checkListener( false, ); const localFunctionNames = new Set(); - if (scope.fn != null) { + { + const scopeFunction = scope.fn ?? listener; for (const name of helperNames) { - if (shadowsName(scope.fn, name)) localFunctionNames.add(name); + if (shadowsName(scopeFunction, name)) localFunctionNames.add(name); } // var bindings belong to the whole function, including nested blocks. for (const statement of scope.statements) { @@ -1089,7 +1090,7 @@ function checkListener( if ( node.type !== "VariableDeclarator" || get(parentOf(node), "kind") !== "var" || - variableRegion(node) !== scope.fn?.body + variableRegion(node) !== scopeFunction.body ) return; for (const name of helperNames) { @@ -1160,8 +1161,7 @@ function checkListener( scope.functionsByName .get(target.name) ?.includes(unwrap(value) as FunctionLikeNode) && - (scope.fn == null || - localFunctionNames.has(target.name) || + (localFunctionNames.has(target.name) || shadowsName( assignmentRegion(node, target.name) ?? node, target.name, diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index 62c304fa3..ffd731fb3 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -438,6 +438,29 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const binding of [ + "let run = async (ctx, activity) => { await ctx.sendActivity(sender, inbox, activity); };", + "async function run(ctx, activity) { await ctx.sendActivity(sender, inbox, activity); }", +]) { + test( + `${ruleName}: root literal writes invalidate enclosing bindings: ${binding}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +${binding} +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + await run(ctx, activity); + run = () => [ctx.sendActivity(sender, inbox, activity)]; + await Promise.all(run()); + }); +`, + rule, + ruleName, + }), + ); +} + for (const declaration of [ "function deliver() { return ctx.sendActivity(sender, inbox, activity); }", "var deliver = () => ctx.sendActivity(sender, inbox, activity);", From 3f077ea7345da52bf7b7deb853ade2745cffc647 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Sun, 22 Nov 2026 20:37:28 +0900 Subject: [PATCH 41/41] Respect static variable scopes in shadow checks Compare helper variable regions instead of only enclosing functions when checking var shadows. Static blocks own their var bindings and can hide an outer delivery helper. Normalize Deno's wrapped static-block body when reading declarations. Cover non-delivering inner var helpers. https://github.com/fedify-dev/fedify/pull/1446#discussion_r4657667126 Assisted-by: OpenCode:gpt-6.1-sol --- .../outbox-listener-delivery-not-awaited.ts | 16 +++++--- ...tbox-listener-delivery-not-awaited.test.ts | 37 +++++++++++++++++++ 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts index f962f0920..c02122e79 100644 --- a/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts +++ b/packages/lint/src/rules/outbox-listener-delivery-not-awaited.ts @@ -210,9 +210,13 @@ function shadowsName(region: Node, name: string, lexicalOnly = false): boolean { if (region.type === "CatchClause") { return bindsName(asNode(get(region, "param")), name); } + // Deno wraps a static block's statement list in a BlockStatement. + const body = get(region, "body"); const declarations: Node[] = region.type === "BlockStatement" || region.type === "StaticBlock" - ? (get(region, "body") as Node[]) + ? Array.isArray(body) + ? body + : (get(asNode(body), "body") as Node[]) : region.type === "SwitchStatement" ? (get(region, "cases") as Node[]).flatMap( (clause) => get(clause, "consequent") as Node[], @@ -317,7 +321,7 @@ function helpersAt( : variableRegion(fn); if (region?.type === "SwitchCase") region = parentOf(region); if (region == null) return []; - const functionScope = enclosingFunction(fn); + const variableScope = variableRegion(fn); let current: Node | null = node; while (current != null && current !== region) { // The discriminant executes before the switch's case bindings exist. @@ -326,13 +330,15 @@ function helpersAt( get(region, "discriminant") === current ) return []; - // A var declaration in this function initializes the same binding, - // even inside a block or loop head. In another function it can shadow. + // A var declaration in the same variable scope initializes the same + // binding. Another function or static block can shadow it. if ( shadowsName( current, node.name, - enclosingFunction(current) === functionScope, + (current.type === "StaticBlock" + ? current + : variableRegion(current)) === variableScope, ) ) return []; diff --git a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts index ffd731fb3..0309ab41f 100644 --- a/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts +++ b/packages/lint/src/tests/outbox-listener-delivery-not-awaited.test.ts @@ -438,6 +438,43 @@ federation.setOutboxListeners("/users/{identifier}/outbox") ); } +for (const [outer, inner] of [ + [ + "const run = () => [ctx.sendActivity(sender, inbox, activity)];", + "var run = () => [];", + ], + [ + "function run() { return [ctx.sendActivity(sender, inbox, activity)]; }", + "var run = () => [];", + ], + [ + "const run = () => [ctx.sendActivity(sender, inbox, activity)];", + "var run = async () => {};", + ], +] as const) { + test( + `${ruleName}: static block vars shadow outer helpers: ${outer} ${inner}`, + lintTest({ + code: ` +import { Activity } from "@fedify/vocab"; +federation.setOutboxListeners("/users/{identifier}/outbox") + .on(Activity, async (ctx, activity) => { + ${outer} + await Promise.all(run()); + class Holder { + static { + ${inner} + run(); + } + } + }); +`, + rule, + ruleName, + }), + ); +} + for (const binding of [ "let run = async (ctx, activity) => { await ctx.sendActivity(sender, inbox, activity); };", "async function run(ctx, activity) { await ctx.sendActivity(sender, inbox, activity); }",