Skip to content

feat: publish API v2 as OpenAPI spec - #1874

Merged
dangeredwolf merged 12 commits into
mainfrom
openapi
Mar 26, 2026
Merged

dangeredwolf merged 12 commits into
mainfrom
openapi

Conversation

@dangeredwolf

@dangeredwolf dangeredwolf commented Mar 24, 2026 •

Copy link
Copy Markdown
Member

Resolves #1735

When merged, https://api.fxtwitter.com/2/openapi.json returns OpenAPI 3 spec

Internal types are mostly derived from this new specification as well

Summary by CodeRabbit

  • New Features

    • v2 API now exposes an OpenAPI 3.0 document and registers v2 routes with schema-driven contracts and validation.
  • Bug Fixes

    • /2/hit and /2/go return explicit 204 for invalid/missing URLs.
    • oEmbed responses use JSON and proper headers.
    • v2 endpoints enforce validated query params and consistently return 400 for invalid/empty inputs.
  • Chores

    • Moved many types/schemas to schema-backed modules and tightened typings.
  • Tests

    • Added OpenAPI spec test and updated v2 endpoint tests.

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

coderabbitai Bot commented Mar 24, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds OpenAPI/Zod v2 support: new Zod schemas and types, OpenAPI-aware router and validation hook, typed route definitions and docs endpoint, explicit /2/hit and /2/go 204 handling, many runtime imports converted to type-only, and tests updated for OpenAPI output and validation.

Changes

