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..c9298e856 100644 --- a/docs/manual/lint.md +++ b/docs/manual/lint.md @@ -1017,13 +1017,22 @@ 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. + An intermediate `await` preserves the array: + `await Promise.all(await deliverAll())` and storing `await deliverAll()` + 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. - 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..49de6aae2 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 }; @@ -152,6 +156,149 @@ 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, lexicalOnly = false): 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" + ? (!lexicalOnly || get(declaration, "kind") !== "var") && + (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), + ); +} + +/** 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 + * 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, + 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; + while ( + parentOf(declaration) != null && + TRANSPARENT_WRAPPERS.has(parentOf(declaration)!.type) + ) { + 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 = + fn.type === "FunctionDeclaration" + ? parentOf(fn) + : variable?.type === "VariableDeclaration" && + get(variable, "kind") !== "var" + ? parentOf(variable) + : declarator?.type === "AssignmentExpression" + ? 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) { + // 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 []; + } + return helpers; +} + /** The names an object pattern binds the delivery methods to. */ function deliveryAliasesOf(pattern: Node, out: Set): void { if (pattern.type !== "ObjectPattern") return; @@ -248,13 +395,25 @@ 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, + 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" || 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"); } @@ -278,7 +437,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 +454,21 @@ function returnedOutcome( function returnedContainerOutcome( fn: FunctionLikeNode | null, analysis: Analysis, + shape: Shape, ): Outcome { - return fn === analysis.listener ? DROPPED : HANDLED; + 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; } /** Follows the value of `expression` up through its parents to where it ends up. */ @@ -320,20 +492,35 @@ 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" ? 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 +669,194 @@ 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, + unknownWrites: ReadonlySet, +): { + 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 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. + 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, @@ -490,6 +865,122 @@ 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) { + 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); + if ( + (parent?.type === "ForOfStatement" || + parent?.type === "ForInStatement") && + get(parent, "right") === statement + ) { + const target = asNode(get(parent, "left")); + 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); + } + } + } + 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" + ) + 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)) && + // 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) { + if (bindsName(target, name)) unknownWrites.add(name); + } + }, + false, + ); + } + } + const targets = findDeliveryTargets(listener, scopes); if (targets.contextName == null && targets.aliases.size === 0) return; @@ -509,6 +1000,11 @@ function checkListener( const mentioned = new Set(); collectReferencedNames(listener.body, mentioned, true); const analysis: Analysis = { listener, mentioned }; + const { shapes, arrayInvolved } = helperReturnShapes( + scopes, + isDeliveryCall, + unknownWrites, + ); const callsByScope = scopes.map((scope) => { const calls: CallExpression[] = []; @@ -523,16 +1019,47 @@ 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 carriesArray = (helpers: readonly FunctionLikeNode[]): boolean => + helpers.some((fn) => carryingArrays.has(fn)) && + helpers.every((fn) => shapes.get(fn) === "promises"); + 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; - const helpers = scope.functionsByName.get(callee.name); - return helpers?.some((helper) => carrying.has(helper)) ?? false; + const helpers = isFunctionLikeNode(callee) + ? [callee] + : helpersAt(callee, scope, unknownWrites); + if (helpers.length === 0) return null; + if (carriesCompletion(helpers)) return "promise"; + if (carriesArray(helpers)) return "promises"; + 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 +1069,33 @@ 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 = helpersAt(arg, scope, unknownWrites); + const shape = carriesCompletion(helpers) + ? "promise" + : carriesArray(helpers) + ? "promises" + : null; + if (shape == null) continue; + const outcome = callbackResultOutcome(call, analysis, arg, shape); + if (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 +1109,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); } } @@ -577,7 +1124,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, + ); } } @@ -587,9 +1141,16 @@ 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 || !held.some((fn) => carrying.has(fn))) continue; - if (callbackResultOutcome(call, analysis).fate === "dropped") { + const held = helpersAt(arg, scope, unknownWrites); + 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 c2fd671f1..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 @@ -1,10 +1,799 @@ +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};`], + [ + "array IIFE", + `const deliverAll = () => (() => [${arrayHelperDelivery}])();`, + ], + [ + "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}; });`, + ], + [ + "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], + ["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], + [ + "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 [ + [ + "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], + [ + "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}; }`, + "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" } : {}), + }), + ); +} + +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 }", + "{ 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; }", + "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)]; }", +]) { + 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", + }), +); + +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, + }), + ); +} + +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();", + "({ 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}`, + 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); })()", + "((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") + .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", `