Skip to content

feat: twitter search api - #1852

Merged
dangeredwolf merged 8 commits into
mainfrom
search-api
Mar 16, 2026
Merged

dangeredwolf merged 8 commits into
mainfrom
search-api

Conversation

@dangeredwolf

@dangeredwolf dangeredwolf commented Mar 13, 2026 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • Added a /2/search API powered by Twitter search, returning standardized results with top/bottom cursors.
  • Bug Fixes / Improvements

    • More robust handling of varied timeline instruction shapes and safer nested content access to reduce missing-data errors.
    • Improved pagination and request parameter validation.
  • Tests

    • Added API tests and expanded test harness with search timeline mocks.

@dangeredwolf dangeredwolf self-assigned this Mar 13, 2026
@coderabbitai

coderabbitai Bot commented Mar 13, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

Pull request was closed or merged during review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: e60ad11c-14c2-4614-9ef3-c744b6c99617

📥 Commits

Reviewing files that changed from the base of the PR and between 9f3b45d and 6e09f00.

📒 Files selected for processing (4)
  • src/providers/twitter/conversation.ts
  • src/providers/twitter/processor.ts
  • src/providers/twitter/search.ts
  • src/realms/api/routes/twitter.ts
💤 Files with no reviewable changes (1)
  • src/providers/twitter/processor.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/realms/api/routes/twitter.ts
  • src/providers/twitter/search.ts

📝 Walkthrough

Walkthrough

Adds a GraphQL-based Twitter search flow: new SearchTimelineQuery and search provider, timeline instruction types replaced with a discriminated union, conversation processing updated to accept TimelineInstruction[], new /2/search route and handler, APISearchResults type, tests, and test-harness mock support.

Changes

Cohort / File(s) Summary
Timeline Types
src/types/vendor/twitter.d.ts
Replaced prior TimelineInstruction shape with a discriminated union (TimelineAddEntriesInstruction, TimelineAddModulesInstruction, TimelineTerminateTimelineInstruction, TimelineReplaceEntryInstruction), added TwitterSearchTimelineResponse, and changed TweetDetailResponse.instructions to TimelineInstruction[].
Conversation Processing
src/providers/twitter/conversation.ts
Updated processResponse signature from ThreadInstruction[] to TimelineInstruction[] and added guarded casts/optional chaining to safely read entries, moduleItems, content, and nested tweet_results.
GraphQL Queries
src/providers/twitter/graphql/queries.ts
Added SearchTimelineQuery: GraphQLQuery (GET) with queryId/queryName, default variables, and an expanded features flags object.
Search Provider
src/providers/twitter/search.ts
New searchAPI(query, feed, count, cursor, c) implementation: executes SearchTimelineQuery, processes TimelineInstruction[] into APITwitterStatus entries and cursors, builds statuses concurrently, returns APISearchResults with HTTP-like codes and logs errors.
API Routing & Handler
src/realms/api/router.ts, src/realms/api/routes/twitter.ts
Registered GET /2/search route and added searchAPIRequest handler (param parsing/validation, clamps count, invokes searchAPI, forwards headers). Minor formatting tweak to shouldIncludeAboutAccount.
Public Types
src/types/types.d.ts
Added APISearchResults interface (code, results[], cursor top/bottom); removed export from three Mastodon V1 interfaces and expanded ActivityMediaAttachment fields.
Tests & Test Harness
test/api.search.test.ts, test/helpers/harness.ts
Added Vitest tests for /2/search and extended test harness with SearchTimeline mock loader (dynamic import of ../mocks/SearchTimeline/<sanitized_query>.json with fallback).
Processor Cleanup
src/providers/twitter/processor.ts
Removed several @ts-expect-error comments around legacy video.variants assignments; no logic change.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client
    participant Router as Router
    participant Handler as Handler
    participant Provider as SearchProvider
    participant GraphQL as GraphQL
    participant Processor as Processor

    Client->>Router: GET /2/search?q=...&feed=...&count=...&cursor=...
    Router->>Handler: route to searchAPIRequest
    Handler->>Handler: validate & parse params
    Handler->>Provider: searchAPI(query, feed, count, cursor, c)
    Provider->>GraphQL: execute SearchTimelineQuery (GET)
    GraphQL-->>Provider: timeline (TimelineInstruction[])
    Provider->>Processor: processSearchInstructions(instructions)
    Processor-->>Provider: statuses + cursors
    Provider-->>Handler: APISearchResults (code, results, cursor)
    Handler->>Client: HTTP response (status, body)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I hopped through timelines, fetched each thread,