Cohort / File(s) Summary
Package manifest
package.json
Added zod and @hono/zod-openapi; adjusted @typescript-eslint devDependency entries.
OpenAPI core & docs
src/realms/api/router.ts, src/realms/api/openapi-validation-hook.ts
Router switched to OpenAPIHono with apiOpenapiValidationHook as defaultHook; added GET /2/openapi.json.
Route definitions (new)
src/realms/api/routes.ts
New file: Zod/OpenAPI route definitions for v2 endpoints (params, queries, coercion, defaults, response schemas).
Schemas (new, large)
src/realms/api/schemas.ts
New comprehensive Zod schemas and exported TS types (recursive APITwitterStatus, media, user, thread, search, trends, error shapes).
Validation + handlers
src/realms/api/routes/twitter.ts, src/realms/api/routes/oembed.ts, src/realms/api/hit.ts
Handlers typed as RouteHandler<typeof ...V2Route> using c.req.valid(...); oembed returns c.json with API headers; hit/go now try-parse URL and return 204 on invalid.
Type surface & globals
src/types/apiStatus.ts, src/types/types.d.ts, tsconfig.json
Added provider-agnostic APIStatus types; .d.ts refactored to import API types from schemas/status modules; removed @sentry/integrations from global types.
Widespread type-only imports
src/embed/*, src/helpers/*, src/providers/*, src/render/*, test/*
Converted many APITwitterStatus and related imports to import type from src/realms/api/schemas; small typing adjustments across helpers/providers/renderers/tests.
Providers & processors
src/providers/twitter/*, src/providers/bsky/*, src/providers/tiktok/*
Minor control-flow/typing tweaks: local variable initializations adjusted, some unused imports removed, and explicit return/shape annotations added.
Tests & mocks
test/api.openapi.test.ts, test/*, test/mocks/*
Added test for /2/openapi.json, updated search/trends tests to reflect validation behavior, many tests switched to type-only imports; reformatted a JSON mock.
Utilities & misc
src/helpers/*.ts, src/helpers/article.ts, src/helpers/utils.ts, src/worker.ts
Minor API and typing fixes (withTimeout error cause, Draft.js entity guards), Sentry integration import simplified to toucan-js.

Sequence Diagram(s)

sequenceDiagram
  participant Client as Client
  participant Router as OpenAPIHono (router)
  participant Hook as apiOpenapiValidationHook
  participant Schemas as Zod Schemas
  participant Handler as Route Handler

  Client->>Router: HTTP request (e.g. GET /2/status/{id})
  Router->>Schemas: lookup route metadata & schema
  Router->>Hook: run defaultHook (validation)
  Hook->>Schemas: validate params/query
  Schemas-->>Hook: validation success / issues
  alt validation fails
    Hook-->>Client: 400 JSON { code:400, message }
  else validation succeeds
    Router->>Handler: invoke with validated input
    Handler->>Schemas: shape/serialize response
    Handler-->>Client: HTTP JSON response (200 / 4xx / 5xx)
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 I hopped through schemas, neat and spry,
Zod stitched the inputs, OpenAPI the sky.
Routes now validate, handlers behave,
I left a tiny spec for folks who crave.
🥕

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning Several changes appear unrelated to OpenAPI spec publication: dependency downgrades, URL validation logic in hit.ts, error handling improvements in various files, and Sentry integration updates. Review and isolate changes unrelated to OpenAPI spec publication (dependency version changes, hit.ts URL handling, error handling, Sentry updates) into separate PRs for clarity.
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 (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: publish API v2 as OpenAPI spec' clearly and concisely describes the main objective of the PR, which is to expose the API v2 as an OpenAPI specification.
Linked Issues check ✅ Passed The PR implements OpenAPI support via Zod schemas, route definitions, and OpenAPI endpoint. Core requirements from #1735 are met: OpenAPI spec generation, TypeScript type generation, and API documentation enabled.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch openapi

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.

@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: 7

🤖 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/realms/api/hit.ts`:
- Around line 9-13: The code currently assumes new URL(c.req.query('url')) is
always valid and will throw on malformed input; update both occurrences where
c.req.query('url') is handled so that after confirming typeof c.req.query('url')
=== 'string' you wrap the new URL(...) call in a try-catch, and on catch return
the fallback Response (204 or 400) instead of letting the exception bubble; when
the URL is successfully constructed continue to call c.redirect(url.href, 302)
as before.

In `@src/realms/api/router.ts`:
- Around line 47-69: The /2/owoembed route (registered via
api.get('/2/owoembed', oembed)) is not included in the OpenAPI surface; either
convert it to a documented route by registering it with api.openapi (e.g.,
create a corresponding owoembedAPIRequest and call api.openapi(owoembedV2Route,
owoembedAPIRequest) alongside the other api.openapi(...) calls), or mark it as
internal by renaming/moving it to the private endpoints (like '/2/hit' or
'/2/go') and ensure the oembed handler (function oembed) is updated accordingly
so the route ownership matches the chosen visibility.

In `@src/realms/api/routes.ts`:
- Around line 147-151: The query schema for the /2/search route incorrectly
marks q as optional; update the zod schema in the query object by removing
.optional() from the q field so q is a required string (i.e., change the
z.string().optional().openapi(...) declaration to z.string().openapi(...)) to
align the schema with the documented 400 response for missing q and ensure
generated clients require q when calling the search route.
- Around line 21-51: Routes like statusV2Route (and threadV2Route,
profileV2Route, profileStatusesV2Route, searchV2Route, trendsV2Route) are
missing the required User-Agent header in their request declarations and their
401 responses use the wrong schema; import UserAgentErrorSchema from schemas.ts
and update each route's request to declare the required header (e.g. add a
headers zod object or shared aboutAccountQuery place where headers belong) to
document the User-Agent requirement, then change the 401 response schema to
either UserAgentErrorSchema or a oneOf([UserAgentErrorSchema, <existing route
error schema>]) so the OpenAPI contract matches the router.ts middleware
behavior that returns { error: string } on missing User-Agent; reference the
route factory createRoute and the response objects within each route
(statusV2Route, threadV2Route, profileV2Route, profileStatusesV2Route,
searchV2Route, trendsV2Route) when applying these edits.

In `@src/realms/api/routes/twitter.ts`:
- Around line 87-97: The route schema for searchV2Route currently marks the
query param q as optional while the handler searchAPIRequest treats it as
required; update the route's schema by removing .optional() from the q field in
the searchV2Route/query schema so q is required, ensure the TypeBox/validator
type reflects a required string (not optional), run the OpenAPI/spec generation
to confirm q appears under required parameters, and re-run tests or a spec diff
to verify generated clients will see q as required.
- Around line 112-129: The route schema currently declares the query "type" as
z.string().optional(), causing the handler trendsAPIRequest to perform runtime
validation; replace that schema entry with
z.enum(PUBLIC_EXPLORE_TIMELINE_KINDS).optional() so the OpenAPI spec and
validation are aware of allowed values. Import PUBLIC_EXPLORE_TIMELINE_KINDS
into the module that defines the route schema (the one that contains the query
schema for trendsV2Route), update the schema definition for "type" to use
z.enum(...) and remove or simplify the runtime isPublicExploreTimelineKind check
in trendsAPIRequest since invalid values will be rejected by the request
validator. Ensure types still align with trendsV2Route and update any
tests/examples expecting free-form strings.

In `@src/realms/api/schemas.ts`:
- Around line 252-291: APITwitterStatusSchema and the handwritten
APITwitterStatus type have diverged (notably the recursive quote field and
community_note nullability); stop maintaining a separate APITwitterStatus
interface and derive the TypeScript type from the schema using z.infer<typeof
APITwitterStatusSchema>, and adjust the schema (or the single source) so the
recursive contract is unified (ensure quote uses the intended optional/nullish
recursive shape and community_note matches the intended required|null vs
optional|null behavior by using APITwitterCommunityNoteSchema or .nullable()/
.optional() consistently). Update references that imported APITwitterStatus to
use the inferred type so runtime validation, OpenAPI generation and TypeScript
stay in sync.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 50bb7883-f590-4c76-8b35-a926b94b47af

📥 Commits

Reviewing files that changed from the base of the PR and between 53b4da7 and 7a5f855.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (10)
  • package.json
  • src/realms/api/hit.ts
  • src/realms/api/router.ts
  • src/realms/api/routes.ts
  • src/realms/api/routes/oembed.ts
  • src/realms/api/routes/twitter.ts
  • src/realms/api/schemas.ts
  • src/types/apiStatus.ts
  • src/types/types.d.ts
  • test/api.openapi.test.ts

Comment thread src/realms/api/hit.ts Resolved
Comment thread src/realms/api/router.ts Resolved
Comment thread src/realms/api/routes.ts Resolved
Comment thread src/realms/api/routes.ts Resolved
Comment thread src/realms/api/routes/twitter.ts Resolved
Comment thread src/realms/api/routes/twitter.ts Resolved
Comment thread src/realms/api/schemas.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.

Actionable comments posted: 1

🤖 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/realms/api/routes.ts`:
- Around line 119-126: Validator errors from the Zod schemas are causing
undocumented/ inconsistent 400 payloads across routes (e.g.,
/2/profile/{handle}/statuses, /2/trends) and /2/search currently allows empty q;
fix by (1) tightening the search query schema: add a non-empty constraint to the
query parameter schema used by /2/search (replace z.string() with
z.string().min(1) and keep/openapi metadata) so the validator rejects empty q,
and (2) normalize validator error handling for all affected routes by either
adding explicit 400 OpenAPI response docs referencing the validator error format
or by converting Zod errors into your API's canonical { code, message } response
in a shared middleware/validator wrapper (modify the central validation wrapper
used by routes in src/realms/api/routes.ts so functions like the schema
validation step return the normalized error payload instead of the framework
default).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 87777cad-219e-4f0f-9929-71d1d4a6114d

📥 Commits

Reviewing files that changed from the base of the PR and between 7a5f855 and f809392.

📒 Files selected for processing (23)
  • src/embed/activity.ts
  • src/embed/status.ts
  • src/helpers/socialproof.ts
  • src/helpers/translate.ts
  • src/helpers/translateAI.ts
  • src/helpers/translateGrok.ts
  • src/providers/twitter/conversation.ts
  • src/providers/twitter/processor.ts
  • src/providers/twitter/search.ts
  • src/providers/twitter/trends.ts
  • src/providers/twitter/userStatuses.ts
  • src/realms/api/hit.ts
  • src/realms/api/routes.ts
  • src/realms/api/routes/twitter.ts
  • src/realms/api/schemas.ts
  • src/render/instantview.ts
  • src/render/video.ts
  • src/types/apiStatus.ts
  • src/types/types.d.ts
  • test/api.profileStatuses.test.ts
  • test/api.search.test.ts
  • test/api.status.test.ts
  • test/api.trends.test.ts
💤 Files with no reviewable changes (1)
  • src/providers/twitter/trends.ts
✅ Files skipped from review due to trivial changes (12)
  • src/providers/twitter/search.ts
  • test/api.profileStatuses.test.ts
  • src/embed/status.ts
  • test/api.search.test.ts
  • test/api.status.test.ts
  • src/embed/activity.ts
  • src/helpers/translateAI.ts
  • src/helpers/translateGrok.ts
  • src/providers/twitter/processor.ts
  • src/providers/twitter/conversation.ts
  • src/helpers/socialproof.ts
  • src/render/instantview.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/realms/api/hit.ts
  • src/realms/api/schemas.ts

Comment thread src/realms/api/routes.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.

Actionable comments posted: 1

🤖 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/realms/api/schemas.ts`:
- Around line 66-89: The media union currently tries APIPhotoSchema before
APIVideoSchema causing GIFs to validate as photos and miss video fields; reorder
the union so APIVideoSchema is evaluated before APIPhotoSchema in the media.all
union, and replace the duplicated inline base object with a reference to
APIMediaBaseSchema to remove redundancy (update the union construction that
references APIPhotoSchema, APIVideoSchema and the inline base schema).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 63324a90-73db-4f07-896f-f088e74c6562

📥 Commits

Reviewing files that changed from the base of the PR and between f809392 and 1490987.

📒 Files selected for processing (5)
  • src/realms/api/schemas.ts
  • src/types/types.d.ts
  • test/api.search.test.ts
  • test/api.trends.test.ts
  • test/trends.test.ts
✅ Files skipped from review due to trivial changes (1)
  • test/trends.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • test/api.trends.test.ts
  • test/api.search.test.ts

Comment thread src/realms/api/schemas.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)
src/realms/api/routes/twitter.ts (1)

21-23: Use validated query params for about_account check.

shouldIncludeAboutAccount uses raw c.req.query() while the handlers use validated params via c.req.valid('param'). For consistency and to leverage the OpenAPI validation, access the validated query instead:

♻️ Suggested refactor
-const shouldIncludeAboutAccount = (c: Context) => {
-  return isParamTruthy(c.req.query('about_account') ?? c.req.query('aboutAccount'));
-};
-
 export const statusAPIRequest: RouteHandler<typeof statusV2Route> = async c => {
   const { id } = c.req.valid('param');
+  const query = c.req.valid('query');
+  const includeAboutAccount = isParamTruthy(query.about_account ?? query.aboutAccount);

   let processedResponse = await constructTwitterThread(id, false, c, undefined, undefined);
-  if (processedResponse.code === 200 && shouldIncludeAboutAccount(c)) {
+  if (processedResponse.code === 200 && includeAboutAccount) {
     processedResponse = await attachAboutAccountData(c, processedResponse);
   }

Apply the same pattern to threadAPIRequest.

Also applies to: 25-31

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

In `@src/realms/api/routes/twitter.ts` around lines 21 - 23, The helper
shouldIncludeAboutAccount currently reads raw query strings via c.req.query();
change it to use the validated request params (c.req.valid('param')) so it
relies on OpenAPI validation — read the validated 'about_account' (or fallback
'aboutAccount') value and pass that into isParamTruthy; apply the same change to
threadAPIRequest where it inspects query params so both helpers consistently use
c.req.valid('about_account'/'aboutAccount') instead of c.req.query().
src/realms/api/routes.ts (1)

96-120: Add 500 response to maintain consistency with other routes.

profileStatusesV2Route, searchV2Route, and trendsV2Route all document 500 responses for upstream or processing errors, but profileV2Route omits it. Add a 500 response definition for consistency:

Suggested addition
    500: {
      description: 'Upstream or processing error',
      content: { 'application/json': { schema: UserAPIResponseSchema } }
    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/realms/api/routes.ts` around lines 96 - 120, Add a 500 response entry to
the profileV2Route responses so it matches other routes (profileStatusesV2Route,
searchV2Route, trendsV2Route); specifically update the responses object inside
profileV2Route to include a 500 key with description 'Upstream or processing
error' and content using the existing UserAPIResponseSchema to return the same
error shape as other routes. Locate the responses block for profileV2Route and
insert the 500 response definition consistent with the pattern used elsewhere.
🤖 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/realms/api/routes.ts`:
- Around line 96-120: Add a 500 response entry to the profileV2Route responses
so it matches other routes (profileStatusesV2Route, searchV2Route,
trendsV2Route); specifically update the responses object inside profileV2Route
to include a 500 key with description 'Upstream or processing error' and content
using the existing UserAPIResponseSchema to return the same error shape as other
routes. Locate the responses block for profileV2Route and insert the 500
response definition consistent with the pattern used elsewhere.

In `@src/realms/api/routes/twitter.ts`:
- Around line 21-23: The helper shouldIncludeAboutAccount currently reads raw
query strings via c.req.query(); change it to use the validated request params
(c.req.valid('param')) so it relies on OpenAPI validation — read the validated
'about_account' (or fallback 'aboutAccount') value and pass that into
isParamTruthy; apply the same change to threadAPIRequest where it inspects query
params so both helpers consistently use
c.req.valid('about_account'/'aboutAccount') instead of c.req.query().

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 6f79dcf5-57b9-4119-987f-d3ea035d2ac4

📥 Commits

Reviewing files that changed from the base of the PR and between 1490987 and e741ff2.

📒 Files selected for processing (7)
  • src/realms/api/openapi-validation-hook.ts
  • src/realms/api/router.ts
  • src/realms/api/routes.ts
  • src/realms/api/routes/twitter.ts
  • src/realms/api/schemas.ts
  • test/api.search.test.ts
  • test/api.trends.test.ts
✅ Files skipped from review due to trivial changes (2)
  • test/api.trends.test.ts
  • src/realms/api/schemas.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/api.search.test.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.

Actionable comments posted: 1

🧹 Nitpick comments (4)
src/worker.ts (1)

5-5: Prefer a type-only import for ContentfulStatusCode.

At Line 5, ContentfulStatusCode is only used in a type assertion (Line 122), so this should be a type-only import to avoid unnecessary runtime code emission.

Proposed change
-import { ContentfulStatusCode } from 'hono/utils/http-status';
+import type { ContentfulStatusCode } from 'hono/utils/http-status';
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/worker.ts` at line 5, The import of ContentfulStatusCode should be made
type-only to avoid emitting runtime code; change the import statement that
currently brings in ContentfulStatusCode to a type import (e.g., use "import
type { ContentfulStatusCode } from 'hono/utils/http-status'") and keep its usage
as the type assertion where it's referenced (the type assertion at the location
using ContentfulStatusCode). Ensure no other runtime uses of
ContentfulStatusCode exist so the type-only import is valid.
src/providers/twitter/fetch.ts (1)

140-140: Initialize apiRequest explicitly to avoid implicit undefined state.

Line 140 declares Response | null but leaves it uninitialized. Initializing to null keeps runtime state aligned with the declared type and makes later control flow easier to reason about.

♻️ Proposed fix
-    let apiRequest: Response | null;
+    let apiRequest: Response | null = null;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/providers/twitter/fetch.ts` at line 140, The variable apiRequest is
declared as Response | null but left uninitialized; initialize it explicitly to
null (e.g., change the declaration of apiRequest to assign null) so its runtime
state matches the declared type and later control flow (reads/if-checks) can
rely on a null value instead of implicit undefined; update any downstream checks
that compare to undefined to use null if needed.
src/embed/activity.ts (1)

421-421: The cast is safe but could be more explicit.

The as APIStatus cast is protected by the null guard at line 416. Since getStatusText internally handles Twitter-specific fields via status.provider === DataProvider.Twitter check and secondary cast, this works correctly. However, consider using a non-null assertion (thread.status!) or refactoring getStatusText to accept the union type directly for clearer intent.

Alternative: Use non-null assertion for clarity
-  const statusResult = getStatusText(thread.status as APIStatus);
+  const statusResult = getStatusText(thread.status!);

This would require updating getStatusText signature to accept the union:

const getStatusText = (status: APIStatus | APITwitterStatus): StatusTextResult => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/embed/activity.ts` at line 421, The usage of an explicit cast to
APIStatus when calling getStatusText is misleading; replace the cast with a
non-null assertion on thread.status (thread.status!) or alternatively change
getStatusText's signature to accept the union type (APIStatus |
APITwitterStatus) so you can pass thread.status directly; update call sites that
currently use getStatusText(thread.status as APIStatus) to use thread.status! or
the new union-accepting signature, and keep the internal DataProvider.Twitter
check and any secondary casts inside getStatusText unchanged.
src/providers/bsky/processor.ts (1)

96-105: Consider removing or documenting the commented-out line.

The commented-out thumbnail_url assignment suggests either incomplete work or a workaround. If this is intentional (e.g., Tenor doesn't provide usable thumbnail data in this format), consider adding a brief comment explaining why, or remove the line entirely if it's no longer needed.

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

In `@src/providers/bsky/processor.ts` around lines 96 - 105, The commented-out
thumbnail assignment inside the block that sets apiStatus.media.photos (the
object with type 'gif', url: external?.uri, format 'image/gif', width/height) is
ambiguous; either remove the commented line "thumbnail_url:
external?.thumb?.ref?.$link ?? ''" if it's dead code, or replace it with a short
explanatory comment describing why Tenor/this provider doesn't supply a usable
thumbnail (e.g., missing ref/$link, inconsistent schema) so future readers
understand the rationale; update the apiStatus.media.photos population near the
external?.thumb?.ref?.$link usage accordingly and keep code/comments consistent.
🤖 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 555-570: The isTweetDetailResponse type guard currently uses the
'in' operator on resp.data without confirming it's an object; update the guard
to first ensure resp is truthy and resp.data is an object (e.g., typeof
resp.data === "object" && resp.data !== null && !Array.isArray(resp.data))
before checking for 'threaded_conversation_with_injections_v2' with 'in'. Modify
the isTweetDetailResponse function to perform that typeof/Array check prior to
the property-in check so malformed non-object data won't throw.

---

Nitpick comments:
In `@src/embed/activity.ts`:
- Line 421: The usage of an explicit cast to APIStatus when calling
getStatusText is misleading; replace the cast with a non-null assertion on
thread.status (thread.status!) or alternatively change getStatusText's signature
to accept the union type (APIStatus | APITwitterStatus) so you can pass
thread.status directly; update call sites that currently use
getStatusText(thread.status as APIStatus) to use thread.status! or the new
union-accepting signature, and keep the internal DataProvider.Twitter check and
any secondary casts inside getStatusText unchanged.

In `@src/providers/bsky/processor.ts`:
- Around line 96-105: The commented-out thumbnail assignment inside the block
that sets apiStatus.media.photos (the object with type 'gif', url:
external?.uri, format 'image/gif', width/height) is ambiguous; either remove the
commented line "thumbnail_url: external?.thumb?.ref?.$link ?? ''" if it's dead
code, or replace it with a short explanatory comment describing why Tenor/this
provider doesn't supply a usable thumbnail (e.g., missing ref/$link,
inconsistent schema) so future readers understand the rationale; update the
apiStatus.media.photos population near the external?.thumb?.ref?.$link usage
accordingly and keep code/comments consistent.

In `@src/providers/twitter/fetch.ts`:
- Line 140: The variable apiRequest is declared as Response | null but left
uninitialized; initialize it explicitly to null (e.g., change the declaration of
apiRequest to assign null) so its runtime state matches the declared type and
later control flow (reads/if-checks) can rely on a null value instead of
implicit undefined; update any downstream checks that compare to undefined to
use null if needed.

In `@src/worker.ts`:
- Line 5: The import of ContentfulStatusCode should be made type-only to avoid
emitting runtime code; change the import statement that currently brings in
ContentfulStatusCode to a type import (e.g., use "import type {
ContentfulStatusCode } from 'hono/utils/http-status'") and keep its usage as the
type assertion where it's referenced (the type assertion at the location using
ContentfulStatusCode). Ensure no other runtime uses of ContentfulStatusCode
exist so the type-only import is valid.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: abd962c5-ff52-4050-bb79-91c03586229b

📥 Commits

Reviewing files that changed from the base of the PR and between e741ff2 and a9ed4cb.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (34)
  • package.json
  • src/embed/activity.ts
  • src/embed/status.ts
  • src/helpers/article.ts
  • src/helpers/media.ts
  • src/helpers/mosaic.ts
  • src/helpers/quote.ts
  • src/helpers/socialproof.ts
  • src/helpers/translate.ts
  • src/helpers/translateAI.ts
  • src/helpers/translateGrok.ts
  • src/helpers/utils.ts
  • src/providers/bsky/conversation.ts
  • src/providers/bsky/processor.ts
  • src/providers/tiktok/conversation.ts
  • src/providers/tiktok/processor.ts
  • src/providers/twitter/aboutAccount.ts
  • src/providers/twitter/card.ts
  • src/providers/twitter/conversation.ts
  • src/providers/twitter/fetch.ts
  • src/providers/twitter/graphql/request.ts
  • src/providers/twitter/processor.ts
  • src/providers/twitter/profile.ts
  • src/providers/twitter/search.ts
  • src/providers/twitter/trends.ts
  • src/providers/twitter/userStatuses.ts
  • src/realms/api/schemas.ts
  • src/render/photo.ts
  • src/types/apiStatus.ts
  • src/user.ts
  • src/worker.ts
  • test/mocks/SearchTimeline/neo.json
  • test/mocks/UserTweets/783214.json
  • tsconfig.json
💤 Files with no reviewable changes (9)
  • src/helpers/mosaic.ts
  • src/providers/twitter/card.ts
  • src/providers/bsky/conversation.ts
  • src/helpers/media.ts
  • src/providers/twitter/profile.ts
  • tsconfig.json
  • src/helpers/quote.ts
  • src/render/photo.ts
  • src/providers/tiktok/conversation.ts
✅ Files skipped from review due to trivial changes (8)
  • src/user.ts
  • src/providers/twitter/graphql/request.ts
  • src/helpers/socialproof.ts
  • src/providers/twitter/aboutAccount.ts
  • src/helpers/article.ts
  • src/providers/twitter/userStatuses.ts
  • src/providers/tiktok/processor.ts
  • test/mocks/UserTweets/783214.json
🚧 Files skipped from review as they are similar to previous changes (9)
  • src/providers/twitter/search.ts
  • src/helpers/translateGrok.ts
  • package.json
  • src/embed/status.ts
  • src/helpers/translate.ts
  • src/providers/twitter/processor.ts
  • src/helpers/translateAI.ts
  • src/providers/twitter/trends.ts
  • src/realms/api/schemas.ts

Comment on lines +555 to +570
const isTweetDetailResponse = (
resp:
| TweetDetailResponse
| TweetResultByRestIdResponse
| TweetResultsByRestIdsResponse
| TweetResultsByIdsResponse
| TweetResultByIdResponse
| null
) => {
return (
resp &&
'data' in resp &&
resp.data !== null &&
'threaded_conversation_with_injections_v2' in (resp.data || {})
);
};

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.

⚠️ Potential issue | 🟡 Minor

Harden TweetDetail guard against malformed data shapes.

On Line 568, using in assumes resp.data is an object. If upstream returns a non-object data, this can throw and skip graceful fallback.

🛡️ Proposed fix
   const isTweetDetailResponse = (
@@
   ) => {
     return (
       resp &&
       'data' in resp &&
+      typeof resp.data === 'object' &&
       resp.data !== null &&
-      'threaded_conversation_with_injections_v2' in (resp.data || {})
+      'threaded_conversation_with_injections_v2' in resp.data
     );
   };
🤖 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 555 - 570, The
isTweetDetailResponse type guard currently uses the 'in' operator on resp.data
without confirming it's an object; update the guard to first ensure resp is
truthy and resp.data is an object (e.g., typeof resp.data === "object" &&
resp.data !== null && !Array.isArray(resp.data)) before checking for
'threaded_conversation_with_injections_v2' with 'in'. Modify the
isTweetDetailResponse function to perform that typeof/Array check prior to the
property-in check so malformed non-object data won't throw.

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.

OpenAPI Support

1 participant