GraphQL carrots and cursors snug in my shed,
/2/search blossoms, results tidy and near,
Little rabbit cheers — new queries bring cheer,
A nibble of tweets for devs to hold dear.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: twitter search api' accurately summarizes the main change—adding a new Twitter search API feature across multiple files including search endpoint, routes, and GraphQL queries.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch search-api
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Comment thread src/providers/twitter/search.ts Dismissed

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (3)
src/providers/twitter/search.ts (2)

154-157: Simplify Promise creation.

new Promise(resolve => resolve(null)) can be simplified to Promise.resolve(null).

♻️ Proposed fix
         } catch (e) {
           console.error('Error building status', e);
-          return new Promise(resolve => resolve(null));
+          return Promise.resolve(null);
         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/providers/twitter/search.ts` around lines 154 - 157, The catch block in
the status-building code currently returns a manually created promise via new
Promise(resolve => resolve(null)); simplify this by returning
Promise.resolve(null) instead; locate the catch in the status builder (the catch
handling errors while building status in src/providers/twitter/search.ts, e.g.,
the catch block that logs "Error building status") and replace the manual
Promise construction with Promise.resolve(null) to make the code clearer and
more concise.

132-132: Consider removing or reducing verbose response logging.

Logging the entire GraphQL response with JSON.stringify(response) may include user data (tweet content, usernames) in production logs. Consider removing this or logging only essential debug information.

🔒 Proposed fix
-    console.log('response', JSON.stringify(response));
+    // console.log('response', JSON.stringify(response)); // Enable for debugging only
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/providers/twitter/search.ts` at line 132, Remove the verbose console.log
call that prints the full GraphQL response (the line console.log('response',
JSON.stringify(response))) to avoid leaking user data; either delete it or
replace it with a safe, minimal log (e.g., log a summary like response.status,
response.meta, or the count of items) or use a debug-level logger that only runs
when a debug flag is enabled and redacts sensitive fields (tweet text,
usernames, ids) before logging.
src/types/vendor/twitter.d.ts (1)

703-721: Consider adding TimelineReplaceEntry to the union.

The TimelineInstruction union may be incomplete for search API responses. The code in src/providers/twitter/search.ts handles a TimelineReplaceEntry instruction type for cursor updates during pagination, but this type is not defined in the union.

If Twitter's search API returns this instruction type, consider adding it:

♻️ Proposed addition
 type TimelineInstruction =
   | TimelineAddEntriesInstruction
   | TimelineTerminateTimelineInstruction
-  | TimelineAddModulesInstruction;
+  | TimelineAddModulesInstruction
+  | TimelineReplaceEntryInstruction;

+type TimelineReplaceEntryInstruction = {
+  type: 'TimelineReplaceEntry';
+  entry: {
+    content: GraphQLTimelineCursor;
+  };
+};
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/types/vendor/twitter.d.ts` around lines 703 - 721, Add a new
TimelineReplaceEntry instruction type and include it in the TimelineInstruction
union: define a TimelineReplaceEntryInstruction type with type:
'TimelineReplaceEntry' and fields matching how src/providers/twitter/search.ts
reads cursor updates (e.g., the entry payload/key(s) used for pagination such as
cursor/entryId/moduleItems or similar), then add TimelineReplaceEntryInstruction
to the union alongside TimelineAddEntriesInstruction,
TimelineAddModulesInstruction, and TimelineTerminateTimelineInstruction so the
type definitions align with the code that expects 'TimelineReplaceEntry'.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/providers/twitter/conversation.ts`:
- Around line 314-324: The code reads entryType from
content.itemContent?.tweet_results.result?.__typename but then pushes
content.itemContent?.tweet_results.result (or .result.tweet) without verifying
result exists, which can add undefined to bucket.statuses; modify the logic in
the block around entryType to first capture const result =
content.itemContent?.tweet_results.result and if (result) { if (entryType ===
'Tweet') bucket.statuses.push(result as GraphQLTwitterStatus); if (entryType ===
'TweetWithVisibilityResults' && result.tweet) bucket.statuses.push(result.tweet
as GraphQLTwitterStatus); } so you only push when result (and result.tweet) are
defined.

In `@src/providers/twitter/graphql/queries.ts`:
- Line 351: Remove the trailing comma after the querySource property in the
object literal (the line containing "querySource: 'typed_query'") so the
property is the last entry without a comma; update the object in the GraphQL
queries file where querySource is defined (search for the querySource property
in the queries.ts snippet) to satisfy ESLint formatting rules.

In `@src/providers/twitter/search.ts`:
- Around line 42-57: The branch checking for instruction.type ===
'TimelineReplaceEntry' inside the instructions?.forEach (the instruction
variable in src/providers/twitter/search.ts) is dead because
TimelineReplaceEntry is not part of the TimelineInstruction union in
src/types/vendor/twitter.d.ts; fix by either removing this unreachable block
(delete the TimelineReplaceEntry check and its cursor-pushing logic) or add a
proper TimelineReplaceEntry variant to the TimelineInstruction union in
src/types/vendor/twitter.d.ts (model the new type to include entry?: { content?:
{ __typename: 'TimelineTimelineCursor'; /* cursor fields */ } } so the existing
code can type-check and push cursors correctly).

In `@src/types/types.d.ts`:
- Line 337: The interfaces ActivityStatus, ActivityAccount, and
ActivityMediaAttachment are missing the export keyword which breaks TypeScript
imports; fix by updating their declarations in types.d.ts to be exported (e.g.,
change the declarations for ActivityStatus, ActivityAccount, and
ActivityMediaAttachment to use "export interface ...") and ensure the export
style matches other exported types in the file so imports in
src/embed/activity.ts and test/activity.test.ts resolve correctly.

---

Nitpick comments:
In `@src/providers/twitter/search.ts`:
- Around line 154-157: The catch block in the status-building code currently
returns a manually created promise via new Promise(resolve => resolve(null));
simplify this by returning Promise.resolve(null) instead; locate the catch in
the status builder (the catch handling errors while building status in
src/providers/twitter/search.ts, e.g., the catch block that logs "Error building
status") and replace the manual Promise construction with Promise.resolve(null)
to make the code clearer and more concise.
- Line 132: Remove the verbose console.log call that prints the full GraphQL
response (the line console.log('response', JSON.stringify(response))) to avoid
leaking user data; either delete it or replace it with a safe, minimal log
(e.g., log a summary like response.status, response.meta, or the count of items)
or use a debug-level logger that only runs when a debug flag is enabled and
redacts sensitive fields (tweet text, usernames, ids) before logging.

In `@src/types/vendor/twitter.d.ts`:
- Around line 703-721: Add a new TimelineReplaceEntry instruction type and
include it in the TimelineInstruction union: define a
TimelineReplaceEntryInstruction type with type: 'TimelineReplaceEntry' and
fields matching how src/providers/twitter/search.ts reads cursor updates (e.g.,
the entry payload/key(s) used for pagination such as cursor/entryId/moduleItems
or similar), then add TimelineReplaceEntryInstruction to the union alongside
TimelineAddEntriesInstruction, TimelineAddModulesInstruction, and
TimelineTerminateTimelineInstruction so the type definitions align with the code
that expects 'TimelineReplaceEntry'.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 147ceafa-002f-4671-98b6-23fb30838f28

📥 Commits

Reviewing files that changed from the base of the PR and between 41b7622 and 9962402.

📒 Files selected for processing (7)
  • src/providers/twitter/conversation.ts
  • src/providers/twitter/graphql/queries.ts
  • src/providers/twitter/search.ts
  • src/realms/api/router.ts
  • src/realms/api/routes/twitter.ts
  • src/types/types.d.ts
  • src/types/vendor/twitter.d.ts

Comment thread src/providers/twitter/conversation.ts Resolved
Comment thread src/providers/twitter/search.ts Resolved
Comment thread src/types/types.d.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
test/api.search.test.ts (1)

43-70: Tests verify parameter acceptance but not behavioral effect.

Both tests confirm the endpoint accepts feed and count parameters without error, but they don't verify these parameters influence the response. Since the harness returns identical mock data regardless of parameter values, distinguishing behavior would require either:

  • Multiple mocks keyed by the product variable (derived from feed)
  • Asserting response.results.length <= count when count is passed

This is fine as acceptance tests, but consider expanding coverage later to validate parameter effects end-to-end.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/api.search.test.ts` around lines 43 - 70, The tests "API search accepts
feed parameter" and "API search accepts count parameter" only check acceptance;
update them to verify behavior: for the count test (test name "API search
accepts count parameter") assert that response.results.length is <= the
requested count (e.g., 10) and/or exactly equals when your mock supports that;
for the feed test (test name "API search accepts feed parameter") either make
the harness return different mock responses keyed by the product variable
(derived from the feed query) so you can assert different response contents for
feed=top vs feed=latest, or assert that the returned response matches the
specific mock tied to product; reference APISearchResults, harness and the
product variable when implementing these assertions or mock-keying changes.
test/helpers/harness.ts (1)

105-122: Static analysis flags unscoped switch declarations, but this follows existing file patterns.

Biome correctly identifies that rawQuery and searchFilename are declared without block scope (lines 106-107). However, all other cases in this switch (lines 23, 34, 45, 56, etc.) use the same pattern. While wrapping the case body in braces { } would be cleaner, refactoring should apply to all cases for consistency rather than just this one.

The fallback response structure correctly matches the expected path data.search_by_raw_query.search_timeline.timeline.instructions as validated by the search provider.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/helpers/harness.ts` around lines 105 - 122, The switch case
'SearchTimeline' declares rawQuery and searchFilename without block scope which
triggers static analysis; wrap the case body in braces (i.e., case
'SearchTimeline': { ... } break;) so rawQuery and searchFilename are
block-scoped, and apply the same bracing pattern consistently to the other
switch cases in this file (refer to the variables rawQuery and searchFilename
and the case 'SearchTimeline' in test/helpers/harness.ts) to keep declarations
scoped and satisfy the linter.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@test/api.search.test.ts`:
- Around line 43-70: The tests "API search accepts feed parameter" and "API
search accepts count parameter" only check acceptance; update them to verify
behavior: for the count test (test name "API search accepts count parameter")
assert that response.results.length is <= the requested count (e.g., 10) and/or
exactly equals when your mock supports that; for the feed test (test name "API
search accepts feed parameter") either make the harness return different mock
responses keyed by the product variable (derived from the feed query) so you can
assert different response contents for feed=top vs feed=latest, or assert that
the returned response matches the specific mock tied to product; reference
APISearchResults, harness and the product variable when implementing these
assertions or mock-keying changes.

In `@test/helpers/harness.ts`:
- Around line 105-122: The switch case 'SearchTimeline' declares rawQuery and
searchFilename without block scope which triggers static analysis; wrap the case
body in braces (i.e., case 'SearchTimeline': { ... } break;) so rawQuery and
searchFilename are block-scoped, and apply the same bracing pattern consistently
to the other switch cases in this file (refer to the variables rawQuery and
searchFilename and the case 'SearchTimeline' in test/helpers/harness.ts) to keep
declarations scoped and satisfy the linter.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 188ede24-35c1-44b6-bc86-7097a65bdf2e

📥 Commits

Reviewing files that changed from the base of the PR and between b4f2ef0 and f01cc48.

📒 Files selected for processing (4)
  • src/providers/twitter/search.ts
  • test/api.search.test.ts
  • test/helpers/harness.ts
  • test/mocks/SearchTimeline/neo.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/providers/twitter/search.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
src/providers/twitter/search.ts (3)

146-149: Simplify promise creation.

new Promise(resolve => resolve(null)) can be replaced with Promise.resolve(null).

♻️ Simplified fix
         } catch (e) {
           console.error('Error building status', e);
-          return new Promise(resolve => resolve(null));
+          return Promise.resolve(null);
         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/providers/twitter/search.ts` around lines 146 - 149, In the catch block
that logs "Error building status" (inside the function that builds statuses in
src/providers/twitter/search.ts, e.g., buildStatus or the function wrapping that
console.error), replace the manual promise creation new Promise(resolve =>
resolve(null)) with the simpler Promise.resolve(null); this reduces allocation
and expresses intent directly.

77-80: Consider adding a type guard to avoid as unknown as double-cast.

The double cast through unknown suggests the type definitions don't fully capture this code path. A type guard would be safer and more self-documenting.

♻️ Suggested type guard
+const isTimelineCursor = (content: unknown): content is GraphQLTimelineCursor =>
+  (content as GraphQLTimelineCursor)?.__typename === 'TimelineTimelineCursor';

 // In the forEach:
-} else if (content.__typename === 'TimelineTimelineCursor') {
-  // In search timeline, cursors appear directly as entry content rather than
-  // nested inside a TimelineTimelineItem wrapper as seen in TweetDetail
-  cursors.push(content as unknown as GraphQLTimelineCursor);
+} else if (isTimelineCursor(content)) {
+  // In search timeline, cursors appear directly as entry content rather than
+  // nested inside a TimelineTimelineItem wrapper as seen in TweetDetail
+  cursors.push(content);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/providers/twitter/search.ts` around lines 77 - 80, Replace the unsafe
double-cast by implementing a type guard that checks content.__typename ===
'TimelineTimelineCursor' and narrows content to GraphQLTimelineCursor before
pushing; create a predicate function (e.g., isGraphQLTimelineCursor(obj): obj is
GraphQLTimelineCursor) and use it in the branch that currently does
cursors.push(content as unknown as GraphQLTimelineCursor) so the compiler
understands the type without casting and the intent is documented.

137-138: Variable c shadows the outer Context parameter.

The callback parameter c in cursors.find(c => ...) shadows the c: Context from line 105. While this works, it reduces readability.

♻️ Rename the callback parameter
-  const topCursor = cursors.find(c => c.cursorType === 'Top')?.value ?? null;
-  const bottomCursor = cursors.find(c => c.cursorType === 'Bottom')?.value ?? null;
+  const topCursor = cursors.find(cursor => cursor.cursorType === 'Top')?.value ?? null;
+  const bottomCursor = cursors.find(cursor => cursor.cursorType === 'Bottom')?.value ?? null;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/providers/twitter/search.ts` around lines 137 - 138, The callback
parameter in the cursors.find calls shadows the outer Context parameter named
`c`; rename the inner parameter to a descriptive name (e.g., `cursor` or `cur`)
in both expressions that compute `topCursor` and `bottomCursor` so the code
reads `cursors.find(cursor => cursor.cursorType === 'Top')` and
`cursors.find(cursor => cursor.cursorType === 'Bottom')`, preserving the
existing null coalescing behavior and avoiding shadowing of the `c: Context`
variable.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/providers/twitter/search.ts`:
- Around line 146-149: In the catch block that logs "Error building status"
(inside the function that builds statuses in src/providers/twitter/search.ts,
e.g., buildStatus or the function wrapping that console.error), replace the
manual promise creation new Promise(resolve => resolve(null)) with the simpler
Promise.resolve(null); this reduces allocation and expresses intent directly.
- Around line 77-80: Replace the unsafe double-cast by implementing a type guard
that checks content.__typename === 'TimelineTimelineCursor' and narrows content
to GraphQLTimelineCursor before pushing; create a predicate function (e.g.,
isGraphQLTimelineCursor(obj): obj is GraphQLTimelineCursor) and use it in the
branch that currently does cursors.push(content as unknown as
GraphQLTimelineCursor) so the compiler understands the type without casting and
the intent is documented.
- Around line 137-138: The callback parameter in the cursors.find calls shadows
the outer Context parameter named `c`; rename the inner parameter to a
descriptive name (e.g., `cursor` or `cur`) in both expressions that compute
`topCursor` and `bottomCursor` so the code reads `cursors.find(cursor =>
cursor.cursorType === 'Top')` and `cursors.find(cursor => cursor.cursorType ===
'Bottom')`, preserving the existing null coalescing behavior and avoiding
shadowing of the `c: Context` variable.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: ef6619aa-9634-4413-bd7d-1af8b19df776

📥 Commits

Reviewing files that changed from the base of the PR and between f01cc48 and 9f3b45d.

📒 Files selected for processing (2)
  • src/providers/twitter/search.ts
  • src/types/vendor/twitter.d.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/providers/twitter/conversation.ts (1)

291-301: 🛠️ Refactor suggestion | 🟠 Major

Replace @ts-expect-error with explicit discriminated union narrowing.

Using @ts-expect-error to suppress type checking here masks a real limitation in how TypeScript narrows the discriminated union. Explicit property access after type narrowing is the cleaner, safer approach that maintains type safety. Also add a default parameter to handle undefined gracefully at the call site.

♻️ Proposed refactor
-const processResponse = (instructions: TimelineInstruction[]): GraphQLProcessBucket => {
+const processResponse = (instructions: TimelineInstruction[] = []): GraphQLProcessBucket => {
   const bucket: GraphQLProcessBucket = {
     statuses: [],
     allStatuses: [],
     cursors: []
   };
-  instructions?.forEach?.(instruction => {
-    if (instruction.type === 'TimelineAddEntries' || instruction.type === 'TimelineAddToModule') {
-      // `@ts-expect-error` Use entries or moduleItems depending on the type
-      (instruction?.entries ?? instruction?.moduleItems)?.forEach(_entry => {
+  instructions.forEach(instruction => {
+    const entries =
+      instruction.type === 'TimelineAddEntries'
+        ? instruction.entries
+        : instruction.type === 'TimelineAddToModule'
+          ? instruction.moduleItems
+          : null;
+    if (!entries) return;
+    entries.forEach(_entry => {
         const entry = _entry as
           | GraphQLTimelineTweetEntry
           | GraphQLConversationThread
           | GraphQLModuleTweetEntry;
         const content =
           (entry as GraphQLModuleTweetEntry)?.item ?? (entry as GraphQLTimelineTweetEntry)?.content;
@@
-      });
-    }
+    });
   });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/providers/twitter/conversation.ts` around lines 291 - 301, The code uses
`@ts-expect-error` to access either entries or moduleItems on TimelineInstruction;
instead, update processResponse to explicitly narrow the discriminated union by
checking instruction.type (e.g., in the branch for 'TimelineAddEntries' access
instruction.entries, and in the 'TimelineAddToModule' branch access
instruction.moduleItems) before iterating, removing the `@ts-expect-error`; also
add a default parameter for instructions (e.g., instructions:
TimelineInstruction[] = []) or guard at the top so undefined is handled safely;
refer to the function processResponse and the
TimelineInstruction/GraphQLProcessBucket symbols when making these changes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@src/providers/twitter/conversation.ts`:
- Around line 291-301: The code uses `@ts-expect-error` to access either entries
or moduleItems on TimelineInstruction; instead, update processResponse to
explicitly narrow the discriminated union by checking instruction.type (e.g., in
the branch for 'TimelineAddEntries' access instruction.entries, and in the
'TimelineAddToModule' branch access instruction.moduleItems) before iterating,
removing the `@ts-expect-error`; also add a default parameter for instructions
(e.g., instructions: TimelineInstruction[] = []) or guard at the top so
undefined is handled safely; refer to the function processResponse and the
TimelineInstruction/GraphQLProcessBucket symbols when making these changes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 10872202-9fdd-470f-b040-17ca5604ddfd

📥 Commits

Reviewing files that changed from the base of the PR and between 9f3b45d and dee8455.

📒 Files selected for processing (1)
  • src/providers/twitter/conversation.ts

@dangeredwolf dangeredwolf left a comment •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reviewed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants